merkle 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/.rspec +3 -0
- data/.ruby-gemset +1 -0
- data/.ruby-version +1 -0
- data/CODE_OF_CONDUCT.md +132 -0
- data/LICENSE.txt +21 -0
- data/README.md +108 -0
- data/Rakefile +8 -0
- data/lib/merkle/abstract_tree.rb +72 -0
- data/lib/merkle/adaptive_tree.rb +60 -0
- data/lib/merkle/binary_tree.rb +56 -0
- data/lib/merkle/config.rb +59 -0
- data/lib/merkle/proof.rb +51 -0
- data/lib/merkle/util.rb +40 -0
- data/lib/merkle/version.rb +5 -0
- data/lib/merkle.rb +16 -0
- data/sig/merkle.rbs +4 -0
- metadata +59 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: bce04358fd44b062aa388fdc8bb834a33e6dc082ae522e097f7a90a777cceb7d
|
4
|
+
data.tar.gz: e9cdee4066043760ecd72b89bc355060cb47273ae13a4b1c379e7ecca494fb62
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: 7f5719c3393e13411152b2207ad1c3c109c468d0611d9c5d5c83d1430ee427dbfe914aa427145052a7bc8a55f8ebb71aaa809d45516b61243981f50a58388165
|
7
|
+
data.tar.gz: 7dac36c4c6aaa55107f8ca2b7c7b06efba49c59f66017e50a225c463d17f4635f13f5401b640a0735c2893ac819574589655ec9f5e5eeed0ffaf2a1704a0a7f8
|
data/.rspec
ADDED
data/.ruby-gemset
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
merkle
|
data/.ruby-version
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
ruby-3.4.5
|
data/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,132 @@
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
2
|
+
|
3
|
+
## Our Pledge
|
4
|
+
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our
|
6
|
+
community a harassment-free experience for everyone, regardless of age, body
|
7
|
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
8
|
+
identity and expression, level of experience, education, socio-economic status,
|
9
|
+
nationality, personal appearance, race, caste, color, religion, or sexual
|
10
|
+
identity and orientation.
|
11
|
+
|
12
|
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
13
|
+
diverse, inclusive, and healthy community.
|
14
|
+
|
15
|
+
## Our Standards
|
16
|
+
|
17
|
+
Examples of behavior that contributes to a positive environment for our
|
18
|
+
community include:
|
19
|
+
|
20
|
+
* Demonstrating empathy and kindness toward other people
|
21
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
22
|
+
* Giving and gracefully accepting constructive feedback
|
23
|
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
24
|
+
and learning from the experience
|
25
|
+
* Focusing on what is best not just for us as individuals, but for the overall
|
26
|
+
community
|
27
|
+
|
28
|
+
Examples of unacceptable behavior include:
|
29
|
+
|
30
|
+
* The use of sexualized language or imagery, and sexual attention or advances of
|
31
|
+
any kind
|
32
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
33
|
+
* Public or private harassment
|
34
|
+
* Publishing others' private information, such as a physical or email address,
|
35
|
+
without their explicit permission
|
36
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
37
|
+
professional setting
|
38
|
+
|
39
|
+
## Enforcement Responsibilities
|
40
|
+
|
41
|
+
Community leaders are responsible for clarifying and enforcing our standards of
|
42
|
+
acceptable behavior and will take appropriate and fair corrective action in
|
43
|
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
44
|
+
or harmful.
|
45
|
+
|
46
|
+
Community leaders have the right and responsibility to remove, edit, or reject
|
47
|
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
48
|
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
49
|
+
decisions when appropriate.
|
50
|
+
|
51
|
+
## Scope
|
52
|
+
|
53
|
+
This Code of Conduct applies within all community spaces, and also applies when
|
54
|
+
an individual is officially representing the community in public spaces.
|
55
|
+
Examples of representing our community include using an official email address,
|
56
|
+
posting via an official social media account, or acting as an appointed
|
57
|
+
representative at an online or offline event.
|
58
|
+
|
59
|
+
## Enforcement
|
60
|
+
|
61
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
62
|
+
reported to the community leaders responsible for enforcement at
|
63
|
+
[INSERT CONTACT METHOD].
|
64
|
+
All complaints will be reviewed and investigated promptly and fairly.
|
65
|
+
|
66
|
+
All community leaders are obligated to respect the privacy and security of the
|
67
|
+
reporter of any incident.
|
68
|
+
|
69
|
+
## Enforcement Guidelines
|
70
|
+
|
71
|
+
Community leaders will follow these Community Impact Guidelines in determining
|
72
|
+
the consequences for any action they deem in violation of this Code of Conduct:
|
73
|
+
|
74
|
+
### 1. Correction
|
75
|
+
|
76
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
77
|
+
unprofessional or unwelcome in the community.
|
78
|
+
|
79
|
+
**Consequence**: A private, written warning from community leaders, providing
|
80
|
+
clarity around the nature of the violation and an explanation of why the
|
81
|
+
behavior was inappropriate. A public apology may be requested.
|
82
|
+
|
83
|
+
### 2. Warning
|
84
|
+
|
85
|
+
**Community Impact**: A violation through a single incident or series of
|
86
|
+
actions.
|
87
|
+
|
88
|
+
**Consequence**: A warning with consequences for continued behavior. No
|
89
|
+
interaction with the people involved, including unsolicited interaction with
|
90
|
+
those enforcing the Code of Conduct, for a specified period of time. This
|
91
|
+
includes avoiding interactions in community spaces as well as external channels
|
92
|
+
like social media. Violating these terms may lead to a temporary or permanent
|
93
|
+
ban.
|
94
|
+
|
95
|
+
### 3. Temporary Ban
|
96
|
+
|
97
|
+
**Community Impact**: A serious violation of community standards, including
|
98
|
+
sustained inappropriate behavior.
|
99
|
+
|
100
|
+
**Consequence**: A temporary ban from any sort of interaction or public
|
101
|
+
communication with the community for a specified period of time. No public or
|
102
|
+
private interaction with the people involved, including unsolicited interaction
|
103
|
+
with those enforcing the Code of Conduct, is allowed during this period.
|
104
|
+
Violating these terms may lead to a permanent ban.
|
105
|
+
|
106
|
+
### 4. Permanent Ban
|
107
|
+
|
108
|
+
**Community Impact**: Demonstrating a pattern of violation of community
|
109
|
+
standards, including sustained inappropriate behavior, harassment of an
|
110
|
+
individual, or aggression toward or disparagement of classes of individuals.
|
111
|
+
|
112
|
+
**Consequence**: A permanent ban from any sort of public interaction within the
|
113
|
+
community.
|
114
|
+
|
115
|
+
## Attribution
|
116
|
+
|
117
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
118
|
+
version 2.1, available at
|
119
|
+
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
120
|
+
|
121
|
+
Community Impact Guidelines were inspired by
|
122
|
+
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
123
|
+
|
124
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
125
|
+
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
|
126
|
+
[https://www.contributor-covenant.org/translations][translations].
|
127
|
+
|
128
|
+
[homepage]: https://www.contributor-covenant.org
|
129
|
+
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
130
|
+
[Mozilla CoC]: https://github.com/mozilla/diversity
|
131
|
+
[FAQ]: https://www.contributor-covenant.org/faq
|
132
|
+
[translations]: https://www.contributor-covenant.org/translations
|
data/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2025 azuchi
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
13
|
+
all copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
21
|
+
THE SOFTWARE.
|
data/README.md
ADDED
@@ -0,0 +1,108 @@
|
|
1
|
+
# Merkle
|
2
|
+
|
3
|
+
A Ruby library for Merkle tree construction and proof generation with support for multiple tree structures and hashing algorithms.
|
4
|
+
|
5
|
+
## Features
|
6
|
+
|
7
|
+
- **Multiple tree structures**: Binary Tree (Bitcoin-compatible) and Adaptive Tree implementations
|
8
|
+
- **Flexible configuration**: Support for different hash algorithms (SHA256, Double SHA256) and tagged hashing
|
9
|
+
- **Proof generation and verification**: Generate and verify Merkle proofs for any leaf
|
10
|
+
- **Sorted hashing support**: Optional lexicographical sorting for deterministic tree construction
|
11
|
+
|
12
|
+
## Installation
|
13
|
+
|
14
|
+
Add this line to your application's Gemfile:
|
15
|
+
|
16
|
+
```ruby
|
17
|
+
gem 'merkle'
|
18
|
+
```
|
19
|
+
|
20
|
+
And then execute:
|
21
|
+
|
22
|
+
$ bundle install
|
23
|
+
|
24
|
+
Or install it yourself as:
|
25
|
+
|
26
|
+
$ gem install merkle
|
27
|
+
|
28
|
+
## Usage
|
29
|
+
|
30
|
+
### Basic Example
|
31
|
+
|
32
|
+
```ruby
|
33
|
+
require 'merkle'
|
34
|
+
|
35
|
+
# Create configuration
|
36
|
+
config = Merkle::Config.new(hash_type: :sha256)
|
37
|
+
|
38
|
+
# Prepare leaves (hex strings)
|
39
|
+
leaves = [
|
40
|
+
'a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3',
|
41
|
+
'b3a8e0e1f9ab1bfe3a36f231f676f78bb30a519d2b21e6c530c0eee8ebb4a5d0',
|
42
|
+
'c3c9bc9a6c7c5b4e8c3b6b5a2a8c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c'
|
43
|
+
]
|
44
|
+
|
45
|
+
# Create binary tree (Bitcoin-compatible)
|
46
|
+
tree = Merkle::BinaryTree.new(config: config, leaves: leaves)
|
47
|
+
|
48
|
+
# Compute merkle root
|
49
|
+
root = tree.compute_root
|
50
|
+
puts "Merkle root: #{root}"
|
51
|
+
|
52
|
+
# Generate proof for leaf at index 1
|
53
|
+
proof = tree.generate_proof(1)
|
54
|
+
puts "Proof siblings: #{proof.siblings}"
|
55
|
+
puts "Proof directions: #{proof.directions}"
|
56
|
+
|
57
|
+
# Verify proof
|
58
|
+
puts "Proof valid: #{proof.valid?}"
|
59
|
+
```
|
60
|
+
|
61
|
+
### Adaptive Tree Example
|
62
|
+
|
63
|
+
```ruby
|
64
|
+
# Create adaptive tree for better performance with frequently accessed leaves
|
65
|
+
adaptive_tree = Merkle::AdaptiveTree.new(config: config, leaves: leaves)
|
66
|
+
|
67
|
+
root = adaptive_tree.compute_root
|
68
|
+
proof = adaptive_tree.generate_proof(0)
|
69
|
+
puts "Adaptive tree proof valid: #{proof.valid?}"
|
70
|
+
```
|
71
|
+
|
72
|
+
### Configuration Options
|
73
|
+
|
74
|
+
```ruby
|
75
|
+
# Bitcoin-compatible configuration with double SHA256
|
76
|
+
bitcoin_config = Merkle::Config.new(hash_type: :double_sha256)
|
77
|
+
|
78
|
+
# Configuration with tagged hashing (Taproot-style)
|
79
|
+
taproot_config = Merkle::Config.taptree
|
80
|
+
|
81
|
+
# Configuration with sorted hashing (no directions needed in proofs)
|
82
|
+
sorted_config = Merkle::Config.new(
|
83
|
+
hash_type: :sha256,
|
84
|
+
sort_hashes: true
|
85
|
+
)
|
86
|
+
```
|
87
|
+
|
88
|
+
## Architecture
|
89
|
+
|
90
|
+
### Tree Structures
|
91
|
+
|
92
|
+
- **BinaryTree**: Bitcoin-compatible merkle tree that duplicates odd nodes
|
93
|
+
- **AdaptiveTree**: Unbalanced tree that promotes odd nodes to higher levels for optimized access patterns
|
94
|
+
|
95
|
+
### Proof System
|
96
|
+
|
97
|
+
The library generates compact Merkle proofs that include:
|
98
|
+
- `siblings`: Array of sibling hashes needed for verification
|
99
|
+
- `directions`: Array indicating left (0) or right (1) position at each level
|
100
|
+
- `root`: The merkle root hash
|
101
|
+
- `leaf`: The original leaf value
|
102
|
+
|
103
|
+
### Verification
|
104
|
+
|
105
|
+
```ruby
|
106
|
+
proof = tree.generate_proof(leaf_index)
|
107
|
+
is_valid = proof.valid? # Returns true/false
|
108
|
+
```
|
data/Rakefile
ADDED
@@ -0,0 +1,72 @@
|
|
1
|
+
require 'digest'
|
2
|
+
|
3
|
+
module Merkle
|
4
|
+
# Base class for Merkle tree implementations
|
5
|
+
class AbstractTree
|
6
|
+
include Util
|
7
|
+
|
8
|
+
attr_reader :config, :leaves
|
9
|
+
|
10
|
+
# Constructor
|
11
|
+
# @param [Merkle::Config] config Configuration for merkle tree.
|
12
|
+
# @param [Array] leaves An array of leaves.
|
13
|
+
# @raise [ArgumentError]
|
14
|
+
def initialize(config:, leaves: [])
|
15
|
+
raise ArgumentError, 'config must be Merkle::Config' unless config.is_a?(Merkle::Config)
|
16
|
+
raise ArgumentError, 'leaves must be Array' unless leaves.is_a?(Array)
|
17
|
+
@config = config
|
18
|
+
@leaves = leaves
|
19
|
+
end
|
20
|
+
|
21
|
+
# Compute merkle root.
|
22
|
+
# @return [String] merkle root (hex value). For Bitcoin, the endianness of this value must be reversed.
|
23
|
+
# @raise [Merkle::Error] If leaves is empty.
|
24
|
+
def compute_root
|
25
|
+
raise Error, 'leaves is empty' if leaves.empty?
|
26
|
+
# nodes = leaves
|
27
|
+
nodes = leaves.map {|leaf| hex_to_bin(leaf) }
|
28
|
+
while nodes.length > 1
|
29
|
+
nodes = build_next_level(nodes)
|
30
|
+
end
|
31
|
+
root = nodes.first
|
32
|
+
root.unpack1('H*')
|
33
|
+
end
|
34
|
+
|
35
|
+
# Generates a merkle proof for the specified +leaf_index+.
|
36
|
+
# @param [Integer] leaf_index The leaf index.
|
37
|
+
# @return [Merkle::Proof] The merkle proof.
|
38
|
+
# @raise [ArgumentError] If invalid +leaf_index+ specified.
|
39
|
+
def generate_proof(leaf_index)
|
40
|
+
raise ArgumentError, 'leaf_index must be Integer' unless leaf_index.is_a?(Integer)
|
41
|
+
raise ArgumentError, 'leaf_index out of range' if leaf_index < 0 || leaves.length <= leaf_index
|
42
|
+
|
43
|
+
siblings, directions = siblings_with_directions(leaf_index)
|
44
|
+
siblings = siblings.map{|sibling| hex_string?(sibling) ? sibling : sibling.unpack1('H*')}
|
45
|
+
directions = [] if config.sort_hashes
|
46
|
+
Proof.new(config: config, root: compute_root, leaf: leaves[leaf_index], siblings: siblings, directions: directions)
|
47
|
+
end
|
48
|
+
|
49
|
+
private
|
50
|
+
|
51
|
+
# Gets the siblings that corresponds to +leaf_index+ and its directions (if necessary).
|
52
|
+
# @param [Integer] leaf_index The leaf index.
|
53
|
+
# @return [Array] An array of siblings and directions.
|
54
|
+
def siblings_with_directions(leaf_index)
|
55
|
+
raise NotImplementedError
|
56
|
+
end
|
57
|
+
|
58
|
+
# Get branch hash.
|
59
|
+
# @param [String] data The data to be hashed.
|
60
|
+
# @return [String] Branch hash value.
|
61
|
+
def branch_hash(data)
|
62
|
+
config.tagged_hash(data)
|
63
|
+
end
|
64
|
+
|
65
|
+
# Build next level in tree.
|
66
|
+
# @param [Array] nodes Current level nodes in tree.
|
67
|
+
# @return [Array] An array of next level nodes in tree.
|
68
|
+
def build_next_level(nodes)
|
69
|
+
raise NotImplementedError
|
70
|
+
end
|
71
|
+
end
|
72
|
+
end
|
@@ -0,0 +1,60 @@
|
|
1
|
+
module Merkle
|
2
|
+
# The AdaptiveTree class implements an unbalanced binary tree structure for Merkle tree construction,
|
3
|
+
# optimized for scenarios where frequently used scripts should be placed at shallower depths.
|
4
|
+
# Unlike the standard Bitcoin Merkle tree which maintains a complete binary tree by duplicating odd elements,
|
5
|
+
# AdaptiveTree promotes odd nodes to higher levels, creating variable-depth paths.
|
6
|
+
class AdaptiveTree < AbstractTree
|
7
|
+
|
8
|
+
private
|
9
|
+
|
10
|
+
def siblings_with_directions(leaf_index)
|
11
|
+
siblings = []
|
12
|
+
directions = []
|
13
|
+
|
14
|
+
current_index = leaf_index
|
15
|
+
nodes = leaves.map {|leaf| hex_to_bin(leaf) }
|
16
|
+
|
17
|
+
while nodes.length > 1
|
18
|
+
# For adaptive tree, odd nodes are promoted to next level
|
19
|
+
if current_index.even? && current_index + 1 < nodes.length
|
20
|
+
# Current node has a right sibling
|
21
|
+
sibling_index = current_index + 1
|
22
|
+
directions << 1 # sibling is on the right
|
23
|
+
siblings << nodes[sibling_index]
|
24
|
+
current_index = current_index / 2
|
25
|
+
elsif current_index.odd?
|
26
|
+
# Current node has a left sibling
|
27
|
+
sibling_index = current_index - 1
|
28
|
+
directions << 0 # sibling is on the left
|
29
|
+
siblings << nodes[sibling_index]
|
30
|
+
current_index = current_index / 2
|
31
|
+
else
|
32
|
+
# Current node is the last node (odd), no sibling at this level
|
33
|
+
# It gets promoted to the next level
|
34
|
+
# Find its new index in the next level
|
35
|
+
current_index = nodes.length / 2
|
36
|
+
end
|
37
|
+
|
38
|
+
# Move to next level
|
39
|
+
nodes = build_next_level(nodes)
|
40
|
+
end
|
41
|
+
|
42
|
+
[siblings, directions]
|
43
|
+
end
|
44
|
+
|
45
|
+
def build_next_level(nodes)
|
46
|
+
next_level = []
|
47
|
+
nodes.each_slice(2) do |left, right|
|
48
|
+
if right
|
49
|
+
combined = combine_sorted(config, left, right)
|
50
|
+
parent_hash = branch_hash(combined)
|
51
|
+
next_level << parent_hash
|
52
|
+
else
|
53
|
+
next_level << left
|
54
|
+
end
|
55
|
+
end
|
56
|
+
|
57
|
+
next_level
|
58
|
+
end
|
59
|
+
end
|
60
|
+
end
|
@@ -0,0 +1,56 @@
|
|
1
|
+
module Merkle
|
2
|
+
# Merkle trees take the same approach as Bitcoin to construct a complete binary tree.
|
3
|
+
# If the number of hashes in the list at a given level is odd,
|
4
|
+
# the last one is duplicated before computing the next level (which is unusual in Merkle trees).
|
5
|
+
# So keep in mind that this following merkle tree algorithm has a serious flaw related to duplicate elements,
|
6
|
+
# resulting in a vulnerability (CVE-2012-2459).
|
7
|
+
class BinaryTree < AbstractTree
|
8
|
+
|
9
|
+
private
|
10
|
+
|
11
|
+
def siblings_with_directions(leaf_index)
|
12
|
+
siblings = []
|
13
|
+
directions = []
|
14
|
+
|
15
|
+
current_index = leaf_index
|
16
|
+
nodes = leaves.map {|leaf| hex_to_bin(leaf) }
|
17
|
+
|
18
|
+
while nodes.length > 1
|
19
|
+
# If odd number of nodes, duplicate the last one
|
20
|
+
nodes << nodes.last if nodes.length.odd?
|
21
|
+
|
22
|
+
# Determine sibling index and direction (0=left, 1=right)
|
23
|
+
if current_index.even?
|
24
|
+
sibling_index = current_index + 1
|
25
|
+
directions << 1 # sibling is on the right
|
26
|
+
else
|
27
|
+
sibling_index = current_index - 1
|
28
|
+
directions << 0 # sibling is on the left
|
29
|
+
end
|
30
|
+
|
31
|
+
# Add sibling to the list
|
32
|
+
siblings << nodes[sibling_index]
|
33
|
+
|
34
|
+
# Move to next level
|
35
|
+
current_index = current_index / 2
|
36
|
+
nodes = build_next_level(nodes)
|
37
|
+
end
|
38
|
+
|
39
|
+
[siblings, directions]
|
40
|
+
end
|
41
|
+
|
42
|
+
def build_next_level(nodes)
|
43
|
+
next_level = []
|
44
|
+
nodes = nodes + [nodes.last] if nodes.length.odd?
|
45
|
+
nodes.each_slice(2) do |left, right|
|
46
|
+
combined = combine_sorted(config, left, right)
|
47
|
+
parent_hash = branch_hash(combined)
|
48
|
+
next_level << parent_hash
|
49
|
+
end
|
50
|
+
|
51
|
+
next_level
|
52
|
+
end
|
53
|
+
|
54
|
+
end
|
55
|
+
|
56
|
+
end
|
@@ -0,0 +1,59 @@
|
|
1
|
+
module Merkle
|
2
|
+
# Merkle tree configuration class.
|
3
|
+
class Config
|
4
|
+
include Util
|
5
|
+
|
6
|
+
# Supported Hash type.
|
7
|
+
HASH_TYPES = [:sha256, :double_sha256]
|
8
|
+
|
9
|
+
attr_reader :hash_type, :branch_tag, :sort_hashes
|
10
|
+
|
11
|
+
# Constructor
|
12
|
+
# @param [Symbol] hash_type The hashing algorithm used to hash the internal nodes.
|
13
|
+
# @param [String] branch_tag Tags to use when hashing internal nodes.
|
14
|
+
# @param [Boolean] sort_hashes Whether to sort internal nodes in lexicographical order and hash them.
|
15
|
+
# If you enable this, Merkle::Proof's directions are not required.
|
16
|
+
# @raise [ArgumentError]
|
17
|
+
def initialize(hash_type: :sha256, branch_tag: '', sort_hashes: false)
|
18
|
+
raise ArgumentError, "hash_type #{hash_type} does not supported." unless HASH_TYPES.include?(hash_type)
|
19
|
+
raise ArgumentError, "internal_tag must be string." unless branch_tag.is_a?(String)
|
20
|
+
raise ArgumentError, "sort_hashes must be boolean." unless sort_hashes.is_a?(TrueClass) || sort_hashes.is_a?(FalseClass)
|
21
|
+
@hash_type = hash_type
|
22
|
+
@branch_tag = branch_tag
|
23
|
+
@sort_hashes = sort_hashes
|
24
|
+
end
|
25
|
+
|
26
|
+
# Bitcoin configuration.
|
27
|
+
# @return [Merkle::Config]
|
28
|
+
def self.bitcoin
|
29
|
+
Config.new(hash_type: :double_sha256)
|
30
|
+
end
|
31
|
+
|
32
|
+
# Taptree configuration.
|
33
|
+
# @return [Merkle::Config]
|
34
|
+
def self.taptree
|
35
|
+
Config.new(branch_tag: 'TapBranch', sort_hashes: true)
|
36
|
+
end
|
37
|
+
|
38
|
+
# Generate tagged hash.
|
39
|
+
# @param [String] data The data to be hashed.
|
40
|
+
# @param [String] tag Tag string used tagging.
|
41
|
+
# @return [String] Tagged hash value.
|
42
|
+
def tagged_hash(data, tag = branch_tag)
|
43
|
+
raise ArgumentError, "data must be string." unless data.is_a?(String)
|
44
|
+
data = [data].pack('H*') if hex_string?(data)
|
45
|
+
|
46
|
+
unless tag.empty?
|
47
|
+
tag_hash = Digest::SHA256.digest(tag)
|
48
|
+
data = tag_hash + tag_hash + data
|
49
|
+
end
|
50
|
+
|
51
|
+
case hash_type
|
52
|
+
when :sha256
|
53
|
+
Digest::SHA256.digest(data)
|
54
|
+
when :double_sha256
|
55
|
+
Digest::SHA256.digest(Digest::SHA256.digest(data))
|
56
|
+
end
|
57
|
+
end
|
58
|
+
end
|
59
|
+
end
|
data/lib/merkle/proof.rb
ADDED
@@ -0,0 +1,51 @@
|
|
1
|
+
module Merkle
|
2
|
+
class Proof
|
3
|
+
include Util
|
4
|
+
|
5
|
+
attr_reader :config, :root, :leaf, :siblings, :directions
|
6
|
+
|
7
|
+
# Constructor.
|
8
|
+
# @param [Merkle::Config] config
|
9
|
+
# @param [String] root
|
10
|
+
# @param [String] leaf
|
11
|
+
# @param [Array] siblings
|
12
|
+
# @param [Array] directions Array of positions at each level(0: left, 1: right),
|
13
|
+
# only required if sort_hashes is false in config.
|
14
|
+
def initialize(config:, root:, leaf:, siblings:, directions: [])
|
15
|
+
raise ArgumentError, 'config must be a Merkle::Config' unless config.is_a?(Merkle::Config)
|
16
|
+
raise ArgumentError, 'root must be string' unless root.is_a?(String)
|
17
|
+
raise ArgumentError, 'leaf must be string' unless leaf.is_a?(String)
|
18
|
+
raise ArgumentError, 'directions must be an Array' unless directions.is_a?(Array)
|
19
|
+
raise ArgumentError, 'No directions are required because sorted_hash is enabled' if config.sort_hashes && !directions.empty?
|
20
|
+
@config = config
|
21
|
+
@root = root
|
22
|
+
@leaf = leaf
|
23
|
+
@siblings = siblings
|
24
|
+
@directions = directions
|
25
|
+
end
|
26
|
+
|
27
|
+
# Verify the proof.
|
28
|
+
# @return [Boolean] true if the proof is valid, false otherwise.
|
29
|
+
def valid?
|
30
|
+
current = hex_to_bin(leaf)
|
31
|
+
|
32
|
+
siblings.each_with_index do |sibling, index|
|
33
|
+
sibling_bin = hex_to_bin(sibling)
|
34
|
+
|
35
|
+
if config.sort_hashes
|
36
|
+
# Sort lexicographically when combining
|
37
|
+
combined = combine_sorted(config, current, sibling_bin)
|
38
|
+
else
|
39
|
+
# Use direction to determine order
|
40
|
+
direction = directions[index]
|
41
|
+
combined = direction == 0 ? sibling_bin + current : current + sibling_bin
|
42
|
+
end
|
43
|
+
|
44
|
+
current = config.tagged_hash(combined)
|
45
|
+
end
|
46
|
+
|
47
|
+
current.unpack1('H*') == root
|
48
|
+
end
|
49
|
+
|
50
|
+
end
|
51
|
+
end
|
data/lib/merkle/util.rb
ADDED
@@ -0,0 +1,40 @@
|
|
1
|
+
module Merkle
|
2
|
+
module Util
|
3
|
+
|
4
|
+
# Check whether +data+ is hex string or not.
|
5
|
+
# @return [Boolean]
|
6
|
+
# @raise [ArgumentError]
|
7
|
+
def hex_string?(data)
|
8
|
+
raise ArgumentError, 'data must be string' unless data.is_a?(String)
|
9
|
+
data.match?(/\A[0-9a-fA-F]+\z/)
|
10
|
+
end
|
11
|
+
|
12
|
+
# Convert hex string +data+ to binary.
|
13
|
+
# @return [String]
|
14
|
+
# @raise [ArgumentError]
|
15
|
+
def hex_to_bin(data)
|
16
|
+
raise ArgumentError, 'data must be string' unless data.is_a?(String)
|
17
|
+
hex_string?(data) ? [data].pack('H*') : data
|
18
|
+
end
|
19
|
+
|
20
|
+
# Combine two elements(+left+ and +right+) with sort configuration.
|
21
|
+
# @param [Merkle::Config] config
|
22
|
+
# @param [String] left Left element(binary format).
|
23
|
+
# @param [String] right Right element(binary format).
|
24
|
+
# @return [String] Combined string.
|
25
|
+
# @raise [ArgumentError]
|
26
|
+
def combine_sorted(config, left, right)
|
27
|
+
raise ArgumentError, "config must be Merkle::Config" unless config.is_a?(Merkle::Config)
|
28
|
+
raise ArgumentError, "left must be string" unless left.is_a?(String)
|
29
|
+
raise ArgumentError, "right must be string" unless right.is_a?(String)
|
30
|
+
if config.sort_hashes
|
31
|
+
lh = left.unpack1('H*')
|
32
|
+
rh = right.unpack1('H*')
|
33
|
+
lh < rh ? left + right : right + left
|
34
|
+
else
|
35
|
+
left + right
|
36
|
+
end
|
37
|
+
end
|
38
|
+
|
39
|
+
end
|
40
|
+
end
|
data/lib/merkle.rb
ADDED
@@ -0,0 +1,16 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "merkle/version"
|
4
|
+
require_relative 'merkle/util'
|
5
|
+
require_relative 'merkle/config'
|
6
|
+
require_relative 'merkle/abstract_tree'
|
7
|
+
require_relative 'merkle/binary_tree'
|
8
|
+
require_relative 'merkle/adaptive_tree'
|
9
|
+
require_relative 'merkle/proof'
|
10
|
+
|
11
|
+
# Merkle tree module.
|
12
|
+
module Merkle
|
13
|
+
|
14
|
+
class Error < StandardError; end
|
15
|
+
# Your code goes here...
|
16
|
+
end
|
data/sig/merkle.rbs
ADDED
metadata
ADDED
@@ -0,0 +1,59 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: merkle
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.1.0
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- azuchi
|
8
|
+
bindir: exe
|
9
|
+
cert_chain: []
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
11
|
+
dependencies: []
|
12
|
+
description: A Ruby library for Merkle trees
|
13
|
+
email:
|
14
|
+
- azuchi@chaintope.com
|
15
|
+
executables: []
|
16
|
+
extensions: []
|
17
|
+
extra_rdoc_files: []
|
18
|
+
files:
|
19
|
+
- ".rspec"
|
20
|
+
- ".ruby-gemset"
|
21
|
+
- ".ruby-version"
|
22
|
+
- CODE_OF_CONDUCT.md
|
23
|
+
- LICENSE.txt
|
24
|
+
- README.md
|
25
|
+
- Rakefile
|
26
|
+
- lib/merkle.rb
|
27
|
+
- lib/merkle/abstract_tree.rb
|
28
|
+
- lib/merkle/adaptive_tree.rb
|
29
|
+
- lib/merkle/binary_tree.rb
|
30
|
+
- lib/merkle/config.rb
|
31
|
+
- lib/merkle/proof.rb
|
32
|
+
- lib/merkle/util.rb
|
33
|
+
- lib/merkle/version.rb
|
34
|
+
- sig/merkle.rbs
|
35
|
+
homepage: https://github.com/chaintope/merkle
|
36
|
+
licenses:
|
37
|
+
- MIT
|
38
|
+
metadata:
|
39
|
+
homepage_uri: https://github.com/chaintope/merkle
|
40
|
+
source_code_uri: https://github.com/chaintope/merkle
|
41
|
+
changelog_uri: https://github.com/chaintope/merkle
|
42
|
+
rdoc_options: []
|
43
|
+
require_paths:
|
44
|
+
- lib
|
45
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
46
|
+
requirements:
|
47
|
+
- - ">="
|
48
|
+
- !ruby/object:Gem::Version
|
49
|
+
version: 3.0.0
|
50
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
51
|
+
requirements:
|
52
|
+
- - ">="
|
53
|
+
- !ruby/object:Gem::Version
|
54
|
+
version: '0'
|
55
|
+
requirements: []
|
56
|
+
rubygems_version: 3.6.9
|
57
|
+
specification_version: 4
|
58
|
+
summary: A Ruby library for Merkle trees
|
59
|
+
test_files: []
|