github.com/RobustRoundRobin/quorum@v20.10.0+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  	"bytes"
    21  	"context"
    22  	"encoding/hex"
    23  	"encoding/json"
    24  	"errors"
    25  	"fmt"
    26  	"math/big"
    27  	"net/http"
    28  	"strings"
    29  	"sync"
    30  	"time"
    31  
    32  	"github.com/davecgh/go-spew/spew"
    33  	"github.com/ethereum/go-ethereum/accounts"
    34  	"github.com/ethereum/go-ethereum/accounts/keystore"
    35  	"github.com/ethereum/go-ethereum/accounts/pluggable"
    36  	"github.com/ethereum/go-ethereum/accounts/scwallet"
    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/clique"
    41  	"github.com/ethereum/go-ethereum/consensus/ethash"
    42  	"github.com/ethereum/go-ethereum/core"
    43  	"github.com/ethereum/go-ethereum/core/rawdb"
    44  	"github.com/ethereum/go-ethereum/core/state"
    45  	"github.com/ethereum/go-ethereum/core/types"
    46  	"github.com/ethereum/go-ethereum/core/vm"
    47  	"github.com/ethereum/go-ethereum/crypto"
    48  	"github.com/ethereum/go-ethereum/log"
    49  	"github.com/ethereum/go-ethereum/p2p"
    50  	"github.com/ethereum/go-ethereum/params"
    51  	"github.com/ethereum/go-ethereum/private"
    52  	"github.com/ethereum/go-ethereum/private/engine"
    53  	"github.com/ethereum/go-ethereum/rlp"
    54  	"github.com/ethereum/go-ethereum/rpc"
    55  	"github.com/tyler-smith/go-bip39"
    56  )
    57  
    58  const (
    59  	defaultGasPrice = params.GWei
    60  	//Hex-encoded 64 byte array of "17" values
    61  	maxPrivateIntrinsicDataHex = "11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"
    62  )
    63  
    64  type TransactionType uint8
    65  
    66  const (
    67  	FillTransaction TransactionType = iota + 1
    68  	RawTransaction
    69  	NormalTransaction
    70  )
    71  
    72  // PublicEthereumAPI provides an API to access Ethereum related information.
    73  // It offers only methods that operate on public data that is freely available to anyone.
    74  type PublicEthereumAPI struct {
    75  	b Backend
    76  }
    77  
    78  // NewPublicEthereumAPI creates a new Ethereum protocol API.
    79  func NewPublicEthereumAPI(b Backend) *PublicEthereumAPI {
    80  	return &PublicEthereumAPI{b}
    81  }
    82  
    83  // GasPrice returns a suggestion for a gas price.
    84  func (s *PublicEthereumAPI) GasPrice(ctx context.Context) (*hexutil.Big, error) {
    85  	price, err := s.b.SuggestPrice(ctx)
    86  	return (*hexutil.Big)(price), err
    87  }
    88  
    89  // ProtocolVersion returns the current Ethereum protocol version this node supports
    90  func (s *PublicEthereumAPI) ProtocolVersion() hexutil.Uint {
    91  	return hexutil.Uint(s.b.ProtocolVersion())
    92  }
    93  
    94  // Syncing returns false in case the node is currently not syncing with the network. It can be up to date or has not
    95  // yet received the latest block headers from its pears. In case it is synchronizing:
    96  // - startingBlock: block number this node started to synchronise from
    97  // - currentBlock:  block number this node is currently importing
    98  // - highestBlock:  block number of the highest block header this node has received from peers
    99  // - pulledStates:  number of state entries processed until now
   100  // - knownStates:   number of known state entries that still need to be pulled
   101  func (s *PublicEthereumAPI) Syncing() (interface{}, error) {
   102  	progress := s.b.Downloader().Progress()
   103  
   104  	// Return not syncing if the synchronisation already completed
   105  	if progress.CurrentBlock >= progress.HighestBlock {
   106  		return false, nil
   107  	}
   108  	// Otherwise gather the block sync stats
   109  	return map[string]interface{}{
   110  		"startingBlock": hexutil.Uint64(progress.StartingBlock),
   111  		"currentBlock":  hexutil.Uint64(progress.CurrentBlock),
   112  		"highestBlock":  hexutil.Uint64(progress.HighestBlock),
   113  		"pulledStates":  hexutil.Uint64(progress.PulledStates),
   114  		"knownStates":   hexutil.Uint64(progress.KnownStates),
   115  	}, nil
   116  }
   117  
   118  // PublicTxPoolAPI offers and API for the transaction pool. It only operates on data that is non confidential.
   119  type PublicTxPoolAPI struct {
   120  	b Backend
   121  }
   122  
   123  // NewPublicTxPoolAPI creates a new tx pool service that gives information about the transaction pool.
   124  func NewPublicTxPoolAPI(b Backend) *PublicTxPoolAPI {
   125  	return &PublicTxPoolAPI{b}
   126  }
   127  
   128  // Content returns the transactions contained within the transaction pool.
   129  func (s *PublicTxPoolAPI) Content() map[string]map[string]map[string]*RPCTransaction {
   130  	content := map[string]map[string]map[string]*RPCTransaction{
   131  		"pending": make(map[string]map[string]*RPCTransaction),
   132  		"queued":  make(map[string]map[string]*RPCTransaction),
   133  	}
   134  	pending, queue := s.b.TxPoolContent()
   135  
   136  	// Flatten the pending transactions
   137  	for account, txs := range pending {
   138  		dump := make(map[string]*RPCTransaction)
   139  		for _, tx := range txs {
   140  			dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx)
   141  		}
   142  		content["pending"][account.Hex()] = dump
   143  	}
   144  	// Flatten the queued transactions
   145  	for account, txs := range queue {
   146  		dump := make(map[string]*RPCTransaction)
   147  		for _, tx := range txs {
   148  			dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx)
   149  		}
   150  		content["queued"][account.Hex()] = dump
   151  	}
   152  	return content
   153  }
   154  
   155  // Status returns the number of pending and queued transaction in the pool.
   156  func (s *PublicTxPoolAPI) Status() map[string]hexutil.Uint {
   157  	pending, queue := s.b.Stats()
   158  	return map[string]hexutil.Uint{
   159  		"pending": hexutil.Uint(pending),
   160  		"queued":  hexutil.Uint(queue),
   161  	}
   162  }
   163  
   164  // Inspect retrieves the content of the transaction pool and flattens it into an
   165  // easily inspectable list.
   166  func (s *PublicTxPoolAPI) Inspect() map[string]map[string]map[string]string {
   167  	content := map[string]map[string]map[string]string{
   168  		"pending": make(map[string]map[string]string),
   169  		"queued":  make(map[string]map[string]string),
   170  	}
   171  	pending, queue := s.b.TxPoolContent()
   172  
   173  	// Define a formatter to flatten a transaction into a string
   174  	var format = func(tx *types.Transaction) string {
   175  		if to := tx.To(); to != nil {
   176  			return fmt.Sprintf("%s: %v wei + %v gas × %v wei", tx.To().Hex(), tx.Value(), tx.Gas(), tx.GasPrice())
   177  		}
   178  		return fmt.Sprintf("contract creation: %v wei + %v gas × %v wei", tx.Value(), tx.Gas(), tx.GasPrice())
   179  	}
   180  	// Flatten the pending transactions
   181  	for account, txs := range pending {
   182  		dump := make(map[string]string)
   183  		for _, tx := range txs {
   184  			dump[fmt.Sprintf("%d", tx.Nonce())] = format(tx)
   185  		}
   186  		content["pending"][account.Hex()] = dump
   187  	}
   188  	// Flatten the queued transactions
   189  	for account, txs := range queue {
   190  		dump := make(map[string]string)
   191  		for _, tx := range txs {
   192  			dump[fmt.Sprintf("%d", tx.Nonce())] = format(tx)
   193  		}
   194  		content["queued"][account.Hex()] = dump
   195  	}
   196  	return content
   197  }
   198  
   199  // PublicAccountAPI provides an API to access accounts managed by this node.
   200  // It offers only methods that can retrieve accounts.
   201  type PublicAccountAPI struct {
   202  	am *accounts.Manager
   203  }
   204  
   205  // NewPublicAccountAPI creates a new PublicAccountAPI.
   206  func NewPublicAccountAPI(am *accounts.Manager) *PublicAccountAPI {
   207  	return &PublicAccountAPI{am: am}
   208  }
   209  
   210  // Accounts returns the collection of accounts this node manages
   211  func (s *PublicAccountAPI) Accounts() []common.Address {
   212  	return s.am.Accounts()
   213  }
   214  
   215  // PrivateAccountAPI provides an API to access accounts managed by this node.
   216  // It offers methods to create, (un)lock en list accounts. Some methods accept
   217  // passwords and are therefore considered private by default.
   218  type PrivateAccountAPI struct {
   219  	am        *accounts.Manager
   220  	nonceLock *AddrLocker
   221  	b         Backend
   222  }
   223  
   224  // NewPrivateAccountAPI create a new PrivateAccountAPI.
   225  func NewPrivateAccountAPI(b Backend, nonceLock *AddrLocker) *PrivateAccountAPI {
   226  	return &PrivateAccountAPI{
   227  		am:        b.AccountManager(),
   228  		nonceLock: nonceLock,
   229  		b:         b,
   230  	}
   231  }
   232  
   233  // listAccounts will return a list of addresses for accounts this node manages.
   234  func (s *PrivateAccountAPI) ListAccounts() []common.Address {
   235  	return s.am.Accounts()
   236  }
   237  
   238  // rawWallet is a JSON representation of an accounts.Wallet interface, with its
   239  // data contents extracted into plain fields.
   240  type rawWallet struct {
   241  	URL      string             `json:"url"`
   242  	Status   string             `json:"status"`
   243  	Failure  string             `json:"failure,omitempty"`
   244  	Accounts []accounts.Account `json:"accounts,omitempty"`
   245  }
   246  
   247  // ListWallets will return a list of wallets this node manages.
   248  func (s *PrivateAccountAPI) ListWallets() []rawWallet {
   249  	wallets := make([]rawWallet, 0) // return [] instead of nil if empty
   250  	for _, wallet := range s.am.Wallets() {
   251  		status, failure := wallet.Status()
   252  
   253  		raw := rawWallet{
   254  			URL:      wallet.URL().String(),
   255  			Status:   status,
   256  			Accounts: wallet.Accounts(),
   257  		}
   258  		if failure != nil {
   259  			raw.Failure = failure.Error()
   260  		}
   261  		wallets = append(wallets, raw)
   262  	}
   263  	return wallets
   264  }
   265  
   266  // OpenWallet initiates a hardware wallet opening procedure, establishing a USB
   267  // connection and attempting to authenticate via the provided passphrase. Note,
   268  // the method may return an extra challenge requiring a second open (e.g. the
   269  // Trezor PIN matrix challenge).
   270  func (s *PrivateAccountAPI) OpenWallet(url string, passphrase *string) error {
   271  	wallet, err := s.am.Wallet(url)
   272  	if err != nil {
   273  		return err
   274  	}
   275  	pass := ""
   276  	if passphrase != nil {
   277  		pass = *passphrase
   278  	}
   279  	return wallet.Open(pass)
   280  }
   281  
   282  // DeriveAccount requests a HD wallet to derive a new account, optionally pinning
   283  // it for later reuse.
   284  func (s *PrivateAccountAPI) DeriveAccount(url string, path string, pin *bool) (accounts.Account, error) {
   285  	wallet, err := s.am.Wallet(url)
   286  	if err != nil {
   287  		return accounts.Account{}, err
   288  	}
   289  	derivPath, err := accounts.ParseDerivationPath(path)
   290  	if err != nil {
   291  		return accounts.Account{}, err
   292  	}
   293  	if pin == nil {
   294  		pin = new(bool)
   295  	}
   296  	return wallet.Derive(derivPath, *pin)
   297  }
   298  
   299  // NewAccount will create a new account and returns the address for the new account.
   300  func (s *PrivateAccountAPI) NewAccount(password string) (common.Address, error) {
   301  	ks, err := fetchKeystore(s.am)
   302  	if err != nil {
   303  		return common.Address{}, err
   304  	}
   305  	acc, err := ks.NewAccount(password)
   306  	if err == nil {
   307  		log.Info("Your new key was generated", "address", acc.Address)
   308  		log.Warn("Please backup your key file!", "path", acc.URL.Path)
   309  		log.Warn("Please remember your password!")
   310  		return acc.Address, nil
   311  	}
   312  	return common.Address{}, err
   313  }
   314  
   315  // fetchKeystore retrieves the encrypted keystore from the account manager.
   316  func fetchKeystore(am *accounts.Manager) (*keystore.KeyStore, error) {
   317  	if ks := am.Backends(keystore.KeyStoreType); len(ks) > 0 {
   318  		return ks[0].(*keystore.KeyStore), nil
   319  	}
   320  	return nil, errors.New("local keystore not used")
   321  }
   322  
   323  // ImportRawKey stores the given hex encoded ECDSA key into the key directory,
   324  // encrypting it with the passphrase.
   325  func (s *PrivateAccountAPI) ImportRawKey(privkey string, password string) (common.Address, error) {
   326  	key, err := crypto.HexToECDSA(privkey)
   327  	if err != nil {
   328  		return common.Address{}, err
   329  	}
   330  	ks, err := fetchKeystore(s.am)
   331  	if err != nil {
   332  		return common.Address{}, err
   333  	}
   334  	acc, err := ks.ImportECDSA(key, password)
   335  	return acc.Address, err
   336  }
   337  
   338  // UnlockAccount will unlock the account associated with the given address with
   339  // the given password for duration seconds. If duration is nil it will use a
   340  // default of 300 seconds. It returns an indication if the account was unlocked.
   341  func (s *PrivateAccountAPI) UnlockAccount(ctx context.Context, addr common.Address, password string, duration *uint64) (bool, error) {
   342  	// When the API is exposed by external RPC(http, ws etc), unless the user
   343  	// explicitly specifies to allow the insecure account unlocking, otherwise
   344  	// it is disabled.
   345  	if s.b.ExtRPCEnabled() && !s.b.AccountManager().Config().InsecureUnlockAllowed {
   346  		return false, errors.New("account unlock with HTTP access is forbidden")
   347  	}
   348  
   349  	const max = uint64(time.Duration(math.MaxInt64) / time.Second)
   350  	var d time.Duration
   351  	if duration == nil {
   352  		d = 300 * time.Second
   353  	} else if *duration > max {
   354  		return false, errors.New("unlock duration too large")
   355  	} else {
   356  		d = time.Duration(*duration) * time.Second
   357  	}
   358  	err := s.unlockAccount(addr, password, d)
   359  	if err != nil {
   360  		log.Warn("Failed account unlock attempt", "address", addr, "err", err)
   361  	}
   362  	return err == nil, err
   363  }
   364  
   365  func (s *PrivateAccountAPI) unlockAccount(addr common.Address, password string, duration time.Duration) error {
   366  	acct := accounts.Account{Address: addr}
   367  
   368  	backend, err := s.am.Backend(acct)
   369  	if err != nil {
   370  		return err
   371  	}
   372  
   373  	switch b := backend.(type) {
   374  	case *pluggable.Backend:
   375  		return b.TimedUnlock(acct, password, duration)
   376  	case *keystore.KeyStore:
   377  		return b.TimedUnlock(acct, password, duration)
   378  	default:
   379  		return errors.New("unlock only supported for keystore or plugin wallets")
   380  	}
   381  }
   382  
   383  // LockAccount will lock the account associated with the given address when it's unlocked.
   384  func (s *PrivateAccountAPI) LockAccount(addr common.Address) bool {
   385  	if err := s.lockAccount(addr); err != nil {
   386  		log.Warn("Failed account lock attempt", "address", addr, "err", err)
   387  		return false
   388  	}
   389  
   390  	return true
   391  }
   392  
   393  func (s *PrivateAccountAPI) lockAccount(addr common.Address) error {
   394  	acct := accounts.Account{Address: addr}
   395  
   396  	backend, err := s.am.Backend(acct)
   397  	if err != nil {
   398  		return err
   399  	}
   400  
   401  	switch b := backend.(type) {
   402  	case *pluggable.Backend:
   403  		return b.Lock(acct)
   404  	case *keystore.KeyStore:
   405  		return b.Lock(addr)
   406  	default:
   407  		return errors.New("lock only supported for keystore or plugin wallets")
   408  	}
   409  }
   410  
   411  // signTransaction sets defaults and signs the given transaction
   412  // NOTE: the caller needs to ensure that the nonceLock is held, if applicable,
   413  // and release it after the transaction has been submitted to the tx pool
   414  func (s *PrivateAccountAPI) signTransaction(ctx context.Context, args *SendTxArgs, passwd string) (*types.Transaction, error) {
   415  	// Look up the wallet containing the requested signer
   416  	account := accounts.Account{Address: args.From}
   417  	wallet, err := s.am.Find(account)
   418  	if err != nil {
   419  		return nil, err
   420  	}
   421  	// Set some sanity defaults and terminate on failure
   422  	if err := args.setDefaults(ctx, s.b); err != nil {
   423  		return nil, err
   424  	}
   425  	// Assemble the transaction and sign with the wallet
   426  	tx := args.toTransaction()
   427  
   428  	// Quorum
   429  	if args.IsPrivate() {
   430  		tx.SetPrivate()
   431  	}
   432  	var chainID *big.Int
   433  	if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) && !tx.IsPrivate() {
   434  		chainID = config.ChainID
   435  	}
   436  	// /Quorum
   437  
   438  	return wallet.SignTxWithPassphrase(account, passwd, tx, chainID)
   439  }
   440  
   441  // SendTransaction will create a transaction from the given arguments and
   442  // tries to sign it with the key associated with args.To. If the given passwd isn't
   443  // able to decrypt the key it fails.
   444  func (s *PrivateAccountAPI) SendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) {
   445  	if args.Nonce == nil {
   446  		// Hold the addresse's mutex around signing to prevent concurrent assignment of
   447  		// the same nonce to multiple accounts.
   448  		s.nonceLock.LockAddr(args.From)
   449  		defer s.nonceLock.UnlockAddr(args.From)
   450  	}
   451  
   452  	// Set some sanity defaults and terminate on failure
   453  	if err := args.setDefaults(ctx, s.b); err != nil {
   454  		return common.Hash{}, err
   455  	}
   456  
   457  	// Quorum
   458  	isPrivate, data, err := checkAndHandlePrivateTransaction(ctx, s.b, args.toTransaction(), &args.PrivateTxArgs, args.From, NormalTransaction)
   459  	if err != nil {
   460  		return common.Hash{}, err
   461  	}
   462  	if isPrivate && !common.EmptyEncryptedPayloadHash(data) {
   463  		// replace the original payload with encrypted payload hash
   464  		args.Data = data.BytesTypeRef()
   465  	}
   466  	// /Quorum
   467  
   468  	signed, err := s.signTransaction(ctx, &args, passwd)
   469  	if err != nil {
   470  		log.Warn("Failed transaction send attempt", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err)
   471  		return common.Hash{}, err
   472  	}
   473  	return SubmitTransaction(ctx, s.b, signed)
   474  }
   475  
   476  // SignTransaction will create a transaction from the given arguments and
   477  // tries to sign it with the key associated with args.To. If the given passwd isn't
   478  // able to decrypt the key it fails. The transaction is returned in RLP-form, not broadcast
   479  // to other nodes
   480  func (s *PrivateAccountAPI) SignTransaction(ctx context.Context, args SendTxArgs, passwd string) (*SignTransactionResult, error) {
   481  	// No need to obtain the noncelock mutex, since we won't be sending this
   482  	// tx into the transaction pool, but right back to the user
   483  	if args.Gas == nil {
   484  		return nil, fmt.Errorf("gas not specified")
   485  	}
   486  	if args.GasPrice == nil {
   487  		return nil, fmt.Errorf("gasPrice not specified")
   488  	}
   489  	if args.Nonce == nil {
   490  		return nil, fmt.Errorf("nonce not specified")
   491  	}
   492  	signed, err := s.signTransaction(ctx, &args, passwd)
   493  	if err != nil {
   494  		log.Warn("Failed transaction sign attempt", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err)
   495  		return nil, err
   496  	}
   497  	data, err := rlp.EncodeToBytes(signed)
   498  	if err != nil {
   499  		return nil, err
   500  	}
   501  	return &SignTransactionResult{data, signed}, nil
   502  }
   503  
   504  // Sign calculates an Ethereum ECDSA signature for:
   505  // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message))
   506  //
   507  // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
   508  // where the V value will be 27 or 28 for legacy reasons.
   509  //
   510  // The key used to calculate the signature is decrypted with the given password.
   511  //
   512  // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign
   513  func (s *PrivateAccountAPI) Sign(ctx context.Context, data hexutil.Bytes, addr common.Address, passwd string) (hexutil.Bytes, error) {
   514  	// Look up the wallet containing the requested signer
   515  	account := accounts.Account{Address: addr}
   516  
   517  	wallet, err := s.b.AccountManager().Find(account)
   518  	if err != nil {
   519  		return nil, err
   520  	}
   521  	// Assemble sign the data with the wallet
   522  	signature, err := wallet.SignTextWithPassphrase(account, passwd, data)
   523  	if err != nil {
   524  		log.Warn("Failed data sign attempt", "address", addr, "err", err)
   525  		return nil, err
   526  	}
   527  	signature[crypto.RecoveryIDOffset] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
   528  	return signature, nil
   529  }
   530  
   531  // EcRecover returns the address for the account that was used to create the signature.
   532  // Note, this function is compatible with eth_sign and personal_sign. As such it recovers
   533  // the address of:
   534  // hash = keccak256("\x19Ethereum Signed Message:\n"${message length}${message})
   535  // addr = ecrecover(hash, signature)
   536  //
   537  // Note, the signature must conform to the secp256k1 curve R, S and V values, where
   538  // the V value must be 27 or 28 for legacy reasons.
   539  //
   540  // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_ecRecover
   541  func (s *PrivateAccountAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) {
   542  	if len(sig) != crypto.SignatureLength {
   543  		return common.Address{}, fmt.Errorf("signature must be %d bytes long", crypto.SignatureLength)
   544  	}
   545  	if sig[crypto.RecoveryIDOffset] != 27 && sig[crypto.RecoveryIDOffset] != 28 {
   546  		return common.Address{}, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)")
   547  	}
   548  	sig[crypto.RecoveryIDOffset] -= 27 // Transform yellow paper V from 27/28 to 0/1
   549  
   550  	rpk, err := crypto.SigToPub(accounts.TextHash(data), sig)
   551  	if err != nil {
   552  		return common.Address{}, err
   553  	}
   554  	return crypto.PubkeyToAddress(*rpk), nil
   555  }
   556  
   557  // SignAndSendTransaction was renamed to SendTransaction. This method is deprecated
   558  // and will be removed in the future. It primary goal is to give clients time to update.
   559  func (s *PrivateAccountAPI) SignAndSendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) {
   560  	return s.SendTransaction(ctx, args, passwd)
   561  }
   562  
   563  // InitializeWallet initializes a new wallet at the provided URL, by generating and returning a new private key.
   564  func (s *PrivateAccountAPI) InitializeWallet(ctx context.Context, url string) (string, error) {
   565  	wallet, err := s.am.Wallet(url)
   566  	if err != nil {
   567  		return "", err
   568  	}
   569  
   570  	entropy, err := bip39.NewEntropy(256)
   571  	if err != nil {
   572  		return "", err
   573  	}
   574  
   575  	mnemonic, err := bip39.NewMnemonic(entropy)
   576  	if err != nil {
   577  		return "", err
   578  	}
   579  
   580  	seed := bip39.NewSeed(mnemonic, "")
   581  
   582  	switch wallet := wallet.(type) {
   583  	case *scwallet.Wallet:
   584  		return mnemonic, wallet.Initialize(seed)
   585  	default:
   586  		return "", fmt.Errorf("Specified wallet does not support initialization")
   587  	}
   588  }
   589  
   590  // Unpair deletes a pairing between wallet and geth.
   591  func (s *PrivateAccountAPI) Unpair(ctx context.Context, url string, pin string) error {
   592  	wallet, err := s.am.Wallet(url)
   593  	if err != nil {
   594  		return err
   595  	}
   596  
   597  	switch wallet := wallet.(type) {
   598  	case *scwallet.Wallet:
   599  		return wallet.Unpair([]byte(pin))
   600  	default:
   601  		return fmt.Errorf("Specified wallet does not support pairing")
   602  	}
   603  }
   604  
   605  // PublicBlockChainAPI provides an API to access the Ethereum blockchain.
   606  // It offers only methods that operate on public data that is freely available to anyone.
   607  type PublicBlockChainAPI struct {
   608  	b Backend
   609  }
   610  
   611  // NewPublicBlockChainAPI creates a new Ethereum blockchain API.
   612  func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI {
   613  	return &PublicBlockChainAPI{b}
   614  }
   615  
   616  // ChainId returns the chainID value for transaction replay protection.
   617  func (s *PublicBlockChainAPI) ChainId() *hexutil.Big {
   618  	return (*hexutil.Big)(s.b.ChainConfig().ChainID)
   619  }
   620  
   621  // BlockNumber returns the block number of the chain head.
   622  func (s *PublicBlockChainAPI) BlockNumber() hexutil.Uint64 {
   623  	header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available
   624  	return hexutil.Uint64(header.Number.Uint64())
   625  }
   626  
   627  // GetBalance returns the amount of wei for the given address in the state of the
   628  // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
   629  // block numbers are also allowed.
   630  func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Big, error) {
   631  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   632  	if state == nil || err != nil {
   633  		return nil, err
   634  	}
   635  	return (*hexutil.Big)(state.GetBalance(address)), state.Error()
   636  }
   637  
   638  // Result structs for GetProof
   639  type AccountResult struct {
   640  	Address      common.Address  `json:"address"`
   641  	AccountProof []string        `json:"accountProof"`
   642  	Balance      *hexutil.Big    `json:"balance"`
   643  	CodeHash     common.Hash     `json:"codeHash"`
   644  	Nonce        hexutil.Uint64  `json:"nonce"`
   645  	StorageHash  common.Hash     `json:"storageHash"`
   646  	StorageProof []StorageResult `json:"storageProof"`
   647  }
   648  type StorageResult struct {
   649  	Key   string       `json:"key"`
   650  	Value *hexutil.Big `json:"value"`
   651  	Proof []string     `json:"proof"`
   652  }
   653  
   654  // GetProof returns the Merkle-proof for a given account and optionally some storage keys.
   655  func (s *PublicBlockChainAPI) GetProof(ctx context.Context, address common.Address, storageKeys []string, blockNrOrHash rpc.BlockNumberOrHash) (*AccountResult, error) {
   656  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   657  	if state == nil || err != nil {
   658  		return nil, err
   659  	}
   660  
   661  	storageTrie := state.StorageTrie(address)
   662  	storageHash := types.EmptyRootHash
   663  	codeHash := state.GetCodeHash(address)
   664  	storageProof := make([]StorageResult, len(storageKeys))
   665  
   666  	// if we have a storageTrie, (which means the account exists), we can update the storagehash
   667  	if storageTrie != nil {
   668  		storageHash = storageTrie.Hash()
   669  	} else {
   670  		// no storageTrie means the account does not exist, so the codeHash is the hash of an empty bytearray.
   671  		codeHash = crypto.Keccak256Hash(nil)
   672  	}
   673  
   674  	// create the proof for the storageKeys
   675  	for i, key := range storageKeys {
   676  		if storageTrie != nil {
   677  			proof, storageError := state.GetStorageProof(address, common.HexToHash(key))
   678  			if storageError != nil {
   679  				return nil, storageError
   680  			}
   681  			storageProof[i] = StorageResult{key, (*hexutil.Big)(state.GetState(address, common.HexToHash(key)).Big()), common.ToHexArray(proof)}
   682  		} else {
   683  			storageProof[i] = StorageResult{key, &hexutil.Big{}, []string{}}
   684  		}
   685  	}
   686  
   687  	// create the accountProof
   688  	accountProof, proofErr := state.GetProof(address)
   689  	if proofErr != nil {
   690  		return nil, proofErr
   691  	}
   692  
   693  	return &AccountResult{
   694  		Address:      address,
   695  		AccountProof: common.ToHexArray(accountProof),
   696  		Balance:      (*hexutil.Big)(state.GetBalance(address)),
   697  		CodeHash:     codeHash,
   698  		Nonce:        hexutil.Uint64(state.GetNonce(address)),
   699  		StorageHash:  storageHash,
   700  		StorageProof: storageProof,
   701  	}, state.Error()
   702  }
   703  
   704  // GetHeaderByNumber returns the requested canonical block header.
   705  // * When blockNr is -1 the chain head is returned.
   706  // * When blockNr is -2 the pending chain head is returned.
   707  func (s *PublicBlockChainAPI) GetHeaderByNumber(ctx context.Context, number rpc.BlockNumber) (map[string]interface{}, error) {
   708  	header, err := s.b.HeaderByNumber(ctx, number)
   709  	if header != nil && err == nil {
   710  		response := s.rpcMarshalHeader(header)
   711  		if number == rpc.PendingBlockNumber {
   712  			// Pending header need to nil out a few fields
   713  			for _, field := range []string{"hash", "nonce", "miner"} {
   714  				response[field] = nil
   715  			}
   716  		}
   717  		return response, err
   718  	}
   719  	return nil, err
   720  }
   721  
   722  // GetHeaderByHash returns the requested header by hash.
   723  func (s *PublicBlockChainAPI) GetHeaderByHash(ctx context.Context, hash common.Hash) map[string]interface{} {
   724  	header, _ := s.b.HeaderByHash(ctx, hash)
   725  	if header != nil {
   726  		return s.rpcMarshalHeader(header)
   727  	}
   728  	return nil
   729  }
   730  
   731  // GetBlockByNumber returns the requested canonical block.
   732  // * When blockNr is -1 the chain head is returned.
   733  // * When blockNr is -2 the pending chain head is returned.
   734  // * When fullTx is true all transactions in the block are returned, otherwise
   735  //   only the transaction hash is returned.
   736  func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, number rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
   737  	block, err := s.b.BlockByNumber(ctx, number)
   738  	if block != nil && err == nil {
   739  		response, err := s.rpcMarshalBlock(block, true, fullTx)
   740  		if err == nil && number == rpc.PendingBlockNumber {
   741  			// Pending blocks need to nil out a few fields
   742  			for _, field := range []string{"hash", "nonce", "miner"} {
   743  				response[field] = nil
   744  			}
   745  		}
   746  		return response, err
   747  	}
   748  	return nil, err
   749  }
   750  
   751  // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
   752  // detail, otherwise only the transaction hash is returned.
   753  func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, hash common.Hash, fullTx bool) (map[string]interface{}, error) {
   754  	block, err := s.b.BlockByHash(ctx, hash)
   755  	if block != nil {
   756  		return s.rpcMarshalBlock(block, true, fullTx)
   757  	}
   758  	return nil, err
   759  }
   760  
   761  // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true
   762  // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
   763  func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) {
   764  	block, err := s.b.BlockByNumber(ctx, blockNr)
   765  	if block != nil {
   766  		uncles := block.Uncles()
   767  		if index >= hexutil.Uint(len(uncles)) {
   768  			log.Debug("Requested uncle not found", "number", blockNr, "hash", block.Hash(), "index", index)
   769  			return nil, nil
   770  		}
   771  		block = types.NewBlockWithHeader(uncles[index])
   772  		return s.rpcMarshalBlock(block, false, false)
   773  	}
   774  	return nil, err
   775  }
   776  
   777  // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true
   778  // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
   779  func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) {
   780  	block, err := s.b.BlockByHash(ctx, blockHash)
   781  	if block != nil {
   782  		uncles := block.Uncles()
   783  		if index >= hexutil.Uint(len(uncles)) {
   784  			log.Debug("Requested uncle not found", "number", block.Number(), "hash", blockHash, "index", index)
   785  			return nil, nil
   786  		}
   787  		block = types.NewBlockWithHeader(uncles[index])
   788  		return s.rpcMarshalBlock(block, false, false)
   789  	}
   790  	return nil, err
   791  }
   792  
   793  // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
   794  func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
   795  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
   796  		n := hexutil.Uint(len(block.Uncles()))
   797  		return &n
   798  	}
   799  	return nil
   800  }
   801  
   802  // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash
   803  func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
   804  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
   805  		n := hexutil.Uint(len(block.Uncles()))
   806  		return &n
   807  	}
   808  	return nil
   809  }
   810  
   811  // GetCode returns the code stored at the given address in the state for the given block number.
   812  func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
   813  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   814  	if state == nil || err != nil {
   815  		return nil, err
   816  	}
   817  	code := state.GetCode(address)
   818  	return code, state.Error()
   819  }
   820  
   821  // GetStorageAt returns the storage from the state at the given address, key and
   822  // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
   823  // numbers are also allowed.
   824  func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
   825  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   826  	if state == nil || err != nil {
   827  		return nil, err
   828  	}
   829  	res := state.GetState(address, common.HexToHash(key))
   830  	return res[:], state.Error()
   831  }
   832  
   833  // CallArgs represents the arguments for a call.
   834  type CallArgs struct {
   835  	From     *common.Address `json:"from"`
   836  	To       *common.Address `json:"to"`
   837  	Gas      *hexutil.Uint64 `json:"gas"`
   838  	GasPrice *hexutil.Big    `json:"gasPrice"`
   839  	Value    *hexutil.Big    `json:"value"`
   840  	Data     *hexutil.Bytes  `json:"data"`
   841  }
   842  
   843  // account indicates the overriding fields of account during the execution of
   844  // a message call.
   845  // Note, state and stateDiff can't be specified at the same time. If state is
   846  // set, message execution will only use the data in the given state. Otherwise
   847  // if statDiff is set, all diff will be applied first and then execute the call
   848  // message.
   849  type account struct {
   850  	Nonce     *hexutil.Uint64              `json:"nonce"`
   851  	Code      *hexutil.Bytes               `json:"code"`
   852  	Balance   **hexutil.Big                `json:"balance"`
   853  	State     *map[common.Hash]common.Hash `json:"state"`
   854  	StateDiff *map[common.Hash]common.Hash `json:"stateDiff"`
   855  }
   856  
   857  func DoCall(ctx context.Context, b Backend, args CallArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides map[common.Address]account, vmCfg vm.Config, timeout time.Duration, globalGasCap *big.Int) ([]byte, uint64, bool, error) {
   858  	defer func(start time.Time) { log.Debug("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now())
   859  
   860  	state, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   861  	if state == nil || err != nil {
   862  		return nil, 0, false, err
   863  	}
   864  	// Set sender address or use a default if none specified
   865  	var addr common.Address
   866  	if args.From == nil {
   867  		if wallets := b.AccountManager().Wallets(); len(wallets) > 0 {
   868  			if accounts := wallets[0].Accounts(); len(accounts) > 0 {
   869  				addr = accounts[0].Address
   870  			}
   871  		}
   872  	} else {
   873  		addr = *args.From
   874  	}
   875  	// Override the fields of specified contracts before execution.
   876  	for addr, account := range overrides {
   877  		// Override account nonce.
   878  		if account.Nonce != nil {
   879  			state.SetNonce(addr, uint64(*account.Nonce))
   880  		}
   881  		// Override account(contract) code.
   882  		if account.Code != nil {
   883  			state.SetCode(addr, *account.Code)
   884  		}
   885  		// Override account balance.
   886  		if account.Balance != nil {
   887  			state.SetBalance(addr, (*big.Int)(*account.Balance))
   888  		}
   889  		if account.State != nil && account.StateDiff != nil {
   890  			return nil, 0, false, fmt.Errorf("account %s has both 'state' and 'stateDiff'", addr.Hex())
   891  		}
   892  		// Replace entire state if caller requires.
   893  		if account.State != nil {
   894  			state.SetStorage(addr, *account.State)
   895  		}
   896  		// Apply state diff into specified accounts.
   897  		if account.StateDiff != nil {
   898  			for key, value := range *account.StateDiff {
   899  				state.SetState(addr, key, value)
   900  			}
   901  		}
   902  	}
   903  	// Set default gas & gas price if none were set
   904  	gas := uint64(math.MaxUint64 / 2)
   905  	if args.Gas != nil {
   906  		gas = uint64(*args.Gas)
   907  	}
   908  	if globalGasCap != nil && globalGasCap.Uint64() < gas {
   909  		log.Warn("Caller gas above allowance, capping", "requested", gas, "cap", globalGasCap)
   910  		gas = globalGasCap.Uint64()
   911  	}
   912  	gasPrice := new(big.Int).SetUint64(defaultGasPrice)
   913  	// Set Quorum default gas price
   914  	if b.ChainConfig().IsQuorum {
   915  		gasPrice = new(big.Int).SetUint64(0)
   916  	}
   917  	if args.GasPrice != nil {
   918  		gasPrice = args.GasPrice.ToInt()
   919  	}
   920  
   921  	value := new(big.Int)
   922  	if args.Value != nil {
   923  		value = args.Value.ToInt()
   924  	}
   925  
   926  	var data []byte
   927  	if args.Data != nil {
   928  		data = []byte(*args.Data)
   929  	}
   930  
   931  	// Create new call message
   932  	msg := types.NewMessage(addr, args.To, 0, value, gas, gasPrice, data, false)
   933  
   934  	// Setup context so it may be cancelled the call has completed
   935  	// or, in case of unmetered gas, setup a context with a timeout.
   936  	var cancel context.CancelFunc
   937  	if timeout > 0 {
   938  		ctx, cancel = context.WithTimeout(ctx, timeout)
   939  	} else {
   940  		ctx, cancel = context.WithCancel(ctx)
   941  	}
   942  	// Make sure the context is cancelled when the call has completed
   943  	// this makes sure resources are cleaned up.
   944  	defer cancel()
   945  
   946  	// Get a new instance of the EVM.
   947  	evm, vmError, err := b.GetEVM(ctx, msg, state, header)
   948  	if err != nil {
   949  		return nil, 0, false, err
   950  	}
   951  	// Wait for the context to be done and cancel the evm. Even if the
   952  	// EVM has finished, cancelling may be done (repeatedly)
   953  	go func() {
   954  		<-ctx.Done()
   955  		evm.Cancel()
   956  	}()
   957  
   958  	// Setup the gas pool (also for unmetered requests)
   959  	// and apply the message.
   960  	gp := new(core.GasPool).AddGas(math.MaxUint64)
   961  	res, gas, failed, err := core.ApplyMessage(evm, msg, gp)
   962  	if err := vmError(); err != nil {
   963  		return nil, 0, false, err
   964  	}
   965  	// If the timer caused an abort, return an appropriate error message
   966  	if evm.Cancelled() {
   967  		return nil, 0, false, fmt.Errorf("execution aborted (timeout = %v)", timeout)
   968  	}
   969  	return res, gas, failed, err
   970  }
   971  
   972  // Call executes the given transaction on the state for the given block number.
   973  //
   974  // Additionally, the caller can specify a batch of contract for fields overriding.
   975  //
   976  // Note, this function doesn't make and changes in the state/blockchain and is
   977  // useful to execute and retrieve values.
   978  func (s *PublicBlockChainAPI) Call(ctx context.Context, args CallArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *map[common.Address]account) (hexutil.Bytes, error) {
   979  	var accounts map[common.Address]account
   980  	if overrides != nil {
   981  		accounts = *overrides
   982  	}
   983  
   984  	// Quorum - replaced the default 5s time out with the value passed in vm.calltimeout
   985  	result, _, _, err := DoCall(ctx, s.b, args, blockNrOrHash, accounts, vm.Config{}, s.b.CallTimeOut(), s.b.RPCGasCap())
   986  	return (hexutil.Bytes)(result), err
   987  }
   988  
   989  func DoEstimateGas(ctx context.Context, b Backend, args CallArgs, blockNrOrHash rpc.BlockNumberOrHash, gasCap *big.Int) (hexutil.Uint64, error) {
   990  	// Binary search the gas requirement, as it may be higher than the amount used
   991  	var (
   992  		lo  uint64 = params.TxGas - 1
   993  		hi  uint64
   994  		cap uint64
   995  	)
   996  	if args.Gas != nil && uint64(*args.Gas) >= params.TxGas {
   997  		hi = uint64(*args.Gas)
   998  	} else {
   999  		// Retrieve the block to act as the gas ceiling
  1000  		block, err := b.BlockByNumberOrHash(ctx, blockNrOrHash)
  1001  		if err != nil {
  1002  			return 0, err
  1003  		}
  1004  		hi = block.GasLimit()
  1005  	}
  1006  	if gasCap != nil && hi > gasCap.Uint64() {
  1007  		log.Warn("Caller gas above allowance, capping", "requested", hi, "cap", gasCap)
  1008  		hi = gasCap.Uint64()
  1009  	}
  1010  	cap = hi
  1011  
  1012  	// Create a helper to check if a gas allowance results in an executable transaction
  1013  	executable := func(gas uint64) bool {
  1014  		args.Gas = (*hexutil.Uint64)(&gas)
  1015  
  1016  		_, _, failed, err := DoCall(ctx, b, args, blockNrOrHash, nil, vm.Config{}, 0, gasCap)
  1017  		if err != nil || failed {
  1018  			return false
  1019  		}
  1020  		return true
  1021  	}
  1022  	// Execute the binary search and hone in on an executable gas limit
  1023  	for lo+1 < hi {
  1024  		mid := (hi + lo) / 2
  1025  		if !executable(mid) {
  1026  			lo = mid
  1027  		} else {
  1028  			hi = mid
  1029  		}
  1030  	}
  1031  	// Reject the transaction as invalid if it still fails at the highest allowance
  1032  	if hi == cap {
  1033  		if !executable(hi) {
  1034  			return 0, fmt.Errorf("gas required exceeds allowance (%d) or always failing transaction", cap)
  1035  		}
  1036  	}
  1037  
  1038  	//QUORUM
  1039  
  1040  	//We don't know if this is going to be a private or public transaction
  1041  	//It is possible to have a data field that has a lower intrinsic value than the PTM hash
  1042  	//so this checks that if we were to place a PTM hash (with all non-zero values) here then the transaction would
  1043  	//still run
  1044  	//This makes the return value a potential over-estimate of gas, rather than the exact cost to run right now
  1045  
  1046  	//if the transaction has a value then it cannot be private, so we can skip this check
  1047  	if args.Value != nil && args.Value.ToInt().Cmp(big.NewInt(0)) == 0 {
  1048  		homestead := b.ChainConfig().IsHomestead(new(big.Int).SetInt64(int64(rpc.PendingBlockNumber)))
  1049  		istanbul := b.ChainConfig().IsIstanbul(new(big.Int).SetInt64(int64(rpc.PendingBlockNumber)))
  1050  		var data []byte
  1051  		if args.Data == nil {
  1052  			data = nil
  1053  		} else {
  1054  			data = []byte(*args.Data)
  1055  		}
  1056  		intrinsicGasPublic, _ := core.IntrinsicGas(data, args.To == nil, homestead, istanbul)
  1057  		intrinsicGasPrivate, _ := core.IntrinsicGas(common.Hex2Bytes(maxPrivateIntrinsicDataHex), args.To == nil, homestead, istanbul)
  1058  
  1059  		if intrinsicGasPrivate > intrinsicGasPublic {
  1060  			if math.MaxUint64-hi < intrinsicGasPrivate-intrinsicGasPublic {
  1061  				return 0, fmt.Errorf("private intrinsic gas addition exceeds allowance")
  1062  			}
  1063  			return hexutil.Uint64(hi + (intrinsicGasPrivate - intrinsicGasPublic)), nil
  1064  		}
  1065  
  1066  	}
  1067  
  1068  	//END QUORUM
  1069  
  1070  	return hexutil.Uint64(hi), nil
  1071  }
  1072  
  1073  // EstimateGas returns an estimate of the amount of gas needed to execute the
  1074  // given transaction against the current pending block.
  1075  func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args CallArgs) (hexutil.Uint64, error) {
  1076  	blockNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
  1077  	return DoEstimateGas(ctx, s.b, args, blockNrOrHash, s.b.RPCGasCap())
  1078  }
  1079  
  1080  // ExecutionResult groups all structured logs emitted by the EVM
  1081  // while replaying a transaction in debug mode as well as transaction
  1082  // execution status, the amount of gas used and the return value
  1083  type ExecutionResult struct {
  1084  	Gas         uint64         `json:"gas"`
  1085  	Failed      bool           `json:"failed"`
  1086  	ReturnValue string         `json:"returnValue"`
  1087  	StructLogs  []StructLogRes `json:"structLogs"`
  1088  }
  1089  
  1090  // StructLogRes stores a structured log emitted by the EVM while replaying a
  1091  // transaction in debug mode
  1092  type StructLogRes struct {
  1093  	Pc      uint64             `json:"pc"`
  1094  	Op      string             `json:"op"`
  1095  	Gas     uint64             `json:"gas"`
  1096  	GasCost uint64             `json:"gasCost"`
  1097  	Depth   int                `json:"depth"`
  1098  	Error   error              `json:"error,omitempty"`
  1099  	Stack   *[]string          `json:"stack,omitempty"`
  1100  	Memory  *[]string          `json:"memory,omitempty"`
  1101  	Storage *map[string]string `json:"storage,omitempty"`
  1102  }
  1103  
  1104  // FormatLogs formats EVM returned structured logs for json output
  1105  func FormatLogs(logs []vm.StructLog) []StructLogRes {
  1106  	formatted := make([]StructLogRes, len(logs))
  1107  	for index, trace := range logs {
  1108  		formatted[index] = StructLogRes{
  1109  			Pc:      trace.Pc,
  1110  			Op:      trace.Op.String(),
  1111  			Gas:     trace.Gas,
  1112  			GasCost: trace.GasCost,
  1113  			Depth:   trace.Depth,
  1114  			Error:   trace.Err,
  1115  		}
  1116  		if trace.Stack != nil {
  1117  			stack := make([]string, len(trace.Stack))
  1118  			for i, stackValue := range trace.Stack {
  1119  				stack[i] = fmt.Sprintf("%x", math.PaddedBigBytes(stackValue, 32))
  1120  			}
  1121  			formatted[index].Stack = &stack
  1122  		}
  1123  		if trace.Memory != nil {
  1124  			memory := make([]string, 0, (len(trace.Memory)+31)/32)
  1125  			for i := 0; i+32 <= len(trace.Memory); i += 32 {
  1126  				memory = append(memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
  1127  			}
  1128  			formatted[index].Memory = &memory
  1129  		}
  1130  		if trace.Storage != nil {
  1131  			storage := make(map[string]string)
  1132  			for i, storageValue := range trace.Storage {
  1133  				storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
  1134  			}
  1135  			formatted[index].Storage = &storage
  1136  		}
  1137  	}
  1138  	return formatted
  1139  }
  1140  
  1141  // RPCMarshalHeader converts the given header to the RPC output .
  1142  func RPCMarshalHeader(head *types.Header) map[string]interface{} {
  1143  	return map[string]interface{}{
  1144  		"number":           (*hexutil.Big)(head.Number),
  1145  		"hash":             head.Hash(),
  1146  		"parentHash":       head.ParentHash,
  1147  		"nonce":            head.Nonce,
  1148  		"mixHash":          head.MixDigest,
  1149  		"sha3Uncles":       head.UncleHash,
  1150  		"logsBloom":        head.Bloom,
  1151  		"stateRoot":        head.Root,
  1152  		"miner":            head.Coinbase,
  1153  		"difficulty":       (*hexutil.Big)(head.Difficulty),
  1154  		"extraData":        hexutil.Bytes(head.Extra),
  1155  		"size":             hexutil.Uint64(head.Size()),
  1156  		"gasLimit":         hexutil.Uint64(head.GasLimit),
  1157  		"gasUsed":          hexutil.Uint64(head.GasUsed),
  1158  		"timestamp":        hexutil.Uint64(head.Time),
  1159  		"transactionsRoot": head.TxHash,
  1160  		"receiptsRoot":     head.ReceiptHash,
  1161  	}
  1162  }
  1163  
  1164  // RPCMarshalBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
  1165  // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
  1166  // transaction hashes.
  1167  func RPCMarshalBlock(block *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  1168  	fields := RPCMarshalHeader(block.Header())
  1169  	fields["size"] = hexutil.Uint64(block.Size())
  1170  
  1171  	if inclTx {
  1172  		formatTx := func(tx *types.Transaction) (interface{}, error) {
  1173  			return tx.Hash(), nil
  1174  		}
  1175  		if fullTx {
  1176  			formatTx = func(tx *types.Transaction) (interface{}, error) {
  1177  				return newRPCTransactionFromBlockHash(block, tx.Hash()), nil
  1178  			}
  1179  		}
  1180  		txs := block.Transactions()
  1181  		transactions := make([]interface{}, len(txs))
  1182  		var err error
  1183  		for i, tx := range txs {
  1184  			if transactions[i], err = formatTx(tx); err != nil {
  1185  				return nil, err
  1186  			}
  1187  		}
  1188  		fields["transactions"] = transactions
  1189  	}
  1190  	uncles := block.Uncles()
  1191  	uncleHashes := make([]common.Hash, len(uncles))
  1192  	for i, uncle := range uncles {
  1193  		uncleHashes[i] = uncle.Hash()
  1194  	}
  1195  	fields["uncles"] = uncleHashes
  1196  
  1197  	return fields, nil
  1198  }
  1199  
  1200  // rpcMarshalHeader uses the generalized output filler, then adds the total difficulty field, which requires
  1201  // a `PublicBlockchainAPI`.
  1202  func (s *PublicBlockChainAPI) rpcMarshalHeader(header *types.Header) map[string]interface{} {
  1203  	fields := RPCMarshalHeader(header)
  1204  	fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(header.Hash()))
  1205  	return fields
  1206  }
  1207  
  1208  // rpcMarshalBlock uses the generalized output filler, then adds the total difficulty field, which requires
  1209  // a `PublicBlockchainAPI`.
  1210  func (s *PublicBlockChainAPI) rpcMarshalBlock(b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  1211  	fields, err := RPCMarshalBlock(b, inclTx, fullTx)
  1212  	if err != nil {
  1213  		return nil, err
  1214  	}
  1215  	fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(b.Hash()))
  1216  	return fields, err
  1217  }
  1218  
  1219  // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
  1220  type RPCTransaction struct {
  1221  	BlockHash        *common.Hash    `json:"blockHash"`
  1222  	BlockNumber      *hexutil.Big    `json:"blockNumber"`
  1223  	From             common.Address  `json:"from"`
  1224  	Gas              hexutil.Uint64  `json:"gas"`
  1225  	GasPrice         *hexutil.Big    `json:"gasPrice"`
  1226  	Hash             common.Hash     `json:"hash"`
  1227  	Input            hexutil.Bytes   `json:"input"`
  1228  	Nonce            hexutil.Uint64  `json:"nonce"`
  1229  	To               *common.Address `json:"to"`
  1230  	TransactionIndex *hexutil.Uint64 `json:"transactionIndex"`
  1231  	Value            *hexutil.Big    `json:"value"`
  1232  	V                *hexutil.Big    `json:"v"`
  1233  	R                *hexutil.Big    `json:"r"`
  1234  	S                *hexutil.Big    `json:"s"`
  1235  }
  1236  
  1237  // newRPCTransaction returns a transaction that will serialize to the RPC
  1238  // representation, with the given location metadata set (if available).
  1239  func newRPCTransaction(tx *types.Transaction, blockHash common.Hash, blockNumber uint64, index uint64) *RPCTransaction {
  1240  	var signer types.Signer = types.HomesteadSigner{}
  1241  	// joel: this is one of the two places we used a wrong signer to print txes
  1242  	if tx.Protected() && !tx.IsPrivate() {
  1243  		signer = types.NewEIP155Signer(tx.ChainId())
  1244  	}
  1245  	from, _ := types.Sender(signer, tx)
  1246  	v, r, s := tx.RawSignatureValues()
  1247  
  1248  	result := &RPCTransaction{
  1249  		From:     from,
  1250  		Gas:      hexutil.Uint64(tx.Gas()),
  1251  		GasPrice: (*hexutil.Big)(tx.GasPrice()),
  1252  		Hash:     tx.Hash(),
  1253  		Input:    hexutil.Bytes(tx.Data()),
  1254  		Nonce:    hexutil.Uint64(tx.Nonce()),
  1255  		To:       tx.To(),
  1256  		Value:    (*hexutil.Big)(tx.Value()),
  1257  		V:        (*hexutil.Big)(v),
  1258  		R:        (*hexutil.Big)(r),
  1259  		S:        (*hexutil.Big)(s),
  1260  	}
  1261  	if blockHash != (common.Hash{}) {
  1262  		result.BlockHash = &blockHash
  1263  		result.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(blockNumber))
  1264  		result.TransactionIndex = (*hexutil.Uint64)(&index)
  1265  	}
  1266  	return result
  1267  }
  1268  
  1269  // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation
  1270  func newRPCPendingTransaction(tx *types.Transaction) *RPCTransaction {
  1271  	return newRPCTransaction(tx, common.Hash{}, 0, 0)
  1272  }
  1273  
  1274  // newRPCTransactionFromBlockIndex returns a transaction that will serialize to the RPC representation.
  1275  func newRPCTransactionFromBlockIndex(b *types.Block, index uint64) *RPCTransaction {
  1276  	txs := b.Transactions()
  1277  	if index >= uint64(len(txs)) {
  1278  		return nil
  1279  	}
  1280  	return newRPCTransaction(txs[index], b.Hash(), b.NumberU64(), index)
  1281  }
  1282  
  1283  // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index.
  1284  func newRPCRawTransactionFromBlockIndex(b *types.Block, index uint64) hexutil.Bytes {
  1285  	txs := b.Transactions()
  1286  	if index >= uint64(len(txs)) {
  1287  		return nil
  1288  	}
  1289  	blob, _ := rlp.EncodeToBytes(txs[index])
  1290  	return blob
  1291  }
  1292  
  1293  // newRPCTransactionFromBlockHash returns a transaction that will serialize to the RPC representation.
  1294  func newRPCTransactionFromBlockHash(b *types.Block, hash common.Hash) *RPCTransaction {
  1295  	for idx, tx := range b.Transactions() {
  1296  		if tx.Hash() == hash {
  1297  			return newRPCTransactionFromBlockIndex(b, uint64(idx))
  1298  		}
  1299  	}
  1300  	return nil
  1301  }
  1302  
  1303  // PublicTransactionPoolAPI exposes methods for the RPC interface
  1304  type PublicTransactionPoolAPI struct {
  1305  	b         Backend
  1306  	nonceLock *AddrLocker
  1307  }
  1308  
  1309  // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.
  1310  func NewPublicTransactionPoolAPI(b Backend, nonceLock *AddrLocker) *PublicTransactionPoolAPI {
  1311  	return &PublicTransactionPoolAPI{b, nonceLock}
  1312  }
  1313  
  1314  // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
  1315  func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  1316  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1317  		n := hexutil.Uint(len(block.Transactions()))
  1318  		return &n
  1319  	}
  1320  	return nil
  1321  }
  1322  
  1323  // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
  1324  func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  1325  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1326  		n := hexutil.Uint(len(block.Transactions()))
  1327  		return &n
  1328  	}
  1329  	return nil
  1330  }
  1331  
  1332  // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
  1333  func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) *RPCTransaction {
  1334  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1335  		return newRPCTransactionFromBlockIndex(block, uint64(index))
  1336  	}
  1337  	return nil
  1338  }
  1339  
  1340  // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
  1341  func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) *RPCTransaction {
  1342  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1343  		return newRPCTransactionFromBlockIndex(block, uint64(index))
  1344  	}
  1345  	return nil
  1346  }
  1347  
  1348  // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
  1349  func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) hexutil.Bytes {
  1350  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1351  		return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1352  	}
  1353  	return nil
  1354  }
  1355  
  1356  // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index.
  1357  func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) hexutil.Bytes {
  1358  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1359  		return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1360  	}
  1361  	return nil
  1362  }
  1363  
  1364  // GetTransactionCount returns the number of transactions the given address has sent for the given block number
  1365  func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Uint64, error) {
  1366  	// Ask transaction pool for the nonce which includes pending transactions
  1367  	if blockNr, ok := blockNrOrHash.Number(); ok && blockNr == rpc.PendingBlockNumber {
  1368  		nonce, err := s.b.GetPoolNonce(ctx, address)
  1369  		if err != nil {
  1370  			return nil, err
  1371  		}
  1372  		return (*hexutil.Uint64)(&nonce), nil
  1373  	}
  1374  	// Resolve block number and use its state to ask for the nonce
  1375  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1376  	if state == nil || err != nil {
  1377  		return nil, err
  1378  	}
  1379  	nonce := state.GetNonce(address)
  1380  	return (*hexutil.Uint64)(&nonce), state.Error()
  1381  }
  1382  
  1383  // Quorum
  1384  func (s *PublicTransactionPoolAPI) GetContractPrivacyMetadata(ctx context.Context, address common.Address) (*state.PrivacyMetadata, error) {
  1385  	state, _, err := s.b.StateAndHeaderByNumber(ctx, rpc.LatestBlockNumber)
  1386  	if state == nil || err != nil {
  1387  		return nil, err
  1388  	}
  1389  	return state.GetStatePrivacyMetadata(address)
  1390  }
  1391  
  1392  // /Quorum
  1393  
  1394  // GetTransactionByHash returns the transaction for the given hash
  1395  func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) (*RPCTransaction, error) {
  1396  	// Try to return an already finalized transaction
  1397  	tx, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1398  	if err != nil {
  1399  		return nil, err
  1400  	}
  1401  	if tx != nil {
  1402  		return newRPCTransaction(tx, blockHash, blockNumber, index), nil
  1403  	}
  1404  	// No finalized transaction, try to retrieve it from the pool
  1405  	if tx := s.b.GetPoolTransaction(hash); tx != nil {
  1406  		return newRPCPendingTransaction(tx), nil
  1407  	}
  1408  
  1409  	// Transaction unknown, return as such
  1410  	return nil, nil
  1411  }
  1412  
  1413  // GetRawTransactionByHash returns the bytes of the transaction for the given hash.
  1414  func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  1415  	// Retrieve a finalized transaction, or a pooled otherwise
  1416  	tx, _, _, _, err := s.b.GetTransaction(ctx, hash)
  1417  	if err != nil {
  1418  		return nil, err
  1419  	}
  1420  	if tx == nil {
  1421  		if tx = s.b.GetPoolTransaction(hash); tx == nil {
  1422  			// Transaction not found anywhere, abort
  1423  			return nil, nil
  1424  		}
  1425  	}
  1426  	// Serialize to RLP and return
  1427  	return rlp.EncodeToBytes(tx)
  1428  }
  1429  
  1430  // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  1431  func (s *PublicTransactionPoolAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) {
  1432  	tx, blockHash, blockNumber, index := rawdb.ReadTransaction(s.b.ChainDb(), hash)
  1433  	if tx == nil {
  1434  		return nil, nil
  1435  	}
  1436  	receipts, err := s.b.GetReceipts(ctx, blockHash)
  1437  	if err != nil {
  1438  		return nil, err
  1439  	}
  1440  	if len(receipts) <= int(index) {
  1441  		return nil, nil
  1442  	}
  1443  	receipt := receipts[index]
  1444  
  1445  	var signer types.Signer = types.HomesteadSigner{}
  1446  	if tx.Protected() && !tx.IsPrivate() {
  1447  		signer = types.NewEIP155Signer(tx.ChainId())
  1448  	}
  1449  	from, _ := types.Sender(signer, tx)
  1450  
  1451  	fields := map[string]interface{}{
  1452  		"blockHash":         blockHash,
  1453  		"blockNumber":       hexutil.Uint64(blockNumber),
  1454  		"transactionHash":   hash,
  1455  		"transactionIndex":  hexutil.Uint64(index),
  1456  		"from":              from,
  1457  		"to":                tx.To(),
  1458  		"gasUsed":           hexutil.Uint64(receipt.GasUsed),
  1459  		"cumulativeGasUsed": hexutil.Uint64(receipt.CumulativeGasUsed),
  1460  		"contractAddress":   nil,
  1461  		"logs":              receipt.Logs,
  1462  		"logsBloom":         receipt.Bloom,
  1463  	}
  1464  
  1465  	// Assign receipt status or post state.
  1466  	if len(receipt.PostState) > 0 {
  1467  		fields["root"] = hexutil.Bytes(receipt.PostState)
  1468  	} else {
  1469  		fields["status"] = hexutil.Uint(receipt.Status)
  1470  	}
  1471  	if receipt.Logs == nil {
  1472  		fields["logs"] = [][]*types.Log{}
  1473  	}
  1474  	// If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  1475  	if receipt.ContractAddress != (common.Address{}) {
  1476  		fields["contractAddress"] = receipt.ContractAddress
  1477  	}
  1478  	return fields, nil
  1479  }
  1480  
  1481  // Quorum: if signing a private TX, set with tx.SetPrivate() before calling this method.
  1482  // sign is a helper function that signs a transaction with the private key of the given address.
  1483  func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
  1484  	// Look up the wallet containing the requested signer
  1485  	account := accounts.Account{Address: addr}
  1486  
  1487  	wallet, err := s.b.AccountManager().Find(account)
  1488  	if err != nil {
  1489  		return nil, err
  1490  	}
  1491  
  1492  	// Quorum
  1493  	var chainID *big.Int
  1494  	if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) && !tx.IsPrivate() {
  1495  		chainID = config.ChainID
  1496  	}
  1497  	// /Quorum
  1498  
  1499  	// Request the wallet to sign the transaction
  1500  	return wallet.SignTx(account, tx, chainID)
  1501  }
  1502  
  1503  // SendTxArgs represents the arguments to sumbit a new transaction into the transaction pool.
  1504  // Quorum: introducing additional arguments encapsulated in PrivateTxArgs struct
  1505  //		   to support private transactions processing.
  1506  type SendTxArgs struct {
  1507  	PrivateTxArgs // Quorum
  1508  
  1509  	From     common.Address  `json:"from"`
  1510  	To       *common.Address `json:"to"`
  1511  	Gas      *hexutil.Uint64 `json:"gas"`
  1512  	GasPrice *hexutil.Big    `json:"gasPrice"`
  1513  	Value    *hexutil.Big    `json:"value"`
  1514  	Nonce    *hexutil.Uint64 `json:"nonce"`
  1515  	// We accept "data" and "input" for backwards-compatibility reasons. "input" is the
  1516  	// newer name and should be preferred by clients.
  1517  	Data  *hexutil.Bytes `json:"data"`
  1518  	Input *hexutil.Bytes `json:"input"`
  1519  }
  1520  
  1521  func (s SendTxArgs) IsPrivate() bool {
  1522  	return s.PrivateFor != nil
  1523  }
  1524  
  1525  // SendRawTxArgs represents the arguments to submit a new signed private transaction into the transaction pool.
  1526  type SendRawTxArgs struct {
  1527  	PrivateTxArgs
  1528  }
  1529  
  1530  // Additional arguments used in private transactions
  1531  type PrivateTxArgs struct {
  1532  	// PrivateFrom is the public key of the sending party.
  1533  	// The public key must be available in the Private Transaction Manager (i.e.: Tessera) which is paired with this geth node.
  1534  	// Empty value means the Private Transaction Manager will use the first public key
  1535  	// in its list of available keys which it maintains.
  1536  	PrivateFrom string `json:"privateFrom"`
  1537  	// PrivateFor is the list of public keys which are available in the Private Transaction Managers in the network.
  1538  	// The transaction payload is only visible to those party to the transaction.
  1539  	PrivateFor    []string               `json:"privateFor"`
  1540  	PrivateTxType string                 `json:"restriction"`
  1541  	PrivacyFlag   engine.PrivacyFlagType `json:"privacyFlag"`
  1542  }
  1543  
  1544  // setDefaults is a helper function that fills in default values for unspecified tx fields.
  1545  func (args *SendTxArgs) setDefaults(ctx context.Context, b Backend) error {
  1546  	if args.GasPrice == nil {
  1547  		price, err := b.SuggestPrice(ctx)
  1548  		if err != nil {
  1549  			return err
  1550  		}
  1551  		args.GasPrice = (*hexutil.Big)(price)
  1552  	}
  1553  	if args.Value == nil {
  1554  		args.Value = new(hexutil.Big)
  1555  	}
  1556  	if args.Nonce == nil {
  1557  		nonce, err := b.GetPoolNonce(ctx, args.From)
  1558  		if err != nil {
  1559  			return err
  1560  		}
  1561  		args.Nonce = (*hexutil.Uint64)(&nonce)
  1562  	}
  1563  	if args.Data != nil && args.Input != nil && !bytes.Equal(*args.Data, *args.Input) {
  1564  		return errors.New(`Both "data" and "input" are set and not equal. Please use "input" to pass transaction call data.`)
  1565  	}
  1566  	if args.To == nil {
  1567  		// Contract creation
  1568  		var input []byte
  1569  		if args.Data != nil {
  1570  			input = *args.Data
  1571  		} else if args.Input != nil {
  1572  			input = *args.Input
  1573  		}
  1574  		if len(input) == 0 {
  1575  			return errors.New(`contract creation without any data provided`)
  1576  		}
  1577  	}
  1578  	// Estimate the gas usage if necessary.
  1579  	if args.Gas == nil {
  1580  		// For backwards-compatibility reason, we try both input and data
  1581  		// but input is preferred.
  1582  		input := args.Input
  1583  		if input == nil {
  1584  			input = args.Data
  1585  		}
  1586  		callArgs := CallArgs{
  1587  			From:     &args.From, // From shouldn't be nil
  1588  			To:       args.To,
  1589  			GasPrice: args.GasPrice,
  1590  			Value:    args.Value,
  1591  			Data:     input,
  1592  		}
  1593  		pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
  1594  		estimated, err := DoEstimateGas(ctx, b, callArgs, pendingBlockNr, b.RPCGasCap())
  1595  		if err != nil {
  1596  			return err
  1597  		}
  1598  		args.Gas = &estimated
  1599  		log.Trace("Estimate gas usage automatically", "gas", args.Gas)
  1600  	}
  1601  	//Quorum
  1602  	if args.PrivateTxType == "" {
  1603  		args.PrivateTxType = "restricted"
  1604  	}
  1605  	//End-Quorum
  1606  	return nil
  1607  }
  1608  
  1609  func (args *SendTxArgs) inputOrData() (result []byte) {
  1610  	// TODO - check if input (instead of data) is provided whether private transactions are successful
  1611  	if args.Input != nil {
  1612  		result = *args.Input
  1613  	} else if args.Data != nil {
  1614  		result = *args.Data
  1615  	}
  1616  	return result
  1617  }
  1618  
  1619  func (args *SendTxArgs) toTransaction() *types.Transaction {
  1620  	if args.To == nil {
  1621  		return types.NewContractCreation(uint64(*args.Nonce), (*big.Int)(args.Value), uint64(*args.Gas), (*big.Int)(args.GasPrice), args.inputOrData())
  1622  	}
  1623  	return types.NewTransaction(uint64(*args.Nonce), *args.To, (*big.Int)(args.Value), uint64(*args.Gas), (*big.Int)(args.GasPrice), args.inputOrData())
  1624  }
  1625  
  1626  // TODO: this submits a signed transaction, if it is a signed private transaction that should already be recorded in the tx.
  1627  // SubmitTransaction is a helper function that submits tx to txPool and logs a message.
  1628  func SubmitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (common.Hash, error) {
  1629  	if err := b.SendTx(ctx, tx); err != nil {
  1630  		return common.Hash{}, err
  1631  	}
  1632  	if tx.To() == nil {
  1633  		var signer types.Signer
  1634  		if tx.IsPrivate() {
  1635  			signer = types.QuorumPrivateTxSigner{}
  1636  		} else {
  1637  			signer = types.MakeSigner(b.ChainConfig(), b.CurrentBlock().Number())
  1638  		}
  1639  		from, err := types.Sender(signer, tx)
  1640  		if err != nil {
  1641  			return common.Hash{}, err
  1642  		}
  1643  		addr := crypto.CreateAddress(from, tx.Nonce())
  1644  		log.Info("Submitted contract creation", "fullhash", tx.Hash().Hex(), "to", addr.Hex())
  1645  		log.EmitCheckpoint(log.TxCreated, "tx", tx.Hash().Hex(), "to", addr.Hex())
  1646  	} else {
  1647  		log.Info("Submitted transaction", "fullhash", tx.Hash().Hex(), "recipient", tx.To())
  1648  		log.EmitCheckpoint(log.TxCreated, "tx", tx.Hash().Hex(), "to", tx.To().Hex())
  1649  	}
  1650  	return tx.Hash(), nil
  1651  }
  1652  
  1653  // SendTransaction creates a transaction for the given argument, sign it and submit it to the
  1654  // transaction pool.
  1655  func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error) {
  1656  	// Look up the wallet containing the requested signer
  1657  	account := accounts.Account{Address: args.From}
  1658  
  1659  	wallet, err := s.b.AccountManager().Find(account)
  1660  	if err != nil {
  1661  		return common.Hash{}, err
  1662  	}
  1663  
  1664  	if args.Nonce == nil {
  1665  		// Hold the addresse's mutex around signing to prevent concurrent assignment of
  1666  		// the same nonce to multiple accounts.
  1667  		s.nonceLock.LockAddr(args.From)
  1668  		defer s.nonceLock.UnlockAddr(args.From)
  1669  	}
  1670  
  1671  	// Set some sanity defaults and terminate on failure
  1672  	if err := args.setDefaults(ctx, s.b); err != nil {
  1673  		return common.Hash{}, err
  1674  	}
  1675  
  1676  	// Quorum
  1677  	isPrivate, data, err := checkAndHandlePrivateTransaction(ctx, s.b, args.toTransaction(), &args.PrivateTxArgs, args.From, NormalTransaction)
  1678  
  1679  	if err != nil {
  1680  		return common.Hash{}, err
  1681  	}
  1682  	if isPrivate && !common.EmptyEncryptedPayloadHash(data) {
  1683  		// replace the original payload with encrypted payload hash
  1684  		args.Data = data.BytesTypeRef()
  1685  	}
  1686  	// /Quorum
  1687  
  1688  	// Assemble the transaction and sign with the wallet
  1689  	tx := args.toTransaction()
  1690  
  1691  	// Quorum
  1692  	if args.IsPrivate() {
  1693  		tx.SetPrivate()
  1694  	}
  1695  	// /Quorum
  1696  
  1697  	var chainID *big.Int
  1698  	if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) && !tx.IsPrivate() {
  1699  		chainID = config.ChainID
  1700  	}
  1701  	// /Quorum
  1702  
  1703  	signed, err := wallet.SignTx(account, tx, chainID)
  1704  	if err != nil {
  1705  		return common.Hash{}, err
  1706  	}
  1707  	return SubmitTransaction(ctx, s.b, signed)
  1708  }
  1709  
  1710  // FillTransaction fills the defaults (nonce, gas, gasPrice) on a given unsigned transaction,
  1711  // and returns it to the caller for further processing (signing + broadcast)
  1712  func (s *PublicTransactionPoolAPI) FillTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) {
  1713  	// Set some sanity defaults and terminate on failure
  1714  	if err := args.setDefaults(ctx, s.b); err != nil {
  1715  		return nil, err
  1716  	}
  1717  	// Assemble the transaction and obtain rlp
  1718  	// Quorum
  1719  	isPrivate, hash, err := checkAndHandlePrivateTransaction(ctx, s.b, args.toTransaction(), &args.PrivateTxArgs, args.From, FillTransaction)
  1720  	if err != nil {
  1721  		return nil, err
  1722  	}
  1723  	if isPrivate && !common.EmptyEncryptedPayloadHash(hash) {
  1724  		// replace the original payload with encrypted payload hash
  1725  		args.Data = hash.BytesTypeRef()
  1726  	}
  1727  	// /Quorum
  1728  
  1729  	tx := args.toTransaction()
  1730  
  1731  	// Quorum
  1732  	if isPrivate {
  1733  		tx.SetPrivate()
  1734  	}
  1735  	// /Quorum
  1736  
  1737  	data, err := rlp.EncodeToBytes(tx)
  1738  	if err != nil {
  1739  		return nil, err
  1740  	}
  1741  	return &SignTransactionResult{data, tx}, nil
  1742  }
  1743  
  1744  // SendRawTransaction will add the signed transaction to the transaction pool.
  1745  // The sender is responsible for signing the transaction and using the correct nonce.
  1746  func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, encodedTx hexutil.Bytes) (common.Hash, error) {
  1747  	tx := new(types.Transaction)
  1748  	if err := rlp.DecodeBytes(encodedTx, tx); err != nil {
  1749  		return common.Hash{}, err
  1750  	}
  1751  	return SubmitTransaction(ctx, s.b, tx)
  1752  }
  1753  
  1754  // SendRawPrivateTransaction will add the signed transaction to the transaction pool.
  1755  // The sender is responsible for signing the transaction and using the correct nonce.
  1756  func (s *PublicTransactionPoolAPI) SendRawPrivateTransaction(ctx context.Context, encodedTx hexutil.Bytes, args SendRawTxArgs) (common.Hash, error) {
  1757  
  1758  	tx := new(types.Transaction)
  1759  	if err := rlp.DecodeBytes(encodedTx, tx); err != nil {
  1760  		return common.Hash{}, err
  1761  	}
  1762  
  1763  	// Quorum
  1764  	isPrivate, _, err := checkAndHandlePrivateTransaction(ctx, s.b, tx, &args.PrivateTxArgs, common.Address{}, RawTransaction)
  1765  	if err != nil {
  1766  		return common.Hash{}, err
  1767  	}
  1768  
  1769  	if !isPrivate {
  1770  		return common.Hash{}, fmt.Errorf("transaction is not private")
  1771  	}
  1772  	// /Quorum
  1773  	return SubmitTransaction(ctx, s.b, tx)
  1774  }
  1775  
  1776  // Sign calculates an ECDSA signature for:
  1777  // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message).
  1778  //
  1779  // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  1780  // where the V value will be 27 or 28 for legacy reasons.
  1781  //
  1782  // The account associated with addr must be unlocked.
  1783  //
  1784  // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
  1785  func (s *PublicTransactionPoolAPI) Sign(addr common.Address, data hexutil.Bytes) (hexutil.Bytes, error) {
  1786  	// Look up the wallet containing the requested signer
  1787  	account := accounts.Account{Address: addr}
  1788  
  1789  	wallet, err := s.b.AccountManager().Find(account)
  1790  	if err != nil {
  1791  		return nil, err
  1792  	}
  1793  	// Sign the requested hash with the wallet
  1794  	signature, err := wallet.SignText(account, data)
  1795  	if err == nil {
  1796  		signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  1797  	}
  1798  	return signature, err
  1799  }
  1800  
  1801  // SignTransactionResult represents a RLP encoded signed transaction.
  1802  type SignTransactionResult struct {
  1803  	Raw hexutil.Bytes      `json:"raw"`
  1804  	Tx  *types.Transaction `json:"tx"`
  1805  }
  1806  
  1807  // SignTransaction will sign the given transaction with the from account.
  1808  // The node needs to have the private key of the account corresponding with
  1809  // the given from address and it needs to be unlocked.
  1810  func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) {
  1811  	if args.Gas == nil {
  1812  		return nil, fmt.Errorf("gas not specified")
  1813  	}
  1814  	if args.GasPrice == nil {
  1815  		return nil, fmt.Errorf("gasPrice not specified")
  1816  	}
  1817  	if args.Nonce == nil {
  1818  		return nil, fmt.Errorf("nonce not specified")
  1819  	}
  1820  	// Quorum
  1821  	// setDefaults calls DoEstimateGas in ethereum1.9.0, private transaction is not supported for that feature
  1822  	// set gas to constant if nil
  1823  	if args.IsPrivate() && args.Gas == nil {
  1824  		gas := (hexutil.Uint64)(90000)
  1825  		args.Gas = &gas
  1826  	}
  1827  	// /Quorum
  1828  	if err := args.setDefaults(ctx, s.b); err != nil {
  1829  		return nil, err
  1830  	}
  1831  	// Quorum
  1832  	toSign := args.toTransaction()
  1833  
  1834  	if args.IsPrivate() {
  1835  		toSign.SetPrivate()
  1836  	}
  1837  	// /Quorum
  1838  	tx, err := s.sign(args.From, toSign)
  1839  	if err != nil {
  1840  		return nil, err
  1841  	}
  1842  	data, err := rlp.EncodeToBytes(tx)
  1843  	if err != nil {
  1844  		return nil, err
  1845  	}
  1846  	return &SignTransactionResult{data, tx}, nil
  1847  }
  1848  
  1849  // PendingTransactions returns the transactions that are in the transaction pool
  1850  // and have a from address that is one of the accounts this node manages.
  1851  func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error) {
  1852  	pending, err := s.b.GetPoolTransactions()
  1853  	if err != nil {
  1854  		return nil, err
  1855  	}
  1856  	accounts := make(map[common.Address]struct{})
  1857  	for _, wallet := range s.b.AccountManager().Wallets() {
  1858  		for _, account := range wallet.Accounts() {
  1859  			accounts[account.Address] = struct{}{}
  1860  		}
  1861  	}
  1862  	transactions := make([]*RPCTransaction, 0, len(pending))
  1863  	for _, tx := range pending {
  1864  		var signer types.Signer = types.HomesteadSigner{}
  1865  		if tx.Protected() && !tx.IsPrivate() {
  1866  			signer = types.NewEIP155Signer(tx.ChainId())
  1867  		}
  1868  		from, _ := types.Sender(signer, tx)
  1869  		if _, exists := accounts[from]; exists {
  1870  			transactions = append(transactions, newRPCPendingTransaction(tx))
  1871  		}
  1872  	}
  1873  	return transactions, nil
  1874  }
  1875  
  1876  // Resend accepts an existing transaction and a new gas price and limit. It will remove
  1877  // the given transaction from the pool and reinsert it with the new gas price and limit.
  1878  func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs SendTxArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) {
  1879  	if sendArgs.Nonce == nil {
  1880  		return common.Hash{}, fmt.Errorf("missing transaction nonce in transaction spec")
  1881  	}
  1882  	// setDefaults calls DoEstimateGas in ethereum1.9.0, private transaction is not supported for that feature
  1883  	// set gas to constant if nil
  1884  	if sendArgs.IsPrivate() && sendArgs.Gas == nil {
  1885  		gas := (hexutil.Uint64)(90000)
  1886  		sendArgs.Gas = &gas
  1887  	}
  1888  	if err := sendArgs.setDefaults(ctx, s.b); err != nil {
  1889  		return common.Hash{}, err
  1890  	}
  1891  	matchTx := sendArgs.toTransaction()
  1892  	pending, err := s.b.GetPoolTransactions()
  1893  	if err != nil {
  1894  		return common.Hash{}, err
  1895  	}
  1896  
  1897  	for _, p := range pending {
  1898  		var signer types.Signer = types.HomesteadSigner{}
  1899  		if p.IsPrivate() {
  1900  			signer = types.QuorumPrivateTxSigner{}
  1901  		} else if p.Protected() {
  1902  			signer = types.NewEIP155Signer(p.ChainId())
  1903  		}
  1904  		wantSigHash := signer.Hash(matchTx)
  1905  
  1906  		if pFrom, err := types.Sender(signer, p); err == nil && pFrom == sendArgs.From && signer.Hash(p) == wantSigHash {
  1907  			// Match. Re-sign and send the transaction.
  1908  			if gasPrice != nil && (*big.Int)(gasPrice).Sign() != 0 {
  1909  				sendArgs.GasPrice = gasPrice
  1910  			}
  1911  			if gasLimit != nil && *gasLimit != 0 {
  1912  				sendArgs.Gas = gasLimit
  1913  			}
  1914  			newTx := sendArgs.toTransaction()
  1915  			// set v param to 37 to indicate private tx before submitting to the signer.
  1916  			if sendArgs.IsPrivate() {
  1917  				newTx.SetPrivate()
  1918  			}
  1919  			signedTx, err := s.sign(sendArgs.From, newTx)
  1920  			if err != nil {
  1921  				return common.Hash{}, err
  1922  			}
  1923  			if err = s.b.SendTx(ctx, signedTx); err != nil {
  1924  				return common.Hash{}, err
  1925  			}
  1926  			return signedTx.Hash(), nil
  1927  		}
  1928  	}
  1929  
  1930  	return common.Hash{}, fmt.Errorf("Transaction %#x not found", matchTx.Hash())
  1931  }
  1932  
  1933  // PublicDebugAPI is the collection of Ethereum APIs exposed over the public
  1934  // debugging endpoint.
  1935  type PublicDebugAPI struct {
  1936  	b Backend
  1937  }
  1938  
  1939  // NewPublicDebugAPI creates a new API definition for the public debug methods
  1940  // of the Ethereum service.
  1941  func NewPublicDebugAPI(b Backend) *PublicDebugAPI {
  1942  	return &PublicDebugAPI{b: b}
  1943  }
  1944  
  1945  // GetBlockRlp retrieves the RLP encoded for of a single block.
  1946  func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error) {
  1947  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1948  	if block == nil {
  1949  		return "", fmt.Errorf("block #%d not found", number)
  1950  	}
  1951  	encoded, err := rlp.EncodeToBytes(block)
  1952  	if err != nil {
  1953  		return "", err
  1954  	}
  1955  	return fmt.Sprintf("%x", encoded), nil
  1956  }
  1957  
  1958  // TestSignCliqueBlock fetches the given block number, and attempts to sign it as a clique header with the
  1959  // given address, returning the address of the recovered signature
  1960  //
  1961  // This is a temporary method to debug the externalsigner integration,
  1962  // TODO: Remove this method when the integration is mature
  1963  func (api *PublicDebugAPI) TestSignCliqueBlock(ctx context.Context, address common.Address, number uint64) (common.Address, error) {
  1964  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  1965  	if block == nil {
  1966  		return common.Address{}, fmt.Errorf("block #%d not found", number)
  1967  	}
  1968  	header := block.Header()
  1969  	header.Extra = make([]byte, 32+65)
  1970  	encoded := clique.CliqueRLP(header)
  1971  
  1972  	// Look up the wallet containing the requested signer
  1973  	account := accounts.Account{Address: address}
  1974  	wallet, err := api.b.AccountManager().Find(account)
  1975  	if err != nil {
  1976  		return common.Address{}, err
  1977  	}
  1978  
  1979  	signature, err := wallet.SignData(account, accounts.MimetypeClique, encoded)
  1980  	if err != nil {
  1981  		return common.Address{}, err
  1982  	}
  1983  	sealHash := clique.SealHash(header).Bytes()
  1984  	log.Info("test signing of clique block",
  1985  		"Sealhash", fmt.Sprintf("%x", sealHash),
  1986  		"signature", fmt.Sprintf("%x", signature))
  1987  	pubkey, err := crypto.Ecrecover(sealHash, signature)
  1988  	if err != nil {
  1989  		return common.Address{}, err
  1990  	}
  1991  	var signer common.Address
  1992  	copy(signer[:], crypto.Keccak256(pubkey[1:])[12:])
  1993  
  1994  	return signer, nil
  1995  }
  1996  
  1997  // PrintBlock retrieves a block and returns its pretty printed form.
  1998  func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) {
  1999  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  2000  	if block == nil {
  2001  		return "", fmt.Errorf("block #%d not found", number)
  2002  	}
  2003  	return spew.Sdump(block), nil
  2004  }
  2005  
  2006  // SeedHash retrieves the seed hash of a block.
  2007  func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) {
  2008  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  2009  	if block == nil {
  2010  		return "", fmt.Errorf("block #%d not found", number)
  2011  	}
  2012  	return fmt.Sprintf("0x%x", ethash.SeedHash(number)), nil
  2013  }
  2014  
  2015  // PrivateDebugAPI is the collection of Ethereum APIs exposed over the private
  2016  // debugging endpoint.
  2017  type PrivateDebugAPI struct {
  2018  	b Backend
  2019  }
  2020  
  2021  // NewPrivateDebugAPI creates a new API definition for the private debug methods
  2022  // of the Ethereum service.
  2023  func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI {
  2024  	return &PrivateDebugAPI{b: b}
  2025  }
  2026  
  2027  // ChaindbProperty returns leveldb properties of the key-value database.
  2028  func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) {
  2029  	if property == "" {
  2030  		property = "leveldb.stats"
  2031  	} else if !strings.HasPrefix(property, "leveldb.") {
  2032  		property = "leveldb." + property
  2033  	}
  2034  	return api.b.ChainDb().Stat(property)
  2035  }
  2036  
  2037  // ChaindbCompact flattens the entire key-value database into a single level,
  2038  // removing all unused slots and merging all keys.
  2039  func (api *PrivateDebugAPI) ChaindbCompact() error {
  2040  	for b := byte(0); b < 255; b++ {
  2041  		log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1))
  2042  		if err := api.b.ChainDb().Compact([]byte{b}, []byte{b + 1}); err != nil {
  2043  			log.Error("Database compaction failed", "err", err)
  2044  			return err
  2045  		}
  2046  	}
  2047  	return nil
  2048  }
  2049  
  2050  // SetHead rewinds the head of the blockchain to a previous block.
  2051  func (api *PrivateDebugAPI) SetHead(number hexutil.Uint64) {
  2052  	api.b.SetHead(uint64(number))
  2053  }
  2054  
  2055  // PublicNetAPI offers network related RPC methods
  2056  type PublicNetAPI struct {
  2057  	net            *p2p.Server
  2058  	networkVersion uint64
  2059  }
  2060  
  2061  // NewPublicNetAPI creates a new net API instance.
  2062  func NewPublicNetAPI(net *p2p.Server, networkVersion uint64) *PublicNetAPI {
  2063  	return &PublicNetAPI{net, networkVersion}
  2064  }
  2065  
  2066  // Listening returns an indication if the node is listening for network connections.
  2067  func (s *PublicNetAPI) Listening() bool {
  2068  	return true // always listening
  2069  }
  2070  
  2071  // PeerCount returns the number of connected peers
  2072  func (s *PublicNetAPI) PeerCount() hexutil.Uint {
  2073  	return hexutil.Uint(s.net.PeerCount())
  2074  }
  2075  
  2076  // Version returns the current ethereum protocol version.
  2077  func (s *PublicNetAPI) Version() string {
  2078  	return fmt.Sprintf("%d", s.networkVersion)
  2079  }
  2080  
  2081  // Quorum
  2082  // Please note: This is a temporary integration to improve performance in high-latency
  2083  // environments when sending many private transactions. It will be removed at a later
  2084  // date when account management is handled outside Ethereum.
  2085  
  2086  type AsyncSendTxArgs struct {
  2087  	SendTxArgs
  2088  	CallbackUrl string `json:"callbackUrl"`
  2089  }
  2090  
  2091  type AsyncResultSuccess struct {
  2092  	Id     string      `json:"id,omitempty"`
  2093  	TxHash common.Hash `json:"txHash"`
  2094  }
  2095  
  2096  type AsyncResultFailure struct {
  2097  	Id    string `json:"id,omitempty"`
  2098  	Error string `json:"error"`
  2099  }
  2100  
  2101  type Async struct {
  2102  	sync.Mutex
  2103  	sem chan struct{}
  2104  }
  2105  
  2106  func (s *PublicTransactionPoolAPI) send(ctx context.Context, asyncArgs AsyncSendTxArgs) {
  2107  
  2108  	txHash, err := s.SendTransaction(ctx, asyncArgs.SendTxArgs)
  2109  
  2110  	if asyncArgs.CallbackUrl != "" {
  2111  
  2112  		//don't need to nil check this since id is required for every geth rpc call
  2113  		//even though this is stated in the specification as an "optional" parameter
  2114  		jsonId := ctx.Value("id").(*json.RawMessage)
  2115  		id := string(*jsonId)
  2116  
  2117  		var resultResponse interface{}
  2118  		if err != nil {
  2119  			resultResponse = &AsyncResultFailure{Id: id, Error: err.Error()}
  2120  		} else {
  2121  			resultResponse = &AsyncResultSuccess{Id: id, TxHash: txHash}
  2122  		}
  2123  
  2124  		buf := new(bytes.Buffer)
  2125  		err := json.NewEncoder(buf).Encode(resultResponse)
  2126  		if err != nil {
  2127  			log.Info("Error encoding callback JSON", "err", err.Error())
  2128  			return
  2129  		}
  2130  		_, err = http.Post(asyncArgs.CallbackUrl, "application/json", buf)
  2131  		if err != nil {
  2132  			log.Info("Error sending callback", "err", err.Error())
  2133  			return
  2134  		}
  2135  	}
  2136  
  2137  }
  2138  
  2139  func newAsync(n int) *Async {
  2140  	a := &Async{
  2141  		sem: make(chan struct{}, n),
  2142  	}
  2143  	return a
  2144  }
  2145  
  2146  var async = newAsync(100)
  2147  
  2148  // SendTransactionAsync creates a transaction for the given argument, signs it, and
  2149  // submits it to the transaction pool. This call returns immediately to allow sending
  2150  // many private transactions/bursts of transactions without waiting for the recipient
  2151  // parties to confirm receipt of the encrypted payloads. An optional callbackUrl may
  2152  // be specified--when a transaction is submitted to the transaction pool, it will be
  2153  // called with a POST request containing either {"error": "error message"} or
  2154  // {"txHash": "0x..."}.
  2155  //
  2156  // Please note: This is a temporary integration to improve performance in high-latency
  2157  // environments when sending many private transactions. It will be removed at a later
  2158  // date when account management is handled outside Ethereum.
  2159  func (s *PublicTransactionPoolAPI) SendTransactionAsync(ctx context.Context, args AsyncSendTxArgs) (common.Hash, error) {
  2160  
  2161  	select {
  2162  	case async.sem <- struct{}{}:
  2163  		go func() {
  2164  			s.send(ctx, args)
  2165  			<-async.sem
  2166  		}()
  2167  		return common.Hash{}, nil
  2168  	default:
  2169  		return common.Hash{}, errors.New("too many concurrent requests")
  2170  	}
  2171  }
  2172  
  2173  // GetQuorumPayload returns the contents of a private transaction
  2174  func (s *PublicBlockChainAPI) GetQuorumPayload(digestHex string) (string, error) {
  2175  	if private.P == nil {
  2176  		return "", fmt.Errorf("PrivateTransactionManager is not enabled")
  2177  	}
  2178  	if len(digestHex) < 3 {
  2179  		return "", fmt.Errorf("Invalid digest hex")
  2180  	}
  2181  	if digestHex[:2] == "0x" {
  2182  		digestHex = digestHex[2:]
  2183  	}
  2184  	b, err := hex.DecodeString(digestHex)
  2185  	if err != nil {
  2186  		return "", err
  2187  	}
  2188  	if len(b) != common.EncryptedPayloadHashLength {
  2189  		return "", fmt.Errorf("Expected a Quorum digest of length 64, but got %d", len(b))
  2190  	}
  2191  	data, _, err := private.P.Receive(common.BytesToEncryptedPayloadHash(b))
  2192  	if err != nil {
  2193  		return "", err
  2194  	}
  2195  	return fmt.Sprintf("0x%x", data), nil
  2196  }
  2197  
  2198  func checkAndHandlePrivateTransaction(ctx context.Context, b Backend, tx *types.Transaction, privateTxArgs *PrivateTxArgs, from common.Address, txnType TransactionType) (isPrivate bool, hash common.EncryptedPayloadHash, err error) {
  2199  	isPrivate = privateTxArgs != nil && privateTxArgs.PrivateFor != nil
  2200  	if !isPrivate {
  2201  		return
  2202  	}
  2203  
  2204  	if err = privateTxArgs.PrivacyFlag.Validate(); err != nil {
  2205  		return
  2206  	}
  2207  
  2208  	if !b.ChainConfig().IsPrivacyEnhancementsEnabled(b.CurrentBlock().Number()) && privateTxArgs.PrivacyFlag.IsNotStandardPrivate() {
  2209  		err = fmt.Errorf("PrivacyEnhancements are disabled. Can only accept transactions with PrivacyFlag=0(StandardPrivate).")
  2210  		return
  2211  	}
  2212  
  2213  	if len(tx.Data()) > 0 {
  2214  		// check private contract exists on the node initiating the transaction
  2215  		if tx.To() != nil && privateTxArgs.PrivacyFlag.IsNotStandardPrivate() {
  2216  			state, _, lerr := b.StateAndHeaderByNumber(ctx, rpc.BlockNumber(b.CurrentBlock().Number().Uint64()))
  2217  			if lerr != nil && state == nil {
  2218  				err = fmt.Errorf("state not found")
  2219  				return
  2220  			}
  2221  			if state.GetCode(*tx.To()) == nil {
  2222  				err = fmt.Errorf("contract not found. cannot transact")
  2223  				return
  2224  			}
  2225  		}
  2226  
  2227  		hash, err = handlePrivateTransaction(ctx, b, tx, privateTxArgs, from, txnType)
  2228  
  2229  		return
  2230  	}
  2231  
  2232  	return
  2233  }
  2234  
  2235  // If transaction is raw, the tx payload is indeed the hash of the encrypted payload
  2236  //
  2237  // For private transaction, run a simulated execution in order to
  2238  // 1. Find all affected private contract accounts then retrieve encrypted payload hashes of their creation txs
  2239  // 2. Calculate Merkle Root as the result of the simulated execution
  2240  // The above information along with private originating payload are sent to Transaction Manager
  2241  // to obtain hash of the encrypted private payload
  2242  func handlePrivateTransaction(ctx context.Context, b Backend, tx *types.Transaction, privateTxArgs *PrivateTxArgs, from common.Address, txnType TransactionType) (hash common.EncryptedPayloadHash, err error) {
  2243  	defer func(start time.Time) {
  2244  		log.Debug("Handle Private Transaction finished", "took", time.Since(start))
  2245  	}(time.Now())
  2246  
  2247  	data := tx.Data()
  2248  
  2249  	var affectedCATxHashes common.EncryptedPayloadHashes // of affected contract accounts
  2250  	var merkleRoot common.Hash
  2251  	log.Debug("sending private tx", "txnType", txnType, "data", common.FormatTerminalString(data), "privatefrom", privateTxArgs.PrivateFrom, "privatefor", privateTxArgs.PrivateFor, "privacyFlag", privateTxArgs.PrivacyFlag)
  2252  
  2253  	switch txnType {
  2254  	case FillTransaction:
  2255  		hash, err = private.P.StoreRaw(data, privateTxArgs.PrivateFrom)
  2256  		return
  2257  	case RawTransaction:
  2258  		hash = common.BytesToEncryptedPayloadHash(data)
  2259  		privatePayload, _, revErr := private.P.ReceiveRaw(hash)
  2260  		if revErr != nil {
  2261  			return common.EncryptedPayloadHash{}, revErr
  2262  		}
  2263  		log.Trace("received raw payload", "hash", hash, "privatepayload", common.FormatTerminalString(privatePayload))
  2264  		var privateTx *types.Transaction
  2265  		if tx.To() == nil {
  2266  			privateTx = types.NewContractCreation(tx.Nonce(), tx.Value(), tx.Gas(), tx.GasPrice(), privatePayload)
  2267  		} else {
  2268  			privateTx = types.NewTransaction(tx.Nonce(), *tx.To(), tx.Value(), tx.Gas(), tx.GasPrice(), privatePayload)
  2269  		}
  2270  		affectedCATxHashes, merkleRoot, err = simulateExecution(ctx, b, from, privateTx, privateTxArgs)
  2271  		log.Trace("after simulation", "affectedCATxHashes", affectedCATxHashes, "merkleRoot", merkleRoot, "privacyFlag", privateTxArgs.PrivacyFlag, "error", err)
  2272  		if err != nil {
  2273  			return
  2274  		}
  2275  
  2276  		data, err = private.P.SendSignedTx(hash, privateTxArgs.PrivateFor, &engine.ExtraMetadata{
  2277  			ACHashes:     affectedCATxHashes,
  2278  			ACMerkleRoot: merkleRoot,
  2279  			PrivacyFlag:  privateTxArgs.PrivacyFlag,
  2280  		})
  2281  		if err != nil {
  2282  			return
  2283  		}
  2284  
  2285  	case NormalTransaction:
  2286  		affectedCATxHashes, merkleRoot, err = simulateExecution(ctx, b, from, tx, privateTxArgs)
  2287  		log.Trace("after simulation", "affectedCATxHashes", affectedCATxHashes, "merkleRoot", merkleRoot, "privacyFlag", privateTxArgs.PrivacyFlag, "error", err)
  2288  		if err != nil {
  2289  			return
  2290  		}
  2291  
  2292  		hash, err = private.P.Send(data, privateTxArgs.PrivateFrom, privateTxArgs.PrivateFor, &engine.ExtraMetadata{
  2293  			ACHashes:     affectedCATxHashes,
  2294  			ACMerkleRoot: merkleRoot,
  2295  			PrivacyFlag:  privateTxArgs.PrivacyFlag,
  2296  		})
  2297  		if err != nil {
  2298  			return
  2299  		}
  2300  	}
  2301  
  2302  	log.Info("sent private signed tx",
  2303  		"data", common.FormatTerminalString(data),
  2304  		"hash", hash,
  2305  		"privatefrom", privateTxArgs.PrivateFrom,
  2306  		"privatefor", privateTxArgs.PrivateFor,
  2307  		"affectedCATxHashes", affectedCATxHashes,
  2308  		"merkleroot", merkleRoot,
  2309  		"privacyflag", privateTxArgs.PrivacyFlag)
  2310  
  2311  	return
  2312  }
  2313  
  2314  // Simulate execution of a private transaction
  2315  // Returns hashes of encrypted payload of creation transactions for all affected contract accounts
  2316  // and the merkle root combining all affected contract accounts after the simulation
  2317  //
  2318  func simulateExecution(ctx context.Context, b Backend, from common.Address, privateTx *types.Transaction, privateTxArgs *PrivateTxArgs) (common.EncryptedPayloadHashes, common.Hash, error) {
  2319  	defer func(start time.Time) {
  2320  		log.Debug("Simulated Execution EVM call finished", "runtime", time.Since(start))
  2321  	}(time.Now())
  2322  
  2323  	// skip simulation if privacy enhancements are disabled
  2324  	if !b.ChainConfig().IsPrivacyEnhancementsEnabled(b.CurrentBlock().Number()) {
  2325  		return nil, common.Hash{}, nil
  2326  	}
  2327  
  2328  	// Set sender address or use a default if none specified
  2329  	addr := from
  2330  	if addr == (common.Address{}) {
  2331  		if wallets := b.AccountManager().Wallets(); len(wallets) > 0 {
  2332  			if accounts := wallets[0].Accounts(); len(accounts) > 0 {
  2333  				addr = accounts[0].Address
  2334  			}
  2335  		}
  2336  	}
  2337  
  2338  	// Create new call message
  2339  	msg := types.NewMessage(addr, privateTx.To(), privateTx.Nonce(), privateTx.Value(), privateTx.Gas(), privateTx.GasPrice(), privateTx.Data(), false)
  2340  
  2341  	// Setup context with timeout as gas un-metered
  2342  	var cancel context.CancelFunc
  2343  	ctx, cancel = context.WithTimeout(ctx, time.Second*5)
  2344  	// Make sure the context is cancelled when the call has completed
  2345  	// this makes sure resources are cleaned up.
  2346  	defer func() { cancel() }()
  2347  
  2348  	// Get a new instance of the EVM.
  2349  	blockNumber := b.CurrentBlock().Number().Uint64()
  2350  	state, header, err := b.StateAndHeaderByNumber(ctx, rpc.BlockNumber(blockNumber))
  2351  	if state == nil || err != nil {
  2352  		return nil, common.Hash{}, err
  2353  	}
  2354  	evm, _, err := b.GetEVM(ctx, msg, state, header)
  2355  	if err != nil {
  2356  		return nil, common.Hash{}, err
  2357  	}
  2358  
  2359  	// Wait for the context to be done and cancel the evm. Even if the
  2360  	// EVM has finished, cancelling may be done (repeatedly)
  2361  	go func() {
  2362  		<-ctx.Done()
  2363  		evm.Cancel()
  2364  	}()
  2365  
  2366  	var contractAddr common.Address
  2367  	// even the creation of a contract (init code) can invoke other contracts
  2368  	if privateTx.To() != nil {
  2369  		// removed contract availability checks as they are performed in checkAndHandlePrivateTransaction
  2370  		_, _, err = evm.Call(vm.AccountRef(addr), *privateTx.To(), privateTx.Data(), privateTx.Gas(), privateTx.Value())
  2371  	} else {
  2372  		_, contractAddr, _, err = evm.Create(vm.AccountRef(addr), privateTx.Data(), privateTx.Gas(), privateTx.Value())
  2373  		//make sure that nonce is same in simulation as in actual block processing
  2374  		//simulation blockNumber will be behind block processing blockNumber by at least 1
  2375  		//only guaranteed to work for default config where EIP158=1
  2376  		if evm.ChainConfig().IsEIP158(big.NewInt(evm.BlockNumber.Int64() + 1)) {
  2377  			evm.StateDB.SetNonce(contractAddr, 1)
  2378  		}
  2379  	}
  2380  
  2381  	if err != nil {
  2382  		if privateTxArgs.PrivacyFlag.IsStandardPrivate() {
  2383  			log.Debug("An error occurred during StandardPrivate transaction simulation. "+
  2384  				"Continuing to simulation checks.", "error", err)
  2385  		} else {
  2386  			log.Trace("Simulated execution", "error", err)
  2387  			return nil, common.Hash{}, err
  2388  		}
  2389  	}
  2390  	affectedContractsHashes := make(common.EncryptedPayloadHashes)
  2391  	var merkleRoot common.Hash
  2392  	addresses := evm.AffectedContracts()
  2393  	privacyFlag := privateTxArgs.PrivacyFlag
  2394  	log.Trace("after simulation run", "numberOfAffectedContracts", len(addresses), "privacyFlag", privacyFlag)
  2395  	for _, addr := range addresses {
  2396  		// GetStatePrivacyMetadata is invoked directly on the privateState (as the tx is private) and it returns:
  2397  		// 1. public contacts: privacyMetadata = nil, err = nil
  2398  		// 2. private contracts of type:
  2399  		// 2.1. StandardPrivate:     privacyMetadata = nil, err = "The provided contract does not have privacy metadata"
  2400  		// 2.2. PartyProtection/PSV: privacyMetadata = <data>, err = nil
  2401  		privacyMetadata, err := evm.StateDB.GetStatePrivacyMetadata(addr)
  2402  		log.Debug("Found affected contract", "address", addr.Hex(), "privacyMetadata", privacyMetadata)
  2403  		//privacyMetadata not found=non-party, or another db error
  2404  		if err != nil && privacyFlag.IsNotStandardPrivate() {
  2405  			return nil, common.Hash{}, errors.New("PrivacyMetadata not found: " + err.Error())
  2406  		}
  2407  		// when we run simulation, it's possible that affected contracts may contain public ones
  2408  		// public contract will not have any privacyMetadata attached
  2409  		// standard private will be nil
  2410  		if privacyMetadata == nil {
  2411  			continue
  2412  		}
  2413  		//if affecteds are not all the same return an error
  2414  		if privacyFlag != privacyMetadata.PrivacyFlag {
  2415  			return nil, common.Hash{}, errors.New("sent privacy flag doesn't match all affected contract flags")
  2416  		}
  2417  
  2418  		affectedContractsHashes.Add(privacyMetadata.CreationTxHash)
  2419  	}
  2420  	//only calculate the merkle root if all contracts are psv
  2421  	if privacyFlag.Has(engine.PrivacyFlagStateValidation) {
  2422  		merkleRoot, err = evm.CalculateMerkleRoot()
  2423  		if err != nil {
  2424  			return nil, common.Hash{}, err
  2425  		}
  2426  	}
  2427  	log.Trace("post-execution run", "merkleRoot", merkleRoot, "affectedhashes", affectedContractsHashes)
  2428  	return affectedContractsHashes, merkleRoot, nil
  2429  }
  2430  
  2431  //End-Quorum