Merge pull request #11 from 2gotgrossman/master

Modified valid_proof and proof_of_work to include the hash of last block
This commit is contained in:
Daniel van Flymen 2018-01-24 00:03:16 -05:00 committed by GitHub
commit ffc0075964
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 18 additions and 10 deletions

View File

@ -48,7 +48,7 @@ class Blockchain:
return False
# Check that the Proof of Work is correct
if not self.valid_proof(last_block['proof'], block['proof']):
if not self.valid_proof(last_block['proof'], block['proof'], last_block['previous_hash']):
return False
last_block = block
@ -146,30 +146,39 @@ class Blockchain:
block_string = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
def proof_of_work(self, last_proof):
def proof_of_work(self, last_block):
"""
Simple Proof of Work Algorithm:
- Find a number p' such that hash(pp') contains leading 4 zeroes
- Where p is the previous proof, and p' is the new proof
:param last_block: <dict> last Block
:return: <int>
"""
last_proof = last_block['proof']
last_hash = self.hash(last_block)
proof = 0
while self.valid_proof(last_proof, proof) is False:
while self.valid_proof(last_proof, proof, last_hash) is False:
proof += 1
return proof
@staticmethod
def valid_proof(last_proof, proof):
def valid_proof(last_proof, proof, last_hash):
"""
Validates the Proof
:param last_proof: Previous Proof
:param proof: Current Proof
:return: True if correct, False if not.
:param last_proof: <int> Previous Proof
:param proof: <int> Current Proof
:param last_hash: <str> The hash of the Previous Block
:return: <bool> True if correct, False if not.
"""
guess = f'{last_proof}{proof}'.encode()
guess = f'{last_proof}{proof}{last_hash}'.encode()
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:4] == "0000"
@ -188,8 +197,7 @@ blockchain = Blockchain()
def mine():
# We run the proof of work algorithm to get the next proof...
last_block = blockchain.last_block
last_proof = last_block['proof']
proof = blockchain.proof_of_work(last_proof)
proof = blockchain.proof_of_work(last_block)
# We must receive a reward for finding the proof.
# The sender is "0" to signify that this node has mined a new coin.