github.com/aswedchain/aswed@v1.0.1/internal/ethapi/api.go (about)

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