github.com/FUSIONFoundation/efsn@v3.6.2-0.20200916075423-dbb5dd5d2cc7+incompatible/ethclient/ethclient.go (about)

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