Skip to content

Commit 6f78917

Browse files
FletcherManniczyNicholas Zhaofjlahmetavc
authored
Improve rpc(merge related commits from official ethereum) (scroll-tech#42)
* rpc: improve error codes for internal server errors (ethereum#25678) This changes the error code returned by the RPC server in certain situations: - handler panic: code -32603 - result marshaling error: code -32603 - attempt to subscribe via HTTP: code -32001 In all of the above cases, the server previously returned the default error code -32000. Co-authored-by: Nicholas Zhao <nicholas.zhao@gmail.com> Co-authored-by: Felix Lange <fjl@twurst.com> * rpc: add PeerInfo (ethereum#24255) This replaces the sketchy and undocumented string context keys for HTTP requests with a defined interface. Using string keys with context is discouraged because they may clash with keys created by other packages. We added these keys to make connection metadata available in the signer, so this change also updates signer/core to use the new PeerInfo API. * graphql: add query timeout (ethereum#26116) This PR adds a 60 second timeout to graphql queries. * graphql, node, rpc: improve HTTP write timeout handling (ethereum#25457) Here we add special handling for sending an error response when the write timeout of the HTTP server is just about to expire. This is surprisingly difficult to get right, since is must be ensured that all output is fully flushed in time, which needs support from multiple levels of the RPC handler stack: The timeout response can't use chunked transfer-encoding because there is no way to write the final terminating chunk. net/http writes it when the topmost handler returns, but the timeout will already be over by the time that happens. We decided to disable chunked encoding by setting content-length explicitly. Gzip compression must also be disabled for timeout responses because we don't know the true content-length before compressing all output, i.e. compression would reintroduce chunked transfer-encoding. * eth/filters, eth/tracers: add request cancellation checks (ethereum#26320) This ensures that RPC method handlers will react to a timeout or cancelled request soon after the event occurs. Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com> * rpc: add limit for batch request items and response size (ethereum#26681) This PR adds server-side limits for JSON-RPC batch requests. Before this change, batches were limited only by processing time. The server would pick calls from the batch and answer them until the response timeout occurred, then stop processing the remaining batch items. Here, we are adding two additional limits which can be configured: - the 'item limit': batches can have at most N items - the 'response size limit': batches can contain at most X response bytes These limits are optional in package rpc. In Geth, we set a default limit of 1000 items and 25MB response size. When a batch goes over the limit, an error response is returned to the client. However, doing this correctly isn't always possible. In JSON-RPC, only method calls with a valid `id` can be responded to. Since batches may also contain non-call messages or notifications, the best effort thing we can do to report an error with the batch itself is reporting the limit violation as an error for the first method call in the batch. If a batch is too large, but contains only notifications and responses, the error will be reported with a null `id`. The RPC client was also changed so it can deal with errors resulting from too large batches. An older client connected to the server code in this PR could get stuck until the request timeout occurred when the batch is too large. **Upgrading to a version of the RPC client containing this change is strongly recommended to avoid timeout issues.** For some weird reason, when writing the original client implementation, @fjl worked off of the assumption that responses could be distributed across batches arbitrarily. So for a batch request containing requests `[A B C]`, the server could respond with `[A B C]` but also with `[A B] [C]` or even `[A] [B] [C]` and it wouldn't make a difference to the client. So in the implementation of BatchCallContext, the client waited for all requests in the batch individually. If the server didn't respond to some of the requests in the batch, the client would eventually just time out (if a context was used). With the addition of batch limits into the server, we anticipate that people will hit this kind of error way more often. To handle this properly, the client now waits for a single response batch and expects it to contain all responses to the requests. --------- Co-authored-by: Felix Lange <fjl@twurst.com> Co-authored-by: Martin Holst Swende <martin@swende.se> * format * ethereum, ethclient: add FeeHistory support (ethereum#25403) Co-authored-by: Felix Lange <fjl@twurst.com> * internal/ethapi: return error when requesting invalid trie key (ethereum#25762) This change makes eth_getProof and eth_getStorageAt return an error when the argument contains invalid hex in storage keys. Co-authored-by: Felix Lange <fjl@twurst.com> * internal/ethapi: handle odd length hex in decodeHash (ethereum#25883) This change adds zero-padding (prefix) of odd nibbles in the decodeHash function. Co-authored-by: ty <ty@oncoder.com> * eth/filters, ethclient/gethclient: add fullTx option to pending tx filter (ethereum#25186) This PR adds a way to subscribe to the _full_ pending transactions, as opposed to just being notified about hashes. In use cases where client subscribes to newPendingTransactions and gets txhashes only to then request the actual transaction, the caller can now shortcut that flow and obtain the transactions directly. Co-authored-by: Felix Lange <fjl@twurst.com> * graphql: check header first in blocks query (ethereum#24190) Fixes ethereum#24167 New behaviour is that the endpoint returns results only for available blocks without returning an error when it doesn't find a block. Note we skip any block after a non-existent block. This adds a header fetch for every block in range (even if header is not needed). Alternatively, we could do the check in every field's resolver method to avoid this overhead. * graphql: embed *Resolver instead of backend interface (ethereum#25468) This creates some infrastructure to share resources between graphql API objects. * eth/filters: fix getLogs for pending block (ethereum#24949) * eth/filters: fix pending for getLogs * add pending method to test backend * fix block range validation * eth/filters: add global block logs cache (ethereum#25459) This adds a cache for block logs which is shared by all filters. The cache size of is configurable using the `--cache.blocklogs` flag. Co-authored-by: Felix Lange <fjl@twurst.com> * eth/filters: send rpctransactions in pending-subscription (ethereum#26126) This PR changes the pending tx subscription to return RPCTransaction types instead of normal Transaction objects. This will fix the inconsistencies with other tx returning API methods (i.e. getTransactionByHash), and also fill in the sender value for the tx. co-authored by @s1na * rpc: fix unmarshaling of null result in CallContext (ethereum#26723) The change fixes unmarshaling of JSON null results into json.RawMessage. --------- Co-authored-by: Jason Yuan <jason.yuan@curvegrid.com> Co-authored-by: Jason Yuan <jason.yuan869@gmail.com> * eth/filters: fix a breaking change and return rpctransaction (ethereum#26757) * eth/filters: fix a breaking change and return rpctransaction * eth/filters: fix test cases --------- Co-authored-by: Catror <me@catror.com> --------- Co-authored-by: Nicholas <nicholas.zhaoyu@gmail.com> Co-authored-by: Nicholas Zhao <nicholas.zhao@gmail.com> Co-authored-by: Felix Lange <fjl@twurst.com> Co-authored-by: Ahmet Avci <ahmetabdullahavci07@gmail.com> Co-authored-by: Sina Mahmoodi <1591639+s1na@users.noreply.github.com> Co-authored-by: Sina Mahmoodi <itz.s1na@gmail.com> Co-authored-by: mmsqe <mavis@crypto.com> Co-authored-by: Martin Holst Swende <martin@swende.se> Co-authored-by: lightclient <14004106+lightclient@users.noreply.github.com> Co-authored-by: TY <45994721+tylerK1294@users.noreply.github.com> Co-authored-by: ty <ty@oncoder.com> Co-authored-by: lmittmann <lmittmann@users.noreply.github.com> Co-authored-by: Jason Yuan <jason.yuan@curvegrid.com> Co-authored-by: Jason Yuan <jason.yuan869@gmail.com> Co-authored-by: Yier <90763233+yierx@users.noreply.github.com> Co-authored-by: Catror <me@catror.com>
1 parent 4d3749c commit 6f78917

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

61 files changed

+2411
-750
lines changed

accounts/abi/bind/backends/simulated.go

Lines changed: 35 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,12 @@ type SimulatedBackend struct {
6767

6868
consensus consensus.Engine
6969

70-
mu sync.Mutex
71-
pendingBlock *types.Block // Currently pending block that will be imported on request
72-
pendingState *state.StateDB // Currently pending state that will be the active on request
73-
74-
events *filters.EventSystem // Event system for filtering log events live
70+
mu sync.Mutex
71+
pendingBlock *types.Block // Currently pending block that will be imported on request
72+
pendingState *state.StateDB // Currently pending state that will be the active on request
73+
pendingReceipts types.Receipts // Currently receipts for the pending block
74+
events *filters.EventSystem // for filtering log events live
75+
filterSystem *filters.FilterSystem // for filtering database logs
7576

7677
config *params.ChainConfig
7778
}
@@ -88,8 +89,12 @@ func NewSimulatedBackendWithDatabase(database ethdb.Database, alloc core.Genesis
8889
database: database,
8990
blockchain: blockchain,
9091
config: genesis.Config,
91-
events: filters.NewEventSystem(&filterBackend{database, blockchain}, false),
9292
}
93+
94+
filterBackend := &filterBackend{database, blockchain, backend}
95+
backend.filterSystem = filters.NewFilterSystem(filterBackend, filters.Config{})
96+
backend.events = filters.NewEventSystem(backend.filterSystem, false)
97+
9398
backend.rollback(blockchain.CurrentBlock())
9499
return backend
95100
}
@@ -175,8 +180,8 @@ func NewSimulatedBackendWithOpts(opts ...SimulatedBackendOpt) *SimulatedBackend
175180
blockchain: blockchain,
176181
config: config.genesis.Config,
177182
consensus: config.consensus,
178-
events: filters.NewEventSystem(&filterBackend{config.database, blockchain}, false),
179183
}
184+
backend.events = filters.NewEventSystem(backend.filterSystem, false)
180185

181186
backend.rollback(blockchain.CurrentBlock())
182187
return backend
@@ -754,7 +759,7 @@ func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transa
754759
panic(fmt.Errorf("invalid transaction nonce: got %d, want %d", tx.Nonce(), nonce))
755760
}
756761
// Include tx in chain
757-
blocks, _ := core.GenerateChain(b.config, block, ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
762+
blocks, receipts := core.GenerateChain(b.config, block, ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) {
758763
for _, tx := range b.pendingBlock.Transactions() {
759764
block.AddTxWithChain(b.blockchain, tx)
760765
}
@@ -764,6 +769,7 @@ func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transa
764769

765770
b.pendingBlock = blocks[0]
766771
b.pendingState, _ = state.New(b.pendingBlock.Root(), stateDB.Database(), nil)
772+
b.pendingReceipts = receipts[0]
767773
return nil
768774
}
769775

@@ -775,7 +781,7 @@ func (b *SimulatedBackend) FilterLogs(ctx context.Context, query ethereum.Filter
775781
var filter *filters.Filter
776782
if query.BlockHash != nil {
777783
// Block filter requested, construct a single-shot filter
778-
filter = filters.NewBlockFilter(&filterBackend{b.database, b.blockchain}, *query.BlockHash, query.Addresses, query.Topics)
784+
filter = b.filterSystem.NewBlockFilter(*query.BlockHash, query.Addresses, query.Topics)
779785
} else {
780786
// Initialize unset filter boundaries to run from genesis to chain head
781787
from := int64(0)
@@ -787,7 +793,7 @@ func (b *SimulatedBackend) FilterLogs(ctx context.Context, query ethereum.Filter
787793
to = query.ToBlock.Int64()
788794
}
789795
// Construct the range filter
790-
filter = filters.NewRangeFilter(&filterBackend{b.database, b.blockchain}, from, to, query.Addresses, query.Topics)
796+
filter = b.filterSystem.NewRangeFilter(from, to, query.Addresses, query.Topics)
791797
}
792798
// Run the filter and return all the logs
793799
logs, err := filter.Logs(ctx)
@@ -909,11 +915,13 @@ func (m callMsg) IsL1MessageTx() bool { return false }
909915
// filterBackend implements filters.Backend to support filtering for logs without
910916
// taking bloom-bits acceleration structures into account.
911917
type filterBackend struct {
912-
db ethdb.Database
913-
bc *core.BlockChain
918+
db ethdb.Database
919+
bc *core.BlockChain
920+
backend *SimulatedBackend
914921
}
915922

916-
func (fb *filterBackend) ChainDb() ethdb.Database { return fb.db }
923+
func (fb *filterBackend) ChainDb() ethdb.Database { return fb.db }
924+
917925
func (fb *filterBackend) EventMux() *event.TypeMux { panic("not supported") }
918926

919927
func (fb *filterBackend) HeaderByNumber(ctx context.Context, block rpc.BlockNumber) (*types.Header, error) {
@@ -927,6 +935,10 @@ func (fb *filterBackend) HeaderByHash(ctx context.Context, hash common.Hash) (*t
927935
return fb.bc.GetHeaderByHash(hash), nil
928936
}
929937

938+
func (fb *filterBackend) PendingBlockAndReceipts() (*types.Block, types.Receipts) {
939+
return fb.backend.pendingBlock, fb.backend.pendingReceipts
940+
}
941+
930942
func (fb *filterBackend) GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error) {
931943
number := rawdb.ReadHeaderNumber(fb.db, hash)
932944
if number == nil {
@@ -935,19 +947,8 @@ func (fb *filterBackend) GetReceipts(ctx context.Context, hash common.Hash) (typ
935947
return rawdb.ReadReceipts(fb.db, hash, *number, fb.bc.Config()), nil
936948
}
937949

938-
func (fb *filterBackend) GetLogs(ctx context.Context, hash common.Hash) ([][]*types.Log, error) {
939-
number := rawdb.ReadHeaderNumber(fb.db, hash)
940-
if number == nil {
941-
return nil, nil
942-
}
943-
receipts := rawdb.ReadReceipts(fb.db, hash, *number, fb.bc.Config())
944-
if receipts == nil {
945-
return nil, nil
946-
}
947-
logs := make([][]*types.Log, len(receipts))
948-
for i, receipt := range receipts {
949-
logs[i] = receipt.Logs
950-
}
950+
func (fb *filterBackend) GetLogs(ctx context.Context, hash common.Hash, number uint64) ([][]*types.Log, error) {
951+
logs := rawdb.ReadLogs(fb.db, hash, number, fb.bc.Config())
951952
return logs, nil
952953
}
953954

@@ -977,6 +978,14 @@ func (fb *filterBackend) ServiceFilter(ctx context.Context, ms *bloombits.Matche
977978
panic("not supported")
978979
}
979980

981+
func (fb *filterBackend) ChainConfig() *params.ChainConfig {
982+
panic("not supported")
983+
}
984+
985+
func (fb *filterBackend) CurrentHeader() *types.Header {
986+
panic("not supported")
987+
}
988+
980989
func nullSubscription() event.Subscription {
981990
return event.NewSubscription(func(quit <-chan struct{}) error {
982991
<-quit

cmd/clef/main.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -658,6 +658,7 @@ func signer(c *cli.Context) error {
658658
cors := utils.SplitAndTrim(c.GlobalString(utils.HTTPCORSDomainFlag.Name))
659659

660660
srv := rpc.NewServer()
661+
srv.SetBatchLimits(node.DefaultConfig.BatchRequestLimit, node.DefaultConfig.BatchResponseMaxSize)
661662
err := node.RegisterApis(rpcAPI, []string{"account"}, srv, false)
662663
if err != nil {
663664
utils.Fatalf("Could not register API: %w", err)

cmd/geth/config.go

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -162,10 +162,14 @@ func makeFullNode(ctx *cli.Context) (*node.Node, ethapi.Backend) {
162162
}
163163
backend, _ := utils.RegisterEthService(stack, &cfg.Eth)
164164

165-
// Configure GraphQL if requested
166-
if ctx.GlobalIsSet(utils.GraphQLEnabledFlag.Name) {
167-
utils.RegisterGraphQLService(stack, backend, cfg.Node)
165+
// Configure log filter RPC API.
166+
filterSystem := utils.RegisterFilterAPI(stack, backend, &cfg.Eth)
167+
168+
// Configure GraphQL if requested.
169+
if ctx.IsSet(utils.GraphQLEnabledFlag.Name) {
170+
utils.RegisterGraphQLService(stack, backend, filterSystem, &cfg.Node)
168171
}
172+
169173
// Add the Ethereum Stats daemon if requested.
170174
if cfg.Ethstats.URL != "" {
171175
utils.RegisterEthStatsService(stack, backend, cfg.Ethstats.URL)

cmd/geth/main.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,8 @@ var (
117117
utils.CacheSnapshotFlag,
118118
utils.CacheNoPrefetchFlag,
119119
utils.CachePreimagesFlag,
120+
utils.CacheLogSizeFlag,
121+
utils.FDLimitFlag,
120122
utils.ListenPortFlag,
121123
utils.MaxPeersFlag,
122124
utils.MaxPendingPeersFlag,
@@ -193,6 +195,8 @@ var (
193195
utils.RPCGlobalTxFeeCapFlag,
194196
utils.AllowUnprotectedTxs,
195197
utils.MaxBlockRangeFlag,
198+
utils.BatchRequestLimit,
199+
utils.BatchResponseMaxSize,
196200
}
197201

198202
metricsFlags = []cli.Flag{

cmd/utils/flags.go

Lines changed: 54 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ package utils
2020
import (
2121
"crypto/ecdsa"
2222
"fmt"
23+
"github.com/scroll-tech/go-ethereum/eth/filters"
24+
"github.com/scroll-tech/go-ethereum/rpc"
2325
"io"
2426
"io/ioutil"
2527
"math"
@@ -447,6 +449,16 @@ var (
447449
Name: "cache.preimages",
448450
Usage: "Enable recording the SHA3/keccak preimages of trie keys",
449451
}
452+
CacheLogSizeFlag = &cli.IntFlag{
453+
Name: "cache.blocklogs",
454+
Usage: "Size (in number of blocks) of the log cache for filtering",
455+
Value: ethconfig.Defaults.FilterLogCacheSize,
456+
}
457+
FDLimitFlag = &cli.IntFlag{
458+
Name: "fdlimit",
459+
Usage: "Raise the open file descriptor resource limit (default = system fd limit)",
460+
}
461+
450462
// Miner settings
451463
MiningEnabledFlag = cli.BoolFlag{
452464
Name: "mine",
@@ -650,10 +662,21 @@ var (
650662
Name: "preload",
651663
Usage: "Comma separated list of JavaScript files to preload into the console",
652664
}
653-
AllowUnprotectedTxs = cli.BoolFlag{
665+
AllowUnprotectedTxs = &cli.BoolFlag{
654666
Name: "rpc.allow-unprotected-txs",
655667
Usage: "Allow for unprotected (non EIP155 signed) transactions to be submitted via RPC",
656668
}
669+
BatchRequestLimit = &cli.IntFlag{
670+
Name: "rpc.batch-request-limit",
671+
Usage: "Maximum number of requests in a batch",
672+
Value: node.DefaultConfig.BatchRequestLimit,
673+
}
674+
BatchResponseMaxSize = &cli.IntFlag{
675+
Name: "rpc.batch-response-max-size",
676+
Usage: "Maximum number of bytes returned from a batched call",
677+
Value: node.DefaultConfig.BatchResponseMaxSize,
678+
//>>>>>>> f3314bb6d (rpc: add limit for batch request items and response size (#26681))
679+
}
657680

658681
// Network Settings
659682
MaxPeersFlag = cli.IntFlag{
@@ -1061,6 +1084,14 @@ func setHTTP(ctx *cli.Context, cfg *node.Config) {
10611084
if ctx.GlobalIsSet(AllowUnprotectedTxs.Name) {
10621085
cfg.AllowUnprotectedTxs = ctx.GlobalBool(AllowUnprotectedTxs.Name)
10631086
}
1087+
1088+
if ctx.IsSet(BatchRequestLimit.Name) {
1089+
cfg.BatchRequestLimit = ctx.Int(BatchRequestLimit.Name)
1090+
}
1091+
1092+
if ctx.IsSet(BatchResponseMaxSize.Name) {
1093+
cfg.BatchResponseMaxSize = ctx.Int(BatchResponseMaxSize.Name)
1094+
}
10641095
}
10651096

10661097
// setGraphQL creates the GraphQL listener interface string from the set
@@ -1685,7 +1716,10 @@ func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *ethconfig.Config) {
16851716
if ctx.GlobalIsSet(CacheFlag.Name) || ctx.GlobalIsSet(CacheSnapshotFlag.Name) {
16861717
cfg.SnapshotCache = ctx.GlobalInt(CacheFlag.Name) * ctx.GlobalInt(CacheSnapshotFlag.Name) / 100
16871718
}
1688-
if !ctx.GlobalBool(SnapshotFlag.Name) {
1719+
if ctx.IsSet(CacheLogSizeFlag.Name) {
1720+
cfg.FilterLogCacheSize = ctx.Int(CacheLogSizeFlag.Name)
1721+
}
1722+
if !ctx.Bool(SnapshotFlag.Name) {
16891723
// If snap-sync is requested, this flag is also required
16901724
if cfg.SyncMode == downloader.SnapSync {
16911725
log.Info("Snap sync requested, enabling --snapshot")
@@ -1893,21 +1927,34 @@ func RegisterEthService(stack *node.Node, cfg *ethconfig.Config) (ethapi.Backend
18931927
return backend.APIBackend, backend
18941928
}
18951929

1896-
// RegisterEthStatsService configures the Ethereum Stats daemon and adds it to
1897-
// the given node.
1930+
// RegisterEthStatsService configures the Ethereum Stats daemon and adds it to the node.
18981931
func RegisterEthStatsService(stack *node.Node, backend ethapi.Backend, url string) {
18991932
if err := ethstats.New(stack, backend, backend.Engine(), url); err != nil {
19001933
Fatalf("Failed to register the Ethereum Stats service: %v", err)
19011934
}
19021935
}
19031936

1904-
// RegisterGraphQLService is a utility function to construct a new service and register it against a node.
1905-
func RegisterGraphQLService(stack *node.Node, backend ethapi.Backend, cfg node.Config) {
1906-
if err := graphql.New(stack, backend, cfg.GraphQLCors, cfg.GraphQLVirtualHosts); err != nil {
1937+
// RegisterGraphQLService adds the GraphQL API to the node.
1938+
func RegisterGraphQLService(stack *node.Node, backend ethapi.Backend, filterSystem *filters.FilterSystem, cfg *node.Config) {
1939+
err := graphql.New(stack, backend, filterSystem, cfg.GraphQLCors, cfg.GraphQLVirtualHosts)
1940+
if err != nil {
19071941
Fatalf("Failed to register the GraphQL service: %v", err)
19081942
}
19091943
}
19101944

1945+
// RegisterFilterAPI adds the eth log filtering RPC API to the node.
1946+
func RegisterFilterAPI(stack *node.Node, backend ethapi.Backend, ethcfg *ethconfig.Config) *filters.FilterSystem {
1947+
isLightClient := ethcfg.SyncMode == downloader.LightSync
1948+
filterSystem := filters.NewFilterSystem(backend, filters.Config{
1949+
LogCacheSize: ethcfg.FilterLogCacheSize,
1950+
})
1951+
stack.RegisterAPIs([]rpc.API{{
1952+
Namespace: "eth",
1953+
Service: filters.NewFilterAPI(filterSystem, isLightClient, ethcfg.MaxBlockRange),
1954+
}})
1955+
return filterSystem
1956+
}
1957+
19111958
func SetupMetrics(ctx *cli.Context) {
19121959
if metrics.Enabled {
19131960
log.Info("Enabling metrics collection")

eth/api.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -427,13 +427,13 @@ type storageEntry struct {
427427
}
428428

429429
// StorageRangeAt returns the storage at the given block height and transaction index.
430-
func (api *PrivateDebugAPI) StorageRangeAt(blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) {
430+
func (api *PrivateDebugAPI) StorageRangeAt(ctx context.Context, blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) {
431431
// Retrieve the block
432432
block := api.eth.blockchain.GetBlockByHash(blockHash)
433433
if block == nil {
434434
return StorageRangeResult{}, fmt.Errorf("block %#x not found", blockHash)
435435
}
436-
_, _, statedb, err := api.eth.stateAtTransaction(block, txIndex, 0)
436+
_, _, statedb, err := api.eth.stateAtTransaction(ctx, block, txIndex, 0)
437437
if err != nil {
438438
return StorageRangeResult{}, err
439439
}

eth/api_backend.go

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -185,17 +185,8 @@ func (b *EthAPIBackend) GetReceipts(ctx context.Context, hash common.Hash) (type
185185
return b.eth.blockchain.GetReceiptsByHash(hash), nil
186186
}
187187

188-
func (b *EthAPIBackend) GetLogs(ctx context.Context, hash common.Hash) ([][]*types.Log, error) {
189-
db := b.eth.ChainDb()
190-
number := rawdb.ReadHeaderNumber(db, hash)
191-
if number == nil {
192-
return nil, errors.New("failed to get block number from hash")
193-
}
194-
logs := rawdb.ReadLogs(db, hash, *number, b.eth.blockchain.Config())
195-
if logs == nil {
196-
return nil, errors.New("failed to get logs for block")
197-
}
198-
return logs, nil
188+
func (b *EthAPIBackend) GetLogs(ctx context.Context, hash common.Hash, number uint64) ([][]*types.Log, error) {
189+
return rawdb.ReadLogs(b.eth.chainDb, hash, number, b.ChainConfig()), nil
199190
}
200191

201192
func (b *EthAPIBackend) GetTd(ctx context.Context, hash common.Hash) *big.Int {
@@ -358,9 +349,9 @@ func (b *EthAPIBackend) StartMining(threads int) error {
358349
}
359350

360351
func (b *EthAPIBackend) StateAtBlock(ctx context.Context, block *types.Block, reexec uint64, base *state.StateDB, checkLive, preferDisk bool) (*state.StateDB, error) {
361-
return b.eth.stateAtBlock(block, reexec, base, checkLive, preferDisk)
352+
return b.eth.stateAtBlock(ctx, block, reexec, base, checkLive, preferDisk)
362353
}
363354

364355
func (b *EthAPIBackend) StateAtTransaction(ctx context.Context, block *types.Block, txIndex int, reexec uint64) (core.Message, vm.BlockContext, *state.StateDB, error) {
365-
return b.eth.stateAtTransaction(block, txIndex, reexec)
356+
return b.eth.stateAtTransaction(ctx, block, txIndex, reexec)
366357
}

eth/backend.go

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@ import (
3939
"github.com/scroll-tech/go-ethereum/core/vm"
4040
"github.com/scroll-tech/go-ethereum/eth/downloader"
4141
"github.com/scroll-tech/go-ethereum/eth/ethconfig"
42-
"github.com/scroll-tech/go-ethereum/eth/filters"
4342
"github.com/scroll-tech/go-ethereum/eth/gasprice"
4443
"github.com/scroll-tech/go-ethereum/eth/protocols/eth"
4544
"github.com/scroll-tech/go-ethereum/eth/protocols/snap"
@@ -320,11 +319,6 @@ func (s *Ethereum) APIs() []rpc.API {
320319
Version: "1.0",
321320
Service: NewPrivateMinerAPI(s),
322321
Public: false,
323-
}, {
324-
Namespace: "eth",
325-
Version: "1.0",
326-
Service: filters.NewPublicFilterAPI(s.APIBackend, false, 5*time.Minute, s.config.MaxBlockRange),
327-
Public: true,
328322
}, {
329323
Namespace: "admin",
330324
Version: "1.0",

eth/ethconfig/config.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ var Defaults = Config{
8383
TrieDirtyCache: 256,
8484
TrieTimeout: 60 * time.Minute,
8585
SnapshotCache: 102,
86+
FilterLogCacheSize: 32,
8687
Miner: miner.Config{
8788
GasCeil: 8000000,
8889
GasPrice: big.NewInt(params.GWei),
@@ -118,7 +119,7 @@ func init() {
118119
}
119120
}
120121

121-
//go:generate gencodec -type Config -formats toml -out gen_config.go
122+
//go:generate go run github.com/fjl/gencodec -type Config -formats toml -out gen_config.go
122123

123124
// Config contains configuration options for of the ETH and LES protocols.
124125
type Config struct {
@@ -171,6 +172,9 @@ type Config struct {
171172
SnapshotCache int
172173
Preimages bool
173174

175+
// This is the number of blocks for which logs will be cached in the filter system.
176+
FilterLogCacheSize int
177+
174178
// Mining options
175179
Miner miner.Config
176180

0 commit comments

Comments
 (0)