Blockhash.sol 2.2 KB

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