github.com/FusionFoundation/efsn/v4@v4.2.0/internal/ethapi/api.go (about)

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