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