Skip to content

Instantly share code, notes, and snippets.

@nakajo2011
Last active November 20, 2019 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nakajo2011/c2c3ced32f074de57ef458385fbae003 to your computer and use it in GitHub Desktop.
Save nakajo2011/c2c3ced32f074de57ef458385fbae003 to your computer and use it in GitHub Desktop.
Simple Patricia Trie what showed in "Patricia Trie" in Ethereum wiki.
const BaseTrie = require('merkle-patricia-tree/baseTrie')
const TrieNode = require('merkle-patricia-tree/trieNode')
const toNibbleArray = (bytes) => {
let nibbles = []
bytes.forEach((b) => {
nibbles.push(parseInt(b / 16))
nibbles.push(b % 16)
})
return Buffer.from(nibbles)
}
// ######################################################
// ######################################################
// ### Create simple trie what showed in sample. ######
// ######################################################
// ######################################################
async function SampleTrie() {
const putAsync = (trie, key, value) => {
return new Promise((resolve, reject) => {
trie.put(key, value, (err) => {
if(err) {
reject(err)
} else {
resolve()
}
})
})
}
const trie = new BaseTrie()
await putAsync(trie, "do", "verb")
await putAsync(trie, "dog", "puppy")
await putAsync(trie, "doge", "coin")
await putAsync(trie, "horse", "stallion")
const dump = (node) => {
let res = "["+ node.hash().toString("hex") +"] "
if (node.type === 'leaf') {
res += node.type + ": "
res += node.raw[0].toString("hex") + "=" + node.raw[1].toString()
} else if(node.type === 'branch') {
res += node.type + ": "
node.raw.forEach((b,i) => {
let node_hash = ""
if(b instanceof Buffer && b.length > 0) {
node_hash = b.toString("hex")
if(i === 16) {
node_hash = b.toString()
}
} else if(b instanceof Array) {
node_hash = new TrieNode(b).hash().toString("hex")
}
res += "<" + node_hash + ">, "
})
} else {
res += node.type + ": "
let value = node.raw[1].toString("hex")
if(node.raw[1] instanceof Array) {
value = new TrieNode(node.raw[1]).hash().toString("hex")
}
res += node.raw[0].toString("hex") + "=" + value
}
return res
}
trie._walkTrie(trie.root, function (nodeRef, node, key, walkController) {
console.log(dump(node))
walkController.next();
})
}
SampleTrie().then()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment