eth_client.go 17 KB
Newer Older
Andreas Bigger's avatar
Andreas Bigger committed
1 2 3 4 5 6 7 8 9
// Package sources exports a number of clients used to access ethereum chain data.
//
// There are a number of these exported clients used by the op-node:
// [L1Client] wraps an RPC client to retrieve L1 ethereum data.
// [L2Client] wraps an RPC client to retrieve L2 ethereum data.
// [RollupClient] wraps an RPC client to retrieve rollup data.
// [EngineClient] extends the [L2Client] providing engine API bindings.
//
// Internally, the listed clients wrap an [EthClient] which itself wraps a specified RPC client.
10
package sources
11 12 13 14

import (
	"context"
	"fmt"
15
	"math/big"
16
	"time"
17

18
	"github.com/ethereum/go-ethereum"
19 20 21
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/common/hexutil"
	"github.com/ethereum/go-ethereum/core/types"
22
	"github.com/ethereum/go-ethereum/log"
23 24 25

	"github.com/ethereum-optimism/optimism/op-node/client"
	"github.com/ethereum-optimism/optimism/op-node/sources/caching"
26
	"github.com/ethereum-optimism/optimism/op-service/eth"
27 28
)

29
type EthClientConfig struct {
30
	// Maximum number of requests to make per batch
31 32 33 34 35 36 37 38 39 40 41 42 43
	MaxRequestsPerBatch int

	// limit concurrent requests, applies to the source as a whole
	MaxConcurrentRequests int

	// cache sizes

	// Number of blocks worth of receipts to cache
	ReceiptsCacheSize int
	// Number of blocks worth of transactions to cache
	TransactionsCacheSize int
	// Number of block headers to cache
	HeadersCacheSize int
44 45
	// Number of payloads to cache
	PayloadsCacheSize int
46 47 48 49 50 51

	// If the RPC is untrusted, then we should not use cached information from responses,
	// and instead verify against the block-hash.
	// Of real L1 blocks no deposits can be missed/faked, no batches can be missed/faked,
	// only the wrong L1 blocks can be retrieved.
	TrustRPC bool
52 53 54 55 56

	// If the RPC must ensure that the results fit the ExecutionPayload(Header) format.
	// If this is not checked, disabled header fields like the nonce or difficulty
	// may be used to get a different block-hash.
	MustBePostMerge bool
57 58 59

	// RPCProviderKind is a hint at what type of RPC provider we are dealing with
	RPCProviderKind RPCProviderKind
60 61 62 63 64

	// Method reset duration defines how long we stick to available RPC methods,
	// till we re-attempt the user-preferred methods.
	// If this is 0 then the client does not fall back to less optimal but available methods.
	MethodResetDuration time.Duration
65 66
}

67
func (c *EthClientConfig) Check() error {
68 69 70 71 72 73 74 75 76
	if c.ReceiptsCacheSize < 0 {
		return fmt.Errorf("invalid receipts cache size: %d", c.ReceiptsCacheSize)
	}
	if c.TransactionsCacheSize < 0 {
		return fmt.Errorf("invalid transactions cache size: %d", c.TransactionsCacheSize)
	}
	if c.HeadersCacheSize < 0 {
		return fmt.Errorf("invalid headers cache size: %d", c.HeadersCacheSize)
	}
77 78 79
	if c.PayloadsCacheSize < 0 {
		return fmt.Errorf("invalid payloads cache size: %d", c.PayloadsCacheSize)
	}
80 81 82 83 84 85
	if c.MaxConcurrentRequests < 1 {
		return fmt.Errorf("expected at least 1 concurrent request, but max is %d", c.MaxConcurrentRequests)
	}
	if c.MaxRequestsPerBatch < 1 {
		return fmt.Errorf("expected at least 1 request per batch, but max is: %d", c.MaxRequestsPerBatch)
	}
86 87 88
	if !ValidRPCProviderKind(c.RPCProviderKind) {
		return fmt.Errorf("unknown rpc provider kind: %s", c.RPCProviderKind)
	}
89 90 91
	return nil
}

92 93
// EthClient retrieves ethereum data with optimized batch requests, cached results, and flag to not trust the RPC.
type EthClient struct {
94
	client client.RPC
95

96
	maxBatchSize int
97 98 99

	trustRPC bool

100 101
	mustBePostMerge bool

102 103
	provKind RPCProviderKind

104 105
	log log.Logger

106
	// cache receipts in bundles per block hash
107 108
	// We cache the receipts fetching job to not lose progress when we have to retry the `Fetch` call
	// common.Hash -> *receiptsFetchingJob
109
	receiptsCache *caching.LRUCache[common.Hash, *receiptsFetchingJob]
110 111 112

	// cache transactions in bundles per block hash
	// common.Hash -> types.Transactions
113
	transactionsCache *caching.LRUCache[common.Hash, types.Transactions]
114 115 116

	// cache block headers of blocks by hash
	// common.Hash -> *HeaderInfo
117
	headersCache *caching.LRUCache[common.Hash, eth.BlockInfo]
118 119 120

	// cache payloads by hash
	// common.Hash -> *eth.ExecutionPayload
121
	payloadsCache *caching.LRUCache[common.Hash, *eth.ExecutionPayload]
122 123 124 125 126

	// availableReceiptMethods tracks which receipt methods can be used for fetching receipts
	// This may be modified concurrently, but we don't lock since it's a single
	// uint64 that's not critical (fine to miss or mix up a modification)
	availableReceiptMethods ReceiptsFetchingMethod
127 128 129 130 131 132 133 134

	// lastMethodsReset tracks when availableReceiptMethods was last reset.
	// When receipt-fetching fails it falls back to available methods,
	// but periodically it will try to reset to the preferred optimal methods.
	lastMethodsReset time.Time

	// methodResetDuration defines how long we take till we reset lastMethodsReset
	methodResetDuration time.Duration
135 136 137
}

func (s *EthClient) PickReceiptsMethod(txCount uint64) ReceiptsFetchingMethod {
138 139 140 141 142 143 144 145
	if now := time.Now(); now.Sub(s.lastMethodsReset) > s.methodResetDuration {
		m := AvailableReceiptsFetchingMethods(s.provKind)
		if s.availableReceiptMethods != m {
			s.log.Warn("resetting back RPC preferences, please review RPC provider kind setting", "kind", s.provKind.String())
		}
		s.availableReceiptMethods = m
		s.lastMethodsReset = now
	}
146 147 148 149 150 151 152
	return PickBestReceiptsFetchingMethod(s.provKind, s.availableReceiptMethods, txCount)
}

func (s *EthClient) OnReceiptsMethodErr(m ReceiptsFetchingMethod, err error) {
	if unusableMethod(err) {
		// clear the bit of the method that errored
		s.availableReceiptMethods &^= m
153
		s.log.Warn("failed to use selected RPC method for receipt fetching, temporarily falling back to alternatives",
154 155 156 157 158
			"provider_kind", s.provKind, "failed_method", m, "fallback", s.availableReceiptMethods, "err", err)
	} else {
		s.log.Debug("failed to use selected RPC method for receipt fetching, but method does appear to be available, so we continue to use it",
			"provider_kind", s.provKind, "failed_method", m, "fallback", s.availableReceiptMethods&^m, "err", err)
	}
159 160
}

Andreas Bigger's avatar
Andreas Bigger committed
161 162
// NewEthClient returns an [EthClient], wrapping an RPC with bindings to fetch ethereum data with added error logging,
// metric tracking, and caching. The [EthClient] uses a [LimitRPC] wrapper to limit the number of concurrent RPC requests.
163
func NewEthClient(client client.RPC, log log.Logger, metrics caching.Metrics, config *EthClientConfig) (*EthClient, error) {
164 165 166 167
	if err := config.Check(); err != nil {
		return nil, fmt.Errorf("bad config, cannot create L1 source: %w", err)
	}
	client = LimitRPC(client, config.MaxConcurrentRequests)
168
	return &EthClient{
169 170 171 172 173 174
		client:                  client,
		maxBatchSize:            config.MaxRequestsPerBatch,
		trustRPC:                config.TrustRPC,
		mustBePostMerge:         config.MustBePostMerge,
		provKind:                config.RPCProviderKind,
		log:                     log,
175 176 177 178
		receiptsCache:           caching.NewLRUCache[common.Hash, *receiptsFetchingJob](metrics, "receipts", config.ReceiptsCacheSize),
		transactionsCache:       caching.NewLRUCache[common.Hash, types.Transactions](metrics, "txs", config.TransactionsCacheSize),
		headersCache:            caching.NewLRUCache[common.Hash, eth.BlockInfo](metrics, "headers", config.HeadersCacheSize),
		payloadsCache:           caching.NewLRUCache[common.Hash, *eth.ExecutionPayload](metrics, "payloads", config.PayloadsCacheSize),
179
		availableReceiptMethods: AvailableReceiptsFetchingMethods(config.RPCProviderKind),
180 181
		lastMethodsReset:        time.Now(),
		methodResetDuration:     config.MethodResetDuration,
182 183 184 185
	}, nil
}

// SubscribeNewHead subscribes to notifications about the current blockchain head on the given channel.
186
func (s *EthClient) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (ethereum.Subscription, error) {
187 188 189 190 191
	// Note that *types.Header does not cache the block hash unlike *HeaderInfo, it always recomputes.
	// Inefficient if used poorly, but no trust issue.
	return s.client.EthSubscribe(ctx, ch, "newHeads")
}

192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
// rpcBlockID is an internal type to enforce header and block call results match the requested identifier
type rpcBlockID interface {
	// Arg translates the object into an RPC argument
	Arg() any
	// CheckID verifies a block/header result matches the requested block identifier
	CheckID(id eth.BlockID) error
}

// hashID implements rpcBlockID for safe block-by-hash fetching
type hashID common.Hash

func (h hashID) Arg() any { return common.Hash(h) }
func (h hashID) CheckID(id eth.BlockID) error {
	if common.Hash(h) != id.Hash {
		return fmt.Errorf("expected block hash %s but got block %s", common.Hash(h), id)
	}
	return nil
}

// numberID implements rpcBlockID for safe block-by-number fetching
type numberID uint64

func (n numberID) Arg() any { return hexutil.EncodeUint64(uint64(n)) }
func (n numberID) CheckID(id eth.BlockID) error {
	if uint64(n) != id.Number {
		return fmt.Errorf("expected block number %d but got block %s", uint64(n), id)
	}
	return nil
}

222
func (s *EthClient) headerCall(ctx context.Context, method string, id rpcBlockID) (eth.BlockInfo, error) {
223
	var header *rpcHeader
224
	err := s.client.CallContext(ctx, &header, method, id.Arg(), false) // headers are just blocks without txs
225 226 227 228 229 230
	if err != nil {
		return nil, err
	}
	if header == nil {
		return nil, ethereum.NotFound
	}
231
	info, err := header.Info(s.trustRPC, s.mustBePostMerge)
232 233 234
	if err != nil {
		return nil, err
	}
235 236 237
	if err := id.CheckID(eth.ToBlockID(info)); err != nil {
		return nil, fmt.Errorf("fetched block header does not match requested ID: %w", err)
	}
238
	s.headersCache.Add(info.Hash(), info)
239 240 241
	return info, nil
}

242
func (s *EthClient) blockCall(ctx context.Context, method string, id rpcBlockID) (eth.BlockInfo, types.Transactions, error) {
243
	var block *rpcBlock
244
	err := s.client.CallContext(ctx, &block, method, id.Arg(), true)
245 246 247 248 249 250
	if err != nil {
		return nil, nil, err
	}
	if block == nil {
		return nil, nil, ethereum.NotFound
	}
251
	info, txs, err := block.Info(s.trustRPC, s.mustBePostMerge)
252 253 254
	if err != nil {
		return nil, nil, err
	}
255 256 257
	if err := id.CheckID(eth.ToBlockID(info)); err != nil {
		return nil, nil, fmt.Errorf("fetched block data does not match requested ID: %w", err)
	}
258 259
	s.headersCache.Add(info.Hash(), info)
	s.transactionsCache.Add(info.Hash(), txs)
260 261 262
	return info, txs, nil
}

263
func (s *EthClient) payloadCall(ctx context.Context, method string, id rpcBlockID) (*eth.ExecutionPayload, error) {
264
	var block *rpcBlock
265
	err := s.client.CallContext(ctx, &block, method, id.Arg(), true)
266 267 268 269 270 271 272 273 274 275
	if err != nil {
		return nil, err
	}
	if block == nil {
		return nil, ethereum.NotFound
	}
	payload, err := block.ExecutionPayload(s.trustRPC)
	if err != nil {
		return nil, err
	}
276 277 278
	if err := id.CheckID(payload.ID()); err != nil {
		return nil, fmt.Errorf("fetched payload does not match requested ID: %w", err)
	}
279 280 281 282
	s.payloadsCache.Add(payload.BlockHash, payload)
	return payload, nil
}

283 284
// ChainID fetches the chain id of the internal RPC.
func (s *EthClient) ChainID(ctx context.Context) (*big.Int, error) {
Andreas Bigger's avatar
Andreas Bigger committed
285
	var id hexutil.Big
286 287 288 289
	err := s.client.CallContext(ctx, &id, "eth_chainId")
	if err != nil {
		return nil, err
	}
Andreas Bigger's avatar
Andreas Bigger committed
290
	return (*big.Int)(&id), nil
291 292
}

293
func (s *EthClient) InfoByHash(ctx context.Context, hash common.Hash) (eth.BlockInfo, error) {
294
	if header, ok := s.headersCache.Get(hash); ok {
295
		return header, nil
296
	}
297
	return s.headerCall(ctx, "eth_getBlockByHash", hashID(hash))
298 299
}

300
func (s *EthClient) InfoByNumber(ctx context.Context, number uint64) (eth.BlockInfo, error) {
301
	// can't hit the cache when querying by number due to reorgs.
302
	return s.headerCall(ctx, "eth_getBlockByNumber", numberID(number))
303 304
}

305 306
func (s *EthClient) InfoByLabel(ctx context.Context, label eth.BlockLabel) (eth.BlockInfo, error) {
	// can't hit the cache when querying the head due to reorgs / changes.
307
	return s.headerCall(ctx, "eth_getBlockByNumber", label)
308 309 310
}

func (s *EthClient) InfoAndTxsByHash(ctx context.Context, hash common.Hash) (eth.BlockInfo, types.Transactions, error) {
311 312
	if header, ok := s.headersCache.Get(hash); ok {
		if txs, ok := s.transactionsCache.Get(hash); ok {
313
			return header, txs, nil
314 315
		}
	}
316
	return s.blockCall(ctx, "eth_getBlockByHash", hashID(hash))
317 318
}

319
func (s *EthClient) InfoAndTxsByNumber(ctx context.Context, number uint64) (eth.BlockInfo, types.Transactions, error) {
320
	// can't hit the cache when querying by number due to reorgs.
321
	return s.blockCall(ctx, "eth_getBlockByNumber", numberID(number))
322 323
}

324
func (s *EthClient) InfoAndTxsByLabel(ctx context.Context, label eth.BlockLabel) (eth.BlockInfo, types.Transactions, error) {
325
	// can't hit the cache when querying the head due to reorgs / changes.
326
	return s.blockCall(ctx, "eth_getBlockByNumber", label)
327 328
}

329 330
func (s *EthClient) PayloadByHash(ctx context.Context, hash common.Hash) (*eth.ExecutionPayload, error) {
	if payload, ok := s.payloadsCache.Get(hash); ok {
331
		return payload, nil
332
	}
333
	return s.payloadCall(ctx, "eth_getBlockByHash", hashID(hash))
334 335 336
}

func (s *EthClient) PayloadByNumber(ctx context.Context, number uint64) (*eth.ExecutionPayload, error) {
337
	return s.payloadCall(ctx, "eth_getBlockByNumber", numberID(number))
338 339 340
}

func (s *EthClient) PayloadByLabel(ctx context.Context, label eth.BlockLabel) (*eth.ExecutionPayload, error) {
341
	return s.payloadCall(ctx, "eth_getBlockByNumber", label)
342 343
}

