Block Chain Python Code
Block Chain Python Code
import json
import requests
class Blockchain:
def __init__(self):
self.current_transactions = []
self.chain = []
self.nodes = set()
self.new_block(previous_hash='1', proof=100)
"""
"""
parsed_url = urlparse(address)
if parsed_url.netloc:
self.nodes.add(parsed_url.netloc)
elif parsed_url.path:
self.nodes.add(parsed_url.path)
else:
"""
"""
last_block = chain[0]
current_index = 1
block = chain[current_index]
print(f'{last_block}')
print(f'{block}')
print("\n-----------\n")
last_block_hash = self.hash(last_block)
if block['previous_hash'] != last_block_hash:
return False
return False
last_block = block
current_index += 1
return True
def resolve_conflicts(self):
"""
"""
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
response = requests.get(f'http://{node}/chain')
if response.status_code == 200:
length = response.json()['length']
chain = response.json()['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
"""
Create a new Block in the Blockchain
"""
block = {
'index': len(self.chain) + 1,
'timestamp': time(),
'transactions': self.current_transactions,
'proof': proof,
self.current_transactions = []
self.chain.append(block)
return block
"""
:return: The index of the Block that will hold this transaction
"""
self.current_transactions.append({
'sender': sender,
'recipient': recipient,
'amount': amount,
})
return self.last_block['index'] + 1
@property
def last_block(self):
return self.chain[-1]
@staticmethod
def hash(block):
"""
"""
# We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes
return hashlib.sha256(block_string).hexdigest()
def proof_of_work(self, last_block):
"""
:return: <int>
"""
last_proof = last_block['proof']
last_hash = self.hash(last_block)
proof = 0
proof += 1
return proof
@staticmethod
"""
"""
guess = f'{last_proof}{proof}{last_hash}'.encode()
guess_hash = hashlib.sha256(guess).hexdigest()
app = Flask(__name__)
blockchain = Blockchain()
@app.route('/mine', methods=['GET'])
def mine():
last_block = blockchain.last_block
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.
blockchain.new_transaction(
sender="0",
recipient=node_identifier,
amount=1,
previous_hash = blockchain.hash(last_block)
response = {
'index': block['index'],
'transactions': block['transactions'],
'proof': block['proof'],
'previous_hash': block['previous_hash'],
@app.route('/transactions/new', methods=['POST'])
def new_transaction():
values = request.get_json()
@app.route('/chain', methods=['GET'])
def full_chain():
response = {
'chain': blockchain.chain,
'length': len(blockchain.chain),
@app.route('/nodes/register', methods=['POST'])
def register_nodes():
values = request.get_json()
nodes = values.get('nodes')
if nodes is None:
blockchain.register_node(node)
response = {
'total_nodes': list(blockchain.nodes),
@app.route('/nodes/resolve', methods=['GET'])
def consensus():
replaced = blockchain.resolve_conflicts()
if replaced:
response = {
'new_chain': blockchain.chain
}
else:
response = {
'chain': blockchain.chain
if __name__ == '__main__':
parser = ArgumentParser()
args = parser.parse_args()
port = args.port
app.run(host='0.0.0.0', port