Skip to content

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 the explicitverupgrades 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.

Table 6.1. Parsing classes of opcode bytes
Byte(s)Opcode(s)Encoding
0x00OP_0The single byte. Pushes the empty byte string.
0x01–0x4bOP_DATA_1 … OP_DATA_75The byte 𝑛 followed by exactly 𝑛 data bytes.
0x4cOP_PUSHDATA1The byte, a 1-byte length 𝑛, then 𝑛 data bytes.
0x4dOP_PUSHDATA2The byte, a 2-byte little-endian length 𝑛, then 𝑛 data bytes.
0x4eOP_PUSHDATA4The byte, a 4-byte little-endian length 𝑛, then 𝑛 data bytes.
0x4f–0xffall othersThe 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:

  1. If 𝑏 is 0x00 or 𝑏≥ 0x4f, the opcode is 𝑏 with no data and the next offset is 𝑘+1.
  2. If 0x01 ≤ 𝑏 ≤ 0x4b, the script MUST contain at least 1+𝑏 bytes from offset 𝑘; the data is the 𝑏 bytes after 𝑏 and the next offset is 𝑘+1+𝑏.
  3. If 𝑏 is 0x4c, 0x4d or 0x4e, 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 𝑘+1+𝑤+𝑛.

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 the OP_PUSHDATA4 length into a signed 32-bit integer and rejects negative values; since any length of 231 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 ops

dcrd: 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.

Table 6.2. Script engine limits
ConstantValueMeaning and exact comparison
MaxScriptSize16384A signature script or public key script longer than this many bytes fails (len > 16384). Redeem scripts are bounded by the element size instead.
MaxScriptElementSize2048A 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.
MaxOpsPerScript255Per 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).
MaxStackSize1024After each opcode, the combined number of elements on the data stack and alternate stack must not exceed 1024 (fails when > 1024).
MaxPubKeysPerMultiSig20The key count of OP_CHECKMULTISIG(VERIFY) must be in [0,20].
MathOpCodeMaxScriptNumLen4Maximum encoded length of most numeric operands (Section 6.7.2).
CltvMaxScriptNumLen5Maximum encoded length of the OP_CHECKLOCKTIMEVERIFY operand.
CsvMaxScriptNumLen5Maximum encoded length of the OP_CHECKSEQUENCEVERIFY operand.
—1Maximum encoded length of the OP_CHECKSIGALT(VERIFY) signature type operand.
LockTimeThreshold500000000Lock-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:

  1. 𝑆 and 𝑃 are not both empty (ErrEvalFalse).
  2. If the flag ScriptVerifySigPushOnly is set, 𝑆 is push-only (ErrNotPushOnly).
  3. If 𝑃 is P2SH-shaped, 𝑆 is push-only (ErrNotPushOnly). This check is independent of 𝑣.
  4. If 𝑣=0 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 are 0xba–0xbd, plus 0xc1–0xc3 when ScriptVerifyTreasury is set (ErrP2SHStakeOpCodes); this scan stops at the first parse failure of 𝑅, and a parse failure reached before any stake tag opcode also fails (ErrMalformedPush).
  5. |𝑆|≤16384 and |𝑃|≤16384 (ErrScriptTooBig).
  6. 𝑆 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 opcodes OP_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:

  1. the signature script 𝑆, starting from an empty data stack;
  2. the public key script 𝑃, starting from the data stack 𝑆 left behind;
  3. 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).
Figure 6.1. Order of script execution. The data stack is carried from one script to the next; the alternate stack, the operation count and the conditional state belong to a single script.

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:

  1. the conditional nesting depth (Section 6.6.3) MUST be 0 (ErrUnbalancedConditional): an OP_IF or OP_NOTIF block cannot span two scripts;
  2. 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:

  1. If 𝑜 is OP_CODESEPARATOR (0xab), the script MUST fail (ErrDisabledOpcode), whether or not the branch is executing.
  2. If 𝑜 is OP_VERIF (0x65) or OP_VERNOTIF (0x66), the script MUST fail (ErrReservedOpcode), whether or not the branch is executing.
  3. 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 |𝑑|>2048 the script MUST fail (ErrElementTooBig). Both checks apply whether or not the branch is executing.
  4. 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.
  5. If the branch is executing and 𝑜≤ 0x4e, the push MUST be minimal (Rule 6.7).
  6. 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 above 0x60 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):

  1. if |𝑑|=0: 𝑜 is OP_0;
  2. if |𝑑|=1 and 1≤𝑑[0]≤16: 𝑜 is OP_1 + 𝑑[0]−1 (that is, a small-integer opcode, which is not a data push and so never reaches this check);
  3. if |𝑑|=1 and 𝑑[0]= 0x81: 𝑜 is OP_1NEGATE (likewise impossible to satisfy with a data push);
  4. if |𝑑|≤75: 𝑜=|𝑑| (an OP_DATA_n opcode);
  5. if |𝑑|≤255: 𝑜 is OP_PUSHDATA1;
  6. if |𝑑|≤65535: 𝑜 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 𝐷=0, 𝑋=none. 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 with ErrInvalidStackOperation) and interpret it as a boolean (Rule 6.10); if it is false, set 𝑋≔𝐷. In all cases then set 𝐷≔𝐷+1.
  • OP_NOTIF: as OP_IF, except that 𝑋≔𝐷 is set when the popped value is true.
  • OP_ELSE: if 𝐷=0 the script MUST fail (ErrUnbalancedConditional). Otherwise let 𝑑=𝐷−1. If 𝑋 is none, set 𝑋≔𝑑; else if 𝑋=𝑑, set 𝑋≔none; otherwise do nothing.
  • OP_ENDIF: if 𝐷=0 the script MUST fail (ErrUnbalancedConditional). Otherwise set 𝐷≔𝐷−1, and then if 𝑋=𝐷 set 𝑋≔none.

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:

  1. if the flag ScriptVerifyCleanStack is set, the data stack MUST contain exactly one element (ErrCleanStack);
  2. otherwise the data stack MUST contain at least one element (ErrEmptyStack);
  3. 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.

Table 6.3. Execution of a pay-to-pubkey-hash spend
ScriptOpcodeData stack afterwards (bottom … top)
SOP_DATA_72sig
SOP_DATA_33sig pk
POP_DUPsig pk pk
POP_HASH160sig pk H(pk) where H = RIPEMD-160(BLAKE-256(·))
POP_DATA_20sig pk H(pk) h
POP_EQUALVERIFYsig pk (fails unless H(pk) = h)
POP_CHECKSIG1 if the signature verifies, else the empty string
—final checkexactly 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 mag

dcrd: 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 under decode_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 [−(231−1),231−1]; 5 bytes admits [−(239−1),239−1]; 1 byte admits [−127,127]. Note that −231 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 232−2, 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 231−1 become 231−1, values below −231 become −231) 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 [−(231−1),231−1] 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], x2 is 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

Table 6.4. Push opcodes
Byte(s)OpcodeOperation
0x00OP_0, OP_FALSEPush the empty string.
0x01–0x4bOP_DATA_nPush the 𝑛 inline data bytes.
0x4c–0x4eOP_PUSHDATA1/2/4Push the inline data bytes.
0x4fOP_1NEGATEPush the number −1 (81).
0x51–0x60OP_1/OP_TRUE … OP_16Push the number 𝑏− 0x50 (01 … 10).

6.8.2 Flow Control

Table 6.5. Flow-control opcodes
ByteOpcodeOperation when executed
0x61OP_NOPNone.
0x62OP_VERFail (ErrReservedOpcode). Ignored in an unexecuted branch.
0x63OP_IFRule 6.8.
0x64OP_NOTIFRule 6.8.
0x65OP_VERIFFail whenever reached, even in an unexecuted branch (Rule 6.6).
0x66OP_VERNOTIFFail whenever reached, even in an unexecuted branch.
0x67OP_ELSERule 6.8.
0x68OP_ENDIFRule 6.8.
0x69OP_VERIFYPop 𝑥; if 𝑥 is false, fail (ErrVerify).
0x6aOP_RETURNFail (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.

Table 6.6. Stack-manipulation opcodes
ByteOpcodeData stack effectNotes
0x6bOP_TOALTSTACK[x] → []x is pushed onto the alternate stack.
0x6cOP_FROMALTSTACK[] → [x]x is popped from the alternate stack; fails if it is empty.
0x6dOP_2DROP[x1 x2] → []
0x6eOP_2DUP[x1 x2] → [x1 x2 x1 x2]
0x6fOP_3DUP[x1 x2 x3] → [x1 x2 x3 x1 x2 x3]
0x70OP_2OVER[x1 x2 x3 x4] → [x1 x2 x3 x4 x1 x2]
0x71OP_2ROT[x1 … x6] → [x3 x4 x5 x6 x1 x2]Requires 6 elements.
0x72OP_2SWAP[x1 x2 x3 x4] → [x3 x4 x1 x2]
0x73OP_IFDUP[x] → [x x] or [x]Duplicates x only if x is true as a boolean.
0x74OP_DEPTH[] → [n]n is the number of data stack elements before the push.
0x75OP_DROP[x] → []
0x76OP_DUP[x] → [x x]
0x77OP_NIP[x1 x2] → [x2]
0x78OP_OVER[x1 x2] → [x1 x2 x1]
0x79OP_PICK[xn … x0 n] → [xn … x0 xn]See below.
0x7aOP_ROLL[xn … x0 n] → [… x0 xn]See below.
0x7bOP_ROT[x1 x2 x3] → [x2 x3 x1]
0x7cOP_SWAP[x1 x2] → [x2 x1]
0x7dOP_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 0≤𝑛<𝑘 (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 𝑛=0 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 |𝑥1|+|𝑥2| 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 |𝑠|=0, push the empty string regardless of 𝑏 and 𝑒. Otherwise, in this order, MUST hold: 𝑏≥0 and 𝑒≥0 (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 |𝑠|=0, push the empty string regardless of 𝑛. Otherwise MUST hold: 𝑛≥0 (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 of OP_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.

Table 6.7. Bitwise and byte-comparison opcodes
ByteOpcodeOperation ([... x1 x2], x2 on top)
0x83OP_INVERT[x] → [~x]: bitwise complement as int32, equal to −𝑥−1. OP_INVERT of 231−1 yields −231, pushed as 5 bytes.
0x84OP_ANDint32(x1) & int32(x2).
0x85OP_ORint32(x1) | int32(x2).
0x86OP_XORint32(x1) ^ int32(x2).
0x87OP_EQUALPop 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.
0x88OP_EQUALVERIFYOP_EQUAL then verify (ErrEqualVerify).
0x89OP_ROTRRule 6.16.
0x8aOP_ROTLRule 6.16.

Rule 6.16 · OP_ROTR and OP_ROTL

[... v c]. Pop the numeric count 𝑐, then the numeric value 𝑣 (both 4-byte maximum). 𝑐≥0 MUST hold (ErrNegativeRotation) and 𝑐≤31 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 −231 its encoding is 5 bytes and it cannot be used as an operand again. For example 1 1 OP_ROTR pushes −231 (00 00 00 80 80), and feeding that to a second OP_ROTR fails with ErrNumOutOfRange, whereas 1 2 OP_ROTR pushes 230, 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 [−(232−2),232−2] and may encode to 5 bytes). Booleans produced by numeric opcodes are the numbers 1 and 0, that is, 01 and the empty string.

Table 6.8. Arithmetic opcodes
ByteOpcodeResult
0x8bOP_1ADD𝑎+1, exact.
0x8cOP_1SUB𝑎−1, exact.
0x8dOP_2MULNo operation (behaves as OP_NOP; nothing is popped or checked).
0x8eOP_2DIVNo operation (behaves as OP_NOP).
0x8fOP_NEGATE−𝑎.
0x90OP_ABS|𝑎|.
0x91OP_NOT1 if 𝑎=0, else 0.
0x92OP_0NOTEQUAL0 if 𝑎=0, else 1.
0x93OP_ADD𝑎+𝑏, exact.
0x94OP_SUB𝑎−𝑏, exact.
0x95OP_MULint32(a * b): the product reduced modulo 232 and reinterpreted as signed (wrapping).
0x96OP_DIVtdiv(a, b) (truncating toward zero). 𝑏=0 fails (ErrDivideByZero).
0x97OP_MODtmod(a, b) (remainder of truncating division, sign of 𝑎). 𝑏=0 fails (ErrDivideByZero).
0x98OP_LSHIFTRule 6.17.
0x99OP_RSHIFTRule 6.17.
0x9aOP_BOOLAND1 if 𝑎≠0 and 𝑏≠0, else 0.
0x9bOP_BOOLOR1 if 𝑎≠0 or 𝑏≠0, else 0.
0x9cOP_NUMEQUAL1 if 𝑎=𝑏, else 0.
0x9dOP_NUMEQUALVERIFYOP_NUMEQUAL then verify (ErrNumEqualVerify).
0x9eOP_NUMNOTEQUAL1 if 𝑎≠𝑏, else 0.
0x9fOP_LESSTHAN1 if 𝑎<𝑏, else 0.
0xa0OP_GREATERTHAN1 if 𝑎>𝑏, else 0.
0xa1OP_LESSTHANOREQUAL1 if 𝑎≤𝑏, else 0.
0xa2OP_GREATERTHANOREQUAL1 if 𝑎≥𝑏, else 0.
0xa3OP_MINmin(𝑎,𝑏).
0xa4OP_MAXmax(𝑎,𝑏).
0xa5OP_WITHIN[... x lo hi]: pop hi, lo, x; 1 if lo≤𝑥<hi, else 0.

Rule 6.17 · OP_LSHIFT and OP_RSHIFT

[... v c]. Pop the numeric count 𝑐, then the numeric value 𝑣 (both 4-byte maximum). 𝑐≥0 MUST hold (ErrNegativeShift) and 𝑐≤32 MUST hold (ErrOverflowShift). With 𝑣 as a 32-bit two’s complement integer:

  • OP_LSHIFT pushes int32(v << c), discarding bits shifted out of the 32-bit width; for 𝑐=32 the result is 0;
  • OP_RSHIFT pushes the arithmetic (sign-replicating) shift v >> c; for 𝑐=32 the result is 0 if 𝑣≥0 and −1 if 𝑣<0.

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 that x << 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 in OP_DIV or OP_MOD: the only overflowing case of 32-bit truncating division, −231÷−1, needs the operand −231, 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.

Table 6.9. Hash opcodes
ByteOpcodeDigestFunction
0xa6OP_RIPEMD16020RIPEMD-160(x).
0xa7OP_SHA120SHA-1(x).
0xa8OP_BLAKE25632BLAKE-256(x) (14 rounds, as used throughout Decred).
0xa9OP_HASH16020RIPEMD-160(BLAKE-256(x)). Not SHA-256 as in Bitcoin.
0xaaOP_HASH25632BLAKE-256(BLAKE-256(x)). Not double SHA-256.
0xc0OP_SHA25632SHA-256(x), only when ScriptVerifySHA256 is set (Rule 6.18).

Rule 6.18 · OP_SHA256

If the flag ScriptVerifySHA256 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 232−1 (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:

  1. 𝐿≥0 (ErrNegativeLockTime);
  2. 𝐿 and 𝑇 are of the same kind: both <500000000 (block heights) or both ≥500000000 (Unix times) (ErrUnsatisfiedLockTime);
  3. 𝐿≤𝑇 (ErrUnsatisfiedLockTime);
  4. 𝑞≠ 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:

  1. 𝑠≥0 MUST hold (ErrNegativeLockTime);
  2. if bit 31 of 𝑠 is set (𝑠 AND 0x80000000 ≠0), the opcode succeeds with no further checks;
  3. 𝑉≥2 MUST hold (ErrUnsatisfiedLockTime);
  4. bit 31 of 𝑞 MUST be clear (ErrUnsatisfiedLockTime);
  5. let 𝑚 = 0x0040ffff (the type flag, bit 22, together with the low 16 bits), 𝑠′=𝑠 AND 𝑚 and 𝑞′=𝑞 AND 𝑚. 𝑠′ and 𝑞′ MUST be of the same kind: both < 0x00400000 or both ≥ 0x00400000 (ErrUnsatisfiedLockTime);
  6. 𝑠′≤𝑞′ 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 script 05 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.

History

OP_CHECKLOCKTIMEVERIFY is enforced on every block since the genesis block (the flag is unconditionally part of the consensus flags). OP_CHECKSEQUENCEVERIFY was introduced by DCP-0003 [30] and is enforced once the lnfeatures agenda is active; before that byte 0xb2 is a no-operation.

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 opcodes 0xba–0xbd have no effect under any flags;
  • the upgradable no-operations OP_NOP1 (0xb0), OP_NOP4–OP_NOP10 (0xb3–0xb9) and OP_UNKNOWN196–OP_UNKNOWN248 (0xc4–0xf8), and the flag-gated opcodes 0xb1, 0xb2, 0xc0, 0xc1, 0xc2, 0xc3 when their enabling flag is not set, have no effect unless the flag ScriptDiscourageUpgradableNops is 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

Executing OP_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 𝑡 AND 0x7f 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 𝐿=|𝑔|.

  1. 𝐿≥8 (ErrSigTooShort) and 𝐿≤72 (ErrSigTooLong).
  2. 𝑔[0]= 0x30 (ErrSigInvalidSeqID).
  3. 𝑔[1]=𝐿−2 (ErrSigInvalidDataLen).
  4. Let 𝑟len=𝑔[3] and 𝑠type=4+𝑟len. 𝑠type<𝐿 (ErrSigMissingSTypeID) and 𝑠type+1<𝐿 (ErrSigMissingSLen).
  5. Let 𝑠len=𝑔[𝑠type+1]. 𝑠type+2+𝑠len=𝐿 (ErrSigInvalidSLen).
  6. 𝑔[2]= 0x02 (ErrSigInvalidRIntID); 𝑟len≠0 (ErrSigZeroRLen); 𝑔[4] AND 0x80 =0 (ErrSigNegativeR); not (𝑟len>1 and 𝑔[4]= 0x00 and 𝑔[5] AND 0x80 =0) (ErrSigTooMuchRPadding).
  7. 𝑔[𝑠type]= 0x02 (ErrSigInvalidSIntID); 𝑠len≠0 (ErrSigZeroSLen); the first byte of 𝑆 has its top bit clear (ErrSigNegativeS); not (𝑠len>1 and 𝑆’s first byte is 0x00 and its second byte has the top bit clear) (ErrSigTooMuchSPadding).
  8. With leading zero bytes removed, 𝑆 is at most 32 bytes, and as a big-endian integer 𝑆<𝑛 and 𝑆≤𝑛2 (rounded down), where 𝑛 is the order of the secp256k1 group (ErrSigHighS).

The bytes of 𝑅 are 𝑔[4:4+𝑟len] and those of 𝑆 are 𝑔[𝑠type+2:𝐿].

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 for OP_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 out

dcrd: 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:

  1. Pop 𝑝 (the public key), then 𝑒 (the signature element).
  2. If |𝑒|=0, push false and stop. (The public key is not checked.)
  3. 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.
  4. 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_SINGLE case of Rule 6.30), push false and stop.
  5. Parse 𝑝 as a secp256k1 point and 𝑔 as a DER signature (Chapter 3); if either fails, push false and stop.
  6. 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:

  1. Pop the numeric operand 𝑛 (4-byte maximum). 0≤𝑛≤20 MUST hold (ErrInvalidPubKeyCount).
  2. Add 𝑛 to the per-script operation count; the count MUST NOT exceed 255 (ErrTooManyOperations).
  3. Pop 𝑛 public keys. Call them 𝐾0,…,𝐾𝑛−1 in popping order (𝐾0 was on top, so 𝐾0= pk_n).
  4. Pop the numeric operand 𝑚 (4-byte maximum). 0≤𝑚≤𝑛 MUST hold (ErrInvalidSignatureCount).
  5. Pop 𝑚 signature elements 𝐸0,…,𝐸𝑚−1 in popping order (𝐸0= sig_m).
  6. Compute the subscript by applying Rule 6.26 for 𝐸0, then 𝐸1, and so on.
  7. 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 True

dcrd: 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 𝑚≥1 empty elements, the result is false after the keys are exhausted.
  • With 𝑚=0 the result is true and no key is examined; 0 0 OP_CHECKMULTISIG pushes true.
  • Unlike OP_CHECKSIG, an out-of-range SIGHASH_SINGLE makes 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.

Table 6.10. Signature types for OP_CHECKSIGALT
TypeSuitePublic keyElementBehaviour
0(ECDSA, not allowed here)——Pushes false; nothing else popped.
1Ed2551932 bytes65 bytesVerified as below.
2EC-Schnorr-DCRv0 (secp256k1)33 bytes65 bytesVerified as below.
otherunassigned——Pushes true; nothing else popped.

Rule 6.29 · OP_CHECKSIGALT

[... sig pk type] → [... bool]. In this order:

  1. Pop the numeric operand 𝑦 with maximum length 1 (so −127≤𝑦≤127; a longer element fails with ErrNumOutOfRange).
  2. If 𝑦=0, 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.
  3. Pop 𝑝. If |𝑝|≠32 (for 𝑦=1) or |𝑝|≠33 (for 𝑦=2), push false and stop; the signature element is not popped.
  4. Pop 𝑒. If |𝑒|≠65, push false and stop.
  5. Let 𝑡=𝑒[64] and 𝑔=𝑒[0:64]. 𝑡 MUST pass Rule 6.23 (encoding failure). No DER or public key format check applies.
  6. 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.
  7. For 𝑦=1: parse 𝑝 as an Ed25519 public key and 𝑔 as an Ed25519 signature; for 𝑦=2: parse 𝑝 as a compressed secp256k1 public key (first byte 0x02 or 0x03) and 𝑔 as an EC-Schnorr-DCRv0 signature (𝑟,𝑠) with 𝑟<𝑝field 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 of OP_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.

Table 6.11. Failure modes of the signature opcodes
ConditionCHECKSIGCHECKMULTISIGCHECKSIGALT
Too few stack elementsfailfailfaila
Empty signature elementfalseskip keyfalse (wrong length)
Invalid hash typefailfail (if reached)fail
DER encoding violationfailfail (if reached)n/a
Public key format violationfailfail (if reached)false (length only)
Key not a valid point / signature unparseablefalseskipfalse
SIGHASH_SINGLE index out of rangefalsefailfalse
Signature does not verifyfalseskip keyfalse

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.

Table 6.12. Signature hash types
ValueNameCommits to
0x01SIGHASH_ALLAll inputs and all outputs.
0x02SIGHASH_NONEAll inputs (other inputs’ sequence numbers replaced by 0) and no outputs.
0x03SIGHASH_SINGLEAll 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.
0x80SIGHASH_ANYONECANPAYFlag 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 =1 and SigHashSerializeWitness =3.

Rule 6.30 · SIGHASH_SINGLE with no matching output

If the hash type AND 0x1f 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.version is 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. varint is the variable-length integer of Chapter 4. prev_hash is the 32-byte previous transaction hash in its internal (non-reversed) byte order, and prev_tree is 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_ALL without SIGHASH_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_SINGLE case, every output before the signed index is committed with amount −1 (eight 0xff bytes), its original script version, and an empty script; outputs after the index are omitted. With SIGHASH_ANYONECANPAY, the comparison j != idx still uses the original input index, since output positions are not renumbered.
  • Within the engine the hash type has already passed Rule 6.23, so base is 1, 2 or 3. The mask 0x1f and the treatment of other values as SIGHASH_ALL matter only to external callers of the function (dcrd’s test vectors exercise them).
  • OP_CODESEPARATOR has no role: it cannot appear in a script that executes. The subscript sub is 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.

Table 6.13. Pay-to-script-hash patterns
FormLengthBytes
P2SH23a9 14 ‖ 20-byte hash ‖ 87
Stake-tagged P2SH24tag ‖ 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:

  1. the signature script MUST be push-only, and for version 0 the redeem-script conditions of Rule 6.3 step 4 MUST hold;
  2. 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);
  3. 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;
  4. 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;
  5. 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 opcodes 0xba–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 the treasury 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.

  1. 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).
  2. Redeem scripts must not contain tags (Rule 6.32).
  3. The treasury tags 0xc1–0xc3 are tags only when ScriptVerifyTreasury is 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.

Table 6.14. Where tag placement is enforced (informative)
TagRequired formsSpecified in
OP_SSTXTicket output 0: tag followed by a P2PKH or P2SH script (26 or 24 bytes).Chapter 8
OP_SSTXCHANGETicket change outputs, and the optional change output (output 1) of a treasury add: tag followed by P2PKH or P2SH.Chapter 8, Chapter 12
OP_SSGENVote payment outputs: tag followed by P2PKH or P2SH.Chapter 8
OP_SSRTXRevocation outputs: tag followed by P2PKH or P2SH.Chapter 8
OP_TADDTreasury add and treasurybase output 0: the single byte c1.Chapter 12
OP_TGENTreasury spend payouts: tag followed by P2PKH or P2SH.Chapter 12
OP_TSPENDTreasury spend signature script: OP_DATA_64 <sig> OP_DATA_33 <key> OP_TSPEND (100 bytes).Chapter 12
anyOutputs 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 in 0xba–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).

