Source: docs/lotus-v2/research/addendum-designs/O1-v2-opcodes.md
Research β€” non-normative. This page records an investigation. It defines no rule; a research result enters the specification only through a decision recorded in decision history.

O1 β€” Lotus V2 planned opcodes and VM semantics: implementation plan

Status: implementation-ready plan, consensus change, not yet approved. Every item marked [SIGN-OFF] is a decision the specs leave ambiguous or contradictory. The coding agent must not start the affected patch until the user has picked a resolution (the recommended one is listed first). Nothing in this plan was built or executed. All source reads were read-only.

Prepared 2026-10-19.


0. Inputs, pins and what was verified

Input Pin / location Notes
P03 VM semantics lotus-v2-optimizations 2db77639:docs/lotus-v2/decisions/vm-semantics.md authoritative opcode/semantics text
Script ABI (LC-1, LC-2) 2db77639:docs/lotus-v2/script-abi.md LC-2 section Β§1–§9 (lines 194–296)
P01 encoding/signatures 2db77639:docs/lotus-v2/decisions/encoding-and-signatures.md Output grammar, HAS_STATE, sighash
Opcode registry 2db77639:docs/lotus-v2/tools/opcodes.json 225 entries, name/byte/group only (no stack effects/costs)
Structural checker 2db77639:docs/lotus-v2/tools/spec_candidate_checks.py success scan, Merkle, framing, signing vectors
Compiler ABI plan 2db77639:docs/plans/lotus-v2-compiler-abi.md Β§"Tentative Compiler & VM Spec Update (October 18)"
Example contract 2db77639:docs/lotus-v2/examples/evm-porting/proposed/flash-and-staking.lotus the path in the task brief (docs/lotus-v2/evm-porting/...) does not exist at 2db77639; the file is under examples/
Implementation lotus-v2-repaired-source 3cf1891b91 the checked-out worktree is at 596537e978 (different lineage, same subject). git diff --stat 3cf1891b91 596537e978 shows no differences in vm.*, vm_cost.inc, output.*, transaction.*, ordinary_validation.cpp, signing.cpp, test_vm.cpp, so the VM analysis holds for both. The agent must branch from 3cf1891b91 as instructed and re-check this diff first.
Patch stack lotus-v2-stack-repair daemon/patches/v2/series @include ../ecash/series and then V2 patches 001…057. New patches start at 058.

Verified in source (read directly)

Assumed (not verified)


1. Summary

Twelve V2-tier patches (058–069) change the following:

  1. A 16-bit internal opcode representation with EXT2 (ff xx) framing. All 256 ff xx values are OP_SUCCESS_EXT. No assigned two-byte ops.
  2. Allocation synced to opcodes.json: 67/68 retired to OP_SUCCESS, 6c permanent invalid, and the new bytes assigned.
  3. One loop form, TXINPUTCOUNT|TXOUTPUTCOUNT ENUMERATE, with a static-cost idiom that keeps the precision of the old fused headers.
  4. Conditional BREAK (Boolean(cond) N(depth)).
  5. HAS_STATE (flags bit 2) with a 32-byte state_root in the wire format, coins DB, compressor, RPC and Chronik.
  6. Read-only introspection: UTXOFLAGS, UTXOSTATEROOT, OUTPUTSTATEROOT, ACTIVEBRANCHINDEX, ACTIVEWITNESSINDEX, TXTOKENBALANCE, INPUTWITNESSARG.
  7. STATEHASH and STATEVERIFY.
  8. Transaction-scoped VM effects (unclaimed_value, state_authorized) with a defined invocation order and a post-check. V2 script checks become per-transaction instead of per-input (parallel across transactions only).
  9. ENFORCEOUTPUT strict mode with a binary OutputTemplate parser.
  10. A separate, non-consensus simulation evaluator (EMITLOG events, constructive ENFORCEOUTPUT).
  11. RPC/Chronik exposure for the SDK.
  12. Cross-implementation vectors.

Decisions (user, 2026-10-19) β€” supersede the matching items in section 2

This is work in progress for regtest and testnets, months before release. Where section 2 offers a recommendation, it is adopted unless changed here. Expect to refactor; keep choices easy to change.

2. Spec inconsistencies and gaps (each needs user sign-off)

Locations are file:line at 2db77639 (VS = vm-semantics.md, ABI = script-abi.md, ENC = encoding-and-signatures.md, CMP = lotus-v2-compiler-abi.md, CHK = spec_candidate_checks.py, EX = flash-and-staking.lotus).

I-1 Two-byte encoding: Candidate A (MSB) vs Candidate B (EXT2). [SIGN-OFF]

I-2 The checker's success scan does not implement EXT2. [SIGN-OFF: confirm the spec text wins] VS:365 says "At 0xff (EXT2), require at least 1 following byte … if 0xff <ext_op> is an unassigned two-byte opcode … immediately return invocation success." CHK:572–608 treats ff as an ordinary one-byte assigned op (continue), so ff 4c would continue and parse 4c as PUSHDATA. Recommendation: follow VS. A trailing lone ff is Invalid (framing), any ff xx is AutomaticSuccess, and the selector byte is never parsed as a push. Fix CHK separately in the spec repo. The daemon vectors in Β§7 encode the VS behaviour.

I-3 EMITLOG is "unconditionally" invalid, but the scan can reach success first. [SIGN-OFF] VS:56 says "consensus OP_INVALID on-chain (unconditionally rejects if ever broadcast …)". VS:367 says "At any other assigned single-byte instruction, advance one byte". With that rule, 6c fe scans past 6c and succeeds at fe. Nothing says whether an EMITLOG in a skipped arm rejects. Recommendation: the scan rejects immediately at 0x6c, including in skipped arms and after RETURN, before any later success byte. That makes the rejection unconditional. It is permanent and is never a soft-fork point. Alternative: reject only at decode time if no success byte is found.

I-4 Name: SIMLOG vs EMITLOG. ABI:194 and CMP:209 headings say SIMLOG; every table and the registry say EMITLOG. Recommendation: EMITLOG.

I-5 Retiring 0x67/0x68 and editing a "frozen" genesis allocation. [SIGN-OFF] VS:53 says "67 and 68 are retired to unassigned OP_SUCCESS_N". vm.cpp says "Frozen genesis allocation … must not edit this." Changing assigned bytes to success, or success to assigned, is only legal before genesis. Recommendation: treat it as a pre-genesis reallocation, regenerate every fixture, branch root and dev chain, and record the new opcodes.json SHA-256 in opcode_coverage.json.

I-6 TXINPUTCOUNT ENUMERATE vs the 256 bound. [SIGN-OFF] VS:53 says "ENUMERATE | pop N in 0..256 … use TXINPUTCOUNT ENUMERATE … to iterate inputs/outputs". Counts go up to 65,535 (ENC:17). Any covenant that loops over inputs or outputs therefore errors when there are more than 256 of them. The fused 67/68 had no such cap. With partial-mode (01/02) signatures, a third party can add inputs or outputs and make the covenant unspendable in that transaction (griefing). Recommendation: keep 0..256 and document "contracts that enumerate inputs or outputs support at most 256", so wallets must split. Alternative: allow up to 65,535 when the bound comes from the idiom in I-7.

I-7 Static cost of the loop idiom is unspecified. [SIGN-OFF] The fused ops were charged at the exact count (vm_cost.inc). TXINPUTCOUNT ENUMERATE would be charged at 256 Γ— body, or 65,536 Γ— body when nested. That is a large cost regression and can push existing contracts over max_invocation_cost. Recommendation: SizePass rule. If the instruction immediately before ENUMERATE, in the same sequence, is TXINPUTCOUNT/TXOUTPUTCOUNT, the static bound is min(256, count), with the count taken from the tx context. Otherwise use the literal, otherwise 256.

I-8 HAS_STATE contradicts older text. [SIGN-OFF]

I-9 Undefined HAS_STATE edge cases. [SIGN-OFF] (a) HAS_STATE|IS_BURN. VS:238 says a burn output's "OUTPUTFLAGS returns 0x02 (native) or 0x03 (token)", which implies a burn never has state. Recommendation: reject flags with both 0x02 and 0x04. (b) A zero state_root. UTXOSTATEROOT/OUTPUTSTATEROOT return 0x00..00 when the state is absent (VS:202–203), which is ambiguous with a present zero root. Recommendation: require a nonzero state_root when the flag is set, like token_id (ENC:44). (c) Coinbase. It runs no script, so it can never satisfy the post-check. Recommendation: reject HAS_STATE in coinbase outputs explicitly.

I-10 state_authorized is not authentication. [SIGN-OFF on documentation, and optionally on extending ea] VS:288 says "(automatically preventing forged initial state on any output that wasn't explicitly authorized by an input or mint contract!)". state_authorized[j] is global to the transaction. Any input the attacker controls can run <template matching j> FROM_STACK 0 ENFORCEOUTPUT (claim 0) and authorize arbitrary state on output j. The rule only rejects HAS_STATE outputs that no script mentioned. Trust in a coin's state must come from its own code and lineage (STATEVERIFY plus the successor's own ENFORCEOUTPUT). Also, OUTPUTCONTINUESBRANCH (ea) compares only branches and paths, so a contract that continues via ea does not constrain the successor's state. Recommendation: document both facts. Optionally make ea also require equal HAS_STATE and state_root; that changes existing ea semantics and needs a decision.

I-11 Shared mutable state between invocations, and order dependence. [SIGN-OFF, highest priority]

I-12 INPUTWITNESSARG contradicts VS:236 and reads unsigned data. [SIGN-OFF] VS:236 says "There is no introspection of other invocations' … signature arguments …". VS:182 says df reads "argument a of witness w of input i", which includes other inputs' signature arguments. ENC:128 says arguments are excluded from TxID and SigMessage, so they can be malleated unless the owning input's script verifies them. Indexing is also unstated. Recommendation: amend VS:236. a = 0 is the first wire argument (the bottom of the initial stack, ABI:11). w indexes the selected path's witnesses for a spend, and must be 0 for a mint. A mint's node-pushed delta is not an argument. Coinbase errors. Document that a reader may rely on a sibling argument only if the sibling's own script authenticates it.

I-13 STATEHASH domain tag collides in name with the chain StateRoot. [SIGN-OFF] VS:148 uses H_state(...). The implementation already uses Lotus/v2/state for the block StateRoot envelope. The preimages cannot collide (a STATEHASH preimage starting with 00 is exactly the 1-byte k=0 case, while the envelope is 130 bytes), but reusing the domain conflates two kinds of "state root". Recommendation: add the new tag Lotus/v2/contractstate. Also specify that item_1 is the deepest item, CS is shortest-form, and each item is ≀ element cap.

I-14 ENFORCEOUTPUT template underspecification (VS:290–303). [SIGN-OFF for each item; recommendations in Β§4.6] (a) The pop order of stack_branches… is not given. (b) The meaning of branch_count (0..16, while outputs need 1..16) under each paths_mode is not given, nor whether it must equal len(output.branches). (c) Overlap of branch_mask and branch_stack_mask, and mask bits β‰₯ branch_count. (d) paths_mode = 11 and state_mode > 2. (e) Bit 7 is defined only "under INHERIT_INPUT_PATHS", yet EX:38 sets wildcard_unset_branches: true with PathsMode::Explicit. (f) Burn outputs. OMIT requires RequiresBranch, which is always false for a burn (VS:238), so burn_mode=1 with any pinned branch can never match. INHERIT requires non-empty coin paths, which a burn can never satisfy. (g) The range of expected_value and claim_amount (N up to 1024 bytes; values are u64). (h) Malformed templates (truncation, trailing bytes): error, or "no match"? (i) The bit 0–1 text for OMIT, "deducts claim_amount if claim_amount > 0", is redundant with the general budget rule. Read it as identical.

I-15 Simulation mode is undefined in places. [SIGN-OFF] VS:311 says the simulator "constructively appends (or coalesces)". Coalescing is undefined, as are the omitted fields of a synthetic output (OMIT/MIN value, OMIT token, wildcard branches, OMIT paths), how CHECKSIG behaves before signatures exist, and how TXID/SIGHASH behave over a provisional transaction. EMITLOG k has no bound. Whether the daemon or only the SDK hosts EvaluateVmSimulated is unstated. Recommendations are in Β§4.9.

I-16 Small gaps.

I-17 Soft-fork limits introduced by ENFORCEOUTPUT and HAS_STATE. [SIGN-OFF to record in VS:371] Old nodes treat an OP_SUCCESS invocation as success without executing its claims or authorizations. A future opcode that sets state_authorized would make a transaction valid to new nodes and invalid to old nodes, which is a hard fork. Recommendation: add to the soft-fork contract that newly assigned opcodes may consume unclaimed_value (stricter) but may never authorize state or relax the post-check.

I-18 Example contract issues (not daemon-blocking).


3. Opcode table (checked against opcodes.json; "now" = behaviour at 3cf1891b91)

N = 16-byte canonical int128 unless stated. "Err" = script error (VmStatus::Invalid). "ctx" = requires an authenticated context (without one: Unsupported, as the current Context() does). Cost shape: base + per_operand_byteΒ·Ξ£ops + per_result_byteΒ·Ξ£results (existing VmOpcodeCost), plus the listed extras. No numeric schedule is frozen (VS:390).

Byte(s) Name (registry βœ“) Stack effect Consensus rules / failures Static size pass (result bytes) Cost extras Simulation mode Now
67, 68 β€” (retired) β€” OP_SUCCESS_103/104 (I-5) structural only structural same fused loops β†’ remove
69 ENUMERATE βœ“ N(bound) β†’; each iteration pushes N(i) bound canonical N, 0..256 (I-6) else Err; ≀2 nested loops at decode body Γ— bound; bound = literal | idiom count (I-7) | 256 per-iteration 6a charge (existing) same exists (keep)
6a ENDENUMERATE βœ“ structural unmatched β†’ decode Err β€” per iteration same exists
6b BREAK βœ“ Boolean(cond) N(depth) β†’ always pop both; depth ∈ 1..active_loops (≀2) else Err; cond ∈ {N(0),N(1)} else Err; cond=1 β†’ ExitLoops(depth); outside a loop β†’ Err when executed; in a skipped arm, no error pops 2; not terminating: the fall-through state continues; exit states recorded for depth (literal) or all depths base + operand 32 same depth-only β†’ change
6c EMITLOG βœ“ sim: item_1…item_k N(k) β†’ consensus: scan-time Invalid (I-3) n/a n/a records event (items…), topic = item_k (top); k ∈ 0..64, stack must hold k+1 unassigned (success!) β†’ change
c3 STATEHASH βœ“ item_1…item_k N(k) β†’ Hash32 k ∈ 0..64 else Err; underflow Err; digest H_contractstate(CS(k)β€–Ξ£ CS(len)β€–item) (I-13), item_1 deepest pops k+1 (k from literal, else worst 64Γ—limit); push 32 per_operand_byte over the preimage size (charge Ξ£(len+CS)+CS(k)) same unassigned
c9 / ca TXINPUTCOUNT / TXOUTPUTCOUNT βœ“ β†’ N as now 16 β€” counts include appended drafts exist
de UTXOFLAGS βœ“ i β†’ N(flags) ctx; i in range; input must be a spend with a resolved coin (else Err, like CoinAt) 16 β€” same unassigned
df INPUTWITNESSARG βœ“ i w a β†’ bytes ctx; i < inputs; input flags 1: w < len(witnesses); flags 3: w == 0; flags 2: Err; a < len(args) (I-12); result ≀ element cap exact field size from tx (new 0xdf field-size vector), else max arg size per_result_byte same unassigned
eb ENFORCEOUTPUT βœ“ [Hash32 st]? [roots…]? [N(v)]? template N(claim) β†’ (pushes nothing) Β§4.6; no match β†’ Err; template malformed β†’ Err; records (claim, match mask) and, with a state mode, the authorization of every matched output; staged and committed on invocation success; assignment checked in phase 2 (claim assignment section) pops variable (needs literal template; else worst); no push base + per_operand_byteΒ·(template + popped) + new flat per_tx_output Γ— output_count (node schedule: 32); static charge = executed charge constructive (Β§4.9) unassigned
ec TXTOKENBALANCE βœ“ Bytes32(asset) β†’ N(in) N(out) ctx; asset exactly 32 bytes else Err; zero = native; totals precomputed; asset absent β†’ 0 0 push 16, 16 O(1) over provisional outputs unassigned
ed STATEVERIFY βœ“ Hash32 β†’ ctx; spend-only (mint β†’ Err); operand exactly 32 else Err; coin lacks HAS_STATE β†’ Err; mismatch β†’ Err pop 1 operand 32 same unassigned
ee UTXOSTATEROOT βœ“ i β†’ Hash32 spend coin required (CoinAt); zeros if no HAS_STATE 32 β€” same unassigned
ef OUTPUTSTATEROOT βœ“ j β†’ Hash32 j < outputs; zeros if no HAS_STATE 32 β€” drafts included unassigned
f5 ACTIVEBRANCHINDEX βœ“ β†’ N(k) ctx; spend: coin.paths[path_index][witness_index]; mint: N(βˆ’1) 16 β€” same unassigned
f6 ACTIVEWITNESSINDEX βœ“ β†’ N(w) ctx; spend: witness_index; mint: N(0) (I-16) 16 β€” same unassigned
ff xx EXT2 βœ“ / OP_SUCCESS_EXT_N β€” scan: lone trailing ff Invalid; any ff xx AutomaticSuccess (none assigned) structural structural same unassigned (single-byte success)
dc, e7 UTXOOUTPUT / OUTPUTRECORD unchanged serialized output now includes state_root (≀844 B) field sizes grow per_result_byte β€” exists
e0 OUTPUTFLAGS unchanged may now return 0x04/0x05 β€” β€” β€” exists
ea OUTPUTCONTINUESBRANCH unchanged does not inspect state (I-10) β€” β€” β€” exists

4. Design details

4.1 Opcode representation and framing (patch 058)

4.2 Allocation (patch 059)

GenesisAssigned becomes a table generated from the registry: 00–5d, 60–66, 69–6c, 70–81, 88–94, 98–b4, b8–c3, c8–df, e0–ef, f0–f6, ff. That is 225 entries. Add a unit test that compares the table byte for byte with the pinned opcodes.json (SHA-256 recorded). 0x6c is "assigned" for counting purposes but rejected by Scan (I-3). New semantic opcodes are added as throw VmFailure("assigned opcode not implemented", true) until their patch lands, so in this interim they are Unsupported, never success.

4.3 Loops and BREAK (patches 060, 061)

4.4 Output data model (patch 062)

4.5 Transaction-scoped effects (patch 066)

New in vm.h:

struct VmTransactionEffects {            // owned by one validation run of one tx
    std::vector<uint64_t> unclaimed_value; // = outputs[j].value
    std::vector<uint8_t>  state_authorized;
    void Reset(const Transaction&);
};
struct VmInvocationEffects { std::vector<std::pair<uint16_t,uint64_t>> claims; std::vector<uint16_t> authorized; };

New output_template.h/.cpp: bool ParseOutputTemplate(span, OutputTemplate&, std::string&). Every parse error is a script Err.

flags:u8   v=bits0-1  t=bits2-3  p=bits4-5  burn=bit6  wild=bit7
[template_value:u64]     iff v∈{01,10}
[template_token_id:h32]  iff t==10
branch_count:u8 (0..16)  branch_mask:u16  branch_stack_mask:u16  state_mode:u8 (0..2)
[template_state_root:h32] iff state_mode==1
popcount(branch_mask) Γ— h32  (ascending slot)
[paths: Vec(Vec(CS))]    iff p==01   (shortest CS; ≀16 paths; ≀16 entries; each index <16)
no trailing bytes; total ≀ element cap (max 865 bytes)

Template-level errors (raised before scanning):

Pop order (I-14a):

  1. Pop claim (N, 0 ≀ claim ≀ 2^64βˆ’1, else Err).
  2. Pop template.
  3. If v == 11, pop expected_value (N, 0..2^64βˆ’1, else Err).
  4. For the set bits of branch_stack_mask in descending slot order, pop 32 bytes each (wrong size is Err). The highest slot is on top, so the script pushes in ascending slot order.
  5. If state_mode == 2, pop the 32-byte expected_state (zero is Err).

Match(j) is true iff all of the following hold:

(Superseded, user 2026-10-20: there is no per-output budget in Match; claims are assigned in phase 2.)

