Class: Tapyrus::MerkleTree
- Inherits:
-
Object
- Object
- Tapyrus::MerkleTree
- Defined in:
- lib/tapyrus/merkle_tree.rb
Overview
merkle tree
Defined Under Namespace
Classes: Node
Instance Attribute Summary collapse
-
#root ⇒ Object
Returns the value of attribute root.
Class Method Summary collapse
- .build_from_leaf(txids) ⇒ Object
- .build_initial_tree(nodes) ⇒ Object
- .build_partial(tx_count, hashes, flags) ⇒ Object
Instance Method Summary collapse
- #find_node(value) ⇒ Object
-
#initialize(root = nil) ⇒ MerkleTree
constructor
A new instance of MerkleTree.
- #merkle_root ⇒ Object
Constructor Details
#initialize(root = nil) ⇒ MerkleTree
Returns a new instance of MerkleTree.
6 7 8 |
# File 'lib/tapyrus/merkle_tree.rb', line 6 def initialize(root = nil) @root = root end |
Instance Attribute Details
#root ⇒ Object
Returns the value of attribute root.
4 5 6 |
# File 'lib/tapyrus/merkle_tree.rb', line 4 def root @root end |
Class Method Details
.build_from_leaf(txids) ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/tapyrus/merkle_tree.rb', line 14 def self.build_from_leaf(txids) if txids.size == 1 nodes = [Node.new(txids.first)] else nodes = txids .each_slice(2) .map do |m| left = Node.new(m[0]) right = Node.new(m[1] ? m[1] : m[0]) [left, right] end .flatten end new(build_initial_tree(nodes)) end |
.build_initial_tree(nodes) ⇒ Object
52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/tapyrus/merkle_tree.rb', line 52 def self.build_initial_tree(nodes) while nodes.size != 1 nodes = nodes .each_slice(2) .map do |m| parent = Node.new parent.left = m[0] parent.right = m[1] ? m[1] : m[0].dup parent end end nodes.first end |
.build_partial(tx_count, hashes, flags) ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/tapyrus/merkle_tree.rb', line 32 def self.build_partial(tx_count, hashes, flags) flags = flags.each_char.map(&:to_i) root = build_initial_tree(Array.new(tx_count) { Node.new }) current_node = root hash_index = 0 flags.each do |f| current_node.flag = f if f.zero? || current_node.leaf? current_node.value = hashes[hash_index] hash_index += 1 end current_node = current_node.next_partial if hash_index == hashes.size current_node.value = hashes.last if current_node&.leaf? break end end new(root) end |