github.com/daragao/go-ethereum@v1.8.14-0.20180809141559-45eaef243198/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  			if proot != (common.Hash{}) {
   301  				database.TrieDB().Dereference(proot)
   302  			}
   303  			proot = root
   304  
   305  			// TODO(karalabe): Do we need the preimages? Won't they accumulate too much?
   306  		}
   307  	}()
   308  
   309  	// Keep reading the trace results and stream the to the user
   310  	go func() {
   311  		var (
   312  			done = make(map[uint64]*blockTraceResult)
   313  			next = origin + 1
   314  		)
   315  		for res := range results {
   316  			// Queue up next received result
   317  			result := &blockTraceResult{
   318  				Block:  hexutil.Uint64(res.block.NumberU64()),
   319  				Hash:   res.block.Hash(),
   320  				Traces: res.results,
   321  			}
   322  			done[uint64(result.Block)] = result
   323  
   324  			// Dereference any paret tries held in memory by this task
   325  			database.TrieDB().Dereference(res.rootref)
   326  
   327  			// Stream completed traces to the user, aborting on the first error
   328  			for result, ok := done[next]; ok; result, ok = done[next] {
   329  				if len(result.Traces) > 0 || next == end.NumberU64() {
   330  					notifier.Notify(sub.ID, result)
   331  				}
   332  				delete(done, next)
   333  				next++
   334  			}
   335  		}
   336  	}()
   337  	return sub, nil
   338  }
   339  
   340  // TraceBlockByNumber returns the structured logs created during the execution of
   341  // EVM and returns them as a JSON object.
   342  func (api *PrivateDebugAPI) TraceBlockByNumber(ctx context.Context, number rpc.BlockNumber, config *TraceConfig) ([]*txTraceResult, error) {
   343  	// Fetch the block that we want to trace
   344  	var block *types.Block
   345  
   346  	switch number {
   347  	case rpc.PendingBlockNumber:
   348  		block = api.eth.miner.PendingBlock()
   349  	case rpc.LatestBlockNumber:
   350  		block = api.eth.blockchain.CurrentBlock()
   351  	default:
   352  		block = api.eth.blockchain.GetBlockByNumber(uint64(number))
   353  	}
   354  	// Trace the block if it was found
   355  	if block == nil {
   356  		return nil, fmt.Errorf("block #%d not found", number)
   357  	}
   358  	return api.traceBlock(ctx, block, config)
   359  }
   360  
   361  // TraceBlockByHash returns the structured logs created during the execution of
   362  // EVM and returns them as a JSON object.
   363  func (api *PrivateDebugAPI) TraceBlockByHash(ctx context.Context, hash common.Hash, config *TraceConfig) ([]*txTraceResult, error) {
   364  	block := api.eth.blockchain.GetBlockByHash(hash)
   365  	if block == nil {
   366  		return nil, fmt.Errorf("block #%x not found", hash)
   367  	}
   368  	return api.traceBlock(ctx, block, config)
   369  }
   370  
   371  // TraceBlock returns the structured logs created during the execution of EVM
   372  // and returns them as a JSON object.
   373  func (api *PrivateDebugAPI) TraceBlock(ctx context.Context, blob []byte, config *TraceConfig) ([]*txTraceResult, error) {
   374  	block := new(types.Block)
   375  	if err := rlp.Decode(bytes.NewReader(blob), block); err != nil {
   376  		return nil, fmt.Errorf("could not decode block: %v", err)
   377  	}
   378  	return api.traceBlock(ctx, block, config)
   379  }
   380  
   381  // TraceBlockFromFile returns the structured logs created during the execution of
   382  // EVM and returns them as a JSON object.
   383  func (api *PrivateDebugAPI) TraceBlockFromFile(ctx context.Context, file string, config *TraceConfig) ([]*txTraceResult, error) {
   384  	blob, err := ioutil.ReadFile(file)
   385  	if err != nil {
   386  		return nil, fmt.Errorf("could not read file: %v", err)
   387  	}
   388  	return api.TraceBlock(ctx, blob, config)
   389  }
   390  
   391  // traceBlock configures a new tracer according to the provided configuration, and
   392  // executes all the transactions contained within. The return value will be one item
   393  // per transaction, dependent on the requestd tracer.
   394  func (api *PrivateDebugAPI) traceBlock(ctx context.Context, block *types.Block, config *TraceConfig) ([]*txTraceResult, error) {
   395  	// Create the parent state database
   396  	if err := api.eth.engine.VerifyHeader(api.eth.blockchain, block.Header(), true); err != nil {
   397  		return nil, err
   398  	}
   399  	parent := api.eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
   400  	if parent == nil {
   401  		return nil, fmt.Errorf("parent %x not found", block.ParentHash())
   402  	}
   403  	reexec := defaultTraceReexec
   404  	if config != nil && config.Reexec != nil {
   405  		reexec = *config.Reexec
   406  	}
   407  	statedb, err := api.computeStateDB(parent, reexec)
   408  	if err != nil {
   409  		return nil, err
   410  	}
   411  	// Execute all the transaction contained within the block concurrently
   412  	var (
   413  		signer = types.MakeSigner(api.config, block.Number())
   414  
   415  		txs     = block.Transactions()
   416  		results = make([]*txTraceResult, len(txs))
   417  
   418  		pend = new(sync.WaitGroup)
   419  		jobs = make(chan *txTraceTask, len(txs))
   420  	)
   421  	threads := runtime.NumCPU()
   422  	if threads > len(txs) {
   423  		threads = len(txs)
   424  	}
   425  	for th := 0; th < threads; th++ {
   426  		pend.Add(1)
   427  		go func() {
   428  			defer pend.Done()
   429  
   430  			// Fetch and execute the next transaction trace tasks
   431  			for task := range jobs {
   432  				msg, _ := txs[task.index].AsMessage(signer)
   433  				vmctx := core.NewEVMContext(msg, block.Header(), api.eth.blockchain, nil)
   434  
   435  				res, err := api.traceTx(ctx, msg, vmctx, task.statedb, config)
   436  				if err != nil {
   437  					results[task.index] = &txTraceResult{Error: err.Error()}
   438  					continue
   439  				}
   440  				results[task.index] = &txTraceResult{Result: res}
   441  			}
   442  		}()
   443  	}
   444  	// Feed the transactions into the tracers and return
   445  	var failed error
   446  	for i, tx := range txs {
   447  		// Send the trace task over for execution
   448  		jobs <- &txTraceTask{statedb: statedb.Copy(), index: i}
   449  
   450  		// Generate the next state snapshot fast without tracing
   451  		msg, _ := tx.AsMessage(signer)
   452  		vmctx := core.NewEVMContext(msg, block.Header(), api.eth.blockchain, nil)
   453  
   454  		vmenv := vm.NewEVM(vmctx, statedb, api.config, vm.Config{})
   455  		if _, _, _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas())); err != nil {
   456  			failed = err
   457  			break
   458  		}
   459  		// Finalize the state so any modifications are written to the trie
   460  		statedb.Finalise(true)
   461  	}
   462  	close(jobs)
   463  	pend.Wait()
   464  
   465  	// If execution failed in between, abort
   466  	if failed != nil {
   467  		return nil, failed
   468  	}
   469  	return results, nil
   470  }
   471  
   472  // computeStateDB retrieves the state database associated with a certain block.
   473  // If no state is locally available for the given block, a number of blocks are
   474  // attempted to be reexecuted to generate the desired state.
   475  func (api *PrivateDebugAPI) computeStateDB(block *types.Block, reexec uint64) (*state.StateDB, error) {
   476  	// If we have the state fully available, use that
   477  	statedb, err := api.eth.blockchain.StateAt(block.Root())
   478  	if err == nil {
   479  		return statedb, nil
   480  	}
   481  	// Otherwise try to reexec blocks until we find a state or reach our limit
   482  	origin := block.NumberU64()
   483  	database := state.NewDatabase(api.eth.ChainDb())
   484  
   485  	for i := uint64(0); i < reexec; i++ {
   486  		block = api.eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
   487  		if block == nil {
   488  			break
   489  		}
   490  		if statedb, err = state.New(block.Root(), database); err == nil {
   491  			break
   492  		}
   493  	}
   494  	if err != nil {
   495  		switch err.(type) {
   496  		case *trie.MissingNodeError:
   497  			return nil, errors.New("required historical state unavailable")
   498  		default:
   499  			return nil, err
   500  		}
   501  	}
   502  	// State was available at historical point, regenerate
   503  	var (
   504  		start  = time.Now()
   505  		logged time.Time
   506  		proot  common.Hash
   507  	)
   508  	for block.NumberU64() < origin {
   509  		// Print progress logs if long enough time elapsed
   510  		if time.Since(logged) > 8*time.Second {
   511  			log.Info("Regenerating historical state", "block", block.NumberU64()+1, "target", origin, "elapsed", time.Since(start))
   512  			logged = time.Now()
   513  		}
   514  		// Retrieve the next block to regenerate and process it
   515  		if block = api.eth.blockchain.GetBlockByNumber(block.NumberU64() + 1); block == nil {
   516  			return nil, fmt.Errorf("block #%d not found", block.NumberU64()+1)
   517  		}
   518  		_, _, _, err := api.eth.blockchain.Processor().Process(block, statedb, vm.Config{})
   519  		if err != nil {
   520  			return nil, err
   521  		}
   522  		// Finalize the state so any modifications are written to the trie
   523  		root, err := statedb.Commit(true)
   524  		if err != nil {
   525  			return nil, err
   526  		}
   527  		if err := statedb.Reset(root); err != nil {
   528  			return nil, err
   529  		}
   530  		database.TrieDB().Reference(root, common.Hash{})
   531  		if proot != (common.Hash{}) {
   532  			database.TrieDB().Dereference(proot)
   533  		}
   534  		proot = root
   535  	}
   536  	nodes, imgs := database.TrieDB().Size()
   537  	log.Info("Historical state regenerated", "block", block.NumberU64(), "elapsed", time.Since(start), "nodes", nodes, "preimages", imgs)
   538  	return statedb, nil
   539  }
   540  
   541  // TraceTransaction returns the structured logs created during the execution of EVM
   542  // and returns them as a JSON object.
   543  func (api *PrivateDebugAPI) TraceTransaction(ctx context.Context, hash common.Hash, config *TraceConfig) (interface{}, error) {
   544  	// Retrieve the transaction and assemble its EVM context
   545  	tx, blockHash, _, index := rawdb.ReadTransaction(api.eth.ChainDb(), hash)
   546  	if tx == nil {
   547  		return nil, fmt.Errorf("transaction %x not found", hash)
   548  	}
   549  	reexec := defaultTraceReexec
   550  	if config != nil && config.Reexec != nil {
   551  		reexec = *config.Reexec
   552  	}
   553  	msg, vmctx, statedb, err := api.computeTxEnv(blockHash, int(index), reexec)
   554  	if err != nil {
   555  		return nil, err
   556  	}
   557  	// Trace the transaction and return
   558  	return api.traceTx(ctx, msg, vmctx, statedb, config)
   559  }
   560  
   561  // traceTx configures a new tracer according to the provided configuration, and
   562  // executes the given message in the provided environment. The return value will
   563  // be tracer dependent.
   564  func (api *PrivateDebugAPI) traceTx(ctx context.Context, message core.Message, vmctx vm.Context, statedb *state.StateDB, config *TraceConfig) (interface{}, error) {
   565  	// Assemble the structured logger or the JavaScript tracer
   566  	var (
   567  		tracer vm.Tracer
   568  		err    error
   569  	)
   570  	switch {
   571  	case config != nil && config.Tracer != nil:
   572  		// Define a meaningful timeout of a single transaction trace
   573  		timeout := defaultTraceTimeout
   574  		if config.Timeout != nil {
   575  			if timeout, err = time.ParseDuration(*config.Timeout); err != nil {
   576  				return nil, err
   577  			}
   578  		}
   579  		// Constuct the JavaScript tracer to execute with
   580  		if tracer, err = tracers.New(*config.Tracer); err != nil {
   581  			return nil, err
   582  		}
   583  		// Handle timeouts and RPC cancellations
   584  		deadlineCtx, cancel := context.WithTimeout(ctx, timeout)
   585  		go func() {
   586  			<-deadlineCtx.Done()
   587  			tracer.(*tracers.Tracer).Stop(errors.New("execution timeout"))
   588  		}()
   589  		defer cancel()
   590  
   591  	case config == nil:
   592  		tracer = vm.NewStructLogger(nil)
   593  
   594  	default:
   595  		tracer = vm.NewStructLogger(config.LogConfig)
   596  	}
   597  	// Run the transaction with tracing enabled.
   598  	vmenv := vm.NewEVM(vmctx, statedb, api.config, vm.Config{Debug: true, Tracer: tracer})
   599  
   600  	ret, gas, failed, err := core.ApplyMessage(vmenv, message, new(core.GasPool).AddGas(message.Gas()))
   601  	if err != nil {
   602  		return nil, fmt.Errorf("tracing failed: %v", err)
   603  	}
   604  	// Depending on the tracer type, format and return the output
   605  	switch tracer := tracer.(type) {
   606  	case *vm.StructLogger:
   607  		return &ethapi.ExecutionResult{
   608  			Gas:         gas,
   609  			Failed:      failed,
   610  			ReturnValue: fmt.Sprintf("%x", ret),
   611  			StructLogs:  ethapi.FormatLogs(tracer.StructLogs()),
   612  		}, nil
   613  
   614  	case *tracers.Tracer:
   615  		return tracer.GetResult()
   616  
   617  	default:
   618  		panic(fmt.Sprintf("bad tracer type %T", tracer))
   619  	}
   620  }
   621  
   622  // computeTxEnv returns the execution environment of a certain transaction.
   623  func (api *PrivateDebugAPI) computeTxEnv(blockHash common.Hash, txIndex int, reexec uint64) (core.Message, vm.Context, *state.StateDB, error) {
   624  	// Create the parent state database
   625  	block := api.eth.blockchain.GetBlockByHash(blockHash)
   626  	if block == nil {
   627  		return nil, vm.Context{}, nil, fmt.Errorf("block %x not found", blockHash)
   628  	}
   629  	parent := api.eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
   630  	if parent == nil {
   631  		return nil, vm.Context{}, nil, fmt.Errorf("parent %x not found", block.ParentHash())
   632  	}
   633  	statedb, err := api.computeStateDB(parent, reexec)
   634  	if err != nil {
   635  		return nil, vm.Context{}, nil, err
   636  	}
   637  	// Recompute transactions up to the target index.
   638  	signer := types.MakeSigner(api.config, block.Number())
   639  
   640  	for idx, tx := range block.Transactions() {
   641  		// Assemble the transaction call message and return if the requested offset
   642  		msg, _ := tx.AsMessage(signer)
   643  		context := core.NewEVMContext(msg, block.Header(), api.eth.blockchain, nil)
   644  		if idx == txIndex {
   645  			return msg, context, statedb, nil
   646  		}
   647  		// Not yet the searched for transaction, execute on top of the current state
   648  		vmenv := vm.NewEVM(context, statedb, api.config, vm.Config{})
   649  		if _, _, _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
   650  			return nil, vm.Context{}, nil, fmt.Errorf("tx %x failed: %v", tx.Hash(), err)
   651  		}
   652  		// Ensure any modifications are committed to the state
   653  		statedb.Finalise(true)
   654  	}
   655  	return nil, vm.Context{}, nil, fmt.Errorf("tx index %d out of range for block %x", txIndex, blockHash)
   656  }