github.com/janotchain/janota@v0.0.0-20220824112012-93ea4c5dee78/eth/api.go (about)

     1  // Copyright 2015 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  	"compress/gzip"
    22  	"context"
    23  	"fmt"
    24  	"io"
    25  	"io/ioutil"
    26  	"math/big"
    27  	"os"
    28  	"strings"
    29  	"time"
    30  
    31  	"github.com/ethereum/go-ethereum/common"
    32  	"github.com/ethereum/go-ethereum/common/hexutil"
    33  	"github.com/ethereum/go-ethereum/core"
    34  	"github.com/ethereum/go-ethereum/core/state"
    35  	"github.com/ethereum/go-ethereum/core/types"
    36  	"github.com/ethereum/go-ethereum/core/vm"
    37  	"github.com/ethereum/go-ethereum/internal/ethapi"
    38  	"github.com/ethereum/go-ethereum/log"
    39  	"github.com/ethereum/go-ethereum/miner"
    40  	"github.com/ethereum/go-ethereum/params"
    41  	"github.com/ethereum/go-ethereum/rlp"
    42  	"github.com/ethereum/go-ethereum/rpc"
    43  	"github.com/ethereum/go-ethereum/trie"
    44  )
    45  
    46  const defaultTraceTimeout = 5 * time.Second
    47  
    48  // PublicEthereumAPI provides an API to access Ethereum full node-related
    49  // information.
    50  type PublicEthereumAPI struct {
    51  	e *Ethereum
    52  }
    53  
    54  // NewPublicEthereumAPI creates a new Ethereum protocol API for full nodes.
    55  func NewPublicEthereumAPI(e *Ethereum) *PublicEthereumAPI {
    56  	return &PublicEthereumAPI{e}
    57  }
    58  
    59  // Etherbase is the address that mining rewards will be send to
    60  func (api *PublicEthereumAPI) Etherbase() (common.Address, error) {
    61  	return api.e.Etherbase()
    62  }
    63  
    64  // Coinbase is the address that mining rewards will be send to (alias for Etherbase)
    65  func (api *PublicEthereumAPI) Coinbase() (common.Address, error) {
    66  	return api.Etherbase()
    67  }
    68  
    69  // Hashrate returns the POW hashrate
    70  func (api *PublicEthereumAPI) Hashrate() hexutil.Uint64 {
    71  	return hexutil.Uint64(api.e.Miner().HashRate())
    72  }
    73  
    74  // ChainId is the EIP-155 replay-protection chain id for the current ethereum chain config.
    75  func (api *PublicEthereumAPI) ChainId() hexutil.Uint64 {
    76      chainID := api.e.chainConfig.ChainId
    77  	return (hexutil.Uint64)(chainID.Uint64())
    78  }
    79  
    80  // PublicMinerAPI provides an API to control the miner.
    81  // It offers only methods that operate on data that pose no security risk when it is publicly accessible.
    82  type PublicMinerAPI struct {
    83  	e     *Ethereum
    84  	agent *miner.RemoteAgent
    85  }
    86  
    87  // NewPublicMinerAPI create a new PublicMinerAPI instance.
    88  func NewPublicMinerAPI(e *Ethereum) *PublicMinerAPI {
    89  	agent := miner.NewRemoteAgent(e.BlockChain(), e.Engine())
    90  	e.Miner().Register(agent)
    91  
    92  	return &PublicMinerAPI{e, agent}
    93  }
    94  
    95  // Mining returns an indication if this node is currently mining.
    96  func (api *PublicMinerAPI) Mining() bool {
    97  	return api.e.IsMining()
    98  }
    99  
   100  // SubmitWork can be used by external miner to submit their POW solution. It returns an indication if the work was
   101  // accepted. Note, this is not an indication if the provided work was valid!
   102  func (api *PublicMinerAPI) SubmitWork(nonce types.BlockNonce, solution, digest common.Hash) bool {
   103  	return api.agent.SubmitWork(nonce, digest, solution)
   104  }
   105  
   106  // GetWork returns a work package for external miner. The work package consists of 3 strings
   107  // result[0], 32 bytes hex encoded current block header pow-hash
   108  // result[1], 32 bytes hex encoded seed hash used for DAG
   109  // result[2], 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty
   110  func (api *PublicMinerAPI) GetWork() ([3]string, error) {
   111  	if !api.e.IsMining() {
   112  		if err := api.e.StartMining(false); err != nil {
   113  			return [3]string{}, err
   114  		}
   115  	}
   116  	work, err := api.agent.GetWork()
   117  	if err != nil {
   118  		return work, fmt.Errorf("mining not ready: %v", err)
   119  	}
   120  	return work, nil
   121  }
   122  
   123  // SubmitHashrate can be used for remote miners to submit their hash rate. This enables the node to report the combined
   124  // hash rate of all miners which submit work through this node. It accepts the miner hash rate and an identifier which
   125  // must be unique between nodes.
   126  func (api *PublicMinerAPI) SubmitHashrate(hashrate hexutil.Uint64, id common.Hash) bool {
   127  	api.agent.SubmitHashrate(id, uint64(hashrate))
   128  	return true
   129  }
   130  
   131  // PrivateMinerAPI provides private RPC methods to control the miner.
   132  // These methods can be abused by external users and must be considered insecure for use by untrusted users.
   133  type PrivateMinerAPI struct {
   134  	e *Ethereum
   135  }
   136  
   137  // NewPrivateMinerAPI create a new RPC service which controls the miner of this node.
   138  func NewPrivateMinerAPI(e *Ethereum) *PrivateMinerAPI {
   139  	return &PrivateMinerAPI{e: e}
   140  }
   141  
   142  // Start the miner with the given number of threads. If threads is nil the number
   143  // of workers started is equal to the number of logical CPUs that are usable by
   144  // this process. If mining is already running, this method adjust the number of
   145  // threads allowed to use.
   146  func (api *PrivateMinerAPI) Start(threads *int) error {
   147  	// Set the number of threads if the seal engine supports it
   148  	if threads == nil {
   149  		threads = new(int)
   150  	} else if *threads == 0 {
   151  		*threads = -1 // Disable the miner from within
   152  	}
   153  	type threaded interface {
   154  		SetThreads(threads int)
   155  	}
   156  	if th, ok := api.e.engine.(threaded); ok {
   157  		log.Info("Updated mining threads", "threads", *threads)
   158  		th.SetThreads(*threads)
   159  	}
   160  	// Start the miner and return
   161  	if !api.e.IsMining() {
   162  		// Propagate the initial price point to the transaction pool
   163  		api.e.lock.RLock()
   164  		price := api.e.gasPrice
   165  		api.e.lock.RUnlock()
   166  
   167  		api.e.txPool.SetGasPrice(price)
   168  		return api.e.StartMining(true)
   169  	}
   170  	return nil
   171  }
   172  
   173  // Stop the miner
   174  func (api *PrivateMinerAPI) Stop() bool {
   175  	type threaded interface {
   176  		SetThreads(threads int)
   177  	}
   178  	if th, ok := api.e.engine.(threaded); ok {
   179  		th.SetThreads(-1)
   180  	}
   181  	api.e.StopMining()
   182  	return true
   183  }
   184  
   185  // SetExtra sets the extra data string that is included when this miner mines a block.
   186  func (api *PrivateMinerAPI) SetExtra(extra string) (bool, error) {
   187  	if err := api.e.Miner().SetExtra([]byte(extra)); err != nil {
   188  		return false, err
   189  	}
   190  	return true, nil
   191  }
   192  
   193  // SetGasPrice sets the minimum accepted gas price for the miner.
   194  func (api *PrivateMinerAPI) SetGasPrice(gasPrice hexutil.Big) bool {
   195  	api.e.lock.Lock()
   196  	api.e.gasPrice = (*big.Int)(&gasPrice)
   197  	api.e.lock.Unlock()
   198  
   199  	api.e.txPool.SetGasPrice((*big.Int)(&gasPrice))
   200  	return true
   201  }
   202  
   203  // SetEtherbase sets the etherbase of the miner
   204  func (api *PrivateMinerAPI) SetEtherbase(etherbase common.Address) bool {
   205  	api.e.SetEtherbase(etherbase)
   206  	return true
   207  }
   208  
   209  // GetHashrate returns the current hashrate of the miner.
   210  func (api *PrivateMinerAPI) GetHashrate() uint64 {
   211  	return uint64(api.e.miner.HashRate())
   212  }
   213  
   214  // PrivateAdminAPI is the collection of Ethereum full node-related APIs
   215  // exposed over the private admin endpoint.
   216  type PrivateAdminAPI struct {
   217  	eth *Ethereum
   218  }
   219  
   220  // NewPrivateAdminAPI creates a new API definition for the full node private
   221  // admin methods of the Ethereum service.
   222  func NewPrivateAdminAPI(eth *Ethereum) *PrivateAdminAPI {
   223  	return &PrivateAdminAPI{eth: eth}
   224  }
   225  
   226  // ExportChain exports the current blockchain into a local file.
   227  func (api *PrivateAdminAPI) ExportChain(file string) (bool, error) {
   228  	// Make sure we can create the file to export into
   229  	out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
   230  	if err != nil {
   231  		return false, err
   232  	}
   233  	defer out.Close()
   234  
   235  	var writer io.Writer = out
   236  	if strings.HasSuffix(file, ".gz") {
   237  		writer = gzip.NewWriter(writer)
   238  		defer writer.(*gzip.Writer).Close()
   239  	}
   240  
   241  	// Export the blockchain
   242  	if err := api.eth.BlockChain().Export(writer); err != nil {
   243  		return false, err
   244  	}
   245  	return true, nil
   246  }
   247  
   248  func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
   249  	for _, b := range bs {
   250  		if !chain.HasBlock(b.Hash(), b.NumberU64()) {
   251  			return false
   252  		}
   253  	}
   254  
   255  	return true
   256  }
   257  
   258  // ImportChain imports a blockchain from a local file.
   259  func (api *PrivateAdminAPI) ImportChain(file string) (bool, error) {
   260  	// Make sure the can access the file to import
   261  	in, err := os.Open(file)
   262  	if err != nil {
   263  		return false, err
   264  	}
   265  	defer in.Close()
   266  
   267  	var reader io.Reader = in
   268  	if strings.HasSuffix(file, ".gz") {
   269  		if reader, err = gzip.NewReader(reader); err != nil {
   270  			return false, err
   271  		}
   272  	}
   273  
   274  	// Run actual the import in pre-configured batches
   275  	stream := rlp.NewStream(reader, 0)
   276  
   277  	blocks, index := make([]*types.Block, 0, 2500), 0
   278  	for batch := 0; ; batch++ {
   279  		// Load a batch of blocks from the input file
   280  		for len(blocks) < cap(blocks) {
   281  			block := new(types.Block)
   282  			if err := stream.Decode(block); err == io.EOF {
   283  				break
   284  			} else if err != nil {
   285  				return false, fmt.Errorf("block %d: failed to parse: %v", index, err)
   286  			}
   287  			blocks = append(blocks, block)
   288  			index++
   289  		}
   290  		if len(blocks) == 0 {
   291  			break
   292  		}
   293  
   294  		if hasAllBlocks(api.eth.BlockChain(), blocks) {
   295  			blocks = blocks[:0]
   296  			continue
   297  		}
   298  		// Import the batch and reset the buffer
   299  		if _, err := api.eth.BlockChain().InsertChain(blocks); err != nil {
   300  			return false, fmt.Errorf("batch %d: failed to insert: %v", batch, err)
   301  		}
   302  		blocks = blocks[:0]
   303  	}
   304  	return true, nil
   305  }
   306  
   307  // PublicDebugAPI is the collection of Ethereum full node APIs exposed
   308  // over the public debugging endpoint.
   309  type PublicDebugAPI struct {
   310  	eth *Ethereum
   311  }
   312  
   313  // NewPublicDebugAPI creates a new API definition for the full node-
   314  // related public debug methods of the Ethereum service.
   315  func NewPublicDebugAPI(eth *Ethereum) *PublicDebugAPI {
   316  	return &PublicDebugAPI{eth: eth}
   317  }
   318  
   319  // DumpBlock retrieves the entire state of the database at a given block.
   320  func (api *PublicDebugAPI) DumpBlock(blockNr rpc.BlockNumber) (state.Dump, error) {
   321  	if blockNr == rpc.PendingBlockNumber {
   322  		// If we're dumping the pending state, we need to request
   323  		// both the pending block as well as the pending state from
   324  		// the miner and operate on those
   325  		_, stateDb := api.eth.miner.Pending()
   326  		return stateDb.RawDump(), nil
   327  	}
   328  	var block *types.Block
   329  	if blockNr == rpc.LatestBlockNumber {
   330  		block = api.eth.blockchain.CurrentBlock()
   331  	} else {
   332  		block = api.eth.blockchain.GetBlockByNumber(uint64(blockNr))
   333  	}
   334  	if block == nil {
   335  		return state.Dump{}, fmt.Errorf("block #%d not found", blockNr)
   336  	}
   337  	stateDb, err := api.eth.BlockChain().StateAt(block.Root())
   338  	if err != nil {
   339  		return state.Dump{}, err
   340  	}
   341  	return stateDb.RawDump(), nil
   342  }
   343  
   344  // PrivateDebugAPI is the collection of Ethereum full node APIs exposed over
   345  // the private debugging endpoint.
   346  type PrivateDebugAPI struct {
   347  	config *params.ChainConfig
   348  	eth    *Ethereum
   349  }
   350  
   351  // NewPrivateDebugAPI creates a new API definition for the full node-related
   352  // private debug methods of the Ethereum service.
   353  func NewPrivateDebugAPI(config *params.ChainConfig, eth *Ethereum) *PrivateDebugAPI {
   354  	return &PrivateDebugAPI{config: config, eth: eth}
   355  }
   356  
   357  // BlockTraceResult is the returned value when replaying a block to check for
   358  // consensus results and full VM trace logs for all included transactions.
   359  type BlockTraceResult struct {
   360  	Validated  bool                  `json:"validated"`
   361  	StructLogs []ethapi.StructLogRes `json:"structLogs"`
   362  	Error      string                `json:"error"`
   363  }
   364  
   365  // TraceArgs holds extra parameters to trace functions
   366  type TraceArgs struct {
   367  	*vm.LogConfig
   368  	Tracer  *string
   369  	Timeout *string
   370  }
   371  
   372  // TraceBlock processes the given block'api RLP but does not import the block in to
   373  // the chain.
   374  func (api *PrivateDebugAPI) TraceBlock(blockRlp []byte, config *vm.LogConfig) BlockTraceResult {
   375  	var block types.Block
   376  	err := rlp.Decode(bytes.NewReader(blockRlp), &block)
   377  	if err != nil {
   378  		return BlockTraceResult{Error: fmt.Sprintf("could not decode block: %v", err)}
   379  	}
   380  
   381  	validated, logs, err := api.traceBlock(&block, config)
   382  	return BlockTraceResult{
   383  		Validated:  validated,
   384  		StructLogs: ethapi.FormatLogs(logs),
   385  		Error:      formatError(err),
   386  	}
   387  }
   388  
   389  // TraceBlockFromFile loads the block'api RLP from the given file name and attempts to
   390  // process it but does not import the block in to the chain.
   391  func (api *PrivateDebugAPI) TraceBlockFromFile(file string, config *vm.LogConfig) BlockTraceResult {
   392  	blockRlp, err := ioutil.ReadFile(file)
   393  	if err != nil {
   394  		return BlockTraceResult{Error: fmt.Sprintf("could not read file: %v", err)}
   395  	}
   396  	return api.TraceBlock(blockRlp, config)
   397  }
   398  
   399  // TraceBlockByNumber processes the block by canonical block number.
   400  func (api *PrivateDebugAPI) TraceBlockByNumber(blockNr rpc.BlockNumber, config *vm.LogConfig) BlockTraceResult {
   401  	// Fetch the block that we aim to reprocess
   402  	var block *types.Block
   403  	switch blockNr {
   404  	case rpc.PendingBlockNumber:
   405  		// Pending block is only known by the miner
   406  		block = api.eth.miner.PendingBlock()
   407  	case rpc.LatestBlockNumber:
   408  		block = api.eth.blockchain.CurrentBlock()
   409  	default:
   410  		block = api.eth.blockchain.GetBlockByNumber(uint64(blockNr))
   411  	}
   412  
   413  	if block == nil {
   414  		return BlockTraceResult{Error: fmt.Sprintf("block #%d not found", blockNr)}
   415  	}
   416  
   417  	validated, logs, err := api.traceBlock(block, config)
   418  	return BlockTraceResult{
   419  		Validated:  validated,
   420  		StructLogs: ethapi.FormatLogs(logs),
   421  		Error:      formatError(err),
   422  	}
   423  }
   424  
   425  // TraceBlockByHash processes the block by hash.
   426  func (api *PrivateDebugAPI) TraceBlockByHash(hash common.Hash, config *vm.LogConfig) BlockTraceResult {
   427  	// Fetch the block that we aim to reprocess
   428  	block := api.eth.BlockChain().GetBlockByHash(hash)
   429  	if block == nil {
   430  		return BlockTraceResult{Error: fmt.Sprintf("block #%x not found", hash)}
   431  	}
   432  
   433  	validated, logs, err := api.traceBlock(block, config)
   434  	return BlockTraceResult{
   435  		Validated:  validated,
   436  		StructLogs: ethapi.FormatLogs(logs),
   437  		Error:      formatError(err),
   438  	}
   439  }
   440  
   441  // traceBlock processes the given block but does not save the state.
   442  func (api *PrivateDebugAPI) traceBlock(block *types.Block, logConfig *vm.LogConfig) (bool, []vm.StructLog, error) {
   443  	// Validate and reprocess the block
   444  	var (
   445  		blockchain = api.eth.BlockChain()
   446  		validator  = blockchain.Validator()
   447  		processor  = blockchain.Processor()
   448  	)
   449  
   450  	structLogger := vm.NewStructLogger(logConfig)
   451  
   452  	config := vm.Config{
   453  		Debug:  true,
   454  		Tracer: structLogger,
   455  	}
   456  	if err := api.eth.engine.VerifyHeader(blockchain, block.Header(), true); err != nil {
   457  		return false, structLogger.StructLogs(), err
   458  	}
   459  	statedb, err := blockchain.StateAt(blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1).Root())
   460  	if err != nil {
   461  		return false, structLogger.StructLogs(), err
   462  	}
   463  
   464  	receipts, _, usedGas, err := processor.Process(block, statedb, config)
   465  	if err != nil {
   466  		return false, structLogger.StructLogs(), err
   467  	}
   468  	if err := validator.ValidateState(block, blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1), statedb, receipts, usedGas); err != nil {
   469  		return false, structLogger.StructLogs(), err
   470  	}
   471  	return true, structLogger.StructLogs(), nil
   472  }
   473  
   474  // formatError formats a Go error into either an empty string or the data content
   475  // of the error itself.
   476  func formatError(err error) string {
   477  	if err == nil {
   478  		return ""
   479  	}
   480  	return err.Error()
   481  }
   482  
   483  type timeoutError struct{}
   484  
   485  func (t *timeoutError) Error() string {
   486  	return "Execution time exceeded"
   487  }
   488  
   489  // TraceTransaction returns the structured logs created during the execution of EVM
   490  // and returns them as a JSON object.
   491  func (api *PrivateDebugAPI) TraceTransaction(ctx context.Context, txHash common.Hash, config *TraceArgs) (interface{}, error) {
   492  	var tracer vm.Tracer
   493  	if config != nil && config.Tracer != nil {
   494  		timeout := defaultTraceTimeout
   495  		if config.Timeout != nil {
   496  			var err error
   497  			if timeout, err = time.ParseDuration(*config.Timeout); err != nil {
   498  				return nil, err
   499  			}
   500  		}
   501  
   502  		var err error
   503  		if tracer, err = ethapi.NewJavascriptTracer(*config.Tracer); err != nil {
   504  			return nil, err
   505  		}
   506  
   507  		// Handle timeouts and RPC cancellations
   508  		deadlineCtx, cancel := context.WithTimeout(ctx, timeout)
   509  		go func() {
   510  			<-deadlineCtx.Done()
   511  			tracer.(*ethapi.JavascriptTracer).Stop(&timeoutError{})
   512  		}()
   513  		defer cancel()
   514  	} else if config == nil {
   515  		tracer = vm.NewStructLogger(nil)
   516  	} else {
   517  		tracer = vm.NewStructLogger(config.LogConfig)
   518  	}
   519  
   520  	// Retrieve the tx from the chain and the containing block
   521  	tx, blockHash, _, txIndex := core.GetTransaction(api.eth.ChainDb(), txHash)
   522  	if tx == nil {
   523  		return nil, fmt.Errorf("transaction %x not found", txHash)
   524  	}
   525  	msg, context, statedb, err := api.computeTxEnv(blockHash, int(txIndex))
   526  	if err != nil {
   527  		return nil, err
   528  	}
   529  
   530  	// Run the transaction with tracing enabled.
   531  	vmenv := vm.NewEVM(context, statedb, api.config, vm.Config{Debug: true, Tracer: tracer})
   532  	ret, gas, failed, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas()))
   533  	if err != nil {
   534  		return nil, fmt.Errorf("tracing failed: %v", err)
   535  	}
   536  	switch tracer := tracer.(type) {
   537  	case *vm.StructLogger:
   538  		return &ethapi.ExecutionResult{
   539  			Gas:         gas,
   540  			Failed:      failed,
   541  			ReturnValue: fmt.Sprintf("%x", ret),
   542  			StructLogs:  ethapi.FormatLogs(tracer.StructLogs()),
   543  		}, nil
   544  	case *ethapi.JavascriptTracer:
   545  		return tracer.GetResult()
   546  	default:
   547  		panic(fmt.Sprintf("bad tracer type %T", tracer))
   548  	}
   549  }
   550  
   551  // computeTxEnv returns the execution environment of a certain transaction.
   552  func (api *PrivateDebugAPI) computeTxEnv(blockHash common.Hash, txIndex int) (core.Message, vm.Context, *state.StateDB, error) {
   553  	// Create the parent state.
   554  	block := api.eth.BlockChain().GetBlockByHash(blockHash)
   555  	if block == nil {
   556  		return nil, vm.Context{}, nil, fmt.Errorf("block %x not found", blockHash)
   557  	}
   558  	parent := api.eth.BlockChain().GetBlock(block.ParentHash(), block.NumberU64()-1)
   559  	if parent == nil {
   560  		return nil, vm.Context{}, nil, fmt.Errorf("block parent %x not found", block.ParentHash())
   561  	}
   562  	statedb, err := api.eth.BlockChain().StateAt(parent.Root())
   563  	if err != nil {
   564  		return nil, vm.Context{}, nil, err
   565  	}
   566  	txs := block.Transactions()
   567  
   568  	// Recompute transactions up to the target index.
   569  	signer := types.MakeSigner(api.config, block.Number())
   570  	for idx, tx := range txs {
   571  		// Assemble the transaction call message
   572  		msg, _ := tx.AsMessage(signer)
   573  		context := core.NewEVMContext(msg, block.Header(), api.eth.BlockChain(), nil)
   574  		if idx == txIndex {
   575  			return msg, context, statedb, nil
   576  		}
   577  
   578  		vmenv := vm.NewEVM(context, statedb, api.config, vm.Config{})
   579  		gp := new(core.GasPool).AddGas(tx.Gas())
   580  		_, _, _, err := core.ApplyMessage(vmenv, msg, gp)
   581  		if err != nil {
   582  			return nil, vm.Context{}, nil, fmt.Errorf("tx %x failed: %v", tx.Hash(), err)
   583  		}
   584  		statedb.DeleteSuicides()
   585  	}
   586  	return nil, vm.Context{}, nil, fmt.Errorf("tx index %d out of range for block %x", txIndex, blockHash)
   587  }
   588  
   589  // Preimage is a debug API function that returns the preimage for a sha3 hash, if known.
   590  func (api *PrivateDebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
   591  	db := core.PreimageTable(api.eth.ChainDb())
   592  	return db.Get(hash.Bytes())
   593  }
   594  
   595  // GetBadBLocks returns a list of the last 'bad blocks' that the client has seen on the network
   596  // and returns them as a JSON list of block-hashes
   597  func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]core.BadBlockArgs, error) {
   598  	return api.eth.BlockChain().BadBlocks()
   599  }
   600  
   601  // StorageRangeResult is the result of a debug_storageRangeAt API call.
   602  type StorageRangeResult struct {
   603  	Storage storageMap   `json:"storage"`
   604  	NextKey *common.Hash `json:"nextKey"` // nil if Storage includes the last key in the trie.
   605  }
   606  
   607  type storageMap map[common.Hash]storageEntry
   608  
   609  type storageEntry struct {
   610  	Key   *common.Hash `json:"key"`
   611  	Value common.Hash  `json:"value"`
   612  }
   613  
   614  // StorageRangeAt returns the storage at the given block height and transaction index.
   615  func (api *PrivateDebugAPI) StorageRangeAt(ctx context.Context, blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) {
   616  	_, _, statedb, err := api.computeTxEnv(blockHash, txIndex)
   617  	if err != nil {
   618  		return StorageRangeResult{}, err
   619  	}
   620  	st := statedb.StorageTrie(contractAddress)
   621  	if st == nil {
   622  		return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress)
   623  	}
   624  	return storageRangeAt(st, keyStart, maxResult), nil
   625  }
   626  
   627  func storageRangeAt(st state.Trie, start []byte, maxResult int) StorageRangeResult {
   628  	it := trie.NewIterator(st.NodeIterator(start))
   629  	result := StorageRangeResult{Storage: storageMap{}}
   630  	for i := 0; i < maxResult && it.Next(); i++ {
   631  		e := storageEntry{Value: common.BytesToHash(it.Value)}
   632  		if preimage := st.GetKey(it.Key); preimage != nil {
   633  			preimage := common.BytesToHash(preimage)
   634  			e.Key = &preimage
   635  		}
   636  		result.Storage[common.BytesToHash(it.Key)] = e
   637  	}
   638  	// Add the 'next key' so clients can continue downloading.
   639  	if it.Next() {
   640  		next := common.BytesToHash(it.Key)
   641  		result.NextKey = &next
   642  	}
   643  	return result
   644  }
   645  
   646  // GetModifiedAccountsByumber returns all accounts that have changed between the
   647  // two blocks specified. A change is defined as a difference in nonce, balance,
   648  // code hash, or storage hash.
   649  //
   650  // With one parameter, returns the list of accounts modified in the specified block.
   651  func (api *PrivateDebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum *uint64) ([]common.Address, error) {
   652  	var startBlock, endBlock *types.Block
   653  
   654  	startBlock = api.eth.blockchain.GetBlockByNumber(startNum)
   655  	if startBlock == nil {
   656  		return nil, fmt.Errorf("start block %x not found", startNum)
   657  	}
   658  
   659  	if endNum == nil {
   660  		endBlock = startBlock
   661  		startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash())
   662  		if startBlock == nil {
   663  			return nil, fmt.Errorf("block %x has no parent", endBlock.Number())
   664  		}
   665  	} else {
   666  		endBlock = api.eth.blockchain.GetBlockByNumber(*endNum)
   667  		if endBlock == nil {
   668  			return nil, fmt.Errorf("end block %d not found", *endNum)
   669  		}
   670  	}
   671  	return api.getModifiedAccounts(startBlock, endBlock)
   672  }
   673  
   674  // GetModifiedAccountsByHash returns all accounts that have changed between the
   675  // two blocks specified. A change is defined as a difference in nonce, balance,
   676  // code hash, or storage hash.
   677  //
   678  // With one parameter, returns the list of accounts modified in the specified block.
   679  func (api *PrivateDebugAPI) GetModifiedAccountsByHash(startHash common.Hash, endHash *common.Hash) ([]common.Address, error) {
   680  	var startBlock, endBlock *types.Block
   681  	startBlock = api.eth.blockchain.GetBlockByHash(startHash)
   682  	if startBlock == nil {
   683  		return nil, fmt.Errorf("start block %x not found", startHash)
   684  	}
   685  
   686  	if endHash == nil {
   687  		endBlock = startBlock
   688  		startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash())
   689  		if startBlock == nil {
   690  			return nil, fmt.Errorf("block %x has no parent", endBlock.Number())
   691  		}
   692  	} else {
   693  		endBlock = api.eth.blockchain.GetBlockByHash(*endHash)
   694  		if endBlock == nil {
   695  			return nil, fmt.Errorf("end block %x not found", *endHash)
   696  		}
   697  	}
   698  	return api.getModifiedAccounts(startBlock, endBlock)
   699  }
   700  
   701  func (api *PrivateDebugAPI) getModifiedAccounts(startBlock, endBlock *types.Block) ([]common.Address, error) {
   702  	if startBlock.Number().Uint64() >= endBlock.Number().Uint64() {
   703  		return nil, fmt.Errorf("start block height (%d) must be less than end block height (%d)", startBlock.Number().Uint64(), endBlock.Number().Uint64())
   704  	}
   705  
   706  	oldTrie, err := trie.NewSecure(startBlock.Root(), api.eth.chainDb, 0)
   707  	if err != nil {
   708  		return nil, err
   709  	}
   710  	newTrie, err := trie.NewSecure(endBlock.Root(), api.eth.chainDb, 0)
   711  	if err != nil {
   712  		return nil, err
   713  	}
   714  
   715  	diff, _ := trie.NewDifferenceIterator(oldTrie.NodeIterator([]byte{}), newTrie.NodeIterator([]byte{}))
   716  	iter := trie.NewIterator(diff)
   717  
   718  	var dirty []common.Address
   719  	for iter.Next() {
   720  		key := newTrie.GetKey(iter.Key)
   721  		if key == nil {
   722  			return nil, fmt.Errorf("no preimage found for hash %x", iter.Key)
   723  		}
   724  		dirty = append(dirty, common.BytesToAddress(key))
   725  	}
   726  	return dirty, nil
   727  }