0% found this document useful (0 votes)
4 views7 pages

Lab Assignment 1

This document outlines a lab assignment focused on implementing blockchain technology, specifically through the development of a Solidity-based smart contract for fund transfers and a simple blockchain using Python. It details the components and testing of the smart contract, as well as the structure and functionality of the Python blockchain, including API endpoints for interaction. The assignment aims to provide a comprehensive understanding of blockchain technology and its applications.

Uploaded by

avadhoot.dhumal9
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)
4 views7 pages

Lab Assignment 1

This document outlines a lab assignment focused on implementing blockchain technology, specifically through the development of a Solidity-based smart contract for fund transfers and a simple blockchain using Python. It details the components and testing of the smart contract, as well as the structure and functionality of the Python blockchain, including API endpoints for interaction. The assignment aims to provide a comprehensive understanding of blockchain technology and its applications.

Uploaded by

avadhoot.dhumal9
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/ 7

PRASAD AROTE B21 ROLL NO - 77

Lab Assignment 1
AIM: To study implementation of Blockchain Technology.
LO1: Develop and test smart contract on local blockchain.
Theory:
Introduction
It demonstrates two key aspects of blockchain technology:
1. Smart Contract Development: A Solidity-based smart contract for transferring funds
between accounts on the Ethereum blockchain.
2. Blockchain Implementation: A simple blockchain implementation using Python to
understand the underlying concepts of blockchain technology.

Part 1: Smart Contract for Fund Transfer


Code Explanation
The smart contract, named FinancialContract, is written in Solidity and consists of the
following key components:
1. Mapping for Balances:
o A mapping is used to store the balance of each address:
o This allows the contract to manage funds for multiple accounts.
2. Constructor:
o The constructor initializes the deployer’s balance to 25000:
3. getBalance Function:
o This function returns the balance of a specific account:
4. deposit Function:
o Users can deposit funds into their own account:
5. transfer Function:
o This function transfers funds from the sender to a recipient:
o It includes a require statement to ensure the sender has sufficient funds and
emits a Transfer event to log the transaction.
6. Event:
o The Transfer event logs the details of each transfer:
Testing the Contract
The contract was tested using the Remix IDE. Below is the workflow:
PRASAD AROTE B21 ROLL NO - 77

1. Deployment:
o The contract was deployed, and the deployer’s address was initialized with a
balance of 25000.
2. Deposit:
o The deposit function was called with an amount of 1000. The deployer’s
balance increased to 26000.
3. Transfer:
o The transfer function was called to send 500 to a recipient address. The
deployer’s balance decreased to 25500, and the recipient’s balance increased
to 500.
4. Balance Check:
o The getBalance function was used to verify the balances of both the deployer
and the recipient.

Part 2: Blockchain Implementation Using Python


Code Explanation
A simple blockchain was implemented using Python to demonstrate the core concepts of
blockchain technology. The implementation includes the following components:
1. Blockchain Class:
o Manages the chain, transactions, and proof-of-work.
PRASAD AROTE B21 ROLL NO - 77

o Key methods:
▪ new_block: Creates a new block and adds it to the chain.
▪ new_transaction: Adds a new transaction to the list of pending
transactions.
▪ proof_of_work: Implements a simple proof-of-work algorithm.
▪ valid_proof: Validates the proof-of-work.
2. Flask API:
o Provides endpoints to interact with the blockchain:
▪ /mine: Mines a new block.
▪ /transactions/new: Adds a new transaction.
▪ /chain: Returns the full blockchain.

import hashlib
import json
from time import time
from uuid import uuid4
from flask import Flask, jsonify, request

class Blockchain:
def __init__(self):
self.chain = []
self.current_transactions = []
self.new_block(previous_hash='1', proof=100) # Genesis block

def new_block(self, proof, previous_hash=None):


block = {
'index': len(self.chain) + 1,
'timestamp': time(),
'transactions': self.current_transactions,
'proof': proof,
'previous_hash': previous_hash or self.hash(self.chain[-1]),
PRASAD AROTE B21 ROLL NO - 77

}
self.current_transactions = []
self.chain.append(block)
return block

def new_transaction(self, sender, recipient, amount):


self.current_transactions.append({
'sender': sender,
'recipient': recipient,
'amount': amount,
})
return self.last_block['index'] + 1

@staticmethod
def hash(block):
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):


proof = 0
while self.valid_proof(last_proof, proof) is False:
proof += 1
return proof

@staticmethod
def valid_proof(last_proof, proof):
PRASAD AROTE B21 ROLL NO - 77

guess = f'{last_proof}{proof}'.encode()
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:4] == "0000"

app = Flask(__name__)
node_identifier = str(uuid4()).replace('-', '')
blockchain = Blockchain()

@app.route('/mine', methods=['GET'])
def mine():
last_block = blockchain.last_block
last_proof = last_block['proof']
proof = blockchain.proof_of_work(last_proof)

blockchain.new_transaction(
sender="0",
recipient=node_identifier,
amount=1,
)

block = blockchain.new_block(proof)
response = {
'message': "New Block Forged",
'index': block['index'],
'transactions': block['transactions'],
'proof': block['proof'],
'previous_hash': block['previous_hash'],
}
return jsonify(response), 200
PRASAD AROTE B21 ROLL NO - 77

@app.route('/transactions/new', methods=['POST'])
def new_transaction():
values = request.get_json()
required = ['sender', 'recipient', 'amount']
if not all(k in values for k in required):
return 'Missing values', 400

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

if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)

Testing the Blockchain


1. Run the Python Script:
o Start the Flask server by running the script.
o The blockchain will be accessible at http://localhost:5000.
2. Interact with the API:
o Use tools like Postman or cURL to:
▪ Add a transaction: POST to /transactions/new with JSON data.
PRASAD AROTE B21 ROLL NO - 77

▪ Mine a block: GET /mine.


▪ View the chain: GET /chain.
Conclusion:
This assignment successfully demonstrates:
Smart Contract Development: A Solidity-based contract for fund transfer.
Blockchain Implementation: A Python-based blockchain with mining and transaction
capabilities.

Together, these components provide a comprehensive understanding of blockchain technology


and its applications.

You might also like