Skip to content

Instantly share code, notes, and snippets.

@kopylovvlad
Last active October 12, 2018 21:42
Show Gist options
  • Save kopylovvlad/555ab130f3e20d9afb375e58a44fd029 to your computer and use it in GitHub Desktop.
Save kopylovvlad/555ab130f3e20d9afb375e58a44fd029 to your computer and use it in GitHub Desktop.
require 'time'
module HashGenerator
# calculating hash for string "#{string}#{number}"
def self.call(string, number)
# for macOS
return `echo '#{string}#{number}' | sha2 -256`
.gsub('SHA-256 ((null)) = ', '')
.gsub(/\n/, '')
# for Linux
# return `echo '#{string}#{number}' | sha256sum`.gsub(/\s\s\-$/, '')
end
end
module HashChecker
# check does hash start with corrent numbers
def self.call(hash_str, zero_count)
hash_start = hash_str[0..(zero_count - 1)]
hash_start == ('0' * zero_count)
end
end
module TimeSplitter
# prepare time format for output
def self.call(time_start, time_end)
seconds = ((time_end - time_start)).round
minutes = ((time_end - time_start) / 60).round
[minutes, seconds]
end
end
# class for calculcation
# it takes main string and number of leading zeros
class MainMachine
attr_reader :main_string, :zero_count
def initialize(main_string, zero_count)
@main_string = main_string
@zero_count = zero_count
end
def perform
time_start = Time.now
number = 0
sha_hash = ''
# infinity loop
loop do
# generate hash
sha_hash = HashGenerator.call(main_string, number)
# check is hash valid
if HashChecker.call(sha_hash, zero_count) == true
# break loop if hash is valid
break
end
# increase number for another iteration
number += 1
end
# output
time_end = Time.now
minutes, seconds = TimeSplitter.call(time_start, time_end)
puts "\n\rstring: '#{main_string}'"
puts "number: '#{number}'"
puts "hash: '#{sha_hash}'"
puts "time: '#{minutes}'(minutes), '#{seconds}'(seconds)"
end
end
main_string = 'hello world!'
number_of_leading_zeros = 3
MainMachine.new(main_string, number_of_leading_zeros).perform
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment