Glossary

Midstate Hash

A midstate hash is a partial SHA-256 computation cached to speed up Bitcoin mining by avoiding redundant hashing of unchanged block header bytes.

Key Takeaways

  • A midstate hash is the saved internal state of SHA-256 after processing the first 64 bytes of a Bitcoin block header. Because those bytes stay constant during nonce iteration, the computation only needs to run once per work unit.
  • Caching the midstate roughly halves the hashing work per attempt: miners only need to run the second compression round (covering the final 16 bytes plus padding) for each nonce value they try.
  • Rolling the extranonce or the version field changes bytes in the first chunk, which invalidates the cached midstate and forces a full recomputation. Modern ASICs manage this tradeoff through version rolling and efficient midstate precomputation on the control board.

What Is a Midstate Hash?

A midstate hash is a partial result of the SHA-256 hash function, saved after processing one complete 64-byte (512-bit) input block. In Bitcoin mining, the 80-byte block header naturally splits across two SHA-256 compression rounds: the first 64 bytes form one complete block, and the remaining 16 bytes (plus 48 bytes of padding) form the second. Because the first 64 bytes rarely change while a miner sweeps through nonce values, their hash state can be computed once and reused for billions of subsequent attempts.

This optimization is fundamental to how Bitcoin mining hardware operates. Rather than feeding the full 80-byte header to each hashing core, a mining control board computes the midstate once and distributes it alongside the 16-byte tail to individual ASIC chips. Each chip then only performs the second compression round and the final double-hash, saving roughly half the work per hash attempt.

How It Works

Understanding midstate hashing requires knowing how SHA-256 processes data internally.

SHA-256 Internals

SHA-256 is an iterated hash function built on a compression function that operates on 64-byte (512-bit) blocks. It maintains an internal state of eight 32-bit words (256 bits total), initialized to fixed values derived from the fractional parts of the square roots of the first eight primes:

Initial Hash Values (SHA-256 IV):
H0 = 0x6a09e667    H4 = 0x510e527f
H1 = 0xbb67ae85    H5 = 0x9b05688c
H2 = 0x3c6ef372    H6 = 0x1f83d9ab
H3 = 0xa54ff53a    H7 = 0x5be0cd19

For each 64-byte block of input, the compression function runs 64 rounds that mix the message data into the state using bitwise operations, modular addition, and 64 round constants. The output of one compression becomes the input state for the next block. When all blocks are processed, the final state is the hash digest.

The Block Header Split

A Bitcoin block header is exactly 80 bytes, containing six fields:

Block Header Layout (80 bytes total):

First chunk (64 bytes) — cached as midstate:
┌─────────────────────────────────────────┐
│ Version              │  4 bytes         │
│ Previous Block Hash  │ 32 bytes         │
│ Merkle Root (first)  │ 28 bytes         │
├─────────────────────────────────────────┤
│ Total                │ 64 bytes         │
└─────────────────────────────────────────┘

Second chunk (16 bytes + 48 bytes padding):
┌─────────────────────────────────────────┐
│ Merkle Root (last)   │  4 bytes         │
│ Timestamp (nTime)    │  4 bytes         │
│ Difficulty (nBits)   │  4 bytes         │
│ Nonce                │  4 bytes         │
│ SHA-256 Padding      │ 48 bytes         │
├─────────────────────────────────────────┤
│ Total                │ 64 bytes         │
└─────────────────────────────────────────┘

During a nonce sweep, the miner increments only the 4-byte nonce field. Since this field resides entirely in the second chunk, the first 64 bytes remain unchanged. The midstate captures the SHA-256 state after compressing that first chunk, allowing the miner to skip directly to the second compression round for each nonce attempt.

Mining with Midstates

The mining process using midstate optimization follows these steps:

  1. The control board receives a block template from the pool or node
  2. It constructs the 80-byte header and runs SHA-256 compression on the first 64 bytes, producing the 32-byte midstate (eight 32-bit words)
  3. It sends each ASIC chip the midstate plus the 16-byte tail (last 4 bytes of the Merkle root, timestamp, difficulty bits, and starting nonce)
  4. Each chip iterates through nonce values, running only the second compression round per attempt
  5. When the 4-byte nonce space (approximately 4.29 billion values) is exhausted, the control board generates a new work unit

Double SHA-256

Bitcoin's proof of work uses double SHA-256: the header is hashed, and then the resulting 32-byte digest is hashed again. The midstate optimization applies to the first SHA-256 pass. The second pass always processes exactly 32 bytes (plus padding to fill one 64-byte block), so it runs the compression function once regardless.

Why It Matters

ASIC Design Efficiency

In modern ASIC miners, the midstate optimization directly influences chip architecture. Instead of building hashing cores that process a full 80-byte header, manufacturers design cores that accept a 32-byte midstate and a 16-byte tail. This reduces the silicon area per core, lowers power consumption, and increases the number of hashing cores that fit on a single die.

The work packet sent to chips in miners like the Bitmain Antminer series consists of the 32-byte midstate plus the tail fields: not the full 80-byte header. This compact format reduces data transfer between the control board and hashing chips, which matters when a single board coordinates thousands of cores.

Stratum Protocol Integration

