1
0
mirror of https://github.com/bitcoinbook/bitcoinbook synced 2024-12-26 00:18:11 +00:00

All: update to comply with current draft of bip-bikeshed

This commit is contained in:
David A. Harding 2023-06-30 13:39:58 -10:00
parent e6f895732a
commit a4f337b840
17 changed files with 375 additions and 374 deletions

View File

@ -880,7 +880,7 @@ The transaction decode shows all the components of this transaction,
including the transaction inputs and outputs. In this case we see that
the transaction used one input and generated two outputs. The input to
this transaction was the output from a previously confirmed transaction
(shown as the vin +txid+). The two outputs correspond to the payment to
(shown as the input +txid+). The two outputs correspond to the payment to
Bob and the change back to Alice.
We can further explore the blockchain by examining the previous

View File

@ -388,21 +388,21 @@ library] to do the elliptic curve math.
.Elliptic curve cryptography: visualizing the multiplication of a point G by an integer k on an elliptic curve
image::images/mbc2_0404.png["ecc_illustrated"]
=== ScriptPubKey and ScriptSig
=== Output and Input Scripts
Although the illustration from the original Bitcoin paper, <<pay-to-pure-pubkey>>,
shows public keys (pubkeys) and signatures (sigs) being used directly,
the first version of Bitcoin instead had payments sent to a field called
_scriptPubKey_ and had them authorized by a field called _scriptSig_.
_output script_ and had spends of those bitcoins authorized by a field called _input script_.
These fields allow additional operations to be performed in addition to
(or instead of) verifying that a signature corresponds to a public key.
For example, a scriptPubKey can contain two public keys and require two
corresponding signatures be placed in the spending scriptSig.
For example, an output script can contain two public keys and require two
corresponding signatures be placed in the spending input script.
Later, in <<tx_script>>, we'll learn about scripts in detail. For now,
all we need to understand is that bitcoins are received to a
scriptPubKey which acts like a public key, and bitcoin spending is
authorized by a scriptSig which acts like a signature.
all we need to understand is that bitcoins are received to an
output script which acts like a public key, and bitcoin spending is
authorized by a input script which acts like a signature.
[[p2pk]]
=== IP Addresses: The Original Address For Bitcoin (P2PK)
@ -439,21 +439,21 @@ looking at the blockchain and noticing that all of the transactions paid
the same public key.
Using the public key her node received from Bob's node, Alice's wallet
would construct a transaction output paying a very simple scriptPubKey:
would construct a transaction output paying a very simple output script:
----
<Bob's public key> OP_CHECKSIG
----
Bob would later be able to spend that output with a scriptSig consisting
Bob would later be able to spend that output with an input script consisting
entirely of his signature:
----
<Bob's signature>
----
To figure out what a scriptPubKey and scriptSig are doing, you can
combine them together (scriptSig first) and then note that each piece of
To figure out what an output and input script are doing, you can
combine them together (input script first) and then note that each piece of
data (shown in angle brackets) is placed at the top of a list of items,
called a stack. When an operation code (opcode) is encountered, it uses
items from the stack, starting with the topmost items. Let's look at
@ -564,13 +564,13 @@ where _K_ is the public key and _A_ is the resulting commitment.
Now that we understand how to make a commitment to a public key, we need
to figure out how to use it in a transaction. Consider the following
scriptPubKey:
output script:
----
OP_DUP OP_HASH160 <Bob's commitment> OP_EQUAL OP_CHECKSIG
----
And also the following scriptSig:
And also the following input script:
----
<Bob's signature> <Bob's public key>
@ -592,8 +592,8 @@ so now the top of the stack is a hash of Bob's public key. Next, the
commitment to Bob's public key is added to the top of the stack. The
+OP_EQUALVERIFY+ operation consumes the top two items and verifies that
they are equal; that should be the case if the public key Bob provided
in the scriptSig is the same public key used to create the commitment in
the scriptPubKey that Alice paid. If +OP_EQUALVERIFY+ fails, the whole
in the input script is the same public key used to create the commitment in
the output script that Alice paid. If +OP_EQUALVERIFY+ fails, the whole
script fails. Finally, we're left with a stack containing just Bob's
signature and his public key; the +OP_CHECKSIG+ opcode verifies they
correspond with each other and that the signature commits to the
@ -664,7 +664,7 @@ To convert data (a number) into a base58check format, we first add a
prefix to the data, called the "version byte," which serves to easily
identify the type of data that is encoded. For example, the prefix zero
(0x00 in hex) indicates that the data should be used as the commitment (hash) in
a legacy P2PKH scriptPubKey. A list of common version prefixes is shown
a legacy P2PKH output script. A list of common version prefixes is shown
in <<base58check_versions>>.
Next, we compute the "double-SHA" checksum, meaning we apply the SHA256
@ -866,14 +866,14 @@ compressed public keys.
As we've seen in preceding sections, someone receiving Bitcoins (like
Bob) can require payments to him contain certain constraints in their
scriptPubKeys. Bob will need to fulfill those constraints using a
scriptSig when he spends those bitcoins. In <<p2pk>>, the constraint
was simply that the scriptSig needed to provide an appropriate
output script. Bob will need to fulfill those constraints using an
input script when he spends those bitcoins. In <<p2pk>>, the constraint
was simply that the input script needed to provide an appropriate
signature. In <<addresses_for_p2pkh>>, an appropriate public key also needed to be
provided.
In order for a spender (like Alice) to place the constraints Bob wants
in the scriptPubKey she uses to pay him, Bob needs to communicate those
in the output script she uses to pay him, Bob needs to communicate those
constraints to her. This is similar to the problem of Bob needing to
communicate his public key to her. Like that problem, where
public keys can be fairly large, the constraints Bob uses can also be
@ -883,22 +883,22 @@ for which she needs to pay transaction fees every time she wants to spend
money to Bob. However, the solution of using hash functions to create
small commitments to large amounts of data also applies here.
The BIP16 upgrade to the Bitcoin protocol in 2013 allows a
scriptPubKey to commit to a _redemption script_ (_redeemScript_). When
Bob spends his bitcoins, his scriptSig need to provide a redeemScript
The BIP16 upgrade to the Bitcoin protocol in 2013 allows an
output script to commit to a _redemption script_ (_redeem script_). When
Bob spends his bitcoins, his input script need to provide a redeem script
that matches the commitment and also any data necessary to satisfy the
redeemScript (such as signatures). Let's start by imagining Bob wants
redeem script (such as signatures). Let's start by imagining Bob wants
to require two signatures to spend his bitcoins, one signature from his
desktop wallet and one from a hardware signing device. He puts those
conditions into a redeemScript:
conditions into a redeem script:
----
<public key 1> OP_CHECKSIGVERIFY <public key 2> OP_CHECKSIG
----
He then creates a commitment to the redeemScript using the same
He then creates a commitment to the redeem script using the same
HASH160 mechanism used for P2PKH commitments, +RIPEMD160(SHA256(script))+.
That commitment is placed into the scriptPubKey using a special
That commitment is placed into the output script using a special
template:
----
@ -908,24 +908,24 @@ OP_HASH160 <commitment> OP_EQUAL
[WARNING]
====
Payments to Script Hashes (P2SH) must use the specific P2SH template
with no extra data or conditions in the scriptPubKey. If the
scriptPubKey is not exactly +OP_HASH160 <20 bytes> OP_EQUAL+, the
redeemScript will not be used and any bitcoins may either be unspendable
with no extra data or conditions in the output script. If the
output script is not exactly +OP_HASH160 <20 bytes> OP_EQUAL+, the
redeem script will not be used and any bitcoins may either be unspendable
or spendable by anyone (meaning anyone can take them).
====
When Bob goes to spend the payment he received to the commitment for his
script, he uses a scriptSig that includes the redeemScript, with it
script, he uses an input script that includes the redeem script, with it
serialized as a single data element. He also provides the signatures
he needs to satisfy the redeemScript, putting them in the order that
he needs to satisfy the redeem script, putting them in the order that
they will be consumed by the opcodes:
----
<signature2> <signature1> <redeemScript>
<signature2> <signature1> <redeem script>
----
When Bitcoin full nodes receive Bob's spend, they'll verify that the
serialized redeemScript will hash to the same value as the commitment.
serialized redeem script will hash to the same value as the commitment.
Then they'll replace it on the stack with its deserialized value:
----
@ -968,7 +968,7 @@ Legacy addresses were supplanted by the bech32 family of addresses.
.P2SH collision attacks
****
All addresses based on hash functions are theoretically vulnerable to an
attacker finding two different inputs (e.g. redeemScripts) that produce
attacker finding two different inputs (e.g. redeem scripts) that produce
the same hash function output (commitment). For addresses created
entirely by a single party, the chance of an attacker generating a
different input for an existing commitment is proportional to the
@ -1363,7 +1363,7 @@ With the checksum created, each 5-bit character in the data part
(including the witness version, witness program, and checksum) is
converted to alphanumeric characters.
For decoding back into a scriptPubKey, we work in reverse. First let's
For decoding back into an output script, we work in reverse. First let's
use the reference library to decode two of our addresses:
----
@ -1378,7 +1378,7 @@ decode(hrp, addr)
----
We get back both the witness version and the witness program. Those can
be inserted into the template for our scriptPubKey:
be inserted into the template for our output script:
----
<version> <program>

View File

@ -284,7 +284,7 @@ node will start a "handshake" (see <<network_handshake>>) by
transmitting a +version+ message, which contains basic identifying
information, including:
+nVersion+:: The Bitcoin P2P protocol version the client "speaks" (e.g., 70002)
+Version+:: The Bitcoin P2P protocol version the client "speaks" (e.g., 70002)
+nLocalServices+:: A list of local services supported by the node, currently just +NODE_NETWORK+
+nTime+:: The current time
+addrYou+:: The IP address of the remote node as seen from this node
@ -296,7 +296,7 @@ information, including:
The +version+ message is always the first message sent by any peer to
another peer. The local peer receiving a +version+ message will examine
the remote peer's reported +nVersion+ and decide if the remote peer is
the remote peer's reported +Version+ and decide if the remote peer is
compatible. If the remote peer is compatible, the local peer will
acknowledge the +version+ message and establish a connection by sending
a +verack+.
@ -974,7 +974,7 @@ transaction affecting that wallet. For a wallet to be effective, it
needs to learn two types of information:
1. When it has received money. Specifically, when a transaction
output contains a scriptPubKey that the wallet controls (such as by
output contains a script that the wallet controls (such as by
controlling the authorized private key).
2. When it has spent money. Specifically, when a transaction input
@ -991,7 +991,7 @@ accurate filter.
For both the primary and secondary goals to be met, a filter would need
to reference two types of information:
1. The scriptPubKey for every output in every transaction in a block.
1. The script for every output in every transaction in a block.
2. The outpoint for every input in every transaction in a block.
@ -1001,27 +1001,27 @@ to accomplish the primary goal if we sacrificed the secondary goal. In
the new design, a block filter would still references two types of
information, but they'd be more closely related:
1. As before, the scriptPubKey for every output in every transaction in a
1. As before, the script for every output in every transaction in a
block.
2. In a change, it would also reference the scriptPubKey of the output
2. In a change, it would also reference the script of the output
referenced by the outpoint for every input in every transaction in a
block. In other words, the scriptPubKey being spent.
block. In other words, the output script being spent.
This had several advantages. First, it meant that wallets didn't need
to track outpoints; they could instead just scan for the the
scriptPubKeys to which they expected to receive money. Second, any time a
output scripts to which they expected to receive money. Second, any time a
later transaction in a block spends the output of an earlier
transaction in the same block, they'll both reference the same
scriptPubKey. More than one reference to the same scriptPubKey is
output script. More than one reference to the same output script is
redundant in a compact block filter, so the redundant copies can be
removed, shrinking the size of the filters.
When full nodes validate a block, they need access to the scriptPubKeys
When full nodes validate a block, they need access to the output scripts
for both the current transaction outputs in a block and the transaction
outputs from previous blocks that are being referenced in inputs, so
they're able to build compact block filters in this simplified model.
But a block itself doesn't include the scriptPubKeys from transactions
But a block itself doesn't include the output scripts from transactions
included in previous blocks, so there's no convenient way for a client
to verify a block filter was built correctly. However, there is an
alternative that can help a client detect if a peer is lying to it:
@ -1066,7 +1066,7 @@ more bandwidth than expected.
==== Reducing bandwidth with lossy encoding
The data about the transactions in a block that we want to communicate
is a scriptPubKey. ScriptPubKeys vary in length and follow patterns,
is an output script. Output scripts vary in length and follow patterns,
which means the differences between them won't be evenly distributed
like we want. However, we've already seen in many places in this book
that we can use a hash function to create a commitment to some data and
@ -1079,23 +1079,23 @@ faster and more configurable non-cryptographic hash functions, such as
the SipHash function we'll use for compact block filters.
The details of the algorithm used are described in BIP158, but the gist
is that each scriptPubKey is reduced to a 64 bit commitment using
is that each output script is reduced to a 64 bit commitment using
SipHash and some arthritic operations. You can think of this as
taking a set of large numbers and truncating them to shorter numbers, a
process that loses data (so it's called _lossy encoding_). By losing
some information, we don't need to store as much information later,
which saves space. In this case, we go from a typical scriptPubKey
which saves space. In this case, we go from a typical output script
that's 160 bits or longer down to just 64 bits.
==== Using compact block filters
The 64 bit value for every commitment to a scriptPubKey in a block are
The 64 bit value for every commitment to an output script in a block are
sorted, duplicate entries are removed, and the GCS is constructed by
finding the differences (deltas) between each entry. That compact block
filter is then distributed by peers to their clients (such as wallets).
A client uses the deltas to reconstruct the original commitments. The
client such as a wallet also takes all the scriptPubKeys it is
client such as a wallet also takes all the output scripts it is
monitoring for and generates commitments in the same way as BIP158. It
checks whether any of its generated commitments match the commitments in
the filter.

View File

@ -273,8 +273,8 @@ criteria:
- Each output value, as well as the total, must be within the allowed
range of values (zero or more, but less than 21m coins).
- +nLocktime+ is equal to +INT_MAX+, or +nLocktime+ and +nSequence+
values are satisfied according to the locktime and BIP68 rules.
- Lock time is equal to +INT_MAX+, or lock time and sequence
values are satisfied according to the lock time and BIP68 rules.
- The number of signature operations (SIGOPS) contained in the
transaction is less than the signature operation limit.
@ -492,7 +492,7 @@ structure of the coinbase transaction's input.
| 32 bytes | Transaction Hash | Pointer to the transaction containing the UTXO to be spent
| 4 bytes | Output Index | The index number of the UTXO to be spent, first one is 0
| 1&#x2013;9 bytes (VarInt) | Script Size | Script length in bytes, to follow
| Variable | ScriptSig | A script that fulfills the conditions of the UTXO scriptPubKey
| Variable | Input script | A script that fulfills the conditions of the UTXO output script
| 4 bytes | Sequence Number | Multipurpose field used for BIP68 time locks and transaction replacement signaling
|=======
@ -512,14 +512,14 @@ In a coinbase transaction, the first two fields are set to values that
do not represent a UTXO reference. Instead of a "transaction hash," the
first field is filled with 32 bytes all set to zero. The "output index"
is filled with 4 bytes all set to 0xFF (255 decimal). The
+scriptSig+ is replaced by coinbase data, a data field used by
input script is replaced by coinbase data, a data field used by
the miners, as we will see next.
[[duplicate_transactions]]
==== Coinbase Data
((("coinbase transactions", "coinbase data")))Coinbase transactions do
not have a +scriptSig+ field. Instead, this
not have an input script field. Instead, this
field is replaced by coinbase data, which must be between 2 and 100
bytes. Except for the first few bytes, the rest of the coinbase data can
be used by miners in any way they want; it is arbitrary data.
@ -1169,11 +1169,11 @@ miner can influence the timestamps in order to gain fees from
transactions with a timelock that hasn't yet matured.
Median time past changes the implementation of time calculations for
+nLocktime+, +CLTV+, +nSequence+, and +CSV+. The consensus time
lock time, +CLTV+, sequence, and +CSV+. The consensus time
calculated by median time past is usually about one hour behind
wall clock time. If you create timelock transactions, you should account
for it when estimating the desired value to encode in +nLocktime+,
+nSequence+, +CLTV+, and +CSV+.
for it when estimating the desired value to encode in lock time,
sequence, +CLTV+, and +CSV+.
=== Successfully Mining the Block
@ -2173,7 +2173,7 @@ effect. Execution continues after the NOP opcode as if it wasn't there.
A soft fork therefore can modify the semantics of a NOP code to give it
new meaning. For example, BIP65 (+CHECKLOCKTIMEVERIFY+) reinterpreted
the NOP2 opcode. Clients implementing BIP65 interpret NOP2 as
+OP_CHECKLOCKTIMEVERIFY+ and impose an absolute locktime consensus rule
+OP_CHECKLOCKTIMEVERIFY+ and impose an absolute lock time consensus rule
on UTXOs that contain this opcode in their locking scripts. This change
is a soft fork because a transaction that is valid under BIP65 is also
valid on any client that is not implementing (ignorant of) BIP65. To

View File

@ -581,7 +581,7 @@ to fix those:
commitment that is in her favor.
Both of these problems can be solved with timelocks&#x2014;let's look at
how we could use transaction-level timelocks (+nLocktime+).
how we could use transaction-level time locks.
Emma cannot risk funding a 2-of-2 multisig unless she has a guaranteed
refund. To solve this problem, Emma constructs the funding and refund
@ -591,7 +591,7 @@ transaction to Fabian and obtains his signature.
The refund transaction acts as the first commitment transaction and its
timelock establishes the upper bound for the channel's life. In this
case, Emma could set the +nLocktime+ to 30 days or 4320 blocks into the
case, Emma could set the lock time to 30 days or 4320 blocks into the
future. All subsequent commitment transactions must have a shorter
timelock, so that they can be redeemed before the refund transaction.
@ -604,7 +604,7 @@ Every commitment transaction the parties exchange during the life of the
channel will be timelocked into the future. But the delay will be
slightly shorter for each commitment so the most recent commitment can
be redeemed before the prior commitment it invalidates. Because of the
nLockTime, neither party can successfully propagate any of the
lock time, neither party can successfully propagate any of the
commitment transactions until their timelock expires. If all goes well,
they will cooperate and close the channel gracefully with a settlement
transaction, making it unnecessary to transmit an intermediate
@ -641,8 +641,8 @@ commitments. Thus, the most recent commitment transaction can be
transmitted, spending the inputs and invalidating prior commitment
transactions. The enforcement of smart contracts with absolute timelocks
protects against cheating by one of the parties. This implementation
needs nothing more than absolute transaction-level timelocks
(+nLocktime+). Next, we will see how script-level timelocks,
needs nothing more than absolute transaction-level lock time.
Next, we will see how script-level timelocks,
+CHECKLOCKTIMEVERIFY+ and +CHECKSEQUENCEVERIFY+, can be used to
construct more flexible, useful, and sophisticated state channels.
@ -959,7 +959,7 @@ IF
HASH160 <H> EQUALVERIFY
ELSE
# Refund after timeout.
<locktime> CHECKLOCKTIMEVERIFY DROP
<lock time> CHECKLOCKTIMEVERIFY DROP
<Payer Public Key> CHECKSIG
ENDIF
----
@ -1194,7 +1194,7 @@ startref="alicetwelve")))
Each element of the path contains information on the HTLC that must be
extended to the next hop, the amount that is being sent, the fee to
include, and the CLTV locktime (in blocks) expiration of the HTLC. As
include, and the CLTV lock time (in blocks) expiration of the HTLC. As
the route information propagates, the nodes make HTLC commitments
forward to the next hop.

View File

