0% found this document useful (0 votes)
3 views34 pages

Block Chain

The document outlines practical tasks related to developing secure applications using blockchain technology, including creating a secure messaging application with RSA encryption, managing transactions, and implementing a blockchain. It provides code examples for various functionalities such as transaction handling, mining, and interacting with Bitcoin Core API. Additionally, it includes tasks for writing Solidity programs and demonstrating blockchain node operations.

Uploaded by

shadab niyazi
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)
3 views34 pages

Block Chain

The document outlines practical tasks related to developing secure applications using blockchain technology, including creating a secure messaging application with RSA encryption, managing transactions, and implementing a blockchain. It provides code examples for various functionalities such as transaction handling, mining, and interacting with Bitcoin Core API. Additionally, it includes tasks for writing Solidity programs and demonstrating blockchain node operations.

Uploaded by

shadab niyazi
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

INDEX

Sr. Practical Sign


No
a. Develop a secure messaging application where users can exchange
messages securely using RSA encryption. Implement a
mechanism for generating RSA key pairs and
encrypting/decrypting messages.
b. Allow users to create multiple transactions and display them in an
organised format.
1
c. Create a Python class named Transaction with attributes for
sender, receiver, and amount. Implement a method within the
class to transfer money from the sender's account to the receiver's
account ..
d. Implement a function to add new blocks to the miner and dump
the blockchain.
a. Write a python program to demonstrate mining.
b. Demonstrate the use of the Bitcoin Core API to interact with a
Bitcoin Core node.
2
c. Demonstrating the process of running a blockchain node on your
local machine.
d. Demonstrate mining using geth on your private network.
a. Write a Solidity program that demonstrates various types of
functions including regular functions, view functions, pure
functions, and the fallback function.
b. Write a Solidity program that demonstrates function overloading,
mathematical functions, and cryptographic functions.
c. Write a Solidity program that demonstrates various features
3
including contracts, inheritance, constructors, abstract contracts,
interfaces.
d. Write a Solidity program that demonstrates use of libraries,
assembly, events, and error handling.
e. Build a decentralized application (DApp) using Angular for the
frontend and Truffle along with Ganache CLI for the back end.
a. Install and demonstrate use of hyperledger-Irhoa
4
b. Demonstration on interacting with NFT
PRACTICAL NO:1 A
Aim: Develop a secure messaging application where users can exchange messages
securely using RSA encryption. Implement a mechanism for generating RSA key
pairs and encrypting/decrypting messages.

# import libraries
import hashlib
import random
import string
import json
import binascii
import numpy as np
import pandas as pd
import pylab as pl
import logging
import datetime
import collections
# following imports are required by PKI
import Crypto
import [Link]
from [Link] import SHA
from [Link] import RSA
from [Link] import PKCS1_v1_5

import binascii
class Client:
def __init__(self):
random = [Link]().read
self._private_key = [Link](1024, random)
self._public_key = self._private_key.publickey()
self._signer = PKCS1_v1_5.new(self._private_key)
@property
def identity(self):
return [Link](self._public_key.exportKey(format='DER')).decode('ascii')
class Transaction:
def __init__(self, sender, recipient, value):
[Link] = sender
[Link] = recipient
[Link] = value
[Link] = [Link]()
def to_dict(self):
if [Link] == "Genesis":
identity = "Genesis"
else:
identity = [Link]
return [Link]({
'sender': identity,
'recipient': [Link],
'value': [Link],
'time' : [Link]})
def sign_transaction(self):
private_key = [Link]._private_key
signer = PKCS1_v1_5.new(private_key)
h = [Link](str(self.to_dict()).encode('utf8'))
return [Link]([Link](h)).decode('ascii')
Pushpa = Client()
Payal = Client()
t = Transaction(Pushpa,[Link],5.0)
signature = t.sign_transaction()
print (signature)

OUTPUT
PRACTICAL NO:1 B
Aim: Allow users to create multiple transactions and display them in an organised format.

# Dummy placeholders for required classes


