Class: Merkle::Proof

Inherits:
Object
  • Object
show all
Includes:
Util
Defined in:
lib/merkle/proof.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Util

#bin_to_hex, #combine_sorted, #hex_string?, #hex_to_bin

Constructor Details

#initialize(config:, root:, leaf:, siblings:, directions: []) ⇒ Proof

Constructor. only required if sort_hashes is false in config.

Parameters:

  • config (Merkle::Config)
  • root (String)
  • leaf (String)
  • siblings (Array)
  • directions (Array) (defaults to: [])

    Array of positions at each level(0: left, 1: right),

Raises:

  • (ArgumentError)


14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/merkle/proof.rb', line 14

def initialize(config:, root:, leaf:, siblings:, directions: [])
  raise ArgumentError, 'config must be a Merkle::Config' unless config.is_a?(Merkle::Config)
  raise ArgumentError, 'root must be string' unless root.is_a?(String)
  raise ArgumentError, 'leaf must be string' unless leaf.is_a?(String)
  raise ArgumentError, 'directions must be an Array' unless directions.is_a?(Array)
  raise ArgumentError, 'No directions are required because sorted_hash is enabled' if config.sort_hashes && !directions.empty?
  @config = config
  @root = root
  @leaf = leaf
  @siblings = siblings
  @directions = directions
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



5
6
7
# File 'lib/merkle/proof.rb', line 5

def config
  @config
end

#directionsObject (readonly)

Returns the value of attribute directions.



5
6
7
# File 'lib/merkle/proof.rb', line 5

def directions
  @directions
end

#leafObject (readonly)

Returns the value of attribute leaf.



5
6
7
# File 'lib/merkle/proof.rb', line 5

def leaf
  @leaf
end

#rootObject (readonly)

Returns the value of attribute root.



5
6
7
# File 'lib/merkle/proof.rb', line 5

def root
  @root
end

#siblingsObject (readonly)

Returns the value of attribute siblings.



5
6
7
# File 'lib/merkle/proof.rb', line 5

def siblings
  @siblings
end

Instance Method Details

#valid?Boolean

Verify the proof.

Returns:

  • (Boolean)

    true if the proof is valid, false otherwise.



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

def valid?
  current = hex_to_bin(leaf)

  siblings.each_with_index do |sibling, index|
    sibling_bin = hex_to_bin(sibling)
    
    if config.sort_hashes
      # Sort lexicographically when combining
      combined = combine_sorted(config, current, sibling_bin)
    else
      # Use direction to determine order
      direction = directions[index]
      combined = direction == 0 ? sibling_bin + current : current + sibling_bin
    end
    
    current = config.tagged_hash(combined)
  end

  current.unpack1('H*') == root
end