Go-Ethereum

ethereum-go 如何獲取最新區塊?

  • December 16, 2017

我已經建立了一個私有的本地乙太坊節點,只有一個創世塊,我有這個 Go 程式碼,我想在私有本地網路上執行:

package main

   import (
       "fmt"
       "math/big"

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

   type Block struct {
       Number *big.Int
   }

   func main() {
       // Connect the client
       client, err := rpc.Dial("http://localhost:8000")
       if err != nil {
           panic(err)
       }

       var lastBlock Block
       if err := client.Call(&lastBlock,
           "eth_getBlockByNumber",
           "latest"); err != nil {
           fmt.Println("can't get latest block:", err)
           return
       }

       // Print events from the subscription as they arrive.
       fmt.Println("latest block:", lastBlock.Number)
   }

它編譯得很好,但是當我執行它時,我得到了這個錯誤:can't get latest block: missing value for required argument 1

我正在傳遞"latest",根據文件,這是 RPC 呼叫的有效參數。

我跟踪到此文件的錯誤輸出,似乎字元串正在轉換為nil並且 RPC 呼叫失敗。有誰知道這裡發生了什麼或如何解決這個奇怪的問題?

我通過在其中添加true參數err = client.Call(&lastBlock, "eth_getBlockByNumber", "latest", true)並更改*bit.Intstring

像這樣:

package main

import(
   "fmt"
   "log"

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

type Block struct {
   Number string
}

func main() {
 // Connect the client
 client, err := rpc.Dial("http://localhost:8000")
 if err != nil {
   log.Fatalf("could not create ipc client: %v", err)
 }

 var lastBlock Block
 err = client.Call(&lastBlock, "eth_getBlockByNumber", "latest", true)
 if err != nil {
     fmt.Println("can't get latest block:", err)
     return
 }

 // Print events from the subscription as they arrive.
 fmt.Printf("latest block: %v\n", lastBlock.Number)
}

結果應為六進制(如 0x5c67)

引用自:https://ethereum.stackexchange.com/questions/13341