Created
January 11, 2017 14:34
-
-
Save keiya/deda9676dc21a7d67f1685e0df8af437 to your computer and use it in GitHub Desktop.
Proof Of Work in Ruby // this snippet shows an example of Bitcoin "proof of work"
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/sha2' | |
| class ProofOfWork | |
| @charset = (" ".."~").to_a | |
| def self.solve(target,maxlength) | |
| for i in 1..maxlength+1 | |
| ProofOfWork.chain(ProofOfWork.product(i)) do |candidate| | |
| hashval = Digest::SHA256.hexdigest(candidate) | |
| if hashval.start_with?(target) | |
| return candidate | |
| end | |
| end | |
| end | |
| return nil | |
| end | |
| def self.chain(*iterables) | |
| for it in iterables | |
| if it.instance_of? String | |
| it.split("").each do |i| | |
| yield i | |
| end | |
| else | |
| for elem in it | |
| yield elem | |
| end | |
| end | |
| end | |
| end | |
| def self.product(max) | |
| strings = 1.upto(max).flat_map do |n| | |
| @charset.repeated_permutation(n).map(&:join) | |
| end | |
| end | |
| end | |
| p ProofOfWork.solve("0000",8) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment