Skip to content

Instantly share code, notes, and snippets.

@cryptowen
Last active April 18, 2019 04:06
Show Gist options
  • Save cryptowen/1efc2ddadb3c296e82defb18ceddc4a2 to your computer and use it in GitHub Desktop.
Save cryptowen/1efc2ddadb3c296e82defb18ceddc4a2 to your computer and use it in GitHub Desktop.
ehtereum trie in golang and python
package main
import (
"bytes"
"github.com/davecgh/go-spew/spew"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/trie"
)
func updateString(trie *trie.Trie, k, v string) {
trie.Update([]byte(k), []byte(v))
}
type proofList [][]byte
func (n *proofList) Put(key []byte, value []byte) error {
*n = append(*n, value)
return nil
}
func (n *proofList) Delete(key []byte) error {
panic("not supported")
}
func (n proofList) Has(key []byte) (bool, error) {
for _, value := range n {
hash := crypto.Keccak256(value)
if bytes.Equal(key, hash) {
return true, nil
}
}
return false, nil
}
func (n proofList) Get(key []byte) ([]byte, error) {
for _, value := range n {
hash := crypto.Keccak256(value)
if bytes.Equal(key, hash) {
return value, nil
}
}
return []byte{}, nil
}
func main() {
t := new(trie.Trie)
updateString(t, "doe", "reindeer")
updateString(t, "dog", "puppy")
updateString(t, "dogglesworth", "cat")
rootHash := t.Hash()
spew.Dump(rootHash)
proofKey := []byte("dogglesworth")
var proof proofList
err := t.Prove(proofKey, 0, &proof)
// proof := memorydb.New()
// err := t.Prove([]byte("111"), 0, proof)
spew.Dump(err)
spew.Dump(proof)
value, nodes, err := trie.VerifyProof(rootHash, proofKey, proof)
spew.Dump(value, nodes, err)
}
# pip install trie -U
from trie import HexaryTrie
from pprint import pprint
import rlp
import binascii
t = HexaryTrie(db={})
t.set(b'doe', b'reindeer')
t.set(b'dog', b'puppy')
t.set(b'dogglesworth', b'cat')
# pprint(t.db)
proof_key = b'dogglesworth'
proof = t.get_proof(proof_key)
print(binascii.hexlify(t.root_hash))
print(proof)
pprint(len(proof))
pprint([binascii.hexlify(rlp.encode(p)) for p in proof])
proof_res = HexaryTrie.get_from_proof(t.root_hash, proof_key, proof)
print(proof_res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment