gitlab.com/aquachain/aquachain@v1.17.16-rc3.0.20221018032414-e3ddf1e1c055/internal/aquaapi/api.go (about)

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