description: Tutorial on how to query blocks in Ethereum with Go.

Querying Blocks

There’s two ways you can query block information as we’ll see.

Block header

You can call the client’s HeaderByNumber to return header information about a block. It’ll return the latest block header if you pass nil.

  1. header, err := client.HeaderByNumber(context.Background(), nil)
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. fmt.Println(header.Number.String()) // 5671744

Full block

Call the client’s BlockByNumber method to get the full block. You can read all the contents and metadata of the block such as block number, block timestamp, block hash, block difficulty, as well as the list of transactions and much much more.

  1. blockNumber := big.NewInt(5671744)
  2. block, err := client.BlockByNumber(context.Background(), blockNumber)
  3. if err != nil {
  4. log.Fatal(err)
  5. }
  6. fmt.Println(block.Number().Uint64()) // 5671744
  7. fmt.Println(block.Time().Uint64()) // 1527211625
  8. fmt.Println(block.Difficulty().Uint64()) // 3217000136609065
  9. fmt.Println(block.Hash().Hex()) // 0x9e8751ebb5069389b855bba72d94902cc385042661498a415979b7b6ee9ba4b9
  10. fmt.Println(len(block.Transactions())) // 144

Call TransactionCount to return just the count of transactions in a block.

  1. count, err := client.TransactionCount(context.Background(), block.Hash())
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. fmt.Println(count) // 144

In the next section we’ll learn how to query transactions in a block.

Full code

blocks.go

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "math/big"
  7. "github.com/ethereum/go-ethereum/ethclient"
  8. )
  9. func main() {
  10. client, err := ethclient.Dial("https://mainnet.infura.io")
  11. if err != nil {
  12. log.Fatal(err)
  13. }
  14. header, err := client.HeaderByNumber(context.Background(), nil)
  15. if err != nil {
  16. log.Fatal(err)
  17. }
  18. fmt.Println(header.Number.String()) // 5671744
  19. blockNumber := big.NewInt(5671744)
  20. block, err := client.BlockByNumber(context.Background(), blockNumber)
  21. if err != nil {
  22. log.Fatal(err)
  23. }
  24. fmt.Println(block.Number().Uint64()) // 5671744
  25. fmt.Println(block.Time().Uint64()) // 1527211625
  26. fmt.Println(block.Difficulty().Uint64()) // 3217000136609065
  27. fmt.Println(block.Hash().Hex()) // 0x9e8751ebb5069389b855bba72d94902cc385042661498a415979b7b6ee9ba4b9
  28. fmt.Println(len(block.Transactions())) // 144
  29. count, err := client.TransactionCount(context.Background(), block.Hash())
  30. if err != nil {
  31. log.Fatal(err)
  32. }
  33. fmt.Println(count) // 144
  34. }