class MerkleTree::Node

Holds information about intermediate hashes @api private

Constants

EMPTY
UNDEFINED

Attributes

height[R]

The node height in the tree

left[RW]
left_index[R]

The sequential position in the tree

right[RW]
right_index[R]
value[R]

Public Class Methods

build(left, right, digest: MerkleTree.default_digest) click to toggle source
# File lib/merkle_tree/node.rb, line 25
def self.build(left, right, digest: MerkleTree.default_digest)
  value  = digest.(left.value + right.value)
  height = left.height + 1
  left_index  = left.left_index
  right_index = right.right_index

  new(value, left, right, height, left_index, right_index)
end
new(value, left, right, height, left_index, right_index) click to toggle source

Create a node

@api private

# File lib/merkle_tree/node.rb, line 37
def initialize(value, left, right, height, left_index, right_index)
  @value  = value
  @left   = left
  @right  = right
  @height = height
  @left_index  = left_index
  @right_index = right_index
end

Public Instance Methods

<=>(other) click to toggle source
# File lib/merkle_tree/node.rb, line 88
def <=>(other)
  value <=> other.value &&
    left_index <=> other.left_index &&
    right_index <=> other.right_index
end
child(index) click to toggle source
# File lib/merkle_tree/node.rb, line 62
def child(index)
  if left.include?(index)
    left
  else
    right.include?(index) ? right : EMPTY
  end
end
include?(index) click to toggle source
# File lib/merkle_tree/node.rb, line 54
def include?(index)
  (left_index..right_index).cover?(index)
end
leaf?() click to toggle source
# File lib/merkle_tree/node.rb, line 46
def leaf?
  false
end
sibling(index) click to toggle source

Find sibling child node for the index

# File lib/merkle_tree/node.rb, line 71
def sibling(index)
  if left.include?(index)
    [:right, right.value]
  else
    right.include?(index) ? [:left, left.value] : EMPTY
  end
end
size() click to toggle source
# File lib/merkle_tree/node.rb, line 50
def size
  left.size + 1 + right.size
end
subtree(index) click to toggle source

Find subtree that matches the index

# File lib/merkle_tree/node.rb, line 80
def subtree(index)
  if left.include?(index)
    left
  else
    right.include?(index) ? right : EMPTY
  end
end
to_h() click to toggle source
# File lib/merkle_tree/node.rb, line 94
def to_h
  { value: value, left: left.to_h, right: right.to_h }
end
to_s(indent = "") click to toggle source
# File lib/merkle_tree/node.rb, line 98
def to_s(indent = "")
  indent + value.to_s + $RS +
    left.to_s(indent + "  ") + $RS +
    right.to_s(indent + "  ")
end
update(digest) click to toggle source
# File lib/merkle_tree/node.rb, line 58
def update(digest)
  @value = digest.(left.value + right.value)
end