2019-11-01 23:51:39 +01:00
|
|
|
"""This file contains the class for the Blockchain."""
|
|
|
|
|
|
|
|
from block import Block
|
|
|
|
|
|
|
|
|
|
|
|
class Blockchain:
|
|
|
|
"""docstring for Blockchain"""
|
|
|
|
def __init__(self):
|
|
|
|
self.chain = []
|
|
|
|
self.all_transactions = []
|
|
|
|
self.genesis_block()
|
2019-11-06 10:12:03 +01:00
|
|
|
self.proof_difficulty = 2
|
2019-11-01 23:51:39 +01:00
|
|
|
|
|
|
|
def genesis_block(self):
|
|
|
|
"""First block of the Blockchain"""
|
|
|
|
|
|
|
|
transactions = {}
|
|
|
|
genesis_block = Block(transactions, '0')
|
|
|
|
self.chain.append(genesis_block)
|
|
|
|
|
|
|
|
def print_blocks(self):
|
|
|
|
"""Print contents of blockchain."""
|
|
|
|
|
2019-11-04 11:01:53 +01:00
|
|
|
for i, current_block in enumerate(self.chain):
|
2019-11-01 23:51:39 +01:00
|
|
|
print('=====')
|
|
|
|
print(f'Block {i} {current_block}')
|
|
|
|
current_block.print_block()
|
|
|
|
print('=====')
|
|
|
|
print()
|
|
|
|
|
|
|
|
def add_block(self, transactions):
|
|
|
|
"""Add a block to the blockchain's chain."""
|
|
|
|
|
|
|
|
previous_block_hash = self.chain[-1].hash
|
|
|
|
new_block = Block(transactions, previous_block_hash)
|
|
|
|
proof = self.proof_of_work(new_block)
|
2019-11-04 11:01:53 +01:00
|
|
|
new_block.proof = proof
|
2019-11-01 23:51:39 +01:00
|
|
|
self.chain.append(new_block)
|
|
|
|
|
2019-11-04 11:01:53 +01:00
|
|
|
return new_block
|
2019-11-01 23:51:39 +01:00
|
|
|
|
|
|
|
def validate_chain(self):
|
|
|
|
"""Check to see if blocks are linked to each other properly."""
|
|
|
|
|
|
|
|
for i in range(1, len(self.chain)):
|
|
|
|
current = self.chain[i]
|
|
|
|
previous = self.chain[i - 1]
|
|
|
|
|
|
|
|
if current.hash != current.generate_hash():
|
|
|
|
print('WARNING!! The current hash of the block does not equal '
|
|
|
|
'the generated hash of the block!!!')
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
if current.previous_hash != previous.generate_hash():
|
|
|
|
print('WARNING!! The previous hash of the block does not equal'
|
|
|
|
' the generated hash of the previous block!!!')
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
print('Blockchain is valid!')
|
|
|
|
|
|
|
|
return True
|
|
|
|
|
2019-11-06 10:12:03 +01:00
|
|
|
def proof_of_work(self, block):
|
2019-11-01 23:51:39 +01:00
|
|
|
"""Implement a proof of work in the blockchain."""
|
|
|
|
|
2019-11-03 10:04:12 +01:00
|
|
|
proof = block.hash
|
2019-11-01 23:51:39 +01:00
|
|
|
|
2019-11-06 10:12:03 +01:00
|
|
|
while not proof.startswith('0' * self.proof_difficulty):
|
2019-11-01 23:51:39 +01:00
|
|
|
block.nonce += 1
|
2019-11-03 10:04:12 +01:00
|
|
|
proof = block.generate_hash()
|
2019-11-01 23:51:39 +01:00
|
|
|
|
|
|
|
block.nonce = 0
|
|
|
|
|
2019-11-03 10:04:12 +01:00
|
|
|
return proof
|