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