@ -29,8 +29,8 @@ used.
id="Tsript06")))((("scripting", "transactions and",
id="Stransact06")))The original version of Bitcoin introduced a new
programming language called _Script_, a Forth-like stack-based
language. Both the scriptPubKey placed in an output and the legacy
scriptSig used in a spending transaction are written in this scripting
language. Both the script placed in an output and the legacy
input script used in a spending transaction are written in this scripting
language.
Script is a very simple language. It requires minimal processing and
@ -94,28 +94,28 @@ system.
==== Script Construction
Bitcoin's legacy transaction validation engine relies on two parts of scripts
to validate transactions: a scriptPubKey and a scriptSig.
to validate transactions: an output script and an input script.
A scriptPubKey is a spending condition placed on an output:
An output script is a spending condition placed on an output:
it specifies the conditions that must be met to spend the output in the
future, such as who is authorized to spend the output and how they will
be authenticated.
A scriptSig is a script that satisfies the
conditions placed on an output by a scriptPubKey and allows the output
to be spent. ScriptSigs are part of every transaction input. Most
An input script is a script that satisfies the
conditions placed on an output by an output script and allows the output
to be spent. Input scripts are part of every transaction input. Most
of the time in legacy transactions they contain a digital signature produced by the user's
wallet from his or her private key, but not all scriptSigs
wallet from his or her private key, but not all input scripts
must contain signatures.
Every bitcoin validating node will validate transactions by executing
the scriptPubKey and scriptSig together. As we saw in
the output and input scripts. As we saw in
<<c_transactions>>, each input contains an outpoint which refers to a
previous transaction output. The input also contains a scriptSig. The
validation software will copy the scriptSig, retrieve the UTXO
referenced by the input, and copy the scriptPubKey from that UTXO. The
scriptSig and scriptPubKey are then executed in sequence. The input is
valid if the scriptSig satisfies the scriptPubKey conditions
previous transaction output. The input also contains an input script. The
validation software will copy the input script, retrieve the UTXO
referenced by the input, and copy the output script from that UTXO. The
input and output scripts are then executed in sequence. The input is
valid if the input script satisfies the output script's conditions
(see <<script_exec>>). All the inputs are validated independently, as
part of the overall validation of the transaction.
@ -123,18 +123,18 @@ Note that the steps above involve making copies of all data. The
original data in the previous output and current input is never changed.
In particular, the previous output is invariable and unaffected by
failed attempts to spend it. Only a valid transaction that correctly
satisfies the conditions of the scriptPubKey results in the output being
satisfies the conditions of the output script results in the output being
considered as "spent".
<<scriptSig_and_scriptPubKey>> is an example of the scriptPubKey and
scriptSig for the most common type of legacy Bitcoin transaction (a
<<input_and_output_scripts_legacy>> is an example of the output and
input scripts for the most common type of legacy Bitcoin transaction (a
payment to a public key hash), showing the combined script resulting
from the concatenation of the scripts prior to
validation.
[[scriptSig_and_scriptPubKey]]
.Combining scriptSig and scriptPubKey to evaluate a transaction script
image::../images/mbc2_0603.png["scriptSig_and_scriptPubKey"]
[[input_and_output_scripts_legacy]]
.Combining input and output scripts to evaluate a transaction script
image::../images/mbc2_0603.png["input_and_output_scripts"]
===== The script execution stack
@ -172,21 +172,21 @@ operator +OP_EQUAL+, which checks that the resulting sum is equal to
in this book. For more details on the available script operators and
functions, see <<tx_script_ops>>.
Although most legacy scriptPubKeys refer to a public key hash (essentially, a
Although most legacy output scripts refer to a public key hash (essentially, a
legacy Bitcoin address), thereby requiring proof of ownership to spend the
funds, the script does not have to be that complex. Any combination of
scriptPubKey and scriptSig that results in a TRUE value is valid. The
output and input scripts that results in a TRUE value is valid. The
simple arithmetic we used as an example of the scripting language is
also a valid script.
Use part of the arithmetic example script as the scriptPubKey:
Use part of the arithmetic example script as the output script:
----
3 OP_ADD 5 OP_EQUAL
----
which can be satisfied by a transaction containing an input with the
scriptSig:
input script:
----
2
@ -200,7 +200,7 @@ The validation software combines the scripts:
As we saw in <<simplemath_script>>, when
this script is executed, the result is +OP_TRUE+, making the transaction
valid. Not only have we shown a valid transaction output scriptPubKey, but
valid. Not only have we shown a valid transaction output script, but
the resulting UTXO could be spent by anyone with the arithmetic skills
to know that the number 2 satisfies the script.
@ -237,38 +237,38 @@ When the script execution ends, you should be left with a +TRUE+ value
on the stack.
[[script_exec]]
===== Separate execution of scriptPubKey and scriptSig
===== Separate execution of output and input scripts
In the original Bitcoin
client, scriptPubKey and scriptSig were concatenated and executed
client, output and input scripts were concatenated and executed
in sequence. For security reasons, this was changed in 2010 because of
a vulnerability known as the +1 OP_RETURN+ bug. In the current
implementation, the scripts are executed separately with the stack
transferred between the two executions.
First, the scriptSig executed using the stack execution
engine. If the scriptSig is executed without errors and has
First, the input script executed using the stack execution
engine. If the input script is executed without errors and has
no operations left over, the stack is copied and the
scriptPubKey is executed. If the result of executing scriptPubKey
with the stack data copied from scriptSig is +TRUE+,
the scriptSig has succeeded in resolving the conditions imposed
by the scriptPubKey and, therefore, the input is a valid authorization
output script is executed. If the result of executing the output script
with the stack data copied from the input script is +TRUE+,
the input script has succeeded in resolving the conditions imposed
by the output script and, therefore, the input is a valid authorization
to spend the UTXO. If any result other than +TRUE+ remains after
execution of the combined script, the input is invalid because it has
failed to satisfy the spending conditions placed on the output.
//SOMEDAY:implications of not being able to use script in scriptSig
//SOMEDAY:implications of not being able to use script in input script
[[p2pkh]]
==== Pay-to-Public-Key-Hash (P2PKH)
((("Pay-to-Public-Key-Hash (P2PKH)")))
A Pay-to-Public-Key-Hash or "P2PKH" script uses a scriptPubKey that
A Pay-to-Public-Key-Hash or "P2PKH" script uses a output script that
contains a hash which commits to a public key. P2PKH is best known as a
the basis for a legacy Bitcoin address. A P2PKH output can be spent by
presenting a public key which matches the hash commitment and a digital
signature created by the corresponding private key (see
<<c_signatures>>). Let's look at an example of a P2PKH scriptPubKey:
<<c_signatures>>). Let's look at an example of a P2PKH output script:
----
OP_DUP OP_HASH160 <Key Hash> OP_EQUALVERIFY OP_CHECKSIG
@ -279,7 +279,7 @@ address. Most applications would show the _public key hash_ in a script
using hexadecimal encoding and not the familiar Bitcoin
address Base58Check format that begins with a "1."
The preceding scriptPubKey can be satisfied with a scriptSig
The preceding output script can be satisfied with an input script
of the form:
----
@ -294,8 +294,8 @@ script:
----
When executed, this combined script will evaluate to TRUE if, and only
if, the scriptSig matches the conditions set by the scriptPubKey.
In other words, the result will be TRUE if the scriptSig
if, the input script matches the conditions set by the output script.
In other words, the result will be TRUE if the input script
has a valid signature from Bob's private key that corresponds to
the public key hash set as an encumbrance.
@ -338,7 +338,7 @@ to tell "M" and "N" apart when they're spoken, so we use the alternative
K-of-N. Both phrases refer to the same type of signature scheme.
====
At this time, _standard_ multisignature scriptPubKeys are limited to at most 3
At this time, _standard_ multisignature output scripts are limited to at most 3
listed public keys, meaning you can do anything from a 1-of-1 to a
3-of-3 multisignature or any combination within that range.
You may want to check the +IsStandard()+ function to see what is currently
@ -348,7 +348,7 @@ multisignature scripts wrapped in a Pay-to-Script-Hash (P2SH) script.
P2SH multisignature scripts are limited to 15 keys, allowing for up to
15-of-15 multisignature. We will learn about P2SH in <<p2sh>>.
The general form of a scriptPubKey setting an K-of-N multisignature
The general form of a output script setting an K-of-N multisignature
condition is:
----
@ -358,14 +358,14 @@ K <Public Key 1> <Public Key 2> ... <Public Key N> N OP_CHECKMULTISIG
where N is the total number of listed public keys and K is the threshold
of required signatures to spend the output.
A scriptPubKey setting a 2-of-3 multisignature condition looks like
An output script setting a 2-of-3 multisignature condition looks like
this:
----
2 <Public Key A> <Public Key B> <Public Key C> 3 OP_CHECKMULTISIG
----
The preceding scriptPubKey can be satisfied with a scriptSig
The preceding output script can be satisfied with an input script
containing pairs of signatures and public keys:
----
@ -382,8 +382,8 @@ The two scripts together would form the combined validation script:
----
When executed, this combined script will evaluate to TRUE if, and only
if, the scriptSig script matches the conditions set by the scriptPubKey.
In this case, the condition is whether the scriptSig has
if, the input script script matches the conditions set by the output script.
In this case, the condition is whether the input script has
a valid signature from the two private keys that correspond to two of
the three public keys set as an encumbrance.
@ -429,7 +429,7 @@ like this:
OP_0 <Signature B> <Signature C> 2 <Public Key A> <Public Key B> <Public Key C> 3 OP_CHECKMULTISIG
----
Thus the scriptSig actually used in multisig is not:
Thus the input script actually used in multisig is not:
----
<Signature B> <Signature C>
@ -517,7 +517,7 @@ than a simple payment transaction, because this script contains very
long public keys. The burden of that extra data would be
borne by the customer in the form of extra transaction fees. Finally, a large transaction
script like this would be carried in the UTXO set in every full
node, until it was spent. All of these issues make using complex scriptPubKeys
node, until it was spent. All of these issues make using complex output scripts
difficult in practice.
P2SH was developed to resolve these practical difficulties and to make
@ -529,33 +529,33 @@ matches the commitment in addition to the data which satisfies the script. In si
P2SH means "pay to a script matching this hash, a script that will be
presented later when this output is spent."
((("redeemScripts")))((("scripting", "redeemScripts")))In P2SH
((("redeem scripts")))((("scripting", "redeem scripts")))In P2SH
transactions, the script that is replaced by a hash is referred
to as the _redeemScript_ because it is presented to the system at
redemption time rather than as a scriptPubKey. <<without_p2sh>> shows
to as the _redeem script_ because it is presented to the system at
redemption time rather than as an output script. <<without_p2sh>> shows
the script without P2SH and <<with_p2sh>> shows the same script encoded
with P2SH.
[[without_p2sh]]
.Complex script without P2SH
|=======
| ScriptPubKey | 2 PubKey1 PubKey2 PubKey3 PubKey4 PubKey5 5 OP_CHECKMULTISIG
| ScriptSig | Sig1 Sig2
| Output script | 2 PubKey1 PubKey2 PubKey3 PubKey4 PubKey5 5 OP_CHECKMULTISIG
| Input script | Sig1 Sig2
|=======
[[with_p2sh]]
.Complex script as P2SH
|=======
| RedeemScript | 2 PubKey1 PubKey2 PubKey3 PubKey4 PubKey5 5 OP_CHECKMULTISIG
| ScriptPubKey | OP_HASH160 <20-byte hash of redeemScript> OP_EQUAL
| ScriptSig | Sig1 Sig2 <redeemScript>
| Redeem script | 2 PubKey1 PubKey2 PubKey3 PubKey4 PubKey5 5 OP_CHECKMULTISIG
| Output script | OP_HASH160 <20-byte hash of redeem script> OP_EQUAL
| Input script | Sig1 Sig2 <redeem script>
|=======
As you can see from the tables, with P2SH the complex script that
details the conditions for spending the output (redeemScript) is not
presented in the scriptPubKey. Instead, only a hash of it is in the
scriptPubKey and the reedemScript itself is presented later, as part
of the scriptSig when the output is spent. This shifts the burden
details the conditions for spending the output (redeem script) is not
presented in the output script. Instead, only a hash of it is in the
output script and the reedemScript itself is presented later, as part
of the input script when the output is spent. This shifts the burden
in fees and complexity from the sender to the recipient (spender) of the
transaction.
@ -599,18 +599,18 @@ echo \
----
The series of commands above first encodes Mohammed's multisig
redeemScript as a serialized hex-encoded bitcoin Script. The next +bx+ command
redeem script as a serialized hex-encoded bitcoin Script. The next +bx+ command
calculates the SHA256 hash of that. The next +bx+ command hashes again
with RIPEMD160, producing the final script-hash:
The 20-byte hash of Mohammed's redeemScript is:
The 20-byte hash of Mohammed's redeem script is:
----
54c557e07dde5bb6cb791c7a540e0a4796f5e97e
----
A P2SH transaction locks the output to this hash instead of the longer
redeemScript, using a special scriptPubKey template:
redeem script, using a special output script template:
----
OP_HASH160 54c557e07dde5bb6cb791c7a540e0a4796f5e97e OP_EQUAL
@ -619,23 +619,23 @@ OP_HASH160 54c557e07dde5bb6cb791c7a540e0a4796f5e97e OP_EQUAL
which, as you can see, is much shorter. Instead of "pay to this 5-key
multisignature script," the P2SH equivalent transaction is "pay to a
script with this hash." A customer making a payment to Mohammed's
company need only include this much shorter scriptPubKey in his
company need only include this much shorter output script in his
payment. When Mohammed and his partners want to spend this UTXO, they
must present the original redeemScript (the one whose hash locked the
must present the original redeem script (the one whose hash locked the
UTXO) and the signatures necessary to unlock it, like this:
----
<Sig1> <Sig2> <2 PK1 PK2 PK3 PK4 PK5 5 OP_CHECKMULTISIG>
----
The two scripts are combined in two stages. First, the redeemScript is
checked against the scriptPubKey to make sure the hash matches:
The two scripts are combined in two stages. First, the redeem script is
checked against the output script to make sure the hash matches:
----
<2 PK1 PK2 PK3 PK4 PK5 5 OP_CHECKMULTISIG> OP_HASH160 <redeemScript hash> OP_EQUAL
<2 PK1 PK2 PK3 PK4 PK5 5 OP_CHECKMULTISIG> OP_HASH160 <redeem script hash> OP_EQUAL
----
If the redeemScript hash matches, the redeemScript is executed:
If the redeem script hash matches, the redeem script is executed:
----
<Sig1> <Sig2> 2 PK1 PK2 PK3 PK4 PK5 5 OP_CHECKMULTISIG
@ -698,31 +698,31 @@ scripts in outputs:
present time (payment) to a future time (when it is spent).
- P2SH shifts the transaction fee cost of a long script from the sender
to the recipient, who has to include the long redeemScript to spend
to the recipient, who has to include the long redeem script to spend
it.
==== RedeemScript and Validation
==== Redeem Script and Validation
You are not able to put a P2SH inside a P2SH redeemScript, because the
You are not able to put a P2SH inside a P2SH redeem script, because the
P2SH specification is not recursive. Also, while it is technically
possible to include +OP_RETURN+ (see <<op_return>>) in a redeemScript, as
possible to include +OP_RETURN+ (see <<op_return>>) in a redeem script, as
nothing in the rules prevents you from doing so, it is of no practical
use because executing +OP_RETURN+ during validation will cause the
transaction to be marked invalid.
Note that because the redeemScript is not presented to the network
Note that because the redeem script is not presented to the network
until you attempt to spend a P2SH output, if you create an output with the
hash of an invalid redeemScript, you will not be able to spend
it. The spending transaction, which includes the redeemScript,
hash of an invalid redeem script, you will not be able to spend
it. The spending transaction, which includes the redeem script,
will not be accepted because it is an invalid script. This creates a
risk, because you can send bitcoin to a P2SH address that cannot be spent later.
[WARNING]
====
((("warnings and cautions", "accidental bitcoin invalidation")))P2SH scriptPubKeys
contain the hash of a redeemScript, which gives no clues as to
the content of the redeemScript. The P2SH transaction will be
considered valid and accepted even if the redeemScript is invalid. You
((("warnings and cautions", "accidental bitcoin invalidation")))P2SH output scripts
contain the hash of a redeem script, which gives no clues as to
the content of the redeem script. The P2SH transaction will be
considered valid and accepted even if the redeem script is invalid. You
might accidentally receive bitcoin in such a way that it cannot later be
spent.
====
@ -763,7 +763,7 @@ from the UTXO set and cause the size of the UTXO database to forever
increase, or "bloat."
A compromise was reached
that allows a scriptPubKey starting with +OP_RETURN+ to
that allows an output script starting with +OP_RETURN+ to
add nonpayment data to a transaction output. However, unlike
the use of "fake" UTXOs, the +OP_RETURN+ operator creates an explicitly
_provably unspendable_ output, which does not need to be stored in the
@ -787,7 +787,7 @@ http://proofofexistence.com[Proof of Existence] digital notarization
service uses the 8-byte prefix +DOCPROOF+, which is ASCII encoded as +44
4f 43 50 52 4f 4f 46+ in hexadecimal.
Keep in mind that there is no scriptSig that corresponds to
Keep in mind that there is no input script that corresponds to
+OP_RETURN+ that could possibly be used to "spend" an +OP_RETURN+ output. The
whole point of an +OP_RETURN+ output is that you can't spend the money locked in that
output, and therefore it does not need to be held in the UTXO set as
@ -801,22 +801,22 @@ script to "RETURN" with a +FALSE+ and halt. Thus, if you accidentally
reference a +OP_RETURN+ output as an input in a transaction, that
transaction is invalid.
[[locktime_limitations]]
==== Transaction locktime limitations
[[lock_time_limitations]]
==== Transaction lock time limitations
+nLockTime+ has the limitation that while it makes it possible to spend some outputs in the future, it does not make it impossible to spend them until that time. Let's explain that with the following example.
Lock time has the limitation that while it makes it possible to spend some outputs in the future, it does not make it impossible to spend them until that time. Let's explain that with the following example.
((("use cases", "buying coffee", id="alicesseven")))Alice signs a transaction spending one of her outputs to Bob's address, and sets the transaction +nLockTime+ to 3 months in the future. Alice sends that transaction to Bob to hold. With this transaction Alice and Bob know that:
((("use cases", "buying coffee", id="alicesseven")))Alice signs a transaction spending one of her outputs to Bob's address, and sets the transaction lock time to 3 months in the future. Alice sends that transaction to Bob to hold. With this transaction Alice and Bob know that:
* Bob cannot transmit the transaction to redeem the funds until 3 months have elapsed.
* Bob may transmit the transaction after 3 months.
However:
* Alice can create another transaction, double-spending the same inputs without a locktime. Thus, Alice can spend the same UTXO before the 3 months have elapsed.
* Alice can create another transaction, double-spending the same inputs without a lock time. Thus, Alice can spend the same UTXO before the 3 months have elapsed.
* Bob has no guarantee that Alice won't do that.
It is important to understand the limitations of transaction +nLockTime+. The only guarantee is that Bob will not be able to redeem it before 3 months have elapsed. There is no guarantee that Bob will get the funds. To achieve such a guarantee, the timelock restriction must be placed on the UTXO itself and be part of the script, rather than on the transaction. This is achieved by the next form of timelock, called Check Lock Time Verify.
It is important to understand the limitations of transaction lock time. The only guarantee is that Bob will not be able to redeem it before 3 months have elapsed. There is no guarantee that Bob will get the funds. To achieve such a guarantee, the timelock restriction must be placed on the UTXO itself and be part of the script, rather than on the transaction. This is achieved by the next form of timelock, called Check Lock Time Verify.
==== Check Lock Time Verify (OP_CLTV)
@ -828,7 +828,7 @@ timelock was introduced to Bitcoin as a soft fork upgrade. Based on a
specification in BIP65, a new script operator called
_OP_CHECKLOCKTIMEVERIFY_ (_CLTV_) was added to the scripting language.
+OP_CLTV+ is a per-output timelock, rather than a per-transaction timelock
as is the case with +nLockTime+. This allows for much greater
as is the case with lock time. This allows for much greater
flexibility in the way timelocks are applied.
In simple terms, by committing to the +OP_CLTV+ opcode in an
@ -837,21 +837,21 @@ specified time has elapsed.
[TIP]
====
While +nLockTime+ is a transaction-level timelock, +OP_CLTV+ is an
While lock time is a transaction-level timelock, +OP_CLTV+ is an
output-based timelock.
====
+OP_CLTV+ doesn't replace +nLockTime+, but rather restricts specific UTXO
+OP_CLTV+ doesn't replace lock time, but rather restricts specific UTXO
such that they can only be spent in a future transaction with
+nLockTime+ set to a greater or equal value.
lock time set to a greater or equal value.
The +OP_CLTV+ opcode takes one parameter as input, expressed as a number in
the same format as +nLockTime+ (either a block height or Unix epoch
the same format as lock time (either a block height or Unix epoch
time). As indicated by the +VERIFY+ suffix, +OP_CLTV+ is the type of opcode
that halts execution of the script if the outcome is +FALSE+. If it
results in TRUE, execution continues.
In order to use +OP_CLTV+, you insert it into the redeemScript of the
In order to use +OP_CLTV+, you insert it into the redeem script of the
output in the transaction that creates the output. For
example, if Alice is paying Bob's address, the output would normally
contain a P2PKH script like this:
@ -861,7 +861,7 @@ OP_DUP OP_HASH160 <Bob's Public Key Hash> OP_EQUALVERIFY OP_CHECKSIG
----
To lock it to a time, say 3 months from now, the transaction would be a
P2SH transaction with a redeemScript like this:
P2SH transaction with a redeem script like this:
----
<now + 3 months> OP_CHECKLOCKTIMEVERIFY OP_DROP OP_DUP OP_HASH160 <Bob's Public Key Hash> OP_EQUALVERIFY OP_CHECKSIG
@ -875,13 +875,13 @@ where +<now {plus} 3 months>+ is a block height or time value estimated
When Bob tries to spend this UTXO, he constructs a transaction that
references the UTXO as an input. He uses his signature and public key in
the scriptSig of that input and sets the transaction +nLockTime+
the input script of that input and sets the transaction lock time
to be equal or greater to the timelock in the +OP_CHECKLOCKTIMEVERIFY+
Alice set. Bob then broadcasts the transaction on the Bitcoin network.
Bob's transaction is evaluated as follows. If the +OP_CHECKLOCKTIMEVERIFY+
parameter Alice set is less than or equal the spending transaction's
+nLockTime+, script execution continues (acts as if a _no
lock time, script execution continues (acts as if a _no
operation_ or OP_NOP opcode was executed). Otherwise, script
execution halts and the transaction is deemed invalid.
@ -890,17 +890,17 @@ the transaction invalid if (source: BIP65):
1. the stack is empty; or
2. the top item on the stack is less than 0; or
3. the lock-time type (height versus timestamp) of the top stack item and the +nLockTime+ field are not the same; or
4. the top stack item is greater than the transaction's +nLockTime+ field; or
5. the +nSequence+ field of the input is 0xffffffff.
3. the lock-time type (height versus timestamp) of the top stack item and the lock time field are not the same; or
4. the top stack item is greater than the transaction's lock time field; or
5. the sequence field of the input is 0xffffffff.
[[timelock_conflicts]]
.Timelock conflicts
[WARNING]
====
+OP_CLTV+ and +nLockTime+ use the same format to describe timelocks, either
+OP_CLTV+ and lock time use the same format to describe timelocks, either
a block height or the time elapsed in seconds since Unix epoch.
Critically, when used together, the format of +nLockTime+ must match
Critically, when used together, the format of lock time must match
that of +OP_CLTV+ in the outputs--they must both reference either
block height or time in seconds.
@ -922,10 +922,10 @@ dropped, with +OP_DROP+, for correct execution of subsequent script
opcodes. You will often see +OP_CHECKLOCKTIMEVERIFY+ followed by +OP_DROP+ in
scripts for this reason.
By using nLockTime in conjunction with +OP_CLTV+, the scenario described in
<<locktime_limitations>> changes. Alice can no longer spend the money
By using lock time in conjunction with +OP_CLTV+, the scenario described in
<<lock_time_limitations>> changes. Alice can no longer spend the money
(because it's locked with Bob's key) and Bob cannot spend it before the
3-month locktime has expired.((("", startref="alicesseven")))
3-month lock time has expired.((("", startref="alicesseven")))
By introducing timelock functionality directly into the scripting
language, +OP_CLTV+ allows us to develop some very interesting complex
@ -937,7 +937,7 @@ https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki[BIP65
==== Relative Timelocks
+nLockTime+ and +OP_CLTV+ are ((("timelocks", "relative timelocks",
Lock time and +OP_CLTV+ are ((("timelocks", "relative timelocks",
id="Trelative07")))((("scripting", "timelocks", "relative
timelocks")))((("relative timelocks", id="relativetime07")))both
_absolute timelocks_ in that they specify an absolute point in time. The
@ -956,7 +956,7 @@ and Lightning Networks, as we will see in <<state_channels>>.
Relative timelocks, like absolute timelocks, are implemented with both a
transaction-level feature and a script-level opcode. The
transaction-level relative timelock is implemented as a consensus rule
on the value of +nSequence+, a transaction field that is set in every
on the value of +sequence+, a transaction field that is set in every
transaction input. Script-level relative timelocks are implemented with
the +OP_CHECKSEQUENCEVERIFY+ (OP_CSV) opcode.
@ -976,20 +976,20 @@ the consensus rules.
((("scripting", "timelocks", "relative timelocks with
CHECKSEQUENCEVERIFY")))((("CHECKSEQUENCEVERIFY (CSV)")))Just like OP_CLTV
and +nLockTime+, there is a script opcode for relative timelocks that
leverages the +nSequence+ value in scripts. That opcode is
and lock time, there is a script opcode for relative timelocks that
leverages the sequence value in scripts. That opcode is
+OP_CHECKSEQUENCEVERIFY+, commonly referred to as +OP_CSV+ for short.
The +OP_CSV+ opcode when evaluated in an UTXO's script allows
spending only in a transaction whose input +nSequence+ value is greater
spending only in a transaction whose input sequence value is greater
than or equal to the +OP_CSV+ parameter. Essentially, this restricts
spending the UTXO until a certain number of blocks or seconds have
elapsed relative to the time the UTXO was mined.
As with CLTV, the value in +OP_CSV+ must match the format in the
corresponding +nSequence+ value. If +OP_CSV+ is specified in terms of
blocks, then so must +nSequence+. If +OP_CSV+ is specified in terms of
seconds, then so must +nSequence+.
corresponding sequence value. If +OP_CSV+ is specified in terms of
blocks, then so must sequence. If +OP_CSV+ is specified in terms of
seconds, then so must sequence.
[WARNING]
====
@ -1156,7 +1156,7 @@ OP_ENDIF
OP_CHECKSIG
----
Looking at this redeemScript, you may be wondering: "Where is the
Looking at this redeem script, you may be wondering: "Where is the
condition? There is nothing preceding the +IF+ clause!"
The condition is not part of the script. Instead, the condition
@ -1182,11 +1182,11 @@ known as +OP_0+, pushes an empty byte array to the stack.
<Bob's Sig> OP_FALSE
----
Bob's scriptSig causes the +OP_IF+ clause
Bob's input script causes the +OP_IF+ clause
to execute the second (+OP_ELSE+) script, which requires Bob's signature.
Since +OP_IF+ clauses can be nested, we can create a "maze" of execution
paths. The scriptSig can provide a "map" selecting which
paths. The input script can provide a "map" selecting which
execution path is actually executed:
----
@ -1202,18 +1202,18 @@ OP_ENDIF
----
In this scenario, there are three execution paths (+subscript A+, +subscript
B+, and +subscript C+). The scriptSig provides a path in the form of
B+, and +subscript C+). The input script provides a path in the form of
a sequence of +TRUE+ or +FALSE+ values. To select path +subscript B+, for
example, the scriptSig must end in +OP_1 OP_0+ (+TRUE+, +FALSE+). These
example, the input script must end in +OP_1 OP_0+ (+TRUE+, +FALSE+). These
values will be pushed onto the stack, so that the second value (+FALSE+)
ends up at the top of the stack. The outer +OP_IF+ clause pops the +FALSE+
value and executes the first +OP_ELSE+ clause. Then the +TRUE+ value moves
to the top of the stack and is evaluated by the inner (nested) +OP_IF+,
selecting the +B+ execution path.
Using this construct, we can build redeemScripts with tens or hundreds
Using this construct, we can build redeem scripts with tens or hundreds
of execution paths, each offering a different way to redeem the UTXO. To
spend, we construct an scriptSig that navigates the execution
spend, we construct an input script that navigates the execution
path by putting the appropriate +TRUE+ and +FALSE+ values on the stack
at each flow control point.((("", startref="Sflow07")))((("",
startref="flow07")))((("", startref="condition07")))
@ -1242,7 +1242,7 @@ partner signatures. Finally, if all partners are unavailable or
incapacitated for a while, they want the lawyer to be able to manage the
account directly.
Here's the redeemScript that Mohammed designs to achieve this (line
Here's the redeem script that Mohammed designs to achieve this (line
number prefixed as XX):
[[variable_timelock_multisig]]
@ -1272,7 +1272,7 @@ In the first execution path, this script operates as a simple 2-of-3
multisig with the three partners. This execution path consists of lines
3 and 9. Line 3 sets the quorum of the multisig to +2+ (2-of-3). This
execution path can be selected by putting +OP_TRUE OP_TRUE+ at the end of the
scriptSig:
input script:
.Spending data for the first execution path (2-of-3 multisig)
----
@ -1282,7 +1282,7 @@ OP_0 <Mohammed's Sig> <Zaira's Sig> OP_TRUE OP_TRUE
[TIP]
====
The +OP_0+ at the beginning of this scriptSig is because of an oddity in
The +OP_0+ at the beginning of this input script is because of an oddity in
+OP_CHECKMULTISIG+ that pops an extra value from the stack. The extra value
is disregarded by the +OP_CHECKMULTISIG+, but it must be present or the
script fails. Pushing an empty byte array with +OP_0+ is a workaround to the oddity, as
@ -1293,7 +1293,7 @@ The second execution path can only be used after 30 days have elapsed
from the creation of the UTXO. At that time, it requires the signature
of Abdul the lawyer and one of the three partners (a 1-of-3 multisig).
This is achieved by line 7, which sets the quorum for the multisig to
+1+. To select this execution path, the scriptSig would end in
+1+. To select this execution path, the input script would end in
+OP_FALSE OP_TRUE+:
.Spending data for the second execution path (Lawyer + 1-of-3)
@ -1310,9 +1310,9 @@ stack and +TRUE+ is pushed on top of it.
Finally, the third execution path allows Abdul the lawyer to spend the
funds alone, but only after 90 days. To select this execution path, the
scriptSig has to end in +OP_FALSE+:
input script has to end in +OP_FALSE+:
.ScriptSig for the third execution path (Lawyer only)
.Input script for the third execution path (Lawyer only)
----
<Abdul's Sig> OP_FALSE
----
@ -1333,9 +1333,9 @@ inside a P2SH script.
===== Pay-to-Witness-Public-Key-Hash (P2WPKH)
Let's start by looking at the example of a P2PKH
scriptPubKey:
output script:
.Example P2PKH scriptPubKey
.Example P2PKH output script
----
OP_DUP OP_HASH160 ab68025513c3dbd2f7b92a94e0581f5d50f654e7 OP_EQUALVERIFY OP_CHECKSIG
----
@ -1349,7 +1349,7 @@ to the same public key, it would look like this:
0 ab68025513c3dbd2f7b92a94e0581f5d50f654e7
----
As you can see, a P2WPKH scriptPubKey is much
As you can see, a P2WPKH output script is much
simpler than the P2PKH equivalent. It consists of two values that are
pushed on to the script evaluation stack. To an old (nonsegwit-aware)
Bitcoin client, the two pushes would look like an output that anyone can
@ -1366,7 +1366,7 @@ would have to include a signature within the transaction input:
.Decoded transaction showing a P2PKH output being spent with a signature
----
[...]
“Vin” : [
"vin" : [
"txid": "0627052b6f28912f2703066a912ea577f2ce4da4caa5a5fbd8a57286c345c2f2",
"vout": 0,
"scriptSig": “<Bobs scriptSig>”,
@ -1376,12 +1376,12 @@ would have to include a signature within the transaction input:
However, to spend the P2PKH output, the transaction has no
signature on that input. Instead, Bobs transaction has an empty
+scriptSig+ and includes a witness field:
input script and includes a witness structure:
.Decoded transaction showing a P2WPKH output being spent with a witness field
.Decoded transaction showing a P2WPKH output being spent with a witness structure
----
[...]
“Vin” : [
"vin" : [
"txid": "0627052b6f28912f2703066a912ea577f2ce4da4caa5a5fbd8a57286c345c2f2",
"vout": 0,
"scriptSig": “”,
@ -1424,21 +1424,21 @@ saw this type of script in <<p2sh>>. In that example, P2SH was used by
Mohammed's company to express a multisignature script. Payments to
Mohammed's company were encoded with a script like this:
.Example P2SH scriptPubKey
.Example P2SH output script
----
OP_HASH160 54c557e07dde5bb6cb791c7a540e0a4796f5e97e OP_EQUAL
----
This P2SH script references the hash of a _redeemScript_ that defines a
This P2SH script references the hash of a _redeem script_ that defines a
2-of-3 multisignature requirement to spend funds. To spend this output,
Mohammed's company would present the redeemScript (whose hash matches
Mohammed's company would present the redeem script (whose hash matches
the script hash in the P2SH output) and the signatures necessary to
satisfy that redeemScript, all inside the transaction input:
satisfy that redeem script, all inside the transaction input:
.Decoded transaction showing a P2SH output being spent
----
[...]
“Vin” : [
"vin" : [
"txid": "abcdef12345...",
"vout": 0,
"scriptSig": “<SigA> <SigB> <2 PubA PubB PubC PubD PubE 5 OP_CHECKMULTISIG>”,
@ -1450,7 +1450,7 @@ If Mohammed's customers were using a segwit-compatible wallet, they
would make a payment, creating a Pay-to-Witness-Script-Hash (P2WSH)
output that would look like this:
.Example P2WSH scriptPubKey
.Example P2WSH output script
----
0 a9b7b38d972cabc7961dbfbcb841ad4508d133c47ba87457b4a0e8aae86dbb89
----
@ -1458,7 +1458,7 @@ output that would look like this:
Again, as with the example of P2WPKH, you can see that the Segregated
Witness equivalent script is a lot simpler and reduces the template
overhead that you see in P2SH scripts. Instead, the Segregated Witness
scriptPubKey consists of two values pushed to the stack: a witness version
output script consists of two values pushed to the stack: a witness version
(0) and the 32-byte SHA256 hash of the witness script.
[TIP]
@ -1475,13 +1475,13 @@ Mohammed's company can spend the P2WSH output by presenting the
correct witness script and sufficient signatures to satisfy it. Both the
witness script and the signatures would be
included as part of the witness data. No data would be placed in the
scriptSig because this is a native witness program, which does not use
the legacy scriptSig field.
input script because this is a native witness program, which does not use
the legacy input script field.
.Decoded transaction showing a P2WSH output being spent with witness data
----
[...]
“Vin” : [
"vin" : [
"txid": "abcdef12345...",
"vout": 0,
"scriptSig": “”,
@ -1516,7 +1516,7 @@ Witness is a two-step process. First, wallets must create segwit
type outputs. Then, these outputs can be spent by wallets that know how
to construct Segregated Witness transactions. In the examples, Alice's
wallet is able to create outputs paying
Segregated Witness scriptPubKeys. Bob's wallet is also segwit-aware and able
Segregated Witness output scripts. Bob's wallet is also segwit-aware and able
to spend those outputs.
Segregated Witness was implemented as a
@ -1587,7 +1587,7 @@ echo \
3e0547268b3b19288b3adef9719ec8659f4b2b0b
----
Next, the redeemScript hash is converted to a Bitcoin address. Let's
Next, the redeem script hash is converted to a Bitcoin address. Let's
use +bx+ on the command-line again:
.P2SH address
@ -1625,7 +1625,7 @@ company, regardless of whether their wallets are upgraded for segwit,
Mohammed's wallet can embed the P2WSH witness program inside a P2SH
script.
First, Mohammed's wallet hashes the redeemScript with SHA256 (just
First, Mohammed's wallet hashes the redeem script with SHA256 (just
once). Let's use +bx+ to do that on the command-line:
.Mohammed's wallet creates a P2WSH witness program
@ -1641,7 +1641,7 @@ echo \
9592d601848d04b172905e0ddb0adde59f1590f1e553ffc81ddc4b0ed927dd73
----
Next, the hashed redeemScript is turned into a P2WSH witness program:
Next, the hashed redeem script is turned into a P2WSH witness program:
----
0 9592d601848d04b172905e0ddb0adde59f1590f1e553ffc81ddc4b0ed927dd73

View File

@ -384,8 +384,8 @@ https://bitcoinops.org/en/compatibility/#replace-by-fee-rbf
As a developer, if you plan to implement RBF fee bumping, you will first
need to implement the signaling specified in BIP125, which is a simple
modification to any one of the nSequence fields in a transaction (see
<<nsequence>>).
modification to any one of the sequence fields in a transaction (see
<<sequence>>).
When you need to fee bump a transaction, you will simply create a new
transaction that spends at least one of the same UTXOs as the original
@ -727,11 +727,11 @@ higher than total fees per block. But at some point in the future,
transaction fees will be the majority of the reward (or even the
entirety of the reward). At that time, this scenario becomes inevitable.
Several wallets discourage fee sniping by creating transactions with an
+nLocktime+ that limits those transactions to being included in the next
Several wallets discourage fee sniping by creating transactions with a
lock time that limits those transactions to being included in the next
block or any later block. In our
scenario, our wallet would set +nLocktime+ to 100,001 on any
transaction it created. Under normal circumstances, this +nLocktime+ has
scenario, our wallet would set lock time to 100,001 on any
transaction it created. Under normal circumstances, this lock time has
no effect&#x2014;the transactions could only be included in block
#100,001 anyway; it's the next block.
@ -745,7 +745,7 @@ This does not entirely prevent fee sniping, but it does make it less
profitable in some cases and so can help preserve the stability of the
Bitcoin network as the block subsidy declines. We recommend all wallets
implement anti fee sniping when it doesn't interfere with the wallet's
other uses of the nLockTime field.
other uses of the lock time field.
As Bitcoin continues to mature, and as the subsidy continues to decline,
fees become more and more important to Bitcoin users, both in their

View File

@ -186,8 +186,8 @@ different subsets of the data in the transaction. By including the
[NOTE]
====
All +SIGHASH+ types sign the transaction +nLocktime+ field (see
<<nlocktime>>). In addition, the +SIGHASH+ type
All +SIGHASH+ types sign the transaction lock time field (see
<<lock_time>>). In addition, the +SIGHASH+ type
itself is appended to the transaction before it is signed, so that it
can't be modified once signed.
====
@ -219,7 +219,7 @@ even if they haven't reached the specified value.
+NONE+ :: This construction can be used to create a "bearer check" or
"blank check" of a specific amount. It commits to the input, but allows
the output script to be changed. Anyone can write their own
Bitcoin address into the output scriptPubKey. However, the output value
Bitcoin address into the output script. However, the output value
itself cannot be changed. By itself, this allows any miner to change
the output destination and claim the funds for themselves, but if other
required signatures in the transaction use +SIGHASH_ALL+ or another type

View File

@ -83,7 +83,7 @@ in the transaction and describe any additional fields that they contain.
.A byte map of Alice's transaction
image::../images/tx-map-1.png["A byte map of Alice's transaction"]
[[nVersion]]
[[version]]
=== Version
The first four bytes of a serialized Bitcoin transaction are its
@ -94,7 +94,7 @@ described throughout this book.
Version 2 Bitcoin transactions were introduced in the BIP68 soft fork
change to Bitcoin's consensus rules. BIP68 places additional
constraints on the nSequence field, but those constraints only apply to
constraints on the sequence field, but those constraints only apply to
transactions with version 2 or higher. Version 1 transactions are
unaffected. BIP112, which was part of the same soft fork as BIP68,
upgraded an opcode (OP_CHECKSEQUENCEVERIFY) which will now fail if it is
@ -116,7 +116,7 @@ Network, depend on pre-signed transactions.
This creates a challenge for protocol developers when they assist users
in upgrading the Bitcoin consensus protocol. Adding new
constraints--such as BIP68 did to the nSequence field--may invalidate
constraints--such as BIP68 did to the sequence field--may invalidate
some pre-signed transactions. If there's no way to create a new
signature for an equivalent transaction, then the money being spent in
the pre-signed transaction is permanently lost.
@ -125,7 +125,7 @@ This problem is solved by reserving some transaction features for
upgrades, such as version numbers. Anyone creating pre-signed
transactions prior to BIP68 should have been using version 1
transactions, so only applying BIP68's additional constraints on
nSequence to transactions v2 or higher should not invalidate any
sequence to transactions v2 or higher should not invalidate any
pre-signed transactions.
If you implement a protocol that uses pre-signed transactions, ensure
@ -150,8 +150,8 @@ part of the Segregated Witness (segwit) soft fork change to Bitcoin's
consensus rules. The rules were changed according to BIPs 141 and 143,
but the _extended serialization format_ is defined in BIP144.
If the transaction includes a witness field (which we'll describe in
<<witnesses>>), the marker must be zero (0x00) and the flag must be
If the transaction includes a witness structure (which we'll describe in
<<witness_structure>>), the marker must be zero (0x00) and the flag must be
non-zero. In the current P2P protocol, the flag should always be one
(0x01); alternative flags are reserved for later protocol upgrades.
@ -177,9 +177,9 @@ map of those bytes in <<alice_tx_input_map>>.
.Map of bytes in the input field of Alice's transaction
image::../images/input-byte-map.png["map of bytes in the input field of Alice's transaction"]
==== Inputs Count
==== Length of transaction input list
The input field starts with an integer indicating the number of inputs
The transaction input list starts with an integer indicating the number of inputs
in the transaction. The minimum value is one. There's no explicit
maximum value, but restrictions on the maximum size of a transaction
effectively limit transactions to a few thousand inputs. The number is
@ -210,7 +210,8 @@ For numbers from 0 to 252, compactSize unsigned integers are identical
to the C-language data type +uint8_t+, which is probably the native
encoding familiar to any programmer. For other numbers up to
0xffffffffffffffff, a byte is prefixed to the number to indicate its
length—but otherwise the numbers look like regular unsigned integers.
length—but otherwise the numbers look like regular C-language encoded
unsigned integers.
[cols="1,1,1"]
|===
@ -226,9 +227,9 @@ Each input in a transaction must contain three fields:
- An _outpoint_ field
- A length-prefixed _scriptSig_ field
- A length-prefixed _input script_ field
- An _nSequence_
- A _sequence_
We'll look at each of those fields in the following sections. Some
inputs also include a witness, but this is serialized at the end of a
@ -252,7 +253,7 @@ This txid is in Bitcoin's internal byte order for hashes, see
Because transactions may contain multiple outputs, Alice also needs to
identify which particular output from that transaction to use, called
its output vector (_vout_). Output vectors are four-byte unsigned
its _output index_. Output indices are four-byte unsigned
integers indexed from zero.
When a full node encounters an outpoint, it uses that information to
@ -348,14 +349,14 @@ _little-endian byte order_ for the internal version and _big-endian byte
order_ for the display version.
****
==== ScriptSig
==== Input script
The scriptSig field is a remnant of the legacy transaction format. Our
The input script field is a remnant of the legacy transaction format. Our
example transaction input spends a native segwit output which doesn't
require any data in the scriptSig, so the length prefix for the
scriptSig is set to zero (0x00).
require any data in the input script, so the length prefix for the
input script is set to zero (0x00).
For an example of a length-prefixed scriptSig that spends a legacy
For an example of a length-prefixed input script that spends a legacy
output, we use one from an arbitrary transaction in the most recent
block as of this writing:
@ -367,23 +368,23 @@ fa2580bb664b020220366060ea8203d766722ed0a02d1599b99d3c95b97dab8e
----
The length prefix is a compactSize unsigned integer indicating the
length of the serialized scriptSig field. In this case, it's a single
byte (0x6b) indicating the scriptSig is 107 bytes. We'll cover parsing
length of the serialized input script field. In this case, it's a single
byte (0x6b) indicating the input script is 107 bytes. We'll cover parsing
and using scripts in detail in the next chapter,
<<c_authorization_authentication>>.
[[nsequence]]
==== nSequence
[[sequence]]
==== Sequence
The final four bytes of an input are its sequence number, called
_nSequence_. The use and meaning of this field has changed over time.
The final four bytes of an input are its _sequence_ number.
The use and meaning of this field has changed over time.
[[original_tx_replacement]]
===== Original nSequence-based Transaction Replacement
===== Original Sequence-Based Transaction Replacement
The +nSequence+ field was originally intended to allow creation of
The sequence field was originally intended to allow creation of
multiple versions of the same transaction, with later versions replacing
earlier versions as candidates for confirmation. The nSequence number
earlier versions as candidates for confirmation. The sequence number
tracked the version of the transaction.
For example, imagine Alice and Bob want to bet on a game of cards. They
@ -399,27 +400,27 @@ output:
the transaction at this time. They only need it if there's a problem.
- Alice wins the first round of the card game, so the second version of
the transaction, with nSequence 1, increases the amount of money paid
the transaction, with sequence 1, increases the amount of money paid
to Alice and decreases Bob's share. They both sign the updated
transaction. Again, they don't need to broadcast this version of the
transaction unless there's a problem.
- Bob wins the second round, so the nSequence is incremented to 2,
- Bob wins the second round, so the sequence is incremented to 2,
Alice's share is decreased, and Bob's share is increased. They again
sign but don't broadcast.
- After many more rounds where the nSequence is incremented, the
- After many more rounds where the sequence is incremented, the
funds redistributed, and the resulting transaction is signed but not
broadcast, they decide to finalize the transaction. Creating a
transaction with the final balance of funds, they set nSequence to its
transaction with the final balance of funds, they set sequence to its
maximum value (0xffffffff), finalizing the transaction. They broadcast
this version of the transaction, it's relayed across the network, and
eventually confirmed by miners.
We can see the replacement rules for nSequence at work if we consider
We can see the replacement rules for sequence at work if we consider
alternative scenarios:
- Imagine that Alice broadcasts the final transaction, with an nSequence of
- Imagine that Alice broadcasts the final transaction, with a sequence of
0xffffffff, and then Bob broadcasts one of the earlier transactions
where his balance was higher. Because Bob's version of the
transaction has a lower sequence number, full nodes using the original
@ -429,7 +430,7 @@ alternative scenarios:
- In another scenario, imagine that Bob broadcasts an earlier version of
the transaction a few seconds before Alice broadcasts the final
version. Nodes will relay Bob's version and miners will attempt to
mine it, but when Alice's version with its higher nSequence number
mine it, but when Alice's version with its higher sequence number
arrives, nodes will also relay it and miners using the original
Bitcoin code will try to mine it instead of Bob's version. Unless Bob
got lucky and a block was discovered before Alice's version arrived,
@ -442,7 +443,7 @@ the protocol to support them. We'll learn about several of those other
features later and also discover how modern versions of payment channels
are increasingly being used in Bitcoin today.
There were a few problems with purely nSequence-based payment channels.
There were a few problems with purely sequence-based payment channels.
The first was that the rules for replacing a lower-sequence transaction
with a higher-sequence transaction were only a matter of software
policy. There was no direct incentive for miners to prefer one version
@ -465,27 +466,27 @@ need to pay any costs for the enormous burden they placed on full node
operators.
To eliminate the risk of this attack, the original type of
nSequence-based transaction replacement was disabled in an early version
sequence-based transaction replacement was disabled in an early version
of the Bitcoin software. For several years, Bitcoin full nodes would
not allow an unconfirmed transaction containing a particular input (as
indicated by its outpoint) to be replaced by a different transaction
containing the same input. However, that situation didn't last forever.
[[nsequence-bip125]]
[[sequence-bip125]]
===== Opt-in Transaction Replacement Signaling
After the original nSequence-based transaction replacement was disabled
After the original sequence-based transaction replacement was disabled
due to the potential for abuse, a solution was proposed: programming
Bitcoin Core and other relaying full node software to allow a
transaction that paid a higher transaction fee rate to replace a
conflicting transaction that paid a lower fee rate. This is called
_Replace-By-Fee_, or _RBF_ for short. Some users and businesses
objected to adding support for transaction replacement back into Bitcoin
Core, so a compromise was reached that once again used the nSequence
Core, so a compromise was reached that once again used the sequence
field in support of replacement.
As documented in BIP125, an unconfirmed transaction with any input that
has an nSequence set to a value below 0xfffffffe (i.e., at least 2 below
has an sequence set to a value below 0xfffffffe (i.e., at least 2 below
the maximum value) signals to the network that its signer wants it to be
replaceable by a conflicting transaction paying a higher fee rate.
Bitcoin Core allowed those unconfirmed transactions to be replaced and
@ -495,56 +496,56 @@ ignore unconfirmed transactions containing the BIP125 signal until they
became confirmed.
There's more to modern transaction replacement policies than fee rates
and nSequence signals, which we'll see in <<rbf>>.
and sequence signals, which we'll see in <<rbf>>.
[[relative_timelocks]]
===== nSequence as a consensus-enforced relative timelock
===== Sequence as a consensus-enforced relative timelock
In the <<nVersion>> section, we learned that the BIP68 soft fork added
In the <<version>> section, we learned that the BIP68 soft fork added
a new constraint to transactions with version numbers 2 or higher. That
constraint applies to the nSequence field.
constraint applies to the sequence field.
Transaction inputs with +nSequence+ values less than 2^31^ are
Transaction inputs with sequence values less than 2^31^ are
interpreted as having a relative timelock. Such a transaction may only
be included in the blockchain once the previous output (referenced by the
outpoint) has aged by the relative timelock amount. For example, a
transaction with one input with a relative timelock of 30 blocks can
only be confirmed after least 30 blocks have elapsed from the time the
previous output was confirmed in a block on the current blockchain.
Since +nSequence+ is a per-input field, a transaction may contain any
Since sequence is a per-input field, a transaction may contain any
number of timelocked inputs, all of which must have sufficiently aged
for the transaction to be valid. A transaction can include both
timelocked inputs (+nSequence+ < 2^31^) and inputs without a relative
timelock (+nSequence+ >= 2^31^).
timelocked inputs (sequence < 2^31^) and inputs without a relative
timelock (sequence >= 2^31^).
The +nSequence+ value is specified in either blocks or seconds.
The sequence value is specified in either blocks or seconds.
A type-flag
is used to differentiate between values counting blocks and values
counting time in seconds. The type-flag is set in the 23rd
least-significant bit (i.e., value 1<<22). If the type-flag is set, then
the +nSequence+ value is interpreted as a multiple of 512 seconds. If
the type-flag is not set, the +nSequence+ value is interpreted as a
the sequence value is interpreted as a multiple of 512 seconds. If
the type-flag is not set, the sequence value is interpreted as a
number of blocks.
When interpreting +nSequence+ as a relative timelock, only the 16 least
When interpreting sequence as a relative timelock, only the 16 least
significant bits are considered. Once the flags (bits 32 and 23) are
evaluated, the +nSequence+ value is usually "masked" with a 16-bit mask
(e.g., +nSequence+ & 0x0000FFFF). The multiple of 512 seconds is
evaluated, the sequence value is usually "masked" with a 16-bit mask
(e.g., +sequence+ & 0x0000FFFF). The multiple of 512 seconds is
roughly equal to the average amount of time between blocks, so the
maximum relative timelock in both blocks and seconds from 16 bits
(2^16^) is about one year.
<<bip_68_def_of_nseq>> shows the binary layout of the +nSequence+ value,
<<bip_68_def_of_nseq>> shows the binary layout of the sequence value,
as defined by BIP68.
[[bip_68_def_of_nseq]]
.BIP68 definition of nSequence encoding (Source: BIP68)
image::../images/mbc2_0701.png["BIP68 definition of nSequence encoding"]
.BIP68 definition of sequence encoding (Source: BIP68)
image::../images/mbc2_0701.png["BIP68 definition of sequence encoding"]
Note that any transaction which sets a relative timelock using nSequence
Note that any transaction which sets a relative timelock using sequence
also sends the signal for opt-in replace-by-fee as described in
<<nsequence-bip125>>.
<<sequence-bip125>>.
=== Outputs
@ -566,10 +567,10 @@ transaction. It's a compactSize integer and must be greater than zero.
The example transaction has two outputs.
==== nValue
==== Amount
The first field of a specific output is its value, also called
_nValue_ in Bitcoin Core. This is an eight-byte signed integer indicating
The first field of a specific output is its _amount_, also called
"value" in Bitcoin Core. This is an eight-byte signed integer indicating
the number of _satoshis_ to transfer. A satoshi is the smallest unit of
bitcoin that can be represented in an onchain Bitcoin transaction.
There are 100 million satoshis in a bitcoin.
@ -639,39 +640,39 @@ use Utreexo.
====
Bitcoin Core's policy rules about dust do have one exception: output
scriptPubKeys starting with +OP_RETURN+, called _data carrier outputs_,
scripts starting with +OP_RETURN+, called _data carrier outputs_,
can have a value of zero. The OP_RETURN opcode causes the script to
immediately fail no matter what comes after it, so these outputs can
never be spent. That means full nodes don't need to keep track of them,
a feature Bitcoin Core takes advantage of to allow users to store small
amounts of arbitrary data in the blockchain without increasing the size
of its UTXO database. Since the outputs are unspendable, they aren't
uneconomical--any satoshis in nValue assigned to them becomes
permanently unspendable--so allowing the nValue to be zero ensures
uneconomical--any satoshis assigned to them becomes
permanently unspendable--so allowing the amount to be zero ensures
satoshis aren't being destroyed.
==== ScriptPubKey
==== Output scripts
The output amount is followed by a compactSize integer indicating the
length of the output's _scriptPubKey_, the script that contains the
length of the _output script_, the script that contains the
conditions which will need to be fulfilled in order to spend the
bitcoins, the _spending authorization_. According to Bitcoin's
consensus rules, the minimum size of a scriptPubKey is zero.
consensus rules, the minimum size of an output script is zero.
The consensus maximum allowed size of a scriptPubKey varies depending on
when it's being checked. There's no explicit limit on the size of a
scriptPubKey in the output of a transaction, but a later transaction can
only spend a previous output with a scriptPubKey of 10,000 bytes or
smaller. Implicitly, a scriptPubKey can be almost as large as the
The consensus maximum allowed size of an outputs script varies depending on
when it's being checked. There's no explicit limit on the size of an
output script in the output of a transaction, but a later transaction can
only spend a previous output with a script of 10,000 bytes or
smaller. Implicitly, an output script can be almost as large as the
transaction containing it, and a transaction can be almost as large as
the block containing it.
[[anyone-can-spend]]
[TIP]
====
A scriptPubKey with zero length can be spent by a scriptSig containing
OP_TRUE. Anyone can create that scriptSig, which means anyone
can spend an empty scriptPubKey. There are an essentially unlimited
An output script with zero length can be spent by a input script containing
OP_TRUE. Anyone can create that input script, which means anyone
can spend an empty output script. There are an essentially unlimited
number of scripts which anyone can spend and they are known to Bitcoin
protocol developers as _anyone can spends_. Upgrades to Bitcoin's
script language often take an existing anyone-can-spend script and add
@ -683,7 +684,7 @@ future upgrades don't accidentally interfere with your system.
====
Bitcoin Core's policy for relaying and mining transactions effectively
limits scriptPubKeys to just a few templates, called _standard
limits output scripts to just a few templates, called _standard
transaction outputs_. This was originally implemented after the
discovery of several early bugs in Bitcoin related to the Script
language and is retained in modern Bitcoin Core to support
@ -694,8 +695,8 @@ segwit v2 (taproot) tapscripts.
We'll look at each of the current standard transaction templates and
learn how to parse scripts in <<c_authorization_authentication>>.
[[witnesses]]
=== Witnesses
[[witness_structure]]
=== Witness structure
In court, a witness is someone who testifies that they saw something
important happen. Human witnesses aren't always reliable, so courts
@ -743,10 +744,10 @@ Witnesses, the values used to solve the math problems that protect
bitcoins, need to be included in the transactions where they're used in
order for full nodes to verify them. In the legacy transaction format
used for all early Bitcoin transactions, signatures and other data are
placed in the scriptSig field. However, when developers started to
placed in the input script field. However, when developers started to
implement contract protocols on Bitcoin, such as we saw in
<<original_tx_replacement>>, they discovered several significant
problems with placing witnesses in the scriptSig field.
problems with placing witnesses in the input script field.
==== Circular Dependencies
@ -758,7 +759,7 @@ other person becomes unresponsive. A simple solution is to sign
transactions out of order.
- Tx~0~ pays money from Alice and money from Bob into an output with a
scriptPubKey that requries signatures from both Alice and Bob to spend
script that requries signatures from both Alice and Bob to spend
- Tx~1~ spends the previous output to two outputs, one refunding Alice
her money and one refunding Bob his money (minus a small amount for
@ -770,7 +771,7 @@ transactions out of order.
protocol_.
A problem with this construction in the legacy transaction format is
that every field, including the scriptSig field which contains
that every field, including the input script field which contains
signatures, is used to build a transaction's identifier (txid). The
txid for Tx~0~ is part of the input's outpoint in Tx~1~. That means
there's no way for Alice and Bob to construct Tx~1~ until both
@ -784,13 +785,13 @@ _circular dependency_.
A more complex series of transactions can sometimes eliminate a circular
dependency, but many protocols will then encounter a new concern: it's
often possible to solve the same script in different ways. For example,
consider our simple script from <<witnesses>>:
consider our simple script from <<witness_structure>>:
----
2 OP_ADD 4 OP_EQUAL
----
We can make this script pass by providing the value _2_ in a scriptSig,
We can make this script pass by providing the value _2_ in a input script,
but there are several ways to put that value on the stack in Bitcoin.
Here are just a few:
@ -811,7 +812,7 @@ OP_PUSHDATA4 0x000000020002
...
----
Each alternative encoding of the number _2_ in a scriptSig will produce
Each alternative encoding of the number _2_ in an input script will produce
a slightly different transaction with a completely different txid. Each
different version of the transaction spends the same inputs (outpoints)
as every other version of the transaction, making them all _conflict_
@ -819,7 +820,7 @@ with each other. Only one version of a set of conflicting transactions
can be contained within a valid blockchain.
Imagine Alice creates one version of the transaction with +OP_2+ in the
scriptSig and an output that pays Bob. Bob then immediately spends that
input script and an output that pays Bob. Bob then immediately spends that
output to Carol. Anyone on the network can replace +OP_2+ with
+OP_PUSH1 0x02+, creating a conflict with Alice's original version. If
that conflicting transaction is confirmed, then there's no way to
@ -855,7 +856,7 @@ that person could generate alternative signatures and so change the txid.
For example, Alice and Bob have deposited their money into a script
requiring a signature from both of them to spend. They've also created
a refund transaction that allows each of the to get their money back at
a refund transaction that allows each of them to get their money back at
any time. Alice decides she wants to spend just some of the
money, so she cooperates with Bob to create a chain of transactions.
@ -892,9 +893,9 @@ mutation is called _unwanted second-party transaction malleability_.
As early as https://bitcointalk.org/index.php?topic=40627.msg494697[2011],
protocol developers knew how to solve the problems of circular
dependence, third-party malleability, and second-party malleability. The
idea was to avoid including the scriptSig in the calculation that
idea was to avoid including the input script in the calculation that
produces a transaction's txid. Recall that an abstract name for the data
held by a scriptSig is a _witness_. The idea of separating the rest of
held by a input script is a _witness_. The idea of separating the rest of
the data in a transaction from its witness for the purpose of generating
a txid is called _segregated witness_ (segwit).
@ -915,28 +916,28 @@ explore the details of upgrading Bitcoin's consensus rules in
<<mining>>).
The soft fork segwit approach is based on anyone-can-spend
scriptPubKeys. A script which starts with any of the numbers 0 to 16
output scripts. A script which starts with any of the numbers 0 to 16
and followed by 2 to 40 bytes of data is defined as a segwit
scriptPubKey template. The number indicates its version (e.g. 0 is
output script template. The number indicates its version (e.g. 0 is
segwit version 0, or _segwit v0_). The data is called a _native witness
program_. It's also possible to wrap the segwit template in a P2SH
commitment, called a _P2SH witness program_, but we won't deal with that
here.
From the perspective of old nodes, these scriptPubKey templates can be
spent with an empty scriptSig. From the perspective of a new node which
is aware of the new segwit rules, any payment to a segwit scriptPubKey
template must only be spent with an empty scriptSig. Notice the
difference here: old nodes _allow_ an empty scriptSig; new nodes
_require_ an empty scriptSig.
From the perspective of old nodes, these output script templates can be
spent with an empty input script. From the perspective of a new node which
is aware of the new segwit rules, any payment to a segwit output script
template must only be spent with an empty input script. Notice the
difference here: old nodes _allow_ an empty input script; new nodes
_require_ an empty input script.
An empty scriptSig keeps witnesses from affecting the txid, eliminating
An empty input script keeps witnesses from affecting the txid, eliminating
circular dependencies, third-party transaction malleability, and
second-party transaction malleability. But, with no ability to put
data in a scriptSig, users of segwit scriptPubKey templates need a
new field. That field is called the _witness_.
data in an input script, users of segwit output script templates need a
new field. That field is called the _witness structure_.
The introduction of witnesses and witness programs complicates Bitcoin,
The introduction of witness programs and the witness structure complicates Bitcoin,
but it follows an existing trend of increasing abstraction. Recall from
<<ch04_keys_addresses>> that the original Bitcoin whitepaper describes a system
where bitcoins were received to public keys (pubkeys) and spent with
@ -945,50 +946,50 @@ the bitcoins (whoever controlled the corresponding private key) and the
signature provided _authentication_ that the spending transaction came
from someone who controlled the private key. To make that system more
flexible, the initial release of Bitcoin introduced scripts that allow
bitcoins to be received to scriptPubKeys and spent with scriptSigs.
bitcoins to be received to output scripts and spent with input scripts.
Later experience with contract protocols inspired allowing bitcoins to
be received to witness programs and spent with witnesses.
be received to witness programs and spent with the witness structure.
.Terms used for authorization and authentication data in different parts of Bitcoin
[cols="1,1,1"]
|===
| | **Authorization** | **Authentication**
| **Whitepaper** | Public key | Signature
| **Original (Legacy)** | scriptPubKey | scriptSig
| **Segwit** | Witness program | Witness
| **Original (Legacy)** | Output script | Input script
| **Segwit** | Witness program | Witness structure
|===
==== Witness Serialization
==== Witness Structure Serialization
Similar to the inputs and outputs fields, the witness field contains
several other fields, so we'll start with a map of those bytes from
Similar to the inputs and outputs fields, the witness structure contains
other fields, so we'll start with a map of those bytes from
Alice's transaction in <<alice_tx_witness_map>>:
[[alice_tx_witness_map]]
.A byte map of the witness from Alice's transaction
.A byte map of the witness structure from Alice's transaction
image::../images/witness-byte-map.png["A byte map of the witness from Alice's transaction"]
Unlike the inputs and outputs fields, the overall witness field doesn't
start with any indication of the total number of elements it contains.
Unlike the inputs and outputs fields, the overall witness structure doesn't
start with any indication of the total number of witness stacks it contains.
Instead, this is implied by the inputs field--there's one witness
element for every input in a transaction.
stack for every input in a transaction.
The witness field for a particular input does start with a count of the
number of elements they contain. Those elements are called _stack
The witness structure for a particular input does start with a count of the
number of elements they contain. Those elements are called _witness
items_. We'll explore them in detail in
<<c_authorization_authentication>>, but for now we need to know that
each stack item is prefixed by a compactSize integer indicating its
each witness item is prefixed by a compactSize integer indicating its
size.
Legacy inputs don't contain any witness stack items so their witness
Legacy inputs don't contain any witness items so their witness stack
consists entirely of a count of zero (0x00).
Alice's transaction contains one input and one stack item.
[[nlocktime]]
=== nLockTime
[[lock_time]]
=== Lock Time
The final field in a serialized transaction is its _nLockTime_. This
The final field in a serialized transaction is its lock time. This
field was part of Bitcoin's original serialization format but it was
only initially enforced by Bitcoin's policy for choosing which
transactions to mine. Bitcoin's earliest known soft fork added a rule
@ -996,21 +997,21 @@ that, starting at block height 31,000, forbid the inclusion of a
transaction in a block unless it satisfies one of the following rules:
- The transaction indicates that it should be eligible for inclusion in
any block by setting its nLockTime to 0.
any block by setting its lock time to 0.
- The transaction indicates that it wants to restrict which blocks it
can be included in by setting its nLockTime to a value less than
can be included in by setting its lock time to a value less than
500,000,000. In this case, the transaction can only be included in a
block that has a height equal to the nLockTime or higher. For
example, a transaction with an nLockTime of 123,456 can be included in
block that has a height equal to the lock time or higher. For
example, a transaction with a lock time of 123,456 can be included in
block 123,456 or any later block.
- The transaction indicates that it wants to restrict when it can be
included in the blockchain by setting its nLockTime to a value of
included in the blockchain by setting its lock time to a value of
500,000,000 or greater. In this case, the field is parsed as epoch
time (the number of seconds since 1970-01-01T00:00 UTC) and the
transaction can only be included in a block with a _Median Time Past_
(MTP) greater than the nLockTime. MTP is normally about an hour or
(MTP) greater than the lock time. MTP is normally about an hour or
two behind the current time. The rules for MTP are described in
<<mtp>>.
@ -1040,7 +1041,7 @@ Some of the special rules for coinbase transactions include:
which would (at the very least) be confusing given that the coinbase
transaction spends fees and subsidy.
- The field which would contain a scriptSig in a normal transaction is
- The field which would contain a input script in a normal transaction is
called a _coinbase_. It's this field that gives the coinbase
transaction its name. The coinbase field must be at least two bytes
and not longer than 100 bytes. This script is not executed but legacy
@ -1123,14 +1124,14 @@ creation of uneconomical outputs as described in
| Marker & Flag | 1 | 2
| Inputs Count | 4 | 4
| Outpoint | 4 | 144
| scriptSig | 4 | 4
| nSequence | 4 | 16
| Input script | 4 | 4
| Sequence | 4 | 16
| Outputs Count | 4 | 4
| nValue | 4 | 64 (2 outputs)
| scriptPubKey | 4 | 232 (2 outputs with different scripts)
| Amout | 4 | 64 (2 outputs)
| Output script | 4 | 232 (2 outputs with different scripts)
| Witness Count | 1 | 1
| Witnesses | 1 | 66
| nLockTime | 4 | 16
| Witness items | 1 | 66
| Lock time | 4 | 16
| **Total** | _N/A_ | **569**
|===
@ -1162,13 +1163,13 @@ older format, called _legacy serialization_, must be used on the Bitcoin
P2P network for any transaction with an empty witness (which is only
valid if the transaction doesn't spend any witness programs).
Legacy serialization does not include the marker, flag, and witness
Legacy serialization does not include the marker, flag, and witness structure
fields.
In this chapter, we looked at each of the fields in a transaction and
discovered how they communicate to full nodes the details about the
bitcoins to be transferred between users. We only briefly looked at the
scriptPubKey, scriptSig, and witness fields that allow specifying and
output script, input script, and witness structure that allow specifying and
satisfying conditions which restrict who can spend what bitcoins.
Understanding how to construct and use these conditions is essential to
ensuring that only Alice can spend her bitcoins, so they will be the

View File

@ -7,7 +7,7 @@ address::
A Bitcoin address looks like +1DSrfJdB2AnWaFNgSbv3MZC2m74996JafV+. It consists of a string of letters and numbers. It's really an encoded base58check version of a public key 160-bit hash. Just as you ask others to send an email to your email address, you would ask others to send you bitcoin to one of your Bitcoin addresses.
bip::
Bitcoin Improvement Proposals. A set of proposals that members of the bitcoin community have submitted to improve bitcoin. For example, BIP-21 is a proposal to improve the bitcoin uniform resource identifier (URI) scheme.
Bitcoin Improvement Proposals. A set of proposals that members of the bitcoin community have submitted to improve bitcoin. For example, BIP21 is a proposal to improve the bitcoin uniform resource identifier (URI) scheme.
bitcoin::
The name of the currency unit (the coin), the network, and the software.
@ -107,8 +107,8 @@ LevelDB::
Lightning Networks::
Lightning Network is a proposed implementation of Hashed Timelock Contracts (HTLCs) with bi-directional payment channels which allows payments to be securely routed across multiple peer-to-peer payment channels. This allows the formation of a network where any peer on the network can pay any other peer even if they don't directly have a channel open between each other.
Locktime::
Locktime, or more technically nLockTime, is the part of a transaction which indicates the earliest time or earliest block when that transaction may be added to the block chain.
Lock time::
Lock time is the part of a transaction which indicates the earliest time or earliest block when that transaction may be added to the block chain.
mempool::
The bitcoin Mempool (memory pool) is a collection of all transaction data in a block that have been verified by Bitcoin nodes, but are not yet confirmed.
@ -165,10 +165,10 @@ P2SH address::
P2SH addresses are Base58Check encodings of the 20-byte hash of a script, P2SH addresses use the version prefix "5", which results in Base58Check-encoded addresses that start with a "3". P2SH addresses hide all of the complexity, so that the person making a payment does not see the script.
P2WPKH::
The signature of a P2WPKH (Pay-to-Witness-Public-Key-Hash) contains the same information as a P2PKH spending, but is located in the witness field instead of the scriptSig field. The scriptPubKey is also modified.
The signature of a P2WPKH (Pay-to-Witness-Public-Key-Hash) contains the same information as a P2PKH spending, but is located in the witness structure instead of the input script. The output script is also modified.
P2WSH::
The difference between P2SH and P2WSH (Pay-to-Witness-Script-Hash) is about the cryptographic proof location change from the scriptSig field to the witness field and the scriptPubKey that is also modified.
The difference between P2SH and P2WSH (Pay-to-Witness-Script-Hash) is about the cryptographic proof location change from the input script to the witness structure and the output script that is also modified.
paper wallet::
In the most specific sense, a paper wallet is a document containing all of the data necessary to generate any number of Bitcoin private keys, forming a wallet of keys. However, people often use the term to mean any way of storing bitcoin offline as a physical document. This second definition also includes paper keys and redeemable codes.
@ -200,11 +200,11 @@ Satoshi Nakamoto::
Script::
Bitcoin uses a scripting system for transactions. Forth-like, Script is simple, stack-based, and processed from left to right. It is purposefully not Turing-complete, with no loops.
ScriptPubKey (aka pubkey script)::
ScriptPubKey or pubkey script, is a script included in outputs which sets the conditions that must be fulfilled for those satoshis to be spent. Data for fulfilling the conditions can be provided in a signature script.
Output script::
A script included in outputs which sets the conditions that must be fulfilled for those satoshis to be spent. Data for fulfilling the conditions can be provided in a signature script.
ScriptSig (aka signature script)::
ScriptSig or signature script, is the data generated by a spender which is almost always used as variables to satisfy a pubkey script.
Input script::
The data generated by a spender which is almost always used as variables to satisfy an output script.
secret key (aka private key)::
The secret number that unlocks bitcoin sent to the corresponding address. pass:[<span class="keep-together">A secret</span>] key looks like the following:

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.1 KiB

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

@ -46,9 +46,9 @@
== Chapter 7
* Time Locks
* Transaction level absolute (nLocktime)
* Transaction level absolute lock time
* UTXO/Script level absolute (CHECKLOCKTIMEVERIFY)
* Input level relative (nSequence)
* Input level relative sequence
* UTXO/Script level relative (CHECKSEQUENCEVERIFY)
* Median Time Past
* Timelock defense against fee sniping
@ -82,7 +82,7 @@
* Diverging hard forks
* Soft forks for feature upgrades
* Signaling soft forks with block version
* BIP-9 (versionbits) signaling and activation
* BIP9 (versionbits) signaling and activation
* Consensus software development
== Chapter 11

View File

@ -114,10 +114,10 @@ Bitcoin Addresses, Balances, and Other Abstractions
* Redeem Script and Validation
* Data Recording Output (RETURN)
* Timelocks
* Transaction Locktime (nLocktime)
* Transaction lock time
* Check Lock Time Verify (CLTV)
* Relative Timelocks
* Relative Timelocks with nSequence
* Relative Timelocks with sequence
* Relative Timelocks with CSV
* Median-Time-Past
* Timelock Defense Against Fee Sniping