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