github.com/ImPedro29/bor@v0.2.7/eth/tracers/api.go (about)

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