github.com/Blockdaemon/celo-blockchain@v0.0.0-20200129231733-e667f6b08419/internal/ethapi/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 ethapi
    18  
    19  import (
    20  	"bytes"
    21  	"context"
    22  	"errors"
    23  	"fmt"
    24  	"math/big"
    25  	"strings"
    26  	"time"
    27  
    28  	"github.com/davecgh/go-spew/spew"
    29  	"github.com/ethereum/go-ethereum/accounts"
    30  	"github.com/ethereum/go-ethereum/accounts/keystore"
    31  	"github.com/ethereum/go-ethereum/common"
    32  	"github.com/ethereum/go-ethereum/common/hexutil"
    33  	"github.com/ethereum/go-ethereum/common/math"
    34  	"github.com/ethereum/go-ethereum/consensus/ethash"
    35  	"github.com/ethereum/go-ethereum/contract_comm/blockchain_parameters"
    36  	"github.com/ethereum/go-ethereum/core"
    37  	"github.com/ethereum/go-ethereum/core/rawdb"
    38  	"github.com/ethereum/go-ethereum/core/types"
    39  	"github.com/ethereum/go-ethereum/core/vm"
    40  	"github.com/ethereum/go-ethereum/crypto"
    41  	"github.com/ethereum/go-ethereum/log"
    42  	"github.com/ethereum/go-ethereum/p2p"
    43  	"github.com/ethereum/go-ethereum/params"
    44  	"github.com/ethereum/go-ethereum/rlp"
    45  	"github.com/ethereum/go-ethereum/rpc"
    46  	"github.com/syndtr/goleveldb/leveldb"
    47  	"github.com/syndtr/goleveldb/leveldb/util"
    48  )
    49  
    50  // PublicEthereumAPI provides an API to access Ethereum related information.
    51  // It offers only methods that operate on public data that is freely available to anyone.
    52  type PublicEthereumAPI struct {
    53  	b Backend
    54  }
    55  
    56  // NewPublicEthereumAPI creates a new Ethereum protocol API.
    57  func NewPublicEthereumAPI(b Backend) *PublicEthereumAPI {
    58  	return &PublicEthereumAPI{b}
    59  }
    60  
    61  // GasPrice returns a suggestion for a gas price.
    62  func (s *PublicEthereumAPI) GasPrice(ctx context.Context) (*hexutil.Big, error) {
    63  	price, err := s.b.SuggestPrice(ctx)
    64  	return (*hexutil.Big)(price), err
    65  }
    66  
    67  // ProtocolVersion returns the current Ethereum protocol version this node supports
    68  func (s *PublicEthereumAPI) ProtocolVersion() hexutil.Uint {
    69  	return hexutil.Uint(s.b.ProtocolVersion())
    70  }
    71  
    72  // Syncing returns false in case the node is currently not syncing with the network. It can be up to date or has not
    73  // yet received the latest block headers from its pears. In case it is synchronizing:
    74  // - startingBlock: block number this node started to synchronise from
    75  // - currentBlock:  block number this node is currently importing
    76  // - highestBlock:  block number of the highest block header this node has received from peers
    77  // - pulledStates:  number of state entries processed until now
    78  // - knownStates:   number of known state entries that still need to be pulled
    79  func (s *PublicEthereumAPI) Syncing() (interface{}, error) {
    80  	progress := s.b.Downloader().Progress()
    81  
    82  	// Return not syncing if the synchronisation already completed
    83  	if progress.CurrentBlock >= progress.HighestBlock {
    84  		return false, nil
    85  	}
    86  	// Otherwise gather the block sync stats
    87  	return map[string]interface{}{
    88  		"startingBlock": hexutil.Uint64(progress.StartingBlock),
    89  		"currentBlock":  hexutil.Uint64(progress.CurrentBlock),
    90  		"highestBlock":  hexutil.Uint64(progress.HighestBlock),
    91  		"pulledStates":  hexutil.Uint64(progress.PulledStates),
    92  		"knownStates":   hexutil.Uint64(progress.KnownStates),
    93  	}, nil
    94  }
    95  
    96  // PublicTxPoolAPI offers and API for the transaction pool. It only operates on data that is non confidential.
    97  type PublicTxPoolAPI struct {
    98  	b Backend
    99  }
   100  
   101  // NewPublicTxPoolAPI creates a new tx pool service that gives information about the transaction pool.
   102  func NewPublicTxPoolAPI(b Backend) *PublicTxPoolAPI {
   103  	return &PublicTxPoolAPI{b}
   104  }
   105  
   106  // Content returns the transactions contained within the transaction pool.
   107  func (s *PublicTxPoolAPI) Content() map[string]map[string]map[string]*RPCTransaction {
   108  	content := map[string]map[string]map[string]*RPCTransaction{
   109  		"pending": make(map[string]map[string]*RPCTransaction),
   110  		"queued":  make(map[string]map[string]*RPCTransaction),
   111  	}
   112  	pending, queue := s.b.TxPoolContent()
   113  
   114  	// Flatten the pending transactions
   115  	for account, txs := range pending {
   116  		dump := make(map[string]*RPCTransaction)
   117  		for _, tx := range txs {
   118  			dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx)
   119  		}
   120  		content["pending"][account.Hex()] = dump
   121  	}
   122  	// Flatten the queued transactions
   123  	for account, txs := range queue {
   124  		dump := make(map[string]*RPCTransaction)
   125  		for _, tx := range txs {
   126  			dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx)
   127  		}
   128  		content["queued"][account.Hex()] = dump
   129  	}
   130  	return content
   131  }
   132  
   133  // Status returns the number of pending and queued transaction in the pool.
   134  func (s *PublicTxPoolAPI) Status() map[string]hexutil.Uint {
   135  	pending, queue := s.b.Stats()
   136  	return map[string]hexutil.Uint{
   137  		"pending": hexutil.Uint(pending),
   138  		"queued":  hexutil.Uint(queue),
   139  	}
   140  }
   141  
   142  // Inspect retrieves the content of the transaction pool and flattens it into an
   143  // easily inspectable list.
   144  func (s *PublicTxPoolAPI) Inspect() map[string]map[string]map[string]string {
   145  	content := map[string]map[string]map[string]string{
   146  		"pending": make(map[string]map[string]string),
   147  		"queued":  make(map[string]map[string]string),
   148  	}
   149  	pending, queue := s.b.TxPoolContent()
   150  
   151  	// Define a formatter to flatten a transaction into a string
   152  	var format = func(tx *types.Transaction) string {
   153  		if to := tx.To(); to != nil {
   154  			return fmt.Sprintf("%s: %v wei + %v gas × %v wei", tx.To().Hex(), tx.Value(), tx.Gas(), tx.GasPrice())
   155  		}
   156  		return fmt.Sprintf("contract creation: %v wei + %v gas × %v wei", tx.Value(), tx.Gas(), tx.GasPrice())
   157  	}
   158  	// Flatten the pending transactions
   159  	for account, txs := range pending {
   160  		dump := make(map[string]string)
   161  		for _, tx := range txs {
   162  			dump[fmt.Sprintf("%d", tx.Nonce())] = format(tx)
   163  		}
   164  		content["pending"][account.Hex()] = dump
   165  	}
   166  	// Flatten the queued transactions
   167  	for account, txs := range queue {
   168  		dump := make(map[string]string)
   169  		for _, tx := range txs {
   170  			dump[fmt.Sprintf("%d", tx.Nonce())] = format(tx)
   171  		}
   172  		content["queued"][account.Hex()] = dump
   173  	}
   174  	return content
   175  }
   176  
   177  // PublicAccountAPI provides an API to access accounts managed by this node.
   178  // It offers only methods that can retrieve accounts.
   179  type PublicAccountAPI struct {
   180  	am *accounts.Manager
   181  }
   182  
   183  // NewPublicAccountAPI creates a new PublicAccountAPI.
   184  func NewPublicAccountAPI(am *accounts.Manager) *PublicAccountAPI {
   185  	return &PublicAccountAPI{am: am}
   186  }
   187  
   188  // Accounts returns the collection of accounts this node manages
   189  func (s *PublicAccountAPI) Accounts() []common.Address {
   190  	addresses := make([]common.Address, 0) // return [] instead of nil if empty
   191  	for _, wallet := range s.am.Wallets() {
   192  		for _, account := range wallet.Accounts() {
   193  			addresses = append(addresses, account.Address)
   194  		}
   195  	}
   196  	return addresses
   197  }
   198  
   199  // PrivateAccountAPI provides an API to access accounts managed by this node.
   200  // It offers methods to create, (un)lock en list accounts. Some methods accept
   201  // passwords and are therefore considered private by default.
   202  type PrivateAccountAPI struct {
   203  	am        *accounts.Manager
   204  	nonceLock *AddrLocker
   205  	b         Backend
   206  }
   207  
   208  // NewPrivateAccountAPI create a new PrivateAccountAPI.
   209  func NewPrivateAccountAPI(b Backend, nonceLock *AddrLocker) *PrivateAccountAPI {
   210  	return &PrivateAccountAPI{
   211  		am:        b.AccountManager(),
   212  		nonceLock: nonceLock,
   213  		b:         b,
   214  	}
   215  }
   216  
   217  // ListAccounts will return a list of addresses for accounts this node manages.
   218  func (s *PrivateAccountAPI) ListAccounts() []common.Address {
   219  	addresses := make([]common.Address, 0) // return [] instead of nil if empty
   220  	for _, wallet := range s.am.Wallets() {
   221  		for _, account := range wallet.Accounts() {
   222  			addresses = append(addresses, account.Address)
   223  		}
   224  	}
   225  	return addresses
   226  }
   227  
   228  // rawWallet is a JSON representation of an accounts.Wallet interface, with its
   229  // data contents extracted into plain fields.
   230  type rawWallet struct {
   231  	URL      string             `json:"url"`
   232  	Status   string             `json:"status"`
   233  	Failure  string             `json:"failure,omitempty"`
   234  	Accounts []accounts.Account `json:"accounts,omitempty"`
   235  }
   236  
   237  // ListWallets will return a list of wallets this node manages.
   238  func (s *PrivateAccountAPI) ListWallets() []rawWallet {
   239  	wallets := make([]rawWallet, 0) // return [] instead of nil if empty
   240  	for _, wallet := range s.am.Wallets() {
   241  		status, failure := wallet.Status()
   242  
   243  		raw := rawWallet{
   244  			URL:      wallet.URL().String(),
   245  			Status:   status,
   246  			Accounts: wallet.Accounts(),
   247  		}
   248  		if failure != nil {
   249  			raw.Failure = failure.Error()
   250  		}
   251  		wallets = append(wallets, raw)
   252  	}
   253  	return wallets
   254  }
   255  
   256  // OpenWallet initiates a hardware wallet opening procedure, establishing a USB
   257  // connection and attempting to authenticate via the provided passphrase. Note,
   258  // the method may return an extra challenge requiring a second open (e.g. the
   259  // Trezor PIN matrix challenge).
   260  func (s *PrivateAccountAPI) OpenWallet(url string, passphrase *string) error {
   261  	wallet, err := s.am.Wallet(url)
   262  	if err != nil {
   263  		return err
   264  	}
   265  	pass := ""
   266  	if passphrase != nil {
   267  		pass = *passphrase
   268  	}
   269  	return wallet.Open(pass)
   270  }
   271  
   272  // DeriveAccount requests a HD wallet to derive a new account, optionally pinning
   273  // it for later reuse.
   274  func (s *PrivateAccountAPI) DeriveAccount(url string, path string, pin *bool) (accounts.Account, error) {
   275  	wallet, err := s.am.Wallet(url)
   276  	if err != nil {
   277  		return accounts.Account{}, err
   278  	}
   279  	derivPath, err := accounts.ParseDerivationPath(path)
   280  	if err != nil {
   281  		return accounts.Account{}, err
   282  	}
   283  	if pin == nil {
   284  		pin = new(bool)
   285  	}
   286  	return wallet.Derive(derivPath, *pin)
   287  }
   288  
   289  // NewAccount will create a new account and returns the address for the new account.
   290  func (s *PrivateAccountAPI) NewAccount(password string) (common.Address, error) {
   291  	acc, err := fetchKeystore(s.am).NewAccount(password)
   292  	if err == nil {
   293  		return acc.Address, nil
   294  	}
   295  	return common.Address{}, err
   296  }
   297  
   298  // fetchKeystore retrives the encrypted keystore from the account manager.
   299  func fetchKeystore(am *accounts.Manager) *keystore.KeyStore {
   300  	return am.Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
   301  }
   302  
   303  // ImportRawKey stores the given hex encoded ECDSA key into the key directory,
   304  // encrypting it with the passphrase.
   305  func (s *PrivateAccountAPI) ImportRawKey(privkey string, password string) (common.Address, error) {
   306  	key, err := crypto.HexToECDSA(privkey)
   307  	if err != nil {
   308  		return common.Address{}, err
   309  	}
   310  	acc, err := fetchKeystore(s.am).ImportECDSA(key, password)
   311  	return acc.Address, err
   312  }
   313  
   314  // UnlockAccount will unlock the account associated with the given address with
   315  // the given password for duration seconds. If duration is nil it will use a
   316  // default of 300 seconds. It returns an indication if the account was unlocked.
   317  func (s *PrivateAccountAPI) UnlockAccount(addr common.Address, password string, duration *uint64) (bool, error) {
   318  	const max = uint64(time.Duration(math.MaxInt64) / time.Second)
   319  	var d time.Duration
   320  	if duration == nil {
   321  		d = 300 * time.Second
   322  	} else if *duration > max {
   323  		return false, errors.New("unlock duration too large")
   324  	} else {
   325  		d = time.Duration(*duration) * time.Second
   326  	}
   327  	err := fetchKeystore(s.am).TimedUnlock(accounts.Account{Address: addr}, password, d)
   328  	if err != nil {
   329  		log.Warn("Failed account unlock attempt", "address", addr, "err", err)
   330  	}
   331  	return err == nil, err
   332  }
   333  
   334  // LockAccount will lock the account associated with the given address when it's unlocked.
   335  func (s *PrivateAccountAPI) LockAccount(addr common.Address) bool {
   336  	return fetchKeystore(s.am).Lock(addr) == nil
   337  }
   338  
   339  // signTransaction sets defaults and signs the given transaction
   340  // NOTE: the caller needs to ensure that the nonceLock is held, if applicable,
   341  // and release it after the transaction has been submitted to the tx pool
   342  func (s *PrivateAccountAPI) signTransaction(ctx context.Context, args *SendTxArgs, passwd string) (*types.Transaction, error) {
   343  	// Look up the wallet containing the requested signer
   344  	account := accounts.Account{Address: args.From}
   345  	wallet, err := s.am.Find(account)
   346  	if err != nil {
   347  		return nil, err
   348  	}
   349  	// Set some sanity defaults and terminate on failure
   350  	if err := args.setDefaults(ctx, s.b); err != nil {
   351  		return nil, err
   352  	}
   353  	// Assemble the transaction and sign with the wallet
   354  	tx := args.toTransaction()
   355  
   356  	var chainID *big.Int
   357  	if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) {
   358  		chainID = config.ChainID
   359  	}
   360  	return wallet.SignTxWithPassphrase(account, passwd, tx, chainID)
   361  }
   362  
   363  // SendTransaction will create a transaction from the given arguments and
   364  // tries to sign it with the key associated with args.To. If the given passwd isn't
   365  // able to decrypt the key it fails.
   366  func (s *PrivateAccountAPI) SendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) {
   367  	if args.Nonce == nil {
   368  		// Hold the addresse's mutex around signing to prevent concurrent assignment of
   369  		// the same nonce to multiple accounts.
   370  		s.nonceLock.LockAddr(args.From)
   371  		defer s.nonceLock.UnlockAddr(args.From)
   372  	}
   373  	signed, err := s.signTransaction(ctx, &args, passwd)
   374  	if err != nil {
   375  		log.Warn("Failed transaction send attempt", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err)
   376  		return common.Hash{}, err
   377  	}
   378  	return submitTransaction(ctx, s.b, signed)
   379  }
   380  
   381  // SignTransaction will create a transaction from the given arguments and
   382  // tries to sign it with the key associated with args.To. If the given passwd isn't
   383  // able to decrypt the key it fails. The transaction is returned in RLP-form, not broadcast
   384  // to other nodes
   385  func (s *PrivateAccountAPI) SignTransaction(ctx context.Context, args SendTxArgs, passwd string) (*SignTransactionResult, error) {
   386  	// No need to obtain the noncelock mutex, since we won't be sending this
   387  	// tx into the transaction pool, but right back to the user
   388  	if args.Gas == nil {
   389  		return nil, fmt.Errorf("gas not specified")
   390  	}
   391  	if args.GasPrice == nil {
   392  		return nil, fmt.Errorf("gasPrice not specified")
   393  	}
   394  	if args.Nonce == nil {
   395  		return nil, fmt.Errorf("nonce not specified")
   396  	}
   397  	signed, err := s.signTransaction(ctx, &args, passwd)
   398  	if err != nil {
   399  		log.Warn("Failed transaction sign attempt", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err)
   400  		return nil, err
   401  	}
   402  	data, err := rlp.EncodeToBytes(signed)
   403  	if err != nil {
   404  		return nil, err
   405  	}
   406  	return &SignTransactionResult{data, signed}, nil
   407  }
   408  
   409  // signHash is a helper function that calculates a hash for the given message that can be
   410  // safely used to calculate a signature from.
   411  //
   412  // The hash is calulcated as
   413  //   keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
   414  //
   415  // This gives context to the signed message and prevents signing of transactions.
   416  func signHash(data []byte) []byte {
   417  	msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data)
   418  	return crypto.Keccak256([]byte(msg))
   419  }
   420  
   421  // Sign calculates an Ethereum ECDSA signature for:
   422  // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message))
   423  //
   424  // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
   425  // where the V value will be 27 or 28 for legacy reasons.
   426  //
   427  // The key used to calculate the signature is decrypted with the given password.
   428  //
   429  // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign
   430  func (s *PrivateAccountAPI) Sign(ctx context.Context, data hexutil.Bytes, addr common.Address, passwd string) (hexutil.Bytes, error) {
   431  	// Look up the wallet containing the requested signer
   432  	account := accounts.Account{Address: addr}
   433  
   434  	wallet, err := s.b.AccountManager().Find(account)
   435  	if err != nil {
   436  		return nil, err
   437  	}
   438  	// Assemble sign the data with the wallet
   439  	signature, err := wallet.SignHashWithPassphrase(account, passwd, signHash(data))
   440  	if err != nil {
   441  		log.Warn("Failed data sign attempt", "address", addr, "err", err)
   442  		return nil, err
   443  	}
   444  	signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
   445  	return signature, nil
   446  }
   447  
   448  // EcRecover returns the address for the account that was used to create the signature.
   449  // Note, this function is compatible with eth_sign and personal_sign. As such it recovers
   450  // the address of:
   451  // hash = keccak256("\x19Ethereum Signed Message:\n"${message length}${message})
   452  // addr = ecrecover(hash, signature)
   453  //
   454  // Note, the signature must conform to the secp256k1 curve R, S and V values, where
   455  // the V value must be 27 or 28 for legacy reasons.
   456  //
   457  // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_ecRecover
   458  func (s *PrivateAccountAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) {
   459  	if len(sig) != 65 {
   460  		return common.Address{}, fmt.Errorf("signature must be 65 bytes long")
   461  	}
   462  	if sig[64] != 27 && sig[64] != 28 {
   463  		return common.Address{}, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)")
   464  	}
   465  	sig[64] -= 27 // Transform yellow paper V from 27/28 to 0/1
   466  
   467  	rpk, err := crypto.SigToPub(signHash(data), sig)
   468  	if err != nil {
   469  		return common.Address{}, err
   470  	}
   471  	return crypto.PubkeyToAddress(*rpk), nil
   472  }
   473  
   474  // SignAndSendTransaction was renamed to SendTransaction. This method is deprecated
   475  // and will be removed in the future. It primary goal is to give clients time to update.
   476  func (s *PrivateAccountAPI) SignAndSendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) {
   477  	return s.SendTransaction(ctx, args, passwd)
   478  }
   479  
   480  // PublicBlockChainAPI provides an API to access the Ethereum blockchain.
   481  // It offers only methods that operate on public data that is freely available to anyone.
   482  type PublicBlockChainAPI struct {
   483  	b Backend
   484  }
   485  
   486  // NewPublicBlockChainAPI creates a new Ethereum blockchain API.
   487  func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI {
   488  	return &PublicBlockChainAPI{b}
   489  }
   490  
   491  // BlockNumber returns the block number of the chain head.
   492  func (s *PublicBlockChainAPI) BlockNumber() hexutil.Uint64 {
   493  	header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available
   494  	return hexutil.Uint64(header.Number.Uint64())
   495  }
   496  
   497  // GetBalance returns the amount of wei for the given address in the state of the
   498  // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
   499  // block numbers are also allowed.
   500  func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*hexutil.Big, error) {
   501  	state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
   502  	if state == nil || err != nil {
   503  		return nil, err
   504  	}
   505  	return (*hexutil.Big)(state.GetBalance(address)), state.Error()
   506  }
   507  
   508  // Result structs for GetProof
   509  type AccountResult struct {
   510  	Address      common.Address  `json:"address"`
   511  	AccountProof []string        `json:"accountProof"`
   512  	Balance      *hexutil.Big    `json:"balance"`
   513  	CodeHash     common.Hash     `json:"codeHash"`
   514  	Nonce        hexutil.Uint64  `json:"nonce"`
   515  	StorageHash  common.Hash     `json:"storageHash"`
   516  	StorageProof []StorageResult `json:"storageProof"`
   517  }
   518  type StorageResult struct {
   519  	Key   string       `json:"key"`
   520  	Value *hexutil.Big `json:"value"`
   521  	Proof []string     `json:"proof"`
   522  }
   523  
   524  // GetProof returns the Merkle-proof for a given account and optionally some storage keys.
   525  func (s *PublicBlockChainAPI) GetProof(ctx context.Context, address common.Address, storageKeys []string, blockNr rpc.BlockNumber) (*AccountResult, error) {
   526  	state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
   527  	if state == nil || err != nil {
   528  		return nil, err
   529  	}
   530  
   531  	storageTrie := state.StorageTrie(address)
   532  	storageHash := types.EmptyRootHash
   533  	codeHash := state.GetCodeHash(address)
   534  	storageProof := make([]StorageResult, len(storageKeys))
   535  
   536  	// if we have a storageTrie, (which means the account exists), we can update the storagehash
   537  	if storageTrie != nil {
   538  		storageHash = storageTrie.Hash()
   539  	} else {
   540  		// no storageTrie means the account does not exist, so the codeHash is the hash of an empty bytearray.
   541  		codeHash = crypto.Keccak256Hash(nil)
   542  	}
   543  
   544  	// create the proof for the storageKeys
   545  	for i, key := range storageKeys {
   546  		if storageTrie != nil {
   547  			proof, storageError := state.GetStorageProof(address, common.HexToHash(key))
   548  			if storageError != nil {
   549  				return nil, storageError
   550  			}
   551  			storageProof[i] = StorageResult{key, (*hexutil.Big)(state.GetState(address, common.HexToHash(key)).Big()), common.ToHexArray(proof)}
   552  		} else {
   553  			storageProof[i] = StorageResult{key, &hexutil.Big{}, []string{}}
   554  		}
   555  	}
   556  
   557  	// create the accountProof
   558  	accountProof, proofErr := state.GetProof(address)
   559  	if proofErr != nil {
   560  		return nil, proofErr
   561  	}
   562  
   563  	return &AccountResult{
   564  		Address:      address,
   565  		AccountProof: common.ToHexArray(accountProof),
   566  		Balance:      (*hexutil.Big)(state.GetBalance(address)),
   567  		CodeHash:     codeHash,
   568  		Nonce:        hexutil.Uint64(state.GetNonce(address)),
   569  		StorageHash:  storageHash,
   570  		StorageProof: storageProof,
   571  	}, state.Error()
   572  }
   573  
   574  // GetBlockByNumber returns the requested block. When blockNr is -1 the chain head is returned. When fullTx is true all
   575  // transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
   576  func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, blockNr rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
   577  	block, err := s.b.BlockByNumber(ctx, blockNr)
   578  	if block != nil {
   579  		response, err := s.rpcOutputBlock(block, true, fullTx)
   580  		if err == nil && blockNr == rpc.PendingBlockNumber {
   581  			// Pending blocks need to nil out a few fields
   582  			for _, field := range []string{"hash", "nonce", "miner"} {
   583  				response[field] = nil
   584  			}
   585  		}
   586  		return response, err
   587  	}
   588  	return nil, err
   589  }
   590  
   591  // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
   592  // detail, otherwise only the transaction hash is returned.
   593  func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, blockHash common.Hash, fullTx bool) (map[string]interface{}, error) {
   594  	block, err := s.b.GetBlock(ctx, blockHash)
   595  	if block != nil {
   596  		return s.rpcOutputBlock(block, true, fullTx)
   597  	}
   598  	return nil, err
   599  }
   600  
   601  // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true
   602  // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
   603  func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) {
   604  	block, err := s.b.BlockByNumber(ctx, blockNr)
   605  	if block != nil {
   606  		uncles := block.Uncles()
   607  		if index >= hexutil.Uint(len(uncles)) {
   608  			log.Debug("Requested uncle not found", "number", blockNr, "hash", block.Hash(), "index", index)
   609  			return nil, nil
   610  		}
   611  		block = types.NewBlockWithHeader(uncles[index])
   612  		return s.rpcOutputBlock(block, false, false)
   613  	}
   614  	return nil, err
   615  }
   616  
   617  // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true
   618  // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
   619  func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) {
   620  	block, err := s.b.GetBlock(ctx, blockHash)
   621  	if block != nil {
   622  		uncles := block.Uncles()
   623  		if index >= hexutil.Uint(len(uncles)) {
   624  			log.Debug("Requested uncle not found", "number", block.Number(), "hash", blockHash, "index", index)
   625  			return nil, nil
   626  		}
   627  		block = types.NewBlockWithHeader(uncles[index])
   628  		return s.rpcOutputBlock(block, false, false)
   629  	}
   630  	return nil, err
   631  }
   632  
   633  // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
   634  func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
   635  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
   636  		n := hexutil.Uint(len(block.Uncles()))
   637  		return &n
   638  	}
   639  	return nil
   640  }
   641  
   642  // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash
   643  func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
   644  	if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
   645  		n := hexutil.Uint(len(block.Uncles()))
   646  		return &n
   647  	}
   648  	return nil
   649  }
   650  
   651  // GetCode returns the code stored at the given address in the state for the given block number.
   652  func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (hexutil.Bytes, error) {
   653  	state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
   654  	if state == nil || err != nil {
   655  		return nil, err
   656  	}
   657  	code := state.GetCode(address)
   658  	return code, state.Error()
   659  }
   660  
   661  // GetStorageAt returns the storage from the state at the given address, key and
   662  // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
   663  // numbers are also allowed.
   664  func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNr rpc.BlockNumber) (hexutil.Bytes, error) {
   665  	state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
   666  	if state == nil || err != nil {
   667  		return nil, err
   668  	}
   669  	res := state.GetState(address, common.HexToHash(key))
   670  	return res[:], state.Error()
   671  }
   672  
   673  // CallArgs represents the arguments for a call.
   674  type CallArgs struct {
   675  	From                common.Address  `json:"from"`
   676  	To                  *common.Address `json:"to"`
   677  	Gas                 hexutil.Uint64  `json:"gas"`
   678  	GasPrice            hexutil.Big     `json:"gasPrice"`
   679  	FeeCurrency         *common.Address `json:"feeCurrency"`
   680  	GatewayFeeRecipient *common.Address `json:"gatewayFeeRecipient"`
   681  	GatewayFee          hexutil.Big     `json:"gatewayFee"`
   682  	Value               hexutil.Big     `json:"value"`
   683  	Data                hexutil.Bytes   `json:"data"`
   684  }
   685  
   686  func (s *PublicBlockChainAPI) doCall(ctx context.Context, args CallArgs, blockNr rpc.BlockNumber, timeout time.Duration, estimate bool) (res []byte, gas uint64, failed bool, err error) {
   687  	defer func(start time.Time) { log.Debug("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now())
   688  
   689  	state, header, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
   690  	if state == nil || err != nil {
   691  		return nil, 0, false, err
   692  	}
   693  	// Set sender address or use a default if none specified
   694  	addr := args.From
   695  	if addr == (common.Address{}) {
   696  		if wallets := s.b.AccountManager().Wallets(); len(wallets) > 0 {
   697  			if accounts := wallets[0].Accounts(); len(accounts) > 0 {
   698  				addr = accounts[0].Address
   699  			}
   700  		}
   701  	}
   702  	// Set default gas & gas price if none were set
   703  	gas, gasPrice := uint64(args.Gas), args.GasPrice.ToInt()
   704  	if gas == 0 {
   705  		gas = math.MaxUint64 / 2
   706  	}
   707  	// Checking against 0 is a hack to allow users to bypass the default gas price being set by web3,
   708  	// which will always be in Gold. This allows the default price to be set for the proper currency.
   709  	// TODO(asa): Remove this once this is handled in the Provider.
   710  	if gasPrice.Sign() == 0 || gasPrice.Cmp(big.NewInt(0)) == 0 {
   711  		gasPrice, err = s.b.SuggestPriceInCurrency(ctx, args.FeeCurrency)
   712  	}
   713  
   714  	// Create new call message
   715  	msg := types.NewMessage(addr, args.To, 0, args.Value.ToInt(), gas, gasPrice, args.FeeCurrency, args.GatewayFeeRecipient, args.GatewayFee.ToInt(), args.Data, false)
   716  
   717  	// Setup context so it may be cancelled the call has completed
   718  	// or, in case of unmetered gas, setup a context with a timeout.
   719  	var cancel context.CancelFunc
   720  	if timeout > 0 {
   721  		ctx, cancel = context.WithTimeout(ctx, timeout)
   722  	} else {
   723  		ctx, cancel = context.WithCancel(ctx)
   724  	}
   725  	// Make sure the context is cancelled when the call has completed
   726  	// this makes sure resources are cleaned up.
   727  	defer cancel()
   728  
   729  	// Get a new instance of the EVM.
   730  	evm, vmError, err := s.b.GetEVM(ctx, msg, header, state)
   731  	if err != nil {
   732  		return nil, 0, false, err
   733  	}
   734  	// Wait for the context to be done and cancel the evm. Even if the
   735  	// EVM has finished, cancelling may be done (repeatedly)
   736  	go func() {
   737  		<-ctx.Done()
   738  		evm.Cancel()
   739  	}()
   740  
   741  	// Setup the gas pool (also for unmetered requests) and apply the message.
   742  	gp := new(core.GasPool).AddGas(math.MaxUint64)
   743  	if estimate {
   744  		res, gas, failed, err = core.ApplyEstimatorMessage(evm, msg, gp)
   745  	} else {
   746  		res, gas, failed, err = core.ApplyMessage(evm, msg, gp)
   747  	}
   748  
   749  	if err := vmError(); err != nil {
   750  		return nil, 0, false, err
   751  	}
   752  	return res, gas, failed, err
   753  }
   754  
   755  // Call executes the given transaction on the state for the given block number.
   756  // It doesn't make and changes in the state/blockchain and is useful to execute and retrieve values.
   757  func (s *PublicBlockChainAPI) Call(ctx context.Context, args CallArgs, blockNr rpc.BlockNumber) (hexutil.Bytes, error) {
   758  	result, _, _, err := s.doCall(ctx, args, blockNr, 5*time.Second, false)
   759  	return (hexutil.Bytes)(result), err
   760  }
   761  
   762  // EstimateGas returns an estimate of the amount of gas needed to execute the
   763  // given transaction against the current pending block.
   764  func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args CallArgs) (hexutil.Uint64, error) {
   765  	// Binary search the gas requirement, as it may be higher than the amount used
   766  	var (
   767  		lo  uint64 = params.TxGas - 1
   768  		hi  uint64
   769  		cap uint64
   770  	)
   771  	if uint64(args.Gas) >= params.TxGas {
   772  		hi = uint64(args.Gas)
   773  	} else {
   774  		// Retrieve the current pending block to act as the gas ceiling
   775  		block, err := s.b.BlockByNumber(ctx, rpc.PendingBlockNumber)
   776  		if err != nil {
   777  			return 0, err
   778  		}
   779  		hi = block.GasLimit()
   780  	}
   781  	cap = hi
   782  
   783  	// Create a helper to check if a gas allowance results in an executable transaction
   784  	executable := func(gas uint64) bool {
   785  		args.Gas = hexutil.Uint64(gas)
   786  
   787  		_, _, failed, err := s.doCall(ctx, args, rpc.PendingBlockNumber, 0, true)
   788  		if err != nil || failed {
   789  			return false
   790  		}
   791  		return true
   792  	}
   793  	// Execute the binary search and hone in on an executable gas limit
   794  	for lo+1 < hi {
   795  		mid := (hi + lo) / 2
   796  		if !executable(mid) {
   797  			lo = mid
   798  		} else {
   799  			hi = mid
   800  		}
   801  	}
   802  	// Reject the transaction as invalid if it still fails at the highest allowance
   803  	if hi == cap {
   804  		if !executable(hi) {
   805  			return 0, fmt.Errorf("gas required exceeds allowance or always failing transaction")
   806  		}
   807  	}
   808  	return hexutil.Uint64(hi), nil
   809  }
   810  
   811  // ExecutionResult groups all structured logs emitted by the EVM
   812  // while replaying a transaction in debug mode as well as transaction
   813  // execution status, the amount of gas used and the return value
   814  type ExecutionResult struct {
   815  	Gas         uint64         `json:"gas"`
   816  	Failed      bool           `json:"failed"`
   817  	ReturnValue string         `json:"returnValue"`
   818  	StructLogs  []StructLogRes `json:"structLogs"`
   819  }
   820  
   821  // StructLogRes stores a structured log emitted by the EVM while replaying a
   822  // transaction in debug mode
   823  type StructLogRes struct {
   824  	Pc      uint64             `json:"pc"`
   825  	Op      string             `json:"op"`
   826  	Gas     uint64             `json:"gas"`
   827  	GasCost uint64             `json:"gasCost"`
   828  	Depth   int                `json:"depth"`
   829  	Error   error              `json:"error,omitempty"`
   830  	Stack   *[]string          `json:"stack,omitempty"`
   831  	Memory  *[]string          `json:"memory,omitempty"`
   832  	Storage *map[string]string `json:"storage,omitempty"`
   833  }
   834  
   835  // formatLogs formats EVM returned structured logs for json output
   836  func FormatLogs(logs []vm.StructLog) []StructLogRes {
   837  	formatted := make([]StructLogRes, len(logs))
   838  	for index, trace := range logs {
   839  		formatted[index] = StructLogRes{
   840  			Pc:      trace.Pc,
   841  			Op:      trace.Op.String(),
   842  			Gas:     trace.Gas,
   843  			GasCost: trace.GasCost,
   844  			Depth:   trace.Depth,
   845  			Error:   trace.Err,
   846  		}
   847  		if trace.Stack != nil {
   848  			stack := make([]string, len(trace.Stack))
   849  			for i, stackValue := range trace.Stack {
   850  				stack[i] = fmt.Sprintf("%x", math.PaddedBigBytes(stackValue, 32))
   851  			}
   852  			formatted[index].Stack = &stack
   853  		}
   854  		if trace.Memory != nil {
   855  			memory := make([]string, 0, (len(trace.Memory)+31)/32)
   856  			for i := 0; i+32 <= len(trace.Memory); i += 32 {
   857  				memory = append(memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
   858  			}
   859  			formatted[index].Memory = &memory
   860  		}
   861  		if trace.Storage != nil {
   862  			storage := make(map[string]string)
   863  			for i, storageValue := range trace.Storage {
   864  				storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
   865  			}
   866  			formatted[index].Storage = &storage
   867  		}
   868  	}
   869  	return formatted
   870  }
   871  
   872  // RPCMarshalBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
   873  // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
   874  // transaction hashes.
   875  func RPCMarshalBlock(b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
   876  	head := b.Header() // copies the header once
   877  	// TODO(asa): Consider removing parentHash
   878  	fields := map[string]interface{}{
   879  		"number":           (*hexutil.Big)(head.Number),
   880  		"hash":             b.Hash(),
   881  		"parentHash":       head.ParentHash,
   882  		"nonce":            head.Nonce,
   883  		"mixHash":          head.MixDigest,
   884  		"sha3Uncles":       head.UncleHash,
   885  		"logsBloom":        head.Bloom,
   886  		"stateRoot":        head.Root,
   887  		"miner":            head.Coinbase,
   888  		"difficulty":       (*hexutil.Big)(head.Difficulty),
   889  		"extraData":        hexutil.Bytes(head.Extra),
   890  		"size":             hexutil.Uint64(b.Size()),
   891  		"gasLimit":         hexutil.Uint64(head.GasLimit),
   892  		"gasUsed":          hexutil.Uint64(head.GasUsed),
   893  		"timestamp":        (*hexutil.Big)(head.Time),
   894  		"transactionsRoot": head.TxHash,
   895  		"receiptsRoot":     head.ReceiptHash,
   896  	}
   897  	fields["randomness"] = map[string]interface{}{
   898  		"revealed":  hexutil.Bytes(b.Randomness().Revealed.Bytes()),
   899  		"committed": hexutil.Bytes(b.Randomness().Committed.Bytes()),
   900  	}
   901  
   902  	if inclTx {
   903  		formatTx := func(tx *types.Transaction) (interface{}, error) {
   904  			return tx.Hash(), nil
   905  		}
   906  		if fullTx {
   907  			formatTx = func(tx *types.Transaction) (interface{}, error) {
   908  				return newRPCTransactionFromBlockHash(b, tx.Hash()), nil
   909  			}
   910  		}
   911  		txs := b.Transactions()
   912  		transactions := make([]interface{}, len(txs))
   913  		var err error
   914  		for i, tx := range txs {
   915  			if transactions[i], err = formatTx(tx); err != nil {
   916  				return nil, err
   917  			}
   918  		}
   919  		fields["transactions"] = transactions
   920  	}
   921  
   922  	uncles := b.Uncles()
   923  	uncleHashes := make([]common.Hash, len(uncles))
   924  	for i, uncle := range uncles {
   925  		uncleHashes[i] = uncle.Hash()
   926  	}
   927  	fields["uncles"] = uncleHashes
   928  
   929  	return fields, nil
   930  }
   931  
   932  // rpcOutputBlock uses the generalized output filler, then adds the total difficulty field, which requires
   933  // a `PublicBlockchainAPI`.
   934  func (s *PublicBlockChainAPI) rpcOutputBlock(b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
   935  	fields, err := RPCMarshalBlock(b, inclTx, fullTx)
   936  	if err != nil {
   937  		return nil, err
   938  	}
   939  	fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(b.Hash()))
   940  	return fields, err
   941  }
   942  
   943  // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
   944  type RPCTransaction struct {
   945  	BlockHash           common.Hash     `json:"blockHash"`
   946  	BlockNumber         *hexutil.Big    `json:"blockNumber"`
   947  	From                common.Address  `json:"from"`
   948  	Gas                 hexutil.Uint64  `json:"gas"`
   949  	GasPrice            *hexutil.Big    `json:"gasPrice"`
   950  	FeeCurrency         *common.Address `json:"feeCurrency"`
   951  	GatewayFeeRecipient *common.Address `json:"gatewayFeeRecipient"`
   952  	GatewayFee          *hexutil.Big    `json:"gatewayFee"`
   953  	Hash                common.Hash     `json:"hash"`
   954  	Input               hexutil.Bytes   `json:"input"`
   955  	Nonce               hexutil.Uint64  `json:"nonce"`
   956  	To                  *common.Address `json:"to"`
   957  	TransactionIndex    hexutil.Uint    `json:"transactionIndex"`
   958  	Value               *hexutil.Big    `json:"value"`
   959  	V                   *hexutil.Big    `json:"v"`
   960  	R                   *hexutil.Big    `json:"r"`
   961  	S                   *hexutil.Big    `json:"s"`
   962  }
   963  
   964  // newRPCTransaction returns a transaction that will serialize to the RPC
   965  // representation, with the given location metadata set (if available).
   966  func newRPCTransaction(tx *types.Transaction, blockHash common.Hash, blockNumber uint64, index uint64) *RPCTransaction {
   967  	var signer types.Signer = types.FrontierSigner{}
   968  	if tx.Protected() {
   969  		signer = types.NewEIP155Signer(tx.ChainId())
   970  	}
   971  	from, _ := types.Sender(signer, tx)
   972  	v, r, s := tx.RawSignatureValues()
   973  
   974  	result := &RPCTransaction{
   975  		From:                from,
   976  		Gas:                 hexutil.Uint64(tx.Gas()),
   977  		GasPrice:            (*hexutil.Big)(tx.GasPrice()),
   978  		FeeCurrency:         tx.FeeCurrency(),
   979  		GatewayFeeRecipient: tx.GatewayFeeRecipient(),
   980  		GatewayFee:          (*hexutil.Big)(tx.GatewayFee()),
   981  		Hash:                tx.Hash(),
   982  		Input:               hexutil.Bytes(tx.Data()),
   983  		Nonce:               hexutil.Uint64(tx.Nonce()),
   984  		To:                  tx.To(),
   985  		Value:               (*hexutil.Big)(tx.Value()),
   986  		V:                   (*hexutil.Big)(v),
   987  		R:                   (*hexutil.Big)(r),
   988  		S:                   (*hexutil.Big)(s),
   989  	}
   990  	if blockHash != (common.Hash{}) {
   991  		result.BlockHash = blockHash
   992  		result.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(blockNumber))
   993  		result.TransactionIndex = hexutil.Uint(index)
   994  	}
   995  	return result
   996  }
   997  
   998  // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation
   999  func newRPCPendingTransaction(tx *types.Transaction) *RPCTransaction {
  1000  	return newRPCTransaction(tx, common.Hash{}, 0, 0)
  1001  }
  1002  
  1003  // newRPCTransactionFromBlockIndex returns a transaction that will serialize to the RPC representation.
  1004  func newRPCTransactionFromBlockIndex(b *types.Block, index uint64) *RPCTransaction {
  1005  	txs := b.Transactions()
  1006  	if index >= uint64(len(txs)) {
  1007  		return nil
  1008  	}
  1009  	return newRPCTransaction(txs[index], b.Hash(), b.NumberU64(), index)
  1010  }
  1011  
  1012  // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index.
  1013  func newRPCRawTransactionFromBlockIndex(b *types.Block, index uint64) hexutil.Bytes {
  1014  	txs := b.Transactions()
  1015  	if index >= uint64(len(txs)) {
  1016  		return nil
  1017  	}
  1018  	blob, _ := rlp.EncodeToBytes(txs[index])
  1019  	return blob
  1020  }
  1021  
  1022  // newRPCTransactionFromBlockHash returns a transaction that will serialize to the RPC representation.
  1023  func newRPCTransactionFromBlockHash(b *types.Block, hash common.Hash) *RPCTransaction {
  1024  	for idx, tx := range b.Transactions() {
  1025  		if tx.Hash() == hash {
  1026  			return newRPCTransactionFromBlockIndex(b, uint64(idx))
  1027  		}
  1028  	}
  1029  	return nil
  1030  }
  1031  
  1032  // PublicTransactionPoolAPI exposes methods for the RPC interface
  1033  type PublicTransactionPoolAPI struct {
  1034  	b         Backend
  1035  	nonceLock *AddrLocker
  1036  }
  1037  
  1038  // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.
  1039  func NewPublicTransactionPoolAPI(b Backend, nonceLock *AddrLocker) *PublicTransactionPoolAPI {
  1040  	return &PublicTransactionPoolAPI{b, nonceLock}
  1041  }
  1042  
  1043  // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
  1044  func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  1045  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1046  		n := hexutil.Uint(len(block.Transactions()))
  1047  		return &n
  1048  	}
  1049  	return nil
  1050  }
  1051  
  1052  // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
  1053  func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  1054  	if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  1055  		n := hexutil.Uint(len(block.Transactions()))
  1056  		return &n
  1057  	}
  1058  	return nil
  1059  }
  1060  
  1061  // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
  1062  func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) *RPCTransaction {
  1063  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1064  		return newRPCTransactionFromBlockIndex(block, uint64(index))
  1065  	}
  1066  	return nil
  1067  }
  1068  
  1069  // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
  1070  func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) *RPCTransaction {
  1071  	if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  1072  		return newRPCTransactionFromBlockIndex(block, uint64(index))
  1073  	}
  1074  	return nil
  1075  }
  1076  
  1077  // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
  1078  func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) hexutil.Bytes {
  1079  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1080  		return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1081  	}
  1082  	return nil
  1083  }
  1084  
  1085  // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index.
  1086  func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) hexutil.Bytes {
  1087  	if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  1088  		return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1089  	}
  1090  	return nil
  1091  }
  1092  
  1093  // GetTransactionCount returns the number of transactions the given address has sent for the given block number
  1094  func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*hexutil.Uint64, error) {
  1095  	// Ask transaction pool for the nonce which includes pending transactions
  1096  	if blockNr == rpc.PendingBlockNumber {
  1097  		nonce, err := s.b.GetPoolNonce(ctx, address)
  1098  		if err != nil {
  1099  			return nil, err
  1100  		}
  1101  		return (*hexutil.Uint64)(&nonce), nil
  1102  	}
  1103  	// Resolve block number and use its state to ask for the nonce
  1104  	state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
  1105  	if state == nil || err != nil {
  1106  		return nil, err
  1107  	}
  1108  	nonce := state.GetNonce(address)
  1109  	return (*hexutil.Uint64)(&nonce), state.Error()
  1110  }
  1111  
  1112  // GetTransactionByHash returns the transaction for the given hash
  1113  func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) *RPCTransaction {
  1114  	// Try to return an already finalized transaction
  1115  	if tx, blockHash, blockNumber, index := rawdb.ReadTransaction(s.b.ChainDb(), hash); tx != nil {
  1116  		return newRPCTransaction(tx, blockHash, blockNumber, index)
  1117  	}
  1118  	// No finalized transaction, try to retrieve it from the pool
  1119  	if tx := s.b.GetPoolTransaction(hash); tx != nil {
  1120  		return newRPCPendingTransaction(tx)
  1121  	}
  1122  	// Transaction unknown, return as such
  1123  	return nil
  1124  }
  1125  
  1126  // GetRawTransactionByHash returns the bytes of the transaction for the given hash.
  1127  func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  1128  	var tx *types.Transaction
  1129  
  1130  	// Retrieve a finalized transaction, or a pooled otherwise
  1131  	if tx, _, _, _ = rawdb.ReadTransaction(s.b.ChainDb(), hash); tx == nil {
  1132  		if tx = s.b.GetPoolTransaction(hash); tx == nil {
  1133  			// Transaction not found anywhere, abort
  1134  			return nil, nil
  1135  		}
  1136  	}
  1137  	// Serialize to RLP and return
  1138  	return rlp.EncodeToBytes(tx)
  1139  }
  1140  
  1141  // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  1142  func (s *PublicTransactionPoolAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) {
  1143  	tx, blockHash, blockNumber, index := rawdb.ReadTransaction(s.b.ChainDb(), hash)
  1144  	if tx == nil {
  1145  		return nil, nil
  1146  	}
  1147  	receipts, err := s.b.GetReceipts(ctx, blockHash)
  1148  	if err != nil {
  1149  		return nil, err
  1150  	}
  1151  	if len(receipts) <= int(index) {
  1152  		return nil, nil
  1153  	}
  1154  	receipt := receipts[index]
  1155  
  1156  	var signer types.Signer = types.FrontierSigner{}
  1157  	if tx.Protected() {
  1158  		signer = types.NewEIP155Signer(tx.ChainId())
  1159  	}
  1160  	from, _ := types.Sender(signer, tx)
  1161  
  1162  	fields := map[string]interface{}{
  1163  		"blockHash":         blockHash,
  1164  		"blockNumber":       hexutil.Uint64(blockNumber),
  1165  		"transactionHash":   hash,
  1166  		"transactionIndex":  hexutil.Uint64(index),
  1167  		"from":              from,
  1168  		"to":                tx.To(),
  1169  		"gasUsed":           hexutil.Uint64(receipt.GasUsed),
  1170  		"cumulativeGasUsed": hexutil.Uint64(receipt.CumulativeGasUsed),
  1171  		"contractAddress":   nil,
  1172  		"logs":              receipt.Logs,
  1173  		"logsBloom":         receipt.Bloom,
  1174  	}
  1175  
  1176  	// Assign receipt status or post state.
  1177  	if len(receipt.PostState) > 0 {
  1178  		fields["root"] = hexutil.Bytes(receipt.PostState)
  1179  	} else {
  1180  		fields["status"] = hexutil.Uint(receipt.Status)
  1181  	}
  1182  	if receipt.Logs == nil {
  1183  		fields["logs"] = [][]*types.Log{}
  1184  	}
  1185  	// If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  1186  	if receipt.ContractAddress != (common.Address{}) {
  1187  		fields["contractAddress"] = receipt.ContractAddress
  1188  	}
  1189  	return fields, nil
  1190  }
  1191  
  1192  // sign is a helper function that signs a transaction with the private key of the given address.
  1193  func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
  1194  	// Look up the wallet containing the requested signer
  1195  	account := accounts.Account{Address: addr}
  1196  
  1197  	wallet, err := s.b.AccountManager().Find(account)
  1198  	if err != nil {
  1199  		return nil, err
  1200  	}
  1201  	// Request the wallet to sign the transaction
  1202  	var chainID *big.Int
  1203  	if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) {
  1204  		chainID = config.ChainID
  1205  	}
  1206  	return wallet.SignTx(account, tx, chainID)
  1207  }
  1208  
  1209  // SendTxArgs represents the arguments to sumbit a new transaction into the transaction pool.
  1210  type SendTxArgs struct {
  1211  	From                common.Address  `json:"from"`
  1212  	To                  *common.Address `json:"to"`
  1213  	Gas                 *hexutil.Uint64 `json:"gas"`
  1214  	GasPrice            *hexutil.Big    `json:"gasPrice"`
  1215  	FeeCurrency         *common.Address `json:"feeCurrency"`
  1216  	GatewayFeeRecipient *common.Address `json:"gatewayFeeRecipient"`
  1217  	GatewayFee          *hexutil.Big    `json:"gatewayFee"`
  1218  	Value               *hexutil.Big    `json:"value"`
  1219  	Nonce               *hexutil.Uint64 `json:"nonce"`
  1220  	// We accept "data" and "input" for backwards-compatibility reasons. "input" is the
  1221  	// newer name and should be preferred by clients.
  1222  	Data  *hexutil.Bytes `json:"data"`
  1223  	Input *hexutil.Bytes `json:"input"`
  1224  }
  1225  
  1226  // setDefaults is a helper function that fills in default values for unspecified tx fields.
  1227  func (args *SendTxArgs) setDefaults(ctx context.Context, b Backend) error {
  1228  	if args.Gas == nil {
  1229  		args.Gas = new(hexutil.Uint64)
  1230  		defaultGas := uint64(90000)
  1231  		if args.FeeCurrency == nil {
  1232  			*(*uint64)(args.Gas) = defaultGas
  1233  		} else {
  1234  			// When paying for fees in a currency other than Celo Gold, the intrinsic gas use is greater than when paying for fees in Celo Gold.
  1235  			// We need to cover the gas use of one 'balanceOf', one 'debitFrom', and two 'creditTo' calls.
  1236  			state, header, err := b.StateAndHeaderByNumber(ctx, rpc.LatestBlockNumber)
  1237  			if err != nil {
  1238  				*(*uint64)(args.Gas) = defaultGas + blockchain_parameters.GetIntrinsicGasForAlternativeFeeCurrency(header, state)
  1239  			} else {
  1240  				log.Warn("Cannot read intrinsic gas for alternative fee currency", "err", err)
  1241  				*(*uint64)(args.Gas) = defaultGas + params.IntrinsicGasForAlternativeFeeCurrency
  1242  			}
  1243  		}
  1244  	}
  1245  	// Checking against 0 is a hack to allow users to bypass the default gas price being set by web3,
  1246  	// which will always be in Gold. This allows the default price to be set for the proper currency.
  1247  	// TODO(asa): Remove this once this is handled in the Provider.
  1248  	if args.GasPrice == nil || args.GasPrice.ToInt().Cmp(big.NewInt(0)) == 0 {
  1249  		price, err := b.SuggestPriceInCurrency(ctx, args.FeeCurrency)
  1250  		if err != nil {
  1251  			return err
  1252  		}
  1253  		args.GasPrice = (*hexutil.Big)(price)
  1254  	}
  1255  	if args.Value == nil {
  1256  		args.Value = new(hexutil.Big)
  1257  	}
  1258  	if args.Nonce == nil {
  1259  		nonce, err := b.GetPoolNonce(ctx, args.From)
  1260  		if err != nil {
  1261  			return err
  1262  		}
  1263  		args.Nonce = (*hexutil.Uint64)(&nonce)
  1264  	}
  1265  	if args.Data != nil && args.Input != nil && !bytes.Equal(*args.Data, *args.Input) {
  1266  		return errors.New(`Both "data" and "input" are set and not equal. Please use "input" to pass transaction call data.`)
  1267  	}
  1268  	if args.To == nil {
  1269  		// Contract creation
  1270  		var input []byte
  1271  		if args.Data != nil {
  1272  			input = *args.Data
  1273  		} else if args.Input != nil {
  1274  			input = *args.Input
  1275  		}
  1276  		if len(input) == 0 {
  1277  			return errors.New(`contract creation without any data provided`)
  1278  		}
  1279  	}
  1280  
  1281  	if args.GatewayFeeRecipient == nil {
  1282  		recipient := b.GatewayFeeRecipient()
  1283  		if (recipient != common.Address{}) {
  1284  			args.GatewayFeeRecipient = &recipient
  1285  		}
  1286  	}
  1287  
  1288  	if args.GatewayFeeRecipient != nil && args.GatewayFee == nil {
  1289  		args.GatewayFee = (*hexutil.Big)(b.GatewayFee())
  1290  	}
  1291  	return nil
  1292  }
  1293  
  1294  func (args *SendTxArgs) toTransaction() *types.Transaction {
  1295  	var input []byte
  1296  	if args.Data != nil {
  1297  		input = *args.Data
  1298  	} else if args.Input != nil {
  1299  		input = *args.Input
  1300  	}
  1301  	if args.To == nil {
  1302  		return types.NewContractCreation(uint64(*args.Nonce), (*big.Int)(args.Value), uint64(*args.Gas), (*big.Int)(args.GasPrice), args.FeeCurrency, args.GatewayFeeRecipient, (*big.Int)(args.GatewayFee), input)
  1303  	}
  1304  	return types.NewTransaction(uint64(*args.Nonce), *args.To, (*big.Int)(args.Value), uint64(*args.Gas), (*big.Int)(args.GasPrice), args.FeeCurrency, args.GatewayFeeRecipient, (*big.Int)(args.GatewayFee), input)
  1305  }
  1306  
  1307  // submitTransaction is a helper function that submits tx to txPool and logs a message.
  1308  func submitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (common.Hash, error) {
  1309  	if err := b.SendTx(ctx, tx); err != nil {
  1310  		return common.Hash{}, err
  1311  	}
  1312  	if tx.To() == nil {
  1313  		signer := types.MakeSigner(b.ChainConfig(), b.CurrentBlock().Number())
  1314  		from, err := types.Sender(signer, tx)
  1315  		if err != nil {
  1316  			return common.Hash{}, err
  1317  		}
  1318  		addr := crypto.CreateAddress(from, tx.Nonce())
  1319  		log.Info("Submitted contract creation", "fullhash", tx.Hash().Hex(), "contract", addr.Hex())
  1320  	} else {
  1321  		log.Info("Submitted transaction", "fullhash", tx.Hash().Hex(), "recipient", tx.To())
  1322  	}
  1323  	return tx.Hash(), nil
  1324  }
  1325  
  1326  // SendTransaction creates a transaction for the given argument, sign it and submit it to the
  1327  // transaction pool.
  1328  func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error) {
  1329  
  1330  	// Look up the wallet containing the requested signer
  1331  	account := accounts.Account{Address: args.From}
  1332  
  1333  	wallet, err := s.b.AccountManager().Find(account)
  1334  	if err != nil {
  1335  		return common.Hash{}, err
  1336  	}
  1337  
  1338  	if args.Nonce == nil {
  1339  		// Hold the addresse's mutex around signing to prevent concurrent assignment of
  1340  		// the same nonce to multiple accounts.
  1341  		s.nonceLock.LockAddr(args.From)
  1342  		defer s.nonceLock.UnlockAddr(args.From)
  1343  	}
  1344  
  1345  	// Set some sanity defaults and terminate on failure
  1346  	if err := args.setDefaults(ctx, s.b); err != nil {
  1347  		return common.Hash{}, err
  1348  	}
  1349  	// Assemble the transaction and sign with the wallet
  1350  	tx := args.toTransaction()
  1351  
  1352  	var chainID *big.Int
  1353  	if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) {
  1354  		chainID = config.ChainID
  1355  	}
  1356  	signed, err := wallet.SignTx(account, tx, chainID)
  1357  	if err != nil {
  1358  		return common.Hash{}, err
  1359  	}
  1360  	return submitTransaction(ctx, s.b, signed)
  1361  }
  1362  
  1363  // SendRawTransaction will add the signed transaction to the transaction pool.
  1364  // The sender is responsible for signing the transaction and using the correct nonce.
  1365  func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, encodedTx hexutil.Bytes) (common.Hash, error) {
  1366  	tx := new(types.Transaction)
  1367  	if err := rlp.DecodeBytes(encodedTx, tx); err != nil {
  1368  		return common.Hash{}, err
  1369  	}
  1370  	return submitTransaction(ctx, s.b, tx)
  1371  }
  1372  
  1373  // Sign calculates an ECDSA signature for:
  1374  // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message).
  1375  //
  1376  // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  1377  // where the V value will be 27 or 28 for legacy reasons.
  1378  //
  1379  // The account associated with addr must be unlocked.
  1380  //
  1381  // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
  1382  func (s *PublicTransactionPoolAPI) Sign(addr common.Address, data hexutil.Bytes) (hexutil.Bytes, error) {
  1383  	// Look up the wallet containing the requested signer
  1384  	account := accounts.Account{Address: addr}
  1385  
  1386  	wallet, err := s.b.AccountManager().Find(account)
  1387  	if err != nil {
  1388  		return nil, err
  1389  	}
  1390  	// Sign the requested hash with the wallet
  1391  	signature, err := wallet.SignHash(account, signHash(data))
  1392  	if err == nil {
  1393  		signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  1394  	}
  1395  	return signature, err
  1396  }
  1397  
  1398  // SignTransactionResult represents a RLP encoded signed transaction.
  1399  type SignTransactionResult struct {
  1400  	Raw hexutil.Bytes      `json:"raw"`
  1401  	Tx  *types.Transaction `json:"tx"`
  1402  }
  1403  
  1404  // SignTransaction will sign the given transaction with the from account.
  1405  // The node needs to have the private key of the account corresponding with
  1406  // the given from address and it needs to be unlocked.
  1407  func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) {
  1408  	if args.Gas == nil {
  1409  		return nil, fmt.Errorf("gas not specified")
  1410  	}
  1411  	if args.GasPrice == nil {
  1412  		return nil, fmt.Errorf("gasPrice not specified")
  1413  	}
  1414  	if args.Nonce == nil {
  1415  		return nil, fmt.Errorf("nonce not specified")
  1416  	}
  1417  	if err := args.setDefaults(ctx, s.b); err != nil {
  1418  		return nil, err
  1419  	}
  1420  	tx, err := s.sign(args.From, args.toTransaction())
  1421  	if err != nil {
  1422  		return nil, err
  1423  	}
  1424  	data, err := rlp.EncodeToBytes(tx)
  1425  	if err != nil {
  1426  		return nil, err
  1427  	}
  1428  	return &SignTransactionResult{data, tx}, nil
  1429  }
  1430  
  1431  // PendingTransactions returns the transactions that are in the transaction pool
  1432  // and have a from address that is one of the accounts this node manages.
  1433  func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error) {
  1434  	pending, err := s.b.GetPoolTransactions()
  1435  	if err != nil {
  1436  		return nil, err
  1437  	}
  1438  	accounts := make(map[common.Address]struct{})
  1439  	for _, wallet := range s.b.AccountManager().Wallets() {
  1440  		for _, account := range wallet.Accounts() {
  1441  			accounts[account.Address] = struct{}{}
  1442  		}
  1443  	}
  1444  	transactions := make([]*RPCTransaction, 0, len(pending))
  1445  	for _, tx := range pending {
  1446  		var signer types.Signer = types.HomesteadSigner{}
  1447  		if tx.Protected() {
  1448  			signer = types.NewEIP155Signer(tx.ChainId())
  1449  		}
  1450  		from, _ := types.Sender(signer, tx)
  1451  		if _, exists := accounts[from]; exists {
  1452  			transactions = append(transactions, newRPCPendingTransaction(tx))
  1453  		}
  1454  	}
  1455  	return transactions, nil
  1456  }
  1457  
  1458  // Resend accepts an existing transaction and a new gas price and limit. It will remove
  1459  // the given transaction from the pool and reinsert it with the new gas price and limit.
  1460  func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs SendTxArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) {
  1461  	if sendArgs.Nonce == nil {
  1462  		return common.Hash{}, fmt.Errorf("missing transaction nonce in transaction spec")
  1463  	}
  1464  	if err := sendArgs.setDefaults(ctx, s.b); err != nil {
  1465  		return common.Hash{}, err
  1466  	}
  1467  	matchTx := sendArgs.toTransaction()
  1468  	pending, err := s.b.GetPoolTransactions()
  1469  	if err != nil {
  1470  		return common.Hash{}, err
  1471  	}
  1472  
  1473  	for _, p := range pending {
  1474  		var signer types.Signer = types.HomesteadSigner{}
  1475  		if p.Protected() {
  1476  			signer = types.NewEIP155Signer(p.ChainId())
  1477  		}
  1478  		wantSigHash := signer.Hash(matchTx)
  1479  
  1480  		if pFrom, err := types.Sender(signer, p); err == nil && pFrom == sendArgs.From && signer.Hash(p) == wantSigHash {
  1481  			// Match. Re-sign and send the transaction.
  1482  			if gasPrice != nil && (*big.Int)(gasPrice).Sign() != 0 {
  1483  				sendArgs.GasPrice = gasPrice
  1484  			}
  1485  			if gasLimit != nil && *gasLimit != 0 {
  1486  				sendArgs.Gas = gasLimit
  1487  			}
  1488  			signedTx, err := s.sign(sendArgs.From, sendArgs.toTransaction())
  1489  			if err != nil {
  1490  				return common.Hash{}, err
  1491  			}
  1492  			if err = s.b.SendTx(ctx, signedTx); err != nil {
  1493  				return common.Hash{}, err
  1494  			}
  1495  			return signedTx.Hash(), nil
  1496  		}
  1497  	}
  1498  
  1499  	return common.Hash{}, fmt.Errorf("Transaction %#x not found", matchTx.Hash())
  1500  }
  1501  
  1502  // PublicDebugAPI is the collection of Ethereum APIs exposed over the public
  1503  // debugging endpoint.
  1504  type PublicDebugAPI struct {
  1505  	b Backend
  1506  }
  1507  
  1508  // NewPublicDebugAPI creates a new API definition for the public debug methods
  1509  // of the Ethereum service.
  1510  func NewPublicDebugAPI(b Backend) *PublicDebugAPI {
  1511  	return &PublicDebugAPI{b: b}
  1512  }
  1513  
  1514  // GetBlockRlp retrieves the RLP encoded for of a single block.
  1515  func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error) {
  1516  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1517  	if block == nil {
  1518  		return "", fmt.Errorf("block #%d not found", number)
  1519  	}
  1520  	encoded, err := rlp.EncodeToBytes(block)
  1521  	if err != nil {
  1522  		return "", err
  1523  	}
  1524  	return fmt.Sprintf("%x", encoded), nil
  1525  }
  1526  
  1527  // PrintBlock retrieves a block and returns its pretty printed form.
  1528  func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) {
  1529  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1530  	if block == nil {
  1531  		return "", fmt.Errorf("block #%d not found", number)
  1532  	}
  1533  	return spew.Sdump(block), nil
  1534  }
  1535  
  1536  // SeedHash retrieves the seed hash of a block.
  1537  func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) {
  1538  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1539  	if block == nil {
  1540  		return "", fmt.Errorf("block #%d not found", number)
  1541  	}
  1542  	return fmt.Sprintf("0x%x", ethash.SeedHash(number)), nil
  1543  }
  1544  
  1545  // PrivateDebugAPI is the collection of Ethereum APIs exposed over the private
  1546  // debugging endpoint.
  1547  type PrivateDebugAPI struct {
  1548  	b Backend
  1549  }
  1550  
  1551  // NewPrivateDebugAPI creates a new API definition for the private debug methods
  1552  // of the Ethereum service.
  1553  func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI {
  1554  	return &PrivateDebugAPI{b: b}
  1555  }
  1556  
  1557  // ChaindbProperty returns leveldb properties of the chain database.
  1558  func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) {
  1559  	ldb, ok := api.b.ChainDb().(interface {
  1560  		LDB() *leveldb.DB
  1561  	})
  1562  	if !ok {
  1563  		return "", fmt.Errorf("chaindbProperty does not work for memory databases")
  1564  	}
  1565  	if property == "" {
  1566  		property = "leveldb.stats"
  1567  	} else if !strings.HasPrefix(property, "leveldb.") {
  1568  		property = "leveldb." + property
  1569  	}
  1570  	return ldb.LDB().GetProperty(property)
  1571  }
  1572  
  1573  func (api *PrivateDebugAPI) ChaindbCompact() error {
  1574  	ldb, ok := api.b.ChainDb().(interface {
  1575  		LDB() *leveldb.DB
  1576  	})
  1577  	if !ok {
  1578  		return fmt.Errorf("chaindbCompact does not work for memory databases")
  1579  	}
  1580  	for b := byte(0); b < 255; b++ {
  1581  		log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1))
  1582  		err := ldb.LDB().CompactRange(util.Range{Start: []byte{b}, Limit: []byte{b + 1}})
  1583  		if err != nil {
  1584  			log.Error("Database compaction failed", "err", err)
  1585  			return err
  1586  		}
  1587  	}
  1588  	return nil
  1589  }
  1590  
  1591  // SetHead rewinds the head of the blockchain to a previous block.
  1592  func (api *PrivateDebugAPI) SetHead(number hexutil.Uint64) {
  1593  	api.b.SetHead(uint64(number))
  1594  }
  1595  
  1596  // PublicNetAPI offers network related RPC methods
  1597  type PublicNetAPI struct {
  1598  	net            *p2p.Server
  1599  	networkVersion uint64
  1600  }
  1601  
  1602  // NewPublicNetAPI creates a new net API instance.
  1603  func NewPublicNetAPI(net *p2p.Server, networkVersion uint64) *PublicNetAPI {
  1604  	return &PublicNetAPI{net, networkVersion}
  1605  }
  1606  
  1607  // Listening returns an indication if the node is listening for network connections.
  1608  func (s *PublicNetAPI) Listening() bool {
  1609  	return true // always listening
  1610  }
  1611  
  1612  // PeerCount returns the number of connected peers
  1613  func (s *PublicNetAPI) PeerCount() hexutil.Uint {
  1614  	return hexutil.Uint(s.net.PeerCount())
  1615  }
  1616  
  1617  // Version returns the current ethereum protocol version.
  1618  func (s *PublicNetAPI) Version() string {
  1619  	return fmt.Sprintf("%d", s.networkVersion)
  1620  }