Blockhash.sol 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.20;
  3. /**
  4. * @dev Library for accessing historical block hashes beyond the standard 256 block limit.
  5. * Uses EIP-2935's history storage contract which maintains a ring buffer of the last
  6. * 8191 block hashes in state.
  7. *
  8. * For blocks within the last 256 blocks, it uses the native `BLOCKHASH` opcode.
  9. * For blocks between 257 and 8191 blocks ago, it queries the EIP-2935 history storage.
  10. * For blocks older than 8191 or future blocks, it returns zero, matching the `BLOCKHASH` behavior.
  11. *
  12. * NOTE: After EIP-2935 activation, it takes 8191 blocks to completely fill the history.
  13. * Before that, only block hashes since the fork block will be available.
  14. */
  15. library Blockhash {
  16. address internal constant HISTORY_STORAGE_ADDRESS = 0x0000F90827F1C53a10cb7A02335B175320002935;
  17. /**
  18. * @dev Retrieves the block hash for any historical block within the supported range.
  19. *
  20. * NOTE: The function gracefully handles future blocks and blocks beyond the history window
  21. * by returning zero, consistent with the EVM's native `BLOCKHASH` behavior.
  22. */
  23. function blockHash(uint256 blockNumber) internal view returns (bytes32) {
  24. uint256 current = block.number;
  25. uint256 distance;
  26. unchecked {
  27. // Can only wrap around to `current + 1` given `block.number - (2**256 - 1) = block.number + 1`
  28. distance = current - blockNumber;
  29. }
  30. return distance > 256 && distance <= 8191 ? _historyStorageCall(blockNumber) : blockhash(blockNumber);
  31. }
  32. /// @dev Internal function to query the EIP-2935 history storage contract.
  33. function _historyStorageCall(uint256 blockNumber) private view returns (bytes32 hash) {
  34. assembly ("memory-safe") {
  35. mstore(0, blockNumber) // Store the blockNumber in scratch space
  36. // In case the history storage address is not deployed, the call will succeed
  37. // without returndata, so the hash will be 0 just as querying `blockhash` directly.
  38. if and(gt(returndatasize(), 0), staticcall(gas(), HISTORY_STORAGE_ADDRESS, 0, 0x20, 0, 0x20)) {
  39. hash := mload(0)
  40. }
  41. }
  42. }
  43. }