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