Skip to content

Instantly share code, notes, and snippets.

@neudabei

neudabei/proof_of_work.rb

Last active Feb 17, 2018
Embed
What would you like to do?
Understanding proof-of-work using Ruby - https://blog.robertsj.com/proof-of-work
class ProofOfWork
require 'digest'
def initialize(difficulty:)
@required_number_of_zeros = difficulty
end
def find_nonce_for(block_content:)
nonce = 0
until found_correct_nonce?(nonce, block_content)
nonce += 1
end
nonce
end
private
attr_reader :required_number_of_zeros
def hash(block_content_and_nonce)
Digest::SHA256.hexdigest(block_content_and_nonce)
end
def found_correct_nonce?(nonce, block_content)
hash(block_content + nonce.to_s).start_with? required_number_of_zeros
end
end
worker = ProofOfWork.new(difficulty: "00000")
nonce = worker.find_nonce_for(block_content: "hello world!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.