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