Skip to content

7 Transactions

A transaction moves value. It consumes previously created, still unspent transaction outputs and creates new ones. This chapter specifies every consensus rule whose subject is a single transaction: what makes a transaction well formed, how it is classified, when it may appear in a block, which outputs it may spend, how its fee is determined, and how its scripts are invoked. Rules whose subject is a whole block (sizes, sigop totals, header commitments, the order of block connection) are specified in Chapter 10; the detailed structure of tickets, votes and revocations in Chapter 8; of treasury transactions in Chapter 12; and of the coinbase in Chapter 11. The serialization of transactions and their hashes is given in Chapter 4, and the script engine in Chapter 6.

7.1 Overview

Every transaction in a block passes through the stages listed in Table 7.1. A block is invalid if any transaction in it fails any stage. The stages are listed approximately in the order in which dcrd applies them (dcrd checks expiry before the context stage, and runs the input, sequence-lock and script stages first for the whole stake tree and then for the whole regular tree); the order affects only which error is reported, except where noted in Section 7.10, because the state of the set of unspent outputs changes as transactions are connected.

Table 7.1. Stages of transaction validation within block validation
StageContentSection
SanityContext-free structural checks: counts, size, amounts, duplicate inputs.Section 7.4
ContextChecks that depend on agenda state but not on the set of unspent outputs: versions, input forms per type, stake opcodes in regular outputs, placement of each type in the correct tree.Section 7.3, Section 7.5
ExpiryThe block height must be below the transaction’s expiry.Section 7.6
FinalityThe absolute lock time must have passed.Section 7.7
InputsEach input must reference an available output; maturity, tag, value and fee rules; the transaction is then connected.Section 7.9, Section 7.10
Sequence locksRelative lock times must be satisfied.Section 7.8
ScriptsEvery input script is executed against the script of the output it spends.Section 7.12

Note

A node deciding whether to accept an unconfirmed transaction into its memory pool applies these same rules from the point of view of a hypothetical next block, together with additional, stricter policy rules (standardness, fees, limits on versions and script forms) that are not consensus. Policy is described in Chapter 17.

7.1.1 Agendas affecting transaction rules

Several transaction rules changed through stakeholder votes. Each is identified below by its agenda identifier. Throughout this chapter, “agenda X is active” always means that X is active for the block being validated (the block that contains the transaction), which dcrd determines from the parent of that block as described in Chapter 13.

Table 7.2. Agendas that change transaction-level rules
Agenda idDCPEffect on transaction rules
lnfeaturesDCP-0002, DCP-0003Enables sequence locks; finality uses the parent’s past median time instead of the header timestamp; enables OP_CHECKSEQUENCEVERIFY and OP_SHA256 in scripts.
fixlnseqlocksDCP-0004Corrected the set of outputs visible to sequence-lock evaluation. No longer consulted by dcrd; see Section 7.8.4.
treasuryDCP-0006Treasury transaction types; coinbase must be version 3; treasury opcodes; maturity of vote and revocation outputs raised to CoinbaseMaturity; OP_TGEN maturity; OP_TADD outputs unspendable.
explicitverupgradesDCP-0008Transaction versions above 3 and regular-transaction output script versions above 0 are rejected.
autorevocationsDCP-0009Revocations must be version 2; scripts of version 2 or later revocations are not executed.

7.1.2 Constants

Table 7.3. Constants and parameters used in this chapter
NameValueMeaning
MaxAmount2100000000000000Largest valid amount in atoms (21×106×108).
MaxTxSize393216 (mainnet)Largest serialized transaction, in bytes. 1000000 on the other networks.
CoinbaseMaturity256 (mainnet)Blocks before coinbase and related outputs may be spent. 16 on the other networks.
SStxChangeMaturity1Blocks before ticket change outputs may be spent; 1 on every network.
TicketMaturity256 (mainnet)Used by staking maturity rules; 16 on the other networks.
StakeBaseSigScript0x0000 (mainnet)Required signature script of a vote’s stakebase input (two bytes). 0x7357 on regnet, 0x0000 on testnet3 and simnet.
MinCoinbaseScriptLen2Minimum coinbase and stakebase signature script length.
MaxCoinbaseScriptLen100Maximum coinbase and stakebase signature script length.
TSpendScriptLen100Exact treasury spend signature script length.
LockTimeThreshold500000000Lock times below this are heights, others are Unix times.
NoExpiryValue0Expiry value meaning “never expires”.
NullValueIn−1Placeholder input amount allowed by the sanity rules.
NullBlockHeight0Null input witness block height.
NullBlockIndexffffffffNull input witness block index.
MaxScriptSize16384Output scripts longer than this are never spendable.
MaxSigOpsPerBlock5000Block signature-operation limit (Chapter 10).
TxVersionSeqLock2Lowest transaction version subject to sequence locks.
TxVersionTreasury3Version of treasury transactions and post-treasury coinbases.
TxVersionAutoRevocations2Required revocation version under autorevocations.

7.2 The UTXO Model

Decred, like Bitcoin [1], keeps no account balances. The ledger state is the UTXO set: the set of transaction outputs that exist on the chain and have not been consumed. A transaction input names one entry of the set by its outpoint and consumes it; the transaction’s outputs become new entries. Validation of a transaction therefore needs, for each input, the entry it references.

7.2.1 Outpoints and transaction trees

A block carries two ordered lists of transactions, the regular tree and the stake tree (Chapter 4). Stake transactions (tickets, votes, revocations and the treasury types) live in the stake tree; all others, including the coinbase, live in the regular tree. The tree is part of an output’s identity. An outpoint is the triple

(hash,index,tree)

(7.1)

where hash is the transaction hash of the creating transaction, index its zero-based output index (uint32), and tree is 0 for the regular tree and 1 for the stake tree (int8). Two outpoints are equal only if all three fields are equal.

Rule 7.1 · Outpoint tree must match the creating transaction

The UTXO entry created by output 𝑘 of transaction 𝑇 is keyed by (hash(𝑇),𝑘,𝑡), where 𝑡=1 if 𝑇 is of any stake type (Section 7.3) and 𝑡=0 otherwise. An input whose outpoint carries the other tree value references a nonexistent entry and the transaction MUST be rejected under Rule 7.26.

dcrd: internal/blockchain/utxoviewpoint.go · addTxOuts | internal/blockchain/validate.go · CheckTransactionInputs

The null outpoint is the outpoint with the all-zero hash, index ffffffff and tree 0. It references nothing and is used as the placeholder input of transactions that create value from nothing (coinbase, vote stakebase, treasurybase, treasury spend).

7.2.2 Unspent output entries

An entry records the information consensus later needs about the output and its creating transaction (Table 7.4). These fields are fixed at creation; only the spent/unspent state changes.

Table 7.4. Content of a UTXO entry as used by consensus
FieldTypeMeaning
amountint64Value of the output in atoms.
script versionuint16Version of the output script.
scriptbytesThe output script.
heightuint32Height of the block containing the creating transaction.
indexuint32Position of the creating transaction within its tree (regular-tree position for regular transactions, stake-tree position for stake transactions).
coinbase flagboolThe creating transaction is a coinbase (Algorithm 7.1, evaluated with the treasury state of the creating block).
expiry flagboolThe creating transaction’s expiry field is nonzero.
transaction typeenumstake_type of the creating transaction (Algorithm 7.2; a coinbase is recorded as REGULAR), used by staking rules.
ticket outputslistFor output 0 of a ticket only: the amount, script version and script of every output of the ticket, needed later to validate the vote or revocation that spends it (Chapter 8).

Rule 7.2 · Outputs that never enter the UTXO set

When a transaction is connected, an entry is created for each of its outputs except:

  1. any output whose amount is 0;
  2. any output whose script is longer than MaxScriptSize (16384) bytes;
  3. any output whose script is non-empty and begins with the byte 0x6a (OP_RETURN);
  4. any output whose script does not parse as a version 0 script (Chapter 6), regardless of the output’s script version;
  5. output 0 of a treasury add;
  6. every output of the treasurybase (when treasury is active, the stake transaction at index 0 adds no entries at all).

Such outputs can never be spent: an input referencing one MUST be rejected under Rule 7.26.

dcrd: internal/blockchain/utxoviewpoint.go · addTxOuts, connectStakeTransaction | txscript/script.go · IsUnspendable

An entry is spent once a connected transaction has consumed it; from then on it is no longer part of the UTXO set and no later transaction may reference it. Spending is undone only when the spending transaction is disconnected, either by a chain reorganization or because the next block disapproves the regular tree containing it (Chapter 10); disconnection restores the entry with all of its original fields.

Note

Condition 4 cannot produce a difference for a valid block, because every output of a regular transaction must already tokenize as version 0 (Rule 7.12) and every output of a stake transaction is a version 0 script of a fixed form. The genesis block is never connected to the UTXO set; its outputs are not spendable.

7.2.3 Input witness fields

Each input carries, in the witness part of its serialization (Chapter 4), three fields that duplicate information about the referenced output: ValueIn (int64), BlockHeight (uint32) and BlockIndex (uint32). They were designed to let lightweight clients prove fraud and are called the fraud proof. Consensus constrains them as follows.

Table 7.5. Constraints on input witness fields
InputValueInBlockHeight, BlockIndex
Any input−1 or in [0,MaxAmount] (Rule 7.8).—
Input spending a UTXO entryEqual to the entry’s amount (Rule 7.3).Equal to the entry’s height and index (Rule 7.3).
Coinbase inputEqual to the block’s coinbase subsidy (Chapter 11).0 and ffffffff (Rule 7.13).
Vote stakebase (input 0)Equal to the vote subsidy (Chapter 8).0 and ffffffff (part of the vote’s structural definition, Chapter 8).
Treasurybase inputEqual to the treasury subsidy (Chapter 11, Chapter 12).0 and ffffffff (Rule 7.16).
Treasury spend inputThe amount withdrawn, matching the commitment in output 0 (Chapter 12).0 and ffffffff (Rule 7.17).

Rule 7.3 · Witness fields of spending inputs

For every input that references a UTXO entry (every input except those listed in Rule 7.25), the input’s ValueIn MUST equal the entry’s amount, int64(BlockHeight) MUST equal the entry’s height, and BlockIndex MUST equal the entry’s index. These comparisons are exact.

dcrd: internal/blockchain/validate.go · CheckTransactionInputs

Implementation pitfall

The witness fields are not covered by the transaction hash (Chapter 4), so two encodings of the same transaction with different witness values have the same hash, and only one of them is valid in a given chain context. For an output created earlier in the same block, BlockHeight is the height of the block itself and BlockIndex is the creating transaction’s position in its own tree.

7.3 Classification

Many rules depend on what kind of transaction is being validated. Decred has no explicit type field: the type is inferred from the structure of the transaction. The structural predicates are defined elsewhere and are only named here: is_ticket, is_vote, is_revocation in Chapter 8; is_treasury_add, is_treasury_spend, is_treasurybase in Chapter 12. Each predicate is a pure function of the transaction alone. The coinbase predicate is given below because it depends on the treasury agenda.

Algorithm 7.1 · Coinbase form

ZERO_HASH = bytes(32)

def is_coinbase_form(tx, treasury_active: bool) -> bool:
    if treasury_active and tx.version != 3:
        return False
    if len(tx.inputs) != 1:
        return False
    prev = tx.inputs[0].prev_out
    if prev.index != 0xffffffff or prev.hash != ZERO_HASH:
        return False                     # prev.tree is NOT examined here
    if treasury_active and is_tspend_like(tx):
        return False
    return True

def is_tspend_like(tx) -> bool:          # only reached with exactly one input
    if len(tx.outputs) < 2:
        return False
    sig = tx.inputs[0].sig_script
    if len(sig) == 0 or len(tx.outputs[0].pk_script) == 0 \
            or len(tx.outputs[1].pk_script) == 0:
        return False
    return (sig[-1] == 0xc2                          # OP_TSPEND
            and tx.outputs[0].pk_script[0] == 0x6a   # OP_RETURN
            and tx.outputs[1].pk_script[0] == 0xc3)  # OP_TGEN

dcrd: blockchain/standalone/tx.go · IsCoinBaseTx

Algorithm 7.2 · Transaction type

STAKE_TYPES = {TICKET, VOTE, REVOCATION, TREASURY_ADD, TREASURY_SPEND, TREASURYBASE}

def stake_type(tx):                      # independent of every agenda
    if is_ticket(tx):      return TICKET
    if is_vote(tx):        return VOTE
    if is_revocation(tx):  return REVOCATION
    if tx.version >= 3:
        if is_treasury_add(tx):   return TREASURY_ADD
        if is_treasury_spend(tx): return TREASURY_SPEND
        if is_treasurybase(tx):   return TREASURYBASE
    return REGULAR

def classify(tx, treasury_active):
    t = stake_type(tx)
    if t == REGULAR and is_coinbase_form(tx, treasury_active):
        return COINBASE
    return t

dcrd: blockchain/stake/staketx.go · DetermineTxType | internal/blockchain/validate.go · checkTransactionContext

The six stake predicates are mutually exclusive, so the order of the tests in stake_type does not matter for well-formed input; it is given as dcrd applies it. A transaction that almost, but not exactly, satisfies a stake predicate is classified REGULAR and is then subject to the regular rules, which normally reject it (for example a malformed vote has a null outpoint as input 0 and fails Rule 7.19).

Implementation pitfall

stake_type does not consult the treasury agenda: a version 3 transaction of treasury-add, treasury-spend or treasurybase form is classified as such even before the agenda is active. Before activation such a transaction is invalid in either tree (Rule 7.4). The coinbase predicate, in contrast, does depend on the agenda, and once treasury is active a treasurybase also satisfies is_coinbase_form; code that tests for a coinbase in the stake tree must test for the treasurybase first.
Table 7.6. Transaction types, their trees and where their structure is specified
TypeTreePlacement conditionStructure
CoinbaseregularExactly one, at index 0.Chapter 11
RegularregularAny index other than 0.this chapter
TicketstakeAny position (after the treasurybase when treasury is active).Chapter 8
VotestakeOnly at or above StakeValidationHeight.Chapter 8
RevocationstakeOnly at or above StakeValidationHeight.Chapter 8
TreasurybasestakeExactly one, at stake index 0, when and only when treasury is active.Chapter 12
Treasury addstakeOnly when treasury is active.Chapter 12
Treasury spendstakeOnly when treasury is active, at or above StakeValidationHeight, on a treasury vote interval.Chapter 12

Rule 7.4 · Tree placement of transaction types

  1. Every transaction in the regular tree MUST have stake_type equal to REGULAR (ErrStakeTxInRegularTree).
  2. Every transaction in the stake tree MUST have stake_type different from REGULAR (ErrRegTxInStakeTree).
  3. If treasury is not active, the stake tree MUST NOT contain transactions of type TREASURY_ADD, TREASURY_SPEND or TREASURYBASE. (dcrd enforces this by counting only the other three types when the agenda is inactive and requiring the counts to add up to the size of the stake tree, ErrNonstandardStakeTx.)

The remaining placement conditions of Table 7.6 are block rules specified in Chapter 10, Chapter 8 and Chapter 12.

dcrd: internal/blockchain/validate.go · checkBlockContext

7.4 Context-Free Sanity Rules

These rules depend on nothing but the transaction and the network parameters. dcrd applies them to every transaction of both trees when it first receives a block, before any agenda state is known, and they are identical for all heights.

Rule 7.5 · Inputs and outputs present

A transaction MUST have at least one input (ErrNoTxInputs) and at least one output (ErrNoTxOutputs).

dcrd: blockchain/standalone/tx.go · CheckTransactionSanity

Rule 7.6 · Maximum serialized size

The size in bytes of the serialization of the transaction, in the serialization type with which it was decoded, MUST NOT exceed MaxTxSize. For every transaction that can appear in a valid block this is the full serialization (prefix and witness, Chapter 4), because a transaction of any other serialization type is always rejected by other rules. MaxTxSize is 393216 on mainnet and 1000000 on the other networks (ErrTxTooBig). The limit is inclusive: a transaction of exactly MaxTxSize bytes is valid.

dcrd: blockchain/standalone/tx.go · CheckTransactionSanity

Rule 7.7 · Output amounts

For each output in order, its amount 𝑣 MUST satisfy 0≤𝑣≤MaxAmount, and the running total of the amounts of that output and all preceding outputs MUST satisfy 0≤total≤MaxAmount (ErrBadTxOutValue). A zero amount is valid (such an output is never spendable, Rule 7.2).

dcrd: blockchain/standalone/tx.go · CheckTransactionSanity

Rule 7.8 · Input witness amounts

For each input, ValueIn MUST either equal NullValueIn (−1) or satisfy 0≤ValueIn≤MaxAmount (ErrFraudAmountIn). No constraint is placed on the sum of the ValueIn fields here.

