Skip to content
Developer Handbook

Cash Improvement Proposals

Functions Takes 2 and 3

On this page

CHIP-2025-08 · Alternative · Script

Proposes alternative constraints on how scripts can define function bytecode.

Original proposal

Specification

Take 2

Author’s Take 2 text

Title: Function Definition and Invocation Operations, Take II Type: Standards Layer: Consensus Maintainers: Jason Dreyzehner, Calin Culianu Status: Draft Initial Publication Date: 2024-12-12 Latest Revision Date: 2025-08-11 Version: 2.2.0

Executive Summary

This proposal is a fork of, and pretty much indentical to: CHIP-2025-05 Functions: Function Definition and Invocation Operations. The only difference is that this proposal adds an additional flag fCanDefineFunctions which restricts OP_DEFINE. In this proposal, OP_DEFINE is restricted to only be allowed to execute when this flag is true. The rules governing this flag prohibit "code that writes code". A description of this flag and how it operarates follows in the subsequent proposal below, which is more-or-less the same as the original proposal (with additions that describe fCanDefineFunctions and how it restricts OP_DEFINE). What follows is the amended original proposal:


Summary

This proposal introduces the OP_DEFINE and OP_INVOKE opcodes, enabling Bitcoin Cash contract bytecode to be factored into reusable functions.

Motivation & Benefits

  • Reduced transaction sizes – By eliminating duplicated bytecode, contract lengths can be optimized for a wider variety of use cases: finite field arithmetic, pairing-based cryptography, zero-knowledge proof systems, homomorphic encryption, post-quantum cryptography, and other important applications for the future security and competitiveness of Bitcoin Cash.

  • Stronger privacy and operational security – By enabling contract designs which leak less information about security measures, current assets, and transaction history, this proposal strengthens privacy and operational security for a variety of use cases.

  • Improved auditability – Without reusable functions, contracts are forced to unnecessarily duplicate significant logic. This proposal enables contracts to be written using more succinct, auditable patterns.

Deployment

Deployment of this specification is proposed for the May 2026 upgrade.

  • Activation is proposed for 1763208000 MTP, (2025-11-15T12:00:00.000Z) on chipnet.
  • Activation is proposed for 1778846400 MTP, (2026-05-15T12:00:00.000Z) on the BCH network (mainnet), testnet3, testnet4, and scalenet.

Technical Specification

The virtual machine is modified to add a Function Table of immutable functions, the OP_DEFINE opcode is defined at codepoint 0x89 (137), and the OP_INVOKE opcode is defined at 0x8a (138).

Function Table

The virtual machine (VM) is modified to add a new data structure: the Function Table is a data structure (such as a map or sparse array) that holds immutable byte vectors; it maps each defined function identifier to an immutable function body (the byte vector).

Due to VM limits, the function table does not exceed Maximum Cumulative Depth in length/count, and the function table's held byte vectors do not exceed the Stack Element Length Limit.

Defined Function Count

A Defined Function Count counter is added to track the count of defined functions.

Function Identifier

A function identifier – the function's index in the function table – is an integer greater than or equal to 0 and less than Maximum Cumulative Depth (currently, 1000).

Maximum Cumulative Depth (MAX_CUMULATIVE_DEPTH)

The existing cumulative stack and altstack depth limit (A.K.A. MAX_STACK_SIZE; 1000 items) is modified to incorporate Defined Function Count: the sum of stack depth, alternate stack depth, and Defined Function Count must be less than 1000.

Can Define Functions Flag (fCanDefineFunctions)

A flag is introduced, fCanDefineFunctions, which is initially set to true at the start of an evaluation. It remains true so long as the code being executed is one of the following opcodes:

  • A data push opcode: OP_0, OP_1 through OP_16, OP_1NEGATE, direct data push <= 75 bytes, OP_PUSHDATA1, OP_PUSHDATA2, or OP_PUSHDATA4
  • An OP_DEFINE opcode
  • A stack manipulation opcode in the following inclusive range: OP_TOALTSTACK (0x6b) through OP_TUCK (0x7d), except for OP_DEPTH (0x74)

