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