github.com/unicornultrafoundation/go-u2u@v1.0.0-rc1.0.20240205080301-e74a83d3fadc/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  	"math/rand"
    25  	"runtime"
    26  	"strings"
    27  	"sync"
    28  	"time"
    29  
    30  	"github.com/davecgh/go-spew/spew"
    31  	"github.com/syndtr/goleveldb/leveldb/opt"
    32  	"github.com/tyler-smith/go-bip39"
    33  
    34  	"github.com/unicornultrafoundation/go-helios/hash"
    35  	"github.com/unicornultrafoundation/go-helios/native/idx"
    36  
    37  	"github.com/unicornultrafoundation/go-u2u/accounts"
    38  	"github.com/unicornultrafoundation/go-u2u/accounts/abi"
    39  	"github.com/unicornultrafoundation/go-u2u/accounts/keystore"
    40  	"github.com/unicornultrafoundation/go-u2u/accounts/scwallet"
    41  	"github.com/unicornultrafoundation/go-u2u/common"
    42  	"github.com/unicornultrafoundation/go-u2u/common/hexutil"
    43  	"github.com/unicornultrafoundation/go-u2u/common/math"
    44  	"github.com/unicornultrafoundation/go-u2u/core/state"
    45  	"github.com/unicornultrafoundation/go-u2u/core/types"
    46  	"github.com/unicornultrafoundation/go-u2u/core/vm"
    47  	"github.com/unicornultrafoundation/go-u2u/crypto"
    48  	"github.com/unicornultrafoundation/go-u2u/eth/tracers"
    49  	"github.com/unicornultrafoundation/go-u2u/evmcore"
    50  	"github.com/unicornultrafoundation/go-u2u/gossip/gasprice"
    51  	"github.com/unicornultrafoundation/go-u2u/log"
    52  	"github.com/unicornultrafoundation/go-u2u/p2p"
    53  	"github.com/unicornultrafoundation/go-u2u/params"
    54  	"github.com/unicornultrafoundation/go-u2u/rlp"
    55  	"github.com/unicornultrafoundation/go-u2u/rpc"
    56  	"github.com/unicornultrafoundation/go-u2u/trie"
    57  	"github.com/unicornultrafoundation/go-u2u/u2u"
    58  	"github.com/unicornultrafoundation/go-u2u/utils/adapters/ethdb2udb"
    59  	"github.com/unicornultrafoundation/go-u2u/utils/dbutil/compactdb"
    60  	"github.com/unicornultrafoundation/go-u2u/utils/signers/gsignercache"
    61  	"github.com/unicornultrafoundation/go-u2u/utils/signers/internaltx"
    62  )
    63  
    64  const (
    65  	// defaultTraceTimeout is the amount of time a single transaction can execute
    66  	// by default before being forcefully aborted.
    67  	defaultTraceTimeout = 5 * time.Second
    68  
    69  	// defaultTraceReexec is the number of blocks the tracer is willing to go back
    70  	// and reexecute to produce missing historical state necessary to run a specific
    71  	// trace.
    72  	defaultTraceReexec = uint64(128)
    73  )
    74  
    75  var (
    76  	noUncles = []evmcore.EvmHeader{}
    77  )
    78  
    79  // PublicEthereumAPI provides an API to access Ethereum related information.
    80  // It offers only methods that operate on public data that is freely available to anyone.
    81  type PublicEthereumAPI struct {
    82  	b Backend
    83  }
    84  
    85  // NewPublicEthereumAPI creates a new Ethereum protocol API.
    86  func NewPublicEthereumAPI(b Backend) *PublicEthereumAPI {
    87  	return &PublicEthereumAPI{b}
    88  }
    89  
    90  // GasPrice returns a suggestion for a gas price for legacy transactions.
    91  func (s *PublicEthereumAPI) GasPrice(ctx context.Context) (*hexutil.Big, error) {
    92  	tipcap := s.b.SuggestGasTipCap(ctx, gasprice.AsDefaultCertainty)
    93  	tipcap.Add(tipcap, s.b.MinGasPrice())
    94  	return (*hexutil.Big)(tipcap), nil
    95  }
    96  
    97  // MaxPriorityFeePerGas returns a suggestion for a gas tip cap for dynamic fee transactions.
    98  func (s *PublicEthereumAPI) MaxPriorityFeePerGas(ctx context.Context) (*hexutil.Big, error) {
    99  	tipcap := s.b.SuggestGasTipCap(ctx, gasprice.AsDefaultCertainty)
   100  	return (*hexutil.Big)(tipcap), nil
   101  }
   102  
   103  type feeHistoryResult struct {
   104  	OldestBlock  *hexutil.Big     `json:"oldestBlock"`
   105  	Reward       [][]*hexutil.Big `json:"reward,omitempty"`
   106  	BaseFee      []*hexutil.Big   `json:"baseFeePerGas,omitempty"`
   107  	GasUsedRatio []float64        `json:"gasUsedRatio"`
   108  	Note         string           `json:"note"`
   109  }
   110  
   111  var errInvalidPercentile = errors.New("invalid reward percentile")
   112  
   113  func (s *PublicEthereumAPI) FeeHistory(ctx context.Context, blockCount rpc.DecimalOrHex, lastBlock rpc.BlockNumber, rewardPercentiles []float64) (*feeHistoryResult, error) {
   114  	res := &feeHistoryResult{}
   115  	res.Reward = make([][]*hexutil.Big, 0, blockCount)
   116  	res.BaseFee = make([]*hexutil.Big, 0, blockCount)
   117  	res.GasUsedRatio = make([]float64, 0, blockCount)
   118  	res.OldestBlock = (*hexutil.Big)(new(big.Int))
   119  
   120  	// validate input parameters
   121  	if blockCount == 0 {
   122  		return res, nil
   123  	}
   124  	if blockCount > 1024 {
   125  		blockCount = 1024
   126  	}
   127  	for i, p := range rewardPercentiles {
   128  		if p < 0 || p > 100 {
   129  			return nil, fmt.Errorf("%w: %f", errInvalidPercentile, p)
   130  		}
   131  		if i > 0 && p < rewardPercentiles[i-1] {
   132  			return nil, fmt.Errorf("%w: #%d:%f > #%d:%f", errInvalidPercentile, i-1, rewardPercentiles[i-1], i, p)
   133  		}
   134  	}
   135  	last, err := s.b.ResolveRpcBlockNumberOrHash(ctx, rpc.BlockNumberOrHash{BlockNumber: &lastBlock})
   136  	if err != nil {
   137  		return nil, err
   138  	}
   139  	oldest := last
   140  	if oldest > idx.Block(blockCount) {
   141  		oldest -= idx.Block(blockCount - 1)
   142  	} else {
   143  		oldest = 0
   144  	}
   145  
   146  	baseFee := s.b.MinGasPrice()
   147  
   148  	tips := make([]*big.Int, 0, len(rewardPercentiles))
   149  	for _, p := range rewardPercentiles {
   150  		tip := s.b.SuggestGasTipCap(ctx, uint64(gasprice.DecimalUnit*p/100.0))
   151  		tips = append(tips, tip)
   152  	}
   153  	res.OldestBlock.ToInt().SetUint64(uint64(oldest))
   154  	for i := uint64(0); i < uint64(last-oldest+1); i++ {
   155  		// randomize the output to mimic the ETH API eth_feeHistory for compatibility reasons
   156  		rTips := make([]*hexutil.Big, 0, len(tips))
   157  		for _, t := range tips {
   158  			rTip := t
   159  			// don't randomize last iteration
   160  			if i < uint64(last-oldest) {
   161  				// increase by up to 2% randomly
   162  				rTip = new(big.Int).Mul(t, big.NewInt(int64(rand.Intn(gasprice.DecimalUnit/50)+gasprice.DecimalUnit)))
   163  				rTip.Div(rTip, big.NewInt(gasprice.DecimalUnit))
   164  			}
   165  			rTips = append(rTips, (*hexutil.Big)(rTip))
   166  		}
   167  		res.Reward = append(res.Reward, rTips)
   168  		res.BaseFee = append(res.BaseFee, (*hexutil.Big)(baseFee))
   169  		r := rand.New(rand.NewSource(int64(oldest) + int64(i)))
   170  		res.GasUsedRatio = append(res.GasUsedRatio, 0.9+r.Float64()*0.1)
   171  	}
   172  	res.Note = `In the U2U network, the eth_feeHistory method operates slightly differently due to the network's unique consensus mechanism. ` +
   173  		`Here, instead of returning a range of gas tip values from requested blocks, ` +
   174  		`it provides a singular estimated gas tip based on a defined confidence level (indicated by the percentile parameter). ` +
   175  		`This approach means that while you will receive replicated (and randomized) reward values across the requested blocks, ` +
   176  		`the average or median of these values remains consistent with the intended gas tip.`
   177  	return res, nil
   178  }
   179  
   180  func (s *PublicEthereumAPI) EffectiveBaseFee(ctx context.Context) *hexutil.Big {
   181  	return (*hexutil.Big)(s.b.EffectiveMinGasPrice(ctx))
   182  }
   183  
   184  // Syncing returns true if node is syncing
   185  func (s *PublicEthereumAPI) Syncing() (interface{}, error) {
   186  	progress := s.b.Progress()
   187  	// Return not syncing if the synchronisation already completed
   188  	if time.Since(progress.CurrentBlockTime.Time()) <= 90*time.Minute { // should be >> MaxEmitInterval
   189  		return false, nil
   190  	}
   191  	// Otherwise gather the block sync stats
   192  	return map[string]interface{}{
   193  		"startingBlock":    hexutil.Uint64(0), // back-compatibility
   194  		"currentEpoch":     hexutil.Uint64(progress.CurrentEpoch),
   195  		"currentBlock":     hexutil.Uint64(progress.CurrentBlock),
   196  		"currentBlockHash": progress.CurrentBlockHash.Hex(),
   197  		"currentBlockTime": hexutil.Uint64(progress.CurrentBlockTime),
   198  		"highestBlock":     hexutil.Uint64(progress.HighestBlock),
   199  		"highestEpoch":     hexutil.Uint64(progress.HighestEpoch),
   200  		"pulledStates":     hexutil.Uint64(0), // back-compatibility
   201  		"knownStates":      hexutil.Uint64(0), // back-compatibility
   202  	}, nil
   203  }
   204  
   205  // PublicTxPoolAPI offers and API for the transaction pool. It only operates on data that is non confidential.
   206  type PublicTxPoolAPI struct {
   207  	b Backend
   208  }
   209  
   210  // NewPublicTxPoolAPI creates a new tx pool service that gives information about the transaction pool.
   211  func NewPublicTxPoolAPI(b Backend) *PublicTxPoolAPI {
   212  	return &PublicTxPoolAPI{b}
   213  }
   214  
   215  // Content returns the transactions contained within the transaction pool.
   216  func (s *PublicTxPoolAPI) Content() map[string]map[string]map[string]*RPCTransaction {
   217  	content := map[string]map[string]map[string]*RPCTransaction{
   218  		"pending": make(map[string]map[string]*RPCTransaction),
   219  		"queued":  make(map[string]map[string]*RPCTransaction),
   220  	}
   221  	pending, queue := s.b.TxPoolContent()
   222  
   223  	curHeader := s.b.CurrentBlock().Header()
   224  	// Flatten the pending transactions
   225  	for account, txs := range pending {
   226  		dump := make(map[string]*RPCTransaction)
   227  		for _, tx := range txs {
   228  			dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx, curHeader.BaseFee)
   229  		}
   230  		content["pending"][account.Hex()] = dump
   231  	}
   232  	// Flatten the queued transactions
   233  	for account, txs := range queue {
   234  		dump := make(map[string]*RPCTransaction)
   235  		for _, tx := range txs {
   236  			dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx, curHeader.BaseFee)
   237  		}
   238  		content["queued"][account.Hex()] = dump
   239  	}
   240  	return content
   241  }
   242  
   243  // ContentFrom returns the transactions contained within the transaction pool.
   244  func (s *PublicTxPoolAPI) ContentFrom(addr common.Address) map[string]map[string]*RPCTransaction {
   245  	content := make(map[string]map[string]*RPCTransaction, 2)
   246  	pending, queue := s.b.TxPoolContentFrom(addr)
   247  	curHeader := s.b.CurrentBlock().Header()
   248  
   249  	// Build the pending transactions
   250  	dump := make(map[string]*RPCTransaction, len(pending))
   251  	for _, tx := range pending {
   252  		dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx, curHeader.BaseFee)
   253  	}
   254  	content["pending"] = dump
   255  
   256  	// Build the queued transactions
   257  	dump = make(map[string]*RPCTransaction, len(queue))
   258  	for _, tx := range queue {
   259  		dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx, curHeader.BaseFee)
   260  	}
   261  	content["queued"] = dump
   262  
   263  	return content
   264  }
   265  
   266  // Status returns the number of pending and queued transaction in the pool.
   267  func (s *PublicTxPoolAPI) Status() map[string]hexutil.Uint {
   268  	pending, queue := s.b.Stats()
   269  	return map[string]hexutil.Uint{
   270  		"pending": hexutil.Uint(pending),
   271  		"queued":  hexutil.Uint(queue),
   272  	}
   273  }
   274  
   275  // Inspect retrieves the content of the transaction pool and flattens it into an
   276  // easily inspectable list.
   277  func (s *PublicTxPoolAPI) Inspect() map[string]map[string]map[string]string {
   278  	content := map[string]map[string]map[string]string{
   279  		"pending": make(map[string]map[string]string),
   280  		"queued":  make(map[string]map[string]string),
   281  	}
   282  	pending, queue := s.b.TxPoolContent()
   283  
   284  	// Define a formatter to flatten a transaction into a string
   285  	var format = func(tx *types.Transaction) string {
   286  		if to := tx.To(); to != nil {
   287  			return fmt.Sprintf("%s: %v wei + %v gas × %v wei", tx.To().Hex(), tx.Value(), tx.Gas(), tx.GasPrice())
   288  		}
   289  		return fmt.Sprintf("contract creation: %v wei + %v gas × %v wei", tx.Value(), tx.Gas(), tx.GasPrice())
   290  	}
   291  	// Flatten the pending transactions
   292  	for account, txs := range pending {
   293  		dump := make(map[string]string)
   294  		for _, tx := range txs {
   295  			dump[fmt.Sprintf("%d", tx.Nonce())] = format(tx)
   296  		}
   297  		content["pending"][account.Hex()] = dump
   298  	}
   299  	// Flatten the queued transactions
   300  	for account, txs := range queue {
   301  		dump := make(map[string]string)
   302  		for _, tx := range txs {
   303  			dump[fmt.Sprintf("%d", tx.Nonce())] = format(tx)
   304  		}
   305  		content["queued"][account.Hex()] = dump
   306  	}
   307  	return content
   308  }
   309  
   310  // PublicAccountAPI provides an API to access accounts managed by this node.
   311  // It offers only methods that can retrieve accounts.
   312  type PublicAccountAPI struct {
   313  	am *accounts.Manager
   314  }
   315  
   316  // NewPublicAccountAPI creates a new PublicAccountAPI.
   317  func NewPublicAccountAPI(am *accounts.Manager) *PublicAccountAPI {
   318  	return &PublicAccountAPI{am: am}
   319  }
   320  
   321  // Accounts returns the collection of accounts this node manages
   322  func (s *PublicAccountAPI) Accounts() []common.Address {
   323  	return s.am.Accounts()
   324  }
   325  
   326  // PrivateAccountAPI provides an API to access accounts managed by this node.
   327  // It offers methods to create, (un)lock en list accounts. Some methods accept
   328  // passwords and are therefore considered private by default.
   329  type PrivateAccountAPI struct {
   330  	am        *accounts.Manager
   331  	nonceLock *AddrLocker
   332  	b         Backend
   333  }
   334  
   335  // NewPrivateAccountAPI create a new PrivateAccountAPI.
   336  func NewPrivateAccountAPI(b Backend, nonceLock *AddrLocker) *PrivateAccountAPI {
   337  	return &PrivateAccountAPI{
   338  		am:        b.AccountManager(),
   339  		nonceLock: nonceLock,
   340  		b:         b,
   341  	}
   342  }
   343  
   344  // ListAccounts will return a list of addresses for accounts this node manages.
   345  func (s *PrivateAccountAPI) ListAccounts() []common.Address {
   346  	return s.am.Accounts()
   347  }
   348  
   349  // RawWallet is a JSON representation of an accounts.Wallet interface, with its
   350  // data contents extracted into plain fields.
   351  type RawWallet struct {
   352  	URL      string             `json:"url"`
   353  	Status   string             `json:"status"`
   354  	Failure  string             `json:"failure,omitempty"`
   355  	Accounts []accounts.Account `json:"accounts,omitempty"`
   356  }
   357  
   358  // ListWallets will return a list of wallets this node manages.
   359  func (s *PrivateAccountAPI) ListWallets() []RawWallet {
   360  	wallets := make([]RawWallet, 0) // return [] instead of nil if empty
   361  	for _, wallet := range s.am.Wallets() {
   362  		status, failure := wallet.Status()
   363  
   364  		raw := RawWallet{
   365  			URL:      wallet.URL().String(),
   366  			Status:   status,
   367  			Accounts: wallet.Accounts(),
   368  		}
   369  		if failure != nil {
   370  			raw.Failure = failure.Error()
   371  		}
   372  		wallets = append(wallets, raw)
   373  	}
   374  	return wallets
   375  }
   376  
   377  // OpenWallet initiates a hardware wallet opening procedure, establishing a USB
   378  // connection and attempting to authenticate via the provided passphrase. Note,
   379  // the method may return an extra challenge requiring a second open (e.g. the
   380  // Trezor PIN matrix challenge).
   381  func (s *PrivateAccountAPI) OpenWallet(url string, passphrase *string) error {
   382  	wallet, err := s.am.Wallet(url)
   383  	if err != nil {
   384  		return err
   385  	}
   386  	pass := ""
   387  	if passphrase != nil {
   388  		pass = *passphrase
   389  	}
   390  	return wallet.Open(pass)
   391  }
   392  
   393  // DeriveAccount requests a HD wallet to derive a new account, optionally pinning
   394  // it for later reuse.
   395  func (s *PrivateAccountAPI) DeriveAccount(url string, path string, pin *bool) (accounts.Account, error) {
   396  	wallet, err := s.am.Wallet(url)
   397  	if err != nil {
   398  		return accounts.Account{}, err
   399  	}
   400  	derivPath, err := accounts.ParseDerivationPath(path)
   401  	if err != nil {
   402  		return accounts.Account{}, err
   403  	}
   404  	if pin == nil {
   405  		pin = new(bool)
   406  	}
   407  	return wallet.Derive(derivPath, *pin)
   408  }
   409  
   410  // NewAccount will create a new account and returns the address for the new account.
   411  func (s *PrivateAccountAPI) NewAccount(password string) (common.Address, error) {
   412  	ks, err := fetchKeystore(s.am)
   413  	if err != nil {
   414  		return common.Address{}, err
   415  	}
   416  	acc, err := ks.NewAccount(password)
   417  	if err == nil {
   418  		log.Info("Your new key was generated", "address", acc.Address)
   419  		log.Warn("Please backup your key file!", "path", acc.URL.Path)
   420  		log.Warn("Please remember your password!")
   421  		return acc.Address, nil
   422  	}
   423  	return common.Address{}, err
   424  }
   425  
   426  // fetchKeystore retrieves the encrypted keystore from the account manager.
   427  func fetchKeystore(am *accounts.Manager) (*keystore.KeyStore, error) {
   428  	if ks := am.Backends(keystore.KeyStoreType); len(ks) > 0 {
   429  		return ks[0].(*keystore.KeyStore), nil
   430  	}
   431  	return nil, errors.New("local keystore not used")
   432  }
   433  
   434  // ImportRawKey stores the given hex encoded ECDSA key into the key directory,
   435  // encrypting it with the passphrase.
   436  func (s *PrivateAccountAPI) ImportRawKey(privkey string, password string) (common.Address, error) {
   437  	key, err := crypto.HexToECDSA(privkey)
   438  	if err != nil {
   439  		return common.Address{}, err
   440  	}
   441  	ks, err := fetchKeystore(s.am)
   442  	if err != nil {
   443  		return common.Address{}, err
   444  	}
   445  	acc, err := ks.ImportECDSA(key, password)
   446  	return acc.Address, err
   447  }
   448  
   449  // UnlockAccount will unlock the account associated with the given address with
   450  // the given password for duration seconds. If duration is nil it will use a
   451  // default of 300 seconds. It returns an indication if the account was unlocked.
   452  func (s *PrivateAccountAPI) UnlockAccount(ctx context.Context, addr common.Address, password string, duration *uint64) (bool, error) {
   453  	// When the API is exposed by external RPC(http, ws etc), unless the user
   454  	// explicitly specifies to allow the insecure account unlocking, otherwise
   455  	// it is disabled.
   456  	if s.b.ExtRPCEnabled() && !s.b.AccountManager().Config().InsecureUnlockAllowed {
   457  		return false, errors.New("account unlock with HTTP access is forbidden")
   458  	}
   459  
   460  	const max = uint64(time.Duration(math.MaxInt64) / time.Second)
   461  	var d time.Duration
   462  	if duration == nil {
   463  		d = 300 * time.Second
   464  	} else if *duration > max {
   465  		return false, errors.New("unlock duration too large")
   466  	} else {
   467  		d = time.Duration(*duration) * time.Second
   468  	}
   469  	ks, err := fetchKeystore(s.am)
   470  	if err != nil {
   471  		return false, err
   472  	}
   473  	err = ks.TimedUnlock(accounts.Account{Address: addr}, password, d)
   474  	if err != nil {
   475  		log.Warn("Failed account unlock attempt", "address", addr, "err", err)
   476  	}
   477  	return err == nil, err
   478  }
   479  
   480  // LockAccount will lock the account associated with the given address when it's unlocked.
   481  func (s *PrivateAccountAPI) LockAccount(addr common.Address) bool {
   482  	if ks, err := fetchKeystore(s.am); err == nil {
   483  		return ks.Lock(addr) == nil
   484  	}
   485  	return false
   486  }
   487  
   488  // signTransaction sets defaults and signs the given transaction
   489  // NOTE: the caller needs to ensure that the nonceLock is held, if applicable,
   490  // and release it after the transaction has been submitted to the tx pool
   491  func (s *PrivateAccountAPI) signTransaction(ctx context.Context, args *TransactionArgs, passwd string) (*types.Transaction, error) {
   492  	// Look up the wallet containing the requested signer
   493  	account := accounts.Account{Address: args.from()}
   494  	wallet, err := s.am.Find(account)
   495  	if err != nil {
   496  		return nil, err
   497  	}
   498  	// Set some sanity defaults and terminate on failure
   499  	if err := args.setDefaults(ctx, s.b); err != nil {
   500  		return nil, err
   501  	}
   502  	// Assemble the transaction and sign with the wallet
   503  	tx := args.toTransaction()
   504  
   505  	return wallet.SignTxWithPassphrase(account, passwd, tx, s.b.ChainConfig().ChainID)
   506  }
   507  
   508  // SendTransaction will create a transaction from the given arguments and
   509  // tries to sign it with the key associated with args.From. If the given
   510  // passwd isn't able to decrypt the key it fails.
   511  func (s *PrivateAccountAPI) SendTransaction(ctx context.Context, args TransactionArgs, passwd string) (common.Hash, error) {
   512  	if args.Nonce == nil {
   513  		// Hold the addresse's mutex around signing to prevent concurrent assignment of
   514  		// the same nonce to multiple accounts.
   515  		s.nonceLock.LockAddr(args.from())
   516  		defer s.nonceLock.UnlockAddr(args.from())
   517  	}
   518  	signed, err := s.signTransaction(ctx, &args, passwd)
   519  	if err != nil {
   520  		log.Warn("Failed transaction send attempt", "from", args.from(), "to", args.To, "value", args.Value.ToInt(), "err", err)
   521  		return common.Hash{}, err
   522  	}
   523  	return SubmitTransaction(ctx, s.b, signed)
   524  }
   525  
   526  // SignTransaction will create a transaction from the given arguments and
   527  // tries to sign it with the key associated with args.From. If the given passwd isn't
   528  // able to decrypt the key it fails. The transaction is returned in RLP-form, not broadcast
   529  // to other nodes
   530  func (s *PrivateAccountAPI) SignTransaction(ctx context.Context, args TransactionArgs, passwd string) (*SignTransactionResult, error) {
   531  	// No need to obtain the noncelock mutex, since we won't be sending this
   532  	// tx into the transaction pool, but right back to the user
   533  	if args.From == nil {
   534  		return nil, fmt.Errorf("sender not specified")
   535  	}
   536  	if args.Gas == nil {
   537  		return nil, fmt.Errorf("gas not specified")
   538  	}
   539  	if args.GasPrice == nil && (args.MaxFeePerGas == nil || args.MaxPriorityFeePerGas == nil) {
   540  		return nil, fmt.Errorf("missing gasPrice or maxFeePerGas/maxPriorityFeePerGas")
   541  	}
   542  	if args.Nonce == nil {
   543  		return nil, fmt.Errorf("nonce not specified")
   544  	}
   545  	// Before actually signing the transaction, ensure the transaction fee is reasonable.
   546  	tx := args.toTransaction()
   547  	if err := checkTxFee(tx.GasPrice(), tx.Gas(), s.b.RPCTxFeeCap()); err != nil {
   548  		return nil, err
   549  	}
   550  	signed, err := s.signTransaction(ctx, &args, passwd)
   551  	if err != nil {
   552  		log.Warn("Failed transaction sign attempt", "from", args.from(), "to", args.To, "value", args.Value.ToInt(), "err", err)
   553  		return nil, err
   554  	}
   555  	data, err := signed.MarshalBinary()
   556  	if err != nil {
   557  		return nil, err
   558  	}
   559  	return &SignTransactionResult{data, signed}, nil
   560  }
   561  
   562  // Sign calculates an Ethereum ECDSA signature for:
   563  // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message))
   564  //
   565  // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
   566  // where the V value will be 27 or 28 for legacy reasons.
   567  //
   568  // The key used to calculate the signature is decrypted with the given password.
   569  //
   570  // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign
   571  func (s *PrivateAccountAPI) Sign(ctx context.Context, data hexutil.Bytes, addr common.Address, passwd string) (hexutil.Bytes, error) {
   572  	// Look up the wallet containing the requested signer
   573  	account := accounts.Account{Address: addr}
   574  
   575  	wallet, err := s.b.AccountManager().Find(account)
   576  	if err != nil {
   577  		return nil, err
   578  	}
   579  	// Assemble sign the data with the wallet
   580  	signature, err := wallet.SignTextWithPassphrase(account, passwd, data)
   581  	if err != nil {
   582  		log.Warn("Failed data sign attempt", "address", addr, "err", err)
   583  		return nil, err
   584  	}
   585  	signature[crypto.RecoveryIDOffset] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
   586  	return signature, nil
   587  }
   588  
   589  // EcRecover returns the address for the account that was used to create the signature.
   590  // Note, this function is compatible with eth_sign and personal_sign. As such it recovers
   591  // the address of:
   592  // hash = keccak256("\x19Ethereum Signed Message:\n"${message length}${message})
   593  // addr = ecrecover(hash, signature)
   594  //
   595  // Note, the signature must conform to the secp256k1 curve R, S and V values, where
   596  // the V value must be 27 or 28 for legacy reasons.
   597  //
   598  // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_ecRecover
   599  func (s *PrivateAccountAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) {
   600  	if len(sig) != crypto.SignatureLength {
   601  		return common.Address{}, fmt.Errorf("signature must be %d bytes long", crypto.SignatureLength)
   602  	}
   603  	if sig[crypto.RecoveryIDOffset] != 27 && sig[crypto.RecoveryIDOffset] != 28 {
   604  		return common.Address{}, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)")
   605  	}
   606  	sig[crypto.RecoveryIDOffset] -= 27 // Transform yellow paper V from 27/28 to 0/1
   607  
   608  	rpk, err := crypto.SigToPub(accounts.TextHash(data), sig)
   609  	if err != nil {
   610  		return common.Address{}, err
   611  	}
   612  	return crypto.PubkeyToAddress(*rpk), nil
   613  }
   614  
   615  // SignAndSendTransaction was renamed to SendTransaction. This method is deprecated
   616  // and will be removed in the future. It primary goal is to give clients time to update.
   617  func (s *PrivateAccountAPI) SignAndSendTransaction(ctx context.Context, args TransactionArgs, passwd string) (common.Hash, error) {
   618  	return s.SendTransaction(ctx, args, passwd)
   619  }
   620  
   621  // InitializeWallet initializes a new wallet at the provided URL, by generating and returning a new private key.
   622  func (s *PrivateAccountAPI) InitializeWallet(ctx context.Context, url string) (string, error) {
   623  	wallet, err := s.am.Wallet(url)
   624  	if err != nil {
   625  		return "", err
   626  	}
   627  
   628  	entropy, err := bip39.NewEntropy(256)
   629  	if err != nil {
   630  		return "", err
   631  	}
   632  
   633  	mnemonic, err := bip39.NewMnemonic(entropy)
   634  	if err != nil {
   635  		return "", err
   636  	}
   637  
   638  	seed := bip39.NewSeed(mnemonic, "")
   639  
   640  	switch wallet := wallet.(type) {
   641  	case *scwallet.Wallet:
   642  		return mnemonic, wallet.Initialize(seed)
   643  	default:
   644  		return "", fmt.Errorf("specified wallet does not support initialization")
   645  	}
   646  }
   647  
   648  // Unpair deletes a pairing between wallet and geth.
   649  func (s *PrivateAccountAPI) Unpair(ctx context.Context, url string, pin string) error {
   650  	wallet, err := s.am.Wallet(url)
   651  	if err != nil {
   652  		return err
   653  	}
   654  
   655  	switch wallet := wallet.(type) {
   656  	case *scwallet.Wallet:
   657  		return wallet.Unpair([]byte(pin))
   658  	default:
   659  		return fmt.Errorf("specified wallet does not support pairing")
   660  	}
   661  }
   662  
   663  // PublicBlockChainAPI provides an API to access the Ethereum blockchain.
   664  // It offers only methods that operate on public data that is freely available to anyone.
   665  type PublicBlockChainAPI struct {
   666  	b Backend
   667  }
   668  
   669  // NewPublicBlockChainAPI creates a new Ethereum blockchain API.
   670  func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI {
   671  	return &PublicBlockChainAPI{b}
   672  }
   673  
   674  // CurrentEpoch returns current epoch number.
   675  func (s *PublicBlockChainAPI) CurrentEpoch(ctx context.Context) hexutil.Uint64 {
   676  	return hexutil.Uint64(s.b.CurrentEpoch(ctx))
   677  }
   678  
   679  // GetRules returns network rules for an epoch
   680  func (s *PublicBlockChainAPI) GetRules(ctx context.Context, epoch rpc.BlockNumber) (*u2u.Rules, error) {
   681  	_, es, err := s.b.GetEpochBlockState(ctx, epoch)
   682  	if err != nil {
   683  		return nil, err
   684  	}
   685  	if es == nil {
   686  		return nil, nil
   687  	}
   688  	return &es.Rules, nil
   689  }
   690  
   691  // GetEpochBlock returns block height in a beginning of an epoch
   692  func (s *PublicBlockChainAPI) GetEpochBlock(ctx context.Context, epoch rpc.BlockNumber) (hexutil.Uint64, error) {
   693  	bs, _, err := s.b.GetEpochBlockState(ctx, epoch)
   694  	if err != nil {
   695  		return 0, err
   696  	}
   697  	if bs == nil {
   698  		return 0, nil
   699  	}
   700  	return hexutil.Uint64(bs.LastBlock.Idx), nil
   701  }
   702  
   703  // ChainId is the EIP-155 replay-protection chain id for the current ethereum chain config.
   704  func (api *PublicBlockChainAPI) ChainId() (*hexutil.Big, error) {
   705  	// if current block is at or past the EIP-155 replay-protection fork block, return chainID from config
   706  	if config := api.b.ChainConfig(); config.IsEIP155(api.b.CurrentBlock().Number) {
   707  		return (*hexutil.Big)(config.ChainID), nil
   708  	}
   709  	return nil, fmt.Errorf("chain not synced beyond EIP-155 replay-protection fork block")
   710  }
   711  
   712  // BlockNumber returns the block number of the chain head.
   713  func (s *PublicBlockChainAPI) BlockNumber() hexutil.Uint64 {
   714  	header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available
   715  	return hexutil.Uint64(header.Number.Uint64())
   716  }
   717  
   718  // GetBalance returns the amount of wei for the given address in the state of the
   719  // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
   720  // block numbers are also allowed.
   721  func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Big, error) {
   722  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   723  	if state == nil || err != nil {
   724  		return nil, err
   725  	}
   726  	return (*hexutil.Big)(state.GetBalance(address)), state.Error()
   727  }
   728  
   729  // AccountResult is result struct for GetProof
   730  type AccountResult struct {
   731  	Address      common.Address  `json:"address"`
   732  	AccountProof []string        `json:"accountProof"`
   733  	Balance      *hexutil.Big    `json:"balance"`
   734  	CodeHash     common.Hash     `json:"codeHash"`
   735  	Nonce        hexutil.Uint64  `json:"nonce"`
   736  	StorageHash  common.Hash     `json:"storageHash"`
   737  	StorageProof []StorageResult `json:"storageProof"`
   738  }
   739  
   740  // StorageResult is result struct for GetProof
   741  type StorageResult struct {
   742  	Key   string       `json:"key"`
   743  	Value *hexutil.Big `json:"value"`
   744  	Proof []string     `json:"proof"`
   745  }
   746  
   747  // GetProof returns the Merkle-proof for a given account and optionally some storage keys.
   748  func (s *PublicBlockChainAPI) GetProof(ctx context.Context, address common.Address, storageKeys []string, blockNrOrHash rpc.BlockNumberOrHash) (*AccountResult, error) {
   749  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   750  	if state == nil || err != nil {
   751  		return nil, err
   752  	}
   753  
   754  	storageTrie := state.StorageTrie(address)
   755  	storageHash := types.EmptyRootHash
   756  	codeHash := state.GetCodeHash(address)
   757  	storageProof := make([]StorageResult, len(storageKeys))
   758  
   759  	// if we have a storageTrie, (which means the account exists), we can update the storagehash
   760  	if storageTrie != nil {
   761  		storageHash = storageTrie.Hash()
   762  	} else {
   763  		// no storageTrie means the account does not exist, so the codeHash is the hash of an empty bytearray.
   764  		codeHash = crypto.Keccak256Hash(nil)
   765  	}
   766  
   767  	// create the proof for the storageKeys
   768  	for i, key := range storageKeys {
   769  		if storageTrie != nil {
   770  			proof, storageError := state.GetStorageProof(address, common.HexToHash(key))
   771  			if storageError != nil {
   772  				return nil, storageError
   773  			}
   774  			storageProof[i] = StorageResult{key, (*hexutil.Big)(state.GetState(address, common.HexToHash(key)).Big()), toHexSlice(proof)}
   775  		} else {
   776  			storageProof[i] = StorageResult{key, &hexutil.Big{}, []string{}}
   777  		}
   778  	}
   779  
   780  	// create the accountProof
   781  	accountProof, proofErr := state.GetProof(address)
   782  	if proofErr != nil {
   783  		return nil, proofErr
   784  	}
   785  
   786  	return &AccountResult{
   787  		Address:      address,
   788  		AccountProof: toHexSlice(accountProof),
   789  		Balance:      (*hexutil.Big)(state.GetBalance(address)),
   790  		CodeHash:     codeHash,
   791  		Nonce:        hexutil.Uint64(state.GetNonce(address)),
   792  		StorageHash:  storageHash,
   793  		StorageProof: storageProof,
   794  	}, state.Error()
   795  }
   796  
   797  // GetHeaderByNumber returns the requested canonical block header.
   798  // * When blockNr is -1 the chain head is returned.
   799  // * When blockNr is -2 the pending chain head is returned.
   800  func (s *PublicBlockChainAPI) GetHeaderByNumber(ctx context.Context, number rpc.BlockNumber) (map[string]interface{}, error) {
   801  	header, err := s.b.HeaderByNumber(ctx, number)
   802  	if header != nil && err == nil {
   803  		response := s.rpcMarshalHeader(header, s.calculateExtBlockApi(ctx, number))
   804  		if number == rpc.PendingBlockNumber {
   805  			// Pending header need to nil out a few fields
   806  			for _, field := range []string{"hash", "nonce", "miner"} {
   807  				response[field] = nil
   808  			}
   809  		}
   810  		return response, err
   811  	}
   812  	return nil, err
   813  }
   814  
   815  // GetHeaderByHash returns the requested header by hash.
   816  func (s *PublicBlockChainAPI) GetHeaderByHash(ctx context.Context, hash common.Hash) map[string]interface{} {
   817  	header, _ := s.b.HeaderByHash(ctx, hash)
   818  	if header != nil {
   819  		return s.rpcMarshalHeader(header, s.calculateExtBlockApi(ctx, rpc.BlockNumber(header.Number.Uint64())))
   820  	}
   821  	return nil
   822  }
   823  
   824  func (s *PublicBlockChainAPI) calculateExtBlockApi(ctx context.Context, blkNumber rpc.BlockNumber) extBlockApi {
   825  	var ext extBlockApi
   826  	if s.b.CalcBlockExtApi() && blkNumber != rpc.EarliestBlockNumber {
   827  		receipts, err := s.b.GetReceiptsByNumber(ctx, blkNumber)
   828  		if err != nil {
   829  			return ext
   830  		}
   831  		if receipts.Len() != 0 {
   832  			ext.receiptsRoot = types.DeriveSha(receipts, trie.NewStackTrie(nil))
   833  			ext.bloom = types.CreateBloom(receipts)
   834  		} else {
   835  			ext.receiptsRoot = types.EmptyRootHash
   836  		}
   837  	}
   838  	return ext
   839  }
   840  
   841  // GetBlockByNumber returns the requested canonical block.
   842  //   - When blockNr is -1 the chain head is returned.
   843  //   - When blockNr is -2 the pending chain head is returned.
   844  //   - When fullTx is true all transactions in the block are returned, otherwise
   845  //     only the transaction hash is returned.
   846  func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, number rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
   847  	block, err := s.b.BlockByNumber(ctx, number)
   848  	if block != nil && err == nil {
   849  		response, err := s.rpcMarshalBlock(block, s.calculateExtBlockApi(ctx, number), true, fullTx)
   850  		if err == nil && number == rpc.PendingBlockNumber {
   851  			// Pending blocks need to nil out a few fields
   852  			for _, field := range []string{"hash", "nonce", "miner"} {
   853  				response[field] = nil
   854  			}
   855  		}
   856  		return response, err
   857  	}
   858  	return nil, err
   859  }
   860  
   861  // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
   862  // detail, otherwise only the transaction hash is returned.
   863  func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, hash common.Hash, fullTx bool) (map[string]interface{}, error) {
   864  	block, err := s.b.BlockByHash(ctx, hash)
   865  	if block != nil {
   866  		return s.rpcMarshalBlock(block, s.calculateExtBlockApi(ctx, rpc.BlockNumber(block.NumberU64())), true, fullTx)
   867  	}
   868  	return nil, err
   869  }
   870  
   871  // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true
   872  // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
   873  func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) {
   874  	block, err := s.b.BlockByNumber(ctx, blockNr)
   875  	if block != nil {
   876  		log.Debug("Requested uncle not found", "number", blockNr, "hash", block.Hash, "index", index)
   877  		return nil, nil
   878  	}
   879  	return nil, err
   880  }
   881  
   882  // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true
   883  // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
   884  func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) {
   885  	block, err := s.b.BlockByHash(ctx, blockHash)
   886  	if block != nil {
   887  		log.Debug("Requested uncle not found", "number", block.Number, "hash", blockHash, "index", index)
   888  		return nil, nil
   889  	}
   890  	return nil, err
   891  }
   892  
   893  // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
   894  func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
   895  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
   896  		n := hexutil.Uint(len(noUncles))
   897  		return &n
   898  	}
   899  	return nil
   900  }
   901  
   902  // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash
   903  func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
   904  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
   905  		n := hexutil.Uint(len(noUncles))
   906  		return &n
   907  	}
   908  	return nil
   909  }
   910  
   911  // GetCode returns the code stored at the given address in the state for the given block number.
   912  func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
   913  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   914  	if state == nil || err != nil {
   915  		return nil, err
   916  	}
   917  	code := state.GetCode(address)
   918  	return code, state.Error()
   919  }
   920  
   921  // GetStorageAt returns the storage from the state at the given address, key and
   922  // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
   923  // numbers are also allowed.
   924  func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNr rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
   925  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNr)
   926  	if state == nil || err != nil {
   927  		return nil, err
   928  	}
   929  	res := state.GetState(address, common.HexToHash(key))
   930  	return res[:], state.Error()
   931  }
   932  
   933  // OverrideAccount indicates the overriding fields of account during the execution
   934  // of a message call.
   935  // Note, state and stateDiff can't be specified at the same time. If state is
   936  // set, message execution will only use the data in the given state. Otherwise
   937  // if statDiff is set, all diff will be applied first and then execute the call
   938  // message.
   939  type OverrideAccount struct {
   940  	Nonce     *hexutil.Uint64              `json:"nonce"`
   941  	Code      *hexutil.Bytes               `json:"code"`
   942  	Balance   **hexutil.Big                `json:"balance"`
   943  	State     *map[common.Hash]common.Hash `json:"state"`
   944  	StateDiff *map[common.Hash]common.Hash `json:"stateDiff"`
   945  }
   946  
   947  // StateOverride is the collection of overridden accounts.
   948  type StateOverride map[common.Address]OverrideAccount
   949  
   950  // Apply overrides the fields of specified accounts into the given state.
   951  func (diff *StateOverride) Apply(state *state.StateDB) error {
   952  	if diff == nil {
   953  		return nil
   954  	}
   955  	for addr, account := range *diff {
   956  		// Override account nonce.
   957  		if account.Nonce != nil {
   958  			state.SetNonce(addr, uint64(*account.Nonce))
   959  		}
   960  		// Override account(contract) code.
   961  		if account.Code != nil {
   962  			state.SetCode(addr, *account.Code)
   963  		}
   964  		// Override account balance.
   965  		if account.Balance != nil {
   966  			state.SetBalance(addr, (*big.Int)(*account.Balance))
   967  		}
   968  		if account.State != nil && account.StateDiff != nil {
   969  			return fmt.Errorf("account %s has both 'state' and 'stateDiff'", addr.Hex())
   970  		}
   971  		// Replace entire state if caller requires.
   972  		if account.State != nil {
   973  			state.SetStorage(addr, *account.State)
   974  		}
   975  		// Apply state diff into specified accounts.
   976  		if account.StateDiff != nil {
   977  			for key, value := range *account.StateDiff {
   978  				state.SetState(addr, key, value)
   979  			}
   980  		}
   981  	}
   982  	return nil
   983  }
   984  
   985  // BlockOverrides is a set of header fields to override.
   986  type BlockOverrides struct {
   987  	Number     *hexutil.Big
   988  	Difficulty *hexutil.Big
   989  	Time       *hexutil.Uint64
   990  	GasLimit   *hexutil.Uint64
   991  	Coinbase   *common.Address
   992  	Random     *common.Hash
   993  	BaseFee    *hexutil.Big
   994  }
   995  
   996  // Apply overrides the given header fields into the given block context.
   997  func (diff *BlockOverrides) Apply(blockCtx *vm.BlockContext) {
   998  	if diff == nil {
   999  		return
  1000  	}
  1001  	if diff.Number != nil {
  1002  		blockCtx.BlockNumber = diff.Number.ToInt()
  1003  	}
  1004  	if diff.Difficulty != nil {
  1005  		blockCtx.Difficulty = diff.Difficulty.ToInt()
  1006  	}
  1007  	if diff.Time != nil {
  1008  		blockCtx.Time = big.NewInt(int64(*diff.Time))
  1009  	}
  1010  	if diff.GasLimit != nil {
  1011  		blockCtx.GasLimit = uint64(*diff.GasLimit)
  1012  	}
  1013  	if diff.Coinbase != nil {
  1014  		blockCtx.Coinbase = *diff.Coinbase
  1015  	}
  1016  	if diff.BaseFee != nil {
  1017  		blockCtx.BaseFee = diff.BaseFee.ToInt()
  1018  	}
  1019  }
  1020  
  1021  // ChainContextBackend provides methods required to implement ChainContext.
  1022  type ChainContextBackend interface {
  1023  	HeaderByNumber(context.Context, rpc.BlockNumber) (*evmcore.EvmHeader, error)
  1024  }
  1025  
  1026  // ChainContext is an implementation of core.ChainContext. It's main use-case
  1027  // is instantiating a vm.BlockContext without having access to the BlockChain object.
  1028  type ChainContext struct {
  1029  	b   ChainContextBackend
  1030  	ctx context.Context
  1031  }
  1032  
  1033  // NewChainContext creates a new ChainContext object.
  1034  func NewChainContext(ctx context.Context, backend ChainContextBackend) *ChainContext {
  1035  	return &ChainContext{ctx: ctx, b: backend}
  1036  }
  1037  
  1038  func (context *ChainContext) GetHeader(hash common.Hash, number uint64) *evmcore.EvmHeader {
  1039  	// This method is called to get the hash for a block number when executing the BLOCKHASH
  1040  	// opcode. Hence no need to search for non-canonical blocks.
  1041  	header, err := context.b.HeaderByNumber(context.ctx, rpc.BlockNumber(number))
  1042  	if err != nil || header.Hash != hash {
  1043  		return nil
  1044  	}
  1045  	return header
  1046  }
  1047  
  1048  func DoCall(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *StateOverride, timeout time.Duration, globalGasCap uint64) (*evmcore.ExecutionResult, error) {
  1049  	defer func(start time.Time) { log.Debug("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now())
  1050  
  1051  	state, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1052  	if state == nil || err != nil {
  1053  		return nil, err
  1054  	}
  1055  	if err := overrides.Apply(state); err != nil {
  1056  		return nil, err
  1057  	}
  1058  	// Setup context so it may be cancelled the call has completed
  1059  	// or, in case of unmetered gas, setup a context with a timeout.
  1060  	var cancel context.CancelFunc
  1061  	if timeout > 0 {
  1062  		ctx, cancel = context.WithTimeout(ctx, timeout)
  1063  	} else {
  1064  		ctx, cancel = context.WithCancel(ctx)
  1065  	}
  1066  	// Make sure the context is cancelled when the call has completed
  1067  	// this makes sure resources are cleaned up.
  1068  	defer cancel()
  1069  
  1070  	// Get a new instance of the EVM.
  1071  	msg, err := args.ToMessage(globalGasCap, header.BaseFee)
  1072  	if err != nil {
  1073  		return nil, err
  1074  	}
  1075  	vmConfig := u2u.DefaultVMConfig
  1076  	vmConfig.NoBaseFee = true
  1077  	evm, vmError, err := b.GetEVM(ctx, msg, state, header, &vmConfig)
  1078  	if err != nil {
  1079  		return nil, err
  1080  	}
  1081  	// Wait for the context to be done and cancel the evm. Even if the
  1082  	// EVM has finished, cancelling may be done (repeatedly)
  1083  	go func() {
  1084  		<-ctx.Done()
  1085  		evm.Cancel()
  1086  	}()
  1087  
  1088  	// Execute the message.
  1089  	gp := new(evmcore.GasPool).AddGas(math.MaxUint64)
  1090  	result, err := evmcore.ApplyMessage(evm, msg, gp)
  1091  	if err := vmError(); err != nil {
  1092  		return nil, err
  1093  	}
  1094  
  1095  	// If the timer caused an abort, return an appropriate error message
  1096  	if evm.Cancelled() {
  1097  		return nil, fmt.Errorf("execution aborted (timeout = %v)", timeout)
  1098  	}
  1099  	if err != nil {
  1100  		return result, fmt.Errorf("err: %w (supplied gas %d)", err, msg.Gas())
  1101  	}
  1102  	return result, nil
  1103  }
  1104  
  1105  func newRevertError(result *evmcore.ExecutionResult) *revertError {
  1106  	reason, errUnpack := abi.UnpackRevert(result.Revert())
  1107  	err := errors.New("execution reverted")
  1108  	if errUnpack == nil {
  1109  		err = fmt.Errorf("execution reverted: %v", reason)
  1110  	}
  1111  	return &revertError{
  1112  		error:  err,
  1113  		reason: hexutil.Encode(result.Revert()),
  1114  	}
  1115  }
  1116  
  1117  // revertError is an API error that encompassas an EVM revertal with JSON error
  1118  // code and a binary data blob.
  1119  type revertError struct {
  1120  	error
  1121  	reason string // revert reason hex encoded
  1122  }
  1123  
  1124  // ErrorCode returns the JSON error code for a revertal.
  1125  // See: https://github.com/ethereum/wiki/wiki/JSON-RPC-Error-Codes-Improvement-Proposal
  1126  func (e *revertError) ErrorCode() int {
  1127  	return 3
  1128  }
  1129  
  1130  // ErrorData returns the hex encoded revert reason.
  1131  func (e *revertError) ErrorData() interface{} {
  1132  	return e.reason
  1133  }
  1134  
  1135  // Call executes the given transaction on the state for the given block number.
  1136  //
  1137  // Additionally, the caller can specify a batch of contract for fields overriding.
  1138  //
  1139  // Note, this function doesn't make and changes in the state/blockchain and is
  1140  // useful to execute and retrieve values.
  1141  func (s *PublicBlockChainAPI) Call(ctx context.Context, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *StateOverride) (hexutil.Bytes, error) {
  1142  	result, err := DoCall(ctx, s.b, args, blockNrOrHash, overrides, s.b.RPCTimeout(), s.b.RPCGasCap())
  1143  	if err != nil {
  1144  		return nil, err
  1145  	}
  1146  	// If the result contains a revert reason, try to unpack and return it.
  1147  	if len(result.Revert()) > 0 {
  1148  		return nil, newRevertError(result)
  1149  	}
  1150  	return result.Return(), result.Err
  1151  }
  1152  
  1153  // DoEstimateGas - binary search the gas requirement, as it may be higher than the amount used
  1154  func DoEstimateGas(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, gasCap uint64) (hexutil.Uint64, error) {
  1155  	// Binary search the gas requirement, as it may be higher than the amount used
  1156  	var (
  1157  		lo  uint64 = params.TxGas - 1
  1158  		hi  uint64
  1159  		cap uint64
  1160  	)
  1161  	// Use zero address if sender unspecified.
  1162  	if args.From == nil {
  1163  		args.From = new(common.Address)
  1164  	}
  1165  	// Determine the highest gas limit can be used during the estimation.
  1166  	if args.Gas != nil && uint64(*args.Gas) >= params.TxGas {
  1167  		hi = uint64(*args.Gas)
  1168  	} else {
  1169  		hi = b.MaxGasLimit()
  1170  	}
  1171  	// Normalize the max fee per gas the call is willing to spend.
  1172  	var feeCap *big.Int
  1173  	if args.GasPrice != nil && (args.MaxFeePerGas != nil || args.MaxPriorityFeePerGas != nil) {
  1174  		return 0, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")
  1175  	} else if args.GasPrice != nil {
  1176  		feeCap = args.GasPrice.ToInt()
  1177  	} else if args.MaxFeePerGas != nil {
  1178  		feeCap = args.MaxFeePerGas.ToInt()
  1179  	} else {
  1180  		feeCap = common.Big0
  1181  	}
  1182  	// Recap the highest gas limit with account's available balance.
  1183  	if feeCap.BitLen() != 0 {
  1184  		state, _, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1185  		if state == nil || err != nil {
  1186  			return 0, err
  1187  		}
  1188  		balance := state.GetBalance(*args.From) // from can't be nil
  1189  		available := new(big.Int).Set(balance)
  1190  		if args.Value != nil {
  1191  			if args.Value.ToInt().Cmp(available) >= 0 {
  1192  				return 0, errors.New("insufficient funds for transfer")
  1193  			}
  1194  			available.Sub(available, args.Value.ToInt())
  1195  		}
  1196  		allowance := new(big.Int).Div(available, feeCap)
  1197  
  1198  		// If the allowance is larger than maximum uint64, skip checking
  1199  		if allowance.IsUint64() && hi > allowance.Uint64() {
  1200  			transfer := args.Value
  1201  			if transfer == nil {
  1202  				transfer = new(hexutil.Big)
  1203  			}
  1204  			log.Warn("Gas estimation capped by limited funds", "original", hi, "balance", balance,
  1205  				"sent", transfer.ToInt(), "maxFeePerGas", feeCap, "fundable", allowance)
  1206  			hi = allowance.Uint64()
  1207  		}
  1208  	}
  1209  	// Recap the highest gas allowance with specified gascap.
  1210  	if gasCap != 0 && hi > gasCap {
  1211  		log.Warn("Caller gas above allowance, capping", "requested", hi, "cap", gasCap)
  1212  		hi = gasCap
  1213  	}
  1214  	cap = hi
  1215  
  1216  	// Create a helper to check if a gas allowance results in an executable transaction
  1217  	executable := func(gas uint64) (bool, *evmcore.ExecutionResult, error) {
  1218  		args.Gas = (*hexutil.Uint64)(&gas)
  1219  
  1220  		result, err := DoCall(ctx, b, args, blockNrOrHash, nil, 0, gasCap)
  1221  		if err != nil {
  1222  			if errors.Is(err, evmcore.ErrIntrinsicGas) {
  1223  				return true, nil, nil // Special case, raise gas limit
  1224  			}
  1225  			return true, nil, err // Bail out
  1226  		}
  1227  		return result.Failed(), result, nil
  1228  	}
  1229  	// Execute the binary search and hone in on an executable gas limit
  1230  	for lo+1 < hi {
  1231  		mid := (hi + lo) / 2
  1232  		failed, _, err := executable(mid)
  1233  
  1234  		// If the error is not nil(consensus error), it means the provided message
  1235  		// call or transaction will never be accepted no matter how much gas it is
  1236  		// assigned. Return the error directly, don't struggle any more.
  1237  		if err != nil {
  1238  			return 0, err
  1239  		}
  1240  		if failed {
  1241  			lo = mid
  1242  		} else {
  1243  			hi = mid
  1244  		}
  1245  	}
  1246  	// Reject the transaction as invalid if it still fails at the highest allowance
  1247  	if hi == cap {
  1248  		failed, result, err := executable(hi)
  1249  		if err != nil {
  1250  			return 0, err
  1251  		}
  1252  		if failed {
  1253  			if result != nil && result.Err != vm.ErrOutOfGas {
  1254  				if len(result.Revert()) > 0 {
  1255  					return 0, newRevertError(result)
  1256  				}
  1257  				return 0, result.Err
  1258  			}
  1259  			// Otherwise, the specified gas cap is too low
  1260  			return 0, fmt.Errorf("gas required exceeds allowance (%d)", cap)
  1261  		}
  1262  	}
  1263  	return hexutil.Uint64(hi), nil
  1264  }
  1265  
  1266  // EstimateGas returns an estimate of the amount of gas needed to execute the
  1267  // given transaction against the current pending block.
  1268  func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args TransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash) (hexutil.Uint64, error) {
  1269  	bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.LatestBlockNumber)
  1270  	if blockNrOrHash != nil {
  1271  		bNrOrHash = *blockNrOrHash
  1272  	}
  1273  	return DoEstimateGas(ctx, s.b, args, bNrOrHash, s.b.RPCGasCap())
  1274  }
  1275  
  1276  // ExecutionResult groups all structured logs emitted by the EVM
  1277  // while replaying a transaction in debug mode as well as transaction
  1278  // execution status, the amount of gas used and the return value
  1279  type ExecutionResult struct {
  1280  	Gas         uint64         `json:"gas"`
  1281  	Failed      bool           `json:"failed"`
  1282  	ReturnValue string         `json:"returnValue"`
  1283  	StructLogs  []StructLogRes `json:"structLogs"`
  1284  }
  1285  
  1286  // StructLogRes stores a structured log emitted by the EVM while replaying a
  1287  // transaction in debug mode
  1288  type StructLogRes struct {
  1289  	Pc      uint64             `json:"pc"`
  1290  	Op      string             `json:"op"`
  1291  	Gas     uint64             `json:"gas"`
  1292  	GasCost uint64             `json:"gasCost"`
  1293  	Depth   int                `json:"depth"`
  1294  	Error   string             `json:"error,omitempty"`
  1295  	Stack   *[]string          `json:"stack,omitempty"`
  1296  	Memory  *[]string          `json:"memory,omitempty"`
  1297  	Storage *map[string]string `json:"storage,omitempty"`
  1298  }
  1299  
  1300  // FormatLogs formats EVM returned structured logs for json output
  1301  func FormatLogs(logs []vm.StructLog) []StructLogRes {
  1302  	formatted := make([]StructLogRes, len(logs))
  1303  	for index, trace := range logs {
  1304  		formatted[index] = StructLogRes{
  1305  			Pc:      trace.Pc,
  1306  			Op:      trace.Op.String(),
  1307  			Gas:     trace.Gas,
  1308  			GasCost: trace.GasCost,
  1309  			Depth:   trace.Depth,
  1310  			Error:   trace.ErrorString(),
  1311  		}
  1312  		if trace.Stack != nil {
  1313  			stack := make([]string, len(trace.Stack))
  1314  			for i, stackValue := range trace.Stack {
  1315  				stack[i] = stackValue.Hex()
  1316  			}
  1317  			formatted[index].Stack = &stack
  1318  		}
  1319  		if trace.Memory != nil {
  1320  			memory := make([]string, 0, (len(trace.Memory)+31)/32)
  1321  			for i := 0; i+32 <= len(trace.Memory); i += 32 {
  1322  				memory = append(memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
  1323  			}
  1324  			formatted[index].Memory = &memory
  1325  		}
  1326  		if trace.Storage != nil {
  1327  			storage := make(map[string]string)
  1328  			for i, storageValue := range trace.Storage {
  1329  				storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
  1330  			}
  1331  			formatted[index].Storage = &storage
  1332  		}
  1333  	}
  1334  	return formatted
  1335  }
  1336  
  1337  type extBlockApi struct {
  1338  	bloom        types.Bloom
  1339  	receiptsRoot common.Hash
  1340  }
  1341  
  1342  // RPCMarshalHeader converts the given header to the RPC output .
  1343  func RPCMarshalHeader(head *evmcore.EvmHeader, ext extBlockApi) map[string]interface{} {
  1344  	result := map[string]interface{}{
  1345  		"number":           (*hexutil.Big)(head.Number),
  1346  		"epoch":            hexutil.Uint64(hash.Event(head.Hash).Epoch()),
  1347  		"hash":             head.Hash, // store EvmBlock's hash in extra, because extra is always empty
  1348  		"parentHash":       head.ParentHash,
  1349  		"nonce":            types.BlockNonce{},
  1350  		"mixHash":          common.Hash{},
  1351  		"sha3Uncles":       types.EmptyUncleHash,
  1352  		"logsBloom":        ext.bloom,
  1353  		"stateRoot":        head.Root,
  1354  		"miner":            head.Coinbase,
  1355  		"difficulty":       (*hexutil.Big)(new(big.Int)),
  1356  		"extraData":        hexutil.Bytes([]byte{}),
  1357  		"size":             hexutil.Uint64(head.EthHeader().Size()),
  1358  		"gasLimit":         hexutil.Uint64(0xffffffffffff), // don't use too much bits here to avoid parsing issues
  1359  		"gasUsed":          hexutil.Uint64(head.GasUsed),
  1360  		"timestamp":        hexutil.Uint64(head.Time.Unix()),
  1361  		"timestampNano":    hexutil.Uint64(head.Time),
  1362  		"transactionsRoot": head.TxHash,
  1363  		"receiptsRoot":     ext.receiptsRoot,
  1364  	}
  1365  	if head.BaseFee != nil {
  1366  		result["baseFeePerGas"] = (*hexutil.Big)(head.BaseFee)
  1367  	}
  1368  	return result
  1369  }
  1370  
  1371  // RPCMarshalBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
  1372  // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
  1373  // transaction hashes.
  1374  func RPCMarshalBlock(block *evmcore.EvmBlock, ext extBlockApi, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  1375  	fields := RPCMarshalHeader(block.Header(), ext)
  1376  	fields["size"] = hexutil.Uint64(block.EthBlock().Size())
  1377  
  1378  	if inclTx {
  1379  		formatTx := func(tx *types.Transaction) (interface{}, error) {
  1380  			return tx.Hash(), nil
  1381  		}
  1382  		if fullTx {
  1383  			formatTx = func(tx *types.Transaction) (interface{}, error) {
  1384  				return newRPCTransactionFromBlockHash(block, tx.Hash()), nil
  1385  			}
  1386  		}
  1387  		txs := block.Transactions
  1388  		transactions := make([]interface{}, len(txs))
  1389  		var err error
  1390  		for i, tx := range txs {
  1391  			if transactions[i], err = formatTx(tx); err != nil {
  1392  				return nil, err
  1393  			}
  1394  		}
  1395  		fields["transactions"] = transactions
  1396  	}
  1397  	uncles := noUncles
  1398  	uncleHashes := make([]common.Hash, len(uncles))
  1399  	for i, uncle := range uncles {
  1400  		uncleHashes[i] = uncle.Hash
  1401  	}
  1402  	fields["uncles"] = uncleHashes
  1403  
  1404  	return fields, nil
  1405  }
  1406  
  1407  // rpcMarshalHeader uses the generalized output filler, then adds the total difficulty field, which requires
  1408  // a `PublicBlockchainAPI`.
  1409  func (s *PublicBlockChainAPI) rpcMarshalHeader(header *evmcore.EvmHeader, ext extBlockApi) map[string]interface{} {
  1410  	fields := RPCMarshalHeader(header, ext)
  1411  	fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(header.Hash))
  1412  	return fields
  1413  }
  1414  
  1415  // rpcMarshalBlock uses the generalized output filler, then adds the total difficulty field, which requires
  1416  // a `PublicBlockchainAPI`.
  1417  func (s *PublicBlockChainAPI) rpcMarshalBlock(b *evmcore.EvmBlock, ext extBlockApi, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  1418  	fields, err := RPCMarshalBlock(b, ext, inclTx, fullTx)
  1419  	if err != nil {
  1420  		return nil, err
  1421  	}
  1422  	fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(b.Hash))
  1423  	return fields, err
  1424  }
  1425  
  1426  // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
  1427  type RPCTransaction struct {
  1428  	BlockHash        *common.Hash      `json:"blockHash"`
  1429  	BlockNumber      *hexutil.Big      `json:"blockNumber"`
  1430  	From             common.Address    `json:"from"`
  1431  	Gas              hexutil.Uint64    `json:"gas"`
  1432  	GasPrice         *hexutil.Big      `json:"gasPrice"`
  1433  	GasFeeCap        *hexutil.Big      `json:"maxFeePerGas,omitempty"`
  1434  	GasTipCap        *hexutil.Big      `json:"maxPriorityFeePerGas,omitempty"`
  1435  	Hash             common.Hash       `json:"hash"`
  1436  	Input            hexutil.Bytes     `json:"input"`
  1437  	Nonce            hexutil.Uint64    `json:"nonce"`
  1438  	To               *common.Address   `json:"to"`
  1439  	TransactionIndex *hexutil.Uint64   `json:"transactionIndex"`
  1440  	Value            *hexutil.Big      `json:"value"`
  1441  	Type             hexutil.Uint64    `json:"type"`
  1442  	Accesses         *types.AccessList `json:"accessList,omitempty"`
  1443  	ChainID          *hexutil.Big      `json:"chainId,omitempty"`
  1444  	V                *hexutil.Big      `json:"v"`
  1445  	R                *hexutil.Big      `json:"r"`
  1446  	S                *hexutil.Big      `json:"s"`
  1447  }
  1448  
  1449  // newRPCTransaction returns a transaction that will serialize to the RPC
  1450  // representation, with the given location metadata set (if available).
  1451  func newRPCTransaction(tx *types.Transaction, blockHash common.Hash, blockNumber uint64, index uint64, baseFee *big.Int) *RPCTransaction {
  1452  	// Determine the signer. For replay-protected transactions, use the most permissive
  1453  	// signer, because we assume that signers are backwards-compatible with old
  1454  	// transactions. For non-protected transactions, the homestead signer signer is used
  1455  	// because the return value of ChainId is zero for those transactions.
  1456  	var signer types.Signer
  1457  	if tx.Protected() {
  1458  		signer = gsignercache.Wrap(types.LatestSignerForChainID(tx.ChainId()))
  1459  	} else {
  1460  		signer = gsignercache.Wrap(types.HomesteadSigner{})
  1461  	}
  1462  	from, _ := internaltx.Sender(signer, tx)
  1463  	v, r, s := tx.RawSignatureValues()
  1464  	result := &RPCTransaction{
  1465  		Type:     hexutil.Uint64(tx.Type()),
  1466  		From:     from,
  1467  		Gas:      hexutil.Uint64(tx.Gas()),
  1468  		GasPrice: (*hexutil.Big)(tx.GasPrice()),
  1469  		Hash:     tx.Hash(),
  1470  		Input:    hexutil.Bytes(tx.Data()),
  1471  		Nonce:    hexutil.Uint64(tx.Nonce()),
  1472  		To:       tx.To(),
  1473  		Value:    (*hexutil.Big)(tx.Value()),
  1474  		V:        (*hexutil.Big)(v),
  1475  		R:        (*hexutil.Big)(r),
  1476  		S:        (*hexutil.Big)(s),
  1477  	}
  1478  	if blockHash != (common.Hash{}) {
  1479  		result.BlockHash = &blockHash
  1480  		result.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(blockNumber))
  1481  		result.TransactionIndex = (*hexutil.Uint64)(&index)
  1482  	}
  1483  	switch tx.Type() {
  1484  	case types.AccessListTxType:
  1485  		al := tx.AccessList()
  1486  		result.Accesses = &al
  1487  		result.ChainID = (*hexutil.Big)(tx.ChainId())
  1488  	case types.DynamicFeeTxType:
  1489  		al := tx.AccessList()
  1490  		result.Accesses = &al
  1491  		result.ChainID = (*hexutil.Big)(tx.ChainId())
  1492  		result.GasFeeCap = (*hexutil.Big)(tx.GasFeeCap())
  1493  		result.GasTipCap = (*hexutil.Big)(tx.GasTipCap())
  1494  		// if the transaction has been mined, compute the effective gas price
  1495  		if baseFee != nil && blockHash != (common.Hash{}) {
  1496  			// price = min(tip, gasFeeCap - baseFee) + baseFee
  1497  			price := math.BigMin(new(big.Int).Add(tx.GasTipCap(), baseFee), tx.GasFeeCap())
  1498  			result.GasPrice = (*hexutil.Big)(price)
  1499  		} else {
  1500  			result.GasPrice = (*hexutil.Big)(tx.GasFeeCap())
  1501  		}
  1502  	}
  1503  	return result
  1504  }
  1505  
  1506  // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation
  1507  func newRPCPendingTransaction(tx *types.Transaction, baseFee *big.Int) *RPCTransaction {
  1508  	return newRPCTransaction(tx, common.Hash{}, 0, 0, baseFee)
  1509  }
  1510  
  1511  // newRPCTransactionFromBlockIndex returns a transaction that will serialize to the RPC representation.
  1512  func newRPCTransactionFromBlockIndex(b *evmcore.EvmBlock, index uint64) *RPCTransaction {
  1513  	txs := b.Transactions
  1514  	if index >= uint64(len(txs)) {
  1515  		return nil
  1516  	}
  1517  	return newRPCTransaction(txs[index], b.Hash, b.NumberU64(), index, b.BaseFee)
  1518  }
  1519  
  1520  // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index.
  1521  func newRPCRawTransactionFromBlockIndex(b *evmcore.EvmBlock, index uint64) hexutil.Bytes {
  1522  	txs := b.Transactions
  1523  	if index >= uint64(len(txs)) {
  1524  		return nil
  1525  	}
  1526  	blob, _ := txs[index].MarshalBinary()
  1527  	return blob
  1528  }
  1529  
  1530  // newRPCTransactionFromBlockHash returns a transaction that will serialize to the RPC representation.
  1531  func newRPCTransactionFromBlockHash(b *evmcore.EvmBlock, hash common.Hash) *RPCTransaction {
  1532  	for idx, tx := range b.Transactions {
  1533  		if tx.Hash() == hash {
  1534  			return newRPCTransactionFromBlockIndex(b, uint64(idx))
  1535  		}
  1536  	}
  1537  	return nil
  1538  }
  1539  
  1540  // accessListResult returns an optional accesslist
  1541  // Its the result of the `debug_createAccessList` RPC call.
  1542  // It contains an error if the transaction itself failed.
  1543  type accessListResult struct {
  1544  	Accesslist *types.AccessList `json:"accessList"`
  1545  	Error      string            `json:"error,omitempty"`
  1546  	GasUsed    hexutil.Uint64    `json:"gasUsed"`
  1547  }
  1548  
  1549  // CreateAccessList creates a EIP-2930 type AccessList for the given transaction.
  1550  // Reexec and BlockNrOrHash can be specified to create the accessList on top of a certain state.
  1551  func (s *PublicBlockChainAPI) CreateAccessList(ctx context.Context, args TransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash) (*accessListResult, error) {
  1552  	bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
  1553  	if blockNrOrHash != nil {
  1554  		bNrOrHash = *blockNrOrHash
  1555  	}
  1556  	acl, gasUsed, vmerr, err := AccessList(ctx, s.b, bNrOrHash, args)
  1557  	if err != nil {
  1558  		return nil, err
  1559  	}
  1560  	result := &accessListResult{Accesslist: &acl, GasUsed: hexutil.Uint64(gasUsed)}
  1561  	if vmerr != nil {
  1562  		result.Error = vmerr.Error()
  1563  	}
  1564  	return result, nil
  1565  }
  1566  
  1567  // AccessList creates an access list for the given transaction.
  1568  // If the accesslist creation fails an error is returned.
  1569  // If the transaction itself fails, an vmErr is returned.
  1570  func AccessList(ctx context.Context, b Backend, blockNrOrHash rpc.BlockNumberOrHash, args TransactionArgs) (acl types.AccessList, gasUsed uint64, vmErr error, err error) {
  1571  	// Retrieve the execution context
  1572  	db, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1573  	if db == nil || err != nil {
  1574  		return nil, 0, nil, err
  1575  	}
  1576  	// If the gas amount is not set, extract this as it will depend on access
  1577  	// lists and we'll need to reestimate every time
  1578  	nogas := args.Gas == nil
  1579  
  1580  	// Ensure any missing fields are filled, extract the recipient and input data
  1581  	if err := args.setDefaults(ctx, b); err != nil {
  1582  		return nil, 0, nil, err
  1583  	}
  1584  	var to common.Address
  1585  	if args.To != nil {
  1586  		to = *args.To
  1587  	} else {
  1588  		to = crypto.CreateAddress(args.from(), uint64(*args.Nonce))
  1589  	}
  1590  	// Retrieve the precompiles since they don't need to be added to the access list
  1591  	precompiles := vm.ActivePrecompiles(b.ChainConfig().Rules(header.Number))
  1592  
  1593  	// Create an initial tracer
  1594  	prevTracer := vm.NewAccessListTracer(nil, args.from(), to, precompiles)
  1595  	if args.AccessList != nil {
  1596  		prevTracer = vm.NewAccessListTracer(*args.AccessList, args.from(), to, precompiles)
  1597  	}
  1598  	for {
  1599  		// Retrieve the current access list to expand
  1600  		accessList := prevTracer.AccessList()
  1601  		log.Trace("Creating access list", "input", accessList)
  1602  
  1603  		// If no gas amount was specified, each unique access list needs it's own
  1604  		// gas calculation. This is quite expensive, but we need to be accurate
  1605  		// and it's convered by the sender only anyway.
  1606  		if nogas {
  1607  			args.Gas = nil
  1608  			if err := args.setDefaults(ctx, b); err != nil {
  1609  				return nil, 0, nil, err // shouldn't happen, just in case
  1610  			}
  1611  		}
  1612  		// Copy the original db so we don't modify it
  1613  		statedb := db.Copy()
  1614  		// Set the accesslist to the last al
  1615  		args.AccessList = &accessList
  1616  		msg, err := args.ToMessage(b.RPCGasCap(), header.BaseFee)
  1617  		if err != nil {
  1618  			return nil, 0, nil, err
  1619  		}
  1620  
  1621  		// Apply the transaction with the access list tracer
  1622  		tracer := vm.NewAccessListTracer(accessList, args.from(), to, precompiles)
  1623  		config := u2u.DefaultVMConfig
  1624  		config.Tracer = tracer
  1625  		config.Debug = true
  1626  		config.NoBaseFee = true
  1627  		vmenv, _, err := b.GetEVM(ctx, msg, statedb, header, &config)
  1628  		if err != nil {
  1629  			return nil, 0, nil, err
  1630  		}
  1631  		res, err := evmcore.ApplyMessage(vmenv, msg, new(evmcore.GasPool).AddGas(msg.Gas()))
  1632  		if err != nil {
  1633  			return nil, 0, nil, fmt.Errorf("failed to apply transaction: %v err: %v", args.toTransaction().Hash(), err)
  1634  		}
  1635  		if tracer.Equal(prevTracer) {
  1636  			return accessList, res.UsedGas, res.Err, nil
  1637  		}
  1638  		prevTracer = tracer
  1639  	}
  1640  }
  1641  
  1642  // PublicTransactionPoolAPI exposes methods for the RPC interface
  1643  type PublicTransactionPoolAPI struct {
  1644  	b         Backend
  1645  	nonceLock *AddrLocker
  1646  	signer    types.Signer
  1647  }
  1648  
  1649  // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.
  1650  func NewPublicTransactionPoolAPI(b Backend, nonceLock *AddrLocker) *PublicTransactionPoolAPI {
  1651  	// The signer used by the API should always be the 'latest' known one because we expect
  1652  	// signers to be backwards-compatible with old transactions.
  1653  	signer := gsignercache.Wrap(types.LatestSignerForChainID(b.ChainConfig().ChainID))
  1654  	return &PublicTransactionPoolAPI{b, nonceLock, signer}
  1655  }
  1656  
  1657  // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
  1658  func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  1659  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1660  		n := hexutil.Uint(len(block.Transactions))
  1661  		return &n
  1662  	}
  1663  	return nil
  1664  }
  1665  
  1666  // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
  1667  func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  1668  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1669  		n := hexutil.Uint(len(block.Transactions))
  1670  		return &n
  1671  	}
  1672  	return nil
  1673  }
  1674  
  1675  // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
  1676  func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) *RPCTransaction {
  1677  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1678  		return newRPCTransactionFromBlockIndex(block, uint64(index))
  1679  	}
  1680  	return nil
  1681  }
  1682  
  1683  // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
  1684  func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) *RPCTransaction {
  1685  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1686  		return newRPCTransactionFromBlockIndex(block, uint64(index))
  1687  	}
  1688  	return nil
  1689  }
  1690  
  1691  // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
  1692  func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) hexutil.Bytes {
  1693  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1694  		return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1695  	}
  1696  	return nil
  1697  }
  1698  
  1699  // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index.
  1700  func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) hexutil.Bytes {
  1701  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1702  		return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1703  	}
  1704  	return nil
  1705  }
  1706  
  1707  // GetTransactionCount returns the number of transactions the given address has sent for the given block number
  1708  func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Uint64, error) {
  1709  	// Ask transaction pool for the nonce which includes pending transactions
  1710  	if blockNr, ok := blockNrOrHash.Number(); ok && blockNr == rpc.PendingBlockNumber {
  1711  		nonce, err := s.b.GetPoolNonce(ctx, address)
  1712  		if err != nil {
  1713  			return nil, err
  1714  		}
  1715  		return (*hexutil.Uint64)(&nonce), nil
  1716  	}
  1717  	// Resolve block number and use its state to ask for the nonce
  1718  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1719  	if state == nil || err != nil {
  1720  		return nil, err
  1721  	}
  1722  	nonce := state.GetNonce(address)
  1723  	return (*hexutil.Uint64)(&nonce), state.Error()
  1724  }
  1725  
  1726  // GetTransactionByHash returns the transaction for the given hash
  1727  func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) (*RPCTransaction, error) {
  1728  	// Try to return an already finalized transaction
  1729  	tx, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1730  	if err != nil {
  1731  		return nil, err
  1732  	}
  1733  	if tx != nil {
  1734  		header, err := s.b.HeaderByNumber(ctx, rpc.BlockNumber(blockNumber))
  1735  		if header == nil || err != nil {
  1736  			return nil, err
  1737  		}
  1738  		return newRPCTransaction(tx, header.Hash, blockNumber, index, header.BaseFee), nil
  1739  	}
  1740  	// No finalized transaction, try to retrieve it from the pool
  1741  	if tx := s.b.GetPoolTransaction(hash); tx != nil {
  1742  		return newRPCPendingTransaction(tx, s.b.MinGasPrice()), nil
  1743  	}
  1744  
  1745  	// Transaction unknown, return as such
  1746  	return nil, nil
  1747  }
  1748  
  1749  // GetRawTransactionByHash returns the bytes of the transaction for the given hash.
  1750  func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  1751  	// Retrieve a finalized transaction, or a pooled otherwise
  1752  	tx, _, _, err := s.b.GetTransaction(ctx, hash)
  1753  	if err != nil {
  1754  		return nil, err
  1755  	}
  1756  	if tx == nil {
  1757  		if tx = s.b.GetPoolTransaction(hash); tx == nil {
  1758  			// Transaction not found anywhere, abort
  1759  			return nil, nil
  1760  		}
  1761  	}
  1762  	// Serialize to RLP and return
  1763  	return tx.MarshalBinary()
  1764  }
  1765  
  1766  // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  1767  func (s *PublicTransactionPoolAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) {
  1768  	tx, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1769  	if tx == nil || err != nil {
  1770  		return nil, err
  1771  	}
  1772  	header, err := s.b.HeaderByNumber(ctx, rpc.BlockNumber(blockNumber)) // retrieve header to get block hash
  1773  	if header == nil || err != nil {
  1774  		return nil, err
  1775  	}
  1776  	receipts, err := s.b.GetReceiptsByNumber(ctx, rpc.BlockNumber(blockNumber))
  1777  	if receipts == nil || err != nil {
  1778  		return nil, err
  1779  	}
  1780  	if receipts.Len() <= int(index) {
  1781  		return nil, nil
  1782  	}
  1783  	receipt := receipts[index]
  1784  
  1785  	for _, l := range receipt.Logs {
  1786  		l.TxHash = hash
  1787  		l.BlockHash = header.Hash
  1788  		l.BlockNumber = blockNumber
  1789  	}
  1790  
  1791  	// Derive the sender.
  1792  	bigblock := new(big.Int).SetUint64(blockNumber)
  1793  	signer := gsignercache.Wrap(types.MakeSigner(s.b.ChainConfig(), bigblock))
  1794  	from, _ := internaltx.Sender(signer, tx)
  1795  
  1796  	fields := map[string]interface{}{
  1797  		"blockHash":         header.Hash,
  1798  		"blockNumber":       hexutil.Uint64(blockNumber),
  1799  		"transactionHash":   hash,
  1800  		"transactionIndex":  hexutil.Uint64(index),
  1801  		"from":              from,
  1802  		"to":                tx.To(),
  1803  		"gasUsed":           hexutil.Uint64(receipt.GasUsed),
  1804  		"cumulativeGasUsed": hexutil.Uint64(receipt.CumulativeGasUsed),
  1805  		"contractAddress":   nil,
  1806  		"logs":              receipt.Logs,
  1807  		"logsBloom":         &receipt.Bloom,
  1808  		"type":              hexutil.Uint(tx.Type()),
  1809  	}
  1810  	// Assign the effective gas price paid
  1811  	if header.BaseFee == nil {
  1812  		fields["effectiveGasPrice"] = hexutil.Uint64(tx.GasPrice().Uint64())
  1813  	} else {
  1814  		gasPrice := new(big.Int).Add(header.BaseFee, tx.EffectiveGasTipValue(header.BaseFee))
  1815  		fields["effectiveGasPrice"] = hexutil.Uint64(gasPrice.Uint64())
  1816  	}
  1817  	// Assign receipt status or post state.
  1818  	if len(receipt.PostState) > 0 {
  1819  		fields["root"] = hexutil.Bytes(receipt.PostState)
  1820  	} else {
  1821  		fields["status"] = hexutil.Uint(receipt.Status)
  1822  	}
  1823  	if receipt.Logs == nil {
  1824  		fields["logs"] = [][]*types.Log{}
  1825  	}
  1826  	// If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  1827  	if tx.To() == nil {
  1828  		fields["contractAddress"] = receipt.ContractAddress
  1829  	}
  1830  	return fields, nil
  1831  }
  1832  
  1833  // sign is a helper function that signs a transaction with the private key of the given address.
  1834  func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
  1835  	// Look up the wallet containing the requested signer
  1836  	account := accounts.Account{Address: addr}
  1837  
  1838  	wallet, err := s.b.AccountManager().Find(account)
  1839  	if err != nil {
  1840  		return nil, err
  1841  	}
  1842  	// Request the wallet to sign the transaction
  1843  	return wallet.SignTx(account, tx, s.b.ChainConfig().ChainID)
  1844  }
  1845  
  1846  // SubmitTransaction is a helper function that submits tx to txPool and logs a message.
  1847  func SubmitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (common.Hash, error) {
  1848  	// If the transaction fee cap is already specified, ensure the
  1849  	// fee of the given transaction is _reasonable_.
  1850  	if err := checkTxFee(tx.GasPrice(), tx.Gas(), b.RPCTxFeeCap()); err != nil {
  1851  		return common.Hash{}, err
  1852  	}
  1853  	if !b.UnprotectedAllowed() && !tx.Protected() {
  1854  		// Ensure only eip155 signed transactions are submitted if EIP155Required is set.
  1855  		return common.Hash{}, errors.New("only replay-protected (EIP-155) transactions allowed over RPC")
  1856  	}
  1857  	if err := b.SendTx(ctx, tx); err != nil {
  1858  		return common.Hash{}, err
  1859  	} // Print a log with full tx details for manual investigations and interventions
  1860  	signer := gsignercache.Wrap(types.MakeSigner(b.ChainConfig(), b.CurrentBlock().Number))
  1861  	from, err := types.Sender(signer, tx)
  1862  	if err != nil {
  1863  		return common.Hash{}, err
  1864  	}
  1865  
  1866  	if tx.To() == nil {
  1867  		addr := crypto.CreateAddress(from, tx.Nonce())
  1868  		log.Info("Submitted contract creation", "hash", tx.Hash().Hex(), "from", from, "nonce", tx.Nonce(), "contract", addr.Hex(), "value", tx.Value())
  1869  	} else {
  1870  		log.Info("Submitted transaction", "hash", tx.Hash().Hex(), "from", from, "nonce", tx.Nonce(), "recipient", tx.To(), "value", tx.Value())
  1871  	}
  1872  	return tx.Hash(), nil
  1873  }
  1874  
  1875  // SendTransaction creates a transaction for the given argument, sign it and submit it to the
  1876  // transaction pool.
  1877  func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args TransactionArgs) (common.Hash, error) {
  1878  	// Look up the wallet containing the requested signer
  1879  	account := accounts.Account{Address: args.from()}
  1880  
  1881  	wallet, err := s.b.AccountManager().Find(account)
  1882  	if err != nil {
  1883  		return common.Hash{}, err
  1884  	}
  1885  
  1886  	if args.Nonce == nil {
  1887  		// Hold the addresse's mutex around signing to prevent concurrent assignment of
  1888  		// the same nonce to multiple accounts.
  1889  		s.nonceLock.LockAddr(args.from())
  1890  		defer s.nonceLock.UnlockAddr(args.from())
  1891  	}
  1892  
  1893  	// Set some sanity defaults and terminate on failure
  1894  	if err := args.setDefaults(ctx, s.b); err != nil {
  1895  		return common.Hash{}, err
  1896  	}
  1897  	// Assemble the transaction and sign with the wallet
  1898  	tx := args.toTransaction()
  1899  
  1900  	signed, err := wallet.SignTx(account, tx, s.b.ChainConfig().ChainID)
  1901  	if err != nil {
  1902  		return common.Hash{}, err
  1903  	}
  1904  	return SubmitTransaction(ctx, s.b, signed)
  1905  }
  1906  
  1907  // FillTransaction fills the defaults (nonce, gas, gasPrice or 1559 fields)
  1908  // on a given unsigned transaction, and returns it to the caller for further
  1909  // processing (signing + broadcast).
  1910  func (s *PublicTransactionPoolAPI) FillTransaction(ctx context.Context, args TransactionArgs) (*SignTransactionResult, error) {
  1911  	// Set some sanity defaults and terminate on failure
  1912  	if err := args.setDefaults(ctx, s.b); err != nil {
  1913  		return nil, err
  1914  	}
  1915  	// Assemble the transaction and obtain rlp
  1916  	tx := args.toTransaction()
  1917  	data, err := tx.MarshalBinary()
  1918  	if err != nil {
  1919  		return nil, err
  1920  	}
  1921  	return &SignTransactionResult{data, tx}, nil
  1922  }
  1923  
  1924  // SendRawTransaction will add the signed transaction to the transaction pool.
  1925  // The sender is responsible for signing the transaction and using the correct nonce.
  1926  func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, encodedTx hexutil.Bytes) (common.Hash, error) {
  1927  	tx := new(types.Transaction)
  1928  	if err := tx.UnmarshalBinary(encodedTx); err != nil {
  1929  		return common.Hash{}, err
  1930  	}
  1931  	return SubmitTransaction(ctx, s.b, tx)
  1932  }
  1933  
  1934  // Sign calculates an ECDSA signature for:
  1935  // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message).
  1936  //
  1937  // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  1938  // where the V value will be 27 or 28 for legacy reasons.
  1939  //
  1940  // The account associated with addr must be unlocked.
  1941  //
  1942  // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
  1943  func (s *PublicTransactionPoolAPI) Sign(addr common.Address, data hexutil.Bytes) (hexutil.Bytes, error) {
  1944  	// Look up the wallet containing the requested signer
  1945  	account := accounts.Account{Address: addr}
  1946  
  1947  	wallet, err := s.b.AccountManager().Find(account)
  1948  	if err != nil {
  1949  		return nil, err
  1950  	}
  1951  	// Sign the requested hash with the wallet
  1952  	signature, err := wallet.SignText(account, data)
  1953  	if err == nil {
  1954  		signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  1955  	}
  1956  	return signature, err
  1957  }
  1958  
  1959  // SignTransactionResult represents a RLP encoded signed transaction.
  1960  type SignTransactionResult struct {
  1961  	Raw hexutil.Bytes      `json:"raw"`
  1962  	Tx  *types.Transaction `json:"tx"`
  1963  }
  1964  
  1965  // SignTransaction will sign the given transaction with the from account.
  1966  // The node needs to have the private key of the account corresponding with
  1967  // the given from address and it needs to be unlocked.
  1968  func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args TransactionArgs) (*SignTransactionResult, error) {
  1969  	if args.Gas == nil {
  1970  		return nil, fmt.Errorf("gas not specified")
  1971  	}
  1972  	if args.GasPrice == nil && (args.MaxPriorityFeePerGas == nil || args.MaxFeePerGas == nil) {
  1973  		return nil, fmt.Errorf("missing gasPrice or maxFeePerGas/maxPriorityFeePerGas")
  1974  	}
  1975  	if args.Nonce == nil {
  1976  		return nil, fmt.Errorf("nonce not specified")
  1977  	}
  1978  	if err := args.setDefaults(ctx, s.b); err != nil {
  1979  		return nil, err
  1980  	}
  1981  	// Before actually sign the transaction, ensure the transaction fee is reasonable.
  1982  	tx := args.toTransaction()
  1983  	if err := checkTxFee(tx.GasPrice(), tx.Gas(), s.b.RPCTxFeeCap()); err != nil {
  1984  		return nil, err
  1985  	}
  1986  	signed, err := s.sign(args.from(), tx)
  1987  	if err != nil {
  1988  		return nil, err
  1989  	}
  1990  	data, err := signed.MarshalBinary()
  1991  	if err != nil {
  1992  		return nil, err
  1993  	}
  1994  	return &SignTransactionResult{data, signed}, nil
  1995  }
  1996  
  1997  // PendingTransactions returns the transactions that are in the transaction pool
  1998  // and have a from address that is one of the accounts this node manages.
  1999  func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error) {
  2000  	pending, err := s.b.GetPoolTransactions()
  2001  	if err != nil {
  2002  		return nil, err
  2003  	}
  2004  	accounts := make(map[common.Address]struct{})
  2005  	for _, wallet := range s.b.AccountManager().Wallets() {
  2006  		for _, account := range wallet.Accounts() {
  2007  			accounts[account.Address] = struct{}{}
  2008  		}
  2009  	}
  2010  	transactions := make([]*RPCTransaction, 0, len(pending))
  2011  	for _, tx := range pending {
  2012  		from, _ := internaltx.Sender(s.signer, tx)
  2013  		if _, exists := accounts[from]; exists {
  2014  			transactions = append(transactions, newRPCPendingTransaction(tx, s.b.MinGasPrice()))
  2015  		}
  2016  	}
  2017  	return transactions, nil
  2018  }
  2019  
  2020  // Resend accepts an existing transaction and a new gas price and limit. It will remove
  2021  // the given transaction from the pool and reinsert it with the new gas price and limit.
  2022  func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs TransactionArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) {
  2023  	if sendArgs.Nonce == nil {
  2024  		return common.Hash{}, fmt.Errorf("missing transaction nonce in transaction spec")
  2025  	}
  2026  	if err := sendArgs.setDefaults(ctx, s.b); err != nil {
  2027  		return common.Hash{}, err
  2028  	}
  2029  	matchTx := sendArgs.toTransaction()
  2030  
  2031  	// Before replacing the old transaction, ensure the _new_ transaction fee is reasonable.
  2032  	var price = matchTx.GasPrice()
  2033  	if gasPrice != nil {
  2034  		price = gasPrice.ToInt()
  2035  	}
  2036  	var gas = matchTx.Gas()
  2037  	if gasLimit != nil {
  2038  		gas = uint64(*gasLimit)
  2039  	}
  2040  	if err := checkTxFee(price, gas, s.b.RPCTxFeeCap()); err != nil {
  2041  		return common.Hash{}, err
  2042  	}
  2043  	// Iterate the pending list for replacement
  2044  	pending, err := s.b.GetPoolTransactions()
  2045  	if err != nil {
  2046  		return common.Hash{}, err
  2047  	}
  2048  
  2049  	for _, p := range pending {
  2050  		wantSigHash := s.signer.Hash(matchTx)
  2051  		pFrom, err := types.Sender(s.signer, p)
  2052  		if err == nil && pFrom == sendArgs.from() && s.signer.Hash(p) == wantSigHash {
  2053  			// Match. Re-sign and send the transaction.
  2054  			if gasPrice != nil && (*big.Int)(gasPrice).Sign() != 0 {
  2055  				sendArgs.GasPrice = gasPrice
  2056  			}
  2057  			if gasLimit != nil && *gasLimit != 0 {
  2058  				sendArgs.Gas = gasLimit
  2059  			}
  2060  			signedTx, err := s.sign(sendArgs.from(), sendArgs.toTransaction())
  2061  			if err != nil {
  2062  				return common.Hash{}, err
  2063  			}
  2064  			if err = s.b.SendTx(ctx, signedTx); err != nil {
  2065  				return common.Hash{}, err
  2066  			}
  2067  			return signedTx.Hash(), nil
  2068  		}
  2069  	}
  2070  	return common.Hash{}, fmt.Errorf("transaction %#x not found", matchTx.Hash())
  2071  }
  2072  
  2073  // PublicDebugAPI is the collection of Ethereum APIs exposed over the public
  2074  // debugging endpoint.
  2075  type PublicDebugAPI struct {
  2076  	b Backend
  2077  }
  2078  
  2079  // NewPublicDebugAPI creates a new API definition for the public debug methods
  2080  // of the Ethereum service.
  2081  func NewPublicDebugAPI(b Backend) *PublicDebugAPI {
  2082  	return &PublicDebugAPI{b: b}
  2083  }
  2084  
  2085  // GetBlockRlp retrieves the RLP encoded for of a single block.
  2086  func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error) {
  2087  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  2088  	if block == nil {
  2089  		return "", fmt.Errorf("block #%d not found", number)
  2090  	}
  2091  	encoded, err := rlp.EncodeToBytes(block)
  2092  	if err != nil {
  2093  		return "", err
  2094  	}
  2095  	return fmt.Sprintf("%x", encoded), nil
  2096  }
  2097  
  2098  // TestSignCliqueBlock fetches the given block number, and attempts to sign it as a clique header with the
  2099  // given address, returning the address of the recovered signature
  2100  //
  2101  // This is a temporary method to debug the externalsigner integration,
  2102  func (api *PublicDebugAPI) TestSignCliqueBlock(ctx context.Context, address common.Address, number uint64) (common.Address, error) {
  2103  	return common.Address{}, errors.New("Clique isn't supported")
  2104  }
  2105  
  2106  // PrintBlock retrieves a block and returns its pretty printed form.
  2107  func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) {
  2108  	block, err := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  2109  	if err != nil {
  2110  		return "", err
  2111  	}
  2112  	if block == nil {
  2113  		return "", fmt.Errorf("block #%d not found", number)
  2114  	}
  2115  	return spew.Sdump(block), nil
  2116  }
  2117  
  2118  // BlocksTransactionTimes returns the map time => number of transactions
  2119  // This data may be used to draw a histogram to calculate a peak TPS of a range of blocks
  2120  func (api *PublicDebugAPI) BlocksTransactionTimes(ctx context.Context, untilBlock rpc.BlockNumber, maxBlocks hexutil.Uint64) (map[hexutil.Uint64]hexutil.Uint, error) {
  2121  
  2122  	until, err := api.b.HeaderByNumber(ctx, untilBlock)
  2123  	if until == nil || err != nil {
  2124  		return nil, err
  2125  	}
  2126  	untilN := until.Number.Uint64()
  2127  	times := map[hexutil.Uint64]hexutil.Uint{}
  2128  	for i := untilN; i >= 1 && i+uint64(maxBlocks) > untilN; i-- {
  2129  		b, err := api.b.BlockByNumber(ctx, rpc.BlockNumber(i))
  2130  		if b == nil || err != nil {
  2131  			return nil, err
  2132  		}
  2133  		if b.Transactions.Len() == 0 {
  2134  			continue
  2135  		}
  2136  		times[hexutil.Uint64(b.Time)] += hexutil.Uint(b.Transactions.Len())
  2137  	}
  2138  
  2139  	return times, nil
  2140  }
  2141  
  2142  // TraceConfig holds extra parameters to trace functions.
  2143  type TraceConfig struct {
  2144  	*vm.LogConfig
  2145  	Tracer  *string
  2146  	Timeout *string
  2147  	Reexec  *uint64
  2148  }
  2149  
  2150  // TraceCallConfig is the config for traceCall API. It holds one more
  2151  // field to override the state for tracing.
  2152  type TraceCallConfig struct {
  2153  	TraceConfig
  2154  	StateOverrides *StateOverride
  2155  	BlockOverrides *BlockOverrides
  2156  }
  2157  
  2158  // TraceTransaction returns the structured logs created during the execution of EVM
  2159  // and returns them as a JSON object.
  2160  func (api *PublicDebugAPI) TraceTransaction(ctx context.Context, hash common.Hash, config *TraceConfig) (interface{}, error) {
  2161  	tx, blockNumber, index, err := api.b.GetTransaction(ctx, hash)
  2162  	if err != nil {
  2163  		return nil, err
  2164  	}
  2165  	if tx == nil {
  2166  		return nil, fmt.Errorf("transaction %s not found", hash.Hex())
  2167  	}
  2168  
  2169  	// It shouldn't happen in practice.
  2170  	if blockNumber == 0 {
  2171  		return nil, errors.New("genesis is not traceable")
  2172  	}
  2173  
  2174  	block, err := api.b.BlockByNumber(ctx, rpc.BlockNumber(blockNumber))
  2175  	if err != nil {
  2176  		return nil, errors.New("cannot get block from db")
  2177  	}
  2178  
  2179  	msg, vmctx, statedb, err := api.stateAtTransaction(ctx, block, int(index))
  2180  	if err != nil {
  2181  		return nil, err
  2182  	}
  2183  
  2184  	txctx := &tracers.Context{
  2185  		BlockHash: block.Hash,
  2186  		TxIndex:   int(index),
  2187  		TxHash:    hash,
  2188  	}
  2189  
  2190  	return api.traceTx(ctx, msg, txctx, vmctx, statedb, config)
  2191  }
  2192  
  2193  // TraceCall lets you trace a given eth_call. It collects the structured logs
  2194  // created during the execution of EVM if the given transaction was added on
  2195  // top of the provided block and returns them as a JSON object.
  2196  // You can provide -2 as a block number to trace on top of the pending block.
  2197  func (api *PublicDebugAPI) TraceCall(ctx context.Context, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, config *TraceCallConfig) (interface{}, error) {
  2198  	// Try to retrieve the specified block
  2199  	var (
  2200  		err   error
  2201  		block *evmcore.EvmBlock
  2202  	)
  2203  	if hash, ok := blockNrOrHash.Hash(); ok {
  2204  		block, err = api.blockByHash(ctx, hash)
  2205  	} else if number, ok := blockNrOrHash.Number(); ok {
  2206  		block, err = api.blockByNumber(ctx, number)
  2207  	} else {
  2208  		return nil, errors.New("invalid arguments; neither block nor hash specified")
  2209  	}
  2210  	if err != nil {
  2211  		return nil, err
  2212  	}
  2213  	// try to recompute the state
  2214  	reexec := defaultTraceReexec
  2215  	if config != nil && config.Reexec != nil {
  2216  		reexec = *config.Reexec
  2217  	}
  2218  	statedb, err := api.b.StateAtBlock(ctx, block, reexec, nil, true)
  2219  	if err != nil {
  2220  		return nil, err
  2221  	}
  2222  	// Apply the customized state rules if required.
  2223  	if config != nil {
  2224  		if err := config.StateOverrides.Apply(statedb); err != nil {
  2225  			return nil, err
  2226  		}
  2227  	}
  2228  	// Execute the trace
  2229  	msg, err := args.ToMessage(api.b.RPCGasCap(), block.EthHeader().BaseFee)
  2230  	if err != nil {
  2231  		return nil, err
  2232  	}
  2233  	vmctx := evmcore.NewEVMBlockContext(block.Header(), api.chainContext(ctx), nil)
  2234  
  2235  	var traceConfig *TraceConfig
  2236  	if config != nil {
  2237  		traceConfig = &TraceConfig{
  2238  			LogConfig: config.LogConfig,
  2239  			Tracer:    config.Tracer,
  2240  			Timeout:   config.Timeout,
  2241  			Reexec:    config.Reexec,
  2242  		}
  2243  	}
  2244  	return api.traceTx(ctx, msg, new(tracers.Context), vmctx, statedb, traceConfig)
  2245  }
  2246  
  2247  // traceTx configures a new tracer according to the provided configuration, and
  2248  // executes the given message in the provided environment. The return value will
  2249  // be tracer dependent.
  2250  func (api *PublicDebugAPI) traceTx(ctx context.Context, message evmcore.Message, txctx *tracers.Context, vmctx vm.BlockContext, statedb *state.StateDB, config *TraceConfig) (interface{}, error) {
  2251  	// Assemble the structured logger or the JavaScript tracer
  2252  	var (
  2253  		tracer    vm.Tracer
  2254  		err       error
  2255  		txContext = evmcore.NewEVMTxContext(message)
  2256  	)
  2257  
  2258  	switch {
  2259  	case config == nil:
  2260  		tracer = vm.NewStructLogger(nil)
  2261  	case config.Tracer != nil:
  2262  		// Define a meaningful timeout of a single transaction trace
  2263  		timeout := defaultTraceTimeout
  2264  		if config.Timeout != nil {
  2265  			if timeout, err = time.ParseDuration(*config.Timeout); err != nil {
  2266  				return nil, err
  2267  			}
  2268  		}
  2269  		if t, err := tracers.New(*config.Tracer, txctx); err != nil {
  2270  			return nil, err
  2271  		} else {
  2272  			deadlineCtx, cancel := context.WithTimeout(ctx, timeout)
  2273  			go func() {
  2274  				<-deadlineCtx.Done()
  2275  				if errors.Is(deadlineCtx.Err(), context.DeadlineExceeded) {
  2276  					t.Stop(errors.New("execution timeout"))
  2277  				}
  2278  			}()
  2279  			defer cancel()
  2280  			tracer = t
  2281  		}
  2282  	default:
  2283  		tracer = vm.NewStructLogger(config.LogConfig)
  2284  	}
  2285  
  2286  	// Run the transaction with tracing enabled.
  2287  	evmconfig := u2u.DefaultVMConfig
  2288  	evmconfig.Tracer = tracer
  2289  	evmconfig.Debug = true
  2290  	evmconfig.NoBaseFee = true
  2291  	vmenv := vm.NewEVM(vmctx, txContext, statedb, api.b.ChainConfig(), evmconfig)
  2292  
  2293  	// Call Prepare to clear out the statedb access list
  2294  	statedb.Prepare(txctx.TxHash, txctx.TxIndex)
  2295  
  2296  	result, err := evmcore.ApplyMessage(vmenv, message, new(evmcore.GasPool).AddGas(message.Gas()))
  2297  	if err != nil {
  2298  		return nil, fmt.Errorf("tracing failed: %w", err)
  2299  	}
  2300  
  2301  	// Depending on the tracer type, format and return the output.
  2302  	switch tracer := tracer.(type) {
  2303  	case *vm.StructLogger:
  2304  		// If the result contains a revert reason, return it.
  2305  		returnVal := fmt.Sprintf("%x", result.Return())
  2306  		if len(result.Revert()) > 0 {
  2307  			returnVal = fmt.Sprintf("%x", result.Revert())
  2308  		}
  2309  		return &ExecutionResult{
  2310  			Gas:         result.UsedGas,
  2311  			Failed:      result.Failed(),
  2312  			ReturnValue: returnVal,
  2313  			StructLogs:  FormatLogs(tracer.StructLogs()),
  2314  		}, nil
  2315  
  2316  	case *tracers.Tracer:
  2317  		result, err := tracer.GetResult()
  2318  		if err != nil && result == nil {
  2319  			// Only for tracer called callTracer
  2320  			if config.Tracer != nil && strings.Compare(*config.Tracer, "callTracer") == 0 {
  2321  				if strings.Contains(err.Error(), "cannot read property 'toString' of undefined") {
  2322  					log.Debug("error when debug with callTracer", "err", err.Error())
  2323  					callTracer, _ := tracers.New(*config.Tracer, txctx)
  2324  					callTracer.CaptureStart(vmenv, message.From(), *message.To(), false, message.Data(), message.Gas(), message.Value())
  2325  					callTracer.CaptureEnd([]byte{}, message.Gas(), time.Duration(0), fmt.Errorf("execution reverted"))
  2326  					result, err = callTracer.GetResult()
  2327  				}
  2328  			}
  2329  		}
  2330  		return result, err
  2331  
  2332  	default:
  2333  		panic(fmt.Sprintf("bad tracer type %T", tracer))
  2334  	}
  2335  }
  2336  
  2337  // txTraceResult is the result of a single transaction trace.
  2338  type txTraceResult struct {
  2339  	Result interface{} `json:"result,omitempty"` // Trace results produced by the tracer
  2340  	Error  string      `json:"error,omitempty"`  // Trace failure produced by the tracer
  2341  }
  2342  
  2343  // txTraceTask represents a single transaction trace task when an entire block
  2344  // is being traced.
  2345  type txTraceTask struct {
  2346  	statedb *state.StateDB // Intermediate state prepped for tracing
  2347  	index   int            // Transaction offset in the block
  2348  }
  2349  
  2350  // TraceBlockByNumber returns the structured logs created during the execution of
  2351  // EVM and returns them as a JSON object.
  2352  func (api *PublicDebugAPI) TraceBlockByNumber(ctx context.Context, number rpc.BlockNumber, config *TraceConfig) ([]*txTraceResult, error) {
  2353  	block, err := api.blockByNumber(ctx, number)
  2354  	if err != nil {
  2355  		return nil, err
  2356  	}
  2357  	return api.traceBlock(ctx, block, config)
  2358  }
  2359  
  2360  // TraceBlockByHash returns the structured logs created during the execution of
  2361  // EVM and returns them as a JSON object.
  2362  func (api *PublicDebugAPI) TraceBlockByHash(ctx context.Context, hash common.Hash, config *TraceConfig) ([]*txTraceResult, error) {
  2363  	block, err := api.blockByHash(ctx, hash)
  2364  	if err != nil {
  2365  		return nil, err
  2366  	}
  2367  	return api.traceBlock(ctx, block, config)
  2368  }
  2369  
  2370  // chainContext constructs the context reader which is used by the evm for reading
  2371  // the necessary chain context.
  2372  func (api *PublicDebugAPI) chainContext(ctx context.Context) evmcore.DummyChain {
  2373  	return NewChainContext(ctx, api.b)
  2374  }
  2375  
  2376  // blockByNumber is the wrapper of the chain access function offered by the backend.
  2377  // It will return an error if the block is not found.
  2378  func (api *PublicDebugAPI) blockByNumber(ctx context.Context, number rpc.BlockNumber) (*evmcore.EvmBlock, error) {
  2379  	block, err := api.b.BlockByNumber(ctx, number)
  2380  	if err != nil {
  2381  		return nil, err
  2382  	}
  2383  	if block == nil {
  2384  		return nil, fmt.Errorf("block #%d not found", number)
  2385  	}
  2386  	return block, nil
  2387  }
  2388  
  2389  // blockByHash is the wrapper of the chain access function offered by the backend.
  2390  // It will return an error if the block is not found.
  2391  func (api *PublicDebugAPI) blockByHash(ctx context.Context, hash common.Hash) (*evmcore.EvmBlock, error) {
  2392  	block, err := api.b.BlockByHash(ctx, hash)
  2393  	if err != nil {
  2394  		return nil, err
  2395  	}
  2396  	if block == nil {
  2397  		return nil, fmt.Errorf("block %s not found", hash.Hex())
  2398  	}
  2399  	return block, nil
  2400  }
  2401  
  2402  // traceBlock configures a new tracer according to the provided configuration, and
  2403  // executes all the transactions contained within. The return value will be one item
  2404  // per transaction, dependent on the requestd tracer.
  2405  func (api *PublicDebugAPI) traceBlock(ctx context.Context, block *evmcore.EvmBlock, config *TraceConfig) ([]*txTraceResult, error) {
  2406  	if block.NumberU64() == 0 {
  2407  		return nil, errors.New("genesis is not traceable")
  2408  	}
  2409  	statedb, _, err := api.b.StateAndHeaderByNumberOrHash(ctx, rpc.BlockNumberOrHashWithHash(block.ParentHash, false))
  2410  	if err != nil {
  2411  		return nil, err
  2412  	}
  2413  	// Execute all the transaction contained within the block concurrently
  2414  	var (
  2415  		signer  = types.MakeSigner(api.b.ChainConfig(), block.Number)
  2416  		txs     = block.Transactions
  2417  		results = make([]*txTraceResult, len(txs))
  2418  
  2419  		pend = new(sync.WaitGroup)
  2420  		jobs = make(chan *txTraceTask, len(txs))
  2421  	)
  2422  	threads := runtime.NumCPU()
  2423  	if threads > len(txs) {
  2424  		threads = len(txs)
  2425  	}
  2426  
  2427  	blockHeader := block.Header()
  2428  	blockHash := block.Hash
  2429  	for th := 0; th < threads; th++ {
  2430  		pend.Add(1)
  2431  		go func() {
  2432  			defer pend.Done()
  2433  			blockCtx := api.b.GetBlockContext(blockHeader)
  2434  
  2435  			// Fetch and execute the next transaction trace tasks
  2436  			for task := range jobs {
  2437  				msg, _ := txs[task.index].AsMessage(signer, block.BaseFee)
  2438  				txctx := &tracers.Context{
  2439  					BlockHash: blockHash,
  2440  					TxIndex:   task.index,
  2441  					TxHash:    txs[task.index].Hash(),
  2442  				}
  2443  				res, err := api.traceTx(ctx, msg, txctx, blockCtx, task.statedb, config)
  2444  				if err != nil {
  2445  					results[task.index] = &txTraceResult{Error: err.Error()}
  2446  					continue
  2447  				}
  2448  				results[task.index] = &txTraceResult{Result: res}
  2449  			}
  2450  		}()
  2451  	}
  2452  	// Feed the transactions into the tracers and return
  2453  	blockCtx := api.b.GetBlockContext(blockHeader)
  2454  	var failed error
  2455  	for i, tx := range txs {
  2456  		// Send the trace task over for execution
  2457  		jobs <- &txTraceTask{statedb: statedb.Copy(), index: i}
  2458  
  2459  		// Generate the next state snapshot fast without tracing
  2460  		msg, _ := tx.AsMessage(signer, block.BaseFee)
  2461  		statedb.Prepare(tx.Hash(), i)
  2462  		vmenv := vm.NewEVM(blockCtx, evmcore.NewEVMTxContext(msg), statedb, api.b.ChainConfig(), u2u.DefaultVMConfig)
  2463  		if _, err := evmcore.ApplyMessage(vmenv, msg, new(evmcore.GasPool).AddGas(msg.Gas())); err != nil {
  2464  			failed = err
  2465  			break
  2466  		}
  2467  		// Finalize the state so any modifications are written to the trie
  2468  		statedb.Finalise(vmenv.ChainConfig().IsByzantium(block.Number) || vmenv.ChainConfig().IsEIP158(block.Number))
  2469  	}
  2470  	close(jobs)
  2471  	pend.Wait()
  2472  
  2473  	// If execution failed in between, abort
  2474  	if failed != nil {
  2475  		return nil, failed
  2476  	}
  2477  	return results, nil
  2478  }
  2479  
  2480  // stateAtTransaction returns the execution environment of a certain transaction.
  2481  func (api *PublicDebugAPI) stateAtTransaction(ctx context.Context, block *evmcore.EvmBlock, txIndex int) (evmcore.Message, vm.BlockContext, *state.StateDB, error) {
  2482  	// Short circuit if it's genesis block.
  2483  	if block.NumberU64() == 0 {
  2484  		return nil, vm.BlockContext{}, nil, errors.New("no transaction in genesis")
  2485  	}
  2486  	// Lookup the statedb of parent block from the live database,
  2487  	// otherwise regenerate it on the flight.
  2488  	statedb, _, err := api.b.StateAndHeaderByNumberOrHash(ctx, rpc.BlockNumberOrHashWithHash(block.ParentHash, false))
  2489  	if err != nil {
  2490  		return nil, vm.BlockContext{}, nil, err
  2491  	}
  2492  	if txIndex == 0 && len(block.Transactions) == 0 {
  2493  		return nil, vm.BlockContext{}, statedb, nil
  2494  	}
  2495  	// Recompute transactions up to the target index.
  2496  	signer := gsignercache.Wrap(types.MakeSigner(api.b.ChainConfig(), block.Number))
  2497  	for idx, tx := range block.Transactions {
  2498  		// Assemble the transaction call message and return if the requested offset
  2499  		msg, _ := tx.AsMessage(signer, block.BaseFee)
  2500  		txContext := evmcore.NewEVMTxContext(msg)
  2501  		context := api.b.GetBlockContext(block.Header())
  2502  		if idx == txIndex {
  2503  			return msg, context, statedb, nil
  2504  		}
  2505  		// Not yet the searched for transaction, execute on top of the current state
  2506  		vmenv := vm.NewEVM(context, txContext, statedb, api.b.ChainConfig(), u2u.DefaultVMConfig)
  2507  		statedb.Prepare(tx.Hash(), idx)
  2508  		if _, err := evmcore.ApplyMessage(vmenv, msg, new(evmcore.GasPool).AddGas(tx.Gas())); err != nil {
  2509  			return nil, vm.BlockContext{}, nil, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err)
  2510  		}
  2511  		// Ensure any modifications are committed to the state
  2512  		statedb.Finalise(vmenv.ChainConfig().IsByzantium(block.Number) || vmenv.ChainConfig().IsEIP158(block.Number))
  2513  	}
  2514  	return nil, vm.BlockContext{}, nil, fmt.Errorf("transaction index %d out of range for block %#x", txIndex, block.Hash)
  2515  }
  2516  
  2517  // PrivateDebugAPI is the collection of Ethereum APIs exposed over the private
  2518  // debugging endpoint.
  2519  type PrivateDebugAPI struct {
  2520  	b Backend
  2521  }
  2522  
  2523  // NewPrivateDebugAPI creates a new API definition for the private debug methods
  2524  // of the Ethereum service.
  2525  func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI {
  2526  	return &PrivateDebugAPI{b: b}
  2527  }
  2528  
  2529  // ChaindbProperty returns leveldb properties of the key-value database.
  2530  func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) {
  2531  	if property == "" {
  2532  		property = "stats"
  2533  	}
  2534  	return api.b.ChainDb().Stat(property)
  2535  }
  2536  
  2537  // ChaindbCompact flattens the entire key-value database into a single level,
  2538  // removing all unused slots and merging all keys.
  2539  func (api *PrivateDebugAPI) ChaindbCompact() error {
  2540  	if err := compactdb.Compact(ethdb2udb.Wrap(api.b.ChainDb()), "EVM", 64*opt.GiB); err != nil {
  2541  		log.Error("Database compaction failed", "err", err)
  2542  		return err
  2543  	}
  2544  	return nil
  2545  }
  2546  
  2547  // SetHead rewinds the head of the blockchain to a previous block.
  2548  func (api *PrivateDebugAPI) SetHead(number hexutil.Uint64) error {
  2549  	return errors.New("hashgraph cannot rewind blocks due to the BFT algorithm")
  2550  }
  2551  
  2552  // PublicNetAPI offers network related RPC methods
  2553  type PublicNetAPI struct {
  2554  	net            *p2p.Server
  2555  	networkVersion uint64
  2556  }
  2557  
  2558  // NewPublicNetAPI creates a new net API instance.
  2559  func NewPublicNetAPI(net *p2p.Server, networkVersion uint64) *PublicNetAPI {
  2560  	return &PublicNetAPI{net, networkVersion}
  2561  }
  2562  
  2563  // Listening returns an indication if the node is listening for network connections.
  2564  func (s *PublicNetAPI) Listening() bool {
  2565  	return true // always listening
  2566  }
  2567  
  2568  // PeerCount returns the number of connected peers
  2569  func (s *PublicNetAPI) PeerCount() hexutil.Uint {
  2570  	return hexutil.Uint(s.net.PeerCount())
  2571  }
  2572  
  2573  // Version returns the current ethereum protocol version.
  2574  func (s *PublicNetAPI) Version() string {
  2575  	return fmt.Sprintf("%d", s.networkVersion)
  2576  }
  2577  
  2578  // checkTxFee is an internal function used to check whether the fee of
  2579  // the given transaction is _reasonable_(under the cap).
  2580  func checkTxFee(gasPrice *big.Int, gas uint64, cap float64) error {
  2581  	// Short circuit if there is no cap for transaction fee at all.
  2582  	if cap == 0 {
  2583  		return nil
  2584  	}
  2585  	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)))
  2586  	feeFloat, _ := feeEth.Float64()
  2587  	if feeFloat > cap {
  2588  		return fmt.Errorf("tx fee (%.2f U2U) exceeds the configured cap (%.2f U2U)", feeFloat, cap)
  2589  	}
  2590  	return nil
  2591  }
  2592  
  2593  // toHexSlice creates a slice of hex-strings based on []byte.
  2594  func toHexSlice(b [][]byte) []string {
  2595  	r := make([]string, len(b))
  2596  	for i := range b {
  2597  		r[i] = hexutil.Encode(b[i])
  2598  	}
  2599  	return r
  2600  }