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 :-

  1. Open Remix IDE.

  2. Create SimpleStorage.sol.

  3. Paste the code.

  4. Open Solidity Compiler and compile.

  5. Open Deploy & Run Transactions.

  6. Select Remix VM.

  7. Click Deploy.

  8. Expand the deployed contract.

  9. Enter Hello Blockchain in the store function and execute.

  10. Click retrieve to see Hello 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 :-

  1. Start the program.

  2. Import the hashlib and datetime modules.

  3. Create a class named Block.

  4. Define the block properties: index, timestamp, data, previous hash, and current hash.

  5. Create a function calculate_hash() to calculate the SHA-256 hash of the block.

  6. Create the first block called the Genesis Block.

  7. Assign the previous hash as "0".

  8. Calculate the hash using the block information.

  9. Display the block index, data, and generated hash.

  10. Stop the program.

PRACTICAL NO. 2

Aim :- Blockchain Implementation Using Python.

Algorithm :-

  1. Start the program.

  2. Import the hashlib and datetime modules.

  3. Create a Block class to represent a blockchain block.

  4. Initialize the block index, timestamp, transactions, previous hash, and nonce.

  5. Define calculate_hash() to generate the SHA-256 hash of the block data.

  6. Define a display() function to print the block information.

  7. Create the first block, called the Genesis Block, containing a transaction.

  8. Calculate and display the hash of the first block.

  9. Create a second block and assign the first block's hash as its previous hash.

  10. Display the details of both blocks.

  11. Stop the program.

PRACTICAL NO. 3

Aim :- Creating a Merkle Tree.

Algorithm :-

  1. Start the program.

  2. Import the hashlib module.

  3. Create a list of transactions.

  4. Define a function to calculate the SHA-256 hash of each transaction.

  5. Generate individual hashes for all transactions.

  6. Combine the hashes into pairs.

  7. Calculate a new hash for each pair.

  8. If the number of hashes is odd, duplicate the last hash.

  9. Repeat the process until only one hash remains.

  10. Display the final hash, called the Merkle Root.

  11. Stop the program.

PRACTICAL NO. 4

Aim :- Java Code to Implement Blockchain in a Merkle Tree.

Algorithm :-

  1. Start the program.

  2. Import the required Java packages.

  3. Create a class named Merkle_tree.

  4. Define the applysha256() method to calculate the SHA-256 hash.

  5. Create a list containing transactions TX1, TX2, TX3, TX4, and TX5.

  6. Generate the hash of every transaction.

  7. Define the getMerkleRoot() method.

  8. Combine adjacent transaction hashes in pairs.

  9. Calculate the hash of each combined pair.

  10. If a hash has no partner, duplicate it before combining.

  11. Continue generating new levels until only one hash remains.

  12. Display the final Merkle Root.

  13. Stop the program.

PRACTICAL NO. 5

Aim :- Creating a Cryptocurrency Wallet (Helium).

Algorithm :-

  1. Start the program.

  2. Import the Node.js crypto module.

  3. Create a class named HeliumWallet.

  4. Generate a random private key.

  5. Generate a demonstration public-key value using SHA-256 hashing.

  6. Generate a wallet identifier from the public-key value.

  7. Initialize the wallet with a sample balance.

  8. Create a function to display the wallet balance.

  9. Create a function to send tokens to another wallet identifier.

  10. Check whether the transfer amount is valid and sufficient balance is available.

  11. If valid, deduct the amount and save the simulated transaction.

  12. Display the wallet address, updated balance, and transaction history.

  13. Stop the program.

Note: This is a cryptocurrency wallet simulation, not an actual Helium wallet implementation.

PRACTICAL NO. 6

Aim :- Mining Using Java.

Algorithm :-

  1. Start the program.

  2. Import the required Java packages.

  3. Create a class named SimpleBlockchain.

  4. Define an inner class named Block.

  5. Initialize block properties such as index, timestamp, data, previous hash, and hash.

  6. Define a calculateHash() method using the SHA-256 algorithm.

  7. Create an ArrayList to store blockchain blocks.

  8. Create the first block, called the Genesis Block.

  9. Add the Genesis Block to the blockchain.

  10. Create additional blocks containing transaction information.

  11. Link each new block to the previous block using its hash.

  12. Display each block's index, timestamp, data, previous hash, and current hash.

  13. 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 :-

  1. Start the program.

  2. Import the required Python cryptography libraries.

  3. Generate a private key using the ECDSA algorithm.

  4. Generate the corresponding public key.

  5. Apply SHA-256 and RIPEMD-160 hashing to create the public-key hash.

  6. Generate an address payload from the public-key hash.

  7. Create sender and receiver wallets.

  8. Enter the transaction details, including sender, receiver, and amount.

  9. Generate the transaction hash using SHA-256.

  10. Sign the transaction hash using the sender's private key.

  11. Verify the signature using the sender's public key.

  12. Display the wallet identifiers, transaction hash, signature, and verification result.

  13. 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 :-

  1. Start the experiment.

  2. Open a web browser.

  3. Visit Remix IDE.

  4. Open the File Explorer.

  5. Create a new file named SimpleStorage.sol.

  6. Write or paste the Solidity smart contract code.

  7. Define a variable to store a message.

  8. Create a store() function to save the message.

  9. Create a retrieve() function to read the stored message.

  10. Open the Solidity Compiler.

  11. Select a compatible compiler version and compile the contract.

  12. Check that no compilation errors are displayed.

  13. Open the Deploy & Run Transactions section.

  14. Select the Remix VM environment.

  15. Deploy the SimpleStorage contract.

  16. Expand the deployed contract.

  17. Enter Hello Blockchain in the store() function.

  18. Execute the store() function.

  19. Click retrieve() to display the saved message.

  20. Repeat the process using another message, such as Ethereum Smart Contract.

  21. Verify that the updated message is displayed.

  22. 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