123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191 |
- import hashlib
- import json
- from time import time
- from urllib.parse import urlparse
- import requests
- class Blockchain:
- def __init__(self):
- self.current_transactions = []
- self.chain = []
- self.nodes = set()
- # Create the genesis block
- self.new_block(previous_hash=1, proof=100)
- @staticmethod
- def hash(block):
- """
- Creates a SHA-256 hash of a Block
- :param block: <dict> Block
- :return: <str>
- """
- # We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes
- block_string = json.dumps(block, sort_keys=True).encode()
- return hashlib.sha256(block_string).hexdigest()
- @property
- def last_block(self):
- return self.chain[-1]
- 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"
- def register_node(self, address):
- """
- Add a new node to the list of nodes
- :param address: <str> Address of node. Eg. 'http://192.168.0.5:5000'
- """
- parsed_url = urlparse(address)
- if parsed_url.netloc:
- self.nodes.add(parsed_url.netloc)
- elif parsed_url.path:
- # Accepts an URL without scheme like '192.168.0.5:5000'.
- self.nodes.add(parsed_url.path)
- else:
- raise ValueError('Invalid URL')
- 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]
- if block['previous_hash'] != self.hash(last_block):
- return False
- 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
- def new_block(self, proof, previous_hash=None):
- """
- Create a new Block in the Blockchain
- :param proof: <int> The proof given by the Proof of Work algorithm
- :param previous_hash: (Optional) <str> Hash of previous Block
- :return: <dict> New Block
- """
- block = {
- 'index': len(self.chain) + 1,
- 'timestamp': time(),
- 'transactions': self.current_transactions,
- 'proof': proof,
- 'previous_hash': previous_hash or self.hash(self.chain[-1]),
- }
- # Reset the current list of transactions
- self.current_transactions = []
- self.chain.append(block)
- return block
- def new_transaction(self, sender, recipient, amount):
- """
- Creates a new transaction to go into the next mined Block
- :param sender: <str> Address of the Sender
- :param recipient: <str> Address of the Recipient
- :param amount: <int> Amount
- :return: <int> The index of the Block that will hold this transaction
- """
- self.current_transactions.append({
- 'sender': sender,
- 'recipient': recipient,
- 'amount': amount,
- })
- def remove_block(self, index):
- # Remove the block at the specified index
- self.chain.pop(index)
- # Update the previous block to point to the new block
- if index > 0:
- self.chain[index - 1]['next_block'] = self.chain[index]['next_block']
- # Re-encrypt the subsequent blocks
- for i in range(index, len(self.chain)):
- block = self.chain[i]
- previous_hash = self.hash(self.chain[i - 1])
- block['previous_hash'] = previous_hash
- block['hash'] = self.hash(block)
- return self.last_block['index'] + 1
|