Skip to content

Instantly share code, notes, and snippets.

@neudabei
Last active February 17, 2018 10:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neudabei/3e5973390eda8e4c35f8f8b3d1024618 to your computer and use it in GitHub Desktop.
Save neudabei/3e5973390eda8e4c35f8f8b3d1024618 to your computer and use it in GitHub Desktop.
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