You've already forked specification
wiki commit
This commit is contained in:
committed by
buwiki
parent
010556df4d
commit
adc4dd512f
@@ -0,0 +1 @@
|
||||
empty page
|
||||
@@ -46,19 +46,19 @@
|
||||
- N-of-M Multisig Signatures
|
||||
- [Memory Pool](/protocol/blockchain/memory-pool)
|
||||
- Forks
|
||||
- Bip-16
|
||||
- [Bip-16](/protocol/forks/bip-0016)
|
||||
- [Bip-34](/protocol/forks/bip-0034)
|
||||
- [Bip-37](/protocol/forks/bip-0037)
|
||||
- [Bip-64](/protocol/forks/bip-0064)
|
||||
- Bip-65
|
||||
- Bip-66
|
||||
- Bip-68
|
||||
- Bip-112
|
||||
- Bip-113
|
||||
- [Bip-65](/protocol/forks/bip-0065)
|
||||
- [Bip-66](/protocol/forks/bip-0066)
|
||||
- [Bip-68](/protocol/forks/bip-0068)
|
||||
- [Bip-112](/protocol/forks/bip-0112)
|
||||
- [Bip-113](/protocol/forks/bip-0113)
|
||||
- [Bip-157](/protocol/forks/bip-0157)
|
||||
- [Bip-158](/protocol/forks/bip-0158)
|
||||
- [Bip-159](/protocol/forks/bip-0159)
|
||||
- BCH-UAHF (BUIP-55)
|
||||
- [BCH-UAHF]((/protocol/forks/bch-uahf)) (BUIP-55)
|
||||
- [HF-20171113](/protocol/forks/hf-20171113)
|
||||
- HF-20180515
|
||||
- HF-20181115
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
<pre>
|
||||
BIP: 16
|
||||
Layer: Consensus (soft fork)
|
||||
Title: Pay to Script Hash
|
||||
Author: Gavin Andresen <gavinandresen@gmail.com>
|
||||
Comments-Summary: No comments yet.
|
||||
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0016
|
||||
Status: Final
|
||||
Type: Standards Track
|
||||
Created: 2012-01-03
|
||||
</pre>
|
||||
|
||||
## Abstract
|
||||
|
||||
This BIP describes a new "standard" transaction type for the Bitcoin scripting system, and defines additional validation rules that apply only to the new transactions.
|
||||
|
||||
## Motivation
|
||||
|
||||
The purpose of pay-to-script-hash is to move the responsibility for supplying the conditions to redeem a transaction from the sender of the funds to the redeemer.
|
||||
|
||||
The benefit is allowing a sender to fund any arbitrary transaction, no matter how complicated, using a fixed-length 20-byte hash that is short enough to scan from a QR code or easily copied and pasted.
|
||||
|
||||
## Specification
|
||||
|
||||
A new standard transaction type that is relayed and included in mined blocks is defined:
|
||||
|
||||
OP_HASH160 [20-byte-hash-value] OP_EQUAL
|
||||
|
||||
[20-byte-hash-value] shall be the push-20-bytes-onto-the-stack opcode (0x14) followed by exactly 20 bytes.
|
||||
|
||||
This new transaction type is redeemed by a standard scriptSig:
|
||||
|
||||
...signatures... {serialized script}
|
||||
|
||||
Transactions that redeem these pay-to-script outpoints are only considered standard if the ''serialized script'' - also referred to as the ''redeemScript'' - is, itself, one of the other standard transaction types.
|
||||
|
||||
The rules for validating these outpoints when relaying transactions or considering them for inclusion in a new block are as follows:
|
||||
|
||||
1. Validation fails if there are any operations other than "push data" operations in the scriptSig.
|
||||
2. Normal validation is done: an initial stack is created from the signatures and {serialized script}, and the hash of the script is computed and validation fails immediately if it does not match the hash in the outpoint.
|
||||
3. {serialized script} is popped off the initial stack, and the transaction is validated again using the popped stack and the deserialized script as the scriptPubKey.
|
||||
|
||||
These new rules should only be applied when validating transactions in blocks with timestamps >= 1333238400 (Apr 1 2012) [Remove -bip16 and -paytoscripthashtime command-line arguments](https://github.com/bitcoin/bitcoin/commit/8f188ece3c82c4cf5d52a3363e7643c23169c0ff). There are transactions earlier than 1333238400 in the block chain that fail these new validation rules. [Transaction 6a26d2ecb67f27d1fa5524763b49029d7106e91e3cc05743073461a719776192](http://blockexplorer.com/tx/6a26d2ecb67f27d1fa5524763b49029d7106e91e3cc05743073461a719776192). Older transactions must be validated under the old rules. (see the Backwards Compatibility section for details).
|
||||
|
||||
For example, the scriptPubKey and corresponding scriptSig for a one-signature-required transaction is:
|
||||
|
||||
scriptSig: [signature] {[pubkey] OP_CHECKSIG}
|
||||
scriptPubKey: OP_HASH160 [20-byte-hash of {[pubkey] OP_CHECKSIG} ] OP_EQUAL
|
||||
|
||||
Signature operations in the {serialized script} shall contribute to the maximum number allowed per block (20,000) as follows:
|
||||
|
||||
1. OP_CHECKSIG and OP_CHECKSIGVERIFY count as 1 signature operation, whether or not they are evaluated.
|
||||
2. OP_CHECKMULTISIG and OP_CHECKMULTISIGVERIFY immediately preceded by OP_1 through OP_16 are counted as 1 to 16 signature operation, whether or not they are evaluated.
|
||||
3. All other OP_CHECKMULTISIG and OP_CHECKMULTISIGVERIFY are counted as 20 signature operations.
|
||||
|
||||
Examples:
|
||||
|
||||
+3 signature operations:
|
||||
{2 [pubkey1] [pubkey2] [pubkey3] 3 OP_CHECKMULTISIG}
|
||||
|
||||
+22 signature operations
|
||||
{OP_CHECKSIG OP_IF OP_CHECKSIGVERIFY OP_ELSE OP_CHECKMULTISIGVERIFY OP_ENDIF}
|
||||
|
||||
## Rationale
|
||||
|
||||
This BIP replaces BIP 12, which proposed a new Script opcode ("OP_EVAL") to accomplish everything in this BIP and more.
|
||||
|
||||
The Motivation for this BIP (and BIP 13, the pay-to-script-hash address type) is somewhat controversial; several people feel that it is unnecessary, and complex/multisignature transaction types should be supported by simply giving the sender the complete {serialized script}. The author believes that this BIP will minimize the changes needed to all of the supporting infrastructure that has already been created to send funds to a base58-encoded-20-byte bitcoin addresses, allowing merchants and exchanges and other software to start supporting multisignature transactions sooner.
|
||||
|
||||
Recognizing one 'special' form of scriptPubKey and performing extra validation when it is detected is ugly. However, the consensus is that the alternatives are either uglier, are more complex to implement, and/or expand the power of the expression language in dangerous ways.
|
||||
|
||||
The signature operation counting rules are intended to be easy and quick to implement by statically scanning the {serialized script}. Bitcoin imposes a maximum-number-of-signature-operations per block to prevent denial-of-service attacks on miners. If there was no limit, a rogue miner might broadcast a block that required hundreds of thousands of ECDSA signature operations to validate, and it might be able to get a head start computing the next block while the rest of the network worked to validate the current one.
|
||||
|
||||
There is a 1-confirmation attack on old implementations, but it is expensive and difficult in practice. The attack is:
|
||||
|
||||
1. Attacker creates a pay-to-script-hash transaction that is valid as seen by old software, but invalid for new implementation, and sends themselves some coins using it.
|
||||
2. Attacker also creates a standard transaction that spends the pay-to-script transaction, and pays the victim who is running old software.
|
||||
3. Attacker mines a block that contains both transactions.
|
||||
|
||||
If the victim accepts the 1-confirmation payment, then the attacker wins because both transactions will be invalidated when the rest of the network overwrites the attacker's invalid block.
|
||||
|
||||
The attack is expensive because it requires the attacker create a block that they know will be invalidated by the rest of the network. It is difficult because creating blocks is difficult and users should not accept 1-confirmation transactions for higher-value transactions.
|
||||
|
||||
## Backwards Compatibility
|
||||
|
||||
These transactions are non-standard to old implementations, which will (typically) not relay them or include them in blocks.
|
||||
|
||||
Old implementations will validate that the {serialize script}'s hash value matches when they validate blocks created by software that fully support this BIP, but will do no other validation.
|
||||
|
||||
Avoiding a block-chain split by malicious pay-to-script transactions requires careful handling of one case:
|
||||
|
||||
* A pay-to-script-hash transaction that is invalid for new clients/miners but valid for old clients/miners.
|
||||
|
||||
To gracefully upgrade and ensure no long-lasting block-chain split occurs, more than 50% of miners must support full validation of the new transaction type and must switch from the old validation rules to the new rules at the same time.
|
||||
|
||||
To judge whether or not more than 50% of hashing power supports this BIP, miners are asked to upgrade their software and put the string "/P2SH/" in the input of the coinbase transaction for blocks that they create.
|
||||
|
||||
On February 1, 2012, the block-chain will be examined to determine the number of blocks supporting pay-to-script-hash for the previous 7 days. If 550 or more contain "/P2SH/" in their coinbase, then all blocks with timestamps after 15 Feb 2012, 00:00:00 GMT shall have their pay-to-script-hash transactions fully validated. Approximately 1,000 blocks are created in a week; 550 should, therefore, be approximately 55% of the network supporting the new feature.
|
||||
|
||||
If a majority of hashing power does not support the new validation rules, then rollout will be postponed (or rejected if it becomes clear that a majority will never be achieved).
|
||||
|
||||
### 520-byte limitation on serialized script size
|
||||
|
||||
As a consequence of the requirement for backwards compatibility the serialized script is itself subject to the same rules as any other PUSHDATA operation, including the rule that no data greater than 520 bytes may be pushed to the stack. Thus it is not possible to spend a P2SH output if the redemption script it refers to is >520 bytes in length. For instance while the OP_CHECKMULTISIG opcode can itself accept up to 20 pubkeys, with 33-byte compressed pubkeys it is only possible to spend a P2SH output requiring a maximum of 15 pubkeys to redeem: 3 bytes + 15 pubkeys * 34 bytes/pubkey = 513 bytes.
|
||||
|
||||
|
||||
## Reference Implementation
|
||||
|
||||
https://gist.github.com/gavinandresen/3966071
|
||||
|
||||
## See Also
|
||||
|
||||
* https://bitcointalk.org/index.php?topic=46538
|
||||
* The [Address format for Pay to Script Hash BIP](/protocol/forks/bip-0013)
|
||||
* M-of-N Multisignature Transactions [BIP 11](/protocol/forks/bip-0011)
|
||||
* [Quality Assurance test checklist](https://github.com/bitcoin/bips/blob/master/bip-0016/qa.mediawiki)
|
||||
|
||||
## References
|
||||
|
||||
(inlined above)
|
||||
@@ -0,0 +1,337 @@
|
||||
<pre>
|
||||
BIP: 65
|
||||
Layer: Consensus (soft fork)
|
||||
Title: OP_CHECKLOCKTIMEVERIFY
|
||||
Author: Peter Todd <pete@petertodd.org>
|
||||
Comments-Summary: No comments yet.
|
||||
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0065
|
||||
Status: Final
|
||||
Type: Standards Track
|
||||
Created: 2014-10-01
|
||||
License: PD
|
||||
</pre>
|
||||
|
||||
## Abstract
|
||||
|
||||
This BIP describes a new opcode (OP_CHECKLOCKTIMEVERIFY) for the Bitcoin
|
||||
scripting system that allows a transaction output to be made unspendable until
|
||||
some point in the future.
|
||||
|
||||
|
||||
## Summary
|
||||
|
||||
CHECKLOCKTIMEVERIFY redefines the existing NOP2 opcode. When executed, if
|
||||
any of the following conditions are true, the script interpreter will terminate
|
||||
with an error:
|
||||
|
||||
* the stack is empty; or
|
||||
* the top item on the stack is less than 0; or
|
||||
* the lock-time type (height vs. timestamp) of the top stack item and the nLockTime field are not the same; or
|
||||
* the top stack item is greater than the transaction's nLockTime field; or
|
||||
* the nSequence field of the txin is 0xffffffff;
|
||||
|
||||
Otherwise, script execution will continue as if a NOP had been executed.
|
||||
|
||||
The nLockTime field in a transaction prevents the transaction from being mined
|
||||
until either a certain block height, or block time, has been reached. By
|
||||
comparing the argument to CHECKLOCKTIMEVERIFY against the nLockTime field, we
|
||||
indirectly verify that the desired block height or block time has been reached;
|
||||
until that block height or block time has been reached the transaction output
|
||||
remains unspendable.
|
||||
|
||||
|
||||
## Motivation
|
||||
|
||||
The nLockTime field in transactions can be used to prove that it is
|
||||
''possible'' to spend a transaction output in the future, by constructing a
|
||||
valid transaction spending that output with the nLockTime field set.
|
||||
|
||||
However, the nLockTime field can't prove that it is ''impossible'' to spend a
|
||||
transaction output until some time in the future, as there is no way to know if
|
||||
a valid signature for a different transaction spending that output has been
|
||||
created.
|
||||
|
||||
|
||||
### Escrow
|
||||
|
||||
If Alice and Bob jointly operate a business they may want to
|
||||
ensure that all funds are kept in 2-of-2 multisig transaction outputs that
|
||||
require the co-operation of both parties to spend. However, they recognise that
|
||||
in exceptional circumstances such as either party getting "hit by a bus" they
|
||||
need a backup plan to retrieve the funds. So they appoint their lawyer, Lenny,
|
||||
to act as a third-party.
|
||||
|
||||
With a standard 2-of-3 CHECKMULTISIG at any time Lenny could conspire with
|
||||
either Alice or Bob to steal the funds illegitimately. Equally Lenny may prefer
|
||||
not to have immediate access to the funds to discourage bad actors from
|
||||
attempting to get the secret keys from him by force.
|
||||
|
||||
However, with CHECKLOCKTIMEVERIFY the funds can be stored in scriptPubKeys of
|
||||
the form:
|
||||
|
||||
IF
|
||||
<now + 3 months> CHECKLOCKTIMEVERIFY DROP
|
||||
<Lenny's pubkey> CHECKSIGVERIFY
|
||||
1
|
||||
ELSE
|
||||
2
|
||||
ENDIF
|
||||
<Alice's pubkey> <Bob's pubkey> 2 CHECKMULTISIG
|
||||
|
||||
At any time the funds can be spent with the following scriptSig:
|
||||
|
||||
0 <Alice's signature> <Bob's signature> 0
|
||||
|
||||
After 3 months have passed Lenny and one of either Alice or Bob can spend the
|
||||
funds with the following scriptSig:
|
||||
|
||||
0 <Alice/Bob's signature> <Lenny's signature> 1
|
||||
|
||||
|
||||
### Non-interactive time-locked refunds
|
||||
|
||||
There exist a number of protocols where a transaction output is created that
|
||||
requires the co-operation of both parties to spend the output. To ensure the
|
||||
failure of one party does not result in the funds becoming lost, refund
|
||||
transactions are setup in advance using nLockTime. These refund transactions
|
||||
need to be created interactively, and additionally, are currently vulnerable to
|
||||
transaction malleability. CHECKLOCKTIMEVERIFY can be used in these protocols,
|
||||
replacing the interactive setup with a non-interactive setup, and additionally,
|
||||
making transaction malleability a non-issue.
|
||||
|
||||
|
||||
#### Two-factor wallets
|
||||
|
||||
Services like GreenAddress store bitcoins with 2-of-2 multisig scriptPubKey's
|
||||
such that one keypair is controlled by the user, and the other keypair is
|
||||
controlled by the service. To spend funds the user uses locally installed
|
||||
wallet software that generates one of the required signatures, and then uses a
|
||||
2nd-factor authentication method to authorize the service to create the second
|
||||
SIGHASH_NONE signature that is locked until some time in the future and sends
|
||||
the user that signature for storage. If the user needs to spend their funds and
|
||||
the service is not available, they wait until the nLockTime expires.
|
||||
|
||||
The problem is there exist numerous occasions the user will not have a valid
|
||||
signature for some or all of their transaction outputs. With
|
||||
CHECKLOCKTIMEVERIFY rather than creating refund signatures on demand
|
||||
scriptPubKeys of the following form are used instead:
|
||||
|
||||
IF
|
||||
<service pubkey> CHECKSIGVERIFY
|
||||
ELSE
|
||||
<expiry time> CHECKLOCKTIMEVERIFY DROP
|
||||
ENDIF
|
||||
<user pubkey> CHECKSIG
|
||||
|
||||
Now the user is always able to spend their funds without the co-operation of
|
||||
the service by waiting for the expiry time to be reached.
|
||||
|
||||
|
||||
#### Payment Channels
|
||||
|
||||
Jeremy Spilman style payment channels first setup a deposit controlled by
|
||||
2-of-2 multisig, tx1, and then adjust a second transaction, tx2, that spends
|
||||
the output of tx1 to payor and payee. Prior to publishing tx1 a refund
|
||||
transaction is created, tx3, to ensure that should the payee vanish the payor
|
||||
can get their deposit back. The process by which the refund transaction is
|
||||
created is currently vulnerable to transaction malleability attacks, and
|
||||
additionally, requires the payor to store the refund. Using the same
|
||||
scriptPubKey form as in the Two-factor wallets example solves both these issues.
|
||||
|
||||
|
||||
### Trustless Payments for Publishing Data
|
||||
|
||||
The PayPub protocol makes it possible to pay for information in a trustless way
|
||||
by first proving that an encrypted file contains the desired data, and secondly
|
||||
crafting scriptPubKeys used for payment such that spending them reveals the
|
||||
encryption keys to the data. However the existing implementation has a
|
||||
significant flaw: the publisher can delay the release of the keys indefinitely.
|
||||
|
||||
This problem can be solved interactively with the refund transaction technique;
|
||||
with CHECKLOCKTIMEVERIFY the problem can be non-interactively solved using
|
||||
scriptPubKeys of the following form:
|
||||
|
||||
IF
|
||||
HASH160 <Hash160(encryption key)> EQUALVERIFY
|
||||
<publisher pubkey> CHECKSIG
|
||||
ELSE
|
||||
<expiry time> CHECKLOCKTIMEVERIFY DROP
|
||||
<buyer pubkey> CHECKSIG
|
||||
ENDIF
|
||||
|
||||
The buyer of the data is now making a secure offer with an expiry time. If the
|
||||
publisher fails to accept the offer before the expiry time is reached the buyer
|
||||
can cancel the offer by spending the output.
|
||||
|
||||
|
||||
### Proving sacrifice to miners' fees
|
||||
|
||||
Proving the sacrifice of some limited resource is a common technique in a
|
||||
variety of cryptographic protocols. Proving sacrifices of coins to mining fees
|
||||
has been proposed as a ''universal public good'' to which the sacrifice could
|
||||
be directed, rather than simply destroying the coins. However doing so is
|
||||
non-trivial, and even the best existing technqiue - announce-commit sacrifices
|
||||
- could encourage mining centralization. CHECKLOCKTIMEVERIFY can be used to
|
||||
create outputs that are provably spendable by anyone (thus to mining fees
|
||||
assuming miners behave optimally and rationally) but only at a time
|
||||
sufficiently far into the future that large miners can't profitably sell the
|
||||
sacrifices at a discount.
|
||||
|
||||
|
||||
### Freezing Funds
|
||||
|
||||
In addition to using cold storage, hardware wallets, and P2SH multisig outputs
|
||||
to control funds, now funds can be frozen in UTXOs directly on the blockchain.
|
||||
With the following scriptPubKey, nobody will be able to spend the encumbered
|
||||
output until the provided expiry time. This ability to freeze funds reliably may
|
||||
be useful in scenarios where reducing duress or confiscation risk is desired.
|
||||
|
||||
<expiry time> CHECKLOCKTIMEVERIFY DROP DUP HASH160 <pubKeyHash> EQUALVERIFY CHECKSIG
|
||||
|
||||
|
||||
### Replacing the nLockTime field entirely
|
||||
|
||||
As an aside, note how if the SignatureHash() algorithm could optionally cover
|
||||
part of the scriptSig the signature could require that the scriptSig contain
|
||||
CHECKLOCKTIMEVERIFY opcodes, and additionally, require that they be executed.
|
||||
(the CODESEPARATOR opcode came very close to making this possible in v0.1 of
|
||||
Bitcoin) This per-signature capability could replace the per-transaction
|
||||
nLockTime field entirely as a valid signature would now be the proof that a
|
||||
transaction output ''can'' be spent.
|
||||
|
||||
|
||||
## Detailed Specification
|
||||
|
||||
Refer to the reference implementation, reproduced below, for the precise
|
||||
semantics and detailed rationale for those semantics.
|
||||
|
||||
|
||||
case OP_NOP2:
|
||||
{
|
||||
// CHECKLOCKTIMEVERIFY
|
||||
//
|
||||
// (nLockTime -- nLockTime )
|
||||
|
||||
if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY))
|
||||
break; // not enabled; treat as a NOP
|
||||
|
||||
if (stack.size() < 1)
|
||||
return false;
|
||||
|
||||
// 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.
|
||||
//
|
||||
// If we kept to that limit we'd have a year 2038 problem,
|
||||
// even though the nLockTime field in transactions
|
||||
// themselves is uint32 which only becomes meaningless
|
||||
// after the year 2106.
|
||||
//
|
||||
// Thus as a special case we tell CScriptNum to accept up
|
||||
// to 5-byte bignums, which are good until 2**32-1, the
|
||||
// same limit as the nLockTime field itself.
|
||||
const CScriptNum nLockTime(stacktop(-1), 5);
|
||||
|
||||
// In the rare event that the argument may be < 0 due to
|
||||
// some arithmetic being done first, you can always use
|
||||
// 0 MAX CHECKLOCKTIMEVERIFY.
|
||||
if (nLockTime < 0)
|
||||
return false;
|
||||
|
||||
// There are two types of nLockTime: lock-by-blockheight
|
||||
// and lock-by-blocktime, distinguished by whether
|
||||
// nLockTime < LOCKTIME_THRESHOLD.
|
||||
//
|
||||
// We want to compare apples to apples, so fail the script
|
||||
// unless the type of nLockTime being tested is the same as
|
||||
// the nLockTime in the transaction.
|
||||
if (!(
|
||||
(txTo.nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
|
||||
(txTo.nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
|
||||
))
|
||||
return false;
|
||||
|
||||
// Now that we know we're comparing apples-to-apples, the
|
||||
// comparison is a simple numeric one.
|
||||
if (nLockTime > (int64_t)txTo.nLockTime)
|
||||
return false;
|
||||
|
||||
// Finally the nLockTime feature can be disabled and thus
|
||||
// CHECKLOCKTIMEVERIFY bypassed if every txin has been
|
||||
// finalized by setting nSequence to maxint. The
|
||||
// transaction would be allowed into the blockchain, making
|
||||
// the opcode ineffective.
|
||||
//
|
||||
// Testing if this vin is not final is sufficient to
|
||||
// prevent this condition. Alternatively we could test all
|
||||
// inputs, but testing just this input minimizes the data
|
||||
// required to prove correct CHECKLOCKTIMEVERIFY execution.
|
||||
if (txTo.vin[nIn].IsFinal())
|
||||
return false;
|
||||
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
https://github.com/petertodd/bitcoin/commit/ab0f54f38e08ee1e50ff72f801680ee84d0f1bf4
|
||||
|
||||
|
||||
## Deployment
|
||||
|
||||
We reuse the double-threshold IsSuperMajority() switchover mechanism used in
|
||||
BIP66 with the same thresholds, but for nVersion = 4. The new rules are
|
||||
in effect for every block (at height H) with nVersion = 4 and at least
|
||||
750 out of 1000 blocks preceding it (with heights H-1000..H-1) also
|
||||
have nVersion >= 4. Furthermore, when 950 out of the 1000 blocks
|
||||
preceding a block do have nVersion >= 4, nVersion < 4 blocks become
|
||||
invalid, and all further blocks enforce the new rules.
|
||||
|
||||
It should be noted that BIP9 involves permanently setting a high-order bit to
|
||||
1 which results in nVersion >= all prior IsSuperMajority() soft-forks and thus
|
||||
no bits in nVersion are permanently lost.
|
||||
|
||||
|
||||
### SPV Clients
|
||||
|
||||
While SPV clients are (currently) unable to validate blocks in general,
|
||||
trusting miners to do validation for them, they are able to validate block
|
||||
headers and thus can validate a subset of the deployment rules. SPV clients
|
||||
should reject nVersion < 4 blocks if 950 out of 1000 preceding blocks have
|
||||
nVersion >= 4 to prevent false confirmations from the remaining 5% of
|
||||
non-upgraded miners when the 95% threshold has been reached.
|
||||
|
||||
|
||||
## Credits
|
||||
|
||||
Thanks goes to Gregory Maxwell for suggesting that the argument be compared
|
||||
against the per-transaction nLockTime, rather than the current block height and
|
||||
time.
|
||||
|
||||
|
||||
## References
|
||||
|
||||
PayPub
|
||||
|
||||
* https://github.com/unsystem/paypub
|
||||
|
||||
Jeremy Spilman Payment Channels
|
||||
|
||||
* https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2013-April/002433.html
|
||||
|
||||
|
||||
## Implementations
|
||||
|
||||
Python / python-bitcoinlib
|
||||
|
||||
* https://github.com/petertodd/checklocktimeverify-demos
|
||||
|
||||
JavaScript / Node.js / bitcore
|
||||
|
||||
* https://github.com/mruddy/bip65-demos
|
||||
|
||||
|
||||
## Copyright
|
||||
|
||||
This document is placed in the public domain.
|
||||
@@ -0,0 +1,146 @@
|
||||
<pre>
|
||||
BIP: 66
|
||||
Layer: Consensus (soft fork)
|
||||
Title: Strict DER signatures
|
||||
Author: Pieter Wuille <pieter.wuille@gmail.com>
|
||||
Comments-Summary: No comments yet.
|
||||
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0066
|
||||
Status: Final
|
||||
Type: Standards Track
|
||||
Created: 2015-01-10
|
||||
License: BSD-2-Clause
|
||||
</pre>
|
||||
|
||||
## Abstract
|
||||
|
||||
This document specifies proposed changes to the Bitcoin transaction validity rules to restrict signatures to strict DER encoding.
|
||||
|
||||
## Copyright
|
||||
|
||||
This BIP is licensed under the 2-clause BSD license.
|
||||
|
||||
## Motivation
|
||||
|
||||
Bitcoin's reference implementation currently relies on OpenSSL for signature validation, which means it is implicitly defining Bitcoin's block validity rules. Unfortunately, OpenSSL is not designed for consensus-critical behaviour (it does not guarantee bug-for-bug compatibility between versions), and thus changes to it can - and have - affected Bitcoin software.
|
||||
|
||||
One specifically critical area is the encoding of signatures. Until recently, OpenSSL's releases would accept various deviations from the DER standard and accept signatures as valid. When this changed in OpenSSL 1.0.0p and 1.0.1k, it made some nodes reject the chain.
|
||||
|
||||
This document proposes to restrict valid signatures to exactly what is mandated by DER, to make the consensus rules not depend on OpenSSL's signature parsing. A change like this is required if implementations would want to remove all of OpenSSL from the consensus code.
|
||||
|
||||
## Specification
|
||||
|
||||
Every signature passed to OP_CHECKSIG, OP_CHECKSIGVERIFY, OP_CHECKMULTISIG, or OP_CHECKMULTISIGVERIFY, to which ECDSA verification is applied, must be encoded using strict DER encoding (see further).
|
||||
|
||||
These operators all perform ECDSA verifications on pubkey/signature pairs, iterating from the top of the stack backwards. For each such verification, if the signature does not pass the <code>IsValidSignatureEncoding</code> check below, the entire script evaluates to false immediately. If the signature is valid DER, but does not pass ECDSA verification, opcode execution continues as it used to, causing opcode execution to stop and push false on the stack (but not immediately fail the script) in some cases, which potentially skips further signatures (and thus does not subject them to <code>IsValidSignatureEncoding</code>).
|
||||
|
||||
### DER encoding reference
|
||||
|
||||
The following code specifies the behaviour of strict DER checking. Note that this function tests a signature byte vector which includes the 1-byte sighash flag that Bitcoin adds, even though that flag falls outside of the DER specification, and is unaffected by this proposal. The function is also not called for cases where the length of sig is 0, in order to provide a simple, short and efficiently-verifiable encoding for deliberately invalid signatures.
|
||||
|
||||
DER is specified in https://www.itu.int/rec/T-REC-X.690/en .
|
||||
|
||||
<pre>
|
||||
bool static IsValidSignatureEncoding(const std::vector<unsigned char> &sig) {
|
||||
// Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] [sighash]
|
||||
// * total-length: 1-byte length descriptor of everything that follows,
|
||||
// excluding the sighash byte.
|
||||
// * R-length: 1-byte length descriptor of the R value that follows.
|
||||
// * R: arbitrary-length big-endian encoded R value. It must use the shortest
|
||||
// possible encoding for a positive integers (which means no null bytes at
|
||||
// the start, except a single one when the next byte has its highest bit set).
|
||||
// * S-length: 1-byte length descriptor of the S value that follows.
|
||||
// * S: arbitrary-length big-endian encoded S value. The same rules apply.
|
||||
// * sighash: 1-byte value indicating what data is hashed (not part of the DER
|
||||
// signature)
|
||||
|
||||
// Minimum and maximum size constraints.
|
||||
if (sig.size() < 9) return false;
|
||||
if (sig.size() > 73) return false;
|
||||
|
||||
// A signature is of type 0x30 (compound).
|
||||
if (sig[0] != 0x30) return false;
|
||||
|
||||
// Make sure the length covers the entire signature.
|
||||
if (sig[1] != sig.size() - 3) return false;
|
||||
|
||||
// Extract the length of the R element.
|
||||
unsigned int lenR = sig[3];
|
||||
|
||||
// Make sure the length of the S element is still inside the signature.
|
||||
if (5 + lenR >= sig.size()) return false;
|
||||
|
||||
// Extract the length of the S element.
|
||||
unsigned int lenS = sig[5 + lenR];
|
||||
|
||||
// Verify that the length of the signature matches the sum of the length
|
||||
// of the elements.
|
||||
if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
|
||||
|
||||
// Check whether the R element is an integer.
|
||||
if (sig[2] != 0x02) return false;
|
||||
|
||||
// Zero-length integers are not allowed for R.
|
||||
if (lenR == 0) return false;
|
||||
|
||||
// Negative numbers are not allowed for R.
|
||||
if (sig[4] & 0x80) return false;
|
||||
|
||||
// Null bytes at the start of R are not allowed, unless R would
|
||||
// otherwise be interpreted as a negative number.
|
||||
if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
|
||||
|
||||
// Check whether the S element is an integer.
|
||||
if (sig[lenR + 4] != 0x02) return false;
|
||||
|
||||
// Zero-length integers are not allowed for S.
|
||||
if (lenS == 0) return false;
|
||||
|
||||
// Negative numbers are not allowed for S.
|
||||
if (sig[lenR + 6] & 0x80) return false;
|
||||
|
||||
// Null bytes at the start of S are not allowed, unless S would otherwise be
|
||||
// interpreted as a negative number.
|
||||
if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
</pre>
|
||||
|
||||
### Examples
|
||||
|
||||
Notation: P1 and P2 are valid, serialized, public keys. S1 and S2 are valid signatures using respective keys P1 and P2. S1' and S2' are non-DER but otherwise valid signatures using those same keys. F is any invalid but DER-compliant signature (including 0, the empty string). F' is any invalid and non-DER-compliant signature.
|
||||
|
||||
1. <code>S1' P1 CHECKSIG</code> fails (<b>changed</b>)
|
||||
2. <code>S1' P1 CHECKSIG NOT</code> fails (unchanged)
|
||||
3. <code>F P1 CHECKSIG</code> fails (unchanged)
|
||||
4. <code>F P1 CHECKSIG NOT</code> can succeed (unchanged)
|
||||
5. <code>F' P1 CHECKSIG</code> fails (unchanged)
|
||||
6. <code>F' P1 CHECKSIG NOT</code> fails (<b>changed</b>)
|
||||
7. <code>0 S1' S2 2 P1 P2 2 CHECKMULTISIG</code> fails (<b>changed</b>)
|
||||
8. <code>0 S1' S2 2 P1 P2 2 CHECKMULTISIG NOT</code> fails (unchanged)
|
||||
9. <code>0 F S2' 2 P1 P2 2 CHECKMULTISIG</code> fails (unchanged)
|
||||
10. <code>0 F S2' 2 P1 P2 2 CHECKMULTISIG NOT</code> fails (<b>changed</b>)
|
||||
11. <code>0 S1' F 2 P1 P2 2 CHECKMULTISIG</code> fails (unchanged)
|
||||
12. <code>0 S1' F 2 P1 P2 2 CHECKMULTISIG NOT</code> can succeed (unchanged)
|
||||
|
||||
Note that the examples above show that only additional failures are required by this change, as required for a soft forking change.
|
||||
|
||||
## Deployment
|
||||
|
||||
We reuse the double-threshold switchover mechanism from BIP 34, with the same thresholds, but for nVersion = 3. The new rules are in effect for every block (at height H) with nVersion = 3 and at least 750 out of 1000 blocks preceding it (with heights H-1000..H-1) also have nVersion = 3. Furthermore, when 950 out of the 1000 blocks preceding a block do have nVersion = 3, nVersion = 2 blocks become invalid, and all further blocks enforce the new rules.
|
||||
|
||||
## Compatibility
|
||||
|
||||
The requirement to have signatures that comply strictly with DER has been enforced as a relay policy by the reference client since v0.8.0, and very few transactions violating it are being added to the chain as of January 2015. In addition, every non-compliant signature can trivially be converted into a compliant one, so there is no loss of functionality by this requirement. This proposal has the added benefit of reducing transaction malleability (see BIP 62).
|
||||
|
||||
## Implementation
|
||||
|
||||
An implementation for the reference client is available at https://github.com/bitcoin/bitcoin/pull/5713
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
This document is extracted from the previous BIP62 proposal, which had input from various people, in particular Greg Maxwell and Peter Todd, who gave feedback about this document as well.
|
||||
|
||||
## Disclosures
|
||||
|
||||
* Subsequent to the network-wide adoption and enforcement of this BIP, the author [disclosed](https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2015-July/009697.html) that strict DER signatures provided an indirect solution to a consensus bug he had previously discovered.
|
||||
@@ -0,0 +1,264 @@
|
||||
<pre>
|
||||
BIP: 68
|
||||
Layer: Consensus (soft fork)
|
||||
Title: Relative lock-time using consensus-enforced sequence numbers
|
||||
Author: Mark Friedenbach <mark@friedenbach.org>
|
||||
BtcDrak <btcdrak@gmail.com>
|
||||
Nicolas Dorier <nicolas.dorier@gmail.com>
|
||||
kinoshitajona <kinoshitajona@gmail.com>
|
||||
Comments-Summary: No comments yet.
|
||||
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0068
|
||||
Status: Final
|
||||
Type: Standards Track
|
||||
Created: 2015-05-28
|
||||
</pre>
|
||||
|
||||
## Abstract
|
||||
|
||||
This BIP introduces relative lock-time (RLT) consensus-enforced semantics of the sequence number field to enable a signed transaction input to remain invalid for a defined period of time after confirmation of its corresponding outpoint.
|
||||
|
||||
## Motivation
|
||||
|
||||
Bitcoin transactions have a sequence number field for each input. The original idea appears to have been that a transaction in the mempool would be replaced by using the same input with a higher sequence value. Although this was not properly implemented, it assumes miners would prefer higher sequence numbers even if the lower ones were more profitable to mine. However, a miner acting on profit motives alone would break that assumption completely. The change described by this BIP repurposes the sequence number for new use cases without breaking existing functionality. It also leaves room for future expansion and other use cases.
|
||||
|
||||
The transaction nLockTime is used to prevent the mining of a transaction until a certain date. nSequence will be repurposed to prevent mining of a transaction until a certain age of the spent output in blocks or timespan. This, among other uses, allows bi-directional payment channels as used in [Hashed Timelock Contracts (HTLCs)](https://github.com/ElementsProject/lightning/raw/master/doc/deployable-lightning.pdf) and [BIP112](/protocol/forks/bip-0112#bidirectional-payment-channels).
|
||||
|
||||
## Specification
|
||||
|
||||
This specification defines the meaning of sequence numbers for transactions with an nVersion greater than or equal to 2 for which the rest of this specification relies on.
|
||||
|
||||
All references to median-time-past (MTP) are as defined by BIP113.
|
||||
|
||||
If bit (1 << 31) of the sequence number is set, then no consensus meaning is applied to the sequence number and can be included in any block under all currently possible circumstances.
|
||||
|
||||
If bit (1 << 31) of the sequence number is not set, then the sequence number is interpreted as an encoded relative lock-time.
|
||||
|
||||
The sequence number encoding is interpreted as follows:
|
||||
|
||||
Bit (1 << 22) determines if the relative lock-time is time-based or block based: If the bit is set, the relative lock-time specifies a timespan in units of 512 seconds granularity. The timespan starts from the median-time-past of the output’s previous block, and ends at the MTP of the previous block. If the bit is not set, the relative lock-time specifies a number of blocks.
|
||||
|
||||
The flag (1<<22) is the highest order bit in a 3-byte signed integer for use in bitcoin scripts as a 3-byte PUSHDATA with OP_CHECKSEQUENCEVERIFY (BIP 112).
|
||||
|
||||
This specification only interprets 16 bits of the sequence number as relative lock-time, so a mask of 0x0000ffff MUST be applied to the sequence field to extract the relative lock-time. The 16-bit specification allows for a year of relative lock-time and the remaining bits allow for future expansion.
|
||||
|
||||
<img src=https://raw.githubusercontent.com/bitcoin/bips/master/bip-0068/encoding.png></img>
|
||||
|
||||
For time based relative lock-time, 512 second granularity was chosen because bitcoin blocks are generated every 600 seconds. So when using block-based or time-based, the same amount of time can be encoded with the available number of bits. Converting from a sequence number to seconds is performed by multiplying by 512 = 2^9, or equivalently shifting up by 9 bits.
|
||||
|
||||
When the relative lock-time is time-based, it is interpreted as a minimum block-time constraint over the input's age. A relative time-based lock-time of zero indicates an input which can be included in any block. More generally, a relative time-based lock-time n can be included into any block produced 512 * n seconds after the mining date of the output it is spending, or any block thereafter.
|
||||
The mining date of the output is equal to the median-time-past of the previous block which mined it.
|
||||
|
||||
The block produced time is equal to the median-time-past of its previous block.
|
||||
|
||||
When the relative lock-time is block-based, it is interpreted as a minimum block-height constraint over the input's age. A relative block-based lock-time of zero indicates an input which can be included in any block. More generally, a relative block lock-time n can be included n blocks after the mining date of the output it is spending, or any block thereafter.
|
||||
|
||||
The new rules are not applied to the nSequence field of the input of the coinbase transaction.
|
||||
|
||||
## Implementation
|
||||
|
||||
A reference implementation is provided by the following pull request
|
||||
|
||||
https://github.com/bitcoin/bitcoin/pull/7184
|
||||
|
||||
<pre>
|
||||
enum {
|
||||
/* Interpret sequence numbers as relative lock-time constraints. */
|
||||
LOCKTIME_VERIFY_SEQUENCE = (1 << 0),
|
||||
};
|
||||
|
||||
/* Setting nSequence to this value for every input in a transaction
|
||||
* disables nLockTime. */
|
||||
static const uint32_t SEQUENCE_FINAL = 0xffffffff;
|
||||
|
||||
/* Below flags apply in the context of BIP 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;
|
||||
|
||||
/* In order to use the same number of bits to encode roughly the
|
||||
* same wall-clock duration, and because blocks are naturally
|
||||
* limited to occur every 600s on average, the minimum granularity
|
||||
* for time-based relative lock-time is fixed at 512 seconds.
|
||||
* Converting from CTxIn::nSequence to seconds is performed by
|
||||
* multiplying by 512 = 2^9, or equivalently shifting up by
|
||||
* 9 bits. */
|
||||
static const int SEQUENCE_LOCKTIME_GRANULARITY = 9;
|
||||
|
||||
/**
|
||||
* Calculates the block height and previous block's median time past at
|
||||
* which the transaction will be considered final in the context of BIP 68.
|
||||
* Also removes from the vector of input heights any entries which did not
|
||||
* correspond to sequence locked inputs as they do not affect the calculation.
|
||||
*/
|
||||
static std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
|
||||
{
|
||||
assert(prevHeights->size() == tx.vin.size());
|
||||
|
||||
// Will be set to the equivalent height- and time-based nLockTime
|
||||
// values that would be necessary to satisfy all relative lock-
|
||||
// time constraints given our view of block chain history.
|
||||
// The semantics of nLockTime are the last invalid height/time, so
|
||||
// use -1 to have the effect of any height or time being valid.
|
||||
int nMinHeight = -1;
|
||||
int64_t nMinTime = -1;
|
||||
|
||||
// tx.nVersion is signed integer so requires cast to unsigned otherwise
|
||||
// we would be doing a signed comparison and half the range of nVersion
|
||||
// wouldn't support BIP 68.
|
||||
bool fEnforceBIP68 = static_cast<uint32_t>(tx.nVersion) >= 2
|
||||
&& flags & LOCKTIME_VERIFY_SEQUENCE;
|
||||
|
||||
// Do not enforce sequence numbers as a relative lock time
|
||||
// unless we have been instructed to
|
||||
if (!fEnforceBIP68) {
|
||||
return std::make_pair(nMinHeight, nMinTime);
|
||||
}
|
||||
|
||||
for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
|
||||
const CTxIn& txin = tx.vin[txinIndex];
|
||||
|
||||
// Sequence numbers with the most significant bit set are not
|
||||
// treated as relative lock-times, nor are they given any
|
||||
// consensus-enforced meaning at this point.
|
||||
if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) {
|
||||
// The height of this input is not relevant for sequence locks
|
||||
(*prevHeights)[txinIndex] = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
int nCoinHeight = (*prevHeights)[txinIndex];
|
||||
|
||||
if (txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) {
|
||||
int64_t nCoinTime = block.GetAncestor(std::max(nCoinHeight-1, 0))->GetMedianTimePast();
|
||||
// NOTE: Subtract 1 to maintain nLockTime semantics
|
||||
// BIP 68 relative lock times have the semantics of calculating
|
||||
// the first block or time at which the transaction would be
|
||||
// valid. When calculating the effective block time or height
|
||||
// for the entire transaction, we switch to using the
|
||||
// semantics of nLockTime which is the last invalid block
|
||||
// time or height. Thus we subtract 1 from the calculated
|
||||
// time or height.
|
||||
|
||||
// Time-based relative lock-times are measured from the
|
||||
// smallest allowed timestamp of the block containing the
|
||||
// txout being spent, which is the median time past of the
|
||||
// block prior.
|
||||
nMinTime = std::max(nMinTime, nCoinTime + (int64_t)((txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) << CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) - 1);
|
||||
} else {
|
||||
nMinHeight = std::max(nMinHeight, nCoinHeight + (int)(txin.nSequence & CTxIn::SEQUENCE_LOCKTIME_MASK) - 1);
|
||||
}
|
||||
}
|
||||
|
||||
return std::make_pair(nMinHeight, nMinTime);
|
||||
}
|
||||
|
||||
static bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair)
|
||||
{
|
||||
assert(block.pprev);
|
||||
int64_t nBlockTime = block.pprev->GetMedianTimePast();
|
||||
if (lockPair.first >= block.nHeight || lockPair.second >= nBlockTime)
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block)
|
||||
{
|
||||
return EvaluateSequenceLocks(block, CalculateSequenceLocks(tx, flags, prevHeights, block));
|
||||
}
|
||||
|
||||
bool CheckSequenceLocks(const CTransaction &tx, int flags)
|
||||
{
|
||||
AssertLockHeld(cs_main);
|
||||
AssertLockHeld(mempool.cs);
|
||||
|
||||
CBlockIndex* tip = chainActive.Tip();
|
||||
CBlockIndex index;
|
||||
index.pprev = tip;
|
||||
// CheckSequenceLocks() uses chainActive.Height()+1 to evaluate
|
||||
// height based locks because when SequenceLocks() is called within
|
||||
// ConnectBlock(), the height of the block *being*
|
||||
// evaluated is what is used.
|
||||
// Thus if we want to know if a transaction can be part of the
|
||||
// *next* block, we need to use one more than chainActive.Height()
|
||||
index.nHeight = tip->nHeight + 1;
|
||||
|
||||
// pcoinsTip contains the UTXO set for chainActive.Tip()
|
||||
CCoinsViewMemPool viewMemPool(pcoinsTip, mempool);
|
||||
std::vector<int> prevheights;
|
||||
prevheights.resize(tx.vin.size());
|
||||
for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) {
|
||||
const CTxIn& txin = tx.vin[txinIndex];
|
||||
CCoins coins;
|
||||
if (!viewMemPool.GetCoins(txin.prevout.hash, coins)) {
|
||||
return error("%s: Missing input", __func__);
|
||||
}
|
||||
if (coins.nHeight == MEMPOOL_HEIGHT) {
|
||||
// Assume all mempool transaction confirm in the next block
|
||||
prevheights[txinIndex] = tip->nHeight + 1;
|
||||
} else {
|
||||
prevheights[txinIndex] = coins.nHeight;
|
||||
}
|
||||
}
|
||||
|
||||
std::pair<int, int64_t> lockPair = CalculateSequenceLocks(tx, flags, &prevheights, index);
|
||||
return EvaluateSequenceLocks(index, lockPair);
|
||||
}
|
||||
</pre>
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
Credit goes to Gregory Maxwell for providing a succinct and clear description of the behavior of this change, which became the basis of this BIP text.
|
||||
|
||||
This BIP was edited by BtcDrak, Nicolas Dorier and kinoshitajona.
|
||||
|
||||
## Deployment
|
||||
|
||||
This BIP is to be deployed by "versionbits" BIP9 using bit 0.
|
||||
|
||||
For Bitcoin '''mainnet''', the BIP9 '''starttime''' will be midnight 1st May 2016 UTC (Epoch timestamp 1462060800) and BIP9 '''timeout''' will be midnight 1st May 2017 UTC (Epoch timestamp 1493596800).
|
||||
|
||||
For Bitcoin '''testnet''', the BIP9 '''starttime''' will be midnight 1st March 2016 UTC (Epoch timestamp 1456790400) and BIP9 '''timeout''' will be midnight 1st May 2017 UTC (Epoch timestamp 1493596800).
|
||||
|
||||
This BIP must be deployed simultaneously with BIP112 and BIP113 using the same deployment mechanism.
|
||||
|
||||
## Compatibility
|
||||
|
||||
The only use of sequence numbers by the Bitcoin Core reference client software is to disable checking the nLockTime constraints in a transaction. The semantics of that application are preserved by this BIP.
|
||||
|
||||
As can be seen from the specification section, a number of bits are undefined by this BIP to allow for other use cases by setting bit (1 << 31) as the remaining 31 bits have no meaning under this BIP. Additionally, bits (1 << 23) through (1 << 30) inclusive have no meaning at all when bit (1 << 31) is unset.
|
||||
|
||||
Additionally, this BIP specifies only 16 bits to actually encode relative lock-time meaning a further 6 are unused (1 << 16 through 1 << 21 inclusive). This allows the possibility to increase granularity by soft-fork, or for increasing the maximum possible relative lock-time in the future.
|
||||
|
||||
The most efficient way to calculate sequence number from relative lock-time is with bit masks and shifts:
|
||||
|
||||
<pre>
|
||||
// 0 <= nHeight < 65,535 blocks (1.25 years)
|
||||
nSequence = nHeight;
|
||||
nHeight = nSequence & 0x0000ffff;
|
||||
|
||||
// 0 <= nTime < 33,554,431 seconds (1.06 years)
|
||||
nSequence = (1 << 22) | (nTime >> 9);
|
||||
nTime = (nSequence & 0x0000ffff) << 9;
|
||||
</pre>
|
||||
|
||||
## References
|
||||
|
||||
Bitcoin mailing list discussion: https://www.mail-archive.com/bitcoin-development@lists.sourceforge.net/msg07864.html
|
||||
|
||||
[BIP9](/protocol/forks/bip-0009): https://github.com/bitcoin/bips/blob/master/bip-0009.mediawiki
|
||||
|
||||
[BIP112](/protocol/forks/bip-0112): https://github.com/bitcoin/bips/blob/master/bip-0112.mediawiki
|
||||
|
||||
[BIP113](/protocol/forks/bip-0113): https://github.com/bitcoin/bips/blob/master/bip-0113.mediawiki
|
||||
|
||||
Hashed Timelock Contracts (HTLCs): https://github.com/ElementsProject/lightning/raw/master/doc/deployable-lightning.pdf
|
||||
@@ -0,0 +1,398 @@
|
||||
<pre>
|
||||
BIP: 112
|
||||
Layer: Consensus (soft fork)
|
||||
Title: CHECKSEQUENCEVERIFY
|
||||
Author: BtcDrak <btcdrak@gmail.com>
|
||||
Mark Friedenbach <mark@friedenbach.org>
|
||||
Eric Lombrozo <elombrozo@gmail.com>
|
||||
Comments-Summary: No comments yet.
|
||||
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0112
|
||||
Status: Final
|
||||
Type: Standards Track
|
||||
Created: 2015-08-10
|
||||
License: PD
|
||||
</pre>
|
||||
|
||||
## Abstract
|
||||
|
||||
This BIP describes a new opcode (CHECKSEQUENCEVERIFY) for the Bitcoin
|
||||
scripting system that in combination with BIP 68 allows execution
|
||||
pathways of a script to be restricted based on the age of the output
|
||||
being spent.
|
||||
|
||||
|
||||
## Summary
|
||||
|
||||
CHECKSEQUENCEVERIFY redefines the existing NOP3 opcode.
|
||||
When executed, if any of the following conditions are true, the script interpreter will terminate with an error:
|
||||
|
||||
* the stack is empty; or
|
||||
* the top item on the stack is less than 0; or
|
||||
* the top item on the stack has the disable flag (1 << 31) unset; and
|
||||
* the transaction version is less than 2; or
|
||||
* the transaction input sequence number disable flag (1 << 31) is set; or
|
||||
* the relative lock-time type is not the same; or
|
||||
* the top stack item is greater than the transaction input sequence (when masked according to the BIP68);
|
||||
|
||||
Otherwise, script execution will continue as if a NOP had been executed.
|
||||
|
||||
BIP 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 CHECKSEQUENCEVERIFY against the nSequence 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 CHECKSEQUENCEVERIFY will fail to validate, causing the transaction not to be selected for inclusion in a block.
|
||||
|
||||
|
||||
## Motivation
|
||||
|
||||
BIP 68 repurposes the transaction nSequence field meaning by giving
|
||||
sequence numbers new consensus-enforced semantics as a relative
|
||||
lock-time. However, there is no way to build Bitcoin scripts to make
|
||||
decisions based on this field.
|
||||
|
||||
By making the nSequence 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.
|
||||
|
||||
|
||||
### Contracts With Expiration Deadlines
|
||||
|
||||
#### Escrow with Timeout
|
||||
|
||||
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 redeemscript.
|
||||
|
||||
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 funds can be spent using signatures from any two of Alice,
|
||||
Bob or the Escrow.
|
||||
|
||||
After 30 days Alice can sign alone.
|
||||
|
||||
The clock does not start ticking until the payment to the escrow address
|
||||
confirms.
|
||||
|
||||
|
||||
### Retroactive Invalidation
|
||||
|
||||
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 blockchain, it
|
||||
is practically impossible to retroactively invalidate a previous commitment that
|
||||
has already confirmed. The only mechanism we really have for retroactive
|
||||
invalidation is blockchain reorganization which, for fundamental security
|
||||
reasons, is designed to be very hard and very expensive to do.
|
||||
|
||||
Despite this limitation, we do have a way to provide something functionally similar to retroactive invalidation while preserving irreversibility of past commitments
|
||||
using CHECKSEQUENCEVERIFY. 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.
|
||||
|
||||
Some more specific applications of this idea:
|
||||
|
||||
#### Hash Time-Locked Contracts
|
||||
|
||||
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.
|
||||
|
||||
#### Bidirectional Payment Channels
|
||||
|
||||
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 reopen it when getting close to the timeout,
|
||||
whereas with relative locktime, the clock starts ticking the moment the
|
||||
transactions 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.
|
||||
|
||||
|
||||
#### Lightning Network
|
||||
|
||||
The lightning network extends the bidirectional payment channel idea to allow for payments to be routed over multiple bidirectional payment channel hops.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
A simple output, paying to Alice might then look like:
|
||||
|
||||
HASH160 <revokehash> EQUAL
|
||||
IF
|
||||
<Bob's pubkey>
|
||||
ELSE
|
||||
"24h" CHECKSEQUENCEVERIFY DROP
|
||||
<Alice's pubkey>
|
||||
ENDIF
|
||||
CHECKSIG
|
||||
|
||||
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.
|
||||
|
||||
With CHECKLOCKTIMEVERIFY, this would look like:
|
||||
|
||||
HASH160 <revokehash> EQUAL
|
||||
IF
|
||||
<Bob's pubkey>
|
||||
ELSE
|
||||
"2015/12/15" CHECKLOCKTIMEVERIFY DROP
|
||||
<Alice's pubkey>
|
||||
ENDIF
|
||||
CHECKSIG
|
||||
|
||||
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.
|
||||
|
||||
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. CHECKSEQUENCEVERIFY allows you
|
||||
to avoid making such a tradeoff.
|
||||
|
||||
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 CHECKSEQUENCEVERIFY, a HTLC payable to
|
||||
Alice might look like the following 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
|
||||
|
||||
and correspondingly in Bob's commitment transaction:
|
||||
|
||||
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 that both CHECKSEQUENCEVERIFY and CHECKLOCKTIMEVERIFY are used in the
|
||||
final branch of 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.
|
||||
|
||||
See the [https://github.com/ElementsProject/lightning/blob/master/doc/deployable-lightning.pdf Deployable Lightning] paper.
|
||||
|
||||
|
||||
#### 2-Way Pegged Sidechains
|
||||
|
||||
The 2-way pegged sidechain requires a new REORGPROOFVERIFY opcode, the semantics of which are outside the scope of this BIP. CHECKSEQUENCEVERIFY is used to make sure that sufficient time has passed since the return peg was posted to publish a reorg proof:
|
||||
|
||||
IF
|
||||
lockTxHeight <lockTxHash> nlocktxOut [<workAmount>] reorgBounty Hash160(<...>) <genesisHash> REORGPROOFVERIFY
|
||||
ELSE
|
||||
withdrawLockTime CHECKSEQUENCEVERIFY DROP HASH160 p2shWithdrawDest EQUAL
|
||||
ENDIF
|
||||
|
||||
|
||||
## Specification
|
||||
|
||||
Refer to the reference implementation, reproduced below, for the precise
|
||||
semantics and detailed rationale for those semantics.
|
||||
|
||||
<pre>
|
||||
/* Below flags apply in the context of BIP 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 BIP 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;
|
||||
}
|
||||
</pre>
|
||||
|
||||
## Reference Implementation
|
||||
|
||||
A reference implementation is provided by the following pull request:
|
||||
|
||||
https://github.com/bitcoin/bitcoin/pull/7524
|
||||
|
||||
|
||||
## Deployment
|
||||
|
||||
This BIP is to be deployed by "versionbits" BIP9 using bit 0.
|
||||
|
||||
For Bitcoin '''mainnet''', the BIP9 '''starttime''' will be midnight 1st May 2016 UTC (Epoch timestamp 1462060800) and BIP9 '''timeout''' will be midnight 1st May 2017 UTC (Epoch timestamp 1493596800).
|
||||
|
||||
For Bitcoin '''testnet''', the BIP9 '''starttime''' will be midnight 1st March 2016 UTC (Epoch timestamp 1456790400) and BIP9 '''timeout''' will be midnight 1st May 2017 UTC (Epoch timestamp 1493596800).
|
||||
|
||||
This BIP must be deployed simultaneously with BIP68 and BIP113 using the same deployment mechanism.
|
||||
|
||||
## Credits
|
||||
|
||||
Mark Friedenbach invented the application of sequence numbers to
|
||||
achieve relative lock-time, and wrote the reference implementation of
|
||||
CHECKSEQUENCEVERIFY.
|
||||
|
||||
The reference implementation and this BIP was based heavily on work
|
||||
done by Peter Todd for the closely related BIP 65.
|
||||
|
||||
BtcDrak authored this BIP document.
|
||||
|
||||
Thanks to Eric Lombrozo and Anthony Towns for contributing example use cases.
|
||||
|
||||
|
||||
## References
|
||||
|
||||
[BIP 9](/protocol/forks/bip-0009) Versionbits
|
||||
|
||||
[BIP 68](/protocol/forks/bip-0068) Relative lock-time through consensus-enforced sequence numbers
|
||||
|
||||
[BIP 65](/protocol/forks/bip-0065) OP_CHECKLOCKTIMEVERIFY
|
||||
|
||||
[BIP 113](/protocol/forks/bip-0113) Median past block time for time-lock constraints
|
||||
|
||||
[HTLCs using OP_CHECKSEQUENCEVERIFY/OP_LOCKTIMEVERIFY and revocation hashes](http://lists.linuxfoundation.org/pipermail/lightning-dev/2015-July/000021.html)
|
||||
|
||||
[Lightning Network](http://lightning.network/lightning-network-paper.pdf)
|
||||
|
||||
[Deployable Lightning](https://github.com/ElementsProject/lightning/blob/master/doc/deployable-lightning.pdf)
|
||||
|
||||
[Scaling Bitcoin to Billions of Transactions Per Day](http://diyhpl.us/diyhpluswiki/transcripts/sf-bitcoin-meetup/2015-02-23-scaling-bitcoin-to-billions-of-transactions-per-day/)
|
||||
|
||||
[Softfork deployment considerations](http://lists.linuxfoundation.org/pipermail/bitcoin-dev/2015-August/010396.html)
|
||||
|
||||
[Version bits](https://gist.github.com/sipa/bf69659f43e763540550)
|
||||
|
||||
[Jeremy Spilman Micropayment Channels](https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2013-April/002433.html)
|
||||
|
||||
|
||||
## Copyright
|
||||
|
||||
This document is placed in the public domain.
|
||||
@@ -0,0 +1,126 @@
|
||||
<pre>
|
||||
BIP: 113
|
||||
Layer: Consensus (soft fork)
|
||||
Title: Median time-past as endpoint for lock-time calculations
|
||||
Author: Thomas Kerin <me@thomaskerin.io>
|
||||
Mark Friedenbach <mark@friedenbach.org>
|
||||
Comments-Summary: No comments yet.
|
||||
Comments-URI: https://github.com/bitcoin/bips/wiki/Comments:BIP-0113
|
||||
Status: Final
|
||||
Type: Standards Track
|
||||
Created: 2015-08-10
|
||||
License: PD
|
||||
</pre>
|
||||
|
||||
|
||||
## Abstract
|
||||
|
||||
This BIP is a proposal to redefine the semantics used in determining a
|
||||
time-locked transaction's eligibility for inclusion in a block. The
|
||||
median of the last 11 blocks is used instead of the block's timestamp,
|
||||
ensuring that it increases monotonically with each block.
|
||||
|
||||
|
||||
## Motivation
|
||||
|
||||
At present, transactions are excluded from inclusion in a block if the
|
||||
present time or block height is less than or equal to that specified
|
||||
in the locktime. Since the consensus rules do not mandate strict
|
||||
ordering of block timestamps, this has the unfortunate outcome of
|
||||
creating a perverse incentive for miners to lie about the time of
|
||||
their blocks in order to collect more fees by including transactions
|
||||
that by wall clock determination have not yet matured.
|
||||
|
||||
This BIP proposes comparing the locktime against the median of the
|
||||
past 11 block's timestamps, rather than the timestamp of the block
|
||||
including the transaction. Existing consensus rules guarantee this
|
||||
value to monotonically advance, thereby removing the capability for
|
||||
miners to claim more transaction fees by lying about the timestamps of
|
||||
their block.
|
||||
|
||||
This proposal seeks to ensure reliable behaviour in locktime calculations
|
||||
as required by BIP65 (CHECKLOCKTIMEVERIFY) and matching the behavior of
|
||||
BIP68 (sequence numbers) and BIP112 (CHECKSEQUENCEVERIFY).
|
||||
|
||||
|
||||
## Specification
|
||||
|
||||
The values for transaction locktime remain unchanged. The difference is only in
|
||||
the calculation determining whether a transaction can be included. Instead of
|
||||
an unreliable timestamp, the following function is used to determine the current
|
||||
block time for the purpose of checking lock-time constraints:
|
||||
|
||||
enum { nMedianTimeSpan=11 };
|
||||
|
||||
int64_t GetMedianTimePast(const CBlockIndex* pindex)
|
||||
{
|
||||
int64_t pmedian[nMedianTimeSpan];
|
||||
int64_t* pbegin = &pmedian[nMedianTimeSpan];
|
||||
int64_t* pend = &pmedian[nMedianTimeSpan];
|
||||
for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
|
||||
*(--pbegin) = pindex->GetBlockTime();
|
||||
std::sort(pbegin, pend);
|
||||
return pbegin[(pend - pbegin)/2];
|
||||
}
|
||||
|
||||
Lock-time constraints are checked by the consensus method IsFinalTx().
|
||||
This method takes the block time as one parameter. This BIP proposes
|
||||
that after activation calls to IsFinalTx() within consensus code use
|
||||
the return value of `GetMedianTimePast(pindexPrev)` instead.
|
||||
|
||||
The new rule applies to all transactions, including the coinbase transaction.
|
||||
|
||||
A reference implementation of this proposal is provided by the
|
||||
following pull request:
|
||||
|
||||
https://github.com/bitcoin/bitcoin/pull/6566
|
||||
|
||||
|
||||
## Deployment
|
||||
|
||||
This BIP is to be deployed by "versionbits" BIP9 using bit 0.
|
||||
|
||||
For Bitcoin '''mainnet''', the BIP9 '''starttime''' will be midnight 1st May 2016 UTC (Epoch timestamp 1462060800) and BIP9 '''timeout''' will be midnight 1st May 2017 UTC (Epoch timestamp 1493596800).
|
||||
|
||||
For Bitcoin '''testnet''', the BIP9 '''starttime''' will be midnight 1st March 2016 UTC (Epoch timestamp 1456790400) and BIP9 '''timeout''' will be midnight 1st May 2017 UTC (Epoch timestamp 1493596800).
|
||||
|
||||
This BIP must be deployed simultaneously with BIP68 and BIP112 using the same deployment mechanism.
|
||||
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
Mark Friedenbach for designing and authoring the reference
|
||||
implementation of this BIP.
|
||||
|
||||
Thanks go to Gregory Maxwell who came up with the original idea,
|
||||
in #bitcoin-wizards on 2013-07-16.
|
||||
|
||||
Thomas Kerin authored this BIP document.
|
||||
|
||||
|
||||
## Compatibility
|
||||
|
||||
Transactions generated using time-based lock-time will take
|
||||
approximately an hour longer to confirm than would be expected under
|
||||
the old rules. This is not known to introduce any compatibility
|
||||
concerns with existing protocols.
|
||||
|
||||
|
||||
## References
|
||||
|
||||
[BIP9: Versionbits](/protocol/forks/bip-0009)
|
||||
|
||||
[BIP65: OP_CHECKLOCKTIMEVERIFY](/protocol/forks/bip-0065)
|
||||
|
||||
[BIP68: Consensus-enforced transaction replacement signaled via sequence numbers](/protocol/forks/bip-0068)
|
||||
|
||||
[BIP112: CHECKSEQUENCEVERIFY](/protocol/forks/bip-0112)
|
||||
|
||||
[Softfork deployment considerations](http://lists.linuxfoundation.org/pipermail/bitcoin-dev/2015-August/010396.html)
|
||||
|
||||
[Version bits](https://gist.github.com/sipa/bf69659f43e763540550)
|
||||
|
||||
|
||||
## Copyright
|
||||
|
||||
This document is placed in the public domain.
|
||||
Reference in New Issue
Block a user