Skip to content

Instantly share code, notes, and snippets.

@germanattanasio
Created December 15, 2020 21:18
Show Gist options
  • Save germanattanasio/70843a7c5ec956bccc1d2dd425dc4bc2 to your computer and use it in GitHub Desktop.
Save germanattanasio/70843a7c5ec956bccc1d2dd425dc4bc2 to your computer and use it in GitHub Desktop.
Mining the nonce for a take home exam at NYU Stern
import hashlib
import time
import re
from datetime import date
# Block information
block = 1
data = 'German gets a PD'
prevHash = '0000000000000000000000000000000000000000000000000000000000000000'
# Number of leading zeros
difficulty = 10
targetHash = ''.zfill(difficulty)
def leading_zeros(s):
return len(re.match('^0*', s).group())
start = time.time()
print('EMBA A21 - Digital Currency - German Attanasio')
print('Start time: {}'.format(date.today()))
print('Block: {}, Data: {}, difficulty: {}, prevHash: {}'.format(
block, data, difficulty, prevHash))
nonce = 0
bestNonce = nonce
bestDifficulty = 0
foundNonce = False
while not foundNonce:
blockStr = "{}{}{}{}".format(block, nonce, data, prevHash)
hash = hashlib.sha256(blockStr.encode()).hexdigest()
currDiff = leading_zeros(hash)
if currDiff > bestDifficulty or currDiff == difficulty:
end = time.time()
print('Leading zeros: {}, time: {:.2f} sec, nonce: {}, hash: {}'.format(
currDiff, end - start, nonce, hash))
bestDifficulty = currDiff
bestNonce = nonce
if currDiff == difficulty:
foundNonce = True
nonce += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment