1.4.1 • Published 11 months ago

@headerprotocol/contracts v1.4.1

Weekly downloads
-
License
MIT
Repository
github
Last release
11 months ago

HeaderProtocol: On-Chain Block Header Service


Header Protocol is a smart contract system that allows other contracts to request and retrieve specific fields from Ethereum block headers. This is achieved in a secure, efficient, and trustless manner, enabling advanced use cases like on-chain randomness, gas price games, and historical data retrieval.

With Header Protocol, you can request both free tasks (no fees) and paid tasks (with fees to incentivize completion). Executors (off-chain agents) listen for requests, fetch the block header data from the blockchain, and provide it back to the protocol for on-chain validation.


Table of Contents

  1. Features
  2. How It Works
  3. Block Header Indexes
  4. Task Types
  5. Key Functions
  6. Examples
  7. Diagrams

Features

  • Secure Access to Block Headers: Retrieve specific block header fields such as baseFeePerGas, mixHash, timestamp, miner, and more.
  • Free or Paid Tasks: Choose between free tasks (emit events) and paid tasks (store fees for executor rewards).
  • Long-Term Accessibility: Use the commit function to preserve block hashes beyond Ethereum’s 256-block limitation.
  • Error Handling and Refunds: Built-in mechanisms to refund fees for incomplete tasks.
  • Versatile Applications: Ideal for randomness, gas price prediction, analytics, and more.

How It Works

Header Protocol operates in three key phases:

  1. Request Phase:

    • A contract requests specific block header data by calling request(blockNumber, headerIndex).
    • The task is either free or paid, depending on whether msg.value is provided.
  2. Execution Phase:

    • Executors listen for BlockHeaderRequested events.
    • They fetch the block header from the Ethereum blockchain off-chain and call response(...) to provide the data.
  3. Validation Phase:

    • The protocol validates the block header data on-chain using the blockhash function.
    • Upon successful validation:
      • Free tasks trigger the responseBlockHeader callback.
      • Paid tasks transfer the fee reward to the executor and trigger the callback.

Block Header Indexes

IndexField NameTypeDescription
0parentHashbytes32Hash of the parent block.
1sha3Unclesbytes32Hash of the uncles' list.
2mineraddressAddress of the block miner.
3stateRootbytes32State root hash of the block.
4transactionsRootbytes32Root hash of the block's transactions.
5receiptsRootbytes32Root hash of the block's receipts.
_logsBloombytes256Logs bloom filter for the block (not retrievable onchain).
7difficultyuint256Difficulty level of the block.
8numberuint256Block number.
9gasLimituint256Gas limit for the block.
10gasUseduint256Gas used by the block.
11timestampuint256Timestamp of the block.
_extraDatabytesExtra data field of the block (not retrievable onchain).
13mixHashbytes32Mix hash used for proof-of-work.
14nonceuint64Nonce used for mining the block.
15baseFeePerGasuint256Base fee per gas unit for the block (EIP-1559).
16withdrawalsRootbytes32Withdrawals root for beacon chain withdrawals.
17blobGasUseduint256Blob gas used in the block.
18excessBlobGasuint256Excess blob gas in the block.
19parentBeaconBlockRootbytes32Parent beacon block root hash.

Task Types

Free Tasks

Free tasks emit an event and do not store any fee. They rely on altruistic executors.

Requesting a Free Task:

protocol.request(blockNumber, headerIndex); // no msg.value

Paid Tasks

Paid tasks lock Ether as a reward for whoever responds first with the correct header data.

Requesting a Paid Task:

protocol.request{value: 1 ether}(blockNumber, headerIndex);

Key Functions

Request Header Data

function request(uint256 blockNumber, uint256 headerIndex) external payable;

Provide Response

function response(uint256 blockNumber, uint256 headerIndex, bytes calldata blockHeader, address contractAddress) external;

Commit Blockhash

function commit(uint256 blockNumber) external;

Refund Fees

function refund(uint256 blockNumber, uint256 headerIndex) external;

Get Header

function getHeader(uint256 blockNumber, uint256 headerIndex) external view returns (bytes32);

Get Hash

function getHash(uint256 blockNumber) external view returns (bytes32);

Examples

Full Open Example

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {IHeaderProtocol, IHeader} from "@headerprotocol/contracts/v1/interfaces/IHeaderProtocol.sol";

contract MockHeader is IHeader {
    IHeaderProtocol private protocol;

    // blockNumber => headerIndex => headerData
    mapping(uint256 => mapping(uint256 => bytes32)) public headers;

    constructor(address _protocol) {
        protocol = IHeaderProtocol(_protocol);
    }

    function mockRequest(
        uint256 blockNumber,
        uint256 headerIndex
    ) external payable {
        protocol.request(blockNumber, headerIndex);
    }

    // required implementation of IHeader
    function responseBlockHeader(
        uint256 blockNumber,
        uint256 headerIndex,
        bytes32 headerData
    ) external {
        require(msg.sender == address(protocol), "Only Header Protocol");
        headers[blockNumber][headerIndex] = headerData; // 30,000 gas limit, only save
    }
}

Full Reward Example

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {IHeaderProtocol, IHeader} from "@headerprotocol/contracts/v1/interfaces/IHeaderProtocol.sol";

contract MockHeader is IHeader {
    IHeaderProtocol private protocol;

    // blockNumber => headerIndex => headerData
    mapping(uint256 => mapping(uint256 => bytes32)) public headers;

    constructor(address _protocol) {
        protocol = IHeaderProtocol(_protocol);
    }

    function mockRequest(
        uint256 blockNumber,
        uint256 headerIndex
    ) external payable {
        protocol.request{value: msg.value}(blockNumber, headerIndex);
    }

    function mockCommit(uint256 blockNumber) external {
        protocol.commit(blockNumber);
    }

    function mockRefund(uint256 blockNumber, uint256 headerIndex) external {
        protocol.refund(blockNumber, headerIndex);
    }

    // required implementation of IHeader
    function responseBlockHeader(
        uint256 blockNumber,
        uint256 headerIndex,
        bytes32 headerData
    ) external {
        require(msg.sender == address(protocol), "Only Header Protocol");
        headers[blockNumber][headerIndex] = headerData; // 30,000 gas limit, only save
    }

    receive() external payable {} // accept refunds
}

Diagrams

sequenceDiagram
    participant User as Consumer Contract
    participant Protocol as Header Protocol
    participant Executor as Off-Chain Executor

    User->>Protocol: request(blockNumber, headerIndex)
    Protocol->>Executor: Emit BlockHeaderRequested Event
    Executor->>Executor: Fetch and Verify Block Header (Off-Chain)
    Executor->>Protocol: response(blockNumber, headerIndex, blockHeader, contractAddress)
    Protocol->>User: Trigger responseBlockHeader(blockNumber, headerIndex, headerData)