Last active
April 8, 2018 00:23
-
-
Save dvf/83436d7b0b9040ca2cf5856d369f2a14 to your computer and use it in GitHub Desktop.
Step 4: Proof of Work
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
import hashlib | |
import json | |
from time import time | |
from uuid import uuid4 | |
class Blockchain(object): | |
... | |
def proof_of_work(self, last_proof): | |
""" | |
Simple Proof of Work Algorithm: | |
- Find a number p' such that hash(pp') contains leading 4 zeroes, where p is the previous p' | |
- p is the previous proof, and p' is the new proof | |
:param last_proof: <int> | |
:return: <int> | |
""" | |
proof = 0 | |
while self.valid_proof(last_proof, proof) is False: | |
proof += 1 | |
return proof | |
@staticmethod | |
def valid_proof(last_proof, proof): | |
""" | |
Validates the Proof: Does hash(last_proof, proof) contain 4 leading zeroes? | |
:param last_proof: <int> Previous Proof | |
:param proof: <int> Current Proof | |
:return: <bool> True if correct, False if not. | |
""" | |
guess = f'{last_proof}{proof}'.encode() | |
guess_hash = hashlib.sha256(guess).hexdigest() | |
return guess_hash[:4] == "0000" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I met the same mistakes but I fixed it with improving my python version to 3.6.@zhouzhou84