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