ethereum / go-ethereum

Go implementation of the Ethereum protocol
https://geth.ethereum.org
GNU Lesser General Public License v3.0
47.57k stars 20.13k forks source link

How to sync trie data to leveldb #29693

Closed cantincy closed 6 months ago

cantincy commented 6 months ago

I am studying trie in Ethereum (merkle patricia tree) and when I run the following code, the leveldb data directory is empty with no data in it. I would like to ask how to persist trie data to leveldb? I would appreciate it if there's any help.

go ethereum: 1.14.0 go: 1.22.0

package main

import (
    "github.com/ethereum/go-ethereum/core/rawdb"
    "github.com/ethereum/go-ethereum/trie"
    "github.com/ethereum/go-ethereum/triedb"
    "strconv"
)

func f() {
    dir := "./data"
    db, err := rawdb.NewLevelDBDatabase(dir, 16, 16, "leveldb", false)
    if err != nil {
        panic(err)
    }
    defer db.Close()

    mpt := trie.NewEmpty(triedb.NewDatabase(db, triedb.HashDefaults))

    for i := 0; i < 100_0000; i++ {
        mpt.MustUpdate([]byte(strconv.Itoa(i)), []byte(strconv.Itoa(i)))
    }

    _, _, err = mpt.Commit(true)
    if err != nil {
        panic(err)
    }
}

func main() {
    f()
}
rjl493456442 commented 6 months ago
package main

import (
    "strconv"

    "github.com/ethereum/go-ethereum/core/rawdb"
    "github.com/ethereum/go-ethereum/trie"
    "github.com/ethereum/go-ethereum/triedb"

)

func f() {
    dir := "./data"
    db, err := rawdb.NewLevelDBDatabase(dir, 16, 16, "leveldb", false)
    if err != nil {
        panic(err)
    }
    defer db.Close()

    tdb := triedb.NewDatabase(db, triedb.HashDefaults)
    mpt := trie.NewEmpty(tdb)

    for i := 0; i < 100_0000; i++ {
        mpt.MustUpdate([]byte(strconv.Itoa(i)), []byte(strconv.Itoa(i)))
    }
    root, nodes, err = mpt.Commit(true)
    if err != nil {
        panic(err)
    }
    tdb.Update(root, types.EmptyRootHash, trienode.NewWithNodeSet(nodes))
    tdb.Commit(root)
}

func main() {
    f()
}

You need to explicitly flush the trie changes to underlying database with these additional codes.

cantincy commented 6 months ago

@rjl493456442 It does work! Thank you very much for your help :)