Skip to content

Commit adf130d

Browse files
authored
eth/tracers: move tracing APIs into eth/tracers (#22161)
This moves the tracing RPC API implementation to package eth/tracers. By doing so, package eth no longer depends on tracing and the duktape JS engine. The change also enables tracing using the light client. All tracing methods work with the light client, but it's a lot slower compared to using a full node.
1 parent 49cdcf5 commit adf130d

File tree

8 files changed

+1071
-322
lines changed

8 files changed

+1071
-322
lines changed

cmd/utils/flags.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ import (
4545
"github.com/ethereum/go-ethereum/eth"
4646
"github.com/ethereum/go-ethereum/eth/downloader"
4747
"github.com/ethereum/go-ethereum/eth/gasprice"
48+
"github.com/ethereum/go-ethereum/eth/tracers"
4849
"github.com/ethereum/go-ethereum/ethdb"
4950
"github.com/ethereum/go-ethereum/ethstats"
5051
"github.com/ethereum/go-ethereum/graphql"
@@ -1724,6 +1725,7 @@ func RegisterEthService(stack *node.Node, cfg *eth.Config) ethapi.Backend {
17241725
if err != nil {
17251726
Fatalf("Failed to register the Ethereum service: %v", err)
17261727
}
1728+
stack.RegisterAPIs(tracers.APIs(backend.ApiBackend))
17271729
return backend.ApiBackend
17281730
}
17291731
backend, err := eth.New(stack, cfg)
@@ -1736,6 +1738,7 @@ func RegisterEthService(stack *node.Node, cfg *eth.Config) ethapi.Backend {
17361738
Fatalf("Failed to create the LES server: %v", err)
17371739
}
17381740
}
1741+
stack.RegisterAPIs(tracers.APIs(backend.APIBackend))
17391742
return backend.APIBackend
17401743
}
17411744