dcrd: blockchain/standalone/tx.go · CheckTransactionSanity

Rule 7.9 · No duplicate inputs

No two inputs of a transaction may have equal outpoints, where equality compares hash, index and tree (ErrDuplicateTxInputs).

dcrd: blockchain/standalone/tx.go · CheckTransactionSanity

Note

Because the tree is part of outpoint equality, two inputs that differ only in the tree byte pass Rule 7.9; at most one of them can reference an existing entry, so the transaction still fails input validation. Null outpoints count for the purpose of the duplicate check.

Algorithm 7.3 · Context-free sanity check

MAX_AMOUNT = 2_100_000_000_000_000

def check_sanity(tx, max_tx_size):
    if len(tx.inputs) == 0:  reject("ErrNoTxInputs")
    if len(tx.outputs) == 0: reject("ErrNoTxOutputs")
    if full_serialize_size(tx) > max_tx_size: reject("ErrTxTooBig")
    total = 0
    for out in tx.outputs:
        if out.value < 0 or out.value > MAX_AMOUNT: reject("ErrBadTxOutValue")
        total = total + out.value      # cannot exceed 2*MAX_AMOUNT: no overflow
        if total > MAX_AMOUNT:          reject("ErrBadTxOutValue")
    for txin in tx.inputs:
        if (txin.value_in < 0 and txin.value_in != -1) or txin.value_in > MAX_AMOUNT:
            reject("ErrFraudAmountIn")
    seen = set()
    for txin in tx.inputs:
        key = (txin.prev_out.hash, txin.prev_out.index, txin.prev_out.tree)
        if key in seen: reject("ErrDuplicateTxInputs")
        seen.add(key)

dcrd: blockchain/standalone/tx.go · CheckTransactionSanity

Test vector: Sanity checks (results from standalone.CheckTransactionSanity)
one output of 2100000000000000                      valid
one output of 2100000000000001                      ErrBadTxOutValue
outputs 2100000000000000 and 1                      ErrBadTxOutValue (total)
one output of 0                                     valid
one output of -1                                    ErrBadTxOutValue
input ValueIn -2                                    ErrFraudAmountIn
input ValueIn 2100000000000000                      valid
input ValueIn 2100000000000001                      ErrFraudAmountIn
inputs (h, 1, tree 0) and (h, 1, tree 1)            valid
inputs (h, 1, tree 0) and (h, 1, tree 0)            ErrDuplicateTxInputs

7.5 Contextual Structure Rules

The rules in this section depend on the transaction and on the agenda state for the containing block, but not on the UTXO set. They apply to every transaction of both trees. The type t used below is classify(tx, treasury_active) (Algorithm 7.2).

7.5.1 Versions

The transaction version is a 16-bit field (Chapter 4). Script versions are 16-bit fields of each output.

Rule 7.10 · Maximum transaction version

If explicitverupgrades (DCP-0008) is active, the transaction version MUST be at most 3. Otherwise every version from 0 to 65535 is permitted by this rule (ErrTxVersionTooHigh). This applies to all types in both trees.

dcrd: internal/blockchain/validate.go · checkTransactionContext

Rule 7.11 · Maximum output script version of regular transactions

If t is REGULAR or COINBASE and explicitverupgrades is active, every output MUST have script version 0 (ErrScriptVersionTooHigh). Without the agenda any script version is permitted by this rule. Stake transactions are exempt from this rule because their structural definitions already require version 0 for every output.

dcrd: internal/blockchain/validate.go · checkTransactionContext

Rationale

DCP-0008 makes every future change to transaction or script semantics introduce a new version number, so that the version itself proves the enabling agenda is active and old software cannot be tricked into treating new-version outputs as anyone-can-spend. Before the agenda, output scripts with a nonzero version always succeed when executed (Chapter 6), provided the script engine can be created for the spend (Rule 7.43); such outputs created before activation remain in the UTXO set and remain spendable afterwards, because Rule 7.11 constrains only the outputs a transaction creates.

Version-specific semantics elsewhere: sequence locks apply to versions 2 and above (Section 7.8); the coinbase must be version 3 when treasury is active (Algorithm 7.1); revocations must be version 2 under autorevocations (Rule 7.15); treasury transactions are version 3 by definition (Chapter 12); votes carrying treasury-spend votes are version 3 (Chapter 8).

7.5.2 Regular transaction outputs

Rule 7.12 · No stake opcodes in regular outputs

If t is REGULAR or COINBASE, every output script is tokenized as a version 0 script (Chapter 6), whatever its declared script version.

  1. If tokenization fails (for example a data push extends past the end of the script), the transaction MUST be rejected (ErrScriptMalformed).
  2. No opcode of the script (data inside pushes is not an opcode) may be one of OP_SSTX (0xba), OP_SSGEN (0xbb), OP_SSRTX (0xbc), OP_SSTXCHANGE (0xbd); and, if treasury is active, also OP_TADD (0xc1), OP_TSPEND (0xc2), OP_TGEN (0xc3) (ErrRegTxCreateStakeOut).

dcrd scans as it tokenizes, so a script with a forbidden opcode before a malformed push is reported with the second error kind; the transaction is rejected either way.

dcrd: internal/blockchain/validate.go · checkTransactionContext | txscript/script.go · ContainsStakeOpCodes

Implementation pitfall

Output scripts with a nonzero script version are nonetheless tokenized with version 0 rules here. Before explicitverupgrades, a regular output with script version 1 whose bytes do not tokenize as version 0 makes the whole block invalid.

7.5.3 Input forms by type

Rule 7.13 · Coinbase input

If t is COINBASE:

  1. its single input’s outpoint MUST be the null outpoint, including tree 0 (ErrBadCoinbaseOutpoint; is_coinbase_form does not examine the tree);
  2. the input’s BlockHeight MUST be 0 and BlockIndex MUST be ffffffff (ErrBadCoinbaseFraudProof);
  3. the length 𝑙 of its signature script MUST satisfy 2≤𝑙≤100 (ErrBadCoinbaseScriptLen).

The coinbase’s ValueIn, outputs and height commitment are specified in Chapter 11.

dcrd: internal/blockchain/validate.go · checkTransactionContext

Rule 7.14 · Vote stakebase and ticket input

If t is VOTE:

  1. the length 𝑙 of the signature script of input 0 (the stakebase) MUST satisfy 2≤𝑙≤100 (ErrBadStakebaseScriptLen);
  2. the signature script of input 0 MUST equal StakeBaseSigScript byte for byte (ErrBadStakebaseScrVal);
  3. the outpoint of input 1 MUST NOT be the null outpoint (ErrBadTxInput).

dcrd: internal/blockchain/validate.go · checkTransactionContext

Rule 7.15 · Revocation version and input

If t is REVOCATION:

  1. if autorevocations (DCP-0009) is active, the transaction version MUST equal 2 (ErrInvalidRevocationTxVersion);
  2. the outpoint of input 0 MUST NOT be the null outpoint (ErrBadTxInput).

dcrd: internal/blockchain/validate.go · checkTransactionContext

Rule 7.16 · Treasurybase input

If t is TREASURYBASE: input 0 MUST have the null outpoint (ErrBadTreasurybaseOutpoint), BlockHeight 0 and BlockIndex ffffffff (ErrBadTreasurybaseFraudProof), and an empty signature script (ErrBadTreasurybaseScriptLen). The first and third conditions are already implied by is_treasurybase.

dcrd: internal/blockchain/validate.go · checkTransactionContext

Rule 7.17 · Treasury spend input

If t is TREASURY_SPEND: input 0 MUST have the null outpoint (ErrBadTSpendOutpoint), BlockHeight 0 and BlockIndex ffffffff (ErrBadTSpendFraudProof), and a signature script of exactly 100 bytes (ErrBadTSpendScriptLen, already implied by is_treasury_spend). Note that is_treasury_spend itself does not require the null outpoint.

dcrd: internal/blockchain/validate.go · checkTransactionContext

Rule 7.18 · Treasury add change

If t is TREASURY_ADD and it has exactly two outputs, the amount of output 1 (the change) MUST NOT be 0 (ErrInvalidTAddChange). Treasury adds are additionally subject to Rule 7.19.

dcrd: internal/blockchain/validate.go · checkTransactionContext

Rule 7.19 · Non-null inputs

If t is REGULAR, TICKET or TREASURY_ADD, no input may have the null outpoint (ErrBadTxInput).

dcrd: internal/blockchain/validate.go · checkTransactionContext

Note

The coinbase, treasurybase and treasury spend each have exactly one input by their definitions, so the rules above constrain all of their inputs. A vote has exactly two inputs and a revocation exactly one (Chapter 8).

Algorithm 7.4 · Contextual structure check

def check_context(tx, params, treasury, explicit_upgrades, auto_revocations):
    if explicit_upgrades and tx.version > 3: reject("ErrTxVersionTooHigh")
    t = classify(tx, treasury)
    i0 = tx.inputs[0]
    if t == VOTE:
        if not 2 <= len(i0.sig_script) <= 100: reject("ErrBadStakebaseScriptLen")
        if i0.sig_script != params.stake_base_sig_script:
            reject("ErrBadStakebaseScrVal")
        if is_null_outpoint(tx.inputs[1].prev_out):  reject("ErrBadTxInput")
    elif t == REVOCATION:
        if auto_revocations and tx.version != 2: reject("ErrInvalidRevocationTxVersion")
        if is_null_outpoint(i0.prev_out): reject("ErrBadTxInput")
    elif t == COINBASE:
        if not is_null_outpoint(i0.prev_out): reject("ErrBadCoinbaseOutpoint")
        if not is_null_witness(i0):           reject("ErrBadCoinbaseFraudProof")
        if not 2 <= len(i0.sig_script) <= 100: reject("ErrBadCoinbaseScriptLen")
    elif t == TREASURYBASE:
        if not is_null_outpoint(i0.prev_out): reject("ErrBadTreasurybaseOutpoint")
        if not is_null_witness(i0):           reject("ErrBadTreasurybaseFraudProof")
        if len(i0.sig_script) != 0:           reject("ErrBadTreasurybaseScriptLen")
    elif t == TREASURY_SPEND:
        if not is_null_outpoint(i0.prev_out): reject("ErrBadTSpendOutpoint")
        if not is_null_witness(i0):           reject("ErrBadTSpendFraudProof")
        if len(i0.sig_script) != 100:         reject("ErrBadTSpendScriptLen")
    else:                                     # REGULAR, TICKET, TREASURY_ADD
        if t == TREASURY_ADD and len(tx.outputs) == 2 and tx.outputs[1].value == 0:
            reject("ErrInvalidTAddChange")
        for txin in tx.inputs:
            if is_null_outpoint(txin.prev_out): reject("ErrBadTxInput")
    if t in (REGULAR, COINBASE):
        for out in tx.outputs:
            if explicit_upgrades and out.version > 0: reject("ErrScriptVersionTooHigh")
            ops = tokenize_v0(out.pk_script)  # reject("ErrScriptMalformed") on failure
            if any(is_stake_opcode(op, treasury) for op in ops):
                reject("ErrRegTxCreateStakeOut")

def is_null_outpoint(op):
    return op.hash == ZERO_HASH and op.index == 0xffffffff and op.tree == 0

def is_null_witness(txin):          # ValueIn is not part of this test
    return txin.block_height == 0 and txin.block_index == 0xffffffff

dcrd: internal/blockchain/validate.go · checkTransactionContext

7.6 Expiry

A transaction may name a height from which it can no longer be mined. This lets a transaction that fails to confirm in time become permanently invalid instead of lingering. The Expiry field (uint32) of value 0 means no expiry.

Rule 7.20 · Expired transactions

Let ℎ be the height of the block containing the transaction and 𝐸 its Expiry. If 𝐸≠0 and ℎ≥𝐸, the transaction is expired and the block MUST be rejected (ErrExpiredTx). Equivalently, a transaction with 𝐸≠0 is valid only in blocks of height at most 𝐸−1. This applies to every transaction in both trees, the coinbase included.

dcrd: internal/blockchain/validate.go · IsExpiredTx | internal/blockchain/validate.go · checkBlockDataPositional

Expiry has one further consensus effect: outputs of a transaction with a nonzero expiry require CoinbaseMaturity confirmations before they can be spent (Rule 7.30). Treasury spends have additional expiry requirements tied to the treasury voting windows, specified in Chapter 12.

Test vector: Expiry (results from IsExpiredTx)
Expiry 0,    height 1000000   not expired
Expiry 1000, height 999       not expired
Expiry 1000, height 1000      expired
Expiry 1000, height 1001      expired

7.7 Lock Time Finality

The LockTime field (uint32) sets the earliest point at which a transaction may be mined, either as a block height or as a Unix time. A transaction that may be mined is final. As in Bitcoin, setting every input’s sequence number to its maximum value ffffffff disables the lock time.

Rule 7.21 · Lock time finality

Every transaction in both trees of a block at height ℎ MUST be final, otherwise the block is invalid (ErrUnfinalizedTx). Let 𝐿 be the transaction’s LockTime. The transaction is final if and only if at least one of the following holds:

  1. 𝐿=0;
  2. 𝐿<500000000 (LockTimeThreshold) and 𝐿<ℎ;
  3. 𝐿≥500000000 and 𝐿<𝜏, where 𝜏 is the lock-time reference time defined below;
  4. every input has sequence number ffffffff.

All comparisons are strict as written. The reference time 𝜏 is:

  • if lnfeatures is not active: the timestamp field of the header of the block being validated;
  • if lnfeatures is active: the past median time of the parent of the block being validated (the median of the timestamps of the 11 blocks ending with the parent, or of all blocks back to the genesis block if there are fewer, as defined in Chapter 10).

dcrd: internal/blockchain/validate.go · IsFinalizedTransaction | internal/blockchain/validate.go · checkBlockContext

History

DCP-0003 changed the reference time from the block’s own timestamp to the parent’s past median time, because the median time never decreases while miner-chosen timestamps need not. On mainnet lnfeatures became active at block 189568.

Implementation pitfall

An input sequence number of fffffffe disables relative locks for that input (its bit 31 is set, Section 7.8) but does not count toward condition 4. Condition 4 is evaluated on all inputs, including the null inputs of a coinbase or stakebase.
Test vector: Finality (results from IsFinalizedTransaction; ℎ = block height, 𝜏 = reference time)
LockTime    sequences             h          tau          final
0           00000000              100        1600000000   yes
99          00000000              100        1600000000   yes
100         00000000              100        1600000000   no
101         00000000              100        1600000000   no
100         ffffffff              100        1600000000   yes
100         ffffffff fffffffe     100        1600000000   no
499999999   00000000              499999999  1600000000   no
499999999   00000000              500000000  1            yes
500000000   00000000              999999999  500000000    no
500000000   00000000              1          500000001    yes
1600000000  00000000              1          1599999999   no
1600000000  00000000              1          1600000000   no
1600000000  00000000              1          1600000001   yes

7.8 Relative Lock Times (Sequence Locks)

DCP-0003 repurposes the 32-bit sequence number of each input to express a relative lock: a minimum age of the spent output, measured in blocks or in units of 512 seconds from the block that created the output. The script opcode OP_CHECKSEQUENCEVERIFY lets an output script require such a lock (Chapter 6); the consensus rule in this section enforces it.

7.8.1 Encoding

Table 7.7. Interpretation of an input sequence number under sequence locks
BitsMaskMeaning
3180000000Disable flag (SequenceLockTimeDisabled). If set, the input has no relative lock.
30–23—Ignored.
2200400000Type flag (SequenceLockTimeIsSeconds). Set: the value counts units of 29=512 seconds. Clear: the value counts blocks.
21–16—Ignored.
15–00000ffffValue 𝑣 (SequenceLockTimeMask), 0≤𝑣≤65535.

The maximum relative lock is therefore 65535 blocks or 65535×512=33553920 seconds.

Implementation pitfall

The text of DCP-0003 states the type flag the other way round (“when set … blocks”). The reference implementation, and therefore consensus, treats a set bit 22 as time-based, as in Table 7.7; the DCP’s own reference code agrees with this table.

7.8.2 Applicability

Rule 7.22 · Transactions subject to sequence locks

Sequence locks are enforced only when lnfeatures is active. When it is, a transaction is subject to them if and only if all of the following hold:

  1. its version is at least 2 (any value from 2 to 65535);
  2. it is not of coinbase form, is_coinbase_form(tx, treasury_active) (this excludes the coinbase and, when treasury is active, the treasurybase);
  3. it is not a vote.

This includes regular transactions other than the coinbase, tickets, revocations, treasury adds and treasury spends. Within a subject transaction, an input participates if and only if bit 31 of its sequence number is clear.

dcrd: internal/blockchain/sequencelock.go · calcSequenceLock | internal/blockchain/validate.go · checkConnectBlock

Rule 7.23 · Treasury spend sequence number

When lnfeatures and treasury are both active, the input of a treasury spend MUST have bit 31 of its sequence number set. If it is clear, the sequence-lock calculation looks up the null outpoint, which never exists, and the block is rejected (ErrMissingTxOut).

dcrd: internal/blockchain/sequencelock.go · calcSequenceLock

7.8.3 Calculation and enforcement

For each participating input, the lock is computed from the UTXO entry it spends: its height ℎ𝑜 and, for time locks, the past median time of the block preceding the one that contains the output. Each transaction gets one pair (MinHeight,MinTime), the maxima over its inputs, with −1 meaning “no constraint”.

Algorithm 7.5 · Sequence lock of a transaction

def sequence_lock(tx, block, view, treasury_active):
    # block: the block being validated (height block.height).
    min_height, min_time = -1, -1                     # int64
    if tx.version < 2 or is_coinbase_form(tx, treasury_active) or is_vote(tx):
        return (min_height, min_time)
    for txin in tx.inputs:
        seq = txin.sequence                           # uint32
        if seq & 0x80000000:
            continue
        entry = view.lookup_including_spent(txin.prev_out)
        if entry is None:
            reject("ErrMissingTxOut")
        h_o = entry.height
        value = seq & 0x0000ffff
        if seq & 0x00400000:                          # time based
            prev_h = max(h_o - 1, 0)
            mtp = past_median_time(ancestor(block, prev_h))   # blocks chapter
            t = mtp + (value << 9) - 1
            min_time = max(min_time, t)
        else:                                         # height based
            min_height = max(min_height, h_o + value - 1)
    return (min_height, min_time)

dcrd: internal/blockchain/sequencelock.go · calcSequenceLock

lookup_including_spent returns the entry whether or not it has been marked spent: the calculation runs after the transaction’s tree has been connected (Section 7.10), so the entries it reads have already been spent by the transaction itself. ancestor(block, n) is the block at height 𝑛 on the chain ending with block; for 𝑛 equal to the parent’s height it is the parent.

Rule 7.24 · Sequence lock enforcement

When lnfeatures is active, let ℎ be the height of the block being validated and 𝑚 the past median time of its parent. For every transaction subject to sequence locks in either tree, with lock (MinHeight,MinTime) from Algorithm 7.5, the block MUST be rejected (ErrUnfinalizedTx) if ℎ≤MinHeight or 𝑚≤MinTime. Equivalently, each block-based input requires ℎ≥ℎ𝑜+𝑣 and each time-based input requires 𝑚≥mtp𝑜+512𝑣.

dcrd: internal/blockchain/validate.go · SequenceLockActive | internal/blockchain/validate.go · checkConnectBlock

Note

A relative lock of 𝑣=0 is always satisfied. A regular transaction spending an output created earlier in the same block (ℎ𝑜=ℎ) can carry only 𝑣=0 locks: a block lock of 1 gives MinHeight=ℎ, and a time lock of 𝑣≥1 gives MinTime≥𝑚 because the preceding block is the parent. The value 0x7fffffff that dcrd’s sequence-lock code treats as an “unconfirmed” height is used only by mempool policy and never occurs in block validation.
Test vector: Sequence locks (from calcSequenceLock and SequenceLockActive)

Chain of regnet blocks with timestamps 1600000000+512ℎ for ℎ≥1. Past median times: block 19 → 1600007168, block 24 (the parent) → 1600009728. Output A is created at height 20 and output B at height 25; the transaction is validated in the block at height 25.

version  inputs (sequence)                 MinHeight  MinTime     satisfied
1        A:00000005                        -1         -1          yes
2        A:80000005                        -1         -1          yes
2        A:00000000                        19         -1          yes
2        A:00000005                        24         -1          yes
2        A:00000006                        25         -1          no
2        A:7f3f0005 (reserved bits set)    24         -1          yes
2        A:00400005                        -1         1600009727  yes
2        A:00400006                        -1         1600010239  no
2        A:00400000                        -1         1600007167  yes
2        B:00000000                        24         -1          yes
2        B:00000001                        25         -1          no
2        A:00400005 B:00000000 A:80000000  24         1600009727  yes
65535    A:00000005                        24         -1          yes

For the time locks: 1600007168+5×512−1=1600009727<1600009728, so the lock with 𝑣=5 is satisfied, and the lock with 𝑣=6 (MinTime=1600010239) is not.

7.8.4 The DCP-0004 correction

History

From the activation of lnfeatures (mainnet block 189568) dcrd in effect evaluated sequence locks of regular-tree transactions against a restricted view of the outputs, a by-product of the transaction-indexed UTXO storage of the time (from January 2019 reproduced by an explicitly constructed “legacy” view). That view contained only: outputs of transactions of the parent block’s regular tree and outputs of transactions referenced by that tree’s inputs (both only if the block approved its parent), and outputs of transactions referenced by, or contained in, the current block’s stake tree, together with whatever the node’s working view happened to contain. As a result, a version 2 transaction with an enabled relative lock was rejected (with ErrMissingTxOut) when it spent an output of an earlier transaction in the same block, an output from a block before the parent whose transaction was not otherwise referenced, or an output of a transaction shared with a disapproved parent.

DCP-0004 [32] (agenda fixlnseqlocks, mainnet activation at block 342784) replaced this with the rule of this section: the view is exactly the set of outputs that exist from the point of view of the block being validated. The legacy behaviour also depended on the node’s prior history (for example on the contents of the working view after a reorganization) and so cannot be specified as a pure function of the chain.

dcrd no longer implements the legacy view: at the commit this document describes, Rule 7.24 with Algorithm 7.5 applies to every block for which lnfeatures is active, and fixlnseqlocks is not consulted. Because the corrected rule is strictly less restrictive, every block of the historical chains also satisfies it, as DCP-0004 anticipates (“new implementations will not require any additional code”). An implementation that follows this document therefore matches the reference implementation exactly.

7.9 Input Validation

Input validation checks every input of a transaction against the UTXO set that exists when the transaction is connected (Section 7.10), enforces maturity and tag restrictions on what is spent, sums the input amounts and computes the fee. Several transaction types have additional input rules specified in other chapters; Table 7.10 says where each one plugs in.

7.9.1 Inputs without a referenced output

Rule 7.25 · Inputs exempt from UTXO lookup

The following inputs do not reference a UTXO entry and are exempt from Rule 7.26 through Rule 7.36:

  1. the input of the coinbase (the coinbase is exempt from input validation altogether, and its fee is 0 by definition);
  2. input 0 (the stakebase) of a vote;
  3. the input of the treasurybase, when treasury is active;
  4. the input of a treasury spend, when treasury is active.

For items 2 to 4 the input’s ValueIn is added to the input total (Rule 7.37). Its correctness is a rule of the chapter that owns the type (Table 7.10).

dcrd: internal/blockchain/validate.go · CheckTransactionInputs

7.9.2 Per-input rules

In the following rules, ℎ is the height of the block containing the transaction, 𝑒 the UTXO entry referenced by the input, and age=ℎ−𝑒.height. A script is tagged with opcode 𝑜 when its script version is 0, its first byte is 𝑜, and the remaining bytes are exactly a pay-to-pubkey-hash script (25 bytes: OP_DUP OP_HASH160 OP_DATA_20 <20 bytes> OP_EQUALVERIFY OP_CHECKSIG) or a pay-to-script-hash script (23 bytes: OP_HASH160 OP_DATA_20 <20 bytes> OP_EQUAL).

Rule 7.26 · Referenced output exists and is unspent

The outpoint of each input MUST identify an entry of the UTXO set that is unspent at the moment the transaction is connected (ErrMissingTxOut). The set is that of Section 7.10: it reflects every transaction connected before this one, including earlier transactions of the same block.

dcrd: internal/blockchain/validate.go · CheckTransactionInputs

Rule 7.27 · Stake transactions do not spend same-block outputs

If the transaction is of any stake type and 𝑒.height=ℎ, the transaction MUST be rejected (ErrMissingTxOut), unless the input is one of the historical exceptions of Table 7.12.

dcrd: internal/blockchain/validate.go · CheckTransactionInputs

Rule 7.28 · Zero-value outputs are not spendable

If 𝑒.amount=0 the transaction MUST be rejected (ErrZeroValueOutputSpend). (Such entries cannot exist by Rule 7.2; the check is defensive.)

dcrd: internal/blockchain/validate.go · CheckTransactionInputs

The witness rule Rule 7.3 applies at this point.

Rule 7.29 · Coinbase maturity

If 𝑒 has the coinbase flag, age MUST be at least CoinbaseMaturity (256 on mainnet) (ErrImmatureSpend). An output of the coinbase in block 𝑏 is thus first spendable in block 𝑏+CoinbaseMaturity.

dcrd: internal/blockchain/validate.go · CheckTransactionInputs

Rule 7.30 · Maturity of outputs of expiring transactions

If 𝑒 has the expiry flag (its creating transaction had a nonzero Expiry), age MUST be at least CoinbaseMaturity (ErrExpiryTxSpentEarly).

dcrd: internal/blockchain/validate.go · CheckTransactionInputs

Rationale

A transaction with an expiry can become invalid if a reorganization moves it past its expiry height. Requiring the same maturity as the coinbase limits the damage to descendants of such a transaction, just as coinbase maturity does for coinbases invalidated by reorganizations.

Rule 7.31 · Treasury generation output maturity

If treasury is active and 𝑒’s script is tagged with OP_TGEN (0xc3), age MUST be at least CoinbaseMaturity (ErrImmatureSpend).

dcrd: internal/blockchain/validate.go · CheckTransactionInputs

Rule 7.32 · Ticket outputs are spent only by votes and revocations

If 𝑒’s script is tagged with OP_SSTX (0xba), the spending transaction MUST be a vote or a revocation (ErrTxSStxOutSpend).

dcrd: internal/blockchain/validate.go · CheckTransactionInputs

Rule 7.33 · Treasury add outputs are unspendable

If treasury is active, 𝑒’s script version is 0 and its script is the single byte 0xc1 (OP_TADD), the transaction MUST be rejected (ErrBadTxInput).

dcrd: internal/blockchain/validate.go · CheckTransactionInputs

Note

Treasury add and treasurybase OP_TADD outputs never enter the UTXO set (Rule 7.2). Rule 7.33 matters for regular outputs consisting of the single byte 0xc1 created before treasury activated, when 0xc1 was not a stake opcode: they become permanently unspendable on activation.

Rule 7.34 · Vote and revocation output maturity

If 𝑒’s script is tagged with OP_SSGEN (0xbb) or OP_SSRTX (0xbc), age MUST be at least 𝑀 (ErrImmatureSpend), where 𝑀=CoinbaseMaturity if treasury is active and 𝑀=SStxChangeMaturity (1 on every network) otherwise.

dcrd: internal/blockchain/validate.go · CheckTransactionInputs

History

Before the treasury agenda (DCP-0006), outputs of votes and revocations required only SStxChangeMaturity (1) confirmation, although dcrd’s comments have long described them as subject to coinbase maturity. The agenda raised the requirement to CoinbaseMaturity. Both forms are normative; the selection is by the agenda state of the block containing the spending transaction.

Rule 7.35 · Stake change maturity

If 𝑒’s script is tagged with OP_SSTXCHANGE (0xbd), age MUST be at least SStxChangeMaturity (ErrImmatureSpend). This covers ticket change outputs and treasury add change outputs.

dcrd: internal/blockchain/validate.go · CheckTransactionInputs

Rule 7.36 · Referenced amount range

𝑒.amount MUST satisfy 0≤𝑒.amount≤MaxAmount (ErrBadTxOutValue). (This cannot fail for entries created under Rule 7.7.)

dcrd: internal/blockchain/validate.go · CheckTransactionInputs

All maturity rules are independent: an input may be subject to several (for example a ticket change output of a ticket with a nonzero expiry needs both 1 and CoinbaseMaturity confirmations). Every maturity comparison is “age≥𝑀”, with age computed from the height of the block containing the spending transaction.

Table 7.8. All maturity requirements on spent outputs
Spent outputRequired ageRule
Coinbase outputCoinbaseMaturityRule 7.29
Any output of a transaction with nonzero expiryCoinbaseMaturityRule 7.30
OP_TGEN-tagged (treasury spend payouts), treasury activeCoinbaseMaturityRule 7.31
OP_SSGEN/OP_SSRTX-tagged, treasury activeCoinbaseMaturityRule 7.34
OP_SSGEN/OP_SSRTX-tagged, treasury inactiveSStxChangeMaturityRule 7.34
OP_SSTXCHANGE-taggedSStxChangeMaturityRule 7.35
Ticket output 0 spent by a voteTicketMaturity +1Chapter 8
Ticket output 0 spent by a revocationTicketMaturity +2, or +1 with autorevocationsChapter 8
Treasury balanceCoinbaseMaturityChapter 12

7.9.3 Spending across trees

Taken together, the rules above and the structural rules of the stake transactions determine which outputs each kind of transaction may spend (Table 7.9). Apart from the restrictions listed, an output of either tree may be spent by a transaction of either tree.

Table 7.9. Which spenders may consume which kinds of outputs (outside the same block)
Output kindWho may spend itRules
OP_SSTX-tagged (ticket output 0)Only a vote (as its input 1) or a revocation (as its input 0).Rule 7.32, Chapter 8
OP_SSTXCHANGE-tagged (ticket and treasury add change)Any transaction after SStxChangeMaturity.Rule 7.35
OP_SSGEN/OP_SSRTX-tagged (vote and revocation payouts)Any transaction after the maturity of Rule 7.34.Rule 7.34
OP_TGEN-tagged (treasury spend payouts)Any transaction after CoinbaseMaturity.Rule 7.31
Single-byte OP_TADD scriptNobody, once treasury is active.Rule 7.2, Rule 7.33
Coinbase outputsAny transaction after CoinbaseMaturity.Rule 7.29
Other outputsAny transaction, subject to the input rules of the spender’s type.—

Votes and revocations have no inputs other than the ticket (and, for votes, the stakebase); treasury spends and treasurybases have no real inputs. Tickets and treasury adds are therefore the only stake transactions that spend ordinary outputs. Tickets are further limited to version 0 outputs that are plain P2PKH or P2SH, or P2PKH or P2SH tagged with OP_SSGEN, OP_SSRTX or OP_SSTXCHANGE (so a ticket cannot spend an OP_TGEN output directly; Chapter 8). Treasury adds may spend any output permitted by the rules of this chapter.

7.9.4 Value and fee

Rule 7.37 · Input total

The input total is accumulated in a signed 64-bit integer, in input order, from the ValueIn of each input of Rule 7.25 items 2–4 and the entry amount 𝑒.amount of each other input. After each addition the accumulation MUST NOT have overflowed (signed overflow) and the running total MUST NOT exceed MaxAmount (ErrBadTxOutValue in both cases).

dcrd: internal/blockchain/validate.go · CheckTransactionInputs

Rule 7.38 · Outputs do not exceed inputs; fee

Let 𝐼 be the input total and 𝑂 the sum of the output amounts (bounded by Rule 7.7). The transaction MUST satisfy 𝐼≥𝑂 (ErrSpendTooHigh). Its fee is 𝐼−𝑂. There is no minimum fee in consensus. The coinbase’s fee is defined as 0. The block-level use of fees (the coinbase may claim them) is specified in Chapter 11.

dcrd: internal/blockchain/validate.go · CheckTransactionInputs

7.9.5 Delegated input rules

Table 7.10. Type-specific input rules specified in other chapters, in the order dcrd applies them before the per-input rules
TypeRulesChapter
CoinbaseValueIn equals the subsidy; output total bounded by subsidy plus fees; block-one ledger.Chapter 11
TicketEvery input spends an existing unspent version 0 P2PKH or P2SH output (plain, or tagged with OP_SSGEN, OP_SSRTX or OP_SSTXCHANGE); each commitment amount plus change equals its input amount (checkTicketPurchaseInputs). Ticket price versus header: Chapter 10.Chapter 8
VoteStakebase ValueIn equals the vote subsidy; input 1 spends output 0 of an unspent, mature ticket; payouts match the ticket’s commitments (checkVoteInputs); the ticket is a winner (block rule).Chapter 8
RevocationInput 0 spends output 0 of an unspent, mature ticket eligible for revocation; payouts match the commitments (checkRevocationInputs).Chapter 8
Treasury spendPublic key is a sanctioned Pi key (ErrUnknownPiKey); signature valid (ErrInvalidPiSignature); ValueIn in range and equal to the output 0 commitment (checkTreasurySpendInputs); voting, window and expenditure checks.Chapter 12
TreasurybaseValueIn equals the treasury subsidy; output structure.Chapter 12, Chapter 11

7.9.6 Algorithm

Algorithm 7.6 · Input validation and fee

COINBASE_MATURITY = params.coinbase_maturity
SSTX_CHANGE_MATURITY = params.sstx_change_maturity

def check_inputs(tx, h, view, treasury, auto_revocations, params) -> int:
    t = classify(tx, treasury)          # treasurybase tested before coinbase form
    if t == COINBASE:
        return 0                        # see subsidy chapter
    if t == TICKET:         staking.check_ticket_purchase_inputs(tx, view)
    if t == VOTE:           staking.check_vote_inputs(tx, h, view, ...)
    if t == REVOCATION:     staking.check_revocation_inputs(tx, h, view, ...)
    if t == TREASURY_SPEND: treasury.check_tspend_key_signature_and_value(tx)
    stake_out_maturity = COINBASE_MATURITY if treasury else SSTX_CHANGE_MATURITY
    total_in = 0                                      # int64
    for idx, txin in enumerate(tx.inputs):
        if idx == 0 and t in (VOTE, TREASURYBASE, TREASURY_SPEND):
            total_in = add_amount(total_in, txin.value_in)
            continue
        e = view.lookup(txin.prev_out)
        if e is None or e.spent:           reject("ErrMissingTxOut")
        if t in STAKE_TYPES and e.height == h \
                and not is_sbss_exception(params.net, h, txin.prev_out.hash):
            reject("ErrMissingTxOut")
        if e.amount == 0:                  reject("ErrZeroValueOutputSpend")
        if txin.value_in != e.amount:      reject("ErrFraudAmountIn")
        if txin.block_height != e.height:  reject("ErrFraudBlockHeight")
        if txin.block_index != e.index:    reject("ErrFraudBlockIndex")
        age = h - e.height
        if e.is_coinbase and age < COINBASE_MATURITY: reject("ErrImmatureSpend")
        if e.has_expiry and age < COINBASE_MATURITY:  reject("ErrExpiryTxSpentEarly")
        if treasury and tagged(e, 0xc3) and age < COINBASE_MATURITY:
            reject("ErrImmatureSpend")
        if t not in (VOTE, REVOCATION) and tagged(e, 0xba):
            reject("ErrTxSStxOutSpend")
        if treasury and e.script_version == 0 and e.pk_script == b"\xc1":
            reject("ErrBadTxInput")
        if (tagged(e, 0xbb) or tagged(e, 0xbc)) and age < stake_out_maturity:
            reject("ErrImmatureSpend")
        if tagged(e, 0xbd) and age < SSTX_CHANGE_MATURITY:
            reject("ErrImmatureSpend")
        if e.amount < 0 or e.amount > MAX_AMOUNT:
            reject("ErrBadTxOutValue")
        total_in = add_amount(total_in, e.amount)
    total_out = sum(out.value for out in tx.outputs)
    if total_in < total_out:
        reject("ErrSpendTooHigh")
    return total_in - total_out

def add_amount(total: int64, amount: int64) -> int64:
    s = int64(total + amount)                         # two's complement wrap
    if (s > total) != (amount > 0):  reject("ErrBadTxOutValue")   # overflow
    if s > MAX_AMOUNT:               reject("ErrBadTxOutValue")
    return s

def tagged(e, opcode) -> bool:
    s = e.pk_script
    return (e.script_version == 0 and len(s) >= 1 and s[0] == opcode
            and (is_p2pkh(s[1:]) or is_p2sh(s[1:])))

dcrd: internal/blockchain/validate.go · CheckTransactionInputs

7.10 Connecting Transactions and In-Block Spending

After a transaction passes input validation it is connected: the entries it spends are marked spent and entries for its outputs are created (Rule 7.2). The UTXO set against which a transaction is validated is the set as it stands at that moment, so the order of connection determines which outputs are available. The block-level orchestration is specified in Chapter 10; the consequences for a single transaction are stated here.

Rule 7.39 · Connection order and output availability

For a block 𝐵 at height ℎ, transactions are validated and connected in this order, starting from the UTXO set as of 𝐵’s parent:

  1. if ℎ>1 and 𝐵’s header disapproves its parent’s regular tree, the effects of that regular tree are undone first: its outputs are removed and the outputs it spent are restored (Chapter 10);
  2. the transactions of 𝐵’s stake tree, in order;
  3. the transactions of 𝐵’s regular tree, in order.

Each transaction is validated (Algorithm 7.6) against the set produced by all preceding steps and is then connected before the next is validated. Consequently:

  • an input MAY reference an output of an earlier transaction of the same tree or of a tree connected before, subject to all other rules;
  • an input referencing an output of the same transaction or of a later transaction in the block references a nonexistent entry and MUST be rejected;
  • two inputs anywhere in the block that spend the same output are a double spend: the second one to be connected references a spent entry and MUST be rejected.

dcrd: internal/blockchain/validate.go · checkConnectBlock, checkTransactionsAndConnect | internal/blockchain/utxoviewpoint.go · connectBlock

The combination of Rule 7.39 with the maturity and same-block rules yields the following availability matrix.

Table 7.11. May a transaction spend an output created in the same block?
SpenderCreatorVerdict
RegularEarlier regular transaction (not the coinbase)Yes, unless the creator has a nonzero expiry (Rule 7.30).
RegularCoinbaseNo: coinbase maturity.
RegularSame or later regular transactionNo: entry does not yet exist.
RegularStake transaction of the same blockThe entry exists, but every spendable stake output is tagged and subject to a maturity of at least SStxChangeMaturity =1 (OP_SSTX outputs are not spendable by regular transactions at all), so: no.
StakeAny transaction of the same blockNo (Rule 7.27), except Table 7.12.

Rationale

The stake tree is connected before the regular tree, and may not use outputs of the same block, because the next block’s votes may disapprove this block’s regular tree while its stake tree remains valid regardless. A stake transaction depending on the regular tree could otherwise be left spending outputs that no longer exist.

Implementation pitfall

Disapproval is applied before the current block’s stake tree is validated. Neither tree of a block that disapproves its parent can spend outputs created by the parent’s regular tree, and outputs that the parent’s regular transactions had spent are available again to both trees of the block.

7.10.1 Historical same-block stake spends

Rules enforced by earlier software versions allowed stake transactions in a handful of blocks to spend output 0 of a regular transaction of the same block. These blocks are part of the main and test chains and must remain valid.

Rule 7.40 · Historical same-block stake spend exceptions

On the networks and at the heights listed in Table 7.12, if the regular tree of the block at that height contains a transaction with the listed hash, then before the stake tree of that block is connected (and after any disapproval of the parent is applied), an entry for output 0 of that transaction is added to the UTXO set as if that transaction had been connected (height ℎ, index equal to its regular-tree position, subject to Rule 7.2). Rule 7.27 does not apply to inputs of that block that reference an output of the listed transaction (only output 0 is made available in this way). When the regular tree is later connected, the listed transaction’s outputs are created as usual, which sets output 0 unspent again even if a stake transaction spent it.

dcrd: internal/blockchain/validate.go · isSBSSViolation, CheckTransactionInputs | internal/blockchain/utxoviewpoint.go · addSBSSViolations

Table 7.12. Historical same-block stake spend exceptions (transaction hashes in display form)
NetworkHeightRegular transaction whose output 0 may be spent
mainnet11068170875ecdc5f12c8aa6ee0d54331fd5b5e786639882a3adb09882de5e3b939613b
mainnet1106831714e71358937cd33480fd2900853d43ea3440ca67b38bacdfeaeb0c37c80ee27
mainnet1106837aeba09a4efa334e3c13e68f27f40bd37cda7643c263f88d69f38a33c2cdacd18
mainnet110685417228266d9d6dd7084aa2e479319aca6d755c2a9d2dbb3cf28c8151470c7a439
mainnet110686020d6d3ed1b609f03969474dca1f452c25e035766457dfd58061f9b9270fc4e6d
mainnet11071955d2e1898fe0c631cb795b1906fb3cf8d9772f1826be8dea64dd3ab85ac0ab2d3
testnet31980161451b6eed1a777bc5bbb5c1dbe10a9e444cbeb7d863adb75fc6b7a676b3dcbb58

Implementation pitfall

The exception is keyed on the network, the height of the block being validated and the hash of the referenced transaction; it applies on side chains at those heights as well. After such a block, output 0 of the listed transaction is an unspent entry of the UTXO set, even though a stake transaction in the block consumed it (unless a regular transaction later in the same block spends it again). An implementation that marks it spent diverges from the reference UTXO set.

7.11 Signature Operations

Blocks limit the number of signature-checking operations they contain (Chapter 10). The limit is defined in terms of two per-transaction counts built on the script-level counting functions of Chapter 6: sigop_count, which counts OP_CHECKSIG-class opcodes in one script with the quick, imprecise method, and precise_p2sh_sigop_count, which, given a signature script and the P2SH output script it spends, counts the opcodes of the redeem script.

Algorithm 7.7 · Per-transaction signature operation counts

def basic_sigops(tx, is_coinbase, is_vote, treasury) -> uint32:
    if treasury and is_treasurybase(tx):
        return 0
    inputs = [] if is_coinbase else (tx.inputs[1:] if is_vote else tx.inputs)
    n = 0
    for txin in inputs:
        n = checked_add_u32(n, sigop_count(txin.sig_script, treasury))
    for out in tx.outputs:
        n = checked_add_u32(n, sigop_count(out.pk_script, treasury))
    return n

def p2sh_sigops(tx, is_coinbase, is_vote, view, treasury) -> uint32:
    if is_coinbase:
        return 0
    if treasury and (is_treasury_spend(tx) or is_treasurybase(tx)):
        return 0
    n = 0
    for txin in (tx.inputs[1:] if is_vote else tx.inputs):
        e = view.lookup(txin.prev_out)
        if e is None or e.spent: reject("ErrMissingTxOut")
        if not is_p2sh(e.pk_script):           # untagged 23-byte form only
            continue
        n = checked_add_u32(n, precise_p2sh_sigop_count(txin.sig_script,
                                                        e.pk_script, treasury))
    return n

def total_sigops(tx, is_coinbase, is_vote, view, treasury) -> uint32:
    return checked_add_u32(basic_sigops(tx, is_coinbase, is_vote, treasury),
                           p2sh_sigops(tx, is_coinbase, is_vote, view, treasury))
# checked_add_u32 rejects with ErrTooManySigOps on uint32 overflow.

dcrd: internal/blockchain/validate.go · countSigOps, countP2SHSigOps, CountTotalSigOps

The arguments is_coinbase and is_vote are derived differently at dcrd’s two call sites: from the form of the transaction for every transaction of both trees in the contextual check, and from its position (first of the regular tree; a vote in the stake tree) during connection. The two agree for every block that passes the other rules (Chapter 10).

No limit applies to a single transaction. Chapter 10 specifies the two block limits: the sum of basic_sigops over both trees, and, separately for each tree during connection, the running sum of total_sigops, each bounded by MaxSigOpsPerBlock (5000).

Implementation pitfall

p2sh_sigops recognizes only the untagged pay-to-script-hash form. Inputs spending stake-tagged P2SH outputs (for example OP_SSGEN followed by a P2SH script) contribute only their quick count from basic_sigops. During connection the p2sh_sigops lookup happens before the transaction is connected, against the same UTXO state as Algorithm 7.6.

7.12 Script Validation

Ownership of an output is proved by script execution: for each input, the signature script of the input and the output script of the referenced output are executed together by the script engine (Chapter 6). This section specifies which inputs are executed, with which parameters, and the effect of a failure.

Rule 7.41 · Inputs whose scripts are executed

For every transaction in both trees, every input whose outpoint index is not ffffffff (no UTXO entry can have that index) MUST have its scripts executed successfully, except that, if autorevocations is active, no input of a stake-tree transaction that is a revocation (is_revocation) with version at least 2 is executed. Inputs with index ffffffff (the null inputs of the coinbase, vote stakebase, treasurybase and treasury spend) are never executed. The treasury spend’s authorization is verified outside the script engine (Chapter 12).

dcrd: internal/blockchain/scriptval.go · checkBlockScripts | internal/blockchain/validate.go · checkConnectBlock

Rationale

Under DCP-0009, consensus already forces a version 2 revocation to pay exactly the amounts committed by the ticket to the committed addresses, with an empty signature script and no fee, so anyone may publish it and no signature is needed.

Rule 7.42 · Script execution parameters

An executed input 𝑖 of transaction 𝑇 spending entry 𝑒 is evaluated by the script engine with: output script 𝑒.script; script version 𝑒.script version (the version of the spent output, not of any output of 𝑇); the transaction 𝑇 and input index 𝑖 (for signature hashing); and the flag set 𝐹 of Table 7.13, determined by the agenda state of the block containing 𝑇. The entry is read from the UTXO set after the whole tree containing 𝑇 has been connected, ignoring its spent state.

dcrd: internal/blockchain/scriptval.go · validateHandler | internal/blockchain/validate.go · consensusScriptVerifyFlags

Table 7.13. Consensus script verification flags
FlagIncluded when
ScriptVerifyCleanStackAlways (from the genesis block).
ScriptVerifyCheckLockTimeVerifyAlways (from the genesis block).
ScriptVerifyCheckSequenceVerifylnfeatures is active.
ScriptVerifySHA256lnfeatures is active.
ScriptVerifyTreasurytreasury is active.
ScriptDiscourageUpgradableNopsNever in consensus (a policy flag, Chapter 17).
ScriptVerifySigPushOnlyNever in consensus, and not set by dcrd’s policy either, which checks for push-only signature scripts separately (Chapter 17).

The meaning of each flag is specified in Chapter 6.

Rule 7.43 · Script failure invalidates the block

If creating the script engine for an executed input fails (malformed scripts, a non-push-only signature script spending a P2SH-shaped output, and the other preconditions of Chapter 6; ErrScriptMalformed), or if execution fails (ErrScriptValidation), the block MUST be rejected. An output script with a nonzero script version passes execution once the engine is created (Chapter 6).

dcrd: internal/blockchain/scriptval.go · validateHandler

Note

dcrd validates scripts in parallel and caches verified signatures; the cache and the evaluation order have no effect on the verdict. dcrd skips script execution (and expiry and finality checks) for blocks that are ancestors of its configured assumed-valid block; that is a trust optimization described in Chapter 10, not a change to the rules.

7.13 Error Kinds

Table 7.14 maps each error kind of the reference implementation that arises from the rules of this chapter to the rule that produces it. Error kinds do not affect consensus; they are listed as a cross-check.

Table 7.14. Error kinds produced by the rules of this chapter
Error kindRule
ErrNoTxInputs, ErrNoTxOutputsRule 7.5
ErrTxTooBigRule 7.6
ErrBadTxOutValueRule 7.7, Rule 7.36, Rule 7.37
ErrFraudAmountInRule 7.8, Rule 7.3
ErrFraudBlockHeight, ErrFraudBlockIndexRule 7.3
ErrDuplicateTxInputsRule 7.9
ErrTxVersionTooHighRule 7.10
ErrScriptVersionTooHighRule 7.11
ErrRegTxCreateStakeOutRule 7.12
ErrScriptMalformedRule 7.12, Rule 7.43
ErrBadCoinbaseOutpoint, ErrBadCoinbaseFraudProof, ErrBadCoinbaseScriptLenRule 7.13
ErrBadStakebaseScriptLen, ErrBadStakebaseScrValRule 7.14
ErrInvalidRevocationTxVersionRule 7.15
ErrBadTreasurybaseOutpoint, ErrBadTreasurybaseFraudProof, ErrBadTreasurybaseScriptLenRule 7.16
ErrBadTSpendOutpoint, ErrBadTSpendFraudProof, ErrBadTSpendScriptLenRule 7.17
ErrInvalidTAddChangeRule 7.18
ErrBadTxInputRule 7.14, Rule 7.15, Rule 7.19, Rule 7.33
ErrStakeTxInRegularTree, ErrRegTxInStakeTree, ErrNonstandardStakeTxRule 7.4
ErrExpiredTxRule 7.20
ErrUnfinalizedTxRule 7.21, Rule 7.24
ErrMissingTxOutRule 7.1, Rule 7.2, Rule 7.26, Rule 7.27, Rule 7.23, Rule 7.39
ErrZeroValueOutputSpendRule 7.28
ErrImmatureSpendRule 7.29, Rule 7.31, Rule 7.34, Rule 7.35
ErrExpiryTxSpentEarlyRule 7.30
ErrTxSStxOutSpendRule 7.32
ErrSpendTooHighRule 7.38
ErrTooManySigOpsAlgorithm 7.7 (overflow); limits in Chapter 10
ErrScriptValidationRule 7.43