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