github.com/ebakus/go-ebakus@v1.0.5-0.20200520105415-dbccef9ec421/eth/api.go (about)

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