Skip to content

Instantly share code, notes, and snippets.

@dimosr
Created February 24, 2016 14:55
Show Gist options
  • Save dimosr/fee902358f25f2f4a3d7 to your computer and use it in GitHub Desktop.
Save dimosr/fee902358f25f2f4a3d7 to your computer and use it in GitHub Desktop.
A function finding suitable nonce for encryption to guarantee certain number of leading zeros (here:8) in the cipher text (mimicking bitcoin mining)
import hashlib
import random
import itertools
alphabetString = "abcdefghijklmnopqrstuvwxyz"
def doubleSHA256( plainText ):
firstEncryption = hashlib.sha256()
secondEncryption = hashlib.sha256()
firstEncryption.update(plainText)
secondEncryption.update(firstEncryption.digest())
return secondEncryption.hexdigest()
def createHashWithLeadingZeros (plainText, numberOfZeros):
nonceSize = 0
enoughDifficulty = False
composedMessage = None
while enoughDifficulty is False:
for nonce in itertools.imap(''.join, itertools.product(alphabetString, repeat=nonceSize)):
doubleHash = doubleSHA256(plainText + nonce)
if getNumberOfLeadingZeros(doubleHash) >= numberOfZeros:
enoughDifficulty = True
composedMessage = plainText + nonce
nonceSize = nonceSize + 1
return composedMessage
def getNumberOfLeadingZeros(word):
return len(word) - len(word.lstrip('0'))
message = "aSampleTransactionToMine"
print createHashWithLeadingZeros(message, 8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment