write a code for a complete runable blockchain with the possibility to acess it for…
- User
write a code for a complete runable blockchain with the possibility to acess it for external users
- Assistant
write a code for a complete runable blockchain with the possibility to acess it for external users
Creating a complete, runnable blockchain that external users can access involves implementing several core components:
Below is a simplified implementation of a blockchain in Python using the Flask framework for the web interface. This example includes basic functionalities such as adding transactions, mining new blocks, and viewing the blockchain.
pip install Flaskimport hashlib
import json
from time import time
from uuid import uuid4
from flask import Flask, jsonify, request
class Blockchain:
def __init__(self):
self.current_transactions = []
self.chain = []
# Create the genesis block
self.new_block(previous_hash='1', proof=100)
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 the 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: <float> Amount
:return: <int> 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
@staticmethod
def hash(block):
"""
Creates a SHA-256 hash of a Block
:param block: <dict> Block
:return: <str>
"""
# Ensure the Dictionary is Ordered to have consistent 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
- 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
: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"
# Instantiate the Flask app
app = Flask(__name__)
# Generate a globally unique address for this node
node_identifier = str(uuid4()).replace('-', '')
# Instantiate the Blockchain
blockchain = Blockchain()
@app.route('/mine', methods=['GET'])
def mine():
# 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)
# Reward for finding the proof is adding a transaction granting 1 coin
blockchain.new_transaction(
sender="0",
recipient=node_identifier,
amount=1,
)
# Forge the new Block by adding it to the chain
previous_hash = blockchain.hash(last_block)
block = blockchain.new_block(proof, previous_hash)
response = {
'message': "New Block Forged",
'index': block['index'],
'transactions': block['transactions'],
'proof': block['proof'],
'previous_hash': block['previous_hash'],
}
return jsonify(response), 200
@app.route('/transactions/new', methods=['POST'])
def new_transaction():
values = request.get_json()
# Check that required fields are in the POSTed data
required = ['sender', 'recipient', 'amount']
if not values:
return 'Missing JSON body', 400
if not all(k in values for k in required):
return 'Missing values', 400
# Create a new transaction
index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount'])
response = {'message': f'Transaction will be added to Block {index}'}
return jsonify(response), 201
@app.route('/chain', methods=['GET'])
def full_chain():
response = {
'chain': blockchain.chain,
'length': len(blockchain.chain),
}
return jsonify(response), 200
@app.route('/nodes/register', methods=['POST'])
def register_nodes():
"""
This endpoint allows new nodes to join the network.
Currently not implemented, but placeholder for future expansion.
"""
values = request.get_json()
nodes = values.get('nodes')
if nodes is None:
return "Error: Please supply a valid list of nodes", 400
# Here you would add nodes to the blockchain's node list
# and handle consensus, etc.
response = {
'message': 'New nodes have been added',
'total_nodes': list(blockchain.chain), # Placeholder
}
return jsonify(response), 201
@app.route('/nodes/resolve', methods=['GET'])
def consensus():
"""
This endpoint resolves conflicts by replacing our chain with the longest one in the network.
Currently not implemented, but placeholder for future expansion.
"""
# Placeholder response
response = {
'message': 'Consensus algorithm not implemented.',
}
return jsonify(response), 200
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('-p', '--port', default=5000, type=int, help='Port to listen on')
args = parser.parse_args()
port = args.port
app.run(host='0.0.0.0', port=port)
Blockchain Class:
new_block Method: Adds a new block to the chain after mining.new_transaction Method: Adds a new transaction to the list of transactions.hash Method: Creates a SHA-256 hash of a block.proof_of_work Method: Simple proof-of-work algorithm to find a number that when hashed with the last proof, results in a hash with four leading zeros.valid_proof Method: Validates the proof by checking the hash.Flask API Endpoints:
/mine (GET): Mines a new block by finding the proof-of-work, rewards the miner, and adds the block to the chain./transactions/new (POST): Creates a new transaction by accepting sender, recipient, and amount in the JSON body./chain (GET): Returns the full blockchain./nodes/register and /nodes/resolve: Placeholders for node registration and consensus, useful for expanding the network.Running the Application:
python blockchain.py -p 5000Save the Code:
blockchain.py.Install Flask:
pip install Flask
Run the Blockchain Node:
python blockchain.py
5000. To specify a different port:
python blockchain.py -p 5001
Interact with the Blockchain:
curl http://localhost:5000/mine
curl -X POST -H "Content-Type: application/json" -d '{
"sender": "address1",
"recipient": "address2",
"amount": 5
}' http://localhost:5000/transactions/new
curl http://localhost:5000/chain
This is a basic implementation. For a more robust and secure blockchain, consider implementing the following:
This example provides a foundational understanding of how a blockchain can be implemented and interacted with via an API. It serves as a starting point for building more complex and feature-rich blockchain applications.
Not yet included in a published release.