Skip to content

Instantly share code, notes, and snippets.

@keiya
Created January 11, 2017 14:34
Show Gist options
  • Select an option

  • Save keiya/deda9676dc21a7d67f1685e0df8af437 to your computer and use it in GitHub Desktop.

Select an option

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"
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