BT p
Practical No. | Practical Name | Date |
|---|---|---|
1 | Create a Blockchain | 11/07/2026 |
2 | Blockchain Implementation Using Python | 25/07/2026 |
3 | Creating a Merkle Tree | 01/08/2026 |
4 | Java Code to Implement Blockchain in a Merkle Tree | 08/08/2026 |
5 | Creating a Cryptocurrency Wallet (Helium) | 22/08/2026 |
6 | Mining Using Java | 12/09/2026 |
7 | Program Bitcoin Application | 12/09/2026 |
8 | Smart Contract on Remix IDE | 12/09/2026 |
PRACTICAL NO. 1
Aim :- Create a Blockchain.
Code :-
import hashlib
import datetime
class Block:
def __init__(self, index, data, previous_hash):
self.index = index
self.timestamp = str(datetime.datetime.now())
self.data = data
self.previous_hash = previous_hash
self.hash = self.calculate_hash()
def calculate_hash(self):
value = (str(self.index) + self.timestamp +
self.data + self.previous_hash)
return hashlib.sha256(value.encode()).hexdigest()
block1 = Block(1, "Genesis Block", "0")
print("Index:", block1.index)
print("Data:", block1.data)
print("Hash:", block1.hash)
PRACTICAL NO. 2
Aim :- Blockchain Implementation Using Python.
Code :-
import hashlib
import datetime
class Block:
def __init__(self, index, transactions, previous_hash):
self.index = index
self.timestamp = str(datetime.datetime.now())
self.transactions = transactions
self.previous_hash = previous_hash
self.nonce = 0
self.hash = self.calculate_hash()
def calculate_hash(self):
block_data = (
str(self.index) +
self.timestamp +
str(self.transactions) +
self.previous_hash +
str(self.nonce)
)
return hashlib.sha256(
block_data.encode()
).hexdigest()
def display(self):
print("Block Number:", self.index)
print("Timestamp:", self.timestamp)
print("Transactions:", self.transactions)
print("Previous Hash:", self.previous_hash)
print("Nonce:", self.nonce)
print("Current Hash:", self.hash)
print("-----------------------------")
# Genesis Block
block1 = Block(
1,
["Alice pays Bob 10 BTC"],
"0000000000000000"
)
block1.display()
# Second Block
block2 = Block(
2,
["Bob pays Charlie 5 BTC"],
block1.hash
)
block2.display()
PRACTICAL NO. 3
Aim :- Creating a Merkle Tree.
Code :-
import hashlib
def calculate_hash(data):
return hashlib.sha256(
data.encode()
).hexdigest()
def merkle_tree(transactions):
hashes = [calculate_hash(tx) for tx in transactions]
print("Transaction Hashes:")
for h in hashes:
print(h)
while len(hashes) > 1:
if len(hashes) % 2 != 0:
hashes.append(hashes[-1])
new_level = []
for i in range(0, len(hashes), 2):
combined = hashes[i] + hashes[i + 1]
new_hash = calculate_hash(combined)
new_level.append(new_hash)
hashes = new_level
return hashes[0]
transactions = ["TX1", "TX2", "TX3", "TX4"]
root = merkle_tree(transactions)
print("Merkle Root:", root)
PRACTICAL NO. 4
Aim :- Java Code to Implement Blockchain in a Merkle Tree.
Code :-
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
public class Merkle_tree {
public static String applysha256(String input) {
try {
MessageDigest digest =
MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(
input.getBytes("UTF-8"));
StringBuilder hexString =
new StringBuilder();
for (byte b : hash) {
String hex =
Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String getMerkleRoot(
List<String> transactions) {
List<String> tempList = new ArrayList<>();
System.out.println("Initial Transaction Hashes:");
for (String transaction : transactions) {
String hashedTransaction =
applysha256(transaction);
System.out.println(
transaction + " -> " + hashedTransaction);
tempList.add(hashedTransaction);
}
while (tempList.size() > 1) {
tempList = getNewLevel(tempList);
}
return tempList.get(0);
}
private static List<String> getNewLevel(
List<String> level) {
List<String> newLevel = new ArrayList<>();
System.out.println("\nNew Level:");
for (int i = 0; i < level.size(); i += 2) {
String left = level.get(i);
String right = (i + 1 < level.size())
? level.get(i + 1)
: left;
String combinedHash =
applysha256(left + right);
System.out.println(
left + " + " + right +
" -> " + combinedHash);
newLevel.add(combinedHash);
}
return newLevel;
}
public static void main(String[] args) {
List<String> transaction = new ArrayList<>();
transaction.add("TX1");
transaction.add("TX2");
transaction.add("TX3");
transaction.add("TX4");
transaction.add("TX5");
String merkleRoot =
getMerkleRoot(transaction);
System.out.println(
"\nMerkle Root: " + merkleRoot);
}
}
PRACTICAL NO. 5
Aim :- Creating a Cryptocurrency Wallet (Helium).
Code :-
const crypto = require('crypto');
class HeliumWallet {
constructor() {
this.privateKey = this.generatePrivateKey();
this.publicKey = this.generatePublicKey(this.privateKey);
this.address = this.generateAddress(this.publicKey);
this.transactions = [];
this.balance = 9000000000;
}
generatePrivateKey() {
return crypto.randomBytes(32).toString('hex');
}
generatePublicKey(privateKey) {
return crypto.createHash('sha256')
.update(privateKey)
.digest('hex');
}
generateAddress(publicKey) {
return publicKey.substring(0, 10);
}
sendTokens(receiverAddress, amount) {
if (amount > 0 && amount <= this.balance) {
this.balance -= amount;
this.transactions.push({
sender: this.address,
receiver: receiverAddress,
amount: amount
});
return true;
} else {
return false;
}
}
getBalance() {
return this.balance;
}
getTransactionHistory() {
return this.transactions;
}
}
// Example usage
const myWallet = new HeliumWallet();
console.log("Address:", myWallet.address);
console.log("Balance:", myWallet.getBalance());
const sendSuccess = myWallet.sendTokens(
"receiver_address",
900000002
);
if (sendSuccess) {
console.log("Tokens sent successfully.");
} else {
console.log("Insufficient balance.");
}
console.log("New Balance:", myWallet.getBalance());
console.log(
"Transaction History:",
myWallet.getTransactionHistory()
);
PRACTICAL NO. 6
Aim :- Mining Using Java.
Code :-
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class SimpleBlockchain {
static class Block {
int index;
long timestamp;
String data;
String previousHash;
String hash;
Block(int index, long timestamp,
String data, String previousHash) {
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.previousHash = previousHash;
this.hash = calculateHash();
}
private String calculateHash() {
try {
MessageDigest digest =
MessageDigest.getInstance("SHA-256");
String input = index +
Long.toString(timestamp) +
data + previousHash;
byte[] hashBytes = digest.digest(
input.getBytes("UTF-8"));
StringBuilder hexString =
new StringBuilder();
for (byte b : hashBytes) {
String hex =
Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args) {
List<Block> blockchain = new ArrayList<>();
Block genesisBlock = new Block(
0,
System.currentTimeMillis(),
"Genesis Block",
"0"
);
blockchain.add(genesisBlock);
for (int i = 1; i <= 2; i++) {
Block previousBlock =
blockchain.get(i - 1);
Block newBlock = new Block(
i,
System.currentTimeMillis(),
"Transactions " + i,
previousBlock.hash
);
blockchain.add(newBlock);
}
SimpleDateFormat dateFormat =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (Block block : blockchain) {
System.out.println(
"Block " + block.index);
System.out.println(
"Timestamp (Epoch): " + block.timestamp);
System.out.println(
"Timestamp (Date): " +
dateFormat.format(new Date(block.timestamp)));
System.out.println(
"Data: " + block.data);
System.out.println(
"Previous Hash: " + block.previousHash);
System.out.println(
"Hash: " + block.hash);
System.out.println();
}
}
}
PRACTICAL NO. 7
Aim :- Program Bitcoin Application.
Code :-
import hashlib
import ecdsa
import binascii
from Crypto.Hash import RIPEMD160
def generate_wallet():
private_key = ecdsa.SigningKey.generate(
curve=ecdsa.SECP256k1
)
public_key = private_key.get_verifying_key()
return private_key, public_key
def create_address(public_key):
sha256_pk = hashlib.sha256(
public_key.to_string()
).digest()
ripemd160 = RIPEMD160.new()
ripemd160.update(sha256_pk)
hashed_pk = ripemd160.digest()
versioned_pk = b'\x00' + hashed_pk
checksum = hashlib.sha256(
hashlib.sha256(versioned_pk).digest()
).digest()[:4]
address = versioned_pk + checksum
return binascii.hexlify(address).decode('utf-8')
def hash_transaction(message):
return hashlib.sha256(
message.encode('utf-8')
).hexdigest()
def sign_transaction(private_key, transaction_hash):
signature = private_key.sign(
transaction_hash.encode('utf-8')
)
return binascii.hexlify(signature).decode('utf-8')
def verify_transaction(public_key, signature, transaction_hash):
try:
public_key.verify(
binascii.unhexlify(signature),
transaction_hash.encode('utf-8')
)
return True
except ecdsa.BadSignatureError:
return False
def simulate_transaction():
print("Generating Wallets...")
sender_private_key, sender_public_key = generate_wallet()
receiver_private_key, receiver_public_key = generate_wallet()
sender_address = create_address(sender_public_key)
receiver_address = create_address(receiver_public_key)
print("Sender Address:", sender_address)
print("Receiver Address:", receiver_address)
transaction_data = (
f"Sender: {sender_address}, "
f"Receiver: {receiver_address}, "
f"Amount: 0.5 BTC"
)
transaction_hash = hash_transaction(transaction_data)
print("Transaction Data:", transaction_data)
print("Transaction Hash:", transaction_hash)
signature = sign_transaction(
sender_private_key,
transaction_hash
)
print("Signature:", signature)
is_valid = verify_transaction(
sender_public_key,
signature,
transaction_hash
)
print("Transaction Verification:", is_valid)
simulate_transaction()
package install:
pip install ecdsa pycryptodome
python practical7.py
PRACTICAL NO. 8
Aim :- Smart Contract on Remix IDE.
Code :-
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SimpleStorage {
string private storedData;
function store(string memory message) public {
storedData = message;
}
function retrieve() public view returns (string memory) {
return storedData;
}
}
Steps to Run :-
Open Remix IDE.
Create
SimpleStorage.sol.Paste the code.
Open Solidity Compiler and compile.
Open Deploy & Run Transactions.
Select Remix VM.
Click Deploy.
Expand the deployed contract.
Enter
Hello Blockchainin thestorefunction and execute.Click
retrieveto seeHello Blockchain.
Algorithms and Steps of all pract
BLOCKCHAIN TECHNOLOGY (BT) – ALGORITHMS FOR ALL 8 PRACTICALS
These algorithms are written in simple English, step by step, according to the codes provided earlier. You can directly copy and paste them into your practical journal.
PRACTICAL NO. 1
Aim :- Create a Blockchain.
Algorithm :-
Start the program.
Import the
hashlibanddatetimemodules.Create a class named
Block.Define the block properties: index, timestamp, data, previous hash, and current hash.
Create a function
calculate_hash()to calculate the SHA-256 hash of the block.Create the first block called the Genesis Block.
Assign the previous hash as
"0".Calculate the hash using the block information.
Display the block index, data, and generated hash.
Stop the program.
PRACTICAL NO. 2
Aim :- Blockchain Implementation Using Python.
Algorithm :-
Start the program.
Import the
hashlibanddatetimemodules.Create a
Blockclass to represent a blockchain block.Initialize the block index, timestamp, transactions, previous hash, and nonce.
Define
calculate_hash()to generate the SHA-256 hash of the block data.Define a
display()function to print the block information.Create the first block, called the Genesis Block, containing a transaction.
Calculate and display the hash of the first block.
Create a second block and assign the first block's hash as its previous hash.
Display the details of both blocks.
Stop the program.
PRACTICAL NO. 3
Aim :- Creating a Merkle Tree.
Algorithm :-
Start the program.
Import the
hashlibmodule.Create a list of transactions.
Define a function to calculate the SHA-256 hash of each transaction.
Generate individual hashes for all transactions.
Combine the hashes into pairs.
Calculate a new hash for each pair.
If the number of hashes is odd, duplicate the last hash.
Repeat the process until only one hash remains.
Display the final hash, called the Merkle Root.
Stop the program.
PRACTICAL NO. 4
Aim :- Java Code to Implement Blockchain in a Merkle Tree.
Algorithm :-
Start the program.
Import the required Java packages.
Create a class named
Merkle_tree.Define the
applysha256()method to calculate the SHA-256 hash.Create a list containing transactions
TX1,TX2,TX3,TX4, andTX5.Generate the hash of every transaction.
Define the
getMerkleRoot()method.Combine adjacent transaction hashes in pairs.
Calculate the hash of each combined pair.
If a hash has no partner, duplicate it before combining.
Continue generating new levels until only one hash remains.
Display the final Merkle Root.
Stop the program.
PRACTICAL NO. 5
Aim :- Creating a Cryptocurrency Wallet (Helium).
Algorithm :-
Start the program.
Import the Node.js
cryptomodule.Create a class named
HeliumWallet.Generate a random private key.
Generate a demonstration public-key value using SHA-256 hashing.
Generate a wallet identifier from the public-key value.
Initialize the wallet with a sample balance.
Create a function to display the wallet balance.
Create a function to send tokens to another wallet identifier.
Check whether the transfer amount is valid and sufficient balance is available.
If valid, deduct the amount and save the simulated transaction.
Display the wallet address, updated balance, and transaction history.
Stop the program.
Note: This is a cryptocurrency wallet simulation, not an actual Helium wallet implementation.
PRACTICAL NO. 6
Aim :- Mining Using Java.
Algorithm :-
Start the program.
Import the required Java packages.
Create a class named
SimpleBlockchain.Define an inner class named
Block.Initialize block properties such as index, timestamp, data, previous hash, and hash.
Define a
calculateHash()method using the SHA-256 algorithm.Create an ArrayList to store blockchain blocks.
Create the first block, called the Genesis Block.
Add the Genesis Block to the blockchain.
Create additional blocks containing transaction information.
Link each new block to the previous block using its hash.
Display each block's index, timestamp, data, previous hash, and current hash.
Stop the program.
Important: These steps match the Java code in your journal. That code demonstrates blockchain creation and hash linking, not actual Proof-of-Work mining. Actual mining requires repeatedly changing a nonce until the block hash satisfies the difficulty target.
PRACTICAL NO. 7
Aim :- Program Bitcoin Application.
Algorithm :-
Start the program.
Import the required Python cryptography libraries.
Generate a private key using the ECDSA algorithm.
Generate the corresponding public key.
Apply SHA-256 and RIPEMD-160 hashing to create the public-key hash.
Generate an address payload from the public-key hash.
Create sender and receiver wallets.
Enter the transaction details, including sender, receiver, and amount.
Generate the transaction hash using SHA-256.
Sign the transaction hash using the sender's private key.
Verify the signature using the sender's public key.
Display the wallet identifiers, transaction hash, signature, and verification result.
Stop the program.
Note: The provided journal code generates an address payload in hexadecimal form, not a standard displayed Bitcoin address. It also performs local transaction verification without broadcasting a real Bitcoin transaction.
PRACTICAL NO. 8
Aim :- Smart Contract on Remix IDE.
Algorithm / Steps :-
Start the experiment.
Open a web browser.
Visit Remix IDE.
Open the File Explorer.
Create a new file named
SimpleStorage.sol.Write or paste the Solidity smart contract code.
Define a variable to store a message.
Create a
store()function to save the message.Create a
retrieve()function to read the stored message.Open the Solidity Compiler.
Select a compatible compiler version and compile the contract.
Check that no compilation errors are displayed.
Open the Deploy & Run Transactions section.
Select the Remix VM environment.
Deploy the
SimpleStoragecontract.Expand the deployed contract.
Enter
Hello Blockchainin thestore()function.Execute the
store()function.Click
retrieve()to display the saved message.Repeat the process using another message, such as
Ethereum Smart Contract.Verify that the updated message is displayed.
Stop the experiment.
These are the algorithms for all eight BT practicals, corresponding to the code provided in the previous messages.
For your journal, you can arrange each practical as:
PRACTICAL NO. → AIM → THEORY → ALGORITHM → CODE → OUTPUT
This keeps the journal clean and suitable for practical exam preparation.
Comments
Post a Comment