Merge remote-tracking branch 'verde/master'

This commit is contained in:
2021-05-29 18:00:01 +02:00
53 changed files with 2701 additions and 198 deletions
+54
View File
@@ -0,0 +1,54 @@
# Address Types
Addresses are commonly used identifiers that act as a shorthand for who can spend a given output.
Since Bitcoin Cash [transactions](/protocol/blockchain/transaction) do not inherently have a concept of accounts with balances, it is not always easy (or even possible) to determine which unspent outputs are spendable by a given person.
However, the [standard scripts](/protocol/blockchain/transaction/locking-script#standard-scripts) were designed to provide a straightforward structure that can be used to identify transactions that spendable in similar ways.
In most cases, the address contains all of the information necessary to create a transaction output that is spendable by the owner of the address.
Due to this and their compactness, addresses are the most common way to specify to others how ("where") they can receive funds.
Raw addresses are rarely used outside of scripts, though, as they lack context and redundancy.
Instead, addresses are typically encoded using the [Base58Check](/protocol/blockchain/encoding/base58check) or [CashAddr](/protocol/blockchain/encoding/cashaddr) formats to ensure they are received and interpreted correctly.
These encodings include checksums as well as information about the type of address being encoded.
CashAddr was created after Base58Check (also referred to as legacy encoding) to avoid conflicts with pre-existing BTC address.
## Pay to Public Key Hash (P2PKH) Addresses
[P2PKH](/protocol/blockchain/transaction/locking-script#pay-to-public-key-hash-p2pkh) addresses encode the hash of the public key that is locking the output (i.e. `RIPEMD-160(SHA-256(publicKey))`).
Mainnet P2PKH addresses always start with `1` in Base58Check encoding and `q` in CashAddr encoding:
Base58Check: 1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa
CashAddr: bitcoincash:qp3wjpa3tjlj042z2wv7hahsldgwhwy0rq9sywjpyy
The following diagram show the full creation process for a P2PKH address:
```mermaid
graph LR
PrivK["Private Key"] ==>PubK[Public key]
PubK == SHA256 and RIPEMD160 ==> PubKH[Public Key Hash]
PubKH ==> Address
Address ==> PubKH
style PubK fill:#F06,stroke:#333,stroke-width:2px;
style PrivK fill:#B06,stroke:#333,stroke-width:8px;
style PubKH fill:#0F6,stroke:#333,stroke-width:2px;
style Address fill:#0F6,stroke:#333,stroke-width:2px;
```
## Pay to Script Hash (P2SH) Addresses
[P2SH](/protocol/blockchain/transaction/locking-script#pay-to-script-hash-p2sh) addresses encode the redeem script hash (i.e. `RIPEMD-160(redeemScript)`).
Mainnet P2SH addresses always start with `3` in Base58Check encoding and `p` in CashAddr encoding.
Base58Check: 3N5i3Vs9UMyjYbBCFNQqU3ybSuDepX7oT3
CashAddr: bitcoincash:pr0662zpd7vr936d83f64u629v886aan7c77r3j5v5
## Multisig Addresses
Multisig addresses are occasionally referenced despite there not being a specific process for creating them.
This is because the addresses being referred to are actually P2SH addresses for redeem scripts that perform [multisignature](/protocol/blockchain/cryptography/multisignature) validation.
As such, they look exactly like P2SH addresses and are indistinguishable from them until the script is known and inspected.
Moreover, outputs created using multsig addresses use the P2SH script format, not the [Multisig (P2MS)](/protocol/blockchain/transaction/locking-script#multisig-p2ms) script format.
Alternatively, with the advent of [Schnorr signatures](/protocol/blockchain/cryptography/signatures#schnorr-signatures) in BCH, it is also possible perform n-of-n multisignature locking and unlocking using [aggregated keys and signatures](/protocol/blockchain/cryptography/multisignature#private-multisignature).
Only a single signature is produces, regardless of the number of parties involved, reducing the cost of multisignature validation and minimizing transaction size.
This also means it could fit in a P2PKH (or P2PK) script, and therefore have a typical address of that type.
This technique is newer, however, and not as widely implemented as the P2SH method.
+2 -2
View File
@@ -16,9 +16,9 @@ Since validation of all the transactions in the block can be expensive, the abil
| Field | Length | Format | Description |
|--|--|--|--|
| version | 4 bytes | unsigned integer<sup>[(LE)](/protocol/misc/endian/little)</sup> | The block format version. |
| version | 4 bytes | unsigned integer<sup>[(LE)](/protocol/misc/endian/little)</sup> | The block format version. Currently 0x04000000. <br>For more details refer to the [block version history](/history/block-version). |
| previous block hash | 32 bytes | [block hash](/protocol/blockchain/hash)<sup>[(LE)](/protocol/misc/endian/little)</sup> | The hash of the block immediately preceding this block in the blockchain. |
| merkle root | 32 bytes | [merkle root](/protocol/blockchain/merkle-tree)<sup>[(LE)](/protocol/misc/endian/little)</sup> | The merkle tree root of the transactions in the block. |
| merkle root | 32 bytes | [merkle root](/protocol/blockchain/block/merkle-tree)<sup>[(LE)](/protocol/misc/endian/little)</sup> | The merkle tree root of the transactions in the block. |
| timestamp | 4 bytes | unix timestamp<sup>[(LE)](/protocol/misc/endian/little)</sup> | The epoch timestamp of the block in seconds. |
| target | 4 bytes | [compressed target](#compressed-target-format)<sup>[(LE)](/protocol/misc/endian/little)</sup> | The target that the block hash must be below to be valid. This value is determined by the timestamps of previously mined blocks. See [Target](/protocol/blockchain/proof-of-work#target) for more information. |
| nonce | 4 bytes | bytes<sup>[(LE)](/protocol/misc/endian/little)</sup> | A random value that is repeatedly changes during block mining in order to achieve the block hash requirements. |
+73
View File
@@ -0,0 +1,73 @@
# Bitcoin Keys
Bitcoin Cash transactions are secured through the use of key-pairs generated by all senders and receivers.
The key-pair is comprised of a **private key**, which is generated randomly and stored securely on a user's device, and a **public key**, which is calculated from the private key but can be sent to others without revealing the private key.
The private key can be used to generate [signatures](/protocol/blockchain/cryptography/signatures), which can then be verified using the public key.
## Private Key Generation
Bitcoin Cash uses [elliptic-curve cryptography (ECC)](https://en.wikipedia.org/wiki/Elliptic-curve_cryptography); in particular, the secp256k1 curve with 32-byte (256-bit) private keys.
From [SEC 2, ver. 2.0](https://www.secg.org/sec2-v2.pdf), the curve parameters are as follows:
> The elliptic curve domain parameters over Fp associated with a Koblitz curve secp256k1 are
> specified by the sextuple `T = (p, a, b, G, n, h)` where the finite field `F<sub>p</sub>` is defined by:
>
> p = FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE FFFFFC2F
> = 2<sup>256</sup> − 2<sup>32</sup> − 2<sup>9</sup> − 2<sup>8</sup> − 2<sup>7</sup> − 2<sup>6</sup> − 2<sup>4</sup> − 1
>
> The curve E: `y<sup>2</sup> = x<sup>3</sup> + ax + b` over `F<sub>p</sub>` is defined by:
>
> a = 00000000 00000000 00000000 00000000 00000000 00000000 00000000
> 00000000
>
> b = 00000000 00000000 00000000 00000000 00000000 00000000 00000000
> 00000007
>
> The base point G in compressed form is:
>
> G = 02 79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9 59F2815B 16F81798
>
> and in uncompressed form is:
>
> G = 04 79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9
> 59F2815B 16F81798 483ADA77 26A3C465 5DA4FBFC 0E1108A8 FD17B448
> A6855419 9C47D08F FB10D4B8
>
> Finally the order n of G and the cofactor are:
>
> n = FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141
>
> h = 01
Private keys are then 256-bit values and can be chosen at [random](https://en.wikipedia.org/wiki/Cryptographically-secure_pseudorandom_number_generator) from the set `[1, n-1]`.
It is important that private keys are stored securely and never revealed to untrusted third-parties.
Anyone with access to a given private key would be able to control any funds secured with that key.
## Public Key Generation
Public keys are created by performing [scalar multiplication of the generator](https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication), G, with the private key.
This means that public keys are a point on the elliptic curve, represented as two 256-bit coordinates, `(x, y)`.
This means that a full public key is 512-bits (64 bytes) in length.
However, since elliptic curves are symmetrical across the x-axis, there are always two y-values that correspond to a given x-value, which can be calculated using the curve function, E.
These are also necessarily negations of each other mod p (i.e. y<sub>1</sub> = p - y<sub>2</sub>).
As a result, public keys are often **compressed** into 33 bytes, 32 bytes for the x-value and an additional bit (generally expanded to a full byte) indicating which y-value should be used.
When included in [scripts](/protocol/blockchain/script), public keys follow one of two formats:
### Uncompressed Public Key Format
| Field | Length | Format | Description |
|--|--|--|--|
| magic number | 1 byte | byte | Always `0x04`, indicating that this is an uncompressed public key. |
| x-value | 32 bytes | bytes | The zero-padded x-value of the public key. |
| y-value | 32 bytes | bytes | The zero-padded y-value of the public key. |
### Compressed Public Key Format
| Field | Length | Format | Description |
|--|--|--|--|
| magic number | 1 byte | byte | `0x02` if the (discarded) y-value was even, `0x03` if it was odd. This bytes indicates both that this is a compressed public key and which y-value should be used.<br/><br/>NOTE: this works because the y-values are negations of each other (mod p), so it is always that case that one is even and the other odd. |
| x-value | 32 bytes | bytes | The zero-padded x-value of the public key. |
@@ -4,7 +4,7 @@ Multisignature (often called "multisig") refers to requiring multiple keys to sp
Multisignature scripts set a condition where N public keys are recorded in the script and at least M of those must provide signatures to unlock the funds. This is also known as *M-of-N multisignature scheme*, where N is the total number of keys and M is the threshold of signatures required for validation. The signatures used can either be ECDSA signatures or Schnorr signatures.
## Public multisignature: OP_CHECKMULTISIG(VERIFY)
## Public Multisignature: OP_CHECKMULTISIG(VERIFY)
Multisig schemes can be built with the opcodes `OP_CHECKMULTISIG` and `OP_CHECKMULTISIGVERIFY`, two opcodes of the Bitcoin Cash [scripting language](/protocol/blockchain/script). `OP_CHECKMULTISIGVERIFY` has the same implementation as `OP_CHECKMULTISIG`, except OP_VERIFY is executed afterward.
@@ -78,7 +78,9 @@ If they want to use Schnorr, they have to sign the transaction with this algorit
The value of the `dummy` element is 5, whose binary representation is `0b101`. This ensures that Alice's signature (`sigA`) is checked against her public key (`pubkeyA`), that Carol's signature (`sigC`) is not checked against Bob's public key (`pubkeyB`) but against her public key (`pubkeyC`).
## Private multisignature
Multisig schemes can also be implemented in P2PKH outputs, using Schnorr agregation property.
## Private Multisignature
N-of-N multisig schemes can also be implemented in P2PKH outputs, using the Schnorr aggregation property.
By combining the public keys of the cooperating parties, a combined public key can be created and used in a locking script.
When spending the output, the parties can jointly create a signature that will validate as a normal Schnorr signature for the combined public key in the locking script.
For more details, see [MuSig](https://eprint.iacr.org/2018/068).
@@ -0,0 +1,36 @@
# Signatures
Bitcoin transaction generally require at least one signature in order to be valid.
Signatures prove that the intended recipient(s) of the funds being spent were involved in the creation of the transaction.
Each signature is generated using a [private key](/protocol/blockchain/cryptography/keys) and indicates that the owner of that private key approves of certain data in the transaction.
This page describes how these signature are generated, given data to be signed and a private key.
For details on what data is signed when signing a transaction and how the signature is formatted, see [Transaction Signing](/protocol/blockchain/transaction/transaction-signing).
Bitcoin Cash permits two algorithms for transaction signatures: [ECDSA](#ecdsa-signatures) and [Schnorr](#schnorr-signatures).
## ECDSA Signatures
ECDSA, as defined in [RFC 6979](https://tools.ietf.org/html/rfc6979), can be thought of as taking three input parameters: the private key, the message to be signed, and a random value, **k**, taken from the [same domain as a private key](/protocol/blockchain/cryptography/keys#private-key-generation), `[1, n-1]`.
Generally with ECDSA, the message used is a hash of the data that is intended to be signed.
In the case of Bitcoin Cash, this is the hash of the transaction [preimage](/protocol/blockchain/transaction/transaction-signing#preimage-format) for the context in which the signature will be provided (i.e. for a given position in a script).
It is also common, and recommended, to use a **deterministic k** value (defined in [RFC 6979, section 3](https://tools.ietf.org/html/rfc6979#section-3)), which is dependent on the private key and the message being signed.
Using a deterministic k value guarantees that a different k will never be used to sign an identical message, a mistake which would reveal the user's private key.
However, since it is impossible to know the method used to generate k without the user's private key, it is impossible to enforce the use of this method.
The output of ECDSA is two values, **r** and **s** which can be used with the public key and message to verify the authenticity of the signature.
However, there are technically two valid s value that are possible, which are additive inverses (i.e. `s<sub>1</sub> + s<sub>2</sub> (mod p) = 0 (mod p)`).
By convention, and since [HF-20171113](/protocol/forks/hf-20171113), the lower s value must be used (this is known as the "LOW_S" rule).
## Schnorr Signatures
Schnorr signatures have been accepted in Bitcoin Cash since [HF-20190515](/protocol/forks/hf-20190515).
Details on the implementation of Schnorr used in Bitcoin Cash can be found [here](/protocol/forks/2019-05-15-schnorr).
Of particular importance are the following points:
- Pre-existing Public and Private Keys are valid for generating Schnorr signatures.
- Following activation of Schnorr signatures, all 64-byte signatures passed to OP_CHECKDATASIG/VERIFY and all 65-byte signatures passed to OP_CHECKSIG/VERIFY are interpretted as Schnorr signatures.
65-byte signatures passed to OP_CHECKMULTISIG/VERIFY will trigger script failure.
- Bitcoin Cash uses the (r, s) variant of Schnorr, instead of the (e, s) variant, with an altered approach from that originally proposed by Pieter Wuille.
- Both random and deterministic k values are considered secure, though care must be taken with deterministic k values to avoid conflicts with deterministic ECDSA k values.
@@ -1,22 +1,83 @@
# Difficulty Adjustment Algorithm
In order to correct for changes in the Bitcoin Cash network's total hashing power (i.e. as hardware improves or nodes are added to or removed from the network), the amount of work required to mine a block must change in tandem.
Bitcoin Cash solves this by adjusting the difficulty according to an algorithm that looks at recent block timestamps, infers the hashing power that led to those timestamps, and adjusts the difficulty for future blocks accordingly.
Bitcoin Cash solves this by adjusting the [target](/protocol/blockchain/proof-of-work#target) according to an algorithm that looks at recent block timestamps, infers the hashing power that led to those timestamps, and attempts to change the [difficulty](/protocol/blockchain/proof-of-work#difficulty) of mining future blocks accordingly.
The calculation used is referred to as the Difficulty Adjustment Algorithm, or DAA, and has changed a number of times.
In order to validate the blockchain, however, the difficulty must be verified using the DAA that was in use when that block was mined.
Consequently, the historical DAAs remain relevant to node implementation that wish to validate historical headers.
The current Bitcoin Cash difficulty adjustment algorithm attempts to ensure that the difficulty of new blocks is always closely tied to recent block difficulties.
The algorithms used, from newest to oldest, are:
- [ASERT](#asert)
- [CW-144](#cw-144)
- [Emergency DAA](#emergency-daa)
- [Legacy DAA](#legacy-daa)
## ASERT
Absolutely Scheduled Exponentially Rising Targets (ASERT), more specifically [aserti3-2d](/protocol/forks/2020-11-15-asert), was implemented as a part of [HF-20201115](/protocol/forks/hf-20201115).
It uses an [exponential moving average](https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average) approach that should theoretically always target a correction toward a 10 minute average block time.
ASERT bases it's calculations on the following components:
1. The **fork block**: The first block mined with the ASERT DAA
2. The **anchor block**: The parent of the fork block
3. The current head block
Though this is not used directly in practice, the exponential form of the calculation of the target for the next block is:
```
exponent = (time_delta - ideal_block_time * (height_delta + 1)) / halflife
next_target = anchor_target * 2**(exponent)
```
where:
- `anchor_target` is the unsigned 256 bit integer equivalent of the `nBits` value in
the header of the anchor block.
- `time_delta` is the difference, in signed integer seconds, between the
timestamp in the header of the current block and the timestamp in the
parent of the anchor block.
- `ideal_block_time` is a constant: 600 seconds, the targeted
average time between blocks.
- `height_delta` is the difference in block height between the current
block and the anchor block.
- `halflife` is a constant parameter sometimes referred to as
'tau', with a value of 172800 (seconds) on mainnet.
- `next_target` is the integer value of the target computed for the block
after the current block.
In order to avoid subtle platform-dependent floating point issues, however, ASERT is instead calculated using fixed-point integer arithmetic with a cubic polynomial approximation of the exponential.
See [ASERT:target computeration](/protocol/forks/2020-11-15-asert#target-computation) for the Python reference implementation and additional details on where new implementations of the algorithm must be cautious to ensure full compatibility.
## CW-144
CW-144 attempts to ensure that the difficulty of new blocks is always closely tied to the amount of work done on recent blocks.
The name referes to the fact that it evaluates the difference in [chainwork](/protocol/blockchain/proof-of-work#chainwork) (CW) across the most recent 144 blocks.
Put into place as a part of [HF-20171113](/protocol/forks/hf-20171113), it performs the following calculation to determine the difficulty of a block, <code>B<sub>n+1</sub></code>, with block height `n+1`:
- Select <code>B<sub>new</sub></code>: The block with the median timestamp of the blocks <code>B<sub>n</sub></code>, <code>B<sub>n-1</sub></code>, and <code>B<sub>n-2</sub></code>
- Select <code>B<sub>old</sub></code>: The block with the median timestamp of the blocks <code>B<sub>n-144</sub></code>, <code>B<sub>n-145</sub></code>, and <code>B<sub>n-146</sub></code>.
- Calculate `t`, the difference between the timestamps of <code>B<sub>new</sub></code> and <code>B<sub>old</sub></code>. If this difference is less than `72 * 600`, use `72 * 600`, if it is above `288 * 600`, use `288 * 600`.
- Calculate `W`, the difference in [chainwork](/protocol/blockchain/proof-of-work#chainwork) between <code>B<sub>new</sub></code> and <code>B<sub>old</sub></code>.
- Calculate `W`, the difference in chainwork between <code>B<sub>new</sub></code> and <code>B<sub>old</sub></code>.
- Calculate `PW`, the projected work for the next block, as `(W * 600) / t`.
- Calculate `T`, the target difficulty, as <code>(2<sup>256</sup> - PW) / PW</code>. In 256-bit two's-complement arithmetic, this is equivalent to `(-PW) / PW`.
- If `T` is greater than the maximum target of `0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF`, use the maximum target. Otherwise, use `T`.
In other words, for any given block the projected work is be equal to the difference in chainwork multiplied by an adjustment. The adjustment is 600 seconds (the goal timeframe for a block to be mined) divided by the difference in timestamps between the median block (by timestamp) of its prior three immediate ancestors and its 144th, 145th, and 146th ancestors (bounded by `72 * 600` and `288 * 600`). The projected work is then converted into the target by subtracting it from 2<sup>256</sup> and then dividing the result by the projected work. Then minimum of that calculated value and the maximum target is then used as the target for that block.
## Legacy Difficulty Adjustment Algorithm
## Emergency DAA
As a part of [BCH-UAHF](/protocol/forks/bch-uahf), due to the anticipated decrease in hashing power, the following adjustment to the legacy difficulty adjustment algorithm above was put into place:
>In case the MTP of the tip of the chain is 12h or more after the MTP 6 block before the tip, the proof of work target is increased by a quarter, or 25%, which corresponds to a difficulty reduction of 20% .
>
> RATIONALE: The hashrate supporting the chain is dependent on market price and hard to predict. In order to make sure the chain remains viable no matter what difficulty needs to adjust down in case of abrupt hashrate drop.
That is, if the block height is not divisible by 2016, the target may still be adjusted if the current MTP is more than 12 hours after the MTP from 6 blocks prior. In this case, the target is multiplied by 1.25.
This algorithm was superseded by the current difficulty adjustment algorithm as a part of HF-20171113.
## Legacy DAA
Prior to [BCH-UAHF](/protocol/forks/bch-uahf), the original Bitcoin difficulty adjustment algorithm was used.
To determine the difficulty of a block, <code>B<sub>n+1</sub></code>, with block height `n+1`:
@@ -30,15 +91,3 @@ To determine the difficulty of a block, <code>B<sub>n+1</sub></code>, with block
- If `T` is greater than the maximum target of `0x00000000FFFF0000000000000000000000000000000000000000000000000000`, use the maximum target instead. Otherwise, use `T`.
This boils down to a possible change in difficulty every 2016 blocks, where the new target (for the next 2016 blocks) is calculated by dividing the time taken for the last 2015 blocks by the time expectation for 2016 blocks (bounded by 0.25 and 4) and multiplying that ratio by the existing target.
## Emergency Difficulty Adjustment Algorithm
As a part of BCH-UAHF, due to the anticipated decrease in hashing power, the following adjustment to the legacy difficulty adjustment algorithm above was put into place:
>In case the MTP of the tip of the chain is 12h or more after the MTP 6 block before the tip, the proof of work target is increased by a quarter, or 25%, which corresponds to a difficulty reduction of 20% .
>
> RATIONALE: The hashrate supporting the chain is dependent on market price and hard to predict. In order to make sure the chain remains viable no matter what difficulty needs to adjust down in case of abrupt hashrate drop.
That is, if the block height is not divisible by 2016, the target may still be adjusted if the current MTP is more than 12 hours after the MTP from 6 blocks prior. In this case, the target is multiplied by 1.25.
This algorithm was superseded by the current difficulty adjustment algorithm as a part of HF-20171113.
+8 -3
View File
@@ -41,11 +41,14 @@ In general, though, this combined unlocking/locking script is then executed and
Additionally, in order for the combined script to be valid, the following must be true:
- **Non-Empty Scripts** - both the locking and unlocking scripts must be non-empty.
- **Max Script Length** - the locking and unlocking script must each be less than the max script length of 10,000 bytes (for a combined script maximum of 20,000 bytes).
- **Max Script Length** - the locking and unlocking script, when executed, must each be less than the max script length of 10,000 bytes (for a combined script maximum of 20,000 bytes).
- **Contained Control Flow** - an IF/ELSE block cannot start in the unlocking script and end in the locking script, the script must be in the top-level scope when the locking script execution begins.
- **Permitted Operations Only** - the locking script must not include operations that are disallowed and must not execute operations that are disabled..
- **Push Only** - the unlocking script must contain only push operations (i.e. those with op codes 0x60 or less). Added in [HF-20181115](/protocol/forks/hf-20181115).
NOTE: violations of the above rules does not necessarily make a transaction invalid.
For example, a locking script may be longer than 10,000 bytes, but it would be unspendable, since the max script length is only checked when the scripts are combined before execution.
## Operation codes (opcodes)
The table below lists the currently allocated op codes. Op codes marked with **(ignored)** are permitted but will do nothing when executed.
@@ -125,6 +128,8 @@ Op codes marked with **(do not use)** are disallowed and will make a transaction
### Arithmetic
Numeric opcodes (OP_1ADD, etc) are restricted to operating on 4-byte integers. The semantics are subtle, though: operands must be in the range [-2^31 +1...2^31 -1], but results may overflow (and are valid as long as they are not used in a subsequent numeric operation).
|Word |Value |Hex |Input |Output | Description |
|---------------------|-------|----|--------------|-----------------|------------------------------------------------------|
|OP_1ADD | 139 |0x8b|in |out | 1 is added to the input. |
@@ -138,8 +143,8 @@ Op codes marked with **(do not use)** are disallowed and will make a transaction
|OP_ADD | 147 |0x93|a b |out | *a* is added to *b*. |
|OP_SUB | 148 |0x94|a b |out | *b* is subtracted from *a*. |
|OP_MUL | 149 |0x95|a b |out | *a* is multiplied by *b*. **DISABLED** |
|OP_DIV | 150 |0x96|a b |out | *a* is divided by *b*. |
|OP_MOD | 151 |0x97|a b |out | Returns the remainder after *a* is divided by *b*. |
|OP_DIV | 150 |0x96|a b |out | *a* is [divided](/protocol/blockchain/script/integer-division) by *b*. |
|OP_MOD | 151 |0x97|a b |out | Returns the remainder after *a* is [divided](/protocol/blockchain/script/integer-division) by *b*. |
|OP_LSHIFT | 152 |0x98|a b |out | Shifts *a* left *b* bits, preserving sign. **DISABLED** |
|OP_RSHIFT | 153 |0x99|a b |out | Shifts *a* right *b* bits, preserving sign. **DISABLED** |
|OP_BOOLAND | 154 |0x9a|a b |true / false | If both *a* and *b* are not 0, the output is 1. Otherwise 0. |
@@ -0,0 +1,19 @@
# Script Integer Division
The Bitcoin Script [OP_DIV](/protocol/blockchain/script#arithmetic) and [OP_MOD](/protocol/blockchain/script#arithmetic) operations are performed on script numbers, which are signed integers.
However, there are multiple valid approaches to signed integer division, particularly with respect to how negative values are handled, so this must be disambiguated.
The above operations follow [C](https://en.wikipedia.org/wiki/C_(programming_language))-style integer division semantics.
For a given `numerator` and `denominator`, if `OP_DIV` returns `quotient` and `OP_MOD` returns `remainder`, the following relation be true: `numerator = quotient * denominator + remainder`.
This allows for both negative quotients and remainders.
The following examples may provide clarity:
OP_DIV 5 2 -> 2
OP_MOD 5 2 -> 1
OP_DIV -5 2 -> -2
OP_MOD -5 2 -> -1
OP_DIV 5 -2 -> -2
OP_MOD 5 -2 -> 1
OP DIV -5 -2 -> 2
OP_MOD -5 -2 -> -1
@@ -1,8 +1,13 @@
# Block-Level Validation Rules
Block-level validation rules, also referred to as consensus rules, define what is permitted to be included in a block.
Block-level validation rules are absolute and any block or transaction that would cause a violation such a rule must be rejected.
These differ from [network-level validation rules](/protocol/blockchain/transaction-validation/network-level-validation-rules), also referred to as standardness rules, which can be circumvented by miners, should they wish to include a non-standard transaction in a block.
In short, consensus (block-level) rules define what is permitted in a block, while standardness (network-level) rules define recommended behavior for nodes on the network.
When validating a transaction, it must be done within the context of a block. That may be a historical (or new) block that the transaction is a part of or it may be as a part of a hypothetical "next" block. The latter category, often referred to as "mempool" transactions, represent transactions that a node is aware of, and considers valid, but that have not yet been added to a block. In this case, they are treated as though they are all in a new block that follows after the last block in the longest chain the node is currently aware of.
The reason that transaction validation is context-dependent in this way stems from what is probably the most important validation rule: the inputs to a transaction must be a UTXO. That is, transactions must spend transaction outputs that were created by a prior transaction but that have not been spent by another transaction in the target block or its history. Note that this means that blocks with divergent histories will treat different transactions as valid. For example, consider the following scenario:
The reason that transaction validation is context-dependent in this way stems from what is probably the most important validation rule: the inputs to a transaction must be UTXOs. That is, transactions must spend transaction outputs that were created by a prior transaction but that have not been spent by another transaction in the target block or its history. Note that this means that blocks with divergent histories will treat different transactions as valid. For example, consider the following scenario:
```mermaid
graph LR;
@@ -15,13 +20,39 @@ blockb --> blockb2(Block B')
Since `Block A'` and `Block B'` are at the same block height, there may be some nodes that treat `Block A'` as the most recent block (e.g. `Node A`) and others that treat `Block B'` as the most recent block (e.g. `Node B`). If a transaction is submitted to both `Node A` and `Node B` that spends an output created in a transaction in `Block A`, `Node A` may consider the transaction valid while `Node B` would reject it on the grounds that it is dependent on a UTXO that is not a part of `Block B'`'s history, which only contains `Block B'`, `Block B`, and `Block N` (and its parents).
Other block-level validation rules include:
## Consensus Rules
- Double-Spend Validation
- The inputs of a transaction may only be spent once on a given blockchain fork.
- That is, if two transactions spend a given input, only one may be valid at any given time.
- See [blockchain reorganization](/protocol/blockchain#blockchain-reorganization) for information on how resolution of such conflicts is resolved.
- Transaction Input and Output Validation
- The total value of the outputs of a transaction may not exceed the total input value of the transaction, except in the case of [coinbase transactions](/protocol/blockchain/block#coinbase-transaction).
- Coinbase Transaction Reward Validation
- The coinbase transaction in a block must collect the correct reward for the block height. For more information see [Coinbase Transaction](/protocol/blockchain/block#coinbase-transaction).
- Transaction Chaining Limit
- Many nodes impose a limit of transactions that can be chained together in a single block. That is, if transaction Z spends an output of transaction Y, which spends an input of transaction X, and so on to Transaction A, the transaction may be rejected.
- This limit is often set to 25 chained transactions.
- Coinbase Maturity
- Outputs of coinbase transactions may not be spent for 100 blocks.
- That is, the block reward from block 1,000 may not be spent until block 1,100.
- Coinbase Transaction Block Height
- The coinbase transaction in a block must provide an unlocking script that that starts with a push operation which pushes the block height of the block it is contained in.
- This requirement was added in [BIP-34](/protocol/forks/bip-0034) to ensure that coinbase transactions are unique.
- This requirement was added in [BIP-34](/protocol/forks/bip-0034) to ensure that coinbase transactions are unique.
- Signature Check Counting
- The number of signature checks in a transaction may not exceed 3,000.
- The number of signature checks in a block may not exceed the max block size divided by 141 (currently this is 226,950).
- For details on how signature checks are counted, see [SigChecks](#sigchecks)
- Transaction
### SigChecks
SigChecks was implemented as a part of [HF-20200515](/protocol/forks/hf-20200515) and replaced the existing system of signature operation counting (SigOps).
During script execution, signature checks are counted using the following rules:
- Executing OP_CHECKSIG / OP_CHECKSIGVERIFY / OP_CHECKDATASIG / OP_CHECKDATASIGVERIFY increments SigChecks by:
- +0, if signature is NULL.
- +1, if signature is non-NULL.
- Executing an M-of-N OP_CHECKMULTISIG / OP_CHECKMULTISIGVERIFY increments SigChecks by:
- +0, if all M signatures are NULL.
- +M, if at least one signature is non-NULL and the verification is in [New/Schnorr mode](/protocol/forks/2019-11-15-schnorrmultisig) (dummy element is non-NULL).
- +N, if at least one signature is non-NULL and the verification is in Old/ECDSA mode (dummy element is NULL).
@@ -14,11 +14,10 @@ Standard transactions are those that:
- Have a version 1 or [version 2](/protocol/forks/bip-0068/)
- Have input scripts that only contain push operations
- Have input scripts with unlocking scripts less or equal to 1650 bytes in length (see scriptSig limit below)
- Have at most one [data output](/protocol/blockchain/transaction/locking-script#data-output), with a script no longer than 223 bytes (see [data output size limit](#data-output-size-limit) below)
- Have the total size of [data output](/protocol/blockchain/transaction/locking-script#data-output) locking scripts no larger than 223 bytes (see [data output size limit](#data-output-size-limit) below)
- For [multisig](/protocol/blockchain/transaction/locking-script#multisig) outputs, must have at most 3 parties and at least 1 required party (i.e. 1-of-1 through 3-of-3).
- Have non-data outputs with amount above the [dust](#dust) threshold
\* 223 bytes was chosen to allow for the `OP_RETURN` operation (1 byte), a push operations (2 bytes), and 220 bytes of pushed data.
- Each input of the transaction, must require no more than `((scriptLength + 60) / 43)` [SigChecks](/protocol/blockchain/transaction-validation/block-level-validation-rules#sigchecks)
Be aware, however, that these rules may vary from node-to-node as they are often configurable.
Some nodes may also accept and relay non-standard transactions.
@@ -44,6 +43,10 @@ The data output size limit is calculated as follows:
* 2 bytes for a push operation
* Up to 220 bytes of data to be "pushed"
In [HF-20210515](/protocol/forks/hf-20210515) this size limit was kept the same but allowed to apply to any number of data outputs in the transaction, provided the total size of data output locking scripts does not exceed the limit.
For example, a transaction is now allowed to have three locking scripts that are each 74 bytes in length.
However, a transaction with two data outputs each with 112-byte locking scripts would be invalid as `112 * 2 = 224` exceeds the 223-byte limit.
## Dust
In order to limit the propagation of transactions with limited utility, outputs that would be cost-prohibitive to spend are rejected as "dust."
+1 -1
View File
@@ -13,7 +13,7 @@ Verification of a transaction ensures that:
| Field | Length | Format | Description |
|--|--|--|--|
| version | 4 bytes | unsigned integer<sup>[(LE)](/protocol/misc/endian/little)</sup> | The version of the transaction format. Currently `0x02000000`. |
| version | 4 bytes | unsigned integer<sup>[(LE)](/protocol/misc/endian/little)</sup> | The version of the transaction format. Currently `0x02000000`.<br>For more details refer to the [transaction version history](/history/transaction-version). |
| input count | variable | [variable length integer](/protocol/formats/variable-length-integer) | The number of inputs in the transaction. |
| transaction inputs | variable | `input_count` [transaction inputs](#transaction-input) | Each of the transaction's inputs serialized in order. |
| output count | variable | [variable length integer](/protocol/formats/variable-length-integer) | The number of output in the transaction. |
@@ -20,7 +20,7 @@ If the signature is valid for the specified public key in the locking script, th
| Operation | Description |
|--|--|
| [OP_DATA_X](/protocol/blockchain/script/op-codes/op-data-x) (public key) | Add the recipient's public key to the stack. The data pushed must be either a compressed or uncompressed public key with appropriate length (33 bytes if the key is compressed, 65 bytes if it is not) for the type for the script to be recognized as P2PK. |
| [OP_CHECKSIG](/protocol/blockchain/script/opcodes/op-checksig) | Check the public key at the top of the stack against the signature below it on the stack. |
| [OP_CHECKSIG](/protocol/blockchain/script#cryptography) | Check the public key at the top of the stack against the signature below it on the stack. |
<img src="/_static_/images/warning.png" /> **NOTE:** Pay to Public Key is a largely obsolete type of locking script due to its property of leaking the public key of the recipient before the output is unlocked, resulting in:
@@ -31,18 +31,18 @@ That is, if it ever becomes possible to create a signature using a public key (n
### Pay to Public Key Hash (P2PKH)
Pay to Public Key Hash is a widely used standard locking script format, that works similarly to P2PK but instead of pushing the public key, it pushes a hash of the public key, commonly referred to as an address.
Pay to Public Key Hash is a widely used standard locking script format, that works similarly to P2PK but instead of pushing the public key, it pushes a hash of the public key, commonly referred to as an [address](/protocol/blockchain/addresses).
This heavily reduces the risks associated with a plain P2PK script as the hashing algorithms used provide a considerable barrier to determining the public key a priori.
To spend an output locked with this type of script, the unlocking script is expected to push a signature and then the public key corresponding to the private key that created the signature.
If that public key hashes to the expected address, and the signature is valid, the output is allowed to be spent.
| Operation | Description |
|--|--|
| [OP_DUP](/protocol/blockchain/script/opcodes/op-dup) | Copy the value at the top of the stack (public key of the recipient). |
| [OP_HASH160](/protocol/blockchain/script/opcodes/op-hash160) | Perform a SHA-256 then a RIPEMD-160 on the copied value. |
| [OP_DUP](/protocol/blockchain/script#stack) | Copy the value at the top of the stack (public key of the recipient). |
| [OP_HASH160](/protocol/blockchain/script#cryptography) | Perform a SHA-256 then a RIPEMD-160 on the copied value. |
| [OP_DATA_X](/protocol/blockchain/script/op-codes/op-data-x) (20 bytes) | Push the expected 20 byte address. |
| [OP_EQUALVERIFY](/protocol/blockchain/script/opcodes/op-equalverify) | Verify that the hash of the copied value matches the expected hash that was pushed. |
| [OP_CHECKSIG](/protocol/blockchain/script/opcodes/op-checksig) | Verify that the stack now contains only a public key (which was duplicated, hashed, and checked against the expected value) and a signature and verify that the signature is valid for that public key. |
| [OP_EQUALVERIFY](/protocol/blockchain/script#bitwise) | Verify that the hash of the copied value matches the expected hash that was pushed. |
| [OP_CHECKSIG](/protocol/blockchain/script#cryptography) | Verify that the stack now contains only a public key (which was duplicated, hashed, and checked against the expected value) and a signature and verify that the signature is valid for that public key. |
### Pay to Script Hash (P2SH)
@@ -53,9 +53,9 @@ If this redeem script finishes execution successfully, the output is allowed to
| Operation | Description |
|--|--|
| [OP_HASH160](/protocol/blockchain/script/opcodes/op-hash160) | Hash the data at the top of the stack, this should be the script to be executed. |
| [OP_HASH160](/protocol/blockchain/script#cryptography) | Hash the data at the top of the stack, this should be the script to be executed. |
| [OP_DATA_X](/protocol/blockchain/script/op-codes/op-data-x) (20 bytes) | Push the expected redeem script hash. |
| [OP_EQUAL](/protocol/blockchain/script/opcodes/op-equal) | Verify that the hash of the provided script is equal to the expected hash. |
| [OP_EQUAL](/protocol/blockchain/script#bitwise) | Verify that the hash of the provided script is equal to the expected hash. |
Due to the nature of this type of locking script, the following steps must be performed by a node executing this script:
@@ -84,7 +84,7 @@ One drawback of this is that it is not possible to determine whether certain ins
This makes retirement of opcodes impossible.
However, it's also possible for people to create transactions and not commit them to the blockchain, so the viability of opcode retirement is questionable anyway.
### Multisig
### Multisig (P2MS)
Multiple-signature, or multisig, scripts provide a mechanism to have multiple private keys coordinate with spending funds.
For example, three people could share funds and require that for some transactions any one of them could spend it while, for others, two of them would need to agree, and for others still, all three people would need to agree to spend the funds.
@@ -92,12 +92,14 @@ Each party's public key is included in the locking script along with the require
An unlocking script is therefore expected to provide the required number of signatures which are then checked against the list of public keys. If a sufficient number of valid signatures are provided, the output is allowed to be spent.
These are also referred to as "bare multisig" scripts to disambiguate them from P2SH multisig scripts (see [Multisignature](/protocol/blockchain/cryptography/multisignature)).
| Operation | Description |
|--|--|
| [OP_X](/protocol/blockchain/script/op-codes/op-x) | Push the number of parties required to provide signatures. |
| 1 or more [OP_DATA_X](/protocol/blockchain/script/op-codes/op-data-x) (public key) | Push 1 or more public keys, indicating all of the parties that could provide signatures. |
| [OP_X](/protocol/blockchain/script/op-codes/op-x) | The total number of parties added (i.e. the number of public keys pushed). |
| [OP_CHECKMULTISIG](/protocol/blockchain/script/op-codes/op-checkmultisig) | Check for signatures matching the number of required parties, verify that they correspond to permitted public keys, and that the signatures are valid. |
| [OP_CHECKMULTISIG](/protocol/blockchain/script#cryptography) | Check for signatures matching the number of required parties, verify that they correspond to permitted public keys, and that the signatures are valid. |
NOTE: due to a historical bug, the locking script must push an additional value before the signatures. Traditionally this is done via [OP_0](/protocol/blockchain/script/op-codes/op-x). The value is not used but is popped off of the stack by the OP_CHECKMULTISIG at the end of the locking script.
@@ -109,5 +111,5 @@ As such, outputs locked with data scripts generally have zero satoshis associate
| Operation | Description |
|--|--|
| [OP_RETURN](/protocol/blockchain/script/opcodes/op-return) | Fail execution immediately. |
| Data | Any additional data is not executed and thus can be whatever data is desired by the script creator. |
| [OP_RETURN](/protocol/blockchain/script#flow-control) | Fail execution immediately. |
| Data Pushes | Data may optionally be added as a series of push operations. However, these push operations are not executed and thus can push whatever arbitrary data is desired by the script creator. |
@@ -52,15 +52,30 @@ Combining these, there are 6 valid signature hash types in Bitcoin Cash. Only t
## Bitcoin Cash Signatures
In Bitcoin Cash, transaction signatures use the transaction digest algorithm described in [BIP143](https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki), in order to minimize redundant data hashing in verification and to cover the input value by the signature.
In Bitcoin Cash, transaction signatures use the transaction digest algorithm described in a modification of [BIP143](/protocol/forks/replay-protected-sighash), in order to minimize redundant data hashing in verification and to cover the input value by the signature.
### Preimage Format
At a high level, the preimage format for a signature within a single input is a serialization of the following transaction components, **many of which are hashed, modified, or substituted** depending on the context:
1. Transaction version
2. Previous transaction outputs identifiers
3. Transaction input sequence numbers
4. The identifier of the output being spent
5. The locking script of the output being spent
6. The value of the output being spent
7. The sequence number of the transaction input
8. The created transaction outputs
9. Transaction locktime
10. The signature hash type
The following table specifies, in detail, the preimage format for a signature within a single input:
| Field | Length | Format | Description |
|--|--|--|--|
| transaction version | 4 bytes | unsigned integer<sup>[(LE)](/protocol/misc/endian/little)</sup> | The value of transaction's version field. |
| previous outputs hash | 32 bytes | hash<sup>[(BE)](/protocol/misc/endian/big)</sup> | A double SHA-256 hash of the set of previous outputs spent by the inputs of the transaction. See [Previous Outputs](#previous-outputs-hash) for the hash preimage format.<br/><br/>If hash type is "ANYONE CAN PAY" then this is all `0x00` bytes. |
| sequence numbers hash | 32 bytes | hash<sup>[(BE)](/protocol/misc/endian/big)</sup> | A double SHA-256 hash of the set of sequence numbers of the inputs of the transaction. See [Sequence Numbers](#sequence-numbers-hash) for the hash preimage format.<br/><br/>If hash type is "ANYONE CAN PAY" then this is all `0x00` bytes. |
| previous outputs hash | 32 bytes | hash<sup>[(BE)](/protocol/misc/endian/big)</sup> | A double SHA-256 hash of the set of previous outputs spent by the inputs of the transaction. See [Previous Outputs](#previous-outputs-hash) for the hash preimage format.<br/><br/>If hash type is "ANYONECANPAY" then this is all `0x00` bytes. |
| sequence numbers hash | 32 bytes | hash<sup>[(BE)](/protocol/misc/endian/big)</sup> | A double SHA-256 hash of the set of sequence numbers of the inputs of the transaction. See [Sequence Numbers](#sequence-numbers-hash) for the hash preimage format.<br/><br/>If hash type is "ANYONECANPAY", "SINGLE", or "NONE" then this is all `0x00` bytes. |
| previous output hash | 32 bytes | hash<sup>[(LE)](/protocol/misc/endian/little)</sup> | The transaction ID of the previous output being spent. |
| previous output index | 4 bytes | unsigned integer<sup>[(LE)](/protocol/misc/endian/little)</sup> | The index of the output to be spent. |
| modified locking script length | variable | [variable length integer](/protocol/format/variable-length-integer) | The number of bytes for `modified_locking_script`. |