0% found this document useful (0 votes)
20 views117 pages

Blockchain Journal

The document certifies that Miss Heetika Mahesh Vaity has completed a series of lab assignments in Blockchain Lab at Vivekanand Education Society's Institute of Technology during the academic year 2024-2025. The assignments include implementations of cryptographic techniques such as Caesar Cipher, RSA, SHA-256, and Merkle Tree, along with their theoretical explanations and Python code examples. The document also contains details about the course structure, grading, and student information.

Uploaded by

Riya singh
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)
20 views117 pages

Blockchain Journal

The document certifies that Miss Heetika Mahesh Vaity has completed a series of lab assignments in Blockchain Lab at Vivekanand Education Society's Institute of Technology during the academic year 2024-2025. The assignments include implementations of cryptographic techniques such as Caesar Cipher, RSA, SHA-256, and Merkle Tree, along with their theoretical explanations and Python code examples. The document also contains details about the course structure, grading, and student information.

Uploaded by

Riya singh
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/ 117

Roll No. 57 Exam Seat No.

VIVEKANANDEDUCATION SOCIETY’S
INSTITUTE OF TECHNOLOGY

Hashu Advani Memorial Complex, Collector’s Colony, R. C.


Marg,Chembur, Mumbai – 400074. Contact No. 02261532532

Since 1962

CERTIFICATE

Certified that Miss Heetika Mahesh Vaity Of SY MCA/ Division-B has


satisfactorily completed a course of the necessary experiments in Blockchain Lab
under my supervisionin the Institute of Technology in the academic year 2024- 2025.

Principal Head of Department

Lab In-charge Subject Teacher


V.E.S. Institute of Technology, Collector Colony, Chembur,
Mumbai, Maharashtra 400047
Department of M.C.A

INDEX

S. No. Contents Date Date Marks Faculty


Of Of
Preparation Submission
Sign
1. Implement Caesar Cipher 07/08/24 14/08/24
(Symmetric Encryption) and show the Encryption and
the Decryption Process.
2. Implement RSA and show the 07/08/24 14/08/24
Encryption as well as Decryption process.

3. To implement SHA 256 Algorithm. 14/08/24 21/08/24

4. Implementation of Binary Tree 14/08/24 21/08/24

5. Implement the creation of Bitcoin 21/08/24 28/08/24


Block (Genesis Block)
6. Install Ganache(Personal block 28/08/24 13/09/24
chain) and MetaMask (Show the installation Steps) .
Compile and deploy an election smart contract in the
personal blockchain using injected web 3
environment(MetaMask wallet) .Use Remix
online ide to compile and deploy the smart contract.
7. Simple Experiments using Solidity 13/09/24 20/09/24
Program Constructs (if-then, while etc...)

8. Execution of smart contract using 13/09/24 20/09/24


truffle framework.
9. Creation of Dapp in Ethereum 03/10/24 10/10/24

10. Mini Project: Implementation of Blockchain 03/10/24 10/10/24

Final Grade Instructor Signature


Name of Student : Heetika Mahesh Vaity

Roll No : 57 LAB Assignment Number : 1

Title of LAB Assignment : IMPLEMENT CAESAR CIPHER (SYMMETRIC


ENCRYPTION) AND SHOW THE ENCRYPTION AS WELL AS DECRYPTION
PROCESS.

DOP : 07/08/2024 DOS: 14/08/2024

CO MAPPED : PO MAPPED: FACULTY MARKS:

CO1 PO2, PO3, SIGNATURE:


PSO1
Heetika Vaity Blockchain Lab SYMCA- 57/B

AIM: IMPLEMENT CAESAR CIPHER (SYMMETRIC ENCRYPTION) AND


SHOW THE ENCRYPTION AS WELL AS DECRYPTION PROCESS.

THEORY:

WHAT IS CRYPTOGRAPHY?
Cryptography is a method of protecting information and communications through the use
of codes, so that only those for whom the information is intended can read and process it.
In computer science, cryptography refers to secure information and communication
techniques derived from mathematical concepts and a set of rule-based calculations called
algorithms, to transform messages in ways that are hard to decipher. These deterministic
algorithms are used for cryptographic key generation, digital signing, verification to protect
data privacy, web browsing on the internet and confidential communications such as credit
card transactions and email.

WHAT IS SYMMETRIC ENCRYPTION?


Symmetric encryption uses a single key to encrypt and decrypt. If you encrypt a zip file,
then decrypt with the same key, you are using symmetric encryption. Symmetric encryption
is also called “secret key” encryption because the key must be kept secret from third
parties.

CAESAR CIPHER
The Caesar Cipher technique is one of the earliest and simplest methods of encryption
technique. It’s simply a type of substitution cipher, i.e., each letter of a given text is replaced
by a letter with a fixed number of positions down the alphabet. For example with a shift of
1, A would be replaced by B, B would become C, and so on. The method is apparently
named after Julius Caesar, who apparently used it to communicate with his officials.

CODE:

2
Heetika Vaity Blockchain Lab SYMCA- 57/B

def caesar_encrypt(realText, step):


outText = []
cryptText = []
uppercase = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
lowercase = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
for eachLetter in realText:
if eachLetter in uppercase:
index = uppercase.index(eachLetter)
crypting = (index + step) % 26
cryptText.append(crypting)
newLetter = uppercase[crypting]
outText.append(newLetter)

elif eachLetter in lowercase:


index = lowercase.index(eachLetter)
crypting = (index + step) % 26
cryptText.append(crypting)
newLetter = lowercase[crypting]
outText.append(newLetter)

return outText

encode = caesar_encrypt('abcDEF', 2)
print(encode)

decode = caesar_encrypt(caesar_encrypt('abcDEF',2),26-2)
print(decode)

OUTPUT:

CONCLUSION:

From this practical, I have learned and implemented the caesar cipher in the python.

3
Name of Student : Heetika Mahesh Vaity

Roll No : 57 LAB Assignment Number : 2

Title of LAB Assignment : IMPLEMENT RSA AND SHOW THE


ENCRYPTION AS WELL AS DECRYPTION PROCESS.

DOP : 07/08/2024 DOS: 14/08/2024

CO MAPPED : PO MAPPED: FACULTY MARKS:

CO2, CO3 PO2, PO3, SIGNATURE:


PSO1
Heetika Vaity Blockchain Lab SYMCA- 57/B

AIM: IMPLEMENT RSA AND SHOW THE ENCRYPTION AS WELL AS


DECRYPTION PROCESS.

THEORY:

RSA algorithm is a public key encryption technique and is considered as the most secure
way of encryption. It was invented by Rivest, Shamir and Adleman in year 1978 and hence
named RSA algorithm.

Algorithm:
The RSA algorithm holds the following features −

● RSA algorithm is a popular exponentiation in a finite field over integers including


prime numbers.
● The integers used by this method are sufficiently large making it difficult to solve.
● There are two sets of keys in this algorithm: private key and public key.

You will have to go through the following steps to work on RSA algorithm −

Step 1: Generate the RSA modulus


The initial procedure begins with selection of two prime numbers namely p and q, and then
calculating their product n, as shown −
n=pxq

Here, let n be the specified large number.

2
Heetika Vaity Blockchain Lab SYMCA- 57/B

Step 2: Derived Number (e)


Choose a number e less than n, such that n is relatively prime to (p - 1) x (q -1). It means
that e and (p - 1) x (q - 1) have no common factor except 1. Choose "e" such that 1<e < φ
(n), e is prime to φ (n),
gcd (e,d(n)) =1

Step 3: Public key


The specified pair of numbers n and e forms the RSA public key and it is made public.

Step 4: Private Key


Private Key d is calculated from the numbers p, q and e. The mathematical relationship
between the numbers is as follows −
De mod {(p - 1) x (q - 1)} = 1
The above formula is the basic formula for Extended Euclidean Algorithm, which takes p
and q as the input parameters.

Encryption Formula
Consider a sender who sends the plain text message to someone whose public key is (n,e).
To encrypt the plain text message m in the given scenario, use the following syntax
C = me mod n

Decryption Formula
The decryption process is very straightforward and includes analytics for calculation in a
systematic approach. Considering receiver C has the private key d, the result modulus will
be calculated as −
Plaintext, m = cd mod n

3
Heetika Vaity Blockchain Lab SYMCA- 57/B

CODE:

import math

# Function to compute GCD


def gcd(a, h):
while h != 0:
a, h = h, a % h
return a

# Function to compute modular inverse using Extended Euclidean Algorithm


def mod_inverse(e, phi):
original_phi = phi
x0, x1 = 0, 1
if phi == 1:
return 0
while e > 1:
# q is the quotient
q = e // phi
t = phi
# Update phi and e
phi = e % phi
e=t
t = x0
x0 = x1 - q * x0
x1 = t
if x1 < 0:
x1 += original_phi
return x1

# RSA Key Setup


p = 61 # Changed to larger primes for practical RSA example
q = 53 # Changed to larger primes for practical RSA example
n=p*q
phi = (p - 1) * (q - 1)
e = 17 # Common choice for e that is co-prime with phi

# Ensure e is co-prime with phi


while gcd(e, phi) != 1:
e += 1

# Compute private key d

4
Heetika Vaity Blockchain Lab SYMCA- 57/B

d = mod_inverse(e, phi)

if d is None:
raise ValueError("Modular inverse does not exist. Choose different values for e.")

# Message to be encrypted (must be less than n)


msg = 57
print("Message data = ", msg)

# Encryption
c = pow(msg, e, n)
print(f"Encrypted data = {c}")

# Decryption
m = pow(c, d, n)
print(f"Original Message Sent = {m}")

OUTPUT:

CONCLUSION:
From this practical, I have understood how to implement the RSA algorithm in python.

5
Name of Student : Heetika Mahesh Vaity

Roll No : 57 LAB Assignment Number : 3

Title of LAB Assignment : To implement SHA 256 Algorithm.

DOP : 14/08/2024 DOS: 21/08/2024

CO MAPPED : PO MAPPED: FACULTY MARKS:

CO2, CO3 PO2, PO3, SIGNATURE:


PSO1
Heetika Vaity Blockchain Lab SYMCA- 57/B

AIM: TO IMPLEMENT SHA 256 ALGORITHM

THEORY:

Introduction to Hashing

Hashing is the process of converting raw information into a scrambled format such that it cannot be
reversed to its original form. This is achieved through a function known as the hash function, which
performs mathematical operations on the plaintext input. The output of this function is called the
hash value or digest.

Characteristics of Hash Functions

● Irreversibility: Hash functions are designed to be irreversible, meaning that the hash digest
should not allow the original plaintext to be reconstructed.
● Consistency: The same input will always produce the same hash value, regardless of how
many times the function is applied.

Applications of Hashing

1. Password Hashing:
○ Websites convert user passwords into hash values before storing them on servers.
During login, the server recalculates the hash of the provided password and
compares it with the stored hash for validation.
2. Integrity Verification:
○ When uploading files to a website, a hash of the file is often provided. Users can
recalculate the hash of the downloaded file and compare it with the provided hash to
ensure the file’s integrity.

Hash Functions Overview

Hash functions transform data into a fixed-size hash value. The process involves breaking the data
into blocks and converting them into a shorter, fixed-length key or value. The term “hash” refers to
both the hash function and the hash value.

Purpose and Use:

● Hash functions were initially created to compress data, reducing memory requirements for
large files. The resulting hashes are stored in hash tables, which facilitate quick data
lookups.
● Hash functions ensure that each input generates a unique identifier, and any duplication of
hash outputs (collisions) indicates a potential issue.

2
Heetika Vaity Blockchain Lab SYMCA- 57/B

SHA-256 (Secure Hash Algorithm 256-bit)

Overview:

● SHA-256 is part of the SHA-2 family of hash algorithms. It was introduced in 2001 by the
NSA and NIST as an improvement over the SHA-1 family, which was becoming vulnerable to
brute-force attacks.
● The "256" in SHA-256 refers to the length of the final hash digest: 256 bits (32 bytes).

Significance:

● SHA-256 generates a unique, fixed-size 256-bit hash. It is a one-way function, which means
the original data cannot be derived from the hash.

Applications:

● SHA-256 is widely used for data integrity checks, authentication, anti-tamper measures,
digital signatures, and in blockchain technologies.

Limitations:

● With advancements in hardware, decryption of SHA-256 has become more feasible,


reducing its effectiveness for password protection. It is still reliable for data integrity
verification but not recommended for secure password storage.

Hashlib Module in Python

The hashlib module in Python provides a common interface to various secure hash and message
digest algorithms. Supported algorithms include:

● SHA1: 160-bit hash function, similar to MD5.


● SHA224: A truncated version of SHA-256 with a 32-bit internal block size.
● SHA256: The 32-bit internal block size version of SHA-2.
● SHA384: A truncated version of SHA-512 with a 32-bit internal block size.
● SHA512: A 64-bit internal block size version.
● MD5: A widely used hash function with known vulnerabilities.

Functions in hashlib:

● encode(): Converts a string into bytes suitable for hashing.


● hexdigest(): Returns the hash value in hexadecimal format.
● digest_size(): Returns the size of the hash digest.
● block_size(): Returns the block size used by the hash function.

3
Heetika Vaity Blockchain Lab SYMCA- 57/B

CODE:

import hashlib

string="Heetika Vaity"

encoded=string.encode()
result = hashlib.sha256(encoded)

print("String : ", end ="")


print(string)

print("Hash Value : ", end ="")


print(result)

print("Hexadecimal equivalent: ",result.hexdigest())

print("Digest Size : ", end ="")


print(result.digest_size)

print("Block Size : ", end ="")


print(result.block_size)

OUTPUT:

CONCLUSION:

From this practical, I have learned & implemented sha-256 hashing using hashlib in python.

4
Name of Student : Heetika Mahesh Vaity

Roll No : 57 LAB Assignment Number : 4

Title of LAB Assignment : Implementation of MerkleTree

DOP : 14/08/2024 DOS: 21/08/2024

CO MAPPED : PO MAPPED: FACULTY MARKS:

CO2, CO3 PO2, PO3, SIGNATURE:


PSO1
Heetika Vaity Blockchain Lab SYMCA- 57/B

AIM: IMPLEMENTATION OF MERKLE TREE

THEORY:

Introduction to Merkle Trees

A Merkle tree, also known as a hash tree, is a specialized data structure used for data
verification and synchronization. It organizes data in a hierarchical manner where each
non-leaf node is a hash of its child nodes. All leaf nodes are positioned at the same depth
and are as far left as possible. This structure ensures data integrity and is particularly
useful for efficient data management and verification.

How Merkle Trees Work

Structure:

● Leaf Nodes: Represent the hash values of the data blocks or transactions. They are
the bottom-most level of the tree.
● Non-Leaf Nodes: Each non-leaf node is a hash of its two child nodes. The hash of a
non-leaf node is computed by combining the hashes of its children.
● Root Node: The topmost node, known as the root hash or Merkle root, represents a
hash of the entire tree. It provides a single fingerprint for the entire dataset.

Process:

1. Hashing Data Blocks: Start by hashing the individual data blocks. These hashes
form the leaf nodes of the tree.
2. Building the Tree: Pair up leaf nodes and compute the hash of each pair to form the
next level of the tree. Repeat this process until only one hash remains, which
becomes the root hash.
3. Root Hash: The root hash serves as a compact representation of all the data in the
tree. It enables efficient verification of data integrity.

2
Heetika Vaity Blockchain Lab SYMCA- 57/B

Hash Functions

A hash function maps an input (or "message") to a fixed-size output, known as a hash or
digest. The primary characteristics of a hash function include:

● Uniqueness: Each unique input produces a unique hash output, allowing for data
fingerprinting.
● Deterministic: The same input will always produce the same hash output.
● Fast Computation: The hash function should quickly compute the hash value for
any given input.
● Collision Resistance: It should be computationally infeasible to find two different
inputs that produce the same hash output.

Hash functions are crucial in Merkle trees for ensuring that small changes in data are
reflected in the hash values, making it easier to detect discrepancies.

3
Heetika Vaity Blockchain Lab SYMCA- 57/B

Binary Merkle Tree

In a binary Merkle tree, each non-leaf node has exactly two children. This binary structure
is commonly used because it simplifies the computation and verification of hash values.

Example Structure:

1. Leaf Nodes: Hash values of individual data blocks.


2. Intermediate Nodes: Hashes of pairs of child nodes.
3. Root Node: Hash of all data blocks, providing a single hash value representing the
entire tree.

Advantages:

● Efficient Verification: To verify the integrity of a data block, you only need to
traverse a small part of the tree, rather than checking the entire dataset.
● Change Detection: Small changes in the data will propagate up the tree, altering the
root hash. This allows for quick detection of data changes or inconsistencies.

Applications of Merkle Trees

1. Distributed Systems:
○ Merkle trees are used in distributed systems to ensure that the same data
exists across multiple locations. They help in identifying discrepancies
between replicas of data.
2. Database Consistency:
○ Systems like Apache Cassandra use Merkle trees to detect inconsistencies
between database replicas. By comparing Merkle roots, the system can
efficiently identify which parts of the data are out of sync.
3. Blockchain and Cryptocurrencies:
○ Merkle trees are integral to blockchain technology. They are used in
cryptocurrencies like Bitcoin to ensure data integrity and facilitate efficient
verification of transactions. Each block in the blockchain includes a Merkle
root, which represents all the transactions within the block.

CODE:

4
Heetika Vaity Blockchain Lab SYMCA- 57/B

class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data

# Insert Node
def insert(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data

# Print the Tree


def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()

# Preorder traversal
# Root -> Left ->Right
def PreorderTraversal(self, root):
res = []
if root:
res.append(root.data)
res = res + self.PreorderTraversal(root.left)
res = res + self.PreorderTraversal(root.right)
return res

# Postorder traversal
# Left ->Right -> Root
def PostorderTraversal(self, root):
res = []
if root:
res = self.PostorderTraversal(root.left)
res = res + self.PostorderTraversal(root.right)

5
Heetika Vaity Blockchain Lab SYMCA- 57/B

res.append(root.data)
return res

# Inorder traversal of a binary tree


def inorder(temp):
if(not temp):
return
inorder(temp.left)
print(temp.data, end = " ")
inorder(temp.right)

# function to delete the given deepest node (d_node) in binary tree


def deleteDeepest(root,d_node):
q = []
q.append(root)
while(len(q)):
temp = q.pop(0)
if temp is d_node:
temp = None
return
if temp.right:
if temp.right is d_node:
temp.right = None
return
else:
q.append(temp.right)
if temp.left:
if temp.left is d_node:
temp.left = None
return
else:
q.append(temp.left)

# function to delete element in binary tree


def deletion(root, key):
if root == None :
return None
if root.left == None and root.right == None:
if root.key == key :
return None
else :
return root
key_node = None
q = []
q.append(root)
temp = None
while(len(q)):
temp = q.pop(0)
if temp.data == key:

6
Heetika Vaity Blockchain Lab SYMCA- 57/B

key_node = temp
if temp.left:
q.append(temp.left)
if temp.right:
q.append(temp.right)
if key_node :
x = temp.data
deleteDeepest(root,temp)
key_node.data = x
return root

print("Binary Tree :")


root = Node(27)
root.insert(10)
root.insert(20)
root.insert(30)
root.insert(40)
root.insert(50)
root.insert(60)
root.PrintTree()

print("Inorder Traversal before the deletion:")


inorder(root)
key = 14
root = deletion(root, key)
print()
print("Inorder Traversal after the deletion;")
inorder(root)
print("\nPreorder Traversal :",root.PreorderTraversal(root))
print("Postorder Traversal :",root.PostorderTraversal(root))

OUTPUT:

7
Heetika Vaity Blockchain Lab SYMCA- 57/B

CONCLUSION:
From this practical, I have successfully learned & implemented the merkle tree in python.

8
Name of Student : Heetika Mahesh Vaity

Roll No : 57 LAB Assignment Number : 5

Title of LAB Assignment : Implement the creation of Bitcoin Block


(Genesis Block)

DOP : 21/08/2024 DOS: 28/08/2024

CO MAPPED : PO MAPPED: FACULTY MARKS:

CO2, CO3 PO2, PO3, SIGNATURE:


PSO1
Heetika Vaity Blockchain Lab SYMCA- 57/B

AIM: Install Geth Ethereum Node (Show installation steps also). Create a
Genesis block and a private chain. Use geth commands to create user
accounts, mine, transact etc.

THEORY:

What is a node?

● A node is generally a point of intersection or connection in a telecommunications


network. A node may also mean any system or physical device that is connected to a
network and can execute certain functions like creating, receiving or sending
information via a communication channel. The explanation of a node varies
depending on the protocol layer being referred to.
● For example, a basic resident network may consist of a file server, two laptops and a
fax machine. In this case, the network has four nodes, each equipped with a MAC
address to uniquely identify them.
● The most popular usage of the term “node” is seen in the blockchain space. In this
guide, we will explain what nodes are in more detail, including the different types of
blockchain nodes being used today.
● In Ethereum, a user can run three different kinds of nodes: light, full and archive.
Their differences lie in how fast they can synchronize with the entire network.
● There are many ways to run your own Ethereum node, but some popular hardware
that can work on the network are DAppNode and Avado. Ethereum nodes have
almost the same requirements as Bitcoin nodes, only that the former requires less
computing power.
● Note that before you run an Ethereum node, it is advisable to check your bandwidth
limitations first.
● Ethereum nodes are essential in keeping its blockchain network secure and reliable,
as well as transparent. In fact, anyone can view the nodes and their performances on
the network via Etherscan’s node tracker.
● In order to receive block rewards, you would have to run an Ethereum staking node.

Geth:

● Geth(Go Ethereum) is a command line interface for running Ethereum node


implemented in Go Language. Using Geth you can join Ethereum network, transfer
ether between accounts or even mine ethers.

2
Heetika Vaity Blockchain Lab SYMCA- 57/B

Genesis Block:

● A genesis block refers to the first block in a blockchain and is usually hardcoded into
its application’s software. A blockchain has multiple “blocks” (containing validated
transactions and recorded activity data) linked together by a metaphorical chain.
● Each “block” of a crypto asset contains referential data for the previous one and
derives its value/legitimacy from its predecessor.The genesis block, thus, refers to
the first block (Block 0 or Block 1) of a new blockchain, to which all other
subsequent blocks are attached.
● A genesis block is unique as it is the only block in a blockchain that does not
reference a predecessor block, and in almost all cases, the first mining rewards it
unlocks are unspendable.
● Genesis blocks have special significance, as they form the very foundation of a
blockchain and often contain interesting stories or hidden meanings. For instance,
Bitcoin’s genesis block contains the now-famous message ” The Times 03/Jan/2009
Chancellor on brink of second bailout for banks”— a reference to the deteriorating
financial conditions of that time and the rationale for creating cryptocurrencies like
Bitcoin and Ethereum. Bitcoin’s genesis block in 2009 contained 50 BTC.
● The Bitcoin genesis block is very intriguing not just for its included message, but
also due to the fact that the next block was timestamped nearly six days later (the
average time is 10 minutes).

Commands used in this practical:

● geth --datadir chaindata init genesis.json: Initializes geth into chaindata.


● geth --datadir=./chaindata/: Used to run geth.
● geth attach ipc:\\.\pipe\geth.ipc: IPC to interact with geth.
● personal.newAccount(): Create a new account.
● eth.accounts: Get information about all the accounts present.
● eth.coinbase: Get information about the coinbase account.
● eth.getBalance(eth.accounts[0]): Get the current balance of an account.
● miner.start() / miner.stop(): Start/Stop the mining process.
● eth.blockNumber: Get the blockNumber.
● personal.unlockAccount(eth.accounts[0]): Unlock the coinbase account for
transaction.
● eth.sendTransaction({from: eth.coinbase, to: eth.accounts[1], value: web3.toWei(10,
“ether”)}): Command for transaction. Enter the account number to which we want to
transfer the ethers to.
● eth.getTransaction(txHash): get the information about the transaction. Enter the
hash instead of “txHash”.

3
Heetika Vaity Blockchain Lab SYMCA- 57/B

● web3.fromWei(eth.getBalance(eth.accounts[1]), “ether”): get balance of the second


account in ethers.
● eth.getBlock(“latest”): Get information about the latest block.
● eth.getBlock(388): Get information about a specific block.

STEPS/OUTPUT:

Steps to Install Go-Ethereum:

1. Visit the Go Ethereum website and install Geth.

2. Visit here: https://geth.ethereum.org/downloads/

Download the latest release of Geth for Windows, make sure you download the 64-bit
version.

4
Heetika Vaity Blockchain Lab SYMCA- 57/B

5
Heetika Vaity Blockchain Lab SYMCA- 57/B

Establishing Our Own Private Ethereum Network

● Create a new folder on your desktop called “Private-chain”


● Open command prompt in this folder and create a data directory folder for our
chaindata by typing “mkdir chaindata”
● Next, we need to create and save our genesis.json block in our Private-chain folder,
as the genesis block will be used to initialize our private network and store data in
the data directory folder “chaindata”

Open up notepad, copy & paste the code below into a new file called “genesis.json” and save
this file in our Private-chain folder.

"config": {

"chainId": 4777,

"homesteadBlock": 0,

"eip150Block": 0,

"eip155Block": 0,

"eip158Block": 0

},

"alloc" : {},

"difficulty" : "0x400",

"extraData" : "",

"gasLimit" : "0x7A1200",

"parentHash" :

"0x0000000000000000000000000000000000000000000000000000000000000000",

"timestamp" : "0x00"

6
Heetika Vaity Blockchain Lab SYMCA- 57/B

Now, we have to initialize our Ethereum Node. For that, open the command
prompt and change your current directory to the Private Chain folder.

A) Intialize geth into chaindata

Command: geth --datadir chaindata init genesis.json

B) run geth:

Command: geth –datadir=./chaindata/

C) IPC to interact with Geth:

Command: geth attach ipc:\\.\pipe\geth.ipc

7
Heetika Vaity Blockchain Lab SYMCA- 57/B

D) CREATE NEW ACCOUNT:

Command: personal.newAccount()

E) SHOW ALL ACCOUNTS

Command: eth.accounts

//hexadecimal address, will show the accounts

F) CREATING SECOND ACCOUNT:

G) CHECK COINBASE ACCOUNT:

Command: eth.coinbase

//first account is called as the coinbase account

H) CHECKING BALANCE:

Command: eth.getBalance(eth.accounts[0])

8
Heetika Vaity Blockchain Lab SYMCA- 57/B

I) MINING:

Command:

miner.start()

miner.stop()

//After a transaction, stop to get some amount in other accounts

eth.blockNumber

J) Unlock account before transaction:

Command: personal.unlockAccount(eth.accounts[0])

K) CHECKING BALANCE OF SECOND ACCOUNT:

Command: eth.getBalance(eth.accounts[1])

L) TRANSACTION FROM ACC 1 TO ACC 2:

Command: eth.sendTransaction({from: eth.coinbase, to: eth.accounts[1], value:


web3.toWei(10, "ether")})

9
Heetika Vaity Blockchain Lab SYMCA- 57/B

M) MINING:

miner.start()

miner.stop()

N) CHECK BALANCE:

Command:

eth.getBalance(eth.accounts[0])

eth.getBalance(eth.accounts[1])

O) GET TRANSACTION:

Command:
eth.getTransaction(“;0x2a7c7851424ca4ed55667ea09a17ff44d73ec53658f759fdb852db9
0100260c4”)

10
Heetika Vaity Blockchain Lab SYMCA- 57/B

P) CHECK BALANCE IN ETHERS:

Command:

web3.fromWei(eth.getBalance(eth.accounts[0]), “ether”)

web3.fromWei(eth.getBalance(eth.accounts[1]), “ether”)

Q) GET LATEST BLOCK:

Command: eth.getBlock(“latest”)

R) GET SPECIFIC BLOCK INFO:

Command: eth.getBlock(100)

11
Heetika Vaity Blockchain Lab SYMCA- 57/B

CONCLUSION:

We have successfully learnt how to install Geth, create a genesis block,


private chain and commands to create user accounts, mine and transact
ethers among accounts.

12
Name of Student : Heetika Mahesh Vaity

Roll No : 57 LAB Assignment Number : 6

Title of LAB Assignment : To Implement The Installation Of Ganache,


Metamask And Remix Ide And Deploy Smart Contract Using Injected Web 3
Environment

DOP : 28/08/2024 DOS: 13/09/2024

CO MAPPED : PO MAPPED: FACULTY MARKS:

CO2, CO3 PO2, PO3, SIGNATURE:


PSO1
Heetika Vaity Blockchain Lab SYMCA-57/B

AIM:TO IMPLEMENT THE INSTALLATION OF GANACHE, METAMASK AND


REMIX IDE AND DEPLOY SMART CONTRACT USING INJECTED WEB 3
ENVIRONMENT

THEORY:

Blockchain and Smart Contracts:

● Blockchain: A decentralized ledger that records transactions across many


computers in such a way that the registered transactions cannot be altered
retroactively.
● Smart Contracts: Self-executing contracts with the terms of the agreement directly
written into code. They run on the blockchain and automatically enforce and execute
the terms of the contract.

Development Tools:

● Ganache: A personal Ethereum blockchain used for development. It allows you to


deploy contracts, develop your applications, and run tests. Ganache provides a local
Ethereum network that mimics the public Ethereum network but runs locally on
your machine, offering more control and faster execution.
● MetaMask: A browser extension that acts as a cryptocurrency wallet and gateway to
blockchain applications. It manages identities and connects to decentralized
applications (dApps) via a browser.
● Remix IDE: An open-source web and desktop application used for writing,
compiling, and deploying smart contracts. Remix supports Solidity, the
programming language for Ethereum smart contracts.

Injected Web3 Environment:

● Injected Web3: A configuration where a dApp (like Remix IDE) connects to the
Ethereum network via a web3 provider injected by MetaMask. This setup allows the
dApp to interact with the blockchain through MetaMask’s wallet.

1
Heetika Vaity Blockchain Lab SYMCA-57/B

Steps for Implementation

1. Install Ganache:
○ Download Ganache from the Truffle Suite website and install it on your
machine.
○ Launch Ganache. It will start a local Ethereum blockchain and display a list of
accounts with private keys and Ether balances.
2. Install MetaMask:
○ Add MetaMask as a browser extension from the MetaMask website.
○ Set up MetaMask by creating a new wallet or importing an existing one. Make
sure to securely store your seed phrase.
○ Connect MetaMask to the Ganache network:
■ Open MetaMask and go to Settings > Networks > Add Network.
■ Enter Ganache network details (usually, http://localhost:7545
for Ganache default).
3. Install and Use Remix IDE:
○ Access Remix IDE via its web interface or by downloading the desktop
application.
○ Ensure that Remix is set to use the Injected Web3 environment:
■ In Remix, go to the Deploy & Run Transactions tab.
■ Choose Injected Web3 from the environment dropdown. Remix
should connect to MetaMask, and MetaMask should be connected to
Ganache.
4. Deploy a Smart Contract:

Write a simple smart contract in Solidity using Remix IDE. Here’s an example of a basic
smart contract:

pragma solidity ^0.8.0;

contract SimpleStorage {
uint256 public storedData;

function set(uint256 x) public {


storedData = x;
}
}

○ Compile the smart contract in Remix.


○ Go to the Deploy & Run Transactions tab.

2
Heetika Vaity Blockchain Lab SYMCA-57/B

○ Ensure Injected Web3 is selected. You should see the MetaMask network
and accounts.
○ Deploy the contract by clicking the Deploy button. MetaMask will prompt
you to confirm the transaction.
5. Interacting with the Contract:
○ After deployment, you can interact with the smart contract directly from
Remix. The deployed contract address and functions will be accessible
through Remix’s interface.

STEPS:

● Add metamask extension to Chrome

● Create your account and note down your recovery passwords

3
Heetika Vaity Blockchain Lab SYMCA-57/B

● Click on “Ethereum Mainnet”

● Add network manually

4
Heetika Vaity Blockchain Lab SYMCA-57/B

● Open Ganache and click on Quickstart

5
Heetika Vaity Blockchain Lab SYMCA-57/B

● Copy the RPC Url

● Keep the network name as localhost and paste the RPC Url, put Chain ID as 1337 and set
Currency Symbol to ETH and save

6
Heetika Vaity Blockchain Lab SYMCA-57/B

● Now, click on your account

7
Heetika Vaity Blockchain Lab SYMCA-57/B

● Click on add account

● Import account

● Go to Ganache and copy the private key

8
Heetika Vaity Blockchain Lab SYMCA-57/B

● Enter it here in Metamask

9
Heetika Vaity Blockchain Lab SYMCA-57/B

● Now, 100 Ethers have been deposited to the account

10
Heetika Vaity Blockchain Lab SYMCA-57/B

Remix IDE:

Remix IDE (Integrated Development Environment) is a web application that can


be used to write, debug, and deploy Ethereum Smart Contracts. Smart contract
is a technology that consist in formalize contract rules through an algorithm, this
code is written in solidity language, and is executed in a data decentralized
platform named blockchain, which is simulated in the IDE remix ethereum,
allowing automatic events, real time information, transparency, rastreability,
immutability and data security.

● Go to Remix IDE (https://remix.ethereum.org/)

● Create new File


a. As we use Solidity to write our smart contracts, .sol extension is used.
b. Let’s now create a new contract. For that, right-click on the
workspace and select New File. Name our file

11
Heetika Vaity Blockchain Lab SYMCA-57/B

● Create your smart contract

CODE:

election.sol

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

contract Election {
// Model a Candidate
struct Candidate {
uint id;
string name;
uint voteCount;
}

// Store accounts that have voted


mapping(address => bool) public voters;

// Store Candidates and fetch Candidate


mapping(uint => Candidate) public candidates;

// Store Candidates Count


uint public candidatesCount;

12
Heetika Vaity Blockchain Lab SYMCA-57/B

// Voted event
event votedEvent(
uint indexed _candidateId
);

constructor() {
addCandidate("N MODI, BJP");
addCandidate("A Kejriwal, AAP");
addCandidate("Rahul G, Congress");
addCandidate("Nikhil, JDS");
}

function addCandidate(string memory _name) private {


candidatesCount++;
candidates[candidatesCount] = Candidate(candidatesCount, _name,
0);
}

function vote(uint _candidateId) public {


// Require that they haven't voted before
require(!voters[msg.sender]);

// Require a valid candidate


require(_candidateId > 0 && _candidateId <= candidatesCount);

// Record that voter has voted


voters[msg.sender] = true;

// Update candidate vote count


candidates[_candidateId].voteCount++;

// Trigger voted event


emit votedEvent(_candidateId);
}
}

● Set your compiler version to 0.8.0

13
Heetika Vaity Blockchain Lab SYMCA-57/B

● Add this line

● Compile your script

● Change environment to Metamask and perform similar steps

14
Heetika Vaity Blockchain Lab SYMCA-57/B

15
Heetika Vaity Blockchain Lab SYMCA-57/B

● Click on the deploy button

● Check deployed contracts:

16
Heetika Vaity Blockchain Lab SYMCA-57/B

● Try to check candidate no : 5 , you will get the error, because the candidate 5 is not
available.

● Check any candidate information (Example Candidate: 1)

● Check whether the voter has voted or not by providing the account number. It
returns true if it has voted otherwise

17
Heetika Vaity Blockchain Lab SYMCA-57/B

● Vote any candidate[1-4], we are voting candidate 1. Click on transact

● Click on the confirm transaction in metamask

● Check how many votes are received by the candidate [for example, candidate 1]

18
Heetika Vaity Blockchain Lab SYMCA-57/B

● Check whether the voter has voted or not by providing the account number. It
returns true if it has voted otherwise no

● Try to vote again: [You will get the error]

19
Heetika Vaity Blockchain Lab SYMCA-57/B

● Check your balance: [Transaction processing fee has been debited from the
metamask account]

CONCLUSION:
By using Ganache, MetaMask, and Remix IDE together, you create a local Ethereum
development environment. Ganache provides a private blockchain for testing, MetaMask
manages Ethereum accounts and interactions, and Remix IDE offers a powerful platform for
smart contract development and deployment. The Injected Web3 environment facilitates
seamless communication between Remix and MetaMask, enabling efficient testing and
development of smart contracts.

20
Name of Student : Heetika Mahesh Vaity

Roll No : 57 LAB Assignment Number : 7

Title of LAB Assignment : Simple Experiments using Solidity


Program Constructs (if-then, while etc...)

DOP : 13/09/2024 DOS: 20/09/2024

CO MAPPED : PO MAPPED: FACULTY MARKS:

CO2, CO3 PO2, PO3, SIGNATURE:


PSO1
Heetika Vaity Blockchain Lab SYMCA-57/B

AIM: SIMPLE EXPERIMENTS USING SOLIDITY PROGRAM CONSTRUCTS


(IF-THEN, WHILE ETC...)

THEORY:

Solidity

Definition: Solidity is a high-level programming language designed for writing smart


contracts on blockchain platforms, particularly Ethereum.

Key Features:

1. Statically Typed: Variables must be declared with a specific data type (e.g., uint,
address, bool), which helps catch errors at compile time.
2. Contract-oriented: The primary building block of Solidity is the contract, which can
contain data and functions.
3. Inheritance: Solidity supports inheritance, allowing contracts to inherit properties
and methods from other contracts, enabling code reuse.
4. Libraries: Developers can create libraries to hold reusable code that can be shared
across contracts.
5. Events: Solidity allows contracts to emit events, which can be used to log
information and facilitate communication between contracts and the front end.
6. Modifiers: These are functions that can be used to change the behavior of functions
in a declarative way, often used for access control.

1
Heetika Vaity Blockchain Lab SYMCA-57/B

Smart Contracts

Definition: Smart contracts are self-executing contracts with the terms of the agreement
directly written into code. They run on a blockchain, enabling trustless transactions and
automation.

Characteristics:

1. Autonomous: Once deployed, they run independently and can execute


automatically based on predefined conditions.
2. Immutable: Once a smart contract is deployed on the blockchain, it cannot be
changed. This ensures the integrity of the contract.
3. Transparent: All transactions and contract states are recorded on the blockchain,
providing transparency to all parties involved.
4. Trustless: Parties do not need to trust each other; they trust the code. The execution
of the contract is handled by the blockchain network.

Use Cases:

1. Financial Services: Automating transactions, loans, and insurance without


intermediaries.
2. Supply Chain Management: Tracking goods and verifying their authenticity
throughout the supply chain.
3. Identity Verification: Storing and verifying identity information securely.
4. Voting Systems: Ensuring transparency and tamper-proof election processes.

Components:

● Functions: Define how the contract behaves and interacts with the blockchain.
● State Variables: Hold the data of the contract.
● Events: Enable the contract to log important information for external listeners

2
Heetika Vaity Blockchain Lab SYMCA-57/B

1) Write a program in solidity to find area and circumference of a circle,


rectangle

CODE:
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

contract q1 {
uint256 l = 50;
uint256 w = 25;
uint256 s = 9;
uint256 r = 5;

function area_of_rectangle() public view returns (uint256) {


uint256 area = l * w;
return area;
}

function area_of_square() public view returns (uint256) {


uint256 area = s * s;
return area;
}

function area_of_circle() public view returns (uint256) {


uint256 area = 3 * r * r;
return area;
}

function perimeter_of_rectangle() public view returns (uint256) {


uint256 perimeter = 2 * (l + w);
return perimeter;
}

function perimeter_of_square() public view returns (uint256) {


uint256 perimeter = 4 * s;
return perimeter;
}

function circumference_of_circle() public view returns (uint256) {

3
Heetika Vaity Blockchain Lab SYMCA-57/B

uint256 circumference = 2 * 3 * r;
return circumference;
}
}
OUTPUT:

4
Heetika Vaity Blockchain Lab SYMCA-57/B

2) Write a program in solidity to input the basic salary of an employee


and calculate
gross salary according to given conditions:
a) Base Salary <= 10000 HRA=20% DA = 80%
b) Base Salary is between 10001 to 20000:HRA =25% DA=90%
c) Base Salary>=20001 HRA=30% DA=95%

CODE:
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

contract q2 {
function gross_salary(uint256 basic_salary) public view returns
(uint256) {
if (basic_salary <= 10000) {
uint256 hra = basic_salary * 20 / 100;
uint256 da = basic_salary * 80 / 100;
uint256 gross_salary_total = basic_salary + hra + da;
return gross_salary_total;
}
else if (basic_salary >= 10001 && basic_salary <= 20000) {
uint256 hra = basic_salary * 25 / 100;
uint256 da = basic_salary * 90 / 100;
uint256 gross_salary_total = basic_salary + hra + da;
return gross_salary_total;
}
else if (basic_salary >= 20001) {
uint256 hra = basic_salary * 30 / 100;
uint256 da = basic_salary * 95 / 100;
uint256 gross_salary_total = basic_salary + hra + da;
return gross_salary_total;
}
}
}

5
Heetika Vaity Blockchain Lab SYMCA-57/B

OUTPUT:

6
Heetika Vaity Blockchain Lab SYMCA-57/B

3) Write a program in solidity to create a structure student with Roll no,


Name, Class, Department, Course enrolled as variables.
i) Add information about 5 students.
ii)Search for a student using Roll no
iii)Display all information

CODE:
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;

contract q3 {
struct student {
uint256 rollNo;
string name;
string placedCompany;
string degreeCourse;
}

student[] s;

function addStudent(
uint256 rollNo,
string memory name,
string memory placedCompany,
string memory degreeCourse
)
public
{
s.push(student(rollNo, name, placedCompany, degreeCourse));
}

function getStudentByRollNo(uint256 rollNumber)


public
view
returns (uint256, string memory)
{
for (uint256 i = 0; i < s.length; i++) {

7
Heetika Vaity Blockchain Lab SYMCA-57/B

if (s[i].rollNo == rollNumber) {
return (s[i].rollNo, s[i].name);
}
}
return (s[0].rollNo, s[0].name); // Consider handling cases where
no student is found
}

function getAllStudents()
public
view
returns (student[] memory)
{
return s;
}
}
OUTPUT:

8
Heetika Vaity Blockchain Lab SYMCA-57/B

9
Heetika Vaity Blockchain Lab SYMCA-57/B

4) Create a structure Consumer with Name, Address, Consumer ID, Units


and Amount as members.Write a program in solidity to calculate the
total electricity bill according to the given condition:
For first 50 units Rs. 0.50/unit For next 100 units
Rs. 0.75/unit For next 100 units
Rs. 1.20/unit For unit above 250
Rs. 1.50/unit An additional surcharge of 20% is added to the bill. Display
the information of 5 such consumers along with their units consumed
and amount.

CODE:
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;

contract q4 {
struct Consumer {
uint256 units;
string name;
string addr;
uint256 consumerID;
uint256 amount;
}

Consumer[] consumer;

function addConsumerInfo(
uint256 units,
string memory name,
string memory addr,
uint256 consumerID
)
public
{
consumer.push(Consumer(units, name, addr, consumerID, 0));
}

function getBillAmount() public {

10
Heetika Vaity Blockchain Lab SYMCA-57/B

uint256 i = 0;
uint256 amount = 0;
uint256 surcharge = 0;
uint256 units = 0;

for (i = 0; i < consumer.length; i++) {


units = consumer[i].units;

if (units <= 50) {


amount = ((units * 1) / 2);
} else if (units <= 150) {
amount = 25 + (((units - 50) * 3) / 4);
} else if (units <= 250) {
amount = 100 + (((units - 150) * 6) / 5);
} else {
amount = 220 + (((units - 250) * 3) / 2);
}

surcharge = (amount * 20) / 100;


amount = amount + surcharge;
consumer[i].amount = amount;
}
}

function displayConsumerInfo(uint256 consumerID)


public
view
returns (
uint256,
string memory,
string memory,
uint256,
uint256
)
{
uint256 i = 0;

for (i = 0; i < consumer.length; i++) {


if (consumer[i].consumerID == consumerID) {

11
Heetika Vaity Blockchain Lab SYMCA-57/B

return (
consumer[i].units,
consumer[i].name,
consumer[i].addr,
consumer[i].consumerID,
consumer[i].amount
);
}
}

return (
consumer[0].units,
consumer[0].name,
consumer[0].addr,
consumer[0].consumerID,
consumer[0].amount
);
}

function displayAllInfo()
public
view
returns (Consumer[] memory)
{
return consumer;
}
}
OUTPUT:

12
Heetika Vaity Blockchain Lab SYMCA-57/B

CONCLUSION:

Solidity and smart contracts represent a revolutionary approach to digital agreements and
automation. Their unique properties, such as transparency, immutability, and autonomy,
are paving the way for new business models and decentralized applications. As the
blockchain ecosystem continues to evolve, understanding these concepts becomes
increasingly essential for developers and businesses alike.

13
Name of Student : Heetika Mahesh Vaity

Roll No : 57 LAB Assignment Number : 8

Title of LAB Assignment : Smart Contract using Truffle Framework.

DOP : 13/09/2024 DOS: 20/09/2024

CO MAPPED : PO MAPPED: FACULTY MARKS:

CO5 PO1, PO2, PO3, SIGNATURE:


PO4, PO5, PO6,
PO7, PO8, PO9,
PSO1, PSO2
Heetika Vaity Blockchain Lab SYMCA-57/B

AIM: SMART CONTRACT USING TRUFFLE FRAMEWORK.

THEORY:

Truffle framework:

Truffle is a world-class development environment, testing framework and asset pipeline


for blockchains using the Ethereum Virtual Machine (EVM), aiming to make life as a
developer easier. Truffle is widely considered the most popular tool for blockchain
application development with over 1.5 million lifetime downloads. Truffle supports
developers across the full lifecycle of their projects, whether they are looking to build on
Ethereum, Hyperledger, Quorum, or one of an ever-growing list of other supported
platforms. Paired with Ganache, a personal blockchain, and Drizzle, a front-end dApp
development kit, the full Truffle suite of tools promises to be an end-to-end dApp
development platform.

1. Built-in smart contract compilation, linking, deployment and binary management.

2. Automated contract testing for rapid development.

3. Scriptable, extensible deployment & migrations framework.

4. Network management for deploying to any number of public & private networks.

5. Package management with EthPM & NPM, using the ERC190 standard.

6. Interactive console for direct contract communication.

7. Configurable build pipeline with support for tight integration.

8. External script runner that executes scripts within a Truffle environment.

You can install Truffle with NPM in your command line like this:

$ npm install -g truffle

Smart Contract:

A smart contract is a stand-alone script usually written in Solidity and compiled into binary
or JSON and deployed to a specific address on the blockchain. In the same way that we can
call a specific URL endpoint of a RESTful API to execute some logic through an HttpRequest,
we can similarly execute the deployed smart contract at a specific address by submitting
the correct data along with the necessary Ethereum to call the deployed and compiled
Solidity function.

1
Heetika Vaity Blockchain Lab SYMCA-57/B

→ 1. Install Node JS and Truffle Suite to develop and migrate the smart
contracts into the Private Blockchain network. Make use of Truffle tools
like compile, migrate and test for compilation, migration and testing the
smart contracts through Blockchain.

Developing smart contracts using Truffle

● Now that you have a private blockchain running, you need to configure your
environment for developing smart contracts.
● The first dependency you'll need is Node Package Manager, or NPM, which comes
with Node.js.
● You can see if you have node already installed by going to your terminal and typing:
$ node –v
● Otherwise, Download from: URL: https://nodejs.org/en/

Truffle Framework:

Truffle Framework, which provides a suite of tools for developing Ethereum smart contacts
with the Solidity programming language.
► Smart Contract Management
► Automated Testing
► Deployment & Migrations
► Network Management
► Script Runner
► Client Side Development

You can install Truffle with NPM in your command line like this:

$ npm install -g truffle

2
Heetika Vaity Blockchain Lab SYMCA-57/B

Create a new truffle project:


► Go to cmd prompt:
► $ mkdir blockchain-toolkit
► $ cd blockchain-toolkit
► $ truffle init
► $ touch package.json
► copy-and-pasting the below code into package.json file

package.json:
{
"name": "blockchain-toolkit-8",
"version": "1.0.0",
"description": "The Complete Blockchain Developer Toolkit for 2019 & Beyond",
"main": "truffle-config.js",
"directories": {
"test": "test"
},
"scripts": {
"dev": "lite-server",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "[email protected]",
"license": "ISC",
"devDependencies": {
"bootstrap": "4.1.3",
"chai": "^4.1.2",
"chai-as-promised": "^7.1.1",
"chai-bignumber": "^2.0.2",
"dotenv": "^4.0.0",
"ganache-cli": "^6.1.8",
"lite-server": "^2.3.0",
"nodemon": "^1.17.3",
"solidity-coverage": "^0.4.15",
"truffle": "5.0.0-beta.0",
"truffle-contract": "3.0.6",
"truffle-hdwallet-provider": "^1.0.0-web3one.0"
}
}

Save package.json file

3
Heetika Vaity Blockchain Lab SYMCA-57/B

$ npm install

Start developing a smart contract using solidity

► $ touch ./contracts/MyContract.sol

Copy the below contract code and save in Mycontract.sol

MyContract.sol:
pragma solidity >=0.4.2 <=0.8.17;
contract MyContract {
string value;
constructor() public {
value = "myValue";
}
function get() public view returns (string memory) {
return value;

4
Heetika Vaity Blockchain Lab SYMCA-57/B

}
function set(string memory _value) public {
value = _value;
}
}

Run:

► $ truffle compile

Update the project configuration file (Find the file truffle-config.js and paste the
following code:)

truffle-config.js:
module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*" // Match any network id
}
},
solc: {
optimizer: {
enabled: true,
runs: 200
}
}
}

5
Heetika Vaity Blockchain Lab SYMCA-57/B

Create a migration script inside the migrations directory to deploy the smart
contract to the personal blockchain network.

Run:

$ touch migrations/2_deploy_contracts.js

(Copy the below script into 2_depoy_contracts.js)

2_depoy_contracts.js:
var MyContract = artifacts.require("./MyContract.sol");
module.exports = function(deployer)
{
deployer.deploy(MyContract);
};

Run the following commands:

► truffle migrate

► $ truffle console

6
Heetika Vaity Blockchain Lab SYMCA-57/B

► MyContract.deployed().then((instance) => { app = instance } )


Now we can read the storage value
► app.get()
// => 'myValue’
Now we can set a new value like this:
► app.set('New Value')
We can read that the value was updated like this:
► app.get()
// => 'New Value’
You can exit the Truffle console by typing this command: .exit

GANACHE TRANSACTION LOGS:

7
Heetika Vaity Blockchain Lab SYMCA-57/B

→ 2. Create a Smart contract to simulate function overloading . Execute


the contract using the truffle framework.

Go to cmd prompt
$ mkdir blockchain-toolkit-overloading
$ cd blockchain-toolkit-overloading
$ truffle init
$ touch package.json

package.json:
{
"name": "blockchain-toolkit-overloading",
"version": "1.0.0",
"description": "The Complete Blockchain Developer Toolkit for 2019 & Beyond",
"main": "truffle-config.js",
"directories": {
"test": "test"
},
"scripts": {
"dev": "lite-server",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "[email protected]",
"license": "ISC",
"devDependencies": {
"bootstrap": "4.1.3",
"chai": "^4.1.2",
"chai-as-promised": "^7.1.1",
"chai-bignumber": "^2.0.2",
"dotenv": "^4.0.0",
"ganache-cli": "^6.1.8",
"lite-server": "^2.3.0",
"nodemon": "^1.17.3",
"solidity-coverage": "^0.4.15",
"truffle": "5.0.0-beta.0",
"truffle-contract": "3.0.6",
"truffle-hdwallet-provider": "^1.0.0-web3one.0"
}
}

8
Heetika Vaity Blockchain Lab SYMCA-57/B

Save package.json file

npm install

Update the project config file( find truffle-config.js and paste the code)

truffle-config.js:
module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*", // Match any network id
},
},
solc: {
optimizer: {
enabled: true,
runs: 200,
},
},
};

Open Ganache network

Start developing a smart contract using solidity:

In contracts folder:

overloading.js:
pragma solidity >=0.4.2 <=0.8.0;
contract overloading {
function getSum(uint a, uint b) public pure returns (uint) {
return a + b;
}
function getSum(
uint a,
uint b,
uint c
) public pure returns (uint) {
return a + b + c;

9
Heetika Vaity Blockchain Lab SYMCA-57/B

}
function callSumWithTwoArguments() public pure returns (uint) {
return getSum(1, 2);
}
function callSumWithThreeArguments() public pure returns (uint) {
return getSum(1, 2, 3);
}
}

In migration folder:

2_deploy_contracts.js:
var overloading = artifacts.require("./overloading.sol");
module.exports = function (deployer) {
deployer.deploy(overloading);
};
● truffle compile

● truffle migrate

10
Heetika Vaity Blockchain Lab SYMCA-57/B

● truffle console
overloading.deployed().then((instance) => {app = instance} )
app.getSum(5,6)
app.callSumWithTwoArguments()
app.callSumWithThreeArguments()

GANACHE TRANSACTION LOGS:

CONCLUSION:

Hence, we have successfully executed the smart contract using the truffle framework.

11
Name of Student : Heetika Mahesh Vaity

Roll No : 57 LAB Assignment Number : 9

Title of LAB Assignment : Creation of Dapp in Ethereum

DOP : 03/10/2024 DOS: 10/10/2024

CO MAPPED : PO MAPPED: FACULTY MARKS:

CO5 PO1, PO2, PO3, SIGNATURE:


PO4, PO5, PO6,
PO7, PO8, PO9,
PSO1, PSO2
Heetika Vaity Blockchain Lab SYMCA-57/B

AIM: CREATE DAPPS IN ETHEREUM.


THEORY:
Decentralized Applications
Decentralized Applications (or DApps) are applications that do not rely on a centralized
backend running in AWS or Azure that power traditional web and mobile applications
(outside of hosting the frontend code itself). Instead, the application interacts directly with
a blockchain which can be thought of distributed cluster of nodes analogous to
applications interacting directly with a “masterless” cluster of Cassandra nodes with full
replication on every peer in an untrusted peer-to-peer network.These blockchain nodes do
not require a leader which would defeat the purpose of being truly decentralized. Unlike
leader election in various consensus protocols like Raft and Paxos, blockchain transactions
are sent to and processed by “random” nodes via Proof of Work or Proof of Stake. These
nodes are untrusted nodes running in an arbitrary sized network on various compute
devices around the world. Such technology can enable true decentralized ledgers and
systems of records. DApps are the frontend apps which interact with these blockchain over
an API. For Ethereum, this API is a JSON-RPC layer called the Ethereum Web3 API which
Moesif supports natively.
Advantages

● Many of the advantages of dApps center around the program's ability to safeguard
user privacy. With decentralized apps, users do not need to submit their personal
information to use the function the app provides. DApps use smart contracts to
complete the transaction between two anonymous parties without the need to rely
on a central authority. • Proponents interested in free speech point out that dApps
can be developed as alternative social media platforms. A decentralized social
media platform would be resistant to censorship because no single participant on
the blockchain can delete messages or block messages from being posted.
● Ethereum is a flexible platform for creating new dApps, providing the infrastructure
needed for developers to focus their efforts on finding innovative uses for digital
applications. This could enable rapid deployment of dApps in a variety of industries
including banking and finance, gaming, social media, and online shopping

Description of the file directory structure:

● contracts directory- holds all smart contracts


● migrations directory: Whenever we deploy smart contracts to the blockchain, we are
updating the blockchain's state, and therefore need a migration.
● node_modules directory: this is the home of all of our Node dependencies.
● src directory: this is where we'll develop our client-side application.

1
Heetika Vaity Blockchain Lab SYMCA-57/B

● test directory: this is where we'll write our tests for our smart contracts.
● truffle.js file: this is the main configuration file for our Truffle project

Steps to follow:

1. Create a project directory for our dApp in the command line like this:
$ mkdir election
$ cd election

2. Install truffle:
npm install -g truffle

3. From within your project directory, install the pet shop box from the command line
like this:
$ truffle unbox pet-shop

4. create a new contract file in the contracts directory like this:


$ touch contracts/Election.sol
$ touch migrations/2_deploy_contracts.js

5. Migrate:
truffle migrate

6. open the console to interact with the smart contract.


$ truffle console

7. inside the console, let's get an instance of our deployed smart contract and see if we
can read the candidate's name from the contract. From the console, run this code:
Election.deployed().then(function(instance) { app = instance })
Here Election is the name of the variable that we created in the migration file. We
retrieved a deployed instance of the contract with the deployed() function, and
assigned it to an app variable inside the promise's callback function.

8. run the tests from the command line like this:


$ truffle test

9. Client-Side Application
$ truffle migrate --reset

10. Next, start your development server from the command line like this:
$ npm run dev or $ npm run start

A) E-VOTING APPLICATION BASED ON THE BLOCKCHAIN

2
Heetika Vaity Blockchain Lab SYMCA-57/B

SOURCE CODE:

1. contracts/Election.sol:

pragma solidity >=0.4.2 <=0.8.0;


contract Election {
// Model a Candidate
struct Candidate {
uint id;
string name;
uint voteCount;
}
// Read/write candidates
mapping(uint => Candidate) public candidates;
// Store accounts that have voted
mapping(address => bool) public voters;
// Store Candidates Count
uint public candidatesCount;
constructor() public {
addCandidate("Candidate 1");
addCandidate("Candidate 2");
}
event votedEvent(uint indexed _candidateId);
function addCandidate (string memory _name) private {
candidatesCount ++;
candidates[candidatesCount] = Candidate(candidatesCount, _name, 0);
}
function vote (uint _candidateId) public {
// require that they haven't voted before
require(!voters[msg.sender]);

// require a valid candidate


require(_candidateId > 0 && _candidateId <= candidatesCount);

// record that voter has voted


voters[msg.sender] = true;

// update candidate vote Count

3
Heetika Vaity Blockchain Lab SYMCA-57/B

candidates[_candidateId].voteCount ++;
// trigger voted event
emit votedEvent(_candidateId);
}
}

2. contracts/Migrations.sol:

pragma solidity >=0.4.22 <0.8.0;


contract Migrations {
address public owner = msg.sender;
uint public last_completed_migration;
modifier restricted() {
require(
msg.sender == owner,
"This function is restricted to the contract's owner"
);
_;
}
function setCompleted(uint completed) public restricted {
last_completed_migration = completed;
}
}

3. Migrations/1_initial_migrations.js:

var Migrations = artifacts.require("./Migrations.sol");


module.exports = function(deployer) {
deployer.deploy(Migrations);
};

4. Migrations/2_deploy_contracts.js:

var Election = artifacts.require("./Election.sol");


module.exports = function(deployer) {
deployer.deploy(Election);
};

4
Heetika Vaity Blockchain Lab SYMCA-57/B

5. truffle-config.js:

module.exports = {
// See <http://truffleframework.com/docs/advanced/configuration>
// for more about customizing your Truffle configuration!
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*" // Match any network id
},
develop: {
port: 7545
}
}
};

6. test/election.js:

var Election = artifacts.require("./Election.sol");


contract("Election", function(accounts) {
var electionInstance;
it("initializes with two candidates", function() {
return Election.deployed().then(function(instance) {
return instance.candidatesCount();
}).then(function(count) {
assert.equal(count, 2);
});
});

it("it initializes the candidates with the correct values", function() {


return Election.deployed().then(function(instance) {
electionInstance = instance;
return electionInstance.candidates(1);
}).then(function(candidate) {
assert.equal(candidate[0], 1, "contains the correct id");
assert.equal(candidate[1], "Candidate 1", "contains the correct name");
assert.equal(candidate[2], 0, "contains the correct votes count");
return electionInstance.candidates(2);

5
Heetika Vaity Blockchain Lab SYMCA-57/B

}).then(function(candidate) {
assert.equal(candidate[0], 2, "contains the correct id");
assert.equal(candidate[1], "Candidate 2", "contains the correct name");
assert.equal(candidate[2], 0, "contains the correct votes count");
});
});

it("allows a voter to cast a vote", function() {


return Election.deployed().then(function(instance) {
electionInstance = instance;
candidateId = 1;
return electionInstance.vote(candidateId, { from: accounts[0] });
}).then(function(receipt) {
assert.equal(receipt.logs.length, 1, "an event was triggered");
assert.equal(receipt.logs[0].event, "votedEvent", "the event type is correct");
assert.equal(receipt.logs[0].args._candidateId.toNumber(), candidateId, "the
candidate id is correct");
return electionInstance.voters(accounts[0]);
}).then(function(voted) {
assert(voted, "the voter was marked as voted");
return electionInstance.candidates(candidateId);
}).then(function(candidate) {
var voteCount = candidate[2];
assert.equal(voteCount, 1, "increments the candidate's vote count");
})
});

it("throws an exception for invalid candiates", function() {


return Election.deployed().then(function(instance) {
electionInstance = instance;
return electionInstance.vote(99, { from: accounts[1] })
}).then(assert.fail).catch(function(error) {
assert(error.message.indexOf('revert') >= 0, "error message must contain
revert");
return electionInstance.candidates(1);
}).then(function(candidate1) {
var voteCount = candidate1[2];
assert.equal(voteCount, 1, "candidate 1 did not receive any votes");
return electionInstance.candidates(2);

6
Heetika Vaity Blockchain Lab SYMCA-57/B

}).then(function(candidate2) {
var voteCount = candidate2[2];
assert.equal(voteCount, 0, "candidate 2 did not receive any votes");
});
});

it("throws an exception for double voting", function() {


return Election.deployed().then(function(instance) {
electionInstance = instance;
candidateId = 2;
electionInstance.vote(candidateId, { from: accounts[1] });
return electionInstance.candidates(candidateId);
}).then(function(candidate) {
var voteCount = candidate[2];
assert.equal(voteCount, 1, "accepts first vote");
// Try to vote again
return electionInstance.vote(candidateId, { from: accounts[1] });
}).then(assert.fail).catch(function(error) {
assert(error.message.indexOf('revert') >= 0, "error message must contain
revert");
return electionInstance.candidates(1);
}).then(function(candidate1) {
var voteCount = candidate1[2];
assert.equal(voteCount, 1, "candidate 1 did not receive any votes");
return electionInstance.candidates(2);
}).then(function(candidate2) {
var voteCount = candidate2[2];
assert.equal(voteCount, 1, "candidate 2 did not receive any votes");
});
});
});

7. index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">

7
Heetika Vaity Blockchain Lab SYMCA-57/B

<meta name="viewport" content="width=device-width, initial-scale=1">


<title>Election Results</title>

<link href="css/bootstrap.min.css" rel="stylesheet">

<script
src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container" style="width: 650px;">
<div class="row">
<div class="col-lg-12">
<h1 class="text-center">Election Results</h1>
<hr/>
<br/>
<div id="loader">
<p class="text-center">Loading...</p>
</div>
<div id="content" style="display: none;">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Votes</th>
</tr>
</thead>
<tbody id="candidatesResults">
</tbody>
</table>
<hr/>
<form onSubmit="App.castVote(); return false;">
<div class="form-group">
<label for="candidatesSelect">Select Candidate</label>
<select class="form-control" id="candidatesSelect">
</select>
</div>

8
Heetika Vaity Blockchain Lab SYMCA-57/B

<button type="submit" class="btn btn-primary">Vote</button>


<hr />
</form>
<p id="accountAddress" class="text-center"></p>
</div>
</div>
</div>
</div>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/web3.min.js"></script>
<script src="js/truffle-contract.js"></script>
<script src="js/app.js"></script>
</body>
</html>

STEPS INVOLVED IN EXECUTION:

1. CHANGING DIRECTORY & TRUFFLE MIGRATE:

➢ cd election
➢ truffle migrate

9
Heetika Vaity Blockchain Lab SYMCA-57/B

10
Heetika Vaity Blockchain Lab SYMCA-57/B

➢ truffle console

➢ truffle test

11
Heetika Vaity Blockchain Lab SYMCA-57/B

➢ truffle migrate –reset

➢ npm run dev

12
Heetika Vaity Blockchain Lab SYMCA-57/B

OUTPUT:

CAST VOTE:
COUNT OF VOTES:

13
Heetika Vaity Blockchain Lab SYMCA-57/B

B) SUPPLY CHAIN MANAGEMENT IN ETHEREUM:

SOURCE CODE:

Refer on this website:


https://github.com/rishav4101/eth-supplychain-dapp

CHANGING GAS IN GANACHE:

➢ truffle migrate –network-develop –reset

14
Heetika Vaity Blockchain Lab SYMCA-57/B

➢ npm install

15
Heetika Vaity Blockchain Lab SYMCA-57/B

➢ npm start

OUTPUT:

Create 4 accounts on metamask [import from ganache] and assign the private key
address to manufacturer, third party, delivery, customer:
Manufacturer: Account 3
Third Party: Account 4
Delivery Hub: Account 5
Customer: Account 6
also, connect website (http://localhost:3000) to all 4 account & switch account based
on the role

16
Heetika Vaity Blockchain Lab SYMCA-57/B

ADD ROLES:

CLICK ON CONFIRM:

17
Heetika Vaity Blockchain Lab SYMCA-57/B

MANUFACTURER:
ADD PRODUCT:

CONFIRM TRANSACTION:

18
Heetika Vaity Blockchain Lab SYMCA-57/B

EXPLORER:
CHECK WHETHER THE PRODUCT IS ADDED SUCCESSFULLY OR NOT:

19
Heetika Vaity Blockchain Lab SYMCA-57/B

THIRD PARTY:
BUY PRODUCT:

20
Heetika Vaity Blockchain Lab SYMCA-57/B

SHIP PRODUCT:

RECEIVE PRODUCT:

21
Heetika Vaity Blockchain Lab SYMCA-57/B

22
Heetika Vaity Blockchain Lab SYMCA-57/B

CUSTOMER:
PURCHASE PRODUCT:

THIRD PARTY:
PRODUCTS TO BE SHIPPED:

23
Heetika Vaity Blockchain Lab SYMCA-57/B

DELIVERY HUB:
Products To be Received:

24
Heetika Vaity Blockchain Lab SYMCA-57/B

25
Heetika Vaity Blockchain Lab SYMCA-57/B

DELIVERY HUB:
SHIP PRODUCT:

CUSTOMER:
RECEIVE:

26
Heetika Vaity Blockchain Lab SYMCA-57/B

CUSTOMER:
PRODUCT:

27
Heetika Vaity Blockchain Lab SYMCA-57/B

EXPLORER:
PRODUCT HISTORY: [ALL TRANSACTIONS]

CONCLUSION:

Hence, we have successfully created Dapp with ethereum.

28
Name of Student : Heetika Mahesh Vaity

Roll No : 57 LAB Assignment Number : 10

Title of LAB Assignment : Mini Project

DOP : 03/10/2024 DOS: 10/10/2024

CO MAPPED : PO MAPPED: FACULTY MARKS:

CO5 PO1, PO2, PO3, SIGNATURE:


PO4, PO5, PO6,
PO7, PO8, PO9,
PSO1, PSO2
Heetika Vaity Blockchain Lab SYMCA-57/B

MINI PROJECT: PROOF OF CONCEPT IMPLEMENTATION OF BLOCKCHAIN

Abstract:
Blockchain technology has gained significant attention for its potential to revolutionize
various industries through its transparent, secure, and decentralized nature. This project
presents a proof of concept implementation of a blockchain system using Java, aiming to
explore the fundamental concepts and demonstrate the feasibility of a custom blockchain
implementation in a popular programming language. The dissertation provides an
overview of blockchain technology, the motivations behind the project, and a
comprehensive analysis of the design, implementation, and evaluation of the Java-based
blockchain system.

The project starts with a thorough literature review, encompassing the essential principles
of blockchain technology and prior efforts in implementing blockchains in Java. This
knowledge serves as the foundation for the project's methodology, guiding the selection of
suitable software tools and the design of the blockchain architecture. Key aspects of the
project include the data structures for blocks and transactions, the implementation of a
consensus mechanism (Proof of Work in this case), cryptographic techniques for securing
data, and optional features such as smart contracts.

The core implementation covers essential elements of a blockchain system, including the
data structure for blocks, transaction processing, block validation and mining, networking
with peer-to-peer communication, and security measures to safeguard the integrity of the
blockchain.

The results and evaluation section discusses the testing methodology, performance metrics,
and the validation of the proof of concept implementation. By evaluating the blockchain
system's performance and functionality, the project highlights its potential for practical
applications and identifies the challenges faced during the implementation process. The
evaluation is also presented alongside comparisons with existing blockchain solutions.

The discussion section interprets the project's findings, explores the implications of the
proof of concept, and delves into its practical applications and use cases. The limitations
and scalability of the Java-based blockchain are also discussed, providing insight into areas
for potential improvement and further research.

In conclusion, the project's proof of concept implementation demonstrates the feasibility of


developing a blockchain system in Java and contributes to the understanding of blockchain

1
Heetika Vaity Blockchain Lab SYMCA-57/B

technology. This research project not only lays the groundwork for potential real-world
applications of Java-based blockchains but also serves as a valuable resource for future
research and enhancements in the field.

1. Introduction

1.1 Background and Motivation


Blockchain technology, initially introduced as the underlying technology for Bitcoin, has
evolved into a revolutionary concept with far-reaching applications beyond
cryptocurrencies. Its fundamental principles of decentralization, transparency,
immutability, and security have inspired innovative solutions across various industries,
including finance, supply chain management, healthcare, and more. The blockchain's
potential to disrupt traditional systems and provide solutions to existing challenges has
captured the attention of researchers, developers, and businesses worldwide.

The adoption of blockchain technology, however, often necessitates a deep understanding


of its core principles, mechanisms, and design considerations. Building a practical
understanding is crucial for the effective utilization of blockchain in various domains. In
response to this need, this project embarks on the implementation of a blockchain system
using Java, one of the most widely used programming languages. By creating a proof of
concept blockchain system, we aim to explore the foundational concepts and demonstrate
the feasibility of a custom blockchain implementation in a language known for its
versatility and community support.

1.2 Research Objectives


The primary objectives of this project are as follows:
● To implement a custom blockchain system in Java, encompassing core blockchain
components such as blocks, transactions, consensus mechanisms, and security
measures.
● To analyze the performance, functionality, and limitations of the Java-based
blockchain through testing and evaluation.
● To evaluate the project's implications for real-world applications and its potential
contributions to the field of blockchain technology.

1.3 Scope of the Project


This project focuses on the development of a proof of concept blockchain in Java, examining
its essential components and providing insights into its practical applications and

2
Heetika Vaity Blockchain Lab SYMCA-57/B

limitations. The scope encompasses the design, implementation, testing, and evaluation of
the blockchain system, with an emphasis on understanding how blockchain technology can
be leveraged in a Java-based environment.

2. Implementation

2.1 Code
Block.java

package vesit.bc.mp.g1.poc_impl_blockchain;

import java.util.Date;

import vesit.bc.mp.g1.poc_impl_blockchain.utility.StringUtil;

public class Block {

public String hash;


public String previousHash;
private String data;
private long timeStamp;
private int nonce;

public Block(String data, String previousHash) {


this.data = data;
this.previousHash = previousHash;
this.timeStamp = new Date().getTime();
this.hash = calculateHash();
}

public String calculateHash() {


String calculatedhash = StringUtil
.getSha256HashOf(previousHash +
Long.toString(timeStamp) + Integer.toString(nonce) + data);
return calculatedhash;
}

public void mineBlock(int difficulty) {


String target = new String(new char[difficulty]).replace('\0',
'0'); // Create a string with difficulty * "0"
while (!hash.substring(0, difficulty).equals(target)) {
nonce++;
hash = calculateHash();
}
System.out.println("Block Mined!!! : " + hash);
}
}

3
Heetika Vaity Blockchain Lab SYMCA-57/B

utility/StringUtil.java

package vesit.bc.mp.g1.poc_impl_blockchain.utility;

import java.security.MessageDigest;

public class StringUtil {


public static String getSha256HashOf(String input) {
try {
MessageDigest digest =
MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(input.getBytes("UTF-8"));
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if (hex.length() == 1)
hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

runner/Driver.java

package vesit.bc.mp.g1.poc_impl_blockchain.runner;

import java.util.ArrayList;

import com.google.gson.GsonBuilder;

import vesit.bc.mp.g1.poc_impl_blockchain.Block;

public class Driver {


final public static int difficulty = 5;
final public static ArrayList<Block> blockchain = new
ArrayList<Block>();

public static Boolean isChainValid() {


Block currentBlock;
Block previousBlock;
String hashTarget = new String(new
char[difficulty]).replace('\0', '0');

// loop through blockchain to check hashes:


for (int i = 1; i < blockchain.size(); i++) {
currentBlock = blockchain.get(i);
previousBlock = blockchain.get(i - 1);

4
Heetika Vaity Blockchain Lab SYMCA-57/B

// compare registered hash and calculated hash:


if
(!currentBlock.hash.equals(currentBlock.calculateHash())) {
System.out.println("Current Hashes not equal");
return false;
}
// compare previous hash and registered previous hash
if
(!previousBlock.hash.equals(currentBlock.previousHash)) {
System.out.println("Previous Hashes not equal");
return false;
}
// check if hash is solved
if (!currentBlock.hash.substring(0,
difficulty).equals(hashTarget)) {
System.out.println("This block hasn't been mined");
return false;
}
}
return true;
}

public static void main(String... args) {


blockchain.add(new Block("Hi im the first block", "0"));
System.out.println("Trying to Mine block 1... ");
blockchain.get(0).mineBlock(difficulty);

blockchain.add(new Block("Yo im the second block",


blockchain.get(blockchain.size() - 1).hash));
System.out.println("Trying to Mine block 2... ");
blockchain.get(1).mineBlock(difficulty);

blockchain.add(new Block("Hey im the third block",


blockchain.get(blockchain.size() - 1).hash));
System.out.println("Trying to Mine block 3... ");
blockchain.get(2).mineBlock(difficulty);

System.out.println("\nBlockchain is Valid: " +


isChainValid());

String blockchainJson = new


GsonBuilder().setPrettyPrinting().create().toJson(blockchain);
System.out.println("\nThe block chain: ");
System.out.println(blockchainJson);
}
}

5
Heetika Vaity Blockchain Lab SYMCA-57/B

2.2 Demo

3. Conclusion

In the implementation of the blockchain project, key objectives were achieved by leveraging
blockchain's decentralized, secure, and transparent nature. The project successfully
established a distributed ledger that ensures data immutability, providing tamper-proof
records and enhancing trust among participants. Smart contracts were implemented to
automate processes, reducing the need for intermediaries and increasing efficiency.
Additionally, security protocols like cryptography safeguarded transactions and user
identities. Overall, the blockchain integration demonstrated significant improvements in
transparency, security, and operational efficiency for the project's use case.

You might also like