Scan j over the outputs in range (all outputs, or the one index of output_mode 1/2) and collect every match into the match mask. If there is none, Err. Otherwise stage the record (claim, mask), stage the authorization of every matched output if state_mode != 0, and push nothing.

Cost: base + per_operand_byteΒ·(template_len + Ξ£popped) + per_tx_outputΒ·output_count (no result push). The per_tx_output term is flat: it does not depend on the output mode or on how many outputs match, so the static charge and the executed charge are the same. It pays for the scan and for the claim's phase-2 edges (at most one per output); see the claim assignment section for how the node value 32 was chosen. For the size pass, a literal template push immediately before the claim allows an exact pop count. Otherwise treat it as unknown and charge Worst(eb) with operands at the limit. This needs the new per_tx_output coefficient in VmOpcodeCost (defaults to 0; CheckCostProfile requires it to be > 0 for eb). [SIGN-OFF: the cost-model extension]

4.7 STATEHASH / STATEVERIFY / introspection (patches 063–065)

4.8 Signing, sighash and identities

4.10 What the daemon exposes for the compiler, wallet SDK and indexers (patch 069)

Editions and optimizer_version are compiler-only; the daemon never sees them. The daemon exposes:

  1. getv2vmprofile: the assigned-opcode inventory (single and EXT2) with a status, the opcodes.json SHA-256, VmProfile, VmCostProfile and their digests (the artifact "target profile digest"), plus loop and template limits.
  2. testv2transaction (strict, non-mutating): per-invocation status, error string, accounting/enforcement cost, matched j/claims/authorizations, the final unclaimed_value, and the post-check result.
  3. simulatev2transaction (Β§4.9): events, drafts, signing requests and provisional flags. Behind -v2simulationrpc (default on regtest/dev only). [SIGN-OFF]
  4. Stable error strings for ENFORCEOUTPUT/STATEVERIFY failures (enforce-no-match, enforce-template-*, state-mismatch, state-output-unauthorized, …).
  5. RPC and Chronik stateRoot. Chronik may index branches[0]/branches[1] by the slot convention (ABI Β§8). This is index-only: the daemon must not enforce the slot convention in consensus.

5. Patch-by-patch plan (V2 tier, appended to lotus-v2-stack-repair/daemon/patches/v2/series after 057)

Each patch is one authored commit on the V2 tier, exported with the stack's existing tooling. Each must replay cleanly and keep every intermediate tree buildable with its tests passing. Paths below are relative to the source root (src/).

# Title Files Tests
058 vm(v2): 16-bit opcode IR and EXT2 two-byte framing lotus_v2/vm.h, vm.cpp (Scan, Instruction), vm_cost.inc (OpCost, CheckCostProfile, ext table), vm_test/runner.cpp, test/fuzz/v2_vm_and_tx.cpp scan vectors Β§6.1 (lone ff Invalid, ff00/ff4c/ffff success, 01ff push payload, fe ff, ff in a skipped arm)
059 vm(v2): sync opcode allocation with registry (retire 67/68, EMITLOG invalid, register new bytes) vm.cpp (GenesisAssigned table, Scan 6c), vm_test/opcode_coverage.json (225 entries, new spec sha), vm_test/check_opcode_coverage.py, differential*.py, test_vm.cpp registry equality test; 67/68 now AutomaticSuccess; 6c Invalid everywhere incl. skipped arm/after RETURN/before success; new bytes Unsupported
060 vm(v2): unify loops on ENUMERATE with count-idiom static bound vm.cpp (Structure/Execute), vm_cost.inc (SizePass idiom) c9 69 … 6a at 0/1/256/257 inputs (257 β†’ Err); nested Γ—2; cost equals the old 67 charge for identical bodies
061 vm(v2): conditional BREAK vm.cpp, vm_cost.inc cond 0 continues, 1 exits; depth 2; invalid depth with cond 0 still Err; non-Boolean cond Err; skipped-arm BREAK no Err; SizePass fall-through
062 output(v2): HAS_STATE state_root in wire, coins, RPC and Chronik lotus_v2/output.h/.cpp, transaction.cpp, field_size.cpp, disk_state.cpp, fast_sync.cpp, sparse_state.cpp, block.cpp, ordinary_validation.cpp (interim reject), primitives/transaction.h/.cpp, compressor.h, validation.cpp (interim reject), kernel/coinstats.cpp, RPC/Chronik/wallet V2 output renderers test_output (844 maximum, flags 0x04/0x05, reject 0x06/0x07/0xf8/zero root), test_sparse_state 900, primitives round-trip, compressor round-trip, identities differ by state root, coinbase reject
063 vm(v2): UTXOFLAGS, UTXOSTATEROOT, OUTPUTSTATEROOT, ACTIVEBRANCHINDEX, ACTIVEWITNESSINDEX vm.cpp, vm_cost.inc (Transfer cases) mint/coinbase errors; βˆ’1 in mint; zeros without state
064 vm(v2): TXTOKENBALANCE with prepared asset totals vm.h/.cpp (PreparedVmTransaction), shared totals helper extracted from ordinary_validation.cpp native/token/absent asset; mint delta = outβˆ’in; burn outputs counted; 31/33-byte asset Err
065 vm(v2): INPUTWITNESSARG, STATEHASH, STATEVERIFY, Lotus/v2/contractstate vm.cpp, vm_cost.inc, field_size.*, tagged_hash.h/.cpp index bounds per input kind; k=0/64/65; preimage vectors from Python; STATEVERIFY mint Err, missing state Err, mismatch Err
066 validation(v2): transaction-scoped VM effects, canonical order, post-check, per-tx script check vm.h/.cpp, ordinary_validation.cpp, validation.cpp (V2 single check job), remove interim rejects from 062 staged effects discarded on failure; HAS_STATE without authorizer rejects; parallel block connect gives the same result as sequential; tl_cache reuse does not leak effects
067 vm(v2): ENFORCEOUTPUT strict mode and OutputTemplate parser new lotus_v2/output_template.h/.cpp, vm.cpp, vm_cost.inc (per_tx_output), CMakeLists.txt (both), vm_test/CMakeLists.txt Β§6.3 matrix; flash-loan, mint+vault, N-to-1 merge, double-claim, greedy-order and forged-state (I-10) cases
068 vm(v2): non-consensus simulation evaluator (EMITLOG, constructive ENFORCEOUTPUT) new lotus_v2/vm_simulation.h/.cpp, vm.cpp (simulation flag), CMake consensus rejects 6c while sim accepts; draft construction rules; signing requests; provisional flags
069 rpc(v2): VM profile, test and simulate RPCs; Chronik stateRoot; functional tests rpc/ V2 file(s), Chronik bridge, test/functional/feature_v2_vm_opcodes.py (new), test/fuzz/v2_vm_and_tx.cpp functional test: create, spend and continue a stateful vault; reorg/undo restores state roots and claims; RPC schema

Stop at 058–061 if I-1, I-3, I-5, I-6 or I-7 are unsigned. Stop 062 on I-8/I-9, 066 on I-11, 065 on I-12/I-13, 067 on I-14/I-17, and 068 on I-15.


6. Test vectors: what to generate and how

Use one generator, src/lotus_v2/vm_test/generate_opcode_vectors.py. It should import, not copy, the primitives from a pinned spec_candidate_checks.py (u, cs, blob, h, leaf, branch, indexed_tree_root, op, OPCODES, success_scan), loaded by path and pinned by SHA-256 the same way opcode_coverage.json pins opcodes.json. Patch success_scan locally for EXT2 (I-2) until the spec repo fixes it, and assert that the patched result differs from the upstream result only on ff-containing cases. Write the output to vm_test/v2_opcode_vectors.json, consumed by test_vm.cpp and runner.cpp. Run Python with -I. Where the reference VM covers the opcodes, run the differential against it.

  1. Scan/framing: all 31 single-byte success bytes; 67, 68; all 256 ff xx; lone ff; ff after a truncated push (error); 6c in every position; the CHK cases re-run.
  2. Control: ENUMERATE bounds 0/1/256/257; the idiom at counts 0/1/255/256/257; BREAK operand matrix {cond 0, 1, 2, non-16-byte} Γ— {depth 0, 1, 2, 3} Γ— {in loop, nested, skipped arm, top level}; expected status plus static and executed cost (unit schedule).
  3. ENFORCEOUTPUT matrix: each value_mode Γ— token_mode Γ— paths_mode Γ— burn Γ— wild Γ— state_mode over a fixed 4-output transaction. Mask overlap, out-of-range bits, truncation and trailing bytes; pop-order cases with three stack roots. Budget cases: 1-to-1 twice with identical templates (succeeds via unclaimed), N-to-1 (100+100 ≀ 200), over-claim (100+101 > 200). Greedy-order failure. Mint-only modes; INHERIT in a mint (Err).
  4. State: STATEHASH digests for k=0,1,64 and items of length 0/16/8192; STATEVERIFY outcomes; HAS_STATE output bytes, OutputLeaf, TxID and each sighash mode with and without state; Coin record of 900 bytes.
  5. Introspection: UTXOFLAGS, UTXOSTATEROOT, OUTPUTSTATEROOT, ACTIVE*, TXTOKENBALANCE and INPUTWITNESSARG per input kind (spend/mint), including out-of-range indexes.
  6. Example contracts: hand-assemble the bytecode equivalents of EX FlashVault.flash_loan, StakingMint.deposit_and_mint and StandardStakingVault.merge, and run them in full-transaction contexts. Adversarial variants: a forged-state authorizer (I-10) expected valid, documenting the weakness; a value shortfall; a wrong token; dropped paths.
  7. Simulation: given a zero-output draft, the drafts produced by each template; the EMITLOG event list.

Each vector records the registry SHA, generator commit, profile digest, script hex, arguments, transaction hex, resolved coins, expected status/error class, final stack, costs and effects.


7. Cost accounting and block limits


8. Risks

  1. Order dependence and parallelism (I-11). Missing one of the call paths, for example the validation.cpp CScriptCheck path, causes consensus divergence between mempool and block validation. Mitigation: one shared RunV2TransactionScripts() helper used by both paths, plus a parallel-vs-sequential test.
  2. Stale effects through tl_cache in validation.cpp. Mitigation: effects are never stored in PreparedVmTransaction.
  3. The compressor silently drops the HAS_STATE bit (verified bug if not fixed). This corrupts the coins DB and UTXO root. Mitigation: round-trip test in patch 062; reindex the dev chains.
  4. Genesis reallocation breaks every existing script and branch root that uses 67/68, or that relied on the bytes now assigned being OP_SUCCESS. Mitigation: regenerate fixtures; confirm no persistent V2 network relies on them (assumption).
  5. The state-authorization weakness (I-10) could lead to a false sense of security in contracts. Document it in the ABI and the compiler lints.
  6. The success-opcode soft-fork contract (I-17) is now constrained.
  7. Spec churn: HAS_STATE and ENFORCEOUTPUT are marked "Tentative" or "Recommended candidate". Freeze them before 062/067 merge.
  8. Cost schedule not frozen: unit-schedule tests only. Mainnet constants remain a separate P05 obligation.
  9. Unverified interfaces: RPC/Chronik render sites were not inspected; the reference Python VM is outside this repository.

Follow-up: generic two-phase (deferred) checks (user, 2026-10-20)

The spec is WIP and the deferred rules will change as contracts get built, so the post-check is a small generic mechanism, not ENFORCEOUTPUT-specific code.

Revision (user, 2026-10-20): accumulate inline against per-output counters

Instead of per-input effect lists checked afterwards, each check kind owns per-transaction accumulators, for example one atomic counter per output. Inputs update them as they run.

Unified accounting kinds (user, 2026-10-20)

Value conservation and ENFORCEOUTPUT claims use the same counter mechanism. Inputs and outputs add to or subtract from counters; final rules check the totals.

Kind Counter Adds Subtracts Final rule
Native conservation per tx input values output values (incl. burns) >= 0, remainder is fee
Token conservation per token id input amounts, mint deltas output amounts (incl. burns) == 0
ENFORCEOUTPUT claims per output output value (initial) each script's claim >= 0 at every step (fail fast)
State authorization per HAS_STATE output set by an authorizing script β€” must be set

ENFORCEOUTPUT claim assignment (user, 2026-10-20) β€” supersedes the per-output counter rows above