github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/ethclient/ethclient.go (about)

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