github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/eth/api.go (about)

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