Table 6.15. Script verification flags
BitFlagEffect when set
0x01ScriptDiscourageUpgradableNopsExecuting an upgradable no-operation fails (Rule 6.21). Policy only.
0x02ScriptVerifyCheckLockTimeVerifyByte 0xb1 is OP_CHECKLOCKTIMEVERIFY (Rule 6.19); otherwise it is the no-operation OP_NOP2.
0x04ScriptVerifyCheckSequenceVerifyByte 0xb2 is OP_CHECKSEQUENCEVERIFY (Rule 6.20); otherwise it is OP_NOP3.
0x08ScriptVerifyCleanStackThe data stack must hold exactly one element at the end (Rule 6.9).
0x10ScriptVerifySigPushOnlyEvery signature script must be push-only (Rule 6.3 step 2). Set by neither consensus nor dcrd’s policy.
0x20ScriptVerifySHA256Byte 0xc0 is OP_SHA256 (Rule 6.18); otherwise it is OP_UNKNOWN192.
0x40ScriptVerifyTreasuryBytes 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 n

dcrd: 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 (tr), is 𝐴+𝐵, where:

𝐴 (the imprecise part):

  • if tr and the transaction is a treasurybase, 𝐴=0;
  • otherwise 𝐴 is the sum of GetSigOpCount over the signature scripts of all inputs (no inputs for a coinbase; all inputs except the first for a vote) plus the sum of GetSigOpCount over the public key scripts of all outputs.

𝐵 (the P2SH part):

  • if the transaction is a coinbase, or if tr and it is a treasury spend or treasurybase, 𝐵=0;
  • 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, add precise_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. And OP_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:

  • 𝑎=0;
  • |𝑃|>16384;
  • |𝑃|>0 and 𝑃[0]= 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 script 51 (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 𝑣=0, |𝑃|≥1, 𝑃[0]= 0x6a, and either |𝑃|=1 and ℓ=0, or the remainder 𝑃[1:] 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 ℓ=1, 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.

Table 6.16. Standard version 0 script templates (policy)
ClassBytesTemplate
pubkey35 / 6721 ‖ K33 ‖ ac or 41 ‖ K65 ‖ ac
pubkey-ed255193520 ‖ E32 ‖ 51 ‖ be
pubkey-schnorr-secp256k13621 ‖ K33 ‖ 52 ‖ be
pubkeyhash2576 a9 14 ‖ H ‖ 88 ac
pubkeyhash-ed255192676 a9 14 ‖ H ‖ 88 51 be
pubkeyhash-schnorr-secp256k12676 a9 14 ‖ H ‖ 88 52 be
scripthash23a9 14 ‖ H ‖ 87
multisigvar.OP_m ‖ (𝑛 pushes of K33) ‖ OP_n ‖ ae, 1≤𝑚≤𝑛≤16
nulldata1–2606a, or 6a ‖ one canonical push of at most 256 bytes
stakesubmission-pubkeyhash26ba ‖ pubkeyhash
stakesubmission-scripthash24ba ‖ scripthash
stakegen-pubkeyhash26bb ‖ pubkeyhash
stakegen-scripthash24bb ‖ scripthash
stakerevoke-pubkeyhash26bc ‖ pubkeyhash
stakerevoke-scripthash24bc ‖ scripthash
stakechange-pubkeyhash26bd ‖ pubkeyhash
stakechange-scripthash24bd ‖ scripthash
treasuryadd1c1
treasurygen-pubkeyhash26c3 ‖ pubkeyhash
treasurygen-scripthash24c3 ‖ 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 and 52 (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 be 02 or 03; the Ed25519 form imposes no condition on the 32 key bytes.
  • Multisig. The first opcode is OP_1–OP_16 giving 𝑚 (OP_0 is rejected). It is followed by one or more opcodes whose data is a strict compressed key (any push opcode qualifies, not only OP_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 then ae (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 most 0x60 that is canonical under is_canonical_for_removal of 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 CHECKSIG

6.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

Table 6.17. Script number encodings
ValueEncodingValueEncoding
0(empty)−25600 81
10132767ff 7f
−181−3276800 80 80
16108388607ff ff 7f
1277f−838860800 00 80 80
−127ff2147483647ff ff ff 7f
12880 00−2147483647ff ff ff ff
−12880 80214748364800 00 00 80 00
255ff 00−214748364800 00 00 80 80
−255ff 804294967294fe ff ff ff 00
25600 01549755813887ff ff ff ff 7f
Table 6.18. Script number decoding (maximum length 4 and 5)
ElementMax length 4Max length 5
(empty)00
00ErrMinimalDataErrMinimalData
80ErrMinimalDataErrMinimalData
01 00ErrMinimalDataErrMinimalData
ff 00255255
ff 80−255−255
7f127127
ff−127−127
00 80ErrMinimalDataErrMinimalData
ff ff ff 7f21474836472147483647
ff ff ff ff−2147483647−2147483647
00 00 00 80 00ErrNumOutOfRange2147483648
ff ff ff ff 7fErrNumOutOfRange549755813887
00 00 00ErrMinimalDataErrMinimalData
Table 6.19. Boolean interpretation
ElementValueElementValueElementValueElementValue
(empty)false00false80false00 80false
80 00true00 00 80false00 01true01true
Table 6.20. Hash opcode outputs
OpcodeInputOutput
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
ItemValue
Full serialization0100000002000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f0100000000ffffffff202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f0000000001feffffff02e80300000000000000001976a9140102030405060708090a0b0c0d0e0f101112131488acd0070000000000000000016a04030201080706050200f2052a010000006400000002000000015100e1f50500000000c8000000030000000152
Transaction hash (internal order)f3deadbbf50b1c407d09bc893408432844a0685df21ea15c4a73a9eba6480c5a
Subscript76a9140102030405060708090a0b0c0d0e0f101112131488ac
Test vector: Signature hash: SIGHASH_ALL (0x1), input 0
ItemValue
Prefix serialization0100010002000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f0100000000ffffffff202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f0000000001feffffff02e80300000000000000001976a9140102030405060708090a0b0c0d0e0f101112131488acd0070000000000000000016a0403020108070605
Prefix hashf3deadbbf50b1c407d09bc893408432844a0685df21ea15c4a73a9eba6480c5a
Witness serialization01000300021976a9140102030405060708090a0b0c0d0e0f101112131488ac00
Witness hashbb75f775cbeee9c804eb983c29fcc2d97a2264e6fa75a87a15a06dd4286982e5
Final serialization01000000f3deadbbf50b1c407d09bc893408432844a0685df21ea15c4a73a9eba6480c5abb75f775cbeee9c804eb983c29fcc2d97a2264e6fa75a87a15a06dd4286982e5
Signature hashf4ce6e37ab599bcd9c770d086c79749a77f99e4a50e774caf5ff50a123feff91
Test vector: Signature hash: SIGHASH_NONE (0x2), input 0
ItemValue
Prefix serialization0100010002000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f0100000000ffffffff202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f000000000100000000000403020108070605
Prefix hash8aa0fda4bf9cc8936b0eec1cabc6795b0de37badda0b26b7063d475d74bd967b
Witness serialization01000300021976a9140102030405060708090a0b0c0d0e0f101112131488ac00
Witness hashbb75f775cbeee9c804eb983c29fcc2d97a2264e6fa75a87a15a06dd4286982e5
Final serialization020000008aa0fda4bf9cc8936b0eec1cabc6795b0de37badda0b26b7063d475d74bd967bbb75f775cbeee9c804eb983c29fcc2d97a2264e6fa75a87a15a06dd4286982e5
Signature hash03319bed79cbb29b3c6fe90e4ff6e301071ddeb3568d16462ca5ffeed787d44b
Test vector: Signature hash: SIGHASH_SINGLE (0x3), input 1
ItemValue
Prefix serialization0100010002000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f010000000000000000202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f0000000001feffffff02ffffffffffffffff000000d0070000000000000000016a0403020108070605
Prefix hash1c60e4485f51debb2dcdc9893293a6b4e6290a3d66c57756ed95cb74b7548927
Witness serialization0100030002001976a9140102030405060708090a0b0c0d0e0f101112131488ac
Witness hash4902291a3dcd005c1a087f947d7d37cc0de0f06daa470a5d7713f8d53b093cc7
Final serialization030000001c60e4485f51debb2dcdc9893293a6b4e6290a3d66c57756ed95cb74b75489274902291a3dcd005c1a087f947d7d37cc0de0f06daa470a5d7713f8d53b093cc7
Signature hash4641bb9be1f590a5cae964b188317cf168e158d24cfa27c7280941c684e42dc2
Test vector: Signature hash: SIGHASH_ALL | SIGHASH_ANYONECANPAY (0x81), input 0
ItemValue
Prefix serialization0100010001000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f0100000000ffffffff02e80300000000000000001976a9140102030405060708090a0b0c0d0e0f101112131488acd0070000000000000000016a0403020108070605
Prefix hash12912c99d91053050096a5745dc0d45c829c73fd45f7fa9164649c8fada6b272
Witness serialization01000300011976a9140102030405060708090a0b0c0d0e0f101112131488ac
Witness hash3db60c902d6e97e3b0a3ec8b55a7c330392e4740a46a3b79a93445c680e58a45
Final serialization8100000012912c99d91053050096a5745dc0d45c829c73fd45f7fa9164649c8fada6b2723db60c902d6e97e3b0a3ec8b55a7c330392e4740a46a3b79a93445c680e58a45
Signature hash4a1ecb30301eb4a7445ffca36202deda5f9552479fd2b223e3589f8738dbbde3
Table 6.21. Signature hashes of the sample transaction for every hash type
InputHash typeSignature hash
00x1f4ce6e37ab599bcd9c770d086c79749a77f99e4a50e774caf5ff50a123feff91
00x203319bed79cbb29b3c6fe90e4ff6e301071ddeb3568d16462ca5ffeed787d44b
00x3e8fb9b72477a691a3c5c05aa4147a3fb5feaa4e43940ead1107ef94de9392cd4
00x814a1ecb30301eb4a7445ffca36202deda5f9552479fd2b223e3589f8738dbbde3
00x82487f799838a05a534aa50daa92487e17c2715cc1ada7ce48c3a9fa052d05740f
00x83e2e9e2e61df3dc7a668dc0418f5e1fa4d56f77d2dd2a8a427780d8bc423e54f3
10x1901d5f6eac2d838d4ca1f3cc5a4ea4e2c10394ac507a7a2bb891958412d03871
10x293deae66a64e67888a1a03a319923cd3f948f27a375ed00d926ac19365b3fa4d
10x34641bb9be1f590a5cae964b188317cf168e158d24cfa27c7280941c684e42dc2
10x819df281682b102567a25fb8d3ca09f392efe5ee5499d8c12c0254974c05b070c5
10x8293c4e51c4dc384c723940f0b64f4ef450dee23d12f9806516d83470ea2fa399c
10x83d71ccf15b435685367f77257aef4ac96a959838c42d4164de2a795da0a9254bb

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)
ItemValue
Private key0000000000000000000000000000000000000000000000000000000000000001
Public key (compressed)0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798
HASH160 of public keye280cb6e66b96679aec288b1fbdbd4db08077a1b
Public key script76a914e280cb6e66b96679aec288b1fbdbd4db08077a1b88ac
Signature hash (ALL)5a5f06a3652928aae830f38a45325564e1973fb10073ef671df0be1e69466331
Signature element3045022100a944fc7a28deab0b5c3f07b834995b2d2d5f42d708d0d7a04e3bec572c5779b202202d2730e2e9116305e8e731c7de302e11f43c2e9f1d87e19dd21d8c165175bab001
Signature script483045022100a944fc7a28deab0b5c3f07b834995b2d2d5f42d708d0d7a04e3bec572c5779b202202d2730e2e9116305e8e731c7de302e11f43c2e9f1d87e19dd21d8c165175bab001210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798
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 04invalid: ErrInvalidSigHashType (encoding failure)
Test vector: EC-Schnorr-DCRv0 via OP_CHECKSIGALT (type 2, same key)
ItemValue
Public key script210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f8179852be
Signature hash (ALL)99b24bd56eb2ff75a229d24a2a0d11f3025380add7655abce1e64a2fe5ceebf4
Signature script415326e2256467605135e786593379842f6087245aa4fcd1fa428849e20a8cb412d59effa4e8366ebe1cfbc7bac65a04e1aa9946e0ec4b10e154800e05edcdee5a01
Result (consensus flags)valid
Test vector: Ed25519 via OP_CHECKSIGALT (type 1)
ItemValue
Public key script204cb5abf6ad79fbf5abbccafcc269d85cd2651ed4b885b5869f241aedf0a5ba2951be
Signature hash (ALL)d9fbdf699eafab052dad4c7c873444809717dd3643329adbe6e2c043c7b869c3
Signature script410a299ecbc9e4800db91797d9090b21fdd76aba7fcab02c5dba370cc5ef4b79472705d52fe57bfe9ed7a034663cc0301c191006e2790f134a38b2bb77ef57fc0101
Result (consensus flags)valid
Test vector: 2-of-3 multisignature, bare and through P2SH
ItemValue
Private keys1, 3 and 6 (as 32-byte big-endian scalars); signatures by keys 1 and 6
Public key script52210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f817982102f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f92103fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a146029755653ae
Signature script (no dummy element)483045022100f5600c0a319d9d71df82ccbee4d0dd08a6a1b9aa840b29700b86cecf4660ad1f022030475c9aa791e59d0ff7cb08df2112743fe28886127ea9d9ed12a9e3b21bb6a00147304402206194d7eecb75ef075cda4e46d50bf66caef91350b12ccc767dd13e2d7f7c2669022046f8c544e3c4a4cb031f8058be3bc2882fd2b9c556f9fad200df758b3ef165e201
Resultvalid
Signatures in reverse orderinvalid: ErrEvalFalse
With a leading OP_0 dummyinvalid under consensus flags: ErrCleanStack (valid without the clean-stack flag)
P2SH public key scripta914f86b5a7c6d32566aa4dccc04d1533530b4d64cf387
P2SH signature script483045022100f5600c0a319d9d71df82ccbee4d0dd08a6a1b9aa840b29700b86cecf4660ad1f022030475c9aa791e59d0ff7cb08df2112743fe28886127ea9d9ed12a9e3b21bb6a00147304402206194d7eecb75ef075cda4e46d50bf66caef91350b12ccc767dd13e2d7f7c2669022046f8c544e3c4a4cb031f8058be3bc2882fd2b9c556f9fad200df758b3ef165e2014c6952210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f817982102f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f92103fff97bd5755eeea420453a14355235d382f6472f8568a18b2f057a146029755653ae
P2SH resultvalid; 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.

Table 6.22. OP_CHECKLOCKTIMEVERIFY and OP_CHECKSEQUENCEVERIFY
ScriptTx ver.Lock timeSequenceResult
100 CLTV11000valid
101 CLTV11000ErrUnsatisfiedLockTime
500000000 CLTV11000ErrUnsatisfiedLockTime (kind mismatch)
100 CLTV1100ffffffffErrUnsatisfiedLockTime (input final)
-1 CLTV11000ErrNegativeLockTime
4294967295 CLTV142949672950valid (5-byte operand)
549755813887 CLTV142949672950ErrUnsatisfiedLockTime
10 CSV200000000avalid
11 CSV200000000aErrUnsatisfiedLockTime
10 CSV100000000aErrUnsatisfiedLockTime (version)
2147483648 CSV100000000avalid (disable bit in operand)
10 CSV208000000aErrUnsatisfiedLockTime (disable bit in input)
4194314 CSV200000000aErrUnsatisfiedLockTime (kind mismatch)
4194314 CSV200040000avalid
4294967306 CSV200000000avalid (bits above 31 ignored)
-1 CSV200000000aErrNegativeLockTime

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.

Table 6.23. Script execution vectors
EntrySignature scriptPublic key scriptResult
5410IF 'b'{2049} ENDIF 1ErrElementTooBig (unexecuted push)
5420IF <NOP>{256} ENDIF 1ErrTooManyOperations (unexecuted ops count)
22390IF 0x50{255} ENDIF 1valid (0x50 is not counted)
5890IF ELSE 1 ELSE VERIF ENDIFErrReservedOpcode
18380IF CODESEPARATOR ENDIF 1ErrDisabledOpcode
—10 IF VER ENDIFvalid (OP_VER unexecuted)
5470 IF 0x4c 0x00 ENDIF 1(empty)valid (unexecuted non-minimal push)
3890x4c 0x00DROP 1ErrMinimalData
4130x01 0x001valid
4330x01 0x00NOT DROP 1ErrMinimalData (numeric use)
5241 0x01 0x80IF 0 ENDIFvalid (negative zero is false)
6061 0x05 0x0100000000VERIFYvalid (long boolean)
5080IF 0 ELSE 1 ELSE 0 ENDIFvalid (two ELSEs)
5431 IF1 ENDIFErrUnbalancedConditional
13792147483647 DUP ADD4294967294 EQUALvalid (5-byte result)
131921474836471ADD 1SUB 1ErrNumOutOfRange
13312 2MUL4 EQUALErrEvalFalse (OP_2MUL is a no-op)
1439-7 3MOD -1 EQUALvalid
14841 31LSHIFT -2147483648 EQUALvalid
14851 32LSHIFT 0 EQUALvalid
—(empty)-1 32 RSHIFT -1 EQUALvalid
14931 33LSHIFT 0 EQUALErrOverflowShift
—(empty)65536 65536 MUL 0 EQUALvalid (wrapping)
920'abcd' 3 1SUBSTR 'bc' EQUALvalid
925'' 2147483647 2147483646SUBSTR '' EQUALvalid
2040(empty)0 0 CHECKMULTISIGVERIFY DEPTH 0 EQUALvalid
20371<0 0 CHECKMULTISIGVERIFY>{255}valid (255 operations)
20381<0 0 CHECKMULTISIGVERIFY>{256}ErrTooManyOperations
20391<NOP>{3} <0 'a' … 't' 20 CHECKMULTISIGVERIFY>{12}valid (3+12×21=255)
192100x21 <key 3> CHECKSIGErrEvalFalse (empty signature)
—(empty)3 CHECKSIGALTvalid (unassigned type)
—(empty)128 CHECKSIGALTErrNumOutOfRange
—'x' 'y'1 CHECKSIGALT NOT, clean stackErrCleanStack ('x' left behind)
22461 3 DATA_2 ADD SSTXHASH160 DATA_20 0xdcbd…ff8f EQUALErrP2SHStakeOpCodes
22631 3 DATA_2 ADD TADDHASH160 DATA_20 0xdd89…fb05 EQUAL, TREASURYErrP2SHStakeOpCodes
2267as 2263as 2263, no flagsvalid (0xc1 is OP_UNKNOWN193)
2088NOP1NOP10ErrEmptyStack
—(empty)RETURN, version 1valid (not executed)
—(empty)(empty), version 1ErrEvalFalse (construction)
—NOPHASH160 0x14 <20 zero bytes> EQUAL, version 1ErrNotPushOnly
—(empty)0x4c, version 1ErrMalformedPush

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

Table 6.24. Signature operation counts (treasury rules in effect unless noted)
ScriptImprecisePrecise
DUP HASH160 <20> EQUALVERIFY CHECKSIG11
2 <K33> <K33> <K33> 3 CHECKMULTISIG203
0 CHECKMULTISIG2020
17 CHECKMULTISIG (17 is pushed as 01 11)2020
16 CHECKMULTISIGVERIFY2016
CHECKSIG CHECKSIGVERIFY CHECKSIGALT CHECKSIGALTVERIFY44
TSPEND1 (0 without treasury rules)1
CHECKSIG 0x4c (parse failure after the first opcode)11
CHECKSIG 0x01 0xac (0xac is push data)11
0 IF CHECKSIG ENDIF11

6.17.7 Provably Unspendable Outputs

Table 6.25. Provably unspendable outputs
AmountScriptUnspendable
051yes
16ayes
151 6ano
14c (parse failure)yes
151no
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.

Table 6.26. Script error kinds and the rules that produce them
Error kindRule
ErrMalformedPushRule 6.2, Rule 6.3, Rule 6.31
ErrScriptTooBigRule 6.3
ErrNotPushOnlyRule 6.3
ErrP2SHStakeOpCodesRule 6.3, Rule 6.32
ErrEvalFalse, ErrEmptyStack, ErrCleanStackRule 6.9, Rule 6.31, Rule 6.3
ErrUnbalancedConditionalRule 6.4, Rule 6.8
ErrStackOverflowRule 6.5
ErrDisabledOpcode, ErrTooManyOperations, ErrElementTooBigRule 6.6, Rule 6.28, Rule 6.13
ErrReservedOpcodeRule 6.6, Rule 6.22
ErrMinimalDataRule 6.7, Rule 6.11
ErrNumOutOfRangeRule 6.11
ErrInvalidStackOperationSection 6.8 (all opcodes), Rule 6.12
ErrVerify, ErrEqualVerify, ErrNumEqualVerifySection 6.8.2
ErrCheckSigVerify, ErrCheckMultiSigVerify, ErrCheckSigAltVerifySection 6.9
ErrEarlyReturnTable 6.5
ErrNegativeSubstrIdx, ErrOverflowSubstrIdxRule 6.14, Rule 6.15
ErrNegativeRotation, ErrOverflowRotationRule 6.16
ErrNegativeShift, ErrOverflowShiftRule 6.17
ErrDivideByZeroTable 6.8
ErrNegativeLockTime, ErrUnsatisfiedLockTimeRule 6.19, Rule 6.20
ErrInvalidSigHashTypeRule 6.23
ErrSigTooShort … ErrSigHighS (16 kinds)Rule 6.24
ErrPubKeyTypeRule 6.25
ErrInvalidPubKeyCount, ErrInvalidSignatureCountRule 6.28
ErrInvalidSigHashSingleIndexRule 6.30 (fails only via OP_CHECKMULTISIG)