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