Three new Tapleaf 0xc2 (GSR) drafts, building on BIP 440 and BIP 441 as revised in #2358.
- OP_TX: transaction introspection
- Extended Primitives: OP_CHECKSIGFROMSTACK, OP_TWEAKADD and OP_BYTEREV
- Reusable Macros: OP_MACRO and OP_CALLMACRO
Transaction introspection for Tapleaf 0xc2.
OP_CHECKSIGFROMSTACK, OP_TWEAKADD and OP_BYTEREV for Tapleaf 0xc2.
OP_MACRO and OP_CALLMACRO for Tapleaf 0xc2.
55 | + 56 | +Each *declaration* is OP_MACRO, the length of its body as a CompactSize, and the body. Bodies are numbered from 0 in the order they appear. Everything after the last declaration is the *main script*; without declarations, the whole script is the main script. 57 | + 58 | +A *reference*, `OP_CALLMACRO <index>` with the index as a CompactSize, names a body by its number. References can appear in bodies and in the main script. 59 | + 60 | +Lengths and indices are CompactSize integers, as in Bitcoin's transaction serialization, and must use the shortest encoding. For example, 5 must be encoded as `05`; its longer encoding `fd 05 00` makes the scan fail.
I think this should be OP_MACRO [push] rather than compactsize + length, with push being minimal, but at least two bytes of data (because a zero or one byte macro would be pointless and that removes ambiguity with op_1 etc), which makes it easier for existing parsers to parse the new scripts. That's one byte longer for 76-252 byte macros and one byte shorter for 253-255 byte macros, and everything else is the same, I think.
Ditto for OP_CALLMACRO [pushnum] to make parsing sensible. Since number pushes are all treated as unsigned per bip 441, that imposes a +1 byte cost for each call for macros 17-127 and also 128-252.
I think this would also avoid introducing CompactSize parsing into script interpretation.
Agreed, for parsing it's better to not introduce CompactSize into the script interpreter.
The intention with CompactSize was to keep small values (for macro indices and for body lengths) as compact as possible, I suppose most scripts have less than 253 macros and short bodies.
Your byte counts seem correct, I tested this alternative on a few constructions: the difference is negligible for the SHRINCS and RISC Zero verifiers (1–12 bytes, 14–16 macros), and only a Stwo verifier with 128 macros grows by about 4%.
Keeping the committed script parsable as ordinary script is sensible and we will switch it to that:
OP_MACRO <body>, where the length prefix and the body form a minimal push and the body is at least 2 bytes.OP_CALLMACRO <index>, where index is a minimal number push.185 | +OP_SUCCESS80 # main script 186 | +``` 187 | + 188 | +## Security Considerations 189 | + 190 | +Nested references let a small committed script describe a large unrolled script, so script weight alone no longer limits the number of executed operations. The size limit bounds the unrolled script's memory to 4,000,000 bytes per script. This assumes the unrolled script is written in one pass that follows each reference into its body, in time linear in the unrolled length and references visited. Unrolling each body separately first would hold every intermediate expansion, which is subject to neither the limit nor the charge. The unrolling charge is computed and paid before the unrolled script is constructed, so unrolling work is metered even when the unrolled script is tiny. Execution of the unrolled script is metered by BIP 440 as for any script.
This seems somewhat inconsistent with the bip440 varops budget which describes the varops budget being set as a fixed multiple of the transaction weight -- so script weight alone presumably does still limit the number of executed operations.
There's possibly something of conflicting goals there -- you want the script to have minimal varops usage when executed, then you want to compress the script to reduce the weight, but you don't want to compress the script so far that the executed varops ends up exceeding the reduced weight.
I don’t think there is a conflict here, it’s only unclear phrasing on my side: the varops budget still limits script execution. It was meant as a more general statement that, with macros, a single unit of weight can stand for multiple executed instructions. I’ll rephrase it.
The trade-off is intended: macros let scripts with many cheap, repeated operations, such as field arithmetic, take up much less block space and in turn use a larger share of the varops budget the smaller size still funds.
189 | + 190 | +Nested references let a small committed script describe a large unrolled script, so script weight alone no longer limits the number of executed operations. The size limit bounds the unrolled script's memory to 4,000,000 bytes per script. This assumes the unrolled script is written in one pass that follows each reference into its body, in time linear in the unrolled length and references visited. Unrolling each body separately first would hold every intermediate expansion, which is subject to neither the limit nor the charge. The unrolling charge is computed and paid before the unrolled script is constructed, so unrolling work is metered even when the unrolled script is tiny. Execution of the unrolled script is metered by BIP 440 as for any script. 191 | + 192 | +Only committed bodies can be executed, and literal references prevent witness-supplied code and computed references. References go only to earlier declarations, so there is no recursion. The scan is unmetered but linear in the committed script's length, which weight funds. 193 | + 194 | +If scripts compressed with macros become common, mean block validation time could rise, because such scripts use much more of the varops budget their weight funds than typical transactions do. It still stays within the worst case that existing script versions, including Tapleaf 0xc0, already allow, which BIP 440 calibrates the budget not to exceed.
Right, I added this part after remembering this delving discussion, the target of the budget is one of the main design decisions of BIP440 and I'm happy to discuss it further, I still think that arguing "no slower than worst case 0xc0" is fine, but I get your position, if we expect typical blocks to use close to 100% of varops, the budget itself should have a target that is acceptable for those typical blocks.
114 | + 115 | +**One scan.** Scanning the whole committed script once, in serialized order, makes the scan result depend only on the committed script, keeps the BIP 342 OP_SUCCESSx rule in its simplest form, and takes linear time. Counting OP_SUCCESSx in unreferenced bodies matches BIP 342, where an OP_SUCCESSx in a branch that never executes also makes the script succeed, and preserves the most room for future soft forks to redefine OP_SUCCESSx inside bodies. 116 | + 117 | +**Size limit.** Nested references can grow the unrolled script exponentially in the size of the committed script, and the unrolled script is held in memory. The budget does not limit that memory, because it prices time: a standard-size transaction could pay to write hundreds of megabytes of unrolled script. A separate limit is therefore needed, just as BIP 441 keeps explicit stack limits alongside the budget. It equals the block weight limit, which also applies to every script written inline, so macros reduce a program's weight but do not let it grow past that limit. It is also the limit on the size of a stack element. The scan applies the limit at the instruction that crosses it, rather than to the finished totals, so it is a local rule like every other scan failure and the first success or failure in serialized order still decides. A body over the limit could never be part of a valid unrolled script, so the scan rejects it even when it is not referenced, and the totals stay within the limit without saturating arithmetic, except for references visited. 118 | + 119 | +**Varops charge.** Weight pays for the instructions of the main script but not for instructions substituted from bodies, so the unrolling charge prices the work of unrolling itself. Each substituted instruction pays `BASE`, including instructions that execution later skips in an inactive branch; otherwise a single reference inside an inactive branch could make validators process up to 4,000,000 instructions per script without charge. Each reference visited also pays `BASE`, because nesting can make their number large without adding any bytes. `BASE` per instruction does not cover copying large pushes: a body holding one push of 3,997 bytes is one instruction but copies 4,000 bytes, and a block full of such scripts would copy far more bytes than BIP 440 funds. Constructing the unrolled script copies `unrolled length` bytes into new storage, which is what BIP 440 prices with `WRITE`, so the charge adds `WRITE(unrolled length)`.
What does a script that looks like:
MACRO [OP_TRUE]
MACRO [CALL_MACRO 0 CALL_MACRO 0]
MACRO [CALL_MACRO 1 CALL_MACRO 1]
MACRO [CALL_MACRO 2 CALL_MACRO 2]
...
MACRO [CALL_MACRO 21 CALL_MACRO 21]
OP_TRUE
cost? I believe you could efficiently compute each macros' unrolled size as you go (1, 2, 4, 8, .., 4M), and then lazily unroll them if/when they're referenced from the main script, storing a span of the unrolled value so that it's just a memcpy to unroll any future occurrences of the same macro. Is that implementation essentially mandatory?
25 | + 26 | +Repeated instructions occupy block space each time they appear in a script. Macros let a script store a repeated instruction sequence once and reference it from many places. This can reduce transaction weight and fees for scripts with substantial repeated logic, without adding protocol-specific consensus operations. 27 | + 28 | +BIP 440 funds a transaction's varops budget from its weight, and that budget exists to limit validation time. Many scripts are limited by their weight long before their budget: a proof verifier built from repeated field arithmetic, for example, written out inline, uses only a small fraction of the varops its weight funds. Macros let such scripts spend that headroom on block space instead. A script can be compressed until its execution, together with the unrolling charge this BIP adds, uses the whole budget its transaction's reduced weight still funds. A script compressed further would exceed its budget and fail, so validation time stays limited as for any other script. 29 | + 30 | +Macros are not runtime functions. Functions defined and called during execution let the witness supply code, let the called function be computed, and allow recursion, so they need call frames and make a script's behavior depend on more than its committed bytes. Macros only compress: every body and reference is fixed in the committed script, which is unrolled into an ordinary Tapscript before execution, so the interpreter itself stays unchanged.
I'm still skeptical that avoiding runtime recursion of this form has any value. Note that even bounded iteration looks more like recursion in this model, eg naive fibonacci up to F(128) or so:
MACRO [DUP 0 GREATERTHAN IF 1SUB TOALTSTACK DUP ROT ADD FROMALTSTACK ENDIF]
MACRO [CALLMACRO 0 CALLMACRO 0]
MACRO [CALLMACRO 1 CALLMACRO 1]
MACRO [CALLMACRO 2 CALLMACRO 2]
MACRO [CALLMACRO 3 CALLMACRO 3]
MACRO [CALLMACRO 4 CALLMACRO 4]
MACRO [CALLMACRO 5 CALLMACRO 5]
MACRO [CALLMACRO 6 CALLMACRO 6]
0 1 OVER CALLMACRO 7 NOT VERIFY DROP
Doing macros as simple #define style textual replacements of code, with no parametrisation, is simple enough I suppose, but is only statically-analysable in the "do all the replacements then analyse it" sense.
My goal was to allow script compression with minimal changes to the interpreter, without call frames or anything similar. That's why macros are unrolled before execution starts: the interpreter only ever sees an ordinary script. Runtime recursion didn't fit that model, unrolling expands every reference, in all branches of every condition, so a body that references itself would expand without end, and only execution could decide when to stop. Recursion might be technically safe, since the budget could still limit it, but it adds complexity that I don't think is needed for plain script compression. And yes, static analysis here means unrolling first.
66 | +The BIP 342 OP_SUCCESSx scan is extended to macro declarations and references: it reads the committed script once, from its first byte to its last, without following references. The first rule below that makes the scan succeed or fail decides whether the script is valid; if the scan reaches the end without either, the script is *well-formed*. 67 | + 68 | +1. **Declarations.** While the next unread byte is OP_MACRO, consume it and read a CompactSize length `L`. If the length is missing, truncated or not in its shortest encoding, or `L` exceeds the number of remaining bytes, the scan **fails**. Otherwise, scan the next `L` bytes as the next body, then continue after it. 69 | +2. **Main script.** Scan all remaining bytes as the main script. 70 | + 71 | +A body or the main script is scanned by reading its instructions in order until it ends:
Would be better to say "A macro body" consistently, rather than just "a body" probably.
69 | +2. **Main script.** Scan all remaining bytes as the main script. 70 | + 71 | +A body or the main script is scanned by reading its instructions in order until it ends: 72 | + 73 | +- An instruction that is cut off by the end of the body or main script being scanned causes the scan to **fail**: a push whose length bytes or payload, or an OP_CALLMACRO whose index, would need bytes beyond that end. 74 | +- An OP_SUCCESSx opcode causes the scan to **succeed**: the script is valid, as specified by [BIP 342](bip-0342.mediawiki) for OP_SUCCESSx.
This seems to be:
CALLMACRO x where x is invalid or higher than the current macros id, or if there was a MACRO call within the macro body.I don't think this quite works for op_success opcodes that change the parsing -- eg OP_THREEBYTE that consumes the next two bytes as part of determining how it behaviours, then continue parsing as normal, if included in a macro could be interpreted as:
OP_THREEBYTE[0x04 0x01] OP_TRUE -- probably successOP_SUCCESSxx PUSH4[ 0x01 0x51 ] -- 4-byte push with only two data items, so failureSo using such an OP_SUCCESS implementation in a macro would be invalid, and this wouldn't be a soft-fork. Having an opcode read three bytes is pretty similar to the OP_MACRO 0xFD 0x00 0x10 [256-byte macro] this text is currently proposing.
I think this sort of complexity is probably a natural result of macro-like code reconstruction without meaningful structural awareness.