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