344 345 346 347
// FetchReceipts returns a block info and all of the receipts associated with transactions in the block.
// It verifies the receipt hash in the block header against the receipt hash of the fetched receipts
// to ensure that the execution engine did not fail to return any receipts.
func (s *EthClient) FetchReceipts(ctx context.Context, blockHash common.Hash) (eth.BlockInfo, types.Receipts, error) {
348
	info, txs, err := s.InfoAndTxsByHash(ctx, blockHash)
349
	if err != nil {
350
		return nil, nil, err
351
	}
352 353 354
	// Try to reuse the receipts fetcher because is caches the results of intermediate calls. This means
	// that if just one of many calls fail, we only retry the failed call rather than all of the calls.
	// The underlying fetcher uses the receipts hash to verify receipt integrity.
355
	var job *receiptsFetchingJob
356
	if v, ok := s.receiptsCache.Get(blockHash); ok {
357
		job = v
358
	} else {
359
		txHashes := eth.TransactionsToHashes(txs)
360 361
		job = NewReceiptsFetchingJob(s, s.client, s.maxBatchSize, eth.ToBlockID(info), info.ReceiptHash(), txHashes)
		s.receiptsCache.Add(blockHash, job)
362
	}
363
	receipts, err := job.Fetch(ctx)
364 365 366 367 368
	if err != nil {
		return nil, nil, err
	}

	return info, receipts, nil
369 370
}

371 372 373 374
// GetProof returns an account proof result, with any optional requested storage proofs.
// The retrieval does sanity-check that storage proofs for the expected keys are present in the response,
// but does not verify the result. Call accountResult.Verify(stateRoot) to verify the result.
func (s *EthClient) GetProof(ctx context.Context, address common.Address, storage []common.Hash, blockTag string) (*eth.AccountResult, error) {
375
	var getProofResponse *eth.AccountResult
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
	err := s.client.CallContext(ctx, &getProofResponse, "eth_getProof", address, storage, blockTag)
	if err != nil {
		return nil, err
	}
	if getProofResponse == nil {
		return nil, ethereum.NotFound
	}
	if len(getProofResponse.StorageProof) != len(storage) {
		return nil, fmt.Errorf("missing storage proof data, got %d proof entries but requested %d storage keys", len(getProofResponse.StorageProof), len(storage))
	}
	for i, key := range storage {
		if key != getProofResponse.StorageProof[i].Key {
			return nil, fmt.Errorf("unexpected storage proof key difference for entry %d: got %s but requested %s", i, getProofResponse.StorageProof[i].Key, key)
		}
	}
	return getProofResponse, nil
}

// GetStorageAt returns the storage value at the given address and storage slot, **without verifying the correctness of the result**.
// This should only ever be used as alternative to GetProof when the user opts in.
// E.g. Erigon L1 node users may have to use this, since Erigon does not support eth_getProof, see https://github.com/ledgerwatch/erigon/issues/1349
func (s *EthClient) GetStorageAt(ctx context.Context, address common.Address, storageSlot common.Hash, blockTag string) (common.Hash, error) {
	var out common.Hash
	err := s.client.CallContext(ctx, &out, "eth_getStorageAt", address, storageSlot, blockTag)
	return out, err
}

// ReadStorageAt is a convenience method to read a single storage value at the given slot in the given account.
// The storage slot value is verified against the state-root of the given block if we do not trust the RPC provider, or directly retrieved without proof if we do trust the RPC.
func (s *EthClient) ReadStorageAt(ctx context.Context, address common.Address, storageSlot common.Hash, blockHash common.Hash) (common.Hash, error) {
	if s.trustRPC {
		return s.GetStorageAt(ctx, address, storageSlot, blockHash.String())
	}
	block, err := s.InfoByHash(ctx, blockHash)
	if err != nil {
		return common.Hash{}, fmt.Errorf("failed to retrieve state root of block %s: %w", blockHash, err)
	}

	result, err := s.GetProof(ctx, address, []common.Hash{storageSlot}, blockHash.String())
	if err != nil {
		return common.Hash{}, fmt.Errorf("failed to fetch proof of storage slot %s at block %s: %w", storageSlot, blockHash, err)
	}

	if err := result.Verify(block.Root()); err != nil {
		return common.Hash{}, fmt.Errorf("failed to verify retrieved proof against state root: %w", err)
421
	}
Michael de Hoog's avatar
Michael de Hoog committed
422 423
	value := result.StorageProof[0].Value.ToInt()
	return common.BytesToHash(value.Bytes()), nil
424 425 426
}

func (s *EthClient) Close() {
427 428
	s.client.Close()
}