Last active
May 22, 2020 14:11
-
-
Save dvf/976f547c09160b495f44bb0b70541ff7 to your computer and use it in GitHub Desktop.
Step 11: Implementing Consensus Algorithm
This file contains hidden or 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 requests | |
class Blockchain(object) | |
... | |
def valid_chain(self, chain): | |
""" | |
Determine if a given blockchain is valid | |
:param chain: <list> A blockchain | |
:return: <bool> True if valid, False if not | |
""" | |
last_block = chain[0] | |
current_index = 1 | |
while current_index < len(chain): | |
block = chain[current_index] | |
print(f'{last_block}') | |
print(f'{block}') | |
print("\n-----------\n") | |
# Check that the hash of the block is correct | |
if block['previous_hash'] != self.hash(last_block): | |
return False | |
# Check that the Proof of Work is correct | |
if not self.valid_proof(last_block['proof'], block['proof']): | |
return False | |
last_block = block | |
current_index += 1 | |
return True | |
def resolve_conflicts(self): | |
""" | |
This is our Consensus Algorithm, it resolves conflicts | |
by replacing our chain with the longest one in the network. | |
:return: <bool> True if our chain was replaced, False if not | |
""" | |
neighbours = self.nodes | |
new_chain = None | |
# We're only looking for chains longer than ours | |
max_length = len(self.chain) | |
# Grab and verify the chains from all the nodes in our network | |
for node in neighbours: | |
response = requests.get(f'http://{node}/chain') | |
if response.status_code == 200: | |
length = response.json()['length'] | |
chain = response.json()['chain'] | |
# Check if the length is longer and the chain is valid | |
if length > max_length and self.valid_chain(chain): | |
max_length = length | |
new_chain = chain | |
# Replace our chain if we discovered a new, valid chain longer than ours | |
if new_chain: | |
self.chain = new_chain | |
return True | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment