Class: Bitcoin::MerkleTree

Inherits:
Object
  • Object
show all
Defined in:
lib/bitcoin/merkle_tree.rb

Overview

merkle tree

Defined Under Namespace

Classes: Node

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

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

#rootObject

Returns the value of attribute root.



6
7
8
# File 'lib/bitcoin/merkle_tree.rb', line 6

def root
  @root
end

Class Method Details

.build_from_leaf(txids) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/bitcoin/merkle_tree.rb', line 16

def self.build_from_leaf(txids)
  if txids.size == 1
    nodes = [Node.new(txids.first)]
  else
    nodes = txids.each_slice(2).map{ |m|
      left = Node.new(m[0])
      right = Node.new(m[1] ? m[1] : m[0])
      [left, right]
    }.flatten
  end
  new(build_initial_tree(nodes))
end

.build_initial_tree(nodes) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
# File 'lib/bitcoin/merkle_tree.rb', line 52

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



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/bitcoin/merkle_tree.rb', line 30

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
      if current_node&.leaf?
        current_node.value = hashes.last
      end
      break
    end
  end
  new(root)
end

Instance Method Details

#find_node(value) ⇒ Object



64
65
66
# File 'lib/bitcoin/merkle_tree.rb', line 64

def find_node(value)
  root.find_node(value)
end

#merkle_rootObject



12
13
14
# File 'lib/bitcoin/merkle_tree.rb', line 12

def merkle_root
  root.value
end