# Blockchain

> For the complete documentation index, see [llms.txt](https://bsvblockchain.com/docs/llms.txt).

How a block is built, how blocks link into a chain, and how proof of work, Merkle trees and the coinbase transaction fit together.

import ChainMiner from '/snippets/ChainMiner.jsx';

A block on the BSV blockchain is a header plus a list of transactions, and each header names the header before it. Miners add blocks by finding a header whose hash is below a target, a rule called proof of work (The work a miner does to find a block header whose hash is below the target). [How transactions and fees work](https://bsvblockchain.com/docs/concepts/transactions/) covers the transactions inside a block. On this page you can mine blocks in an interactive chain and run two short scripts that hash a block header and check a Merkle path.

The examples run with Node.js after `npm install @bsv/sdk` and were written against `@bsv/sdk` 4.0.1.

## What a block contains

A block is its header followed by its transactions, and the 80 byte header is the part that gets hashed. Edit a block below and mine it to see how the header hash, the target and the link to the next block fit together.

<ChainMiner />

A chain of three blocks. Each block has a Transactions text, a Merkle root that is the double SHA-256 of that text, the hash of the previous block, a nonce and its own block hash. A block is valid when its hash starts with enough zeros to be below the target, which can be set to 2, 3 or 4 zeros. Editing the text of a block changes its hash, which makes it and every block after it invalid, because each block holds the hash of the one before. Pressing Mine on a block tries nonces until its hash is below the target again, and the counter shows how many hashes that took. A lower target, with more leading zeros, needs more attempts.

### The block header

| Field | Size | What it holds |
| --- | --- | --- |
| Version | 4 bytes | The block version |
| Previous block hash | 32 bytes | The hash of the header before this one |
| Merkle root (One hash that stands for all the transactions in a block) | 32 bytes | One hash that stands for every transaction in the block |
| Time | 4 bytes | Seconds since 1970-01-01 UTC |
| Bits | 4 bytes | The target, in a compact form |
| Nonce (A number the miner changes to get a different hash) | 4 bytes | A number the miner changes to search for a valid hash |

The block hash is the double SHA-256 of the header, and it is written with its bytes reversed, which is how explorers show it. The header below is the first block, and its hash starts with zeros because it is below the target.

```javascript header.mjs
import { Hash, Utils } from '@bsv/sdk'

// The 80 byte header of the first block, as hex
const header =
  '01000000' + // version
  '0000000000000000000000000000000000000000000000000000000000000000' + // previous block hash
  '3ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a' + // Merkle root
  '29ab5f49' + // time
  'ffff001d' + // bits
  '1dac2b7c' // nonce

const hash = Utils.toHex(Hash.hash256(Utils.toArray(header, 'hex')).reverse())

console.log(header.length / 2, 'bytes')
console.log(hash)
```

```text
80 bytes
000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f
```

### Time, height and depth

Numbers in the header are stored little endian, so the time `29ab5f49` is 1,231,006,505, which is January 3, 2009, at 18:15:05 UTC. A transaction has no time of its own. It takes the time of the block that includes it.

The position of a block in the chain is its height, counted from zero at the first block. How many blocks sit on top of it is its depth.

## How blocks form a chain

Each header holds the hash of the header before it, so changing any block changes its hash and breaks the link in the next one. To change an old block, a miner would have to redo its proof of work and that of every block after it. The first block has no parent, so its previous hash is all zeros, as in the header above.

## Proof of work

A block counts only if its hash meets the target, and finding such a hash takes work.

### Finding a valid hash

A miner has a valid block when the hash of its header, read as a 256 bit number, is below the target. The miner changes the nonce until the hash is below the target. The nonce has only 32 bits, so miners also change a field in the coinbase transaction (The first transaction in a block, which pays the miner), which changes the Merkle root and gives them a new set of headers to try.

### The target and difficulty

The bits field holds the target in compact form. The first byte is an exponent and the next three are the start of the number, so `0x1d00ffff` means `0xffff` followed by zeros, the target at difficulty (How much harder a target is to meet than the easiest one) 1. Difficulty measures how much harder a target is than that one, so a lower target means a higher difficulty. The network adjusts the target so blocks keep arriving about 10 minutes apart on average.

Miners hash the header and not the transactions. The transactions are covered through the Merkle root, so searching for a valid hash costs the same for a block with one transaction as for a block with a million.

## Merkle trees

A Merkle tree (A tree of hashes in which pairs are hashed together until one hash is left) lets a block header stand for every transaction in the block.

### The tree and the root

Each transaction ID in a block is a leaf of a Merkle tree, and the leaves are hashed in pairs, level by level, until one hash is left, the Merkle root. A block with one transaction has that transaction's ID as its root, which is why the first block's root is the ID of its only transaction.

### A Merkle path

A Merkle path is the hashes a verifier needs to get from one transaction to the root. Given the path and the transaction ID, anyone can compute the root and compare it with the one in a block header, without the rest of the transactions. `MerklePath` in `@bsv/sdk` does this.

```javascript merkle.mjs
import { Hash, MerklePath, Utils } from '@bsv/sdk'

const bytes = (hex) => Utils.toArray(hex, 'hex').reverse()
const leaf = (text) => Utils.toHex(Hash.hash256(Utils.toArray(text, 'utf8')).reverse())
const parent = (left, right) => Utils.toHex(Hash.hash256([...bytes(left), ...bytes(right)]).reverse())

const [a, b, c, d] = ['tx a', 'tx b', 'tx c', 'tx d'].map(leaf)

const proof = new MerklePath(100, [
  [{ offset: 0, hash: a, txid: true }, { offset: 1, hash: b }],
  [{ offset: 1, hash: parent(c, d) }]
])

console.log(proof.computeRoot(a))
console.log(parent(parent(a, b), parent(c, d)))
```

```text
ebabf2603108438b09fd9ad221b193f8bd35b78d12bf732d2f0d278ed478ca24
ebabf2603108438b09fd9ad221b193f8bd35b78d12bf732d2f0d278ed478ca24
```

- `bytes`, `leaf` and `parent` are helpers. Hashes are written the way explorers show them, so each helper reverses the bytes before and after hashing.
- `a`, `b`, `c` and `d` are four stand-in transaction IDs, and `100` is an arbitrary block height.
- Each entry of the path has an `offset`, its position in that level of the tree, and `txid: true` marks the transaction the path proves.
- The proof for `a` holds only two hashes, `b` and the hash of `c` and `d`, and it gives the same root as hashing the whole tree. A path that does not contain the transaction ID is rejected.

BEEF (Background Evaluation Extended Format (BRC-62)) packages these paths with the transactions they prove, and [BEEF (BRC-62)](https://bsvblockchain.com/docs/concepts/spv/) covers the format.

## The coinbase transaction and block rewards

Every block pays its miner through its first transaction.

### The coinbase transaction

The first transaction in every block is the coinbase transaction, and the miner who found the block creates it. It has a single input with a previous transaction hash of all zeros and an output index of `0xFFFFFFFF`, because it spends nothing, and its outputs pay the miner.

### The block subsidy

A block pays its miner the block subsidy plus the fees of the transactions it includes. The subsidy started at 50 BSV, which is 5,000,000,000 satoshis (The smallest unit of BitcoinSV (BSV), 100,000,000 satoshis make 1 BSV), and halves every 210,000 blocks, about every four years. It reaches zero after 33 halvings, around the year 2140. A miner can only spend coinbase outputs after 100 more blocks have been added.

## When blocks compete

Two miners can find a valid block at about the same time, so the network briefly has two blocks that build on the same parent. A node builds on the first valid one it saw. When the next block extends one of them, the chain with the most proof of work wins, and miners move to it. A valid block that does not end up in that chain is an orphan block (A valid block that is not part of the chain with the most proof of work), and its transactions go back to the pool of unconfirmed transactions unless the winning chain already holds them.

A transaction with one block on top of it can still be reversed if that block loses, and each further block makes that less likely. [How transactions and fees work](https://bsvblockchain.com/docs/concepts/transactions/) shows how an app sees a transaction move from signed to confirmed.

## Related articles

To learn more about blocks on the BSV blockchain, review these articles:

- [Bitcoin transactions](https://bsvblockchain.com/docs/learn/wiki/bitcoin-transactions/)
- [Cryptography](https://bsvblockchain.com/docs/learn/wiki/cryptography/)
- [How transactions and fees work](https://bsvblockchain.com/docs/concepts/transactions/)
- [BEEF (BRC-62)](https://bsvblockchain.com/docs/concepts/spv/)