goethereumgo-ethereum

`go-ethereum` client.BlockByHash() gives error "not found"


I have the following code for subscribing to new blocks as they appear:

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/ethereum/go-ethereum/core/types"
    "github.com/ethereum/go-ethereum/ethclient"
)

func main() {
    client, err := ethclient.Dial("wss://mainnet.infura.io/ws/v3/APIKEY")
    if err != nil {
        log.Fatal(err)
    }

    headers := make(chan *types.Header)
    sub, err := client.SubscribeNewHead(context.Background(), headers)
    if err != nil {
        log.Fatal(err)
    }

    for {
        select {
        case err := <-sub.Err():
            log.Fatal(err)
        case header := <-headers:
            fmt.Println(header.Hash().Hex()) // 0xbc10defa8dda384c96a17640d84de5578804945d347072e091b4e5f390ddea7f

            block, err := client.BlockByHash(context.Background(), header.Hash())
            if err != nil {
                log.Fatal(err)
            }

            fmt.Println(block.Hash().Hex())        // 0xbc10defa8dda384c96a17640d84de5578804945d347072e091b4e5f390ddea7f
            fmt.Println(block.Number().Uint64())   // 3477413
            fmt.Println(block.Time())              // 1529525947
            fmt.Println(block.Nonce())             // 130524141876765836
            fmt.Println(len(block.Transactions())) // 7
        }
    }
}

But in the line

block, err := client.BlockByHash(context.Background(), header.Hash())

I get the error:

2023/04/19 17:31:14 not found
exit status 1

It still prints a hash in fmt.Println(header.Hash().Hex()) so I know the infura connection is working.


Solution

  • Use block number instead of the hash.

    block, err := client.BlockByNumber(context.Background(), header.Number)
    

    The function header.Hash() does not return the block hash, but rather the hash of the header.