Class: Bitcoin::MerkleTree
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
-
#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.
8 9 10 |
# File 'lib/bitcoin/merkle_tree.rb', line 8 def initialize(root = nil) @root = root end |
Instance Attribute Details
Class Method Details
.build_from_leaf(txids) ⇒ Object
16 17 18 19 20 21 22 23 |
# File 'lib/bitcoin/merkle_tree.rb', line 16 def self.build_from_leaf(txids) nodes = txids.each_slice(2).map{ |m| left = Node.new(m[0]) right = Node.new(m[1] ? m[1] : m[0]) [left, right] }.flatten new(build_initial_tree(nodes)) end |
.build_initial_tree(nodes) ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/bitcoin/merkle_tree.rb', line 43 def self.build_initial_tree(nodes) while nodes.size != 1 nodes = nodes.each_slice(2).map { |m| parent = Node.new parent.left = m[0] parent.right = m[1] ? m[1] : m[0].dup parent } end nodes.first end |
.build_partial(tx_count, hashes, flags) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/bitcoin/merkle_tree.rb', line 26 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.hash = hashes[hash_index] hash_index += 1 end current_node = current_node.next_partial break if hash_index == hashes.size end new(root) end |