Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

BCH 2026 VM: OP_INVOKE does not save/reset/restore the last executed code separator (Functions CHIP, BCHN) #167

Open

Description

@mr-zwets

On behalf of Mathieu G. (mr-zwets), written by Claude Opus 5.5:

Summary

In the BCH 2026 instruction set, OP_INVOKE saves and restores only the instructions and the instruction pointer. lastCodeSeparator is one shared program-state index, and libauth applies it to whatever bytecode is currently active. The Functions CHIP and Bitcoin Cash Node give each invocation its own last-code-separator: it is saved on invoke, reset for the body, and restored on return. This has two effects:

  1. Caller separator applied to the body. If the caller executed OP_CODESEPARATOR at instruction k before OP_INVOKE, libauth slices the function body at k + 1 inside the function. The CHIP and BCHN use the whole body.
  2. Body separator applied to the caller. If the function body executes OP_CODESEPARATOR at instruction j, then after the return libauth slices the caller's bytecode at j + 1. The CHIP and BCHN keep the caller's own position.

This affects OP_ACTIVEBYTECODE and the covered bytecode (scriptCode) of OP_CHECKSIG(VERIFY) and OP_CHECKMULTISIG(VERIFY). It changes consensus results in both directions. Signatures made per the CHIP fail in libauth (NULLFAIL), and libauth accepts signatures that BCHN rejects.

Found while comparing a formal model of the VM against BCHN.

Versions checked: @bitauth/libauth@3.1.0-next.8 from npm (the current next tag) and the next branch at 0534f9bb (2025-09-19). Both behave the same way. BCHN v29.1.0.

Specification

CHIP-2025-05 Functions, OP_INVOKE, items 2–4:

  1. Preserve the active bytecode (A.K.A. script), instruction pointer (A.K.A. program counter or pc), and index of the last executed code separator (A.K.A. pbegincodehash) by pushing them to the top of the control stack.
  2. Reset the instruction pointer and last executed code separator, then execute the function body as if it were the active bytecode.
  3. When the evaluation is complete, restore the original bytecode, instruction pointer, and last executed code separator, then continue evaluation after the OP_INVOKE instruction.

Clarifications 3.2–3.4:

Executed OP_CODESEPARATOR operations record the index of the current instruction pointer […] within the OP_INVOKEed bytecode as the last executed code separator […]. In signature operations, the covered bytecode includes only the active bytecode beginning from the last executed code separator (or if none have been executed in the current evaluation, the full active bytecode).

Bitcoin Cash Node

src/script/interpreter.cpp (v29.1.0):

  • Each EvalFrame has its own pbegincodehash, initialised to the start of that frame's script (L236-256):
    const uint8_t *pbegincodehash;  ///< Initially equal to `pc`, but updated if we encounter OP_CODESEPARATOR opcodes
    ...
    EvalFrame(size_t cumCtr, const ByteView &script_)
        : cumulativeCtr(cumCtr), script{script_}, pc{script.data()}, pbegincodehash{pc} {}
  • OP_INVOKE pushes a new frame for the body (L628-651, evalStack.pushFrame(it->second)).
  • At the end of the body, the frame is popped and the caller's frame resumes with its own, untouched pbegincodehash (L2299-2301).
  • OP_CODESEPARATOR updates only the current frame (pbegincodehash = pc, L1417-1420).
  • The consumers use the current frame's (pbegincodehash, pend):

libauth

When no OP_CODESEPARATOR executes, or when the separator and its consumer are in the same frame and no separator from another frame intervenes, both sides agree. That is probably why the existing chip.functions VMB vectors pass. For example, "Expected OP_ACTIVEBYTECODE inside nested definition, one truncated at OP_CODESEPARATOR" does leak the index back to the caller, but the caller never reads it afterwards.

Reproduction

The script uses only @bitauth/libauth@3.1.0-next.8 (Node 24). It evaluates three single-input transactions in the BCH 2026 VM in consensus mode. The same transactions were funded on a BCHN v29.1.0 regtest node (-upgrade12activationheight=1) and submitted with testmempoolaccept, and the accepted ones were mined into a block.

// OP_INVOKE / OP_CODESEPARATOR: libauth vs. the Functions CHIP / BCHN rule.
// npm install @bitauth/libauth@3.1.0-next.8 && node repro.mjs
import {
  createVirtualMachineBch2026, encodeDataPush, flattenBinArray,
  generateSigningSerializationBch, hexToBin, binToHex, secp256k1, sha256,
} from '@bitauth/libauth';

const vm = createVirtualMachineBch2026(false); // consensus mode
const b = (...x) => Uint8Array.of(...x);
const cat = (...x) => flattenBinArray(x);
const push = encodeDataPush;
const [OP_0, OP_1, OP_3, OP_13, OP_DROP, OP_NIP, OP_SIZE, OP_DEFINE, OP_INVOKE, OP_NUMEQUAL,
  OP_CODESEPARATOR, OP_CHECKSIG, OP_ACTIVEBYTECODE] =
  [0x00, 0x51, 0x53, 0x5d, 0x75, 0x77, 0x82, 0x89, 0x8a, 0x9c, 0xab, 0xac, 0xc1];
const p2pkh = b(0x76, 0xa9, 0x14, ...new Uint8Array(20), 0x88, 0xac);

const evaluate = (locking, makeUnlocking = () => b()) => {
  const sourceOutputs = [{ lockingBytecode: locking, valueSatoshis: 100_000n }];
  const transaction = { version: 2, locktime: 0,
    inputs: [{ outpointTransactionHash: hexToBin('11'.repeat(32)), outpointIndex: 0, sequenceNumber: 0xffffffff, unlockingBytecode: b() }],
    outputs: [{ lockingBytecode: p2pkh, valueSatoshis: 99_000n }] };
  transaction.inputs[0].unlockingBytecode = makeUnlocking(transaction, sourceOutputs);
  const result = vm.verify({ sourceOutputs, transaction });
  return result === true ? 'accept' : `reject (${result})`;
};

// 1) Caller's code separator applied to the function body.
//    <OP_ACTIVEBYTECODE OP_SIZE OP_NIP> <1> OP_DEFINE OP_CODESEPARATOR <1> OP_INVOKE <3> OP_NUMEQUAL
//    CHIP/BCHN: inside the body the active bytecode is the whole 3-byte body.
const b1 = cat(push(b(OP_ACTIVEBYTECODE, OP_SIZE, OP_NIP)), b(OP_1, OP_DEFINE, OP_CODESEPARATOR, OP_1, OP_INVOKE, OP_3, OP_NUMEQUAL));
console.log('1)', binToHex(b1), evaluate(b1));

// 2) Function's code separator applied to the caller after return.
//    <OP_0 OP_DROP OP_CODESEPARATOR> <1> OP_DEFINE <1> OP_INVOKE OP_ACTIVEBYTECODE OP_SIZE OP_NIP <13> OP_NUMEQUAL
//    CHIP/BCHN: after return the caller's active bytecode is the whole 13-byte script.
const b2 = cat(push(b(OP_0, OP_DROP, OP_CODESEPARATOR)), b(OP_1, OP_DEFINE, OP_1, OP_INVOKE, OP_ACTIVEBYTECODE, OP_SIZE, OP_NIP, OP_13, OP_NUMEQUAL));
console.log('2)', binToHex(b2), evaluate(b2));

// 3) Signature hash: <OP_CHECKSIG> <1> OP_DEFINE OP_CODESEPARATOR <1> OP_INVOKE, unlocked by <sig> <pubkey>.
//    CHIP/BCHN scriptCode inside the body = 0xac (the whole body); libauth uses body.slice(4) = empty.
const b3 = cat(push(b(OP_CHECKSIG)), b(OP_1, OP_DEFINE, OP_CODESEPARATOR, OP_1, OP_INVOKE));
const key = hexToBin('11'.repeat(32));
const signOver = (coveredBytecode) => (transaction, sourceOutputs) => {
  const ser = generateSigningSerializationBch({ inputIndex: 0, sourceOutputs, transaction },
    { coveredBytecode, signingSerializationType: b(0x41) }, sha256);
  const sig = secp256k1.signMessageHashSchnorr(key, sha256.hash(sha256.hash(ser)));
  return cat(push(cat(sig, b(0x41))), push(secp256k1.derivePublicKeyCompressed(key)));
};
console.log('3a) signed over scriptCode 0xac (CHIP/BCHN):', evaluate(b3, signOver(b(OP_CHECKSIG))));
console.log('3b) signed over empty scriptCode (libauth):  ', evaluate(b3, signOver(b())));

libauth output (abridged):

1) 03c182775189ab518a539c reject (... completed with a non-truthy value on top of the stack ...)
2) 030075ab5189518ac182775d9c reject (... completed with a non-truthy value on top of the stack ...)
3a) signed over scriptCode 0xac (CHIP/BCHN): reject (... Program failed a signature verification with a non-null signature (violating the "NULLFAIL" rule). Algorithm used: Schnorr.)
3b) signed over empty scriptCode (libauth):   accept

In 1), libauth's OP_ACTIVEBYTECODE pushes 0x (empty) instead of 0xc18277. In 2), it pushes 0x518ac182775d9c (the caller sliced after index 2, the body's separator) instead of the whole 13-byte script.

BCHN v29.1.0 (regtest, same scripts and transaction shapes, real parent outpoints):

case libauth 3.1.0-next.8 BCHN v29.1.0 testmempoolaccept
1 reject allowed (and mined)
2 reject allowed (and mined)
3a reject (NULLFAIL) allowed (and mined)
3b accept 16: mandatory-script-verify-flag-failed (Signature must be zero for failed CHECK(MULTI)SIG operation)

Expected and actual behaviour

  • Expected: on OP_INVOKE, the caller's last-code-separator index is saved with the frame and reset to "none" for the body. On return it is restored. OP_ACTIVEBYTECODE and signature operations then cover the active bytecode of the current frame from that frame's last separator.
  • Actual: one index is shared by all frames and applied to whichever bytecode is active. Both directions change verdicts: cases 1, 2 and 3a pass on BCHN and fail in libauth, and case 3b passes in libauth and fails on BCHN.

Impact

  • Signing. Wallets and compilers that use libauth to produce signatures (e.g. CashScript / Bitauth IDE flows) compute a different sighash than nodes. This happens for any function that contains, or is invoked after, an OP_CODESEPARATOR. Signatures made that way are rejected by the network.
  • Verification. Tools that verify with libauth reject valid transactions.
  • Covenants. Covenant code that compares OP_ACTIVEBYTECODE inside or after a function gets different bytes in libauth than on the network.

Suggested fix

Carry lastCodeSeparator in the function stack frame:

// vm-types.ts: AuthenticationProgramStackFrame (or a function-frame type used by OP_INVOKE)
lastCodeSeparator?: number;

// bch-2026-functions.ts, opInvoke
const finalState = pushToControlStack(nextState, {
  instructions: nextState.instructions,
  ip: nextState.ip + manuallyAdvance,
  lastCodeSeparator: nextState.lastCodeSeparator,
});
finalState.lastCodeSeparator = -1;

// bch-2026-instruction-set.ts, continue
const { instructions, ip, lastCodeSeparator } = state.controlStack.pop() as AuthenticationProgramStackFrame;
state.ip = ip;
state.instructions = instructions;
state.lastCodeSeparator = lastCodeSeparator ?? -1;

With the equivalent three-line change applied to a local copy of the 3.1.0-next.8 build:

  • all four cases above match BCHN: 1, 2 and 3a accept, 3b rejects;
  • the BCH 2026 VMB vectors shipped with BCHN (src/test/data/vmb_tests/bch_2026_{standard,nonstandard,invalid}, 29,731 vectors, consensus mode) still all pass, the same as unpatched.

VMB vectors like cases 1–3 (separator before an invoke, separator inside a body followed by a read in the caller, and a signature inside a body) would guard it.

bch-spec-eval.ts (OP_EVAL, not part of the 2026 rules) uses the same frame shape and may need the same change.

Thank you for libauth and the VMB test suite.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions