github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/eth/api.go (about)

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