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