github.com/insight-chain/inb-go@v1.1.3-0.20191221022159-da049980ae38/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 MiningReward, 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/insight-chain/inb-go"
    28  	"github.com/insight-chain/inb-go/common"
    29  	"github.com/insight-chain/inb-go/common/hexutil"
    30  	"github.com/insight-chain/inb-go/core/types"
    31  	"github.com/insight-chain/inb-go/rlp"
    32  	"github.com/insight-chain/inb-go/rpc"
    33  
    34  	"encoding/hex"
    35  	"github.com/insight-chain/inb-go/core/state"
    36  	"github.com/insight-chain/inb-go/crypto"
    37  	"log"
    38  )
    39  
    40  //var SdkRpcTx *RpcTransaction
    41  // Client defines typed wrappers for the Ethereum RPC API.
    42  type Client struct {
    43  	c *rpc.Client
    44  }
    45  
    46  //Client received transaction
    47  type SdkTransaction struct {
    48  	Nonce       uint64
    49  	FromAddress common.Address
    50  	ToAddress   common.Address
    51  	Amount      *big.Int
    52  	//	gasLimit uint64
    53  	Data   []byte
    54  	TxType types.TxType
    55  }
    56  
    57  // sdk recevieve SdkHeader
    58  type SdkHeader struct {
    59  	ParentHash       common.Hash      `json:"parentHash"       gencodec:"required"`
    60  	UncleHash        common.Hash      `json:"sha3Uncles"       gencodec:"required"`
    61  	Coinbase         common.Address   `json:"miner"            gencodec:"required"`
    62  	Root             common.Hash      `json:"stateRoot"        gencodec:"required"`
    63  	TxHash           common.Hash      `json:"transactionsRoot" gencodec:"required"`
    64  	ReceiptHash      common.Hash      `json:"receiptsRoot"     gencodec:"required"`
    65  	Bloom            types.Bloom      `json:"logsBloom"        gencodec:"required"`
    66  	Difficulty       *hexutil.Big     `json:"difficulty"       gencodec:"required"`
    67  	Number           *hexutil.Big     `json:"number"           gencodec:"required"`
    68  	ResLimit         hexutil.Uint64   `json:"resLimit"         gencodec:"required"`
    69  	ResUsed          hexutil.Uint64   `json:"resUsed"          gencodec:"required"`
    70  	Time             *hexutil.Big     `json:"timestamp"        gencodec:"required"`
    71  	Extra            hexutil.Bytes    `json:"extraData"        gencodec:"required"`
    72  	MixDigest        common.Hash      `json:"mixHash"`
    73  	Nonce            types.BlockNonce `json:"nonce"`
    74  	DataRoot         common.Hash      `json:"dataRoot"`
    75  	Reward           string           `json:"reward"           gencodec:"required"`
    76  	SpecialConsensus []byte           `json:"specialConsensus"  gencodec:"required"`
    77  	//VdposContext     *VdposContextProto `json:"vdposContext"     gencodec:"required"`
    78  	Hash common.Hash `json:"hash"`
    79  }
    80  
    81  //SignTransactionResult
    82  type SignTransactionResult struct {
    83  	Raw hexutil.Bytes      `json:"raw"`
    84  	Tx  *types.Transaction `json:"tx"`
    85  }
    86  
    87  // Dial connects a client to the given URL.
    88  func Dial(rawurl string) (*Client, error) {
    89  	return DialContext(context.Background(), rawurl)
    90  }
    91  
    92  func DialContext(ctx context.Context, rawurl string) (*Client, error) {
    93  	c, err := rpc.DialContext(ctx, rawurl)
    94  	if err != nil {
    95  		return nil, err
    96  	}
    97  	return NewClient(c), nil
    98  }
    99  
   100  // NewClient creates a client that uses the given RPC client.
   101  func NewClient(c *rpc.Client) *Client {
   102  	return &Client{c}
   103  }
   104  
   105  func (ec *Client) Close() {
   106  	ec.c.Close()
   107  }
   108  
   109  // Blockchain Access
   110  
   111  // BlockByHash returns the given full block.
   112  //
   113  // Note that loading full blocks requires two requests. Use HeaderByHash
   114  // if you don't need all transactions or uncle headers.
   115  func (ec *Client) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
   116  	return ec.getBlock(ctx, "inb_getBlockByHash", hash, true)
   117  }
   118  
   119  // BlockByNumber returns a block from the current canonical chain. If number is nil, the
   120  // latest known block is returned.
   121  //
   122  // Note that loading full blocks requires two requests. Use HeaderByNumber
   123  // if you don't need all transactions or uncle headers.
   124  func (ec *Client) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) {
   125  	return ec.getBlock(ctx, "inb_getBlockByNumber", toBlockNumArg(number), true)
   126  }
   127  
   128  type rpcBlock struct {
   129  	Hash         common.Hash      `json:"hash"`
   130  	Transactions []RpcTransaction `json:"transactions"`
   131  	UncleHashes  []common.Hash    `json:"uncles"`
   132  }
   133  
   134  func (ec *Client) getBlock(ctx context.Context, method string, args ...interface{}) (*types.Block, error) {
   135  	var raw json.RawMessage
   136  	err := ec.c.CallContext(ctx, &raw, method, args...)
   137  	if err != nil {
   138  		return nil, err
   139  	} else if len(raw) == 0 {
   140  		return nil, ethereum.NotFound
   141  	}
   142  	// Decode header and transactions.
   143  	var head *types.Header
   144  	var body rpcBlock
   145  	if err := json.Unmarshal(raw, &head); err != nil {
   146  		return nil, err
   147  	}
   148  	if err := json.Unmarshal(raw, &body); err != nil {
   149  		return nil, err
   150  	}
   151  	// Quick-verify transaction and uncle lists. This mostly helps with debugging the server.
   152  	if head.UncleHash == types.EmptyUncleHash && len(body.UncleHashes) > 0 {
   153  		return nil, fmt.Errorf("server returned non-empty uncle list but block header indicates no uncles")
   154  	}
   155  	if head.UncleHash != types.EmptyUncleHash && len(body.UncleHashes) == 0 {
   156  		return nil, fmt.Errorf("server returned empty uncle list but block header indicates uncles")
   157  	}
   158  	if head.TxHash == types.EmptyRootHash && len(body.Transactions) > 0 {
   159  		return nil, fmt.Errorf("server returned non-empty transaction list but block header indicates no transactions")
   160  	}
   161  	if head.TxHash != types.EmptyRootHash && len(body.Transactions) == 0 {
   162  		return nil, fmt.Errorf("server returned empty transaction list but block header indicates transactions")
   163  	}
   164  	// Load uncles because they are not included in the block response.
   165  	var uncles []*types.Header
   166  	if len(body.UncleHashes) > 0 {
   167  		uncles = make([]*types.Header, len(body.UncleHashes))
   168  		reqs := make([]rpc.BatchElem, len(body.UncleHashes))
   169  		for i := range reqs {
   170  			reqs[i] = rpc.BatchElem{
   171  				Method: "inb_getUncleByBlockHashAndIndex",
   172  				Args:   []interface{}{body.Hash, hexutil.EncodeUint64(uint64(i))},
   173  				Result: &uncles[i],
   174  			}
   175  		}
   176  		if err := ec.c.BatchCallContext(ctx, reqs); err != nil {
   177  			return nil, err
   178  		}
   179  		for i := range reqs {
   180  			if reqs[i].Error != nil {
   181  				return nil, reqs[i].Error
   182  			}
   183  			if uncles[i] == nil {
   184  				return nil, fmt.Errorf("got null header for uncle %d of block %x", i, body.Hash[:])
   185  			}
   186  		}
   187  	}
   188  	// Fill the sender cache of transactions in the block.
   189  	txs := make([]*types.Transaction, len(body.Transactions))
   190  	for i, tx := range body.Transactions {
   191  		if tx.From != nil {
   192  			setSenderFromServer(tx.tx, *tx.From, body.Hash)
   193  		}
   194  		txs[i] = tx.tx
   195  	}
   196  	return types.NewBlockWithHeader(head).WithBody(txs, uncles), nil
   197  }
   198  
   199  // HeaderByHash returns the block header with the given hash.
   200  func (ec *Client) HeaderByHash(ctx context.Context, hash common.Hash) (*SdkHeader, error) {
   201  	var head *SdkHeader
   202  	err := ec.c.CallContext(ctx, &head, "inb_getBlockByHash", hash, false)
   203  	if err == nil && head == nil {
   204  		err = ethereum.NotFound
   205  	}
   206  	return head, err
   207  }
   208  
   209  // start by cq
   210  //get account balance
   211  /*func (ec *Client) GetBalance(address string) string {
   212  	toAddress := common.HexToAddress(address)
   213  	balance, err := ec.BalanceAt(context.Background(), toAddress, nil)
   214  	if err != nil {
   215  		log.Fatal(err)
   216  	}
   217  	return balance.String()
   218  }*/
   219  func (ec *Client) NewTransaction(chainId *big.Int, nonce uint64, priv string, to string, value *big.Int, data string, txtype types.TxType) (*types.Transaction, error) {
   220  	txdata := []byte(data)
   221  	var tx = new(types.Transaction)
   222  	if common.IsHexAddress(to) {
   223  		toaddr := common.HexToAddress(to)
   224  		tx = types.NewTransaction(nonce, toaddr, value, 0, txdata, txtype)
   225  	} else {
   226  		tx = types.NewNilToTransaction(nonce, value, 0, txdata, txtype)
   227  	}
   228  	key, err := crypto.HexToECDSA(priv)
   229  	if err != nil {
   230  		log.Fatal(err)
   231  		return nil, err
   232  	}
   233  	signedTx, err := types.SignTx(tx, types.NewEIP155Signer(chainId), key)
   234  	if err != nil {
   235  		log.Fatal(err)
   236  		return nil, err
   237  	}
   238  	return signedTx, nil
   239  }
   240  
   241  //special Transaction for receive ReceiveLockedAward
   242  func (ec *Client) NewTransactionForRLA(chainId *big.Int, nonce uint64, priv string, to string, value *big.Int, data []byte, txtype types.TxType) (*types.Transaction, error) {
   243  	//txdata := []byte(data)
   244  	var tx = new(types.Transaction)
   245  	if common.IsHexAddress(to) {
   246  		toaddr := common.HexToAddress(to)
   247  		tx = types.NewTransaction(nonce, toaddr, value, 0, data, txtype)
   248  	} else {
   249  		tx = types.NewNilToTransaction(nonce, value, 0, data, txtype)
   250  	}
   251  	key, err := crypto.HexToECDSA(priv)
   252  	if err != nil {
   253  		log.Fatal(err)
   254  		return nil, err
   255  	}
   256  	signedTx, err := types.SignTx(tx, types.NewEIP155Signer(chainId), key)
   257  	if err != nil {
   258  		log.Fatal(err)
   259  		return nil, err
   260  	}
   261  	return signedTx, nil
   262  }
   263  
   264  //create a raw transaction
   265  func (ec *Client) NewRawTx(chainId *big.Int, nonce uint64, priv, to, resourcePayer string, value *big.Int, data string, txtype types.TxType) (string, error) {
   266  	txdata := []byte(data)
   267  	payment := common.HexToAddress(resourcePayer)
   268  	tx := types.NewTransaction4Payment(nonce, common.HexToAddress(to), value, 0, txdata, txtype, &payment)
   269  	privKey, err := crypto.HexToECDSA(priv)
   270  	if err != nil {
   271  		log.Fatal(err)
   272  		return "", err
   273  	}
   274  	signedTx, err := types.SignTx(tx, types.NewEIP155Signer(chainId), privKey)
   275  	ts := types.Transactions{signedTx}
   276  	rawTxBytes := ts.GetRlp(0)
   277  	rawTx := &types.Transaction{}
   278  	if err := rlp.DecodeBytes(rawTxBytes, rawTx); err != nil {
   279  		return "", err
   280  	}
   281  	rawTxHex := hex.EncodeToString(rawTxBytes)
   282  	//fmt.Println("rawTx_str:", hex.EncodeToString(rawTxBytes))
   283  	return rawTxHex, nil
   284  }
   285  
   286  //send signPayTX
   287  func (ec *Client) SignPaymentTx(chainId *big.Int, rawTxHex string, resourcePayerPriv string) (*SignTransactionResult, error) {
   288  	rawTxBytes, err := hex.DecodeString(rawTxHex)
   289  	tx := new(types.Transaction)
   290  	if err := rlp.DecodeBytes(rawTxBytes, tx); err != nil {
   291  		return nil, err
   292  	}
   293  	key, err := crypto.HexToECDSA(resourcePayerPriv)
   294  	if err != nil {
   295  		log.Fatal(err)
   296  		return nil, err
   297  	}
   298  	//sign for rawTx.......
   299  	payTx, err := types.SignTx(tx, types.NewEIP155Signer(chainId), key)
   300  
   301  	if err != nil {
   302  		return nil, err
   303  	}
   304  	returnData, err := rlp.EncodeToBytes(payTx)
   305  	if err != nil {
   306  		return nil, err
   307  	}
   308  	return &SignTransactionResult{returnData, payTx}, nil
   309  }
   310  
   311  //send raw Transaction
   312  func (ec *Client) SendRawTx(rawTx string) (string, error) {
   313  	rawTxT := rawTx[2:]
   314  	rawTxBytes, err := hex.DecodeString(rawTxT)
   315  	if err != nil {
   316  		log.Fatal(err)
   317  		return "", err
   318  	}
   319  	tx := new(types.Transaction)
   320  	rlp.DecodeBytes(rawTxBytes, &tx)
   321  	err = ec.SendTransaction(context.Background(), tx)
   322  	if err != nil {
   323  		log.Fatal(err)
   324  		return "", err
   325  	}
   326  	return tx.Hash().Hex(), nil
   327  }
   328  
   329  //test rawTx
   330  func (ec *Client) RawTransaction(chainId *big.Int, nonce uint64, priv string, to string, value *big.Int, data string, txtype types.TxType) (*types.Transaction, error) {
   331  	txdata := []byte(data)
   332  	var tx = new(types.Transaction)
   333  	if common.IsHexAddress(to) {
   334  		toaddr := common.HexToAddress(to)
   335  		tx = types.NewTransaction(nonce, toaddr, value, 0, txdata, txtype)
   336  	} else {
   337  		tx = types.NewNilToTransaction(nonce, value, 0, txdata, txtype)
   338  	}
   339  	key, err := crypto.HexToECDSA(priv)
   340  	if err != nil {
   341  		log.Fatal(err)
   342  		return nil, err
   343  	}
   344  	signedTx, err := types.SignTx(tx, types.NewEIP155Signer(chainId), key)
   345  	if err != nil {
   346  		log.Fatal(err)
   347  		return nil, err
   348  	}
   349  	return signedTx, nil
   350  }
   351  
   352  //get account info
   353  func (ec *Client) AccountInfo(ctx context.Context, account common.Address) (*state.Account, error) {
   354  	var accountInfo *state.Account
   355  	err := ec.c.CallContext(ctx, &accountInfo, "inb_getAccountInfo", account)
   356  	if err == nil && accountInfo == nil {
   357  		err = ethereum.NotFound
   358  	}
   359  	return accountInfo, err
   360  }
   361  
   362  //send wrapped transaction
   363  func (ec *Client) SdkSendTransaction(tx *types.Transaction) (string, error) {
   364  	err := ec.SendTransaction(context.Background(), tx)
   365  	if err != nil {
   366  		return "", err
   367  	}
   368  	return tx.Hash().Hex(), nil
   369  }
   370  
   371  //end by cq
   372  
   373  // HeaderByNumber returns a block header from the current canonical chain. If number is
   374  // nil, the latest known header is returned.
   375  func (ec *Client) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
   376  	var head *types.Header
   377  	err := ec.c.CallContext(ctx, &head, "inb_getBlockByNumber", toBlockNumArg(number), false)
   378  	if err == nil && head == nil {
   379  		err = ethereum.NotFound
   380  	}
   381  	return head, err
   382  }
   383  
   384  type RpcTransaction struct {
   385  	tx *types.Transaction
   386  	txExtraInfo
   387  }
   388  
   389  type txExtraInfo struct {
   390  	BlockNumber *string         `json:"blockNumber,omitempty"`
   391  	BlockHash   *common.Hash    `json:"blockHash,omitempty"`
   392  	From        *common.Address `json:"from,omitempty"`
   393  }
   394  
   395  func (tx *RpcTransaction) UnmarshalJSON(msg []byte) error {
   396  	if err := json.Unmarshal(msg, &tx.tx); err != nil {
   397  		return err
   398  	}
   399  	return json.Unmarshal(msg, &tx.txExtraInfo)
   400  }
   401  
   402  // TransactionByHash returns the transaction with the given hash.
   403  func (ec *Client) TransactionByHash(ctx context.Context, hash common.Hash) (tx *RpcTransaction, isPending bool, err error) {
   404  	var json *RpcTransaction
   405  	err = ec.c.CallContext(ctx, &json, "inb_getTransactionByHash", hash)
   406  	fmt.Println()
   407  	if err != nil {
   408  		return nil, false, err
   409  	} else if json == nil {
   410  		return nil, false, ethereum.NotFound
   411  	} else if _, r, _ := json.tx.RawSignatureValues(); r == nil {
   412  		return nil, false, fmt.Errorf("server returned transaction without signature")
   413  	}
   414  	if json.From != nil && json.BlockHash != nil {
   415  		setSenderFromServer(json.tx, *json.From, *json.BlockHash)
   416  	}
   417  	return json, json.BlockNumber == nil, nil
   418  }
   419  
   420  // TransactionSender returns the sender address of the given transaction. The transaction
   421  // must be known to the remote node and included in the blockchain at the given block and
   422  // index. The sender is the one derived by the protocol at the time of inclusion.
   423  //
   424  // There is a fast-path for transactions retrieved by TransactionByHash and
   425  // TransactionInBlock. Getting their sender address can be done without an RPC interaction.
   426  func (ec *Client) TransactionSender(ctx context.Context, tx *types.Transaction, block common.Hash, index uint) (common.Address, error) {
   427  	// Try to load the address from the cache.
   428  	sender, err := types.Sender(&senderFromServer{blockhash: block}, tx)
   429  	if err == nil {
   430  		return sender, nil
   431  	}
   432  	var meta struct {
   433  		Hash common.Hash
   434  		From common.Address
   435  	}
   436  	if err = ec.c.CallContext(ctx, &meta, "inb_getTransactionByBlockHashAndIndex", block, hexutil.Uint64(index)); err != nil {
   437  		return common.Address{}, err
   438  	}
   439  	if meta.Hash == (common.Hash{}) || meta.Hash != tx.Hash() {
   440  		return common.Address{}, errors.New("wrong inclusion block/index")
   441  	}
   442  	return meta.From, nil
   443  }
   444  
   445  // TransactionCount returns the total number of transactions in the given block.
   446  func (ec *Client) TransactionCount(ctx context.Context, blockHash common.Hash) (uint, error) {
   447  	var num hexutil.Uint
   448  	err := ec.c.CallContext(ctx, &num, "inb_getBlockTransactionCountByHash", blockHash)
   449  	return uint(num), err
   450  }
   451  
   452  // TransactionInBlock returns a single transaction at index in the given block.
   453  func (ec *Client) TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (*types.Transaction, error) {
   454  	var json *RpcTransaction
   455  	err := ec.c.CallContext(ctx, &json, "inb_getTransactionByBlockHashAndIndex", blockHash, hexutil.Uint64(index))
   456  	if err == nil {
   457  		if json == nil {
   458  			return nil, ethereum.NotFound
   459  		} else if _, r, _ := json.tx.RawSignatureValues(); r == nil {
   460  			return nil, fmt.Errorf("server returned transaction without signature")
   461  		}
   462  	}
   463  	if json.From != nil && json.BlockHash != nil {
   464  		setSenderFromServer(json.tx, *json.From, *json.BlockHash)
   465  	}
   466  	return json.tx, err
   467  }
   468  
   469  // TransactionReceipt returns the receipt of a transaction by transaction hash.
   470  // Note that the receipt is not available for pending transactions.
   471  func (ec *Client) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) {
   472  	var r *types.Receipt
   473  	err := ec.c.CallContext(ctx, &r, "inb_getTransactionReceipt", txHash)
   474  	if err == nil {
   475  		if r == nil {
   476  			return nil, ethereum.NotFound
   477  		}
   478  	}
   479  	return r, err
   480  }
   481  
   482  func toBlockNumArg(number *big.Int) string {
   483  	if number == nil {
   484  		return "latest"
   485  	}
   486  	return hexutil.EncodeBig(number)
   487  }
   488  
   489  type rpcProgress struct {
   490  	StartingBlock hexutil.Uint64
   491  	CurrentBlock  hexutil.Uint64
   492  	HighestBlock  hexutil.Uint64
   493  	PulledStates  hexutil.Uint64
   494  	KnownStates   hexutil.Uint64
   495  }
   496  
   497  // SyncProgress retrieves the current progress of the sync algorithm. If there's
   498  // no sync currently running, it returns nil.
   499  func (ec *Client) SyncProgress(ctx context.Context) (*ethereum.SyncProgress, error) {
   500  	var raw json.RawMessage
   501  	if err := ec.c.CallContext(ctx, &raw, "inb_syncing"); err != nil {
   502  		return nil, err
   503  	}
   504  	// Handle the possible response types
   505  	var syncing bool
   506  	if err := json.Unmarshal(raw, &syncing); err == nil {
   507  		return nil, nil // Not syncing (always false)
   508  	}
   509  	var progress *rpcProgress
   510  	if err := json.Unmarshal(raw, &progress); err != nil {
   511  		return nil, err
   512  	}
   513  	return &ethereum.SyncProgress{
   514  		StartingBlock: uint64(progress.StartingBlock),
   515  		CurrentBlock:  uint64(progress.CurrentBlock),
   516  		HighestBlock:  uint64(progress.HighestBlock),
   517  		PulledStates:  uint64(progress.PulledStates),
   518  		KnownStates:   uint64(progress.KnownStates),
   519  	}, nil
   520  }
   521  
   522  // SubscribeNewHead subscribes to notifications about the current blockchain head
   523  // on the given channel.
   524  func (ec *Client) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (ethereum.Subscription, error) {
   525  	return ec.c.EthSubscribe(ctx, ch, "newHeads")
   526  }
   527  
   528  // State Access
   529  
   530  // NetworkID returns the network ID (also known as the chain ID) for this chain.
   531  func (ec *Client) NetworkID(ctx context.Context) (*big.Int, error) {
   532  	version := new(big.Int)
   533  	var ver string
   534  	if err := ec.c.CallContext(ctx, &ver, "net_version"); err != nil {
   535  		return nil, err
   536  	}
   537  	if _, ok := version.SetString(ver, 10); !ok {
   538  		return nil, fmt.Errorf("invalid net_version result %q", ver)
   539  	}
   540  	return version, nil
   541  }
   542  
   543  // BalanceAt returns the wei balance of the given account.
   544  // The block number can be nil, in which case the balance is taken from the latest known block.
   545  func (ec *Client) BalanceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (*big.Int, error) {
   546  	var result hexutil.Big
   547  	err := ec.c.CallContext(ctx, &result, "inb_getBalance", account, toBlockNumArg(blockNumber))
   548  	return (*big.Int)(&result), err
   549  }
   550  
   551  //Resource  by zc
   552  func (ec *Client) NetAt(ctx context.Context, account common.Address, blockNumber *big.Int) (*big.Int, error) {
   553  	var result hexutil.Big
   554  	err := ec.c.CallContext(ctx, &result, "inb_getRes", account, toBlockNumArg(blockNumber))
   555  	return (*big.Int)(&result), err
   556  }
   557  
   558  //Resource  by zc
   559  // StorageAt returns the value of key in the contract storage of the given account.
   560  // The block number can be nil, in which case the value is taken from the latest known block.
   561  func (ec *Client) StorageAt(ctx context.Context, account common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error) {
   562  	var result hexutil.Bytes
   563  	err := ec.c.CallContext(ctx, &result, "inb_getStorageAt", account, key, toBlockNumArg(blockNumber))
   564  	return result, err
   565  }
   566  
   567  // CodeAt returns the contract code of the given account.
   568  // The block number can be nil, in which case the code is taken from the latest known block.
   569  func (ec *Client) CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error) {
   570  	var result hexutil.Bytes
   571  	err := ec.c.CallContext(ctx, &result, "inb_getCode", account, toBlockNumArg(blockNumber))
   572  	return result, err
   573  }
   574  
   575  // NonceAt returns the account nonce of the given account.
   576  // The block number can be nil, in which case the nonce is taken from the latest known block.
   577  func (ec *Client) NonceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (uint64, error) {
   578  	var result hexutil.Uint64
   579  	err := ec.c.CallContext(ctx, &result, "inb_getTransactionCount", account, toBlockNumArg(blockNumber))
   580  	return uint64(result), err
   581  }
   582  
   583  // Filters
   584  
   585  // FilterLogs executes a filter query.
   586  func (ec *Client) FilterLogs(ctx context.Context, q ethereum.FilterQuery) ([]types.Log, error) {
   587  	var result []types.Log
   588  	arg, err := toFilterArg(q)
   589  	if err != nil {
   590  		return nil, err
   591  	}
   592  	err = ec.c.CallContext(ctx, &result, "inb_getLogs", arg)
   593  	return result, err
   594  }
   595  
   596  // SubscribeFilterLogs subscribes to the results of a streaming filter query.
   597  func (ec *Client) SubscribeFilterLogs(ctx context.Context, q ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) {
   598  	arg, err := toFilterArg(q)
   599  	if err != nil {
   600  		return nil, err
   601  	}
   602  	return ec.c.EthSubscribe(ctx, ch, "logs", arg)
   603  }
   604  
   605  func toFilterArg(q ethereum.FilterQuery) (interface{}, error) {
   606  	arg := map[string]interface{}{
   607  		"address": q.Addresses,
   608  		"topics":  q.Topics,
   609  	}
   610  	if q.BlockHash != nil {
   611  		arg["blockHash"] = *q.BlockHash
   612  		if q.FromBlock != nil || q.ToBlock != nil {
   613  			return nil, fmt.Errorf("cannot specify both BlockHash and FromBlock/ToBlock")
   614  		}
   615  	} else {
   616  		if q.FromBlock == nil {
   617  			arg["fromBlock"] = "0x0"
   618  		} else {
   619  			arg["fromBlock"] = toBlockNumArg(q.FromBlock)
   620  		}
   621  		arg["toBlock"] = toBlockNumArg(q.ToBlock)
   622  	}
   623  	return arg, nil
   624  }
   625  
   626  // Pending State
   627  
   628  // PendingBalanceAt returns the wei balance of the given account in the pending state.
   629  func (ec *Client) PendingBalanceAt(ctx context.Context, account common.Address) (*big.Int, error) {
   630  	var result hexutil.Big
   631  	err := ec.c.CallContext(ctx, &result, "inb_getBalance", account, "pending")
   632  	return (*big.Int)(&result), err
   633  }
   634  
   635  //Resource by zc
   636  //func (ec *Client) PendingCpuAt(ctx context.Context, account common.Address) (*big.Int, error) {
   637  //	var result hexutil.Big
   638  //	err := ec.c.CallContext(ctx, &result, "inb_getCpu", account, "pending")
   639  //	return (*big.Int)(&result), err
   640  //}
   641  func (ec *Client) PendingNetAt(ctx context.Context, account common.Address) (*big.Int, error) {
   642  	var result hexutil.Big
   643  	err := ec.c.CallContext(ctx, &result, "inb_getRes", account, "pending")
   644  	return (*big.Int)(&result), err
   645  }
   646  
   647  //Resource by zc
   648  // PendingStorageAt returns the value of key in the contract storage of the given account in the pending state.
   649  func (ec *Client) PendingStorageAt(ctx context.Context, account common.Address, key common.Hash) ([]byte, error) {
   650  	var result hexutil.Bytes
   651  	err := ec.c.CallContext(ctx, &result, "inb_getStorageAt", account, key, "pending")
   652  	return result, err
   653  }
   654  
   655  // PendingCodeAt returns the contract code of the given account in the pending state.
   656  func (ec *Client) PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error) {
   657  	var result hexutil.Bytes
   658  	err := ec.c.CallContext(ctx, &result, "inb_getCode", account, "pending")
   659  	return result, err
   660  }
   661  
   662  // PendingNonceAt returns the account nonce of the given account in the pending state.
   663  // This is the nonce that should be used for the next transaction.
   664  func (ec *Client) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
   665  	var result hexutil.Uint64
   666  	err := ec.c.CallContext(ctx, &result, "inb_getTransactionCount", account, "pending")
   667  	return uint64(result), err
   668  }
   669  
   670  // PendingTransactionCount returns the total number of transactions in the pending state.
   671  func (ec *Client) PendingTransactionCount(ctx context.Context) (uint, error) {
   672  	var num hexutil.Uint
   673  	err := ec.c.CallContext(ctx, &num, "inb_getBlockTransactionCountByNumber", "pending")
   674  	return uint(num), err
   675  }
   676  
   677  // TODO: SubscribePendingTransactions (needs server side)
   678  
   679  // Contract Calling
   680  
   681  // CallContract executes a message call transaction, which is directly executed in the VM
   682  // of the node, but never mined into the blockchain.
   683  //
   684  // blockNumber selects the block height at which the call runs. It can be nil, in which
   685  // case the code is taken from the latest known block. Note that state from very old
   686  // blocks might not be available.
   687  func (ec *Client) CallContract(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
   688  	var hex hexutil.Bytes
   689  	err := ec.c.CallContext(ctx, &hex, "inb_call", toCallArg(msg), toBlockNumArg(blockNumber))
   690  	if err != nil {
   691  		return nil, err
   692  	}
   693  	return hex, nil
   694  }
   695  
   696  // PendingCallContract executes a message call transaction using the EVM.
   697  // The state seen by the contract call is the pending state.
   698  func (ec *Client) PendingCallContract(ctx context.Context, msg ethereum.CallMsg) ([]byte, error) {
   699  	var hex hexutil.Bytes
   700  	err := ec.c.CallContext(ctx, &hex, "inb_call", toCallArg(msg), "pending")
   701  	if err != nil {
   702  		return nil, err
   703  	}
   704  	return hex, nil
   705  }
   706  
   707  // SuggestGasPrice retrieves the currently suggested gas price to allow a timely
   708  // execution of a transaction.
   709  func (ec *Client) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
   710  	var hex hexutil.Big
   711  	if err := ec.c.CallContext(ctx, &hex, "inb_gasPrice"); err != nil {
   712  		return nil, err
   713  	}
   714  	return (*big.Int)(&hex), nil
   715  }
   716  
   717  // EstimateGas tries to estimate the gas needed to execute a specific transaction based on
   718  // the current pending state of the backend blockchain. There is no guarantee that this is
   719  // the true gas limit requirement as other transactions may be added or removed by miners,
   720  // but it should provide a basis for setting a reasonable default.
   721  func (ec *Client) EstimateGas(ctx context.Context, msg ethereum.CallMsg) (uint64, error) {
   722  	var hex hexutil.Uint64
   723  	err := ec.c.CallContext(ctx, &hex, "inb_estimateGas", toCallArg(msg))
   724  	if err != nil {
   725  		return 0, err
   726  	}
   727  	return uint64(hex), nil
   728  }
   729  
   730  // SendTransaction injects a signed transaction into the pending pool for execution.
   731  //
   732  // If the transaction was a contract creation use the TransactionReceipt method to get the
   733  // contract address after the transaction has been mined.
   734  func (ec *Client) SendTransaction(ctx context.Context, tx *types.Transaction) error {
   735  	data, err := rlp.EncodeToBytes(tx)
   736  	if err != nil {
   737  		return err
   738  	}
   739  	return ec.c.CallContext(ctx, nil, "inb_sendRawTransaction", common.ToHex(data))
   740  }
   741  
   742  func toCallArg(msg ethereum.CallMsg) interface{} {
   743  	arg := map[string]interface{}{
   744  		"from": msg.From,
   745  		"to":   msg.To,
   746  	}
   747  	if len(msg.Data) > 0 {
   748  		arg["data"] = hexutil.Bytes(msg.Data)
   749  	}
   750  	if msg.Value != nil {
   751  		arg["value"] = (*hexutil.Big)(msg.Value)
   752  	}
   753  	if msg.Net != 0 {
   754  		arg["net"] = hexutil.Uint64(msg.Net)
   755  	}
   756  	//if msg.GasPrice != nil {
   757  	//	arg["gasPrice"] = (*hexutil.Big)(msg.GasPrice)
   758  	//}
   759  	return arg
   760  }