Understanding proof-of-work using Ruby - https://blog.robertsj.com/proof-of-work
This file contains 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
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