Created
May 18, 2020 19:13
-
-
Save bajcmartinez/c5f13c227092999b999b0c8170e8c577 to your computer and use it in GitHub Desktop.
From Zero to Blockchain in Python - Part 1 - PoW
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
@staticmethod | |
def validate_proof_of_work(last_nonce, last_hash, nonce): | |
""" | |
Validates the nonce | |
:param last_nonce: <int> Nonce of the last block | |
:param nonce: <int> Current nonce to be validated | |
:param last_hash: <str> Hash of the last block | |
:return: <bool> True if correct, False if not. | |
""" | |
sha = hashlib.sha256(f'{last_nonce}{last_hash}{nonce}'.encode()) | |
return sha.hexdigest()[:4] == '0000' | |
def generate_proof_of_work(self, block): | |
""" | |
Very simple proof of work algorithm: | |
- Find a number 'p' such that hash(pp') contains 4 leading zeroes | |
- Where p is the previous proof, and p' is the new proof | |
:param block: <Block> reference to the last block object | |
:return: <int> generated nonce | |
""" | |
last_nonce = block.nonce | |
last_hash = block.hash | |
nonce = 0 | |
while not self.validate_proof_of_work(last_nonce, last_hash, nonce): | |
nonce += 1 | |
return nonce |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment