github.com/Debrief-BC/go-debrief@v0.0.0-20200420203408-0c26ca968123/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/Debrief-BC/go-debrief/accounts"
    30  	"github.com/Debrief-BC/go-debrief/accounts/keystore"
    31  	"github.com/Debrief-BC/go-debrief/accounts/scwallet"
    32  	"github.com/Debrief-BC/go-debrief/common"
    33  	"github.com/Debrief-BC/go-debrief/common/hexutil"
    34  	"github.com/Debrief-BC/go-debrief/common/math"
    35  	"github.com/Debrief-BC/go-debrief/consensus/clique"
    36  	"github.com/Debrief-BC/go-debrief/consensus/ethash"
    37  	"github.com/Debrief-BC/go-debrief/core"
    38  	"github.com/Debrief-BC/go-debrief/core/rawdb"
    39  	"github.com/Debrief-BC/go-debrief/core/types"
    40  	"github.com/Debrief-BC/go-debrief/core/vm"
    41  	"github.com/Debrief-BC/go-debrief/crypto"
    42  	"github.com/Debrief-BC/go-debrief/log"
    43  	"github.com/Debrief-BC/go-debrief/p2p"
    44  	"github.com/Debrief-BC/go-debrief/params"
    45  	"github.com/Debrief-BC/go-debrief/rlp"
    46  	"github.com/Debrief-BC/go-debrief/rpc"
    47  	"github.com/tyler-smith/go-bip39"
    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  	return s.am.Accounts()
   191  }
   192  
   193  // PrivateAccountAPI provides an API to access accounts managed by this node.
   194  // It offers methods to create, (un)lock en list accounts. Some methods accept
   195  // passwords and are therefore considered private by default.
   196  type PrivateAccountAPI struct {
   197  	am        *accounts.Manager
   198  	nonceLock *AddrLocker
   199  	b         Backend
   200  }
   201  
   202  // NewPrivateAccountAPI create a new PrivateAccountAPI.
   203  func NewPrivateAccountAPI(b Backend, nonceLock *AddrLocker) *PrivateAccountAPI {
   204  	return &PrivateAccountAPI{
   205  		am:        b.AccountManager(),
   206  		nonceLock: nonceLock,
   207  		b:         b,
   208  	}
   209  }
   210  
   211  // listAccounts will return a list of addresses for accounts this node manages.
   212  func (s *PrivateAccountAPI) ListAccounts() []common.Address {
   213  	return s.am.Accounts()
   214  }
   215  
   216  // rawWallet is a JSON representation of an accounts.Wallet interface, with its
   217  // data contents extracted into plain fields.
   218  type rawWallet struct {
   219  	URL      string             `json:"url"`
   220  	Status   string             `json:"status"`
   221  	Failure  string             `json:"failure,omitempty"`
   222  	Accounts []accounts.Account `json:"accounts,omitempty"`
   223  }
   224  
   225  // ListWallets will return a list of wallets this node manages.
   226  func (s *PrivateAccountAPI) ListWallets() []rawWallet {
   227  	wallets := make([]rawWallet, 0) // return [] instead of nil if empty
   228  	for _, wallet := range s.am.Wallets() {
   229  		status, failure := wallet.Status()
   230  
   231  		raw := rawWallet{
   232  			URL:      wallet.URL().String(),
   233  			Status:   status,
   234  			Accounts: wallet.Accounts(),
   235  		}
   236  		if failure != nil {
   237  			raw.Failure = failure.Error()
   238  		}
   239  		wallets = append(wallets, raw)
   240  	}
   241  	return wallets
   242  }
   243  
   244  // OpenWallet initiates a hardware wallet opening procedure, establishing a USB
   245  // connection and attempting to authenticate via the provided passphrase. Note,
   246  // the method may return an extra challenge requiring a second open (e.g. the
   247  // Trezor PIN matrix challenge).
   248  func (s *PrivateAccountAPI) OpenWallet(url string, passphrase *string) error {
   249  	wallet, err := s.am.Wallet(url)
   250  	if err != nil {
   251  		return err
   252  	}
   253  	pass := ""
   254  	if passphrase != nil {
   255  		pass = *passphrase
   256  	}
   257  	return wallet.Open(pass)
   258  }
   259  
   260  // DeriveAccount requests a HD wallet to derive a new account, optionally pinning
   261  // it for later reuse.
   262  func (s *PrivateAccountAPI) DeriveAccount(url string, path string, pin *bool) (accounts.Account, error) {
   263  	wallet, err := s.am.Wallet(url)
   264  	if err != nil {
   265  		return accounts.Account{}, err
   266  	}
   267  	derivPath, err := accounts.ParseDerivationPath(path)
   268  	if err != nil {
   269  		return accounts.Account{}, err
   270  	}
   271  	if pin == nil {
   272  		pin = new(bool)
   273  	}
   274  	return wallet.Derive(derivPath, *pin)
   275  }
   276  
   277  // NewAccount will create a new account and returns the address for the new account.
   278  func (s *PrivateAccountAPI) NewAccount(password string) (common.Address, error) {
   279  	acc, err := fetchKeystore(s.am).NewAccount(password)
   280  	if err == nil {
   281  		log.Info("Your new key was generated", "address", acc.Address)
   282  		log.Warn("Please backup your key file!", "path", acc.URL.Path)
   283  		log.Warn("Please remember your password!")
   284  		return acc.Address, nil
   285  	}
   286  	return common.Address{}, err
   287  }
   288  
   289  // fetchKeystore retrives the encrypted keystore from the account manager.
   290  func fetchKeystore(am *accounts.Manager) *keystore.KeyStore {
   291  	return am.Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore)
   292  }
   293  
   294  // ImportRawKey stores the given hex encoded ECDSA key into the key directory,
   295  // encrypting it with the passphrase.
   296  func (s *PrivateAccountAPI) ImportRawKey(privkey string, password string) (common.Address, error) {
   297  	key, err := crypto.HexToECDSA(privkey)
   298  	if err != nil {
   299  		return common.Address{}, err
   300  	}
   301  	acc, err := fetchKeystore(s.am).ImportECDSA(key, password)
   302  	return acc.Address, err
   303  }
   304  
   305  // UnlockAccount will unlock the account associated with the given address with
   306  // the given password for duration seconds. If duration is nil it will use a
   307  // default of 300 seconds. It returns an indication if the account was unlocked.
   308  func (s *PrivateAccountAPI) UnlockAccount(ctx context.Context, addr common.Address, password string, duration *uint64) (bool, error) {
   309  	// When the API is exposed by external RPC(http, ws etc), unless the user
   310  	// explicitly specifies to allow the insecure account unlocking, otherwise
   311  	// it is disabled.
   312  	if s.b.ExtRPCEnabled() && !s.b.AccountManager().Config().InsecureUnlockAllowed {
   313  		return false, errors.New("account unlock with HTTP access is forbidden")
   314  	}
   315  
   316  	const max = uint64(time.Duration(math.MaxInt64) / time.Second)
   317  	var d time.Duration
   318  	if duration == nil {
   319  		d = 300 * time.Second
   320  	} else if *duration > max {
   321  		return false, errors.New("unlock duration too large")
   322  	} else {
   323  		d = time.Duration(*duration) * time.Second
   324  	}
   325  	err := fetchKeystore(s.am).TimedUnlock(accounts.Account{Address: addr}, password, d)
   326  	if err != nil {
   327  		log.Warn("Failed account unlock attempt", "address", addr, "err", err)
   328  	}
   329  	return err == nil, err
   330  }
   331  
   332  // LockAccount will lock the account associated with the given address when it's unlocked.
   333  func (s *PrivateAccountAPI) LockAccount(addr common.Address) bool {
   334  	return fetchKeystore(s.am).Lock(addr) == nil
   335  }
   336  
   337  // signTransaction sets defaults and signs the given transaction
   338  // NOTE: the caller needs to ensure that the nonceLock is held, if applicable,
   339  // and release it after the transaction has been submitted to the tx pool
   340  func (s *PrivateAccountAPI) signTransaction(ctx context.Context, args *SendTxArgs, passwd string) (*types.Transaction, error) {
   341  	// Look up the wallet containing the requested signer
   342  	account := accounts.Account{Address: args.From}
   343  	wallet, err := s.am.Find(account)
   344  	if err != nil {
   345  		return nil, err
   346  	}
   347  	// Set some sanity defaults and terminate on failure
   348  	if err := args.setDefaults(ctx, s.b); err != nil {
   349  		return nil, err
   350  	}
   351  	// Assemble the transaction and sign with the wallet
   352  	tx := args.toTransaction()
   353  
   354  	return wallet.SignTxWithPassphrase(account, passwd, tx, s.b.ChainConfig().ChainID)
   355  }
   356  
   357  // SendTransaction will create a transaction from the given arguments and
   358  // tries to sign it with the key associated with args.To. If the given passwd isn't
   359  // able to decrypt the key it fails.
   360  func (s *PrivateAccountAPI) SendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) {
   361  	if args.Nonce == nil {
   362  		// Hold the addresse's mutex around signing to prevent concurrent assignment of
   363  		// the same nonce to multiple accounts.
   364  		s.nonceLock.LockAddr(args.From)
   365  		defer s.nonceLock.UnlockAddr(args.From)
   366  	}
   367  	signed, err := s.signTransaction(ctx, &args, passwd)
   368  	if err != nil {
   369  		log.Warn("Failed transaction send attempt", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err)
   370  		return common.Hash{}, err
   371  	}
   372  	return SubmitTransaction(ctx, s.b, signed)
   373  }
   374  
   375  // SignTransaction will create a transaction from the given arguments and
   376  // tries to sign it with the key associated with args.To. If the given passwd isn't
   377  // able to decrypt the key it fails. The transaction is returned in RLP-form, not broadcast
   378  // to other nodes
   379  func (s *PrivateAccountAPI) SignTransaction(ctx context.Context, args SendTxArgs, passwd string) (*SignTransactionResult, error) {
   380  	// No need to obtain the noncelock mutex, since we won't be sending this
   381  	// tx into the transaction pool, but right back to the user
   382  	if args.Gas == nil {
   383  		return nil, fmt.Errorf("gas not specified")
   384  	}
   385  	if args.GasPrice == nil {
   386  		return nil, fmt.Errorf("gasPrice not specified")
   387  	}
   388  	if args.Nonce == nil {
   389  		return nil, fmt.Errorf("nonce not specified")
   390  	}
   391  	signed, err := s.signTransaction(ctx, &args, passwd)
   392  	if err != nil {
   393  		log.Warn("Failed transaction sign attempt", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err)
   394  		return nil, err
   395  	}
   396  	data, err := rlp.EncodeToBytes(signed)
   397  	if err != nil {
   398  		return nil, err
   399  	}
   400  	return &SignTransactionResult{data, signed}, nil
   401  }
   402  
   403  // Sign calculates an Ethereum ECDSA signature for:
   404  // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message))
   405  //
   406  // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
   407  // where the V value will be 27 or 28 for legacy reasons.
   408  //
   409  // The key used to calculate the signature is decrypted with the given password.
   410  //
   411  // https://github.com/Debrief-BC/go-debrief/wiki/Management-APIs#personal_sign
   412  func (s *PrivateAccountAPI) Sign(ctx context.Context, data hexutil.Bytes, addr common.Address, passwd string) (hexutil.Bytes, error) {
   413  	// Look up the wallet containing the requested signer
   414  	account := accounts.Account{Address: addr}
   415  
   416  	wallet, err := s.b.AccountManager().Find(account)
   417  	if err != nil {
   418  		return nil, err
   419  	}
   420  	// Assemble sign the data with the wallet
   421  	signature, err := wallet.SignTextWithPassphrase(account, passwd, data)
   422  	if err != nil {
   423  		log.Warn("Failed data sign attempt", "address", addr, "err", err)
   424  		return nil, err
   425  	}
   426  	signature[crypto.RecoveryIDOffset] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
   427  	return signature, nil
   428  }
   429  
   430  // EcRecover returns the address for the account that was used to create the signature.
   431  // Note, this function is compatible with eth_sign and personal_sign. As such it recovers
   432  // the address of:
   433  // hash = keccak256("\x19Ethereum Signed Message:\n"${message length}${message})
   434  // addr = ecrecover(hash, signature)
   435  //
   436  // Note, the signature must conform to the secp256k1 curve R, S and V values, where
   437  // the V value must be 27 or 28 for legacy reasons.
   438  //
   439  // https://github.com/Debrief-BC/go-debrief/wiki/Management-APIs#personal_ecRecover
   440  func (s *PrivateAccountAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) {
   441  	if len(sig) != crypto.SignatureLength {
   442  		return common.Address{}, fmt.Errorf("signature must be %d bytes long", crypto.SignatureLength)
   443  	}
   444  	if sig[crypto.RecoveryIDOffset] != 27 && sig[crypto.RecoveryIDOffset] != 28 {
   445  		return common.Address{}, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)")
   446  	}
   447  	sig[crypto.RecoveryIDOffset] -= 27 // Transform yellow paper V from 27/28 to 0/1
   448  
   449  	rpk, err := crypto.SigToPub(accounts.TextHash(data), sig)
   450  	if err != nil {
   451  		return common.Address{}, err
   452  	}
   453  	return crypto.PubkeyToAddress(*rpk), nil
   454  }
   455  
   456  // SignAndSendTransaction was renamed to SendTransaction. This method is deprecated
   457  // and will be removed in the future. It primary goal is to give clients time to update.
   458  func (s *PrivateAccountAPI) SignAndSendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) {
   459  	return s.SendTransaction(ctx, args, passwd)
   460  }
   461  
   462  // InitializeWallet initializes a new wallet at the provided URL, by generating and returning a new private key.
   463  func (s *PrivateAccountAPI) InitializeWallet(ctx context.Context, url string) (string, error) {
   464  	wallet, err := s.am.Wallet(url)
   465  	if err != nil {
   466  		return "", err
   467  	}
   468  
   469  	entropy, err := bip39.NewEntropy(256)
   470  	if err != nil {
   471  		return "", err
   472  	}
   473  
   474  	mnemonic, err := bip39.NewMnemonic(entropy)
   475  	if err != nil {
   476  		return "", err
   477  	}
   478  
   479  	seed := bip39.NewSeed(mnemonic, "")
   480  
   481  	switch wallet := wallet.(type) {
   482  	case *scwallet.Wallet:
   483  		return mnemonic, wallet.Initialize(seed)
   484  	default:
   485  		return "", fmt.Errorf("specified wallet does not support initialization")
   486  	}
   487  }
   488  
   489  // Unpair deletes a pairing between wallet and geth.
   490  func (s *PrivateAccountAPI) Unpair(ctx context.Context, url string, pin string) error {
   491  	wallet, err := s.am.Wallet(url)
   492  	if err != nil {
   493  		return err
   494  	}
   495  
   496  	switch wallet := wallet.(type) {
   497  	case *scwallet.Wallet:
   498  		return wallet.Unpair([]byte(pin))
   499  	default:
   500  		return fmt.Errorf("specified wallet does not support pairing")
   501  	}
   502  }
   503  
   504  // PublicBlockChainAPI provides an API to access the Ethereum blockchain.
   505  // It offers only methods that operate on public data that is freely available to anyone.
   506  type PublicBlockChainAPI struct {
   507  	b Backend
   508  }
   509  
   510  // NewPublicBlockChainAPI creates a new Ethereum blockchain API.
   511  func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI {
   512  	return &PublicBlockChainAPI{b}
   513  }
   514  
   515  // ChainId returns the chainID value for transaction replay protection.
   516  func (s *PublicBlockChainAPI) ChainId() *hexutil.Big {
   517  	return (*hexutil.Big)(s.b.ChainConfig().ChainID)
   518  }
   519  
   520  // BlockNumber returns the block number of the chain head.
   521  func (s *PublicBlockChainAPI) BlockNumber() hexutil.Uint64 {
   522  	header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available
   523  	return hexutil.Uint64(header.Number.Uint64())
   524  }
   525  
   526  // GetBalance returns the amount of wei for the given address in the state of the
   527  // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
   528  // block numbers are also allowed.
   529  func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Big, error) {
   530  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   531  	if state == nil || err != nil {
   532  		return nil, err
   533  	}
   534  	return (*hexutil.Big)(state.GetBalance(address)), state.Error()
   535  }
   536  
   537  // Result structs for GetProof
   538  type AccountResult struct {
   539  	Address      common.Address  `json:"address"`
   540  	AccountProof []string        `json:"accountProof"`
   541  	Balance      *hexutil.Big    `json:"balance"`
   542  	CodeHash     common.Hash     `json:"codeHash"`
   543  	Nonce        hexutil.Uint64  `json:"nonce"`
   544  	StorageHash  common.Hash     `json:"storageHash"`
   545  	StorageProof []StorageResult `json:"storageProof"`
   546  }
   547  type StorageResult struct {
   548  	Key   string       `json:"key"`
   549  	Value *hexutil.Big `json:"value"`
   550  	Proof []string     `json:"proof"`
   551  }
   552  
   553  // GetProof returns the Merkle-proof for a given account and optionally some storage keys.
   554  func (s *PublicBlockChainAPI) GetProof(ctx context.Context, address common.Address, storageKeys []string, blockNrOrHash rpc.BlockNumberOrHash) (*AccountResult, error) {
   555  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   556  	if state == nil || err != nil {
   557  		return nil, err
   558  	}
   559  
   560  	storageTrie := state.StorageTrie(address)
   561  	storageHash := types.EmptyRootHash
   562  	codeHash := state.GetCodeHash(address)
   563  	storageProof := make([]StorageResult, len(storageKeys))
   564  
   565  	// if we have a storageTrie, (which means the account exists), we can update the storagehash
   566  	if storageTrie != nil {
   567  		storageHash = storageTrie.Hash()
   568  	} else {
   569  		// no storageTrie means the account does not exist, so the codeHash is the hash of an empty bytearray.
   570  		codeHash = crypto.Keccak256Hash(nil)
   571  	}
   572  
   573  	// create the proof for the storageKeys
   574  	for i, key := range storageKeys {
   575  		if storageTrie != nil {
   576  			proof, storageError := state.GetStorageProof(address, common.HexToHash(key))
   577  			if storageError != nil {
   578  				return nil, storageError
   579  			}
   580  			storageProof[i] = StorageResult{key, (*hexutil.Big)(state.GetState(address, common.HexToHash(key)).Big()), common.ToHexArray(proof)}
   581  		} else {
   582  			storageProof[i] = StorageResult{key, &hexutil.Big{}, []string{}}
   583  		}
   584  	}
   585  
   586  	// create the accountProof
   587  	accountProof, proofErr := state.GetProof(address)
   588  	if proofErr != nil {
   589  		return nil, proofErr
   590  	}
   591  
   592  	return &AccountResult{
   593  		Address:      address,
   594  		AccountProof: common.ToHexArray(accountProof),
   595  		Balance:      (*hexutil.Big)(state.GetBalance(address)),
   596  		CodeHash:     codeHash,
   597  		Nonce:        hexutil.Uint64(state.GetNonce(address)),
   598  		StorageHash:  storageHash,
   599  		StorageProof: storageProof,
   600  	}, state.Error()
   601  }
   602  
   603  // GetHeaderByNumber returns the requested canonical block header.
   604  // * When blockNr is -1 the chain head is returned.
   605  // * When blockNr is -2 the pending chain head is returned.
   606  func (s *PublicBlockChainAPI) GetHeaderByNumber(ctx context.Context, number rpc.BlockNumber) (map[string]interface{}, error) {
   607  	header, err := s.b.HeaderByNumber(ctx, number)
   608  	if header != nil && err == nil {
   609  		response := s.rpcMarshalHeader(header)
   610  		if number == rpc.PendingBlockNumber {
   611  			// Pending header need to nil out a few fields
   612  			for _, field := range []string{"hash", "nonce", "miner"} {
   613  				response[field] = nil
   614  			}
   615  		}
   616  		return response, err
   617  	}
   618  	return nil, err
   619  }
   620  
   621  // GetHeaderByHash returns the requested header by hash.
   622  func (s *PublicBlockChainAPI) GetHeaderByHash(ctx context.Context, hash common.Hash) map[string]interface{} {
   623  	header, _ := s.b.HeaderByHash(ctx, hash)
   624  	if header != nil {
   625  		return s.rpcMarshalHeader(header)
   626  	}
   627  	return nil
   628  }
   629  
   630  // GetBlockByNumber returns the requested canonical block.
   631  // * When blockNr is -1 the chain head is returned.
   632  // * When blockNr is -2 the pending chain head is returned.
   633  // * When fullTx is true all transactions in the block are returned, otherwise
   634  //   only the transaction hash is returned.
   635  func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, number rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
   636  	block, err := s.b.BlockByNumber(ctx, number)
   637  	if block != nil && err == nil {
   638  		response, err := s.rpcMarshalBlock(block, true, fullTx)
   639  		if err == nil && number == rpc.PendingBlockNumber {
   640  			// Pending blocks need to nil out a few fields
   641  			for _, field := range []string{"hash", "nonce", "miner"} {
   642  				response[field] = nil
   643  			}
   644  		}
   645  		return response, err
   646  	}
   647  	return nil, err
   648  }
   649  
   650  // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
   651  // detail, otherwise only the transaction hash is returned.
   652  func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, hash common.Hash, fullTx bool) (map[string]interface{}, error) {
   653  	block, err := s.b.BlockByHash(ctx, hash)
   654  	if block != nil {
   655  		return s.rpcMarshalBlock(block, true, fullTx)
   656  	}
   657  	return nil, err
   658  }
   659  
   660  // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true
   661  // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
   662  func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) {
   663  	block, err := s.b.BlockByNumber(ctx, blockNr)
   664  	if block != nil {
   665  		uncles := block.Uncles()
   666  		if index >= hexutil.Uint(len(uncles)) {
   667  			log.Debug("Requested uncle not found", "number", blockNr, "hash", block.Hash(), "index", index)
   668  			return nil, nil
   669  		}
   670  		block = types.NewBlockWithHeader(uncles[index])
   671  		return s.rpcMarshalBlock(block, false, false)
   672  	}
   673  	return nil, err
   674  }
   675  
   676  // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true
   677  // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
   678  func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) {
   679  	block, err := s.b.BlockByHash(ctx, blockHash)
   680  	if block != nil {
   681  		uncles := block.Uncles()
   682  		if index >= hexutil.Uint(len(uncles)) {
   683  			log.Debug("Requested uncle not found", "number", block.Number(), "hash", blockHash, "index", index)
   684  			return nil, nil
   685  		}
   686  		block = types.NewBlockWithHeader(uncles[index])
   687  		return s.rpcMarshalBlock(block, false, false)
   688  	}
   689  	return nil, err
   690  }
   691  
   692  // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
   693  func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
   694  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
   695  		n := hexutil.Uint(len(block.Uncles()))
   696  		return &n
   697  	}
   698  	return nil
   699  }
   700  
   701  // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash
   702  func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
   703  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
   704  		n := hexutil.Uint(len(block.Uncles()))
   705  		return &n
   706  	}
   707  	return nil
   708  }
   709  
   710  // GetCode returns the code stored at the given address in the state for the given block number.
   711  func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
   712  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   713  	if state == nil || err != nil {
   714  		return nil, err
   715  	}
   716  	code := state.GetCode(address)
   717  	return code, state.Error()
   718  }
   719  
   720  // GetStorageAt returns the storage from the state at the given address, key and
   721  // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
   722  // numbers are also allowed.
   723  func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
   724  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   725  	if state == nil || err != nil {
   726  		return nil, err
   727  	}
   728  	res := state.GetState(address, common.HexToHash(key))
   729  	return res[:], state.Error()
   730  }
   731  
   732  // CallArgs represents the arguments for a call.
   733  type CallArgs struct {
   734  	From     *common.Address `json:"from"`
   735  	To       *common.Address `json:"to"`
   736  	Gas      *hexutil.Uint64 `json:"gas"`
   737  	GasPrice *hexutil.Big    `json:"gasPrice"`
   738  	Value    *hexutil.Big    `json:"value"`
   739  	Data     *hexutil.Bytes  `json:"data"`
   740  }
   741  
   742  // ToMessage converts CallArgs to the Message type used by the core evm
   743  func (args *CallArgs) ToMessage(globalGasCap *big.Int) types.Message {
   744  	// Set sender address or use zero address if none specified.
   745  	var addr common.Address
   746  	if args.From != nil {
   747  		addr = *args.From
   748  	}
   749  
   750  	// Set default gas & gas price if none were set
   751  	gas := uint64(math.MaxUint64 / 2)
   752  	if args.Gas != nil {
   753  		gas = uint64(*args.Gas)
   754  	}
   755  	if globalGasCap != nil && globalGasCap.Uint64() < gas {
   756  		log.Warn("Caller gas above allowance, capping", "requested", gas, "cap", globalGasCap)
   757  		gas = globalGasCap.Uint64()
   758  	}
   759  	gasPrice := new(big.Int)
   760  	if args.GasPrice != nil {
   761  		gasPrice = args.GasPrice.ToInt()
   762  	}
   763  
   764  	value := new(big.Int)
   765  	if args.Value != nil {
   766  		value = args.Value.ToInt()
   767  	}
   768  
   769  	var data []byte
   770  	if args.Data != nil {
   771  		data = []byte(*args.Data)
   772  	}
   773  
   774  	msg := types.NewMessage(addr, args.To, 0, value, gas, gasPrice, data, false)
   775  	return msg
   776  }
   777  
   778  // account indicates the overriding fields of account during the execution of
   779  // a message call.
   780  // Note, state and stateDiff can't be specified at the same time. If state is
   781  // set, message execution will only use the data in the given state. Otherwise
   782  // if statDiff is set, all diff will be applied first and then execute the call
   783  // message.
   784  type account struct {
   785  	Nonce     *hexutil.Uint64              `json:"nonce"`
   786  	Code      *hexutil.Bytes               `json:"code"`
   787  	Balance   **hexutil.Big                `json:"balance"`
   788  	State     *map[common.Hash]common.Hash `json:"state"`
   789  	StateDiff *map[common.Hash]common.Hash `json:"stateDiff"`
   790  }
   791  
   792  func DoCall(ctx context.Context, b Backend, args CallArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides map[common.Address]account, vmCfg vm.Config, timeout time.Duration, globalGasCap *big.Int) ([]byte, uint64, bool, error) {
   793  	defer func(start time.Time) { log.Debug("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now())
   794  
   795  	state, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   796  	if state == nil || err != nil {
   797  		return nil, 0, false, err
   798  	}
   799  
   800  	// Override the fields of specified contracts before execution.
   801  	for addr, account := range overrides {
   802  		// Override account nonce.
   803  		if account.Nonce != nil {
   804  			state.SetNonce(addr, uint64(*account.Nonce))
   805  		}
   806  		// Override account(contract) code.
   807  		if account.Code != nil {
   808  			state.SetCode(addr, *account.Code)
   809  		}
   810  		// Override account balance.
   811  		if account.Balance != nil {
   812  			state.SetBalance(addr, (*big.Int)(*account.Balance))
   813  		}
   814  		if account.State != nil && account.StateDiff != nil {
   815  			return nil, 0, false, fmt.Errorf("account %s has both 'state' and 'stateDiff'", addr.Hex())
   816  		}
   817  		// Replace entire state if caller requires.
   818  		if account.State != nil {
   819  			state.SetStorage(addr, *account.State)
   820  		}
   821  		// Apply state diff into specified accounts.
   822  		if account.StateDiff != nil {
   823  			for key, value := range *account.StateDiff {
   824  				state.SetState(addr, key, value)
   825  			}
   826  		}
   827  	}
   828  
   829  	// Setup context so it may be cancelled the call has completed
   830  	// or, in case of unmetered gas, setup a context with a timeout.
   831  	var cancel context.CancelFunc
   832  	if timeout > 0 {
   833  		ctx, cancel = context.WithTimeout(ctx, timeout)
   834  	} else {
   835  		ctx, cancel = context.WithCancel(ctx)
   836  	}
   837  	// Make sure the context is cancelled when the call has completed
   838  	// this makes sure resources are cleaned up.
   839  	defer cancel()
   840  
   841  	// Get a new instance of the EVM.
   842  	msg := args.ToMessage(globalGasCap)
   843  	evm, vmError, err := b.GetEVM(ctx, msg, state, header)
   844  	if err != nil {
   845  		return nil, 0, false, err
   846  	}
   847  	// Wait for the context to be done and cancel the evm. Even if the
   848  	// EVM has finished, cancelling may be done (repeatedly)
   849  	go func() {
   850  		<-ctx.Done()
   851  		evm.Cancel()
   852  	}()
   853  
   854  	// Setup the gas pool (also for unmetered requests)
   855  	// and apply the message.
   856  	gp := new(core.GasPool).AddGas(math.MaxUint64)
   857  	res, gas, failed, err := core.ApplyMessage(evm, msg, gp)
   858  	if err := vmError(); err != nil {
   859  		return nil, 0, false, err
   860  	}
   861  	// If the timer caused an abort, return an appropriate error message
   862  	if evm.Cancelled() {
   863  		return nil, 0, false, fmt.Errorf("execution aborted (timeout = %v)", timeout)
   864  	}
   865  	return res, gas, failed, err
   866  }
   867  
   868  // Call executes the given transaction on the state for the given block number.
   869  //
   870  // Additionally, the caller can specify a batch of contract for fields overriding.
   871  //
   872  // Note, this function doesn't make and changes in the state/blockchain and is
   873  // useful to execute and retrieve values.
   874  func (s *PublicBlockChainAPI) Call(ctx context.Context, args CallArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *map[common.Address]account) (hexutil.Bytes, error) {
   875  	var accounts map[common.Address]account
   876  	if overrides != nil {
   877  		accounts = *overrides
   878  	}
   879  	result, _, _, err := DoCall(ctx, s.b, args, blockNrOrHash, accounts, vm.Config{}, 5*time.Second, s.b.RPCGasCap())
   880  	return (hexutil.Bytes)(result), err
   881  }
   882  
   883  func DoEstimateGas(ctx context.Context, b Backend, args CallArgs, blockNrOrHash rpc.BlockNumberOrHash, gasCap *big.Int) (hexutil.Uint64, error) {
   884  	// Binary search the gas requirement, as it may be higher than the amount used
   885  	var (
   886  		lo  uint64 = params.TxGas - 1
   887  		hi  uint64
   888  		cap uint64
   889  	)
   890  	if args.Gas != nil && uint64(*args.Gas) >= params.TxGas {
   891  		hi = uint64(*args.Gas)
   892  	} else {
   893  		// Retrieve the block to act as the gas ceiling
   894  		block, err := b.BlockByNumberOrHash(ctx, blockNrOrHash)
   895  		if err != nil {
   896  			return 0, err
   897  		}
   898  		hi = block.GasLimit()
   899  	}
   900  	if gasCap != nil && hi > gasCap.Uint64() {
   901  		log.Warn("Caller gas above allowance, capping", "requested", hi, "cap", gasCap)
   902  		hi = gasCap.Uint64()
   903  	}
   904  	cap = hi
   905  
   906  	// Use zero address if sender unspecified.
   907  	if args.From == nil {
   908  		args.From = new(common.Address)
   909  	}
   910  	// Create a helper to check if a gas allowance results in an executable transaction
   911  	executable := func(gas uint64) bool {
   912  		args.Gas = (*hexutil.Uint64)(&gas)
   913  
   914  		_, _, failed, err := DoCall(ctx, b, args, blockNrOrHash, nil, vm.Config{}, 0, gasCap)
   915  		if err != nil || failed {
   916  			return false
   917  		}
   918  		return true
   919  	}
   920  	// Execute the binary search and hone in on an executable gas limit
   921  	for lo+1 < hi {
   922  		mid := (hi + lo) / 2
   923  		if !executable(mid) {
   924  			lo = mid
   925  		} else {
   926  			hi = mid
   927  		}
   928  	}
   929  	// Reject the transaction as invalid if it still fails at the highest allowance
   930  	if hi == cap {
   931  		if !executable(hi) {
   932  			return 0, fmt.Errorf("gas required exceeds allowance (%d) or always failing transaction", cap)
   933  		}
   934  	}
   935  	return hexutil.Uint64(hi), nil
   936  }
   937  
   938  // EstimateGas returns an estimate of the amount of gas needed to execute the
   939  // given transaction against the current pending block.
   940  func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args CallArgs) (hexutil.Uint64, error) {
   941  	blockNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
   942  	return DoEstimateGas(ctx, s.b, args, blockNrOrHash, s.b.RPCGasCap())
   943  }
   944  
   945  // ExecutionResult groups all structured logs emitted by the EVM
   946  // while replaying a transaction in debug mode as well as transaction
   947  // execution status, the amount of gas used and the return value
   948  type ExecutionResult struct {
   949  	Gas         uint64         `json:"gas"`
   950  	Failed      bool           `json:"failed"`
   951  	ReturnValue string         `json:"returnValue"`
   952  	StructLogs  []StructLogRes `json:"structLogs"`
   953  }
   954  
   955  // StructLogRes stores a structured log emitted by the EVM while replaying a
   956  // transaction in debug mode
   957  type StructLogRes struct {
   958  	Pc      uint64             `json:"pc"`
   959  	Op      string             `json:"op"`
   960  	Gas     uint64             `json:"gas"`
   961  	GasCost uint64             `json:"gasCost"`
   962  	Depth   int                `json:"depth"`
   963  	Error   error              `json:"error,omitempty"`
   964  	Stack   *[]string          `json:"stack,omitempty"`
   965  	Memory  *[]string          `json:"memory,omitempty"`
   966  	Storage *map[string]string `json:"storage,omitempty"`
   967  }
   968  
   969  // FormatLogs formats EVM returned structured logs for json output
   970  func FormatLogs(logs []vm.StructLog) []StructLogRes {
   971  	formatted := make([]StructLogRes, len(logs))
   972  	for index, trace := range logs {
   973  		formatted[index] = StructLogRes{
   974  			Pc:      trace.Pc,
   975  			Op:      trace.Op.String(),
   976  			Gas:     trace.Gas,
   977  			GasCost: trace.GasCost,
   978  			Depth:   trace.Depth,
   979  			Error:   trace.Err,
   980  		}
   981  		if trace.Stack != nil {
   982  			stack := make([]string, len(trace.Stack))
   983  			for i, stackValue := range trace.Stack {
   984  				stack[i] = fmt.Sprintf("%x", math.PaddedBigBytes(stackValue, 32))
   985  			}
   986  			formatted[index].Stack = &stack
   987  		}
   988  		if trace.Memory != nil {
   989  			memory := make([]string, 0, (len(trace.Memory)+31)/32)
   990  			for i := 0; i+32 <= len(trace.Memory); i += 32 {
   991  				memory = append(memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
   992  			}
   993  			formatted[index].Memory = &memory
   994  		}
   995  		if trace.Storage != nil {
   996  			storage := make(map[string]string)
   997  			for i, storageValue := range trace.Storage {
   998  				storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
   999  			}
  1000  			formatted[index].Storage = &storage
  1001  		}
  1002  	}
  1003  	return formatted
  1004  }
  1005  
  1006  // RPCMarshalHeader converts the given header to the RPC output .
  1007  func RPCMarshalHeader(head *types.Header) map[string]interface{} {
  1008  	return map[string]interface{}{
  1009  		"number":           (*hexutil.Big)(head.Number),
  1010  		"hash":             head.Hash(),
  1011  		"parentHash":       head.ParentHash,
  1012  		"nonce":            head.Nonce,
  1013  		"mixHash":          head.MixDigest,
  1014  		"sha3Uncles":       head.UncleHash,
  1015  		"logsBloom":        head.Bloom,
  1016  		"stateRoot":        head.Root,
  1017  		"miner":            head.Coinbase,
  1018  		"difficulty":       (*hexutil.Big)(head.Difficulty),
  1019  		"extraData":        hexutil.Bytes(head.Extra),
  1020  		"size":             hexutil.Uint64(head.Size()),
  1021  		"gasLimit":         hexutil.Uint64(head.GasLimit),
  1022  		"gasUsed":          hexutil.Uint64(head.GasUsed),
  1023  		"timestamp":        hexutil.Uint64(head.Time),
  1024  		"transactionsRoot": head.TxHash,
  1025  		"receiptsRoot":     head.ReceiptHash,
  1026  	}
  1027  }
  1028  
  1029  // RPCMarshalBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
  1030  // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
  1031  // transaction hashes.
  1032  func RPCMarshalBlock(block *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  1033  	fields := RPCMarshalHeader(block.Header())
  1034  	fields["size"] = hexutil.Uint64(block.Size())
  1035  
  1036  	if inclTx {
  1037  		formatTx := func(tx *types.Transaction) (interface{}, error) {
  1038  			return tx.Hash(), nil
  1039  		}
  1040  		if fullTx {
  1041  			formatTx = func(tx *types.Transaction) (interface{}, error) {
  1042  				return newRPCTransactionFromBlockHash(block, tx.Hash()), nil
  1043  			}
  1044  		}
  1045  		txs := block.Transactions()
  1046  		transactions := make([]interface{}, len(txs))
  1047  		var err error
  1048  		for i, tx := range txs {
  1049  			if transactions[i], err = formatTx(tx); err != nil {
  1050  				return nil, err
  1051  			}
  1052  		}
  1053  		fields["transactions"] = transactions
  1054  	}
  1055  	uncles := block.Uncles()
  1056  	uncleHashes := make([]common.Hash, len(uncles))
  1057  	for i, uncle := range uncles {
  1058  		uncleHashes[i] = uncle.Hash()
  1059  	}
  1060  	fields["uncles"] = uncleHashes
  1061  
  1062  	return fields, nil
  1063  }
  1064  
  1065  // rpcMarshalHeader uses the generalized output filler, then adds the total difficulty field, which requires
  1066  // a `PublicBlockchainAPI`.
  1067  func (s *PublicBlockChainAPI) rpcMarshalHeader(header *types.Header) map[string]interface{} {
  1068  	fields := RPCMarshalHeader(header)
  1069  	fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(header.Hash()))
  1070  	return fields
  1071  }
  1072  
  1073  // rpcMarshalBlock uses the generalized output filler, then adds the total difficulty field, which requires
  1074  // a `PublicBlockchainAPI`.
  1075  func (s *PublicBlockChainAPI) rpcMarshalBlock(b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  1076  	fields, err := RPCMarshalBlock(b, inclTx, fullTx)
  1077  	if err != nil {
  1078  		return nil, err
  1079  	}
  1080  	if inclTx {
  1081  		fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(b.Hash()))
  1082  	}
  1083  	return fields, err
  1084  }
  1085  
  1086  // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
  1087  type RPCTransaction struct {
  1088  	BlockHash        *common.Hash    `json:"blockHash"`
  1089  	BlockNumber      *hexutil.Big    `json:"blockNumber"`
  1090  	From             common.Address  `json:"from"`
  1091  	Gas              hexutil.Uint64  `json:"gas"`
  1092  	GasPrice         *hexutil.Big    `json:"gasPrice"`
  1093  	Hash             common.Hash     `json:"hash"`
  1094  	Input            hexutil.Bytes   `json:"input"`
  1095  	Nonce            hexutil.Uint64  `json:"nonce"`
  1096  	To               *common.Address `json:"to"`
  1097  	TransactionIndex *hexutil.Uint64 `json:"transactionIndex"`
  1098  	Value            *hexutil.Big    `json:"value"`
  1099  	V                *hexutil.Big    `json:"v"`
  1100  	R                *hexutil.Big    `json:"r"`
  1101  	S                *hexutil.Big    `json:"s"`
  1102  }
  1103  
  1104  // newRPCTransaction returns a transaction that will serialize to the RPC
  1105  // representation, with the given location metadata set (if available).
  1106  func newRPCTransaction(tx *types.Transaction, blockHash common.Hash, blockNumber uint64, index uint64) *RPCTransaction {
  1107  	var signer types.Signer = types.FrontierSigner{}
  1108  	if tx.Protected() {
  1109  		signer = types.NewEIP155Signer(tx.ChainId())
  1110  	}
  1111  	from, _ := types.Sender(signer, tx)
  1112  	v, r, s := tx.RawSignatureValues()
  1113  
  1114  	result := &RPCTransaction{
  1115  		From:     from,
  1116  		Gas:      hexutil.Uint64(tx.Gas()),
  1117  		GasPrice: (*hexutil.Big)(tx.GasPrice()),
  1118  		Hash:     tx.Hash(),
  1119  		Input:    hexutil.Bytes(tx.Data()),
  1120  		Nonce:    hexutil.Uint64(tx.Nonce()),
  1121  		To:       tx.To(),
  1122  		Value:    (*hexutil.Big)(tx.Value()),
  1123  		V:        (*hexutil.Big)(v),
  1124  		R:        (*hexutil.Big)(r),
  1125  		S:        (*hexutil.Big)(s),
  1126  	}
  1127  	if blockHash != (common.Hash{}) {
  1128  		result.BlockHash = &blockHash
  1129  		result.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(blockNumber))
  1130  		result.TransactionIndex = (*hexutil.Uint64)(&index)
  1131  	}
  1132  	return result
  1133  }
  1134  
  1135  // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation
  1136  func newRPCPendingTransaction(tx *types.Transaction) *RPCTransaction {
  1137  	return newRPCTransaction(tx, common.Hash{}, 0, 0)
  1138  }
  1139  
  1140  // newRPCTransactionFromBlockIndex returns a transaction that will serialize to the RPC representation.
  1141  func newRPCTransactionFromBlockIndex(b *types.Block, index uint64) *RPCTransaction {
  1142  	txs := b.Transactions()
  1143  	if index >= uint64(len(txs)) {
  1144  		return nil
  1145  	}
  1146  	return newRPCTransaction(txs[index], b.Hash(), b.NumberU64(), index)
  1147  }
  1148  
  1149  // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index.
  1150  func newRPCRawTransactionFromBlockIndex(b *types.Block, index uint64) hexutil.Bytes {
  1151  	txs := b.Transactions()
  1152  	if index >= uint64(len(txs)) {
  1153  		return nil
  1154  	}
  1155  	blob, _ := rlp.EncodeToBytes(txs[index])
  1156  	return blob
  1157  }
  1158  
  1159  // newRPCTransactionFromBlockHash returns a transaction that will serialize to the RPC representation.
  1160  func newRPCTransactionFromBlockHash(b *types.Block, hash common.Hash) *RPCTransaction {
  1161  	for idx, tx := range b.Transactions() {
  1162  		if tx.Hash() == hash {
  1163  			return newRPCTransactionFromBlockIndex(b, uint64(idx))
  1164  		}
  1165  	}
  1166  	return nil
  1167  }
  1168  
  1169  // PublicTransactionPoolAPI exposes methods for the RPC interface
  1170  type PublicTransactionPoolAPI struct {
  1171  	b         Backend
  1172  	nonceLock *AddrLocker
  1173  }
  1174  
  1175  // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.
  1176  func NewPublicTransactionPoolAPI(b Backend, nonceLock *AddrLocker) *PublicTransactionPoolAPI {
  1177  	return &PublicTransactionPoolAPI{b, nonceLock}
  1178  }
  1179  
  1180  // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
  1181  func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  1182  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1183  		n := hexutil.Uint(len(block.Transactions()))
  1184  		return &n
  1185  	}
  1186  	return nil
  1187  }
  1188  
  1189  // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
  1190  func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  1191  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1192  		n := hexutil.Uint(len(block.Transactions()))
  1193  		return &n
  1194  	}
  1195  	return nil
  1196  }
  1197  
  1198  // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
  1199  func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) *RPCTransaction {
  1200  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1201  		return newRPCTransactionFromBlockIndex(block, uint64(index))
  1202  	}
  1203  	return nil
  1204  }
  1205  
  1206  // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
  1207  func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) *RPCTransaction {
  1208  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1209  		return newRPCTransactionFromBlockIndex(block, uint64(index))
  1210  	}
  1211  	return nil
  1212  }
  1213  
  1214  // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
  1215  func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) hexutil.Bytes {
  1216  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1217  		return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1218  	}
  1219  	return nil
  1220  }
  1221  
  1222  // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index.
  1223  func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) hexutil.Bytes {
  1224  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1225  		return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1226  	}
  1227  	return nil
  1228  }
  1229  
  1230  // GetTransactionCount returns the number of transactions the given address has sent for the given block number
  1231  func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Uint64, error) {
  1232  	// Ask transaction pool for the nonce which includes pending transactions
  1233  	if blockNr, ok := blockNrOrHash.Number(); ok && blockNr == rpc.PendingBlockNumber {
  1234  		nonce, err := s.b.GetPoolNonce(ctx, address)
  1235  		if err != nil {
  1236  			return nil, err
  1237  		}
  1238  		return (*hexutil.Uint64)(&nonce), nil
  1239  	}
  1240  	// Resolve block number and use its state to ask for the nonce
  1241  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1242  	if state == nil || err != nil {
  1243  		return nil, err
  1244  	}
  1245  	nonce := state.GetNonce(address)
  1246  	return (*hexutil.Uint64)(&nonce), state.Error()
  1247  }
  1248  
  1249  // GetTransactionByHash returns the transaction for the given hash
  1250  func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) (*RPCTransaction, error) {
  1251  	// Try to return an already finalized transaction
  1252  	tx, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1253  	if err != nil {
  1254  		return nil, err
  1255  	}
  1256  	if tx != nil {
  1257  		return newRPCTransaction(tx, blockHash, blockNumber, index), nil
  1258  	}
  1259  	// No finalized transaction, try to retrieve it from the pool
  1260  	if tx := s.b.GetPoolTransaction(hash); tx != nil {
  1261  		return newRPCPendingTransaction(tx), nil
  1262  	}
  1263  
  1264  	// Transaction unknown, return as such
  1265  	return nil, nil
  1266  }
  1267  
  1268  // GetRawTransactionByHash returns the bytes of the transaction for the given hash.
  1269  func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  1270  	// Retrieve a finalized transaction, or a pooled otherwise
  1271  	tx, _, _, _, err := s.b.GetTransaction(ctx, hash)
  1272  	if err != nil {
  1273  		return nil, err
  1274  	}
  1275  	if tx == nil {
  1276  		if tx = s.b.GetPoolTransaction(hash); tx == nil {
  1277  			// Transaction not found anywhere, abort
  1278  			return nil, nil
  1279  		}
  1280  	}
  1281  	// Serialize to RLP and return
  1282  	return rlp.EncodeToBytes(tx)
  1283  }
  1284  
  1285  // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  1286  func (s *PublicTransactionPoolAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) {
  1287  	tx, blockHash, blockNumber, index := rawdb.ReadTransaction(s.b.ChainDb(), hash)
  1288  	if tx == nil {
  1289  		return nil, nil
  1290  	}
  1291  	receipts, err := s.b.GetReceipts(ctx, blockHash)
  1292  	if err != nil {
  1293  		return nil, err
  1294  	}
  1295  	if len(receipts) <= int(index) {
  1296  		return nil, nil
  1297  	}
  1298  	receipt := receipts[index]
  1299  
  1300  	var signer types.Signer = types.FrontierSigner{}
  1301  	if tx.Protected() {
  1302  		signer = types.NewEIP155Signer(tx.ChainId())
  1303  	}
  1304  	from, _ := types.Sender(signer, tx)
  1305  
  1306  	fields := map[string]interface{}{
  1307  		"blockHash":         blockHash,
  1308  		"blockNumber":       hexutil.Uint64(blockNumber),
  1309  		"transactionHash":   hash,
  1310  		"transactionIndex":  hexutil.Uint64(index),
  1311  		"from":              from,
  1312  		"to":                tx.To(),
  1313  		"gasUsed":           hexutil.Uint64(receipt.GasUsed),
  1314  		"cumulativeGasUsed": hexutil.Uint64(receipt.CumulativeGasUsed),
  1315  		"contractAddress":   nil,
  1316  		"logs":              receipt.Logs,
  1317  		"logsBloom":         receipt.Bloom,
  1318  	}
  1319  
  1320  	// Assign receipt status or post state.
  1321  	if len(receipt.PostState) > 0 {
  1322  		fields["root"] = hexutil.Bytes(receipt.PostState)
  1323  	} else {
  1324  		fields["status"] = hexutil.Uint(receipt.Status)
  1325  	}
  1326  	if receipt.Logs == nil {
  1327  		fields["logs"] = [][]*types.Log{}
  1328  	}
  1329  	// If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  1330  	if receipt.ContractAddress != (common.Address{}) {
  1331  		fields["contractAddress"] = receipt.ContractAddress
  1332  	}
  1333  	return fields, nil
  1334  }
  1335  
  1336  // sign is a helper function that signs a transaction with the private key of the given address.
  1337  func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
  1338  	// Look up the wallet containing the requested signer
  1339  	account := accounts.Account{Address: addr}
  1340  
  1341  	wallet, err := s.b.AccountManager().Find(account)
  1342  	if err != nil {
  1343  		return nil, err
  1344  	}
  1345  	// Request the wallet to sign the transaction
  1346  	return wallet.SignTx(account, tx, s.b.ChainConfig().ChainID)
  1347  }
  1348  
  1349  // SendTxArgs represents the arguments to sumbit a new transaction into the transaction pool.
  1350  type SendTxArgs struct {
  1351  	From     common.Address  `json:"from"`
  1352  	To       *common.Address `json:"to"`
  1353  	Gas      *hexutil.Uint64 `json:"gas"`
  1354  	GasPrice *hexutil.Big    `json:"gasPrice"`
  1355  	Value    *hexutil.Big    `json:"value"`
  1356  	Nonce    *hexutil.Uint64 `json:"nonce"`
  1357  	// We accept "data" and "input" for backwards-compatibility reasons. "input" is the
  1358  	// newer name and should be preferred by clients.
  1359  	Data  *hexutil.Bytes `json:"data"`
  1360  	Input *hexutil.Bytes `json:"input"`
  1361  }
  1362  
  1363  // setDefaults is a helper function that fills in default values for unspecified tx fields.
  1364  func (args *SendTxArgs) setDefaults(ctx context.Context, b Backend) error {
  1365  	if args.GasPrice == nil {
  1366  		price, err := b.SuggestPrice(ctx)
  1367  		if err != nil {
  1368  			return err
  1369  		}
  1370  		args.GasPrice = (*hexutil.Big)(price)
  1371  	}
  1372  	if args.Value == nil {
  1373  		args.Value = new(hexutil.Big)
  1374  	}
  1375  	if args.Nonce == nil {
  1376  		nonce, err := b.GetPoolNonce(ctx, args.From)
  1377  		if err != nil {
  1378  			return err
  1379  		}
  1380  		args.Nonce = (*hexutil.Uint64)(&nonce)
  1381  	}
  1382  	if args.Data != nil && args.Input != nil && !bytes.Equal(*args.Data, *args.Input) {
  1383  		return errors.New(`both "data" and "input" are set and not equal. Please use "input" to pass transaction call data`)
  1384  	}
  1385  	if args.To == nil {
  1386  		// Contract creation
  1387  		var input []byte
  1388  		if args.Data != nil {
  1389  			input = *args.Data
  1390  		} else if args.Input != nil {
  1391  			input = *args.Input
  1392  		}
  1393  		if len(input) == 0 {
  1394  			return errors.New(`contract creation without any data provided`)
  1395  		}
  1396  	}
  1397  	// Estimate the gas usage if necessary.
  1398  	if args.Gas == nil {
  1399  		// For backwards-compatibility reason, we try both input and data
  1400  		// but input is preferred.
  1401  		input := args.Input
  1402  		if input == nil {
  1403  			input = args.Data
  1404  		}
  1405  		callArgs := CallArgs{
  1406  			From:     &args.From, // From shouldn't be nil
  1407  			To:       args.To,
  1408  			GasPrice: args.GasPrice,
  1409  			Value:    args.Value,
  1410  			Data:     input,
  1411  		}
  1412  		pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
  1413  		estimated, err := DoEstimateGas(ctx, b, callArgs, pendingBlockNr, b.RPCGasCap())
  1414  		if err != nil {
  1415  			return err
  1416  		}
  1417  		args.Gas = &estimated
  1418  		log.Trace("Estimate gas usage automatically", "gas", args.Gas)
  1419  	}
  1420  	return nil
  1421  }
  1422  
  1423  func (args *SendTxArgs) toTransaction() *types.Transaction {
  1424  	var input []byte
  1425  	if args.Input != nil {
  1426  		input = *args.Input
  1427  	} else if args.Data != nil {
  1428  		input = *args.Data
  1429  	}
  1430  	if args.To == nil {
  1431  		return types.NewContractCreation(uint64(*args.Nonce), (*big.Int)(args.Value), uint64(*args.Gas), (*big.Int)(args.GasPrice), input)
  1432  	}
  1433  	return types.NewTransaction(uint64(*args.Nonce), *args.To, (*big.Int)(args.Value), uint64(*args.Gas), (*big.Int)(args.GasPrice), input)
  1434  }
  1435  
  1436  // SubmitTransaction is a helper function that submits tx to txPool and logs a message.
  1437  func SubmitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (common.Hash, error) {
  1438  	if err := b.SendTx(ctx, tx); err != nil {
  1439  		return common.Hash{}, err
  1440  	}
  1441  	if tx.To() == nil {
  1442  		signer := types.MakeSigner(b.ChainConfig(), b.CurrentBlock().Number())
  1443  		from, err := types.Sender(signer, tx)
  1444  		if err != nil {
  1445  			return common.Hash{}, err
  1446  		}
  1447  		addr := crypto.CreateAddress(from, tx.Nonce())
  1448  		log.Info("Submitted contract creation", "fullhash", tx.Hash().Hex(), "contract", addr.Hex())
  1449  	} else {
  1450  		log.Info("Submitted transaction", "fullhash", tx.Hash().Hex(), "recipient", tx.To())
  1451  	}
  1452  	return tx.Hash(), nil
  1453  }
  1454  
  1455  // SendTransaction creates a transaction for the given argument, sign it and submit it to the
  1456  // transaction pool.
  1457  func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error) {
  1458  	// Look up the wallet containing the requested signer
  1459  	account := accounts.Account{Address: args.From}
  1460  
  1461  	wallet, err := s.b.AccountManager().Find(account)
  1462  	if err != nil {
  1463  		return common.Hash{}, err
  1464  	}
  1465  
  1466  	if args.Nonce == nil {
  1467  		// Hold the addresse's mutex around signing to prevent concurrent assignment of
  1468  		// the same nonce to multiple accounts.
  1469  		s.nonceLock.LockAddr(args.From)
  1470  		defer s.nonceLock.UnlockAddr(args.From)
  1471  	}
  1472  
  1473  	// Set some sanity defaults and terminate on failure
  1474  	if err := args.setDefaults(ctx, s.b); err != nil {
  1475  		return common.Hash{}, err
  1476  	}
  1477  	// Assemble the transaction and sign with the wallet
  1478  	tx := args.toTransaction()
  1479  
  1480  	signed, err := wallet.SignTx(account, tx, s.b.ChainConfig().ChainID)
  1481  	if err != nil {
  1482  		return common.Hash{}, err
  1483  	}
  1484  	return SubmitTransaction(ctx, s.b, signed)
  1485  }
  1486  
  1487  // FillTransaction fills the defaults (nonce, gas, gasPrice) on a given unsigned transaction,
  1488  // and returns it to the caller for further processing (signing + broadcast)
  1489  func (s *PublicTransactionPoolAPI) FillTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) {
  1490  	// Set some sanity defaults and terminate on failure
  1491  	if err := args.setDefaults(ctx, s.b); err != nil {
  1492  		return nil, err
  1493  	}
  1494  	// Assemble the transaction and obtain rlp
  1495  	tx := args.toTransaction()
  1496  	data, err := rlp.EncodeToBytes(tx)
  1497  	if err != nil {
  1498  		return nil, err
  1499  	}
  1500  	return &SignTransactionResult{data, tx}, nil
  1501  }
  1502  
  1503  // SendRawTransaction will add the signed transaction to the transaction pool.
  1504  // The sender is responsible for signing the transaction and using the correct nonce.
  1505  func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, encodedTx hexutil.Bytes) (common.Hash, error) {
  1506  	tx := new(types.Transaction)
  1507  	if err := rlp.DecodeBytes(encodedTx, tx); err != nil {
  1508  		return common.Hash{}, err
  1509  	}
  1510  	return SubmitTransaction(ctx, s.b, tx)
  1511  }
  1512  
  1513  // Sign calculates an ECDSA signature for:
  1514  // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message).
  1515  //
  1516  // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  1517  // where the V value will be 27 or 28 for legacy reasons.
  1518  //
  1519  // The account associated with addr must be unlocked.
  1520  //
  1521  // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
  1522  func (s *PublicTransactionPoolAPI) Sign(addr common.Address, data hexutil.Bytes) (hexutil.Bytes, error) {
  1523  	// Look up the wallet containing the requested signer
  1524  	account := accounts.Account{Address: addr}
  1525  
  1526  	wallet, err := s.b.AccountManager().Find(account)
  1527  	if err != nil {
  1528  		return nil, err
  1529  	}
  1530  	// Sign the requested hash with the wallet
  1531  	signature, err := wallet.SignText(account, data)
  1532  	if err == nil {
  1533  		signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  1534  	}
  1535  	return signature, err
  1536  }
  1537  
  1538  // SignTransactionResult represents a RLP encoded signed transaction.
  1539  type SignTransactionResult struct {
  1540  	Raw hexutil.Bytes      `json:"raw"`
  1541  	Tx  *types.Transaction `json:"tx"`
  1542  }
  1543  
  1544  // SignTransaction will sign the given transaction with the from account.
  1545  // The node needs to have the private key of the account corresponding with
  1546  // the given from address and it needs to be unlocked.
  1547  func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) {
  1548  	if args.Gas == nil {
  1549  		return nil, fmt.Errorf("gas not specified")
  1550  	}
  1551  	if args.GasPrice == nil {
  1552  		return nil, fmt.Errorf("gasPrice not specified")
  1553  	}
  1554  	if args.Nonce == nil {
  1555  		return nil, fmt.Errorf("nonce not specified")
  1556  	}
  1557  	if err := args.setDefaults(ctx, s.b); err != nil {
  1558  		return nil, err
  1559  	}
  1560  	tx, err := s.sign(args.From, args.toTransaction())
  1561  	if err != nil {
  1562  		return nil, err
  1563  	}
  1564  	data, err := rlp.EncodeToBytes(tx)
  1565  	if err != nil {
  1566  		return nil, err
  1567  	}
  1568  	return &SignTransactionResult{data, tx}, nil
  1569  }
  1570  
  1571  // PendingTransactions returns the transactions that are in the transaction pool
  1572  // and have a from address that is one of the accounts this node manages.
  1573  func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error) {
  1574  	pending, err := s.b.GetPoolTransactions()
  1575  	if err != nil {
  1576  		return nil, err
  1577  	}
  1578  	accounts := make(map[common.Address]struct{})
  1579  	for _, wallet := range s.b.AccountManager().Wallets() {
  1580  		for _, account := range wallet.Accounts() {
  1581  			accounts[account.Address] = struct{}{}
  1582  		}
  1583  	}
  1584  	transactions := make([]*RPCTransaction, 0, len(pending))
  1585  	for _, tx := range pending {
  1586  		var signer types.Signer = types.HomesteadSigner{}
  1587  		if tx.Protected() {
  1588  			signer = types.NewEIP155Signer(tx.ChainId())
  1589  		}
  1590  		from, _ := types.Sender(signer, tx)
  1591  		if _, exists := accounts[from]; exists {
  1592  			transactions = append(transactions, newRPCPendingTransaction(tx))
  1593  		}
  1594  	}
  1595  	return transactions, nil
  1596  }
  1597  
  1598  // Resend accepts an existing transaction and a new gas price and limit. It will remove
  1599  // the given transaction from the pool and reinsert it with the new gas price and limit.
  1600  func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs SendTxArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) {
  1601  	if sendArgs.Nonce == nil {
  1602  		return common.Hash{}, fmt.Errorf("missing transaction nonce in transaction spec")
  1603  	}
  1604  	if err := sendArgs.setDefaults(ctx, s.b); err != nil {
  1605  		return common.Hash{}, err
  1606  	}
  1607  	matchTx := sendArgs.toTransaction()
  1608  	pending, err := s.b.GetPoolTransactions()
  1609  	if err != nil {
  1610  		return common.Hash{}, err
  1611  	}
  1612  
  1613  	for _, p := range pending {
  1614  		var signer types.Signer = types.HomesteadSigner{}
  1615  		if p.Protected() {
  1616  			signer = types.NewEIP155Signer(p.ChainId())
  1617  		}
  1618  		wantSigHash := signer.Hash(matchTx)
  1619  
  1620  		if pFrom, err := types.Sender(signer, p); err == nil && pFrom == sendArgs.From && signer.Hash(p) == wantSigHash {
  1621  			// Match. Re-sign and send the transaction.
  1622  			if gasPrice != nil && (*big.Int)(gasPrice).Sign() != 0 {
  1623  				sendArgs.GasPrice = gasPrice
  1624  			}
  1625  			if gasLimit != nil && *gasLimit != 0 {
  1626  				sendArgs.Gas = gasLimit
  1627  			}
  1628  			signedTx, err := s.sign(sendArgs.From, sendArgs.toTransaction())
  1629  			if err != nil {
  1630  				return common.Hash{}, err
  1631  			}
  1632  			if err = s.b.SendTx(ctx, signedTx); err != nil {
  1633  				return common.Hash{}, err
  1634  			}
  1635  			return signedTx.Hash(), nil
  1636  		}
  1637  	}
  1638  
  1639  	return common.Hash{}, fmt.Errorf("transaction %#x not found", matchTx.Hash())
  1640  }
  1641  
  1642  // PublicDebugAPI is the collection of Ethereum APIs exposed over the public
  1643  // debugging endpoint.
  1644  type PublicDebugAPI struct {
  1645  	b Backend
  1646  }
  1647  
  1648  // NewPublicDebugAPI creates a new API definition for the public debug methods
  1649  // of the Ethereum service.
  1650  func NewPublicDebugAPI(b Backend) *PublicDebugAPI {
  1651  	return &PublicDebugAPI{b: b}
  1652  }
  1653  
  1654  // GetBlockRlp retrieves the RLP encoded for of a single block.
  1655  func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error) {
  1656  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1657  	if block == nil {
  1658  		return "", fmt.Errorf("block #%d not found", number)
  1659  	}
  1660  	encoded, err := rlp.EncodeToBytes(block)
  1661  	if err != nil {
  1662  		return "", err
  1663  	}
  1664  	return fmt.Sprintf("%x", encoded), nil
  1665  }
  1666  
  1667  // TestSignCliqueBlock fetches the given block number, and attempts to sign it as a clique header with the
  1668  // given address, returning the address of the recovered signature
  1669  //
  1670  // This is a temporary method to debug the externalsigner integration,
  1671  // TODO: Remove this method when the integration is mature
  1672  func (api *PublicDebugAPI) TestSignCliqueBlock(ctx context.Context, address common.Address, number uint64) (common.Address, error) {
  1673  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1674  	if block == nil {
  1675  		return common.Address{}, fmt.Errorf("block #%d not found", number)
  1676  	}
  1677  	header := block.Header()
  1678  	header.Extra = make([]byte, 32+65)
  1679  	encoded := clique.CliqueRLP(header)
  1680  
  1681  	// Look up the wallet containing the requested signer
  1682  	account := accounts.Account{Address: address}
  1683  	wallet, err := api.b.AccountManager().Find(account)
  1684  	if err != nil {
  1685  		return common.Address{}, err
  1686  	}
  1687  
  1688  	signature, err := wallet.SignData(account, accounts.MimetypeClique, encoded)
  1689  	if err != nil {
  1690  		return common.Address{}, err
  1691  	}
  1692  	sealHash := clique.SealHash(header).Bytes()
  1693  	log.Info("test signing of clique block",
  1694  		"Sealhash", fmt.Sprintf("%x", sealHash),
  1695  		"signature", fmt.Sprintf("%x", signature))
  1696  	pubkey, err := crypto.Ecrecover(sealHash, signature)
  1697  	if err != nil {
  1698  		return common.Address{}, err
  1699  	}
  1700  	var signer common.Address
  1701  	copy(signer[:], crypto.Keccak256(pubkey[1:])[12:])
  1702  
  1703  	return signer, nil
  1704  }
  1705  
  1706  // PrintBlock retrieves a block and returns its pretty printed form.
  1707  func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) {
  1708  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1709  	if block == nil {
  1710  		return "", fmt.Errorf("block #%d not found", number)
  1711  	}
  1712  	return spew.Sdump(block), nil
  1713  }
  1714  
  1715  // SeedHash retrieves the seed hash of a block.
  1716  func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) {
  1717  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1718  	if block == nil {
  1719  		return "", fmt.Errorf("block #%d not found", number)
  1720  	}
  1721  	return fmt.Sprintf("0x%x", ethash.SeedHash(number)), nil
  1722  }
  1723  
  1724  // PrivateDebugAPI is the collection of Ethereum APIs exposed over the private
  1725  // debugging endpoint.
  1726  type PrivateDebugAPI struct {
  1727  	b Backend
  1728  }
  1729  
  1730  // NewPrivateDebugAPI creates a new API definition for the private debug methods
  1731  // of the Ethereum service.
  1732  func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI {
  1733  	return &PrivateDebugAPI{b: b}
  1734  }
  1735  
  1736  // ChaindbProperty returns leveldb properties of the key-value database.
  1737  func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) {
  1738  	if property == "" {
  1739  		property = "leveldb.stats"
  1740  	} else if !strings.HasPrefix(property, "leveldb.") {
  1741  		property = "leveldb." + property
  1742  	}
  1743  	return api.b.ChainDb().Stat(property)
  1744  }
  1745  
  1746  // ChaindbCompact flattens the entire key-value database into a single level,
  1747  // removing all unused slots and merging all keys.
  1748  func (api *PrivateDebugAPI) ChaindbCompact() error {
  1749  	for b := byte(0); b < 255; b++ {
  1750  		log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1))
  1751  		if err := api.b.ChainDb().Compact([]byte{b}, []byte{b + 1}); err != nil {
  1752  			log.Error("Database compaction failed", "err", err)
  1753  			return err
  1754  		}
  1755  	}
  1756  	return nil
  1757  }
  1758  
  1759  // SetHead rewinds the head of the blockchain to a previous block.
  1760  func (api *PrivateDebugAPI) SetHead(number hexutil.Uint64) {
  1761  	api.b.SetHead(uint64(number))
  1762  }
  1763  
  1764  // PublicNetAPI offers network related RPC methods
  1765  type PublicNetAPI struct {
  1766  	net            *p2p.Server
  1767  	networkVersion uint64
  1768  }
  1769  
  1770  // NewPublicNetAPI creates a new net API instance.
  1771  func NewPublicNetAPI(net *p2p.Server, networkVersion uint64) *PublicNetAPI {
  1772  	return &PublicNetAPI{net, networkVersion}
  1773  }
  1774  
  1775  // Listening returns an indication if the node is listening for network connections.
  1776  func (s *PublicNetAPI) Listening() bool {
  1777  	return true // always listening
  1778  }
  1779  
  1780  // PeerCount returns the number of connected peers
  1781  func (s *PublicNetAPI) PeerCount() hexutil.Uint {
  1782  	return hexutil.Uint(s.net.PeerCount())
  1783  }
  1784  
  1785  // Version returns the current ethereum protocol version.
  1786  func (s *PublicNetAPI) Version() string {
  1787  	return fmt.Sprintf("%d", s.networkVersion)
  1788  }