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