Skip to content

Instantly share code, notes, and snippets.

@quad
Created May 10, 2013 05:18
Show Gist options
  • Select an option

  • Save quad/5552532 to your computer and use it in GitHub Desktop.

Select an option

Save quad/5552532 to your computer and use it in GitHub Desktop.
A (probably incorrect) proof of work system based on my understanding of Hashcash. For instructional purposes only!
require 'digest/sha1'
class Proof < Struct.new :data, :difficulty, :token
def valid?
hash = Digest::SHA1.hexdigest("#{data} #{difficulty} #{token}")
pl = prefix_length(hash.to_i(16))
difficulty <= pl
end
def increment
Proof.new data, difficulty, token + 1
end
private
def prefix_length number
b = 0
while (number & 1) > 0
number = number >> 1
b += 1
end
b
end
end
def work data, difficulty
proof = Proof.new data, difficulty, 0
until proof.valid?
proof = proof.increment
end
proof
end
p work "test", 21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment