github.com/aidoskuneen/adk-node@v0.0.0-20220315131952-2e32567cb7f4/eth/api.go (about)

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