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