Skip to content

Instantly share code, notes, and snippets.

@lumunge
Created June 11, 2022 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lumunge/289743aed153dae1e6826828606ebbae to your computer and use it in GitHub Desktop.
Save lumunge/289743aed153dae1e6826828606ebbae to your computer and use it in GitHub Desktop.
import hashlib
import time
# text = "Bitcoin mining uses the SHA256 hashing algorithm"
# text_hash = hashlib.sha256(text.encode('utf-8')).hexdigest()
# print(text_hash)
# def findNonce(text):
# for nonce in range(20):
# n = text + str(nonce)
# hash = hashlib.sha256(n.encode('utf-8')).hexdigest()
# print(f'{nonce} : {hash}')
# findNonce(text)
def proof_of_work(header, difficulty_bits, max_nonce):
target = 2 ** (256-difficulty_bits) # difficulty target
for nonce in range(max_nonce):
to_hash = (str(header) + str(nonce)).encode('utf-8')
hashed = hashlib.sha256(to_hash).hexdigest()
if int(hashed, 16) < target: # valid result less than target
print(f"### SUCCESS ### {nonce}")
print(f"Nonce: {nonce}\nHashed Result: {hashed}")
return (hashed, nonce)
print(f"### FAILED after {nonce} (max_nonce) tries ###")
return nonce
def solve(nonce, hashed):
for difficulty_bits in range(32): # difficulty from 0 - 31 bits
difficulty = 2 ** difficulty_bits
print("### Mining Started...")
print(f"Difficulty: {difficulty} ({difficulty_bits} bits)")
start = time.time()
block = 'Random test block header with transactions' + hashed
max_nonce = 2 ** 32 # 4 billion
hashed, nonce = proof_of_work(block, difficulty_bits, max_nonce) # get valid nonce
end = time.time()
elapsed_time = end - start
print(f"Took: {elapsed_time:.4f} seconds")
if elapsed_time > 0:
hash_power = float(int(nonce) / elapsed_time) # hashes/second
print(f"Hashing Power: {hash_power} hashes/second")
print()
if __name__ == '__main__':
solve(0, '')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment