Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ethclient/gethclient: RPC client wrapper for geth-specific API #22977

Merged
merged 10 commits into from
Jun 30, 2021
46 changes: 23 additions & 23 deletions ethclient/ethclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ func (ec *Client) BlockByHash(ctx context.Context, hash common.Hash) (*types.Blo
// Note that loading full blocks requires two requests. Use HeaderByNumber
// if you don't need all transactions or uncle headers.
func (ec *Client) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) {
return ec.getBlock(ctx, "eth_getBlockByNumber", toBlockNumArg(number), true)
return ec.getBlock(ctx, "eth_getBlockByNumber", ToBlockNumArg(number), true)
}

// BlockNumber returns the most recent block number
Expand Down Expand Up @@ -179,7 +179,7 @@ func (ec *Client) HeaderByHash(ctx context.Context, hash common.Hash) (*types.He
// nil, the latest known header is returned.
func (ec *Client) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) {
var head *types.Header
err := ec.c.CallContext(ctx, &head, "eth_getBlockByNumber", toBlockNumArg(number), false)
err := ec.c.CallContext(ctx, &head, "eth_getBlockByNumber", ToBlockNumArg(number), false)
if err == nil && head == nil {
err = ethereum.NotFound
}
Expand Down Expand Up @@ -284,17 +284,6 @@ func (ec *Client) TransactionReceipt(ctx context.Context, txHash common.Hash) (*
return r, err
}

func toBlockNumArg(number *big.Int) string {
if number == nil {
return "latest"
}
pending := big.NewInt(-1)
if number.Cmp(pending) == 0 {
return "pending"
}
return hexutil.EncodeBig(number)
}

type rpcProgress struct {
StartingBlock hexutil.Uint64
CurrentBlock hexutil.Uint64
Expand Down Expand Up @@ -353,31 +342,31 @@ func (ec *Client) NetworkID(ctx context.Context) (*big.Int, error) {
// The block number can be nil, in which case the balance is taken from the latest known block.
func (ec *Client) BalanceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (*big.Int, error) {
var result hexutil.Big
err := ec.c.CallContext(ctx, &result, "eth_getBalance", account, toBlockNumArg(blockNumber))
err := ec.c.CallContext(ctx, &result, "eth_getBalance", account, ToBlockNumArg(blockNumber))
return (*big.Int)(&result), err
}

// StorageAt returns the value of key in the contract storage of the given account.
// The block number can be nil, in which case the value is taken from the latest known block.
func (ec *Client) StorageAt(ctx context.Context, account common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error) {
var result hexutil.Bytes
err := ec.c.CallContext(ctx, &result, "eth_getStorageAt", account, key, toBlockNumArg(blockNumber))
err := ec.c.CallContext(ctx, &result, "eth_getStorageAt", account, key, ToBlockNumArg(blockNumber))
return result, err
}

// CodeAt returns the contract code of the given account.
// The block number can be nil, in which case the code is taken from the latest known block.
func (ec *Client) CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error) {
var result hexutil.Bytes
err := ec.c.CallContext(ctx, &result, "eth_getCode", account, toBlockNumArg(blockNumber))
err := ec.c.CallContext(ctx, &result, "eth_getCode", account, ToBlockNumArg(blockNumber))
return result, err
}

// NonceAt returns the account nonce of the given account.
// The block number can be nil, in which case the nonce is taken from the latest known block.
func (ec *Client) NonceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (uint64, error) {
var result hexutil.Uint64
err := ec.c.CallContext(ctx, &result, "eth_getTransactionCount", account, toBlockNumArg(blockNumber))
err := ec.c.CallContext(ctx, &result, "eth_getTransactionCount", account, ToBlockNumArg(blockNumber))
return uint64(result), err
}

Expand Down Expand Up @@ -417,9 +406,9 @@ func toFilterArg(q ethereum.FilterQuery) (interface{}, error) {
if q.FromBlock == nil {
arg["fromBlock"] = "0x0"
} else {
arg["fromBlock"] = toBlockNumArg(q.FromBlock)
arg["fromBlock"] = ToBlockNumArg(q.FromBlock)
}
arg["toBlock"] = toBlockNumArg(q.ToBlock)
arg["toBlock"] = ToBlockNumArg(q.ToBlock)
}
return arg, nil
}
Expand Down Expand Up @@ -474,7 +463,7 @@ func (ec *Client) PendingTransactionCount(ctx context.Context) (uint, error) {
// blocks might not be available.
func (ec *Client) CallContract(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
var hex hexutil.Bytes
err := ec.c.CallContext(ctx, &hex, "eth_call", toCallArg(msg), toBlockNumArg(blockNumber))
err := ec.c.CallContext(ctx, &hex, "eth_call", ToCallArg(msg), ToBlockNumArg(blockNumber))
if err != nil {
return nil, err
}
Expand All @@ -485,7 +474,7 @@ func (ec *Client) CallContract(ctx context.Context, msg ethereum.CallMsg, blockN
// The state seen by the contract call is the pending state.
func (ec *Client) PendingCallContract(ctx context.Context, msg ethereum.CallMsg) ([]byte, error) {
var hex hexutil.Bytes
err := ec.c.CallContext(ctx, &hex, "eth_call", toCallArg(msg), "pending")
err := ec.c.CallContext(ctx, &hex, "eth_call", ToCallArg(msg), "pending")
if err != nil {
return nil, err
}
Expand All @@ -508,7 +497,7 @@ func (ec *Client) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
// but it should provide a basis for setting a reasonable default.
func (ec *Client) EstimateGas(ctx context.Context, msg ethereum.CallMsg) (uint64, error) {
var hex hexutil.Uint64
err := ec.c.CallContext(ctx, &hex, "eth_estimateGas", toCallArg(msg))
err := ec.c.CallContext(ctx, &hex, "eth_estimateGas", ToCallArg(msg))
if err != nil {
return 0, err
}
Expand All @@ -527,7 +516,18 @@ func (ec *Client) SendTransaction(ctx context.Context, tx *types.Transaction) er
return ec.c.CallContext(ctx, nil, "eth_sendRawTransaction", hexutil.Encode(data))
}

func toCallArg(msg ethereum.CallMsg) interface{} {
func ToBlockNumArg(number *big.Int) string {
if number == nil {
return "latest"
}
pending := big.NewInt(-1)
if number.Cmp(pending) == 0 {
return "pending"
}
return hexutil.EncodeBig(number)
}

func ToCallArg(msg ethereum.CallMsg) interface{} {
MariusVanDerWijden marked this conversation as resolved.
Show resolved Hide resolved
arg := map[string]interface{}{
"from": msg.From,
"to": msg.To,
Expand Down
97 changes: 97 additions & 0 deletions gethclient/gethclient.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package gethclient

import (
"context"
"math/big"

"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/internal/ethapi"
"github.com/ethereum/go-ethereum/rpc"
)

// Client is a wrapper around the rpc.Client that
// implements geth specific functionalities.
// Please use ethclient.Client instead if you want to
// access the standardized Etheeum RPC functionality.
type Client struct {
c *rpc.Client
}

// Dial connects a client to the given URL.
func Dial(rawurl string) (*Client, error) {
return DialContext(context.Background(), rawurl)
}

// DialContext connects a client with a given context and URL.
func DialContext(ctx context.Context, rawurl string) (*Client, error) {
c, err := rpc.DialContext(ctx, rawurl)
if err != nil {
return nil, err
}
return NewClient(c), nil
}

// NewClient creates a client that uses the given RPC client.
func NewClient(c *rpc.Client) *Client {
return &Client{c}
}

// Close closes the underlying RPC connection.
func (ec *Client) Close() {
ec.c.Close()
}

// CreateAccessList tries to create an access list for a specific transaction based on the
// current pending state of the blockchain.
func (ec *Client) CreateAccessList(ctx context.Context, msg ethereum.CallMsg) (*types.AccessList, uint64, string, error) {
type accessListResult struct {
Accesslist *types.AccessList `json:"accessList"`
Error string `json:"error,omitempty"`
GasUsed hexutil.Uint64 `json:"gasUsed"`
}
var result accessListResult
if err := ec.c.CallContext(ctx, &result, "eth_createAccessList", ethclient.ToCallArg(msg)); err != nil {
return nil, 0, "", err
}
return result.Accesslist, uint64(result.GasUsed), result.Error, nil
}

// GetProof returns the account and storage values of the specified account including the Merkle-proof.
// The block number can be nil, in which case the value is taken from the latest known block.
func (ec *Client) GetProof(ctx context.Context, account common.Address, keys []string, blockNumber *big.Int) (*ethapi.AccountResult, error) {
var result ethapi.AccountResult
err := ec.c.CallContext(ctx, &result, "eth_getProof", account, keys, ethclient.ToBlockNumArg(blockNumber))
return &result, err
}

// OverrideAccount specifies the state of an account to be overridden.
type OverrideAccount struct {
Nonce *hexutil.Uint64 `json:"nonce"`
Code *hexutil.Bytes `json:"code"`
Balance **hexutil.Big `json:"balance"`
State *map[common.Hash]common.Hash `json:"state"`
StateDiff *map[common.Hash]common.Hash `json:"stateDiff"`
}

// CallContract executes a message call transaction, which is directly executed in the VM
// of the node, but never mined into the blockchain.
//
// blockNumber selects the block height at which the call runs. It can be nil, in which
// case the code is taken from the latest known block. Note that state from very old
// blocks might not be available.
//
// overrides specifies a map of contract states that should be overwritten before executing
// the message call.
// Please use ethclient.CallContract instead if you don't need the override functionality.
func (ec *Client) CallContract(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int, overrides *map[common.Address]OverrideAccount) ([]byte, error) {
var hex hexutil.Bytes
err := ec.c.CallContext(
ctx, &hex, "eth_call", ethclient.ToCallArg(msg),
ethclient.ToBlockNumArg(blockNumber), overrides,
)
return hex, err
}
143 changes: 143 additions & 0 deletions gethclient/gethclient_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
package gethclient

import (
"context"
"math/big"
"testing"

"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/consensus/ethash"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/rawdb"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/eth/ethconfig"
"github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rpc"
)

var (
testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
testAddr = crypto.PubkeyToAddress(testKey.PublicKey)
testBalance = big.NewInt(2e10)
)

func newTestBackend(t *testing.T) (*node.Node, []*types.Block) {
// Generate test chain.
genesis, blocks := generateTestChain()
// Create node
n, err := node.New(&node.Config{})
if err != nil {
t.Fatalf("can't create new node: %v", err)
}
// Create Ethereum Service
config := &ethconfig.Config{Genesis: genesis}
config.Ethash.PowMode = ethash.ModeFake
ethservice, err := eth.New(n, config)
if err != nil {
t.Fatalf("can't create new ethereum service: %v", err)
}
// Import the test chain.
if err := n.Start(); err != nil {
t.Fatalf("can't start test node: %v", err)
}
if _, err := ethservice.BlockChain().InsertChain(blocks[1:]); err != nil {
t.Fatalf("can't import test blocks: %v", err)
}
return n, blocks
}

func generateTestChain() (*core.Genesis, []*types.Block) {
db := rawdb.NewMemoryDatabase()
config := params.AllEthashProtocolChanges
genesis := &core.Genesis{
Config: config,
Alloc: core.GenesisAlloc{testAddr: {Balance: testBalance}},
ExtraData: []byte("test genesis"),
Timestamp: 9000,
}
generate := func(i int, g *core.BlockGen) {
g.OffsetTime(5)
g.SetExtra([]byte("test"))
}
gblock := genesis.ToBlock(db)
engine := ethash.NewFaker()
blocks, _ := core.GenerateChain(config, gblock, engine, db, 1, generate)
blocks = append([]*types.Block{gblock}, blocks...)
return genesis, blocks
}

func TestEthClient(t *testing.T) {
backend, _ := newTestBackend(t)
client, _ := backend.Attach()
defer backend.Close()
defer client.Close()

tests := map[string]struct {
test func(t *testing.T)
}{"TestAccessList": {
func(t *testing.T) { testAccessList(t, client) },
},
}
t.Parallel()
for name, tt := range tests {
t.Run(name, tt.test)
}
}

func testAccessList(t *testing.T, client *rpc.Client) {
ec := NewClient(client)
// Test transfer
msg := ethereum.CallMsg{
From: testAddr,
To: &common.Address{},
Gas: 21000,
GasPrice: big.NewInt(1),
Value: big.NewInt(1),
}
al, gas, vmErr, err := ec.CreateAccessList(context.Background(), msg)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if vmErr != "" {
t.Fatalf("unexpected vm error: %v", vmErr)
}
if gas != 21000 {
t.Fatalf("unexpected gas used: %v", gas)
}
if len(*al) != 0 {
t.Fatalf("unexpected length of accesslist: %v", len(*al))
}
// Test reverting transaction
msg = ethereum.CallMsg{
From: testAddr,
To: nil,
Gas: 100000,
GasPrice: big.NewInt(1),
Value: big.NewInt(1),
Data: common.FromHex("0x608060806080608155fd"),
}
al, gas, vmErr, err = ec.CreateAccessList(context.Background(), msg)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if vmErr == "" {
t.Fatalf("wanted vmErr, got none")
}
if gas == 21000 {
t.Fatalf("unexpected gas used: %v", gas)
}
if len(*al) != 1 || al.StorageKeys() != 1 {
t.Fatalf("unexpected length of accesslist: %v", len(*al))
}
// address changes between calls, so we can't test for it.
if (*al)[0].Address == common.HexToAddress("0x0") {
t.Fatalf("unexpected address: %v", (*al)[0].Address)
}
if (*al)[0].StorageKeys[0] != common.HexToHash("0x0000000000000000000000000000000000000000000000000000000000000081") {
t.Fatalf("unexpected storage key: %v", (*al)[0].StorageKeys[0])
}
}