Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion builtin/builtin.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@ var (
Staker = &stakerContract{mustLoadContract("Staker")}
Measure = mustLoadContract("Measure")

// History is the EIP-2935 historical-block-hash facade. Its address is
// fixed by the EIP (not derived from the contract name) so dApps that
// already speak the EIP-2935 calling convention work unchanged on Thor.
History = &historyContract{mustLoadContractAt(
"History",
thor.MustParseAddress("0x0000F90827F1C53a10cb7A02335B175320002935"),
)}

// return gas map maintains the builtin contracts that can be made native call cheaper
// only the 0.4.24 compiled contracts are allowed to return gas, as the newer compiler
// versions have dynamic cost and pattern that is not predictable, any further added new
Expand All @@ -60,7 +68,8 @@ type (
V2 *contract
V3 *contract
}
stakerContract struct{ *contract }
stakerContract struct{ *contract }
historyContract struct{ *contract }
)

func (p *paramsContract) Native(state *state.State) *params.Params {
Expand Down
9 changes: 8 additions & 1 deletion builtin/contract.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ type contract struct {
}

func mustLoadContract(name string) *contract {
return mustLoadContractAt(name, thor.BytesToAddress([]byte(name)))
}

// mustLoadContractAt loads a builtin contract whose deployed address is fixed
// (i.e. not derived from its name). Used for contracts that follow an
// externally specified address such as EIP-2935 HISTORY_STORAGE.
func mustLoadContractAt(name string, address thor.Address) *contract {
asset := "compiled/" + name + ".abi"
data := gen.MustABI(asset)
abi, err := abi.New(data)
Expand All @@ -29,7 +36,7 @@ func mustLoadContract(name string) *contract {

return &contract{
name,
thor.BytesToAddress([]byte(name)),
address,
abi,
}
}
Expand Down
1 change: 1 addition & 0 deletions builtin/gen/compiled/History.abi
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[{"stateMutability":"nonpayable","type":"fallback"}]
1 change: 1 addition & 0 deletions builtin/gen/compiled/History.bin-runtime
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
608060405234801561001057600080fd5b5060003660606020821461002357600080fd5b6000610031838501856100ce565b9050438110158061004c5750611fff61004a82436100e7565b115b1561005657600080fd5b604051633549f8d160e21b81526004810182905260009068457874656e73696f6e9063d527e34490602401602060405180830381865afa15801561009e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100c2919061010e565b90508060005260206000f35b6000602082840312156100e057600080fd5b5035919050565b8181038181111561010857634e487b7160e01b600052601160045260246000fd5b92915050565b60006020828403121561012057600080fd5b505191905056fea2646970667358221220474b422970f8e180e121359790bb9cc4ef3fa87a6525ca9cc2709029bce634d564736f6c63430008140033
2 changes: 1 addition & 1 deletion builtin/gen/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ package gen

//go:generate rm -rf ./compiled/
//go:generate docker run --rm -v ./:/solidity ghcr.io/argotorg/solc:0.4.24 --optimize-runs 200 --overwrite --bin-runtime --abi -o /solidity/compiled authority.sol energy.sol executor.sol extension.sol extension-v2.sol extension-v3.sol measure.sol params.sol prototype.sol
//go:generate docker run --rm -v ./:/sources ghcr.io/argotorg/solc:0.8.20 --evm-version paris --optimize --optimize-runs 200 -o /sources/compiled --abi --bin-runtime /sources/staker.sol
//go:generate docker run --rm -v ./:/sources ghcr.io/argotorg/solc:0.8.20 --evm-version paris --optimize --optimize-runs 200 -o /sources/compiled --abi --bin-runtime /sources/staker.sol /sources/history.sol
// cleanup - remove all files starting with _
//go:generate docker run --rm -v ./compiled:/compiled alpine sh -c "find /compiled -type f \\( -name '_*' \\) -delete"
37 changes: 37 additions & 0 deletions builtin/gen/history.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// SPDX-License-Identifier: LGPL-3.0
Comment thread
moglu2017 marked this conversation as resolved.
Outdated
pragma solidity 0.8.20;

/// @title History serves historical block hashes via the EIP-2935 calling convention.
///
/// Calldata is exactly 32 bytes — a uint256 block number with no function
/// selector. Dispatch therefore goes through the fallback function. All
/// invalid inputs revert with empty returndata (matching the EIP-2935
/// reference bytecode's `revert(0, 0)`) so dApps written for ETH mainnet
/// observe identical failure semantics on Thor.
contract History {
uint256 constant SERVE_WINDOW = 8191;
Comment thread
moglu2017 marked this conversation as resolved.
Outdated

// builtin.Extension.Address == thor.BytesToAddress([]byte("Extension"))
address constant EXTENSION = 0x0000000000000000000000457874656E73696F6e;

fallback(bytes calldata input) external returns (bytes memory) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this return bytes32 ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, at the end of function , it will return bytes32 data.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ooc, why do we need the assembly ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's equivalent this:
return abi.encodePacked(_Extension(EXTENSION).blockID(num));
Assembly is used because it is more concise.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be a view ?

Suggested change
fallback(bytes calldata input) external returns (bytes memory) {
fallback(bytes calldata input) external view returns (bytes memory) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It can't set 'view', the fallback method only could be set 'payable' or 'non-payable', default is 'non-payable'.

if (input.length != 32) revert();
uint256 num = abi.decode(input, (uint256));
if (num >= block.number || block.number - num > SERVE_WINDOW) revert();

bytes32 result = _Extension(EXTENSION).blockID(num);

assembly {
mstore(0, result)
return(0, 32)
}
}
}

/// @dev Minimal interface against the 0.4.24-compiled Extension builtin
/// (see builtin/gen/extension.sol). Underscore prefix follows the repo
/// convention (see _Token, _proto_helper) — the `_*` cleanup step in
/// gen.go drops the unused artifact from compiled/.
interface _Extension {
function blockID(uint256 num) external view returns (bytes32);
}
143 changes: 143 additions & 0 deletions builtin/history_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
// Copyright (c) 2025 The VeChainThor developers
Comment thread
moglu2017 marked this conversation as resolved.
Outdated

// Distributed under the GNU Lesser General Public License v3.0 software license, see the accompanying
// file LICENSE or <https://www.gnu.org/licenses/lgpl-3.0.html>

package builtin_test

import (
"encoding/binary"
"testing"

"github.com/stretchr/testify/require"

"github.com/vechain/thor/v2/builtin"
"github.com/vechain/thor/v2/genesis"
"github.com/vechain/thor/v2/test/testchain"
"github.com/vechain/thor/v2/tx"
)

// callHistory invokes the EIP-2935 facade with raw 32-byte calldata
// (the EIP-2935 convention has no function selector).
func callHistory(chain *testchain.Chain, num uint32) ([]byte, error) {
out, _, err := callHistoryWithGas(chain, num)
return out, err
}

func callHistoryWithGas(chain *testchain.Chain, num uint32) ([]byte, uint64, error) {
Comment thread
moglu2017 marked this conversation as resolved.
Outdated
var data [32]byte
binary.BigEndian.PutUint32(data[28:], num)
return callHistoryRawWithGas(chain, data[:])
}

// callHistoryRaw invokes the History contract with the given raw calldata
// (no selector mangling). Used for testing invalid-length inputs.
func callHistoryRaw(chain *testchain.Chain, data []byte) ([]byte, error) {
out, _, err := callHistoryRawWithGas(chain, data)
return out, err
}

func callHistoryRawWithGas(chain *testchain.Chain, data []byte) ([]byte, uint64, error) {
addr := builtin.History.Address
clause := tx.NewClause(&addr).WithData(data)
trx := new(tx.Builder).
ChainTag(chain.Repo().ChainTag()).
Expiration(50).
Gas(200000).
Clause(clause).
Build()
return chain.ClauseCall(genesis.DevAccounts()[0], trx, 0)
}

func TestHistory_ForkActivation(t *testing.T) {
chain := newChain(t, nil) // SoloFork: INTERSTELLAR = 1
require.NoError(t, chain.MintBlock())

st := chain.State()
code, err := st.GetCode(builtin.History.Address)
require.NoError(t, err)
require.Equal(t, builtin.History.RuntimeBytecodes(), code)
}

func TestHistory_ValidRead(t *testing.T) {
chain := newChain(t, nil)
require.NoError(t, chain.MintBlock())
require.NoError(t, chain.MintBlock())
require.NoError(t, chain.MintBlock())

want, err := chain.Repo().NewBestChain().GetBlockID(1)
require.NoError(t, err)

got, err := callHistory(chain, 1)
require.NoError(t, err)
require.Equal(t, want.Bytes(), got)
}

// TestHistory_WindowBoundary exercises the edges of the [best-8191, best-1]
// valid range. SERVE_WINDOW is hard-coded to 8191 in history.sol, so the
// chain must be deep enough to expose both sides of the boundary.
func TestHistory_WindowBoundary(t *testing.T) {
if testing.Short() {
t.Skip("requires minting >8191 blocks; skipped in -short mode")
}
Comment thread
moglu2017 marked this conversation as resolved.
Outdated
chain := newChain(t, nil)
for range 8193 {
require.NoError(t, chain.MintBlock())
}

best := chain.Repo().BestBlockSummary().Header.Number()

// Passing num == block.number must revert per EIP-2935 (execution reverted).
got, err := callHistory(chain, best)
require.ErrorContains(t, err, "execution reverted")
require.Empty(t, got, "EIP-2935 revert must carry no return data")

// distance == 1: the most recent block, the newest in-window value.
newest := best - 1
want, err := chain.Repo().NewBestChain().GetBlockID(newest)
require.NoError(t, err)
got, err = callHistory(chain, newest)
require.NoError(t, err)
require.Equal(t, want.Bytes(), got)

// distance == 8191: the oldest in-window value (block.number - num == SERVE_WINDOW).
oldestIn := best - 8191
want, err = chain.Repo().NewBestChain().GetBlockID(oldestIn)
require.NoError(t, err)
got, err = callHistory(chain, oldestIn)
require.NoError(t, err)
require.Equal(t, want.Bytes(), got)

// distance == 8192: one step past the window — must revert with empty data.
out, err := callHistory(chain, oldestIn-1)
require.ErrorContains(t, err, "execution reverted")
require.Empty(t, out, "EIP-2935 revert must carry no return data")
}

func TestHistory_FutureBlockReverts(t *testing.T) {
chain := newChain(t, nil)
require.NoError(t, chain.MintBlock())
require.NoError(t, chain.MintBlock())

best := chain.Repo().BestBlockSummary().Header.Number()
out, err := callHistory(chain, best+9999)
require.ErrorContains(t, err, "execution reverted")
require.Empty(t, out, "EIP-2935 revert must carry no return data")
}

func TestHistory_InvalidCalldataLength(t *testing.T) {
chain := newChain(t, nil)
require.NoError(t, chain.MintBlock())

out, err := callHistoryRaw(chain, make([]byte, 31))
require.ErrorContains(t, err, "execution reverted")
require.Empty(t, out, "EIP-2935 revert must carry no return data")

out, err = callHistoryRaw(chain, make([]byte, 33))
require.ErrorContains(t, err, "execution reverted")
require.Empty(t, out, "EIP-2935 revert must carry no return data")

out, err = callHistoryRaw(chain, nil)
require.ErrorContains(t, err, "execution reverted")
require.Empty(t, out, "EIP-2935 revert must carry no return data")
}
7 changes: 7 additions & 0 deletions runtime/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,13 @@ func New(
}
}

// EIP-2935 HISTORY_STORAGE facade. The contract reads historical block
if forkConfig.INTERSTELLAR == ctx.Number {
if err := state.SetCode(builtin.History.Address, builtin.History.RuntimeBytecodes()); err != nil {
panic(err)
}
}

rt := Runtime{
chain: chain,
state: state,
Expand Down
Loading