Created
May 10, 2013 05:18
-
-
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!
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/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