zips/rendered/zip-0112.html

309 lines
24 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<title>ZIP 112: CHECKSEQUENCEVERIFY</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1"><link rel="stylesheet" href="css/style.css"></head>
<body>
<section>
<pre>ZIP: 112
Title: CHECKSEQUENCEVERIFY
Author: Daira Hopwood &lt;daira@electriccoin.co&gt;
Credits: BtcDrak &lt;btcdrak@gmail.com&gt;
Mark Friedenbach &lt;mark@friedenbach.org&gt;
Eric Lombrozo &lt;elombrozo@gmail.com&gt;
Category: Consensus
Status: Draft
Created: 2019-06-06
License: MIT</pre>
<section id="terminology"><h2><span class="section-heading">Terminology</span><span class="section-anchor"> <a rel="bookmark" href="#terminology"><img width="24" height="24" class="section-anchor" src="assets/images/section-anchor.png" alt=""></a></span></h2>
<p>The key word "MUST" in this document is to be interpreted as described in RFC 2119. <a id="footnote-reference-1" class="footnote_reference" href="#rfc2119">1</a></p>
</section>
<section id="abstract"><h2><span class="section-heading">Abstract</span><span class="section-anchor"> <a rel="bookmark" href="#abstract"><img width="24" height="24" class="section-anchor" src="assets/images/section-anchor.png" alt=""></a></span></h2>
<p>This ZIP describes a new opcode (<code>CHECKSEQUENCEVERIFY</code>) for the Zcash scripting system, that in combination with ZIP 68 allows execution pathways of a script to be restricted based on the age of the output being spent.</p>
</section>
<section id="motivation"><h2><span class="section-heading">Motivation</span><span class="section-anchor"> <a rel="bookmark" href="#motivation"><img width="24" height="24" class="section-anchor" src="assets/images/section-anchor.png" alt=""></a></span></h2>
<p>ZIP 68 repurposes the transaction <code>nSequence</code> field meaning by giving sequence numbers new consensus-enforced semantics as a relative lock-time. However, there is no way to build Zcash scripts to make decisions based on this field.</p>
<p>By making the <code>nSequence</code> field accessible to script, it becomes possible to construct code pathways that only become accessible some minimum time after proof-of-publication. This enables a wide variety of applications in phased protocols such as escrow, payment channels, or bidirectional pegs.</p>
</section>
<section id="specification"><h2><span class="section-heading">Specification</span><span class="section-anchor"> <a rel="bookmark" href="#specification"><img width="24" height="24" class="section-anchor" src="assets/images/section-anchor.png" alt=""></a></span></h2>
<p><code>CHECKSEQUENCEVERIFY</code> redefines the existing <code>NOP3</code> opcode. When executed, if any of the following conditions are true, the script interpreter MUST terminate with an error:</p>
<ul>
<li>the stack is empty; or</li>
<li>the top item on the stack is less than 0; or</li>
<li>the top item on the stack has the disable flag (1 &lt;&lt; 31) unset; and any of the following hold:
<ul>
<li>the transaction version is less than 2; or</li>
<li>the transaction input sequence number disable flag (1 &lt;&lt; 31) is set; or</li>
<li>the relative lock-time type is not the same; or</li>
<li>the top stack item is greater than the transaction input sequence (when masked according to <a id="footnote-reference-2" class="footnote_reference" href="#zip-0068">4</a>;</li>
</ul>
</li>
</ul>
<p>Otherwise, script execution MUST continue as if a <code>NOP</code> had been executed.</p>
<p>ZIP 68 prevents a non-final transaction from being selected for inclusion in a block until the corresponding input has reached the specified age, as measured in block-height or block-time. By comparing the argument to <code>CHECKSEQUENCEVERIFY</code> against the <code>nSequence</code> field, we indirectly verify a desired minimum age of the the output being spent; until that relative age has been reached any script execution pathway including the <code>CHECKSEQUENCEVERIFY</code> will fail to validate, causing the transaction not to be selected for inclusion in a block.</p>
</section>
<section id="use-cases"><h2><span class="section-heading">Use cases</span><span class="section-anchor"> <a rel="bookmark" href="#use-cases"><img width="24" height="24" class="section-anchor" src="assets/images/section-anchor.png" alt=""></a></span></h2>
<section id="contracts-with-expiration-deadlines"><h3><span class="section-heading">Contracts With Expiration Deadlines</span><span class="section-anchor"> <a rel="bookmark" href="#contracts-with-expiration-deadlines"><img width="24" height="24" class="section-anchor" src="assets/images/section-anchor.png" alt=""></a></span></h3>
<section id="escrow-with-timeout"><h4><span class="section-heading">Escrow with Timeout</span><span class="section-anchor"> <a rel="bookmark" href="#escrow-with-timeout"><img width="24" height="24" class="section-anchor" src="assets/images/section-anchor.png" alt=""></a></span></h4>
<p>An escrow that times out automatically 30 days after being funded can be established in the following way. Alice, Bob and Escrow create a 2-of-3 address with the following redeem script:</p>
<pre>IF
2 &lt;Alice's pubkey&gt; &lt;Bob's pubkey&gt; &lt;Escrow's pubkey&gt; 3 CHECKMULTISIG
ELSE
"30d" CHECKSEQUENCEVERIFY DROP
&lt;Alice's pubkey&gt; CHECKSIG
ENDIF</pre>
<p>At any time funds can be spent using signatures from any two of Alice, Bob or the Escrow.</p>
<p>After 30 days Alice can sign alone.</p>
<p>The clock does not start ticking until the payment to the escrow address confirms.</p>
</section>
</section>
<section id="retroactive-invalidation"><h3><span class="section-heading">Retroactive Invalidation</span><span class="section-anchor"> <a rel="bookmark" href="#retroactive-invalidation"><img width="24" height="24" class="section-anchor" src="assets/images/section-anchor.png" alt=""></a></span></h3>
<p>In many instances, we would like to create contracts that can be revoked in case of some future event. However, given the immutable nature of the block chain, it is practically impossible to retroactively invalidate a previous commitment that has already confirmed. The only mechanism we really have for retroactive invalidation is block chain reorganization which, for fundamental security reasons, is designed to be very hard and very expensive to do.</p>
<p>Despite this limitation, we do have a way to provide something functionally similar to retroactive invalidation while preserving irreversibility of past commitments using <code>CHECKSEQUENCEVERIFY</code>. By constructing scripts with multiple branches of execution where one or more of the branches are delayed we provide a time window in which someone can supply an invalidation condition that allows the output to be spent, effectively invalidating the would-be delayed branch and potentially discouraging another party from broadcasting the transaction in the first place. If the invalidation condition does not occur before the timeout, the delayed branch becomes spendable, honoring the original contract.</p>
<p>Some more specific applications of this idea:</p>
<section id="hash-time-locked-contracts"><h4><span class="section-heading">Hash Time-Locked Contracts</span><span class="section-anchor"> <a rel="bookmark" href="#hash-time-locked-contracts"><img width="24" height="24" class="section-anchor" src="assets/images/section-anchor.png" alt=""></a></span></h4>
<p>Hash Time-Locked Contracts (HTLCs) provide a general mechanism for off-chain contract negotiation. An execution pathway can be made to require knowledge of a secret (a hash preimage) that can be presented within an invalidation time window. By sharing the secret it is possible to guarantee to the counterparty that the transaction will never be broadcast since this would allow the counterparty to claim the output immediately while one would have to wait for the time window to pass. If the secret has not been shared, the counterparty will be unable to use the instant pathway and the delayed pathway must be used instead.</p>
</section>
<section id="bidirectional-payment-channels"><h4><span class="section-heading">Bidirectional Payment Channels</span><span class="section-anchor"> <a rel="bookmark" href="#bidirectional-payment-channels"><img width="24" height="24" class="section-anchor" src="assets/images/section-anchor.png" alt=""></a></span></h4>
<p>Scriptable relative locktime provides a predictable amount of time to respond in the event a counterparty broadcasts a revoked transaction: Absolute locktime necessitates closing the channel and reopening it when getting close to the timeout, whereas with relative locktime, the clock starts ticking the moment the transaction confirms in a block. It also provides a means to know exactly how long to wait (in number of blocks) before funds can be pulled out of the channel in the event of a noncooperative counterparty.</p>
</section>
<section id="lightning-network"><h4><span class="section-heading">Lightning Network</span><span class="section-anchor"> <a rel="bookmark" href="#lightning-network"><img width="24" height="24" class="section-anchor" src="assets/images/section-anchor.png" alt=""></a></span></h4>
<p>The lightning network protocol <a id="footnote-reference-3" class="footnote_reference" href="#lightning">6</a> extends the bidirectional payment channel idea to allow for payments to be routed over multiple bidirectional payment channel hops.</p>
<p>These channels are based on an anchor transaction that requires a 2-of-2 multisig from Alice and Bob, and a series of revocable commitment transactions that spend the anchor transaction. The commitment transaction splits the funds from the anchor between Alice and Bob and the latest commitment transaction may be published by either party at any time, finalising the channel.</p>
<p>Ideally then, a revoked commitment transaction would never be able to be successfully spent; and the latest commitment transaction would be able to be spent very quickly.</p>
<p>To allow a commitment transaction to be effectively revoked, Alice and Bob have slightly different versions of the latest commitment transaction. In Alice's version, any outputs in the commitment transaction that pay Alice also include a forced delay, and an alternative branch that allows Bob to spend the output if he knows that transaction's revocation code. In Bob's version, payments to Bob are similarly encumbered. When Alice and Bob negotiate new balances and new commitment transactions, they also reveal the old revocation code, thus committing to not relaying the old transaction.</p>
<p>A simple output, paying to Alice might then look like:</p>
<pre>HASH160 &lt;revokehash&gt; EQUAL
IF
&lt;Bob's pubkey&gt;
ELSE
"24h" CHECKSEQUENCEVERIFY DROP
&lt;Alice's pubkey&gt;
ENDIF
CHECKSIG</pre>
<p>This allows Alice to publish the latest commitment transaction at any time and spend the funds after 24 hours, but also ensures that if Alice relays a revoked transaction, that Bob has 24 hours to claim the funds.</p>
<p>With <code>CHECKLOCKTIMEVERIFY</code>, this would look like:</p>
<pre>HASH160 &lt;revokehash&gt; EQUAL
IF
&lt;Bob's pubkey&gt;
ELSE
"2015/12/15" CHECKLOCKTIMEVERIFY DROP
&lt;Alice's pubkey&gt;
ENDIF
CHECKSIG</pre>
<p>This form of transaction would mean that if the anchor is unspent on 2015/12/16, Alice can use this commitment even if it has been revoked, simply by spending it immediately, giving no time for Bob to claim it.</p>
<p>This means that the channel has a deadline that cannot be pushed back without hitting the blockchain; and also that funds may not be available until the deadline is hit. <code>CHECKSEQUENCEVERIFY</code> allows you to avoid making such a tradeoff.</p>
<p>Hashed Time-Lock Contracts (HTLCs) make this slightly more complicated, since in principle they may pay either Alice or Bob, depending on whether Alice discovers a secret R, or a timeout is reached, but the same principle applies -- the branch paying Alice in Alice's commitment transaction gets a delay, and the entire output can be claimed by the other party if the revocation secret is known. With <code>CHECKSEQUENCEVERIFY</code>, a HTLC payable to Alice might look like the following in Alice's commitment transaction:</p>
<pre>HASH160 DUP &lt;R-HASH&gt; EQUAL
IF
"24h" CHECKSEQUENCEVERIFY
2DROP
&lt;Alice's pubkey&gt;
ELSE
&lt;Commit-Revocation-Hash&gt; EQUAL
NOTIF
"2015/10/20 10:33" CHECKLOCKTIMEVERIFY DROP
ENDIF
&lt;Bob's pubkey&gt;
ENDIF
CHECKSIG</pre>
<p>and correspondingly in Bob's commitment transaction:</p>
<pre>HASH160 DUP &lt;R-HASH&gt; EQUAL
SWAP &lt;Commit-Revocation-Hash&gt; EQUAL ADD
IF
&lt;Alice's pubkey&gt;
ELSE
"2015/10/20 10:33" CHECKLOCKTIMEVERIFY
"24h" CHECKSEQUENCEVERIFY
2DROP
&lt;Bob's pubkey&gt;
ENDIF
CHECKSIG</pre>
<p>Note that both <code>CHECKSEQUENCEVERIFY</code> and <code>CHECKLOCKTIMEVERIFY</code> are used in the final branch above to ensure Bob cannot spend the output until after both the timeout is complete and Alice has had time to reveal the revocation secret.</p>
<p>See also the 'Deployable Lightning' paper <a id="footnote-reference-4" class="footnote_reference" href="#deployable-lightning">5</a>.</p>
</section>
</section>
<section id="way-pegged-sidechains"><h3><span class="section-heading">2-Way Pegged Sidechains</span><span class="section-anchor"> <a rel="bookmark" href="#way-pegged-sidechains"><img width="24" height="24" class="section-anchor" src="assets/images/section-anchor.png" alt=""></a></span></h3>
<p>The 2-way pegged sidechain requires a new <code>REORGPROOFVERIFY</code> opcode, the semantics of which are outside the scope of this ZIP. <code>CHECKSEQUENCEVERIFY</code> is used to make sure that sufficient time has passed since the return peg was posted to publish a reorg proof:</p>
<pre>IF
lockTxHeight &lt;lockTxHash&gt; nlocktxOut [&lt;workAmount&gt;] reorgBounty Hash160(&lt;...&gt;) &lt;genesisHash&gt; REORGPROOFVERIFY
ELSE
withdrawLockTime CHECKSEQUENCEVERIFY DROP HASH160 p2shWithdrawDest EQUAL
ENDIF</pre>
</section>
</section>
<section id="reference-implementation"><h2><span class="section-heading">Reference Implementation</span><span class="section-anchor"> <a rel="bookmark" href="#reference-implementation"><img width="24" height="24" class="section-anchor" src="assets/images/section-anchor.png" alt=""></a></span></h2>
<!-- highlight::c++
/* 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 &lt;&lt; 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 &lt;&lt; 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 &amp; SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
// not enabled; treat as a NOP3
if (flags &amp; SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
}
break;
}
if (stack.size() &lt; 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 &lt; 0 due to
// some arithmetic being done first, you can always use
// 0 MAX CHECKSEQUENCEVERIFY.
if (nSequence &lt; 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 &amp; 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&amp; 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-&gt;vin[nIn].nSequence;
// Fail if the transaction's version number is not set high
// enough to trigger ZIP 68 rules.
if (static_cast&lt;uint32_t&gt;(txTo-&gt;nVersion) &lt; 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 &amp; 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 &amp; nLockTimeMask;
const CScriptNum nSequenceMasked = nSequence &amp; nLockTimeMask;
// There are two kinds of nSequence: lock-by-blockheight
// and lock-by-blocktime, distinguished by whether
// nSequenceMasked &lt; 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 &lt; CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG &amp;&amp; nSequenceMasked &lt; CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
(txToSequenceMasked &gt;= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG &amp;&amp; nSequenceMasked &gt;= 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 &gt; txToSequenceMasked)
return false;
return true;
} -->
</section>
<section id="deployment"><h2><span class="section-heading">Deployment</span><span class="section-anchor"> <a rel="bookmark" href="#deployment"><img width="24" height="24" class="section-anchor" src="assets/images/section-anchor.png" alt=""></a></span></h2>
<p>At the time of writing it has not been decided which network upgrade (if any) will implement this proposal.</p>
<p>This ZIP must be deployed simultaneously with ZIP 68 <a id="footnote-reference-5" class="footnote_reference" href="#zip-0068">4</a>.</p>
</section>
<section id="acknowledgements"><h2><span class="section-heading">Acknowledgements</span><span class="section-anchor"> <a rel="bookmark" href="#acknowledgements"><img width="24" height="24" class="section-anchor" src="assets/images/section-anchor.png" alt=""></a></span></h2>
<p>This ZIP is closely based on BIP 112, authored by BtcDrak.</p>
<p>Mark Friedenbach invented the application of sequence numbers to achieve relative lock-time, and wrote the reference implementation of <code>CHECKSEQUENCEVERIFY</code> for Bitcoin.</p>
<p>The Bitcoin reference implementation and BIP 112 was based heavily on work done by Peter Todd for the closely related BIP 65. Eric Lombrozo and Anthony Towns contributed example use cases.</p>
</section>
<section id="references"><h2><span class="section-heading">References</span><span class="section-anchor"> <a rel="bookmark" href="#references"><img width="24" height="24" class="section-anchor" src="assets/images/section-anchor.png" alt=""></a></span></h2>
<table id="rfc2119" class="footnote">
<tbody>
<tr>
<th>1</th>
<td><a href="https://tools.ietf.org/html/rfc2119">Key words for use in RFCs to Indicate Requirement Levels</a></td>
</tr>
</tbody>
</table>
<table id="protocol" class="footnote">
<tbody>
<tr>
<th>2</th>
<td><a href="https://github.com/zcash/zips/blob/master/protocol/protocol.pdf">Zcash Protocol Specification, Version 2019.0.1 or later [Overwinter+Sapling]</a></td>
</tr>
</tbody>
</table>
<table id="bip-0065" class="footnote">
<tbody>
<tr>
<th>3</th>
<td><a href="https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki">BIP 65: OP_CHECKLOCKTIMEVERIFY</a></td>
</tr>
</tbody>
</table>
<table id="zip-0068" class="footnote">
<tbody>
<tr>
<th>4</th>
<td><a href="https://github.com/zcash/zips/blob/op-csv/zip-0068.rst">ZIP 68: Relative lock-time through consensus-enforced sequence numbers</a></td>
</tr>
</tbody>
</table>
<table id="deployable-lightning" class="footnote">
<tbody>
<tr>
<th>5</th>
<td><a href="https://github.com/ElementsProject/lightning/blob/master/doc/deployable-lightning.pdf">Deployable Lightning</a></td>
</tr>
</tbody>
</table>
<table id="lightning" class="footnote">
<tbody>
<tr>
<th>6</th>
<td><a href="http://lightning.network/lightning-network-paper.pdf">Lightning Network paper</a></td>
</tr>
</tbody>
</table>
<table id="htlcs" class="footnote">
<tbody>
<tr>
<th>7</th>
<td><a href="http://lists.linuxfoundation.org/pipermail/lightning-dev/2015-July/000021.html">HTLCs using OP_CHECKSEQUENCEVERIFY/OP_LOCKTIMEVERIFY and revocation hashes</a></td>
</tr>
</tbody>
</table>
<table id="scaling" class="footnote">
<tbody>
<tr>
<th>8</th>
<td><a href="http://diyhpl.us/diyhpluswiki/transcripts/sf-bitcoin-meetup/2015-02-23-scaling-bitcoin-to-billions-of-transactions-per-day/">Scaling Bitcoin to Billions of Transactions Per Day</a></td>
</tr>
</tbody>
</table>
<table id="micropayments" class="footnote">
<tbody>
<tr>
<th>9</th>
<td><a href="https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2013-April/002433.html">Jeremy Spilman, Micropayment Channels</a></td>
</tr>
</tbody>
</table>
</section>
</section>
</body>
</html>