Blockhash.sol 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. /// @dev Address of the EIP-2935 history storage contract.
  17. address internal constant HISTORY_STORAGE_ADDRESS = 0x0000F90827F1C53a10cb7A02335B175320002935;
  18. /**
  19. * @dev Retrieves the block hash for any historical block within the supported range.
  20. *
  21. * NOTE: The function gracefully handles future blocks and blocks beyond the history window
  22. * by returning zero, consistent with the EVM's native `BLOCKHASH` behavior.
  23. */
  24. function blockHash(uint256 blockNumber) internal view returns (bytes32) {
  25. uint256 current = block.number;
  26. uint256 distance;
  27. unchecked {
  28. // Can only wrap around to `current + 1` given `block.number - (2**256 - 1) = block.number + 1`
  29. distance = current - blockNumber;
  30. }
  31. return distance < 257 ? blockhash(blockNumber) : _historyStorageCall(blockNumber);
  32. }
  33. /// @dev Internal function to query the EIP-2935 history storage contract.
  34. function _historyStorageCall(uint256 blockNumber) private view returns (bytes32 hash) {
  35. assembly ("memory-safe") {
  36. // Store the blockNumber in scratch space
  37. mstore(0x00, blockNumber)
  38. mstore(0x20, 0)
  39. // call history storage address
  40. pop(staticcall(gas(), HISTORY_STORAGE_ADDRESS, 0x00, 0x20, 0x20, 0x20))
  41. // load result
  42. hash := mload(0x20)
  43. }
  44. }
  45. }