github.com/hyperion-hyn/go-ethereum@v2.4.0+incompatible/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/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/rawdb"
    35  	"github.com/ethereum/go-ethereum/core/state"
    36  	"github.com/ethereum/go-ethereum/core/types"
    37  	"github.com/ethereum/go-ethereum/internal/ethapi"
    38  	"github.com/ethereum/go-ethereum/params"
    39  	"github.com/ethereum/go-ethereum/rlp"
    40  	"github.com/ethereum/go-ethereum/rpc"
    41  	"github.com/ethereum/go-ethereum/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  // StorageRoot returns the storage root of an account on the the given (optional) block height.
    66  // If block number is not given the latest block is used.
    67  func (s *PublicEthereumAPI) StorageRoot(addr common.Address, blockNr *rpc.BlockNumber) (common.Hash, error) {
    68  	var (
    69  		pub, priv *state.StateDB
    70  		err       error
    71  	)
    72  
    73  	if blockNr == nil || blockNr.Int64() == rpc.LatestBlockNumber.Int64() {
    74  		pub, priv, err = s.e.blockchain.State()
    75  	} else {
    76  		if ch := s.e.blockchain.GetHeaderByNumber(uint64(blockNr.Int64())); ch != nil {
    77  			pub, priv, err = s.e.blockchain.StateAt(ch.Root)
    78  		} else {
    79  			return common.Hash{}, fmt.Errorf("invalid block number")
    80  		}
    81  	}
    82  
    83  	if err != nil {
    84  		return common.Hash{}, err
    85  	}
    86  
    87  	if priv.Exist(addr) {
    88  		return priv.GetStorageRoot(addr)
    89  	}
    90  	return pub.GetStorageRoot(addr)
    91  }
    92  
    93  // Hashrate returns the POW hashrate
    94  func (api *PublicEthereumAPI) Hashrate() hexutil.Uint64 {
    95  	return hexutil.Uint64(api.e.Miner().HashRate())
    96  }
    97  
    98  // ChainId is the EIP-155 replay-protection chain id for the current ethereum chain config.
    99  func (api *PublicEthereumAPI) ChainId() hexutil.Uint64 {
   100  	chainID := new(big.Int)
   101  	if config := api.e.chainConfig; config.IsEIP155(api.e.blockchain.CurrentBlock().Number()) {
   102  		chainID = config.ChainID
   103  	}
   104  	return (hexutil.Uint64)(chainID.Uint64())
   105  }
   106  
   107  // PublicMinerAPI provides an API to control the miner.
   108  // It offers only methods that operate on data that pose no security risk when it is publicly accessible.
   109  type PublicMinerAPI struct {
   110  	e *Ethereum
   111  }
   112  
   113  // NewPublicMinerAPI create a new PublicMinerAPI instance.
   114  func NewPublicMinerAPI(e *Ethereum) *PublicMinerAPI {
   115  	return &PublicMinerAPI{e}
   116  }
   117  
   118  // Mining returns an indication if this node is currently mining.
   119  func (api *PublicMinerAPI) Mining() bool {
   120  	return api.e.IsMining()
   121  }
   122  
   123  // PrivateMinerAPI provides private RPC methods to control the miner.
   124  // These methods can be abused by external users and must be considered insecure for use by untrusted users.
   125  type PrivateMinerAPI struct {
   126  	e *Ethereum
   127  }
   128  
   129  // NewPrivateMinerAPI create a new RPC service which controls the miner of this node.
   130  func NewPrivateMinerAPI(e *Ethereum) *PrivateMinerAPI {
   131  	return &PrivateMinerAPI{e: e}
   132  }
   133  
   134  // Start starts the miner with the given number of threads. If threads is nil,
   135  // the number of workers started is equal to the number of logical CPUs that are
   136  // usable by this process. If mining is already running, this method adjust the
   137  // number of threads allowed to use and updates the minimum price required by the
   138  // transaction pool.
   139  func (api *PrivateMinerAPI) Start(threads *int) error {
   140  	if threads == nil {
   141  		return api.e.StartMining(runtime.NumCPU())
   142  	}
   143  	return api.e.StartMining(*threads)
   144  }
   145  
   146  // Stop terminates the miner, both at the consensus engine level as well as at
   147  // the block creation level.
   148  func (api *PrivateMinerAPI) Stop() {
   149  	api.e.StopMining()
   150  }
   151  
   152  // SetExtra sets the extra data string that is included when this miner mines a block.
   153  func (api *PrivateMinerAPI) SetExtra(extra string) (bool, error) {
   154  	if err := api.e.Miner().SetExtra([]byte(extra)); err != nil {
   155  		return false, err
   156  	}
   157  	return true, nil
   158  }
   159  
   160  // SetGasPrice sets the minimum accepted gas price for the miner.
   161  func (api *PrivateMinerAPI) SetGasPrice(gasPrice hexutil.Big) bool {
   162  	api.e.lock.Lock()
   163  	api.e.gasPrice = (*big.Int)(&gasPrice)
   164  	api.e.lock.Unlock()
   165  
   166  	api.e.txPool.SetGasPrice((*big.Int)(&gasPrice))
   167  	return true
   168  }
   169  
   170  // SetEtherbase sets the etherbase of the miner
   171  func (api *PrivateMinerAPI) SetEtherbase(etherbase common.Address) bool {
   172  	api.e.SetEtherbase(etherbase)
   173  	return true
   174  }
   175  
   176  // SetRecommitInterval updates the interval for miner sealing work recommitting.
   177  func (api *PrivateMinerAPI) SetRecommitInterval(interval int) {
   178  	api.e.Miner().SetRecommitInterval(time.Duration(interval) * time.Millisecond)
   179  }
   180  
   181  // GetHashrate returns the current hashrate of the miner.
   182  func (api *PrivateMinerAPI) GetHashrate() uint64 {
   183  	return api.e.miner.HashRate()
   184  }
   185  
   186  // PrivateAdminAPI is the collection of Ethereum full node-related APIs
   187  // exposed over the private admin endpoint.
   188  type PrivateAdminAPI struct {
   189  	eth *Ethereum
   190  }
   191  
   192  // NewPrivateAdminAPI creates a new API definition for the full node private
   193  // admin methods of the Ethereum service.
   194  func NewPrivateAdminAPI(eth *Ethereum) *PrivateAdminAPI {
   195  	return &PrivateAdminAPI{eth: eth}
   196  }
   197  
   198  // ExportChain exports the current blockchain into a local file.
   199  func (api *PrivateAdminAPI) ExportChain(file string) (bool, error) {
   200  	// Make sure we can create the file to export into
   201  	out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
   202  	if err != nil {
   203  		return false, err
   204  	}
   205  	defer out.Close()
   206  
   207  	var writer io.Writer = out
   208  	if strings.HasSuffix(file, ".gz") {
   209  		writer = gzip.NewWriter(writer)
   210  		defer writer.(*gzip.Writer).Close()
   211  	}
   212  
   213  	// Export the blockchain
   214  	if err := api.eth.BlockChain().Export(writer); err != nil {
   215  		return false, err
   216  	}
   217  	return true, nil
   218  }
   219  
   220  func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
   221  	for _, b := range bs {
   222  		if !chain.HasBlock(b.Hash(), b.NumberU64()) {
   223  			return false
   224  		}
   225  	}
   226  
   227  	return true
   228  }
   229  
   230  // ImportChain imports a blockchain from a local file.
   231  func (api *PrivateAdminAPI) ImportChain(file string) (bool, error) {
   232  	// Make sure the can access the file to import
   233  	in, err := os.Open(file)
   234  	if err != nil {
   235  		return false, err
   236  	}
   237  	defer in.Close()
   238  
   239  	var reader io.Reader = in
   240  	if strings.HasSuffix(file, ".gz") {
   241  		if reader, err = gzip.NewReader(reader); err != nil {
   242  			return false, err
   243  		}
   244  	}
   245  
   246  	// Run actual the import in pre-configured batches
   247  	stream := rlp.NewStream(reader, 0)
   248  
   249  	blocks, index := make([]*types.Block, 0, 2500), 0
   250  	for batch := 0; ; batch++ {
   251  		// Load a batch of blocks from the input file
   252  		for len(blocks) < cap(blocks) {
   253  			block := new(types.Block)
   254  			if err := stream.Decode(block); err == io.EOF {
   255  				break
   256  			} else if err != nil {
   257  				return false, fmt.Errorf("block %d: failed to parse: %v", index, err)
   258  			}
   259  			blocks = append(blocks, block)
   260  			index++
   261  		}
   262  		if len(blocks) == 0 {
   263  			break
   264  		}
   265  
   266  		if hasAllBlocks(api.eth.BlockChain(), blocks) {
   267  			blocks = blocks[:0]
   268  			continue
   269  		}
   270  		// Import the batch and reset the buffer
   271  		if _, err := api.eth.BlockChain().InsertChain(blocks); err != nil {
   272  			return false, fmt.Errorf("batch %d: failed to insert: %v", batch, err)
   273  		}
   274  		blocks = blocks[:0]
   275  	}
   276  	return true, nil
   277  }
   278  
   279  // PublicDebugAPI is the collection of Ethereum full node APIs exposed
   280  // over the public debugging endpoint.
   281  type PublicDebugAPI struct {
   282  	eth *Ethereum
   283  }
   284  
   285  // NewPublicDebugAPI creates a new API definition for the full node-
   286  // related public debug methods of the Ethereum service.
   287  func NewPublicDebugAPI(eth *Ethereum) *PublicDebugAPI {
   288  	return &PublicDebugAPI{eth: eth}
   289  }
   290  
   291  // DumpBlock retrieves the entire state of the database at a given block.
   292  func (api *PublicDebugAPI) DumpBlock(blockNr rpc.BlockNumber, typ string) (state.Dump, error) {
   293  	var publicState, privateState *state.StateDB
   294  	var err error
   295  	if blockNr == rpc.PendingBlockNumber {
   296  		// If we're dumping the pending state, we need to request
   297  		// both the pending block as well as the pending state from
   298  		// the miner and operate on those
   299  		_, publicState, privateState = api.eth.miner.Pending()
   300  	} else {
   301  		var block *types.Block
   302  		if blockNr == rpc.LatestBlockNumber {
   303  			block = api.eth.blockchain.CurrentBlock()
   304  		} else {
   305  			block = api.eth.blockchain.GetBlockByNumber(uint64(blockNr))
   306  		}
   307  		if block == nil {
   308  			return state.Dump{}, fmt.Errorf("block #%d not found", blockNr)
   309  		}
   310  		publicState, privateState, err = api.eth.BlockChain().StateAt(block.Root())
   311  		if err != nil {
   312  			return state.Dump{}, err
   313  		}
   314  	}
   315  
   316  	switch typ {
   317  	case "public":
   318  		return publicState.RawDump(), nil
   319  	case "private":
   320  		return privateState.RawDump(), nil
   321  	default:
   322  		return state.Dump{}, fmt.Errorf("unknown type: '%s'", typ)
   323  	}
   324  }
   325  
   326  // PrivateDebugAPI is the collection of Ethereum full node APIs exposed over
   327  // the private debugging endpoint.
   328  type PrivateDebugAPI struct {
   329  	config *params.ChainConfig
   330  	eth    *Ethereum
   331  }
   332  
   333  // NewPrivateDebugAPI creates a new API definition for the full node-related
   334  // private debug methods of the Ethereum service.
   335  func NewPrivateDebugAPI(config *params.ChainConfig, eth *Ethereum) *PrivateDebugAPI {
   336  	return &PrivateDebugAPI{config: config, eth: eth}
   337  }
   338  
   339  // Preimage is a debug API function that returns the preimage for a sha3 hash, if known.
   340  func (api *PrivateDebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
   341  	if preimage := rawdb.ReadPreimage(api.eth.ChainDb(), hash); preimage != nil {
   342  		return preimage, nil
   343  	}
   344  	return nil, errors.New("unknown preimage")
   345  }
   346  
   347  // BadBlockArgs represents the entries in the list returned when bad blocks are queried.
   348  type BadBlockArgs struct {
   349  	Hash  common.Hash            `json:"hash"`
   350  	Block map[string]interface{} `json:"block"`
   351  	RLP   string                 `json:"rlp"`
   352  }
   353  
   354  // GetBadBlocks returns a list of the last 'bad blocks' that the client has seen on the network
   355  // and returns them as a JSON list of block-hashes
   356  func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]*BadBlockArgs, error) {
   357  	blocks := api.eth.BlockChain().BadBlocks()
   358  	results := make([]*BadBlockArgs, len(blocks))
   359  
   360  	var err error
   361  	for i, block := range blocks {
   362  		results[i] = &BadBlockArgs{
   363  			Hash: block.Hash(),
   364  		}
   365  		if rlpBytes, err := rlp.EncodeToBytes(block); err != nil {
   366  			results[i].RLP = err.Error() // Hacky, but hey, it works
   367  		} else {
   368  			results[i].RLP = fmt.Sprintf("0x%x", rlpBytes)
   369  		}
   370  		if results[i].Block, err = ethapi.RPCMarshalBlock(block, true, true); err != nil {
   371  			results[i].Block = map[string]interface{}{"error": err.Error()}
   372  		}
   373  	}
   374  	return results, nil
   375  }
   376  
   377  // StorageRangeResult is the result of a debug_storageRangeAt API call.
   378  type StorageRangeResult struct {
   379  	Storage storageMap   `json:"storage"`
   380  	NextKey *common.Hash `json:"nextKey"` // nil if Storage includes the last key in the trie.
   381  }
   382  
   383  type storageMap map[common.Hash]storageEntry
   384  
   385  type storageEntry struct {
   386  	Key   *common.Hash `json:"key"`
   387  	Value common.Hash  `json:"value"`
   388  }
   389  
   390  // StorageRangeAt returns the storage at the given block height and transaction index.
   391  func (api *PrivateDebugAPI) StorageRangeAt(ctx context.Context, blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) {
   392  	_, _, _, statedb, err := api.computeTxEnv(blockHash, txIndex, 0)
   393  	if err != nil {
   394  		return StorageRangeResult{}, err
   395  	}
   396  	st := statedb.StorageTrie(contractAddress)
   397  	if st == nil {
   398  		return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress)
   399  	}
   400  	return storageRangeAt(st, keyStart, maxResult)
   401  }
   402  
   403  func storageRangeAt(st state.Trie, start []byte, maxResult int) (StorageRangeResult, error) {
   404  	it := trie.NewIterator(st.NodeIterator(start))
   405  	result := StorageRangeResult{Storage: storageMap{}}
   406  	for i := 0; i < maxResult && it.Next(); i++ {
   407  		_, content, _, err := rlp.Split(it.Value)
   408  		if err != nil {
   409  			return StorageRangeResult{}, err
   410  		}
   411  		e := storageEntry{Value: common.BytesToHash(content)}
   412  		if preimage := st.GetKey(it.Key); preimage != nil {
   413  			preimage := common.BytesToHash(preimage)
   414  			e.Key = &preimage
   415  		}
   416  		result.Storage[common.BytesToHash(it.Key)] = e
   417  	}
   418  	// Add the 'next key' so clients can continue downloading.
   419  	if it.Next() {
   420  		next := common.BytesToHash(it.Key)
   421  		result.NextKey = &next
   422  	}
   423  	return result, nil
   424  }
   425  
   426  // GetModifiedAccountsByNumber returns all accounts that have changed between the
   427  // two blocks specified. A change is defined as a difference in nonce, balance,
   428  // code hash, or storage hash.
   429  //
   430  // With one parameter, returns the list of accounts modified in the specified block.
   431  func (api *PrivateDebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum *uint64) ([]common.Address, error) {
   432  	var startBlock, endBlock *types.Block
   433  
   434  	startBlock = api.eth.blockchain.GetBlockByNumber(startNum)
   435  	if startBlock == nil {
   436  		return nil, fmt.Errorf("start block %x not found", startNum)
   437  	}
   438  
   439  	if endNum == nil {
   440  		endBlock = startBlock
   441  		startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash())
   442  		if startBlock == nil {
   443  			return nil, fmt.Errorf("block %x has no parent", endBlock.Number())
   444  		}
   445  	} else {
   446  		endBlock = api.eth.blockchain.GetBlockByNumber(*endNum)
   447  		if endBlock == nil {
   448  			return nil, fmt.Errorf("end block %d not found", *endNum)
   449  		}
   450  	}
   451  	return api.getModifiedAccounts(startBlock, endBlock)
   452  }
   453  
   454  // GetModifiedAccountsByHash returns all accounts that have changed between the
   455  // two blocks specified. A change is defined as a difference in nonce, balance,
   456  // code hash, or storage hash.
   457  //
   458  // With one parameter, returns the list of accounts modified in the specified block.
   459  func (api *PrivateDebugAPI) GetModifiedAccountsByHash(startHash common.Hash, endHash *common.Hash) ([]common.Address, error) {
   460  	var startBlock, endBlock *types.Block
   461  	startBlock = api.eth.blockchain.GetBlockByHash(startHash)
   462  	if startBlock == nil {
   463  		return nil, fmt.Errorf("start block %x not found", startHash)
   464  	}
   465  
   466  	if endHash == nil {
   467  		endBlock = startBlock
   468  		startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash())
   469  		if startBlock == nil {
   470  			return nil, fmt.Errorf("block %x has no parent", endBlock.Number())
   471  		}
   472  	} else {
   473  		endBlock = api.eth.blockchain.GetBlockByHash(*endHash)
   474  		if endBlock == nil {
   475  			return nil, fmt.Errorf("end block %x not found", *endHash)
   476  		}
   477  	}
   478  	return api.getModifiedAccounts(startBlock, endBlock)
   479  }
   480  
   481  func (api *PrivateDebugAPI) getModifiedAccounts(startBlock, endBlock *types.Block) ([]common.Address, error) {
   482  	if startBlock.Number().Uint64() >= endBlock.Number().Uint64() {
   483  		return nil, fmt.Errorf("start block height (%d) must be less than end block height (%d)", startBlock.Number().Uint64(), endBlock.Number().Uint64())
   484  	}
   485  
   486  	oldTrie, err := trie.NewSecure(startBlock.Root(), trie.NewDatabase(api.eth.chainDb), 0)
   487  	if err != nil {
   488  		return nil, err
   489  	}
   490  	newTrie, err := trie.NewSecure(endBlock.Root(), trie.NewDatabase(api.eth.chainDb), 0)
   491  	if err != nil {
   492  		return nil, err
   493  	}
   494  
   495  	diff, _ := trie.NewDifferenceIterator(oldTrie.NodeIterator([]byte{}), newTrie.NodeIterator([]byte{}))
   496  	iter := trie.NewIterator(diff)
   497  
   498  	var dirty []common.Address
   499  	for iter.Next() {
   500  		key := newTrie.GetKey(iter.Key)
   501  		if key == nil {
   502  			return nil, fmt.Errorf("no preimage found for hash %x", iter.Key)
   503  		}
   504  		dirty = append(dirty, common.BytesToAddress(key))
   505  	}
   506  	return dirty, nil
   507  }