Skip to main content
This page is a placeholder. All examples on this page are currently AI-generated and are not correct. This documentation will be completed in the future with accurate, tested examples.

Overview

Opcode: 0x40 Introduced: Frontier (EVM genesis) BLOCKHASH retrieves the keccak256 hash of a specified block number. It only returns hashes for the 256 most recent complete blocks. For blocks outside this range or future blocks, it returns zero. This instruction enables contracts to reference historical blockchain state for verification, commitment schemes, and deterministic randomness.

Specification

Stack Input:
Stack Output:
Gas Cost: 20 (GasExtStep) Behavior:
  • Returns block hash if current_block - 256 < block_number < current_block
  • Returns 0x0000...0000 if block is too old (> 256 blocks ago)
  • Returns 0x0000...0000 if block_number >= current_block
  • Returns 0x0000...0000 if block hash not available in context

Behavior

Valid Range Window

BLOCKHASH maintains a sliding 256-block window:

Hash Availability

The EVM maintains an internal block_hashes array indexed with negative offsets:

Examples

Recent Block Hash

Block Too Old

Current or Future Block

Full 256-Block Range

Gas Cost

Cost: 20 gas (GasExtStep) BLOCKHASH is more expensive than simple context queries (2 gas) because it requires:
  • Range validation
  • Array index calculation
  • Hash retrieval from storage
  • 32-byte hash conversion to u256
Comparison:
  • BLOCKHASH: 20 gas
  • NUMBER, TIMESTAMP, GASLIMIT: 2 gas
  • SLOAD (cold): 2100 gas
  • BALANCE (cold): 2600 gas
Despite the 20 gas cost, BLOCKHASH is efficient compared to storage operations.

Common Usage

Commit-Reveal Schemes

Block Hash Verification

Historical Data Anchoring

Simple Randomness (Not Secure)

Security Considerations

Not Suitable for High-Stakes Randomness

Block hashes are predictable by miners and can be manipulated:
Attack Vector:
  • Miner sees they won’t win
  • Miner withholds block to try different nonce
  • Profitability: If jackpot > block reward, rational to try
Mitigation: Use Chainlink VRF or commit-reveal with multiple participants.

256-Block Expiration

Commitments using BLOCKHASH expire after 256 blocks:

Zero Hash Ambiguity

Zero hash can mean multiple things:

Current Block Unavailability

The current block hash is never available within the block:

Implementation

Edge Cases

Exactly 256 Blocks Ago

257 Blocks Ago

Genesis Block Query

Empty Block Hashes Array

Benchmarks

Performance characteristics:
  • Array index calculation: O(1)
  • Hash retrieval: O(1)
  • Conversion to u256: O(32) - iterate 32 bytes
Gas efficiency:
  • 20 gas per query
  • ~50,000 queries per million gas
  • More efficient than equivalent storage reads (2100 gas cold)

References