github.com/dim4egster/coreth@v0.10.2/internal/ethapi/api.go (about)

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