github.com/ethereum-optimism/optimism/l2geth@v0.0.0-20230612200230-50b04ade19e3/internal/ethapi/api.go (about)

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