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