Created
March 12, 2018 00:13
-
-
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
This file contains 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
# 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" |
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
How can I mine BTC with it?