go-ethlibs

repository·master·Indexed 41 days ago

https://github.com/infura/go-ethlibs

A collection of Go-based helper libraries for interacting with Ethereum nodes. It includes packages for JSONRPC parsing, Ethereum type serialization, RLP encoding, and a proto-ethclient implementation for executing high-level Ethereum methods and subscriptions.

Tokens
1.3K
Snippets
4
Records
6
Agent score
100%

What's inside go-ethlibs

  1. Overview of go-ethlibs components

    master

    The go-ethlibs repository is a sandbox of helper libraries designed for interacting with Ethereum nodes. It is intended for use as code snippets and does not come with stability guarantees. The repository is organized into several functional packages:

    • eth: Provides helpers for serializing and deserializing Ethereum JSONRPC types.
    • jsonrpc: Handles parsing of JSONRPC requests and responses.
    • node: Contains a proto-ethclient implementation within the node namespace.
    • rlp: An independent implementation of Recursive Length Prefix (RLP) parsing.
  2. Run RLP fuzzing with make

    master

    The rlp package includes fuzzing support using go-fuzz to identify panics by providing random data to the RLP decoder/encoder.

    To set up and run the fuzzer:

    1. Install the necessary tools: make install (installs go-fuzz and go-fuzz-build).
    2. Build and execute the fuzzer: make or make fuzz (this builds rlp-fuzz.zip and runs it with go-fuzz).

    The fuzzer works by decoding and re-encoding input data; it triggers a panic if re-encoding fails.

    make install
    make fuzz
  3. Understand RLP fuzzing output and corpus

    master

    When running the fuzzer, monitor the following fields in the output:

    • corpus: The size of the input data set. The corpus/ folder contains seed data and auto-generated data found by go-fuzz. Each file represents a single input sample. New files created during a run can be included in Pull Requests to improve test coverage.
    • crashers: The number of test inputs that caused a panic. If this number increases, it indicates new bugs or related panics have been found.

    Handling Crashers: If a crasher is identified, the recommended workflow is to add the crash output to the TestFuzzCrashers test in rlp/fuzz_test.go to ensure the bug is caught in standard test suites.

  4. Initialize an Ethereum Client

    master

    You can create a new Client using NewClient by providing a URL. The client automatically selects the appropriate transport based on the URL scheme:

    • http or https: Uses HTTP transport.
    • ws or wss: Uses WebSocket transport.
    • Other schemes (e.g., ipc): Uses IPC transport.

    Alternatively, if you have custom implementations of Requester and Subscriber, you can use NewCustomClient to wrap them.

    client, err := node.NewClient(ctx, "https://mainnet.infura.io/v3/YOUR_KEY")
    if err != nil {
        log.Fatal(err)
    }
  5. Use the Client interface for Ethereum RPC calls

    master

    The Client interface is the primary entry point for interacting with an Ethereum node. It provides high-level methods for common JSON-RPC operations and low-level methods for raw requests and subscriptions.

    High-level Ethereum Methods

    • BlockNumber(ctx): Returns the current block number as a uint64.
    • GetTransactionCount(ctx, address, numberOrTag): Returns the nonce for a given address.
    • BlockByNumber(ctx, number, full): Retrieves a block by its number. Set full to true to include transaction details.
    • BlockByHash(ctx, hash, full): Retrieves a block by its hash.
    • TransactionByHash(ctx, hash): Retrieves a transaction by its hash.
    • TransactionReceipt(ctx, hash): Retrieves the receipt for a specific transaction hash.
    • Logs(ctx, filter): Returns logs matching the provided eth.LogFilter.
    • EstimateGas(ctx, msg): Estimates the gas required for a transaction.
    • SendRawTransaction(ctx, msg): Broadcasts a signed transaction string.
    • GasPrice(ctx): Returns the current gas price.
    • MaxPriorityFeePerGas(ctx): Returns the current max priority fee per gas.
    • ChainId(ctx): Returns the chain ID as a string.
    • NetVersion(ctx): Returns the network version.

    Subscription Methods

    For real-time updates, use the subscription methods which return a Subscription object:

    • SubscribeNewHeads(ctx): Subscribes to new block headers.
    • SubscribeNewPendingTransactions(ctx): Subscribes to new pending transactions.

    Low-level Methods

    • Request(ctx, r): Executes a raw jsonrpc.Request and returns a *jsonrpc.RawResponse.
    • Subscribe(ctx, r): Creates a subscription for a specific jsonrpc.Request.
    • IsBidirectional(): Indicates if the underlying transport supports bidirectional communication (like WebSockets).
    // Example: Getting the block number
    blockNum, err := client.BlockNumber(ctx)
    
    // Example: Subscribing to new heads
    sub, err := client.SubscribeNewHeads(ctx)
  6. Handle Client errors

    master

    The node package defines specific error variables to help identify common Ethereum RPC failures:

    • ErrBlockNotFound: Returned when a requested block does not exist.
    • ErrTransactionNotFound: Returned when a requested transaction is not recognized by the node.
    var (
    	ErrBlockNotFound       = errors.New("block not found")
    	ErrTransactionNotFound = errors.New("transaction not found")
    )