-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy patheth_api.go
More file actions
611 lines (548 loc) · 22.9 KB
/
Copy patheth_api.go
File metadata and controls
611 lines (548 loc) · 22.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
// Copyright 2024 The Erigon Authors
// This file is part of Erigon.
//
// Erigon is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Erigon is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Erigon. If not, see <http://www.gnu.org/licenses/>.
package jsonrpc
import (
"bytes"
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
lru "github.com/hashicorp/golang-lru/v2"
"github.com/holiman/uint256"
"github.com/erigontech/erigon/common"
"github.com/erigontech/erigon/common/hexutil"
"github.com/erigontech/erigon/common/log/v3"
"github.com/erigontech/erigon/common/math"
"github.com/erigontech/erigon/db/datadir"
"github.com/erigontech/erigon/db/dbservices"
"github.com/erigontech/erigon/db/kv"
"github.com/erigontech/erigon/db/kv/kvcache"
"github.com/erigontech/erigon/db/kv/kvcfg"
"github.com/erigontech/erigon/db/kv/prune"
"github.com/erigontech/erigon/db/kv/rawdbv3"
"github.com/erigontech/erigon/db/rawdb"
"github.com/erigontech/erigon/execution/bal"
"github.com/erigontech/erigon/execution/chain"
"github.com/erigontech/erigon/execution/protocol/misc"
"github.com/erigontech/erigon/execution/protocol/rules"
"github.com/erigontech/erigon/execution/state"
"github.com/erigontech/erigon/execution/types"
"github.com/erigontech/erigon/execution/types/accounts"
"github.com/erigontech/erigon/node/gointerfaces/txpoolproto"
"github.com/erigontech/erigon/rpc"
"github.com/erigontech/erigon/rpc/ethapi"
ethapi2 "github.com/erigontech/erigon/rpc/ethapi"
"github.com/erigontech/erigon/rpc/filters"
"github.com/erigontech/erigon/rpc/gasprice"
"github.com/erigontech/erigon/rpc/jsonrpc/receipts"
"github.com/erigontech/erigon/rpc/rpccfg"
"github.com/erigontech/erigon/rpc/rpchelper"
)
// EthAPI is a collection of functions that are exposed in the
type EthAPI interface {
// Block related (proposed file: ./eth_blocks.go)
GetBlockByNumber(ctx context.Context, number rpc.BlockNumber, fullTx bool) (map[string]any, error)
GetBlockByHash(ctx context.Context, hash rpc.BlockNumberOrHash, fullTx bool) (map[string]any, error)
GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*hexutil.Uint, error)
GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) (*hexutil.Uint, error)
// Transaction related (see ./eth_txs.go)
GetTransactionByHash(ctx context.Context, hash common.Hash) (*ethapi.RPCTransaction, error)
GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, txIndex hexutil.Uint64) (*ethapi.RPCTransaction, error)
GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, txIndex hexutil.Uint) (*ethapi.RPCTransaction, error)
GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (hexutil.Bytes, error)
GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (hexutil.Bytes, error)
GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error)
// Receipt related (see ./eth_receipts.go)
GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]any, error)
GetLogs(ctx context.Context, crit filters.FilterCriteria) (types.RPCLogs, error)
GetBlockReceipts(ctx context.Context, numberOrHash rpc.BlockNumberOrHash) ([]map[string]any, error)
// Block access list related (see ./eth_block_access_list.go)
GetBlockAccessList(ctx context.Context, numberOrHash rpc.BlockNumberOrHash) ([]*ethapi.RPCAccountAccess, error)
// Uncle related (see ./eth_uncles.go)
GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]any, error)
GetUncleByBlockHashAndIndex(ctx context.Context, hash common.Hash, index hexutil.Uint) (map[string]any, error)
GetUncleCountByBlockNumber(ctx context.Context, number rpc.BlockNumber) (*hexutil.Uint, error)
GetUncleCountByBlockHash(ctx context.Context, hash common.Hash) (*hexutil.Uint, error)
// Filter related (see ./eth_filters.go)
NewPendingTransactionFilter(_ context.Context) (string, error)
NewBlockFilter(_ context.Context) (string, error)
NewFilter(_ context.Context, crit filters.FilterCriteria) (string, error)
UninstallFilter(_ context.Context, index string) (bool, error)
GetFilterChanges(_ context.Context, index string) ([]any, error)
GetFilterLogs(_ context.Context, index string) ([]*types.Log, error)
Logs(ctx context.Context, crit filters.FilterCriteria) (*rpc.Subscription, error)
// Account related (see ./eth_accounts.go)
Accounts(ctx context.Context) ([]common.Address, error)
GetBalance(ctx context.Context, address common.Address, blockNrOrHash *rpc.BlockNumberOrHash) (*hexutil.Big, error)
GetTransactionCount(ctx context.Context, address common.Address, blockNrOrHash *rpc.BlockNumberOrHash) (*hexutil.Uint64, error)
GetStorageAt(ctx context.Context, address common.Address, index string, blockNrOrHash *rpc.BlockNumberOrHash) (string, error)
GetStorageValues(ctx context.Context, requests map[common.Address][]common.Hash, blockNrOrHash *rpc.BlockNumberOrHash) (map[common.Address][]hexutil.Bytes, error)
GetCode(ctx context.Context, address common.Address, blockNrOrHash *rpc.BlockNumberOrHash) (hexutil.Bytes, error)
// System related (see ./eth_system.go)
BlockNumber(ctx context.Context) (hexutil.Uint64, error)
Syncing(ctx context.Context) (any, error)
ChainId(ctx context.Context) (hexutil.Uint64, error) /* called eth_protocolVersion elsewhere */
ProtocolVersion(_ context.Context) (hexutil.Uint, error)
GasPrice(_ context.Context) (*hexutil.Big, error)
BaseFee(ctx context.Context) (*hexutil.Big, error)
BlobBaseFee(ctx context.Context) (*hexutil.Big, error)
Config(ctx context.Context, timeArg *hexutil.Uint64) (*EthConfigResp, error)
Capabilities(ctx context.Context) (*CapabilitiesResult, error)
// Sending related (see ./eth_call.go)
Call(ctx context.Context, args ethapi.CallArgs, blockNrOrHash *rpc.BlockNumberOrHash, overrides *ethapi.StateOverrides, blockOverrides *ethapi.BlockOverrides) (hexutil.Bytes, error)
EstimateGas(ctx context.Context, argsOrNil *ethapi.CallArgs, blockNrOrHash *rpc.BlockNumberOrHash, overrides *ethapi.StateOverrides, blockOverrides *ethapi.BlockOverrides) (hexutil.Uint64, error)
// Simulation related (see ./eth_simulation.go)
SimulateV1(ctx context.Context, req SimulationRequest, blockParameter rpc.BlockNumberOrHash) (SimulationResult, error)
SendRawTransaction(ctx context.Context, encodedTx hexutil.Bytes) (common.Hash, error)
SendRawTransactionSync(ctx context.Context, encodedTx hexutil.Bytes, timeoutMs *uint64) (map[string]any, error)
SendTransaction(_ context.Context, txObject any) (common.Hash, error)
Sign(ctx context.Context, _ common.Address, _ hexutil.Bytes) (hexutil.Bytes, error)
SignTransaction(_ context.Context, txObject any) (common.Hash, error)
FillTransaction(ctx context.Context, args ethapi.CallArgs) (*ethapi.SignTransactionResult, error)
GetProof(ctx context.Context, address common.Address, storageKeys []hexutil.Bytes, blockNr *rpc.BlockNumberOrHash) (*accounts.AccProofResult, error)
CreateAccessList(ctx context.Context, args ethapi.CallArgs, blockNrOrHash *rpc.BlockNumberOrHash, overrides *ethapi2.StateOverrides, optimizeGas *bool) (*accessListResult, error)
// Mining related (see ./eth_mining.go)
Coinbase(ctx context.Context) (common.Address, error)
Hashrate(ctx context.Context) (uint64, error)
Mining(ctx context.Context) (bool, error)
GetWork(ctx context.Context) ([4]string, error)
SubmitWork(ctx context.Context, nonce types.BlockNonce, powHash, digest common.Hash) (bool, error)
SubmitHashrate(ctx context.Context, hashRate hexutil.Uint64, id common.Hash) (bool, error)
}
type BaseAPI struct {
// all caches are thread-safe
stateCache kvcache.Cache
blocksLRU *lru.Cache[common.Hash, *types.Block]
filters *rpchelper.Filters
_chainConfig atomic.Pointer[chain.Config]
_genesis atomic.Pointer[types.Block]
_pruneMode atomic.Pointer[prune.Mode]
_commitmentHistoryEnabled atomic.Pointer[bool]
_blockReader dbservices.FullBlockReader
_txNumReader rawdbv3.TxNumsReader
_txnReader dbservices.TxnReader
_engine rules.EngineReader
bridgeReader bridgeReader
evmCallTimeout time.Duration
blockRangeLimit int
getLogsMaxResults int
logQueryLimit int
dirs datadir.Dirs
receiptsGenerator *receipts.Generator
borReceiptGenerator *receipts.BorGenerator
balRegenerator *bal.Regenerator
}
func NewBaseApi(f *rpchelper.Filters, stateCache kvcache.Cache, blockReader dbservices.FullBlockReader, engine rules.Engine, bridgeReader bridgeReader, conf *rpccfg.BaseApiConfig) *BaseAPI {
if conf == nil {
conf = &rpccfg.BaseApiConfig{}
}
blocksLRUSize := 128 // ~32Mb
// if RPCDaemon deployed as independent process: increase cache sizes
if !conf.SingleNodeMode {
blocksLRUSize *= 5
}
blocksLRU, err := lru.New[common.Hash, *types.Block](blocksLRUSize)
if err != nil {
panic(err)
}
evmCallTimeout := conf.EvmCallTimeout
if evmCallTimeout == 0 {
evmCallTimeout = rpccfg.DefaultEvmCallTimeout
}
return &BaseAPI{
filters: f,
stateCache: stateCache,
blocksLRU: blocksLRU,
_blockReader: blockReader,
_txnReader: blockReader,
_txNumReader: blockReader.TxnumReader(),
evmCallTimeout: evmCallTimeout,
_engine: engine,
receiptsGenerator: receipts.NewGenerator(conf.Dirs, blockReader, engine, stateCache, evmCallTimeout, f),
borReceiptGenerator: receipts.NewBorGenerator(blockReader, engine, stateCache, f),
balRegenerator: bal.NewRegenerator(blockReader, engine, log.Root()),
dirs: conf.Dirs,
bridgeReader: bridgeReader,
blockRangeLimit: conf.BlockRangeLimit,
getLogsMaxResults: conf.GetLogsMaxResults,
logQueryLimit: conf.LogQueryLimit,
}
}
func (api *BaseAPI) chainConfig(ctx context.Context, tx kv.Tx) (*chain.Config, error) {
cfg, _, err := api.chainConfigWithGenesis(ctx, tx)
return cfg, err
}
func (api *BaseAPI) chainConfigWithGenesis(ctx context.Context, tx kv.Tx) (*chain.Config, *types.Block, error) {
cc, genesisBlock := api._chainConfig.Load(), api._genesis.Load()
if cc != nil && genesisBlock != nil {
return cc, genesisBlock, nil
}
genesisBlock, err := api.blockByNumberWithSenders(ctx, tx, 0)
if err != nil {
return nil, nil, err
}
if genesisBlock == nil {
return nil, nil, errors.New("genesis block not found in database")
}
cc, err = rawdb.ReadChainConfig(tx, genesisBlock.Hash())
if err != nil {
return nil, nil, err
}
if cc != nil {
api._genesis.Store(genesisBlock)
api._chainConfig.Store(cc)
}
return cc, genesisBlock, nil
}
func (api *BaseAPI) pendingBlock() *types.Block {
if api.filters == nil {
return nil
}
return api.filters.LastPendingBlock()
}
func (api *BaseAPI) engine() rules.EngineReader {
return api._engine
}
func (api *BaseAPI) txnLookup(ctx context.Context, tx kv.Tx, txnHash common.Hash) (blockNum uint64, txNum uint64, ok bool, err error) {
overlayTx := api.filters.WithOverlay(tx)
return api._txnReader.TxnLookup(ctx, overlayTx, txnHash)
}
func (api *BaseAPI) txnLookupWithBorFallback(ctx context.Context, tx kv.Tx, txnHash common.Hash, chainConfig *chain.Config) (blockNum uint64, txNum uint64, isBorStateSyncTxn bool, ok bool, err error) {
blockNum, txNum, ok, err = api.txnLookup(ctx, tx, txnHash)
if err != nil {
return 0, 0, false, false, err
}
if ok {
return blockNum, txNum, false, true, nil
}
if chainConfig.Bor == nil {
return 0, 0, false, false, nil
}
blockNum, ok, err = api.bridgeReader.EventTxnLookup(ctx, txnHash)
if err != nil {
return 0, 0, false, false, err
}
if !ok {
return 0, 0, false, false, nil
}
return blockNum, txNum, true, true, nil
}
// txnIndexInBlock derives the in-block txn index from a global txNum. Bor state sync
// txns are not part of the block body, so they yield the -1 sentinel and the consistency
// check is skipped (their txNum comes from a missed lookup).
func (api *BaseAPI) txnIndexInBlock(ctx context.Context, tx kv.Tx, blockNum, txNum uint64, isBorStateSyncTxn bool) (int, error) {
txNumMin, err := api._txNumReader.Min(ctx, tx, blockNum)
if err != nil {
return 0, err
}
if isBorStateSyncTxn {
return -1, nil
}
if txNumMin+1 > txNum {
return 0, fmt.Errorf("uint underflow txnums error txNum: %d, txNumMin: %d, blockNum: %d", txNum, txNumMin, blockNum)
}
return int(txNum - txNumMin - 1), nil
}
func (api *BaseAPI) blockByNumberWithSenders(ctx context.Context, tx kv.Tx, number uint64) (*types.Block, error) {
blockNumber, hash, _, err := rpchelper.GetBlockNumber(ctx, rpc.BlockNumberOrHashWithNumber(rpc.BlockNumber(number)), tx, api._blockReader, api.filters)
if err != nil {
if errors.As(err, &rpc.BlockNotFoundErr{}) {
return nil, nil
}
return nil, err
}
return api.blockWithSenders(ctx, tx, hash, blockNumber)
}
func (api *BaseAPI) blockByHashWithSenders(ctx context.Context, tx kv.Tx, hash common.Hash) (*types.Block, error) {
if api.blocksLRU != nil {
if it, ok := api.blocksLRU.Get(hash); ok && it != nil {
return it, nil
}
}
overlayTx := api.filters.WithOverlay(tx)
number, err := api._blockReader.HeaderNumber(ctx, overlayTx, hash)
if err != nil {
return nil, err
}
if number == nil {
return nil, nil
}
return api.blockWithSenders(ctx, tx, hash, *number)
}
func (api *BaseAPI) blockWithSenders(ctx context.Context, tx kv.Tx, hash common.Hash, number uint64) (*types.Block, error) {
if api.blocksLRU != nil {
if it, ok := api.blocksLRU.Get(hash); ok && it != nil {
return it, nil
}
}
overlayTx := api.filters.WithOverlay(tx)
block, _, err := api._blockReader.BlockWithSenders(ctx, overlayTx, hash, number)
if err != nil {
return nil, err
}
if block == nil { // don't save nil's to cache
return nil, nil
}
// don't save empty blocks to cache, because in Erigon
// if block become non-canonical - we remove it's transactions, but block can become canonical in future
if block.Transactions().Len() == 0 {
return block, nil
}
if api.blocksLRU != nil {
// calc fields before put to cache
for _, txn := range block.Transactions() {
txn.Hash()
}
block.Hash()
api.blocksLRU.Add(hash, block)
}
return block, nil
}
func (api *BaseAPI) headerNumberByHash(ctx context.Context, tx kv.Tx, hash common.Hash) (uint64, error) {
if api.blocksLRU != nil {
if it, ok := api.blocksLRU.Get(hash); ok && it != nil {
return it.NumberU64(), nil
}
}
number, err := api._blockReader.HeaderNumber(ctx, tx, hash)
if err != nil {
return 0, err
}
if number == nil {
return 0, errors.New("header number not found")
}
return *number, nil
}
// headerByNumberOrHash - intent to read recent headers only, tries from the lru cache before reading from the db
func (api *BaseAPI) headerByNumberOrHash(ctx context.Context, tx kv.Tx, blockNrOrHash rpc.BlockNumberOrHash) (*types.Header, bool, error) {
blockNum, hash, isLatest, err := rpchelper.GetCanonicalBlockNumber(ctx, blockNrOrHash, tx, api._blockReader, api.filters)
if err != nil {
return nil, false, err
}
if api.blocksLRU != nil {
if it, ok := api.blocksLRU.Get(hash); ok && it != nil {
return it.HeaderNoCopy(), isLatest, nil
}
}
overlayTx := api.filters.WithOverlay(tx)
header, err := api._blockReader.HeaderByNumber(ctx, overlayTx, blockNum)
if err != nil {
return nil, false, err
}
// header can be nil
return header, isLatest, nil
}
func (api *BaseAPI) headerByNumber(ctx context.Context, number rpc.BlockNumber, tx kv.Tx) (*types.Header, error) {
n, h, _, err := rpchelper.GetBlockNumber(ctx, rpc.BlockNumberOrHashWithNumber(number), tx, api._blockReader, api.filters)
if err != nil {
return nil, err
}
if api.blocksLRU != nil {
if it, ok := api.blocksLRU.Get(h); ok && it != nil {
return it.HeaderNoCopy(), nil
}
}
overlayTx := api.filters.WithOverlay(tx)
return api._blockReader.Header(ctx, overlayTx, h, n)
}
func (api *BaseAPI) headerByHash(ctx context.Context, hash common.Hash, tx kv.Tx) (*types.Header, error) {
if api.blocksLRU != nil {
if it, ok := api.blocksLRU.Get(hash); ok && it != nil {
return it.HeaderNoCopy(), nil
}
}
number, err := api._blockReader.HeaderNumber(ctx, tx, hash)
if err != nil {
return nil, err
}
if number == nil {
return nil, nil
}
return api._blockReader.Header(ctx, tx, hash, *number)
}
// checks the pruning state to see if we would hold information about this
// block in state history or not. Some strange issues arise getting account
// history for blocks that have been pruned away giving nonce too low errors
// etc. as red herrings
func (api *BaseAPI) checkPruneHistory(ctx context.Context, tx kv.Tx, block uint64) error {
return api.checkPruneField(tx, block, func(p *prune.Mode) prune.BlockAmount { return p.History }, "history is available")
}
// checkPruneBlocks gates on block-body availability rather than state history — use for RPCs
// that read block headers/bodies but do not require state (e.g. GetBlockByNumber, GetTransactionByHash).
func (api *BaseAPI) checkPruneBlocks(ctx context.Context, tx kv.Tx, block uint64) error {
return api.checkPruneField(tx, block, func(p *prune.Mode) prune.BlockAmount { return p.Blocks }, "blocks are available")
}
func (api *BaseAPI) checkPruneField(tx kv.Tx, block uint64, field func(*prune.Mode) prune.BlockAmount, available string) error {
p, err := api.pruneMode(tx)
if err != nil {
return err
}
if p == nil {
return nil
}
amount := field(p)
if !amount.Enabled() {
return nil
}
latest, err := rpchelper.GetLatestBlockNumber(tx)
if err != nil {
return err
}
if block < amount.PruneTo(latest) {
return fmt.Errorf("%w: requested block %d, %s from block %d", state.PrunedError, block, available, amount.PruneTo(latest))
}
return nil
}
// checkReceiptsAvailable checks if receipts are available for the given block.
// In case --prune.include-receipts which makes all historical receipts available even when state history is pruned.
func (api *BaseAPI) checkReceiptsAvailable(ctx context.Context, tx kv.Tx, block uint64) error {
persistReceipts, err := kvcfg.PersistReceipts.Enabled(tx)
if err != nil {
return err
}
if persistReceipts {
return nil
}
return api.checkPruneHistory(ctx, tx, block)
}
func (api *BaseAPI) pruneMode(tx kv.Tx) (*prune.Mode, error) {
p := api._pruneMode.Load()
if p != nil {
return p, nil
}
mode, err := prune.Get(tx)
if err != nil {
return nil, err
}
api._pruneMode.Store(&mode)
return &mode, nil
}
// commitmentHistoryEnabled returns whether --prune.include-commitment-history was set at node
// startup. The flag is written once by checkAndSetCommitmentHistoryFlag and never changed, so
// the result is cached after the first successful read.
// Unlike pruneMode, false is not cached when the DB key is absent: during the brief boot window
// before checkAndSetCommitmentHistoryFlag runs the key may not exist yet, and caching false
// would shadow a subsequent true write. Each request during that window pays one DB lookup.
func (api *BaseAPI) commitmentHistoryEnabled(tx kv.Tx) (bool, error) {
if p := api._commitmentHistoryEnabled.Load(); p != nil {
return *p, nil
}
enabled, ok, err := rawdb.ReadDBCommitmentHistoryEnabled(tx)
if err != nil {
return false, err
}
if ok {
api._commitmentHistoryEnabled.Store(&enabled)
}
return enabled, nil
}
type bridgeReader interface {
Events(ctx context.Context, blockHash common.Hash, blockNum uint64) ([]*types.Message, error)
EventTxnLookup(ctx context.Context, borTxHash common.Hash) (uint64, bool, error)
}
// APIImpl is implementation of the EthAPI interface based on remote Db access
type APIImpl struct {
*BaseAPI
ethBackend rpchelper.ApiBackend
txPool txpoolproto.TxpoolClient
mining txpoolproto.MiningClient
gasCache *GasPriceCache
feeHistoryCache *gasprice.FeeHistoryCache
db kv.TemporalRoDB
GasCap uint64
FeeCap float64
ReturnDataLimit int
AllowUnprotectedTxs bool
MaxGetProofRewindBlockCount int
SubscribeLogsChannelSize int
RpcTxSyncDefaultTimeout time.Duration
RpcTxSyncMaxTimeout time.Duration
logger log.Logger
}
// NewEthAPI returns APIImpl instance
func NewEthAPI(base *BaseAPI, db kv.TemporalRoDB, eth rpchelper.ApiBackend, txPool txpoolproto.TxpoolClient, mining txpoolproto.MiningClient, cfg *rpccfg.EthApiConfig, logger log.Logger) *APIImpl {
gascap := cfg.GasCap
if gascap == 0 {
gascap = uint64(math.MaxUint64 / 2)
}
return &APIImpl{
BaseAPI: base,
db: db,
ethBackend: eth,
txPool: txPool,
mining: mining,
gasCache: NewGasPriceCache(),
feeHistoryCache: gasprice.NewFeeHistoryCache(),
GasCap: gascap,
FeeCap: cfg.FeeCap,
AllowUnprotectedTxs: cfg.AllowUnprotectedTxs,
ReturnDataLimit: cfg.ReturnDataLimit,
MaxGetProofRewindBlockCount: cfg.MaxGetProofRewindBlockCount,
SubscribeLogsChannelSize: cfg.SubscribeLogsChannelSize,
RpcTxSyncDefaultTimeout: cfg.RpcTxSyncDefaultTimeout,
RpcTxSyncMaxTimeout: cfg.RpcTxSyncMaxTimeout,
logger: logger,
}
}
// newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation
func newRPCPendingTransaction(txn types.Transaction, current *types.Header, config *chain.Config) *ethapi.RPCTransaction {
var (
baseFee *uint256.Int
blockTime = uint64(0)
)
if current != nil {
baseFee = misc.CalcBaseFee(config, current)
blockTime = current.Time
}
return ethapi.NewRPCTransaction(txn, common.Hash{}, blockTime, 0, 0, baseFee)
}
// newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index.
func newRPCRawTransactionFromBlockIndex(b *types.Block, index uint64) (hexutil.Bytes, error) {
txs := b.Transactions()
if index >= uint64(len(txs)) {
return nil, nil
}
var buf bytes.Buffer
err := txs[index].MarshalBinary(&buf)
return buf.Bytes(), err
}
type GasPriceCache struct {
latestPrice *uint256.Int
latestHash common.Hash
mtx sync.Mutex
}
func NewGasPriceCache() *GasPriceCache {
return &GasPriceCache{
latestPrice: uint256.NewInt(common.GWei / 1000),
}
}
func (c *GasPriceCache) GetLatest() (common.Hash, *uint256.Int) {
var hash common.Hash
var price *uint256.Int
c.mtx.Lock()
hash = c.latestHash
price = c.latestPrice
c.mtx.Unlock()
return hash, price
}
func (c *GasPriceCache) SetLatest(hash common.Hash, price *uint256.Int) {
c.mtx.Lock()
c.latestPrice = price
c.latestHash = hash
c.mtx.Unlock()
}