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