Last active
April 13, 2018 03:04
-
-
Save MichaelrMentele/c4b596d6c11213b94f3a2f5443dbe964 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'digest' | |
| class Node | |
| attr_accessor :datum, :data, :children, :parent | |
| def initialize(datum, children: nil) | |
| self.parent = nil | |
| self.datum = datum | |
| self.children = [] | |
| end | |
| def add_children(new_children) | |
| self.children += new_children | |
| new_children.each do |child| | |
| child.parent = self | |
| end | |
| end | |
| def to_s | |
| "hash: #{self.datum}" | |
| end | |
| end | |
| class MerkleTree | |
| def self.merklize(data) | |
| nodes = self.nodify(data) | |
| root = self.build_up(nodes) | |
| end | |
| def self.nodify(data) | |
| """ Return list of nodes """ | |
| nodes = [] | |
| data.each do |item| | |
| nodes.push(Node.new(self.hash(item))) | |
| end | |
| nodes | |
| end | |
| private | |
| def self.create_parents(nodes) | |
| parents = [] | |
| nodes.each_slice(2) do |pair| | |
| a, b = pair | |
| puts pair | |
| puts "---" | |
| if(b) | |
| parent_datum = self.hash("#{a}||#{b}") | |
| else | |
| parent_datum = self.hash(a) | |
| end | |
| parent = Node.new(parent_datum) | |
| parent.add_children(pair) | |
| parents.push(parent) | |
| end | |
| parents | |
| end | |
| def self.build_up(nodes) | |
| parents = self.create_parents(nodes) | |
| if(parents.length == 1) | |
| return parents[0] | |
| else | |
| self.build_up(parents) | |
| end | |
| end | |
| def self.hash(content) | |
| Digest::SHA2.hexdigest(content) | |
| end | |
| end | |
| data = ["We", "hold", "these", "truths", "to", "be", "self-evident", "that"] | |
| root = MerkleTree.merklize(data) | |
| puts root.datum == '4a359c93d6b6c9beaa3fe8d8e68935aa5b5081bd2603549af88dee298fbfdd0a' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment