github.com/kisexp/xdchain@v0.0.0-20211206025815-490d6b732aa7/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/kisexp/xdchain/accounts"
    34  	"github.com/kisexp/xdchain/accounts/abi"
    35  	"github.com/kisexp/xdchain/accounts/keystore"
    36  	"github.com/kisexp/xdchain/accounts/pluggable"
    37  	"github.com/kisexp/xdchain/accounts/scwallet"
    38  	"github.com/kisexp/xdchain/common"
    39  	"github.com/kisexp/xdchain/common/hexutil"
    40  	"github.com/kisexp/xdchain/common/math"
    41  	"github.com/kisexp/xdchain/consensus/clique"
    42  	"github.com/kisexp/xdchain/consensus/ethash"
    43  	"github.com/kisexp/xdchain/core"
    44  	"github.com/kisexp/xdchain/core/mps"
    45  	"github.com/kisexp/xdchain/core/state"
    46  	"github.com/kisexp/xdchain/core/types"
    47  	"github.com/kisexp/xdchain/core/vm"
    48  	"github.com/kisexp/xdchain/crypto"
    49  	"github.com/kisexp/xdchain/log"
    50  	"github.com/kisexp/xdchain/multitenancy"
    51  	"github.com/kisexp/xdchain/p2p"
    52  	"github.com/kisexp/xdchain/params"
    53  	"github.com/kisexp/xdchain/private"
    54  	"github.com/kisexp/xdchain/private/engine"
    55  	"github.com/kisexp/xdchain/rlp"
    56  	"github.com/kisexp/xdchain/rpc"
    57  	"github.com/tyler-smith/go-bip39"
    58  )
    59  
    60  type TransactionType uint8
    61  
    62  const (
    63  	FillTransaction TransactionType = iota + 1
    64  	RawTransaction
    65  	NormalTransaction
    66  )
    67  
    68  // PublicEthereumAPI provides an API to access Ethereum related information.
    69  // It offers only methods that operate on public data that is freely available to anyone.
    70  type PublicEthereumAPI struct {
    71  	b Backend
    72  }
    73  
    74  // NewPublicEthereumAPI creates a new Ethereum protocol API.
    75  func NewPublicEthereumAPI(b Backend) *PublicEthereumAPI {
    76  	return &PublicEthereumAPI{b}
    77  }
    78  
    79  // GasPrice returns a suggestion for a gas price.
    80  func (s *PublicEthereumAPI) GasPrice(ctx context.Context) (*hexutil.Big, error) {
    81  	price, err := s.b.SuggestPrice(ctx)
    82  	return (*hexutil.Big)(price), err
    83  }
    84  
    85  // ProtocolVersion returns the current Ethereum protocol version this node supports
    86  func (s *PublicEthereumAPI) ProtocolVersion() hexutil.Uint {
    87  	return hexutil.Uint(s.b.ProtocolVersion())
    88  }
    89  
    90  // Syncing returns false in case the node is currently not syncing with the network. It can be up to date or has not
    91  // yet received the latest block headers from its pears. In case it is synchronizing:
    92  // - startingBlock: block number this node started to synchronise from
    93  // - currentBlock:  block number this node is currently importing
    94  // - highestBlock:  block number of the highest block header this node has received from peers
    95  // - pulledStates:  number of state entries processed until now
    96  // - knownStates:   number of known state entries that still need to be pulled
    97  func (s *PublicEthereumAPI) Syncing() (interface{}, error) {
    98  	progress := s.b.Downloader().Progress()
    99  
   100  	// Return not syncing if the synchronisation already completed
   101  	if progress.CurrentBlock >= progress.HighestBlock {
   102  		return false, nil
   103  	}
   104  	// Otherwise gather the block sync stats
   105  	return map[string]interface{}{
   106  		"startingBlock": hexutil.Uint64(progress.StartingBlock),
   107  		"currentBlock":  hexutil.Uint64(progress.CurrentBlock),
   108  		"highestBlock":  hexutil.Uint64(progress.HighestBlock),
   109  		"pulledStates":  hexutil.Uint64(progress.PulledStates),
   110  		"knownStates":   hexutil.Uint64(progress.KnownStates),
   111  	}, nil
   112  }
   113  
   114  func (s *PublicEthereumAPI) GetPrivacyPrecompileAddress() common.Address {
   115  	return common.QuorumPrivacyPrecompileContractAddress()
   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  	_, replaceDataWithHash, 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 replaceDataWithHash {
   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  
   474  	// Quorum
   475  	if signed.IsPrivate() && s.b.IsPrivacyMarkerTransactionCreationEnabled() {
   476  		// Look up the wallet containing the requested signer
   477  		account := accounts.Account{Address: args.From}
   478  		wallet, err := s.am.Find(account)
   479  		if err != nil {
   480  			return common.Hash{}, err
   481  		}
   482  
   483  		pmt, err := createPrivacyMarkerTransaction(s.b, signed, &args.PrivateTxArgs)
   484  		if err != nil {
   485  			log.Warn("Failed to create privacy marker transaction for private transaction", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err)
   486  			return common.Hash{}, err
   487  		}
   488  
   489  		var pmtChainID *big.Int // PMT is public so will have different chainID used in signing compared to the internal tx
   490  		if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) {
   491  			pmtChainID = config.ChainID
   492  		}
   493  
   494  		signed, err = wallet.SignTxWithPassphrase(account, passwd, pmt, pmtChainID)
   495  		if err != nil {
   496  			log.Warn("Failed to sign privacy marker transaction for private transaction", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err)
   497  			return common.Hash{}, err
   498  		}
   499  	}
   500  	// /Quorum
   501  
   502  	return SubmitTransaction(ctx, s.b, signed, args.PrivateFrom, false)
   503  }
   504  
   505  // SignTransaction will create a transaction from the given arguments and
   506  // tries to sign it with the key associated with args.To. If the given passwd isn't
   507  // able to decrypt the key it fails. The transaction is returned in RLP-form, not broadcast
   508  // to other nodes
   509  func (s *PrivateAccountAPI) SignTransaction(ctx context.Context, args SendTxArgs, passwd string) (*SignTransactionResult, error) {
   510  	// No need to obtain the noncelock mutex, since we won't be sending this
   511  	// tx into the transaction pool, but right back to the user
   512  	if args.Gas == nil {
   513  		return nil, fmt.Errorf("gas not specified")
   514  	}
   515  	if args.GasPrice == nil {
   516  		return nil, fmt.Errorf("gasPrice not specified")
   517  	}
   518  	if args.Nonce == nil {
   519  		return nil, fmt.Errorf("nonce not specified")
   520  	}
   521  	// Before actually sign the transaction, ensure the transaction fee is reasonable.
   522  	if err := checkTxFee(args.GasPrice.ToInt(), uint64(*args.Gas), s.b.RPCTxFeeCap()); err != nil {
   523  		return nil, err
   524  	}
   525  	signed, err := s.signTransaction(ctx, &args, passwd)
   526  	if err != nil {
   527  		log.Warn("Failed transaction sign attempt", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err)
   528  		return nil, err
   529  	}
   530  	data, err := rlp.EncodeToBytes(signed)
   531  	if err != nil {
   532  		return nil, err
   533  	}
   534  	return &SignTransactionResult{data, signed}, nil
   535  }
   536  
   537  // Sign calculates an Ethereum ECDSA signature for:
   538  // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message))
   539  //
   540  // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
   541  // where the V value will be 27 or 28 for legacy reasons.
   542  //
   543  // The key used to calculate the signature is decrypted with the given password.
   544  //
   545  // https://github.com/kisexp/xdchain/wiki/Management-APIs#personal_sign
   546  func (s *PrivateAccountAPI) Sign(ctx context.Context, data hexutil.Bytes, addr common.Address, passwd string) (hexutil.Bytes, error) {
   547  	// Look up the wallet containing the requested signer
   548  	account := accounts.Account{Address: addr}
   549  
   550  	wallet, err := s.b.AccountManager().Find(account)
   551  	if err != nil {
   552  		return nil, err
   553  	}
   554  	// Assemble sign the data with the wallet
   555  	signature, err := wallet.SignTextWithPassphrase(account, passwd, data)
   556  	if err != nil {
   557  		log.Warn("Failed data sign attempt", "address", addr, "err", err)
   558  		return nil, err
   559  	}
   560  	signature[crypto.RecoveryIDOffset] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
   561  	return signature, nil
   562  }
   563  
   564  // EcRecover returns the address for the account that was used to create the signature.
   565  // Note, this function is compatible with eth_sign and personal_sign. As such it recovers
   566  // the address of:
   567  // hash = keccak256("\x19Ethereum Signed Message:\n"${message length}${message})
   568  // addr = ecrecover(hash, signature)
   569  //
   570  // Note, the signature must conform to the secp256k1 curve R, S and V values, where
   571  // the V value must be 27 or 28 for legacy reasons.
   572  //
   573  // https://github.com/kisexp/xdchain/wiki/Management-APIs#personal_ecRecover
   574  func (s *PrivateAccountAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) {
   575  	if len(sig) != crypto.SignatureLength {
   576  		return common.Address{}, fmt.Errorf("signature must be %d bytes long", crypto.SignatureLength)
   577  	}
   578  	if sig[crypto.RecoveryIDOffset] != 27 && sig[crypto.RecoveryIDOffset] != 28 {
   579  		return common.Address{}, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)")
   580  	}
   581  	sig[crypto.RecoveryIDOffset] -= 27 // Transform yellow paper V from 27/28 to 0/1
   582  
   583  	rpk, err := crypto.SigToPub(accounts.TextHash(data), sig)
   584  	if err != nil {
   585  		return common.Address{}, err
   586  	}
   587  	return crypto.PubkeyToAddress(*rpk), nil
   588  }
   589  
   590  // SignAndSendTransaction was renamed to SendTransaction. This method is deprecated
   591  // and will be removed in the future. It primary goal is to give clients time to update.
   592  func (s *PrivateAccountAPI) SignAndSendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) {
   593  	return s.SendTransaction(ctx, args, passwd)
   594  }
   595  
   596  // InitializeWallet initializes a new wallet at the provided URL, by generating and returning a new private key.
   597  func (s *PrivateAccountAPI) InitializeWallet(ctx context.Context, url string) (string, error) {
   598  	wallet, err := s.am.Wallet(url)
   599  	if err != nil {
   600  		return "", err
   601  	}
   602  
   603  	entropy, err := bip39.NewEntropy(256)
   604  	if err != nil {
   605  		return "", err
   606  	}
   607  
   608  	mnemonic, err := bip39.NewMnemonic(entropy)
   609  	if err != nil {
   610  		return "", err
   611  	}
   612  
   613  	seed := bip39.NewSeed(mnemonic, "")
   614  
   615  	switch wallet := wallet.(type) {
   616  	case *scwallet.Wallet:
   617  		return mnemonic, wallet.Initialize(seed)
   618  	default:
   619  		return "", fmt.Errorf("specified wallet does not support initialization")
   620  	}
   621  }
   622  
   623  // Unpair deletes a pairing between wallet and geth.
   624  func (s *PrivateAccountAPI) Unpair(ctx context.Context, url string, pin string) error {
   625  	wallet, err := s.am.Wallet(url)
   626  	if err != nil {
   627  		return err
   628  	}
   629  
   630  	switch wallet := wallet.(type) {
   631  	case *scwallet.Wallet:
   632  		return wallet.Unpair([]byte(pin))
   633  	default:
   634  		return fmt.Errorf("specified wallet does not support pairing")
   635  	}
   636  }
   637  
   638  // PublicBlockChainAPI provides an API to access the Ethereum blockchain.
   639  // It offers only methods that operate on public data that is freely available to anyone.
   640  type PublicBlockChainAPI struct {
   641  	b Backend
   642  }
   643  
   644  // NewPublicBlockChainAPI creates a new Ethereum blockchain API.
   645  func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI {
   646  	return &PublicBlockChainAPI{b}
   647  }
   648  
   649  // ChainId returns the chainID value for transaction replay protection.
   650  func (s *PublicBlockChainAPI) ChainId() *hexutil.Big {
   651  	return (*hexutil.Big)(s.b.ChainConfig().ChainID)
   652  }
   653  
   654  // GetPSI - retunrs the PSI that was resolved based on the client request
   655  func (s *PublicBlockChainAPI) GetPSI(ctx context.Context) (string, error) {
   656  	psm, err := s.b.PSMR().ResolveForUserContext(ctx)
   657  	if err != nil {
   658  		return "", err
   659  	}
   660  	return psm.ID.String(), nil
   661  }
   662  
   663  // BlockNumber returns the block number of the chain head.
   664  func (s *PublicBlockChainAPI) BlockNumber() hexutil.Uint64 {
   665  	header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available
   666  	return hexutil.Uint64(header.Number.Uint64())
   667  }
   668  
   669  // GetBalance returns the amount of wei for the given address in the state of the
   670  // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta
   671  // block numbers are also allowed.
   672  func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Big, error) {
   673  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   674  	if state == nil || err != nil {
   675  		return nil, err
   676  	}
   677  	return (*hexutil.Big)(state.GetBalance(address)), state.Error()
   678  }
   679  
   680  // Result structs for GetProof
   681  type AccountResult struct {
   682  	Address      common.Address  `json:"address"`
   683  	AccountProof []string        `json:"accountProof"`
   684  	Balance      *hexutil.Big    `json:"balance"`
   685  	CodeHash     common.Hash     `json:"codeHash"`
   686  	Nonce        hexutil.Uint64  `json:"nonce"`
   687  	StorageHash  common.Hash     `json:"storageHash"`
   688  	StorageProof []StorageResult `json:"storageProof"`
   689  }
   690  type StorageResult struct {
   691  	Key   string       `json:"key"`
   692  	Value *hexutil.Big `json:"value"`
   693  	Proof []string     `json:"proof"`
   694  }
   695  
   696  // GetProof returns the Merkle-proof for a given account and optionally some storage keys.
   697  func (s *PublicBlockChainAPI) GetProof(ctx context.Context, address common.Address, storageKeys []string, blockNrOrHash rpc.BlockNumberOrHash) (*AccountResult, error) {
   698  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   699  	if state == nil || err != nil {
   700  		return nil, err
   701  	}
   702  
   703  	storageTrie := state.StorageTrie(address)
   704  	storageHash := types.EmptyRootHash
   705  	codeHash := state.GetCodeHash(address)
   706  	storageProof := make([]StorageResult, len(storageKeys))
   707  
   708  	// if we have a storageTrie, (which means the account exists), we can update the storagehash
   709  	if storageTrie != nil {
   710  		storageHash = storageTrie.Hash()
   711  	} else {
   712  		// no storageTrie means the account does not exist, so the codeHash is the hash of an empty bytearray.
   713  		codeHash = crypto.Keccak256Hash(nil)
   714  	}
   715  
   716  	// create the proof for the storageKeys
   717  	for i, key := range storageKeys {
   718  		if storageTrie != nil {
   719  			proof, storageError := state.GetStorageProof(address, common.HexToHash(key))
   720  			if storageError != nil {
   721  				return nil, storageError
   722  			}
   723  			storageProof[i] = StorageResult{key, (*hexutil.Big)(state.GetState(address, common.HexToHash(key)).Big()), toHexSlice(proof)}
   724  		} else {
   725  			storageProof[i] = StorageResult{key, &hexutil.Big{}, []string{}}
   726  		}
   727  	}
   728  
   729  	// create the accountProof
   730  	accountProof, proofErr := state.GetProof(address)
   731  	if proofErr != nil {
   732  		return nil, proofErr
   733  	}
   734  
   735  	return &AccountResult{
   736  		Address:      address,
   737  		AccountProof: toHexSlice(accountProof),
   738  		Balance:      (*hexutil.Big)(state.GetBalance(address)),
   739  		CodeHash:     codeHash,
   740  		Nonce:        hexutil.Uint64(state.GetNonce(address)),
   741  		StorageHash:  storageHash,
   742  		StorageProof: storageProof,
   743  	}, state.Error()
   744  }
   745  
   746  // GetHeaderByNumber returns the requested canonical block header.
   747  // * When blockNr is -1 the chain head is returned.
   748  // * When blockNr is -2 the pending chain head is returned.
   749  func (s *PublicBlockChainAPI) GetHeaderByNumber(ctx context.Context, number rpc.BlockNumber) (map[string]interface{}, error) {
   750  	header, err := s.b.HeaderByNumber(ctx, number)
   751  	if header != nil && err == nil {
   752  		response := s.rpcMarshalHeader(ctx, header)
   753  		if number == rpc.PendingBlockNumber {
   754  			// Pending header need to nil out a few fields
   755  			for _, field := range []string{"hash", "nonce", "miner"} {
   756  				response[field] = nil
   757  			}
   758  		}
   759  		return response, err
   760  	}
   761  	return nil, err
   762  }
   763  
   764  // GetHeaderByHash returns the requested header by hash.
   765  func (s *PublicBlockChainAPI) GetHeaderByHash(ctx context.Context, hash common.Hash) map[string]interface{} {
   766  	header, _ := s.b.HeaderByHash(ctx, hash)
   767  	if header != nil {
   768  		return s.rpcMarshalHeader(ctx, header)
   769  	}
   770  	return nil
   771  }
   772  
   773  // GetBlockByNumber returns the requested canonical block.
   774  // * When blockNr is -1 the chain head is returned.
   775  // * When blockNr is -2 the pending chain head is returned.
   776  // * When fullTx is true all transactions in the block are returned, otherwise
   777  //   only the transaction hash is returned.
   778  func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, number rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
   779  	block, err := s.b.BlockByNumber(ctx, number)
   780  	if block != nil && err == nil {
   781  		response, err := s.rpcMarshalBlock(ctx, block, true, fullTx)
   782  		if err == nil && number == rpc.PendingBlockNumber {
   783  			// Pending blocks need to nil out a few fields
   784  			for _, field := range []string{"hash", "nonce", "miner"} {
   785  				response[field] = nil
   786  			}
   787  		}
   788  		return response, err
   789  	}
   790  	return nil, err
   791  }
   792  
   793  // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full
   794  // detail, otherwise only the transaction hash is returned.
   795  func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, hash common.Hash, fullTx bool) (map[string]interface{}, error) {
   796  	block, err := s.b.BlockByHash(ctx, hash)
   797  	if block != nil {
   798  		return s.rpcMarshalBlock(ctx, block, true, fullTx)
   799  	}
   800  	return nil, err
   801  }
   802  
   803  // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true
   804  // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
   805  func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) {
   806  	block, err := s.b.BlockByNumber(ctx, blockNr)
   807  	if block != nil {
   808  		uncles := block.Uncles()
   809  		if index >= hexutil.Uint(len(uncles)) {
   810  			log.Debug("Requested uncle not found", "number", blockNr, "hash", block.Hash(), "index", index)
   811  			return nil, nil
   812  		}
   813  		block = types.NewBlockWithHeader(uncles[index])
   814  		return s.rpcMarshalBlock(ctx, block, false, false)
   815  	}
   816  	return nil, err
   817  }
   818  
   819  // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true
   820  // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned.
   821  func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) {
   822  	block, err := s.b.BlockByHash(ctx, blockHash)
   823  	if block != nil {
   824  		uncles := block.Uncles()
   825  		if index >= hexutil.Uint(len(uncles)) {
   826  			log.Debug("Requested uncle not found", "number", block.Number(), "hash", blockHash, "index", index)
   827  			return nil, nil
   828  		}
   829  		block = types.NewBlockWithHeader(uncles[index])
   830  		return s.rpcMarshalBlock(ctx, block, false, false)
   831  	}
   832  	return nil, err
   833  }
   834  
   835  // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number
   836  func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
   837  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
   838  		n := hexutil.Uint(len(block.Uncles()))
   839  		return &n
   840  	}
   841  	return nil
   842  }
   843  
   844  // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash
   845  func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
   846  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
   847  		n := hexutil.Uint(len(block.Uncles()))
   848  		return &n
   849  	}
   850  	return nil
   851  }
   852  
   853  // GetCode returns the code stored at the given address in the state for the given block number.
   854  func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
   855  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   856  	if state == nil || err != nil {
   857  		return nil, err
   858  	}
   859  	code := state.GetCode(address)
   860  	return code, state.Error()
   861  }
   862  
   863  // GetStorageAt returns the storage from the state at the given address, key and
   864  // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block
   865  // numbers are also allowed.
   866  func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) {
   867  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   868  	if state == nil || err != nil {
   869  		return nil, err
   870  	}
   871  	res := state.GetState(address, common.HexToHash(key))
   872  	return res[:], state.Error()
   873  }
   874  
   875  // CallArgs represents the arguments for a call.
   876  type CallArgs struct {
   877  	From     *common.Address `json:"from"`
   878  	To       *common.Address `json:"to"`
   879  	Gas      *hexutil.Uint64 `json:"gas"`
   880  	GasPrice *hexutil.Big    `json:"gasPrice"`
   881  	Value    *hexutil.Big    `json:"value"`
   882  	Data     *hexutil.Bytes  `json:"data"`
   883  }
   884  
   885  // ToMessage converts CallArgs to the Message type used by the core evm
   886  func (args *CallArgs) ToMessage(globalGasCap uint64) types.Message {
   887  	// Set sender address or use zero address if none specified.
   888  	var addr common.Address
   889  	if args.From != nil {
   890  		addr = *args.From
   891  	}
   892  
   893  	// Set default gas & gas price if none were set
   894  	gas := globalGasCap
   895  	if gas == 0 {
   896  		gas = uint64(math.MaxUint64 / 2)
   897  	}
   898  	if args.Gas != nil {
   899  		gas = uint64(*args.Gas)
   900  	}
   901  	if globalGasCap != 0 && globalGasCap < gas {
   902  		log.Warn("Caller gas above allowance, capping", "requested", gas, "cap", globalGasCap)
   903  		gas = globalGasCap
   904  	}
   905  	gasPrice := new(big.Int)
   906  	if args.GasPrice != nil {
   907  		gasPrice = args.GasPrice.ToInt()
   908  	}
   909  
   910  	value := new(big.Int)
   911  	if args.Value != nil {
   912  		value = args.Value.ToInt()
   913  	}
   914  
   915  	var data []byte
   916  	if args.Data != nil {
   917  		data = *args.Data
   918  	}
   919  
   920  	msg := types.NewMessage(addr, args.To, 0, value, gas, gasPrice, data, false)
   921  	return msg
   922  }
   923  
   924  // account indicates the overriding fields of account during the execution of
   925  // a message call.
   926  // Note, state and stateDiff can't be specified at the same time. If state is
   927  // set, message execution will only use the data in the given state. Otherwise
   928  // if statDiff is set, all diff will be applied first and then execute the call
   929  // message.
   930  type account struct {
   931  	Nonce     *hexutil.Uint64              `json:"nonce"`
   932  	Code      *hexutil.Bytes               `json:"code"`
   933  	Balance   **hexutil.Big                `json:"balance"`
   934  	State     *map[common.Hash]common.Hash `json:"state"`
   935  	StateDiff *map[common.Hash]common.Hash `json:"stateDiff"`
   936  }
   937  
   938  // Quorum - Multitenancy
   939  // Before returning the result, we need to inspect the EVM and
   940  // perform verification check
   941  func DoCall(ctx context.Context, b Backend, args CallArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides map[common.Address]account, vmCfg vm.Config, timeout time.Duration, globalGasCap uint64) (*core.ExecutionResult, error) {
   942  	defer func(start time.Time) { log.Debug("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now())
   943  
   944  	state, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
   945  	if state == nil || err != nil {
   946  		return nil, err
   947  	}
   948  	// Override the fields of specified contracts before execution.
   949  	for addr, account := range overrides {
   950  		// Override account nonce.
   951  		if account.Nonce != nil {
   952  			state.SetNonce(addr, uint64(*account.Nonce))
   953  		}
   954  		// Override account(contract) code.
   955  		if account.Code != nil {
   956  			state.SetCode(addr, *account.Code)
   957  		}
   958  		// Override account balance.
   959  		if account.Balance != nil {
   960  			state.SetBalance(addr, (*big.Int)(*account.Balance))
   961  		}
   962  		if account.State != nil && account.StateDiff != nil {
   963  			return nil, fmt.Errorf("account %s has both 'state' and 'stateDiff'", addr.Hex())
   964  		}
   965  		// Replace entire state if caller requires.
   966  		if account.State != nil {
   967  			state.SetStorage(addr, *account.State)
   968  		}
   969  		// Apply state diff into specified accounts.
   970  		if account.StateDiff != nil {
   971  			for key, value := range *account.StateDiff {
   972  				state.SetState(addr, key, value)
   973  			}
   974  		}
   975  	}
   976  	// Setup context so it may be cancelled the call has completed
   977  	// or, in case of unmetered gas, setup a context with a timeout.
   978  	var cancel context.CancelFunc
   979  	if timeout > 0 {
   980  		ctx, cancel = context.WithTimeout(ctx, timeout)
   981  	} else {
   982  		ctx, cancel = context.WithCancel(ctx)
   983  	}
   984  	// Make sure the context is cancelled when the call has completed
   985  	// this makes sure resources are cleaned up.
   986  	defer cancel()
   987  
   988  	msg := args.ToMessage(globalGasCap)
   989  	// Get a new instance of the EVM.
   990  	evm, vmError, err := b.GetEVM(ctx, msg, state, header)
   991  	if err != nil {
   992  		return nil, err
   993  	}
   994  	// Wait for the context to be done and cancel the evm. Even if the
   995  	// EVM has finished, cancelling may be done (repeatedly)
   996  	go func() {
   997  		<-ctx.Done()
   998  		evm.Cancel()
   999  	}()
  1000  
  1001  	// Setup the gas pool (also for unmetered requests)
  1002  	// and apply the message.
  1003  	gp := new(core.GasPool).AddGas(math.MaxUint64)
  1004  	result, applyErr := core.ApplyMessage(evm, msg, gp)
  1005  	if err := vmError(); err != nil {
  1006  		return nil, err
  1007  	}
  1008  	// If the timer caused an abort, return an appropriate error message
  1009  	if evm.Cancelled() {
  1010  		return nil, fmt.Errorf("execution aborted (timeout = %v)", timeout)
  1011  	}
  1012  	if applyErr != nil {
  1013  		return result, fmt.Errorf("err: %w (supplied gas %d)", applyErr, msg.Gas())
  1014  	}
  1015  	return result, nil
  1016  }
  1017  
  1018  func newRevertError(result *core.ExecutionResult) *revertError {
  1019  	reason, errUnpack := abi.UnpackRevert(result.Revert())
  1020  	err := errors.New("execution reverted")
  1021  	if errUnpack == nil {
  1022  		err = fmt.Errorf("execution reverted: %v", reason)
  1023  	}
  1024  	return &revertError{
  1025  		error:  err,
  1026  		reason: hexutil.Encode(result.Revert()),
  1027  	}
  1028  }
  1029  
  1030  // revertError is an API error that encompassas an EVM revertal with JSON error
  1031  // code and a binary data blob.
  1032  type revertError struct {
  1033  	error
  1034  	reason string // revert reason hex encoded
  1035  }
  1036  
  1037  // ErrorCode returns the JSON error code for a revertal.
  1038  // See: https://github.com/ethereum/wiki/wiki/JSON-RPC-Error-Codes-Improvement-Proposal
  1039  func (e *revertError) ErrorCode() int {
  1040  	return 3
  1041  }
  1042  
  1043  // ErrorData returns the hex encoded revert reason.
  1044  func (e *revertError) ErrorData() interface{} {
  1045  	return e.reason
  1046  }
  1047  
  1048  // Call executes the given transaction on the state for the given block number.
  1049  //
  1050  // Additionally, the caller can specify a batch of contract for fields overriding.
  1051  //
  1052  // Note, this function doesn't make and changes in the state/blockchain and is
  1053  // useful to execute and retrieve values.
  1054  // Quorum
  1055  // - replaced the default 5s time out with the value passed in vm.calltimeout
  1056  // - multi tenancy verification
  1057  func (s *PublicBlockChainAPI) Call(ctx context.Context, args CallArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *map[common.Address]account) (hexutil.Bytes, error) {
  1058  	var accounts map[common.Address]account
  1059  	if overrides != nil {
  1060  		accounts = *overrides
  1061  	}
  1062  
  1063  	result, err := DoCall(ctx, s.b, args, blockNrOrHash, accounts, vm.Config{}, s.b.CallTimeOut(), s.b.RPCGasCap())
  1064  	if err != nil {
  1065  		return nil, err
  1066  	}
  1067  	// If the result contains a revert reason, try to unpack and return it.
  1068  	if len(result.Revert()) > 0 {
  1069  		return nil, newRevertError(result)
  1070  	}
  1071  	return result.Return(), result.Err
  1072  }
  1073  
  1074  func DoEstimateGas(ctx context.Context, b Backend, args CallArgs, blockNrOrHash rpc.BlockNumberOrHash, gasCap uint64) (hexutil.Uint64, error) {
  1075  	// Binary search the gas requirement, as it may be higher than the amount used
  1076  	var (
  1077  		lo  uint64 = params.TxGas - 1
  1078  		hi  uint64
  1079  		cap uint64
  1080  	)
  1081  	// Use zero address if sender unspecified.
  1082  	if args.From == nil {
  1083  		args.From = new(common.Address)
  1084  	}
  1085  	// Determine the highest gas limit can be used during the estimation.
  1086  	if args.Gas != nil && uint64(*args.Gas) >= params.TxGas {
  1087  		hi = uint64(*args.Gas)
  1088  	} else {
  1089  		// Retrieve the block to act as the gas ceiling
  1090  		block, err := b.BlockByNumberOrHash(ctx, blockNrOrHash)
  1091  		if err != nil {
  1092  			return 0, err
  1093  		}
  1094  		if block == nil {
  1095  			return 0, errors.New("block not found")
  1096  		}
  1097  		hi = block.GasLimit()
  1098  	}
  1099  	// Recap the highest gas limit with account's available balance.
  1100  	if args.GasPrice != nil && args.GasPrice.ToInt().BitLen() != 0 {
  1101  		state, _, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1102  		if err != nil {
  1103  			return 0, err
  1104  		}
  1105  		balance := state.GetBalance(*args.From) // from can't be nil
  1106  		available := new(big.Int).Set(balance)
  1107  		if args.Value != nil {
  1108  			if args.Value.ToInt().Cmp(available) >= 0 {
  1109  				return 0, errors.New("insufficient funds for transfer")
  1110  			}
  1111  			available.Sub(available, args.Value.ToInt())
  1112  		}
  1113  		allowance := new(big.Int).Div(available, args.GasPrice.ToInt())
  1114  
  1115  		// If the allowance is larger than maximum uint64, skip checking
  1116  		if allowance.IsUint64() && hi > allowance.Uint64() {
  1117  			transfer := args.Value
  1118  			if transfer == nil {
  1119  				transfer = new(hexutil.Big)
  1120  			}
  1121  			log.Warn("Gas estimation capped by limited funds", "original", hi, "balance", balance,
  1122  				"sent", transfer.ToInt(), "gasprice", args.GasPrice.ToInt(), "fundable", allowance)
  1123  			hi = allowance.Uint64()
  1124  		}
  1125  	}
  1126  	// Recap the highest gas allowance with specified gascap.
  1127  	if gasCap != 0 && hi > gasCap {
  1128  		log.Warn("Caller gas above allowance, capping", "requested", hi, "cap", gasCap)
  1129  		hi = gasCap
  1130  	}
  1131  	cap = hi
  1132  
  1133  	// Create a helper to check if a gas allowance results in an executable transaction
  1134  	executable := func(gas uint64) (bool, *core.ExecutionResult, error) {
  1135  		args.Gas = (*hexutil.Uint64)(&gas)
  1136  
  1137  		result, err := DoCall(ctx, b, args, blockNrOrHash, nil, vm.Config{}, 0, gasCap)
  1138  		if err != nil {
  1139  			if errors.Is(err, core.ErrIntrinsicGas) {
  1140  				return true, nil, nil // Special case, raise gas limit
  1141  			}
  1142  			return true, nil, err // Bail out
  1143  		}
  1144  		return result.Failed(), result, nil
  1145  	}
  1146  	// Execute the binary search and hone in on an executable gas limit
  1147  	for lo+1 < hi {
  1148  		mid := (hi + lo) / 2
  1149  		failed, _, err := executable(mid)
  1150  
  1151  		// If the error is not nil(consensus error), it means the provided message
  1152  		// call or transaction will never be accepted no matter how much gas it is
  1153  		// assigned. Return the error directly, don't struggle any more.
  1154  		if err != nil {
  1155  			return 0, err
  1156  		}
  1157  		if failed {
  1158  			lo = mid
  1159  		} else {
  1160  			hi = mid
  1161  		}
  1162  	}
  1163  	// Reject the transaction as invalid if it still fails at the highest allowance
  1164  	if hi == cap {
  1165  		failed, result, err := executable(hi)
  1166  		if err != nil {
  1167  			return 0, err
  1168  		}
  1169  		if failed {
  1170  			if result != nil && result.Err != vm.ErrOutOfGas {
  1171  				if len(result.Revert()) > 0 {
  1172  					return 0, newRevertError(result)
  1173  				}
  1174  				return 0, result.Err
  1175  			}
  1176  			// Otherwise, the specified gas cap is too low
  1177  			return 0, fmt.Errorf("gas required exceeds allowance (%d)", cap)
  1178  		}
  1179  	}
  1180  
  1181  	//QUORUM
  1182  
  1183  	//We don't know if this is going to be a private or public transaction
  1184  	//It is possible to have a data field that has a lower intrinsic value than the PTM hash
  1185  	//so this checks that if we were to place a PTM hash (with all non-zero values) here then the transaction would
  1186  	//still run
  1187  	//This makes the return value a potential over-estimate of gas, rather than the exact cost to run right now
  1188  
  1189  	//if the transaction has a value then it cannot be private, so we can skip this check
  1190  	if args.Value != nil && args.Value.ToInt().Cmp(big.NewInt(0)) == 0 {
  1191  		currentBlockHeight := b.CurrentHeader().Number
  1192  		homestead := b.ChainConfig().IsHomestead(currentBlockHeight)
  1193  		istanbul := b.ChainConfig().IsIstanbul(currentBlockHeight)
  1194  
  1195  		var data []byte
  1196  		if args.Data == nil {
  1197  			data = nil
  1198  		} else {
  1199  			data = []byte(*args.Data)
  1200  		}
  1201  		intrinsicGasPublic, _ := core.IntrinsicGas(data, args.To == nil, homestead, istanbul)
  1202  		intrinsicGasPrivate, _ := core.IntrinsicGas(common.Hex2Bytes(common.MaxPrivateIntrinsicDataHex), args.To == nil, homestead, istanbul)
  1203  
  1204  		if intrinsicGasPrivate > intrinsicGasPublic {
  1205  			if math.MaxUint64-hi < intrinsicGasPrivate-intrinsicGasPublic {
  1206  				return 0, fmt.Errorf("private intrinsic gas addition exceeds allowance")
  1207  			}
  1208  			return hexutil.Uint64(hi + (intrinsicGasPrivate - intrinsicGasPublic)), nil
  1209  		}
  1210  
  1211  	}
  1212  
  1213  	//END QUORUM
  1214  
  1215  	return hexutil.Uint64(hi), nil
  1216  }
  1217  
  1218  // EstimateGas returns an estimate of the amount of gas needed to execute the
  1219  // given transaction against the current pending block.
  1220  func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args CallArgs, blockNrOrHash *rpc.BlockNumberOrHash) (hexutil.Uint64, error) {
  1221  	bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
  1222  	if blockNrOrHash != nil {
  1223  		bNrOrHash = *blockNrOrHash
  1224  	}
  1225  	return DoEstimateGas(ctx, s.b, args, bNrOrHash, s.b.RPCGasCap())
  1226  }
  1227  
  1228  // ExecutionResult groups all structured logs emitted by the EVM
  1229  // while replaying a transaction in debug mode as well as transaction
  1230  // execution status, the amount of gas used and the return value
  1231  type ExecutionResult struct {
  1232  	Gas         uint64         `json:"gas"`
  1233  	Failed      bool           `json:"failed"`
  1234  	ReturnValue string         `json:"returnValue"`
  1235  	StructLogs  []StructLogRes `json:"structLogs"`
  1236  }
  1237  
  1238  // StructLogRes stores a structured log emitted by the EVM while replaying a
  1239  // transaction in debug mode
  1240  type StructLogRes struct {
  1241  	Pc      uint64             `json:"pc"`
  1242  	Op      string             `json:"op"`
  1243  	Gas     uint64             `json:"gas"`
  1244  	GasCost uint64             `json:"gasCost"`
  1245  	Depth   int                `json:"depth"`
  1246  	Error   error              `json:"error,omitempty"`
  1247  	Stack   *[]string          `json:"stack,omitempty"`
  1248  	Memory  *[]string          `json:"memory,omitempty"`
  1249  	Storage *map[string]string `json:"storage,omitempty"`
  1250  }
  1251  
  1252  // FormatLogs formats EVM returned structured logs for json output
  1253  func FormatLogs(logs []vm.StructLog) []StructLogRes {
  1254  	formatted := make([]StructLogRes, len(logs))
  1255  	for index, trace := range logs {
  1256  		formatted[index] = StructLogRes{
  1257  			Pc:      trace.Pc,
  1258  			Op:      trace.Op.String(),
  1259  			Gas:     trace.Gas,
  1260  			GasCost: trace.GasCost,
  1261  			Depth:   trace.Depth,
  1262  			Error:   trace.Err,
  1263  		}
  1264  		if trace.Stack != nil {
  1265  			stack := make([]string, len(trace.Stack))
  1266  			for i, stackValue := range trace.Stack {
  1267  				stack[i] = fmt.Sprintf("%x", math.PaddedBigBytes(stackValue, 32))
  1268  			}
  1269  			formatted[index].Stack = &stack
  1270  		}
  1271  		if trace.Memory != nil {
  1272  			memory := make([]string, 0, (len(trace.Memory)+31)/32)
  1273  			for i := 0; i+32 <= len(trace.Memory); i += 32 {
  1274  				memory = append(memory, fmt.Sprintf("%x", trace.Memory[i:i+32]))
  1275  			}
  1276  			formatted[index].Memory = &memory
  1277  		}
  1278  		if trace.Storage != nil {
  1279  			storage := make(map[string]string)
  1280  			for i, storageValue := range trace.Storage {
  1281  				storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue)
  1282  			}
  1283  			formatted[index].Storage = &storage
  1284  		}
  1285  	}
  1286  	return formatted
  1287  }
  1288  
  1289  // RPCMarshalHeader converts the given header to the RPC output .
  1290  func RPCMarshalHeader(head *types.Header) map[string]interface{} {
  1291  	return map[string]interface{}{
  1292  		"number":           (*hexutil.Big)(head.Number),
  1293  		"hash":             head.Hash(),
  1294  		"parentHash":       head.ParentHash,
  1295  		"nonce":            head.Nonce,
  1296  		"mixHash":          head.MixDigest,
  1297  		"sha3Uncles":       head.UncleHash,
  1298  		"logsBloom":        head.Bloom,
  1299  		"stateRoot":        head.Root,
  1300  		"miner":            head.Coinbase,
  1301  		"difficulty":       (*hexutil.Big)(head.Difficulty),
  1302  		"extraData":        hexutil.Bytes(head.Extra),
  1303  		"size":             hexutil.Uint64(head.Size()),
  1304  		"gasLimit":         hexutil.Uint64(head.GasLimit),
  1305  		"gasUsed":          hexutil.Uint64(head.GasUsed),
  1306  		"timestamp":        hexutil.Uint64(head.Time),
  1307  		"transactionsRoot": head.TxHash,
  1308  		"receiptsRoot":     head.ReceiptHash,
  1309  	}
  1310  }
  1311  
  1312  // RPCMarshalBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are
  1313  // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain
  1314  // transaction hashes.
  1315  func RPCMarshalBlock(block *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  1316  	fields := RPCMarshalHeader(block.Header())
  1317  	fields["size"] = hexutil.Uint64(block.Size())
  1318  
  1319  	if inclTx {
  1320  		formatTx := func(tx *types.Transaction) (interface{}, error) {
  1321  			return tx.Hash(), nil
  1322  		}
  1323  		if fullTx {
  1324  			formatTx = func(tx *types.Transaction) (interface{}, error) {
  1325  				return newRPCTransactionFromBlockHash(block, tx.Hash()), nil
  1326  			}
  1327  		}
  1328  		txs := block.Transactions()
  1329  		transactions := make([]interface{}, len(txs))
  1330  		var err error
  1331  		for i, tx := range txs {
  1332  			if transactions[i], err = formatTx(tx); err != nil {
  1333  				return nil, err
  1334  			}
  1335  		}
  1336  		fields["transactions"] = transactions
  1337  	}
  1338  	uncles := block.Uncles()
  1339  	uncleHashes := make([]common.Hash, len(uncles))
  1340  	for i, uncle := range uncles {
  1341  		uncleHashes[i] = uncle.Hash()
  1342  	}
  1343  	fields["uncles"] = uncleHashes
  1344  
  1345  	return fields, nil
  1346  }
  1347  
  1348  // rpcMarshalHeader uses the generalized output filler, then adds the total difficulty field, which requires
  1349  // a `PublicBlockchainAPI`.
  1350  func (s *PublicBlockChainAPI) rpcMarshalHeader(ctx context.Context, header *types.Header) map[string]interface{} {
  1351  	fields := RPCMarshalHeader(header)
  1352  	fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(ctx, header.Hash()))
  1353  	return fields
  1354  }
  1355  
  1356  // rpcMarshalBlock uses the generalized output filler, then adds the total difficulty field, which requires
  1357  // a `PublicBlockchainAPI`.
  1358  func (s *PublicBlockChainAPI) rpcMarshalBlock(ctx context.Context, b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) {
  1359  	fields, err := RPCMarshalBlock(b, inclTx, fullTx)
  1360  	if err != nil {
  1361  		return nil, err
  1362  	}
  1363  	if inclTx {
  1364  		fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(ctx, b.Hash()))
  1365  	}
  1366  	return fields, err
  1367  }
  1368  
  1369  // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction
  1370  type RPCTransaction struct {
  1371  	BlockHash        *common.Hash    `json:"blockHash"`
  1372  	BlockNumber      *hexutil.Big    `json:"blockNumber"`
  1373  	From             common.Address  `json:"from"`
  1374  	Gas              hexutil.Uint64  `json:"gas"`
  1375  	GasPrice         *hexutil.Big    `json:"gasPrice"`
  1376  	Hash             common.Hash     `json:"hash"`
  1377  	Input            hexutil.Bytes   `json:"input"`
  1378  	Nonce            hexutil.Uint64  `json:"nonce"`
  1379  	To               *common.Address `json:"to"`
  1380  	TransactionIndex *hexutil.Uint64 `json:"transactionIndex"`
  1381  	Value            *hexutil.Big    `json:"value"`
  1382  	V                *hexutil.Big    `json:"v"`
  1383  	R                *hexutil.Big    `json:"r"`
  1384  	S                *hexutil.Big    `json:"s"`
  1385  }
  1386  
  1387  // newRPCTransaction returns a transaction that will serialize to the RPC
  1388  // representation, with the given location metadata set (if available).
  1389  func newRPCTransaction(tx *types.Transaction, blockHash common.Hash, blockNumber uint64, index uint64) *RPCTransaction {
  1390  	var signer types.Signer = types.HomesteadSigner{}
  1391  	// joel: this is one of the two places we used a wrong signer to print txes
  1392  	if tx.Protected() && !tx.IsPrivate() {
  1393  		signer = types.NewEIP155Signer(tx.ChainId())
  1394  	}
  1395  	from, _ := types.Sender(signer, tx)
  1396  	v, r, s := tx.RawSignatureValues()
  1397  
  1398  	result := &RPCTransaction{
  1399  		From:     from,
  1400  		Gas:      hexutil.Uint64(tx.Gas()),
  1401  		GasPrice: (*hexutil.Big)(tx.GasPrice()),
  1402  		Hash:     tx.Hash(),
  1403  		Input:    hexutil.Bytes(tx.Data()),
  1404  		Nonce:    hexutil.Uint64(tx.Nonce()),
  1405  		To:       tx.To(),
  1406  		Value:    (*hexutil.Big)(tx.Value()),
  1407  		V:        (*hexutil.Big)(v),
  1408  		R:        (*hexutil.Big)(r),
  1409  		S:        (*hexutil.Big)(s),
  1410  	}
  1411  	if blockHash != (common.Hash{}) {
  1412  		result.BlockHash = &blockHash
  1413  		result.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(blockNumber))
  1414  		result.TransactionIndex = (*hexutil.Uint64)(&index)
  1415  	}
  1416  	return result
  1417  }
  1418  
  1419  // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation
  1420  func newRPCPendingTransaction(tx *types.Transaction) *RPCTransaction {
  1421  	return newRPCTransaction(tx, common.Hash{}, 0, 0)
  1422  }
  1423  
  1424  // newRPCTransactionFromBlockIndex returns a transaction that will serialize to the RPC representation.
  1425  func newRPCTransactionFromBlockIndex(b *types.Block, index uint64) *RPCTransaction {
  1426  	txs := b.Transactions()
  1427  	if index >= uint64(len(txs)) {
  1428  		return nil
  1429  	}
  1430  	return newRPCTransaction(txs[index], b.Hash(), b.NumberU64(), index)
  1431  }
  1432  
  1433  // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index.
  1434  func newRPCRawTransactionFromBlockIndex(b *types.Block, index uint64) hexutil.Bytes {
  1435  	txs := b.Transactions()
  1436  	if index >= uint64(len(txs)) {
  1437  		return nil
  1438  	}
  1439  	blob, _ := rlp.EncodeToBytes(txs[index])
  1440  	return blob
  1441  }
  1442  
  1443  // newRPCTransactionFromBlockHash returns a transaction that will serialize to the RPC representation.
  1444  func newRPCTransactionFromBlockHash(b *types.Block, hash common.Hash) *RPCTransaction {
  1445  	for idx, tx := range b.Transactions() {
  1446  		if tx.Hash() == hash {
  1447  			return newRPCTransactionFromBlockIndex(b, uint64(idx))
  1448  		}
  1449  	}
  1450  	return nil
  1451  }
  1452  
  1453  // PublicTransactionPoolAPI exposes methods for the RPC interface
  1454  type PublicTransactionPoolAPI struct {
  1455  	b         Backend
  1456  	nonceLock *AddrLocker
  1457  }
  1458  
  1459  // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool.
  1460  func NewPublicTransactionPoolAPI(b Backend, nonceLock *AddrLocker) *PublicTransactionPoolAPI {
  1461  	return &PublicTransactionPoolAPI{b, nonceLock}
  1462  }
  1463  
  1464  // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number.
  1465  func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint {
  1466  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1467  		n := hexutil.Uint(len(block.Transactions()))
  1468  		return &n
  1469  	}
  1470  	return nil
  1471  }
  1472  
  1473  // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash.
  1474  func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint {
  1475  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1476  		n := hexutil.Uint(len(block.Transactions()))
  1477  		return &n
  1478  	}
  1479  	return nil
  1480  }
  1481  
  1482  // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index.
  1483  func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) *RPCTransaction {
  1484  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1485  		return newRPCTransactionFromBlockIndex(block, uint64(index))
  1486  	}
  1487  	return nil
  1488  }
  1489  
  1490  // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index.
  1491  func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) *RPCTransaction {
  1492  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1493  		return newRPCTransactionFromBlockIndex(block, uint64(index))
  1494  	}
  1495  	return nil
  1496  }
  1497  
  1498  // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index.
  1499  func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) hexutil.Bytes {
  1500  	if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil {
  1501  		return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1502  	}
  1503  	return nil
  1504  }
  1505  
  1506  // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index.
  1507  func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) hexutil.Bytes {
  1508  	if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil {
  1509  		return newRPCRawTransactionFromBlockIndex(block, uint64(index))
  1510  	}
  1511  	return nil
  1512  }
  1513  
  1514  // GetTransactionCount returns the number of transactions the given address has sent for the given block number
  1515  func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Uint64, error) {
  1516  	// Ask transaction pool for the nonce which includes pending transactions
  1517  	if blockNr, ok := blockNrOrHash.Number(); ok && blockNr == rpc.PendingBlockNumber {
  1518  		nonce, err := s.b.GetPoolNonce(ctx, address)
  1519  		if err != nil {
  1520  			return nil, err
  1521  		}
  1522  		return (*hexutil.Uint64)(&nonce), nil
  1523  	}
  1524  	// Resolve block number and use its state to ask for the nonce
  1525  	state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  1526  	if state == nil || err != nil {
  1527  		return nil, err
  1528  	}
  1529  	nonce := state.GetNonce(address)
  1530  	return (*hexutil.Uint64)(&nonce), state.Error()
  1531  }
  1532  
  1533  // Quorum
  1534  
  1535  type PrivacyMetadataWithMandatoryRecipients struct {
  1536  	*state.PrivacyMetadata
  1537  	MandatoryRecipients []string `json:"mandatoryFor,omitempty"`
  1538  }
  1539  
  1540  func (s *PublicTransactionPoolAPI) GetContractPrivacyMetadata(ctx context.Context, address common.Address) (*PrivacyMetadataWithMandatoryRecipients, error) {
  1541  	state, _, err := s.b.StateAndHeaderByNumber(ctx, rpc.LatestBlockNumber)
  1542  	if state == nil || err != nil {
  1543  		return nil, err
  1544  	}
  1545  	var mandatoryRecipients []string
  1546  
  1547  	privacyMetadata, err := state.GetPrivacyMetadata(address)
  1548  	if privacyMetadata == nil || err != nil {
  1549  		return nil, err
  1550  	}
  1551  
  1552  	if privacyMetadata.PrivacyFlag == engine.PrivacyFlagMandatoryRecipients {
  1553  		mandatoryRecipients, err = private.P.GetMandatory(privacyMetadata.CreationTxHash)
  1554  		if len(mandatoryRecipients) == 0 || err != nil {
  1555  			return nil, err
  1556  		}
  1557  	}
  1558  
  1559  	return &PrivacyMetadataWithMandatoryRecipients{privacyMetadata, mandatoryRecipients}, nil
  1560  }
  1561  
  1562  // End Quorum
  1563  
  1564  // GetTransactionByHash returns the transaction for the given hash
  1565  func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) (*RPCTransaction, error) {
  1566  	// Try to return an already finalized transaction
  1567  	tx, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1568  	if err != nil {
  1569  		return nil, err
  1570  	}
  1571  	if tx != nil {
  1572  		return newRPCTransaction(tx, blockHash, blockNumber, index), nil
  1573  	}
  1574  	// No finalized transaction, try to retrieve it from the pool
  1575  	if tx := s.b.GetPoolTransaction(hash); tx != nil {
  1576  		return newRPCPendingTransaction(tx), nil
  1577  	}
  1578  
  1579  	// Transaction unknown, return as such
  1580  	return nil, nil
  1581  }
  1582  
  1583  // GetRawTransactionByHash returns the bytes of the transaction for the given hash.
  1584  func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  1585  	// Retrieve a finalized transaction, or a pooled otherwise
  1586  	tx, _, _, _, err := s.b.GetTransaction(ctx, hash)
  1587  	if err != nil {
  1588  		return nil, err
  1589  	}
  1590  	if tx == nil {
  1591  		if tx = s.b.GetPoolTransaction(hash); tx == nil {
  1592  			// Transaction not found anywhere, abort
  1593  			return nil, nil
  1594  		}
  1595  	}
  1596  	// Serialize to RLP and return
  1597  	return rlp.EncodeToBytes(tx)
  1598  }
  1599  
  1600  // GetTransactionReceipt returns the transaction receipt for the given transaction hash.
  1601  func (s *PublicTransactionPoolAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) {
  1602  	tx, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1603  	if err != nil {
  1604  		return nil, nil
  1605  	}
  1606  	receipts, err := s.b.GetReceipts(ctx, blockHash)
  1607  	if err != nil {
  1608  		return nil, err
  1609  	}
  1610  	if len(receipts) <= int(index) {
  1611  		return nil, nil
  1612  	}
  1613  	receipt := receipts[index]
  1614  
  1615  	// Quorum: note that upstream code has been refactored into this method
  1616  	return getTransactionReceiptCommonCode(tx, blockHash, blockNumber, hash, index, receipt)
  1617  }
  1618  
  1619  // Quorum
  1620  // Common code extracted from GetTransactionReceipt() to enable reuse
  1621  func getTransactionReceiptCommonCode(tx *types.Transaction, blockHash common.Hash, blockNumber uint64, hash common.Hash, index uint64, receipt *types.Receipt) (map[string]interface{}, error) {
  1622  	var signer types.Signer = types.HomesteadSigner{}
  1623  	if tx.Protected() && !tx.IsPrivate() {
  1624  		signer = types.NewEIP155Signer(tx.ChainId())
  1625  	}
  1626  	from, _ := types.Sender(signer, tx)
  1627  
  1628  	fields := map[string]interface{}{
  1629  		"blockHash":                  blockHash,
  1630  		"blockNumber":                hexutil.Uint64(blockNumber),
  1631  		"transactionHash":            hash,
  1632  		"transactionIndex":           hexutil.Uint64(index),
  1633  		"from":                       from,
  1634  		"to":                         tx.To(),
  1635  		"gasUsed":                    hexutil.Uint64(receipt.GasUsed),
  1636  		"cumulativeGasUsed":          hexutil.Uint64(receipt.CumulativeGasUsed),
  1637  		"contractAddress":            nil,
  1638  		"logs":                       receipt.Logs,
  1639  		"logsBloom":                  receipt.Bloom,
  1640  		"isPrivacyMarkerTransaction": tx.IsPrivacyMarker(),
  1641  	}
  1642  
  1643  	// Quorum
  1644  	if len(receipt.RevertReason) > 0 {
  1645  		fields["revertReason"] = hexutil.Encode(receipt.RevertReason)
  1646  	}
  1647  	// End Quorum
  1648  
  1649  	// Assign receipt status or post state.
  1650  	if len(receipt.PostState) > 0 {
  1651  		fields["root"] = hexutil.Bytes(receipt.PostState)
  1652  	} else {
  1653  		fields["status"] = hexutil.Uint(receipt.Status)
  1654  	}
  1655  	if receipt.Logs == nil {
  1656  		fields["logs"] = [][]*types.Log{}
  1657  	}
  1658  	// If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation
  1659  	if receipt.ContractAddress != (common.Address{}) {
  1660  		fields["contractAddress"] = receipt.ContractAddress
  1661  	}
  1662  	return fields, nil
  1663  }
  1664  
  1665  // Quorum
  1666  // GetPrivateTransactionByHash accepts the hash for a privacy marker transaction,
  1667  // but returns the associated private transaction
  1668  func (s *PublicTransactionPoolAPI) GetPrivateTransactionByHash(ctx context.Context, hash common.Hash) (*RPCTransaction, error) {
  1669  	if !private.IsQuorumPrivacyEnabled() {
  1670  		return nil, fmt.Errorf("PrivateTransactionManager is not enabled")
  1671  	}
  1672  	psm, err := s.b.PSMR().ResolveForUserContext(ctx)
  1673  	if err != nil {
  1674  		return nil, err
  1675  	}
  1676  
  1677  	// first need the privacy marker transaction
  1678  	pmt, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1679  	if err != nil {
  1680  		return nil, err
  1681  	}
  1682  
  1683  	// now retrieve the private transaction
  1684  	if pmt != nil {
  1685  		tx, managedParties, _, err := private.FetchPrivateTransaction(pmt.Data())
  1686  		if err != nil {
  1687  			return nil, err
  1688  		}
  1689  		if tx != nil && !s.b.PSMR().NotIncludeAny(psm, managedParties...) {
  1690  			return newRPCTransaction(tx, blockHash, blockNumber, index), nil
  1691  		}
  1692  	}
  1693  
  1694  	// Transaction unknown or not a participant in the private transaction, return as such
  1695  	return nil, nil
  1696  }
  1697  
  1698  // Quorum
  1699  // GetPrivateTransactionReceipt accepts the hash for a privacy marker transaction,
  1700  // but returns the receipt of the associated private transaction
  1701  func (s *PublicTransactionPoolAPI) GetPrivateTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) {
  1702  	// first need the privacy marker transaction
  1703  	pmt, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash)
  1704  	if err != nil {
  1705  		return nil, err
  1706  	}
  1707  	if pmt == nil {
  1708  		// Transaction unknown, return as such
  1709  		return nil, errors.New("privacy marker transaction not found")
  1710  	}
  1711  
  1712  	// now retrieve the private transaction
  1713  	tx, _, _, err := private.FetchPrivateTransaction(pmt.Data())
  1714  	if err != nil {
  1715  		return nil, err
  1716  	}
  1717  	// Transaction not found, or not a participant in the private transaction, return as such
  1718  	if tx == nil {
  1719  		return nil, errors.New("private transaction not found for this participant")
  1720  	}
  1721  
  1722  	// get receipt for the privacy marker transaction
  1723  	receipts, err := s.b.GetReceipts(ctx, blockHash)
  1724  	if err != nil {
  1725  		return nil, err
  1726  	}
  1727  	if len(receipts) <= int(index) {
  1728  		return nil, errors.New("could not find receipt for private transaction")
  1729  	}
  1730  	pmtReceipt := receipts[index]
  1731  
  1732  	// now extract the receipt for the private transaction
  1733  	psm, err := s.b.PSMR().ResolveForUserContext(ctx)
  1734  	if err != nil {
  1735  		return nil, err
  1736  	}
  1737  	receipt := pmtReceipt.PSReceipts[psm.ID]
  1738  	if receipt == nil {
  1739  		return nil, errors.New("could not find receipt for private transaction")
  1740  	}
  1741  
  1742  	return getTransactionReceiptCommonCode(tx, blockHash, blockNumber, hash, index, receipt)
  1743  }
  1744  
  1745  // Quorum: if signing a private TX, set with tx.SetPrivate() before calling this method.
  1746  // sign is a helper function that signs a transaction with the private key of the given address.
  1747  func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) {
  1748  	// Look up the wallet containing the requested signer
  1749  	account := accounts.Account{Address: addr}
  1750  
  1751  	wallet, err := s.b.AccountManager().Find(account)
  1752  	if err != nil {
  1753  		return nil, err
  1754  	}
  1755  
  1756  	// Quorum
  1757  	var chainID *big.Int
  1758  	if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) && !tx.IsPrivate() {
  1759  		chainID = config.ChainID
  1760  	}
  1761  	// /Quorum
  1762  
  1763  	// Request the wallet to sign the transaction
  1764  	return wallet.SignTx(account, tx, chainID)
  1765  }
  1766  
  1767  // SendTxArgs represents the arguments to sumbit a new transaction into the transaction pool.
  1768  // Quorum: introducing additional arguments encapsulated in PrivateTxArgs struct
  1769  //		   to support private transactions processing.
  1770  type SendTxArgs struct {
  1771  	PrivateTxArgs // Quorum
  1772  
  1773  	From     common.Address  `json:"from"`
  1774  	To       *common.Address `json:"to"`
  1775  	Gas      *hexutil.Uint64 `json:"gas"`
  1776  	GasPrice *hexutil.Big    `json:"gasPrice"`
  1777  	Value    *hexutil.Big    `json:"value"`
  1778  	Nonce    *hexutil.Uint64 `json:"nonce"`
  1779  	// We accept "data" and "input" for backwards-compatibility reasons. "input" is the
  1780  	// newer name and should be preferred by clients.
  1781  	Data  *hexutil.Bytes `json:"data"`
  1782  	Input *hexutil.Bytes `json:"input"`
  1783  }
  1784  
  1785  func (s SendTxArgs) IsPrivate() bool {
  1786  	return s.PrivateFor != nil
  1787  }
  1788  
  1789  // SendRawTxArgs represents the arguments to submit a new signed private transaction into the transaction pool.
  1790  type SendRawTxArgs struct {
  1791  	PrivateTxArgs
  1792  }
  1793  
  1794  // Additional arguments used in private transactions
  1795  type PrivateTxArgs struct {
  1796  	// PrivateFrom is the public key of the sending party.
  1797  	// The public key must be available in the Private Transaction Manager (i.e.: Tessera) which is paired with this geth node.
  1798  	// Empty value means the Private Transaction Manager will use the first public key
  1799  	// in its list of available keys which it maintains.
  1800  	PrivateFrom string `json:"privateFrom"`
  1801  	// PrivateFor is the list of public keys which are available in the Private Transaction Managers in the network.
  1802  	// The transaction payload is only visible to those party to the transaction.
  1803  	PrivateFor          []string               `json:"privateFor"`
  1804  	PrivateTxType       string                 `json:"restriction"`
  1805  	PrivacyFlag         engine.PrivacyFlagType `json:"privacyFlag"`
  1806  	MandatoryRecipients []string               `json:"mandatoryFor"`
  1807  }
  1808  
  1809  func (args *PrivateTxArgs) SetDefaultPrivateFrom(ctx context.Context, b Backend) error {
  1810  	if args.PrivateFor != nil && len(args.PrivateFrom) == 0 && b.ChainConfig().IsMPS {
  1811  		psm, err := b.PSMR().ResolveForUserContext(ctx)
  1812  		if err != nil {
  1813  			return err
  1814  		}
  1815  		args.PrivateFrom = psm.Addresses[0]
  1816  	}
  1817  	return nil
  1818  }
  1819  
  1820  func (args *PrivateTxArgs) SetRawTransactionPrivateFrom(ctx context.Context, b Backend, tx *types.Transaction) error {
  1821  	if args.PrivateFor != nil && b.ChainConfig().IsMPS {
  1822  		hash := common.BytesToEncryptedPayloadHash(tx.Data())
  1823  		_, retrievedPrivateFrom, _, err := private.P.ReceiveRaw(hash)
  1824  		if err != nil {
  1825  			return err
  1826  		}
  1827  		if len(args.PrivateFrom) == 0 {
  1828  			args.PrivateFrom = retrievedPrivateFrom
  1829  		}
  1830  		if args.PrivateFrom != retrievedPrivateFrom {
  1831  			return fmt.Errorf("The PrivateFrom address retrieved from the privacy manager does not match private PrivateFrom (%s) specified in transaction arguments.", args.PrivateFrom)
  1832  		}
  1833  		psm, err := b.PSMR().ResolveForUserContext(ctx)
  1834  		if err != nil {
  1835  			return err
  1836  		}
  1837  		if psm.NotIncludeAny(args.PrivateFrom) {
  1838  			return fmt.Errorf("The PrivateFrom address does not match the specified private state (%s)", psm.ID)
  1839  		}
  1840  	}
  1841  	return nil
  1842  }
  1843  
  1844  // setDefaults is a helper function that fills in default values for unspecified tx fields.
  1845  func (args *SendTxArgs) setDefaults(ctx context.Context, b Backend) error {
  1846  	if args.GasPrice == nil {
  1847  		price, err := b.SuggestPrice(ctx)
  1848  		if err != nil {
  1849  			return err
  1850  		}
  1851  		args.GasPrice = (*hexutil.Big)(price)
  1852  	}
  1853  	if args.Value == nil {
  1854  		args.Value = new(hexutil.Big)
  1855  	}
  1856  	if args.Nonce == nil {
  1857  		nonce, err := b.GetPoolNonce(ctx, args.From)
  1858  		if err != nil {
  1859  			return err
  1860  		}
  1861  		args.Nonce = (*hexutil.Uint64)(&nonce)
  1862  	}
  1863  	if args.Data != nil && args.Input != nil && !bytes.Equal(*args.Data, *args.Input) {
  1864  		return errors.New(`both "data" and "input" are set and not equal. Please use "input" to pass transaction call data`)
  1865  	}
  1866  	if args.To == nil {
  1867  		// Contract creation
  1868  		var input []byte
  1869  		if args.Data != nil {
  1870  			input = *args.Data
  1871  		} else if args.Input != nil {
  1872  			input = *args.Input
  1873  		}
  1874  		if len(input) == 0 {
  1875  			return errors.New(`contract creation without any data provided`)
  1876  		}
  1877  	}
  1878  	// Estimate the gas usage if necessary.
  1879  	if args.Gas == nil {
  1880  		// For backwards-compatibility reason, we try both input and data
  1881  		// but input is preferred.
  1882  		input := args.Input
  1883  		if input == nil {
  1884  			input = args.Data
  1885  		}
  1886  		callArgs := CallArgs{
  1887  			From:     &args.From, // From shouldn't be nil
  1888  			To:       args.To,
  1889  			GasPrice: args.GasPrice,
  1890  			Value:    args.Value,
  1891  			Data:     input,
  1892  		}
  1893  		pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
  1894  		estimated, err := DoEstimateGas(ctx, b, callArgs, pendingBlockNr, b.RPCGasCap())
  1895  		if err != nil {
  1896  			return err
  1897  		}
  1898  		args.Gas = &estimated
  1899  		log.Trace("Estimate gas usage automatically", "gas", args.Gas)
  1900  	}
  1901  	//Quorum
  1902  	if args.PrivateTxType == "" {
  1903  		args.PrivateTxType = "restricted"
  1904  	}
  1905  	return args.SetDefaultPrivateFrom(ctx, b)
  1906  	//End-Quorum
  1907  }
  1908  
  1909  func (args *SendTxArgs) inputOrData() (result []byte) {
  1910  	// TODO - check if input (instead of data) is provided whether private transactions are successful
  1911  	if args.Input != nil {
  1912  		result = *args.Input
  1913  	} else if args.Data != nil {
  1914  		result = *args.Data
  1915  	}
  1916  	return result
  1917  }
  1918  
  1919  func (args *SendTxArgs) toTransaction() *types.Transaction {
  1920  	if args.To == nil {
  1921  		return types.NewContractCreation(uint64(*args.Nonce), (*big.Int)(args.Value), uint64(*args.Gas), (*big.Int)(args.GasPrice), args.inputOrData())
  1922  	}
  1923  	return types.NewTransaction(uint64(*args.Nonce), *args.To, (*big.Int)(args.Value), uint64(*args.Gas), (*big.Int)(args.GasPrice), args.inputOrData())
  1924  }
  1925  
  1926  // TODO: this submits a signed transaction, if it is a signed private transaction that should already be recorded in the tx.
  1927  // SubmitTransaction is a helper function that submits tx to txPool and logs a message.
  1928  // TODO:这会提交一个签名交易,如果它是一个签名的私人交易,应该已经记录在 tx 中。
  1929  // SubmitTransaction 是一个辅助函数,用于将 tx 提交到 txPool 并记录一条消息。
  1930  func SubmitTransaction(ctx context.Context, b Backend, tx *types.Transaction, privateFrom string, isRaw bool) (common.Hash, error) {
  1931  	// If the transaction fee cap is already specified, ensure the
  1932  	// fee of the given transaction is _reasonable_.
  1933  	if err := checkTxFee(tx.GasPrice(), tx.Gas(), b.RPCTxFeeCap()); err != nil {
  1934  		return common.Hash{}, err
  1935  	}
  1936  	// Quorum
  1937  	var signer types.Signer
  1938  	if tx.IsPrivate() {
  1939  		signer = types.QuorumPrivateTxSigner{}
  1940  	} else {
  1941  		signer = types.MakeSigner(b.ChainConfig(), b.CurrentBlock().Number())
  1942  	}
  1943  	from, err := types.Sender(signer, tx)
  1944  	if err != nil {
  1945  		return common.Hash{}, err
  1946  	}
  1947  	// Quorum
  1948  	// Need to do authorization check for Ethereum Account being used in signing.
  1949  	// We only care about private transactions (or the private transaction relating to a privacy marker)
  1950  	if token, ok := b.SupportsMultitenancy(ctx); ok {
  1951  		tx := tx
  1952  		// If we are sending a Privacy Marker Transaction, then get the private txn details
  1953  		if tx.IsPrivacyMarker() {
  1954  			tx, _, _, err = private.FetchPrivateTransaction(tx.Data())
  1955  			if err != nil {
  1956  				return common.Hash{}, err
  1957  			}
  1958  		}
  1959  		innerFrom, err := types.Sender(signer, tx)
  1960  		if err != nil {
  1961  			return common.Hash{}, err
  1962  		}
  1963  
  1964  		if tx.IsPrivate() {
  1965  			psm, err := b.PSMR().ResolveForUserContext(ctx)
  1966  			if err != nil {
  1967  				return common.Hash{}, err
  1968  			}
  1969  			eoaSecAttr := (&multitenancy.PrivateStateSecurityAttribute{}).WithPSI(psm.ID).WithSelfEOAIf(isRaw, innerFrom)
  1970  			psm, err = b.PSMR().ResolveForManagedParty(privateFrom)
  1971  			if err != nil {
  1972  				return common.Hash{}, err
  1973  			}
  1974  			privateFromSecAttr := (&multitenancy.PrivateStateSecurityAttribute{}).WithPSI(psm.ID).WithSelfEOAIf(isRaw, innerFrom)
  1975  			if isAuthorized, _ := multitenancy.IsAuthorized(token, eoaSecAttr, privateFromSecAttr); !isAuthorized {
  1976  				return common.Hash{}, multitenancy.ErrNotAuthorized
  1977  			}
  1978  		}
  1979  	}
  1980  	if err := b.SendTx(ctx, tx); err != nil {
  1981  		return common.Hash{}, err
  1982  	}
  1983  	if tx.To() == nil {
  1984  		addr := crypto.CreateAddress(from, tx.Nonce())
  1985  		log.Info("Submitted contract creation", "fullhash", tx.Hash().Hex(), "to", addr.Hex())
  1986  		log.EmitCheckpoint(log.TxCreated, "tx", tx.Hash().Hex(), "to", addr.Hex())
  1987  	} else {
  1988  		log.Info("Submitted transaction", "fullhash", tx.Hash().Hex(), "recipient", tx.To())
  1989  		log.EmitCheckpoint(log.TxCreated, "tx", tx.Hash().Hex(), "to", tx.To().Hex())
  1990  	}
  1991  	return tx.Hash(), nil
  1992  
  1993  }
  1994  
  1995  // runSimulation runs a simulation of the given transaction.
  1996  // It returns the EVM instance upon completion
  1997  // runSimulation 运行给定事务的模拟。
  1998  // 完成后返回 EVM 实例
  1999  func runSimulation(ctx context.Context, b Backend, from common.Address, tx *types.Transaction) (*vm.EVM, error) {
  2000  	defer func(start time.Time) {
  2001  		log.Debug("Simulated Execution EVM call finished", "runtime", time.Since(start))
  2002  	}(time.Now())
  2003  
  2004  	// Set sender address or use a default if none specified
  2005  	addr := from
  2006  	if addr == (common.Address{}) {
  2007  		if wallets := b.AccountManager().Wallets(); len(wallets) > 0 {
  2008  			if accountList := wallets[0].Accounts(); len(accountList) > 0 {
  2009  				addr = accountList[0].Address
  2010  			}
  2011  		}
  2012  	}
  2013  
  2014  	// Create new call message
  2015  	msg := types.NewMessage(addr, tx.To(), tx.Nonce(), tx.Value(), tx.Gas(), tx.GasPrice(), tx.Data(), false)
  2016  
  2017  	// Setup context with timeout as gas un-metered
  2018  	var cancel context.CancelFunc
  2019  	ctx, cancel = context.WithTimeout(ctx, time.Second*5)
  2020  	// Make sure the context is cancelled when the call has completed
  2021  	// this makes sure resources are cleaned up.
  2022  	// 确保在调用完成时取消上下文
  2023  	// 这确保资源被清理。
  2024  	defer func() { cancel() }()
  2025  
  2026  	// Get a new instance of the EVM.
  2027  	blockNumber := b.CurrentBlock().Number().Uint64()
  2028  	stateAtBlock, header, err := b.StateAndHeaderByNumber(ctx, rpc.BlockNumber(blockNumber))
  2029  	if stateAtBlock == nil || err != nil {
  2030  		return nil, err
  2031  	}
  2032  	evm, _, err := b.GetEVM(ctx, msg, stateAtBlock, header)
  2033  	if err != nil {
  2034  		return nil, err
  2035  	}
  2036  
  2037  	// Wait for the context to be done and cancel the evm. Even if the
  2038  	// EVM has finished, cancelling may be done (repeatedly)
  2039  	// 等待上下文完成并取消 evm。 即使
  2040  	// EVM 已经完成,可以取消(重复)
  2041  	go func() {
  2042  		<-ctx.Done()
  2043  		evm.Cancel()
  2044  	}()
  2045  
  2046  	var contractAddr common.Address
  2047  
  2048  	// even the creation of a contract (init code) can invoke other contracts
  2049  	if tx.To() != nil {
  2050  		// removed contract availability checks as they are performed in checkAndHandlePrivateTransaction
  2051  		_, _, err = evm.Call(vm.AccountRef(addr), *tx.To(), tx.Data(), tx.Gas(), tx.Value())
  2052  	} else {
  2053  		_, contractAddr, _, err = evm.Create(vm.AccountRef(addr), tx.Data(), tx.Gas(), tx.Value())
  2054  		//make sure that nonce is same in simulation as in actual block processing
  2055  		//simulation blockNumber will be behind block processing blockNumber by at least 1
  2056  		//only guaranteed to work for default config where EIP158=1
  2057  		if evm.ChainConfig().IsEIP158(big.NewInt(evm.Context.BlockNumber.Int64() + 1)) {
  2058  			evm.StateDB.SetNonce(contractAddr, 1)
  2059  		}
  2060  	}
  2061  	return evm, err
  2062  }
  2063  
  2064  // SendTransaction creates a transaction for the given argument, sign it and submit it to the
  2065  // transaction pool.
  2066  func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error) {
  2067  	// Look up the wallet containing the requested signer
  2068  	account := accounts.Account{Address: args.From}
  2069  
  2070  	wallet, err := s.b.AccountManager().Find(account)
  2071  	if err != nil {
  2072  		return common.Hash{}, err
  2073  	}
  2074  
  2075  	if args.Nonce == nil {
  2076  		// Hold the addresse's mutex around signing to prevent concurrent assignment of
  2077  		// the same nonce to multiple accounts.
  2078  		// 在签名周围保留地址的互斥锁以防止并发分配
  2079  		// 对多个帐户使用相同的随机数。
  2080  		s.nonceLock.LockAddr(args.From)
  2081  		defer s.nonceLock.UnlockAddr(args.From)
  2082  	}
  2083  
  2084  	// Set some sanity defaults and terminate on failure
  2085  	// 设置一些健全的默认值并在失败时终止
  2086  	if err := args.setDefaults(ctx, s.b); err != nil {
  2087  		return common.Hash{}, err
  2088  	}
  2089  
  2090  	_, replaceDataWithHash, data, err := checkAndHandlePrivateTransaction(ctx, s.b, args.toTransaction(), &args.PrivateTxArgs, args.From, NormalTransaction)
  2091  	if err != nil {
  2092  		return common.Hash{}, err
  2093  	}
  2094  	if replaceDataWithHash {
  2095  		// replace the original payload with encrypted payload hash
  2096  		args.Data = data.BytesTypeRef()
  2097  	}
  2098  	// /Quorum
  2099  
  2100  	// Assemble the transaction and sign with the wallet
  2101  	tx := args.toTransaction()
  2102  
  2103  	// Quorum
  2104  	if args.IsPrivate() {
  2105  		tx.SetPrivate()
  2106  	}
  2107  	// /Quorum
  2108  
  2109  	// Quorum
  2110  	var chainID *big.Int
  2111  	if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) && !tx.IsPrivate() {
  2112  		chainID = config.ChainID
  2113  	}
  2114  	// /Quorum
  2115  
  2116  	signed, err := wallet.SignTx(account, tx, chainID)
  2117  	if err != nil {
  2118  		return common.Hash{}, err
  2119  	}
  2120  
  2121  	// Quorum
  2122  	if signed.IsPrivate() && s.b.IsPrivacyMarkerTransactionCreationEnabled() {
  2123  		pmt, err := createPrivacyMarkerTransaction(s.b, signed, &args.PrivateTxArgs)
  2124  		if err != nil {
  2125  			log.Warn("Failed to create privacy marker transaction for private transaction", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err)
  2126  			return common.Hash{}, err
  2127  		}
  2128  
  2129  		var pmtChainID *big.Int // PMT is public so will have different chainID used in signing compared to the internal tx
  2130  		if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) {
  2131  			pmtChainID = config.ChainID
  2132  		}
  2133  
  2134  		signed, err = wallet.SignTx(account, pmt, pmtChainID)
  2135  		if err != nil {
  2136  			log.Warn("Failed to sign privacy marker transaction for private transaction", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err)
  2137  			return common.Hash{}, err
  2138  		}
  2139  	}
  2140  	// /Quorum
  2141  
  2142  	return SubmitTransaction(ctx, s.b, signed, args.PrivateFrom, false)
  2143  }
  2144  
  2145  // FillTransaction fills the defaults (nonce, gas, gasPrice) on a given unsigned transaction,
  2146  // and returns it to the caller for further processing (signing + broadcast)
  2147  func (s *PublicTransactionPoolAPI) FillTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) {
  2148  	// Set some sanity defaults and terminate on failure
  2149  	if err := args.setDefaults(ctx, s.b); err != nil {
  2150  		return nil, err
  2151  	}
  2152  	// Assemble the transaction and obtain rlp
  2153  	// Quorum
  2154  	isPrivate, replaceDataWithHash, hash, err := checkAndHandlePrivateTransaction(ctx, s.b, args.toTransaction(), &args.PrivateTxArgs, args.From, FillTransaction)
  2155  	if err != nil {
  2156  		return nil, err
  2157  	}
  2158  	if replaceDataWithHash {
  2159  		// replace the original payload with encrypted payload hash
  2160  		args.Data = hash.BytesTypeRef()
  2161  	}
  2162  	// /Quorum
  2163  
  2164  	tx := args.toTransaction()
  2165  
  2166  	// Quorum
  2167  	if isPrivate {
  2168  		tx.SetPrivate()
  2169  	}
  2170  	// /Quorum
  2171  
  2172  	data, err := rlp.EncodeToBytes(tx)
  2173  	if err != nil {
  2174  		return nil, err
  2175  	}
  2176  	return &SignTransactionResult{data, tx}, nil
  2177  }
  2178  
  2179  // SendRawTransaction will add the signed transaction to the transaction pool.
  2180  // The sender is responsible for signing the transaction and using the correct nonce.
  2181  func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, encodedTx hexutil.Bytes) (common.Hash, error) {
  2182  	tx := new(types.Transaction)
  2183  	if err := rlp.DecodeBytes(encodedTx, tx); err != nil {
  2184  		return common.Hash{}, err
  2185  	}
  2186  	return SubmitTransaction(ctx, s.b, tx, "", true)
  2187  }
  2188  
  2189  // Quorum
  2190  //
  2191  // SendRawPrivateTransaction will add the signed transaction to the transaction pool.
  2192  // The sender is responsible for signing the transaction and using the correct nonce.
  2193  func (s *PublicTransactionPoolAPI) SendRawPrivateTransaction(ctx context.Context, encodedTx hexutil.Bytes, args SendRawTxArgs) (common.Hash, error) {
  2194  
  2195  	tx := new(types.Transaction)
  2196  	if err := rlp.DecodeBytes(encodedTx, tx); err != nil {
  2197  		return common.Hash{}, err
  2198  	}
  2199  
  2200  	// Quorum
  2201  	if err := args.SetRawTransactionPrivateFrom(ctx, s.b, tx); err != nil {
  2202  		return common.Hash{}, err
  2203  	}
  2204  	isPrivate, _, _, err := checkAndHandlePrivateTransaction(ctx, s.b, tx, &args.PrivateTxArgs, common.Address{}, RawTransaction)
  2205  	if err != nil {
  2206  		return common.Hash{}, err
  2207  	}
  2208  	if !isPrivate {
  2209  		return common.Hash{}, fmt.Errorf("transaction is not private")
  2210  	}
  2211  
  2212  	return SubmitTransaction(ctx, s.b, tx, args.PrivateFrom, true)
  2213  }
  2214  
  2215  // DistributePrivateTransaction will perform the simulation checks and send the private transactions data to the other
  2216  // private participants
  2217  // It then submits the entire private transaction to the attached PTM and sends it to other private participants,
  2218  // return the PTM generated hash, intended to be used in the Input field of a Privacy Marker Transaction
  2219  func (s *PublicTransactionPoolAPI) DistributePrivateTransaction(ctx context.Context, encodedTx hexutil.Bytes, args SendRawTxArgs) (string, error) {
  2220  	log.Info("distributing raw private tx")
  2221  
  2222  	tx := new(types.Transaction)
  2223  	if err := rlp.DecodeBytes(encodedTx, tx); err != nil {
  2224  		return "", err
  2225  	}
  2226  
  2227  	log.Debug("deserialised raw private tx", "hash", tx.Hash())
  2228  
  2229  	// Quorum
  2230  	if err := args.SetRawTransactionPrivateFrom(ctx, s.b, tx); err != nil {
  2231  		return "", err
  2232  	}
  2233  	isPrivate, _, _, err := checkAndHandlePrivateTransaction(ctx, s.b, tx, &args.PrivateTxArgs, common.Address{}, RawTransaction)
  2234  	if err != nil {
  2235  		return "", err
  2236  	}
  2237  	if !isPrivate {
  2238  		return "", fmt.Errorf("transaction is not private")
  2239  	}
  2240  
  2241  	serialisedTx, err := json.Marshal(tx)
  2242  	if err != nil {
  2243  		return "", err
  2244  	}
  2245  
  2246  	_, _, txnHash, err := private.P.Send(serialisedTx, args.PrivateFrom, args.PrivateFor, &engine.ExtraMetadata{})
  2247  	if err != nil {
  2248  		return "", err
  2249  	}
  2250  	log.Debug("private transaction sent to PTM", "generated ptm-hash", txnHash)
  2251  	return txnHash.Hex(), nil
  2252  }
  2253  
  2254  // /Quorum
  2255  
  2256  // Sign calculates an ECDSA signature for:
  2257  // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message).
  2258  //
  2259  // Note, the produced signature conforms to the secp256k1 curve R, S and V values,
  2260  // where the V value will be 27 or 28 for legacy reasons.
  2261  //
  2262  // The account associated with addr must be unlocked.
  2263  //
  2264  // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
  2265  func (s *PublicTransactionPoolAPI) Sign(addr common.Address, data hexutil.Bytes) (hexutil.Bytes, error) {
  2266  	// Look up the wallet containing the requested signer
  2267  	account := accounts.Account{Address: addr}
  2268  
  2269  	wallet, err := s.b.AccountManager().Find(account)
  2270  	if err != nil {
  2271  		return nil, err
  2272  	}
  2273  	// Sign the requested hash with the wallet
  2274  	signature, err := wallet.SignText(account, data)
  2275  	if err == nil {
  2276  		signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper
  2277  	}
  2278  	return signature, err
  2279  }
  2280  
  2281  // SignTransactionResult represents a RLP encoded signed transaction.
  2282  type SignTransactionResult struct {
  2283  	Raw hexutil.Bytes      `json:"raw"`
  2284  	Tx  *types.Transaction `json:"tx"`
  2285  }
  2286  
  2287  // SignTransaction will sign the given transaction with the from account.
  2288  // The node needs to have the private key of the account corresponding with
  2289  // the given from address and it needs to be unlocked.
  2290  func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) {
  2291  	if args.Gas == nil {
  2292  		return nil, fmt.Errorf("gas not specified")
  2293  	}
  2294  	if args.GasPrice == nil {
  2295  		return nil, fmt.Errorf("gasPrice not specified")
  2296  	}
  2297  	if args.Nonce == nil {
  2298  		return nil, fmt.Errorf("nonce not specified")
  2299  	}
  2300  	// Quorum
  2301  	// setDefaults calls DoEstimateGas in ethereum1.9.0, private transaction is not supported for that feature
  2302  	// set gas to constant if nil
  2303  	if args.IsPrivate() && args.Gas == nil {
  2304  		gas := (hexutil.Uint64)(90000)
  2305  		args.Gas = &gas
  2306  	}
  2307  	// End Quorum
  2308  
  2309  	if err := args.setDefaults(ctx, s.b); err != nil {
  2310  		return nil, err
  2311  	}
  2312  	if err := checkTxFee(args.GasPrice.ToInt(), uint64(*args.Gas), s.b.RPCTxFeeCap()); err != nil {
  2313  		return nil, err
  2314  	}
  2315  
  2316  	// Quorum
  2317  	toSign := args.toTransaction()
  2318  	if args.IsPrivate() {
  2319  		toSign.SetPrivate()
  2320  	}
  2321  	// End Quorum
  2322  
  2323  	tx, err := s.sign(args.From, toSign)
  2324  	if err != nil {
  2325  		return nil, err
  2326  	}
  2327  	data, err := rlp.EncodeToBytes(tx)
  2328  	if err != nil {
  2329  		return nil, err
  2330  	}
  2331  	return &SignTransactionResult{data, tx}, nil
  2332  }
  2333  
  2334  // PendingTransactions returns the transactions that are in the transaction pool
  2335  // and have a from address that is one of the accounts this node manages.
  2336  func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error) {
  2337  	pending, err := s.b.GetPoolTransactions()
  2338  	if err != nil {
  2339  		return nil, err
  2340  	}
  2341  	accounts := make(map[common.Address]struct{})
  2342  	for _, wallet := range s.b.AccountManager().Wallets() {
  2343  		for _, account := range wallet.Accounts() {
  2344  			accounts[account.Address] = struct{}{}
  2345  		}
  2346  	}
  2347  	transactions := make([]*RPCTransaction, 0, len(pending))
  2348  	for _, tx := range pending {
  2349  		var signer types.Signer = types.HomesteadSigner{}
  2350  		if tx.Protected() && !tx.IsPrivate() {
  2351  			signer = types.NewEIP155Signer(tx.ChainId())
  2352  		}
  2353  		from, _ := types.Sender(signer, tx)
  2354  		if _, exists := accounts[from]; exists {
  2355  			transactions = append(transactions, newRPCPendingTransaction(tx))
  2356  		}
  2357  	}
  2358  	return transactions, nil
  2359  }
  2360  
  2361  // Resend accepts an existing transaction and a new gas price and limit. It will remove
  2362  // the given transaction from the pool and reinsert it with the new gas price and limit.
  2363  func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs SendTxArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) {
  2364  	if sendArgs.Nonce == nil {
  2365  		return common.Hash{}, fmt.Errorf("missing transaction nonce in transaction spec")
  2366  	}
  2367  	// setDefaults calls DoEstimateGas in ethereum1.9.0, private transaction is not supported for that feature
  2368  	// set gas to constant if nil
  2369  	if sendArgs.IsPrivate() && sendArgs.Gas == nil {
  2370  		gas := (hexutil.Uint64)(90000)
  2371  		sendArgs.Gas = &gas
  2372  	}
  2373  	if err := sendArgs.setDefaults(ctx, s.b); err != nil {
  2374  		return common.Hash{}, err
  2375  	}
  2376  	matchTx := sendArgs.toTransaction()
  2377  
  2378  	// Before replacing the old transaction, ensure the _new_ transaction fee is reasonable.
  2379  	var price = matchTx.GasPrice()
  2380  	if gasPrice != nil {
  2381  		price = gasPrice.ToInt()
  2382  	}
  2383  	var gas = matchTx.Gas()
  2384  	if gasLimit != nil {
  2385  		gas = uint64(*gasLimit)
  2386  	}
  2387  	if err := checkTxFee(price, gas, s.b.RPCTxFeeCap()); err != nil {
  2388  		return common.Hash{}, err
  2389  	}
  2390  	// Iterate the pending list for replacement
  2391  	pending, err := s.b.GetPoolTransactions()
  2392  	if err != nil {
  2393  		return common.Hash{}, err
  2394  	}
  2395  	for _, p := range pending {
  2396  		var signer types.Signer = types.HomesteadSigner{}
  2397  		if p.IsPrivate() {
  2398  			signer = types.QuorumPrivateTxSigner{}
  2399  		} else if p.Protected() {
  2400  			signer = types.NewEIP155Signer(p.ChainId())
  2401  		}
  2402  		wantSigHash := signer.Hash(matchTx)
  2403  
  2404  		if pFrom, err := types.Sender(signer, p); err == nil && pFrom == sendArgs.From && signer.Hash(p) == wantSigHash {
  2405  			// Match. Re-sign and send the transaction.
  2406  			if gasPrice != nil && (*big.Int)(gasPrice).Sign() != 0 {
  2407  				sendArgs.GasPrice = gasPrice
  2408  			}
  2409  			if gasLimit != nil && *gasLimit != 0 {
  2410  				sendArgs.Gas = gasLimit
  2411  			}
  2412  			newTx := sendArgs.toTransaction()
  2413  			// set v param to 37 to indicate private tx before submitting to the signer.
  2414  			if sendArgs.IsPrivate() {
  2415  				newTx.SetPrivate()
  2416  			}
  2417  			signedTx, err := s.sign(sendArgs.From, newTx)
  2418  			if err != nil {
  2419  				return common.Hash{}, err
  2420  			}
  2421  			if err = s.b.SendTx(ctx, signedTx); err != nil {
  2422  				return common.Hash{}, err
  2423  			}
  2424  			return signedTx.Hash(), nil
  2425  		}
  2426  	}
  2427  
  2428  	return common.Hash{}, fmt.Errorf("transaction %#x not found", matchTx.Hash())
  2429  }
  2430  
  2431  // PublicDebugAPI is the collection of Ethereum APIs exposed over the public
  2432  // debugging endpoint.
  2433  type PublicDebugAPI struct {
  2434  	b Backend
  2435  }
  2436  
  2437  // NewPublicDebugAPI creates a new API definition for the public debug methods
  2438  // of the Ethereum service.
  2439  func NewPublicDebugAPI(b Backend) *PublicDebugAPI {
  2440  	return &PublicDebugAPI{b: b}
  2441  }
  2442  
  2443  // GetBlockRlp retrieves the RLP encoded for of a single block.
  2444  func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error) {
  2445  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  2446  	if block == nil {
  2447  		return "", fmt.Errorf("block #%d not found", number)
  2448  	}
  2449  	encoded, err := rlp.EncodeToBytes(block)
  2450  	if err != nil {
  2451  		return "", err
  2452  	}
  2453  	return fmt.Sprintf("%x", encoded), nil
  2454  }
  2455  
  2456  // TestSignCliqueBlock fetches the given block number, and attempts to sign it as a clique header with the
  2457  // given address, returning the address of the recovered signature
  2458  //
  2459  // This is a temporary method to debug the externalsigner integration,
  2460  // TODO: Remove this method when the integration is mature
  2461  func (api *PublicDebugAPI) TestSignCliqueBlock(ctx context.Context, address common.Address, number uint64) (common.Address, error) {
  2462  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  2463  	if block == nil {
  2464  		return common.Address{}, fmt.Errorf("block #%d not found", number)
  2465  	}
  2466  	header := block.Header()
  2467  	header.Extra = make([]byte, 32+65)
  2468  	encoded := clique.CliqueRLP(header)
  2469  
  2470  	// Look up the wallet containing the requested signer
  2471  	account := accounts.Account{Address: address}
  2472  	wallet, err := api.b.AccountManager().Find(account)
  2473  	if err != nil {
  2474  		return common.Address{}, err
  2475  	}
  2476  
  2477  	signature, err := wallet.SignData(account, accounts.MimetypeClique, encoded)
  2478  	if err != nil {
  2479  		return common.Address{}, err
  2480  	}
  2481  	sealHash := clique.SealHash(header).Bytes()
  2482  	log.Info("test signing of clique block",
  2483  		"Sealhash", fmt.Sprintf("%x", sealHash),
  2484  		"signature", fmt.Sprintf("%x", signature))
  2485  	pubkey, err := crypto.Ecrecover(sealHash, signature)
  2486  	if err != nil {
  2487  		return common.Address{}, err
  2488  	}
  2489  	var signer common.Address
  2490  	copy(signer[:], crypto.Keccak256(pubkey[1:])[12:])
  2491  
  2492  	return signer, nil
  2493  }
  2494  
  2495  // PrintBlock retrieves a block and returns its pretty printed form.
  2496  func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) {
  2497  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  2498  	if block == nil {
  2499  		return "", fmt.Errorf("block #%d not found", number)
  2500  	}
  2501  	return spew.Sdump(block), nil
  2502  }
  2503  
  2504  // SeedHash retrieves the seed hash of a block.
  2505  func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) {
  2506  	block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number))
  2507  	if block == nil {
  2508  		return "", fmt.Errorf("block #%d not found", number)
  2509  	}
  2510  	return fmt.Sprintf("0x%x", ethash.SeedHash(number)), nil
  2511  }
  2512  
  2513  // PrivateDebugAPI is the collection of Ethereum APIs exposed over the private
  2514  // debugging endpoint.
  2515  type PrivateDebugAPI struct {
  2516  	b Backend
  2517  }
  2518  
  2519  // NewPrivateDebugAPI creates a new API definition for the private debug methods
  2520  // of the Ethereum service.
  2521  func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI {
  2522  	return &PrivateDebugAPI{b: b}
  2523  }
  2524  
  2525  // ChaindbProperty returns leveldb properties of the key-value database.
  2526  func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) {
  2527  	if property == "" {
  2528  		property = "leveldb.stats"
  2529  	} else if !strings.HasPrefix(property, "leveldb.") {
  2530  		property = "leveldb." + property
  2531  	}
  2532  	return api.b.ChainDb().Stat(property)
  2533  }
  2534  
  2535  // ChaindbCompact flattens the entire key-value database into a single level,
  2536  // removing all unused slots and merging all keys.
  2537  func (api *PrivateDebugAPI) ChaindbCompact() error {
  2538  	for b := byte(0); b < 255; b++ {
  2539  		log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1))
  2540  		if err := api.b.ChainDb().Compact([]byte{b}, []byte{b + 1}); err != nil {
  2541  			log.Error("Database compaction failed", "err", err)
  2542  			return err
  2543  		}
  2544  	}
  2545  	return nil
  2546  }
  2547  
  2548  // SetHead rewinds the head of the blockchain to a previous block.
  2549  func (api *PrivateDebugAPI) SetHead(number hexutil.Uint64) {
  2550  	api.b.SetHead(uint64(number))
  2551  }
  2552  
  2553  // PublicNetAPI offers network related RPC methods
  2554  type PublicNetAPI struct {
  2555  	net            *p2p.Server
  2556  	networkVersion uint64
  2557  }
  2558  
  2559  // NewPublicNetAPI creates a new net API instance.
  2560  func NewPublicNetAPI(net *p2p.Server, networkVersion uint64) *PublicNetAPI {
  2561  	return &PublicNetAPI{net, networkVersion}
  2562  }
  2563  
  2564  // Listening returns an indication if the node is listening for network connections.
  2565  func (s *PublicNetAPI) Listening() bool {
  2566  	return true // always listening
  2567  }
  2568  
  2569  // PeerCount returns the number of connected peers
  2570  func (s *PublicNetAPI) PeerCount() hexutil.Uint {
  2571  	return hexutil.Uint(s.net.PeerCount())
  2572  }
  2573  
  2574  // Version returns the current ethereum protocol version.
  2575  func (s *PublicNetAPI) Version() string {
  2576  	return fmt.Sprintf("%d", s.networkVersion)
  2577  }
  2578  
  2579  // checkTxFee is an internal function used to check whether the fee of
  2580  // the given transaction is _reasonable_(under the cap).
  2581  func checkTxFee(gasPrice *big.Int, gas uint64, cap float64) error {
  2582  	// Short circuit if there is no cap for transaction fee at all.
  2583  	if cap == 0 {
  2584  		return nil
  2585  	}
  2586  	feeEth := new(big.Float).Quo(new(big.Float).SetInt(new(big.Int).Mul(gasPrice, new(big.Int).SetUint64(gas))), new(big.Float).SetInt(big.NewInt(params.Ether)))
  2587  	feeFloat, _ := feeEth.Float64()
  2588  	if feeFloat > cap {
  2589  		return fmt.Errorf("tx fee (%.2f ether) exceeds the configured cap (%.2f ether)", feeFloat, cap)
  2590  	}
  2591  	return nil
  2592  }
  2593  
  2594  // toHexSlice creates a slice of hex-strings based on []byte.
  2595  func toHexSlice(b [][]byte) []string {
  2596  	r := make([]string, len(b))
  2597  	for i := range b {
  2598  		r[i] = hexutil.Encode(b[i])
  2599  	}
  2600  	return r
  2601  }
  2602  
  2603  // Quorum
  2604  // Please note: This is a temporary integration to improve performance in high-latency
  2605  // environments when sending many private transactions. It will be removed at a later
  2606  // date when account management is handled outside Ethereum.
  2607  
  2608  type AsyncSendTxArgs struct {
  2609  	SendTxArgs
  2610  	CallbackUrl string `json:"callbackUrl"`
  2611  }
  2612  
  2613  type AsyncResultSuccess struct {
  2614  	Id     string      `json:"id,omitempty"`
  2615  	TxHash common.Hash `json:"txHash"`
  2616  }
  2617  
  2618  type AsyncResultFailure struct {
  2619  	Id    string `json:"id,omitempty"`
  2620  	Error string `json:"error"`
  2621  }
  2622  
  2623  type Async struct {
  2624  	sync.Mutex
  2625  	sem chan struct{}
  2626  }
  2627  
  2628  func (s *PublicTransactionPoolAPI) send(ctx context.Context, asyncArgs AsyncSendTxArgs) {
  2629  
  2630  	txHash, err := s.SendTransaction(ctx, asyncArgs.SendTxArgs)
  2631  
  2632  	if asyncArgs.CallbackUrl != "" {
  2633  
  2634  		//don't need to nil check this since id is required for every geth rpc call
  2635  		//even though this is stated in the specification as an "optional" parameter
  2636  		jsonId := ctx.Value("id").(*json.RawMessage)
  2637  		id := string(*jsonId)
  2638  
  2639  		var resultResponse interface{}
  2640  		if err != nil {
  2641  			resultResponse = &AsyncResultFailure{Id: id, Error: err.Error()}
  2642  		} else {
  2643  			resultResponse = &AsyncResultSuccess{Id: id, TxHash: txHash}
  2644  		}
  2645  
  2646  		buf := new(bytes.Buffer)
  2647  		err := json.NewEncoder(buf).Encode(resultResponse)
  2648  		if err != nil {
  2649  			log.Info("Error encoding callback JSON", "err", err.Error())
  2650  			return
  2651  		}
  2652  		_, err = http.Post(asyncArgs.CallbackUrl, "application/json", buf)
  2653  		if err != nil {
  2654  			log.Info("Error sending callback", "err", err.Error())
  2655  			return
  2656  		}
  2657  	}
  2658  
  2659  }
  2660  
  2661  func newAsync(n int) *Async {
  2662  	a := &Async{
  2663  		sem: make(chan struct{}, n),
  2664  	}
  2665  	return a
  2666  }
  2667  
  2668  var async = newAsync(100)
  2669  
  2670  // SendTransactionAsync creates a transaction for the given argument, signs it, and
  2671  // submits it to the transaction pool. This call returns immediately to allow sending
  2672  // many private transactions/bursts of transactions without waiting for the recipient
  2673  // parties to confirm receipt of the encrypted payloads. An optional callbackUrl may
  2674  // be specified--when a transaction is submitted to the transaction pool, it will be
  2675  // called with a POST request containing either {"error": "error message"} or
  2676  // {"txHash": "0x..."}.
  2677  //
  2678  // Please note: This is a temporary integration to improve performance in high-latency
  2679  // environments when sending many private transactions. It will be removed at a later
  2680  // date when account management is handled outside Ethereum.
  2681  func (s *PublicTransactionPoolAPI) SendTransactionAsync(ctx context.Context, args AsyncSendTxArgs) (common.Hash, error) {
  2682  
  2683  	select {
  2684  	case async.sem <- struct{}{}:
  2685  		go func() {
  2686  			s.send(ctx, args)
  2687  			<-async.sem
  2688  		}()
  2689  		return common.Hash{}, nil
  2690  	default:
  2691  		return common.Hash{}, errors.New("too many concurrent requests")
  2692  	}
  2693  }
  2694  
  2695  // GetQuorumPayload returns the contents of a private transaction
  2696  func (s *PublicBlockChainAPI) GetQuorumPayload(ctx context.Context, digestHex string) (string, error) {
  2697  	if !private.IsQuorumPrivacyEnabled() {
  2698  		return "", fmt.Errorf("PrivateTransactionManager is not enabled")
  2699  	}
  2700  	psm, err := s.b.PSMR().ResolveForUserContext(ctx)
  2701  	if err != nil {
  2702  		return "", err
  2703  	}
  2704  	if len(digestHex) < 3 {
  2705  		return "", fmt.Errorf("Invalid digest hex")
  2706  	}
  2707  	if digestHex[:2] == "0x" {
  2708  		digestHex = digestHex[2:]
  2709  	}
  2710  	b, err := hex.DecodeString(digestHex)
  2711  	if err != nil {
  2712  		return "", err
  2713  	}
  2714  
  2715  	if len(b) != common.EncryptedPayloadHashLength {
  2716  		return "", fmt.Errorf("Expected a Quorum digest of length 64, but got %d", len(b))
  2717  	}
  2718  	_, managedParties, data, _, err := private.P.Receive(common.BytesToEncryptedPayloadHash(b))
  2719  	if err != nil {
  2720  		return "", err
  2721  	}
  2722  	if s.b.PSMR().NotIncludeAny(psm, managedParties...) {
  2723  		return "0x", nil
  2724  	}
  2725  	return fmt.Sprintf("0x%x", data), nil
  2726  }
  2727  
  2728  // Quorum
  2729  // for raw private transaction, privateTxArgs.privateFrom will be updated with value from Tessera when payload is retrieved
  2730  // 对于原始私有交易,当检索到有效负载时,privateTxArgs.privateFrom 将使用来自 Tessera 的值进行更新
  2731  func checkAndHandlePrivateTransaction(ctx context.Context, b Backend, tx *types.Transaction, privateTxArgs *PrivateTxArgs, from common.Address, txnType TransactionType) (isPrivate bool, replaceDataWithHash bool, hash common.EncryptedPayloadHash, err error) {
  2732  	replaceDataWithHash = false
  2733  	isPrivate = privateTxArgs != nil && privateTxArgs.PrivateFor != nil
  2734  	if !isPrivate {
  2735  		return
  2736  	}
  2737  
  2738  	if err = privateTxArgs.PrivacyFlag.Validate(); err != nil {
  2739  		return
  2740  	}
  2741  
  2742  	if !b.ChainConfig().IsPrivacyEnhancementsEnabled(b.CurrentBlock().Number()) && privateTxArgs.PrivacyFlag.IsNotStandardPrivate() {
  2743  		err = fmt.Errorf("PrivacyEnhancements are disabled. Can only accept transactions with PrivacyFlag=0(StandardPrivate).")
  2744  		return
  2745  	}
  2746  
  2747  	if engine.PrivacyFlagMandatoryRecipients == privateTxArgs.PrivacyFlag && len(privateTxArgs.MandatoryRecipients) == 0 {
  2748  		err = fmt.Errorf("missing mandatory recipients data. if no mandatory recipients required consider using PrivacyFlag=1(PartyProtection)")
  2749  		return
  2750  	}
  2751  
  2752  	if engine.PrivacyFlagMandatoryRecipients != privateTxArgs.PrivacyFlag && len(privateTxArgs.MandatoryRecipients) > 0 {
  2753  		err = fmt.Errorf("privacy metadata invalid. mandatory recipients are only applicable for PrivacyFlag=2(MandatoryRecipients)")
  2754  		return
  2755  	}
  2756  
  2757  	// validate that PrivateFrom is one of the addresses of the private state resolved from the user context
  2758  	// 验证 PrivateFrom 是从用户上下文解析的私有状态的地址之一
  2759  	if b.ChainConfig().IsMPS {
  2760  		var psm *mps.PrivateStateMetadata
  2761  		psm, err = b.PSMR().ResolveForUserContext(ctx)
  2762  		if err != nil {
  2763  			return
  2764  		}
  2765  		if psm.NotIncludeAny(privateTxArgs.PrivateFrom) {
  2766  			err = fmt.Errorf("The PrivateFrom (%s) address does not match the specified private state (%s) ", privateTxArgs.PrivateFrom, psm.ID)
  2767  			return
  2768  		}
  2769  	}
  2770  
  2771  	if len(tx.Data()) > 0 {
  2772  		// check private contract exists on the node initiating the transaction
  2773  		if tx.To() != nil && privateTxArgs.PrivacyFlag.IsNotStandardPrivate() {
  2774  			state, _, lerr := b.StateAndHeaderByNumber(ctx, rpc.BlockNumber(b.CurrentBlock().Number().Uint64()))
  2775  			if lerr != nil && state == nil {
  2776  				err = fmt.Errorf("state not found")
  2777  				return
  2778  			}
  2779  			if state.GetCode(*tx.To()) == nil {
  2780  				err = fmt.Errorf("contract not found. cannot transact")
  2781  				return
  2782  			}
  2783  		}
  2784  
  2785  		replaceDataWithHash = true
  2786  		hash, err = handlePrivateTransaction(ctx, b, tx, privateTxArgs, from, txnType)
  2787  	}
  2788  
  2789  	return
  2790  }
  2791  
  2792  // Quorum
  2793  // If transaction is raw, the tx payload is indeed the hash of the encrypted payload.
  2794  // Then the sender key will set to privateTxArgs.privateFrom.
  2795  //
  2796  // For private transaction, run a simulated execution in order to
  2797  // 1. Find all affected private contract accounts then retrieve encrypted payload hashes of their creation txs
  2798  // 2. Calculate Merkle Root as the result of the simulated execution
  2799  // The above information along with private originating payload are sent to Transaction Manager
  2800  // to obtain hash of the encrypted private payload
  2801  func handlePrivateTransaction(ctx context.Context, b Backend, tx *types.Transaction, privateTxArgs *PrivateTxArgs, from common.Address, txnType TransactionType) (hash common.EncryptedPayloadHash, err error) {
  2802  	defer func(start time.Time) {
  2803  		log.Debug("Handle Private Transaction finished", "took", time.Since(start))
  2804  	}(time.Now())
  2805  
  2806  	data := tx.Data()
  2807  
  2808  	log.Debug("sending private tx", "txnType", txnType, "data", common.FormatTerminalString(data), "privatefrom", privateTxArgs.PrivateFrom, "privatefor", privateTxArgs.PrivateFor, "privacyFlag", privateTxArgs.PrivacyFlag, "mandatoryfor", privateTxArgs.MandatoryRecipients)
  2809  
  2810  	switch txnType {
  2811  	case FillTransaction:
  2812  		hash, err = private.P.StoreRaw(data, privateTxArgs.PrivateFrom)
  2813  	case RawTransaction:
  2814  		hash, err = handleRawPrivateTransaction(ctx, b, tx, privateTxArgs, from)
  2815  	case NormalTransaction:
  2816  		hash, err = handleNormalPrivateTransaction(ctx, b, tx, data, privateTxArgs, from)
  2817  	}
  2818  	return
  2819  }
  2820  
  2821  // Quorum
  2822  func handleRawPrivateTransaction(ctx context.Context, b Backend, tx *types.Transaction, privateTxArgs *PrivateTxArgs, from common.Address) (hash common.EncryptedPayloadHash, err error) {
  2823  	data := tx.Data()
  2824  	hash = common.BytesToEncryptedPayloadHash(data)
  2825  	privatePayload, privateFrom, _, revErr := private.P.ReceiveRaw(hash)
  2826  	if revErr != nil {
  2827  		return common.EncryptedPayloadHash{}, revErr
  2828  	}
  2829  	log.Trace("received raw payload", "hash", hash, "privatepayload", common.FormatTerminalString(privatePayload), "privateFrom", privateFrom)
  2830  
  2831  	privateTxArgs.PrivateFrom = privateFrom
  2832  	var privateTx *types.Transaction
  2833  	if tx.To() == nil {
  2834  		privateTx = types.NewContractCreation(tx.Nonce(), tx.Value(), tx.Gas(), tx.GasPrice(), privatePayload)
  2835  	} else {
  2836  		privateTx = types.NewTransaction(tx.Nonce(), *tx.To(), tx.Value(), tx.Gas(), tx.GasPrice(), privatePayload)
  2837  	}
  2838  
  2839  	affectedCATxHashes, merkleRoot, err := simulateExecutionForPE(ctx, b, from, privateTx, privateTxArgs)
  2840  	log.Trace("after simulation", "affectedCATxHashes", affectedCATxHashes, "merkleRoot", merkleRoot, "privacyFlag", privateTxArgs.PrivacyFlag, "error", err)
  2841  	if err != nil {
  2842  		return
  2843  	}
  2844  
  2845  	metadata := engine.ExtraMetadata{
  2846  		ACHashes:            affectedCATxHashes,
  2847  		ACMerkleRoot:        merkleRoot,
  2848  		PrivacyFlag:         privateTxArgs.PrivacyFlag,
  2849  		MandatoryRecipients: privateTxArgs.MandatoryRecipients,
  2850  	}
  2851  	_, _, data, err = private.P.SendSignedTx(hash, privateTxArgs.PrivateFor, &metadata)
  2852  	if err != nil {
  2853  		return
  2854  	}
  2855  
  2856  	log.Info("sent raw private signed tx",
  2857  		"data", common.FormatTerminalString(data),
  2858  		"hash", hash,
  2859  		"privatefrom", privateTxArgs.PrivateFrom,
  2860  		"privatefor", privateTxArgs.PrivateFor,
  2861  		"affectedCATxHashes", metadata.ACHashes,
  2862  		"merkleroot", metadata.ACHashes,
  2863  		"privacyflag", metadata.PrivacyFlag,
  2864  		"mandatoryrecipients", metadata.MandatoryRecipients)
  2865  	return
  2866  }
  2867  
  2868  // Quorum
  2869  func handleNormalPrivateTransaction(ctx context.Context, b Backend, tx *types.Transaction, data []byte, privateTxArgs *PrivateTxArgs, from common.Address) (hash common.EncryptedPayloadHash, err error) {
  2870  	affectedCATxHashes, merkleRoot, err := simulateExecutionForPE(ctx, b, from, tx, privateTxArgs)
  2871  	log.Trace("after simulation", "affectedCATxHashes", affectedCATxHashes, "merkleRoot", merkleRoot, "privacyFlag", privateTxArgs.PrivacyFlag, "error", err)
  2872  	if err != nil {
  2873  		return
  2874  	}
  2875  
  2876  	metadata := engine.ExtraMetadata{
  2877  		ACHashes:            affectedCATxHashes,
  2878  		ACMerkleRoot:        merkleRoot,
  2879  		PrivacyFlag:         privateTxArgs.PrivacyFlag,
  2880  		MandatoryRecipients: privateTxArgs.MandatoryRecipients,
  2881  	}
  2882  	_, _, hash, err = private.P.Send(data, privateTxArgs.PrivateFrom, privateTxArgs.PrivateFor, &metadata)
  2883  	if err != nil {
  2884  		return
  2885  	}
  2886  
  2887  	log.Info("sent private signed tx",
  2888  		"data", common.FormatTerminalString(data),
  2889  		"hash", hash,
  2890  		"privatefrom", privateTxArgs.PrivateFrom,
  2891  		"privatefor", privateTxArgs.PrivateFor,
  2892  		"affectedCATxHashes", metadata.ACHashes,
  2893  		"merkleroot", metadata.ACHashes,
  2894  		"privacyflag", metadata.PrivacyFlag,
  2895  		"mandatoryrecipients", metadata.MandatoryRecipients)
  2896  	return
  2897  }
  2898  
  2899  // (Quorum) createPrivacyMarkerTransaction creates a new privacy marker transaction (PMT) with the given signed privateTx.
  2900  // The private tx is sent only to the privateFor recipients. The resulting PMT's 'to' is the privacy precompile address and its 'data' is the
  2901  // privacy manager hash for the private tx.
  2902  func createPrivacyMarkerTransaction(b Backend, privateTx *types.Transaction, privateTxArgs *PrivateTxArgs) (*types.Transaction, error) {
  2903  	log.Trace("creating privacy marker transaction", "from", privateTx.From(), "to", privateTx.To())
  2904  
  2905  	data := new(bytes.Buffer)
  2906  	err := json.NewEncoder(data).Encode(privateTx)
  2907  	if err != nil {
  2908  		return nil, err
  2909  	}
  2910  
  2911  	_, _, ptmHash, err := private.P.Send(data.Bytes(), privateTxArgs.PrivateFrom, privateTxArgs.PrivateFor, &engine.ExtraMetadata{})
  2912  	if err != nil {
  2913  		return nil, err
  2914  	}
  2915  
  2916  	currentBlockHeight := b.CurrentHeader().Number
  2917  	istanbul := b.ChainConfig().IsIstanbul(currentBlockHeight)
  2918  	intrinsicGas, err := core.IntrinsicGas(ptmHash.Bytes(), false, true, istanbul)
  2919  	if err != nil {
  2920  		return nil, err
  2921  	}
  2922  
  2923  	pmt := types.NewTransaction(privateTx.Nonce(), common.QuorumPrivacyPrecompileContractAddress(), privateTx.Value(), intrinsicGas, privateTx.GasPrice(), ptmHash.Bytes())
  2924  
  2925  	return pmt, nil
  2926  }
  2927  
  2928  // Quorum
  2929  // simulateExecutionForPE simulates execution of a private transaction for enhanced privacy
  2930  //
  2931  // Returns hashes of encrypted payload of creation transactions for all affected contract accounts
  2932  // and the merkle root combining all affected contract accounts after the simulation
  2933  func simulateExecutionForPE(ctx context.Context, b Backend, from common.Address, privateTx *types.Transaction, privateTxArgs *PrivateTxArgs) (common.EncryptedPayloadHashes, common.Hash, error) {
  2934  	// skip simulation if privacy enhancements are disabled
  2935  	if !b.ChainConfig().IsPrivacyEnhancementsEnabled(b.CurrentBlock().Number()) {
  2936  		return nil, common.Hash{}, nil
  2937  	}
  2938  
  2939  	evm, err := runSimulation(ctx, b, from, privateTx)
  2940  	if evm == nil {
  2941  		log.Debug("TX Simulation setup failed", "error", err)
  2942  		return nil, common.Hash{}, err
  2943  	}
  2944  	if err != nil {
  2945  		if privateTxArgs.PrivacyFlag.IsStandardPrivate() {
  2946  			log.Debug("An error occurred during StandardPrivate transaction simulation. "+
  2947  				"Continuing to simulation checks.", "error", err)
  2948  		} else {
  2949  			log.Trace("Simulated execution", "error", err)
  2950  			return nil, common.Hash{}, err
  2951  		}
  2952  	}
  2953  	affectedContractsHashes := make(common.EncryptedPayloadHashes)
  2954  	var merkleRoot common.Hash
  2955  	addresses := evm.AffectedContracts()
  2956  	privacyFlag := privateTxArgs.PrivacyFlag
  2957  	log.Trace("after simulation run", "numberOfAffectedContracts", len(addresses), "privacyFlag", privacyFlag)
  2958  	for _, addr := range addresses {
  2959  		// GetPrivacyMetadata is invoked directly on the privateState (as the tx is private) and it returns:
  2960  		// 1. public contacts: privacyMetadata = nil, err = nil
  2961  		// 2. private contracts of type:
  2962  		// 2.1. StandardPrivate:     privacyMetadata = nil, err = "The provided contract does not have privacy metadata"
  2963  		// 2.2. PartyProtection/PSV: privacyMetadata = <data>, err = nil
  2964  		privacyMetadata, err := evm.StateDB.GetPrivacyMetadata(addr)
  2965  		log.Debug("Found affected contract", "address", addr.Hex(), "privacyMetadata", privacyMetadata)
  2966  		//privacyMetadata not found=non-party, or another db error
  2967  		if err != nil && privacyFlag.IsNotStandardPrivate() {
  2968  			return nil, common.Hash{}, errors.New("PrivacyMetadata not found: " + err.Error())
  2969  		}
  2970  		// when we run simulation, it's possible that affected contracts may contain public ones
  2971  		// public contract will not have any privacyMetadata attached
  2972  		// standard private will be nil
  2973  		if privacyMetadata == nil {
  2974  			continue
  2975  		}
  2976  		//if affecteds are not all the same return an error
  2977  		if privacyFlag != privacyMetadata.PrivacyFlag {
  2978  			return nil, common.Hash{}, errors.New("sent privacy flag doesn't match all affected contract flags")
  2979  		}
  2980  
  2981  		affectedContractsHashes.Add(privacyMetadata.CreationTxHash)
  2982  	}
  2983  	//only calculate the merkle root if all contracts are psv
  2984  	if privacyFlag.Has(engine.PrivacyFlagStateValidation) {
  2985  		merkleRoot, err = evm.CalculateMerkleRoot()
  2986  		if err != nil {
  2987  			return nil, common.Hash{}, err
  2988  		}
  2989  	}
  2990  	log.Trace("post-execution run", "merkleRoot", merkleRoot, "affectedhashes", affectedContractsHashes)
  2991  	return affectedContractsHashes, merkleRoot, nil
  2992  }
  2993  
  2994  //End-Quorum