github.com/electroneum/electroneum-sc@v0.0.0-20230105223411-3bc1d078281e/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  	"compress/gzip"
    21  	"context"
    22  	"errors"
    23  	"fmt"
    24  	"io"
    25  	"math/big"
    26  	"os"
    27  	"runtime"
    28  	"strings"
    29  	"time"
    30  
    31  	"github.com/electroneum/electroneum-sc/common"
    32  	"github.com/electroneum/electroneum-sc/common/hexutil"
    33  	"github.com/electroneum/electroneum-sc/core"
    34  	"github.com/electroneum/electroneum-sc/core/rawdb"
    35  	"github.com/electroneum/electroneum-sc/core/state"
    36  	"github.com/electroneum/electroneum-sc/core/types"
    37  	"github.com/electroneum/electroneum-sc/internal/ethapi"
    38  	"github.com/electroneum/electroneum-sc/log"
    39  	"github.com/electroneum/electroneum-sc/rlp"
    40  	"github.com/electroneum/electroneum-sc/rpc"
    41  	"github.com/electroneum/electroneum-sc/trie"
    42  )
    43  
    44  // PublicEthereumAPI provides an API to access Ethereum full node-related
    45  // information.
    46  type PublicEthereumAPI struct {
    47  	e *Ethereum
    48  }
    49  
    50  // NewPublicEthereumAPI creates a new Ethereum protocol API for full nodes.
    51  func NewPublicEthereumAPI(e *Ethereum) *PublicEthereumAPI {
    52  	return &PublicEthereumAPI{e}
    53  }
    54  
    55  // Etherbase is the address that mining rewards will be send to
    56  func (api *PublicEthereumAPI) Etherbase() (common.Address, error) {
    57  	return api.e.Etherbase()
    58  }
    59  
    60  // Coinbase is the address that mining rewards will be send to (alias for Etherbase)
    61  func (api *PublicEthereumAPI) Coinbase() (common.Address, error) {
    62  	return api.Etherbase()
    63  }
    64  
    65  // Hashrate returns the POW hashrate
    66  func (api *PublicEthereumAPI) Hashrate() hexutil.Uint64 {
    67  	return hexutil.Uint64(api.e.Miner().Hashrate())
    68  }
    69  
    70  // PublicMinerAPI provides an API to control the miner.
    71  // It offers only methods that operate on data that pose no security risk when it is publicly accessible.
    72  type PublicMinerAPI struct {
    73  	e *Ethereum
    74  }
    75  
    76  // NewPublicMinerAPI create a new PublicMinerAPI instance.
    77  func NewPublicMinerAPI(e *Ethereum) *PublicMinerAPI {
    78  	return &PublicMinerAPI{e}
    79  }
    80  
    81  // Mining returns an indication if this node is currently mining.
    82  func (api *PublicMinerAPI) Mining() bool {
    83  	return api.e.IsMining()
    84  }
    85  
    86  // PrivateMinerAPI provides private RPC methods to control the miner.
    87  // These methods can be abused by external users and must be considered insecure for use by untrusted users.
    88  type PrivateMinerAPI struct {
    89  	e *Ethereum
    90  }
    91  
    92  // NewPrivateMinerAPI create a new RPC service which controls the miner of this node.
    93  func NewPrivateMinerAPI(e *Ethereum) *PrivateMinerAPI {
    94  	return &PrivateMinerAPI{e: e}
    95  }
    96  
    97  // Start starts the miner with the given number of threads. If threads is nil,
    98  // the number of workers started is equal to the number of logical CPUs that are
    99  // usable by this process. If mining is already running, this method adjust the
   100  // number of threads allowed to use and updates the minimum price required by the
   101  // transaction pool.
   102  func (api *PrivateMinerAPI) Start(threads *int) error {
   103  	if threads == nil {
   104  		return api.e.StartMining(runtime.NumCPU())
   105  	}
   106  	return api.e.StartMining(*threads)
   107  }
   108  
   109  // Stop terminates the miner, both at the consensus engine level as well as at
   110  // the block creation level.
   111  func (api *PrivateMinerAPI) Stop() {
   112  	api.e.StopMining()
   113  }
   114  
   115  // SetExtra sets the extra data string that is included when this miner mines a block.
   116  func (api *PrivateMinerAPI) SetExtra(extra string) (bool, error) {
   117  	if err := api.e.Miner().SetExtra([]byte(extra)); err != nil {
   118  		return false, err
   119  	}
   120  	return true, nil
   121  }
   122  
   123  // SetGasPrice sets the minimum accepted gas price for the miner.
   124  func (api *PrivateMinerAPI) SetGasPrice(gasPrice hexutil.Big) bool {
   125  	api.e.lock.Lock()
   126  	api.e.gasPrice = (*big.Int)(&gasPrice)
   127  	api.e.lock.Unlock()
   128  
   129  	api.e.txPool.SetGasPrice((*big.Int)(&gasPrice))
   130  	return true
   131  }
   132  
   133  // SetGasLimit sets the gaslimit to target towards during mining.
   134  func (api *PrivateMinerAPI) SetGasLimit(gasLimit hexutil.Uint64) bool {
   135  	api.e.Miner().SetGasCeil(uint64(gasLimit))
   136  	return true
   137  }
   138  
   139  // SetEtherbase sets the etherbase of the miner
   140  func (api *PrivateMinerAPI) SetEtherbase(etherbase common.Address) bool {
   141  	api.e.SetEtherbase(etherbase)
   142  	return true
   143  }
   144  
   145  // SetRecommitInterval updates the interval for miner sealing work recommitting.
   146  func (api *PrivateMinerAPI) SetRecommitInterval(interval int) {
   147  	api.e.Miner().SetRecommitInterval(time.Duration(interval) * time.Millisecond)
   148  }
   149  
   150  // PrivateAdminAPI is the collection of Ethereum full node-related APIs
   151  // exposed over the private admin endpoint.
   152  type PrivateAdminAPI struct {
   153  	eth *Ethereum
   154  }
   155  
   156  // NewPrivateAdminAPI creates a new API definition for the full node private
   157  // admin methods of the Ethereum service.
   158  func NewPrivateAdminAPI(eth *Ethereum) *PrivateAdminAPI {
   159  	return &PrivateAdminAPI{eth: eth}
   160  }
   161  
   162  // ExportChain exports the current blockchain into a local file,
   163  // or a range of blocks if first and last are non-nil
   164  func (api *PrivateAdminAPI) ExportChain(file string, first *uint64, last *uint64) (bool, error) {
   165  	if first == nil && last != nil {
   166  		return false, errors.New("last cannot be specified without first")
   167  	}
   168  	if first != nil && last == nil {
   169  		head := api.eth.BlockChain().CurrentHeader().Number.Uint64()
   170  		last = &head
   171  	}
   172  	if _, err := os.Stat(file); err == nil {
   173  		// File already exists. Allowing overwrite could be a DoS vector,
   174  		// since the 'file' may point to arbitrary paths on the drive
   175  		return false, errors.New("location would overwrite an existing file")
   176  	}
   177  	// Make sure we can create the file to export into
   178  	out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
   179  	if err != nil {
   180  		return false, err
   181  	}
   182  	defer out.Close()
   183  
   184  	var writer io.Writer = out
   185  	if strings.HasSuffix(file, ".gz") {
   186  		writer = gzip.NewWriter(writer)
   187  		defer writer.(*gzip.Writer).Close()
   188  	}
   189  
   190  	// Export the blockchain
   191  	if first != nil {
   192  		if err := api.eth.BlockChain().ExportN(writer, *first, *last); err != nil {
   193  			return false, err
   194  		}
   195  	} else if err := api.eth.BlockChain().Export(writer); err != nil {
   196  		return false, err
   197  	}
   198  	return true, nil
   199  }
   200  
   201  func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
   202  	for _, b := range bs {
   203  		if !chain.HasBlock(b.Hash(), b.NumberU64()) {
   204  			return false
   205  		}
   206  	}
   207  
   208  	return true
   209  }
   210  
   211  // ImportChain imports a blockchain from a local file.
   212  func (api *PrivateAdminAPI) ImportChain(file string) (bool, error) {
   213  	// Make sure the can access the file to import
   214  	in, err := os.Open(file)
   215  	if err != nil {
   216  		return false, err
   217  	}
   218  	defer in.Close()
   219  
   220  	var reader io.Reader = in
   221  	if strings.HasSuffix(file, ".gz") {
   222  		if reader, err = gzip.NewReader(reader); err != nil {
   223  			return false, err
   224  		}
   225  	}
   226  
   227  	// Run actual the import in pre-configured batches
   228  	stream := rlp.NewStream(reader, 0)
   229  
   230  	blocks, index := make([]*types.Block, 0, 2500), 0
   231  	for batch := 0; ; batch++ {
   232  		// Load a batch of blocks from the input file
   233  		for len(blocks) < cap(blocks) {
   234  			block := new(types.Block)
   235  			if err := stream.Decode(block); err == io.EOF {
   236  				break
   237  			} else if err != nil {
   238  				return false, fmt.Errorf("block %d: failed to parse: %v", index, err)
   239  			}
   240  			blocks = append(blocks, block)
   241  			index++
   242  		}
   243  		if len(blocks) == 0 {
   244  			break
   245  		}
   246  
   247  		if hasAllBlocks(api.eth.BlockChain(), blocks) {
   248  			blocks = blocks[:0]
   249  			continue
   250  		}
   251  		// Import the batch and reset the buffer
   252  		if _, err := api.eth.BlockChain().InsertChain(blocks); err != nil {
   253  			return false, fmt.Errorf("batch %d: failed to insert: %v", batch, err)
   254  		}
   255  		blocks = blocks[:0]
   256  	}
   257  	return true, nil
   258  }
   259  
   260  // PublicDebugAPI is the collection of Ethereum full node APIs exposed
   261  // over the public debugging endpoint.
   262  type PublicDebugAPI struct {
   263  	eth *Ethereum
   264  }
   265  
   266  // NewPublicDebugAPI creates a new API definition for the full node-
   267  // related public debug methods of the Ethereum service.
   268  func NewPublicDebugAPI(eth *Ethereum) *PublicDebugAPI {
   269  	return &PublicDebugAPI{eth: eth}
   270  }
   271  
   272  // DumpBlock retrieves the entire state of the database at a given block.
   273  func (api *PublicDebugAPI) DumpBlock(blockNr rpc.BlockNumber) (state.Dump, error) {
   274  	opts := &state.DumpConfig{
   275  		OnlyWithAddresses: true,
   276  		Max:               AccountRangeMaxResults, // Sanity limit over RPC
   277  	}
   278  	if blockNr == rpc.PendingBlockNumber {
   279  		// If we're dumping the pending state, we need to request
   280  		// both the pending block as well as the pending state from
   281  		// the miner and operate on those
   282  		_, stateDb := api.eth.miner.Pending()
   283  		return stateDb.RawDump(opts), nil
   284  	}
   285  	var block *types.Block
   286  	if blockNr == rpc.LatestBlockNumber {
   287  		block = api.eth.blockchain.CurrentBlock()
   288  	} else if blockNr == rpc.FinalizedBlockNumber {
   289  		block = api.eth.blockchain.CurrentFinalizedBlock()
   290  	} else {
   291  		block = api.eth.blockchain.GetBlockByNumber(uint64(blockNr))
   292  	}
   293  	if block == nil {
   294  		return state.Dump{}, fmt.Errorf("block #%d not found", blockNr)
   295  	}
   296  	stateDb, err := api.eth.BlockChain().StateAt(block.Root())
   297  	if err != nil {
   298  		return state.Dump{}, err
   299  	}
   300  	return stateDb.RawDump(opts), nil
   301  }
   302  
   303  // PrivateDebugAPI is the collection of Ethereum full node APIs exposed over
   304  // the private debugging endpoint.
   305  type PrivateDebugAPI struct {
   306  	eth *Ethereum
   307  }
   308  
   309  // NewPrivateDebugAPI creates a new API definition for the full node-related
   310  // private debug methods of the Ethereum service.
   311  func NewPrivateDebugAPI(eth *Ethereum) *PrivateDebugAPI {
   312  	return &PrivateDebugAPI{eth: eth}
   313  }
   314  
   315  // Preimage is a debug API function that returns the preimage for a sha3 hash, if known.
   316  func (api *PrivateDebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
   317  	if preimage := rawdb.ReadPreimage(api.eth.ChainDb(), hash); preimage != nil {
   318  		return preimage, nil
   319  	}
   320  	return nil, errors.New("unknown preimage")
   321  }
   322  
   323  // BadBlockArgs represents the entries in the list returned when bad blocks are queried.
   324  type BadBlockArgs struct {
   325  	Hash  common.Hash            `json:"hash"`
   326  	Block map[string]interface{} `json:"block"`
   327  	RLP   string                 `json:"rlp"`
   328  }
   329  
   330  // GetBadBlocks returns a list of the last 'bad blocks' that the client has seen on the network
   331  // and returns them as a JSON list of block-hashes
   332  func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]*BadBlockArgs, error) {
   333  	var (
   334  		err     error
   335  		blocks  = rawdb.ReadAllBadBlocks(api.eth.chainDb)
   336  		results = make([]*BadBlockArgs, 0, len(blocks))
   337  	)
   338  	for _, block := range blocks {
   339  		var (
   340  			blockRlp  string
   341  			blockJSON map[string]interface{}
   342  		)
   343  		if rlpBytes, err := rlp.EncodeToBytes(block); err != nil {
   344  			blockRlp = err.Error() // Hacky, but hey, it works
   345  		} else {
   346  			blockRlp = fmt.Sprintf("0x%x", rlpBytes)
   347  		}
   348  		if blockJSON, err = ethapi.RPCMarshalBlock(block, true, true, api.eth.APIBackend.ChainConfig()); err != nil {
   349  			blockJSON = map[string]interface{}{"error": err.Error()}
   350  		}
   351  		results = append(results, &BadBlockArgs{
   352  			Hash:  block.Hash(),
   353  			RLP:   blockRlp,
   354  			Block: blockJSON,
   355  		})
   356  	}
   357  	return results, nil
   358  }
   359  
   360  // AccountRangeMaxResults is the maximum number of results to be returned per call
   361  const AccountRangeMaxResults = 256
   362  
   363  // AccountRange enumerates all accounts in the given block and start point in paging request
   364  func (api *PublicDebugAPI) AccountRange(blockNrOrHash rpc.BlockNumberOrHash, start []byte, maxResults int, nocode, nostorage, incompletes bool) (state.IteratorDump, error) {
   365  	var stateDb *state.StateDB
   366  	var err error
   367  
   368  	if number, ok := blockNrOrHash.Number(); ok {
   369  		if number == rpc.PendingBlockNumber {
   370  			// If we're dumping the pending state, we need to request
   371  			// both the pending block as well as the pending state from
   372  			// the miner and operate on those
   373  			_, stateDb = api.eth.miner.Pending()
   374  		} else {
   375  			var block *types.Block
   376  			if number == rpc.LatestBlockNumber {
   377  				block = api.eth.blockchain.CurrentBlock()
   378  			} else if number == rpc.FinalizedBlockNumber {
   379  				block = api.eth.blockchain.CurrentFinalizedBlock()
   380  			} else {
   381  				block = api.eth.blockchain.GetBlockByNumber(uint64(number))
   382  			}
   383  			if block == nil {
   384  				return state.IteratorDump{}, fmt.Errorf("block #%d not found", number)
   385  			}
   386  			stateDb, err = api.eth.BlockChain().StateAt(block.Root())
   387  			if err != nil {
   388  				return state.IteratorDump{}, err
   389  			}
   390  		}
   391  	} else if hash, ok := blockNrOrHash.Hash(); ok {
   392  		block := api.eth.blockchain.GetBlockByHash(hash)
   393  		if block == nil {
   394  			return state.IteratorDump{}, fmt.Errorf("block %s not found", hash.Hex())
   395  		}
   396  		stateDb, err = api.eth.BlockChain().StateAt(block.Root())
   397  		if err != nil {
   398  			return state.IteratorDump{}, err
   399  		}
   400  	} else {
   401  		return state.IteratorDump{}, errors.New("either block number or block hash must be specified")
   402  	}
   403  
   404  	opts := &state.DumpConfig{
   405  		SkipCode:          nocode,
   406  		SkipStorage:       nostorage,
   407  		OnlyWithAddresses: !incompletes,
   408  		Start:             start,
   409  		Max:               uint64(maxResults),
   410  	}
   411  	if maxResults > AccountRangeMaxResults || maxResults <= 0 {
   412  		opts.Max = AccountRangeMaxResults
   413  	}
   414  	return stateDb.IteratorDump(opts), nil
   415  }
   416  
   417  // StorageRangeResult is the result of a debug_storageRangeAt API call.
   418  type StorageRangeResult struct {
   419  	Storage storageMap   `json:"storage"`
   420  	NextKey *common.Hash `json:"nextKey"` // nil if Storage includes the last key in the trie.
   421  }
   422  
   423  type storageMap map[common.Hash]storageEntry
   424  
   425  type storageEntry struct {
   426  	Key   *common.Hash `json:"key"`
   427  	Value common.Hash  `json:"value"`
   428  }
   429  
   430  // StorageRangeAt returns the storage at the given block height and transaction index.
   431  func (api *PrivateDebugAPI) StorageRangeAt(blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) {
   432  	// Retrieve the block
   433  	block := api.eth.blockchain.GetBlockByHash(blockHash)
   434  	if block == nil {
   435  		return StorageRangeResult{}, fmt.Errorf("block %#x not found", blockHash)
   436  	}
   437  	_, _, statedb, err := api.eth.stateAtTransaction(block, txIndex, 0)
   438  	if err != nil {
   439  		return StorageRangeResult{}, err
   440  	}
   441  	st := statedb.StorageTrie(contractAddress)
   442  	if st == nil {
   443  		return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress)
   444  	}
   445  	return storageRangeAt(st, keyStart, maxResult)
   446  }
   447  
   448  func storageRangeAt(st state.Trie, start []byte, maxResult int) (StorageRangeResult, error) {
   449  	it := trie.NewIterator(st.NodeIterator(start))
   450  	result := StorageRangeResult{Storage: storageMap{}}
   451  	for i := 0; i < maxResult && it.Next(); i++ {
   452  		_, content, _, err := rlp.Split(it.Value)
   453  		if err != nil {
   454  			return StorageRangeResult{}, err
   455  		}
   456  		e := storageEntry{Value: common.BytesToHash(content)}
   457  		if preimage := st.GetKey(it.Key); preimage != nil {
   458  			preimage := common.BytesToHash(preimage)
   459  			e.Key = &preimage
   460  		}
   461  		result.Storage[common.BytesToHash(it.Key)] = e
   462  	}
   463  	// Add the 'next key' so clients can continue downloading.
   464  	if it.Next() {
   465  		next := common.BytesToHash(it.Key)
   466  		result.NextKey = &next
   467  	}
   468  	return result, nil
   469  }
   470  
   471  // GetModifiedAccountsByNumber returns all accounts that have changed between the
   472  // two blocks specified. A change is defined as a difference in nonce, balance,
   473  // code hash, or storage hash.
   474  //
   475  // With one parameter, returns the list of accounts modified in the specified block.
   476  func (api *PrivateDebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum *uint64) ([]common.Address, error) {
   477  	var startBlock, endBlock *types.Block
   478  
   479  	startBlock = api.eth.blockchain.GetBlockByNumber(startNum)
   480  	if startBlock == nil {
   481  		return nil, fmt.Errorf("start block %x not found", startNum)
   482  	}
   483  
   484  	if endNum == nil {
   485  		endBlock = startBlock
   486  		startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash())
   487  		if startBlock == nil {
   488  			return nil, fmt.Errorf("block %x has no parent", endBlock.Number())
   489  		}
   490  	} else {
   491  		endBlock = api.eth.blockchain.GetBlockByNumber(*endNum)
   492  		if endBlock == nil {
   493  			return nil, fmt.Errorf("end block %d not found", *endNum)
   494  		}
   495  	}
   496  	return api.getModifiedAccounts(startBlock, endBlock)
   497  }
   498  
   499  // GetModifiedAccountsByHash returns all accounts that have changed between the
   500  // two blocks specified. A change is defined as a difference in nonce, balance,
   501  // code hash, or storage hash.
   502  //
   503  // With one parameter, returns the list of accounts modified in the specified block.
   504  func (api *PrivateDebugAPI) GetModifiedAccountsByHash(startHash common.Hash, endHash *common.Hash) ([]common.Address, error) {
   505  	var startBlock, endBlock *types.Block
   506  	startBlock = api.eth.blockchain.GetBlockByHash(startHash)
   507  	if startBlock == nil {
   508  		return nil, fmt.Errorf("start block %x not found", startHash)
   509  	}
   510  
   511  	if endHash == nil {
   512  		endBlock = startBlock
   513  		startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash())
   514  		if startBlock == nil {
   515  			return nil, fmt.Errorf("block %x has no parent", endBlock.Number())
   516  		}
   517  	} else {
   518  		endBlock = api.eth.blockchain.GetBlockByHash(*endHash)
   519  		if endBlock == nil {
   520  			return nil, fmt.Errorf("end block %x not found", *endHash)
   521  		}
   522  	}
   523  	return api.getModifiedAccounts(startBlock, endBlock)
   524  }
   525  
   526  func (api *PrivateDebugAPI) getModifiedAccounts(startBlock, endBlock *types.Block) ([]common.Address, error) {
   527  	if startBlock.Number().Uint64() >= endBlock.Number().Uint64() {
   528  		return nil, fmt.Errorf("start block height (%d) must be less than end block height (%d)", startBlock.Number().Uint64(), endBlock.Number().Uint64())
   529  	}
   530  	triedb := api.eth.BlockChain().StateCache().TrieDB()
   531  
   532  	oldTrie, err := trie.NewSecure(startBlock.Root(), triedb)
   533  	if err != nil {
   534  		return nil, err
   535  	}
   536  	newTrie, err := trie.NewSecure(endBlock.Root(), triedb)
   537  	if err != nil {
   538  		return nil, err
   539  	}
   540  	diff, _ := trie.NewDifferenceIterator(oldTrie.NodeIterator([]byte{}), newTrie.NodeIterator([]byte{}))
   541  	iter := trie.NewIterator(diff)
   542  
   543  	var dirty []common.Address
   544  	for iter.Next() {
   545  		key := newTrie.GetKey(iter.Key)
   546  		if key == nil {
   547  			return nil, fmt.Errorf("no preimage found for hash %x", iter.Key)
   548  		}
   549  		dirty = append(dirty, common.BytesToAddress(key))
   550  	}
   551  	return dirty, nil
   552  }
   553  
   554  // GetAccessibleState returns the first number where the node has accessible
   555  // state on disk. Note this being the post-state of that block and the pre-state
   556  // of the next block.
   557  // The (from, to) parameters are the sequence of blocks to search, which can go
   558  // either forwards or backwards
   559  func (api *PrivateDebugAPI) GetAccessibleState(from, to rpc.BlockNumber) (uint64, error) {
   560  	db := api.eth.ChainDb()
   561  	var pivot uint64
   562  	if p := rawdb.ReadLastPivotNumber(db); p != nil {
   563  		pivot = *p
   564  		log.Info("Found fast-sync pivot marker", "number", pivot)
   565  	}
   566  	var resolveNum = func(num rpc.BlockNumber) (uint64, error) {
   567  		// We don't have state for pending (-2), so treat it as latest
   568  		if num.Int64() < 0 {
   569  			block := api.eth.blockchain.CurrentBlock()
   570  			if block == nil {
   571  				return 0, fmt.Errorf("current block missing")
   572  			}
   573  			return block.NumberU64(), nil
   574  		}
   575  		return uint64(num.Int64()), nil
   576  	}
   577  	var (
   578  		start   uint64
   579  		end     uint64
   580  		delta   = int64(1)
   581  		lastLog time.Time
   582  		err     error
   583  	)
   584  	if start, err = resolveNum(from); err != nil {
   585  		return 0, err
   586  	}
   587  	if end, err = resolveNum(to); err != nil {
   588  		return 0, err
   589  	}
   590  	if start == end {
   591  		return 0, fmt.Errorf("from and to needs to be different")
   592  	}
   593  	if start > end {
   594  		delta = -1
   595  	}
   596  	for i := int64(start); i != int64(end); i += delta {
   597  		if time.Since(lastLog) > 8*time.Second {
   598  			log.Info("Finding roots", "from", start, "to", end, "at", i)
   599  			lastLog = time.Now()
   600  		}
   601  		if i < int64(pivot) {
   602  			continue
   603  		}
   604  		h := api.eth.BlockChain().GetHeaderByNumber(uint64(i))
   605  		if h == nil {
   606  			return 0, fmt.Errorf("missing header %d", i)
   607  		}
   608  		if ok, _ := api.eth.ChainDb().Has(h.Root[:]); ok {
   609  			return uint64(i), nil
   610  		}
   611  	}
   612  	return 0, fmt.Errorf("No state found")
   613  }