For any other opcode (such as OP_CAT, OP_SPLIT, OP_ADD, OP_IF, OP_HASH160, OP_DEPTH, etc), the flag gets latched to false for the remainder of the evaluation. If this flag is false, subsequent OP_DEFINE opcodes encountered in the script will fail the script immediately.

The intent of this new flag is to prevent "code that writes code" situations. This flag forces scripts to essentially push all the code they intend to use as functions up-front, and disallows on-the-fly construction of stack data items intended to be used as code, such that all the code a script will execute as functions is immediately apparent and forced to exist "at the top" of the script bytecode, (more or less). In essence, this flag restricts precisely when and how OP_DEFINE can be used.

It is intended that this flag, and thus the restriction it introduces, will constrain scripts that make use of functions to be more easily amenable to static analysis.

This flag (and thus the restriction on how OP_DEFINE can be used) may be removed in a future Bitcoin Cash network upgrade in order to explicitly allow "code that writes code".

Notice of Possible Future Expansion

While unusual, it is possible to design pre-signed transactions, contract systems, and protocols which rely on the rejection of otherwise-valid transactions made invalid only by specifically exceeding one or more current VM limits. This proposal interprets such failure-reliant constructions as intentional – the constructions are designed to fail unless/until a possible future network upgrade in which such limits are increased, e.g. upgrade-activation futures contracts. Contract authors are advised that future upgrades may raise VM limits by increasing Maximum Cumulative Depth, or otherwise. See Limits CHIP Rationale: Inclusion of "Notice of Possible Future Expansion".

Reset Before Each Bytecode Evaluation

Prior to each phase of evaluation (unlocking bytecode, locking bytecode, and redeem bytecode), the Function Table, Defined Function Count, and fCanDefineFunctions flag must be reset to an empty table, 0, and true respectively.

OP_DEFINE

<function_body> <function_identifier> OP_DEFINE

The OP_DEFINE opcode is defined at codepoint 0x89 (137) with the following behavior:

  1. If the fCanDefineFunctions flag is false, fail execution immediately, otherwise:
  2. Pop the top item from the stack to interpret as a function identifier (a VM Number between 0 and 999, inclusive).1
  3. Pop the next item from the stack to interpret as the function body2, and copy it to the function table at the index equal to the function identifier. If that function index is out of range or already defined, error.3
  4. Increment Defined Function Count by one.4
OP_DEFINE Clarifications
  1. If the stack is empty (no function_identifier), error. If the popped item is not a VM Number between 0 and 999 (inclusive), error. See Rationale: Use of Stack-Based Parameters and Rationale: Use of Positive Integer-Based Function Identifiers.
  2. if the stack is empty (no function_body), error. Note that any stack item is a valid function body (including empty stack items); implementations must not attempt to parse the function body until invoked by OP_INVOKE. See Rationale: Deferred Parsing of Function Bodies.
  3. See Rationale: Immutability of Function Bodies. Note also that function identifiers/table indexes may be defined in any order. See Rationale: Support for Skipping Function Identifiers.
  4. Note that the Operation Cost of OP_DEFINE is equal to the Base Instruction Cost.

OP_INVOKE

<function_identifier> OP_INVOKE

The OP_INVOKE opcode is defined at codepoint 0x8a (138) with the following behavior:

  1. Pop the top item from the stack to interpret as a function identifier.1
  2. 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 (Note that this subjects function invocations to the existing control stack depth limit of 100.)
  3. Reset the instruction pointer and last executed code separator, then execute the function body as if it were the active bytecode.3 If the bytecode is malformed (i.e. a push operation requires more bytes than are available in the remaining segment of bytecode to be parsed), error.
  4. When the evaluation is complete4, restore the original bytecode, instruction pointer, and last executed code separator, then continue evaluation after the OP_INVOKE instruction.5
OP_INVOKE Clarifications
  1. If the stack is empty (no function_identifier), error. If the popped item is not a VM Number representing a previously-defined function in the function table, error. If the referenced function body has a length of zero: error if the control stack depth limit of 100 would be exceeded by a non-empty evaluation; otherwise, continue after the OP_INVOKE instruction.
  2. Note that this requires the control stack to be capable of holding a new stack frame data type to preserve the state of the parent evaluation.
  3. OP_INVOKEed bytecode otherwise shares the context of the parent evaluation:
    1. Invoked functions may modify the stack and alternate stack without limitation, and control stack usage (e.g. OP_IF/OP_END_IF or further OP_INVOKEs) within the evaluation remains restricted by the 100-item depth limit.
    2. Executed OP_CODESEPARATOR operations record the index of the current instruction pointer (A.K.A. pc) within the OP_INVOKEed bytecode as the last executed code separator (A.K.A. pbegincodehash).
    3. The OP_ACTIVEBYTECODE operation produces the serialization of the active bytecode beginning from the last executed code separator.
    4. 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).
  4. For an OP_INVOKE evaluation to complete successfully, the top element remaining on the control stack must be a stack frame to resume after the evaluation. (E.g. Validation fails if an OP_IF within the evaluation is not resolved by a matching OP_ENDIF within the same evaluation.)
  5. After an active bytecode has been fully evaluated, the next stack frame is resumed (restoring its bytecode, instruction pointer, and last executed code separator values) until all stack frames are complete (the control stack is empty) or the evaluation has produced some error. Note that two or more OP_INVOKE operations may be resolved within the same virtual machine step (e.g. if a child OP_INVOKE is the final instruction of a parent OP_INVOKE evaluation). Note that the Operation Cost of OP_INVOKE is equal to the Base Instruction Cost.

Rationale

Evaluations of Alternatives

Risk Assessment

Test Vectors

This proposal includes a suite of functional tests and benchmarks to verify the performance of all operations within virtual machine implementations.

Implementations

Please see the following implementations for examples and additional test vectors:

Feedback & Reviews

Changelog

This section summarizes the evolution of this document.

  • v2.1.0 - 2025-08-11
    • Come up with the fCanDefineFunctions scheme to prohibit "code that writes code".
  • v2.0.0 – 2025-05-27
    • Split OP_EVAL into OP_DEFINE and OP_INVOKE
  • v1.0.1 – 2025-05-02
  • v1.0.0 – 2024-12-12
    • Initial publication

This document is placed in the public domain.

Take 3

Author’s Take 3 text

Title: Function Definition and Invocation Operations, Take III Type: Standards Layer: Consensus Maintainers: Jason Dreyzehner, Calin Culianu, Bitcoin Cash Autist Status: Draft Initial Publication Date: 2024-12-12 Latest Revision Date: 2025-08-11 Version: 2.3.0

Executive Summary

This proposal is a fork of, and pretty much indentical to: CHIP-2025-05 Functions: Function Definition and Invocation Operations. The only difference is that this proposal adds an additional concept, the stack data item executable bit, which restricts OP_DEFINE. In this proposal, OP_DEFINE is restricted to only be allowed to execute successfully when the data item it is given for the function body has its executable bit set to 1. The rules governing this bit prohibit "code that writes code". A description of this bit and how it operarates follows in the subsequent proposal below, which is more-or-less the same as the original proposal (with additions that describe the newly-introduced executable bit mechanism). What follows is the amended original proposal:


Summary

This proposal introduces the OP_DEFINE and OP_INVOKE opcodes, enabling Bitcoin Cash contract bytecode to be factored into reusable functions.

Motivation & Benefits

  • Reduced transaction sizes – By eliminating duplicated bytecode, contract lengths can be optimized for a wider variety of use cases: finite field arithmetic, pairing-based cryptography, zero-knowledge proof systems, homomorphic encryption, post-quantum cryptography, and other important applications for the future security and competitiveness of Bitcoin Cash.

  • Stronger privacy and operational security – By enabling contract designs which leak less information about security measures, current assets, and transaction history, this proposal strengthens privacy and operational security for a variety of use cases.

  • Improved auditability – Without reusable functions, contracts are forced to unnecessarily duplicate significant logic. This proposal enables contracts to be written using more succinct, auditable patterns.

Deployment

Deployment of this specification is proposed for the May 2026 upgrade.

  • Activation is proposed for 1763208000 MTP, (2025-11-15T12:00:00.000Z) on chipnet.
  • Activation is proposed for 1778846400 MTP, (2026-05-15T12:00:00.000Z) on the BCH network (mainnet), testnet3, testnet4, and scalenet.

Technical Specification

The virtual machine is modified to add a Function Table of immutable functions, the OP_DEFINE opcode is defined at codepoint 0x89 (137), and the OP_INVOKE opcode is defined at 0x8a (138).

Function Table

The virtual machine (VM) is modified to add a new data structure: the Function Table is a data structure (such as a map or sparse array) that holds immutable byte vectors; it maps each defined function identifier to an immutable function body (the byte vector).

Due to VM limits, the function table does not exceed Maximum Cumulative Depth in length/count, and the function table's held byte vectors do not exceed the Stack Element Length Limit.

Defined Function Count

A Defined Function Count counter is added to track the count of defined functions.

Function Identifier

A function identifier – the function's index in the function table – is an integer greater than or equal to 0 and less than Maximum Cumulative Depth (currently, 1000).

Maximum Cumulative Depth (MAX_CUMULATIVE_DEPTH)

The existing cumulative stack and altstack depth limit (A.K.A. MAX_STACK_SIZE; 1000 items) is modified to incorporate Defined Function Count: the sum of stack depth, alternate stack depth, and Defined Function Count must be less than 1000.

Stack Data Item Executable Bit

A new concept is introduced: the stack data item excutable bit. The intent behind this bit is to track the provenance of stack data items such that only immediately pushed data items or their copies can ever be used in conjunction with OP_DEFINE, and other data items that are the results of some computation (such as OP_CAT) cannot. This mechanism thus prevents "code that writes code" scenarios.

  • This bit is always set to 1 for data items resulting from a push opcode, which are the following opcodes: OP_0, OP_1 through OP_16, OP_1NEGATE, direct data push <= 75 bytes, OP_PUSHDATA1, OP_PUSHDATA2, or OP_PUSHDATA4
  • This bit is inherited when copying stack items around. So the bit is the same for the newly created copy as it was for the original for opcodes that copy items, which are the following opcodes: OP_TOALTSTACK, OP_FROMALTSTACK, OP_2DUP, OP_3DUP, OP_2ROT, OP_2SWAP, OP_IFDUP, OP_DUP, OP_OVER, OP_PICK, OP_ROLL, OP_ROT, OP_SWAP, OP_TUCK.
  • For all other opcodes (including introspection opcodes such as OP_UTXOBYTECODE), newly-created stack items that result from that opcode always have the executable bit set to 0.

This flag is checked when an OP_DEFINE is encountered by the virtual machine, and only stack data items that have the executable bit set to 1 may be added to the function table. If the data item given to OP_DEFINE has this bit set to 0, then the evaluation fails.

By preventing "code that writes code", it is intended that this mechanism will constrain scripts that make use of functions to be more easily amenable to static analysis.

This executable bit mechanism (and thus the restriction on what types of data items can be given to OP_DEFINE) may be removed in a future Bitcoin Cash network upgrade in order to explicitly allow for "code that writes code".

Notice of Possible Future Expansion

While unusual, it is possible to design pre-signed transactions, contract systems, and protocols which rely on the rejection of otherwise-valid transactions made invalid only by specifically exceeding one or more current VM limits. This proposal interprets such failure-reliant constructions as intentional – the constructions are designed to fail unless/until a possible future network upgrade in which such limits are increased, e.g. upgrade-activation futures contracts. Contract authors are advised that future upgrades may raise VM limits by increasing Maximum Cumulative Depth, or otherwise. See Limits CHIP Rationale: Inclusion of "Notice of Possible Future Expansion".

Reset Before Each Bytecode Evaluation

Prior to each phase of evaluation (unlocking bytecode, locking bytecode, and redeem bytecode), the Function Table and Defined Function Count must be reset to an empty table and 0, respectively.

OP_DEFINE

<function_body> <function_identifier> OP_DEFINE

The OP_DEFINE opcode is defined at codepoint 0x89 (137) with the following behavior:

  1. Pop the top item from the stack to interpret as a function identifier (a VM Number between 0 and 999, inclusive).1
  2. Pop the next item from the stack to interpret as the function body2. If the item has its executable bit set to 0, then error, otherwise copy the item to the function table at the index equal to the function identifier. If that function index is out of range or already defined, error.3
  3. Increment Defined Function Count by one.4
OP_DEFINE Clarifications
  1. If the stack is empty (no function_identifier), error. If the popped item is not a VM Number between 0 and 999 (inclusive), error. See Rationale: Use of Stack-Based Parameters and Rationale: Use of Positive Integer-Based Function Identifiers.
  2. if the stack is empty (no function_body), error. Note that any stack item is a valid function body (including empty stack items); implementations must not attempt to parse the function body until invoked by OP_INVOKE. See Rationale: Deferred Parsing of Function Bodies.
  3. See Rationale: Immutability of Function Bodies. Note also that function identifiers/table indexes may be defined in any order. See Rationale: Support for Skipping Function Identifiers.
  4. Note that the Operation Cost of OP_DEFINE is equal to the Base Instruction Cost.

OP_INVOKE

<function_identifier> OP_INVOKE

The OP_INVOKE opcode is defined at codepoint 0x8a (138) with the following behavior:

  1. Pop the top item from the stack to interpret as a function identifier.1
  2. 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 (Note that this subjects function invocations to the existing control stack depth limit of 100.)
  3. Reset the instruction pointer and last executed code separator, then execute the function body as if it were the active bytecode.3 If the bytecode is malformed (i.e. a push operation requires more bytes than are available in the remaining segment of bytecode to be parsed), error.
  4. When the evaluation is complete4, restore the original bytecode, instruction pointer, and last executed code separator, then continue evaluation after the OP_INVOKE instruction.5
OP_INVOKE Clarifications
  1. If the stack is empty (no function_identifier), error. If the popped item is not a VM Number representing a previously-defined function in the function table, error. If the referenced function body has a length of zero: error if the control stack depth limit of 100 would be exceeded by a non-empty evaluation; otherwise, continue after the OP_INVOKE instruction.
  2. Note that this requires the control stack to be capable of holding a new stack frame data type to preserve the state of the parent evaluation.
  3. OP_INVOKEed bytecode otherwise shares the context of the parent evaluation:
    1. Invoked functions may modify the stack and alternate stack without limitation, and control stack usage (e.g. OP_IF/OP_END_IF or further OP_INVOKEs) within the evaluation remains restricted by the 100-item depth limit.
    2. Executed OP_CODESEPARATOR operations record the index of the current instruction pointer (A.K.A. pc) within the OP_INVOKEed bytecode as the last executed code separator (A.K.A. pbegincodehash).
    3. The OP_ACTIVEBYTECODE operation produces the serialization of the active bytecode beginning from the last executed code separator.
    4. 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).
  4. For an OP_INVOKE evaluation to complete successfully, the top element remaining on the control stack must be a stack frame to resume after the evaluation. (E.g. Validation fails if an OP_IF within the evaluation is not resolved by a matching OP_ENDIF within the same evaluation.)
  5. After an active bytecode has been fully evaluated, the next stack frame is resumed (restoring its bytecode, instruction pointer, and last executed code separator values) until all stack frames are complete (the control stack is empty) or the evaluation has produced some error. Note that two or more OP_INVOKE operations may be resolved within the same virtual machine step (e.g. if a child OP_INVOKE is the final instruction of a parent OP_INVOKE evaluation). Note that the Operation Cost of OP_INVOKE is equal to the Base Instruction Cost.

Rationale

Evaluations of Alternatives

Risk Assessment

Test Vectors

This proposal includes a suite of functional tests and benchmarks to verify the performance of all operations within virtual machine implementations.

Implementations

Please see the following implementations for examples and additional test vectors:

Feedback & Reviews

Changelog

This section summarizes the evolution of this document.

  • v2.3.0 - 2025-08-11
    • Added the executable bit concept to prevent "code that writes code".
  • v2.0.0 – 2025-05-27
    • Split OP_EVAL into OP_DEFINE and OP_INVOKE
  • v1.0.1 – 2025-05-02
  • v1.0.0 – 2024-12-12
    • Initial publication

This document is placed in the public domain.