gitlab.com/flarenetwork/coreth@v0.1.1/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  	"strings"
    35  	"time"
    36  
    37  	"github.com/ava-labs/avalanchego/ids"
    38  	"github.com/davecgh/go-spew/spew"
    39  	"github.com/ethereum/go-ethereum/accounts/abi"
    40  	"github.com/ethereum/go-ethereum/common"
    41  	"github.com/ethereum/go-ethereum/common/hexutil"
    42  	"github.com/ethereum/go-ethereum/common/math"
    43  	"github.com/ethereum/go-ethereum/crypto"
    44  	"github.com/ethereum/go-ethereum/log"
    45  	"github.com/ethereum/go-ethereum/rlp"
    46  	"github.com/tyler-smith/go-bip39"
    47  	"gitlab.com/flarenetwork/coreth/accounts"
    48  	"gitlab.com/flarenetwork/coreth/accounts/keystore"
    49  	"gitlab.com/flarenetwork/coreth/accounts/scwallet"
    50  	"gitlab.com/flarenetwork/coreth/core"
    51  	"gitlab.com/flarenetwork/coreth/core/state"
    52  	"gitlab.com/flarenetwork/coreth/core/types"
    53  	"gitlab.com/flarenetwork/coreth/core/vm"
    54  	"gitlab.com/flarenetwork/coreth/params"
    55  	"gitlab.com/flarenetwork/coreth/rpc"
    56  )
    57  
    58  // PublicEthereumAPI provides an API to access Ethereum related information.
    59  // It offers only methods that operate on public data that is freely available to anyone.
    60  type PublicEthereumAPI struct {
    61  	b Backend
    62  }
    63  
    64  // NewPublicEthereumAPI creates a new Ethereum protocol API.
    65  func NewPublicEthereumAPI(b Backend) *PublicEthereumAPI {
    66  	return &PublicEthereumAPI{b}
    67  }
    68  
    69  // GasPrice returns a suggestion for a gas price for legacy transactions.
    70  func (s *PublicEthereumAPI) 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 *PublicEthereumAPI) 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 *PublicEthereumAPI) 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  // TODO(aaronbuchwald) enable after migrating v1.10.6 gasprice changes
    98  // type feeHistoryResult struct {
    99  // 	OldestBlock  *hexutil.Big     `json:"oldestBlock"`
   100  // 	Reward       [][]*hexutil.Big `json:"reward,omitempty"`
   101  // 	BaseFee      []*hexutil.Big   `json:"baseFeePerGas,omitempty"`
   102  // 	GasUsedRatio []float64        `json:"gasUsedRatio"`
   103  // }
   104  
   105  // func (s *PublicEthereumAPI) 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 returns false in case the node is currently not syncing with the network. It can be up to date or has not
   133  // yet received the latest block headers from its pears. In case it is synchronizing:
   134  // - startingBlock: block number this node started to synchronise from
   135  // - currentBlock:  block number this node is currently importing
   136  // - highestBlock:  block number of the highest block header this node has received from peers
   137  // - pulledStates:  number of state entries processed until now
   138  // - knownStates:   number of known state entries that still need to be pulled
   139  func (s *PublicEthereumAPI) Syncing() (interface{}, error) {
   140  	return nil, errors.New("not implemented in coreth") // Info or Health API should be used instead
   141  	// progress := s.b.Downloader().Progress()
   142  
   143  	// // Return not syncing if the synchronisation already completed
   144  	// if progress.CurrentBlock >= progress.HighestBlock {
   145  	// 	return false, nil
   146  	// }
   147  	// // Otherwise gather the block sync stats
   148  	// return map[string]interface{}{
   149  	// 	"startingBlock": hexutil.Uint64(progress.StartingBlock),
   150  	// 	"currentBlock":  hexutil.Uint64(progress.CurrentBlock),
   151  	// 	"highestBlock":  hexutil.Uint64(progress.HighestBlock),
   152  	// 	"pulledStates":  hexutil.Uint64(progress.PulledStates),
   153  	// 	"knownStates":   hexutil.Uint64(progress.KnownStates),
   154  	// }, nil
   155  }
   156  
   157  // PublicTxPoolAPI offers and API for the transaction pool. It only operates on data that is non confidential.
   158  type PublicTxPoolAPI struct {
   159  	b Backend
   160  }
   161  
   162  // NewPublicTxPoolAPI creates a new tx pool service that gives information about the transaction pool.
   163  func NewPublicTxPoolAPI(b Backend) *PublicTxPoolAPI {
   164  	return &PublicTxPoolAPI{b}
   165  }
   166  
   167  // Content returns the transactions contained within the transaction pool.
   168  func (s *PublicTxPoolAPI) Content() map[string]map[string]map[string]*RPCTransaction {
   169  	content := map[string]map[string]map[string]*RPCTransaction{
   170  		"pending": make(map[string]map[string]*RPCTransaction),
   171  		"queued":  make(map[string]map[string]*RPCTransaction),
   172  	}
   173  	pending, queue := s.b.TxPoolContent()
   174  	curHeader := s.b.CurrentHeader()
   175  	// Flatten the pending transactions
   176  	for account, txs := range pending {
   177  		dump := make(map[string]*RPCTransaction)
   178  		for _, tx := range txs {
   179  			dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx, curHeader, s.b.ChainConfig())
   180  		}
   181  		content["pending"][account.Hex()] = dump
   182  	}
   183  	// Flatten the queued transactions
   184  	for account, txs := range queue {
   185  		dump := make(map[string]*RPCTransaction)
   186  		for _, tx := range txs {
   187  			dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx, curHeader, s.b.ChainConfig())
   188  		}
   189  		content["queued"][account.Hex()] = dump
   190  	}
   191  	return content
   192  }
   193  
   194  // ContentFrom returns the transactions contained within the transaction pool.
   195  func (s *PublicTxPoolAPI) ContentFrom(addr common.Address) map[string]map[string]*RPCTransaction {
   196  	content := make(map[string]map[string]*RPCTransaction, 2)
   197  	pending, queue := s.b.TxPoolContentFrom(addr)
   198  	curHeader := s.b.CurrentHeader()
   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, 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, 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 *PublicTxPoolAPI) 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 *PublicTxPoolAPI) 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  // PublicAccountAPI provides an API to access accounts managed by this node.
   262  // It offers only methods that can retrieve accounts.
   263  type PublicAccountAPI struct {
   264  	am *accounts.Manager
   265  }
   266  
   267  // NewPublicAccountAPI creates a new PublicAccountAPI.
   268  func NewPublicAccountAPI(am *accounts.Manager) *PublicAccountAPI {
   269  	return &PublicAccountAPI{am: am}
   270  }
   271  
   272  // Accounts returns the collection of accounts this node manages
   273  func (s *PublicAccountAPI) Accounts() []common.Address {
   274  	return s.am.Accounts()
   275  }
   276  
   277  // PrivateAccountAPI 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 PrivateAccountAPI struct {
   281  	am        *accounts.Manager
   282  	nonceLock *AddrLocker
   283  	b         Backend
   284  }
   285  
   286  // NewPrivateAccountAPI create a new PrivateAccountAPI.
   287  func NewPrivateAccountAPI(b Backend, nonceLock *AddrLocker) *PrivateAccountAPI {
   288  	return &PrivateAccountAPI{
   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 *PrivateAccountAPI) 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 *PrivateAccountAPI) 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 *PrivateAccountAPI) 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 *PrivateAccountAPI) 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 *PrivateAccountAPI) 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 *PrivateAccountAPI) 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 *PrivateAccountAPI) 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 *PrivateAccountAPI) 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 *PrivateAccountAPI) 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 *PrivateAccountAPI) 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 *PrivateAccountAPI) 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  // keccack256("\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 *PrivateAccountAPI) 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 *PrivateAccountAPI) 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  // SignAndSendTransaction was renamed to SendTransaction. This method is deprecated
   567  // and will be removed in the future. It primary goal is to give clients time to update.
   568  func (s *PrivateAccountAPI) SignAndSendTransaction(ctx context.Context, args TransactionArgs, passwd string) (common.Hash, error) {
   569  	return s.SendTransaction(ctx, args, passwd)
   570  }
   571  
   572  // InitializeWallet initializes a new wallet at the provided URL, by generating and returning a new private key.
   573  func (s *PrivateAccountAPI) InitializeWallet(ctx context.Context, url string) (string, error) {
   574  	wallet, err := s.am.Wallet(url)
   575  	if err != nil {
   576  		return "", err
   577  	}
   578  
   579  	entropy, err := bip39.NewEntropy(256)
   580  	if err != nil {
   581  		return "", err
   582  	}
   583  
   584  	mnemonic, err := bip39.NewMnemonic(entropy)
   585  	if err != nil {
   586  		return "", err
   587  	}
   588  
   589  	seed := bip39.NewSeed(mnemonic, "")
   590  
   591  	switch wallet := wallet.(type) {
   592  	case *scwallet.Wallet:
   593  		return mnemonic, wallet.Initialize(seed)
   594  	default:
   595  		return "", fmt.Errorf("specified wallet does not support initialization")
   596  	}
   597  }
   598  
   599  // Unpair deletes a pairing between wallet and geth.
   600  func (s *PrivateAccountAPI) Unpair(ctx context.Context, url string, pin string) error {
   601  	wallet, err := s.am.Wallet(url)
   602  	if err != nil {
   603  		return err
   604  	}
   605  
   606  	switch wallet := wallet.(type) {
   607  	case *scwallet.Wallet:
   608  		return wallet.Unpair([]byte(pin))
   609  	default:
   610  		return fmt.Errorf("specified wallet does not support pairing")
   611  	}
   612  }
   613  
   614  // PublicBlockChainAPI provides an API to access the Ethereum blockchain.
   615  // It offers only methods that operate on public data that is freely available to anyone.
   616  type PublicBlockChainAPI struct {
   617  	b Backend
   618  }
   619  
   620  // NewPublicBlockChainAPI creates a new Ethereum blockchain API.
   621  func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI {
   622  	return &PublicBlockChainAPI{b}
   623  }
   624  
   625  // ChainId is the EIP-155 replay-protection chain id for the current ethereum chain config.
   626  func (api *PublicBlockChainAPI) ChainId() (*hexutil.Big, error) {
   627  	// if current block is at or past the EIP-155 replay-protection fork block, return chainID from config
   628  	if config := api.b.ChainConfig(); config.IsEIP155(api.b.CurrentBlock().Number()) {
   629  		return (*hexutil.Big)(config.ChainID), nil
   630  	}
   631  	return nil, fmt.Errorf("chain not synced beyond EIP-155 replay-protection fork block")
   632  }
   633  
   634  // BlockNumber returns the block number of the chain head.
   635  func (s *PublicBlockChainAPI) BlockNumber() hexutil.Uint64 {
   636  	header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available
   637  	return hexutil.Uint64(header.Number.Uint64())
   638  }
   639  
   640  // GetBalance returns the amount of wei for the given address in the state of the
   641  // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
   642  // block numbers are also allowed.
   643  func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Big, error) {
   644  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   645  	if state == nil || err != nil {
   646  		return nil, err
   647  	}
   648  	return (*hexutil.Big)(state.GetBalance(address)), state.Error()
   649  }
   650  
   651  // GetAssetBalance returns the amount of [assetID] for the given address in the state of the
   652  // given block number. The rpc.LatestBlockNumber, rpc.PendingBlockNumber, and
   653  // rpc.AcceptedBlockNumber meta block numbers are also allowed.
   654  func (s *PublicBlockChainAPI) GetAssetBalance(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash, assetID ids.ID) (*hexutil.Big, error) {
   655  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   656  	if state == nil || err != nil {
   657  		return nil, err
   658  	}
   659  	return (*hexutil.Big)(state.GetBalanceMultiCoin(address, common.Hash(assetID))), state.Error()
   660  }
   661  
   662  // Result structs for GetProof
   663  type AccountResult struct {
   664  	Address      common.Address  `json:"address"`
   665  	AccountProof []string        `json:"accountProof"`
   666  	Balance      *hexutil.Big    `json:"balance"`
   667  	CodeHash     common.Hash     `json:"codeHash"`
   668  	Nonce        hexutil.Uint64  `json:"nonce"`
   669  	StorageHash  common.Hash     `json:"storageHash"`
   670  	StorageProof []StorageResult `json:"storageProof"`
   671  }
   672  
   673  type StorageResult struct {
   674  	Key   string       `json:"key"`
   675  	Value *hexutil.Big `json:"value"`
   676  	Proof []string     `json:"proof"`
   677  }
   678  
   679  // GetProof returns the Merkle-proof for a given account and optionally some storage keys.
   680  func (s *PublicBlockChainAPI) GetProof(ctx context.Context, address common.Address, storageKeys []string, blockNrOrHash rpc.BlockNumberOrHash) (*AccountResult, error) {
   681  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   682  	if state == nil || err != nil {
   683  		return nil, err
   684  	}
   685  
   686  	storageTrie := state.StorageTrie(address)
   687  	storageHash := types.EmptyRootHash
   688  	codeHash := state.GetCodeHash(address)
   689  	storageProof := make([]StorageResult, len(storageKeys))
   690  
   691  	// if we have a storageTrie, (which means the account exists), we can update the storagehash
   692  	if storageTrie != nil {
   693  		storageHash = storageTrie.Hash()
   694  	} else {
   695  		// no storageTrie means the account does not exist, so the codeHash is the hash of an empty bytearray.
   696  		codeHash = crypto.Keccak256Hash(nil)
   697  	}
   698  
   699  	// create the proof for the storageKeys
   700  	for i, key := range storageKeys {
   701  		if storageTrie != nil {
   702  			proof, storageError := state.GetStorageProof(address, common.HexToHash(key))
   703  			if storageError != nil {
   704  				return nil, storageError
   705  			}
   706  			storageProof[i] = StorageResult{key, (*hexutil.Big)(state.GetState(address, common.HexToHash(key)).Big()), toHexSlice(proof)}
   707  		} else {
   708  			storageProof[i] = StorageResult{key, &hexutil.Big{}, []string{}}
   709  		}
   710  	}
   711  
   712  	// create the accountProof
   713  	accountProof, proofErr := state.GetProof(address)
   714  	if proofErr != nil {
   715  		return nil, proofErr
   716  	}
   717  
   718  	return &AccountResult{
   719  		Address:      address,
   720  		AccountProof: toHexSlice(accountProof),
   721  		Balance:      (*hexutil.Big)(state.GetBalance(address)),
   722  		CodeHash:     codeHash,
   723  		Nonce:        hexutil.Uint64(state.GetNonce(address)),
   724  		StorageHash:  storageHash,
   725  		StorageProof: storageProof,
   726  	}, state.Error()
   727  }
   728  
   729  // GetHeaderByNumber returns the requested canonical block header.
   730  // * When blockNr is -1 the chain head is returned.
   731  // * When blockNr is -2 the pending chain head is returned.
   732  func (s *PublicBlockChainAPI) GetHeaderByNumber(ctx context.Context, number rpc.BlockNumber) (map[string]interface{}, error) {
   733  	header, err := s.b.HeaderByNumber(ctx, number)
   734  	if header != nil && err == nil {
   735  		response := s.rpcMarshalHeader(ctx, header)
   736  		// coreth has no notion of a pending block
   737  		// if number == rpc.PendingBlockNumber {
   738  		// 	// Pending header need to nil out a few fields
   739  		// 	for _, field := range []string{"hash", "nonce", "miner"} {
   740  		// 		response[field] = nil
   741  		// 	}
   742  		// }
   743  		return response, err
   744  	}
   745  	return nil, err
   746  }
   747  
   748  // GetHeaderByHash returns the requested header by hash.
   749  func (s *PublicBlockChainAPI) GetHeaderByHash(ctx context.Context, hash common.Hash) map[string]interface{} {
   750  	header, _ := s.b.HeaderByHash(ctx, hash)
   751  	if header != nil {
   752  		return s.rpcMarshalHeader(ctx, header)
   753  	}
   754  	return nil
   755  }
   756  
   757  // GetBlockByNumber returns the requested canonical block.
   758  // * When blockNr is -1 the chain head is returned.
   759  // * When blockNr is -2 the pending chain head is returned.
   760  // * When fullTx is true all transactions in the block are returned, otherwise
   761  //   only the transaction hash is returned.
   762  func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, number rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
   763  	block, err := s.b.BlockByNumber(ctx, number)
   764  	if block != nil && err == nil {
   765  		response, err := s.rpcMarshalBlock(ctx, block, true, fullTx)
   766  		// coreth has no notion of a pending block
   767  		// if err == nil && number == rpc.PendingBlockNumber {
   768  		// 	// Pending blocks need to nil out a few fields
   769  		// 	for _, field := range []string{"hash", "nonce", "miner"} {
   770  		// 		response[field] = nil
   771  		// 	}
   772  		// }
   773  		return response, err
   774  	}
   775  	return nil, err
   776  }
   777  
   778  // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
   779  // detail, otherwise only the transaction hash is returned.
   780  func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, hash common.Hash, fullTx bool) (map[string]interface{}, error) {
   781  	block, err := s.b.BlockByHash(ctx, hash)
   782  	if block != nil {
   783  		return s.rpcMarshalBlock(ctx, block, true, fullTx)
   784  	}
   785  	return nil, err
   786  }
   787  
   788  // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true
   789  // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
   790  func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) {
   791  	block, err := s.b.BlockByNumber(ctx, blockNr)
   792  	if block != nil {
   793  		uncles := block.Uncles()
   794  		if index >= hexutil.Uint(len(uncles)) {
   795  			log.Debug("Requested uncle not found", "number", blockNr, "hash", block.Hash(), "index", index)
   796  			return nil, nil
   797  		}
   798  		block = types.NewBlockWithHeader(uncles[index])
   799  		return s.rpcMarshalBlock(ctx, block, false, false)
   800  	}
   801  	return nil, err
   802  }
   803  
   804  // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true
   805  // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
   806  func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) {
   807  	block, err := s.b.BlockByHash(ctx, blockHash)
   808  	if block != nil {
   809  		uncles := block.Uncles()
   810  		if index >= hexutil.Uint(len(uncles)) {
   811  			log.Debug("Requested uncle not found", "number", block.Number(), "hash", blockHash, "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  // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
   821  func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
   822  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
   823  		n := hexutil.Uint(len(block.Uncles()))
   824  		return &n
   825  	}
   826  	return nil
   827  }
   828  
   829  // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash
   830  func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
   831  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
   832  		n := hexutil.Uint(len(block.Uncles()))
   833  		return &n
   834  	}
   835  	return nil
   836  }
   837  
   838  // GetCode returns the code stored at the given address in the state for the given block number.
   839  func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
   840  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   841  	if state == nil || err != nil {
   842  		return nil, err
   843  	}
   844  	code := state.GetCode(address)
   845  	return code, state.Error()
   846  }
   847  
   848  // GetStorageAt returns the storage from the state at the given address, key and
   849  // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
   850  // numbers are also allowed.
   851  func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
   852  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   853  	if state == nil || err != nil {
   854  		return nil, err
   855  	}
   856  	res := state.GetState(address, common.HexToHash(key))
   857  	return res[:], state.Error()
   858  }
   859  
   860  // OverrideAccount indicates the overriding fields of account during the execution
   861  // of a message call.
   862  // Note, state and stateDiff can't be specified at the same time. If state is
   863  // set, message execution will only use the data in the given state. Otherwise
   864  // if statDiff is set, all diff will be applied first and then execute the call
   865  // message.
   866  type OverrideAccount struct {
   867  	Nonce     *hexutil.Uint64              `json:"nonce"`
   868  	Code      *hexutil.Bytes               `json:"code"`
   869  	Balance   **hexutil.Big                `json:"balance"`
   870  	State     *map[common.Hash]common.Hash `json:"state"`
   871  	StateDiff *map[common.Hash]common.Hash `json:"stateDiff"`
   872  }
   873  
   874  // StateOverride is the collection of overridden accounts.
   875  type StateOverride map[common.Address]OverrideAccount
   876  
   877  // Apply overrides the fields of specified accounts into the given state.
   878  func (diff *StateOverride) Apply(state *state.StateDB) error {
   879  	if diff == nil {
   880  		return nil
   881  	}
   882  	for addr, account := range *diff {
   883  		// Override account nonce.
   884  		if account.Nonce != nil {
   885  			state.SetNonce(addr, uint64(*account.Nonce))
   886  		}
   887  		// Override account(contract) code.
   888  		if account.Code != nil {
   889  			state.SetCode(addr, *account.Code)
   890  		}
   891  		// Override account balance.
   892  		if account.Balance != nil {
   893  			state.SetBalance(addr, (*big.Int)(*account.Balance))
   894  		}
   895  		if account.State != nil && account.StateDiff != nil {
   896  			return fmt.Errorf("account %s has both 'state' and 'stateDiff'", addr.Hex())
   897  		}
   898  		// Replace entire state if caller requires.
   899  		if account.State != nil {
   900  			state.SetStorage(addr, *account.State)
   901  		}
   902  		// Apply state diff into specified accounts.
   903  		if account.StateDiff != nil {
   904  			for key, value := range *account.StateDiff {
   905  				state.SetState(addr, key, value)
   906  			}
   907  		}
   908  	}
   909  	return nil
   910  }
   911  
   912  func DoCall(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *StateOverride, timeout time.Duration, globalGasCap uint64) (*core.ExecutionResult, error) {
   913  	defer func(start time.Time) { log.Debug("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now())
   914  
   915  	state, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   916  	if state == nil || err != nil {
   917  		return nil, err
   918  	}
   919  	if err := overrides.Apply(state); err != nil {
   920  		return nil, err
   921  	}
   922  	// If the request is for the pending block, set the block timestamp to the current time
   923  	// so that timing assumptions will behave as if a new block were issued.
   924  	if blkNumber, isNum := blockNrOrHash.Number(); isNum && blkNumber == rpc.PendingBlockNumber {
   925  		// Override header with a copy to ensure the original header is not modified
   926  		header = types.CopyHeader(header)
   927  		header.Time = uint64(time.Now().Unix())
   928  		header.Number = new(big.Int).Add(header.Number, big.NewInt(1))
   929  	}
   930  
   931  	// Setup context so it may be cancelled the call has completed
   932  	// or, in case of unmetered gas, setup a context with a timeout.
   933  	var cancel context.CancelFunc
   934  	if timeout > 0 {
   935  		ctx, cancel = context.WithTimeout(ctx, timeout)
   936  	} else {
   937  		ctx, cancel = context.WithCancel(ctx)
   938  	}
   939  	// Make sure the context is cancelled when the call has completed
   940  	// this makes sure resources are cleaned up.
   941  	defer cancel()
   942  
   943  	// Get a new instance of the EVM.
   944  	msg, err := args.ToMessage(globalGasCap, header.BaseFee)
   945  	if err != nil {
   946  		return nil, err
   947  	}
   948  	evm, vmError, err := b.GetEVM(ctx, msg, state, header, &vm.Config{NoBaseFee: true})
   949  	if err != nil {
   950  		return nil, err
   951  	}
   952  	// Wait for the context to be done and cancel the evm. Even if the
   953  	// EVM has finished, cancelling may be done (repeatedly)
   954  	go func() {
   955  		<-ctx.Done()
   956  		evm.Cancel()
   957  	}()
   958  
   959  	// Execute the message.
   960  	gp := new(core.GasPool).AddGas(math.MaxUint64)
   961  	result, err := core.ApplyMessage(evm, msg, gp)
   962  	if err := vmError(); err != nil {
   963  		return nil, err
   964  	}
   965  
   966  	// If the timer caused an abort, return an appropriate error message
   967  	if evm.Cancelled() {
   968  		return nil, fmt.Errorf("execution aborted (timeout = %v)", timeout)
   969  	}
   970  	if err != nil {
   971  		return result, fmt.Errorf("err: %w (supplied gas %d)", err, msg.Gas())
   972  	}
   973  	return result, nil
   974  }
   975  
   976  func newRevertError(result *core.ExecutionResult) *revertError {
   977  	reason, errUnpack := abi.UnpackRevert(result.Revert())
   978  	err := errors.New("execution reverted")
   979  	if errUnpack == nil {
   980  		err = fmt.Errorf("execution reverted: %v", reason)
   981  	}
   982  	return &revertError{
   983  		error:  err,
   984  		reason: hexutil.Encode(result.Revert()),
   985  	}
   986  }
   987  
   988  // revertError is an API error that encompassas an EVM revertal with JSON error
   989  // code and a binary data blob.
   990  type revertError struct {
   991  	error
   992  	reason string // revert reason hex encoded
   993  }
   994  
   995  // ErrorCode returns the JSON error code for a revertal.
   996  // See: https://github.com/ethereum/wiki/wiki/JSON-RPC-Error-Codes-Improvement-Proposal
   997  func (e *revertError) ErrorCode() int {
   998  	return 3
   999  }
  1000  
  1001  // ErrorData returns the hex encoded revert reason.
  1002  func (e *revertError) ErrorData() interface{} {
  1003  	return e.reason
  1004  }
  1005  
  1006  // Call executes the given transaction on the state for the given block number.
  1007  //
  1008  // Additionally, the caller can specify a batch of contract for fields overriding.
  1009  //
  1010  // Note, this function doesn't make and changes in the state/blockchain and is
  1011  // useful to execute and retrieve values.
  1012  func (s *PublicBlockChainAPI) Call(ctx context.Context, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *StateOverride) (hexutil.Bytes, error) {
  1013  	result, err := DoCall(ctx, s.b, args, blockNrOrHash, overrides, 5*time.Second, s.b.RPCGasCap())
  1014  	if err != nil {
  1015  		return nil, err
  1016  	}
  1017  	// If the result contains a revert reason, try to unpack and return it.
  1018  	if len(result.Revert()) > 0 {
  1019  		return nil, newRevertError(result)
  1020  	}
  1021  	return result.Return(), result.Err
  1022  }
  1023  
  1024  func DoEstimateGas(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, gasCap uint64) (hexutil.Uint64, error) {
  1025  	// Binary search the gas requirement, as it may be higher than the amount used
  1026  	var (
  1027  		lo  uint64 = params.TxGas - 1
  1028  		hi  uint64
  1029  		cap uint64
  1030  	)
  1031  	// Use zero address if sender unspecified.
  1032  	if args.From == nil {
  1033  		args.From = new(common.Address)
  1034  	}
  1035  	// Determine the highest gas limit can be used during the estimation.
  1036  	if args.Gas != nil && uint64(*args.Gas) >= params.TxGas {
  1037  		hi = uint64(*args.Gas)
  1038  	} else {
  1039  		// Retrieve the block to act as the gas ceiling
  1040  		block, err := b.BlockByNumberOrHash(ctx, blockNrOrHash)
  1041  		if err != nil {
  1042  			return 0, err
  1043  		}
  1044  		if block == nil {
  1045  			return 0, errors.New("block not found")
  1046  		}
  1047  		hi = block.GasLimit()
  1048  	}
  1049  	// Normalize the max fee per gas the call is willing to spend.
  1050  	var feeCap *big.Int
  1051  	if args.GasPrice != nil && (args.MaxFeePerGas != nil || args.MaxPriorityFeePerGas != nil) {
  1052  		return 0, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")
  1053  	} else if args.GasPrice != nil {
  1054  		feeCap = args.GasPrice.ToInt()
  1055  	} else if args.MaxFeePerGas != nil {
  1056  		feeCap = args.MaxFeePerGas.ToInt()
  1057  	} else {
  1058  		feeCap = common.Big0
  1059  	}
  1060  	// Recap the highest gas limit with account's available balance.
  1061  	if feeCap.BitLen() != 0 {
  1062  		state, _, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1063  		if err != nil {
  1064  			return 0, err
  1065  		}
  1066  		balance := state.GetBalance(*args.From) // from can't be nil
  1067  		available := new(big.Int).Set(balance)
  1068  		if args.Value != nil {
  1069  			if args.Value.ToInt().Cmp(available) >= 0 {
  1070  				return 0, errors.New("insufficient funds for transfer")
  1071  			}
  1072  			available.Sub(available, args.Value.ToInt())
  1073  		}
  1074  		allowance := new(big.Int).Div(available, feeCap)
  1075  
  1076  		// If the allowance is larger than maximum uint64, skip checking
  1077  		if allowance.IsUint64() && hi > allowance.Uint64() {
  1078  			transfer := args.Value
  1079  			if transfer == nil {
  1080  				transfer = new(hexutil.Big)
  1081  			}
  1082  			log.Warn("Gas estimation capped by limited funds", "original", hi, "balance", balance,
  1083  				"sent", transfer.ToInt(), "maxFeePerGas", feeCap, "fundable", allowance)
  1084  			hi = allowance.Uint64()
  1085  		}
  1086  	}
  1087  	// Recap the highest gas allowance with specified gascap.
  1088  	if gasCap != 0 && hi > gasCap {
  1089  		log.Warn("Caller gas above allowance, capping", "requested", hi, "cap", gasCap)
  1090  		hi = gasCap
  1091  	}
  1092  	cap = hi
  1093  
  1094  	// Create a helper to check if a gas allowance results in an executable transaction
  1095  	executable := func(gas uint64) (bool, *core.ExecutionResult, error) {
  1096  		args.Gas = (*hexutil.Uint64)(&gas)
  1097  
  1098  		result, err := DoCall(ctx, b, args, blockNrOrHash, nil, 0, gasCap)
  1099  		if err != nil {
  1100  			if errors.Is(err, core.ErrIntrinsicGas) {
  1101  				return true, nil, nil // Special case, raise gas limit
  1102  			}
  1103  			return true, nil, err // Bail out
  1104  		}
  1105  		return result.Failed(), result, nil
  1106  	}
  1107  	// Execute the binary search and hone in on an executable gas limit
  1108  	for lo+1 < hi {
  1109  		mid := (hi + lo) / 2
  1110  		failed, _, err := executable(mid)
  1111  
  1112  		// If the error is not nil(consensus error), it means the provided message
  1113  		// call or transaction will never be accepted no matter how much gas it is
  1114  		// assigned. Return the error directly, don't struggle any more.
  1115  		if err != nil {
  1116  			return 0, err
  1117  		}
  1118  		if failed {
  1119  			lo = mid
  1120  		} else {
  1121  			hi = mid
  1122  		}
  1123  	}
  1124  	// Reject the transaction as invalid if it still fails at the highest allowance
  1125  	if hi == cap {
  1126  		failed, result, err := executable(hi)
  1127  		if err != nil {
  1128  			return 0, err
  1129  		}
  1130  		if failed {
  1131  			if result != nil && result.Err != vm.ErrOutOfGas {
  1132  				if len(result.Revert()) > 0 {
  1133  					return 0, newRevertError(result)
  1134  				}
  1135  				return 0, result.Err
  1136  			}
  1137  			// Otherwise, the specified gas cap is too low
  1138  			return 0, fmt.Errorf("gas required exceeds allowance (%d)", cap)
  1139  		}
  1140  	}
  1141  	return hexutil.Uint64(hi), nil
  1142  }
  1143  
  1144  // EstimateGas returns an estimate of the amount of gas needed to execute the
  1145  // given transaction against the current pending block.
  1146  func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args TransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash) (hexutil.Uint64, error) {
  1147  	bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
  1148  	if blockNrOrHash != nil {
  1149  		bNrOrHash = *blockNrOrHash
  1150  	}
  1151  	return DoEstimateGas(ctx, s.b, args, bNrOrHash, s.b.RPCGasCap())
  1152  }
  1153  
  1154  // ExecutionResult groups all structured logs emitted by the EVM
  1155  // while replaying a transaction in debug mode as well as transaction
  1156  // execution status, the amount of gas used and the return value
  1157  type ExecutionResult struct {
  1158  	Gas         uint64         `json:"gas"`
  1159  	Failed      bool           `json:"failed"`
  1160  	ReturnValue string         `json:"returnValue"`
  1161  	StructLogs  []StructLogRes `json:"structLogs"`
  1162  }
  1163  
  1164  // StructLogRes stores a structured log emitted by the EVM while replaying a
  1165  // transaction in debug mode
  1166  type StructLogRes struct {
  1167  	Pc      uint64             `json:"pc"`
  1168  	Op      string             `json:"op"`
  1169  	Gas     uint64             `json:"gas"`
  1170  	GasCost uint64             `json:"gasCost"`
  1171  	Depth   int                `json:"depth"`
  1172  	Error   string             `json:"error,omitempty"`
  1173  	Stack   *[]string          `json:"stack,omitempty"`
  1174  	Memory  *[]string          `json:"memory,omitempty"`
  1175  	Storage *map[string]string `json:"storage,omitempty"`
  1176  }
  1177  
  1178  // FormatLogs formats EVM returned structured logs for json output
  1179  func FormatLogs(logs []vm.StructLog) []StructLogRes {
  1180  	formatted := make([]StructLogRes, len(logs))
  1181  	for index, trace := range logs {
  1182  		formatted[index] = StructLogRes{
  1183  			Pc:      trace.Pc,
  1184  			Op:      trace.Op.String(),
  1185  			Gas:     trace.Gas,
  1186  			GasCost: trace.GasCost,
  1187  			Depth:   trace.Depth,
  1188  			Error:   trace.ErrorString(),
  1189  		}
  1190  		if trace.Stack != nil {
  1191  			stack := make([]string, len(trace.Stack))
  1192  			for i, stackValue := range trace.Stack {
  1193  				stack[i] = stackValue.Hex()
  1194  			}
  1195  			formatted[index].Stack = &stack
  1196  		}
  1197  		if trace.Memory != nil {
  1198  			memory := make([]string, 0, (len(trace.Memory)+31)/32)
  1199  			for i := 0; i+32 <= len(trace.Memory); i += 32 {
  1200  				memory = append(memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
  1201  			}
  1202  			formatted[index].Memory = &memory
  1203  		}
  1204  		if trace.Storage != nil {
  1205  			storage := make(map[string]string)
  1206  			for i, storageValue := range trace.Storage {
  1207  				storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
  1208  			}
  1209  			formatted[index].Storage = &storage
  1210  		}
  1211  	}
  1212  	return formatted
  1213  }
  1214  
  1215  // RPCMarshalHeader converts the given header to the RPC output .
  1216  func RPCMarshalHeader(head *types.Header) map[string]interface{} {
  1217  	result := map[string]interface{}{
  1218  		"number":           (*hexutil.Big)(head.Number),
  1219  		"hash":             head.Hash(),
  1220  		"parentHash":       head.ParentHash,
  1221  		"nonce":            head.Nonce,
  1222  		"mixHash":          head.MixDigest,
  1223  		"sha3Uncles":       head.UncleHash,
  1224  		"logsBloom":        head.Bloom,
  1225  		"stateRoot":        head.Root,
  1226  		"miner":            head.Coinbase,
  1227  		"difficulty":       (*hexutil.Big)(head.Difficulty),
  1228  		"extraData":        hexutil.Bytes(head.Extra),
  1229  		"size":             hexutil.Uint64(head.Size()),
  1230  		"gasLimit":         hexutil.Uint64(head.GasLimit),
  1231  		"gasUsed":          hexutil.Uint64(head.GasUsed),
  1232  		"timestamp":        hexutil.Uint64(head.Time),
  1233  		"transactionsRoot": head.TxHash,
  1234  		"receiptsRoot":     head.ReceiptHash,
  1235  		"extDataHash":      head.ExtDataHash,
  1236  	}
  1237  
  1238  	if head.BaseFee != nil {
  1239  		result["baseFeePerGas"] = (*hexutil.Big)(head.BaseFee)
  1240  	}
  1241  
  1242  	return result
  1243  }
  1244  
  1245  // RPCMarshalBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
  1246  // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
  1247  // transaction hashes.
  1248  func RPCMarshalBlock(block *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  1249  	fields := RPCMarshalHeader(block.Header())
  1250  	fields["size"] = hexutil.Uint64(block.Size())
  1251  	fields["blockExtraData"] = hexutil.Bytes(block.ExtData())
  1252  
  1253  	if inclTx {
  1254  		formatTx := func(tx *types.Transaction) (interface{}, error) {
  1255  			return tx.Hash(), nil
  1256  		}
  1257  		if fullTx {
  1258  			formatTx = func(tx *types.Transaction) (interface{}, error) {
  1259  				return newRPCTransactionFromBlockHash(block, tx.Hash()), nil
  1260  			}
  1261  		}
  1262  		txs := block.Transactions()
  1263  		transactions := make([]interface{}, len(txs))
  1264  		var err error
  1265  		for i, tx := range txs {
  1266  			if transactions[i], err = formatTx(tx); err != nil {
  1267  				return nil, err
  1268  			}
  1269  		}
  1270  		fields["transactions"] = transactions
  1271  	}
  1272  	uncles := block.Uncles()
  1273  	uncleHashes := make([]common.Hash, len(uncles))
  1274  	for i, uncle := range uncles {
  1275  		uncleHashes[i] = uncle.Hash()
  1276  	}
  1277  	fields["uncles"] = uncleHashes
  1278  
  1279  	return fields, nil
  1280  }
  1281  
  1282  // rpcMarshalHeader uses the generalized output filler, then adds the total difficulty field, which requires
  1283  // a `PublicBlockchainAPI`.
  1284  func (s *PublicBlockChainAPI) rpcMarshalHeader(ctx context.Context, header *types.Header) map[string]interface{} {
  1285  	fields := RPCMarshalHeader(header)
  1286  	fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(ctx, header.Hash()))
  1287  	return fields
  1288  }
  1289  
  1290  // rpcMarshalBlock uses the generalized output filler, then adds the total difficulty field, which requires
  1291  // a `PublicBlockchainAPI`.
  1292  func (s *PublicBlockChainAPI) rpcMarshalBlock(ctx context.Context, b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  1293  	fields, err := RPCMarshalBlock(b, inclTx, fullTx)
  1294  	if err != nil {
  1295  		return nil, err
  1296  	}
  1297  	if inclTx {
  1298  		fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(ctx, b.Hash()))
  1299  	}
  1300  	return fields, err
  1301  }
  1302  
  1303  // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
  1304  type RPCTransaction struct {
  1305  	BlockHash        *common.Hash      `json:"blockHash"`
  1306  	BlockNumber      *hexutil.Big      `json:"blockNumber"`
  1307  	From             common.Address    `json:"from"`
  1308  	Gas              hexutil.Uint64    `json:"gas"`
  1309  	GasPrice         *hexutil.Big      `json:"gasPrice"`
  1310  	GasFeeCap        *hexutil.Big      `json:"maxFeePerGas,omitempty"`
  1311  	GasTipCap        *hexutil.Big      `json:"maxPriorityFeePerGas,omitempty"`
  1312  	Hash             common.Hash       `json:"hash"`
  1313  	Input            hexutil.Bytes     `json:"input"`
  1314  	Nonce            hexutil.Uint64    `json:"nonce"`
  1315  	To               *common.Address   `json:"to"`
  1316  	TransactionIndex *hexutil.Uint64   `json:"transactionIndex"`
  1317  	Value            *hexutil.Big      `json:"value"`
  1318  	Type             hexutil.Uint64    `json:"type"`
  1319  	Accesses         *types.AccessList `json:"accessList,omitempty"`
  1320  	ChainID          *hexutil.Big      `json:"chainId,omitempty"`
  1321  	V                *hexutil.Big      `json:"v"`
  1322  	R                *hexutil.Big      `json:"r"`
  1323  	S                *hexutil.Big      `json:"s"`
  1324  }
  1325  
  1326  // newRPCTransaction returns a transaction that will serialize to the RPC
  1327  // representation, with the given location metadata set (if available).
  1328  func newRPCTransaction(tx *types.Transaction, blockHash common.Hash, blockNumber uint64, index uint64, baseFee *big.Int) *RPCTransaction {
  1329  	// Determine the signer. For replay-protected transactions, use the most permissive
  1330  	// signer, because we assume that signers are backwards-compatible with old
  1331  	// transactions. For non-protected transactions, the homestead signer signer is used
  1332  	// because the return value of ChainId is zero for those transactions.
  1333  	var signer types.Signer
  1334  	if tx.Protected() {
  1335  		signer = types.LatestSignerForChainID(tx.ChainId())
  1336  	} else {
  1337  		signer = types.HomesteadSigner{}
  1338  	}
  1339  	from, _ := types.Sender(signer, tx)
  1340  	v, r, s := tx.RawSignatureValues()
  1341  	result := &RPCTransaction{
  1342  		Type:     hexutil.Uint64(tx.Type()),
  1343  		From:     from,
  1344  		Gas:      hexutil.Uint64(tx.Gas()),
  1345  		GasPrice: (*hexutil.Big)(tx.GasPrice()),
  1346  		Hash:     tx.Hash(),
  1347  		Input:    hexutil.Bytes(tx.Data()),
  1348  		Nonce:    hexutil.Uint64(tx.Nonce()),
  1349  		To:       tx.To(),
  1350  		Value:    (*hexutil.Big)(tx.Value()),
  1351  		V:        (*hexutil.Big)(v),
  1352  		R:        (*hexutil.Big)(r),
  1353  		S:        (*hexutil.Big)(s),
  1354  	}
  1355  	if blockHash != (common.Hash{}) {
  1356  		result.BlockHash = &blockHash
  1357  		result.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(blockNumber))
  1358  		result.TransactionIndex = (*hexutil.Uint64)(&index)
  1359  	}
  1360  	switch tx.Type() {
  1361  	case types.AccessListTxType:
  1362  		al := tx.AccessList()
  1363  		result.Accesses = &al
  1364  		result.ChainID = (*hexutil.Big)(tx.ChainId())
  1365  	case types.DynamicFeeTxType:
  1366  		al := tx.AccessList()
  1367  		result.Accesses = &al
  1368  		result.ChainID = (*hexutil.Big)(tx.ChainId())
  1369  		result.GasFeeCap = (*hexutil.Big)(tx.GasFeeCap())
  1370  		result.GasTipCap = (*hexutil.Big)(tx.GasTipCap())
  1371  		// if the transaction has been mined, compute the effective gas price
  1372  		if baseFee != nil && blockHash != (common.Hash{}) {
  1373  			// price = min(tip, gasFeeCap - baseFee) + baseFee
  1374  			price := math.BigMin(new(big.Int).Add(tx.GasTipCap(), baseFee), tx.GasFeeCap())
  1375  			result.GasPrice = (*hexutil.Big)(price)
  1376  		} else {
  1377  			result.GasPrice = (*hexutil.Big)(tx.GasFeeCap())
  1378  		}
  1379  	}
  1380  	return result
  1381  }
  1382  
  1383  // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation
  1384  func newRPCPendingTransaction(tx *types.Transaction, current *types.Header, config *params.ChainConfig) *RPCTransaction {
  1385  	var baseFee *big.Int
  1386  	if current != nil {
  1387  		// TODO(aaronbuchwald) apply when CalcBaseFee has been migrated into coreth
  1388  		// baseFee = misc.CalcBaseFee(config, current)
  1389  	}
  1390  	return newRPCTransaction(tx, common.Hash{}, 0, 0, baseFee)
  1391  }
  1392  
  1393  // newRPCTransactionFromBlockIndex returns a transaction that will serialize to the RPC representation.
  1394  func newRPCTransactionFromBlockIndex(b *types.Block, index uint64) *RPCTransaction {
  1395  	txs := b.Transactions()
  1396  	if index >= uint64(len(txs)) {
  1397  		return nil
  1398  	}
  1399  	return newRPCTransaction(txs[index], b.Hash(), b.NumberU64(), index, b.BaseFee())
  1400  }
  1401  
  1402  // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index.
  1403  func newRPCRawTransactionFromBlockIndex(b *types.Block, index uint64) hexutil.Bytes {
  1404  	txs := b.Transactions()
  1405  	if index >= uint64(len(txs)) {
  1406  		return nil
  1407  	}
  1408  	blob, _ := txs[index].MarshalBinary()
  1409  	return blob
  1410  }
  1411  
  1412  // newRPCTransactionFromBlockHash returns a transaction that will serialize to the RPC representation.
  1413  func newRPCTransactionFromBlockHash(b *types.Block, hash common.Hash) *RPCTransaction {
  1414  	for idx, tx := range b.Transactions() {
  1415  		if tx.Hash() == hash {
  1416  			return newRPCTransactionFromBlockIndex(b, uint64(idx))
  1417  		}
  1418  	}
  1419  	return nil
  1420  }
  1421  
  1422  // accessListResult returns an optional accesslist
  1423  // Its the result of the `debug_createAccessList` RPC call.
  1424  // It contains an error if the transaction itself failed.
  1425  type accessListResult struct {
  1426  	Accesslist *types.AccessList `json:"accessList"`
  1427  	Error      string            `json:"error,omitempty"`
  1428  	GasUsed    hexutil.Uint64    `json:"gasUsed"`
  1429  }
  1430  
  1431  // CreateAccessList creates a EIP-2930 type AccessList for the given transaction.
  1432  // Reexec and BlockNrOrHash can be specified to create the accessList on top of a certain state.
  1433  func (s *PublicBlockChainAPI) CreateAccessList(ctx context.Context, args TransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash) (*accessListResult, error) {
  1434  	bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
  1435  	if blockNrOrHash != nil {
  1436  		bNrOrHash = *blockNrOrHash
  1437  	}
  1438  	acl, gasUsed, vmerr, err := AccessList(ctx, s.b, bNrOrHash, args)
  1439  	if err != nil {
  1440  		return nil, err
  1441  	}
  1442  	result := &accessListResult{Accesslist: &acl, GasUsed: hexutil.Uint64(gasUsed)}
  1443  	if vmerr != nil {
  1444  		result.Error = vmerr.Error()
  1445  	}
  1446  	return result, nil
  1447  }
  1448  
  1449  // AccessList creates an access list for the given transaction.
  1450  // If the accesslist creation fails an error is returned.
  1451  // If the transaction itself fails, an vmErr is returned.
  1452  func AccessList(ctx context.Context, b Backend, blockNrOrHash rpc.BlockNumberOrHash, args TransactionArgs) (acl types.AccessList, gasUsed uint64, vmErr error, err error) {
  1453  	// Retrieve the execution context
  1454  	db, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1455  	if db == nil || err != nil {
  1456  		return nil, 0, nil, err
  1457  	}
  1458  	// If the gas amount is not set, extract this as it will depend on access
  1459  	// lists and we'll need to reestimate every time
  1460  	nogas := args.Gas == nil
  1461  
  1462  	// Ensure any missing fields are filled, extract the recipient and input data
  1463  	if err := args.setDefaults(ctx, b); err != nil {
  1464  		return nil, 0, nil, err
  1465  	}
  1466  	var to common.Address
  1467  	if args.To != nil {
  1468  		to = *args.To
  1469  	} else {
  1470  		to = crypto.CreateAddress(args.from(), uint64(*args.Nonce))
  1471  	}
  1472  	// Retrieve the precompiles since they don't need to be added to the access list
  1473  	precompiles := vm.ActivePrecompiles(b.ChainConfig().AvalancheRules(header.Number, new(big.Int).SetUint64(header.Time)))
  1474  
  1475  	// Create an initial tracer
  1476  	prevTracer := vm.NewAccessListTracer(nil, args.from(), to, precompiles)
  1477  	if args.AccessList != nil {
  1478  		prevTracer = vm.NewAccessListTracer(*args.AccessList, args.from(), to, precompiles)
  1479  	}
  1480  	for {
  1481  		// Retrieve the current access list to expand
  1482  		accessList := prevTracer.AccessList()
  1483  		log.Trace("Creating access list", "input", accessList)
  1484  
  1485  		// If no gas amount was specified, each unique access list needs it's own
  1486  		// gas calculation. This is quite expensive, but we need to be accurate
  1487  		// and it's convered by the sender only anyway.
  1488  		if nogas {
  1489  			args.Gas = nil
  1490  			if err := args.setDefaults(ctx, b); err != nil {
  1491  				return nil, 0, nil, err // shouldn't happen, just in case
  1492  			}
  1493  		}
  1494  		// Copy the original db so we don't modify it
  1495  		statedb := db.Copy()
  1496  		// Set the access list tracer to the last al
  1497  
  1498  		args.AccessList = &accessList
  1499  		msg, err := args.ToMessage(b.RPCGasCap(), header.BaseFee)
  1500  		if err != nil {
  1501  			return nil, 0, nil, err
  1502  		}
  1503  
  1504  		// Apply the transaction with the access list tracer
  1505  		tracer := vm.NewAccessListTracer(accessList, args.from(), to, precompiles)
  1506  		config := vm.Config{Tracer: tracer, Debug: true, NoBaseFee: true}
  1507  		vmenv, _, err := b.GetEVM(ctx, msg, statedb, header, &config)
  1508  		if err != nil {
  1509  			return nil, 0, nil, err
  1510  		}
  1511  		res, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas()))
  1512  		if err != nil {
  1513  			return nil, 0, nil, fmt.Errorf("failed to apply transaction: %v err: %v", args.toTransaction().Hash(), err)
  1514  		}
  1515  		if tracer.Equal(prevTracer) {
  1516  			return accessList, res.UsedGas, res.Err, nil
  1517  		}
  1518  		prevTracer = tracer
  1519  	}
  1520  }
  1521  
  1522  // PublicTransactionPoolAPI exposes methods for the RPC interface
  1523  type PublicTransactionPoolAPI struct {
  1524  	b         Backend
  1525  	nonceLock *AddrLocker
  1526  	signer    types.Signer
  1527  }
  1528  
  1529  // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.
  1530  func NewPublicTransactionPoolAPI(b Backend, nonceLock *AddrLocker) *PublicTransactionPoolAPI {
  1531  	// The signer used by the API should always be the 'latest' known one because we expect
  1532  	// signers to be backwards-compatible with old transactions.
  1533  	signer := types.LatestSigner(b.ChainConfig())
  1534  	return &PublicTransactionPoolAPI{b, nonceLock, signer}
  1535  }
  1536  
  1537  // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
  1538  func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  1539  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1540  		n := hexutil.Uint(len(block.Transactions()))
  1541  		return &n
  1542  	}
  1543  	return nil
  1544  }
  1545  
  1546  // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
  1547  func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  1548  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1549  		n := hexutil.Uint(len(block.Transactions()))
  1550  		return &n
  1551  	}
  1552  	return nil
  1553  }
  1554  
  1555  // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
  1556  func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) *RPCTransaction {
  1557  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1558  		return newRPCTransactionFromBlockIndex(block, uint64(index))
  1559  	}
  1560  	return nil
  1561  }
  1562  
  1563  // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
  1564  func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) *RPCTransaction {
  1565  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1566  		return newRPCTransactionFromBlockIndex(block, uint64(index))
  1567  	}
  1568  	return nil
  1569  }
  1570  
  1571  // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
  1572  func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) hexutil.Bytes {
  1573  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1574  		return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1575  	}
  1576  	return nil
  1577  }
  1578  
  1579  // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index.
  1580  func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) hexutil.Bytes {
  1581  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1582  		return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1583  	}
  1584  	return nil
  1585  }
  1586  
  1587  // GetTransactionCount returns the number of transactions the given address has sent for the given block number
  1588  func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Uint64, error) {
  1589  	// Ask transaction pool for the nonce which includes pending transactions
  1590  	if blockNr, ok := blockNrOrHash.Number(); ok && blockNr == rpc.PendingBlockNumber {
  1591  		nonce, err := s.b.GetPoolNonce(ctx, address)
  1592  		if err != nil {
  1593  			return nil, err
  1594  		}
  1595  		return (*hexutil.Uint64)(&nonce), nil
  1596  	}
  1597  	// Resolve block number and use its state to ask for the nonce
  1598  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1599  	if state == nil || err != nil {
  1600  		return nil, err
  1601  	}
  1602  	nonce := state.GetNonce(address)
  1603  	return (*hexutil.Uint64)(&nonce), state.Error()
  1604  }
  1605  
  1606  // GetTransactionByHash returns the transaction for the given hash
  1607  func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) (*RPCTransaction, error) {
  1608  	// Try to return an already finalized transaction
  1609  	tx, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1610  	if err != nil {
  1611  		return nil, err
  1612  	}
  1613  	if tx != nil {
  1614  		header, err := s.b.HeaderByHash(ctx, blockHash)
  1615  		if err != nil {
  1616  			return nil, err
  1617  		}
  1618  		return newRPCTransaction(tx, blockHash, blockNumber, index, header.BaseFee), nil
  1619  	}
  1620  	// No finalized transaction, try to retrieve it from the pool
  1621  	if tx := s.b.GetPoolTransaction(hash); tx != nil {
  1622  		return newRPCPendingTransaction(tx, s.b.CurrentHeader(), s.b.ChainConfig()), nil
  1623  	}
  1624  
  1625  	// Transaction unknown, return as such
  1626  	return nil, nil
  1627  }
  1628  
  1629  // GetRawTransactionByHash returns the bytes of the transaction for the given hash.
  1630  func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  1631  	// Retrieve a finalized transaction, or a pooled otherwise
  1632  	tx, _, _, _, err := s.b.GetTransaction(ctx, hash)
  1633  	if err != nil {
  1634  		return nil, err
  1635  	}
  1636  	if tx == nil {
  1637  		if tx = s.b.GetPoolTransaction(hash); tx == nil {
  1638  			// Transaction not found anywhere, abort
  1639  			return nil, nil
  1640  		}
  1641  	}
  1642  	// Serialize to RLP and return
  1643  	return tx.MarshalBinary()
  1644  }
  1645  
  1646  // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  1647  func (s *PublicTransactionPoolAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) {
  1648  	tx, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1649  	if err != nil {
  1650  		return nil, nil
  1651  	}
  1652  	header, err := s.b.HeaderByHash(ctx, blockHash)
  1653  	if err != nil {
  1654  		return nil, err
  1655  	}
  1656  	receipts, err := s.b.GetReceipts(ctx, blockHash)
  1657  	if err != nil {
  1658  		return nil, err
  1659  	}
  1660  	if len(receipts) <= int(index) {
  1661  		return nil, nil
  1662  	}
  1663  	receipt := receipts[index]
  1664  
  1665  	// Derive the sender.
  1666  	bigblock := new(big.Int).SetUint64(blockNumber)
  1667  	timestamp := new(big.Int).SetUint64(header.Time)
  1668  	signer := types.MakeSigner(s.b.ChainConfig(), bigblock, timestamp)
  1669  	from, _ := types.Sender(signer, tx)
  1670  
  1671  	fields := map[string]interface{}{
  1672  		"blockHash":         blockHash,
  1673  		"blockNumber":       hexutil.Uint64(blockNumber),
  1674  		"transactionHash":   hash,
  1675  		"transactionIndex":  hexutil.Uint64(index),
  1676  		"from":              from,
  1677  		"to":                tx.To(),
  1678  		"gasUsed":           hexutil.Uint64(receipt.GasUsed),
  1679  		"cumulativeGasUsed": hexutil.Uint64(receipt.CumulativeGasUsed),
  1680  		"contractAddress":   nil,
  1681  		"logs":              receipt.Logs,
  1682  		"logsBloom":         receipt.Bloom,
  1683  		"type":              hexutil.Uint(tx.Type()),
  1684  	}
  1685  	// Assign the effective gas price paid
  1686  	if !s.b.ChainConfig().IsApricotPhase3(timestamp) {
  1687  		fields["effectiveGasPrice"] = hexutil.Uint64(tx.GasPrice().Uint64())
  1688  	} else {
  1689  		header, err := s.b.HeaderByHash(ctx, blockHash)
  1690  		if err != nil {
  1691  			return nil, err
  1692  		}
  1693  		gasPrice := new(big.Int).Add(header.BaseFee, tx.EffectiveGasTipValue(header.BaseFee))
  1694  		fields["effectiveGasPrice"] = hexutil.Uint64(gasPrice.Uint64())
  1695  	}
  1696  	// Assign receipt status or post state.
  1697  	if len(receipt.PostState) > 0 {
  1698  		fields["root"] = hexutil.Bytes(receipt.PostState)
  1699  	} else {
  1700  		fields["status"] = hexutil.Uint(receipt.Status)
  1701  	}
  1702  	if receipt.Logs == nil {
  1703  		fields["logs"] = [][]*types.Log{}
  1704  	}
  1705  	// If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  1706  	if receipt.ContractAddress != (common.Address{}) {
  1707  		fields["contractAddress"] = receipt.ContractAddress
  1708  	}
  1709  	return fields, nil
  1710  }
  1711  
  1712  // sign is a helper function that signs a transaction with the private key of the given address.
  1713  func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
  1714  	// Look up the wallet containing the requested signer
  1715  	account := accounts.Account{Address: addr}
  1716  
  1717  	wallet, err := s.b.AccountManager().Find(account)
  1718  	if err != nil {
  1719  		return nil, err
  1720  	}
  1721  	// Request the wallet to sign the transaction
  1722  	return wallet.SignTx(account, tx, s.b.ChainConfig().ChainID)
  1723  }
  1724  
  1725  // SubmitTransaction is a helper function that submits tx to txPool and logs a message.
  1726  func SubmitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (common.Hash, error) {
  1727  	// If the transaction fee cap is already specified, ensure the
  1728  	// fee of the given transaction is _reasonable_.
  1729  	if err := checkTxFee(tx.GasPrice(), tx.Gas(), b.RPCTxFeeCap()); err != nil {
  1730  		return common.Hash{}, err
  1731  	}
  1732  	if !b.UnprotectedAllowed() && !tx.Protected() {
  1733  		// Ensure only eip155 signed transactions are submitted if EIP155Required is set.
  1734  		return common.Hash{}, errors.New("only replay-protected (EIP-155) transactions allowed over RPC")
  1735  	}
  1736  	if err := b.SendTx(ctx, tx); err != nil {
  1737  		return common.Hash{}, err
  1738  	}
  1739  	// Print a log with full tx details for manual investigations and interventions
  1740  	currentBlock := b.CurrentBlock()
  1741  	signer := types.MakeSigner(b.ChainConfig(), currentBlock.Number(), new(big.Int).SetUint64(currentBlock.Time()))
  1742  	from, err := types.Sender(signer, tx)
  1743  	if err != nil {
  1744  		return common.Hash{}, err
  1745  	}
  1746  
  1747  	if tx.To() == nil {
  1748  		addr := crypto.CreateAddress(from, tx.Nonce())
  1749  		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())
  1750  	} else {
  1751  		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())
  1752  	}
  1753  	return tx.Hash(), nil
  1754  }
  1755  
  1756  // SendTransaction creates a transaction for the given argument, sign it and submit it to the
  1757  // transaction pool.
  1758  func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args TransactionArgs) (common.Hash, error) {
  1759  	// Look up the wallet containing the requested signer
  1760  	account := accounts.Account{Address: args.from()}
  1761  
  1762  	wallet, err := s.b.AccountManager().Find(account)
  1763  	if err != nil {
  1764  		return common.Hash{}, err
  1765  	}
  1766  
  1767  	if args.Nonce == nil {
  1768  		// Hold the addresse's mutex around signing to prevent concurrent assignment of
  1769  		// the same nonce to multiple accounts.
  1770  		s.nonceLock.LockAddr(args.from())
  1771  		defer s.nonceLock.UnlockAddr(args.from())
  1772  	}
  1773  
  1774  	// Set some sanity defaults and terminate on failure
  1775  	if err := args.setDefaults(ctx, s.b); err != nil {
  1776  		return common.Hash{}, err
  1777  	}
  1778  	// Assemble the transaction and sign with the wallet
  1779  	tx := args.toTransaction()
  1780  
  1781  	signed, err := wallet.SignTx(account, tx, s.b.ChainConfig().ChainID)
  1782  	if err != nil {
  1783  		return common.Hash{}, err
  1784  	}
  1785  	return SubmitTransaction(ctx, s.b, signed)
  1786  }
  1787  
  1788  // FillTransaction fills the defaults (nonce, gas, gasPrice or 1559 fields)
  1789  // on a given unsigned transaction, and returns it to the caller for further
  1790  // processing (signing + broadcast).
  1791  func (s *PublicTransactionPoolAPI) FillTransaction(ctx context.Context, args TransactionArgs) (*SignTransactionResult, error) {
  1792  	// Set some sanity defaults and terminate on failure
  1793  	if err := args.setDefaults(ctx, s.b); err != nil {
  1794  		return nil, err
  1795  	}
  1796  	// Assemble the transaction and obtain rlp
  1797  	tx := args.toTransaction()
  1798  	data, err := tx.MarshalBinary()
  1799  	if err != nil {
  1800  		return nil, err
  1801  	}
  1802  	return &SignTransactionResult{data, tx}, nil
  1803  }
  1804  
  1805  // SendRawTransaction will add the signed transaction to the transaction pool.
  1806  // The sender is responsible for signing the transaction and using the correct nonce.
  1807  func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, input hexutil.Bytes) (common.Hash, error) {
  1808  	tx := new(types.Transaction)
  1809  	if err := tx.UnmarshalBinary(input); err != nil {
  1810  		return common.Hash{}, err
  1811  	}
  1812  	return SubmitTransaction(ctx, s.b, tx)
  1813  }
  1814  
  1815  // Sign calculates an ECDSA signature for:
  1816  // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message).
  1817  //
  1818  // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  1819  // where the V value will be 27 or 28 for legacy reasons.
  1820  //
  1821  // The account associated with addr must be unlocked.
  1822  //
  1823  // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
  1824  func (s *PublicTransactionPoolAPI) Sign(addr common.Address, data hexutil.Bytes) (hexutil.Bytes, error) {
  1825  	// Look up the wallet containing the requested signer
  1826  	account := accounts.Account{Address: addr}
  1827  
  1828  	wallet, err := s.b.AccountManager().Find(account)
  1829  	if err != nil {
  1830  		return nil, err
  1831  	}
  1832  	// Sign the requested hash with the wallet
  1833  	signature, err := wallet.SignText(account, data)
  1834  	if err == nil {
  1835  		signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  1836  	}
  1837  	return signature, err
  1838  }
  1839  
  1840  // SignTransactionResult represents a RLP encoded signed transaction.
  1841  type SignTransactionResult struct {
  1842  	Raw hexutil.Bytes      `json:"raw"`
  1843  	Tx  *types.Transaction `json:"tx"`
  1844  }
  1845  
  1846  // SignTransaction will sign the given transaction with the from account.
  1847  // The node needs to have the private key of the account corresponding with
  1848  // the given from address and it needs to be unlocked.
  1849  func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args TransactionArgs) (*SignTransactionResult, error) {
  1850  	if args.Gas == nil {
  1851  		return nil, fmt.Errorf("gas not specified")
  1852  	}
  1853  	if args.GasPrice == nil && (args.MaxPriorityFeePerGas == nil || args.MaxFeePerGas == nil) {
  1854  		return nil, fmt.Errorf("missing gasPrice or maxFeePerGas/maxPriorityFeePerGas")
  1855  	}
  1856  	if args.Nonce == nil {
  1857  		return nil, fmt.Errorf("nonce not specified")
  1858  	}
  1859  	if err := args.setDefaults(ctx, s.b); err != nil {
  1860  		return nil, err
  1861  	}
  1862  	// Before actually sign the transaction, ensure the transaction fee is reasonable.
  1863  	tx := args.toTransaction()
  1864  	if err := checkTxFee(tx.GasPrice(), tx.Gas(), s.b.RPCTxFeeCap()); err != nil {
  1865  		return nil, err
  1866  	}
  1867  	signed, err := s.sign(args.from(), tx)
  1868  	if err != nil {
  1869  		return nil, err
  1870  	}
  1871  	data, err := signed.MarshalBinary()
  1872  	if err != nil {
  1873  		return nil, err
  1874  	}
  1875  	return &SignTransactionResult{data, signed}, nil
  1876  }
  1877  
  1878  // PendingTransactions returns the transactions that are in the transaction pool
  1879  // and have a from address that is one of the accounts this node manages.
  1880  func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error) {
  1881  	pending, err := s.b.GetPoolTransactions()
  1882  	if err != nil {
  1883  		return nil, err
  1884  	}
  1885  	accounts := make(map[common.Address]struct{})
  1886  	for _, wallet := range s.b.AccountManager().Wallets() {
  1887  		for _, account := range wallet.Accounts() {
  1888  			accounts[account.Address] = struct{}{}
  1889  		}
  1890  	}
  1891  	curHeader := s.b.CurrentHeader()
  1892  	transactions := make([]*RPCTransaction, 0, len(pending))
  1893  	for _, tx := range pending {
  1894  		from, _ := types.Sender(s.signer, tx)
  1895  		if _, exists := accounts[from]; exists {
  1896  			transactions = append(transactions, newRPCPendingTransaction(tx, curHeader, s.b.ChainConfig()))
  1897  		}
  1898  	}
  1899  	return transactions, nil
  1900  }
  1901  
  1902  // Resend accepts an existing transaction and a new gas price and limit. It will remove
  1903  // the given transaction from the pool and reinsert it with the new gas price and limit.
  1904  func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs TransactionArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) {
  1905  	if sendArgs.Nonce == nil {
  1906  		return common.Hash{}, fmt.Errorf("missing transaction nonce in transaction spec")
  1907  	}
  1908  	if err := sendArgs.setDefaults(ctx, s.b); err != nil {
  1909  		return common.Hash{}, err
  1910  	}
  1911  	matchTx := sendArgs.toTransaction()
  1912  
  1913  	// Before replacing the old transaction, ensure the _new_ transaction fee is reasonable.
  1914  	var price = matchTx.GasPrice()
  1915  	if gasPrice != nil {
  1916  		price = gasPrice.ToInt()
  1917  	}
  1918  	var gas = matchTx.Gas()
  1919  	if gasLimit != nil {
  1920  		gas = uint64(*gasLimit)
  1921  	}
  1922  	if err := checkTxFee(price, gas, s.b.RPCTxFeeCap()); err != nil {
  1923  		return common.Hash{}, err
  1924  	}
  1925  	// Iterate the pending list for replacement
  1926  	pending, err := s.b.GetPoolTransactions()
  1927  	if err != nil {
  1928  		return common.Hash{}, err
  1929  	}
  1930  	for _, p := range pending {
  1931  		wantSigHash := s.signer.Hash(matchTx)
  1932  		pFrom, err := types.Sender(s.signer, p)
  1933  		if err == nil && pFrom == sendArgs.from() && s.signer.Hash(p) == wantSigHash {
  1934  			// Match. Re-sign and send the transaction.
  1935  			if gasPrice != nil && (*big.Int)(gasPrice).Sign() != 0 {
  1936  				sendArgs.GasPrice = gasPrice
  1937  			}
  1938  			if gasLimit != nil && *gasLimit != 0 {
  1939  				sendArgs.Gas = gasLimit
  1940  			}
  1941  			signedTx, err := s.sign(sendArgs.from(), sendArgs.toTransaction())
  1942  			if err != nil {
  1943  				return common.Hash{}, err
  1944  			}
  1945  			if err = s.b.SendTx(ctx, signedTx); err != nil {
  1946  				return common.Hash{}, err
  1947  			}
  1948  			return signedTx.Hash(), nil
  1949  		}
  1950  	}
  1951  	return common.Hash{}, fmt.Errorf("transaction %#x not found", matchTx.Hash())
  1952  }
  1953  
  1954  // PublicDebugAPI is the collection of Ethereum APIs exposed over the public
  1955  // debugging endpoint.
  1956  type PublicDebugAPI struct {
  1957  	b Backend
  1958  }
  1959  
  1960  // NewPublicDebugAPI creates a new API definition for the public debug methods
  1961  // of the Ethereum service.
  1962  func NewPublicDebugAPI(b Backend) *PublicDebugAPI {
  1963  	return &PublicDebugAPI{b: b}
  1964  }
  1965  
  1966  // GetBlockRlp retrieves the RLP encoded for of a single block.
  1967  func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error) {
  1968  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1969  	if block == nil {
  1970  		return "", fmt.Errorf("block #%d not found", number)
  1971  	}
  1972  	encoded, err := rlp.EncodeToBytes(block)
  1973  	if err != nil {
  1974  		return "", err
  1975  	}
  1976  	return fmt.Sprintf("%x", encoded), nil
  1977  }
  1978  
  1979  // PrintBlock retrieves a block and returns its pretty printed form.
  1980  func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) {
  1981  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1982  	if block == nil {
  1983  		return "", fmt.Errorf("block #%d not found", number)
  1984  	}
  1985  	return spew.Sdump(block), nil
  1986  }
  1987  
  1988  // PrivateDebugAPI is the collection of Ethereum APIs exposed over the private
  1989  // debugging endpoint.
  1990  type PrivateDebugAPI struct {
  1991  	b Backend
  1992  }
  1993  
  1994  // NewPrivateDebugAPI creates a new API definition for the private debug methods
  1995  // of the Ethereum service.
  1996  func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI {
  1997  	return &PrivateDebugAPI{b: b}
  1998  }
  1999  
  2000  // ChaindbProperty returns leveldb properties of the key-value database.
  2001  func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) {
  2002  	if property == "" {
  2003  		property = "leveldb.stats"
  2004  	} else if !strings.HasPrefix(property, "leveldb.") {
  2005  		property = "leveldb." + property
  2006  	}
  2007  	return api.b.ChainDb().Stat(property)
  2008  }
  2009  
  2010  // ChaindbCompact flattens the entire key-value database into a single level,
  2011  // removing all unused slots and merging all keys.
  2012  func (api *PrivateDebugAPI) ChaindbCompact() error {
  2013  	for b := byte(0); b < 255; b++ {
  2014  		log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1))
  2015  		if err := api.b.ChainDb().Compact([]byte{b}, []byte{b + 1}); err != nil {
  2016  			log.Error("Database compaction failed", "err", err)
  2017  			return err
  2018  		}
  2019  	}
  2020  	return nil
  2021  }
  2022  
  2023  // PublicNetAPI offers network related RPC methods
  2024  type PublicNetAPI struct {
  2025  	// net            *p2p.Server
  2026  	networkVersion uint64
  2027  }
  2028  
  2029  // NewPublicNetAPI creates a new net API instance.
  2030  func NewPublicNetAPI(networkVersion uint64) *PublicNetAPI {
  2031  	return &PublicNetAPI{networkVersion}
  2032  }
  2033  
  2034  // Listening returns an indication if the node is listening for network connections.
  2035  func (s *PublicNetAPI) Listening() bool {
  2036  	return true // always listening
  2037  }
  2038  
  2039  // PeerCount returns the number of connected peers
  2040  func (s *PublicNetAPI) PeerCount() hexutil.Uint {
  2041  	return hexutil.Uint(0)
  2042  }
  2043  
  2044  // Version returns the current ethereum protocol version.
  2045  func (s *PublicNetAPI) Version() string {
  2046  	return fmt.Sprintf("%d", s.networkVersion)
  2047  }
  2048  
  2049  // checkTxFee is an internal function used to check whether the fee of
  2050  // the given transaction is _reasonable_(under the cap).
  2051  func checkTxFee(gasPrice *big.Int, gas uint64, cap float64) error {
  2052  	// Short circuit if there is no cap for transaction fee at all.
  2053  	if cap == 0 {
  2054  		return nil
  2055  	}
  2056  	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)))
  2057  	feeFloat, _ := feeEth.Float64()
  2058  	if feeFloat > cap {
  2059  		return fmt.Errorf("tx fee (%.2f ether) exceeds the configured cap (%.2f ether)", feeFloat, cap)
  2060  	}
  2061  	return nil
  2062  }
  2063  
  2064  // toHexSlice creates a slice of hex-strings based on []byte.
  2065  func toHexSlice(b [][]byte) []string {
  2066  	r := make([]string, len(b))
  2067  	for i := range b {
  2068  		r[i] = hexutil.Encode(b[i])
  2069  	}
  2070  	return r
  2071  }