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