github.com/puffscoin/go-puffscoin@v0.0.0-20190701205704-e48ad5c90fa1/eth/api.go (about)

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