github.com/aquanetwork/aquachain@v1.7.8/opt/aquaclient/aquaclient.go (about)

     1  // Copyright 2016 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 aquaclient provides a client for the AquaChain RPC API.
    18  package aquaclient
    19  
    20  import (
    21  	"context"
    22  	"encoding/json"
    23  	"errors"
    24  	"fmt"
    25  	"math/big"
    26  
    27  	"gitlab.com/aquachain/aquachain"
    28  	"gitlab.com/aquachain/aquachain/common"
    29  	"gitlab.com/aquachain/aquachain/common/hexutil"
    30  	"gitlab.com/aquachain/aquachain/core/types"
    31  	"gitlab.com/aquachain/aquachain/rlp"
    32  	"gitlab.com/aquachain/aquachain/rpc"
    33  )
    34  
    35  // Client defines typed wrappers for the AquaChain RPC API.
    36  type Client struct {
    37  	c *rpc.Client
    38  }
    39  
    40  // Dial connects a client to the given URL.
    41  func Dial(rawurl string) (*Client, error) {
    42  	c, err := rpc.Dial(rawurl)
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  	return NewClient(c), nil
    47  }
    48  
    49  // NewClient creates a client that uses the given RPC client.
    50  func NewClient(c *rpc.Client) *Client {
    51  	return &Client{c}
    52  }
    53  
    54  // Blockchain Access
    55  
    56  // BlockByHash returns the given full block.
    57  //
    58  // Note that loading full blocks requires two requests. Use HeaderByHash
    59  // if you don't need all transactions or uncle headers.
    60  func (ec *Client) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
    61  	return ec.getBlock(ctx, "aqua_getBlockByHash", hash, true)
    62  }
    63  
    64  // BlockByNumber returns a block from the current canonical chain. If number is nil, the
    65  // latest known block is returned.
    66  //
    67  // Note that loading full blocks requires two requests. Use HeaderByNumber
    68  // if you don't need all transactions or uncle headers.
    69  func (ec *Client) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) {
    70  	return ec.getBlock(ctx, "aqua_getBlockByNumber", toBlockNumArg(number), true)
    71  }
    72  
    73  type rpcBlock struct {
    74  	Hash         common.Hash      `json:"hash"`
    75  	Transactions []rpcTransaction `json:"transactions"`
    76  	UncleHashes  []common.Hash    `json:"uncles"`
    77  }
    78  
    79  func (ec *Client) getBlock(ctx context.Context, method string, args ...interface{}) (*types.Block, error) {
    80  	var raw json.RawMessage
    81  	err := ec.c.CallContext(ctx, &raw, method, args...)
    82  	if err != nil {
    83  		return nil, err
    84  	} else if len(raw) == 0 {
    85  		return nil, aquachain.NotFound
    86  	}
    87  	// Decode header and transactions.
    88  	var head *types.Header
    89  	var body rpcBlock
    90  	if err := json.Unmarshal(raw, &head); err != nil {
    91  		return nil, err
    92  	}
    93  	if err := json.Unmarshal(raw, &body); err != nil {
    94  		return nil, err
    95  	}
    96  	// Quick-verify transaction and uncle lists. This mostly helps with debugging the server.
    97  	if head.UncleHash == types.EmptyUncleHash && len(body.UncleHashes) > 0 {
    98  		return nil, fmt.Errorf("server returned non-empty uncle list but block header indicates no uncles")
    99  	}
   100  	if head.UncleHash != types.EmptyUncleHash && len(body.UncleHashes) == 0 {
   101  		return nil, fmt.Errorf("server returned empty uncle list but block header indicates uncles")
   102  	}
   103  	if head.TxHash == types.EmptyRootHash && len(body.Transactions) > 0 {
   104  		return nil, fmt.Errorf("server returned non-empty transaction list but block header indicates no transactions")
   105  	}
   106  	if head.TxHash != types.EmptyRootHash && len(body.Transactions) == 0 {
   107  		return nil, fmt.Errorf("server returned empty transaction list but block header indicates transactions")
   108  	}
   109  	// Load uncles because they are not included in the block response.
   110  	var uncles []*types.Header
   111  	if len(body.UncleHashes) > 0 {
   112  		uncles = make([]*types.Header, len(body.UncleHashes))
   113  		reqs := make([]rpc.BatchElem, len(body.UncleHashes))
   114  		for i := range reqs {
   115  			reqs[i] = rpc.BatchElem{
   116  				Method: "aqua_getUncleByBlockHashAndIndex",
   117  				Args:   []interface{}{body.Hash, hexutil.EncodeUint64(uint64(i))},
   118  				Result: &uncles[i],
   119  			}
   120  		}
   121  		if err := ec.c.BatchCallContext(ctx, reqs); err != nil {
   122  			return nil, err
   123  		}
   124  		for i := range reqs {
   125  			if reqs[i].Error != nil {
   126  				return nil, reqs[i].Error
   127  			}
   128  			if uncles[i] == nil {
   129  				return nil, fmt.Errorf("got null header for uncle %d of block %x", i, body.Hash[:])
   130  			}
   131  		}
   132  	}
   133  	// Fill the sender cache of transactions in the block.
   134  	txs := make([]*types.Transaction, len(body.Transactions))
   135  	for i, tx := range body.Transactions {
   136  		setSenderFromServer(tx.tx, tx.From, body.Hash)
   137  		txs[i] = tx.tx
   138  	}
   139  	return types.NewBlockWithHeader(head).WithBody(txs, uncles), nil
   140  }
   141  
   142  // HeaderByHash returns the block header with the given hash.
   143  func (ec *Client) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) {
   144  	var head *types.Header
   145  	err := ec.c.CallContext(ctx, &head, "aqua_getBlockByHash", hash, false)
   146  	if err == nil && head == nil {
   147  		err = aquachain.NotFound
   148  	}
   149  	return head, err
   150  }
   151  
   152  // HeaderByNumber returns a block header from the current canonical chain. If number is
   153  // nil, the latest known header is returned.
   154  func (ec *Client) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
   155  	var head *types.Header
   156  	err := ec.c.CallContext(ctx, &head, "aqua_getBlockByNumber", toBlockNumArg(number), false)
   157  	if err == nil && head == nil {
   158  		err = aquachain.NotFound
   159  	}
   160  	return head, err
   161  }
   162  
   163  type rpcTransaction struct {
   164  	tx *types.Transaction
   165  	txExtraInfo
   166  }
   167  
   168  type txExtraInfo struct {
   169  	BlockNumber *string
   170  	BlockHash   common.Hash
   171  	From        common.Address
   172  }
   173  
   174  func (tx *rpcTransaction) UnmarshalJSON(msg []byte) error {
   175  	if err := json.Unmarshal(msg, &tx.tx); err != nil {
   176  		return err
   177  	}
   178  	return json.Unmarshal(msg, &tx.txExtraInfo)
   179  }
   180  
   181  // TransactionByHash returns the transaction with the given hash.
   182  func (ec *Client) TransactionByHash(ctx context.Context, hash common.Hash) (tx *types.Transaction, isPending bool, err error) {
   183  	var json *rpcTransaction
   184  	err = ec.c.CallContext(ctx, &json, "aqua_getTransactionByHash", hash)
   185  	if err != nil {
   186  		return nil, false, err
   187  	} else if json == nil {
   188  		return nil, false, aquachain.NotFound
   189  	} else if _, r, _ := json.tx.RawSignatureValues(); r == nil {
   190  		return nil, false, fmt.Errorf("server returned transaction without signature")
   191  	}
   192  	setSenderFromServer(json.tx, json.From, json.BlockHash)
   193  	return json.tx, json.BlockNumber == nil, nil
   194  }
   195  
   196  // TransactionSender returns the sender address of the given transaction. The transaction
   197  // must be known to the remote node and included in the blockchain at the given block and
   198  // index. The sender is the one derived by the protocol at the time of inclusion.
   199  //
   200  // There is a fast-path for transactions retrieved by TransactionByHash and
   201  // TransactionInBlock. Getting their sender address can be done without an RPC interaction.
   202  func (ec *Client) TransactionSender(ctx context.Context, tx *types.Transaction, block common.Hash, index uint) (common.Address, error) {
   203  	// Try to load the address from the cache.
   204  	sender, err := types.Sender(&senderFromServer{blockhash: block}, tx)
   205  	if err == nil {
   206  		return sender, nil
   207  	}
   208  	var meta struct {
   209  		Hash common.Hash
   210  		From common.Address
   211  	}
   212  	if err = ec.c.CallContext(ctx, &meta, "aqua_getTransactionByBlockHashAndIndex", block, hexutil.Uint64(index)); err != nil {
   213  		return common.Address{}, err
   214  	}
   215  	if meta.Hash == (common.Hash{}) || meta.Hash != tx.Hash() {
   216  		return common.Address{}, errors.New("wrong inclusion block/index")
   217  	}
   218  	return meta.From, nil
   219  }
   220  
   221  // TransactionCount returns the total number of transactions in the given block.
   222  func (ec *Client) TransactionCount(ctx context.Context, blockHash common.Hash) (uint, error) {
   223  	var num hexutil.Uint
   224  	err := ec.c.CallContext(ctx, &num, "aqua_getBlockTransactionCountByHash", blockHash)
   225  	return uint(num), err
   226  }
   227  
   228  // TransactionInBlock returns a single transaction at index in the given block.
   229  func (ec *Client) TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (*types.Transaction, error) {
   230  	var json *rpcTransaction
   231  	err := ec.c.CallContext(ctx, &json, "aqua_getTransactionByBlockHashAndIndex", blockHash, hexutil.Uint64(index))
   232  	if err == nil {
   233  		if json == nil {
   234  			return nil, aquachain.NotFound
   235  		} else if _, r, _ := json.tx.RawSignatureValues(); r == nil {
   236  			return nil, fmt.Errorf("server returned transaction without signature")
   237  		}
   238  	}
   239  	setSenderFromServer(json.tx, json.From, json.BlockHash)
   240  	return json.tx, err
   241  }
   242  
   243  // TransactionReceipt returns the receipt of a transaction by transaction hash.
   244  // Note that the receipt is not available for pending transactions.
   245  func (ec *Client) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) {
   246  	var r *types.Receipt
   247  	err := ec.c.CallContext(ctx, &r, "aqua_getTransactionReceipt", txHash)
   248  	if err == nil {
   249  		if r == nil {
   250  			return nil, aquachain.NotFound
   251  		}
   252  	}
   253  	return r, err
   254  }
   255  
   256  func toBlockNumArg(number *big.Int) string {
   257  	if number == nil {
   258  		return "latest"
   259  	}
   260  	return hexutil.EncodeBig(number)
   261  }
   262  
   263  type rpcProgress struct {
   264  	StartingBlock hexutil.Uint64
   265  	CurrentBlock  hexutil.Uint64
   266  	HighestBlock  hexutil.Uint64
   267  	PulledStates  hexutil.Uint64
   268  	KnownStates   hexutil.Uint64
   269  }
   270  
   271  // SyncProgress retrieves the current progress of the sync algorithm. If there's
   272  // no sync currently running, it returns nil.
   273  func (ec *Client) SyncProgress(ctx context.Context) (*aquachain.SyncProgress, error) {
   274  	var raw json.RawMessage
   275  	if err := ec.c.CallContext(ctx, &raw, "aqua_syncing"); err != nil {
   276  		return nil, err
   277  	}
   278  	// Handle the possible response types
   279  	var syncing bool
   280  	if err := json.Unmarshal(raw, &syncing); err == nil {
   281  		return nil, nil // Not syncing (always false)
   282  	}
   283  	var progress *rpcProgress
   284  	if err := json.Unmarshal(raw, &progress); err != nil {
   285  		return nil, err
   286  	}
   287  	return &aquachain.SyncProgress{
   288  		StartingBlock: uint64(progress.StartingBlock),
   289  		CurrentBlock:  uint64(progress.CurrentBlock),
   290  		HighestBlock:  uint64(progress.HighestBlock),
   291  		PulledStates:  uint64(progress.PulledStates),
   292  		KnownStates:   uint64(progress.KnownStates),
   293  	}, nil
   294  }
   295  
   296  // SubscribeNewHead subscribes to notifications about the current blockchain head
   297  // on the given channel.
   298  func (ec *Client) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (aquachain.Subscription, error) {
   299  	return ec.c.AquaSubscribe(ctx, ch, "newHeads", map[string]struct{}{})
   300  }
   301  
   302  // State Access
   303  
   304  // NetworkID returns the network ID (also known as the chain ID) for this chain.
   305  func (ec *Client) NetworkID(ctx context.Context) (*big.Int, error) {
   306  	version := new(big.Int)
   307  	var ver string
   308  	if err := ec.c.CallContext(ctx, &ver, "net_version"); err != nil {
   309  		return nil, err
   310  	}
   311  	if _, ok := version.SetString(ver, 10); !ok {
   312  		return nil, fmt.Errorf("invalid net_version result %q", ver)
   313  	}
   314  	return version, nil
   315  }
   316  
   317  // BalanceAt returns the wei balance of the given account.
   318  // The block number can be nil, in which case the balance is taken from the latest known block.
   319  func (ec *Client) BalanceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (*big.Int, error) {
   320  	var result hexutil.Big
   321  	err := ec.c.CallContext(ctx, &result, "aqua_getBalance", account, toBlockNumArg(blockNumber))
   322  	return (*big.Int)(&result), err
   323  }
   324  
   325  // StorageAt returns the value of key in the contract storage of the given account.
   326  // The block number can be nil, in which case the value is taken from the latest known block.
   327  func (ec *Client) StorageAt(ctx context.Context, account common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error) {
   328  	var result hexutil.Bytes
   329  	err := ec.c.CallContext(ctx, &result, "aqua_getStorageAt", account, key, toBlockNumArg(blockNumber))
   330  	return result, err
   331  }
   332  
   333  // CodeAt returns the contract code of the given account.
   334  // The block number can be nil, in which case the code is taken from the latest known block.
   335  func (ec *Client) CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error) {
   336  	var result hexutil.Bytes
   337  	err := ec.c.CallContext(ctx, &result, "aqua_getCode", account, toBlockNumArg(blockNumber))
   338  	return result, err
   339  }
   340  
   341  // NonceAt returns the account nonce of the given account.
   342  // The block number can be nil, in which case the nonce is taken from the latest known block.
   343  func (ec *Client) NonceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (uint64, error) {
   344  	var result hexutil.Uint64
   345  	err := ec.c.CallContext(ctx, &result, "aqua_getTransactionCount", account, toBlockNumArg(blockNumber))
   346  	return uint64(result), err
   347  }
   348  
   349  // Filters
   350  
   351  // FilterLogs executes a filter query.
   352  func (ec *Client) FilterLogs(ctx context.Context, q aquachain.FilterQuery) ([]types.Log, error) {
   353  	var result []types.Log
   354  	err := ec.c.CallContext(ctx, &result, "aqua_getLogs", toFilterArg(q))
   355  	return result, err
   356  }
   357  
   358  // SubscribeFilterLogs subscribes to the results of a streaming filter query.
   359  func (ec *Client) SubscribeFilterLogs(ctx context.Context, q aquachain.FilterQuery, ch chan<- types.Log) (aquachain.Subscription, error) {
   360  	return ec.c.AquaSubscribe(ctx, ch, "logs", toFilterArg(q))
   361  }
   362  
   363  func toFilterArg(q aquachain.FilterQuery) interface{} {
   364  	arg := map[string]interface{}{
   365  		"fromBlock": toBlockNumArg(q.FromBlock),
   366  		"toBlock":   toBlockNumArg(q.ToBlock),
   367  		"address":   q.Addresses,
   368  		"topics":    q.Topics,
   369  	}
   370  	if q.FromBlock == nil {
   371  		arg["fromBlock"] = "0x0"
   372  	}
   373  	return arg
   374  }
   375  
   376  // Pending State
   377  
   378  // PendingBalanceAt returns the wei balance of the given account in the pending state.
   379  func (ec *Client) PendingBalanceAt(ctx context.Context, account common.Address) (*big.Int, error) {
   380  	var result hexutil.Big
   381  	err := ec.c.CallContext(ctx, &result, "aqua_getBalance", account, "pending")
   382  	return (*big.Int)(&result), err
   383  }
   384  
   385  // PendingStorageAt returns the value of key in the contract storage of the given account in the pending state.
   386  func (ec *Client) PendingStorageAt(ctx context.Context, account common.Address, key common.Hash) ([]byte, error) {
   387  	var result hexutil.Bytes
   388  	err := ec.c.CallContext(ctx, &result, "aqua_getStorageAt", account, key, "pending")
   389  	return result, err
   390  }
   391  
   392  // PendingCodeAt returns the contract code of the given account in the pending state.
   393  func (ec *Client) PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error) {
   394  	var result hexutil.Bytes
   395  	err := ec.c.CallContext(ctx, &result, "aqua_getCode", account, "pending")
   396  	return result, err
   397  }
   398  
   399  // PendingNonceAt returns the account nonce of the given account in the pending state.
   400  // This is the nonce that should be used for the next transaction.
   401  func (ec *Client) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
   402  	var result hexutil.Uint64
   403  	err := ec.c.CallContext(ctx, &result, "aqua_getTransactionCount", account, "pending")
   404  	return uint64(result), err
   405  }
   406  
   407  // PendingTransactionCount returns the total number of transactions in the pending state.
   408  func (ec *Client) PendingTransactionCount(ctx context.Context) (uint, error) {
   409  	var num hexutil.Uint
   410  	err := ec.c.CallContext(ctx, &num, "aqua_getBlockTransactionCountByNumber", "pending")
   411  	return uint(num), err
   412  }
   413  
   414  // TODO: SubscribePendingTransactions (needs server side)
   415  
   416  // Contract Calling
   417  
   418  // CallContract executes a message call transaction, which is directly executed in the VM
   419  // of the node, but never mined into the blockchain.
   420  //
   421  // blockNumber selects the block height at which the call runs. It can be nil, in which
   422  // case the code is taken from the latest known block. Note that state from very old
   423  // blocks might not be available.
   424  func (ec *Client) CallContract(ctx context.Context, msg aquachain.CallMsg, blockNumber *big.Int) ([]byte, error) {
   425  	var hex hexutil.Bytes
   426  	err := ec.c.CallContext(ctx, &hex, "aqua_call", toCallArg(msg), toBlockNumArg(blockNumber))
   427  	if err != nil {
   428  		return nil, err
   429  	}
   430  	return hex, nil
   431  }
   432  
   433  // PendingCallContract executes a message call transaction using the EVM.
   434  // The state seen by the contract call is the pending state.
   435  func (ec *Client) PendingCallContract(ctx context.Context, msg aquachain.CallMsg) ([]byte, error) {
   436  	var hex hexutil.Bytes
   437  	err := ec.c.CallContext(ctx, &hex, "aqua_call", toCallArg(msg), "pending")
   438  	if err != nil {
   439  		return nil, err
   440  	}
   441  	return hex, nil
   442  }
   443  
   444  // SuggestGasPrice retrieves the currently suggested gas price to allow a timely
   445  // execution of a transaction.
   446  func (ec *Client) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
   447  	var hex hexutil.Big
   448  	if err := ec.c.CallContext(ctx, &hex, "aqua_gasPrice"); err != nil {
   449  		return nil, err
   450  	}
   451  	return (*big.Int)(&hex), nil
   452  }
   453  
   454  // EstimateGas tries to estimate the gas needed to execute a specific transaction based on
   455  // the current pending state of the backend blockchain. There is no guarantee that this is
   456  // the true gas limit requirement as other transactions may be added or removed by miners,
   457  // but it should provide a basis for setting a reasonable default.
   458  func (ec *Client) EstimateGas(ctx context.Context, msg aquachain.CallMsg) (uint64, error) {
   459  	var hex hexutil.Uint64
   460  	err := ec.c.CallContext(ctx, &hex, "aqua_estimateGas", toCallArg(msg))
   461  	if err != nil {
   462  		return 0, err
   463  	}
   464  	return uint64(hex), nil
   465  }
   466  
   467  // SendTransaction injects a signed transaction into the pending pool for execution.
   468  //
   469  // If the transaction was a contract creation use the TransactionReceipt method to get the
   470  // contract address after the transaction has been mined.
   471  func (ec *Client) SendTransaction(ctx context.Context, tx *types.Transaction) error {
   472  	data, err := rlp.EncodeToBytes(tx)
   473  	if err != nil {
   474  		return err
   475  	}
   476  	return ec.c.CallContext(ctx, nil, "aqua_sendRawTransaction", common.ToHex(data))
   477  }
   478  
   479  func (ec *Client) GetWork(ctx context.Context) ([3]string, error) {
   480  	var work [3]string
   481  	err := ec.c.CallContext(ctx, &work, "aqua_getWork")
   482  	return work, err
   483  }
   484  
   485  func (ec *Client) GetBlockTemplate(ctx context.Context, coinbaseAddr common.Address) ([]byte, error) {
   486  	var bt []byte
   487  	err := ec.c.CallContext(ctx, &bt, "testing_getBlockTemplate", coinbaseAddr)
   488  	return bt, err
   489  }
   490  
   491  func (ec *Client) SubmitBlock(ctx context.Context, encoded []byte) bool {
   492  	var ok bool
   493  	return ec.c.CallContext(ctx, &ok, "testing_submitBlock", encoded) == nil && ok
   494  }
   495  
   496  func (ec *Client) SubmitWork(ctx context.Context, nonce types.BlockNonce, solution, digest common.Hash) bool {
   497  	var ok bool
   498  	return ec.c.CallContext(ctx, &ok, "aqua_submitWork", nonce, solution, digest) == nil && ok
   499  }
   500  
   501  func toCallArg(msg aquachain.CallMsg) interface{} {
   502  	arg := map[string]interface{}{
   503  		"from": msg.From,
   504  		"to":   msg.To,
   505  	}
   506  	if len(msg.Data) > 0 {
   507  		arg["data"] = hexutil.Bytes(msg.Data)
   508  	}
   509  	if msg.Value != nil {
   510  		arg["value"] = (*hexutil.Big)(msg.Value)
   511  	}
   512  	if msg.Gas != 0 {
   513  		arg["gas"] = hexutil.Uint64(msg.Gas)
   514  	}
   515  	if msg.GasPrice != nil {
   516  		arg["gasPrice"] = (*hexutil.Big)(msg.GasPrice)
   517  	}
   518  	return arg
   519  }