github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/internal/ethapi/api.go (about)

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