以太坊如何获取当前区块数

ethereum-go how to get the latest block

package main

import (
	"context"
	"fmt"
	"strconv"
	"time"

	"github.com/ethereum/go-ethereum/rpc"
)

type Block struct {
	Number string
}

func getBlockNumber(client *rpc.Client) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	var lastBlock Block
	err := client.CallContext(ctx, &lastBlock, "eth_getBlockByNumber", "latest", true)
	if err != nil {
		fmt.Println("can't get latest block:", err)
		return
	}
	var blockNumber, err1 = strconv.ParseInt(lastBlock.Number, 0, 64)
	if err1 != nil {
		fmt.Println("strconv error:", err1)
		return
	}
	fmt.Println("connection lost: ", blockNumber)
}

func main() {

	client, err := rpc.Dial("http://54.87.26.24:8503")
	if err != nil {
		fmt.Println("rpc.Dial err", err)
		return
	}

	getBlockNumber(client)

}


推荐阅读: