github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/mobile/ethclient.go (about)

     1  // Copyright 2016 The Spectrum Authors
     2  // This file is part of the Spectrum library.
     3  //
     4  // The Spectrum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The Spectrum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the Spectrum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // Contains a wrapper for the Ethereum client.
    18  
    19  package geth
    20  
    21  import (
    22  	"math/big"
    23  
    24  	"github.com/SmartMeshFoundation/Spectrum/common"
    25  	"github.com/SmartMeshFoundation/Spectrum/core/types"
    26  	"github.com/SmartMeshFoundation/Spectrum/ethclient"
    27  )
    28  
    29  // EthereumClient provides access to the Ethereum APIs.
    30  type EthereumClient struct {
    31  	client *ethclient.Client
    32  }
    33  
    34  // NewEthereumClient connects a client to the given URL.
    35  func NewEthereumClient(rawurl string) (client *EthereumClient, _ error) {
    36  	rawClient, err := ethclient.Dial(rawurl)
    37  	return &EthereumClient{rawClient}, err
    38  }
    39  
    40  // GetBlockByHash returns the given full block.
    41  func (ec *EthereumClient) GetBlockByHash(ctx *Context, hash *Hash) (block *Block, _ error) {
    42  	rawBlock, err := ec.client.BlockByHash(ctx.context, hash.hash)
    43  	return &Block{rawBlock}, err
    44  }
    45  
    46  // GetBlockByNumber returns a block from the current canonical chain. If number is <0, the
    47  // latest known block is returned.
    48  func (ec *EthereumClient) GetBlockByNumber(ctx *Context, number int64) (block *Block, _ error) {
    49  	if number < 0 {
    50  		rawBlock, err := ec.client.BlockByNumber(ctx.context, nil)
    51  		return &Block{rawBlock}, err
    52  	}
    53  	rawBlock, err := ec.client.BlockByNumber(ctx.context, big.NewInt(number))
    54  	return &Block{rawBlock}, err
    55  }
    56  
    57  // GetHeaderByHash returns the block header with the given hash.
    58  func (ec *EthereumClient) GetHeaderByHash(ctx *Context, hash *Hash) (header *Header, _ error) {
    59  	rawHeader, err := ec.client.HeaderByHash(ctx.context, hash.hash)
    60  	return &Header{rawHeader}, err
    61  }
    62  
    63  // GetHeaderByNumber returns a block header from the current canonical chain. If number is <0,
    64  // the latest known header is returned.
    65  func (ec *EthereumClient) GetHeaderByNumber(ctx *Context, number int64) (header *Header, _ error) {
    66  	if number < 0 {
    67  		rawHeader, err := ec.client.HeaderByNumber(ctx.context, nil)
    68  		return &Header{rawHeader}, err
    69  	}
    70  	rawHeader, err := ec.client.HeaderByNumber(ctx.context, big.NewInt(number))
    71  	return &Header{rawHeader}, err
    72  }
    73  
    74  // GetTransactionByHash returns the transaction with the given hash.
    75  func (ec *EthereumClient) GetTransactionByHash(ctx *Context, hash *Hash) (tx *Transaction, _ error) {
    76  	// TODO(karalabe): handle isPending
    77  	rawTx, _, err := ec.client.TransactionByHash(ctx.context, hash.hash)
    78  	return &Transaction{rawTx}, err
    79  }
    80  
    81  // GetTransactionSender returns the sender address of a transaction. The transaction must
    82  // be included in blockchain at the given block and index.
    83  func (ec *EthereumClient) GetTransactionSender(ctx *Context, tx *Transaction, blockhash *Hash, index int) (sender *Address, _ error) {
    84  	addr, err := ec.client.TransactionSender(ctx.context, tx.tx, blockhash.hash, uint(index))
    85  	return &Address{addr}, err
    86  }
    87  
    88  // GetTransactionCount returns the total number of transactions in the given block.
    89  func (ec *EthereumClient) GetTransactionCount(ctx *Context, hash *Hash) (count int, _ error) {
    90  	rawCount, err := ec.client.TransactionCount(ctx.context, hash.hash)
    91  	return int(rawCount), err
    92  }
    93  
    94  // GetTransactionInBlock returns a single transaction at index in the given block.
    95  func (ec *EthereumClient) GetTransactionInBlock(ctx *Context, hash *Hash, index int) (tx *Transaction, _ error) {
    96  	rawTx, err := ec.client.TransactionInBlock(ctx.context, hash.hash, uint(index))
    97  	return &Transaction{rawTx}, err
    98  
    99  }
   100  
   101  // GetTransactionReceipt returns the receipt of a transaction by transaction hash.
   102  // Note that the receipt is not available for pending transactions.
   103  func (ec *EthereumClient) GetTransactionReceipt(ctx *Context, hash *Hash) (receipt *Receipt, _ error) {
   104  	rawReceipt, err := ec.client.TransactionReceipt(ctx.context, hash.hash)
   105  	return &Receipt{rawReceipt}, err
   106  }
   107  
   108  // SyncProgress retrieves the current progress of the sync algorithm. If there's
   109  // no sync currently running, it returns nil.
   110  func (ec *EthereumClient) SyncProgress(ctx *Context) (progress *SyncProgress, _ error) {
   111  	rawProgress, err := ec.client.SyncProgress(ctx.context)
   112  	if rawProgress == nil {
   113  		return nil, err
   114  	}
   115  	return &SyncProgress{*rawProgress}, err
   116  }
   117  
   118  // NewHeadHandler is a client-side subscription callback to invoke on events and
   119  // subscription failure.
   120  type NewHeadHandler interface {
   121  	OnNewHead(header *Header)
   122  	OnError(failure string)
   123  }
   124  
   125  // SubscribeNewHead subscribes to notifications about the current blockchain head
   126  // on the given channel.
   127  func (ec *EthereumClient) SubscribeNewHead(ctx *Context, handler NewHeadHandler, buffer int) (sub *Subscription, _ error) {
   128  	// Subscribe to the event internally
   129  	ch := make(chan *types.Header, buffer)
   130  	rawSub, err := ec.client.SubscribeNewHead(ctx.context, ch)
   131  	if err != nil {
   132  		return nil, err
   133  	}
   134  	// Start up a dispatcher to feed into the callback
   135  	go func() {
   136  		for {
   137  			select {
   138  			case header := <-ch:
   139  				handler.OnNewHead(&Header{header})
   140  
   141  			case err := <-rawSub.Err():
   142  				handler.OnError(err.Error())
   143  				return
   144  			}
   145  		}
   146  	}()
   147  	return &Subscription{rawSub}, nil
   148  }
   149  
   150  // State Access
   151  
   152  // GetBalanceAt returns the wei balance of the given account.
   153  // The block number can be <0, in which case the balance is taken from the latest known block.
   154  func (ec *EthereumClient) GetBalanceAt(ctx *Context, account *Address, number int64) (balance *BigInt, _ error) {
   155  	if number < 0 {
   156  		rawBalance, err := ec.client.BalanceAt(ctx.context, account.address, nil)
   157  		return &BigInt{rawBalance}, err
   158  	}
   159  	rawBalance, err := ec.client.BalanceAt(ctx.context, account.address, big.NewInt(number))
   160  	return &BigInt{rawBalance}, err
   161  }
   162  
   163  // GetStorageAt returns the value of key in the contract storage of the given account.
   164  // The block number can be <0, in which case the value is taken from the latest known block.
   165  func (ec *EthereumClient) GetStorageAt(ctx *Context, account *Address, key *Hash, number int64) (storage []byte, _ error) {
   166  	if number < 0 {
   167  		return ec.client.StorageAt(ctx.context, account.address, key.hash, nil)
   168  	}
   169  	return ec.client.StorageAt(ctx.context, account.address, key.hash, big.NewInt(number))
   170  }
   171  
   172  // GetCodeAt returns the contract code of the given account.
   173  // The block number can be <0, in which case the code is taken from the latest known block.
   174  func (ec *EthereumClient) GetCodeAt(ctx *Context, account *Address, number int64) (code []byte, _ error) {
   175  	if number < 0 {
   176  		return ec.client.CodeAt(ctx.context, account.address, nil)
   177  	}
   178  	return ec.client.CodeAt(ctx.context, account.address, big.NewInt(number))
   179  }
   180  
   181  // GetNonceAt returns the account nonce of the given account.
   182  // The block number can be <0, in which case the nonce is taken from the latest known block.
   183  func (ec *EthereumClient) GetNonceAt(ctx *Context, account *Address, number int64) (nonce int64, _ error) {
   184  	if number < 0 {
   185  		rawNonce, err := ec.client.NonceAt(ctx.context, account.address, nil)
   186  		return int64(rawNonce), err
   187  	}
   188  	rawNonce, err := ec.client.NonceAt(ctx.context, account.address, big.NewInt(number))
   189  	return int64(rawNonce), err
   190  }
   191  
   192  // Filters
   193  
   194  // FilterLogs executes a filter query.
   195  func (ec *EthereumClient) FilterLogs(ctx *Context, query *FilterQuery) (logs *Logs, _ error) {
   196  	rawLogs, err := ec.client.FilterLogs(ctx.context, query.query)
   197  	if err != nil {
   198  		return nil, err
   199  	}
   200  	// Temp hack due to vm.Logs being []*vm.Log
   201  	res := make([]*types.Log, len(rawLogs))
   202  	for i := range rawLogs {
   203  		res[i] = &rawLogs[i]
   204  	}
   205  	return &Logs{res}, nil
   206  }
   207  
   208  // FilterLogsHandler is a client-side subscription callback to invoke on events and
   209  // subscription failure.
   210  type FilterLogsHandler interface {
   211  	OnFilterLogs(log *Log)
   212  	OnError(failure string)
   213  }
   214  
   215  // SubscribeFilterLogs subscribes to the results of a streaming filter query.
   216  func (ec *EthereumClient) SubscribeFilterLogs(ctx *Context, query *FilterQuery, handler FilterLogsHandler, buffer int) (sub *Subscription, _ error) {
   217  	// Subscribe to the event internally
   218  	ch := make(chan types.Log, buffer)
   219  	rawSub, err := ec.client.SubscribeFilterLogs(ctx.context, query.query, ch)
   220  	if err != nil {
   221  		return nil, err
   222  	}
   223  	// Start up a dispatcher to feed into the callback
   224  	go func() {
   225  		for {
   226  			select {
   227  			case log := <-ch:
   228  				handler.OnFilterLogs(&Log{&log})
   229  
   230  			case err := <-rawSub.Err():
   231  				handler.OnError(err.Error())
   232  				return
   233  			}
   234  		}
   235  	}()
   236  	return &Subscription{rawSub}, nil
   237  }
   238  
   239  // Pending State
   240  
   241  // GetPendingBalanceAt returns the wei balance of the given account in the pending state.
   242  func (ec *EthereumClient) GetPendingBalanceAt(ctx *Context, account *Address) (balance *BigInt, _ error) {
   243  	rawBalance, err := ec.client.PendingBalanceAt(ctx.context, account.address)
   244  	return &BigInt{rawBalance}, err
   245  }
   246  
   247  // GetPendingStorageAt returns the value of key in the contract storage of the given account in the pending state.
   248  func (ec *EthereumClient) GetPendingStorageAt(ctx *Context, account *Address, key *Hash) (storage []byte, _ error) {
   249  	return ec.client.PendingStorageAt(ctx.context, account.address, key.hash)
   250  }
   251  
   252  // GetPendingCodeAt returns the contract code of the given account in the pending state.
   253  func (ec *EthereumClient) GetPendingCodeAt(ctx *Context, account *Address) (code []byte, _ error) {
   254  	return ec.client.PendingCodeAt(ctx.context, account.address)
   255  }
   256  
   257  // GetPendingNonceAt returns the account nonce of the given account in the pending state.
   258  // This is the nonce that should be used for the next transaction.
   259  func (ec *EthereumClient) GetPendingNonceAt(ctx *Context, account *Address) (nonce int64, _ error) {
   260  	rawNonce, err := ec.client.PendingNonceAt(ctx.context, account.address)
   261  	return int64(rawNonce), err
   262  }
   263  
   264  // GetPendingTransactionCount returns the total number of transactions in the pending state.
   265  func (ec *EthereumClient) GetPendingTransactionCount(ctx *Context) (count int, _ error) {
   266  	rawCount, err := ec.client.PendingTransactionCount(ctx.context)
   267  	return int(rawCount), err
   268  }
   269  
   270  // Contract Calling
   271  
   272  // CallContract executes a message call transaction, which is directly executed in the VM
   273  // of the node, but never mined into the blockchain.
   274  //
   275  // blockNumber selects the block height at which the call runs. It can be <0, in which
   276  // case the code is taken from the latest known block. Note that state from very old
   277  // blocks might not be available.
   278  func (ec *EthereumClient) CallContract(ctx *Context, msg *CallMsg, number int64) (output []byte, _ error) {
   279  	if number < 0 {
   280  		return ec.client.CallContract(ctx.context, msg.msg, nil)
   281  	}
   282  	return ec.client.CallContract(ctx.context, msg.msg, big.NewInt(number))
   283  }
   284  
   285  // add by liangc
   286  func (ec *EthereumClient) CallContractWithHash(ctx *Context, msg *CallMsg, blockHash common.Hash) (output []byte, _ error) {
   287  	return ec.client.CallContractWithHash(ctx.context, msg.msg, blockHash)
   288  }
   289  
   290  // PendingCallContract executes a message call transaction using the EVM.
   291  // The state seen by the contract call is the pending state.
   292  func (ec *EthereumClient) PendingCallContract(ctx *Context, msg *CallMsg) (output []byte, _ error) {
   293  	return ec.client.PendingCallContract(ctx.context, msg.msg)
   294  }
   295  
   296  // SuggestGasPrice retrieves the currently suggested gas price to allow a timely
   297  // execution of a transaction.
   298  func (ec *EthereumClient) SuggestGasPrice(ctx *Context) (price *BigInt, _ error) {
   299  	rawPrice, err := ec.client.SuggestGasPrice(ctx.context)
   300  	return &BigInt{rawPrice}, err
   301  }
   302  
   303  // EstimateGas tries to estimate the gas needed to execute a specific transaction based on
   304  // the current pending state of the backend blockchain. There is no guarantee that this is
   305  // the true gas limit requirement as other transactions may be added or removed by miners,
   306  // but it should provide a basis for setting a reasonable default.
   307  func (ec *EthereumClient) EstimateGas(ctx *Context, msg *CallMsg) (gas *BigInt, _ error) {
   308  	rawGas, err := ec.client.EstimateGas(ctx.context, msg.msg)
   309  	return &BigInt{rawGas}, err
   310  }
   311  
   312  // SendTransaction injects a signed transaction into the pending pool for execution.
   313  //
   314  // If the transaction was a contract creation use the TransactionReceipt method to get the
   315  // contract address after the transaction has been mined.
   316  func (ec *EthereumClient) SendTransaction(ctx *Context, tx *Transaction) error {
   317  	return ec.client.SendTransaction(ctx.context, tx.tx)
   318  }