The original Stratum mining protocol sent midstates directly from pool servers to miners, reducing bandwidth and computation on the miner side. Stratum V2 continues to leverage this optimization while adding encryption and allowing miners to construct their own block templates. In both cases, the midstate remains the foundation of how work is distributed to hashing hardware.

Energy Savings at Scale

At the scale of industrial mining operations running trillions of hashes per second, skipping one of two compression rounds per attempt translates to meaningful energy savings. Since the hashrate of the Bitcoin network exceeds hundreds of exahashes per second, the aggregate energy saved by midstate caching across all mining hardware is substantial.

Use Cases

Standard Nonce Grinding

The most common use of midstate hashing is straightforward nonce iteration. A miner computes one midstate and grinds through up to 2^32 (approximately 4.29 billion) nonce values. At modern ASIC speeds, this nonce space is exhausted in well under a second: a 200 TH/s miner burns through the entire 4-byte nonce range in roughly 21 milliseconds.

Version Rolling

Because the nonce space is so small relative to modern hashrates, miners need additional entropy. One approach is version rolling, where unused bits in the 4-byte version field are toggled to create new first chunks. BIP 320 designates 16 bits (bits 13 through 28) of the version field for miner use, expanding the search space by a factor of 65,536. Each version variant requires a new midstate computation, but the control board can batch-precompute these midstates and distribute them across chips.

This technique is closely related to AsicBoost, which exploits properties of the SHA-256 compression function to reuse partial computations across version variants. Overt AsicBoost (visible in block version fields) is widely used by modern mining pools.

Mining Pool Work Distribution

Mining pools assign each miner a unique range of the extranonce to prevent duplicate work. The pool server computes the coinbase transaction, builds the Merkle tree, and can optionally precompute midstates for miners with limited computational resources. This is especially relevant for older or lower-powered hardware.

Extranonce Rolling and Midstate Invalidation

When a miner exhausts both the nonce and version-rolled search space, the next source of entropy is the extranonce: extra bytes placed in the coinbase transaction's scriptSig field. Changing the extranonce alters the coinbase transaction hash, which propagates up through the Merkle tree and changes the Merkle root in the block header.

Since the first 28 bytes of the Merkle root sit in the first 64-byte chunk, any change to the extranonce invalidates the cached midstate. The miner must then:

  1. Recompute the affected Merkle tree branches (only the left-edge path from the coinbase to the root changes)
  2. Construct a new 80-byte header with the updated Merkle root
  3. Run the SHA-256 compression function on the new first 64 bytes to produce a fresh midstate
  4. Distribute the new midstate and tail to ASIC chips

This recomputation is relatively cheap compared to the trillions of nonce-grinding operations it enables. A single midstate computation takes microseconds on a control board CPU, while the ASIC chips it feeds produce terahashes per second.

Risks and Considerations

Covert Optimization Concerns

The midstate optimization itself is benign, but it enabled a controversy around covert AsicBoost. This technique manipulated the Merkle root to reuse midstate computations across multiple block candidates without changing the version field. Because the optimization was invisible on-chain, it gave certain manufacturers a hidden advantage. The activation of SegWit in August 2017 effectively made covert AsicBoost impractical by changing how the witness commitment interacts with the coinbase transaction.

Nonce Space Exhaustion

The 4-byte nonce provides only 2^32 values, which modern ASICs exhaust in milliseconds. Without additional entropy sources (version rolling, extranonce, timestamp adjustments), miners would need new midstates at an impractical rate. The coordination between midstate generation and nonce-space management is a critical design consideration for mining firmware and the Stratum protocol.

Implementation Correctness

The midstate must be computed with the correct SHA-256 initialization vector and compression function. Using wrong initial values produces midstates that silently generate invalid hashes. Most standard SHA-256 libraries do not expose internal state, which is why mining software often implements the compression function directly or uses specialized libraries.

// Pseudocode: midstate computation for Bitcoin mining
fn compute_midstate(header: &[u8; 80]) -> [u32; 8] {
    // Start with standard SHA-256 initialization vector
    let mut state: [u32; 8] = SHA256_IV;

    // Run compression on first 64-byte chunk only
    sha256_compress(&mut state, &header[0..64]);

    // Return the midstate (internal state after first block)
    state
}

// For each nonce attempt, resume from midstate:
fn hash_with_midstate(midstate: &[u32; 8], tail: &[u8; 16]) -> [u8; 32] {
    let mut state = *midstate;

    // Pad tail to 64 bytes per SHA-256 spec
    let padded = sha256_pad(tail, total_len: 80);
    sha256_compress(&mut state, &padded);

    // First SHA-256 complete; now double-hash
    let first_hash = state_to_bytes(&state);
    sha256(first_hash)
}

Not a Security Weakness

Midstate caching does not weaken the cryptographic security of SHA-256 or Bitcoin's proof of work. It is a straightforward application of the hash function's iterative structure. The same final hash is produced whether the midstate is cached or the full header is processed from scratch. No shortcuts exist for finding valid hashes: the optimization only avoids redundant computation on unchanged input bytes.

For a deeper look at how mining hardware leverages these optimizations, see the research article on ASIC efficiency and joules per terahash and the analysis of Bitcoin mining economics.

This glossary entry is for informational purposes only and does not constitute financial or investment advice. Always do your own research before using any protocol or technology.