Home  >  Article  >  Backend Development  >  `go-ethereum` client.BlockByHash() gives error "not found"

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

PHPz
PHPzforward
2024-02-09 08:00:22883browse

`go-ethereum` client.BlockByHash() 给出错误“未找到”

php Editor Banana recently received a question from a reader. He encountered an error message when using the `client.BlockByHash()` function of `go-ethereum`: " not found". This problem has been bothering him for a long time, so he hopes to get some solution. In this article, we will explore the possible causes of this error and provide some possible solutions.

Question content

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 team

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 the hash in fmt.println(header.hash().hex()) so I know the infura connection is working.

Solution

Use block number instead of hash value.

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

Function header.hash() does not return the block hash, but returns the hash of the header.

The above is the detailed content of `go-ethereum` client.BlockByHash() gives error "not found". For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete