Skip to content

Instantly share code, notes, and snippets.

@akoskovacs
Created March 12, 2018 00:13
Show Gist options
  • Save akoskovacs/608eee878c1eb5dc8c12a7ac7f9d6c03 to your computer and use it in GitHub Desktop.
Save akoskovacs/608eee878c1eb5dc8c12a7ac7f9d6c03 to your computer and use it in GitHub Desktop.
Example Ruby miner. The way Bitcoin miners try to find a hash for a given complexity and transaction
# Mining example
require 'benchmark'
require 'openssl'
def hash_ok?(hash, complexity)
hash.start_with?("0" * complexity)
end
# Appending a nonce the the
def create_target(str, nonce)
"#{str}-#{nonce}"
end
# Hashing with standard SHA256
def digest(str)
OpenSSL::Digest::SHA256.new(str).to_s
end
# Default number of leading zeroes in the target hash
# The more zeroes, the bigger the complexitiy
COMPLEXITY = 3
complexity = COMPLEXITY
msg = "Hello, world"
# Custom message from the command line
if ARGV.count > 0
msg = ARGV[0]
end
if ARGV.count > 1
complexity = ARGV[1].to_i
end
puts "-" * 100
puts "Target complexity is #{complexity} leading zeroes in the hash"
puts "-" * 100
start = Time.now
i = 0
loop do
t = create_target(msg, i)
d = digest(t)
print "trying: '#{t}', hash: #{d}, nonce: #{i} "
break if hash_ok?(d, complexity)
puts "[BAD]"
i += 1
end
finish = Time.now
puts "[GOOD]"
puts "-" * 100
puts "Target is satisfied after #{i} hashes"
puts "Needed #{finish-start} seconds to do it"
@akoskovacs
Copy link
Author

It's just a demonstration about the core concept, unfortunately you can't mine anything with this alone.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment