github.com/intfoundation/intchain@v0.0.0-20220727031208-4316ad31ca73/intprotocol/api_tracer.go (about)

     1  // Copyright 2017 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 intprotocol
    18  
    19  import (
    20  	"bytes"
    21  	"context"
    22  	"errors"
    23  	"fmt"
    24  	"io/ioutil"
    25  	"runtime"
    26  	"sync"
    27  	"time"
    28  
    29  	"github.com/intfoundation/intchain/common"
    30  	"github.com/intfoundation/intchain/common/hexutil"
    31  	"github.com/intfoundation/intchain/core"
    32  	"github.com/intfoundation/intchain/core/rawdb"
    33  	"github.com/intfoundation/intchain/core/state"
    34  	"github.com/intfoundation/intchain/core/types"
    35  	"github.com/intfoundation/intchain/core/vm"
    36  	"github.com/intfoundation/intchain/internal/intapi"
    37  	"github.com/intfoundation/intchain/intprotocol/tracers"
    38  	"github.com/intfoundation/intchain/log"
    39  	"github.com/intfoundation/intchain/rlp"
    40  	"github.com/intfoundation/intchain/rpc"
    41  	"github.com/intfoundation/intchain/trie"
    42  )
    43  
    44  const (
    45  	// defaultTraceTimeout is the amount of time a single transaction can execute
    46  	// by default before being forcefully aborted.
    47  	defaultTraceTimeout = 5 * time.Second
    48  
    49  	// defaultTraceReexec is the number of blocks the tracer is willing to go back
    50  	// and reexecute to produce missing historical state necessary to run a specific
    51  	// trace.
    52  	defaultTraceReexec = uint64(128)
    53  )
    54  
    55  // TraceConfig holds extra parameters to trace functions.
    56  type TraceConfig struct {
    57  	*vm.LogConfig
    58  	Tracer  *string
    59  	Timeout *string
    60  	Reexec  *uint64
    61  }
    62  
    63  // StdTraceConfig holds extra parameters to standard-json trace functions.
    64  type StdTraceConfig struct {
    65  	*vm.LogConfig
    66  	Reexec *uint64
    67  	TxHash common.Hash
    68  }
    69  
    70  // txTraceResult is the result of a single transaction trace.
    71  type txTraceResult struct {
    72  	Result interface{} `json:"result,omitempty"` // Trace results produced by the tracer
    73  	Error  string      `json:"error,omitempty"`  // Trace failure produced by the tracer
    74  }
    75  
    76  // blockTraceTask represents a single block trace task when an entire chain is
    77  // being traced.
    78  type blockTraceTask struct {
    79  	statedb *state.StateDB   // Intermediate state prepped for tracing
    80  	block   *types.Block     // Block to trace the transactions from
    81  	rootref common.Hash      // Trie root reference held for this task
    82  	results []*txTraceResult // Trace results procudes by the task
    83  }
    84  
    85  // blockTraceResult represets the results of tracing a single block when an entire
    86  // chain is being traced.
    87  type blockTraceResult struct {
    88  	Block  hexutil.Uint64   `json:"block"`  // Block number corresponding to this trace
    89  	Hash   common.Hash      `json:"hash"`   // Block hash corresponding to this trace
    90  	Traces []*txTraceResult `json:"traces"` // Trace results produced by the task
    91  }
    92  
    93  // txTraceTask represents a single transaction trace task when an entire block
    94  // is being traced.
    95  type txTraceTask struct {
    96  	statedb *state.StateDB // Intermediate state prepped for tracing
    97  	index   int            // Transaction offset in the block
    98  }
    99  
   100  // TraceChain returns the structured logs created during the execution of EVM
   101  // between two blocks (excluding start) and returns them as a JSON object.
   102  func (api *PrivateDebugAPI) TraceChain(ctx context.Context, start, end rpc.BlockNumber, config *TraceConfig) (*rpc.Subscription, error) {
   103  	// Fetch the block interval that we want to trace
   104  	var from, to *types.Block
   105  
   106  	switch start {
   107  	case rpc.PendingBlockNumber:
   108  		from = api.eth.miner.PendingBlock()
   109  	case rpc.LatestBlockNumber:
   110  		from = api.eth.blockchain.CurrentBlock()
   111  	default:
   112  		from = api.eth.blockchain.GetBlockByNumber(uint64(start))
   113  	}
   114  	switch end {
   115  	case rpc.PendingBlockNumber:
   116  		to = api.eth.miner.PendingBlock()
   117  	case rpc.LatestBlockNumber:
   118  		to = api.eth.blockchain.CurrentBlock()
   119  	default:
   120  		to = api.eth.blockchain.GetBlockByNumber(uint64(end))
   121  	}
   122  	// Trace the chain if we've found all our blocks
   123  	if from == nil {
   124  		return nil, fmt.Errorf("starting block #%d not found", start)
   125  	}
   126  	if to == nil {
   127  		return nil, fmt.Errorf("end block #%d not found", end)
   128  	}
   129  	if from.Number().Cmp(to.Number()) >= 0 {
   130  		return nil, fmt.Errorf("end block (#%d) needs to come after start block (#%d)", end, start)
   131  	}
   132  	return api.traceChain(ctx, from, to, config)
   133  }
   134  
   135  // traceChain configures a new tracer according to the provided configuration, and
   136  // executes all the transactions contained within. The return value will be one item
   137  // per transaction, dependent on the requested tracer.
   138  func (api *PrivateDebugAPI) traceChain(ctx context.Context, start, end *types.Block, config *TraceConfig) (*rpc.Subscription, error) {
   139  	// Tracing a chain is a **long** operation, only do with subscriptions
   140  	notifier, supported := rpc.NotifierFromContext(ctx)
   141  	if !supported {
   142  		return &rpc.Subscription{}, rpc.ErrNotificationsUnsupported
   143  	}
   144  	sub := notifier.CreateSubscription()
   145  
   146  	// Ensure we have a valid starting state before doing any work
   147  	origin := start.NumberU64()
   148  	database := state.NewDatabaseWithCache(api.eth.ChainDb(), 16) // Chain tracing will probably start at genesis
   149  
   150  	if number := start.NumberU64(); number > 0 {
   151  		start = api.eth.blockchain.GetBlock(start.ParentHash(), start.NumberU64()-1)
   152  		if start == nil {
   153  			return nil, fmt.Errorf("parent block #%d not found", number-1)
   154  		}
   155  	}
   156  	statedb, err := state.New(start.Root(), database)
   157  	if err != nil {
   158  		// If the starting state is missing, allow some number of blocks to be reexecuted
   159  		reexec := defaultTraceReexec
   160  		if config != nil && config.Reexec != nil {
   161  			reexec = *config.Reexec
   162  		}
   163  		// Find the most recent block that has the state available
   164  		for i := uint64(0); i < reexec; i++ {
   165  			start = api.eth.blockchain.GetBlock(start.ParentHash(), start.NumberU64()-1)
   166  			if start == nil {
   167  				break
   168  			}
   169  			if statedb, err = state.New(start.Root(), database); err == nil {
   170  				break
   171  			}
   172  		}
   173  		// If we still don't have the state available, bail out
   174  		if err != nil {
   175  			switch err.(type) {
   176  			case *trie.MissingNodeError:
   177  				return nil, errors.New("required historical state unavailable")
   178  			default:
   179  				return nil, err
   180  			}
   181  		}
   182  	}
   183  	// Execute all the transaction contained within the chain concurrently for each block
   184  	blocks := int(end.NumberU64() - origin)
   185  
   186  	threads := runtime.NumCPU()
   187  	if threads > blocks {
   188  		threads = blocks
   189  	}
   190  	var (
   191  		pend    = new(sync.WaitGroup)
   192  		tasks   = make(chan *blockTraceTask, threads)
   193  		results = make(chan *blockTraceTask, threads)
   194  	)
   195  	for th := 0; th < threads; th++ {
   196  		pend.Add(1)
   197  		go func() {
   198  			defer pend.Done()
   199  
   200  			// Fetch and execute the next block trace tasks
   201  			for task := range tasks {
   202  				signer := types.MakeSigner(api.eth.blockchain.Config(), task.block.Number())
   203  
   204  				// Trace all the transactions contained within
   205  				for i, tx := range task.block.Transactions() {
   206  					msg, _ := tx.AsMessage(signer)
   207  					vmctx := core.NewEVMContext(msg, task.block.Header(), api.eth.blockchain, nil)
   208  
   209  					res, err := api.traceTx(ctx, msg, vmctx, task.statedb, config)
   210  					if err != nil {
   211  						task.results[i] = &txTraceResult{Error: err.Error()}
   212  						log.Warn("Tracing failed", "hash", tx.Hash(), "block", task.block.NumberU64(), "err", err)
   213  						break
   214  					}
   215  					// Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
   216  					task.statedb.Finalise(api.eth.blockchain.Config().IsEIP158(task.block.Number()))
   217  					task.results[i] = &txTraceResult{Result: res}
   218  				}
   219  				// Stream the result back to the user or abort on teardown
   220  				select {
   221  				case results <- task:
   222  				case <-notifier.Closed():
   223  					return
   224  				}
   225  			}
   226  		}()
   227  	}
   228  	// Start a goroutine to feed all the blocks into the tracers
   229  	begin := time.Now()
   230  
   231  	go func() {
   232  		var (
   233  			logged time.Time
   234  			number uint64
   235  			traced uint64
   236  			failed error
   237  			proot  common.Hash
   238  		)
   239  		// Ensure everything is properly cleaned up on any exit path
   240  		defer func() {
   241  			close(tasks)
   242  			pend.Wait()
   243  
   244  			switch {
   245  			case failed != nil:
   246  				log.Warn("Chain tracing failed", "start", start.NumberU64(), "end", end.NumberU64(), "transactions", traced, "elapsed", time.Since(begin), "err", failed)
   247  			case number < end.NumberU64():
   248  				log.Warn("Chain tracing aborted", "start", start.NumberU64(), "end", end.NumberU64(), "abort", number, "transactions", traced, "elapsed", time.Since(begin))
   249  			default:
   250  				log.Info("Chain tracing finished", "start", start.NumberU64(), "end", end.NumberU64(), "transactions", traced, "elapsed", time.Since(begin))
   251  			}
   252  			close(results)
   253  		}()
   254  		// Feed all the blocks both into the tracer, as well as fast process concurrently
   255  		for number = start.NumberU64() + 1; number <= end.NumberU64(); number++ {
   256  			// Stop tracing if interruption was requested
   257  			select {
   258  			case <-notifier.Closed():
   259  				return
   260  			default:
   261  			}
   262  			// Print progress logs if long enough time elapsed
   263  			if time.Since(logged) > 8*time.Second {
   264  				if number > origin {
   265  					nodes, imgs := database.TrieDB().Size()
   266  					log.Info("Tracing chain segment", "start", origin, "end", end.NumberU64(), "current", number, "transactions", traced, "elapsed", time.Since(begin), "memory", nodes+imgs)
   267  				} else {
   268  					log.Info("Preparing state for chain trace", "block", number, "start", origin, "elapsed", time.Since(begin))
   269  				}
   270  				logged = time.Now()
   271  			}
   272  			// Retrieve the next block to trace
   273  			block := api.eth.blockchain.GetBlockByNumber(number)
   274  			if block == nil {
   275  				failed = fmt.Errorf("block #%d not found", number)
   276  				break
   277  			}
   278  			// Send the block over to the concurrent tracers (if not in the fast-forward phase)
   279  			if number > origin {
   280  				txs := block.Transactions()
   281  
   282  				select {
   283  				case tasks <- &blockTraceTask{statedb: statedb.Copy(), block: block, rootref: proot, results: make([]*txTraceResult, len(txs))}:
   284  				case <-notifier.Closed():
   285  					return
   286  				}
   287  				traced += uint64(len(txs))
   288  			}
   289  			// Generate the next state snapshot fast without tracing
   290  			_, _, _, _, err := api.eth.blockchain.Processor().Process(block, statedb, vm.Config{})
   291  			if err != nil {
   292  				failed = err
   293  				break
   294  			}
   295  			// Finalize the state so any modifications are written to the trie
   296  			root, err := statedb.Commit(api.eth.blockchain.Config().IsEIP158(block.Number()))
   297  			if err != nil {
   298  				failed = err
   299  				break
   300  			}
   301  			if err := statedb.Reset(root); err != nil {
   302  				failed = err
   303  				break
   304  			}
   305  			// Reference the trie twice, once for us, once for the tracer
   306  			database.TrieDB().Reference(root, common.Hash{})
   307  			if number >= origin {
   308  				database.TrieDB().Reference(root, common.Hash{})
   309  			}
   310  			// Dereference all past tries we ourselves are done working with
   311  			if proot != (common.Hash{}) {
   312  				database.TrieDB().Dereference(proot)
   313  			}
   314  			proot = root
   315  
   316  			// TODO(karalabe): Do we need the preimages? Won't they accumulate too much?
   317  		}
   318  	}()
   319  
   320  	// Keep reading the trace results and stream the to the user
   321  	go func() {
   322  		var (
   323  			done = make(map[uint64]*blockTraceResult)
   324  			next = origin + 1
   325  		)
   326  		for res := range results {
   327  			// Queue up next received result
   328  			result := &blockTraceResult{
   329  				Block:  hexutil.Uint64(res.block.NumberU64()),
   330  				Hash:   res.block.Hash(),
   331  				Traces: res.results,
   332  			}
   333  			done[uint64(result.Block)] = result
   334  
   335  			// Dereference any paret tries held in memory by this task
   336  			database.TrieDB().Dereference(res.rootref)
   337  
   338  			// Stream completed traces to the user, aborting on the first error
   339  			for result, ok := done[next]; ok; result, ok = done[next] {
   340  				if len(result.Traces) > 0 || next == end.NumberU64() {
   341  					notifier.Notify(sub.ID, result)
   342  				}
   343  				delete(done, next)
   344  				next++
   345  			}
   346  		}
   347  	}()
   348  	return sub, nil
   349  }
   350  
   351  // TraceBlockByNumber returns the structured logs created during the execution of
   352  // EVM and returns them as a JSON object.
   353  func (api *PrivateDebugAPI) TraceBlockByNumber(ctx context.Context, number rpc.BlockNumber, config *TraceConfig) ([]*txTraceResult, error) {
   354  	// Fetch the block that we want to trace
   355  	var block *types.Block
   356  
   357  	switch number {
   358  	case rpc.PendingBlockNumber:
   359  		block = api.eth.miner.PendingBlock()
   360  	case rpc.LatestBlockNumber:
   361  		block = api.eth.blockchain.CurrentBlock()
   362  	default:
   363  		block = api.eth.blockchain.GetBlockByNumber(uint64(number))
   364  	}
   365  	// Trace the block if it was found
   366  	if block == nil {
   367  		return nil, fmt.Errorf("block #%d not found", number)
   368  	}
   369  	return api.traceBlock(ctx, block, config)
   370  }
   371  
   372  // TraceBlockByHash returns the structured logs created during the execution of
   373  // EVM and returns them as a JSON object.
   374  func (api *PrivateDebugAPI) TraceBlockByHash(ctx context.Context, hash common.Hash, config *TraceConfig) ([]*txTraceResult, error) {
   375  	block := api.eth.blockchain.GetBlockByHash(hash)
   376  	if block == nil {
   377  		return nil, fmt.Errorf("block #%x not found", hash)
   378  	}
   379  	return api.traceBlock(ctx, block, config)
   380  }
   381  
   382  // TraceBlock returns the structured logs created during the execution of EVM
   383  // and returns them as a JSON object.
   384  func (api *PrivateDebugAPI) TraceBlock(ctx context.Context, blob []byte, config *TraceConfig) ([]*txTraceResult, error) {
   385  	block := new(types.Block)
   386  	if err := rlp.Decode(bytes.NewReader(blob), block); err != nil {
   387  		return nil, fmt.Errorf("could not decode block: %v", err)
   388  	}
   389  	return api.traceBlock(ctx, block, config)
   390  }
   391  
   392  // TraceBlockFromFile returns the structured logs created during the execution of
   393  // EVM and returns them as a JSON object.
   394  func (api *PrivateDebugAPI) TraceBlockFromFile(ctx context.Context, file string, config *TraceConfig) ([]*txTraceResult, error) {
   395  	blob, err := ioutil.ReadFile(file)
   396  	if err != nil {
   397  		return nil, fmt.Errorf("could not read file: %v", err)
   398  	}
   399  	return api.TraceBlock(ctx, blob, config)
   400  }
   401  
   402  // traceBlock configures a new tracer according to the provided configuration, and
   403  // executes all the transactions contained within. The return value will be one item
   404  // per transaction, dependent on the requestd tracer.
   405  func (api *PrivateDebugAPI) traceBlock(ctx context.Context, block *types.Block, config *TraceConfig) ([]*txTraceResult, error) {
   406  	// Create the parent state database
   407  	if err := api.eth.engine.VerifyHeader(api.eth.blockchain, block.Header(), true); err != nil {
   408  		return nil, err
   409  	}
   410  	parent := api.eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
   411  	if parent == nil {
   412  		return nil, fmt.Errorf("parent #%x not found", block.ParentHash())
   413  	}
   414  	reexec := defaultTraceReexec
   415  	if config != nil && config.Reexec != nil {
   416  		reexec = *config.Reexec
   417  	}
   418  	statedb, err := api.computeStateDB(parent, reexec)
   419  	if err != nil {
   420  		return nil, err
   421  	}
   422  	// Execute all the transaction contained within the block concurrently
   423  	var (
   424  		signer = types.MakeSigner(api.eth.blockchain.Config(), block.Number())
   425  
   426  		txs     = block.Transactions()
   427  		results = make([]*txTraceResult, len(txs))
   428  
   429  		pend = new(sync.WaitGroup)
   430  		jobs = make(chan *txTraceTask, len(txs))
   431  	)
   432  	threads := runtime.NumCPU()
   433  	if threads > len(txs) {
   434  		threads = len(txs)
   435  	}
   436  	for th := 0; th < threads; th++ {
   437  		pend.Add(1)
   438  		go func() {
   439  			defer pend.Done()
   440  
   441  			// Fetch and execute the next transaction trace tasks
   442  			for task := range jobs {
   443  				msg, _ := txs[task.index].AsMessage(signer)
   444  				vmctx := core.NewEVMContext(msg, block.Header(), api.eth.blockchain, nil)
   445  
   446  				res, err := api.traceTx(ctx, msg, vmctx, task.statedb, config)
   447  				if err != nil {
   448  					results[task.index] = &txTraceResult{Error: err.Error()}
   449  					continue
   450  				}
   451  				results[task.index] = &txTraceResult{Result: res}
   452  			}
   453  		}()
   454  	}
   455  	// Feed the transactions into the tracers and return
   456  	var failed error
   457  	for i, tx := range txs {
   458  		// Send the trace task over for execution
   459  		jobs <- &txTraceTask{statedb: statedb.Copy(), index: i}
   460  
   461  		// Generate the next state snapshot fast without tracing
   462  		msg, _ := tx.AsMessage(signer)
   463  		vmctx := core.NewEVMContext(msg, block.Header(), api.eth.blockchain, nil)
   464  
   465  		vmenv := vm.NewEVM(vmctx, statedb, api.eth.blockchain.Config(), vm.Config{})
   466  		if _, _, err := core.ApplyMessageEx(vmenv, msg, new(core.GasPool).AddGas(msg.Gas())); err != nil {
   467  			failed = err
   468  			break
   469  		}
   470  		// Finalize the state so any modifications are written to the trie
   471  		// Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
   472  		statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
   473  	}
   474  	close(jobs)
   475  	pend.Wait()
   476  
   477  	// If execution failed in between, abort
   478  	if failed != nil {
   479  		return nil, failed
   480  	}
   481  	return results, nil
   482  }
   483  
   484  // standardTraceBlockToFile configures a new tracer which uses standard JSON output,
   485  // and traces either a full block or an individual transaction. The return value will
   486  // be one filename per transaction traced.
   487  //func (api *PrivateDebugAPI) standardTraceBlockToFile(ctx context.Context, block *types.Block, config *StdTraceConfig) ([]string, error) {
   488  //	// If we're tracing a single transaction, make sure it's present
   489  //	if config != nil && config.TxHash != (common.Hash{}) {
   490  //		if !containsTx(block, config.TxHash) {
   491  //			return nil, fmt.Errorf("transaction %#x not found in block", config.TxHash)
   492  //		}
   493  //	}
   494  //	// Create the parent state database
   495  //	if err := api.eth.engine.VerifyHeader(api.eth.blockchain, block.Header(), true); err != nil {
   496  //		return nil, err
   497  //	}
   498  //	parent := api.eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
   499  //	if parent == nil {
   500  //		return nil, fmt.Errorf("parent %#x not found", block.ParentHash())
   501  //	}
   502  //	reexec := defaultTraceReexec
   503  //	if config != nil && config.Reexec != nil {
   504  //		reexec = *config.Reexec
   505  //	}
   506  //	statedb, err := api.computeStateDB(parent, reexec)
   507  //	if err != nil {
   508  //		return nil, err
   509  //	}
   510  //	// Retrieve the tracing configurations, or use default values
   511  //	var (
   512  //		logConfig vm.LogConfig
   513  //		txHash    common.Hash
   514  //	)
   515  //	if config != nil {
   516  //		if config.LogConfig != nil {
   517  //			logConfig = *config.LogConfig
   518  //		}
   519  //		txHash = config.TxHash
   520  //	}
   521  //	logConfig.Debug = true
   522  //
   523  //	// Execute transaction, either tracing all or just the requested one
   524  //	var (
   525  //		signer = types.MakeSigner(api.eth.blockchain.Config(), block.Number())
   526  //		dumps  []string
   527  //	)
   528  //	for i, tx := range block.Transactions() {
   529  //		// Prepare the trasaction for un-traced execution
   530  //		var (
   531  //			msg, _ = tx.AsMessage(signer)
   532  //			vmctx  = core.NewEVMContext(msg, block.Header(), api.eth.blockchain, nil)
   533  //
   534  //			vmConf vm.Config
   535  //			dump   *os.File
   536  //			writer *bufio.Writer
   537  //			err    error
   538  //		)
   539  //		// If the transaction needs tracing, swap out the configs
   540  //		if tx.Hash() == txHash || txHash == (common.Hash{}) {
   541  //			// Generate a unique temporary file to dump it into
   542  //			prefix := fmt.Sprintf("block_%#x-%d-%#x-", block.Hash().Bytes()[:4], i, tx.Hash().Bytes()[:4])
   543  //
   544  //			dump, err = ioutil.TempFile(os.TempDir(), prefix)
   545  //			if err != nil {
   546  //				return nil, err
   547  //			}
   548  //			dumps = append(dumps, dump.Name())
   549  //
   550  //			// Swap out the noop logger to the standard tracer
   551  //			writer = bufio.NewWriter(dump)
   552  //			vmConf = vm.Config{
   553  //				Debug:                   true,
   554  //				Tracer:                  vm.NewJSONLogger(&logConfig, writer),
   555  //				EnablePreimageRecording: true,
   556  //			}
   557  //		}
   558  //		// Execute the transaction and flush any traces to disk
   559  //		vmenv := vm.NewEVM(vmctx, statedb, api.eth.blockchain.Config(), vmConf)
   560  //		_, _, _, err = core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas()))
   561  //		if writer != nil {
   562  //			writer.Flush()
   563  //		}
   564  //		if dump != nil {
   565  //			dump.Close()
   566  //			log.Info("Wrote standard trace", "file", dump.Name())
   567  //		}
   568  //		if err != nil {
   569  //			return dumps, err
   570  //		}
   571  //		// Finalize the state so any modifications are written to the trie
   572  //		// Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
   573  //		statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
   574  //
   575  //		// If we've traced the transaction we were looking for, abort
   576  //		if tx.Hash() == txHash {
   577  //			break
   578  //		}
   579  //	}
   580  //	return dumps, nil
   581  //}
   582  //
   583  //// containsTx reports whether the transaction with a certain hash
   584  //// is contained within the specified block.
   585  //func containsTx(block *types.Block, hash common.Hash) bool {
   586  //	for _, tx := range block.Transactions() {
   587  //		if tx.Hash() == hash {
   588  //			return true
   589  //		}
   590  //	}
   591  //	return false
   592  //}
   593  
   594  // computeStateDB retrieves the state database associated with a certain block.
   595  // If no state is locally available for the given block, a number of blocks are
   596  // attempted to be reexecuted to generate the desired state.
   597  func (api *PrivateDebugAPI) computeStateDB(block *types.Block, reexec uint64) (*state.StateDB, error) {
   598  	// If we have the state fully available, use that
   599  	statedb, err := api.eth.blockchain.StateAt(block.Root())
   600  	if err == nil {
   601  		return statedb, nil
   602  	}
   603  	// Otherwise try to reexec blocks until we find a state or reach our limit
   604  	origin := block.NumberU64()
   605  	database := state.NewDatabaseWithCache(api.eth.ChainDb(), 16)
   606  
   607  	for i := uint64(0); i < reexec; i++ {
   608  		block = api.eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
   609  		if block == nil {
   610  			break
   611  		}
   612  		if statedb, err = state.New(block.Root(), database); err == nil {
   613  			break
   614  		}
   615  	}
   616  	if err != nil {
   617  		switch err.(type) {
   618  		case *trie.MissingNodeError:
   619  			return nil, fmt.Errorf("required historical state unavailable (reexec=%d)", reexec)
   620  		default:
   621  			return nil, err
   622  		}
   623  	}
   624  	// State was available at historical point, regenerate
   625  	var (
   626  		start  = time.Now()
   627  		logged time.Time
   628  		proot  common.Hash
   629  	)
   630  	for block.NumberU64() < origin {
   631  		// Print progress logs if long enough time elapsed
   632  		if time.Since(logged) > 8*time.Second {
   633  			log.Info("Regenerating historical state", "block", block.NumberU64()+1, "target", origin, "remaining", origin-block.NumberU64()-1, "elapsed", time.Since(start))
   634  			logged = time.Now()
   635  		}
   636  		// Retrieve the next block to regenerate and process it
   637  		if block = api.eth.blockchain.GetBlockByNumber(block.NumberU64() + 1); block == nil {
   638  			return nil, fmt.Errorf("block #%d not found", block.NumberU64()+1)
   639  		}
   640  		_, _, _, _, err := api.eth.blockchain.Processor().Process(block, statedb, vm.Config{})
   641  		if err != nil {
   642  			return nil, fmt.Errorf("processing block %d failed: %v", block.NumberU64(), err)
   643  		}
   644  		// Finalize the state so any modifications are written to the trie
   645  		root, err := statedb.Commit(api.eth.blockchain.Config().IsEIP158(block.Number()))
   646  		if err != nil {
   647  			return nil, err
   648  		}
   649  		if err := statedb.Reset(root); err != nil {
   650  			return nil, fmt.Errorf("state reset after block %d failed: %v", block.NumberU64(), err)
   651  		}
   652  		database.TrieDB().Reference(root, common.Hash{})
   653  		if proot != (common.Hash{}) {
   654  			database.TrieDB().Dereference(proot)
   655  		}
   656  		proot = root
   657  	}
   658  	nodes, imgs := database.TrieDB().Size()
   659  	log.Info("Historical state regenerated", "block", block.NumberU64(), "elapsed", time.Since(start), "nodes", nodes, "preimages", imgs)
   660  	return statedb, nil
   661  }
   662  
   663  // TraceTransaction returns the structured logs created during the execution of EVM
   664  // and returns them as a JSON object.
   665  func (api *PrivateDebugAPI) TraceTransaction(ctx context.Context, hash common.Hash, config *TraceConfig) (interface{}, error) {
   666  	// Retrieve the transaction and assemble its EVM context
   667  	tx, blockHash, _, index := rawdb.ReadTransaction(api.eth.ChainDb(), hash)
   668  	if tx == nil {
   669  		return nil, fmt.Errorf("transaction #%x not found", hash)
   670  	}
   671  	reexec := defaultTraceReexec
   672  	if config != nil && config.Reexec != nil {
   673  		reexec = *config.Reexec
   674  	}
   675  	msg, vmctx, statedb, err := api.computeTxEnv(blockHash, int(index), reexec)
   676  	if err != nil {
   677  		return nil, err
   678  	}
   679  	// Trace the transaction and return
   680  	return api.traceTx(ctx, msg, vmctx, statedb, config)
   681  }
   682  
   683  // traceTx configures a new tracer according to the provided configuration, and
   684  // executes the given message in the provided environment. The return value will
   685  // be tracer dependent.
   686  func (api *PrivateDebugAPI) traceTx(ctx context.Context, message core.Message, vmctx vm.Context, statedb *state.StateDB, config *TraceConfig) (interface{}, error) {
   687  	// Assemble the structured logger or the JavaScript tracer
   688  	var (
   689  		tracer vm.Tracer
   690  		err    error
   691  	)
   692  	switch {
   693  	case config != nil && config.Tracer != nil:
   694  		// Define a meaningful timeout of a single transaction trace
   695  		timeout := defaultTraceTimeout
   696  		if config.Timeout != nil {
   697  			if timeout, err = time.ParseDuration(*config.Timeout); err != nil {
   698  				return nil, err
   699  			}
   700  		}
   701  		// Constuct the JavaScript tracer to execute with
   702  		if tracer, err = tracers.New(*config.Tracer); err != nil {
   703  			return nil, err
   704  		}
   705  		// Handle timeouts and RPC cancellations
   706  		deadlineCtx, cancel := context.WithTimeout(ctx, timeout)
   707  		go func() {
   708  			<-deadlineCtx.Done()
   709  			tracer.(*tracers.Tracer).Stop(errors.New("execution timeout"))
   710  		}()
   711  		defer cancel()
   712  
   713  	case config == nil:
   714  		tracer = vm.NewStructLogger(nil)
   715  
   716  	default:
   717  		tracer = vm.NewStructLogger(config.LogConfig)
   718  	}
   719  	// Run the transaction with tracing enabled.
   720  	vmenv := vm.NewEVM(vmctx, statedb, api.eth.blockchain.Config(), vm.Config{Debug: true, Tracer: tracer})
   721  
   722  	result, _, err := core.ApplyMessageEx(vmenv, message, new(core.GasPool).AddGas(message.Gas()))
   723  	if err != nil {
   724  		return nil, fmt.Errorf("tracing failed: %v", err)
   725  	}
   726  	// Depending on the tracer type, format and return the output
   727  	switch tracer := tracer.(type) {
   728  	case *vm.StructLogger:
   729  		return &intapi.ExecutionResult{
   730  			Gas:         result.UsedGas,
   731  			Failed:      result.Failed(),
   732  			ReturnValue: fmt.Sprintf("%x", result.Revert()),
   733  			StructLogs:  intapi.FormatLogs(tracer.StructLogs()),
   734  		}, nil
   735  
   736  	case *tracers.Tracer:
   737  		return tracer.GetResult()
   738  
   739  	default:
   740  		panic(fmt.Sprintf("bad tracer type %T", tracer))
   741  	}
   742  }
   743  
   744  // computeTxEnv returns the execution environment of a certain transaction.
   745  func (api *PrivateDebugAPI) computeTxEnv(blockHash common.Hash, txIndex int, reexec uint64) (core.Message, vm.Context, *state.StateDB, error) {
   746  	// Create the parent state database
   747  	block := api.eth.blockchain.GetBlockByHash(blockHash)
   748  	if block == nil {
   749  		return nil, vm.Context{}, nil, fmt.Errorf("block %#x not found", blockHash)
   750  	}
   751  	parent := api.eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
   752  	if parent == nil {
   753  		return nil, vm.Context{}, nil, fmt.Errorf("parent %#x not found", block.ParentHash())
   754  	}
   755  	statedb, err := api.computeStateDB(parent, reexec)
   756  	if err != nil {
   757  		return nil, vm.Context{}, nil, err
   758  	}
   759  
   760  	if txIndex == 0 && len(block.Transactions()) == 0 {
   761  		return nil, vm.Context{}, statedb, nil
   762  	}
   763  
   764  	// Recompute transactions up to the target index.
   765  	signer := types.MakeSigner(api.eth.blockchain.Config(), block.Number())
   766  
   767  	for idx, tx := range block.Transactions() {
   768  		// Assemble the transaction call message and return if the requested offset
   769  		msg, _ := tx.AsMessage(signer)
   770  		context := core.NewEVMContext(msg, block.Header(), api.eth.blockchain, nil)
   771  		if idx == txIndex {
   772  			return msg, context, statedb, nil
   773  		}
   774  		// Not yet the searched for transaction, execute on top of the current state
   775  		vmenv := vm.NewEVM(context, statedb, api.eth.blockchain.Config(), vm.Config{})
   776  		if _, _, err := core.ApplyMessageEx(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
   777  			return nil, vm.Context{}, nil, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err)
   778  		}
   779  		// Ensure any modifications are committed to the state
   780  		// Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
   781  		statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
   782  	}
   783  	return nil, vm.Context{}, nil, fmt.Errorf("transaction index %d out of range for block %#x", txIndex, blockHash)
   784  }