A stream that generates a merkle tree based on the incoming data. Port of mafintosh/merkle-tree-stream
- Add the dependency to your
shard.yml
:
dependencies:
merkle_tree_stream:
github: dukeraphaelng/merkle_tree_stream
- Run
shards install
Merkle Tree Stream is a stateful algorithm class that takes data in, hashes it, and computes as many parent hashes as it can through dukeraphaelng/flat_tree - this is done through the .next
method, which keeps track of three properties:
blocks
: an index to keep track of how far along in the sequence we are.nodes
: a vector of hashesroots
: the current roots.
You can read more about Merkle Tree Stream here
require "merkle_tree_stream"
leaf = Proc(MerkleTree::Node, Array(MerkleTree::Node)?, Bytes).new do |node, roots|
Digest::SHA256.digest(node.data)
end
parent = Proc(MerkleTree::Node, MerkleTree::Node, Bytes).new do |left, right|
Digest::SHA256.digest do |ctx|
ctx.update left.data
ctx.update right.data
end
end
merkle = MerkleTree::Stream.new(leaf, parent)
nodes = [] of MerkleTree::Node
merkle.next("a".to_slice, nodes)
merkle.next("b".to_slice, nodes)
puts {nodes: nodes}
# => [
#<MerkleTree::Node:0x107ebfe10
@index=0,
@parent=1,
@hash=Bytes[202, 151, 129, 18, 202, 27, 189, 202, 250, 194, 49, 179, 154, 35, 220, 77, 167, 134, 239, 248, 20, 124, 78, 114, 185, 128, 119, 133, 175, 238, 72, 187],
@size=1,
@data=Bytes[97]
>,
#<MerkleTree::Node:0x107ebfdc0
@index=2,
@parent=1,
@hash=Bytes[62, 35, 232, 22, 0, 57, 89, 74, 51, 137, 79, 101, 100, 225, 177, 52, 139, 189, 122, 0, 136, 212, 44, 74, 203, 115, 238, 174, 213, 156, 0, 157],
@size=1,
@data=Bytes[98]
>,
#<MerkleTree::Node:0x107ebfd70
@index=1,
@parent=3,
@hash=Bytes[251, 142, 32, 252, 46, 76, 63, 36, 140, 96, 195, 155, 214, 82, 243, 193, 52, 114, 152, 187, 151, 123, 139, 77, 89, 3, 184, 80, 85, 98, 6, 3],
@size=2,
@data=Bytes[]
>
]
MerkleTree::Node
Instance Variables:
index
: tree node index, even numbers are data nodesparent
: tree node's parent node's indexhash
: tree node's hashsize
: tree node's data sizedata
: tree node's raw data
- Fork it (https://github.com/dukeraphaelng/merkle_tree_stream/fork)
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request
- Duke Nguyen - creator and maintainer