英文:
`go-ethereum` client.BlockByHash() gives error "not found"
问题
我有以下代码用于订阅新出现的区块:
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
}
}
}
但是在这一行中:
block, err := client.BlockByHash(context.Background(), header.Hash())
我得到了错误:
2023/04/19 17:31:14 not found
exit status 1
它仍然在 fmt.Println(header.Hash().Hex())
中打印出一个哈希值,所以我知道 infura 连接是正常的。
英文:
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.
答案1
得分: 0
使用区块号代替哈希值。
block, err := client.BlockByNumber(context.Background(), header.Number)
函数header.Hash()
并不返回区块的哈希值,而是返回区块头的哈希值。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论