diff --git a/cmd/geth/main.go b/cmd/geth/main.go
index 76d6427fab..2d01e51eb9 100644
--- a/cmd/geth/main.go
+++ b/cmd/geth/main.go
@@ -201,6 +201,11 @@ var (
utils.MetricsInfluxDBBucketFlag,
utils.MetricsInfluxDBOrganizationFlag,
}
+
+ txTraceFlags = []cli.Flag{
+ utils.TxTraceEnabledFlag,
+ utils.TxTraceStoreFlag,
+ }
)
func init() {
@@ -246,7 +251,8 @@ func init() {
rpcFlags,
consoleFlags,
debug.Flags,
- metricsFlags)
+ metricsFlags,
+ txTraceFlags)
app.Before = func(ctx *cli.Context) error {
return debug.Setup(ctx)
diff --git a/cmd/geth/usage.go b/cmd/geth/usage.go
index 56a3d053d6..74c5643013 100644
--- a/cmd/geth/usage.go
+++ b/cmd/geth/usage.go
@@ -215,6 +215,10 @@ var AppHelpFlagGroups = []flags.FlagGroup{
Name: "METRICS AND STATS",
Flags: metricsFlags,
},
+ {
+ Name: "TRANSACTION TRACING",
+ Flags: txTraceFlags,
+ },
{
Name: "ALIASED (deprecated)",
Flags: []cli.Flag{
diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go
index c80de61104..b9eb87a8fb 100644
--- a/cmd/utils/flags.go
+++ b/cmd/utils/flags.go
@@ -67,6 +67,7 @@ import (
"github.com/ethereum/go-ethereum/p2p/nat"
"github.com/ethereum/go-ethereum/p2p/netutil"
"github.com/ethereum/go-ethereum/params"
+ "github.com/ethereum/go-ethereum/txtrace"
pcsclite "github.com/gballet/go-libpcsclite"
gopsutil "github.com/shirou/gopsutil/mem"
"gopkg.in/urfave/cli.v1"
@@ -834,6 +835,16 @@ var (
Usage: "InfluxDB organization name (v2 only)",
Value: metrics.DefaultConfig.InfluxDBOrganization,
}
+
+ // TxTraceEnabledFlag ...
+ TxTraceEnabledFlag = cli.BoolFlag{
+ Name: "txtrace",
+ Usage: "Enable transaction trace while evm processing, default result is openEthereum style",
+ }
+ TxTraceStoreFlag = DirectoryFlag{
+ Name: "txtrace.store",
+ Usage: "Data directory for store transaction trace result (default = inside datadir)",
+ }
)
var (
@@ -1421,6 +1432,15 @@ func setGPO(ctx *cli.Context, cfg *gasprice.Config, light bool) {
}
}
+func setTxTrace(ctx *cli.Context, cfg *txtrace.Config) {
+ if ctx.GlobalIsSet(TxTraceEnabledFlag.Name) {
+ cfg.Enabled = ctx.GlobalBool(TxTraceEnabledFlag.Name)
+ }
+ if ctx.GlobalIsSet(TxTraceStoreFlag.Name) {
+ cfg.StoreDir = ctx.GlobalString(TxTraceStoreFlag.Name)
+ }
+}
+
func setTxPool(ctx *cli.Context, cfg *core.TxPoolConfig) {
if ctx.GlobalIsSet(TxPoolLocalsFlag.Name) {
locals := strings.Split(ctx.GlobalString(TxPoolLocalsFlag.Name), ",")
@@ -1613,6 +1633,7 @@ func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *ethconfig.Config) {
setMiner(ctx, &cfg.Miner)
setRequiredBlocks(ctx, cfg)
setLes(ctx, cfg)
+ setTxTrace(ctx, &cfg.TxTrace)
// Cap the cache allowance and tune the garbage collector
mem, err := gopsutil.VirtualMemory()
diff --git a/core/blockchain.go b/core/blockchain.go
index 366782800d..c615c88461 100644
--- a/core/blockchain.go
+++ b/core/blockchain.go
@@ -43,7 +43,10 @@ import (
"github.com/ethereum/go-ethereum/metrics"
"github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/trie"
+ "github.com/ethereum/go-ethereum/txtrace"
lru "github.com/hashicorp/golang-lru"
+
+ txtracelib "github.com/DeBankDeFi/etherlib/pkg/txtracev2"
)
var (
@@ -171,8 +174,11 @@ var defaultCacheConfig = &CacheConfig{
// included in the canonical one where as GetBlockByNumber always represents the
// canonical chain.
type BlockChain struct {
- chainConfig *params.ChainConfig // Chain & network configuration
- cacheConfig *CacheConfig // Cache configuration for pruning
+ chainConfig *params.ChainConfig // Chain & network configuration
+ cacheConfig *CacheConfig // Cache configuration for pruning
+ txTraceConfig *txtrace.Config
+ // txtraceStore
+ txTraceStore txtracelib.Store
db ethdb.Database // Low level persistent database to store final content in
snaps *snapshot.Tree // Snapshot tree for fast trie leaf access
@@ -225,6 +231,19 @@ type BlockChain struct {
vmConfig vm.Config
}
+// NewBlockChainV2 returns a fully initialised blockchain using information
+// available in the database. It initialises the default Ethereum Validator and
+// Processor. The different between NewBlockChainV2 and NewBlockchain are additional txtrace.Config and txtracelib.Store parameter will passed.
+func NewBlockChainV2(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *params.ChainConfig, txTraceConfig *txtrace.Config, txStore txtracelib.Store, engine consensus.Engine, vmConfig vm.Config, shouldPreserve func(block *types.Header) bool, txLookupLimit *uint64) (*BlockChain, error) {
+ bc, err := NewBlockChain(db, cacheConfig, chainConfig, engine, vmConfig, shouldPreserve, txLookupLimit)
+ if err != nil {
+ return nil, err
+ }
+ bc.txTraceConfig = txTraceConfig
+ bc.txTraceStore = txStore
+ return bc, nil
+}
+
// NewBlockChain returns a fully initialised block chain using information
// available in the database. It initialises the default Ethereum Validator
// and Processor.
@@ -441,6 +460,10 @@ func (bc *BlockChain) empty() bool {
return true
}
+func (bc *BlockChain) tracingTx() bool {
+ return bc.txTraceConfig != nil && bc.txTraceConfig.Enabled
+}
+
// loadLastState loads the last known chain state from the database. This method
// assumes that the chain manager mutex is held.
func (bc *BlockChain) loadLastState() error {
@@ -1654,7 +1677,7 @@ func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals, setHead bool)
// Process block using the parent state as reference point
substart := time.Now()
- receipts, logs, usedGas, err := bc.processor.Process(block, statedb, bc.vmConfig)
+ receipts, logs, usedGas, err := bc.processor.Process(block, statedb, bc.vmConfig, bc.tracingTx())
if err != nil {
bc.reportBlock(block, receipts, err)
atomic.StoreUint32(&followupInterrupt, 1)
@@ -2471,3 +2494,6 @@ func (bc *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (i
_, err := bc.hc.InsertHeaderChain(chain, start, bc.forker)
return 0, err
}
+
+// TxTraceStore retrieves the blockchain's tx-trace store.
+func (bc *BlockChain) TxTraceStore() txtracelib.Store { return bc.txTraceStore }
diff --git a/core/blockchain_test.go b/core/blockchain_test.go
index c1e1d6371e..b36da1d83b 100644
--- a/core/blockchain_test.go
+++ b/core/blockchain_test.go
@@ -159,7 +159,7 @@ func testBlockChainImport(chain types.Blocks, blockchain *BlockChain) error {
if err != nil {
return err
}
- receipts, _, usedGas, err := blockchain.processor.Process(block, statedb, vm.Config{})
+ receipts, _, usedGas, err := blockchain.processor.Process(block, statedb, vm.Config{}, false)
if err != nil {
blockchain.reportBlock(block, receipts, err)
return err
diff --git a/core/rawdb/accessors_trace.go b/core/rawdb/accessors_trace.go
new file mode 100644
index 0000000000..5cac35d714
--- /dev/null
+++ b/core/rawdb/accessors_trace.go
@@ -0,0 +1,41 @@
+// Copyright 2021 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library 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.
+//
+// The go-ethereum library 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 the go-ethereum library. If not, see .
+
+package rawdb
+
+import (
+ "github.com/ethereum/go-ethereum/common"
+ "github.com/ethereum/go-ethereum/ethdb"
+ "github.com/ethereum/go-ethereum/log"
+)
+
+// ReadTxTrace retrieves the result of tx by evm-tracing which stores in db.
+func ReadTxTrace(db ethdb.KeyValueReader, hash common.Hash) []byte {
+ data, err := db.Get(codeKey(hash))
+ if err != nil {
+ log.Error("Failed to read tx trace result", "err", err)
+ }
+ return data
+}
+
+// WriteTxTrace write the result of tx tracing by evm-tracing to db.
+func WriteTxTrace(db ethdb.KeyValueWriter, hash common.Hash, data []byte) error {
+ if err := db.Put(codeKey(hash), data); err != nil {
+ log.Crit("Failed to write tx trace result", "err", err)
+ return err
+ }
+ return nil
+}
diff --git a/core/rawdb/accessors_trace_test.go b/core/rawdb/accessors_trace_test.go
new file mode 100644
index 0000000000..d79a72576c
--- /dev/null
+++ b/core/rawdb/accessors_trace_test.go
@@ -0,0 +1,57 @@
+// Copyright 2021 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library 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.
+//
+// The go-ethereum library 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 the go-ethereum library. If not, see .
+
+package rawdb
+
+import (
+ "bytes"
+ "testing"
+
+ "github.com/ethereum/go-ethereum/common"
+)
+
+func TestTxTrace(t *testing.T) {
+ db := NewMemoryDatabase()
+
+ testCases := []struct {
+ name string
+ txHash common.Hash
+ expectedData []byte
+ }{
+ {
+ name: "test1",
+ txHash: common.Hash{},
+ expectedData: []byte{},
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ data := ReadTxTrace(db, tc.txHash)
+ if !bytes.Equal(tc.expectedData, data) {
+ t.Fatalf("Unexpected tx trace data returned")
+ }
+ })
+ }
+
+ txHashStr := "0x5d763978db1d0aedce8cc7c97389fccd1be95e17da337aeec0dd8f8ff2417726"
+ txHash := common.HexToHash(txHashStr)
+ WriteTxTrace(db, txHash, []byte("hello world"))
+ data := ReadTxTrace(db, txHash)
+ if !bytes.Equal(data, []byte("hello world")) {
+ t.Fatalf("Unexpected tx trace data returned")
+ }
+}
diff --git a/core/state_processor.go b/core/state_processor.go
index 71ecaa6a2a..9542199d50 100644
--- a/core/state_processor.go
+++ b/core/state_processor.go
@@ -19,6 +19,7 @@ package core
import (
"fmt"
"math/big"
+ "time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/consensus"
@@ -27,7 +28,10 @@ import (
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
+ "github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/params"
+
+ txtracelib "github.com/DeBankDeFi/etherlib/pkg/txtracev2"
)
// StateProcessor is a basic Processor, which takes care of transitioning
@@ -56,36 +60,36 @@ func NewStateProcessor(config *params.ChainConfig, bc *BlockChain, engine consen
// Process returns the receipts and logs accumulated during the process and
// returns the amount of gas that was used in the process. If any of the
// transactions failed to execute due to insufficient gas it will return an error.
-func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg vm.Config) (types.Receipts, []*types.Log, uint64, error) {
+func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg vm.Config, tracing bool) (types.Receipts, []*types.Log, uint64, error) {
var (
- receipts types.Receipts
- usedGas = new(uint64)
- header = block.Header()
- blockHash = block.Hash()
- blockNumber = block.Number()
- allLogs []*types.Log
- gp = new(GasPool).AddGas(block.GasLimit())
+ receipts types.Receipts
+ usedGas = new(uint64)
+ header = block.Header()
+ allLogs []*types.Log
+ gp = new(GasPool).AddGas(block.GasLimit())
)
// Mutate the block and state according to any hard-fork specs
if p.config.DAOForkSupport && p.config.DAOForkBlock != nil && p.config.DAOForkBlock.Cmp(block.Number()) == 0 {
misc.ApplyDAOHardFork(statedb)
}
- blockContext := NewEVMBlockContext(header, p.bc, nil)
- vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, p.config, cfg)
// Iterate over and process the individual transactions
+ start := time.Now()
for i, tx := range block.Transactions() {
- msg, err := tx.AsMessage(types.MakeSigner(p.config, header.Number), header.BaseFee)
- if err != nil {
- return nil, nil, 0, fmt.Errorf("could not apply tx %d [%v]: %w", i, tx.Hash().Hex(), err)
- }
statedb.Prepare(tx.Hash(), i)
- receipt, err := applyTransaction(msg, p.config, p.bc, nil, gp, statedb, blockNumber, blockHash, tx, usedGas, vmenv)
+ if tracing {
+ cfg.Tracer = txtracelib.NewOeTracer(p.bc.TxTraceStore(), header.Hash(), header.Number, tx.Hash(), uint64(statedb.TxIndex()))
+ cfg.Debug = true
+ }
+ receipt, err := ApplyTransaction(p.config, p.bc, nil, gp, statedb, header, tx, usedGas, cfg)
if err != nil {
return nil, nil, 0, fmt.Errorf("could not apply tx %d [%v]: %w", i, tx.Hash().Hex(), err)
}
receipts = append(receipts, receipt)
allLogs = append(allLogs, receipt.Logs...)
}
+ if tracing {
+ log.Info("Apply all transaction messages finished", "elapsed", common.PrettyDuration(time.Since(start)), "blockNumber", block.NumberU64(), "txs", len(block.Transactions()))
+ }
// Finalize the block, applying any consensus engine specific extras (e.g. block rewards)
p.engine.Finalize(p.bc, header, statedb, block.Transactions(), block.Uncles())
@@ -149,7 +153,21 @@ func ApplyTransaction(config *params.ChainConfig, bc ChainContext, author *commo
// Create a new context to be used in the EVM environment
blockContext := NewEVMBlockContext(header, bc, author)
vmenv := vm.NewEVM(blockContext, vm.TxContext{}, statedb, config, cfg)
- return applyTransaction(msg, config, bc, author, gp, statedb, header.Number, header.Hash(), tx, usedGas, vmenv)
+
+ receipt, err := applyTransaction(msg, config, bc, author, gp, statedb, header.Number, header.Hash(), tx, usedGas, vmenv)
+ if err != nil {
+ return nil, err
+ }
+
+ // Finalize trace logger result and save to underlying database if necessary.
+ switch t := cfg.Tracer.(type) {
+ case *txtracelib.OeTracer:
+ log.Debug("Persist oe-style trace result to database", "blockNumber", header.Number.Int64(), "txHash", tx.Hash())
+ t.PersistTrace()
+ default:
+ }
+
+ return receipt, nil
}
func ApplyTransactionForPreExec(config *params.ChainConfig, bc ChainContext, author *common.Address, gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, msg types.Message, usedGas *uint64, cfg vm.Config) (*types.Receipt, error) {
diff --git a/core/types.go b/core/types.go
index 4c5b74a498..ddfc379c87 100644
--- a/core/types.go
+++ b/core/types.go
@@ -47,5 +47,5 @@ type Processor interface {
// Process processes the state changes according to the Ethereum rules by running
// the transaction messages using the statedb and applying any rewards to both
// the processor (coinbase) and any included uncles.
- Process(block *types.Block, statedb *state.StateDB, cfg vm.Config) (types.Receipts, []*types.Log, uint64, error)
+ Process(block *types.Block, statedb *state.StateDB, cfg vm.Config, tracing bool) (types.Receipts, []*types.Log, uint64, error)
}
diff --git a/eth/api_tx_trace.go b/eth/api_tx_trace.go
new file mode 100644
index 0000000000..4576335d48
--- /dev/null
+++ b/eth/api_tx_trace.go
@@ -0,0 +1,65 @@
+// Copyright 2022 The go-ethereum Authors
+// // This file is part of the go-ethereum library.
+// //
+// // The go-ethereum library 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.
+// //
+// // The go-ethereum library 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 the go-ethereum library. If not, see .
+//
+// // Package ethapi implements the general Ethereum API functions.
+
+package eth
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+
+ "github.com/ethereum/go-ethereum/common"
+ "github.com/ethereum/go-ethereum/rlp"
+
+ txtracelib "github.com/DeBankDeFi/etherlib/pkg/txtracev2"
+)
+
+// PublicTxTraceAPI provides an API to tracing transaction or block information.
+// // It offers only methods that operate on public data that is freely available to anyone.
+type PublicTxTraceAPI struct {
+ e *Ethereum
+}
+
+// NewPublicTxTraceAPI creates a new trace API.
+func NewPublicTxTraceAPI(e *Ethereum) *PublicTxTraceAPI {
+ return &PublicTxTraceAPI{e: e}
+}
+
+// Transaction trace_transaction function returns transaction traces.
+func (api *PublicTxTraceAPI) Transaction(ctx context.Context, txHash common.Hash) (interface{}, error) {
+ if api.e.blockchain == nil {
+ return []byte{}, fmt.Errorf("blockchain corruput")
+ }
+
+ raw, err := api.e.blockchain.TxTraceStore().ReadTxTrace(ctx, txHash)
+ if err != nil {
+ return []byte{}, err
+ }
+
+ if bytes.Equal(raw, []byte{}) { // empty response
+ return nil, fmt.Errorf("trace result of tx {%#v} not found in tracedb", txHash)
+ }
+
+ flatten := new(txtracelib.ActionTraceList)
+ err = rlp.DecodeBytes(raw, flatten)
+ if err != nil {
+ return nil, fmt.Errorf("failed to decode rlp flatten traces: %v", err)
+ }
+
+ return *flatten, nil
+}
diff --git a/eth/backend.go b/eth/backend.go
index 48d7d1c249..87da61d2bf 100644
--- a/eth/backend.go
+++ b/eth/backend.go
@@ -58,6 +58,7 @@ import (
"github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/rpc"
+ "github.com/ethereum/go-ethereum/txtrace"
)
// Config contains the configuration options of the ETH protocol.
@@ -149,6 +150,16 @@ func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) {
log.Info(strings.Repeat("-", 153))
log.Info("")
+ // Init tx-trace underlying database and storage layer
+ var traceDb ethdb.Database
+ if config.TxTrace.Enabled {
+ traceDb, err = stack.OpenDatabaseWithTrace(config.DatabaseCache, config.DatabaseHandles, config.TxTrace.StoreDir, "eth/db/tracedb", false)
+ if err != nil {
+ return nil, err
+ }
+ }
+ txStore := txtrace.NewTraceStore(traceDb)
+
if err := pruner.RecoverPruning(stack.ResolvePath(""), chainDb, stack.ResolvePath(config.TrieCleanCacheJournal)); err != nil {
log.Error("Failed to recover state", "error", err)
}
@@ -205,7 +216,7 @@ func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) {
AncientRecentLimit: config.AncientRecentLimit,
}
)
- eth.blockchain, err = core.NewBlockChain(chainDb, cacheConfig, chainConfig, eth.engine, vmConfig, eth.shouldPreserve, &config.TxLookupLimit)
+ eth.blockchain, err = core.NewBlockChainV2(chainDb, cacheConfig, chainConfig, &config.TxTrace, txStore, eth.engine, vmConfig, eth.shouldPreserve, &config.TxLookupLimit)
if err != nil {
return nil, err
}
@@ -357,6 +368,12 @@ func (s *Ethereum) APIs() []rpc.API {
Version: "1.0",
Service: NewPreExecAPI(s),
Public: true,
+ }, {
+
+ Namespace: "trace",
+ Version: "1.0",
+ Service: NewPublicTxTraceAPI(s),
+ Public: true,
},
}...)
}
diff --git a/eth/ethconfig/config.go b/eth/ethconfig/config.go
index c37faa1688..50ce0618f4 100644
--- a/eth/ethconfig/config.go
+++ b/eth/ethconfig/config.go
@@ -38,6 +38,7 @@ import (
"github.com/ethereum/go-ethereum/miner"
"github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/params"
+ "github.com/ethereum/go-ethereum/txtrace"
)
// FullNodeGPO contains default gasprice oracle settings for full node.
@@ -183,6 +184,9 @@ type Config struct {
// Transaction pool options
TxPool core.TxPoolConfig
+ // TxTrace
+ TxTrace txtrace.Config
+
// Gas Price Oracle options
GPO gasprice.Config
diff --git a/eth/state_accessor.go b/eth/state_accessor.go
index f01db93a67..243e950263 100644
--- a/eth/state_accessor.go
+++ b/eth/state_accessor.go
@@ -131,7 +131,7 @@ func (eth *Ethereum) StateAtBlock(block *types.Block, reexec uint64, base *state
if current = eth.blockchain.GetBlockByNumber(next); current == nil {
return nil, fmt.Errorf("block #%d not found", next)
}
- _, _, _, err := eth.blockchain.Processor().Process(current, statedb, vm.Config{})
+ _, _, _, err := eth.blockchain.Processor().Process(current, statedb, vm.Config{}, false)
if err != nil {
return nil, fmt.Errorf("processing block %d failed: %v", current.NumberU64(), err)
}
diff --git a/node/node.go b/node/node.go
index c67bbd01d8..de4610279c 100644
--- a/node/node.go
+++ b/node/node.go
@@ -712,6 +712,28 @@ func (n *Node) OpenDatabase(name string, cache, handles int, namespace string, r
return db, err
}
+// OpenDatabaseWithTrace same as OpenDatabaseWithFreezer but open txTrace dedicated database instead.
+func (n *Node) OpenDatabaseWithTrace(cache, handles int, tracer, namespace string, readonly bool) (ethdb.Database, error) {
+ n.lock.Lock()
+ defer n.lock.Unlock()
+ if n.state == closedState {
+ return nil, ErrNodeStopped
+ }
+
+ var db ethdb.Database
+ var err error
+ if tracer == "" {
+ tracer = "tracedb"
+ }
+ tracer = n.ResolvePath(tracer)
+ db, err = rawdb.NewLevelDBDatabase(tracer, cache, handles, namespace, readonly)
+ if err == nil {
+ db = n.wrapDatabase(db)
+ }
+ log.Info("Opened tx-trace database", "database", tracer)
+ return db, err
+}
+
// OpenDatabaseWithFreezer opens an existing database with the given name (or
// creates one if no previous can be found) from within the node's data directory,
// also attaching a chain freezer to it that moves ancient chain data from the
diff --git a/tests/testdata b/tests/testdata
index a380655e5f..092a8834dc 160000
--- a/tests/testdata
+++ b/tests/testdata
@@ -1 +1 @@
-Subproject commit a380655e5ffab1a5ea0f4d860224bdb19013f06a
+Subproject commit 092a8834dc445e683103689d6f0e75a5d380a190
diff --git a/txtrace/config.go b/txtrace/config.go
new file mode 100644
index 0000000000..2a4e463a53
--- /dev/null
+++ b/txtrace/config.go
@@ -0,0 +1,24 @@
+// Copyright 2021 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library 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.
+//
+// The go-ethereum library 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 the go-ethereum library. If not, see .
+
+package txtrace
+
+// Config is the configuration of tx tracer.
+type Config struct {
+ Enabled bool
+ StoreDir string
+ Consistency bool
+}
diff --git a/txtrace/store.go b/txtrace/store.go
new file mode 100644
index 0000000000..d88b8264a2
--- /dev/null
+++ b/txtrace/store.go
@@ -0,0 +1,92 @@
+// Copyright 2021 The go-ethereum Authors
+// This file is part of the go-ethereum library.
+//
+// The go-ethereum library 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.
+//
+// The go-ethereum library 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 the go-ethereum library. If not, see .
+
+package txtrace
+
+import (
+ "context"
+ "fmt"
+ "sync"
+
+ "github.com/ethereum/go-ethereum/common"
+ "github.com/ethereum/go-ethereum/core/rawdb"
+ "github.com/ethereum/go-ethereum/ethdb"
+ "github.com/ethereum/go-ethereum/metrics"
+
+ txtrace "github.com/DeBankDeFi/etherlib/pkg/txtracev2"
+)
+
+var (
+ txTraceWriteSuccessCounter = metrics.NewRegisteredCounter("chain/txtraces/write/success", nil)
+ txTraceWriteFailCounter = metrics.NewRegisteredCounter("chain/txtraces/write/fail", nil)
+)
+
+var (
+ once sync.Once
+ defaultTraceStore *traceStore
+)
+
+var _ txtrace.Store = (*traceStore)(nil)
+
+type traceStore struct {
+ db ethdb.Database
+}
+
+// NewTraceStore creates a new trace store.
+func NewTraceStore(db ethdb.Database) txtrace.Store {
+ if defaultTraceStore != nil {
+ return defaultTraceStore
+ }
+ once.Do(func() {
+ defaultTraceStore = &traceStore{db: db}
+ })
+ return defaultTraceStore
+}
+
+// GetTraceStore get singleton traceStore.
+func GetTraceStore() *traceStore {
+ return defaultTraceStore
+}
+
+func (t *traceStore) guard() error {
+ if t.db == nil {
+ return fmt.Errorf("txtrace mode not enabled")
+ }
+ return nil
+}
+
+// ReadTxTrace retrieves the result of tx by evm-tracing which stores in db.
+func (t *traceStore) ReadTxTrace(ctx context.Context, txHash common.Hash) ([]byte, error) {
+ if err := t.guard(); err != nil {
+ return []byte{}, err
+ }
+ data := rawdb.ReadTxTrace(t.db, txHash)
+ return data, nil
+}
+
+// WriteTxTrace write the result of tx tracing by evm-tracing to db.
+func (t *traceStore) WriteTxTrace(ctx context.Context, txHash common.Hash, trace []byte) error {
+ if err := t.guard(); err != nil {
+ return err
+ }
+ err := rawdb.WriteTxTrace(t.db, txHash, trace)
+ if err == nil {
+ txTraceWriteSuccessCounter.Inc(1)
+ return nil
+ }
+ txTraceWriteFailCounter.Inc(1)
+ return err
+}