github.com/MetalBlockchain/subnet-evm@v0.4.9/eth/api.go (about)

     1  // (c) 2019-2020, Ava Labs, Inc.
     2  //
     3  // This file is a derived work, based on the go-ethereum library whose original
     4  // notices appear below.
     5  //
     6  // It is distributed under a license compatible with the licensing terms of the
     7  // original code from which it is derived.
     8  //
     9  // Much love to the original authors for their work.
    10  // **********
    11  // Copyright 2015 The go-ethereum Authors
    12  // This file is part of the go-ethereum library.
    13  //
    14  // The go-ethereum library is free software: you can redistribute it and/or modify
    15  // it under the terms of the GNU Lesser General Public License as published by
    16  // the Free Software Foundation, either version 3 of the License, or
    17  // (at your option) any later version.
    18  //
    19  // The go-ethereum library is distributed in the hope that it will be useful,
    20  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    21  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    22  // GNU Lesser General Public License for more details.
    23  //
    24  // You should have received a copy of the GNU Lesser General Public License
    25  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    26  
    27  package eth
    28  
    29  import (
    30  	"compress/gzip"
    31  	"context"
    32  	"errors"
    33  	"fmt"
    34  	"io"
    35  	"os"
    36  	"strings"
    37  	"time"
    38  
    39  	"github.com/MetalBlockchain/subnet-evm/core"
    40  	"github.com/MetalBlockchain/subnet-evm/core/rawdb"
    41  	"github.com/MetalBlockchain/subnet-evm/core/state"
    42  	"github.com/MetalBlockchain/subnet-evm/core/types"
    43  	"github.com/MetalBlockchain/subnet-evm/internal/ethapi"
    44  	"github.com/MetalBlockchain/subnet-evm/rpc"
    45  	"github.com/MetalBlockchain/subnet-evm/trie"
    46  	"github.com/ethereum/go-ethereum/common"
    47  	"github.com/ethereum/go-ethereum/common/hexutil"
    48  	"github.com/ethereum/go-ethereum/log"
    49  	"github.com/ethereum/go-ethereum/rlp"
    50  )
    51  
    52  // EthereumAPI provides an API to access Ethereum full node-related information.
    53  type EthereumAPI struct {
    54  	e *Ethereum
    55  }
    56  
    57  // NewEthereumAPI creates a new Ethereum protocol API for full nodes.
    58  func NewEthereumAPI(e *Ethereum) *EthereumAPI {
    59  	return &EthereumAPI{e}
    60  }
    61  
    62  // Etherbase is the address that mining rewards will be send to.
    63  func (api *EthereumAPI) Etherbase() (common.Address, error) {
    64  	return api.e.Etherbase()
    65  }
    66  
    67  // Coinbase is the address that mining rewards will be send to (alias for Etherbase).
    68  func (api *EthereumAPI) Coinbase() (common.Address, error) {
    69  	return api.Etherbase()
    70  }
    71  
    72  // AdminAPI is the collection of Ethereum full node related APIs for node
    73  // administration.
    74  type AdminAPI struct {
    75  	eth *Ethereum
    76  }
    77  
    78  // NewAdminAPI creates a new instance of AdminAPI.
    79  func NewAdminAPI(eth *Ethereum) *AdminAPI {
    80  	return &AdminAPI{eth: eth}
    81  }
    82  
    83  // ExportChain exports the current blockchain into a local file,
    84  // or a range of blocks if first and last are non-nil.
    85  func (api *AdminAPI) ExportChain(file string, first *uint64, last *uint64) (bool, error) {
    86  	if first == nil && last != nil {
    87  		return false, errors.New("last cannot be specified without first")
    88  	}
    89  	if first != nil && last == nil {
    90  		head := api.eth.BlockChain().CurrentHeader().Number.Uint64()
    91  		last = &head
    92  	}
    93  	if _, err := os.Stat(file); err == nil {
    94  		// File already exists. Allowing overwrite could be a DoS vector,
    95  		// since the 'file' may point to arbitrary paths on the drive.
    96  		return false, errors.New("location would overwrite an existing file")
    97  	}
    98  	// Make sure we can create the file to export into
    99  	out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
   100  	if err != nil {
   101  		return false, err
   102  	}
   103  	defer out.Close()
   104  
   105  	var writer io.Writer = out
   106  	if strings.HasSuffix(file, ".gz") {
   107  		writer = gzip.NewWriter(writer)
   108  		defer writer.(*gzip.Writer).Close()
   109  	}
   110  
   111  	// Export the blockchain
   112  	if first != nil {
   113  		if err := api.eth.BlockChain().ExportN(writer, *first, *last); err != nil {
   114  			return false, err
   115  		}
   116  	} else if err := api.eth.BlockChain().Export(writer); err != nil {
   117  		return false, err
   118  	}
   119  	return true, nil
   120  }
   121  
   122  func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
   123  	for _, b := range bs {
   124  		if !chain.HasBlock(b.Hash(), b.NumberU64()) {
   125  			return false
   126  		}
   127  	}
   128  
   129  	return true
   130  }
   131  
   132  // ImportChain imports a blockchain from a local file.
   133  func (api *AdminAPI) ImportChain(file string) (bool, error) {
   134  	// Make sure the can access the file to import
   135  	in, err := os.Open(file)
   136  	if err != nil {
   137  		return false, err
   138  	}
   139  	defer in.Close()
   140  
   141  	var reader io.Reader = in
   142  	if strings.HasSuffix(file, ".gz") {
   143  		if reader, err = gzip.NewReader(reader); err != nil {
   144  			return false, err
   145  		}
   146  	}
   147  
   148  	// Run actual the import in pre-configured batches
   149  	stream := rlp.NewStream(reader, 0)
   150  
   151  	blocks, index := make([]*types.Block, 0, 2500), 0
   152  	for batch := 0; ; batch++ {
   153  		// Load a batch of blocks from the input file
   154  		for len(blocks) < cap(blocks) {
   155  			block := new(types.Block)
   156  			if err := stream.Decode(block); err == io.EOF {
   157  				break
   158  			} else if err != nil {
   159  				return false, fmt.Errorf("block %d: failed to parse: %v", index, err)
   160  			}
   161  			blocks = append(blocks, block)
   162  			index++
   163  		}
   164  		if len(blocks) == 0 {
   165  			break
   166  		}
   167  
   168  		if hasAllBlocks(api.eth.BlockChain(), blocks) {
   169  			blocks = blocks[:0]
   170  			continue
   171  		}
   172  		// Import the batch and reset the buffer
   173  		if _, err := api.eth.BlockChain().InsertChain(blocks); err != nil {
   174  			return false, fmt.Errorf("batch %d: failed to insert: %v", batch, err)
   175  		}
   176  		blocks = blocks[:0]
   177  	}
   178  	return true, nil
   179  }
   180  
   181  // DebugAPI is the collection of Ethereum full node APIs for debugging the
   182  // protocol.
   183  type DebugAPI struct {
   184  	eth *Ethereum
   185  }
   186  
   187  // NewDebugAPI creates a new DebugAPI instance.
   188  func NewDebugAPI(eth *Ethereum) *DebugAPI {
   189  	return &DebugAPI{eth: eth}
   190  }
   191  
   192  // DumpBlock retrieves the entire state of the database at a given block.
   193  func (api *DebugAPI) DumpBlock(blockNr rpc.BlockNumber) (state.Dump, error) {
   194  	opts := &state.DumpConfig{
   195  		OnlyWithAddresses: true,
   196  		Max:               AccountRangeMaxResults, // Sanity limit over RPC
   197  	}
   198  	var block *types.Block
   199  	if blockNr.IsAccepted() {
   200  		block = api.eth.LastAcceptedBlock()
   201  	} else {
   202  		block = api.eth.blockchain.GetBlockByNumber(uint64(blockNr))
   203  	}
   204  	if block == nil {
   205  		return state.Dump{}, fmt.Errorf("block #%d not found", blockNr)
   206  	}
   207  	stateDb, err := api.eth.BlockChain().StateAt(block.Root())
   208  	if err != nil {
   209  		return state.Dump{}, err
   210  	}
   211  	return stateDb.RawDump(opts), nil
   212  }
   213  
   214  // Preimage is a debug API function that returns the preimage for a sha3 hash, if known.
   215  func (api *DebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
   216  	if preimage := rawdb.ReadPreimage(api.eth.ChainDb(), hash); preimage != nil {
   217  		return preimage, nil
   218  	}
   219  	return nil, errors.New("unknown preimage")
   220  }
   221  
   222  // GetBadBlocks returns a list of the last 'bad blocks' that the client has seen on the network
   223  // and returns them as a JSON list of block hashes.
   224  func (api *DebugAPI) GetBadBlocks(ctx context.Context) ([]*ethapi.BadBlockArgs, error) {
   225  	internalAPI := ethapi.NewBlockChainAPI(api.eth.APIBackend)
   226  	return internalAPI.GetBadBlocks(ctx)
   227  }
   228  
   229  // AccountRangeMaxResults is the maximum number of results to be returned per call
   230  const AccountRangeMaxResults = 256
   231  
   232  // AccountRange enumerates all accounts in the given block and start point in paging request
   233  func (api *DebugAPI) AccountRange(blockNrOrHash rpc.BlockNumberOrHash, start hexutil.Bytes, maxResults int, nocode, nostorage, incompletes bool) (state.IteratorDump, error) {
   234  	var stateDb *state.StateDB
   235  	var err error
   236  
   237  	if number, ok := blockNrOrHash.Number(); ok {
   238  		var block *types.Block
   239  		if number.IsAccepted() {
   240  			block = api.eth.LastAcceptedBlock()
   241  		} else {
   242  			block = api.eth.blockchain.GetBlockByNumber(uint64(number))
   243  		}
   244  		if block == nil {
   245  			return state.IteratorDump{}, fmt.Errorf("block #%d not found", number)
   246  		}
   247  		stateDb, err = api.eth.BlockChain().StateAt(block.Root())
   248  		if err != nil {
   249  			return state.IteratorDump{}, err
   250  		}
   251  	} else if hash, ok := blockNrOrHash.Hash(); ok {
   252  		block := api.eth.blockchain.GetBlockByHash(hash)
   253  		if block == nil {
   254  			return state.IteratorDump{}, fmt.Errorf("block %s not found", hash.Hex())
   255  		}
   256  		stateDb, err = api.eth.BlockChain().StateAt(block.Root())
   257  		if err != nil {
   258  			return state.IteratorDump{}, err
   259  		}
   260  	} else {
   261  		return state.IteratorDump{}, errors.New("either block number or block hash must be specified")
   262  	}
   263  
   264  	opts := &state.DumpConfig{
   265  		SkipCode:          nocode,
   266  		SkipStorage:       nostorage,
   267  		OnlyWithAddresses: !incompletes,
   268  		Start:             start,
   269  		Max:               uint64(maxResults),
   270  	}
   271  	if maxResults > AccountRangeMaxResults || maxResults <= 0 {
   272  		opts.Max = AccountRangeMaxResults
   273  	}
   274  	return stateDb.IteratorDump(opts), nil
   275  }
   276  
   277  // StorageRangeResult is the result of a debug_storageRangeAt API call.
   278  type StorageRangeResult struct {
   279  	Storage storageMap   `json:"storage"`
   280  	NextKey *common.Hash `json:"nextKey"` // nil if Storage includes the last key in the trie.
   281  }
   282  
   283  type storageMap map[common.Hash]storageEntry
   284  
   285  type storageEntry struct {
   286  	Key   *common.Hash `json:"key"`
   287  	Value common.Hash  `json:"value"`
   288  }
   289  
   290  // StorageRangeAt returns the storage at the given block height and transaction index.
   291  func (api *DebugAPI) StorageRangeAt(blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) {
   292  	// Retrieve the block
   293  	block := api.eth.blockchain.GetBlockByHash(blockHash)
   294  	if block == nil {
   295  		return StorageRangeResult{}, fmt.Errorf("block %#x not found", blockHash)
   296  	}
   297  	_, _, statedb, err := api.eth.stateAtTransaction(block, txIndex, 0)
   298  	if err != nil {
   299  		return StorageRangeResult{}, err
   300  	}
   301  	st := statedb.StorageTrie(contractAddress)
   302  	if st == nil {
   303  		return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress)
   304  	}
   305  	return storageRangeAt(st, keyStart, maxResult)
   306  }
   307  
   308  func storageRangeAt(st state.Trie, start []byte, maxResult int) (StorageRangeResult, error) {
   309  	it := trie.NewIterator(st.NodeIterator(start))
   310  	result := StorageRangeResult{Storage: storageMap{}}
   311  	for i := 0; i < maxResult && it.Next(); i++ {
   312  		_, content, _, err := rlp.Split(it.Value)
   313  		if err != nil {
   314  			return StorageRangeResult{}, err
   315  		}
   316  		e := storageEntry{Value: common.BytesToHash(content)}
   317  		if preimage := st.GetKey(it.Key); preimage != nil {
   318  			preimage := common.BytesToHash(preimage)
   319  			e.Key = &preimage
   320  		}
   321  		result.Storage[common.BytesToHash(it.Key)] = e
   322  	}
   323  	// Add the 'next key' so clients can continue downloading.
   324  	if it.Next() {
   325  		next := common.BytesToHash(it.Key)
   326  		result.NextKey = &next
   327  	}
   328  	return result, nil
   329  }
   330  
   331  // GetModifiedAccountsByNumber returns all accounts that have changed between the
   332  // two blocks specified. A change is defined as a difference in nonce, balance,
   333  // code hash, or storage hash.
   334  //
   335  // With one parameter, returns the list of accounts modified in the specified block.
   336  func (api *DebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum *uint64) ([]common.Address, error) {
   337  	var startBlock, endBlock *types.Block
   338  
   339  	startBlock = api.eth.blockchain.GetBlockByNumber(startNum)
   340  	if startBlock == nil {
   341  		return nil, fmt.Errorf("start block %x not found", startNum)
   342  	}
   343  
   344  	if endNum == nil {
   345  		endBlock = startBlock
   346  		startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash())
   347  		if startBlock == nil {
   348  			return nil, fmt.Errorf("block %x has no parent", endBlock.Number())
   349  		}
   350  	} else {
   351  		endBlock = api.eth.blockchain.GetBlockByNumber(*endNum)
   352  		if endBlock == nil {
   353  			return nil, fmt.Errorf("end block %d not found", *endNum)
   354  		}
   355  	}
   356  	return api.getModifiedAccounts(startBlock, endBlock)
   357  }
   358  
   359  // GetModifiedAccountsByHash returns all accounts that have changed between the
   360  // two blocks specified. A change is defined as a difference in nonce, balance,
   361  // code hash, or storage hash.
   362  //
   363  // With one parameter, returns the list of accounts modified in the specified block.
   364  func (api *DebugAPI) GetModifiedAccountsByHash(startHash common.Hash, endHash *common.Hash) ([]common.Address, error) {
   365  	var startBlock, endBlock *types.Block
   366  	startBlock = api.eth.blockchain.GetBlockByHash(startHash)
   367  	if startBlock == nil {
   368  		return nil, fmt.Errorf("start block %x not found", startHash)
   369  	}
   370  
   371  	if endHash == nil {
   372  		endBlock = startBlock
   373  		startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash())
   374  		if startBlock == nil {
   375  			return nil, fmt.Errorf("block %x has no parent", endBlock.Number())
   376  		}
   377  	} else {
   378  		endBlock = api.eth.blockchain.GetBlockByHash(*endHash)
   379  		if endBlock == nil {
   380  			return nil, fmt.Errorf("end block %x not found", *endHash)
   381  		}
   382  	}
   383  	return api.getModifiedAccounts(startBlock, endBlock)
   384  }
   385  
   386  func (api *DebugAPI) getModifiedAccounts(startBlock, endBlock *types.Block) ([]common.Address, error) {
   387  	if startBlock.Number().Uint64() >= endBlock.Number().Uint64() {
   388  		return nil, fmt.Errorf("start block height (%d) must be less than end block height (%d)", startBlock.Number().Uint64(), endBlock.Number().Uint64())
   389  	}
   390  	triedb := api.eth.BlockChain().StateCache().TrieDB()
   391  
   392  	oldTrie, err := trie.NewStateTrie(common.Hash{}, startBlock.Root(), triedb)
   393  	if err != nil {
   394  		return nil, err
   395  	}
   396  	newTrie, err := trie.NewStateTrie(common.Hash{}, endBlock.Root(), triedb)
   397  	if err != nil {
   398  		return nil, err
   399  	}
   400  	diff, _ := trie.NewDifferenceIterator(oldTrie.NodeIterator([]byte{}), newTrie.NodeIterator([]byte{}))
   401  	iter := trie.NewIterator(diff)
   402  
   403  	var dirty []common.Address
   404  	for iter.Next() {
   405  		key := newTrie.GetKey(iter.Key)
   406  		if key == nil {
   407  			return nil, fmt.Errorf("no preimage found for hash %x", iter.Key)
   408  		}
   409  		dirty = append(dirty, common.BytesToAddress(key))
   410  	}
   411  	return dirty, nil
   412  }
   413  
   414  // GetAccessibleState returns the first number where the node has accessible
   415  // state on disk. Note this being the post-state of that block and the pre-state
   416  // of the next block.
   417  // The (from, to) parameters are the sequence of blocks to search, which can go
   418  // either forwards or backwards
   419  func (api *DebugAPI) GetAccessibleState(from, to rpc.BlockNumber) (uint64, error) {
   420  	var resolveNum = func(num rpc.BlockNumber) (uint64, error) {
   421  		// We don't have state for pending (-2), so treat it as latest
   422  		if num.Int64() < 0 {
   423  			block := api.eth.blockchain.CurrentBlock()
   424  			if block == nil {
   425  				return 0, fmt.Errorf("current block missing")
   426  			}
   427  			return block.NumberU64(), nil
   428  		}
   429  		return uint64(num.Int64()), nil
   430  	}
   431  	var (
   432  		start   uint64
   433  		end     uint64
   434  		delta   = int64(1)
   435  		lastLog time.Time
   436  		err     error
   437  	)
   438  	if start, err = resolveNum(from); err != nil {
   439  		return 0, err
   440  	}
   441  	if end, err = resolveNum(to); err != nil {
   442  		return 0, err
   443  	}
   444  	if start == end {
   445  		return 0, fmt.Errorf("from and to needs to be different")
   446  	}
   447  	if start > end {
   448  		delta = -1
   449  	}
   450  	for i := int64(start); i != int64(end); i += delta {
   451  		if time.Since(lastLog) > 8*time.Second {
   452  			log.Info("Finding roots", "from", start, "to", end, "at", i)
   453  			lastLog = time.Now()
   454  		}
   455  		h := api.eth.BlockChain().GetHeaderByNumber(uint64(i))
   456  		if h == nil {
   457  			return 0, fmt.Errorf("missing header %d", i)
   458  		}
   459  		if ok, _ := api.eth.ChainDb().Has(h.Root[:]); ok {
   460  			return uint64(i), nil
   461  		}
   462  	}
   463  	return 0, errors.New("no state found")
   464  }