This is a read note of Programming Bitcoin Ch09: Blocks. Blocks are used to order the transactions thus prevent doubl-spend.

1 Coinbase Transactions

Coinbase is the required first transaction of every block and is the only transaction allowed to bring bitcoins into existence. The coinbase transaction’s outputs are kept by whomever the mining entity designates and usually include all the transaction fees of the other transactions in the block as well as something called the block reward. It has a special format as follows:

  1. Coinbase transactions must have exactly one input.
  2. The one input must have a previous transaction of 32 bytes of 00.
  3. The one input must have a previous index of ffffffff.

The ScriptSig of the coinbase transaction is set by whoever mined the transaction. The main restriction is that the ScriptSig has to be at least 2 bytes and no longer than 100 bytes. Later, BIP0034 was created to regulate the coinbase transactions to include block height as the first element of the coinbase ScriptSig. Coinbase transactions in different blocks are required to have different ScriptSigs and thus different transaction IDs.

2 Block Headers

A block header has the following fixed-length fields:

  • Version: 4 bytes
  • Previous block: 32 bytes
  • Merkle root: 32 bytes
  • Timestamp: 4 bytes
  • Bits: 4 bytes
  • Nonce: 4 bytes

A block header has a fixed size of 80 bytes. The block ID is the hex representation of the hash256 of the header interpreted in little-endian.

BIP0009 defines version pattern to signal the availability of specific features.

3 Proof-of-Work

Mining has a property: hard to mine gold but easy to verify that the gold is real.

Proof-of-work is the requirement that the hash of every block header in Bitcoin must be below a certain target. The target is a 256-bit number that is computed directly from the bits field. The bits field is actually two different numbers. The first is the exponent, which is the last byte. The second is the coefficient, which is the other three bytes in little-endian. The formula for calculating the target from these two numbers is: target = coefficient × 256 ** (exponent–3).

To make different targets easier to compare, the concept of difficulty was born. It is measured by the inverse of target: the smaller the target, the harder the proof.

In Bitcoin, each group of 2,016 blocks is called a difficulty adjustment period. The adjustment formula is new_target = previous_target * time_differential / (2 weeks) where the time_difference is the timestamp difference between the last block of the last period and the last block of the current period. Bitcoin controls the time to generate 1 block every 10 minutes thus 2016 blocks takes two weeks.