github.com/aidoskuneen/adk-node@v0.0.0-20220315131952-2e32567cb7f4/internal/ethapi/api.go (about)

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