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