Created
October 19, 2017 23:21
-
-
Save patbenatar/a2f7476d1a4c62d73d46388a7947af58 to your computer and use it in GitHub Desktop.
Ruby Proof of Work example
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 'optparse' | |
require_relative './proof_of_work' | |
options = {} | |
OptionParser.new do |opts| | |
opts.on('--input INPUT', 'Input data') { |v| options[:input] = v } | |
opts.on('--difficulty DIFFICULTY', 'Difficulty (leading zeroes)') { |v| options[:difficulty] = v } | |
end.parse! | |
start_time = Time.now | |
hash, nonce = ProofOfWork.hash_with_proof_of_work(options[:input], options[:difficulty]) | |
puts | |
puts "Hashed data: #{options[:input]}" | |
puts "With difficulty: #{options[:difficulty]}" | |
puts | |
puts "Found nonce: #{nonce}" | |
puts "Result: #{hash}" | |
puts "Time to find nonce: #{Time.now - start_time} s" |
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' | |
module ProofOfWork | |
def self.hash_with_proof_of_work(data, difficulty) | |
0.upto(Float::INFINITY) do |nonce_candidate| | |
result = hash(data, nonce_candidate) | |
puts result | |
return [result, nonce_candidate] if result.start_with?(difficulty) | |
end | |
end | |
def self.hash(data, nonce) | |
sha = Digest::SHA256.new | |
sha.update(nonce.to_s + data) | |
sha.hexdigest | |
end | |
end |
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 'optparse' | |
require_relative './proof_of_work' | |
options = {} | |
OptionParser.new do |opts| | |
opts.on('--input INPUT', 'Input data') { |v| options[:input] = v } | |
opts.on('--hash HASH', 'Hash') { |v| options[:hash] = v } | |
opts.on('--nonce NONCE', 'Nonce') { |v| options[:nonce] = v } | |
end.parse! | |
hash = ProofOfWork.hash(options[:input], options[:nonce]) | |
puts "Hashed data: #{options[:input]}" | |
puts "Given hash: #{options[:hash]}" | |
puts "Given nonce: #{options[:nonce]}" | |
puts | |
if hash == options[:hash] | |
puts "Verified that given nonce is valid proof of work." | |
else | |
puts "Given nonce is invalid, no proof of work." | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment