6 The Script System¶
Every transaction output carries a short program, the public key script, that states the conditions under which the output may be spent. Every transaction input that spends an output carries a second program, the signature script, that supplies the data needed to satisfy those conditions: typically a signature and a public key. To decide whether an input may spend an output, a node runs the two programs one after the other on a simple stack machine. The input is valid only if the machine finishes without error and leaves a value that counts as true.
This chapter specifies that machine as consensus requires it: the byte-level encoding of scripts, every limit, the numeric and boolean conventions, the semantics of all 256 opcode values, signature verification and the signature hash, pay-to-script-hash, the stake and treasury tag opcodes, the verification flags, signature-operation counting, and a few script predicates that other consensus code relies on. Decred’s script language descends from Bitcoin’s, but it differs in many details that are invisible in the common cases and fatal in the uncommon ones. Nothing in this chapter should be assumed to match Bitcoin unless the text says so. Appendix A lists all 256 opcode values in a single table.
Which transactions are checked, which inputs are skipped and which flags are passed are decided by Chapter 7; the per-block signature operation limit is in Chapter 10; the cryptographic primitives (hash functions, DER parsing, ECDSA, EC-Schnorr-DCRv0, Ed25519) are in Chapter 3; the serialization of transactions is in Chapter 4.
6.1 Overview and Terminology¶
A script is a byte string. It is read as a sequence of opcodes, each introduced by a single byte. Some opcodes (the push opcodes) are followed by inline data that they place on the stack; all other opcodes occupy exactly one byte.
A transaction output holds an amount, a 16-bit script version and a public key script. A transaction input holds, among other fields, a signature script. When input of transaction spends output , the script engine is invoked with:
- the public key script of and its script version,
- the transaction and the input index (the signature script is ’s input ’s signature script),
- a set of verification flags (Section 6.13), chosen by the caller.
The engine maintains two stacks of byte strings. The data stack is the main working stack; the alternate stack is auxiliary storage reachable only through two opcodes. An entry on either stack is called an element or item. The top of a stack is its most recently pushed element. In stack diagrams, the stack is written left to right from bottom to top, so in [... x1 x2] the element x2 is on top.
The result of a script check is binary. If the check fails, the transaction containing the input is invalid, and so is any block containing it. The reference implementation reports a specific error kind for each failure (for example ErrEvalFalse); these names are given in the text as an aid to implementers and for cross-checking against dcrd’s test data, but only the binary outcome is consensus.
6.2 Script Versions¶
The script version of an output selects the language its public key script is written in. Only version 0 is defined. The signature script and, for pay-to-script-hash, the redeem script are interpreted under the version of the public key script they redeem.
Rule 6.1 · Non-zero script versions
When the spent output’s script version is not 0, the engine performs every check of Rule 6.3 (the engine construction checks), and if all of them pass, the input MUST be treated as successfully verified without executing any script. Construction checks that depend on version 0 semantics (the redeem-script checks of step 4) are skipped, but all others, including the requirement that both scripts parse under version 0 rules, apply regardless of the version.dcrd: txscript/engine.go · Execute | txscript/engine.go · NewEngine
Implementation pitfall
Outputs with a non-zero script version are therefore spendable by anyone who can supply a signature script that, together with the public key script, passes the construction checks: both scripts at most 16384 bytes, both parseable as version 0 scripts, not both empty, and, if the public key script has the byte pattern of a pay-to-script-hash script, a push-only signature script. Because the parse check uses version 0 rules, a public key script that does not parse as version 0 is unspendable at any version. Several other predicates used by consensus (pay-to-script-hash detection, signature operation counting, Rule 6.35) also ignore the version entirely.History
Before theexplicitverupgrades agenda (DCP-0008), any 16-bit script version was permitted in any output. Once that agenda is active, outputs of regular (non-stake) transactions must carry script version 0, and stake transactions are constrained to specific versions by their own rules. Those limits are transaction-level rules specified in Chapter 7 and Chapter 8; how agenda activation is computed is in Chapter 13. Outputs created earlier with non-zero versions remain in the UTXO set and are governed by Rule 6.1.6.3 Parsing¶
Parsing splits a script into opcodes and their inline data. It is defined for version 0 and is used both by the engine and by every other predicate in this chapter. Opcode bytes fall into four parsing classes, shown in Table 6.1.
| Byte(s) | Opcode(s) | Encoding |
|---|---|---|
0x00 | OP_0 | The single byte. Pushes the empty byte string. |
0x01–0x4b | OP_DATA_1 … OP_DATA_75 | The byte followed by exactly data bytes. |
0x4c | OP_PUSHDATA1 | The byte, a 1-byte length , then data bytes. |
0x4d | OP_PUSHDATA2 | The byte, a 2-byte little-endian length , then data bytes. |
0x4e | OP_PUSHDATA4 | The byte, a 4-byte little-endian length , then data bytes. |
0x4f–0xff | all others | The single byte. No inline data. |
Rule 6.2 · Script parsing
A script is parsed from offset 0. At each offset the byte at is read and:
- If is
0x00or0x4f, the opcode is with no data and the next offset is . - If
0x01≤ ≤0x4b, the script MUST contain at least bytes from offset ; the data is the bytes after and the next offset is . - If is
0x4c,0x4dor0x4e, let be 1, 2 or 4 respectively. The script MUST contain at least bytes after offset . Let be those bytes read as an unsigned little-endian integer. The script MUST contain at least further bytes after the length field. The data is those bytes and the next offset is .
Parsing ends successfully when the offset equals the script length. Any violation of a MUST above is a parse failure (ErrMalformedPush). The empty script parses successfully to zero opcodes.
dcrd: txscript/tokenizer.go · ScriptTokenizer.Next
Note
The reference implementation reads theOP_PUSHDATA4 length into a signed 32-bit integer and rejects negative values; since any length of or more also exceeds the bytes remaining in any script that fits in a transaction, the condition “at least further bytes” is equivalent.Parsing does not inspect what an opcode does: unassigned, reserved and disabled opcode bytes all parse as one-byte opcodes. In what follows, the data of an opcode means its inline data (empty for OP_0 and for every opcode without inline data), and an opcode is a data push if its byte is at most 0x4e. This is narrower than the push-only test of Section 6.5, which admits every opcode up to 0x60 and so also the small-integer opcodes.
Algorithm 6.1 · Script parsing
def parse(script: bytes) -> list[tuple[int, bytes]]:
ops, k, L = [], 0, len(script)
while k < L:
b = script[k]
if b == 0x00 or b >= 0x4f:
ops.append((b, b"")); k += 1
elif b <= 0x4b: # OP_DATA_1 .. OP_DATA_75
if L - k < 1 + b: reject("ErrMalformedPush")
ops.append((b, script[k+1 : k+1+b])); k += 1 + b
else: # OP_PUSHDATA1/2/4
w = {0x4c: 1, 0x4d: 2, 0x4e: 4}[b]
if L - k - 1 < w: reject("ErrMalformedPush")
n = int.from_bytes(script[k+1 : k+1+w], "little")
if n > L - k - 1 - w: reject("ErrMalformedPush")
ops.append((b, script[k+1+w : k+1+w+n])); k += 1 + w + n
return opsdcrd: txscript/tokenizer.go · ScriptTokenizer.Next
Several predicates walk a script only up to its first parse failure, using the opcodes successfully parsed before it. Where that matters the text says so explicitly.
6.4 Limits¶
Table 6.2 collects the numeric limits of the engine. Each is restated in the rule that enforces it, with the exact comparison.
| Constant | Value | Meaning and exact comparison |
|---|---|---|
MaxScriptSize | 16384 | A signature script or public key script longer than this many bytes fails (len > 16384). Redeem scripts are bounded by the element size instead. |
MaxScriptElementSize | 2048 | A data push whose data is longer than this many bytes fails (len > 2048), whether or not the push is executed. OP_CAT enforces the same bound on its result. |
MaxOpsPerScript | 255 | Per script, the count of opcodes with byte value greater than 0x60, plus the key counts of executed multisignature checks, must not exceed 255 (fails when the count becomes > 255). |
MaxStackSize | 1024 | After each opcode, the combined number of elements on the data stack and alternate stack must not exceed 1024 (fails when > 1024). |
MaxPubKeysPerMultiSig | 20 | The key count of OP_CHECKMULTISIG(VERIFY) must be in . |
MathOpCodeMaxScriptNumLen | 4 | Maximum encoded length of most numeric operands (Section 6.7.2). |
CltvMaxScriptNumLen | 5 | Maximum encoded length of the OP_CHECKLOCKTIMEVERIFY operand. |
CsvMaxScriptNumLen | 5 | Maximum encoded length of the OP_CHECKSEQUENCEVERIFY operand. |
| — | 1 | Maximum encoded length of the OP_CHECKSIGALT(VERIFY) signature type operand. |
LockTimeThreshold | 500000000 | Lock-time values below this are block heights, at or above it Unix times. |
6.5 Engine Construction¶
Before anything executes, the engine checks the pair of scripts as a whole. These checks are part of consensus: a failure makes the input invalid exactly as an execution failure does (dcrd reports it as ErrScriptMalformed at the transaction level, but the distinction has no consensus effect).
Two script shapes are recognized by exact byte pattern. A pay-to-script-hash (P2SH) public key script is exactly 23 bytes: a9 14 followed by 20 bytes followed by 87, that is, OP_HASH160 OP_DATA_20 <20 bytes> OP_EQUAL. A stake-tagged P2SH public key script is exactly 24 bytes: a stake tag byte followed by those 23 bytes. The stake tag bytes are 0xba–0xbd (OP_SSTX, OP_SSGEN, OP_SSRTX, OP_SSTXCHANGE) and, only when the ScriptVerifyTreasury flag is set, also 0xc1–0xc3 (OP_TADD, OP_TSPEND, OP_TGEN). A script is P2SH-shaped if it is either. P2SH is specified in Section 6.11.
A script is push-only if it parses (Rule 6.2) and every opcode in it has byte value at most 0x60 (OP_16). Note that this includes OP_RESERVED (0x50), which fails if executed.
Rule 6.3 · Engine construction checks
Let be the signature script, the public key script and the script version of the spent output. The following MUST all hold:
- and are not both empty (
ErrEvalFalse). - If the flag
ScriptVerifySigPushOnlyis set, is push-only (ErrNotPushOnly). - If is P2SH-shaped, is push-only (
ErrNotPushOnly). This check is independent of . - If and is P2SH-shaped: let be the data of the final opcode of , taken from a full parse of (if is empty or fails to parse, is empty). MUST be non-empty (
ErrNotPushOnly). MUST NOT contain a stake tag opcode, where the opcodes considered are0xba–0xbd, plus0xc1–0xc3whenScriptVerifyTreasuryis set (ErrP2SHStakeOpCodes); this scan stops at the first parse failure of , and a parse failure reached before any stake tag opcode also fails (ErrMalformedPush). - and (
ErrScriptTooBig). - and both parse under version 0 rules (
ErrMalformedPush), whatever is.
dcrd: txscript/engine.go · NewEngine | txscript/script.go · hasP2SHRedeemScriptStakeOpCodes
Implementation pitfall
In step 4 the redeem script is the inline data of the last opcode of the signature script, not the top stack element the signature script will produce. The small-integer opcodesOP_1–OP_16 and OP_1NEGATE have no inline data, so a P2SH signature script that ends with one of them fails construction even though executing it would leave a non-empty element on the stack. The same applies to OP_0 and to an empty push such as OP_PUSHDATA1 0x00. A redeem script consisting of the single byte 0x51 must therefore be supplied as 01 51 (an OP_DATA_1 push), never as 51.6.6 Execution Model¶
6.6.1 Order of Execution¶
The engine executes up to three scripts in sequence on a shared data stack:
- the signature script , starting from an empty data stack;
- the public key script , starting from the data stack left behind;
- for P2SH only, the redeem script : the top element of the data stack as it was after finished, executed on that stack with itself removed (Section 6.11).
An empty script is skipped entirely: it executes no opcodes and none of the per-script end checks below apply to it. The alternate stack, the operation count and the conditional state are per script: the alternate stack is emptied and the operation count reset to zero at the end of each non-empty script.
Rule 6.4 · Per-script end conditions
When the last opcode of a non-empty script has executed:
- the conditional nesting depth (Section 6.6.3) MUST be 0 (
ErrUnbalancedConditional): anOP_IForOP_NOTIFblock cannot span two scripts; - the alternate stack is then emptied, and the operation count reset to 0, before the next script starts.
dcrd: txscript/engine.go · Engine.Step
Rule 6.5 · Combined stack size
After every opcode the engine processes, including opcodes in unexecuted branches, the number of elements on the data stack plus the number on the alternate stack MUST NOT exceed 1024 (ErrStackOverflow).dcrd: txscript/engine.go · Engine.Step
6.6.2 Processing One Opcode¶
The engine walks each script opcode by opcode in parse order. Every opcode the program counter reaches is processed, whether or not it lies in a branch that is being executed; processing decides whether the opcode’s operation is actually executed. A branch is executing when no enclosing OP_IF, OP_NOTIF or OP_ELSE has disabled it (Section 6.6.3).
Rule 6.6 · Opcode processing
For each opcode with data reached by the program counter, in this order:
- If is
OP_CODESEPARATOR(0xab), the script MUST fail (ErrDisabledOpcode), whether or not the branch is executing. - If is
OP_VERIF(0x65) orOP_VERNOTIF(0x66), the script MUST fail (ErrReservedOpcode), whether or not the branch is executing. - If
0x60, the per-script operation count is incremented by one, and if it now exceeds 255 the script MUST fail (ErrTooManyOperations). Otherwise (0x60), if the script MUST fail (ErrElementTooBig). Both checks apply whether or not the branch is executing. - If the branch is not executing and is not one of
OP_IF,OP_NOTIF,OP_ELSE,OP_ENDIF, processing of ends here: it has no further effect. - If the branch is executing and
0x4e, the push MUST be minimal (Rule 6.7). - The operation of is executed, as specified in Section 6.8 and Appendix A. The conditional opcodes are executed in unexecuted branches as well, with the behaviour given in Section 6.6.3.
dcrd: txscript/engine.go · executeOpcode | txscript/engine.go · isOpcodeDisabled | txscript/engine.go · isOpcodeAlwaysIllegal
Implementation pitfall
The operation count includes every opcode above0x60 that the program counter passes over, including those in unexecuted branches, and excludes every opcode at or below 0x60, including OP_RESERVED (0x50). The element size limit likewise applies to pushes in unexecuted branches. By contrast, the minimal-push rule applies only to executed pushes.Rule 6.7 · Minimal data pushes
An executed data push with opcode (0x00–0x4e) and data MUST satisfy the first matching condition (ErrMinimalData):
- if : is
OP_0; - if and : is
OP_1+ (that is, a small-integer opcode, which is not a data push and so never reaches this check); - if and
0x81: isOP_1NEGATE(likewise impossible to satisfy with a data push); - if : (an
OP_DATA_nopcode); - if : is
OP_PUSHDATA1; - if : is
OP_PUSHDATA2.
dcrd: txscript/engine.go · checkMinimalDataPush
In effect, every executed push must use the shortest encoding: the empty string only via OP_0; the single bytes 0x01–0x10 and 0x81 only via OP_1–OP_16 and OP_1NEGATE; other strings of 1 to 75 bytes only via OP_DATA_n; 76 to 255 bytes only via OP_PUSHDATA1; 256 to 2048 bytes only via OP_PUSHDATA2. An executed OP_PUSHDATA4 always fails, because a push of at most 65535 bytes requires a shorter opcode and a longer one cannot fit in a script. The single bytes 0x00 and 0x80 may be pushed with OP_DATA_1.
6.6.3 Conditional Execution¶
Branching uses two per-script integers: the nesting depth , the number of currently open OP_IF/OP_NOTIF blocks, and the disable depth , which is either “none” (the branch is executing) or the nesting depth at which execution was disabled. Both start at , . Since must return to 0 at the end of every script, both are effectively reset between scripts.
Rule 6.8 · Conditional opcodes
OP_IF: if is none, pop the top data stack element (an empty stack fails withErrInvalidStackOperation) and interpret it as a boolean (Rule 6.10); if it is false, set . In all cases then set .OP_NOTIF: asOP_IF, except that is set when the popped value is true.OP_ELSE: if the script MUST fail (ErrUnbalancedConditional). Otherwise let . If is none, set ; else if , set ; otherwise do nothing.OP_ENDIF: if the script MUST fail (ErrUnbalancedConditional). Otherwise set , and then if set .
dcrd: txscript/opcode.go · opcodeIf | txscript/opcode.go · opcodeNotIf | txscript/opcode.go · opcodeElse | txscript/opcode.go · opcodeEndif
Consequences worth stating explicitly: an OP_IF reached in an unexecuted branch consumes nothing from the stack but still opens a block; any number of OP_ELSE opcodes may appear in one block, each toggling execution; and the condition value is interpreted as a boolean, with no requirement that it be minimally encoded (Decred has no “minimal if” rule).
6.6.4 Successful Completion¶
Rule 6.9 · Final result
After the last script has finished:
- if the flag
ScriptVerifyCleanStackis set, the data stack MUST contain exactly one element (ErrCleanStack); - otherwise the data stack MUST contain at least one element (
ErrEmptyStack); - the top element, interpreted as a boolean, MUST be true (
ErrEvalFalse).
dcrd: txscript/engine.go · CheckErrorCondition | txscript/engine.go · Engine.Execute
The clean-stack flag is part of the consensus flag set on every block (Section 6.13), so in consensus validation the data stack must end with exactly one element, which must be true. Contents of the alternate stack at the end are irrelevant (the alternate stack has been emptied by Rule 6.4).
For P2SH, an intermediate check precedes the redeem script; it is given in Rule 6.31.
6.6.5 Complete Input Verification¶
Algorithm 6.2 combines the rules of this section into a single procedure. The handlers for individual opcodes are specified in Section 6.8 and Section 6.9.
Algorithm 6.2 · Verifying one input
MAX_SCRIPT_SIZE, MAX_ELEMENT, MAX_OPS, MAX_STACK = 16384, 2048, 255, 1024
def verify_input(tx, idx, pk_script, version, flags):
S, P = tx.inputs[idx].sig_script, pk_script
treasury = TREASURY in flags
if len(S) == 0 and len(P) == 0: reject("ErrEvalFalse")
if SIGPUSHONLY in flags and not is_push_only(S): reject("ErrNotPushOnly")
p2sh = is_p2sh(P) or is_stake_p2sh(P, treasury)
if p2sh and not is_push_only(S): reject("ErrNotPushOnly")
if version == 0 and p2sh:
R = final_opcode_data(S) # b"" if S is empty or unparseable
if len(R) == 0: reject("ErrNotPushOnly")
# contains_stake_opcode tokenizes R and rejects with ErrMalformedPush
# if R does not parse, unless a stake opcode is found first
if contains_stake_opcode(R, treasury): reject("ErrP2SHStakeOpCodes")
for s in (S, P):
if len(s) > MAX_SCRIPT_SIZE: reject("ErrScriptTooBig")
parse(s) # version 0 rules, may reject
if version != 0:
return # valid (rule: non-zero versions)
vm = VM(tx, idx, flags) # empty data and alternate stacks
run_script(vm, S)
saved = list(vm.dstack) # used only for P2SH
run_script(vm, P)
if p2sh:
if len(vm.dstack) < 1: reject("ErrEmptyStack")
if not as_bool(vm.dstack.pop()): reject("ErrEvalFalse")
R = saved[-1]
parse(R) # redundant for version 0: checked above
vm.dstack = saved[:-1]
run_script(vm, R)
if CLEANSTACK in flags and len(vm.dstack) != 1: reject("ErrCleanStack")
if len(vm.dstack) < 1: reject("ErrEmptyStack")
if not as_bool(vm.dstack.pop()): reject("ErrEvalFalse")
def run_script(vm, script):
if len(script) == 0:
return
vm.script = script # the "current script"
vm.num_ops, vm.depth, vm.disabled_at = 0, 0, None
for op, data in parse(script):
process_opcode(vm, op, data)
if len(vm.dstack) + len(vm.astack) > MAX_STACK:
reject("ErrStackOverflow")
if vm.depth != 0: reject("ErrUnbalancedConditional")
vm.astack = []
def process_opcode(vm, op, data):
if op == 0xab: reject("ErrDisabledOpcode") # OP_CODESEPARATOR
if op in (0x65, 0x66): reject("ErrReservedOpcode") # OP_VERIF, OP_VERNOTIF
if op > 0x60:
vm.num_ops += 1
if vm.num_ops > MAX_OPS: reject("ErrTooManyOperations")
elif len(data) > MAX_ELEMENT:
reject("ErrElementTooBig")
executing = vm.disabled_at is None
if not executing and op not in (OP_IF, OP_NOTIF, OP_ELSE, OP_ENDIF):
return
if executing and op <= 0x4e:
check_minimal_push(op, data)
HANDLERS[op](vm, data)dcrd: txscript/engine.go · NewEngine | txscript/engine.go · Engine.Step | txscript/engine.go · Engine.Execute
Note
For a version 0 P2SH spend,saved[-1] and final_opcode_data(S) are always the same byte string: is push-only, construction has ensured its last opcode is a non-empty data push, and that push is the top of the stack produces.6.6.6 Example: Pay-to-Pubkey-Hash¶
The most common public key script is pay-to-pubkey-hash:
It is redeemed by a signature script <signature> <public key>. Table 6.3 shows the data stack after each opcode.
| Script | Opcode | Data stack afterwards (bottom … top) |
|---|---|---|
| S | OP_DATA_72 | sig |
| S | OP_DATA_33 | sig pk |
| P | OP_DUP | sig pk pk |
| P | OP_HASH160 | sig pk H(pk) where H = RIPEMD-160(BLAKE-256(·)) |
| P | OP_DATA_20 | sig pk H(pk) h |
| P | OP_EQUALVERIFY | sig pk (fails unless H(pk) = h) |
| P | OP_CHECKSIG | 1 if the signature verifies, else the empty string |
| — | final check | exactly one element, true: valid |
6.7 Data Representation¶
Stack elements are untyped byte strings. Opcodes interpret them as raw bytes, as booleans or as numbers, and the interpretation is fixed per opcode.
6.7.1 Booleans¶
Rule 6.10 · Boolean interpretation
A byte string is false if every byte of is 0x00, or if every byte except the last is 0x00 and the last byte is 0x80 (“negative zero”). In particular the empty string is false. Every other byte string is true. There is no length limit on a value interpreted as a boolean.
An opcode that pushes a boolean pushes the one-byte string 01 for true and the empty string for false.
dcrd: txscript/stack.go · asBool
Booleans are consumed by OP_IF, OP_NOTIF, OP_VERIFY, OP_IFDUP, the …VERIFY forms of other opcodes, and the final check. OP_NOT, OP_BOOLAND and OP_BOOLOR are numeric opcodes and do not use this interpretation.
6.7.2 Script Numbers¶
Numbers on the stack are encoded as little-endian sign-magnitude byte strings: the magnitude is written in the fewest bytes possible, least significant byte first, and the most significant bit of the last byte is the sign. If the magnitude’s most significant byte already has its top bit set, an extra byte 0x00 (positive) or 0x80 (negative) is appended. Zero is the empty string.
Algorithm 6.3 · Script number encoding and decoding
def encode_num(n: int64) -> bytes:
if n == 0:
return b""
neg, m = n < 0, abs(n)
out = bytearray()
while m > 0:
out.append(m & 0xff); m >>= 8
if out[-1] & 0x80:
out.append(0x80 if neg else 0x00)
elif neg:
out[-1] |= 0x80
return bytes(out)
def decode_num(b: bytes, max_len: int) -> int:
if len(b) > max_len:
reject("ErrNumOutOfRange")
if len(b) > 0 and (b[-1] & 0x7f) == 0: # minimal encoding
if len(b) == 1 or (b[-2] & 0x80) == 0:
reject("ErrMinimalData")
if len(b) == 0:
return 0
mag = int.from_bytes(b, "little")
if b[-1] & 0x80:
return -(mag & ~(0x80 << (8 * (len(b) - 1))))
return magdcrd: txscript/scriptnum.go · ScriptNum.Bytes | txscript/scriptnum.go · MakeScriptNum | txscript/scriptnum.go · checkMinimalDataEncoding
Rule 6.11 · Numeric operands
Whenever an opcode interprets a stack element as a number, the element MUST decode underdecode_num of Algorithm 6.3 with the maximum length for that opcode: its length MUST NOT exceed the maximum (ErrNumOutOfRange) and it MUST be minimally encoded (ErrMinimalData). The length check precedes the minimality check. The maximum length is 5 for the operand of OP_CHECKLOCKTIMEVERIFY and OP_CHECKSEQUENCEVERIFY, 1 for the signature-type operand of OP_CHECKSIGALT(VERIFY), and 4 for every other numeric operand.dcrd: txscript/scriptnum.go · MakeScriptNum | txscript/stack.go · stack.PopInt
A maximum length of 4 bytes admits exactly the integers ; 5 bytes admits ; 1 byte admits . Note that is not a valid 4-byte operand: its encoding 00 00 00 80 80 is 5 bytes long.
The minimality requirement applies only when a value is interpreted as a number. Pushing the two-byte string 05 00 (with OP_DATA_2, which is the minimal push for it) is permitted even though it is a non-minimal encoding of the number 5; the element may be compared with OP_EQUAL, hashed or used as a boolean, and fails only if a numeric opcode consumes it.
Results of numeric opcodes are always pushed with encode_num, which never produces a non-minimal encoding. Results are not range-checked: an addition of two 4-byte operands may produce a 5-byte result such as , which can be pushed, compared bytewise, hashed or interpreted as a boolean, but fails if it is later used as a 4-byte numeric operand.
Note
The reference implementation converts decoded operands to 32-bit integers with a saturating conversion (values above become , values below become ) wherever an operand is used as a 32-bit quantity. Because every operand so converted has already passed a 4-byte length check, it always lies in and the saturation never changes a value. An implementation may use a plain conversion.6.8 Opcode Semantics¶
This section specifies the operation performed when an opcode is executed (step 6 of Rule 6.6). All opcodes are listed by byte value in Appendix A. Unless stated otherwise:
- “pop” removes the top element of the data stack, and popping from an empty stack fails (
ErrInvalidStackOperation); likewise any reference to an element deeper than the stack fails with that error; - a numeric operand is popped and decoded under Rule 6.11 with maximum length 4;
- operands are popped top first: in
[... x1 x2],x2is popped first; - results are pushed after all operands have been popped.
Because any failure invalidates the input, the order in which an opcode checks its operands only affects which error is reported; it is stated where an opcode can either fail or push a result depending on that order.
6.8.1 Push Opcodes¶
| Byte(s) | Opcode | Operation |
|---|---|---|
0x00 | OP_0, OP_FALSE | Push the empty string. |
0x01–0x4b | OP_DATA_n | Push the inline data bytes. |
0x4c–0x4e | OP_PUSHDATA1/2/4 | Push the inline data bytes. |
0x4f | OP_1NEGATE | Push the number (81). |
0x51–0x60 | OP_1/OP_TRUE … OP_16 | Push the number 0x50 (01 … 10). |
6.8.2 Flow Control¶
| Byte | Opcode | Operation when executed |
|---|---|---|
0x61 | OP_NOP | None. |
0x62 | OP_VER | Fail (ErrReservedOpcode). Ignored in an unexecuted branch. |
0x63 | OP_IF | Rule 6.8. |
0x64 | OP_NOTIF | Rule 6.8. |
0x65 | OP_VERIF | Fail whenever reached, even in an unexecuted branch (Rule 6.6). |
0x66 | OP_VERNOTIF | Fail whenever reached, even in an unexecuted branch. |
0x67 | OP_ELSE | Rule 6.8. |
0x68 | OP_ENDIF | Rule 6.8. |
0x69 | OP_VERIFY | Pop ; if is false, fail (ErrVerify). |
0x6a | OP_RETURN | Fail (ErrEarlyReturn). Ignored in an unexecuted branch. |
Every opcode named …VERIFY other than OP_VERIFY, OP_CHECKLOCKTIMEVERIFY and OP_CHECKSEQUENCEVERIFY behaves as its base opcode followed by OP_VERIFY, except that the error on a false result has its own kind (ErrEqualVerify, ErrNumEqualVerify, ErrCheckSigVerify, ErrCheckMultiSigVerify, ErrCheckSigAltVerify). A …VERIFY opcode counts as a single operation.
6.8.3 Stack Manipulation¶
In Table 6.6, a failure because the stack holds too few elements is always ErrInvalidStackOperation.
| Byte | Opcode | Data stack effect | Notes |
|---|---|---|---|
0x6b | OP_TOALTSTACK | [x] → [] | x is pushed onto the alternate stack. |
0x6c | OP_FROMALTSTACK | [] → [x] | x is popped from the alternate stack; fails if it is empty. |
0x6d | OP_2DROP | [x1 x2] → [] | |
0x6e | OP_2DUP | [x1 x2] → [x1 x2 x1 x2] | |
0x6f | OP_3DUP | [x1 x2 x3] → [x1 x2 x3 x1 x2 x3] | |
0x70 | OP_2OVER | [x1 x2 x3 x4] → [x1 x2 x3 x4 x1 x2] | |
0x71 | OP_2ROT | [x1 … x6] → [x3 x4 x5 x6 x1 x2] | Requires 6 elements. |
0x72 | OP_2SWAP | [x1 x2 x3 x4] → [x3 x4 x1 x2] | |
0x73 | OP_IFDUP | [x] → [x x] or [x] | Duplicates x only if x is true as a boolean. |
0x74 | OP_DEPTH | [] → [n] | n is the number of data stack elements before the push. |
0x75 | OP_DROP | [x] → [] | |
0x76 | OP_DUP | [x] → [x x] | |
0x77 | OP_NIP | [x1 x2] → [x2] | |
0x78 | OP_OVER | [x1 x2] → [x1 x2 x1] | |
0x79 | OP_PICK | [xn … x0 n] → [xn … x0 xn] | See below. |
0x7a | OP_ROLL | [xn … x0 n] → [… x0 xn] | See below. |
0x7b | OP_ROT | [x1 x2 x3] → [x2 x3 x1] | |
0x7c | OP_SWAP | [x1 x2] → [x2 x1] | |
0x7d | OP_TUCK | [x1 x2] → [x2 x1 x2] |
Rule 6.12 · OP_PICK and OP_ROLL
Pop a numeric operand (4-byte maximum). Then, on the remaining stack of depth , MUST satisfy (ErrInvalidStackOperation). The element at distance from the top (distance 0 is the top) is copied to the top (OP_PICK) or moved to the top, closing the gap (OP_ROLL). OP_ROLL with leaves the stack unchanged.dcrd: txscript/opcode.go · opcodePick | txscript/opcode.go · opcodeRoll | txscript/stack.go · stack.PickN | txscript/stack.go · stack.RollN
6.8.4 Splice Operations¶
Decred enables the string opcodes that Bitcoin disabled, with its own semantics.
Rule 6.13 · OP_CAT
[... x1 x2] → [... x1 || x2]. Pop x2, then x1. If both are empty, push the empty string. If exactly one is empty, push the other unchanged. Otherwise MUST NOT exceed 2048 (ErrElementTooBig), and the concatenation x1 || x2 is pushed.dcrd: txscript/opcode.go · opcodeCat
Rule 6.14 · OP_SUBSTR
[... s e b] → [... s[b:e]]. Pop the numeric start index (the top element), then the numeric end index , then the string (all numeric operands 4-byte maximum). If , push the empty string regardless of and . Otherwise, in this order, MUST hold: and (ErrNegativeSubstrIdx); , and (ErrOverflowSubstrIdx). Push the bytes of from index up to but not including (empty when ).dcrd: txscript/opcode.go · opcodeSubstr
Rule 6.15 · OP_LEFT and OP_RIGHT
[... s n]. Pop the numeric index , then the string . If , push the empty string regardless of . Otherwise MUST hold: (ErrNegativeSubstrIdx) and (ErrOverflowSubstrIdx). OP_LEFT pushes the first bytes s[0:n]; OP_RIGHT pushes the bytes from index to the end, s[n:].dcrd: txscript/opcode.go · opcodeLeft | txscript/opcode.go · opcodeRight
OP_SIZE (0x82): [... x] → [... x n], where n is encoded as a number; x is not removed.
Implementation pitfall
The operand order ofOP_SUBSTR is the reverse of what its name suggests: the start index is on top, the end index beneath it. 'abcd' 3 1 OP_SUBSTR yields 'bc'. The “empty string” shortcuts are taken after the indices have been decoded (so an over-long index still fails with ErrNumOutOfRange) but before any bounds check, so '' 2147483647 2147483646 OP_SUBSTR succeeds and pushes the empty string.6.8.5 Bitwise Logic, Comparison and Rotation¶
The bitwise opcodes operate on numbers, not on byte strings. Each operand is decoded as a 4-byte script number and then treated as a 32-bit two’s complement integer; the 32-bit result is interpreted as a signed integer and pushed with encode_num.
| Byte | Opcode | Operation ([... x1 x2], x2 on top) |
|---|---|---|
0x83 | OP_INVERT | [x] → [~x]: bitwise complement as int32, equal to . OP_INVERT of yields , pushed as 5 bytes. |
0x84 | OP_AND | int32(x1) & int32(x2). |
0x85 | OP_OR | int32(x1) | int32(x2). |
0x86 | OP_XOR | int32(x1) ^ int32(x2). |
0x87 | OP_EQUAL | Pop two elements; push true if they are identical byte strings (same length and bytes), else false. No numeric interpretation: 00 and the empty string differ. |
0x88 | OP_EQUALVERIFY | OP_EQUAL then verify (ErrEqualVerify). |
0x89 | OP_ROTR | Rule 6.16. |
0x8a | OP_ROTL | Rule 6.16. |
Rule 6.16 · OP_ROTR and OP_ROTL
[... v c]. Pop the numeric count , then the numeric value (both 4-byte maximum). MUST hold (ErrNegativeRotation) and MUST hold (ErrOverflowRotation). Let = uint32(v). The result is rotated right (OP_ROTR) or left (OP_ROTL) by bit positions within 32 bits, reinterpreted as int32. A rotation by 0 returns unchanged.dcrd: txscript/opcode.go · opcodeRotr | txscript/opcode.go · opcodeRotl
Implementation pitfall
Because results are reinterpreted as signed and operands are limited to 4 bytes, a rotation or shift whose result has bit 31 set produces a negative number; if that number is its encoding is 5 bytes and it cannot be used as an operand again. For example1 1 OP_ROTR pushes (00 00 00 80 80), and feeding that to a second OP_ROTR fails with ErrNumOutOfRange, whereas 1 2 OP_ROTR pushes , which remains a valid operand.6.8.6 Arithmetic¶
All operands in Table 6.8 are 4-byte numeric operands. In the binary operations, is the second element from the top (x1) and the top element (x2), so a b OP_SUB computes . Results marked “exact” are computed without overflow (they lie within and may encode to 5 bytes). Booleans produced by numeric opcodes are the numbers 1 and 0, that is, 01 and the empty string.
| Byte | Opcode | Result |
|---|---|---|
0x8b | OP_1ADD | , exact. |
0x8c | OP_1SUB | , exact. |
0x8d | OP_2MUL | No operation (behaves as OP_NOP; nothing is popped or checked). |
0x8e | OP_2DIV | No operation (behaves as OP_NOP). |
0x8f | OP_NEGATE | . |
0x90 | OP_ABS | . |
0x91 | OP_NOT | 1 if , else 0. |
0x92 | OP_0NOTEQUAL | 0 if , else 1. |
0x93 | OP_ADD | , exact. |
0x94 | OP_SUB | , exact. |
0x95 | OP_MUL | int32(a * b): the product reduced modulo and reinterpreted as signed (wrapping). |
0x96 | OP_DIV | tdiv(a, b) (truncating toward zero). fails (ErrDivideByZero). |
0x97 | OP_MOD | tmod(a, b) (remainder of truncating division, sign of ). fails (ErrDivideByZero). |
0x98 | OP_LSHIFT | Rule 6.17. |
0x99 | OP_RSHIFT | Rule 6.17. |
0x9a | OP_BOOLAND | 1 if and , else 0. |
0x9b | OP_BOOLOR | 1 if or , else 0. |
0x9c | OP_NUMEQUAL | 1 if , else 0. |
0x9d | OP_NUMEQUALVERIFY | OP_NUMEQUAL then verify (ErrNumEqualVerify). |
0x9e | OP_NUMNOTEQUAL | 1 if , else 0. |
0x9f | OP_LESSTHAN | 1 if , else 0. |
0xa0 | OP_GREATERTHAN | 1 if , else 0. |
0xa1 | OP_LESSTHANOREQUAL | 1 if , else 0. |
0xa2 | OP_GREATERTHANOREQUAL | 1 if , else 0. |
0xa3 | OP_MIN | . |
0xa4 | OP_MAX | . |
0xa5 | OP_WITHIN | [... x lo hi]: pop hi, lo, x; 1 if , else 0. |
Rule 6.17 · OP_LSHIFT and OP_RSHIFT
[... v c]. Pop the numeric count , then the numeric value (both 4-byte maximum). MUST hold (ErrNegativeShift) and MUST hold (ErrOverflowShift). With as a 32-bit two’s complement integer:
OP_LSHIFTpushesint32(v << c), discarding bits shifted out of the 32-bit width; for the result is 0;OP_RSHIFTpushes the arithmetic (sign-replicating) shiftv >> c; for the result is 0 if and if .
dcrd: txscript/opcode.go · opcodeLShift | txscript/opcode.go · opcodeRShift
Implementation pitfall
Shifts by 32 are defined (Go semantics). In C and C++, shifting a 32-bit value by 32 is undefined; in Rust it panics in debug builds and silently masks the count in release builds, so thatx << 32 yields x. Implementations in those languages must special-case it. The same applies to the 32 - c shift inside a rotation by 0.Note
Overflow cannot occur inOP_DIV or OP_MOD: the only overflowing case of 32-bit truncating division, , needs the operand , which is not a valid 4-byte operand. OP_NOT and OP_0NOTEQUAL decode their operand numerically, so 'abcdef' OP_NOT fails with ErrNumOutOfRange rather than treating the string as a boolean.6.8.7 Hash Opcodes¶
Each hash opcode pops one element, hashes its bytes, and pushes the digest. The functions are defined in Chapter 3.
| Byte | Opcode | Digest | Function |
|---|---|---|---|
0xa6 | OP_RIPEMD160 | 20 | RIPEMD-160(x). |
0xa7 | OP_SHA1 | 20 | SHA-1(x). |
0xa8 | OP_BLAKE256 | 32 | BLAKE-256(x) (14 rounds, as used throughout Decred). |
0xa9 | OP_HASH160 | 20 | RIPEMD-160(BLAKE-256(x)). Not SHA-256 as in Bitcoin. |
0xaa | OP_HASH256 | 32 | BLAKE-256(BLAKE-256(x)). Not double SHA-256. |
0xc0 | OP_SHA256 | 32 | SHA-256(x), only when ScriptVerifySHA256 is set (Rule 6.18). |
Rule 6.18 · OP_SHA256
If the flagScriptVerifySHA256 is set, executing byte 0xc0 pops and pushes SHA-256(). If the flag is not set, it behaves as an upgradable no-operation (Rule 6.21), named OP_UNKNOWN192.dcrd: txscript/opcode.go · opcodeSha256
History
OP_SHA256 was introduced by DCP-0002 [29] to support hash time-locked contracts that share a SHA-256 hash lock with other chains. It is enabled, together with OP_CHECKSEQUENCEVERIFY, by the lnfeatures agenda: the flag is set for a block exactly when that agenda is active for the block (Chapter 7 specifies the flag selection, Chapter 13 the activation). Before activation, byte 0xc0 is a no-operation. The meaning of the byte therefore depends on the flag of the block that contains the spend, and an implementation must select the flag per block. Unlike the lock-time opcodes, which only make a no-operation stricter, this change is not a pure tightening: <x> 0xc0 <SHA-256(x)> OP_EQUAL is invalid before activation and valid after it, and <h> 0xc0 <h> OP_EQUAL the reverse.6.8.8 Lock-Time Opcodes¶
These opcodes compare a stack value with fields of the spending transaction. Neither removes its operand from the stack; scripts conventionally follow them with OP_DROP. Both operands are decoded with a 5-byte maximum so that values up to (and beyond) can be expressed.
Rule 6.19 · OP_CHECKLOCKTIMEVERIFY
If the flag ScriptVerifyCheckLockTimeVerify is not set, byte 0xb1 behaves as an upgradable no-operation (named OP_NOP2) (Rule 6.21). Otherwise, let be the top element decoded as a number with maximum length 5, without popping it (an empty stack fails with ErrInvalidStackOperation), let be the transaction’s lock time and the sequence number of the input being verified. The following MUST hold:
- (
ErrNegativeLockTime); - and are of the same kind: both (block heights) or both (Unix times) (
ErrUnsatisfiedLockTime); - (
ErrUnsatisfiedLockTime); -
0xffffffff(ErrUnsatisfiedLockTime).
dcrd: txscript/opcode.go · opcodeCheckLockTimeVerify | txscript/opcode.go · verifyLockTime
The opcode thus proves that the transaction’s own lock time is at least , and the last condition ensures that the lock time is actually enforced for this transaction (a transaction whose inputs all have the maximum sequence number ignores its lock time; see Chapter 7).
Rule 6.20 · OP_CHECKSEQUENCEVERIFY
If the flag ScriptVerifyCheckSequenceVerify is not set, byte 0xb2 behaves as an upgradable no-operation (named OP_NOP3) (Rule 6.21). Otherwise, let be the top element decoded as a number with maximum length 5, without popping it, let be the transaction version and the sequence number of the input being verified. Then:
- MUST hold (
ErrNegativeLockTime); - if bit 31 of is set ( AND
0x80000000), the opcode succeeds with no further checks; - MUST hold (
ErrUnsatisfiedLockTime); - bit 31 of MUST be clear (
ErrUnsatisfiedLockTime); - let =
0x0040ffff(the type flag, bit 22, together with the low 16 bits), AND and AND . and MUST be of the same kind: both0x00400000or both0x00400000(ErrUnsatisfiedLockTime); - MUST hold (
ErrUnsatisfiedLockTime).
dcrd: txscript/opcode.go · opcodeCheckSequenceVerify
Note
Bits 16 to 21 and 23 to 30 of both values, and bits 32 to 38 of the 5-byte operand, are ignored. The meaning of the input sequence number as a relative lock time (blocks if bit 22 is clear, units of 512 seconds if set) and its enforcement are specified in Chapter 7; this opcode only compares the script’s requirement with the value the transaction commits to.Implementation pitfall
Both lock-time operands are subject to the minimal-encoding rule of Rule 6.11. The test vector table of DCP-0003 lists the public key script05 00 00 00 00 00 b2 51 (a 5-byte non-minimal encoding of zero followed by OP_CHECKSEQUENCEVERIFY OP_1) as valid; dcrd rejects it with ErrMinimalData. (The non-minimal lock-time operands in dcrd’s txscript/testdata/tx_invalid.json are 6 bytes long and fail the length check, ErrNumOutOfRange, before minimality is considered.) The reference implementation is authoritative.6.8.9 No-Operation and Unassigned Opcodes¶
Rule 6.21 · No-operation opcodes
When executed:
OP_NOP(0x61),OP_2MUL(0x8d),OP_2DIV(0x8e) and the stake tag opcodes0xba–0xbdhave no effect under any flags;- the upgradable no-operations
OP_NOP1(0xb0),OP_NOP4–OP_NOP10(0xb3–0xb9) andOP_UNKNOWN196–OP_UNKNOWN248(0xc4–0xf8), and the flag-gated opcodes0xb1,0xb2,0xc0,0xc1,0xc2,0xc3when their enabling flag is not set, have no effect unless the flagScriptDiscourageUpgradableNopsis set, in which case they fail (ErrDiscourageUpgradableNOPs).
All of these count toward the operation limit when reached.
dcrd: txscript/opcode.go · opcodeNop
Rule 6.22 · Reserved and invalid opcodes
ExecutingOP_RESERVED (0x50), OP_VER (0x62), or any of 0xf9–0xff fails (ErrReservedOpcode). In an unexecuted branch they have no effect. 0x50 does not count toward the operation limit; the others do.dcrd: txscript/opcode.go · opcodeReserved | txscript/opcode.go · opcodeInvalid
ScriptDiscourageUpgradableNops is a policy flag and is never set in consensus validation; consensus therefore treats every upgradable no-operation as a plain no-operation. Note also that OP_2MUL and OP_2DIV are no-operations that are not discouraged even under the policy flag.
6.8.10 Stake and Treasury Tag Opcodes¶
Bytes 0xba–0xbd (OP_SSTX, OP_SSGEN, OP_SSRTX, OP_SSTXCHANGE) and 0xc1–0xc3 (OP_TADD, OP_TSPEND, OP_TGEN) are tags: when executed they do nothing. Their meaning is structural and is enforced outside the engine (Section 6.12). The stake tags 0xba–0xbd are no-operations under all flags. The treasury tags are no-operations when ScriptVerifyTreasury is set; when it is not set they are the upgradable no-operations OP_UNKNOWN193–OP_UNKNOWN195 (Rule 6.21).
6.9 Signature Verification¶
Six opcodes verify signatures: OP_CHECKSIG and OP_CHECKSIGVERIFY (ECDSA over secp256k1, one key), OP_CHECKMULTISIG and OP_CHECKMULTISIGVERIFY (ECDSA, of keys), and OP_CHECKSIGALT and OP_CHECKSIGALTVERIFY (alternative suites: Ed25519 and EC-Schnorr-DCRv0). In every case the message signed is the 32-byte signature hash of Section 6.10, computed from the transaction, the input index, the hash type and a subscript derived from the current script.
A signature element on the stack is the encoded signature followed by one hash type byte. The engine distinguishes two kinds of failure. An encoding failure (an invalid hash type, a non-canonical DER signature or a disallowed public key format) makes the script fail immediately. A verification failure (a signature that is well encoded but does not verify, a public key that is not a valid curve point, and similar) makes the opcode push false; the script fails only if that false value is later verified or left as the result. The difference is observable (for example with OP_CHECKSIG OP_NOT) and is consensus.
6.9.1 Encoding Checks¶
Rule 6.23 · Hash type encoding
A hash type byte is valid if and only if AND0x7f is 1, 2 or 3; that is, is one of 0x01, 0x02, 0x03, 0x81, 0x82, 0x83. An invalid hash type is an encoding failure (ErrInvalidSigHashType).dcrd: txscript/consensus.go · CheckHashTypeEncoding
Rule 6.24 · Strict DER signature encoding
An ECDSA signature (the signature element without its hash type byte) MUST satisfy all of the following; any violation is an encoding failure with the error kind shown. Let .
- (
ErrSigTooShort) and (ErrSigTooLong). -
0x30(ErrSigInvalidSeqID). - (
ErrSigInvalidDataLen). - Let and . (
ErrSigMissingSTypeID) and (ErrSigMissingSLen). - Let . (
ErrSigInvalidSLen). -
0x02(ErrSigInvalidRIntID); (ErrSigZeroRLen); AND0x80(ErrSigNegativeR); not ( and0x00and AND0x80) (ErrSigTooMuchRPadding). -
0x02(ErrSigInvalidSIntID); (ErrSigZeroSLen); the first byte of has its top bit clear (ErrSigNegativeS); not ( and ’s first byte is0x00and its second byte has the top bit clear) (ErrSigTooMuchSPadding). - With leading zero bytes removed, is at most 32 bytes, and as a big-endian integer and (rounded down), where is the order of the secp256k1 group (
ErrSigHighS).
The bytes of are and those of are .
dcrd: txscript/consensus.go · CheckSignatureEncoding
These checks do not ensure that is non-zero or less than , nor that is non-zero; those conditions are checked when the signature is parsed (Chapter 3), and a failure there is a verification failure, not an encoding failure.
Rule 6.25 · Public key encoding
A public key forOP_CHECKSIG or OP_CHECKMULTISIG MUST be either 33 bytes beginning with 0x02 or 0x03 (compressed) or 65 bytes beginning with 0x04 (uncompressed). Anything else, including the 65-byte “hybrid” formats beginning with 0x06 or 0x07, is an encoding failure (ErrPubKeyType). Whether the bytes denote a point on the curve is checked later, and a failure there is a verification failure.dcrd: txscript/consensus.go · CheckPubKeyEncoding | txscript/engine.go · isStrictPubKeyEncoding
6.9.2 The Subscript¶
The signature hash commits to the script containing the signature-checking opcode, called the current script: the public key script for an ordinary spend, the redeem script for a P2SH spend, or the signature script itself if the signature opcode appears there. Because OP_CODESEPARATOR is disabled (executing or passing over it fails), the subscript always starts at the beginning of the current script.
Before hashing, every push in the current script whose data contains a signature element being checked is removed. This exists for historical reasons and rarely matters, but it is consensus.
Rule 6.26 · Subscript construction
The subscript for a signature element is the current script with every opcode removed that satisfies both:
- it is canonical in the sense of Algorithm 6.4 (this differs from the minimal-push rule), and
- its data contains as a contiguous substring.
The opcodes that remain are concatenated in their original encoding. If is empty, nothing is removed. For OP_CHECKMULTISIG the removal is applied successively for every signature element popped, in the order they were popped (topmost first), before any signature is checked.
dcrd: txscript/opcode.go · opcodeCheckSig | txscript/script.go · removeOpcodeByData | txscript/script.go · isCanonicalPush
Algorithm 6.4 · Removing signature pushes from the subscript
def is_canonical_for_removal(op, data) -> bool:
if op > 0x60: # not a push-class opcode
return True
if 0x00 < op < 0x4c and len(data) == 1 and data[0] <= 16:
return False # note: includes data == 00
if op == 0x4c and len(data) < 0x4c: return False
if op == 0x4d and len(data) <= 0xff: return False
if op == 0x4e and len(data) <= 0xffff: return False
return True
def remove_sig_pushes(script: bytes, e: bytes) -> bytes:
if len(script) == 0 or len(e) == 0:
return script
out = b""
for op, data, start, end in parse_with_offsets(script):
if is_canonical_for_removal(op, data) and contains(data, e):
continue # drop this opcode
out += script[start:end] # keep its original bytes
return outdcrd: txscript/script.go · removeOpcodeByData
Opcodes without data never match (a non-empty is not a substring of the empty string). Note that OP_DATA_1 00 counts as non-canonical here (although it is a minimal push under Rule 6.7), whereas OP_DATA_1 81 counts as canonical.
6.9.3 OP_CHECKSIG¶
Rule 6.27 · OP_CHECKSIG
[... sig pk] → [... bool]. In this order:
- Pop (the public key), then (the signature element).
- If , push false and stop. (The public key is not checked.)
- Let be the last byte of and the preceding bytes. MUST pass Rule 6.23, MUST pass Rule 6.24 and MUST pass Rule 6.25; each failure is an encoding failure.
- Build the subscript by Rule 6.26 for and compute the signature hash (Algorithm 6.6) with hash type . If the hash cannot be computed (the
SIGHASH_SINGLEcase of Rule 6.30), push false and stop. - Parse as a secp256k1 point and as a DER signature (Chapter 3); if either fails, push false and stop.
- Push true if the ECDSA signature is valid for under , else false.
dcrd: txscript/opcode.go · opcodeCheckSig
OP_CHECKSIGVERIFY performs OP_CHECKSIG followed by verification of the result (ErrCheckSigVerify).
6.9.4 OP_CHECKMULTISIG¶
Decred’s multisignature opcode does not pop an extra “dummy” element. A signature script that supplies Bitcoin’s customary leading OP_0 leaves that element on the stack, which fails the clean-stack rule in consensus validation.
Rule 6.28 · OP_CHECKMULTISIG
[... sig_1 … sig_m m pk_1 … pk_n n] → [... bool]. In this order:
- Pop the numeric operand (4-byte maximum). MUST hold (
ErrInvalidPubKeyCount). - Add to the per-script operation count; the count MUST NOT exceed 255 (
ErrTooManyOperations). - Pop public keys. Call them in popping order ( was on top, so
pk_n). - Pop the numeric operand (4-byte maximum). MUST hold (
ErrInvalidSignatureCount). - Pop signature elements in popping order (
sig_m). - Compute the subscript by applying Rule 6.26 for , then , and so on.
- Match signatures to keys with Algorithm 6.5 and push its result.
dcrd: txscript/opcode.go · opcodeCheckMultiSig
Algorithm 6.5 · OP_CHECKMULTISIG matching
def multisig_match(E, K, subscript, tx, idx) -> bool:
parsed = [None] * len(E) # None: not yet parsed; INVALID; or a signature
keys_left, sigs_left = len(K) + 1, len(E)
ki, si = -1, 0
while sigs_left > 0:
ki += 1; keys_left -= 1
if sigs_left > keys_left:
return False # cannot succeed any more
e, k = E[si], K[ki]
if len(e) == 0:
continue # empty signature: next key
t, g = e[-1], e[:-1]
if parsed[si] is None:
check_hash_type(t) # encoding failure: script fails
check_der(g) # encoding failure: script fails
parsed[si] = parse_der(g) or INVALID
if parsed[si] is INVALID:
continue
elif parsed[si] is INVALID:
continue
check_pubkey_encoding(k) # encoding failure: script fails
point = parse_pubkey(k)
if point is None:
continue
h = signature_hash(subscript, t, tx, idx) # SIGHASH_SINGLE out of range:
# the script FAILS here
if ecdsa_verify(parsed[si], h, point):
si += 1; sigs_left -= 1
return Truedcrd: txscript/opcode.go · opcodeCheckMultiSig
Consequences that must be reproduced exactly:
- Signatures must appear in the same relative order as the keys they match. Matching starts from the topmost signature and topmost key.
- A key that fails to match the current signature is skipped and never reconsidered. Once fewer keys remain than signatures, the result is false without examining the rest.
- Encoding checks are lazy: a signature’s hash type and DER encoding are checked only when that signature is first compared, and a key’s encoding only when it is compared against a non-empty, parseable signature. Elements never reached are never checked, so a badly encoded key or signature beyond the point of early exit does not cause failure.
- An empty signature element matches no key; with empty elements, the result is false after the keys are exhausted.
- With the result is true and no key is examined;
0 0 OP_CHECKMULTISIGpushes true. - Unlike
OP_CHECKSIG, an out-of-rangeSIGHASH_SINGLEmakes the script fail rather than push false. - The key count is added to the operation count whenever the opcode is executed, regardless of how many keys are examined.
OP_CHECKMULTISIGVERIFY performs OP_CHECKMULTISIG followed by verification (ErrCheckMultiSigVerify).
6.9.5 OP_CHECKSIGALT¶
OP_CHECKSIGALT verifies a signature under one of several alternative signature suites, selected by a small integer on top of the stack. Table 6.10 lists the suites.
OP_CHECKSIGALT| Type | Suite | Public key | Element | Behaviour |
|---|---|---|---|---|
| 0 | (ECDSA, not allowed here) | — | — | Pushes false; nothing else popped. |
| 1 | Ed25519 | 32 bytes | 65 bytes | Verified as below. |
| 2 | EC-Schnorr-DCRv0 (secp256k1) | 33 bytes | 65 bytes | Verified as below. |
| other | unassigned | — | — | Pushes true; nothing else popped. |
Rule 6.29 · OP_CHECKSIGALT
[... sig pk type] → [... bool]. In this order:
- Pop the numeric operand with maximum length 1 (so ; a longer element fails with
ErrNumOutOfRange). - If , push false and stop. If is neither 1 nor 2, push true and stop. In both cases the public key and signature are not popped.
- Pop . If (for ) or (for ), push false and stop; the signature element is not popped.
- Pop . If , push false and stop.
- Let and . MUST pass Rule 6.23 (encoding failure). No DER or public key format check applies.
- Build the subscript by Rule 6.26 for and compute the signature hash with hash type . If it cannot be computed, push false and stop.
- For : parse as an Ed25519 public key and as an Ed25519 signature; for : parse as a compressed secp256k1 public key (first byte
0x02or0x03) and as an EC-Schnorr-DCRv0 signature with and (Chapter 3). If either parse fails, push false; otherwise push the result of verifying over under .
dcrd: txscript/opcode.go · opcodeCheckSigAlt
OP_CHECKSIGALTVERIFY performs OP_CHECKSIGALT followed by verification (ErrCheckSigAltVerify).
Implementation pitfall
The early exits ofOP_CHECKSIGALT leave elements on the stack. For an unassigned type such as 3 the opcode consumes only the type and pushes true, so 3 OP_CHECKSIGALT succeeds on an otherwise empty stack. With a wrong-length public key the signature element stays beneath the pushed false. Under the clean-stack rule these leftovers usually cause failure, but an implementation that pops all three operands up front produces different results for scripts such as <sig> <short key> 1 OP_CHECKSIGALT OP_NOT OP_DROP.Rationale
Treating unknown signature types as success was intended to allow new suites to be introduced as soft forks, by making a previously always-succeeding opcode stricter. Type 0 is the identifier of ECDSA over secp256k1 (STEcdsaSecp256k1), which has its own opcodes; through OP_CHECKSIGALT it always yields false.Table 6.11 summarizes which conditions fail the script and which push false.
| Condition | CHECKSIG | CHECKMULTISIG | CHECKSIGALT |
|---|---|---|---|
| Too few stack elements | fail | fail | faila |
| Empty signature element | false | skip key | false (wrong length) |
| Invalid hash type | fail | fail (if reached) | fail |
| DER encoding violation | fail | fail (if reached) | n/a |
| Public key format violation | fail | fail (if reached) | false (length only) |
| Key not a valid point / signature unparseable | false | skip | false |
SIGHASH_SINGLE index out of range | false | fail | false |
| Signature does not verify | false | skip key | false |
a Only for elements actually popped: signature type 0 and unknown types return after popping the type alone, and a public key of the wrong length yields false before the signature is popped, leaving the signature on the stack (Rule 6.29).
6.10 Signature Hash¶
The signature hash is the 32-byte message that signatures commit to. Decred computes it from two intermediate hashes, mirroring its split of a transaction into a prefix (inputs’ outpoints and sequences, outputs, lock time, expiry) and a witness (per-input data, Chapter 4). The prefix hash commits to the parts of the prefix selected by the hash type; the witness hash commits to the subscript, placed at the position of the input being signed. The final hash commits to the hash type and both intermediate hashes. All three hashes use BLAKE-256.
| Value | Name | Commits to |
|---|---|---|
0x01 | SIGHASH_ALL | All inputs and all outputs. |
0x02 | SIGHASH_NONE | All inputs (other inputs’ sequence numbers replaced by 0) and no outputs. |
0x03 | SIGHASH_SINGLE | All inputs (other inputs’ sequence numbers replaced by 0) and the output at the same index as the input; earlier outputs are committed in blanked form, later outputs not at all. |
0x80 | SIGHASH_ANYONECANPAY | Flag combined with one of the above: only the input being signed is committed, in both the prefix and the witness. |
Two constants select the serialization variant and are mixed into the version field of each intermediate serialization: SigHashSerializePrefix and SigHashSerializeWitness .
Rule 6.30 · SIGHASH_SINGLE with no matching output
If the hash type AND0x1f equals 3 and the input index is greater than or equal to the number of transaction outputs, the signature hash is undefined (ErrInvalidSigHashSingleIndex). The consequence is opcode-specific: OP_CHECKSIG and OP_CHECKSIGALT push false, and OP_CHECKMULTISIG fails the script (Table 6.11).dcrd: txscript/sighash.go · calcSignatureHash
Algorithm 6.6 · Signature hash
ALL, NONE, SINGLE, ANYONECANPAY = 0x01, 0x02, 0x03, 0x80
SER_PREFIX, SER_WITNESS = 1, 3
def signature_hash(sub: bytes, t: int, tx, idx: int) -> bytes:
base = t & 0x1f
if base == SINGLE and idx >= len(tx.outputs):
fail("ErrInvalidSigHashSingleIndex")
if t & ANYONECANPAY:
ins, sign_in = [tx.inputs[idx]], 0
else:
ins, sign_in = tx.inputs, idx
if base == NONE:
outs = []
elif base == SINGLE:
outs = tx.outputs[: idx + 1]
else: # ALL (and any other value)
outs = tx.outputs
p = le32(tx.version | (SER_PREFIX << 16)) + varint(len(ins))
for j, ti in enumerate(ins):
seq = ti.sequence
if base in (NONE, SINGLE) and j != sign_in:
seq = 0
p += ti.prev_hash + le32(ti.prev_index) + u8(ti.prev_tree) + le32(seq)
p += varint(len(outs))
for j, to in enumerate(outs):
value, script = to.value, to.pk_script
if base == SINGLE and j != idx:
value, script = -1, b"" # version is kept
p += le64(uint64(value)) + le16(to.version) + varint(len(script)) + script
p += le32(tx.lock_time) + le32(tx.expiry)
w = le32(tx.version | (SER_WITNESS << 16)) + varint(len(ins))
for j in range(len(ins)):
s = sub if j == sign_in else b""
w += varint(len(s)) + s
return BLAKE256(le32(t) + BLAKE256(p) + BLAKE256(w))dcrd: txscript/sighash.go · calcSignatureHash | txscript/sighash.go · CalcSignatureHash
Notes on Algorithm 6.6:
tx.versionis the 16-bit transaction version; the low 16 bits of the 32-bit field are the version and the high 16 bits the serialization type.varintis the variable-length integer of Chapter 4.prev_hashis the 32-byte previous transaction hash in its internal (non-reversed) byte order, andprev_treeis the one-byte tree indicator of the outpoint.- The final serialization is 68 bytes: the full hash type byte zero-extended to 32 bits and written little-endian, followed by the two 32-byte hashes.
- For
SIGHASH_ALLwithoutSIGHASH_ANYONECANPAY, the prefix serialization is byte-for-byte the transaction prefix serialization of Chapter 4, so the prefix hash equals the transaction hash. This is not true of the witness part: the signature-hash witness contains only the subscript for the signed input and an empty script for every other input, and none of the value, block height, block index or signature script fields of the wire witness serialization. - In the
SIGHASH_SINGLEcase, every output before the signed index is committed with amount (eight0xffbytes), its original script version, and an empty script; outputs after the index are omitted. WithSIGHASH_ANYONECANPAY, the comparisonj != idxstill uses the original input index, since output positions are not renumbered. - Within the engine the hash type has already passed Rule 6.23, so
baseis 1, 2 or 3. The mask0x1fand the treatment of other values asSIGHASH_ALLmatter only to external callers of the function (dcrd’s test vectors exercise them). OP_CODESEPARATORhas no role: it cannot appear in a script that executes. The subscriptsubis the whole current script minus the pushes removed by Rule 6.26.
The signature hash vectors in Section 6.17 show the intermediate serializations for each hash type.
6.11 Pay-to-Script-Hash¶
Pay-to-script-hash [31] lets an output commit to the hash of an arbitrary redeem script rather than to the script itself. The spender reveals the redeem script as the last push of the signature script, together with the data that satisfies it. The engine first checks that the revealed script hashes to the committed value, then executes the redeem script. In Decred the hash is OP_HASH160, that is RIPEMD-160(BLAKE-256(·)).
Pay-to-script-hash is recognized purely by the byte pattern of the public key script (Section 6.5), regardless of the script version and of any flags other than ScriptVerifyTreasury, which widens the set of stake tags. There is no activation height: P2SH has been enforced since the genesis block.
| Form | Length | Bytes |
|---|---|---|
| P2SH | 23 | a9 14 ‖ 20-byte hash ‖ 87 |
| Stake-tagged P2SH | 24 | tag ‖ a9 14 ‖ 20-byte hash ‖ 87, tag ∈ {ba, bb, bc, bd}, or also ∈ {c1, c2, c3} when ScriptVerifyTreasury is set |
The 23-byte form is recognized only when the whole public key script is exactly that pattern; the bytes a9 14 … 87 embedded in a longer script do not make it P2SH. A stake-tagged P2SH script executes its tag as a no-operation, then the ordinary hash comparison.
Rule 6.31 · Pay-to-script-hash evaluation
If the public key script is P2SH-shaped:
- the signature script MUST be push-only, and for version 0 the redeem-script conditions of Rule 6.3 step 4 MUST hold;
- after the signature script, the data stack is saved, and the public key script is executed on it as usual (it compares the hash of the top element with the committed hash);
- after the public key script, the data stack MUST be non-empty (
ErrEmptyStack) and its top element MUST be true (ErrEvalFalse). No clean-stack check applies at this point; - the redeem script is the top element of the saved stack. MUST parse (
ErrMalformedPush). The data stack is replaced by the saved stack with removed, and is executed as a third script, with its own operation count, alternate stack and conditional state; - the final result is then determined by Rule 6.9.
dcrd: txscript/engine.go · Engine.Step | txscript/engine.go · NewEngine
Rule 6.32 · No stake opcodes in redeem scripts
For a version 0 spend of a P2SH-shaped output, the redeem script MUST NOT contain any of the opcodes0xba–0xbd, and, when ScriptVerifyTreasury is set, 0xc1–0xc3 (ErrP2SHStakeOpCodes). The redeem script is scanned opcode by opcode from the start; if a parse failure is met before any such opcode, the spend also fails.dcrd: txscript/script.go · hasP2SHRedeemScriptStakeOpCodes
Rationale
Stake and treasury tags are meaningful only in the precise positions the stake system checks. Hiding one inside a redeem script, where no structural rule can see it, is prohibited outright so that tagged scripts cannot be smuggled into regular transactions.Note
Redeem scripts are not subject to the 16384-byte script size limit, but as stack elements they are limited to 2048 bytes by Rule 6.6. Like every script, a redeem script has its own limit of 255 operations.History
Before thetreasury agenda (DCP-0006) is active, the flag ScriptVerifyTreasury is not set, so 0xc1–0xc3 are neither stake tags for P2SH detection nor prohibited in redeem scripts. A script such as c1 a9 14 … 87 is then executed as an ordinary script whose first opcode is a no-operation (OP_UNKNOWN193), not as P2SH; dcrd’s test data includes both cases.6.12 Stake and Treasury Tags¶
Decred’s staking and treasury transactions place tag opcodes at the start of specific output scripts. A ticket’s voting-rights output begins with OP_SSTX, its change outputs with OP_SSTXCHANGE, vote outputs with OP_SSGEN, revocation outputs with OP_SSRTX, treasury additions with OP_TADD, treasury spend payouts with OP_TGEN, and the treasury spend signature script ends with OP_TSPEND. The tags let consensus code recognize these outputs, and impose maturity and other spending restrictions on them, without executing scripts.
The script engine itself enforces only the following; everything else about the tags is a transaction-level rule.
- Executing a tag does nothing (Section 6.8.10). After the tag, a tagged pay-to-pubkey-hash script is executed exactly as the untagged form, and a tagged P2SH script is evaluated as P2SH (Rule 6.31).
- Redeem scripts must not contain tags (Rule 6.32).
- The treasury tags
0xc1–0xc3are tags only whenScriptVerifyTreasuryis set; otherwise they are upgradable no-operations.
The rules that restrict where tags may appear, and what must follow them, are specified elsewhere and summarized in Table 6.14.
| Tag | Required forms | Specified in |
|---|---|---|
OP_SSTX | Ticket output 0: tag followed by a P2PKH or P2SH script (26 or 24 bytes). | Chapter 8 |
OP_SSTXCHANGE | Ticket change outputs, and the optional change output (output 1) of a treasury add: tag followed by P2PKH or P2SH. | Chapter 8, Chapter 12 |
OP_SSGEN | Vote payment outputs: tag followed by P2PKH or P2SH. | Chapter 8 |
OP_SSRTX | Revocation outputs: tag followed by P2PKH or P2SH. | Chapter 8 |
OP_TADD | Treasury add and treasurybase output 0: the single byte c1. | Chapter 12 |
OP_TGEN | Treasury spend payouts: tag followed by P2PKH or P2SH. | Chapter 12 |
OP_TSPEND | Treasury spend signature script: OP_DATA_64 <sig> OP_DATA_33 <key> OP_TSPEND (100 bytes). | Chapter 12 |
| any | Outputs of regular (non-stake) transactions must not contain any tag opcode (Rule 6.33). | Chapter 7 |
Rule 6.33 · Detecting tag opcodes in a script
A script contains a stake opcode if, scanning its opcodes in order with version 0 parsing, an opcode in0xba–0xbd is found, or, when treasury rules are in effect, an opcode in 0xc1–0xc3, before the end of the script or the first parse failure. If a parse failure is reached first, the predicate reports that failure as an error. Opcode bytes are only examined at opcode boundaries; a tag value inside push data does not count.dcrd: txscript/script.go · ContainsStakeOpCodes | txscript/script.go · isStakeOpcode
The transaction-level rule that applies this predicate to regular transactions (and treats the parse error as invalidity) is in Chapter 7.
6.13 Verification Flags¶
The caller passes a set of flags that modify the engine. Table 6.15 lists every flag defined by dcrd, with its bit value and effect. Which flags consensus validation passes for a given block is specified in Chapter 7; as of the reference commit it is ScriptVerifyCleanStack and ScriptVerifyCheckLockTimeVerify for every block, plus ScriptVerifyCheckSequenceVerify and ScriptVerifySHA256 when the lnfeatures agenda is active, plus ScriptVerifyTreasury when the treasury agenda is active. ScriptDiscourageUpgradableNops and ScriptVerifySigPushOnly are never used for consensus. dcrd’s relay policy sets the first but not the second: it obtains the push-only requirement from a separate standardness check (Chapter 17).
| Bit | Flag | Effect when set |
|---|---|---|
0x01 | ScriptDiscourageUpgradableNops | Executing an upgradable no-operation fails (Rule 6.21). Policy only. |
0x02 | ScriptVerifyCheckLockTimeVerify | Byte 0xb1 is OP_CHECKLOCKTIMEVERIFY (Rule 6.19); otherwise it is the no-operation OP_NOP2. |
0x04 | ScriptVerifyCheckSequenceVerify | Byte 0xb2 is OP_CHECKSEQUENCEVERIFY (Rule 6.20); otherwise it is OP_NOP3. |
0x08 | ScriptVerifyCleanStack | The data stack must hold exactly one element at the end (Rule 6.9). |
0x10 | ScriptVerifySigPushOnly | Every signature script must be push-only (Rule 6.3 step 2). Set by neither consensus nor dcrd’s policy. |
0x20 | ScriptVerifySHA256 | Byte 0xc0 is OP_SHA256 (Rule 6.18); otherwise it is OP_UNKNOWN192. |
0x40 | ScriptVerifyTreasury | Bytes 0xc1–0xc3 are the treasury tags: they count as stake tags for P2SH detection and redeem-script prohibition. Otherwise they are OP_UNKNOWN193–OP_UNKNOWN195. |
The signature operation counter (Section 6.14) and Rule 6.33 take a separate “treasury rules in effect” argument. It reflects the same agenda condition as ScriptVerifyTreasury, but is supplied by the caller rather than read from the engine flags.
6.14 Signature Operation Counting¶
To bound the cost of validating a block, consensus limits the number of signature operations a block may contain (Chapter 10). The count is a static estimate made without executing scripts. This section specifies the counting functions; the limit, and which transactions of a block are counted, are in Chapter 10.
Algorithm 6.7 · Counting signature operations in one script
def count_sigops(script: bytes, precise: bool, treasury: bool) -> int:
n, prev = 0, 0xff # prev starts as OP_INVALIDOPCODE
for op, data in parse_prefix(script): # opcodes before any parse failure
if op == 0xc2: # OP_TSPEND
if treasury: n += 1
elif op in (0xac, 0xad, 0xbe, 0xbf): # CHECKSIG(VERIFY), CHECKSIGALT(VERIFY)
n += 1
elif op in (0xae, 0xaf): # CHECKMULTISIG(VERIFY)
if precise and 0x51 <= prev <= 0x60: # OP_1 .. OP_16
n += prev - 0x50
else:
n += 20
prev = op
return ndcrd: txscript/script.go · countSigOpsV0 | txscript/script.go · GetSigOpCount
parse_prefix yields the opcodes of the script that parse successfully before its first parse failure (all of them if there is none); a malformed script is counted up to the failure, not rejected. Opcodes are counted wherever they appear, including in branches that would not be executed and after an OP_RETURN. Push data is not inspected.
The imprecise count, GetSigOpCount(script, treasury), is count_sigops(script, False, treasury): every multisignature opcode counts 20. The precise count applies to P2SH spends.
Algorithm 6.8 · Precise count for a P2SH spend
def precise_sigops(sig_script, pk_script, treasury) -> int:
if not is_p2sh(pk_script): # 23-byte untagged form only
return count_sigops(pk_script, True, treasury)
if len(sig_script) == 0 or not is_push_only(sig_script):
return 0
redeem = final_opcode_data(sig_script) # b"" if unparseable or no data
if len(redeem) == 0:
return 0
return count_sigops(redeem, True, treasury)dcrd: txscript/script.go · GetPreciseSigOpCount | txscript/script.go · finalOpcodeData
In precise mode, a multisignature opcode counts the value of an immediately preceding OP_1–OP_16; it counts 20 if the preceding opcode is anything else, including OP_0 and a numeric data push such as 01 11 (17). Despite its name, the “precise” count is therefore an upper bound for key counts 17 to 20.
Rule 6.34 · Transaction signature operation count
The signature operation count of a transaction, given whether it is a coinbase, whether it is a vote, the UTXO view, and whether the treasury agenda is active (), is , where:
(the imprecise part):
- if and the transaction is a treasurybase, ;
- otherwise is the sum of
GetSigOpCountover the signature scripts of all inputs (no inputs for a coinbase; all inputs except the first for a vote) plus the sum ofGetSigOpCountover the public key scripts of all outputs.
(the P2SH part):
- if the transaction is a coinbase, or if and it is a treasury spend or treasurybase, ;
- otherwise, for every input (all inputs except the first for a vote), the referenced output MUST exist unspent in the view (
ErrMissingTxOut); if its public key script is the 23-byte untagged P2SH form, addprecise_sigops(sig_script, pk_script, tr); other inputs add nothing.
Every addition is performed in unsigned 32-bit arithmetic and MUST NOT overflow (ErrTooManySigOps).
dcrd: internal/blockchain/validate.go · CountTotalSigOps | internal/blockchain/validate.go · countSigOps | internal/blockchain/validate.go · countP2SHSigOps
Implementation pitfall
Spends of stake-tagged P2SH outputs contribute nothing to , because only the untagged 23-byte form is examined; the signature operations of their redeem scripts are not counted anywhere. Signature operations in a redeem script are also never counted by the imprecise pass, because the redeem script is push data within the signature script. AndOP_TSPEND counts as one signature operation once the treasury agenda is active, although the engine executes it as a no-operation, since the treasury spend’s signature is checked by the treasury rules (Chapter 12).6.15 Other Consensus Predicates¶
Besides the engine, consensus code uses a few script predicates defined in the same package.
Rule 6.35 · Provably unspendable outputs
An output with amount and public key script is provably unspendable if any of the following holds, regardless of its script version:
- ;
- ;
- and
0x6a(OP_RETURN); - fails to parse under version 0 rules.
Provably unspendable outputs are never added to the UTXO set (Chapter 7), so no input can ever spend them.
dcrd: txscript/script.go · IsUnspendable | internal/blockchain/utxoviewpoint.go · UtxoViewpoint.AddTxOuts
Implementation pitfall
This predicate ignores the script version and treats every zero-value output as unspendable. A zero-value output with script51 (OP_TRUE), or a version-1 output whose script begins with 0x6a, would pass the script engine but can never be spent, because it never enters the UTXO set. A script with OP_RETURN anywhere other than the first byte is not covered.Rule 6.36 · Strict null-data scripts
A script with version is a strict null-data script with required length if , ,0x6a, and either and , or the remainder parses as exactly one opcode which is canonical under Algorithm 6.4′s is_canonical_for_removal and which is either a small-integer opcode (OP_0 or OP_1–OP_16) with , or an opcode at most 0x4b (OP_DATA_75) whose data length is exactly .dcrd: txscript/consensus.go · IsStrictNullData
The treasury rules use this predicate to check the OP_RETURN outputs of treasurybase and treasury spend transactions (Chapter 12). A companion predicate, strict compressed public key encoding, holds for exactly the 33-byte strings beginning with 0x02 or 0x03; it is used by the treasury spend checks and by policy.
6.16 Standard Script Classes¶
The forms in this section are policy: dcrd’s mempool and wallets recognize them, but consensus never requires a script to be standard (except where the stake and treasury rules require specific forms, which those chapters specify). The mapping between addresses and these templates is in Chapter 5; standardness policy is in Chapter 17.
Recognition is defined for script version 0 only; a script with any other version is non-standard. Table 6.16 lists the templates. In the templates, ‖ is concatenation, H is a 20-byte hash, K33 a 33-byte compressed secp256k1 key (first byte 02 or 03), K65 a 65-byte uncompressed key (first byte 04) and E32 a 32-byte Ed25519 key.
| Class | Bytes | Template |
|---|---|---|
pubkey | 35 / 67 | 21 ‖ K33 ‖ ac or 41 ‖ K65 ‖ ac |
pubkey-ed25519 | 35 | 20 ‖ E32 ‖ 51 ‖ be |
pubkey-schnorr-secp256k1 | 36 | 21 ‖ K33 ‖ 52 ‖ be |
pubkeyhash | 25 | 76 a9 14 ‖ H ‖ 88 ac |
pubkeyhash-ed25519 | 26 | 76 a9 14 ‖ H ‖ 88 51 be |
pubkeyhash-schnorr-secp256k1 | 26 | 76 a9 14 ‖ H ‖ 88 52 be |
scripthash | 23 | a9 14 ‖ H ‖ 87 |
multisig | var. | OP_m ‖ ( pushes of K33) ‖ OP_n ‖ ae, |
nulldata | 1–260 | 6a, or 6a ‖ one canonical push of at most 256 bytes |
stakesubmission-pubkeyhash | 26 | ba ‖ pubkeyhash |
stakesubmission-scripthash | 24 | ba ‖ scripthash |
stakegen-pubkeyhash | 26 | bb ‖ pubkeyhash |
stakegen-scripthash | 24 | bb ‖ scripthash |
stakerevoke-pubkeyhash | 26 | bc ‖ pubkeyhash |
stakerevoke-scripthash | 24 | bc ‖ scripthash |
stakechange-pubkeyhash | 26 | bd ‖ pubkeyhash |
stakechange-scripthash | 24 | bd ‖ scripthash |
treasuryadd | 1 | c1 |
treasurygen-pubkeyhash | 26 | c3 ‖ pubkeyhash |
treasurygen-scripthash | 24 | c3 ‖ scripthash |
Details of the less obvious templates:
- Alternative-signature forms. The signature type is pushed with a small-integer opcode:
51(OP_1) for Ed25519 and52(OP_2) for EC-Schnorr-DCRv0. Type 0 is never standard. The Schnorr pay-to-pubkey form additionally requires the key’s first byte to be02or03; the Ed25519 form imposes no condition on the 32 key bytes. - Multisig. The first opcode is
OP_1–OP_16giving (OP_0is rejected). It is followed by one or more opcodes whose data is a strict compressed key (any push opcode qualifies, not onlyOP_DATA_33; the run of keys ends at the first opcode whose data is not such a key), then a small-integer opcode equal to the number of keys , with , and thenae(OP_CHECKMULTISIG) as the last and only remaining byte. Uncompressed keys are not standard in multisig. The 16-key maximum is narrower than the consensus limit of 20. - Null data. After
6a, exactly one opcode of byte value at most0x60that is canonical underis_canonical_for_removalof Algorithm 6.4 and whose data is at most 256 bytes (MaxDataCarrierSizeV0). - Precedence. A script is assigned the first class that matches, in the order of Table 6.16. The forms are mutually exclusive in practice, so the order rarely matters.
Note
dcrd also recognizes, for informational purposes only, the hash-based atomic swap contract below, intended to be used through P2SH. It is not a standard output class.
IF SIZE <n> EQUALVERIFY SHA256 <32 bytes> EQUALVERIFY DUP HASH160 <20 bytes>
ELSE <locktime> CHECKLOCKTIMEVERIFY DROP DUP HASH160 <20 bytes>
ENDIF EQUALVERIFY CHECKSIG6.17 Test Vectors¶
All vectors in this section were produced by running dcrd’s txscript package at the reference commit. Hexadecimal strings are byte strings in natural order; hashes are not reversed.
6.17.1 Numbers, Booleans and Hashes¶
| Value | Encoding | Value | Encoding |
|---|---|---|---|
| (empty) | 00 81 | ||
01 | ff 7f | ||
81 | 00 80 80 | ||
10 | ff ff 7f | ||
7f | 00 00 80 80 | ||
ff | ff ff ff 7f | ||
80 00 | ff ff ff ff | ||
80 80 | 00 00 00 80 00 | ||
ff 00 | 00 00 00 80 80 | ||
ff 80 | fe ff ff ff 00 | ||
00 01 | ff ff ff ff 7f |
| Element | Max length 4 | Max length 5 |
|---|---|---|
| (empty) | ||
00 | ErrMinimalData | ErrMinimalData |
80 | ErrMinimalData | ErrMinimalData |
01 00 | ErrMinimalData | ErrMinimalData |
ff 00 | ||
ff 80 | ||
7f | ||
ff | ||
00 80 | ErrMinimalData | ErrMinimalData |
ff ff ff 7f | ||
ff ff ff ff | ||
00 00 00 80 00 | ErrNumOutOfRange | |
ff ff ff ff 7f | ErrNumOutOfRange | |
00 00 00 | ErrMinimalData | ErrMinimalData |
| Element | Value | Element | Value | Element | Value | Element | Value |
|---|---|---|---|---|---|---|---|
| (empty) | false | 00 | false | 80 | false | 00 80 | false |
80 00 | true | 00 00 80 | false | 00 01 | true | 01 | true |
| Opcode | Input | Output |
|---|---|---|
OP_RIPEMD160 | (empty) | 9c1185a5c5e9fc54612808977ee8f548b2258d31 |
OP_RIPEMD160 | "abc" | 8eb208f7e05d987a9b044a8e98c6b087f15a0bfc |
OP_SHA1 | (empty) | da39a3ee5e6b4b0d3255bfef95601890afd80709 |
OP_SHA1 | "abc" | a9993e364706816aba3e25717850c26c9cd0d89d |
OP_SHA256 | (empty) | e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 |
OP_SHA256 | "abc" | ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad |
OP_BLAKE256 | (empty) | 716f6e863f744b9ac22c97ec7b76ea5f5908bc5b2f67c61510bfc4751384ea7a |
OP_BLAKE256 | "abc" | 1833a9fa7cf4086bd5fda73da32e5a1d75b4c3f89d5c436369f9d78bb2da5c28 |
OP_HASH160 | (empty) | 413320bee32a3bdb92b145d337316739d54a9287 |
OP_HASH160 | "abc" | 1625a1b44671b89a24386333ef9e00b207bca403 |
OP_HASH256 | (empty) | d8ee5f957b78a961fb729098b4efb56440a14e05e3c55890f5edbc626380aaa6 |
OP_HASH256 | "abc" | f1a44bb867d5ac7053d5e071d62d4513d5b243420d9863e2718823a161c1344a |
6.17.2 Signature Hash¶
The vectors below use a sample transaction with version 1, two inputs and two outputs. Input 0 spends output 1 of a transaction whose hash bytes are 00 01 … 1f, in the regular tree, with sequence ffffffff; input 1 spends output 0 of 20 21 … 3f, in the stake tree, with sequence fffffffe. The inputs’ witness fields (value 5000000000 and 100000000 atoms, block heights 100 and 200, block indexes 2 and 3, signature scripts 51 and 52) appear in the full serialization but do not affect the signature hash. Output 0 pays 1000 atoms to script version 0 76 a9 14 01 02 … 14 88 ac; output 1 pays 2000 atoms to 6a. The lock time is 0x01020304 and the expiry 0x05060708. The subscript is output 0′s script, used here simply as a 25-byte example.
Test vector: Signature hash: the sample transaction
| Item | Value |
|---|---|
| Full serialization | 0100000002000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f0100000000ffffffff202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f0000000001feffffff02e80300000000000000001976a9140102030405060708090a0b0c0d0e0f101112131488acd0070000000000000000016a04030201080706050200f2052a010000006400000002000000015100e1f50500000000c8000000030000000152 |
| Transaction hash (internal order) | f3deadbbf50b1c407d09bc893408432844a0685df21ea15c4a73a9eba6480c5a |
| Subscript | 76a9140102030405060708090a0b0c0d0e0f101112131488ac |
Test vector: Signature hash: SIGHASH_ALL (0x1), input 0
| Item | Value |
|---|---|
| Prefix serialization | 0100010002000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f0100000000ffffffff202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f0000000001feffffff02e80300000000000000001976a9140102030405060708090a0b0c0d0e0f101112131488acd0070000000000000000016a0403020108070605 |
| Prefix hash | f3deadbbf50b1c407d09bc893408432844a0685df21ea15c4a73a9eba6480c5a |
| Witness serialization | 01000300021976a9140102030405060708090a0b0c0d0e0f101112131488ac00 |
| Witness hash | bb75f775cbeee9c804eb983c29fcc2d97a2264e6fa75a87a15a06dd4286982e5 |
| Final serialization | 01000000f3deadbbf50b1c407d09bc893408432844a0685df21ea15c4a73a9eba6480c5abb75f775cbeee9c804eb983c29fcc2d97a2264e6fa75a87a15a06dd4286982e5 |
| Signature hash | f4ce6e37ab599bcd9c770d086c79749a77f99e4a50e774caf5ff50a123feff91 |
Test vector: Signature hash: SIGHASH_NONE (0x2), input 0
| Item | Value |
|---|---|
| Prefix serialization | 0100010002000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f0100000000ffffffff202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f000000000100000000000403020108070605 |
| Prefix hash | 8aa0fda4bf9cc8936b0eec1cabc6795b0de37badda0b26b7063d475d74bd967b |
| Witness serialization | 01000300021976a9140102030405060708090a0b0c0d0e0f101112131488ac00 |
| Witness hash | bb75f775cbeee9c804eb983c29fcc2d97a2264e6fa75a87a15a06dd4286982e5 |
| Final serialization | 020000008aa0fda4bf9cc8936b0eec1cabc6795b0de37badda0b26b7063d475d74bd967bbb75f775cbeee9c804eb983c29fcc2d97a2264e6fa75a87a15a06dd4286982e5 |
| Signature hash | 03319bed79cbb29b3c6fe90e4ff6e301071ddeb3568d16462ca5ffeed787d44b |
Test vector: Signature hash: SIGHASH_SINGLE (0x3), input 1
| Item | Value |
|---|---|
| Prefix serialization | 0100010002000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f010000000000000000202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f0000000001feffffff02ffffffffffffffff000000d0070000000000000000016a0403020108070605 |
| Prefix hash | 1c60e4485f51debb2dcdc9893293a6b4e6290a3d66c57756ed95cb74b7548927 |
| Witness serialization | 0100030002001976a9140102030405060708090a0b0c0d0e0f101112131488ac |
| Witness hash | 4902291a3dcd005c1a087f947d7d37cc0de0f06daa470a5d7713f8d53b093cc7 |
| Final serialization | 030000001c60e4485f51debb2dcdc9893293a6b4e6290a3d66c57756ed95cb74b75489274902291a3dcd005c1a087f947d7d37cc0de0f06daa470a5d7713f8d53b093cc7 |
| Signature hash | 4641bb9be1f590a5cae964b188317cf168e158d24cfa27c7280941c684e42dc2 |
Test vector: Signature hash: SIGHASH_ALL | SIGHASH_ANYONECANPAY (0x81), input 0
| Item | Value |
|---|---|
| Prefix serialization | 0100010001000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f0100000000ffffffff02e80300000000000000001976a9140102030405060708090a0b0c0d0e0f101112131488acd0070000000000000000016a0403020108070605 |
| Prefix hash | 12912c99d91053050096a5745dc0d45c829c73fd45f7fa9164649c8fada6b272 |
| Witness serialization | 01000300011976a9140102030405060708090a0b0c0d0e0f101112131488ac |
| Witness hash | 3db60c902d6e97e3b0a3ec8b55a7c330392e4740a46a3b79a93445c680e58a45 |
| Final serialization | 8100000012912c99d91053050096a5745dc0d45c829c73fd45f7fa9164649c8fada6b2723db60c902d6e97e3b0a3ec8b55a7c330392e4740a46a3b79a93445c680e58a45 |
| Signature hash | 4a1ecb30301eb4a7445ffca36202deda5f9552479fd2b223e3589f8738dbbde3 |
| Input | Hash type | Signature hash |
|---|---|---|
| 0 | 0x1 | f4ce6e37ab599bcd9c770d086c79749a77f99e4a50e774caf5ff50a123feff91 |
| 0 | 0x2 | 03319bed79cbb29b3c6fe90e4ff6e301071ddeb3568d16462ca5ffeed787d44b |
| 0 | 0x3 | e8fb9b72477a691a3c5c05aa4147a3fb5feaa4e43940ead1107ef94de9392cd4 |
| 0 | 0x81 | 4a1ecb30301eb4a7445ffca36202deda5f9552479fd2b223e3589f8738dbbde3 |
| 0 | 0x82 | 487f799838a05a534aa50daa92487e17c2715cc1ada7ce48c3a9fa052d05740f |
| 0 | 0x83 | e2e9e2e61df3dc7a668dc0418f5e1fa4d56f77d2dd2a8a427780d8bc423e54f3 |
| 1 | 0x1 | 901d5f6eac2d838d4ca1f3cc5a4ea4e2c10394ac507a7a2bb891958412d03871 |
| 1 | 0x2 | 93deae66a64e67888a1a03a319923cd3f948f27a375ed00d926ac19365b3fa4d |
| 1 | 0x3 | 4641bb9be1f590a5cae964b188317cf168e158d24cfa27c7280941c684e42dc2 |
| 1 | 0x81 | 9df281682b102567a25fb8d3ca09f392efe5ee5499d8c12c0254974c05b070c5 |
| 1 | 0x82 | 93c4e51c4dc384c723940f0b64f4ef450dee23d12f9806516d83470ea2fa399c |
| 1 | 0x83 | d71ccf15b435685367f77257aef4ac96a959838c42d4164de2a795da0a9254bb |
The SIGHASH_ALL prefix hash equals the transaction hash, as stated in Section 6.10. In the SIGHASH_SINGLE vector for input 1, output 0 appears blanked (ff…ff, version 0000, script length 00) and input 0′s sequence is 0. Signing input 2 of a two-output transaction with SIGHASH_SINGLE has no defined hash (Rule 6.30); dcrd’s txscript/testdata/sighash.json contains such cases, together with real mainnet transactions and undefined hash types, and all of its entries are reproduced by Algorithm 6.6.
6.17.3 Signed Spends¶
Test vector: Signed pay-to-pubkey-hash spend (input 0 of the sample transaction)
| Item | Value |
|---|---|
| Private key | 0000000000000000000000000000000000000000000000000000000000000001 |
| Public key (compressed) | 0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798 |
| HASH160 of public key | e280cb6e66b96679aec288b1fbdbd4db08077a1b |
| Public key script | 76a914e280cb6e66b96679aec288b1fbdbd4db08077a1b88ac |
| Signature hash (ALL) | 5a5f06a3652928aae830f38a45325564e1973fb10073ef671df0be1e69466331 |
| Signature element | 3045022100a944fc7a28deab0b5c3f07b834995b2d2d5f42d708d0d7a04e3bec572c5779b202202d2730e2e9116305e8e731c7de302e11f43c2e9f1d87e19dd21d8c165175bab001 |
| Signature script | 483045022100a944fc7a28deab0b5c3f07b834995b2d2d5f42d708d0d7a04e3bec572c5779b202202d2730e2e9116305e8e731c7de302e11f43c2e9f1d87e19dd21d8c165175bab001210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798 |
| Result (consensus flags) | valid |
| Same, one bit of flipped (a bit that leaves the DER encoding valid) | invalid: ErrEvalFalse (OP_CHECKSIG pushes false) |
Same, hash type byte 04 | invalid: ErrInvalidSigHashType (encoding failure) |
Test vector: EC-Schnorr-DCRv0 via OP_CHECKSIGALT (type 2, same key)
| Item | Value |
|---|---|
| Public key script | 210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f8179852be |
| Signature hash (ALL) | 99b24bd56eb2ff75a229d24a2a0d11f3025380add7655abce1e64a2fe5ceebf4 |
| Signature script | 415326e2256467605135e786593379842f6087245aa4fcd1fa428849e20a8cb412d59effa4e8366ebe1cfbc7bac65a04e1aa9946e0ec4b10e154800e05edcdee5a01 |
| Result (consensus flags) | valid |
Test vector: Ed25519 via OP_CHECKSIGALT (type 1)
| Item | Value |
|---|---|
| Public key script | 204cb5abf6ad79fbf5abbccafcc269d85cd2651ed4b885b5869f241aedf0a5ba2951be |
| Signature hash (ALL) | d9fbdf699eafab052dad4c7c873444809717dd3643329adbe6e2c043c7b869c3 |
| Signature script | 410a299ecbc9e4800db91797d9090b21fdd76aba7fcab02c5dba370cc5ef4b79472705d52fe57bfe9ed7a034663cc0301c191006e2790f134a38b2bb77ef57fc0101 |
| Result (consensus flags) | valid |
Test vector: 2-of-3 multisignature, bare and through P2SH
| Item | Value |
|---|---|
| Private keys | 1, 3 and 6 (as 32-byte big-endian scalars); signatures by keys 1 and 6 |
| Public key script | 52210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f817982102f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f92103fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a146029755653ae |
| Signature script (no dummy element) | 483045022100f5600c0a319d9d71df82ccbee4d0dd08a6a1b9aa840b29700b86cecf4660ad1f022030475c9aa791e59d0ff7cb08df2112743fe28886127ea9d9ed12a9e3b21bb6a00147304402206194d7eecb75ef075cda4e46d50bf66caef91350b12ccc767dd13e2d7f7c2669022046f8c544e3c4a4cb031f8058be3bc2882fd2b9c556f9fad200df758b3ef165e201 |
| Result | valid |
| Signatures in reverse order | invalid: ErrEvalFalse |
With a leading OP_0 dummy | invalid under consensus flags: ErrCleanStack (valid without the clean-stack flag) |
| P2SH public key script | a914f86b5a7c6d32566aa4dccc04d1533530b4d64cf387 |
| P2SH signature script | 483045022100f5600c0a319d9d71df82ccbee4d0dd08a6a1b9aa840b29700b86cecf4660ad1f022030475c9aa791e59d0ff7cb08df2112743fe28886127ea9d9ed12a9e3b21bb6a00147304402206194d7eecb75ef075cda4e46d50bf66caef91350b12ccc767dd13e2d7f7c2669022046f8c544e3c4a4cb031f8058be3bc2882fd2b9c556f9fad200df758b3ef165e2014c6952210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f817982102f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f92103fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a146029755653ae |
| P2SH result | valid; imprecise signature operations 0 + 0, precise (P2SH) count 3 |
6.17.4 Lock-Time Opcodes¶
In Table 6.22 the public key script is the listed opcode sequence followed by OP_DROP OP_1, the signature script is empty, and the consensus flags of a block with all agendas active are used.
OP_CHECKLOCKTIMEVERIFY and OP_CHECKSEQUENCEVERIFY| Script | Tx ver. | Lock time | Sequence | Result |
|---|---|---|---|---|
100 CLTV | 1 | 100 | 0 | valid |
101 CLTV | 1 | 100 | 0 | ErrUnsatisfiedLockTime |
500000000 CLTV | 1 | 100 | 0 | ErrUnsatisfiedLockTime (kind mismatch) |
100 CLTV | 1 | 100 | ffffffff | ErrUnsatisfiedLockTime (input final) |
-1 CLTV | 1 | 100 | 0 | ErrNegativeLockTime |
4294967295 CLTV | 1 | 4294967295 | 0 | valid (5-byte operand) |
549755813887 CLTV | 1 | 4294967295 | 0 | ErrUnsatisfiedLockTime |
10 CSV | 2 | 0 | 0000000a | valid |
11 CSV | 2 | 0 | 0000000a | ErrUnsatisfiedLockTime |
10 CSV | 1 | 0 | 0000000a | ErrUnsatisfiedLockTime (version) |
2147483648 CSV | 1 | 0 | 0000000a | valid (disable bit in operand) |
10 CSV | 2 | 0 | 8000000a | ErrUnsatisfiedLockTime (disable bit in input) |
4194314 CSV | 2 | 0 | 0000000a | ErrUnsatisfiedLockTime (kind mismatch) |
4194314 CSV | 2 | 0 | 0040000a | valid |
4294967306 CSV | 2 | 0 | 0000000a | valid (bits above 31 ignored) |
-1 CSV | 2 | 0 | 0000000a | ErrNegativeLockTime |
6.17.5 Execution Behaviour¶
Table 6.23 gives representative cases. Scripts are written in the short form of dcrd’s test data: a decimal number is its minimal push, 's' pushes the ASCII bytes of s, 0x… inserts raw bytes, <…>{k} repeats the enclosed tokens times, 'b'{k} pushes a single element of copies, and names are opcodes without the OP_ prefix. An entry number refers to the zero-based position in txscript/testdata/script_tests.json; the other rows were run directly. Unless noted, no flags are set and the script version is 0.
| Entry | Signature script | Public key script | Result |
|---|---|---|---|
| 541 | 0 | IF 'b'{2049} ENDIF 1 | ErrElementTooBig (unexecuted push) |
| 542 | 0 | IF <NOP>{256} ENDIF 1 | ErrTooManyOperations (unexecuted ops count) |
| 2239 | 0 | IF 0x50{255} ENDIF 1 | valid (0x50 is not counted) |
| 589 | 0 | IF ELSE 1 ELSE VERIF ENDIF | ErrReservedOpcode |
| 1838 | 0 | IF CODESEPARATOR ENDIF 1 | ErrDisabledOpcode |
| — | 1 | 0 IF VER ENDIF | valid (OP_VER unexecuted) |
| 547 | 0 IF 0x4c 0x00 ENDIF 1 | (empty) | valid (unexecuted non-minimal push) |
| 389 | 0x4c 0x00 | DROP 1 | ErrMinimalData |
| 413 | 0x01 0x00 | 1 | valid |
| 433 | 0x01 0x00 | NOT DROP 1 | ErrMinimalData (numeric use) |
| 524 | 1 0x01 0x80 | IF 0 ENDIF | valid (negative zero is false) |
| 606 | 1 0x05 0x0100000000 | VERIFY | valid (long boolean) |
| 508 | 0 | IF 0 ELSE 1 ELSE 0 ENDIF | valid (two ELSEs) |
| 543 | 1 IF | 1 ENDIF | ErrUnbalancedConditional |
| 1379 | 2147483647 DUP ADD | 4294967294 EQUAL | valid (5-byte result) |
| 1319 | 2147483647 | 1ADD 1SUB 1 | ErrNumOutOfRange |
| 1331 | 2 2MUL | 4 EQUAL | ErrEvalFalse (OP_2MUL is a no-op) |
| 1439 | -7 3 | MOD -1 EQUAL | valid |
| 1484 | 1 31 | LSHIFT -2147483648 EQUAL | valid |
| 1485 | 1 32 | LSHIFT 0 EQUAL | valid |
| — | (empty) | -1 32 RSHIFT -1 EQUAL | valid |
| 1493 | 1 33 | LSHIFT 0 EQUAL | ErrOverflowShift |
| — | (empty) | 65536 65536 MUL 0 EQUAL | valid (wrapping) |
| 920 | 'abcd' 3 1 | SUBSTR 'bc' EQUAL | valid |
| 925 | '' 2147483647 2147483646 | SUBSTR '' EQUAL | valid |
| 2040 | (empty) | 0 0 CHECKMULTISIGVERIFY DEPTH 0 EQUAL | valid |
| 2037 | 1 | <0 0 CHECKMULTISIGVERIFY>{255} | valid (255 operations) |
| 2038 | 1 | <0 0 CHECKMULTISIGVERIFY>{256} | ErrTooManyOperations |
| 2039 | 1 | <NOP>{3} <0 'a' … 't' 20 CHECKMULTISIGVERIFY>{12} | valid () |
| 1921 | 0 | 0x21 <key 3> CHECKSIG | ErrEvalFalse (empty signature) |
| — | (empty) | 3 CHECKSIGALT | valid (unassigned type) |
| — | (empty) | 128 CHECKSIGALT | ErrNumOutOfRange |
| — | 'x' 'y' | 1 CHECKSIGALT NOT, clean stack | ErrCleanStack ('x' left behind) |
| 2246 | 1 3 DATA_2 ADD SSTX | HASH160 DATA_20 0xdcbd…ff8f EQUAL | ErrP2SHStakeOpCodes |
| 2263 | 1 3 DATA_2 ADD TADD | HASH160 DATA_20 0xdd89…fb05 EQUAL, TREASURY | ErrP2SHStakeOpCodes |
| 2267 | as 2263 | as 2263, no flags | valid (0xc1 is OP_UNKNOWN193) |
| 2088 | NOP1 | NOP10 | ErrEmptyStack |
| — | (empty) | RETURN, version 1 | valid (not executed) |
| — | (empty) | (empty), version 1 | ErrEvalFalse (construction) |
| — | NOP | HASH160 0x14 <20 zero bytes> EQUAL, version 1 | ErrNotPushOnly |
| — | (empty) | 0x4c, version 1 | ErrMalformedPush |
For the P2SH output whose redeem script is the single byte 51 (public key script a914f5a8302ee8695bf836258b8f2b57b38a0be14e4787): the signature script 01 51 is valid; 51, 00, the empty script and 61 01 51 fail construction with ErrNotPushOnly; and 01 51 01 51 is valid without the clean-stack flag but fails with it (ErrCleanStack).
6.17.6 Signature Operation Counts¶
| Script | Imprecise | Precise |
|---|---|---|
DUP HASH160 <20> EQUALVERIFY CHECKSIG | 1 | 1 |
2 <K33> <K33> <K33> 3 CHECKMULTISIG | 20 | 3 |
0 CHECKMULTISIG | 20 | 20 |
17 CHECKMULTISIG (17 is pushed as 01 11) | 20 | 20 |
16 CHECKMULTISIGVERIFY | 20 | 16 |
CHECKSIG CHECKSIGVERIFY CHECKSIGALT CHECKSIGALTVERIFY | 4 | 4 |
TSPEND | 1 (0 without treasury rules) | 1 |
CHECKSIG 0x4c (parse failure after the first opcode) | 1 | 1 |
CHECKSIG 0x01 0xac (0xac is push data) | 1 | 1 |
0 IF CHECKSIG ENDIF | 1 | 1 |
6.17.7 Provably Unspendable Outputs¶
| Amount | Script | Unspendable |
|---|---|---|
| 0 | 51 | yes |
| 1 | 6a | yes |
| 1 | 51 6a | no |
| 1 | 4c (parse failure) | yes |
| 1 | 51 | no |
| 1 | (empty) | no |
6.18 Error Kinds¶
Table 6.26 maps every script error kind that can arise in consensus validation to the rule that produces it. The kinds ErrInvalidIndex, ErrUnsupportedScriptVersion, ErrScriptUnfinished and ErrInvalidProgramCounter indicate misuse of the reference implementation’s interface and cannot arise from transaction data; ErrP2SHTreasuryOpCodes is defined but never produced (treasury tags in redeem scripts produce ErrP2SHStakeOpCodes); ErrDiscourageUpgradableNOPs and ErrNotPushOnly from the push-only flag arise only under policy flags.
| Error kind | Rule |
|---|---|
ErrMalformedPush | Rule 6.2, Rule 6.3, Rule 6.31 |
ErrScriptTooBig | Rule 6.3 |
ErrNotPushOnly | Rule 6.3 |
ErrP2SHStakeOpCodes | Rule 6.3, Rule 6.32 |
ErrEvalFalse, ErrEmptyStack, ErrCleanStack | Rule 6.9, Rule 6.31, Rule 6.3 |
ErrUnbalancedConditional | Rule 6.4, Rule 6.8 |
ErrStackOverflow | Rule 6.5 |
ErrDisabledOpcode, ErrTooManyOperations, ErrElementTooBig | Rule 6.6, Rule 6.28, Rule 6.13 |
ErrReservedOpcode | Rule 6.6, Rule 6.22 |
ErrMinimalData | Rule 6.7, Rule 6.11 |
ErrNumOutOfRange | Rule 6.11 |
ErrInvalidStackOperation | Section 6.8 (all opcodes), Rule 6.12 |
ErrVerify, ErrEqualVerify, ErrNumEqualVerify | Section 6.8.2 |
ErrCheckSigVerify, ErrCheckMultiSigVerify, ErrCheckSigAltVerify | Section 6.9 |
ErrEarlyReturn | Table 6.5 |
ErrNegativeSubstrIdx, ErrOverflowSubstrIdx | Rule 6.14, Rule 6.15 |
ErrNegativeRotation, ErrOverflowRotation | Rule 6.16 |
ErrNegativeShift, ErrOverflowShift | Rule 6.17 |
ErrDivideByZero | Table 6.8 |
ErrNegativeLockTime, ErrUnsatisfiedLockTime | Rule 6.19, Rule 6.20 |
ErrInvalidSigHashType | Rule 6.23 |
ErrSigTooShort … ErrSigHighS (16 kinds) | Rule 6.24 |
ErrPubKeyType | Rule 6.25 |
ErrInvalidPubKeyCount, ErrInvalidSignatureCount | Rule 6.28 |
ErrInvalidSigHashSingleIndex | Rule 6.30 (fails only via OP_CHECKMULTISIG) |