Skip to content

Commit 025faa3

Browse files
authored
Wire historical state with RPC endpoints (#4550)
* This PR wires up the new historical state with the related RPC endpoints. Before they only worked with the latest block, now the block with an arbitrary height (as long as its within the retention window) * eth_getBalance * eth_getCode * eth_getStorageAt * eth_getTransactionCount
1 parent 3608f90 commit 025faa3

12 files changed

Lines changed: 542 additions & 102 deletions

File tree

‎giga/evmonly/rpc/server.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,13 +49,15 @@ type Backend interface {
4949
BlockByHash(context.Context, *coretypes.RequestBlockByHash) (*coretypes.ResultBlock, error)
5050
BroadcastTx(context.Context, *coretypes.RequestBroadcastTx) (*coretypes.ResultBroadcastTx, error)
5151
EvmBalance(common.Address) uint256.Int
52+
EvmBalanceAt(address common.Address, height int64) (uint256.Int, error)
5253
EvmBaseFee() (*big.Int, error)
5354
EvmBlockNumber() uint64
5455
ExecutedBlocks() (utils.AtomicRecv[atypes.ExecutedBlocks], error)
5556
EvmCall(context.Context, *core.Message) (*core.ExecutionResult, error)
5657
EvmChainConfig() (*params.ChainConfig, error)
5758
EvmChainID() uint64
5859
EvmCode(common.Address) ([]byte, error)
60+
EvmCodeAt(address common.Address, height int64) ([]byte, error)
5961
// EvmEstimateGas returns the lowest gas limit that lets msg succeed, and
6062
// any revert data if it still fails at gasCap.
6163
EvmEstimateGas(ctx context.Context, msg *core.Message, gasCap uint64) (uint64, []byte, error)
@@ -66,7 +68,9 @@ type Backend interface {
6668
EvmProxy(common.Address) utils.Option[*ethrpc.Client]
6769
EvmProxyEnabled() bool
6870
EvmStorage(common.Address, common.Hash) (common.Hash, error)
71+
EvmStorageAt(address common.Address, key common.Hash, height int64) (common.Hash, error)
6972
EvmTransactionCount(common.Address) uint64
73+
EvmTransactionCountAt(address common.Address, height int64) (uint64, error)
7074
}
7175

7276
// Server serves the EVM-only JSON-RPC API over HTTP and over WebSocket.

‎giga/evmonly/rpc/setup_test.go‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,11 @@ type testBackend struct {
3838
storage func(common.Address, common.Hash) (common.Hash, error)
3939
executedBlocks func() (utils.AtomicRecv[atypes.ExecutedBlocks], error)
4040
transactionCount func(common.Address) uint64
41+
42+
balanceAt func(common.Address, int64) (uint256.Int, error)
43+
codeAt func(common.Address, int64) ([]byte, error)
44+
storageAt func(common.Address, common.Hash, int64) (common.Hash, error)
45+
transactionCountAt func(common.Address, int64) (uint64, error)
4146
}
4247

4348
func (b *testBackend) ExecutedBlocks() (utils.AtomicRecv[atypes.ExecutedBlocks], error) {
@@ -60,6 +65,22 @@ func (b *testBackend) EvmBalance(address common.Address) uint256.Int {
6065
return b.balance(address)
6166
}
6267

68+
func (b *testBackend) EvmBalanceAt(address common.Address, height int64) (uint256.Int, error) {
69+
return b.balanceAt(address, height)
70+
}
71+
72+
func (b *testBackend) EvmCodeAt(address common.Address, height int64) ([]byte, error) {
73+
return b.codeAt(address, height)
74+
}
75+
76+
func (b *testBackend) EvmStorageAt(address common.Address, key common.Hash, height int64) (common.Hash, error) {
77+
return b.storageAt(address, key, height)
78+
}
79+
80+
func (b *testBackend) EvmTransactionCountAt(address common.Address, height int64) (uint64, error) {
81+
return b.transactionCountAt(address, height)
82+
}
83+
6384
func (b *testBackend) EvmBaseFee() (*big.Int, error) {
6485
return b.baseFee()
6586
}

‎giga/evmonly/rpc/state.go‎

Lines changed: 62 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,14 @@ import (
1010
"github.com/ethereum/go-ethereum/common"
1111
"github.com/ethereum/go-ethereum/common/hexutil"
1212
ethrpc "github.com/ethereum/go-ethereum/rpc"
13+
"github.com/holiman/uint256"
1314
)
1415

1516
var (
1617
errHistoricalStateUnsupported = errors.New("historical state is not supported by EVM-only RPC")
18+
errBlockHashUnsupported = errors.New("state queries by block hash are not supported by EVM-only RPC")
19+
errBlockAboveHead = errors.New("block is above the latest block")
20+
errBlockTagUnsupported = errors.New("block tag is not supported by EVM-only RPC")
1721
errStorageKeyInvalid = errors.New("hex string invalid")
1822
errStorageKeyTooLong = errors.New("hex string too long, want at most 32 bytes")
1923
)
@@ -22,39 +26,81 @@ type stateAPI struct {
2226
backend Backend
2327
}
2428

25-
// GetBalance returns the address balance from the current committed EVM state.
29+
// GetBalance returns the address balance in the committed EVM state after block.
2630
func (api *stateAPI) GetBalance(_ context.Context, address common.Address, block ethrpc.BlockNumberOrHash) (*hexutil.Big, error) {
27-
if err := requireCurrentState(block); err != nil {
31+
height, latest, err := stateHeight(api.backend, block)
32+
if err != nil {
33+
return nil, err
34+
}
35+
var balance uint256.Int
36+
if latest {
37+
balance = api.backend.EvmBalance(address)
38+
} else if balance, err = api.backend.EvmBalanceAt(address, height); err != nil {
2839
return nil, err
2940
}
30-
balance := api.backend.EvmBalance(address)
3141
return (*hexutil.Big)(balance.ToBig()), nil
3242
}
3343

34-
// GetCode returns the contract code at address from the current committed EVM
35-
// state. An account without code yields empty bytes, encoded as "0x".
44+
// GetCode returns the contract code at address in the committed EVM state after
45+
// block. An account without code yields empty bytes, encoded as "0x".
3646
func (api *stateAPI) GetCode(_ context.Context, address common.Address, block ethrpc.BlockNumberOrHash) (hexutil.Bytes, error) {
37-
if err := requireCurrentState(block); err != nil {
38-
return nil, err
39-
}
40-
code, err := api.backend.EvmCode(address)
47+
height, latest, err := stateHeight(api.backend, block)
4148
if err != nil {
4249
return nil, err
4350
}
44-
return code, nil
51+
if latest {
52+
return api.backend.EvmCode(address)
53+
}
54+
return api.backend.EvmCodeAt(address, height)
4555
}
4656

47-
// GetStorageAt returns the 32-byte value at hexKey in address's storage from
48-
// the current committed EVM state. An unset slot yields 32 zero bytes.
57+
// stateHeight returns the block a state query reads: the latest committed state for a latest tag,
58+
// or the numbered block, with earliest as block 0.
59+
func stateHeight(backend Backend, block ethrpc.BlockNumberOrHash) (height int64, latest bool, err error) {
60+
number, ok := block.Number()
61+
switch {
62+
case !ok:
63+
return 0, false, errBlockHashUnsupported
64+
case isLatestTag(number):
65+
return 0, true, nil
66+
case number == ethrpc.EarliestBlockNumber:
67+
return 0, false, nil
68+
case number < 0:
69+
return 0, false, fmt.Errorf("%w: %d", errBlockTagUnsupported, number)
70+
}
71+
head := backend.EvmBlockNumber()
72+
if uint64(number) > head { //nolint:gosec // non-negative
73+
return 0, false, fmt.Errorf("%w: block %d, latest %d", errBlockAboveHead, number, head)
74+
}
75+
return number.Int64(), false, nil
76+
}
77+
78+
// isLatestTag reports whether number is a tag answered from the latest committed state.
79+
func isLatestTag(number ethrpc.BlockNumber) bool {
80+
switch number {
81+
case ethrpc.LatestBlockNumber, ethrpc.SafeBlockNumber, ethrpc.FinalizedBlockNumber, ethrpc.PendingBlockNumber:
82+
return true
83+
}
84+
return false
85+
}
86+
87+
// GetStorageAt returns the 32-byte value at hexKey in address's storage in the
88+
// committed EVM state after block. An unset slot yields 32 zero bytes.
4989
func (api *stateAPI) GetStorageAt(_ context.Context, address common.Address, hexKey string, block ethrpc.BlockNumberOrHash) (hexutil.Bytes, error) {
50-
if err := requireCurrentState(block); err != nil {
90+
height, latest, err := stateHeight(api.backend, block)
91+
if err != nil {
5192
return nil, err
5293
}
5394
key, err := decodeStorageKey(hexKey)
5495
if err != nil {
5596
return nil, fmt.Errorf("unable to decode storage key: %w", err)
5697
}
57-
value, err := api.backend.EvmStorage(address, key)
98+
var value common.Hash
99+
if latest {
100+
value, err = api.backend.EvmStorage(address, key)
101+
} else {
102+
value, err = api.backend.EvmStorageAt(address, key, height)
103+
}
58104
if err != nil {
59105
return nil, err
60106
}
@@ -81,14 +127,8 @@ func decodeStorageKey(s string) (common.Hash, error) {
81127
}
82128

83129
func requireCurrentState(block ethrpc.BlockNumberOrHash) error {
84-
number, ok := block.Number()
85-
if !ok {
86-
return errHistoricalStateUnsupported
87-
}
88-
switch number {
89-
case ethrpc.LatestBlockNumber, ethrpc.SafeBlockNumber, ethrpc.FinalizedBlockNumber, ethrpc.PendingBlockNumber:
90-
return nil
91-
default:
130+
if number, ok := block.Number(); !ok || !isLatestTag(number) {
92131
return errHistoricalStateUnsupported
93132
}
133+
return nil
94134
}

‎giga/evmonly/rpc/state_test.go‎

Lines changed: 87 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -39,24 +39,37 @@ func TestGetBalance(t *testing.T) {
3939
}
4040
}
4141

42-
func TestGetBalanceRejectsHistoricalState(t *testing.T) {
43-
backend := &testBackend{
42+
// A numbered block, the head's own included, is read at that block rather than from the latest state.
43+
func TestGetBalanceReadsNumberedBlocksFromHistory(t *testing.T) {
44+
address := common.Address{1}
45+
api := &stateAPI{backend: &testBackend{
46+
blockNumber: func() uint64 { return 9 },
4447
balance: func(common.Address) uint256.Int {
45-
t.Fatal("historical request read the current balance")
48+
t.Fatal("a numbered block read the latest state")
4649
return uint256.Int{}
4750
},
51+
balanceAt: func(got common.Address, height int64) (uint256.Int, error) {
52+
require.Equal(t, address, got)
53+
return *uint256.NewInt(uint64(height) * 100), nil //nolint:gosec // test heights are small
54+
},
55+
}}
56+
57+
for height, want := range map[ethrpc.BlockNumber]int64{ethrpc.EarliestBlockNumber: 0, 7: 700, 9: 900} {
58+
got, err := api.GetBalance(t.Context(), address, ethrpc.BlockNumberOrHashWithNumber(height))
59+
require.NoError(t, err)
60+
require.Equal(t, want, got.ToInt().Int64(), "block %d", height)
4861
}
49-
api := &stateAPI{backend: backend}
50-
address := common.Address{1}
62+
_, err := api.GetBalance(t.Context(), address, ethrpc.BlockNumberOrHashWithNumber(10))
63+
require.ErrorIs(t, err, errBlockAboveHead)
64+
_, err = api.GetBalance(t.Context(), address, ethrpc.BlockNumberOrHashWithNumber(-6))
65+
require.ErrorIs(t, err, errBlockTagUnsupported)
66+
}
5167

52-
for _, block := range []ethrpc.BlockNumberOrHash{
53-
ethrpc.BlockNumberOrHashWithNumber(ethrpc.EarliestBlockNumber),
54-
ethrpc.BlockNumberOrHashWithNumber(7),
55-
ethrpc.BlockNumberOrHashWithHash(common.Hash{2}, true),
56-
{},
57-
} {
58-
got, err := api.GetBalance(t.Context(), address, block)
59-
require.ErrorIs(t, err, errHistoricalStateUnsupported)
68+
func TestGetBalanceRejectsABlockHash(t *testing.T) {
69+
api := &stateAPI{backend: &testBackend{}}
70+
for _, block := range []ethrpc.BlockNumberOrHash{ethrpc.BlockNumberOrHashWithHash(common.Hash{2}, true), {}} {
71+
got, err := api.GetBalance(t.Context(), common.Address{1}, block)
72+
require.ErrorIs(t, err, errBlockHashUnsupported)
6073
require.Nil(t, got)
6174
}
6275
}
@@ -105,24 +118,24 @@ func TestGetCode(t *testing.T) {
105118
}
106119
}
107120

108-
func TestGetCodeRejectsHistoricalState(t *testing.T) {
109-
backend := &testBackend{
110-
code: func(common.Address) ([]byte, error) {
111-
t.Fatal("historical request read the current code")
112-
return nil, nil
113-
},
114-
}
115-
api := &stateAPI{backend: backend}
121+
func TestGetCodeReadsNumberedBlocksFromHistory(t *testing.T) {
116122
address := common.Address{1}
123+
api := &stateAPI{backend: &testBackend{
124+
blockNumber: func() uint64 { return 9 },
125+
codeAt: func(got common.Address, height int64) ([]byte, error) {
126+
require.Equal(t, address, got)
127+
require.Equal(t, int64(7), height)
128+
return []byte{0xfe}, nil
129+
},
130+
}}
117131

118-
for _, block := range []ethrpc.BlockNumberOrHash{
119-
ethrpc.BlockNumberOrHashWithNumber(ethrpc.EarliestBlockNumber),
120-
ethrpc.BlockNumberOrHashWithNumber(7),
121-
ethrpc.BlockNumberOrHashWithHash(common.Hash{2}, true),
122-
{},
123-
} {
132+
got, err := api.GetCode(t.Context(), address, ethrpc.BlockNumberOrHashWithNumber(7))
133+
require.NoError(t, err)
134+
require.Equal(t, hexutil.Bytes{0xfe}, got)
135+
136+
for _, block := range []ethrpc.BlockNumberOrHash{ethrpc.BlockNumberOrHashWithHash(common.Hash{2}, true), {}} {
124137
got, err := api.GetCode(t.Context(), address, block)
125-
require.ErrorIs(t, err, errHistoricalStateUnsupported)
138+
require.ErrorIs(t, err, errBlockHashUnsupported)
126139
require.Nil(t, got)
127140
}
128141
}
@@ -148,6 +161,8 @@ func TestHandlerServesGetCode(t *testing.T) {
148161
}
149162
return nil, nil
150163
},
164+
blockNumber: func() uint64 { return 5 },
165+
codeAt: func(common.Address, int64) ([]byte, error) { return nil, nil },
151166
}
152167
handler, err := newHandler(backend, evmonly.NewMemoryReceiptStore())
153168
require.NoError(t, err)
@@ -167,8 +182,9 @@ func TestHandlerServesGetCode(t *testing.T) {
167182
require.NoError(t, client.CallContext(t.Context(), &raw, "eth_getCode", common.Address{9}, "latest"))
168183
require.JSONEq(t, `"0x"`, string(raw))
169184

170-
err = client.CallContext(t.Context(), &got, "eth_getCode", contract, "0x1")
171-
require.ErrorContains(t, err, errHistoricalStateUnsupported.Error())
185+
// Before the contract was deployed.
186+
require.NoError(t, client.CallContext(t.Context(), &raw, "eth_getCode", contract, "0x1"))
187+
require.JSONEq(t, `"0x"`, string(raw))
172188
}
173189

174190
func TestGetStorageAt(t *testing.T) {
@@ -196,11 +212,9 @@ func TestGetStorageAt(t *testing.T) {
196212
{name: "unprefixed key", key: "ff", block: latest, wantKey: common.BigToHash(big.NewInt(0xff))},
197213
{name: "uppercase prefix", key: "0X1", block: latest, wantKey: common.BigToHash(big.NewInt(1))},
198214
{name: "empty key is slot zero", key: "0x", block: latest},
199-
// Historical state, malformed keys, and backend failures are errors.
200-
{name: "earliest", key: "0x1", block: ethrpc.BlockNumberOrHashWithNumber(ethrpc.EarliestBlockNumber), wantErr: errHistoricalStateUnsupported},
201-
{name: "explicit height", key: "0x1", block: ethrpc.BlockNumberOrHashWithNumber(7), wantErr: errHistoricalStateUnsupported},
202-
{name: "block hash", key: "0x1", block: ethrpc.BlockNumberOrHashWithHash(common.Hash{2}, true), wantErr: errHistoricalStateUnsupported},
203-
{name: "neither number nor hash", key: "0x1", wantErr: errHistoricalStateUnsupported},
215+
// Block hashes, malformed keys, and backend failures are errors.
216+
{name: "block hash", key: "0x1", block: ethrpc.BlockNumberOrHashWithHash(common.Hash{2}, true), wantErr: errBlockHashUnsupported},
217+
{name: "neither number nor hash", key: "0x1", wantErr: errBlockHashUnsupported},
204218
{name: "non-hex key", key: "0xzz", block: latest, wantErr: errStorageKeyInvalid},
205219
{name: "doubled prefix", key: "0x0X1", block: latest, wantErr: errStorageKeyInvalid},
206220
{name: "key longer than 32 bytes", key: "0x01" + common.Hash{}.Hex()[2:], block: latest, wantErr: errStorageKeyTooLong},
@@ -232,16 +246,49 @@ func TestGetStorageAt(t *testing.T) {
232246
}
233247
}
234248

249+
// A numbered block, the head's own included, is read at that block rather than from the latest state.
250+
func TestGetStorageAtReadsNumberedBlocksFromHistory(t *testing.T) {
251+
address := common.Address{1}
252+
slot := common.BigToHash(big.NewInt(1))
253+
api := &stateAPI{backend: &testBackend{
254+
blockNumber: func() uint64 { return 9 },
255+
storage: func(common.Address, common.Hash) (common.Hash, error) {
256+
t.Fatal("a numbered block read the latest state")
257+
return common.Hash{}, nil
258+
},
259+
storageAt: func(gotAddress common.Address, gotKey common.Hash, height int64) (common.Hash, error) {
260+
require.Equal(t, address, gotAddress)
261+
require.Equal(t, slot, gotKey)
262+
return common.Hash{byte(height)}, nil //nolint:gosec // test heights are small
263+
},
264+
}}
265+
266+
for number, want := range map[ethrpc.BlockNumber]common.Hash{ethrpc.EarliestBlockNumber: {0}, 7: {7}, 9: {9}} {
267+
got, err := api.GetStorageAt(t.Context(), address, "0x1", ethrpc.BlockNumberOrHashWithNumber(number))
268+
require.NoError(t, err)
269+
require.Equal(t, hexutil.Bytes(want[:]), got, "block %d", number)
270+
}
271+
_, err := api.GetStorageAt(t.Context(), address, "0x1", ethrpc.BlockNumberOrHashWithNumber(10))
272+
require.ErrorIs(t, err, errBlockAboveHead)
273+
}
274+
235275
func TestHandlerServesGetStorageAt(t *testing.T) {
236276
contract := common.HexToAddress("0x6000000000000000000000000000000000000006")
237277
slot := common.BigToHash(big.NewInt(1))
238278
backend := &testBackend{
279+
blockNumber: func() uint64 { return 5 },
239280
storage: func(address common.Address, key common.Hash) (common.Hash, error) {
240281
if address == contract && key == slot {
241282
return common.BigToHash(big.NewInt(0x2a)), nil
242283
}
243284
return common.Hash{}, nil
244285
},
286+
storageAt: func(address common.Address, key common.Hash, height int64) (common.Hash, error) {
287+
if address == contract && key == slot && height == 3 {
288+
return common.BigToHash(big.NewInt(0x11)), nil
289+
}
290+
return common.Hash{}, nil
291+
},
245292
}
246293
handler, err := newHandler(backend, evmonly.NewMemoryReceiptStore())
247294
require.NoError(t, err)
@@ -260,6 +307,9 @@ func TestHandlerServesGetStorageAt(t *testing.T) {
260307
require.NoError(t, client.CallContext(t.Context(), &got, "eth_getStorageAt", contract, "0x2", "latest"))
261308
require.Equal(t, common.Hash{}.Hex(), got.String())
262309

263-
err = client.CallContext(t.Context(), &got, "eth_getStorageAt", contract, "0x1", "0x1")
264-
require.ErrorContains(t, err, errHistoricalStateUnsupported.Error())
310+
// A numbered block below the head reads that block's history.
311+
require.NoError(t, client.CallContext(t.Context(), &got, "eth_getStorageAt", contract, "0x1", "0x3"))
312+
require.Equal(t, common.BigToHash(big.NewInt(0x11)).Hex(), got.String())
313+
require.NoError(t, client.CallContext(t.Context(), &got, "eth_getStorageAt", contract, "0x1", "0x2"))
314+
require.Equal(t, common.Hash{}.Hex(), got.String())
265315
}

0 commit comments

Comments
 (0)