github.com/cryptotooltop/go-ethereum@v0.0.0-20231103184714-151d1922f3e5/ethclient/gethclient/gethclient.go (about)

     1  // Copyright 2021 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 gethclient provides an RPC client for geth-specific APIs.
    18  package gethclient
    19  
    20  import (
    21  	"context"
    22  	"math/big"
    23  	"runtime"
    24  	"runtime/debug"
    25  
    26  	"github.com/scroll-tech/go-ethereum"
    27  	"github.com/scroll-tech/go-ethereum/common"
    28  	"github.com/scroll-tech/go-ethereum/common/hexutil"
    29  	"github.com/scroll-tech/go-ethereum/core/types"
    30  	"github.com/scroll-tech/go-ethereum/p2p"
    31  	"github.com/scroll-tech/go-ethereum/rpc"
    32  )
    33  
    34  // Client is a wrapper around rpc.Client that implements geth-specific functionality.
    35  //
    36  // If you want to use the standardized Ethereum RPC functionality, use ethclient.Client instead.
    37  type Client struct {
    38  	c *rpc.Client
    39  }
    40  
    41  // New creates a client that uses the given RPC client.
    42  func New(c *rpc.Client) *Client {
    43  	return &Client{c}
    44  }
    45  
    46  // CreateAccessList tries to create an access list for a specific transaction based on the
    47  // current pending state of the blockchain.
    48  func (ec *Client) CreateAccessList(ctx context.Context, msg ethereum.CallMsg) (*types.AccessList, uint64, string, error) {
    49  	type accessListResult struct {
    50  		Accesslist *types.AccessList `json:"accessList"`
    51  		Error      string            `json:"error,omitempty"`
    52  		GasUsed    hexutil.Uint64    `json:"gasUsed"`
    53  	}
    54  	var result accessListResult
    55  	if err := ec.c.CallContext(ctx, &result, "eth_createAccessList", toCallArg(msg)); err != nil {
    56  		return nil, 0, "", err
    57  	}
    58  	return result.Accesslist, uint64(result.GasUsed), result.Error, nil
    59  }
    60  
    61  // AccountResult is the result of a GetProof operation.
    62  type AccountResult struct {
    63  	Address          common.Address  `json:"address"`
    64  	AccountProof     []string        `json:"accountProof"`
    65  	Balance          *big.Int        `json:"balance"`
    66  	KeccakCodeHash   common.Hash     `json:"keccakCodeHash"`
    67  	PoseidonCodeHash common.Hash     `json:"poseidonCodeHash"`
    68  	CodeSize         common.Hash     `json:"codeSize"`
    69  	Nonce            uint64          `json:"nonce"`
    70  	StorageHash      common.Hash     `json:"storageHash"`
    71  	StorageProof     []StorageResult `json:"storageProof"`
    72  }
    73  
    74  // StorageResult provides a proof for a key-value pair.
    75  type StorageResult struct {
    76  	Key   string   `json:"key"`
    77  	Value *big.Int `json:"value"`
    78  	Proof []string `json:"proof"`
    79  }
    80  
    81  // GetProof returns the account and storage values of the specified account including the Merkle-proof.
    82  // The block number can be nil, in which case the value is taken from the latest known block.
    83  func (ec *Client) GetProof(ctx context.Context, account common.Address, keys []string, blockNumber *big.Int) (*AccountResult, error) {
    84  
    85  	type storageResult struct {
    86  		Key   string       `json:"key"`
    87  		Value *hexutil.Big `json:"value"`
    88  		Proof []string     `json:"proof"`
    89  	}
    90  
    91  	type accountResult struct {
    92  		Address          common.Address  `json:"address"`
    93  		AccountProof     []string        `json:"accountProof"`
    94  		Balance          *hexutil.Big    `json:"balance"`
    95  		KeccakCodeHash   common.Hash     `json:"keccakodeHash"`
    96  		PoseidonCodeHash common.Hash     `json:"poseidonCodeHash"`
    97  		CodeSize         common.Hash     `json:"codeSize"`
    98  		Nonce            hexutil.Uint64  `json:"nonce"`
    99  		StorageHash      common.Hash     `json:"storageHash"`
   100  		StorageProof     []storageResult `json:"storageProof"`
   101  	}
   102  
   103  	var res accountResult
   104  	err := ec.c.CallContext(ctx, &res, "eth_getProof", account, keys, toBlockNumArg(blockNumber))
   105  	// Turn hexutils back to normal datatypes
   106  	storageResults := make([]StorageResult, 0, len(res.StorageProof))
   107  	for _, st := range res.StorageProof {
   108  		storageResults = append(storageResults, StorageResult{
   109  			Key:   st.Key,
   110  			Value: st.Value.ToInt(),
   111  			Proof: st.Proof,
   112  		})
   113  	}
   114  	result := AccountResult{
   115  		Address:          res.Address,
   116  		AccountProof:     res.AccountProof,
   117  		Balance:          res.Balance.ToInt(),
   118  		Nonce:            uint64(res.Nonce),
   119  		KeccakCodeHash:   res.KeccakCodeHash,
   120  		PoseidonCodeHash: res.PoseidonCodeHash,
   121  		CodeSize:         res.CodeSize,
   122  		StorageHash:      res.StorageHash,
   123  	}
   124  	return &result, err
   125  }
   126  
   127  // OverrideAccount specifies the state of an account to be overridden.
   128  type OverrideAccount struct {
   129  	Nonce     uint64                      `json:"nonce"`
   130  	Code      []byte                      `json:"code"`
   131  	Balance   *big.Int                    `json:"balance"`
   132  	State     map[common.Hash]common.Hash `json:"state"`
   133  	StateDiff map[common.Hash]common.Hash `json:"stateDiff"`
   134  }
   135  
   136  // CallContract executes a message call transaction, which is directly executed in the VM
   137  // of the node, but never mined into the blockchain.
   138  //
   139  // blockNumber selects the block height at which the call runs. It can be nil, in which
   140  // case the code is taken from the latest known block. Note that state from very old
   141  // blocks might not be available.
   142  //
   143  // overrides specifies a map of contract states that should be overwritten before executing
   144  // the message call.
   145  // Please use ethclient.CallContract instead if you don't need the override functionality.
   146  func (ec *Client) CallContract(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int, overrides *map[common.Address]OverrideAccount) ([]byte, error) {
   147  	var hex hexutil.Bytes
   148  	err := ec.c.CallContext(
   149  		ctx, &hex, "eth_call", toCallArg(msg),
   150  		toBlockNumArg(blockNumber), toOverrideMap(overrides),
   151  	)
   152  	return hex, err
   153  }
   154  
   155  // GCStats retrieves the current garbage collection stats from a geth node.
   156  func (ec *Client) GCStats(ctx context.Context) (*debug.GCStats, error) {
   157  	var result debug.GCStats
   158  	err := ec.c.CallContext(ctx, &result, "debug_gcStats")
   159  	return &result, err
   160  }
   161  
   162  // MemStats retrieves the current memory stats from a geth node.
   163  func (ec *Client) MemStats(ctx context.Context) (*runtime.MemStats, error) {
   164  	var result runtime.MemStats
   165  	err := ec.c.CallContext(ctx, &result, "debug_memStats")
   166  	return &result, err
   167  }
   168  
   169  // SetHead sets the current head of the local chain by block number.
   170  // Note, this is a destructive action and may severely damage your chain.
   171  // Use with extreme caution.
   172  func (ec *Client) SetHead(ctx context.Context, number *big.Int) error {
   173  	return ec.c.CallContext(ctx, nil, "debug_setHead", toBlockNumArg(number))
   174  }
   175  
   176  // GetNodeInfo retrieves the node info of a geth node.
   177  func (ec *Client) GetNodeInfo(ctx context.Context) (*p2p.NodeInfo, error) {
   178  	var result p2p.NodeInfo
   179  	err := ec.c.CallContext(ctx, &result, "admin_nodeInfo")
   180  	return &result, err
   181  }
   182  
   183  // SubscribePendingTransactions subscribes to new pending transactions.
   184  func (ec *Client) SubscribePendingTransactions(ctx context.Context, ch chan<- common.Hash) (*rpc.ClientSubscription, error) {
   185  	return ec.c.EthSubscribe(ctx, ch, "newPendingTransactions")
   186  }
   187  
   188  func toBlockNumArg(number *big.Int) string {
   189  	if number == nil {
   190  		return "latest"
   191  	}
   192  	pending := big.NewInt(-1)
   193  	if number.Cmp(pending) == 0 {
   194  		return "pending"
   195  	}
   196  	return hexutil.EncodeBig(number)
   197  }
   198  
   199  func toCallArg(msg ethereum.CallMsg) interface{} {
   200  	arg := map[string]interface{}{
   201  		"from": msg.From,
   202  		"to":   msg.To,
   203  	}
   204  	if len(msg.Data) > 0 {
   205  		arg["data"] = hexutil.Bytes(msg.Data)
   206  	}
   207  	if msg.Value != nil {
   208  		arg["value"] = (*hexutil.Big)(msg.Value)
   209  	}
   210  	if msg.Gas != 0 {
   211  		arg["gas"] = hexutil.Uint64(msg.Gas)
   212  	}
   213  	if msg.GasPrice != nil {
   214  		arg["gasPrice"] = (*hexutil.Big)(msg.GasPrice)
   215  	}
   216  	return arg
   217  }
   218  
   219  func toOverrideMap(overrides *map[common.Address]OverrideAccount) interface{} {
   220  	if overrides == nil {
   221  		return nil
   222  	}
   223  	type overrideAccount struct {
   224  		Nonce     hexutil.Uint64              `json:"nonce"`
   225  		Code      hexutil.Bytes               `json:"code"`
   226  		Balance   *hexutil.Big                `json:"balance"`
   227  		State     map[common.Hash]common.Hash `json:"state"`
   228  		StateDiff map[common.Hash]common.Hash `json:"stateDiff"`
   229  	}
   230  	result := make(map[common.Address]overrideAccount)
   231  	for addr, override := range *overrides {
   232  		result[addr] = overrideAccount{
   233  			Nonce:     hexutil.Uint64(override.Nonce),
   234  			Code:      override.Code,
   235  			Balance:   (*hexutil.Big)(override.Balance),
   236  			State:     override.State,
   237  			StateDiff: override.StateDiff,
   238  		}
   239  	}
   240  	return &result
   241  }