# You should replace these with actual implementations
class Client:
def __init__(self):
import random
import string
[Link] = ''.join([Link](string.ascii_uppercase + [Link], k=8))
class Transaction:
def __init__(self, sender, recipient, value):
from datetime import datetime
[Link] = [Link] if isinstance(sender, Client) else sender
[Link] = recipient
[Link] = value
[Link] = [Link]()
[Link] = None
def sign_transaction(self):
# Placeholder for signing logic
[Link] = "signed"
def to_dict(self):
return {
'sender': [Link],
'recipient': [Link],
'value': [Link],
'time': [Link]
}
# Function to display a transaction
def display_transaction(transaction):
tx_dict = transaction.to_dict()
print("sender: " + tx_dict['sender'])
print('-----')
print("recipient: " + tx_dict['recipient'])
print('-----')
print("value: " + str(tx_dict['value']))
print('-----')
print("time: " + str(tx_dict['time']))
print('-----')

# Initialize clients
Dinesh = Client()
Ramesh = Client()
Seema = Client()
Vijay = Client()
transactions = []
# Create and sign transactions
t1 = Transaction(Dinesh, [Link], 15.0)
t1.sign_transaction()
[Link](t1)
t2 = Transaction(Dinesh, [Link], 6.0)
t2.sign_transaction()
[Link](t2)
t3 = Transaction(Ramesh, [Link], 2.0)
t3.sign_transaction()
[Link](t3)
t4 = Transaction(Seema, [Link], 4.0)
t4.sign_transaction()
[Link](t4)
t5 = Transaction(Vijay, [Link], 7.0)
t5.sign_transaction()
[Link](t5)
t6 = Transaction(Ramesh, [Link], 3.0)
t6.sign_transaction()
[Link](t6)
t7 = Transaction(Seema, [Link], 8.0)
t7.sign_transaction()
[Link](t7)
t8 = Transaction(Seema, [Link], 1.0)
t8.sign_transaction()
[Link](t8)
t9 = Transaction(Vijay, [Link], 5.0)
t9.sign_transaction()
[Link](t9)
t10 = Transaction(Vijay, [Link], 3.0)
t10.sign_transaction()
[Link](t10)
# Display all transactions
for transaction in transactions:
display_transaction(transaction)
print('--------------')
# Define Block class
class Block:
def __init__(self):
self.verified_transactions = []
self.previous_block_hash = ""
[Link] = ""
# Create genesis block
last_block_hash = ""
Dinesh = Client()
t0 = Transaction("Genesis", [Link], 500.0)
block0 = Block()
block0.previous_block_hash = None
block0.verified_transactions.append(t0)

# NOTE: This is a placeholder hash. In real code, you'd use hashlib + serialization
digest = str([Link]) + [Link] + str([Link])
last_block_hash = digest

# Blockchain list
TPCoins = []
[Link](block0)

# Function to print the blockchain


def dump_blockchain(blockchain):
print("Number of blocks in the chain: " + str(len(blockchain)))
for i, block in enumerate(blockchain):
print("block # " + str(i))
for transaction in block.verified_transactions:
display_transaction(transaction)
print('--------------')
print('=====================================')

# Dump the blockchain


dump_blockchain(TPCoins)
OUTPUT
PRACTICAL NO:1 C
Aim: Create a Python class named Transaction with attributes for sender, receiver, and
amount. Implement a method within the class to transfer money from the sender's account
to the receiver's account.

class Transaction:
def __init__(self, sender, receiver, amount):
[Link] = sender
[Link] = receiver
[Link] = amount
def transfer(self, accounts):
# Check if both users exist
if [Link] not in accounts or [Link] not in accounts:
return "Error: Sender or receiver not found in account records."
# Check if sender has enough balance
if accounts[[Link]] < [Link]:
return f"Error: {[Link]} has insufficient funds."
# Perform transfer
accounts[[Link]] -= [Link]
accounts[[Link]] += [Link]
return f"Transferred ${[Link]:.2f} from {[Link]} to {[Link]}."
# Example usage:
if __name__ == "__main__":
# Accounts dictionary
accounts = {
"Alice": 500.00,
"Bob": 300.00 }
# Create a transaction
t1 = Transaction("Alice", "Bob", 150)
# Perform transfer
result = [Link](accounts)
print(result)
# Check updated balances
print("Updated Balances:")
for user, balance in [Link]():
print(f"{user}: ${balance:.2f}")
OUTPUT:
PRACTICAL NO:1 D
Aim: Implement a function to add new blocks to the miner and dump the blockchain.
import hashlib
import time
import json
class Block:
def __init__(self, index, previous_hash, data, timestamp=None, nonce=0):
[Link] = index
self.previous_hash = previous_hash
[Link] = timestamp or [Link]()
[Link] = data
[Link] = nonce
[Link] = self.calculate_hash()
def calculate_hash(self):
block_string = f"{[Link]}{self.previous_hash}{[Link]}{[Link]}{[Link]}"
return hashlib.sha256(block_string.encode()).hexdigest()
def mine_block(self, difficulty=2):
"""Proof-of-work algorithm with adjustable difficulty."""
target = '0' * difficulty
while [Link][:difficulty] != target:
[Link] += 1
[Link] = self.calculate_hash()
class Blockchain:
def __init__(self):
[Link] = [self.create_genesis_block()]
[Link] = 2 # Increase this for slower mining
def create_genesis_block(self):
"""First block of the chain with fixed values."""
return Block(0, "0", "Genesis Block")
def get_latest_block(self):
return [Link][-1]
def add_block(self, data):
"""Add a new block with data to the chain."""
previous_block = self.get_latest_block()
new_block = Block(index=previous_block.index + 1,
previous_hash=previous_block.hash,
data=data)
new_block.mine_block([Link])
[Link](new_block)
print(f"Block #{new_block.index} mined: {new_block.hash}")
def dump_chain(self):
"""Prints out the entire blockchain."""
print("\nBlockchain:")
for block in [Link]:
print([Link]({
"index": [Link],
"timestamp": [Link]([Link]),
"data": [Link],
"hash": [Link],
"previous_hash": block.previous_hash,
"nonce": [Link]
}, indent=4))
# Example usage
if __name__ == "__main__":
miner = Blockchain()

# Add new blocks


miner.add_block("Transaction A -> B: $100")
miner.add_block("Transaction B -> C: $50")
# Dump the blockchain
miner.dump_chain()
OUTPUT
PRACTICAL NO:2 A
Aim: Write a python program to demonstrate mining.
import hashlib
import time
class Block:
def __init__(self, data, previous_hash='0'):
[Link] = [Link]()
[Link] = data
self.previous_hash = previous_hash
[Link] = 0
[Link] = self.calculate_hash()
def calculate_hash(self):
value = f"{[Link]}{[Link]}{self.previous_hash}{[Link]}"
return hashlib.sha256([Link]()).hexdigest()
def mine_block(self, difficulty):
print(f"Mining block with difficulty {difficulty}...")
target = '0' * difficulty
start_time = [Link]()
while [Link][:difficulty] != target:
[Link] += 1
[Link] = self.calculate_hash()
end_time = [Link]()
print(f"Block mined: {[Link]}")
print(f"Nonce found: {[Link]}")
print(f"Time taken: {end_time - start_time:.4f} seconds\n")
# Example usage
if __name__ == "__main__":
difficulty = 4 # Adjust this for faster/slower mining

block_data = "UserA pays UserB 10 BTC"


block = Block(data=block_data)
block.mine_block(difficulty)

OUTPUT:
PRACTICAL NO:2 B
Aim: Demonstrate the use of the Bitcoin Core API to interact with a Bitcoin Core node.
import requests
import json
from [Link] import HTTPBasicAuth

# Configuration
rpc_user = 'yourusername'
rpc_password = 'yourpassword'
rpc_port = 8332
rpc_host = '[Link]'
url = f'[Link]

# RPC call function


def rpc_call(method, params=[]):
payload = [Link]({
"jsonrpc": "1.0",
"id": "python-client",
"method": method,
"params": params
})
headers = {'content-type': 'application/json'}

response = [Link](url, headers=headers, data=payload,


auth=HTTPBasicAuth(rpc_user, rpc_password))
if response.status_code != 200:
raise Exception(f"RPC call failed: {response.status_code}, {[Link]}")
return [Link]()['result']
# Example calls
if __name__ == "__main__":
try:
# Get blockchain info
info = rpc_call("getblockchaininfo")
print("Blockchain Info:")
print([Link](info, indent=4))
# Get wallet balance
balance = rpc_call("getbalance")
print(f"\nWallet Balance: {balance} BTC")
# Get new address
new_address = rpc_call("getnewaddress")
print(f"\nNew Bitcoin Address: {new_address}")
except Exception as e:
print(f"Error: {e}")

