class Blockchain(object): def init(self): self.chain = [] self.nodes = set() self.current_transactions = []
self.new_block(hash="1", proof=100)
def new_block(self, proof: int, hash: str = None) -> dict:
"""
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,
'hash': hash or self.hash(self.chain[-1]),
}
self.current_transactions = []
self.chain.append(block)
return block
def new_transaction(self, sender: str, digitalsignature: str, temperature: float, humidity: float) -> int:
"""
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,
'digitalsignature': digitalsignature,
'temperature': temperature,
'humidity': humidity,
})
return self.last_block['index'] + 1
@staticmethod
def hash(block: dict) -> str:
"""
Creates a SHA-256 hash of a Block
:param block: <dict> Block
:return: <str>
"""
block_string = dumps(block, sort_keys=True).encode()
return sha256(block_string).hexdigest()
@property
def last_block(self) -> dict:
"""
Returns the last block in the chain
:return: <dict> block
"""
return self.chain[-1]
def proof_of_work(self, last_proof: int) -> int:
"""
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: int, proof: int) -> bool:
"""
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 = sha256(guess).hexdigest()
return guess_hash[:4] == "0000"
def register_node(self, address: str):
"""
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)
self.nodes.add(parsed_url.netloc)
def valid_chain(self, chain: [dict]) -> bool:
"""
Determine if a given blockchain is valid
:param chain: <list><dict> 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}\n{block}\n\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) -> bool:
"""
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 = urlopen(f'http://{node}/chain')
if response.status == 200:
response = load(response.read())
length = response['length']
chain = response['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
main.py
[coding]app = FastAPI(title='test')
# Instantiate the Blockchain
blockchain = Blockchain()
# Generate a globally unique address for this node
digital_signature = str(uuid4()).replace('-', '')
# used to create a new transaction
class Transaction(BaseModel):
sender: str
digitalsignature: str
temperature: float
humidity: float
# used to access list of nodes when creating new ones
class Nodes(BaseModel):
nodes: List[str]
# used to generate a response model for all our returns
class Response(BaseModel):
message: Optional[str] = None
new_chain: List[dict] = None
total_nodes: list = None
chain: List[dict] = None
length: int = None
index: int = None
transactions: List[dict] = None
proof: int = None
hash: str = None
@app.get('/mine/', status_code=200, response_model=Response, response_model_exclude_unset=True)
async def mine() -> dict:
"""
Mine a new block
:return: <dict> message, index, transaction, proof, previous hash
"""
# 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)
# We must receive a reward for finding the proof.
# The sender is "0" to signify that this node has mined a new coin.
blockchain.new_transaction(
sender="0",
digitalsignature=digital_signature,
temperature=25.0,
humidity=25.0,
)
# Forge the new Block by adding it to the chain
hash = blockchain.hash(last_block)
block = blockchain.new_block(proof, hash)
response = {
'message': "Add New Block ",
'index': block['index'],
'transactions': block['transactions'],
'proof': block['proof'],
'hash': block['hash'],
}
return response
@app.post('/transactions/new/', status_code=201, response_model=Response, response_model_exclude_unset=True)
async def new_transaction(values: Transaction) -> dict:
"""
Create a new transaction to a block
:param values: <Transaction> our new transaction to create
:return: <dict> message
"""
index = blockchain.new_transaction(values.sender, values.recipient, values.amount)
response = {'message': f'Transaction will be added to Block {index}'}
return response
@app.get('/chain/', status_code=200, response_model=Response, response_model_exclude_unset=True)
async def full_chain() -> dict:
"""
Gives users the full Blockchain.
:return: <dict> chains, length of list
"""
response = {
'chain': blockchain.chain,
'length': len(blockchain.chain),
}
return response
@app.post('/nodes/register/', status_code=201, response_model=Response, response_model_exclude_unset=True)
def register_nodes(values: Nodes) -> dict:
"""
Accept a list of new nodes in the form of URLs
:param values: <Nodes> list of nodes
:return: <dict> message, new total nodes
"""
for node in values.nodes:
blockchain.register_node(node)
response = {
'message': 'New nodes have been added',
'total_nodes': list(blockchain.nodes),
}
return response
@app.get('/nodes/resolve/', status_code=200, response_model=Response, response_model_exclude_unset=True)
def consensus() -> dict:
"""
Resolves any conflicts — to ensure a node has the correct chain
:return: <dict> message, latest chain
"""
replaced = blockchain.resolve_conflicts()
message = 'Our chain was replaced' if replaced else 'Our chain is authoritative'
response = {'message': message, 'new_chain': blockchain.chain}
return response