eth/api.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -426,10 +426,11 @@ func (api *PrivateDebugAPI) StorageRangeAt(blockHash common.Hash, txIndex int, c
426426
if block == nil {
427427
return StorageRangeResult{}, fmt.Errorf("block %#x not found", blockHash)
428428
}
429-
_, _, statedb, err := api.computeTxEnv(block, txIndex, 0)
429+
_, _, statedb, release, err := api.eth.stateAtTransaction(block, txIndex, 0)
430430
if err != nil {
431431
return StorageRangeResult{}, err
432432
}
433+
defer release()
433434
st := statedb.StorageTrie(contractAddress)
434435
if st == nil {
435436
return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress)

eth/api_backend.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,3 +326,15 @@ func (b *EthAPIBackend) Miner() *miner.Miner {
326326
func (b *EthAPIBackend) StartMining(threads int) error {
327327
return b.eth.StartMining(threads)
328328
}
329+
330+
func (b *EthAPIBackend) StateAtBlock(ctx context.Context, block *types.Block, reexec uint64) (*state.StateDB, func(), error) {
331+
return b.eth.stateAtBlock(block, reexec)
332+
}
333+
334+
func (b *EthAPIBackend) StatesInRange(ctx context.Context, fromBlock *types.Block, toBlock *types.Block, reexec uint64) ([]*state.StateDB, func(), error) {
335+
return b.eth.statesInRange(fromBlock, toBlock, reexec)
336+
}
337+
338+
func (b *EthAPIBackend) StateAtTransaction(ctx context.Context, block *types.Block, txIndex int, reexec uint64) (core.Message, vm.BlockContext, *state.StateDB, func(), error) {
339+
return b.eth.stateAtTransaction(block, txIndex, reexec)
340+
}

eth/state_accessor.go

Lines changed: 230 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
1+
// Copyright 2021 The go-ethereum Authors
2+
// This file is part of the go-ethereum library.
3+
//
4+
// The go-ethereum library is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU Lesser General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// The go-ethereum library is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU Lesser General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU Lesser General Public License
15+
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16+
17+
package eth
18+
19+
import (
20+
"errors"
21+
"fmt"
22+
"time"
23+
24+
"github.com/ethereum/go-ethereum/common"
25+
"github.com/ethereum/go-ethereum/core"
26+
"github.com/ethereum/go-ethereum/core/state"
27+
"github.com/ethereum/go-ethereum/core/types"
28+
"github.com/ethereum/go-ethereum/core/vm"
29+
"github.com/ethereum/go-ethereum/log"
30+
"github.com/ethereum/go-ethereum/trie"
31+
)
32+
33+
// stateAtBlock retrieves the state database associated with a certain block.
34+
// If no state is locally available for the given block, a number of blocks are
35+
// attempted to be reexecuted to generate the desired state.
36+
func (eth *Ethereum) stateAtBlock(block *types.Block, reexec uint64) (statedb *state.StateDB, release func(), err error) {
37+
// If we have the state fully available, use that
38+
statedb, err = eth.blockchain.StateAt(block.Root())
39+
if err == nil {
40+
return statedb, func() {}, nil
41+
}
42+
// Otherwise try to reexec blocks until we find a state or reach our limit
43+
origin := block.NumberU64()
44+
database := state.NewDatabaseWithConfig(eth.chainDb, &trie.Config{Cache: 16, Preimages: true})
45+
46+
for i := uint64(0); i < reexec; i++ {
47+
if block.NumberU64() == 0 {
48+
return nil, nil, errors.New("genesis state is missing")
49+
}
50+
parent := eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
51+
if parent == nil {
52+
return nil, nil, fmt.Errorf("missing block %v %d", block.ParentHash(), block.NumberU64()-1)
53+
}
54+
block = parent
55+
56+
statedb, err = state.New(block.Root(), database, nil)
57+
if err == nil {
58+
break
59+
}
60+
}
61+
if err != nil {
62+
switch err.(type) {
63+
case *trie.MissingNodeError:
64+
return nil, nil, fmt.Errorf("required historical state unavailable (reexec=%d)", reexec)
65+
default:
66+
return nil, nil, err
67+
}
68+
}
69+
// State was available at historical point, regenerate
70+
var (
71+
start = time.Now()
72+
logged time.Time
73+
parent common.Hash
74+
)
75+
defer func() {
76+
if err != nil && parent != (common.Hash{}) {
77+
database.TrieDB().Dereference(parent)
78+
}
79+
}()
80+
for block.NumberU64() < origin {
81+
// Print progress logs if long enough time elapsed
82+
if time.Since(logged) > 8*time.Second {
83+
log.Info("Regenerating historical state", "block", block.NumberU64()+1, "target", origin, "remaining", origin-block.NumberU64()-1, "elapsed", time.Since(start))
84+
logged = time.Now()
85+
}
86+
// Retrieve the next block to regenerate and process it
87+
if block = eth.blockchain.GetBlockByNumber(block.NumberU64() + 1); block == nil {
88+
return nil, nil, fmt.Errorf("block #%d not found", block.NumberU64()+1)
89+
}
90+
_, _, _, err := eth.blockchain.Processor().Process(block, statedb, vm.Config{})
91+
if err != nil {
92+
return nil, nil, fmt.Errorf("processing block %d failed: %v", block.NumberU64(), err)
93+
}
94+
// Finalize the state so any modifications are written to the trie
95+
root, err := statedb.Commit(eth.blockchain.Config().IsEIP158(block.Number()))
96+
if err != nil {
97+
return nil, nil, err
98+
}
99+
statedb, err = state.New(root, database, nil)
100+
if err != nil {
101+
return nil, nil, fmt.Errorf("state reset after block %d failed: %v", block.NumberU64(), err)
102+
}
103+
database.TrieDB().Reference(root, common.Hash{})
104+
if parent != (common.Hash{}) {
105+
database.TrieDB().Dereference(parent)
106+
}
107+
parent = root
108+
}
109+
nodes, imgs := database.TrieDB().Size()
110+
log.Info("Historical state regenerated", "block", block.NumberU64(), "elapsed", time.Since(start), "nodes", nodes, "preimages", imgs)
111+
return statedb, func() { database.TrieDB().Dereference(parent) }, nil
112+
}
113+
114+
// statesInRange retrieves a batch of state databases associated with the specific
115+
// block ranges. If no state is locally available for the given range, a number of
116+
// blocks are attempted to be reexecuted to generate the ancestor state.
117+
func (eth *Ethereum) statesInRange(fromBlock, toBlock *types.Block, reexec uint64) (states []*state.StateDB, release func(), err error) {
118+
statedb, err := eth.blockchain.StateAt(fromBlock.Root())
119+
if err != nil {
120+
statedb, _, err = eth.stateAtBlock(fromBlock, reexec)
121+
}
122+
if err != nil {
123+
return nil, nil, err
124+
}
125+
states = append(states, statedb.Copy())
126+
127+
var (
128+
logged time.Time
129+
parent common.Hash
130+
start = time.Now()
131+
refs = []common.Hash{fromBlock.Root()}
132+
database = state.NewDatabaseWithConfig(eth.chainDb, &trie.Config{Cache: 16, Preimages: true})
133+
)
134+
// Release all resources(including the states referenced by `stateAtBlock`)
135+
// if error is returned.
136+
defer func() {
137+
if err != nil {
138+
for _, ref := range refs {
139+
database.TrieDB().Dereference(ref)
140+
}
141+
}
142+
}()
143+
for i := fromBlock.NumberU64() + 1; i <= toBlock.NumberU64(); i++ {
144+
// Print progress logs if long enough time elapsed
145+
if time.Since(logged) > 8*time.Second {
146+
logged = time.Now()
147+
log.Info("Regenerating historical state", "block", i, "target", fromBlock.NumberU64(), "remaining", toBlock.NumberU64()-i, "elapsed", time.Since(start))
148+
}
149+
// Retrieve the next block to regenerate and process it
150+
block := eth.blockchain.GetBlockByNumber(i)
151+
if block == nil {
152+
return nil, nil, fmt.Errorf("block #%d not found", i)
153+
}
154+
_, _, _, err := eth.blockchain.Processor().Process(block, statedb, vm.Config{})
155+
if err != nil {
156+
return nil, nil, fmt.Errorf("processing block %d failed: %v", block.NumberU64(), err)
157+
}
158+
// Finalize the state so any modifications are written to the trie
159+
root, err := statedb.Commit(eth.blockchain.Config().IsEIP158(block.Number()))
160+
if err != nil {
161+
return nil, nil, err
162+
}
163+
statedb, err := eth.blockchain.StateAt(root)
164+
if err != nil {
165+
return nil, nil, fmt.Errorf("state reset after block %d failed: %v", block.NumberU64(), err)
166+
}
167+
states = append(states, statedb.Copy())
168+
169+
// Reference the trie twice, once for us, once for the tracer
170+
database.TrieDB().Reference(root, common.Hash{})
171+
database.TrieDB().Reference(root, common.Hash{})
172+
refs = append(refs, root)
173+
174+
// Dereference all past tries we ourselves are done working with
175+
if parent != (common.Hash{}) {
176+
database.TrieDB().Dereference(parent)
177+
}
178+
parent = root
179+
}
180+
// release is handler to release all states referenced, including
181+
// the one referenced in `stateAtBlock`.
182+
release = func() {
183+
for _, ref := range refs {
184+
database.TrieDB().Dereference(ref)
185+
}
186+
}
187+
return states, release, nil
188+
}
189+
190+
// stateAtTransaction returns the execution environment of a certain transaction.
191+
func (eth *Ethereum) stateAtTransaction(block *types.Block, txIndex int, reexec uint64) (core.Message, vm.BlockContext, *state.StateDB, func(), error) {
192+
// Short circuit if it's genesis block.
193+
if block.NumberU64() == 0 {
194+
return nil, vm.BlockContext{}, nil, nil, errors.New("no transaction in genesis")
195+
}
196+
// Create the parent state database
197+
parent := eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
198+
if parent == nil {
199+
return nil, vm.BlockContext{}, nil, nil, fmt.Errorf("parent %#x not found", block.ParentHash())
200+
}
201+
statedb, release, err := eth.stateAtBlock(parent, reexec)
202+
if err != nil {
203+
return nil, vm.BlockContext{}, nil, nil, err
204+
}
205+
if txIndex == 0 && len(block.Transactions()) == 0 {
206+
return nil, vm.BlockContext{}, statedb, release, nil
207+
}
208+
// Recompute transactions up to the target index.
209+
signer := types.MakeSigner(eth.blockchain.Config(), block.Number())
210+
for idx, tx := range block.Transactions() {
211+
// Assemble the transaction call message and return if the requested offset
212+
msg, _ := tx.AsMessage(signer)
213+
txContext := core.NewEVMTxContext(msg)
214+
context := core.NewEVMBlockContext(block.Header(), eth.blockchain, nil)
215+
if idx == txIndex {
216+
return msg, context, statedb, release, nil
217+
}
218+
// Not yet the searched for transaction, execute on top of the current state
219+
vmenv := vm.NewEVM(context, txContext, statedb, eth.blockchain.Config(), vm.Config{})
220+
if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
221+
release()
222+
return nil, vm.BlockContext{}, nil, nil, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err)
223+
}
224+
// Ensure any modifications are committed to the state
225+
// Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
226+
statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
227+
}
228+
release()
229+
return nil, vm.BlockContext{}, nil, nil, fmt.Errorf("transaction index %d out of range for block %#x", txIndex, block.Hash())
230+
}

0 commit comments

Comments
 (0)