This page is the Simplified Technical English version of ZIP 112. The source ZIP is the normative text. Read the writing rules to understand the marked words.
ZIP 112: CHECKSEQUENCEVERIFY
ZIP: 112
Title: CHECKSEQUENCEVERIFY
Owners: Daira-Emma Hopwood <daira@jacaranda.org>
Credits: BtcDrak
Mark Friedenbach
Eric Lombrozo
Category: Consensus
Status: Draft
Created: 2019-06-06
License: MIT
Terminology
On this page, STE words are in the place of the BCP 14 key words of the source. Refer to the key word table.
Abstract
This ZIP contains the description of a new opcode, CHECKSEQUENCEVERIFY, for the Zcash scripting system. With this opcode and ZIP 68, the execution paths of a script can be restricted according to the age of the output that is spent.
Motivation
ZIP 68 contains a new meaning for the transaction nSequence field. In this meaning, a sequence number is a relative lock-time, and this meaning is enforced by consensus. But in a Zcash script, it is not possible to make a decision from the value of this field.
If a script has access to the nSequence field, it is possible to make execution paths that become available only some minimum time after proof-of-publication. Thus a wide range of applications in phased protocols becomes possible. Examples of these protocols are:
- Escrow.
- Payment channels.
- Bidirectional pegs.
Specification
CHECKSEQUENCEVERIFY is a new definition of the existing NOP3 opcode. When the script interpreter executes it, the script interpreter must stop with an error if one or more of these conditions are true:
- The stack is empty.
- The top item on the stack is less than 0.
- The top item on the stack has the disable flag (
1 << 31) unset, and one or more of these conditions are true:- The transaction version is less than 2.
- The disable flag (
1 << 31) of the sequence number of the transaction input is set. - The relative lock-time type is not the same.
- The top stack item is greater than the sequence number of the transaction input (when masked as in ZIP 68 [zip-0068]).
Otherwise, script execution must continue as if a NOP was executed.
In ZIP 68, a non-final transaction cannot be selected for inclusion in a block until the related input reaches the specified age. This age is measured in block height or in block time.
We compare the argument of CHECKSEQUENCEVERIFY with the nSequence field. Thus we indirectly verify a minimum age that we want for the output that is spent. Until the output has that relative age, each script execution path that includes the CHECKSEQUENCEVERIFY will fail validation. As a result, the transaction will not be selected for inclusion in a block.
Use cases
Contracts With Expiration Deadlines
Escrow with Timeout
An escrow can have an automatic timeout 30 days after it is funded. To set up this escrow, Alice, Bob and Escrow create a 2-of-3 address with this redeem script:
IF
2 <Alice's pubkey> <Bob's pubkey> <Escrow's pubkey> 3 CHECKMULTISIG
ELSE
"30d" CHECKSEQUENCEVERIFY DROP
<Alice's pubkey> CHECKSIG
ENDIF
At any time, the funds can be spent with the signatures of any two of the three parties.
After 30 days, Alice can sign alone.
The 30-day period starts when the payment to the escrow address is confirmed.
Retroactive Invalidation
In many cases, we want to make contracts that can be revoked if a specified event occurs in the future. But the block chain is immutable. Thus, in practice, it is impossible to retroactively make a previous commitment invalid after it is confirmed. The only real mechanism that we have for retroactive invalidation is a block chain reorganization. For basic security reasons, a reorganization is very hard and very expensive by design.
But with CHECKSEQUENCEVERIFY, we have a method with a function similar to retroactive invalidation. With this method, past commitments stay irreversible.
We make scripts with more than one execution branch, and one or more of these branches have a delay. With such a script, there is a time window. In this time window, someone can supply an invalidation condition. If this condition is supplied, the output can be spent. In effect, the branch that has the delay then becomes invalid. Also, another party is possibly discouraged from broadcasting the transaction at all.
If the invalidation condition does not occur before the timeout, the delayed branch becomes spendable. Thus the terms of the original contract are obeyed.
Some more specific applications of this idea follow.
Hash Time-Locked Contracts
Hash Time-Locked Contracts (HTLCs) are a general mechanism for off-chain contract negotiation. It is possible to make an execution path that is usable only with the knowledge of a secret (a hash preimage). The secret can be presented in an invalidation time window.
A party can share the secret with the counterparty. Then the counterparty can be sure that the transaction will never be broadcast. The reason is as follows. After a broadcast, the counterparty can claim the output immediately. But the party that shared the secret can claim the output only after the time window ends.
If the secret is not shared, the counterparty cannot use the instant path. Then the delayed path must be used.
Bidirectional Payment Channels
With scriptable relative lock-time, there is a predictable amount of time to respond if a counterparty broadcasts a revoked transaction. With absolute lock-time, it is necessary to close the channel and open it again when the timeout is near. With relative lock-time, the time period starts when the transaction is confirmed in a block.
Relative lock-time also has this advantage if a counterparty does not cooperate: it is possible to know exactly how long to wait before the funds can be removed from the channel. This wait is a number of blocks.
Lightning Network
The lightning network protocol [lightning] is an extension of the bidirectional payment channel idea. In this protocol, payments can be routed over more than one bidirectional payment channel hop.
These channels are based on these items:
- An anchor transaction that is spendable only with a 2-of-2 multisig from Alice and Bob.
- A series of revocable commitment transactions that spend the anchor transaction.
In the commitment transaction, the funds from the anchor are divided between Alice and Bob. Either party can publish the latest commitment transaction at any time. When a party publishes it, the channel becomes final.
Thus, in the ideal case, it is never possible to spend a revoked commitment transaction successfully. Also in the ideal case, it is possible to spend the latest commitment transaction very quickly.
To let a commitment transaction be revoked in effect, Alice and Bob have slightly different versions of the latest commitment transaction. In Alice's version, each output in the commitment transaction that pays Alice also includes these items:
- A forced delay.
- An alternative branch. With this branch, Bob can spend the output if he knows the revocation code of that transaction.
In Bob's version, payments to Bob are encumbered in a similar way. When Alice and Bob negotiate new balances and new commitment transactions, they also reveal the old revocation code. Thus they commit that they will not relay the old transaction.
Thus a simple output that pays Alice can look like this:
HASH160 <revokehash> EQUAL
IF
<Bob's pubkey>
ELSE
"24h" CHECKSEQUENCEVERIFY DROP
<Alice's pubkey>
ENDIF
CHECKSIG
With this output, Alice can publish the latest commitment transaction at any time. She can then spend the funds after 24 hours. Also, if Alice relays a revoked transaction, it is certain that Bob has 24 hours to claim the funds.
With CHECKLOCKTIMEVERIFY, this output can look like this:
HASH160 <revokehash> EQUAL
IF
<Bob's pubkey>
ELSE
"2015/12/15" CHECKLOCKTIMEVERIFY DROP
<Alice's pubkey>
ENDIF
CHECKSIG
With this form of transaction, if the anchor is unspent on 2015/12/16, Alice can use this commitment even if it is revoked. To do this, she simply spends it immediately. Then Bob has no time to claim it.
Thus the channel has a deadline that can be moved later only with an action on the block chain. Also, the funds can be unavailable until the deadline. With CHECKSEQUENCEVERIFY, you can avoid such a compromise.
With Hashed Time-Lock Contracts (HTLCs), this is slightly more complicated. In principle, an HTLC can be payable to Alice or to Bob. This depends on if Alice discovers a secret R, or if a timeout occurs. But the same principle applies:
- In Alice's commitment transaction, the branch that pays Alice has a delay.
- If the revocation secret is known, the other party can claim the entire output.
With CHECKSEQUENCEVERIFY, an HTLC payable to Alice can look like this in Alice's commitment transaction:
HASH160 DUP <R-HASH> EQUAL
IF
"24h" CHECKSEQUENCEVERIFY
2DROP
<Alice's pubkey>
ELSE
<Commit-Revocation-Hash> EQUAL
NOTIF
"2015/10/20 10:33" CHECKLOCKTIMEVERIFY DROP
ENDIF
<Bob's pubkey>
ENDIF
CHECKSIG
The corresponding HTLC in Bob's commitment transaction can look like this:
HASH160 DUP <R-HASH> EQUAL
SWAP <Commit-Revocation-Hash> EQUAL ADD
IF
<Alice's pubkey>
ELSE
"2015/10/20 10:33" CHECKLOCKTIMEVERIFY
"24h" CHECKSEQUENCEVERIFY
2DROP
<Bob's pubkey>
ENDIF
CHECKSIG
Note: Both CHECKSEQUENCEVERIFY and CHECKLOCKTIMEVERIFY are used in the final branch above. They are used to make sure that Bob can spend the output only after these two conditions are true:
- The timeout is complete.
- Alice had time to reveal the revocation secret.
Refer also to the paper 'Deployable Lightning' [deployable-lightning].
2-Way Pegged Sidechains
For the 2-way pegged sidechain, a new opcode, REORGPROOFVERIFY, is necessary. The semantics of this opcode are outside the scope of this ZIP. CHECKSEQUENCEVERIFY is used to make sure that, after the return peg was posted, sufficient time passed to publish a reorg proof:
IF
lockTxHeight <lockTxHash> nlocktxOut [<workAmount>] reorgBounty Hash160(<...>) <genesisHash> REORGPROOFVERIFY
ELSE
withdrawLockTime CHECKSEQUENCEVERIFY DROP HASH160 p2shWithdrawDest EQUAL
ENDIF
Reference Implementation
/* Below flags apply in the context of ZIP 68 */
/* If this flag set, CTxIn::nSequence is NOT interpreted as a
* relative lock-time. */
static const uint32_t SEQUENCE_LOCKTIME_DISABLE_FLAG = (1 << 31);
/* If CTxIn::nSequence encodes a relative lock-time and this flag
* is set, the relative lock-time has units of 512 seconds,
* otherwise it specifies blocks with a granularity of 1. */
static const uint32_t SEQUENCE_LOCKTIME_TYPE_FLAG = (1 << 22);
/* If CTxIn::nSequence encodes a relative lock-time, this mask is
* applied to extract that lock-time from the sequence field. */
static const uint32_t SEQUENCE_LOCKTIME_MASK = 0x0000ffff;
case OP_NOP3:
{
if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
// not enabled; treat as a NOP3
if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
}
break;
}
if (stack.size() < 1)
return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
// Note that elsewhere numeric opcodes are limited to
// operands in the range -2**31+1 to 2**31-1, however it is
// legal for opcodes to produce results exceeding that
// range. This limitation is implemented by CScriptNum's
// default 4-byte limit.
//
// Thus as a special case we tell CScriptNum to accept up
// to 5-byte bignums, which are good until 2**39-1, well
// beyond the 2**32-1 limit of the nSequence field itself.
const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5);
// In the rare event that the argument may be < 0 due to
// some arithmetic being done first, you can always use
// 0 MAX CHECKSEQUENCEVERIFY.
if (nSequence < 0)
return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
// To provide for future soft-fork extensibility, if the
// operand has the disabled lock-time flag set,
// CHECKSEQUENCEVERIFY behaves as a NOP.
if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
break;
// Compare the specified sequence number with the input.
if (!checker.CheckSequence(nSequence))
return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
break;
}
bool TransactionSignatureChecker::CheckSequence(const CScriptNum& nSequence) const
{
// Relative lock times are supported by comparing the passed
// in operand to the sequence number of the input.
const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
// Fail if the transaction's version number is not set high
// enough to trigger ZIP 68 rules.
if (static_cast<uint32_t>(txTo->nVersion) < 2)
return false;
// Sequence numbers with their most significant bit set are not
// consensus constrained. Testing that the transaction's sequence
// number do not have this bit set prevents using this property
// to get around a CHECKSEQUENCEVERIFY check.
if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
return false;
// Mask off any bits that do not have consensus-enforced meaning
// before doing the integer comparisons
const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
// There are two kinds of nSequence: lock-by-blockheight
// and lock-by-blocktime, distinguished by whether
// nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
//
// We want to compare apples to apples, so fail the script
// unless the type of nSequenceMasked being tested is the same as
// the nSequenceMasked in the transaction.
if (!(
(txToSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
(txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
))
return false;
// Now that we know we're comparing apples-to-apples, the
// comparison is a simple numeric one.
if (nSequenceMasked > txToSequenceMasked)
return false;
return true;
}
Deployment
At the time of writing, the network upgrade for this ZIP was not decided. Possibly no network upgrade will include this ZIP.
This ZIP must be deployed at the same time as ZIP 68 [zip-0068].
Acknowledgements
This ZIP is closely based on BIP 112. BtcDrak wrote BIP 112.
Mark Friedenbach invented the use of sequence numbers for relative lock-time. He also wrote the reference implementation of CHECKSEQUENCEVERIFY for Bitcoin.
The Bitcoin reference implementation and BIP 112 were based heavily on the work of Peter Todd for BIP 65. BIP 65 is closely related. Eric Lombrozo and Anthony Towns gave example use cases.
References
- [RFC2119]
- Key words for use in RFCs to Indicate Requirement Levels
- [protocol]
- Zcash Protocol Specification, Version 2019.0.1 or later [Overwinter+Sapling]
- [bip-0065]
- BIP 65: OP_CHECKLOCKTIMEVERIFY
- [zip-0068]
- ZIP 68: Relative lock-time through consensus-enforced sequence numbers
- [deployable-lightning]
- Deployable Lightning
- [lightning]
- Lightning Network paper
- [HTLCs]
- HTLCs using OP_CHECKSEQUENCEVERIFY/OP_LOCKTIMEVERIFY and revocation hashes
- [scaling]
- Scaling Bitcoin to Billions of Transactions Per Day
- [micropayments]
- Jeremy Spilman, Micropayment Channels