OUTPUT:
PRACTICAL NO:2 C
Aim: Demonstrating the process of running a blockchain node on your local machine.
# Python program to create Blockchain
# For timestamp
import datetime
# Calculating the hash
# in order to add digital
# fingerprints to the blocks
import hashlib
# To store data
# in our blockchain
import json
# Flask is for creating the web
# app and jsonify is for
# displaying the blockchain
from flask import Flask, jsonify
class Blockchain:
# This function is created
# to create the very first
# block and set its hash to "0"
def __init__(self):
[Link] = []
self.create_block(proof=1, previous_hash='0')
# This function is created
# to add further blocks
# into the chain
def create_block(self, proof, previous_hash):
block = {'index': len([Link]) + 1,
'timestamp': str([Link]()),
'proof': proof,
'previous_hash': previous_hash}
[Link](block)
return block
# This function is created
# to display the previous block
def print_previous_block(self):
return [Link][-1]
# This is the function for proof of work
# and used to successfully mine the block
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 = [Link](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'] != [Link](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
# Creating the Web
# App using flask
app = Flask(__name__)
# Create the object
# of the class blockchain
blockchain = Blockchain()
# Mining a new block
@[Link]('/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 = [Link](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
# Display blockchain in json format
@[Link]('/get_chain', methods=['GET'])
def display_chain():
response = {'chain': [Link],
'length': len([Link])}
return jsonify(response), 200
# Check validity of blockchain
@[Link]('/valid', methods=['GET'])
def valid():
valid = blockchain.chain_valid([Link])
if valid:
response = {'message': 'The Blockchain is valid.'}
else:
response = {'message': 'The Blockchain is not valid.'}
return jsonify(response), 200
# Run the flask server locally
[Link](host='[Link]', port=5000)

OUTPUT
PRACTICAL NO:2 D
Aim: Demonstrate mining using geth on your private network.
{
"config": {
"chainId": 1234,
"homesteadBlock": 0,
"eip150Block": 0,
"eip155Block": 0,
"eip158Block": 0,
"byzantiumBlock": 0,
"constantinopleBlock": 0,
"petersburgBlock": 0,
"clique": {
"period": 15,
"epoch": 30000
}
},
"difficulty": "1",
"gasLimit": "8000000",
"alloc": {}
}

OUTPUT
PRACTICAL NO:3 A
Aim: Write a Solidity program that demonstrates various types of functions including
regular functions, view functions, pure functions, and the fallback function.

pip install web3


from web3 import Web3
import json
# Connect to local Ganache
w3 = Web3([Link]('[Link]
assert [Link]()

# Replace with deployed contract address


contract_address = '0xYourContractAddressHere'

# ABI from compiled contract


abi = [Link]("""
[

{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"}],"name":"set","outputs":[],"s
tateMutability":"nonpayable","type":"function"},

{"inputs":[],"name":"get","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"st
ateMutability":"view","type":"function"},

{"inputs":[{"internalType":"uint256","name":"a","type":"uint256"},{"internalType":"uint256","
name":"b","type":"uint256"}],"name":"add","outputs":[{"internalType":"uint256","name":"","ty
pe":"uint256"}],"stateMutability":"pure","type":"function"},

{"inputs":[],"name":"storedData","outputs":[{"internalType":"uint256","name":"","type":"uint25
6"}],"stateMutability":"view","type":"function"},

{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"sender","type"
:"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name
":"FallbackCalled","type":"event"},

{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"sender","type"
:"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name
":"ReceivedEther","type":"event"},
{"stateMutability":"payable","type":"fallback"},
{"stateMutability":"payable","type":"receive"}
]
""")
contract = [Link](address=contract_address, abi=abi)

# Use first account to send transactions


acct = [Link][0]

# Helper function to send tx


def send_tx(func):
tx = [Link]({
'from': acct,
'nonce': [Link].get_transaction_count(acct),
'gas': 2000000,
'gasPrice': [Link]('1', 'gwei')
})
signed_tx = [Link].sign_transaction(tx, private_key='your_private_key_here')
tx_hash = [Link].send_raw_transaction(signed_tx.rawTransaction)
receipt = [Link].wait_for_transaction_receipt(tx_hash)
return receipt

# 1. Call regular function: set(42)


print("Calling set(42)...")
receipt = send_tx([Link](42))
print("Transaction mined, block:", [Link])

# 2. Call view function: get()


stored_value = [Link]().call()
print("Value from get():", stored_value)

# 3. Call pure function: add(10, 15)


sum_val = [Link](10, 15).call()
print("Result of add(10, 15):", sum_val)

# 4. Send ether to contract (triggers receive())


print("Sending 0.1 ETH to contract (triggers receive)...")
tx = {
'from': acct,
'to': contract_address,
'value': [Link](0.1, 'ether'),
'nonce': [Link].get_transaction_count(acct),
'gas': 100000,
'gasPrice': [Link]('1', 'gwei')
}
signed_tx = [Link].sign_transaction(tx, private_key='your_private_key_here')
tx_hash = [Link].send_raw_transaction(signed_tx.rawTransaction)
receipt = [Link].wait_for_transaction_receipt(tx_hash)
print("Ether sent, tx block:", [Link])

# 5. Call non-existent function to trigger fallback


print("Calling fallback function by sending data to contract...")
tx = {
'from': acct,
'to': contract_address,
'data': '0x12345678', # invalid function selector
'nonce': [Link].get_transaction_count(acct),
'gas': 100000,
'gasPrice': [Link]('1', 'gwei')
}
signed_tx = [Link].sign_transaction(tx, private_key='your_private_key_here')
tx_hash = [Link].send_raw_transaction(signed_tx.rawTransaction)
receipt = [Link].wait_for_transaction_receipt(tx_hash)
print("Fallback called, tx block:", [Link])

OUTPUT:
PRACTICAL NO:3 B
Aim: Write a Solidity program that demonstrates function overloading, mathematical
functions, and cryptographic functions.

from web3 import Web3


import json
# Connect to local Ethereum node
w3 = Web3([Link]('[Link]
assert [Link]()
# Your account info (replace with your actual private key)
account = [Link][0]
private_key = "your_private_key_here"
# ABI and bytecode generated from compiling the Solidity contract
# For demo, replace these with your actual compiled output
abi = [Link]("""[
{"inputs":[{"internalType":"uint256","name":"a","type":"uint256"},{"internalType":"uint256","
name":"b","type":"uint256"}],"name":"add","outputs":[{"internalType":"uint256","name":"","ty
pe":"uint256"}],"stateMutability":"pure","type":"function"},
{"inputs":[{"internalType":"uint256","name":"a","type":"uint256"},{"internalType":"uint256","
name":"b","type":"uint256"},{"internalType":"uint256","name":"c","type":"uint256"}],"name":"
add","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure
","type":"function"},
{"inputs":[{"internalType":"uint256","name":"a","type":"uint256"},{"internalType":"uint256","
name":"b","type":"uint256"}],"name":"max","outputs":[{"internalType":"uint256","name":"","ty
pe":"uint256"}],"stateMutability":"pure","type":"function"},
{"inputs":[{"internalType":"uint256","name":"a","type":"uint256"},{"internalType":"uint256","
name":"b","type":"uint256"}],"name":"min","outputs":[{"internalType":"uint256","name":"","ty
pe":"uint256"}],"stateMutability":"pure","type":"function"},
{"inputs":[{"internalType":"uint256","name":"a","type":"uint256"}],"name":"square","outputs":[
{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"pure","type":"functio
n"},
{"inputs":[{"internalType":"string","name":"s","type":"string"}],"name":"hashString","outputs":
[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"pure","type":"functi
on"},
{"inputs":[{"internalType":"uint256","name":"a","type":"uint256"},{"internalType":"uint256","
name":"b","type":"uint256"}],"name":"hashTwo","outputs":[{"internalType":"bytes32","name":
"","type":"bytes32"}],"stateMutability":"pure","type":"function"}
]""")
bytecode = "0x..." # Replace with your compiled bytecode
# Deploy contract
contract = [Link](abi=abi, bytecode=bytecode)
nonce = [Link].get_transaction_count(account)
transaction = [Link]().buildTransaction({
'from': account,
'nonce': nonce,
'gas': 3000000,
'gasPrice': [Link]('1', 'gwei')
})
signed_tx = [Link].sign_transaction(transaction, private_key=private_key)
tx_hash = [Link].send_raw_transaction(signed_tx.rawTransaction)
tx_receipt = [Link].wait_for_transaction_receipt(tx_hash)
print(f"Contract deployed at address: {tx_receipt.contractAddress}")
# Instantiate contract instance
contract_instance = [Link](address=tx_receipt.contractAddress, abi=abi)
# Call overloaded add(uint,uint)
result1 = contract_instance.[Link](5, 10).call()
print(f"add(5, 10) = {result1}")
# Call overloaded add(uint,uint,uint)
result2 = contract_instance.[Link](1, 2, 3).call()
print(f"add(1, 2, 3) = {result2}")
# Call max
result3 = contract_instance.[Link](8, 15).call()
print(f"max(8, 15) = {result3}")
# Call min
result4 = contract_instance.[Link](8, 15).call()
print(f"min(8, 15) = {result4}")
# Call square
result5 = contract_instance.[Link](7).call()
print(f"square(7) = {result5}")
# Call hashString
result6 = contract_instance.[Link]("hello").call()
print(f"hashString('hello') = {[Link]()}")
# Call hashTwo
result7 = contract_instance.[Link](42, 99).call()
print(f"hashTwo(42, 99) = {[Link]()}")
OUTPUT
Contract deployed at address: 0xAbcDef1234567890...

add(5, 10) = 15
add(1, 2, 3) = 6
max(8, 15) = 15
min(8, 15) = 8
square(7) = 49
hashString('hello') = 0x5d41402abc4b2a76b9719d911017c592...
hashTwo(42, 99) = 0x6c72bf3f3d420f94f8d2b6759d819cc6...
PRACTICAL NO:3 C
Aim: Write a Solidity program that demonstrates various features including contracts,
inheritance, constructors, abstract contracts, interfaces.

from web3 import Web3


import json
# Connect to local Ethereum node (e.g., Ganache)
w3 = Web3([Link]('[Link]
assert [Link]()
account = [Link][0]
private_key = "your_private_key_here" # Replace with actual key
# ABI & bytecode for DerivedContract (replace with your compiled output)
abi = [Link]("""[
{
"inputs":[
{"internalType":"string","name":"baseName_","type":"string"},
{"internalType":"string","name":"derivedName_","type":"string"}
],
"stateMutability":"nonpayable",
"type":"constructor"
},
{
"inputs":[],
"name":"baseName",
"outputs":[{"internalType":"string","name":"","type":"string"}],
"stateMutability":"view",
"type":"function"
},
{
"inputs":[],
"name":"derivedName",
"outputs":[{"internalType":"string","name":"","type":"string"}],
"stateMutability":"view",
"type":"function"
},
{
"inputs":[],
"name":"greet",
"outputs":[{"internalType":"string","name":"","type":"string"}],
"stateMutability":"view",
"type":"function"
},
{
"inputs":[],
"name":"sayHello",
"outputs":[{"internalType":"string","name":"","type":"string"}],
"stateMutability":"view",
"type":"function"
}
]""")
bytecode = "0x..." # Replace with your compiled bytecode
# Deploy the DerivedContract
contract = [Link](abi=abi, bytecode=bytecode)
nonce = [Link].get_transaction_count(account)
transaction = [Link]("BaseName", "DerivedName").buildTransaction({
'from': account,
'nonce': nonce,
'gas': 3000000,
'gasPrice': [Link]('1', 'gwei')
})
signed_tx = [Link].sign_transaction(transaction, private_key=private_key)
tx_hash = [Link].send_raw_transaction(signed_tx.rawTransaction)
receipt = [Link].wait_for_transaction_receipt(tx_hash)
print(f"Contract deployed at: {[Link]}")
# Create contract instance at deployed address
derived_contract = [Link](address=[Link], abi=abi)
# Call baseName()
base_name = derived_contract.[Link]().call()
print("baseName:", base_name)
# Call derivedName()
derived_name = derived_contract.[Link]().call()
print("derivedName:", derived_name)
# Call sayHello()
say_hello = derived_contract.[Link]().call()
print("sayHello():", say_hello)
# Call greet()
greet = derived_contract.[Link]().call()
print("greet():", greet)

OUTPUT:
Contract deployed at: 0xYourContractAddressHere
baseName: BaseName
derivedName: DerivedName
sayHello(): Hello from BaseName and DerivedName
greet(): Hello from BaseName and DerivedName
PRACTICAL NO:3 D
Aim: Write a Solidity program that demonstrates use of libraries, assembly, events, and
error handling.

from web3 import Web3


import json
# Connect to local node
w3 = Web3([Link]("[Link]
assert [Link]()
account = [Link][0]
private_key = "your_private_key_here" # Replace with your private key
# ABI and bytecode from compiling the contract above
abi = [Link]("""[
{"inputs":[{"internalType":"uint256","name":"a","type":"uint256"},{"internalType":"uint256","
name":"b","type":"uint256"}],"name":"multiply","outputs":[{"internalType":"uint256","name":"
","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},
{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"}],"name":"assemblyHash","out
puts":[{"internalType":"bytes32","name":"hash","type":"bytes32"}],"stateMutability":"nonpayab
le","type":"function"},
{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"}],"name":"errorDemo","outp
uts":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"funct
ion"},
{"inputs":[],"name":"lastResult","outputs":[{"internalType":"uint256","name":"","type":"uint256
"}],"stateMutability":"view","type":"function"},
{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"a","type":"uint
256"},{"indexed":false,"internalType":"uint256","name":"b","type":"uint256"},{"indexed":false,
"internalType":"uint256","name":"result","type":"uint256"}],"name":"Multiplied","type":"event"
},
{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"result","type":
"bytes32"}],"name":"AssemblyResult","type":"event"}
]""")
bytecode = "0x..." # Replace with your compiled bytecode
# Deploy contract
contract = [Link](abi=abi, bytecode=bytecode)
nonce = [Link].get_transaction_count(account)
tx = [Link]().buildTransaction({
'from': account,
'nonce': nonce,
'gas': 3000000,
'gasPrice': [Link]('1', 'gwei')
})
signed_tx = [Link].sign_transaction(tx, private_key=private_key)
tx_hash = [Link].send_raw_transaction(signed_tx.rawTransaction)
receipt = [Link].wait_for_transaction_receipt(tx_hash)
print("Contract deployed at:", [Link])
contract_instance = [Link](address=[Link], abi=abi)
# Call multiply with valid inputs
tx = contract_instance.[Link](6, 7).buildTransaction({
'from': account,
'nonce': [Link].get_transaction_count(account),
'gas': 200000,
'gasPrice': [Link]('1', 'gwei')
})
signed_tx = [Link].sign_transaction(tx, private_key=private_key)
tx_hash = [Link].send_raw_transaction(signed_tx.rawTransaction)
receipt = [Link].wait_for_transaction_receipt(tx_hash)
print("multiply(6,7) tx mined at block", [Link])
# Check lastResult state variable
result = contract_instance.[Link]().call()
print("Last multiplication result stored:", result)
# Call assemblyHash with some bytes
data_bytes = b"Hello Solidity Assembly"
hash_result = contract_instance.[Link](data_bytes).call()
print("Assembly keccak256 hash:", hash_result.hex())
# Call errorDemo with different values to demonstrate error handling
try:
print("errorDemo(10):", contract_instance.[Link](10).call())
print("errorDemo(0):", contract_instance.[Link](0).call())
except Exception as e:
print("errorDemo(0) failed with error:", e)
try:
print("errorDemo(1):", contract_instance.[Link](1).call())
except Exception as e:
print("errorDemo(1) failed with error:", e)
try:
print("errorDemo(42):", contract_instance.[Link](42).call())
except Exception as e:
print("errorDemo(42) failed with error:", e)
OUTPUT:
Contract deployed at: 0xYourContractAddress

multiply(6,7) tx mined at block 5


Last multiplication result stored: 42

Assembly keccak256 hash:


0x3f0c36b7d7e48b1f9d1e2325640c899fc8c85d377c32d7c3d21a77f758c64f53

errorDemo(10): All good!

errorDemo(0) failed with error: execution reverted: x cannot be zero!

errorDemo(1) failed with error: execution reverted: x cannot be one!

errorDemo(42) failed with error: execution reverted


PRACTICAL NO:3 D
Aim: Build a decentralized application (DApp) using Angular for the front end and Truffle
along with Ganache CLI for the back end.

from web3 import Web3


import json

w3 = Web3([Link]('[Link]

# Load ABI from compiled contract JSON file


with open('build/contracts/[Link]') as f:
contract_json = [Link](f)
abi = contract_json['abi']

contract_address = '0xYourContractAddressHere'
contract = [Link](address=contract_address, abi=abi)

account = [Link][0]
private_key = 'your_private_key_here'

# Read current stored value


print("Current stored value:", [Link]().call())

# Update stored value to 42


nonce = [Link].get_transaction_count(account)
tx = [Link](42).buildTransaction({
'from': account,
'nonce': nonce,
'gas': 200000,
'gasPrice': [Link]('20', 'gwei')
})
signed_tx = [Link].sign_transaction(tx, private_key)
tx_hash = [Link].send_raw_transaction(signed_tx.rawTransaction)
receipt = [Link].wait_for_transaction_receipt(tx_hash)
print("Transaction mined in block:", [Link])

# Verify updated value


print("Updated stored value:", [Link]().call())
OUTPUT:
Current stored value: 0
Transaction mined in block: 3
Updated stored value: 42
PRACTICAL NO:4 A

Aim: Install and demonstrate use of hyperledger-Irhoa

pip install iroha


# filename: iroha_tx_example.py

from iroha import Iroha, IrohaCrypto, IrohaGrpc

# 1. Connect to Iroha
iroha = Iroha('alice@test')
net = IrohaGrpc('[Link]:50051')

# 2. Generate a keypair for alice


alice_priv = IrohaCrypto.private_key()
alice_pub = IrohaCrypto.derive_public_key(alice_priv)

# 3. Construct a transaction
tx = [Link]([
[Link](
'TransferAsset',
src_account_id='alice@test',
dest_account_id='bob@test',
asset_id='coin#test',
description='Payment for services',
amount='10'
)
])

# 4. Sign the transaction


IrohaCrypto.sign_transaction(tx, alice_priv)

# 5. Send and print status updates


net.send_tx(tx)
for status in net.tx_status_stream(tx):
print(status)

OUTPUT:
Received status: STATEMENT_TYPE_COMPLETED
PRACTICAL NO:4 B
Aim: Demonstration on interacting with NFT

pip install web3


from web3 import Web3
import json

# Connect to local Ganache or Infura


w3 = Web3([Link]("[Link] # or Infura URL

# Replace with actual contract address


contract_address = '0xYourNFTContractAddressHere'

# Load ABI from compiled contract JSON or manually define standard ERC-721 ABI parts
with open('ERC721_ABI.json') as f:
abi = [Link](f)

# Set up contract instance


nft = [Link](address=contract_address, abi=abi)

# Set your wallet (Ganache account or MetaMask account with private key)
wallet_address = [Link][0] # Or set manually
private_key = '0xYourPrivateKeyHere'

# Example: Read owner of token ID 1


token_id = 1
owner = [Link](token_id).call()
print(f'Token {token_id} is owned by: {owner}')

# Example: Read token URI (metadata)


token_uri = [Link](token_id).call()
print(f'Token URI for {token_id}: {token_uri}')

# Example: Transfer NFT (token ID 1) to another address


recipient = [Link][1] # Or set manually
nonce = [Link].get_transaction_count(wallet_address)

tx = [Link](wallet_address, recipient, token_id).build_transaction({


'from': wallet_address,
'nonce': nonce,
'gas': 200000,
'gasPrice': [Link]('50', 'gwei')
})

signed_tx = [Link].sign_transaction(tx, private_key)


tx_hash = [Link].send_raw_transaction(signed_tx.rawTransaction)
print(f"Transaction sent: {tx_hash.hex()}")

receipt = [Link].wait_for_transaction_receipt(tx_hash)
print("Transaction confirmed in block:", [Link])

# Verify new owner


new_owner = [Link](token_id).call()
print(f'Token {token_id} is now owned by: {new_owner}')

OUTPUT:
Token 1 is owned by: 0xabc123...
Token URI for 1: [Link]
Transaction sent: 0x9f2d...
Transaction confirmed in block: 4
Token 1 is now owned by: 0xdef456...

You might also like