KEMBAR78
Blockchain Lab Instructions | PDF | Python (Programming Language) | Json
0% found this document useful (0 votes)
64 views5 pages

Blockchain Lab Instructions

Uploaded by

avenirsirene
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views5 pages

Blockchain Lab Instructions

Uploaded by

avenirsirene
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Lab Instructions

Creating a Simple Blockchain in Python


27/11/2024
Dr. Noureddine Lasla

Objective:
By the end of this lab, students will understand the basics of blockchain technology by implementing
a simple blockchain in Python. They will explore how blocks are created, mined, chained together,
and validated, as well as how to deploy the blockchain using a Flask-based web application.

Prerequisites:
● Python 3 installed on your system.
● Basic understanding of Python programming.
● Basic understanding of Json.
● Familiarity with Flask framework (optional, we will cover necessary basics).

Instructions:

Step 1: Set Up the Environment

1. Open your code editor (e.g., VSCode, PyCharm, or any text editor with Python support).
2. Install the required Python packages by running:

pip install flask

3. Create a new Python file named blockchain.py.

Step 2: Import Required Libraries

1. Copy and paste the following imports into your blockchain.py file:

import datetime
import hashlib
import json
from flask import Flask, jsonify

2. Explanation:

● datetime: Adds timestamps to blocks.


● hashlib: Generates SHA-256 hashes for fingerprinting.
● json: Formats data in JSON for easy storage and retrieval.
● Flask: Enables the creation of a web app to interact with the blockchain.
Step 3: Define the Blockchain Class

1. Implement the Blockchain class by adding the following code:

class Blockchain:
def __init__(self):
self.chain = []
self.create_block(proof=1, previous_hash='0')

def create_block(self, proof, previous_hash):


block = {
'index': len(self.chain) + 1,
'timestamp': str(datetime.datetime.now()),
'proof': proof,
'previous_hash': previous_hash
}
self.chain.append(block)
return block

def print_previous_block(self):
return self.chain[-1]

def proof_of_work(self, previous_proof):


new_proof = 1
check_proof = False
while check_proof is False:
hash_operation = hashlib.sha256(str(new_proof**2 - previous_proof**2).encode()).hexdigest()
if hash_operation[:5] == '00000':
check_proof = True
else:
new_proof += 1
return new_proof

def hash(self, block):


encoded_block = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(encoded_block).hexdigest()

def chain_valid(self, chain):


previous_block = chain[0]
block_index = 1
while block_index < len(chain):
block = chain[block_index]
if block['previous_hash'] != self.hash(previous_block):
return False
previous_proof = previous_block['proof']
proof = block['proof']
hash_operation = hashlib.sha256(str(proof**2 - previous_proof**2).encode()).hexdigest()
if hash_operation[:5] != '00000':
return False
previous_block = block
block_index += 1
return True
2. Explanation:

● __init__: Initializes the blockchain and creates the genesis block.


● create_block: Adds a new block to the chain.
● proof_of_work: Ensures mining requires computational effort.
● hash: Generates the hash for a block.
● chain_valid: Validates the blockchain to prevent tampering.

Step 4: Set Up the Flask Web Application

1. Add the following code into the same blockchain.py file to initialize the Flask application:

app = Flask(__name__)
blockchain = Blockchain()

2. Define the route to mine a block:

@app.route('/mine_block', methods=['GET'])
def mine_block():
previous_block = blockchain.print_previous_block()
previous_proof = previous_block['proof']
proof = blockchain.proof_of_work(previous_proof)
previous_hash = blockchain.hash(previous_block)
block = blockchain.create_block(proof, previous_hash)
response = {
'message': 'A block is MINED',
'index': block['index'],
'timestamp': block['timestamp'],
'proof': block['proof'],
'previous_hash': block['previous_hash']
}
return jsonify(response), 200

3. Define the route to display the blockchain:

@app.route('/get_chain', methods=['GET'])
def display_chain():
response = {
'chain': blockchain.chain,
'length': len(blockchain.chain)
}
return jsonify(response), 200

4. Define the route to validate the blockchain:

@app.route('/valid', methods=['GET'])
def valid():
valid = blockchain.chain_valid(blockchain.chain)
response = {'message': 'The Blockchain is valid.'} if valid else
{'message': 'The Blockchain is not valid.'}
return jsonify(response), 200
Step 5: Run the Application

1. Add the following code at the end of your blockchain.py file to start the Flask server:

app.run(host='127.0.0.1', port=5000)

2. Save and run your Python script:

python blockchain.py

Step 6: Interact with the Blockchain

1. Mine a block: Open your browser and navigate to:

http://127.0.0.1:5000/mine_block

Observe the block details in the output.

2. Display the blockchain: Go to:

http://127.0.0.1:5000/get_chain

View all blocks in JSON format.

3. Validate the blockchain: Access:

http://127.0.0.1:5000/valid

Step 7: Understand the Outputs

● Mining Output:

{
"index": 2,
"message": "A block is MINED",
"previous_hash": "<previous_block_hash>",
"proof": 632238,
"timestamp": "<timestamp>"
}

● Blockchain Output:

{
"chain": [...],
"length": 2
}

● Validation Output:

{
"message": "The Blockchain is valid."
}
Deliverables:
● Python script (blockchain.py).
● Screenshots of outputs from /mine_block, /get_chain, and /valid.

Bonus:
Try deploying the Flask application publicly using cloud services like Heroku.

You might also like