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?

1

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"
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.