4

Exploring Ethereum's state trie with Node.js

It is a nice article to explore ethereum internal storage, but the code is Node.js. Does anyone have a golang version?

Shawn Guo
  • 211
  • 2
  • 4

1 Answers1

2

The go-ethereum client provides a trie package.

Here's an example:

package main

import (
    "fmt"
    "log"

    "github.com/ethereum/go-ethereum/common"
    "github.com/ethereum/go-ethereum/ethdb"
    ethtrie "github.com/ethereum/go-ethereum/trie"
)

func main() {
    diskdb := ethdb.NewMemDatabase()
    triedb := ethtrie.NewDatabase(diskdb)
    trie, err := ethtrie.New(common.Hash{}, triedb)
    if err != nil {
        log.Fatal(err)
    }

    trie.Update([]byte("foo"), []byte("bar"))
    value, err := trie.TryGet([]byte("foo"))
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(value)) // bar
}

You'll also need to use the rlp package for decoding.

Here's an example:

package main

import (
    "bytes"
    "encoding/hex"
    "fmt"
    "log"

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

type simplestruct struct {
    A uint
    B string
}

func main() {
    s := new(simplestruct)

    b, err := hex.DecodeString("C50583343434")
    if err != nil {
        log.Fatal(err)
    }

    r := bytes.NewReader(b)
    err = rlp.Decode(r, &s)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(s.A) // 55
    fmt.Println(s.B) // "444"
}
Miguel Mota
  • 5,143
  • 29
  • 47