Skip to content

feat: upgrade to op-vm v1.0.0-beta.1#39

Merged
BlobMaster41 merged 22 commits intomainfrom
feat/upgrade-op-vm
Feb 17, 2026
Merged

feat: upgrade to op-vm v1.0.0-beta.1#39
BlobMaster41 merged 22 commits intomainfrom
feat/upgrade-op-vm

Conversation

@BlobMaster41
Copy link
Contributor

@BlobMaster41 BlobMaster41 commented Feb 15, 2026

Upgrade to op-vm v1.0.0-rc.0

Major upgrade of the unit test framework to support op-vm v1.0.0-beta.1, bringing ECDSA/Keccak-256 support, contract upgrade handling, Buffer-to-Uint8Array migration, and P2MR (BIP-360) compatibility across the full dependency tree.

What Changed

  • op-vm v1.0.0-beta.1: Upgraded from local file path reference to published beta package
  • updateFromAddress handler: Register and implement handler across runtime and blockchain bindings, plus corresponding Rust contract binding
  • Buffer hardening: Use Buffer.from(Array.from(...)) and Buffer.copyBytesFrom, normalize contract IDs and numeric fields to BigInt, convert ExitDataResponse results to readonly objects with proper buffer/gas/proof conversions
  • Contract upgrades: ContractRuntime supports scheduling pending bytecode replacement executed on next block, runs onUpdate on temporary WASM instance to validate/commit upgrades, cancels pending upgrades on revert, prevents nested/cross-contract calls after upgrade in same execution
  • ECDSA support: Add ECDSA contract sources, AssemblyScript build config, runtime wrapper, and tests (including debug variant)
  • Error handling: Add error encoding helper (getErrorAsBuffer), adjust revert decoding, add uncaughtException logger
  • TSConfig: Standardize compiler options to ESNext module/target, compact lib to [ESNext]
  • Misc: Disable/replace returnProofs usage in runtime options, add bypassCache flag to generateParams and RustContract

Related PRs

op-vm (direct dependency)

btc-runtime (contract runtime)

opnet (client library)

@btc-vision/bitcoin

@btc-vision/transaction

@btc-vision/bip32

@btc-vision/ecpair

opnet-node (integration context)

Also Open on unit-test-framework

Breaking Changes

  • Buffer APIs replaced with Uint8Array throughout — consumers must update any code that passes or expects Node.js Buffer objects
  • op-vm consensus flag renamed to ALLOW_CLASSICAL_SIGNATURES
  • Provider configuration now uses config objects instead of positional constructor params (from opnet PR 134)
  • Contract simulation calls now throw on revert instead of returning error objects (from opnet PR 134)

Register and implement updateFromAddress handler across runtime and blockchain bindings, and add corresponding Rust contract binding. Switch @btc-vision/op-vm dependency to a local file path. Harden buffer handling and conversions (use Buffer.from(Array.from(...)) and Buffer.copyBytesFrom), normalize contract IDs and numeric fields to BigInt, and convert ExitDataResponse results to readonly objects with proper buffer/gas/proof conversions. Add error encoding helper (getErrorAsBuffer), adjust revert decoding, and add an uncaughtException logger. Also disable/replace returnProofs usage in runtime options.
@BlobMaster41 BlobMaster41 added the enhancement New feature or request label Feb 15, 2026
@BlobMaster41 BlobMaster41 changed the title Add updateFromAddress binding and safety fixes Upgrade to op-vm v1.0.0-beta.1 Feb 15, 2026
Delete examples/gas.js (remove obsolete/generated gas benchmark). Update package.json to replace the local @btc-vision/op-vm file reference with the published ^1.0.0-beta.1 version so the project uses the released beta package instead of a local workspace dependency.
Standardize TypeScript compiler options: change "module" and "target" values to "ESNext" and replace the verbose "lib" list with ["ESNext"]. Compact array formatting for "typeRoots" and other fields, adjust include/exclude globs by removing recursive test includes from "include" and adding test patterns to "exclude". Minor whitespace/formatting cleanups. Note: the new exclude array contains a duplicated "test/**/*.ts" entry which may be accidental.
Implement bytecode upgrades initiated by another contract address. ContractRuntime now supports scheduling a pending bytecode replacement executed on the next block, runs onUpdate on a temporary WASM instance to validate/commit upgrades, cancels pending upgrades on revert, and prevents nested/cross-contract calls after an upgrade in the same execution. Added helpers to GetBytecode/BytecodeManager (forceSetBytecode, clear) and ensure caches are cleared (Blockchain.clearContracts, contractManager cache). Introduced a consensus flag UPDATE_CONTRACT_BY_ADDRESS and enabled it in ConsensusManager.default. Added extensive E2E tests and two example upgradeable contracts (v1 and v2) plus runtime adapters and test runner (UpdateFromAddress.test). Misc: use toHex in bench.ts and add a test script entry for update-from-address in package.json.
Adjust the Dos e2e test to be more explicit and assertive: rename the test to 'should not crash when querying own account type', remove the expectation that the call throws, actually call accountTypeCall, assert the returned account type equals 1 (contract), and ensure execution completes within a reasonable time (elapsed < 5000ms). Also remove an extraneous numeric comment in the TestContractRuntime constructor. Simplify tsconfig.json include/exclude patterns by consolidating globs and only excluding node_modules to avoid redundant entries.
Add end-to-end ECDSA contract, runtime helpers and tests, and enhance contract upgrade handling.

- Add ECDSA contract sources, AssemblyScript build config and runtime wrapper, plus ECDSA tests (including debug variant) and a new npm test script (test:ecdsa) in package.json.
- Extend ContractRuntime to store pending upgrade calldata, make applyPendingBytecodeUpgrade async and perform an onUpdate call on the new bytecode (swapping bytecode first, calling onUpdate, and reverting the swap if onUpdate fails). Clear pending calldata on commit/cancel.
- Add bypassCache flag to generateParams and RustContract so upgrades and some calls can bypass the Rust VM precomputation/cache.

These changes enable testing of ECDSA verification and ensure onUpdate handlers on upgraded bytecode are invoked safely with rollback on failure.
Update ECDSA test helpers to sign raw messages (noble/curves hashes internally) and pass the SHA-256 prehash to the contract.

- Remove unused randomBytes import.
- Change signEthereum and signBitcoin to accept rawMessage (not pre-hashed) because secp256k1.sign() internally hashes the input; signEthereum now derives the compressed public key, recovers the public key to find the recovery id, and constructs an Ethereum-style 65-byte signature from the signature bytes.
- Ensure recovery comparison uses secp256k1.getPublicKey(privateKey, true) and secp256k1.recoverPublicKey(rawMessage).
- Replace all test calls to signEthereum/signBitcoin to pass the raw message bytes; compute testHash = sha256(testMessage) to pass to contract verification (the Rust VM verifies prehash).
- Add clarifying comments about noble's internal SHA-256 hashing and why tests sign raw messages but supply the pre-hash to the VM.

This fixes mismatches between how signatures were produced and how the VM expects prehashed inputs, preventing incorrect verification results.
Build: extend scripts/buildTestContracts.js to compile additional test contracts (upgradeable, upgradeable-v2, ecdsa, gas-test).
Consensus: rename UNSAFE_QUANTUM_SIGNATURES_ALLOWED to ALLOW_CLASSICAL_SIGNATURES and update usages in ConsensusManager and ConsensusRules (including unsafeSignaturesAllowed()).
Tests: add new e2e import test test/e2e/imports/Blockchain.test.js; update UpdateFromAddress.test.ts to import ABICoder and BinaryWriter and use ABICoder.encodeSelector when building calldata.
Config: add tsconfig.contracts.json for contract sources and tsconfig.test.json for test compilation; remove test/**/*.ts from the main tsconfig.json include to separate test/contract compilation paths.

Remove legacy e2e import tests

Delete legacy end-to-end test files from test/e2e/imports. Removed files: Blockchain.test.js, Dos.test.js, ECDSA.test.js and ECDSA_debug.test.js. These tests (including ECDSA debug helpers) have been removed as part of test-suite cleanup or migration to a different test layout; no other code changes were made in this changeset.

Remove e2e import tests and test contract runtime

Delete legacy end-to-end test files and their associated runtime helper to clean up the test suite. Removed: test/e2e/contracts/test-contract/runtime/TestContractRuntime.js, test/e2e/imports/Blockchain.test.js, and test/e2e/imports/MLDSA.test.js.
Large documentation overhaul: rewritten README into a comprehensive quickstart/API reference and developer guide. Build changes: added tsconfig.build.json and updated gulpfile.js to use it for TypeScript builds. Removed obsolete e2e/debug artifacts (test/e2e/contracts/test-contract/runtime/TestContractRuntime.js and test/e2e/imports/ECDSA_debug.test.ts) and removed legacy tsconfig.contracts.json and tsconfig.test.json. Also includes adjustments to tsconfig.json. Purpose: consolidate build configuration, tidy test artifacts, and improve developer-facing documentation.
Add a full docs site under /docs (getting-started, writing-tests, built-in-contracts, api-reference, examples, and multiple advanced topics such as cross-contract-calls, consensus-rules, gas-profiling, signature-verification, state-management, transaction-simulation, upgradeable-contracts). Update top-level README to point to the new /docs, streamline content and add Quick Start note to set Blockchain.msgSender/txOrigin in the example. Also refresh docs/README.md with a structured index and links to the new pages.
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR upgrades the framework to use op-vm v1.0.0-beta.1, introducing contract upgrade functionality via updateFromAddress, improving buffer handling, normalizing types to BigInt, and adding comprehensive documentation. The changes include:

Changes:

  • Upgrade to @btc-vision/op-vm v1.0.0-beta.1 with enhanced buffer safety and BigInt normalization
  • Add updateFromAddress handler for contract upgrades with block-boundary enforcement
  • Improve buffer handling using Buffer.copyBytesFrom() and Buffer.from(Array.from(...)) for memory safety
  • Add getErrorAsBuffer helper and consensus flags for upgrade features
  • Add extensive test coverage for upgrades (UpdateFromAddress), ECDSA signatures, and DoS scenarios
  • Add comprehensive documentation covering all features, API references, and usage examples

Reviewed changes

Copilot reviewed 55 out of 56 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
tsconfig.json Simplified lib configuration to ESNext only
tsconfig.build.json New build-specific TypeScript configuration
package.json Updated dependencies to RC/beta versions
RustContract.ts Added onUpdate, getErrorAsBuffer, improved buffer handling, readonly responses
RustContractBinding.ts Added updateFromAddress to binding interface
ContractRuntime.ts Implemented upgrade queue system, pending bytecode management, updateFromAddress handler
Blockchain.ts Added updateFromAddress binding and BytecodeManager.clear() call
BytecodeManager.ts Added forceSetBytecode and clear methods
ConsensusRules.ts Renamed flags and added UPDATE_CONTRACT_BY_ADDRESS
UpdateFromAddress.test.ts Comprehensive test suite for contract upgrades (395 lines)
ECDSA.test.ts Test suite for ECDSA signature verification (302 lines)
Dos.test.ts Fixed test expectation for account type queries
docs/* Added extensive documentation covering all framework features

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Add detailed internal mechanism for contract upgrades to docs (phases, blocking cross-contract calls after update, response format and rollback behavior). Bump @btc-vision/op-vm dependency from beta to rc. Include original error cause when throwing on invalid tweaked public key in ContractRuntime for better debugging.
Track and charge Phase 2 (onUpdate) gas and protect upgrade flow.

- ContractRuntime.applyPendingBytecodeUpgrade now returns Phase-2 gas and the caller adds it to gasUsed so the first post-mine call pays the onUpdate cost.
- Introduced _hasUpgradedInCurrentExecution guard to block nested upgrades and prevent deployments after an upgrade during the same execution; guard is set during Phase 2 and always cleared in finally.
- Enforce calldata decompressed size limit for upgrades and store pending upgrade calldata when scheduling an upgrade for the next block.
- Handle bytecode removal when reverting to no previous bytecode (BytecodeManager.removeBytecode usage).
- Added BytecodeManager.removeBytecode API to delete bytecode and filename entries.
- Small docs updates: add RESERVED_FLAG_2 to consensus rules and fix an import path in state-management.md.
- Expanded E2E tests: add BytecodeManager removal tests and many upgrade lifecycle tests (phase-2 gas accounting, guard behavior, state preservation, multi-block behavior).

These changes ensure correct gas accounting for post-mine bytecode swaps, prevent unsafe nested upgrade/deploy scenarios, and add targeted bytecode removal support.
Prevent state/event leaks and ensure proper gas accounting for failed Phase 2 contract upgrades. Changes include:

- ContractRuntime: preserve previous contract reference, capture Phase 2 gas earlier, rollback bytecode deterministically, clear temporary state and emitted events on failed onUpdate, attempt to read gas from the temp VM if needed, and always restore the original contract reference.
- Tests: add a malicious-v2 AssemblyScript contract (writes storage, emits an event, then reverts) and extend UpdateFromAddress tests to verify that failed onUpdate does not leak storage or events, that gas is charged, and that bytecode is reverted.
- Build script: scripts/buildTestContracts.js now builds the malicious-v2 test contract.
- Docs: README updated with Running Tests, Test Contracts guidance and a Changelog pointer.

These changes ensure failed upgrade attempts cannot leave persistent side effects while still charging appropriate gas costs.
Add GitHub issue templates (bug_report, feature_request), ISSUE_TEMPLATE config with security contact link, and a PULL_REQUEST_TEMPLATE. Add changelog-config.json for automated changelog generation. Update CI workflow (ci.yml): rename job, use actions/checkout@v6 and setup-node@v6, fetch full history, install Rust toolchain, build/test steps, detect npm tag from git tag and publish with the appropriate npm dist-tag, and add a release job that generates changelog, updates CHANGELOG.md, commits it, and creates a GitHub release (softprops/action-gh-release). Add a PR validation workflow (pr.yml) to run build/test on pull requests. These changes improve automated publishing, release notes, and PR validation.
Add SECURITY.md (vulnerability reporting policy and scope) and a placeholder CHANGELOG.md for automated changelog generation. Bump package version from 1.0.0-beta.0 to 1.0.0-alpha.0. Refactor ContractRuntime.getErrorAsBuffer to delegate error serialization to RustContract.getErrorAsBuffer instead of building the BinaryWriter inline.
@BlobMaster41 BlobMaster41 changed the title Upgrade to op-vm v1.0.0-beta.1 feat: upgrade to op-vm v1.0.0-beta.1 Feb 17, 2026
@BlobMaster41 BlobMaster41 merged commit efe74a4 into main Feb 17, 2026
3 checks passed
@BlobMaster41 BlobMaster41 deleted the feat/upgrade-op-vm branch February 17, 2026 09:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant