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