github.com/reapchain/go-reapchain@v0.2.15-0.20210609012950-9735c110c705/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  // signTransaction sets defaults and signs the given transaction
   317  // NOTE: the caller needs to ensure that the nonceLock is held, if applicable,
   318  // and release it after the transaction has been submitted to the tx pool
   319  func (s *PrivateAccountAPI) signTransaction(ctx context.Context, args *SendTxArgs, passwd string) (*types.Transaction, error) {
   320      // Look up the wallet containing the requested signer
   321      account := accounts.Account{Address: args.From}
   322      wallet, err := s.am.Find(account)
   323      if err != nil {
   324          return nil, err
   325      }
   326      // Set some sanity defaults and terminate on failure
   327      if err := args.setDefaults(ctx, s.b); err != nil {
   328          return nil, err
   329      }
   330      // Assemble the transaction and sign with the wallet
   331      tx := args.toTransaction()
   332  
   333      return wallet.SignTxWithPassphrase(account, passwd, tx, s.b.ChainConfig().ChainId)
   334  }
   335  
   336  // SendTransaction will create a transaction from the given arguments and
   337  // tries to sign it with the key associated with args.To. If the given passwd isn't
   338  // able to decrypt the key it fails.
   339  
   340  func (s *PrivateAccountAPI) SendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) {
   341      if args.Nonce == nil {
   342          // Hold the addresse's mutex around signing to prevent concurrent assignment of
   343          // the same nonce to multiple accounts.
   344          s.nonceLock.LockAddr(args.From)
   345          defer s.nonceLock.UnlockAddr(args.From)
   346      }
   347      signed, err := s.signTransaction(ctx, &args, passwd)
   348      if err != nil {
   349          return common.Hash{}, err
   350      }
   351  	types.TxChecking(types.MakeSigner(s.b.ChainConfig(), s.b.CurrentBlock().Number()), signed)
   352  
   353      return submitTransaction(ctx, s.b, signed)
   354  }
   355  
   356  // SignTransaction will create a transaction from the given arguments and
   357  // tries to sign it with the key associated with args.To. If the given passwd isn't
   358  // able to decrypt the key it fails. The transaction is returned in RLP-form, not broadcast
   359  // to other nodes
   360  func (s *PrivateAccountAPI) SignTransaction(ctx context.Context, args SendTxArgs, passwd string) (*SignTransactionResult, error) {
   361      // No need to obtain the noncelock mutex, since we won't be sending this
   362      // tx into the transaction pool, but right back to the user
   363      if args.Gas == nil {
   364          return nil, fmt.Errorf("gas not specified")
   365      }
   366      if args.GasPrice == nil {
   367          return nil, fmt.Errorf("gasPrice not specified")
   368      }
   369      if args.Nonce == nil {
   370          return nil, fmt.Errorf("nonce not specified")
   371      }
   372      signed, err := s.signTransaction(ctx, &args, passwd)
   373      if err != nil {
   374          return nil, err
   375      }
   376      data, err := rlp.EncodeToBytes(signed)
   377      if err != nil {
   378          return nil, err
   379      }
   380      return &SignTransactionResult{data, signed}, nil
   381  }
   382  
   383  // signHash is a helper function that calculates a hash for the given message that can be
   384  // safely used to calculate a signature from.
   385  //
   386  // The hash is calulcated as
   387  //   keccak256("\x19Ethereum Signed Message:\n"${message length}${message}).
   388  //
   389  // This gives context to the signed message and prevents signing of transactions.
   390  func signHash(data []byte) []byte {
   391  	msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data)
   392  	return crypto.Keccak256([]byte(msg))
   393  }
   394  
   395  // Sign calculates an Ethereum ECDSA signature for:
   396  // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message))
   397  //
   398  // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
   399  // where the V value will be 27 or 28 for legacy reasons.
   400  //
   401  // The key used to calculate the signature is decrypted with the given password.
   402  //
   403  // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign
   404  func (s *PrivateAccountAPI) Sign(ctx context.Context, data hexutil.Bytes, addr common.Address, passwd string) (hexutil.Bytes, error) {
   405  	// Look up the wallet containing the requested signer
   406  	account := accounts.Account{Address: addr}
   407  
   408  	wallet, err := s.b.AccountManager().Find(account)
   409  	if err != nil {
   410  		return nil, err
   411  	}
   412  	// Assemble sign the data with the wallet
   413  	signature, err := wallet.SignHashWithPassphrase(account, passwd, signHash(data))
   414  	if err != nil {
   415  		return nil, err
   416  	}
   417  	signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
   418  	return signature, nil
   419  }
   420  
   421  // EcRecover returns the address for the account that was used to create the signature.
   422  // Note, this function is compatible with eth_sign and personal_sign. As such it recovers
   423  // the address of:
   424  // hash = keccak256("\x19Ethereum Signed Message:\n"${message length}${message})
   425  // addr = ecrecover(hash, signature)
   426  //
   427  // Note, the signature must conform to the secp256k1 curve R, S and V values, where
   428  // the V value must be be 27 or 28 for legacy reasons.
   429  //
   430  // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_ecRecover
   431  func (s *PrivateAccountAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) {
   432  	if len(sig) != 65 {
   433  		return common.Address{}, fmt.Errorf("signature must be 65 bytes long")
   434  	}
   435  	if sig[64] != 27 && sig[64] != 28 {
   436  		return common.Address{}, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)")
   437  	}
   438  	sig[64] -= 27 // Transform yellow paper V from 27/28 to 0/1
   439  
   440  	rpk, err := crypto.Ecrecover(signHash(data), sig)
   441  	if err != nil {
   442  		return common.Address{}, err
   443  	}
   444  	pubKey := crypto.ToECDSAPub(rpk)
   445  	recoveredAddr := crypto.PubkeyToAddress(*pubKey)
   446  	return recoveredAddr, nil
   447  }
   448  
   449  func (s *PrivateAccountAPI) PubkeyHash(ctx context.Context, data, sig hexutil.Bytes) (common.Hash, error) {
   450  	if len(sig) != 65 {
   451  		return common.Hash{}, fmt.Errorf("signature must be 65 bytes long")
   452  	}
   453  	if sig[64] != 27 && sig[64] != 28 {
   454  		return common.Hash{}, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)")
   455  	}
   456  	sig[64] -= 27 // Transform yellow paper V from 27/28 to 0/1
   457  
   458  	rpk, err := crypto.Ecrecover(signHash(data), sig)
   459  	if err != nil {
   460  		return common.Hash{}, err
   461  	}
   462  	pubKey := crypto.ToECDSAPub(rpk)
   463  	pubBytes := crypto.FromECDSAPub(pubKey)
   464  	pkHash := common.BytesToHash(pubBytes)
   465  	return pkHash, nil
   466  }
   467  
   468  // SignAndSendTransaction was renamed to SendTransaction. This method is deprecated
   469  // and will be removed in the future. It primary goal is to give clients time to update.
   470  func (s *PrivateAccountAPI) SignAndSendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) {
   471  	return s.SendTransaction(ctx, args, passwd)
   472  }
   473  
   474  // PublicBlockChainAPI provides an API to access the Ethereum blockchain.
   475  // It offers only methods that operate on public data that is freely available to anyone.
   476  type PublicBlockChainAPI struct {
   477  	b Backend
   478  }
   479  
   480  // NewPublicBlockChainAPI creates a new Etheruem blockchain API.
   481  func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI {
   482  	return &PublicBlockChainAPI{b}
   483  }
   484  
   485  // BlockNumber returns the block number of the chain head.
   486  func (s *PublicBlockChainAPI) BlockNumber() *big.Int {
   487  	header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available
   488  	return header.Number
   489  }
   490  
   491  // GetBalance returns the amount of wei for the given address in the state of the
   492  // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
   493  // block numbers are also allowed.
   494  func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*big.Int, error) {
   495  	state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
   496  	if state == nil || err != nil {
   497  		return nil, err
   498  	}
   499  
   500  	return state.GetBalance(ctx, address)
   501  }
   502  
   503  // GetBlockByNumber returns the requested block. When blockNr is -1 the chain head is returned. When fullTx is true all
   504  // transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
   505  func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, blockNr rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
   506  	block, err := s.b.BlockByNumber(ctx, blockNr)
   507  	if block != nil {
   508  		response, err := s.rpcOutputBlock(block, true, fullTx)
   509  		if err == nil && blockNr == rpc.PendingBlockNumber {
   510  			// Pending blocks need to nil out a few fields
   511  			for _, field := range []string{"hash", "nonce", "miner"} {
   512  				response[field] = nil
   513  			}
   514  		}
   515  		return response, err
   516  	}
   517  	return nil, err
   518  }
   519  
   520  // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
   521  // detail, otherwise only the transaction hash is returned.
   522  func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, blockHash common.Hash, fullTx bool) (map[string]interface{}, error) {
   523  	block, err := s.b.GetBlock(ctx, blockHash)
   524  	if block != nil {
   525  		return s.rpcOutputBlock(block, true, fullTx)
   526  	}
   527  	return nil, err
   528  }
   529  
   530  // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true
   531  // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
   532  func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) {
   533  	block, err := s.b.BlockByNumber(ctx, blockNr)
   534  	if block != nil {
   535  		uncles := block.Uncles()
   536  		if index >= hexutil.Uint(len(uncles)) {
   537  			log.Debug("Requested uncle not found", "number", blockNr, "hash", block.Hash(), "index", index)
   538  			return nil, nil
   539  		}
   540  		block = types.NewBlockWithHeader(uncles[index])
   541  		return s.rpcOutputBlock(block, false, false)
   542  	}
   543  	return nil, err
   544  }
   545  
   546  // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true
   547  // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
   548  func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) {
   549  	block, err := s.b.GetBlock(ctx, blockHash)
   550  	if block != nil {
   551  		uncles := block.Uncles()
   552  		if index >= hexutil.Uint(len(uncles)) {
   553  			log.Debug("Requested uncle not found", "number", block.Number(), "hash", blockHash, "index", index)
   554  			return nil, nil
   555  		}
   556  		block = types.NewBlockWithHeader(uncles[index])
   557  		return s.rpcOutputBlock(block, false, false)
   558  	}
   559  	return nil, err
   560  }
   561  
   562  // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
   563  func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
   564  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
   565  		n := hexutil.Uint(len(block.Uncles()))
   566  		return &n
   567  	}
   568  	return nil
   569  }
   570  
   571  // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash
   572  func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
   573  	if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
   574  		n := hexutil.Uint(len(block.Uncles()))
   575  		return &n
   576  	}
   577  	return nil
   578  }
   579  
   580  // GetCode returns the code stored at the given address in the state for the given block number.
   581  func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (string, error) {
   582  	state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
   583  	if state == nil || err != nil {
   584  		return "", err
   585  	}
   586  	res, err := state.GetCode(ctx, address)
   587  	if len(res) == 0 || err != nil { // backwards compatibility
   588  		if err != nil {
   589  		}
   590  		return "0x", err
   591  	}
   592  	return common.ToHex(res), nil
   593  }
   594  
   595  // GetStorageAt returns the storage from the state at the given address, key and
   596  // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
   597  // numbers are also allowed.
   598  func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNr rpc.BlockNumber) (string, error) {
   599  	state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
   600  	if state == nil || err != nil {
   601  		return "0x", err
   602  	}
   603  	res, err := state.GetState(ctx, address, common.HexToHash(key))
   604  	if err != nil {
   605  		return "0x", err
   606  	}
   607  	return res.Hex(), nil
   608  }
   609  
   610  // callmsg is the message type used for call transitions.
   611  type callmsg struct {
   612  	addr          common.Address
   613  	to            *common.Address
   614  	gas, gasPrice *big.Int
   615  	value         *big.Int
   616  	data          []byte
   617  }
   618  
   619  // accessor boilerplate to implement core.Message
   620  func (m callmsg) From() (common.Address, error)         { return m.addr, nil }
   621  func (m callmsg) FromFrontier() (common.Address, error) { return m.addr, nil }
   622  func (m callmsg) Nonce() uint64                         { return 0 }
   623  func (m callmsg) CheckNonce() bool                      { return false }
   624  func (m callmsg) To() *common.Address                   { return m.to }
   625  func (m callmsg) GasPrice() *big.Int                    { return m.gasPrice }
   626  func (m callmsg) Gas() *big.Int                         { return m.gas }
   627  func (m callmsg) Value() *big.Int                       { return m.value }
   628  func (m callmsg) Data() []byte                          { return m.data }
   629  
   630  // CallArgs represents the arguments for a call.
   631  type CallArgs struct {
   632  	From     common.Address  `json:"from"`
   633  	To       *common.Address `json:"to"`
   634  	Gas      hexutil.Big     `json:"gas"`
   635  	GasPrice hexutil.Big     `json:"gasPrice"`
   636  	Value    hexutil.Big     `json:"value"`
   637  	Data     hexutil.Bytes   `json:"data"`
   638  }
   639  
   640  func (s *PublicBlockChainAPI) doCall(ctx context.Context, args CallArgs, blockNr rpc.BlockNumber, vmCfg vm.Config) ([]byte, *big.Int, bool, error) {
   641  	defer func(start time.Time) { log.Debug("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now())
   642  
   643  	state, header, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
   644  	if state == nil || err != nil {
   645  		return nil, common.Big0, false, err
   646  	}
   647  	// Set sender address or use a default if none specified
   648  	addr := args.From
   649  	if addr == (common.Address{}) {
   650  		if wallets := s.b.AccountManager().Wallets(); len(wallets) > 0 {
   651  			if accounts := wallets[0].Accounts(); len(accounts) > 0 {
   652  				addr = accounts[0].Address
   653  			}
   654  		}
   655  	}
   656  	// Set default gas & gas price if none were set
   657  	gas, gasPrice := args.Gas.ToInt(), args.GasPrice.ToInt()
   658  	if gas.Sign() == 0 {
   659  		gas = big.NewInt(50000000)
   660  	}
   661  	if gasPrice.Sign() == 0 {
   662  		gasPrice = new(big.Int).SetUint64(defaultGasPrice)
   663  	}
   664  
   665  	// Create new call message
   666  	msg := types.NewMessage(addr, args.To, 0, args.Value.ToInt(), gas, gasPrice, args.Data, false, false)
   667  
   668  	// Setup context so it may be cancelled the call has completed
   669  	// or, in case of unmetered gas, setup a context with a timeout.
   670  	var cancel context.CancelFunc
   671  	if vmCfg.DisableGasMetering {
   672  		ctx, cancel = context.WithTimeout(ctx, time.Second*5)
   673  	} else {
   674  		ctx, cancel = context.WithCancel(ctx)
   675  	}
   676  	// Make sure the context is cancelled when the call has completed
   677  	// this makes sure resources are cleaned up.
   678  	defer func() { cancel() }()
   679  
   680  	// Get a new instance of the EVM.
   681  	evm, vmError, err := s.b.GetEVM(ctx, msg, state, header, vmCfg)
   682  	if err != nil {
   683  		return nil, common.Big0, false, err
   684  	}
   685  	// Wait for the context to be done and cancel the evm. Even if the
   686  	// EVM has finished, cancelling may be done (repeatedly)
   687  	go func() {
   688  		select {
   689  		case <-ctx.Done():
   690  			evm.Cancel()
   691  		}
   692  	}()
   693  
   694  	// Setup the gas pool (also for unmetered requests)
   695  	// and apply the message.
   696  	gp := new(core.GasPool).AddGas(math.MaxBig256)
   697  	res, gas, failed, err := core.ApplyMessage(evm, msg, gp)
   698  	if err := vmError(); err != nil {
   699  		return nil, common.Big0, false, err
   700  	}
   701  	return res, gas, failed, err
   702  }
   703  
   704  // Call executes the given transaction on the state for the given block number.
   705  // It doesn't make and changes in the state/blockchain and is useful to execute and retrieve values.
   706  func (s *PublicBlockChainAPI) Call(ctx context.Context, args CallArgs, blockNr rpc.BlockNumber) (hexutil.Bytes, error) {
   707  	result, _, _, err := s.doCall(ctx, args, blockNr, vm.Config{DisableGasMetering: true})
   708  	return (hexutil.Bytes)(result), err
   709  }
   710  
   711  // EstimateGas returns an estimate of the amount of gas needed to execute the given transaction.
   712  func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args CallArgs) (*hexutil.Big, error) {
   713  	// Binary search the gas requirement, as it may be higher than the amount used
   714  	var (
   715  		lo  uint64 = params.TxGas - 1
   716  		hi  uint64
   717  		cap uint64
   718  	)
   719  	if  (*big.Int)(&args.Gas).Uint64() >= params.TxGas {
   720  		hi =  (*big.Int)(&args.Gas).Uint64()
   721  	} else {
   722  		// Retrieve the current pending block to act as the gas ceiling
   723  		block, err := s.b.BlockByNumber(ctx, rpc.PendingBlockNumber)
   724  		if err != nil {
   725  			return nil, err
   726  		}
   727  		hi = block.GasLimit().Uint64()
   728  	}
   729  	cap = hi
   730  
   731  	// Create a helper to check if a gas allowance results in an executable transaction
   732  	executable := func(gas uint64) bool {
   733  		(*big.Int)(&args.Gas).SetUint64(gas)
   734  
   735  		_, _, failed, err := s.doCall(ctx, args, rpc.PendingBlockNumber, vm.Config{EstimateGasMetering:true})
   736  		if err != nil || failed {
   737  			return false
   738  		}
   739  		return true
   740  	}
   741  	// Execute the binary search and hone in on an executable gas limit
   742  	for lo+1 < hi {
   743  		// Take a guess at the gas, and check transaction validity
   744  		mid := (hi + lo) / 2
   745  		if !executable(mid) {
   746  			lo = mid
   747  		} else {
   748  			hi = mid
   749  		}
   750  	}
   751  	// Reject the transaction as invalid if it still fails at the highest allowance
   752  	if hi == cap {
   753  		if !executable(hi) {
   754  			return (*hexutil.Big)(new(big.Int).SetUint64(0)), fmt.Errorf("gas required exceeds allowance or always failing transaction")
   755  		}
   756  	}
   757  	return (*hexutil.Big)(new(big.Int).SetUint64(hi)), nil
   758  }
   759  
   760  // ExecutionResult groups all structured logs emitted by the EVM
   761  // while replaying a transaction in debug mode as well as the amount of
   762  // gas used and the return value
   763  type ExecutionResult struct {
   764  	Gas         *big.Int       `json:"gas"`
   765  	ReturnValue string         `json:"returnValue"`
   766  	StructLogs  []StructLogRes `json:"structLogs"`
   767  }
   768  
   769  // StructLogRes stores a structured log emitted by the EVM while replaying a
   770  // transaction in debug mode
   771  type StructLogRes struct {
   772  	Pc      uint64            `json:"pc"`
   773  	Op      string            `json:"op"`
   774  	Gas     uint64            `json:"gas"`
   775  	GasCost uint64            `json:"gasCost"`
   776  	Depth   int               `json:"depth"`
   777  	Error   error             `json:"error"`
   778  	Stack   []string          `json:"stack"`
   779  	Memory  []string          `json:"memory"`
   780  	Storage map[string]string `json:"storage"`
   781  }
   782  
   783  // formatLogs formats EVM returned structured logs for json output
   784  func FormatLogs(structLogs []vm.StructLog) []StructLogRes {
   785  	formattedStructLogs := make([]StructLogRes, len(structLogs))
   786  	for index, trace := range structLogs {
   787  		formattedStructLogs[index] = StructLogRes{
   788  			Pc:      trace.Pc,
   789  			Op:      trace.Op.String(),
   790  			Gas:     trace.Gas,
   791  			GasCost: trace.GasCost,
   792  			Depth:   trace.Depth,
   793  			Error:   trace.Err,
   794  			Stack:   make([]string, len(trace.Stack)),
   795  			Storage: make(map[string]string),
   796  		}
   797  
   798  		for i, stackValue := range trace.Stack {
   799  			formattedStructLogs[index].Stack[i] = fmt.Sprintf("%x", math.PaddedBigBytes(stackValue, 32))
   800  		}
   801  
   802  		for i := 0; i+32 <= len(trace.Memory); i += 32 {
   803  			formattedStructLogs[index].Memory = append(formattedStructLogs[index].Memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
   804  		}
   805  
   806  		for i, storageValue := range trace.Storage {
   807  			formattedStructLogs[index].Storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
   808  		}
   809  	}
   810  	return formattedStructLogs
   811  }
   812  
   813  // rpcOutputBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
   814  // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
   815  // transaction hashes.
   816  func (s *PublicBlockChainAPI) rpcOutputBlock(b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
   817  	head := b.Header() // copies the header once
   818  	fields := map[string]interface{}{
   819  		"number":           (*hexutil.Big)(head.Number),
   820  		"hash":             b.Hash(),
   821  		"parentHash":       head.ParentHash,
   822  		"nonce":            head.Nonce,
   823  		"mixHash":          head.MixDigest,
   824  		"sha3Uncles":       head.UncleHash,
   825  		"logsBloom":        head.Bloom,
   826  		"stateRoot":        head.Root,
   827  		"miner":            head.Coinbase,
   828  		"difficulty":       (*hexutil.Big)(head.Difficulty),
   829  		"totalDifficulty":  (*hexutil.Big)(s.b.GetTd(b.Hash())),
   830  		"extraData":        hexutil.Bytes(head.Extra),
   831  		"size":             hexutil.Uint64(uint64(b.Size().Int64())),
   832  		"gasLimit":         (*hexutil.Big)(head.GasLimit),
   833  		"gasUsed":          (*hexutil.Big)(head.GasUsed),
   834  		"timestamp":        (*hexutil.Big)(head.Time),
   835  		"transactionsRoot": head.TxHash,
   836  		"receiptsRoot":     head.ReceiptHash,
   837  	}
   838  
   839  	if inclTx {
   840  		formatTx := func(tx *types.Transaction) (interface{}, error) {
   841  			return tx.Hash(), nil
   842  		}
   843  
   844  		if fullTx {
   845  			formatTx = func(tx *types.Transaction) (interface{}, error) {
   846  				return newRPCTransaction(b, tx.Hash())
   847  			}
   848  		}
   849  
   850  		txs := b.Transactions()
   851  		transactions := make([]interface{}, len(txs))
   852  		var err error
   853  		for i, tx := range b.Transactions() {
   854  			if transactions[i], err = formatTx(tx); err != nil {
   855  				return nil, err
   856  			}
   857  		}
   858  		fields["transactions"] = transactions
   859  	}
   860  
   861  	uncles := b.Uncles()
   862  	uncleHashes := make([]common.Hash, len(uncles))
   863  	for i, uncle := range uncles {
   864  		uncleHashes[i] = uncle.Hash()
   865  	}
   866  	fields["uncles"] = uncleHashes
   867  
   868  	return fields, nil
   869  }
   870  
   871  // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
   872  type RPCTransaction struct {
   873  	BlockHash        common.Hash     `json:"blockHash"`
   874  	BlockNumber      *hexutil.Big    `json:"blockNumber"`
   875  	From             common.Address  `json:"from"`
   876  	Gas              *hexutil.Big    `json:"gas"`
   877  	GasPrice         *hexutil.Big    `json:"gasPrice"`
   878  	Hash             common.Hash     `json:"hash"`
   879  	Input            hexutil.Bytes   `json:"input"`
   880  	Nonce            hexutil.Uint64  `json:"nonce"`
   881  	To               *common.Address `json:"to"`
   882  	TransactionIndex hexutil.Uint    `json:"transactionIndex"`
   883  	Value            *hexutil.Big    `json:"value"`
   884  	V                *hexutil.Big    `json:"v"`
   885  	R                *hexutil.Big    `json:"r"`
   886  	S                *hexutil.Big    `json:"s"`
   887  }
   888  
   889  // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation
   890  func newRPCPendingTransaction(tx *types.Transaction) *RPCTransaction {
   891  	var signer types.Signer = types.FrontierSigner{}
   892  	if tx.Protected() {
   893  		signer = types.NewEIP155Signer(tx.ChainId())
   894  	}
   895  	from, _ := types.Sender(signer, tx)
   896  	v, r, s := tx.RawSignatureValues()
   897  	return &RPCTransaction{
   898  		From:     from,
   899  		Gas:      (*hexutil.Big)(tx.Gas()),
   900  		GasPrice: (*hexutil.Big)(tx.GasPrice()),
   901  		Hash:     tx.Hash(),
   902  		Input:    hexutil.Bytes(tx.Data()),
   903  		Nonce:    hexutil.Uint64(tx.Nonce()),
   904  		To:       tx.To(),
   905  		Value:    (*hexutil.Big)(tx.Value()),
   906  		V:        (*hexutil.Big)(v),
   907  		R:        (*hexutil.Big)(r),
   908  		S:        (*hexutil.Big)(s),
   909  	}
   910  }
   911  
   912  // newRPCTransaction returns a transaction that will serialize to the RPC representation.
   913  func newRPCTransactionFromBlockIndex(b *types.Block, txIndex uint) (*RPCTransaction, error) {
   914  	if txIndex < uint(len(b.Transactions())) {
   915  		tx := b.Transactions()[txIndex]
   916  		var signer types.Signer = types.FrontierSigner{}
   917  		if tx.Protected() {
   918  			signer = types.NewEIP155Signer(tx.ChainId())
   919  		}
   920  		from, _ := types.Sender(signer, tx)
   921  		v, r, s := tx.RawSignatureValues()
   922  		return &RPCTransaction{
   923  			BlockHash:        b.Hash(),
   924  			BlockNumber:      (*hexutil.Big)(b.Number()),
   925  			From:             from,
   926  			Gas:              (*hexutil.Big)(tx.Gas()),
   927  			GasPrice:         (*hexutil.Big)(tx.GasPrice()),
   928  			Hash:             tx.Hash(),
   929  			Input:            hexutil.Bytes(tx.Data()),
   930  			Nonce:            hexutil.Uint64(tx.Nonce()),
   931  			To:               tx.To(),
   932  			TransactionIndex: hexutil.Uint(txIndex),
   933  			Value:            (*hexutil.Big)(tx.Value()),
   934  			V:                (*hexutil.Big)(v),
   935  			R:                (*hexutil.Big)(r),
   936  			S:                (*hexutil.Big)(s),
   937  		}, nil
   938  	}
   939  
   940  	return nil, nil
   941  }
   942  
   943  // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index.
   944  func newRPCRawTransactionFromBlockIndex(b *types.Block, txIndex uint) (hexutil.Bytes, error) {
   945  	if txIndex < uint(len(b.Transactions())) {
   946  		tx := b.Transactions()[txIndex]
   947  		return rlp.EncodeToBytes(tx)
   948  	}
   949  
   950  	return nil, nil
   951  }
   952  
   953  // newRPCTransaction returns a transaction that will serialize to the RPC representation.
   954  func newRPCTransaction(b *types.Block, txHash common.Hash) (*RPCTransaction, error) {
   955  	for idx, tx := range b.Transactions() {
   956  		if tx.Hash() == txHash {
   957  			return newRPCTransactionFromBlockIndex(b, uint(idx))
   958  		}
   959  	}
   960  
   961  	return nil, nil
   962  }
   963  
   964  // PublicTransactionPoolAPI exposes methods for the RPC interface
   965  type PublicTransactionPoolAPI struct {
   966  	b         Backend
   967  	nonceLock *AddrLocker
   968  }
   969  
   970  // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.
   971  func NewPublicTransactionPoolAPI(b Backend, nonceLock *AddrLocker) *PublicTransactionPoolAPI {
   972  	return &PublicTransactionPoolAPI{b, nonceLock}
   973  }
   974  
   975  func getTransaction(chainDb ethdb.Database, b Backend, txHash common.Hash) (*types.Transaction, bool, error) {
   976  	txData, err := chainDb.Get(txHash.Bytes())
   977  	isPending := false
   978  	tx := new(types.Transaction)
   979  
   980  	if err == nil && len(txData) > 0 {
   981  		if err := rlp.DecodeBytes(txData, tx); err != nil {
   982  			return nil, isPending, err
   983  		}
   984  	} else {
   985  		// pending transaction?
   986  		tx = b.GetPoolTransaction(txHash)
   987  		isPending = true
   988  	}
   989  
   990  	return tx, isPending, nil
   991  }
   992  
   993  // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
   994  func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
   995  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
   996  		n := hexutil.Uint(len(block.Transactions()))
   997  		return &n
   998  	}
   999  	return nil
  1000  }
  1001  
  1002  // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
  1003  func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  1004  	if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  1005  		n := hexutil.Uint(len(block.Transactions()))
  1006  		return &n
  1007  	}
  1008  	return nil
  1009  }
  1010  
  1011  // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
  1012  func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (*RPCTransaction, error) {
  1013  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1014  		return newRPCTransactionFromBlockIndex(block, uint(index))
  1015  	}
  1016  	return nil, nil
  1017  }
  1018  
  1019  // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
  1020  func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (*RPCTransaction, error) {
  1021  	if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  1022  		return newRPCTransactionFromBlockIndex(block, uint(index))
  1023  	}
  1024  	return nil, nil
  1025  }
  1026  
  1027  // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
  1028  func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (hexutil.Bytes, error) {
  1029  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1030  		return newRPCRawTransactionFromBlockIndex(block, uint(index))
  1031  	}
  1032  	return nil, nil
  1033  }
  1034  
  1035  // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index.
  1036  func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (hexutil.Bytes, error) {
  1037  	if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  1038  		return newRPCRawTransactionFromBlockIndex(block, uint(index))
  1039  	}
  1040  	return nil, nil
  1041  }
  1042  
  1043  // GetTransactionCount returns the number of transactions the given address has sent for the given block number
  1044  func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*hexutil.Uint64, error) {
  1045  	state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr)
  1046  	if state == nil || err != nil {
  1047  		return nil, err
  1048  	}
  1049  	nonce, err := state.GetNonce(ctx, address)
  1050  	if err != nil {
  1051  		return nil, err
  1052  	}
  1053  	return (*hexutil.Uint64)(&nonce), nil
  1054  }
  1055  
  1056  // getTransactionBlockData fetches the meta data for the given transaction from the chain database. This is useful to
  1057  // retrieve block information for a hash. It returns the block hash, block index and transaction index.
  1058  func getTransactionBlockData(chainDb ethdb.Database, txHash common.Hash) (common.Hash, uint64, uint64, error) {
  1059  	var txBlock struct {
  1060  		BlockHash  common.Hash
  1061  		BlockIndex uint64
  1062  		Index      uint64
  1063  	}
  1064  
  1065  	blockData, err := chainDb.Get(append(txHash.Bytes(), 0x0001))
  1066  	if err != nil {
  1067  		return common.Hash{}, uint64(0), uint64(0), err
  1068  	}
  1069  
  1070  	reader := bytes.NewReader(blockData)
  1071  	if err = rlp.Decode(reader, &txBlock); err != nil {
  1072  		return common.Hash{}, uint64(0), uint64(0), err
  1073  	}
  1074  
  1075  	return txBlock.BlockHash, txBlock.BlockIndex, txBlock.Index, nil
  1076  }
  1077  
  1078  // GetTransactionByHash returns the transaction for the given hash
  1079  func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) (*RPCTransaction, error) {
  1080  	var tx *types.Transaction
  1081  	var isPending bool
  1082  	var err error
  1083  
  1084  	if tx, isPending, err = getTransaction(s.b.ChainDb(), s.b, hash); err != nil {
  1085  		log.Debug("Failed to retrieve transaction", "hash", hash, "err", err)
  1086  		return nil, nil
  1087  	} else if tx == nil {
  1088  		return nil, nil
  1089  	}
  1090  	if isPending {
  1091  		return newRPCPendingTransaction(tx), nil
  1092  	}
  1093  
  1094  	blockHash, _, _, err := getTransactionBlockData(s.b.ChainDb(), hash)
  1095  	if err != nil {
  1096  		log.Debug("Failed to retrieve transaction block", "hash", hash, "err", err)
  1097  		return nil, nil
  1098  	}
  1099  
  1100  	if block, _ := s.b.GetBlock(ctx, blockHash); block != nil {
  1101  		return newRPCTransaction(block, hash)
  1102  	}
  1103  	return nil, nil
  1104  }
  1105  
  1106  // GetRawTransactionByHash returns the bytes of the transaction for the given hash.
  1107  func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  1108  	var tx *types.Transaction
  1109  	var err error
  1110  
  1111  	if tx, _, err = getTransaction(s.b.ChainDb(), s.b, hash); err != nil {
  1112  		log.Debug("Failed to retrieve transaction", "hash", hash, "err", err)
  1113  		return nil, nil
  1114  	} else if tx == nil {
  1115  		return nil, nil
  1116  	}
  1117  
  1118  	return rlp.EncodeToBytes(tx)
  1119  }
  1120  
  1121  // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  1122  func (s *PublicTransactionPoolAPI) GetTransactionReceipt(hash common.Hash) (map[string]interface{}, error) {
  1123  	receipt := core.GetReceipt(s.b.ChainDb(), hash)
  1124  	if receipt == nil {
  1125  		log.Debug("Receipt not found for transaction", "hash", hash)
  1126  		return nil, nil
  1127  	}
  1128  
  1129  	tx, _, err := getTransaction(s.b.ChainDb(), s.b, hash)
  1130  	if err != nil {
  1131  		log.Debug("Failed to retrieve transaction", "hash", hash, "err", err)
  1132  		return nil, nil
  1133  	}
  1134  
  1135  	txBlock, blockIndex, index, err := getTransactionBlockData(s.b.ChainDb(), hash)
  1136  	if err != nil {
  1137  		log.Debug("Failed to retrieve transaction block", "hash", hash, "err", err)
  1138  		return nil, nil
  1139  	}
  1140  
  1141  	var signer types.Signer = types.FrontierSigner{}
  1142  	if tx.Protected() {
  1143  		signer = types.NewEIP155Signer(tx.ChainId())
  1144  	}
  1145  	from, _ := types.Sender(signer, tx)
  1146  
  1147  	fields := map[string]interface{}{
  1148  		"root":              hexutil.Bytes(receipt.PostState),
  1149  		"blockHash":         txBlock,
  1150  		"blockNumber":       hexutil.Uint64(blockIndex),
  1151  		"transactionHash":   hash,
  1152  		"transactionIndex":  hexutil.Uint64(index),
  1153  		"from":              from,
  1154  		"to":                tx.To(),
  1155  		"gasUsed":           (*hexutil.Big)(receipt.GasUsed),
  1156  		"cumulativeGasUsed": (*hexutil.Big)(receipt.CumulativeGasUsed),
  1157  		"contractAddress":   nil,
  1158  		"logs":              receipt.Logs,
  1159  		"logsBloom":         receipt.Bloom,
  1160  	}
  1161  	if receipt.Logs == nil {
  1162  		fields["logs"] = [][]*types.Log{}
  1163  	}
  1164  	// If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  1165  	if receipt.ContractAddress != (common.Address{}) {
  1166  		fields["contractAddress"] = receipt.ContractAddress
  1167  	}
  1168  	return fields, nil
  1169  }
  1170  
  1171  // sign is a helper function that signs a transaction with the private key of the given address.
  1172  func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
  1173  	// Look up the wallet containing the requested signer
  1174  	account := accounts.Account{Address: addr}
  1175  
  1176  	wallet, err := s.b.AccountManager().Find(account)
  1177  	if err != nil {
  1178  		return nil, err
  1179  	}
  1180  	// Request the wallet to sign the transaction
  1181  	var chainID *big.Int
  1182  	if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) {
  1183  		chainID = config.ChainId
  1184  	}
  1185  	return wallet.SignTx(account, tx, chainID)
  1186  }
  1187  
  1188  // SendTxArgs represents the arguments to sumbit a new transaction into the transaction pool.
  1189  type SendTxArgs struct {
  1190  	From     common.Address  `json:"from"`
  1191  	To       *common.Address `json:"to"`
  1192  	Gas      *hexutil.Big    `json:"gas"`
  1193  	GasPrice *hexutil.Big    `json:"gasPrice"`
  1194  	Value    *hexutil.Big    `json:"value"`
  1195  	Data     hexutil.Bytes   `json:"data"`
  1196  	Nonce    *hexutil.Uint64 `json:"nonce"`
  1197  }
  1198  
  1199  // prepareSendTxArgs is a helper function that fills in default values for unspecified tx fields.
  1200  func (args *SendTxArgs) setDefaults(ctx context.Context, b Backend) error {
  1201  	if args.Gas == nil {
  1202  		args.Gas = (*hexutil.Big)(big.NewInt(defaultGas))
  1203  	}
  1204  	if args.GasPrice == nil {
  1205  		price, err := b.SuggestPrice(ctx)
  1206  		if err != nil {
  1207  			return err
  1208  		}
  1209  		args.GasPrice = (*hexutil.Big)(price)
  1210  	}
  1211  	if args.Value == nil {
  1212  		args.Value = new(hexutil.Big)
  1213  	}
  1214  	if args.Nonce == nil {
  1215  		nonce, err := b.GetPoolNonce(ctx, args.From)
  1216  		if err != nil {
  1217  			return err
  1218  		}
  1219  		args.Nonce = (*hexutil.Uint64)(&nonce)
  1220  	}
  1221  	return nil
  1222  }
  1223  
  1224  func (args *SendTxArgs) toTransaction() *types.Transaction {
  1225  	if args.To == nil {
  1226  		return types.NewContractCreation(uint64(*args.Nonce), (*big.Int)(args.Value), (*big.Int)(args.Gas), (*big.Int)(args.GasPrice), args.Data)
  1227  	}
  1228  	return types.NewTransaction(uint64(*args.Nonce), *args.To, (*big.Int)(args.Value), (*big.Int)(args.Gas), (*big.Int)(args.GasPrice), args.Data)
  1229  }
  1230  
  1231  // submitTransaction is a helper function that submits tx to txPool and logs a message.
  1232  func submitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (common.Hash, error) {
  1233  	if err := b.SendTx(ctx, tx); err != nil {
  1234  		return common.Hash{}, err
  1235  	}
  1236  	if tx.To() == nil {
  1237  		signer := types.MakeSigner(b.ChainConfig(), b.CurrentBlock().Number())
  1238  		from, _ := types.Sender(signer, tx)
  1239  		addr := crypto.CreateAddress(from, tx.Nonce())
  1240  		if !tx.Governance() {
  1241  			log.Warn("no contract creation permissions", "tx.Governance", tx.Governance(), "from", from)
  1242  			return common.Hash{}, vm.ErrDeployPermissions
  1243  		}
  1244  		log.Info("Submitted contract creation", "fullhash", tx.Hash().Hex(), "contract", addr.Hex())
  1245  	}
  1246  	return tx.Hash(), nil
  1247  }
  1248  
  1249  // SendTransaction creates a transaction for the given argument, sign it and submit it to the
  1250  // transaction pool.
  1251  func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error) {
  1252  	// Look up the wallet containing the requested signer
  1253  	account := accounts.Account{Address: args.From}
  1254  	wallet, err := s.b.AccountManager().Find(account)
  1255  	if err != nil {
  1256  		return common.Hash{}, err
  1257  	}
  1258  
  1259  	if args.Nonce == nil {
  1260  		// Hold the addresse's mutex around signing to prevent concurrent assignment of
  1261  		// the same nonce to multiple accounts.
  1262  		s.nonceLock.LockAddr(args.From)
  1263  		defer s.nonceLock.UnlockAddr(args.From)
  1264  	}
  1265  
  1266  	// Set some sanity defaults and terminate on failure
  1267  	if err := args.setDefaults(ctx, s.b); err != nil {
  1268  		return common.Hash{}, err
  1269  	}
  1270  	// Assemble the transaction and sign with the wallet
  1271  	tx := args.toTransaction()
  1272  
  1273  	var chainID *big.Int
  1274  	if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) {
  1275  		chainID = config.ChainId
  1276  	}
  1277  	signed, err := wallet.SignTx(account, tx, chainID)
  1278  	if err != nil {
  1279  		return common.Hash{}, err
  1280  	}
  1281  	types.TxChecking(types.MakeSigner(s.b.ChainConfig(), s.b.CurrentBlock().Number()), signed)
  1282  
  1283  	return submitTransaction(ctx, s.b, signed)
  1284  }
  1285  
  1286  // SendRawTransaction will add the signed transaction to the transaction pool.
  1287  // The sender is responsible for signing the transaction and using the correct nonce.
  1288  func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, encodedTx hexutil.Bytes) (string, error) {
  1289  	tx := new(types.Transaction)
  1290  	if err := rlp.DecodeBytes(encodedTx, tx); err != nil {
  1291  		return "", err
  1292  	}
  1293  	types.TxChecking(types.MakeSigner(s.b.ChainConfig(), s.b.CurrentBlock().Number()), tx)
  1294  
  1295  	if err := s.b.SendTx(ctx, tx); err != nil {
  1296  		return "", err
  1297  	}
  1298  
  1299  	signer := types.MakeSigner(s.b.ChainConfig(), s.b.CurrentBlock().Number())
  1300  	if tx.To() == nil {
  1301  		from, err := types.Sender(signer, tx)
  1302  		if err != nil {
  1303  			return "", err
  1304  		}
  1305  		addr := crypto.CreateAddress(from, tx.Nonce())
  1306  		if !tx.Governance() {
  1307  			log.Warn("no contract creation permissions", "tx.Governance", tx.Governance(), "from", from, "signer", signer)
  1308  			return "", vm.ErrDeployPermissions
  1309  		}
  1310  		log.Info("Submitted contract creation", "fullhash", tx.Hash().Hex(), "contract", addr.Hex())
  1311  	} else {
  1312  		log.Info("Submitted transaction", "fullhash", tx.Hash().Hex(), "recipient", tx.To())
  1313  	}
  1314  
  1315  	return tx.Hash().Hex(), nil
  1316  }
  1317  
  1318  // Sign calculates an ECDSA signature for:
  1319  // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message).
  1320  //
  1321  // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  1322  // where the V value will be 27 or 28 for legacy reasons.
  1323  //
  1324  // The account associated with addr must be unlocked.
  1325  //
  1326  // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
  1327  func (s *PublicTransactionPoolAPI) Sign(addr common.Address, data hexutil.Bytes) (hexutil.Bytes, error) {
  1328  	// Look up the wallet containing the requested signer
  1329  	account := accounts.Account{Address: addr}
  1330  
  1331  	wallet, err := s.b.AccountManager().Find(account)
  1332  	if err != nil {
  1333  		return nil, err
  1334  	}
  1335  	// Sign the requested hash with the wallet
  1336  	signature, err := wallet.SignHash(account, signHash(data))
  1337  	if err == nil {
  1338  		signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  1339  	}
  1340  	return signature, err
  1341  }
  1342  
  1343  // SignTransactionResult represents a RLP encoded signed transaction.
  1344  type SignTransactionResult struct {
  1345  	Raw hexutil.Bytes      `json:"raw"`
  1346  	Tx  *types.Transaction `json:"tx"`
  1347  }
  1348  
  1349  // SignTransaction will sign the given transaction with the from account.
  1350  // The node needs to have the private key of the account corresponding with
  1351  // the given from address and it needs to be unlocked.
  1352  func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) {
  1353  	if args.Nonce == nil {
  1354  		// Hold the addresse's mutex around signing to prevent concurrent assignment of
  1355  		// the same nonce to multiple accounts.
  1356  		s.nonceLock.LockAddr(args.From)
  1357  		defer s.nonceLock.UnlockAddr(args.From)
  1358  	}
  1359  	if err := args.setDefaults(ctx, s.b); err != nil {
  1360  		return nil, err
  1361  	}
  1362  	tx, err := s.sign(args.From, args.toTransaction())
  1363  	if err != nil {
  1364  		return nil, err
  1365  	}
  1366  	data, err := rlp.EncodeToBytes(tx)
  1367  	if err != nil {
  1368  		return nil, err
  1369  	}
  1370  	return &SignTransactionResult{data, tx}, nil
  1371  }
  1372  
  1373  // PendingTransactions returns the transactions that are in the transaction pool and have a from address that is one of
  1374  // the accounts this node manages.
  1375  func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error) {
  1376  	pending, err := s.b.GetPoolTransactions()
  1377  	if err != nil {
  1378  		return nil, err
  1379  	}
  1380  
  1381  	transactions := make([]*RPCTransaction, 0, len(pending))
  1382  	for _, tx := range pending {
  1383  		var signer types.Signer = types.HomesteadSigner{}
  1384  		if tx.Protected() {
  1385  			signer = types.NewEIP155Signer(tx.ChainId())
  1386  		}
  1387  		from, _ := types.Sender(signer, tx)
  1388  		if _, err := s.b.AccountManager().Find(accounts.Account{Address: from}); err == nil {
  1389  			transactions = append(transactions, newRPCPendingTransaction(tx))
  1390  		}
  1391  	}
  1392  	return transactions, nil
  1393  }
  1394  
  1395  // Resend accepts an existing transaction and a new gas price and limit. It will remove
  1396  // the given transaction from the pool and reinsert it with the new gas price and limit.
  1397  func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs SendTxArgs, gasPrice, gasLimit *hexutil.Big) (common.Hash, error) {
  1398  	if sendArgs.Nonce == nil {
  1399  		return common.Hash{}, fmt.Errorf("missing transaction nonce in transaction spec")
  1400  	}
  1401  	if err := sendArgs.setDefaults(ctx, s.b); err != nil {
  1402  		return common.Hash{}, err
  1403  	}
  1404  	matchTx := sendArgs.toTransaction()
  1405  	pending, err := s.b.GetPoolTransactions()
  1406  	if err != nil {
  1407  		return common.Hash{}, err
  1408  	}
  1409  
  1410  	for _, p := range pending {
  1411  		var signer types.Signer = types.HomesteadSigner{}
  1412  		if p.Protected() {
  1413  			signer = types.NewEIP155Signer(p.ChainId())
  1414  		}
  1415  		wantSigHash := signer.Hash(matchTx)
  1416  
  1417  		if pFrom, err := types.Sender(signer, p); err == nil && pFrom == sendArgs.From && signer.Hash(p) == wantSigHash {
  1418  			// Match. Re-sign and send the transaction.
  1419  			if gasPrice != nil {
  1420  				sendArgs.GasPrice = gasPrice
  1421  			}
  1422  			if gasLimit != nil {
  1423  				sendArgs.Gas = gasLimit
  1424  			}
  1425  			signedTx, err := s.sign(sendArgs.From, sendArgs.toTransaction())
  1426  			if err != nil {
  1427  				return common.Hash{}, err
  1428  			}
  1429  			s.b.RemoveTx(p.Hash())
  1430  			if err = s.b.SendTx(ctx, signedTx); err != nil {
  1431  				return common.Hash{}, err
  1432  			}
  1433  			return signedTx.Hash(), nil
  1434  		}
  1435  	}
  1436  
  1437  	return common.Hash{}, fmt.Errorf("Transaction %#x not found", matchTx.Hash())
  1438  }
  1439  
  1440  // PublicDebugAPI is the collection of Etheruem APIs exposed over the public
  1441  // debugging endpoint.
  1442  type PublicDebugAPI struct {
  1443  	b Backend
  1444  }
  1445  
  1446  // NewPublicDebugAPI creates a new API definition for the public debug methods
  1447  // of the Ethereum service.
  1448  func NewPublicDebugAPI(b Backend) *PublicDebugAPI {
  1449  	return &PublicDebugAPI{b: b}
  1450  }
  1451  
  1452  // GetBlockRlp retrieves the RLP encoded for of a single block.
  1453  func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error) {
  1454  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1455  	if block == nil {
  1456  		return "", fmt.Errorf("block #%d not found", number)
  1457  	}
  1458  	encoded, err := rlp.EncodeToBytes(block)
  1459  	if err != nil {
  1460  		return "", err
  1461  	}
  1462  	return fmt.Sprintf("%x", encoded), nil
  1463  }
  1464  
  1465  // PrintBlock retrieves a block and returns its pretty printed form.
  1466  func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) {
  1467  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1468  	if block == nil {
  1469  		return "", fmt.Errorf("block #%d not found", number)
  1470  	}
  1471  	return fmt.Sprintf("%s", block), nil
  1472  }
  1473  
  1474  // SeedHash retrieves the seed hash of a block.
  1475  func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) {
  1476  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1477  	if block == nil {
  1478  		return "", fmt.Errorf("block #%d not found", number)
  1479  	}
  1480  	return fmt.Sprintf("0x%x", ethash.SeedHash(number)), nil
  1481  }
  1482  
  1483  // PrivateDebugAPI is the collection of Etheruem APIs exposed over the private
  1484  // debugging endpoint.
  1485  type PrivateDebugAPI struct {
  1486  	b Backend
  1487  }
  1488  
  1489  // NewPrivateDebugAPI creates a new API definition for the private debug methods
  1490  // of the Ethereum service.
  1491  func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI {
  1492  	return &PrivateDebugAPI{b: b}
  1493  }
  1494  
  1495  // ChaindbProperty returns leveldb properties of the chain database.
  1496  func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) {
  1497  	ldb, ok := api.b.ChainDb().(interface {
  1498  		LDB() *leveldb.DB
  1499  	})
  1500  	if !ok {
  1501  		return "", fmt.Errorf("chaindbProperty does not work for memory databases")
  1502  	}
  1503  	if property == "" {
  1504  		property = "leveldb.stats"
  1505  	} else if !strings.HasPrefix(property, "leveldb.") {
  1506  		property = "leveldb." + property
  1507  	}
  1508  	return ldb.LDB().GetProperty(property)
  1509  }
  1510  
  1511  func (api *PrivateDebugAPI) ChaindbCompact() error {
  1512  	ldb, ok := api.b.ChainDb().(interface {
  1513  		LDB() *leveldb.DB
  1514  	})
  1515  	if !ok {
  1516  		return fmt.Errorf("chaindbCompact does not work for memory databases")
  1517  	}
  1518  	for b := byte(0); b < 255; b++ {
  1519  		log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1))
  1520  		err := ldb.LDB().CompactRange(util.Range{Start: []byte{b}, Limit: []byte{b + 1}})
  1521  		if err != nil {
  1522  			log.Error("Database compaction failed", "err", err)
  1523  			return err
  1524  		}
  1525  	}
  1526  	return nil
  1527  }
  1528  
  1529  // SetHead rewinds the head of the blockchain to a previous block.
  1530  func (api *PrivateDebugAPI) SetHead(number hexutil.Uint64) {
  1531  	api.b.SetHead(uint64(number))
  1532  }
  1533  
  1534  // PublicNetAPI offers network related RPC methods
  1535  type PublicNetAPI struct {
  1536  	net            *p2p.Server
  1537  	networkVersion uint64
  1538  }
  1539  
  1540  // NewPublicNetAPI creates a new net API instance.
  1541  func NewPublicNetAPI(net *p2p.Server, networkVersion uint64) *PublicNetAPI {
  1542  	return &PublicNetAPI{net, networkVersion}
  1543  }
  1544  
  1545  // Listening returns an indication if the node is listening for network connections.
  1546  func (s *PublicNetAPI) Listening() bool {
  1547  	return true // always listening
  1548  }
  1549  
  1550  // PeerCount returns the number of connected peers
  1551  func (s *PublicNetAPI) PeerCount() hexutil.Uint {
  1552  	return hexutil.Uint(s.net.PeerCount())
  1553  }
  1554  
  1555  // Version returns the current ethereum protocol version.
  1556  func (s *PublicNetAPI) Version() string {
  1557  	return fmt.Sprintf("%d", s.networkVersion)
  1558  }