github.com/aidoskuneen/adk-node@v0.0.0-20220315131952-2e32567cb7f4/eth/tracers/api.go (about)

     1  // Copyright 2021 The adkgo Authors
     2  // This file is part of the adkgo library (adapted for adkgo from go--ethereum v1.10.8).
     3  //
     4  // the adkgo 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 adkgo 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 adkgo library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package tracers
    18  
    19  import (
    20  	"bufio"
    21  	"bytes"
    22  	"context"
    23  	"errors"
    24  	"fmt"
    25  	"io/ioutil"
    26  	"os"
    27  	"runtime"
    28  	"sync"
    29  	"time"
    30  
    31  	"github.com/aidoskuneen/adk-node/common"
    32  	"github.com/aidoskuneen/adk-node/common/hexutil"
    33  	"github.com/aidoskuneen/adk-node/consensus"
    34  	"github.com/aidoskuneen/adk-node/core"
    35  	"github.com/aidoskuneen/adk-node/core/rawdb"
    36  	"github.com/aidoskuneen/adk-node/core/state"
    37  	"github.com/aidoskuneen/adk-node/core/types"
    38  	"github.com/aidoskuneen/adk-node/core/vm"
    39  	"github.com/aidoskuneen/adk-node/ethdb"
    40  	"github.com/aidoskuneen/adk-node/internal/ethapi"
    41  	"github.com/aidoskuneen/adk-node/log"
    42  	"github.com/aidoskuneen/adk-node/params"
    43  	"github.com/aidoskuneen/adk-node/rlp"
    44  	"github.com/aidoskuneen/adk-node/rpc"
    45  )
    46  
    47  const (
    48  	// defaultTraceTimeout is the amount of time a single transaction can execute
    49  	// by default before being forcefully aborted.
    50  	defaultTraceTimeout = 5 * time.Second
    51  
    52  	// defaultTraceReexec is the number of blocks the tracer is willing to go back
    53  	// and reexecute to produce missing historical state necessary to run a specific
    54  	// trace.
    55  	defaultTraceReexec = uint64(128)
    56  )
    57  
    58  // Backend interface provides the common API services (that are provided by
    59  // both full and light clients) with access to necessary functions.
    60  type Backend interface {
    61  	HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error)
    62  	HeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Header, error)
    63  	BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error)
    64  	BlockByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Block, error)
    65  	GetTransaction(ctx context.Context, txHash common.Hash) (*types.Transaction, common.Hash, uint64, uint64, error)
    66  	RPCGasCap() uint64
    67  	ChainConfig() *params.ChainConfig
    68  	Engine() consensus.Engine
    69  	ChainDb() ethdb.Database
    70  	StateAtBlock(ctx context.Context, block *types.Block, reexec uint64, base *state.StateDB, checkLive bool) (*state.StateDB, error)
    71  	StateAtTransaction(ctx context.Context, block *types.Block, txIndex int, reexec uint64) (core.Message, vm.BlockContext, *state.StateDB, error)
    72  }
    73  
    74  // API is the collection of tracing APIs exposed over the private debugging endpoint.
    75  type API struct {
    76  	backend Backend
    77  }
    78  
    79  // NewAPI creates a new API definition for the tracing methods of the Ethereum service.
    80  func NewAPI(backend Backend) *API {
    81  	return &API{backend: backend}
    82  }
    83  
    84  type chainContext struct {
    85  	api *API
    86  	ctx context.Context
    87  }
    88  
    89  func (context *chainContext) Engine() consensus.Engine {
    90  	return context.api.backend.Engine()
    91  }
    92  
    93  func (context *chainContext) GetHeader(hash common.Hash, number uint64) *types.Header {
    94  	header, err := context.api.backend.HeaderByNumber(context.ctx, rpc.BlockNumber(number))
    95  	if err != nil {
    96  		return nil
    97  	}
    98  	if header.Hash() == hash {
    99  		return header
   100  	}
   101  	header, err = context.api.backend.HeaderByHash(context.ctx, hash)
   102  	if err != nil {
   103  		return nil
   104  	}
   105  	return header
   106  }
   107  
   108  // chainContext construts the context reader which is used by the evm for reading
   109  // the necessary chain context.
   110  func (api *API) chainContext(ctx context.Context) core.ChainContext {
   111  	return &chainContext{api: api, ctx: ctx}
   112  }
   113  
   114  // blockByNumber is the wrapper of the chain access function offered by the backend.
   115  // It will return an error if the block is not found.
   116  func (api *API) blockByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Block, error) {
   117  	block, err := api.backend.BlockByNumber(ctx, number)
   118  	if err != nil {
   119  		return nil, err
   120  	}
   121  	if block == nil {
   122  		return nil, fmt.Errorf("block #%d not found", number)
   123  	}
   124  	return block, nil
   125  }
   126  
   127  // blockByHash is the wrapper of the chain access function offered by the backend.
   128  // It will return an error if the block is not found.
   129  func (api *API) blockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
   130  	block, err := api.backend.BlockByHash(ctx, hash)
   131  	if err != nil {
   132  		return nil, err
   133  	}
   134  	if block == nil {
   135  		return nil, fmt.Errorf("block %s not found", hash.Hex())
   136  	}
   137  	return block, nil
   138  }
   139  
   140  // blockByNumberAndHash is the wrapper of the chain access function offered by
   141  // the backend. It will return an error if the block is not found.
   142  //
   143  // Note this function is friendly for the light client which can only retrieve the
   144  // historical(before the CHT) header/block by number.
   145  func (api *API) blockByNumberAndHash(ctx context.Context, number rpc.BlockNumber, hash common.Hash) (*types.Block, error) {
   146  	block, err := api.blockByNumber(ctx, number)
   147  	if err != nil {
   148  		return nil, err
   149  	}
   150  	if block.Hash() == hash {
   151  		return block, nil
   152  	}
   153  	return api.blockByHash(ctx, hash)
   154  }
   155  
   156  // TraceConfig holds extra parameters to trace functions.
   157  type TraceConfig struct {
   158  	*vm.LogConfig
   159  	Tracer  *string
   160  	Timeout *string
   161  	Reexec  *uint64
   162  }
   163  
   164  // TraceCallConfig is the config for traceCall API. It holds one more
   165  // field to override the state for tracing.
   166  type TraceCallConfig struct {
   167  	*vm.LogConfig
   168  	Tracer         *string
   169  	Timeout        *string
   170  	Reexec         *uint64
   171  	StateOverrides *ethapi.StateOverride
   172  }
   173  
   174  // StdTraceConfig holds extra parameters to standard-json trace functions.
   175  type StdTraceConfig struct {
   176  	vm.LogConfig
   177  	Reexec *uint64
   178  	TxHash common.Hash
   179  }
   180  
   181  // txTraceResult is the result of a single transaction trace.
   182  type txTraceResult struct {
   183  	Result interface{} `json:"result,omitempty"` // Trace results produced by the tracer
   184  	Error  string      `json:"error,omitempty"`  // Trace failure produced by the tracer
   185  }
   186  
   187  // blockTraceTask represents a single block trace task when an entire chain is
   188  // being traced.
   189  type blockTraceTask struct {
   190  	statedb *state.StateDB   // Intermediate state prepped for tracing
   191  	block   *types.Block     // Block to trace the transactions from
   192  	rootref common.Hash      // Trie root reference held for this task
   193  	results []*txTraceResult // Trace results procudes by the task
   194  }
   195  
   196  // blockTraceResult represets the results of tracing a single block when an entire
   197  // chain is being traced.
   198  type blockTraceResult struct {
   199  	Block  hexutil.Uint64   `json:"block"`  // Block number corresponding to this trace
   200  	Hash   common.Hash      `json:"hash"`   // Block hash corresponding to this trace
   201  	Traces []*txTraceResult `json:"traces"` // Trace results produced by the task
   202  }
   203  
   204  // txTraceTask represents a single transaction trace task when an entire block
   205  // is being traced.
   206  type txTraceTask struct {
   207  	statedb *state.StateDB // Intermediate state prepped for tracing
   208  	index   int            // Transaction offset in the block
   209  }
   210  
   211  // TraceChain returns the structured logs created during the execution of EVM
   212  // between two blocks (excluding start) and returns them as a JSON object.
   213  func (api *API) TraceChain(ctx context.Context, start, end rpc.BlockNumber, config *TraceConfig) (*rpc.Subscription, error) { // Fetch the block interval that we want to trace
   214  	from, err := api.blockByNumber(ctx, start)
   215  	if err != nil {
   216  		return nil, err
   217  	}
   218  	to, err := api.blockByNumber(ctx, end)
   219  	if err != nil {
   220  		return nil, err
   221  	}
   222  	if from.Number().Cmp(to.Number()) >= 0 {
   223  		return nil, fmt.Errorf("end block (#%d) needs to come after start block (#%d)", end, start)
   224  	}
   225  	return api.traceChain(ctx, from, to, config)
   226  }
   227  
   228  // traceChain configures a new tracer according to the provided configuration, and
   229  // executes all the transactions contained within. The return value will be one item
   230  // per transaction, dependent on the requested tracer.
   231  func (api *API) traceChain(ctx context.Context, start, end *types.Block, config *TraceConfig) (*rpc.Subscription, error) {
   232  	// Tracing a chain is a **long** operation, only do with subscriptions
   233  	notifier, supported := rpc.NotifierFromContext(ctx)
   234  	if !supported {
   235  		return &rpc.Subscription{}, rpc.ErrNotificationsUnsupported
   236  	}
   237  	sub := notifier.CreateSubscription()
   238  
   239  	// Prepare all the states for tracing. Note this procedure can take very
   240  	// long time. Timeout mechanism is necessary.
   241  	reexec := defaultTraceReexec
   242  	if config != nil && config.Reexec != nil {
   243  		reexec = *config.Reexec
   244  	}
   245  	blocks := int(end.NumberU64() - start.NumberU64())
   246  	threads := runtime.NumCPU()
   247  	if threads > blocks {
   248  		threads = blocks
   249  	}
   250  	var (
   251  		pend     = new(sync.WaitGroup)
   252  		tasks    = make(chan *blockTraceTask, threads)
   253  		results  = make(chan *blockTraceTask, threads)
   254  		localctx = context.Background()
   255  	)
   256  	for th := 0; th < threads; th++ {
   257  		pend.Add(1)
   258  		go func() {
   259  			defer pend.Done()
   260  
   261  			// Fetch and execute the next block trace tasks
   262  			for task := range tasks {
   263  				signer := types.MakeSigner(api.backend.ChainConfig(), task.block.Number())
   264  				blockCtx := core.NewEVMBlockContext(task.block.Header(), api.chainContext(localctx), nil)
   265  				// Trace all the transactions contained within
   266  				for i, tx := range task.block.Transactions() {
   267  					msg, _ := tx.AsMessage(signer, task.block.BaseFee())
   268  					txctx := &Context{
   269  						BlockHash: task.block.Hash(),
   270  						TxIndex:   i,
   271  						TxHash:    tx.Hash(),
   272  					}
   273  					res, err := api.traceTx(localctx, msg, txctx, blockCtx, task.statedb, config)
   274  					if err != nil {
   275  						task.results[i] = &txTraceResult{Error: err.Error()}
   276  						log.Warn("Tracing failed", "hash", tx.Hash(), "block", task.block.NumberU64(), "err", err)
   277  						break
   278  					}
   279  					// Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
   280  					task.statedb.Finalise(api.backend.ChainConfig().IsEIP158(task.block.Number()))
   281  					task.results[i] = &txTraceResult{Result: res}
   282  				}
   283  				// Stream the result back to the user or abort on teardown
   284  				select {
   285  				case results <- task:
   286  				case <-notifier.Closed():
   287  					return
   288  				}
   289  			}
   290  		}()
   291  	}
   292  	// Start a goroutine to feed all the blocks into the tracers
   293  	begin := time.Now()
   294  
   295  	go func() {
   296  		var (
   297  			logged  time.Time
   298  			number  uint64
   299  			traced  uint64
   300  			failed  error
   301  			parent  common.Hash
   302  			statedb *state.StateDB
   303  		)
   304  		// Ensure everything is properly cleaned up on any exit path
   305  		defer func() {
   306  			close(tasks)
   307  			pend.Wait()
   308  
   309  			switch {
   310  			case failed != nil:
   311  				log.Warn("Chain tracing failed", "start", start.NumberU64(), "end", end.NumberU64(), "transactions", traced, "elapsed", time.Since(begin), "err", failed)
   312  			case number < end.NumberU64():
   313  				log.Warn("Chain tracing aborted", "start", start.NumberU64(), "end", end.NumberU64(), "abort", number, "transactions", traced, "elapsed", time.Since(begin))
   314  			default:
   315  				log.Info("Chain tracing finished", "start", start.NumberU64(), "end", end.NumberU64(), "transactions", traced, "elapsed", time.Since(begin))
   316  			}
   317  			close(results)
   318  		}()
   319  		// Feed all the blocks both into the tracer, as well as fast process concurrently
   320  		for number = start.NumberU64(); number < end.NumberU64(); number++ {
   321  			// Stop tracing if interruption was requested
   322  			select {
   323  			case <-notifier.Closed():
   324  				return
   325  			default:
   326  			}
   327  			// Print progress logs if long enough time elapsed
   328  			if time.Since(logged) > 8*time.Second {
   329  				logged = time.Now()
   330  				log.Info("Tracing chain segment", "start", start.NumberU64(), "end", end.NumberU64(), "current", number, "transactions", traced, "elapsed", time.Since(begin))
   331  			}
   332  			// Retrieve the parent state to trace on top
   333  			block, err := api.blockByNumber(localctx, rpc.BlockNumber(number))
   334  			if err != nil {
   335  				failed = err
   336  				break
   337  			}
   338  			// Prepare the statedb for tracing. Don't use the live database for
   339  			// tracing to avoid persisting state junks into the database.
   340  			statedb, err = api.backend.StateAtBlock(localctx, block, reexec, statedb, false)
   341  			if err != nil {
   342  				failed = err
   343  				break
   344  			}
   345  			if statedb.Database().TrieDB() != nil {
   346  				// Hold the reference for tracer, will be released at the final stage
   347  				statedb.Database().TrieDB().Reference(block.Root(), common.Hash{})
   348  
   349  				// Release the parent state because it's already held by the tracer
   350  				if parent != (common.Hash{}) {
   351  					statedb.Database().TrieDB().Dereference(parent)
   352  				}
   353  			}
   354  			parent = block.Root()
   355  
   356  			next, err := api.blockByNumber(localctx, rpc.BlockNumber(number+1))
   357  			if err != nil {
   358  				failed = err
   359  				break
   360  			}
   361  			// Send the block over to the concurrent tracers (if not in the fast-forward phase)
   362  			txs := next.Transactions()
   363  			select {
   364  			case tasks <- &blockTraceTask{statedb: statedb.Copy(), block: next, rootref: block.Root(), results: make([]*txTraceResult, len(txs))}:
   365  			case <-notifier.Closed():
   366  				return
   367  			}
   368  			traced += uint64(len(txs))
   369  		}
   370  	}()
   371  
   372  	// Keep reading the trace results and stream the to the user
   373  	go func() {
   374  		var (
   375  			done = make(map[uint64]*blockTraceResult)
   376  			next = start.NumberU64() + 1
   377  		)
   378  		for res := range results {
   379  			// Queue up next received result
   380  			result := &blockTraceResult{
   381  				Block:  hexutil.Uint64(res.block.NumberU64()),
   382  				Hash:   res.block.Hash(),
   383  				Traces: res.results,
   384  			}
   385  			done[uint64(result.Block)] = result
   386  
   387  			// Dereference any parent tries held in memory by this task
   388  			if res.statedb.Database().TrieDB() != nil {
   389  				res.statedb.Database().TrieDB().Dereference(res.rootref)
   390  			}
   391  			// Stream completed traces to the user, aborting on the first error
   392  			for result, ok := done[next]; ok; result, ok = done[next] {
   393  				if len(result.Traces) > 0 || next == end.NumberU64() {
   394  					notifier.Notify(sub.ID, result)
   395  				}
   396  				delete(done, next)
   397  				next++
   398  			}
   399  		}
   400  	}()
   401  	return sub, nil
   402  }
   403  
   404  // TraceBlockByNumber returns the structured logs created during the execution of
   405  // EVM and returns them as a JSON object.
   406  func (api *API) TraceBlockByNumber(ctx context.Context, number rpc.BlockNumber, config *TraceConfig) ([]*txTraceResult, error) {
   407  	block, err := api.blockByNumber(ctx, number)
   408  	if err != nil {
   409  		return nil, err
   410  	}
   411  	return api.traceBlock(ctx, block, config)
   412  }
   413  
   414  // TraceBlockByHash returns the structured logs created during the execution of
   415  // EVM and returns them as a JSON object.
   416  func (api *API) TraceBlockByHash(ctx context.Context, hash common.Hash, config *TraceConfig) ([]*txTraceResult, error) {
   417  	block, err := api.blockByHash(ctx, hash)
   418  	if err != nil {
   419  		return nil, err
   420  	}
   421  	return api.traceBlock(ctx, block, config)
   422  }
   423  
   424  // TraceBlock returns the structured logs created during the execution of EVM
   425  // and returns them as a JSON object.
   426  func (api *API) TraceBlock(ctx context.Context, blob []byte, config *TraceConfig) ([]*txTraceResult, error) {
   427  	block := new(types.Block)
   428  	if err := rlp.Decode(bytes.NewReader(blob), block); err != nil {
   429  		return nil, fmt.Errorf("could not decode block: %v", err)
   430  	}
   431  	return api.traceBlock(ctx, block, config)
   432  }
   433  
   434  // TraceBlockFromFile returns the structured logs created during the execution of
   435  // EVM and returns them as a JSON object.
   436  func (api *API) TraceBlockFromFile(ctx context.Context, file string, config *TraceConfig) ([]*txTraceResult, error) {
   437  	blob, err := ioutil.ReadFile(file)
   438  	if err != nil {
   439  		return nil, fmt.Errorf("could not read file: %v", err)
   440  	}
   441  	return api.TraceBlock(ctx, blob, config)
   442  }
   443  
   444  // TraceBadBlock returns the structured logs created during the execution of
   445  // EVM against a block pulled from the pool of bad ones and returns them as a JSON
   446  // object.
   447  func (api *API) TraceBadBlock(ctx context.Context, hash common.Hash, config *TraceConfig) ([]*txTraceResult, error) {
   448  	for _, block := range rawdb.ReadAllBadBlocks(api.backend.ChainDb()) {
   449  		if block.Hash() == hash {
   450  			return api.traceBlock(ctx, block, config)
   451  		}
   452  	}
   453  	return nil, fmt.Errorf("bad block %#x not found", hash)
   454  }
   455  
   456  // StandardTraceBlockToFile dumps the structured logs created during the
   457  // execution of EVM to the local file system and returns a list of files
   458  // to the caller.
   459  func (api *API) StandardTraceBlockToFile(ctx context.Context, hash common.Hash, config *StdTraceConfig) ([]string, error) {
   460  	block, err := api.blockByHash(ctx, hash)
   461  	if err != nil {
   462  		return nil, err
   463  	}
   464  	return api.standardTraceBlockToFile(ctx, block, config)
   465  }
   466  
   467  // StandardTraceBadBlockToFile dumps the structured logs created during the
   468  // execution of EVM against a block pulled from the pool of bad ones to the
   469  // local file system and returns a list of files to the caller.
   470  func (api *API) StandardTraceBadBlockToFile(ctx context.Context, hash common.Hash, config *StdTraceConfig) ([]string, error) {
   471  	for _, block := range rawdb.ReadAllBadBlocks(api.backend.ChainDb()) {
   472  		if block.Hash() == hash {
   473  			return api.standardTraceBlockToFile(ctx, block, config)
   474  		}
   475  	}
   476  	return nil, fmt.Errorf("bad block %#x not found", hash)
   477  }
   478  
   479  // traceBlock configures a new tracer according to the provided configuration, and
   480  // executes all the transactions contained within. The return value will be one item
   481  // per transaction, dependent on the requestd tracer.
   482  func (api *API) traceBlock(ctx context.Context, block *types.Block, config *TraceConfig) ([]*txTraceResult, error) {
   483  	if block.NumberU64() == 0 {
   484  		return nil, errors.New("genesis is not traceable")
   485  	}
   486  	parent, err := api.blockByNumberAndHash(ctx, rpc.BlockNumber(block.NumberU64()-1), block.ParentHash())
   487  	if err != nil {
   488  		return nil, err
   489  	}
   490  	reexec := defaultTraceReexec
   491  	if config != nil && config.Reexec != nil {
   492  		reexec = *config.Reexec
   493  	}
   494  	statedb, err := api.backend.StateAtBlock(ctx, parent, reexec, nil, true)
   495  	if err != nil {
   496  		return nil, err
   497  	}
   498  	// Execute all the transaction contained within the block concurrently
   499  	var (
   500  		signer  = types.MakeSigner(api.backend.ChainConfig(), block.Number())
   501  		txs     = block.Transactions()
   502  		results = make([]*txTraceResult, len(txs))
   503  
   504  		pend = new(sync.WaitGroup)
   505  		jobs = make(chan *txTraceTask, len(txs))
   506  	)
   507  	threads := runtime.NumCPU()
   508  	if threads > len(txs) {
   509  		threads = len(txs)
   510  	}
   511  	blockCtx := core.NewEVMBlockContext(block.Header(), api.chainContext(ctx), nil)
   512  	blockHash := block.Hash()
   513  	for th := 0; th < threads; th++ {
   514  		pend.Add(1)
   515  		go func() {
   516  			defer pend.Done()
   517  			// Fetch and execute the next transaction trace tasks
   518  			for task := range jobs {
   519  				msg, _ := txs[task.index].AsMessage(signer, block.BaseFee())
   520  				txctx := &Context{
   521  					BlockHash: blockHash,
   522  					TxIndex:   task.index,
   523  					TxHash:    txs[task.index].Hash(),
   524  				}
   525  				res, err := api.traceTx(ctx, msg, txctx, blockCtx, task.statedb, config)
   526  				if err != nil {
   527  					results[task.index] = &txTraceResult{Error: err.Error()}
   528  					continue
   529  				}
   530  				results[task.index] = &txTraceResult{Result: res}
   531  			}
   532  		}()
   533  	}
   534  	// Feed the transactions into the tracers and return
   535  	var failed error
   536  	for i, tx := range txs {
   537  		// Send the trace task over for execution
   538  		jobs <- &txTraceTask{statedb: statedb.Copy(), index: i}
   539  
   540  		// Generate the next state snapshot fast without tracing
   541  		msg, _ := tx.AsMessage(signer, block.BaseFee())
   542  		statedb.Prepare(tx.Hash(), i)
   543  		vmenv := vm.NewEVM(blockCtx, core.NewEVMTxContext(msg), statedb, api.backend.ChainConfig(), vm.Config{})
   544  		if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas())); err != nil {
   545  			failed = err
   546  			break
   547  		}
   548  		// Finalize the state so any modifications are written to the trie
   549  		// Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
   550  		statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
   551  	}
   552  	close(jobs)
   553  	pend.Wait()
   554  
   555  	// If execution failed in between, abort
   556  	if failed != nil {
   557  		return nil, failed
   558  	}
   559  	return results, nil
   560  }
   561  
   562  // standardTraceBlockToFile configures a new tracer which uses standard JSON output,
   563  // and traces either a full block or an individual transaction. The return value will
   564  // be one filename per transaction traced.
   565  func (api *API) standardTraceBlockToFile(ctx context.Context, block *types.Block, config *StdTraceConfig) ([]string, error) {
   566  	// If we're tracing a single transaction, make sure it's present
   567  	if config != nil && config.TxHash != (common.Hash{}) {
   568  		if !containsTx(block, config.TxHash) {
   569  			return nil, fmt.Errorf("transaction %#x not found in block", config.TxHash)
   570  		}
   571  	}
   572  	if block.NumberU64() == 0 {
   573  		return nil, errors.New("genesis is not traceable")
   574  	}
   575  	parent, err := api.blockByNumberAndHash(ctx, rpc.BlockNumber(block.NumberU64()-1), block.ParentHash())
   576  	if err != nil {
   577  		return nil, err
   578  	}
   579  	reexec := defaultTraceReexec
   580  	if config != nil && config.Reexec != nil {
   581  		reexec = *config.Reexec
   582  	}
   583  	statedb, err := api.backend.StateAtBlock(ctx, parent, reexec, nil, true)
   584  	if err != nil {
   585  		return nil, err
   586  	}
   587  	// Retrieve the tracing configurations, or use default values
   588  	var (
   589  		logConfig vm.LogConfig
   590  		txHash    common.Hash
   591  	)
   592  	if config != nil {
   593  		logConfig = config.LogConfig
   594  		txHash = config.TxHash
   595  	}
   596  	logConfig.Debug = true
   597  
   598  	// Execute transaction, either tracing all or just the requested one
   599  	var (
   600  		dumps       []string
   601  		signer      = types.MakeSigner(api.backend.ChainConfig(), block.Number())
   602  		chainConfig = api.backend.ChainConfig()
   603  		vmctx       = core.NewEVMBlockContext(block.Header(), api.chainContext(ctx), nil)
   604  		canon       = true
   605  	)
   606  	// Check if there are any overrides: the caller may wish to enable a future
   607  	// fork when executing this block. Note, such overrides are only applicable to the
   608  	// actual specified block, not any preceding blocks that we have to go through
   609  	// in order to obtain the state.
   610  	// Therefore, it's perfectly valid to specify `"futureForkBlock": 0`, to enable `futureFork`
   611  
   612  	if config != nil && config.Overrides != nil {
   613  		// Copy the config, to not screw up the main config
   614  		// Note: the Clique-part is _not_ deep copied
   615  		chainConfigCopy := new(params.ChainConfig)
   616  		*chainConfigCopy = *chainConfig
   617  		chainConfig = chainConfigCopy
   618  		if berlin := config.LogConfig.Overrides.BerlinBlock; berlin != nil {
   619  			chainConfig.BerlinBlock = berlin
   620  			canon = false
   621  		}
   622  	}
   623  	for i, tx := range block.Transactions() {
   624  		// Prepare the trasaction for un-traced execution
   625  		var (
   626  			msg, _    = tx.AsMessage(signer, block.BaseFee())
   627  			txContext = core.NewEVMTxContext(msg)
   628  			vmConf    vm.Config
   629  			dump      *os.File
   630  			writer    *bufio.Writer
   631  			err       error
   632  		)
   633  		// If the transaction needs tracing, swap out the configs
   634  		if tx.Hash() == txHash || txHash == (common.Hash{}) {
   635  			// Generate a unique temporary file to dump it into
   636  			prefix := fmt.Sprintf("block_%#x-%d-%#x-", block.Hash().Bytes()[:4], i, tx.Hash().Bytes()[:4])
   637  			if !canon {
   638  				prefix = fmt.Sprintf("%valt-", prefix)
   639  			}
   640  			dump, err = ioutil.TempFile(os.TempDir(), prefix)
   641  			if err != nil {
   642  				return nil, err
   643  			}
   644  			dumps = append(dumps, dump.Name())
   645  
   646  			// Swap out the noop logger to the standard tracer
   647  			writer = bufio.NewWriter(dump)
   648  			vmConf = vm.Config{
   649  				Debug:                   true,
   650  				Tracer:                  vm.NewJSONLogger(&logConfig, writer),
   651  				EnablePreimageRecording: true,
   652  			}
   653  		}
   654  		// Execute the transaction and flush any traces to disk
   655  		vmenv := vm.NewEVM(vmctx, txContext, statedb, chainConfig, vmConf)
   656  		statedb.Prepare(tx.Hash(), i)
   657  		_, err = core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas()))
   658  		if writer != nil {
   659  			writer.Flush()
   660  		}
   661  		if dump != nil {
   662  			dump.Close()
   663  			log.Info("Wrote standard trace", "file", dump.Name())
   664  		}
   665  		if err != nil {
   666  			return dumps, err
   667  		}
   668  		// Finalize the state so any modifications are written to the trie
   669  		// Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
   670  		statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
   671  
   672  		// If we've traced the transaction we were looking for, abort
   673  		if tx.Hash() == txHash {
   674  			break
   675  		}
   676  	}
   677  	return dumps, nil
   678  }
   679  
   680  // containsTx reports whether the transaction with a certain hash
   681  // is contained within the specified block.
   682  func containsTx(block *types.Block, hash common.Hash) bool {
   683  	for _, tx := range block.Transactions() {
   684  		if tx.Hash() == hash {
   685  			return true
   686  		}
   687  	}
   688  	return false
   689  }
   690  
   691  // TraceTransaction returns the structured logs created during the execution of EVM
   692  // and returns them as a JSON object.
   693  func (api *API) TraceTransaction(ctx context.Context, hash common.Hash, config *TraceConfig) (interface{}, error) {
   694  	_, blockHash, blockNumber, index, err := api.backend.GetTransaction(ctx, hash)
   695  	if err != nil {
   696  		return nil, err
   697  	}
   698  	// It shouldn't happen in practice.
   699  	if blockNumber == 0 {
   700  		return nil, errors.New("genesis is not traceable")
   701  	}
   702  	reexec := defaultTraceReexec
   703  	if config != nil && config.Reexec != nil {
   704  		reexec = *config.Reexec
   705  	}
   706  	block, err := api.blockByNumberAndHash(ctx, rpc.BlockNumber(blockNumber), blockHash)
   707  	if err != nil {
   708  		return nil, err
   709  	}
   710  	msg, vmctx, statedb, err := api.backend.StateAtTransaction(ctx, block, int(index), reexec)
   711  	if err != nil {
   712  		return nil, err
   713  	}
   714  	txctx := &Context{
   715  		BlockHash: blockHash,
   716  		TxIndex:   int(index),
   717  		TxHash:    hash,
   718  	}
   719  	return api.traceTx(ctx, msg, txctx, vmctx, statedb, config)
   720  }
   721  
   722  // TraceCall lets you trace a given eth_call. It collects the structured logs
   723  // created during the execution of EVM if the given transaction was added on
   724  // top of the provided block and returns them as a JSON object.
   725  // You can provide -2 as a block number to trace on top of the pending block.
   726  func (api *API) TraceCall(ctx context.Context, args ethapi.TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, config *TraceCallConfig) (interface{}, error) {
   727  	// Try to retrieve the specified block
   728  	var (
   729  		err   error
   730  		block *types.Block
   731  	)
   732  	if hash, ok := blockNrOrHash.Hash(); ok {
   733  		block, err = api.blockByHash(ctx, hash)
   734  	} else if number, ok := blockNrOrHash.Number(); ok {
   735  		block, err = api.blockByNumber(ctx, number)
   736  	} else {
   737  		return nil, errors.New("invalid arguments; neither block nor hash specified")
   738  	}
   739  	if err != nil {
   740  		return nil, err
   741  	}
   742  	// try to recompute the state
   743  	reexec := defaultTraceReexec
   744  	if config != nil && config.Reexec != nil {
   745  		reexec = *config.Reexec
   746  	}
   747  	statedb, err := api.backend.StateAtBlock(ctx, block, reexec, nil, true)
   748  	if err != nil {
   749  		return nil, err
   750  	}
   751  	// Apply the customized state rules if required.
   752  	if config != nil {
   753  		if err := config.StateOverrides.Apply(statedb); err != nil {
   754  			return nil, err
   755  		}
   756  	}
   757  	// Execute the trace
   758  	msg, err := args.ToMessage(api.backend.RPCGasCap(), block.BaseFee())
   759  	if err != nil {
   760  		return nil, err
   761  	}
   762  	vmctx := core.NewEVMBlockContext(block.Header(), api.chainContext(ctx), nil)
   763  
   764  	var traceConfig *TraceConfig
   765  	if config != nil {
   766  		traceConfig = &TraceConfig{
   767  			LogConfig: config.LogConfig,
   768  			Tracer:    config.Tracer,
   769  			Timeout:   config.Timeout,
   770  			Reexec:    config.Reexec,
   771  		}
   772  	}
   773  	return api.traceTx(ctx, msg, new(Context), vmctx, statedb, traceConfig)
   774  }
   775  
   776  // traceTx configures a new tracer according to the provided configuration, and
   777  // executes the given message in the provided environment. The return value will
   778  // be tracer dependent.
   779  func (api *API) traceTx(ctx context.Context, message core.Message, txctx *Context, vmctx vm.BlockContext, statedb *state.StateDB, config *TraceConfig) (interface{}, error) {
   780  	// Assemble the structured logger or the JavaScript tracer
   781  	var (
   782  		tracer    vm.Tracer
   783  		err       error
   784  		txContext = core.NewEVMTxContext(message)
   785  	)
   786  	switch {
   787  	case config != nil && config.Tracer != nil:
   788  		// Define a meaningful timeout of a single transaction trace
   789  		timeout := defaultTraceTimeout
   790  		if config.Timeout != nil {
   791  			if timeout, err = time.ParseDuration(*config.Timeout); err != nil {
   792  				return nil, err
   793  			}
   794  		}
   795  		// Constuct the JavaScript tracer to execute with
   796  		if tracer, err = New(*config.Tracer, txctx); err != nil {
   797  			return nil, err
   798  		}
   799  		// Handle timeouts and RPC cancellations
   800  		deadlineCtx, cancel := context.WithTimeout(ctx, timeout)
   801  		go func() {
   802  			<-deadlineCtx.Done()
   803  			if deadlineCtx.Err() == context.DeadlineExceeded {
   804  				tracer.(*Tracer).Stop(errors.New("execution timeout"))
   805  			}
   806  		}()
   807  		defer cancel()
   808  
   809  	case config == nil:
   810  		tracer = vm.NewStructLogger(nil)
   811  
   812  	default:
   813  		tracer = vm.NewStructLogger(config.LogConfig)
   814  	}
   815  	// Run the transaction with tracing enabled.
   816  	vmenv := vm.NewEVM(vmctx, txContext, statedb, api.backend.ChainConfig(), vm.Config{Debug: true, Tracer: tracer, NoBaseFee: true})
   817  
   818  	// Call Prepare to clear out the statedb access list
   819  	statedb.Prepare(txctx.TxHash, txctx.TxIndex)
   820  
   821  	result, err := core.ApplyMessage(vmenv, message, new(core.GasPool).AddGas(message.Gas()))
   822  	if err != nil {
   823  		return nil, fmt.Errorf("tracing failed: %w", err)
   824  	}
   825  
   826  	// Depending on the tracer type, format and return the output.
   827  	switch tracer := tracer.(type) {
   828  	case *vm.StructLogger:
   829  		// If the result contains a revert reason, return it.
   830  		returnVal := fmt.Sprintf("%x", result.Return())
   831  		if len(result.Revert()) > 0 {
   832  			returnVal = fmt.Sprintf("%x", result.Revert())
   833  		}
   834  		return &ethapi.ExecutionResult{
   835  			Gas:         result.UsedGas,
   836  			Failed:      result.Failed(),
   837  			ReturnValue: returnVal,
   838  			StructLogs:  ethapi.FormatLogs(tracer.StructLogs()),
   839  		}, nil
   840  
   841  	case *Tracer:
   842  		return tracer.GetResult()
   843  
   844  	default:
   845  		panic(fmt.Sprintf("bad tracer type %T", tracer))
   846  	}
   847  }
   848  
   849  // APIs return the collection of RPC services the tracer package offers.
   850  func APIs(backend Backend) []rpc.API {
   851  	// Append all the local APIs and return
   852  	return []rpc.API{
   853  		{
   854  			Namespace: "debug",
   855  			Version:   "1.0",
   856  			Service:   NewAPI(backend),
   857  			Public:    false,
   858  		},
   859  	}
   860  }