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