citahub / cita_trie

Rust implementation of the Modified Patricia Tree (aka Trie).
Apache License 2.0
71 stars 28 forks source link

Reconstruction from db and then remove keys will result wrong root hash #14

Closed mohanson closed 5 years ago

mohanson commented 5 years ago

See codes below, I think it should be root1 == root2 == root3, but (root1 == root2) != root3 in fact.

fn main() {
    let root1 = {
        let mut db = cita_trie::db::MemoryDB::new();
        let mut trie = cita_trie::trie::PatriciaTrie::new(&mut db, cita_trie::codec::RLPNodeCodec::default());
        trie.insert(b"a", b"a").unwrap();
        trie.root().unwrap()
    };

    let root2 = {
        let mut db = cita_trie::db::MemoryDB::new();
        let mut trie = cita_trie::trie::PatriciaTrie::new(&mut db, cita_trie::codec::RLPNodeCodec::default());
        trie.insert(b"a", b"a").unwrap();
        trie.insert(b"b", b"b").unwrap();
        trie.root().unwrap();
        trie.remove(b"b").unwrap();
        trie.root().unwrap()
    };

    let root3 = {
        let mut db = cita_trie::db::MemoryDB::new();
        let mut t1 = cita_trie::trie::PatriciaTrie::new(&mut db, cita_trie::codec::RLPNodeCodec::default());
        t1.insert(b"a", b"a").unwrap();
        t1.insert(b"b", b"b").unwrap();
        let root = t1.root().unwrap();
        let mut t2 = cita_trie::trie::PatriciaTrie::from(&mut db, cita_trie::codec::RLPNodeCodec::default(), &root).unwrap();
        t2.remove(b"b").unwrap();
        t2.root().unwrap()
    };

    println!("{:?}", hex::encode(root1)); // "668aee9307d4b41714f33b61fd7e0704d31b95e42169292ba56af48929079580"
    println!("{:?}", hex::encode(root2)); // "668aee9307d4b41714f33b61fd7e0704d31b95e42169292ba56af48929079580"
    println!("{:?}", hex::encode(root3)); // "f3313809b6501771b8a698b8c70979f3f8340b4f7e90dc5db96caf81cf5a25e0"
}
yejiayu commented 5 years ago

Is it the latest version? Also, is this a bug blocking your work?

mohanson commented 5 years ago

1) Is it the latest version Yes. 2) is this a bug blocking your work Yes.

yejiayu commented 5 years ago

emmm, i will fix it as soon as possible