Blockchain_Practicals_Reference Journal.docx

Download as pdf or txt
Download as pdf or txt
You are on page 1of 146

Exam Seat No.

VIVEKANANDEDUCATION SOCIETY’S
INSTITUTE OF TECHNOLOGY
HashuAdvani Memorial Complex, Collector’s Colony, R. C. Marg,
Chembur, Mumbai – 400074. Contact No. 02261532532

Since 1962

CERTIFICATE

Certified that _____________of ____________ has satisfactorily completed a


course of the necessary experiments in _____________under my supervision in
the ______________in the academic year ____________

Principal Head of Department

Faculty In-charge External Examiner


Sr. Date Of Page
Contents Marks Sign
No Submission No

Implementation of Ceaser Cipher


1 07/10/2021 3
(Symmetric Encryption)

Implementation of RSA Algorithm


2 07/10/2021 9
(Asymmetric Encryption)

3 Implementation of SHA-256 09/10/2021 13

4 Implementation of Binary Tree 10/10/2021 20

Implement the creation of Bitcoin Block


5 05/11/2021 35
(Genesis Block)

Install Ganache and metamask.


Compile and deploy an election smart
contract in the personal blockchain using
6 injected web 3 environment. Use Remix 08/11/2021 50
online ide to compile and deploy the smart
contract. Execute the smart contract and
show the output.

7 Programming In Solidity. 10/12/2021 70

8 Implementation of Smart Contracts 09/12/2021 83

Implementation of Decentralized
9 10/12/2021 96
Applications

10 Mini Project 11/12/2021 123


Practical 1
Aim:
Implement Caesar Cipher (Symmetric Encryption) and show the
encryption as well as decryption process.

Theory:
What is Cryptography?

Cryptography is the study of securing communications from outside


observers. Encryption algorithms take the original message, or
plaintext, and convert it into cipher text, which is not understandable.
The key allows the user to decrypt the message, thus ensuring they can
read the message. The strength of the randomness of an encryption is
also studied, which makes it harder for anyone to guess the key or input
of the algorithm.
Cryptography is how we can achieve more secure and robust
connections to elevate our privacy. Advancements in cryptography
makes it harder to break encryptions so that encrypted files, folders, or
network connections are only accessible to authorized users.

Cryptography focuses on four different objectives:


1) Confidentiality: Confidentiality ensures that only the intended
recipient can decrypt the message and read its contents.
2) Non-repudiation: Non-repudiation means the sender of the message cannot
backtrack in the future and deny their reasons for sending or creating the
message.
3) Integrity: Integrity focuses on the ability to be certain that the information
contained within the message cannot be modified while in storage or transit.
4) Authenticity: Authenticity ensures the sender and recipient can verify
each other’s identities and the destination of the message.
What is Symmetric Encryption?

Symmetric Key Cryptography also known as Symmetric Encryption is


when a secret key is leveraged for both encryption and decryption
functions. This method is the opposite of Asymmetric Encryption where
one key is used to encrypt and another is used to decrypt. During this
process, data is converted to a format that cannot be read or inspected
by anyone who does not have the secret key that was used to encrypt it.
The success of this approach depends on the strength of the random
number generator that is used to create the secret key. Symmetric Key
Cryptography is widely used in today’s Internet and primarily consists of
two types of algorithms, Block and Stream. Some common encryption
algorithms include the Advanced Encryption Standard (AES) and the
Data Encryption Standard (DES). This form of encryption is
traditionally much faster than Asymmetric however it requires both the
sender and the recipient of the data to have the secret key.
Explanation about Caesar cipher The Caesar cipher is one of the earliest known and
simplest ciphers. It is a type of substitution cipher in which each letter in the
plaintext is 'shifted' a certain number of places 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 named after Julius Caesar, who apparently used it to communicate with
his generals. More complex encryption schemes such as the Vigenère cipher
employ the Caesar cipher as one element of the encryption process. The widely
known ROT13 'encryption' is simply a Caesar cipher with an offset of 13. The
Caesar cipher offers essentially no communication security, and it will be shown
that it can be easily broken even by hand. Example: To pass an encrypted
message from one person to another, it is first necessary that both parties have the
'key' for the cipher, so that the sender may encrypt it and the receiver may decrypt
it. For the Caesar cipher, the key is the number of characters to shift the cipher
alphabet. Here is a quick example of the encryption and decryption steps involved
with the Caesar cipher. The text we will encrypt is 'defend the east wall of the
castle', with a shift (key) of 1.
Plain-text: defend the east wall of the castle

Cipher-text: efgfoe uif fbtu xbmm pg uif dbtumf

It is easy to see how each character in the plaintext is shifted up the


alphabet. Decryption is just as easy, by using an offset of -1.

Plain-text: abcdefghijklmnopqrstuvwxyz

Cipher-text: bcdefghijklmnopqrstuvwxyza

Obviously, if a different key is used, the cipher alphabet will be shifted a


different amount.

Code:
Output:

Conclusion:
Hence, we have successfully implemented Caesar Cipher (Symmetric
Encryption) and we have shown the encryption as well as the decryption
process.
Practical 2
Aim:
Implement RSA Algorithm (Asymmetric Encryption), Encrypt and decrypt a
string.

Theory:
What is Asymmetric Encryption?

Asymmetric encryption is a type of encryption that uses two separates


yet mathematically related keys to encrypt and decrypt data. The public
key encrypts data while its corresponding private key decrypts it. This
is why it’s also known as public key encryption, public key
cryptography, and asymmetric key encryption.

The public key is open to everyone. Anyone can access it and encrypt
data with it. However, once encrypted, the data can only be unlocked by
using the corresponding private key. As you can imagine, the private key
must be kept secret to keep it from becoming compromised. So, only the
authorized person, server, machine, or instrument has access to the
private key.

Explanation about RSA (steps and example) 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 the year
1978 and hence name 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=p*q
Here, let N be the specified large number.

Step 2: Derived Number (e)

Consider number e as a derived number which should be greater than 1


and less than (p-1) and (q-1). The primary condition will be that there
should be no common factor of (p-1) and (q-1) except 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:

ed = 1 mod (p-1) (q-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 in the given
scenario, use the following syntax:

C = Pe 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 = Cd mod n

Code:

Output:

Conclusion:
Hence, we have successfully implemented RSA Algorithm (Asymmetric
Encryption) and we have encrypted and decrypted a string.
Practical 3
Aim:
To implement SHA 256 Algorithm

Theory:
Hashing

Hashing is the process of scrambling raw information to the extent that


it cannot reproduce it back to its original form. It takes a piece of
information and passes it through a function that performs
mathematical operations on the plaintext. This function is called the
hash function, and the output is called the hash value/digest.

As seen from the above image, the hash function is responsible for
converting the plaintext to its respective hash digest. They are designed
to be irreversible, which means your digest should not provide you with
the original plaintext by any means necessary.
Hash functions also provide the same output value if the input remains
unchanged, irrespective of the number of iterations.

There are two primary applications of hashing:

Password Hashes: In most website servers, it converts user passwords


into a hash value before being stored on the server. It compares the hash
value recalculated during login to the one stored in the database for
validation.
Integrity Verification: When it uploads a file to a website, it also shared
its hash as a bundle. When a user downloads it, it can recalculate the
hash and compare it to establish data integrity.

It is one of the algorithms which calculates a string value from a file,


which is of a fixed size. Basically, it contains blocks of data, which is
transformed into a short fixed-length key or value from the original
string. Additionally, the term “hash” is used for describing both the hash
function as well as the hash value.

Hash functions were created to compress data to reduce the amount of


memory required for storing large files. The hashes they create can be
stored in a special data structure called hash tables, which enables
quicker data lookups. The core reason for hash functions arose from the
need to compress content, but the unique identifiers of hash values soon
became a staple of simplicity in database management. No two hash
inputs should ever return the same hash, but instead create singularly
unique identifiers for each hash input. When two different hash inputs
return the same output hash, it is called a collision. A more extensive
family of hash functions were created with privacy, security and
transparency in mind.

SHA256:
SHA 256 is a part of the SHA 2 family of algorithms, where SHA stands for Secure
Hash Algorithm. Published in 2001, it was a joint effort between the NSA and NIST
to introduce a successor to the SHA 1 family, which was slowly losing strength
against brute force attacks. The significance of the 256 in the name stands for the
final hash digest value, i.e., irrespective of the size of plaintext/cleartext, the hash
value will always be 256 bits.

The other algorithms in the SHA family are more or less similar to SHA 256. Now,
look into knowing a little more about their guidelines. The Secure Hash Algorithm
is one of a number of cryptographic hash functions. A cryptographic hash is like a
signature for a data set. If you would like to compare two sets of raw data it is
always better to hash it and compare SHA256 values. It is like the fingerprints of
the data. Even if only one symbol is changed the algorithm will produce a different
hash value.
SHA256 algorithm generates an almost-unique, fixed size 256-bit
(32-byte) hash. Hash is so called a one-way function. This makes it
suitable for checking integrity of your data, challenge hash
authentication, anti-tamper, digital signatures, blockchain. With the
newest hardware improvements, it has become

possible to decrypt SHA256 algorithm back. So, it is no longer


recommended to use it for password protection or other similar use
cases. Some years ago, you would protect your passwords from hackers
by storing SHA256 encrypted passwords in your database. This is no
longer a case. SHA256 algorithm can be still used for making sure you
acquired the same data as the original one.

For example, if you download something you can easily check if data has
not changed due to network errors or malware injection. You can
compare hashes of your file and original one which is usually provided
in the website you are getting data or the file from. SHA-256 is one of
the successor hash functions to SHA-1, and is one of the strongest hash
functions available.

Hashlib module in python:

The hashlib module of Python is used to implement a common interface


to many different secure hash and message digest algorithms.

The hash algorithms included in this module are:

• SHA1: a 160-bit hash function that resembles MD5 hash


• SHA224: internal block size of 32 bits (truncated version)
• SHA256: internal block size of 32 bits
• SHA384: internal block size of 32 bits (truncated version)
• SHA512: internal block size of 64 bits
• MD5 algorithm
Different functions associated with Python sha256:
• encode(): used to convert the string into bytes
• Syntax: string.encode(encoding=encoding, errors=errors)
• Parameter Values: encoding: type of encoding that will be used Default value:
• UTF – 8 errors: error method like backslashreplace, namereplace etc.
• hexdigest(): used to return the encoded data in hexadecimal format

hashlib.sha256(): This function is used to create a SHA-256 hash object

Code:

Output:

Conclusion:
Hence, we have successfully implemented RSA algorithm (asymmetric
encryption), encrypt and decrypt a string.
Practical 4
Aim:
To Implementation of Binary Tree and to show all operations (Insert,
Delete, Traversals, Display)

Theory:
Tree

A tree is a nonlinear hierarchical data structure that consists of nodes


connected by edges. It connects each node in the tree data structure
using "edges”, both directed and undirected. It can also be defined as a
collection of objects or entities known as nodes that are linked together
to represent or simulate hierarchy. It is a non-linear data structure
because it does not store in a sequential manner. It is a hierarchical
structure as elements in a Tree are arranged in multiple levels.

In the Tree data structure, the topmost node is known as a root node.
Each node contains some data, and data can be of any type. In the
above tree structure, the node contains the name of the employee, so
the type of data would be a string. Each node contains some data and
the link or reference of other nodes that can be called children.
Tree Terminologies

Root

In a tree data structure, the root is the first node of the tree. The root
node is the initial node of the tree in data structures. In the tree data
structure, there must be only one root node.

Edge

In a tree in data structures, the connecting link of any two nodes is


called the edge of the tree data structure. In the tree data structure, N
number of nodes connecting with N -1 number of edges.

Parent

In the tree in data structures, the node that is the predecessor of any
node is known as a parent node, or a node with a branch from itself to
any other successive node is called the parent node.

Child

The node, a descendant of any node, is known as child nodes in data


structures. In a tree, any number of parent nodes can have any number
of child nodes. Ina tree, every node except the root node is a child node.

Siblings

In trees in the data structure, nodes that belong to the same parent are
called siblings.

Leaf

Trees in the data structure, the node with no child, is known as a leaf
node. In trees, leaf nodes are also called external nodes or terminal
nodes.
Internal nodes

Trees in the data structure have at least one child node known as
internal nodes. In trees, nodes other than leaf nodes are internal nodes.
Sometimes root nodes are also called internal nodes if the tree has more
than one node.

Degree

In the tree data structure, the total number of children of a node is


called the degree of the node. The highest degree of the node among all
the nodes in a tree is called the Degree of Tree.

Level

In tree data structures, the root node is said to be at level 0, and the root
node's children are at level 1, and the children of that node at level 1 will
be level 2, and so on.

Height

In a tree data structure, the number of edges from the leaf node to the
particular node in the longest path is known as the height of that node.
In the tree, the height of the root node is called "Height of Tree". The
tree height of all leaf nodes is 0.

Depth

In a tree, many edges from the root node to the particular node are
called the depth of the tree. In the tree, the total number of edges from
the root node to the leaf node in the longest path is known as "Depth of
Tree". In the tree data structures, the depth of the root node is 0.

Path

In the tree in data structures, the sequence of nodes and edges from one
node to another node is called the path between those two nodes. The
length of a path is the total number of nodes in a path.zx
Subtree

In the tree in data structures, each child from a node shapes a


sub-tree recursively and every child in the tree will form a sub- tree
on its parent node.

Binary Tree:

A binary tree is a tree data structure in which each parent node can have
at most two children. Each node has a key and an associated value. The
value of the key of the left sub-tree is less than the value of its parent
(root) node's key. The value of the key of the right sub-tree is greater
than or equal to the value of its parent (root) node's key.

A parent node has two child nodes: the left child and right child.
Hashing, routing data for network traffic, data compression, preparing
binary heaps, and binary search trees are some of the applications that
use a binary tree.

Each node of a binary tree consists of three items:

• data item
• address of left child
• address of right child

Basic Operations

Following are the basic operations of a tree −

​ Create Root − We just create a Node class and assign a value to the
node. This becomes a tree with only a root node.

​ Search − Searches an element in a tree.

​ Insert – (Inserts an element in a tree.) To insert into a tree, we use the same

node class created above and add an insert class to it. The insert class
compares the value of the node to the parent node and decides to add it as a
left node or a right node. Finally, the PrintTree class is used to print the tree.
​ Traversing a Tree – The tree can be traversed by deciding on a

sequence to visit each node. As we can clearly see we can start at


a node then visit the left subtree first and right subtree next. We
can also visit the right subtree first and left sub-tree next.
Accordingly, there are different names for these tree traversal
methods. Traversal is a process to visit all the nodes of a tree
and may print their values too. Because all nodes are connected
via edges, we always start from the root node. That is, we cannot
randomly access a node in a tree. There are three ways which
we use to traverse a tree:
o Pre-order Traversal – In this traversal method, the root
node is visited first, then the left subtree and finally the
right subtree. We use the Node class to create
placeholders for the root node as well as the left and right
nodes. Then, we create an insert function to add data to the
tree. Finally, the Pre-order traversal logic is implemented
by creating an empty list and adding the root node first
followed by the left node. At last, the right node is added to
complete the Pre-order traversal.
o In-order Traversal – In this traversal method, the left
subtree is visited first, then the root and later the right
subtree. We should always remember that every node may
represent a subtree itself. We use the Node class to create
placeholders for the root node as well as the left and right
nodes. Then, we create an insert function to add data to the
tree. Finally, the Inorder traversal logic is implemented by
creating an empty list and adding the left node first
followed by the root or parent node. At last, the left node is
added to complete the In- order traversal.
o Post-order Traversal – In this traversal method, the root
node is visited last, hence the name. First, we traverse the
left subtree, then the right subtree and finally the root node.
We use the Node class to create place holders for the root
node as well as the left and right nodes. Then, we create an
insert function to add data to the tree. Finally, the
Post-order traversal logic is implemented by creating an
empty list and adding the left node first followed by the
right node. At last, the root or parent node is added to
complete the post- order traversal.

​ Delete – Given a binary tree, delete a node from it by making

sure that tree shrinks from the bottom. This is different from
BST deletion. Here we do not have any order among elements, so
we replace it with the last element.

Algorithm
1. Starting at the root, find the deepest and rightmost node in the binary
tree and node which we want to delete.

2. Replace the deepest rightmost node’s data with the node to be deleted.

3. Then delete the deepest rightmost node.

Merkle Tree

Merkle tree / Hash Tree is a tree in which every leaf node is labelled
with the cryptographic hash of a data block, and every non-leaf node is
labelled with the cryptographic hash of the labels of its child nodes.
Hash trees allow efficient and secure verification of the contents of large
data structures. Hash trees are a generalization of hash lists and hash
chains. used for data verification and synchronization. It is a tree data
structure where each non-leaf node is a hash of its child nodes. All the
leaf nodes are at the same depth and are as far left as possible. It
maintains data integrity and uses hash functions for this purpose.
Every leaf node is a hash of transactional data, and the non-leaf node
is a hash of its previous hashes. Merkle trees are in a binary tree, so it
requires an even number of leaf nodes. If there is an odd number of
transactions, the last hash will be duplicated once to create an even
number of leaf nodes.

Applications:

• Merkle trees are useful in distributed systems where same data


should exist in multiple places.
• Merkle trees can be used to check inconsistencies.
• Apache Cassandra uses Merkle trees to detect
inconsistencies between replicas of entire databases.
• It is used in bitcoin and blockchain.

Benefits:

Merkle trees have three benefits:

• It provides a means to maintain the integrity and validity of data.


• It helps in saving the memory or disk space as the proofs,
computationally easy and fast.

Their proofs and management require tiny amounts of information to


be transmitted across networks.
Code:
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(dat
a) elif data > self.data:
if self.right is None:
self.right =
Node(data)
else:
self.right.insert(dat
a) 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)
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.righ
t) 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.a ppend(
root) temp =
None
while(len(q)):
temp = q.pop(0)
if temp.data ==
key:
key_node =
temp if temp.left:
q.append(temp.lef
t) if temp.right:
q.append(temp.right
) if key_node :
x = temp.data
deleteDeepest(root,tem
p) key_node.data = x
return root
print("Binary
Tree:") root =
Node(27)
root.insert(14)
root.insert(35)
root.insert(10)
root.insert(19)
root.insert(31)
root.insert(42)
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:

Conclusion:
Hence, we have successfully implemented Binary Tree and showed all
operations (Insert, Delete, Traversals, Display).
Practical 5
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.

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 cryptoasset
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). The present
hypothesis is that the catchy Times headline enticed Satoshi Nakamoto
to release Bitcoin in public, but that he actually created the genesis block
earlier and altered the timestamp accordingly. After testing his software
from Jan. 3, 2009, Satoshi possibly deleted all the test blocks and used
the genesis block for his mainnet launch.

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

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


Code:
Steps / Code:

o Steps to install Go-Ethereum(Geth):


o Visit the Go Ethereum website and install Geth.
o Visit here: https://geth.ethereum.org/downloads/
o Download the latest release of Geth for Windows, make sure you
download the 64-bit version.

o Once your download is complete, open the installer and


click “I Agree”
o Follow all the installation steps.
Setting Path: If you do, then go to the installation path of geth and copy
the path of the folder. Then open up environment variables and add the
path to the “Path” section there.

Click OK. The installation of Geth is now done.


Steps to create a Genesis block and a private chain:

​ 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" :
"0x000000000000000000000000000000000000000000000
0000000000 000000000", "timestamp" : "0x00"
}

​ Now, we have to initialize our Ethereum Node. For that, open

the command prompt and change your current directory to


the Private Chain folder.
​ Intialize geth into chaindata: geth --datadir chaindata init

genesis.json.
​ run geth: geth --datadir=./chaindata/

​ Now minimize this and open up another command prompt.

​ IPC to interact with Geth: geth attach ipc:\\.\pipe\geth.ipc

In this command prompt you can execute geth commands


Output:
Create new account, check pre-existing accounts, check coinbase account hash
and balance:

1. Start mining:
2. Stop mining:

3. Check blockNumber:

Now for transaction, we need 2 accounts. One would be the coinbase


account and the other one would be the account which we would be
transferring to. After creating the new account, we need to unlock the
coinbase account as well.

Transaction:

Now to add the transaction to the blockchain, we need to start the


mining process again.
Check the information about the occurred transaction:

Check balance in terms of ether:

Get information about the latest block:


Get information about a specific block by entering its block number.

Conclusion:
Hence, we have successfully learned how to install Geth, create a genesis
block, private chain and commands to create user accounts, mine and
transact ethers among accounts.
Practical 6
Aim:
To implement the installation of Ganache, Metamask and Remix IDE and
deploy smart contract using injected web 3 environment.

Theory:
Ganache is used for setting up a personal Ethereum Blockchain for
testing your Solidity contracts. It provides more features when
compared to Remix. Ganache is a personal blockchain for rapid
Ethereum and Corda distributed application development. You can use
Ganache across the entire development cycle; enabling you to develop,
deploy, and test your dApps in a safe and deterministic environment.

On the other hand, Ganache is a high-end development tool used to run


your own local blockchain for both Ethereum and Corda dApp
development. Ganache is helpful in all parts of the development process.
The local chain allows you to develop, deploy and test your projects and
smart contracts in a deterministic and safe environment.

There are two different ”versions” of Ganache, one desktop application,


and one command-line tool. The desktop application is called Ganache
UI, and it supports development for both Ethereum and Corda;
meanwhile, the command-line tool is called ganache-CLI, which solely
supports Ethereum development.
Furthermore, all the different versions of Ganache are available for Mac,
Windows, and Linux.
Installation Steps:

Ganache:

1) Download Ganache from


https://www.trufflesuite.com/ganache

2) Install Ganache
The console in the above screenshot shows user accounts with balance
of 100 ETH (Ether - a currency for transaction on Ethereum platform).
It shows a transaction count of zero for each account. As the user has
not performed any transactions so far, this count is obviously zero.
Metamask: Installation:

MetaMask is a software cryptocurrency wallet used to interact with the


Ethereum blockchain. It allows users to access their Ethereum wallet
through a browser extension or mobile app, which can then be used to
interact with decentralized applications. MetaMask is developed by
ConsenSys Software Inc., a blockchain software company focusing on
Ethereum-based tools and infrastructure.

MetaMask allows users to store and manage account keys, broadcast


transactions, send and receive Ethereum-based cryptocurrencies and
tokens, and securely connect to decentralized applications through a
compatible web browser or the mobile app's built-in browser.

Step 1: Go to Chrome Web Store Extensions Section.

Step 2: Search MetaMask and click add to chrome

Step 3: Once installation is complete this page will be displayed. Click


on the Get Started button.
Step 5: This is the first time creating a wallet, so click the Create a
Wallet button. If there is already a wallet then import the already
created using the Import Wallet button.

Step 6: Click I Agree button to allow data to be collected to help


improve MetaMask or else click the No Thanks button. The wallet can
still be created even if the user will click on the No Thanks button.
Step 7: Create a password for your wallet. This password is to be
entered every time the browser is launched and wants to use MetaMask.
A new password needs to be created if chrome is uninstalled or if there is
a switching of browsers. In that case, go through the Import Wallet
button. This is because MetaMask stores the keys in the browser. Agree
to Terms of Use.

Step 8: Click on the dark area which says Click here to reveal secret
words to get your secret phrase.

Step 9: This is the most important step. Back up your secret phrase
properly. Do not store your secret phrase on your computer. Please read
everything on this screen until you understand it completely before
proceeding. The secret phrase is the only way to access your wallet if you
forget your password.
Once done click the Next button.
Step 10: Click the buttons respective to the order of the words in your
seed phrase. In other words, type the seed phrase using the button on
the screen. If done correctly the Confirm button should turn blue.
Step 11: Click the All Done button. Please follow the tips
mentioned.

Step 12: One can see the balance and copy the address of the account
by clicking on the Account 1 area.
Step 13: One can access MetaMask in the browser by clicking the
MetaMask extension icon on the top right.

Step 14: Adding Ganache Network to MetaMask.

● Click on the Networks Dropdown and Select Custom RPC.

● Fill the network details such as Network Name, RPC Url and Chain
Id and Save it.
Note: RPC url is mentioned on your ganache console as RPC Server.
Step 15: Importing Accounts.

To Import an account click on the circular icon at the top – right of


your MetaMask Extension and select Import accounts. Copy the
private key of your ganache account by clicking on key icon of
particular account.
You will need to copy the private key of your ganache account by
clicking on key icon of particular account.

- Click on import button once private key string is pasted.


- Once imported you can see it at your MetaMask extension as
Account 2.
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.

Step 1: Go to https://remix.ethereum.org/

As we use Solidity to write our smart contracts, .sol extension is used.

Let’s now create a new contract. For that, right-click on the workspace
and select New File. Name our file.
Step 2: Select your newly created file and type the following code.

Code:
pragma solidity ^0.4.2;
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
// Fetch Candidate
mapping(uint => Candidate) public candidates;

// Store Candidates Count uint


public candidatesCount;

// voted event event


votedEvent (
uint indexed _candidateId
);

function Election() public {


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

function addCandidate (string _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


votedEvent(_candidateId);
}
}

Step 3:

Click on the solidity compiler present on the left.

Select Auto-compile so our contract automatically compiles when we do


some changes.
Step 4:
Click on Deploy and Run Transactions Button.
Set Environment to “Injected Web3”.(Make sure you are
connected to website with Metamask).

Click on Deploy Button and you will see a pop up for confirmation.
Once confirm your contract is deployed.
After your contract is successfully deployed, you will able to see your
contract under the deployed contracts.

If you give the input as 1 in Candiates column , you will be to see the
details of our first candidate. In our case, the first candidate is Modi.

If you give the input as 1 in Candiates column , you will be to see the
details of our first candidate. In our case, the first candidate is Modi.

If you click on votes button with any account address as input you can
see whether the person has voted or not.
It gives the Boolean result meaning false as not voted and true as voted.

If you click on vote button with input as your candidates id for eg 1, a


pop up will appear to confirm the transaction.

Once confirmed the voted will be registered.

If you click on candidatesCount Button you will ge the count of total


candidates standing for election.

Conclusion:
Hence, we have successfully completed the installation of Ganache,
Metamask and Remix IDE and the deployed the smart contract and
shown its output.
Practical 7
Aim:
To study solidity and implement some examples with it.

Theory:
Solidity:

Solidity is an object-oriented, high-level language for implementing


smart contracts. Smart contracts are programs which govern the
behaviour of accounts within the Ethereum state.

Solidity is a curly-bracket language. It is influenced by C++, Python


and JavaScript, and is designed to target the Ethereum Virtual
Machine (EVM). You can find more details about which languages
Solidity has been inspired by in the language influences section.
Solidity is statically typed, supports inheritance, libraries and complex
user-defined types among other features. With Solidity you can create
contracts for uses such as voting, crowdfunding, blind auctions, and
multi- signature wallets.

When deploying contracts, you should use the latest released version of
Solidity. Apart from exceptional cases, only the latest version receives
security fixes. Furthermore, breaking changes as well as new features
are introduced regularly. We currently use a
0.y.z version number to indicate this fast pace of change.

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.
Q1. Write a program in solidity to create a structured
student with Roll no, Name,Class, Department,Course
enrolled as variables.

i) Add information of 5 students.


ii) ii)Search for a student using Roll no
iii) iii)Display all information
Code:

Students.sol
pragma solidity ^ 0.5 .0;

pragma experimental ABIEncoderV2;

contract students

struct Student

uint rn;

string name;

string class;

string department;

string course;

Student[] student;

uint count;

constructor() public

count = 0;
}

function addStudentInfo(uint rollNumber, string memory name, string memory


class, string memory dept, string memory course) public

student.push(Student(rollNumber, name, class, dept, course));

function getStudent(uint rollNumber) public view returns(uint, string memory)

uint i = 0;

for (i = 0; i < student.length; i++)

if (student[i].rn == rollNumber)

return (student[i].rn, student[i].name);

return (student[0].rn, student[0].name);

function displayAllInfo() public view returns(Student[] memory)

return student;

}}
Output:
- Deploy the code:

- Add student Information:


- Display all Students information:

- Get individual student:


2) 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:
pragma solidity ^ 0.8 .0;
pragma experimental ABIEncoderV2;
contract pract7b
{
struct Consumer {
uint units;
string name;
string addr;
uint consumerID;
uint amount;
}

Consumer[] consumer;

function addConsumerInfo(uint units, string memory name, string memory


addr,
uint consumerID) public{
consumer.push(Consumer(units, name, addr, consumerID, 0));
}

function getBillAmount() public {


uint i = 0;
uint amount = 0; uint
surcharge = 0; uint
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(uint consumerID) public view returns(uint,


string memory, string memory, uint, uint)
{
uint i = 0;
for (i = 0; i < consumer.length; i++)
{
if (consumer[i].consumerID == consumerID)
{
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:
- Deploy the Contract:
- Add Consumers:

- Click “getBillAmount” to calculate bill:

- Display individual consumer:

- Display all consumers:

Conclusion:
Hence, we have successfully studied solidity and implemented some
examples with it.
Practical 8
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.

− Built-in smart contract compilation, linking, deployment and


binary management.
− Automated contract testing for rapid development.
− Scriptable, extensible deployment & migrations framework.
− Network management for deploying to any number of public &
private networks.
− Package management with EthPM & NPM, using the
ERC190 standard.
− Interactive console for direct contract communication.
− Configurable build pipeline with support for tight
integration.
− 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.
Q1. ) Create a Bank Account contract and implement the
following services:

− Deposit
− Withdraw ( keep a condition that only the owner of the
contract can withdraw)
− Receive Ether
− Transfer Ether
− Check Balance
Code:
- FC1.sol
pragma solidity ^ 0.5 .0;
contract FC1
{
address owner;
constructor() public
{
owner = msg.sender;
}

modifier ifOwner()
{
if (owner != msg.sender)
{
revert();
}
else
{
_;
}
}

function receiveDeposit() payable public {}

function getbalance() public view returns(uint)


{
return address(this).balance;
}

function withdraw(uint funds) public ifOwner


{
msg.sender.transfer(funds); }}
Steps and Output:
1. Deploy the code

2. Enter value 3 ether and click on receiveDeposit


3. Click on getbalance

4. Withdraw some amount and check balance


Q2. Create a Smart contract to simulate function
overloading. Execute the contract using the truffle
framework.

Steps:
1. Go to cmd prompt:
$ mkdir blockchain-toolkit

$ cd blockchain-toolkit

$ truffle init

$ touch package.json

2. copy-and-pasting the below code into package.json file:


{
"name": "blockchain-toolkit",
"version": "1.0.0",
"description": "The Complete Blockchain Developer Toolkit for2019 & Beyond",
"main": "truffle-config.js",
"directories": {
"test": "test"
},
"scripts": {
"dev": "lite-server",
"test": "echo \"Error: no test specified\" && sexit 1"
},
"author": "gregory@dappuniversity.com",
"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"
}
}

3. Save package.json file

4. $ npm install

5. Update the project configuration file (Find the file truffle-


config.js and paste the following code:)
module.exports = { networks:
{
development:
{
host: "127.0.0.1",
port: 7545,
network_id: "*" // Match any network id
},
develop:
{
port: 8545
}
}
};
6. Open Ganache network.

7. Start developing a smart contract using solidity:


Code:
In contracts folder->overloading.sol
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;
}

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);

};
Outputs:
1. $ truffle compile

2. $ truffle migrate
3. $ truffle console
4. > overloading.deployed().then((instance) => {app = instance} )

5. > app.getSum(5,6)

6. > app.callSumWithTwoArguments()

7. > app.callSumWithThreeArguments()

Conclusion:
Hence, we have successfully executed the smart contract using truffle
framework.
Practical 9
Aim:
Create Daps using Solidity smart contract and web3.

Theory:
Solidity Smart Contracts:

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

Truffle is a development environment, testing framework and asset


pipeline for Ethereum, aiming to make life as an Ethereum developer
easier.

With Truffle, you get:

● Built-in smart contract compilation, linking, deployment and


binary management.
● Automated contract testing with Mocha and Chai.
● Configurable build pipeline with support for custom build
processes.
● Scriptable deployment & migrations framework.
● Network management for deploying to many public &
private networks.
● Interactive console for direct contract communication.
● Instant rebuilding of assets during development.
● 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.

Web3:

Web3 enhances the internet as we know it today with a few other added
characteristics. web3 is:

● Verifiable
● Trustless
● Self-governing
● Permissionless
● Distributed and robust
● Stateful
● Native built-in payments

In web3, developers don't usually build and deploy applications that run
on a single server or that store their data in a single database (usually
hosted on and manage by a single cloud provider). Instead, web3
applications either run on blockchains, decentralized networks of many
peer to peer nodes (servers), or a combination of the two that forms a
cryptoeconomic protocol.
These apps are often referred to as dapps (decentralized apps), and you
will see that term used often in the web3 space. To achieve a stable and
secure decentralized network, network participants (developers) are
incentivized and compete to provide the highest quality services to
anyone using the service.
Ethereum:

Ethereum is a blockchain platform with its own cryptocurrency, called


Ether (ETH) or Ethereum, and its own programming language, called
Solidity. As a blockchain network, Ethereum is a decentralized public
ledger for verifying and recording transactions. The network's users can
create, publish, monetize, and use applications on the platform, and use
its Ether cryptocurrency as payment. Insiders call the decentralized
applications on the network "dApps."
Q.1. Voting Process:

Code:
- Election.sol
pragma solidity 0.4.25;
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 // Fetch Candidate
mapping(uint => Candidate) public candidates;
// Store Candidates Count
uint public candidatesCount;
// voted event
event votedEvent (uint indexed _candidateId);
constructor () public {
addCandidate("Candidate 1");
addCandidate("Candidate 2");
}
function addCandidate (string _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);
}}
- index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Election Results</title>

<!-- Bootstrap -->


<link href="css/bootstrap.min.css" rel="stylesheet">
</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>
<button type="submit" class="btn btn-primary">Vote</button>
<hr />
</form>
<p id="accountAddress" class="text-center"></p>
</div>
</div>
</div>
</div>

<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"><
/script>
<!-- Include all compiled plugins (below), or include individual files as needed
-->
<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>

- app.js

App = {
web3Provider: null,
contracts: {},
account: '0x0',
hasVoted: false,
init: function() {
return App.initWeb3();
},
initWeb3: function() {
// TODO: refactor conditional if
(typeof web3 !== 'undefined') {
// If a web3 instance is already provided by Meta Mask. App.web3Provider =
web3.currentProvider;
web3 = new Web3(web3.currentProvider);
} else {
// Specify default instance if no web3 instance provided App.web3Provider =
new
Web3.providers.HttpProvider('http://localhost:7545'); web3
= new Web3(App.web3Provider);
}
return App.initContract();
},
initContract: function() {
$.getJSON("Election.json", function(election) {
// Instantiate a new truffle contract from the artifact App.contracts.Election =
TruffleContract(election);
// Connect provider to interact with contract
App.contracts.Election.setProvider(App.web3Provider); App.listenForEvents();
return App.render();
});
},
// Listen for events emitted from the contract
listenForEvents: function() {
App.contracts.Election.deployed().then(function(instance) {
// Restart Chrome if you are unable to receive this event
// This is a known issue with Metamask
// https://github.com/MetaMask/metamask-extension/issues/2393
instance.votedEvent({}, {
fromBlock: 0,
toBlock: 'latest'
}).watch(function(error, event) {
console.log("event triggered", event)
// Reload when a new vote is recorded App.render();
});
});
},
render: function() {
var electionInstance;
var loader = $("#loader");
var content = $("#content");
loader.show();
content.hide();
// Load account data web3.eth.getCoinbase(function(err,
account) {
if (err === null) {
App.account = account;
$("#accountAddress").html("Your Account: " + account);
}
});
// Load contract data App.contracts.Election.deployed().then(function(instance)
{
electionInstance = instance;
return electionInstance.candidatesCount();
}).then(function(candidatesCount) {
var candidatesResults = $("#candidatesResults"); candidatesResults.empty();
var candidatesSelect = $('#candidatesSelect');
candidatesSelect.empty();
for (var i = 1; i <= candidatesCount; i++) {
electionInstance.candidates(i).then(function(candidate) {
var id = candidate[0];
var name = candidate[1];
var voteCount = candidate[2];
// Render candidate Result
var candidateTemplate = "<tr><th>" + id + "</th><td>" + name +
"</td><td>" + voteCount + "</td></tr>"
candidatesResults.append(candidateTemplate);
// Render candidate ballot option
var candidateOption = "<option value='" + id + "' >" + name + "</
option>"
candidatesSelect.append(candidateOption);
});
}
return electionInstance.voters(App.account);
}).then(function(hasVoted) {
// Do not allow a user to vote if(hasVoted)
{
$('form').hide();
}
loader.hide();
content.show();
}).catch(function(error) {
console.warn(error);
});
},
castVote: function() {
var candidateId = $('#candidatesSelect').val();
App.contracts.Election.deployed().then(function(instance) {
return instance.vote(candidateId, { from: App.account });
}).then(function(result) {
// Wait for votes to update
$("#content").hide();
$("#loader").show();
}).catch(function(err) {
console.error(err);
});
}
};
$(function() {
$(window).load(function() {
App.init();
});
});
- 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
}
},
compilers: {
solc: {
version: '0.4.25',
optimizer: {
enabled: true,
runs: 200
}
}
}
};

- bs-config.js

{
"server": {
"baseDir": ["./src", "./build/contracts"]
}
}

- package.json

{
"name": "election",
"version": "1.0.0",
"description": "",
"main": "truffle.js",
"directories": {
"test": "test"
},
"scripts": {
"dev": "lite-server",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"lite-server": "^2.3.0",
"truffle": "5.0.0-beta.0"
}
}

- 2_deploy_contracts.js

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

module.exports = function(deployer) {
deployer.deploy(Election);
};
Output:
Q.2. Supply Chain Management:

Code:
- AssetTracker.sol
pragma solidity ^0.5.0;
contract AssetTracker {
struct Asset {
string name;
string description;
address manufacturer;
bool initialized;
}
struct tracking {
address location;
string uuid;
}
mapping(string => tracking) locations;
mapping(string => Asset) private assetStore;
event AssetCreate(address manufacturer, string uuid, address location); event
AssetTransfer(address from, address to, string uuid);
function createAsset(string memory name, string memory description, string
memory uuid) public {
require(!assetStore[uuid].initialized, "Asset With This UUID Already
Exists");
assetStore[uuid] = Asset(name, description, msg.sender,true); locations[uuid] =
tracking(msg.sender, uuid);
emit AssetCreate(msg.sender, uuid, msg.sender);
}
function transferAsset(address to, string memory uuid) public {
require(locations[uuid].location==msg.sender, "You are Not
Authorized to Transfer This Asset");
locations[uuid]= tracking(to, uuid);
emit AssetTransfer(msg.sender, to, uuid);
}
function getAssetLocation2()public view returns (bool) {
return false;
}
function getAssetDetails(string memory uuid)public view returns (string memory,string
memory,address) {
return (assetStore[uuid].name, assetStore[uuid].description,
assetStore[uuid].manufacturer);
}
function getAssetLocation(string memory uuid)public view returns (address) {
return (locations[uuid].location); }}
- index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Supplychain Tracking Dapp</title>
</head>
<body>
<div id="band"></div>
<h2>Supplychain Tracking System</h2>
</br>
<div style="text-align: center;">
<label><b>Create Asset:</b></label>
<form id='createAsset' onSubmit="App.createAsset(); return false;" >
<input type="text" id="assetName" placeholder=" Asset Name" required
/>
<input type="text" id="assetDescription" placeholder="Description"
required />
<input type="number" id="assetUuid" placeholder="UUID" required />
<button id='createAsset' type="submit" class="registerbtn">Create Asset</button>
</form>
</div>

<div style="text-align: center;">


<label><b>Transfer Asset:</b></label>
<form id='transferAsset' onSubmit="App.transferAsset(); return false;" >
<input type="text" id="address" placeholder="To address" required />
<input type="number" id="Uuid" placeholder="UUID" required />
<button id='transferAsset' type="submit" class="registerbtn">Transfer
Asset</button>
</form>
</div>

<div style="text-align: center;">


<label><b>Track Asset Details:</b></label>
<form id='getAssetDetails' onSubmit="App.getAssetDetails(); return false;"
>
<input type="number" id="trackUuid" placeholder="UUID" required />
<button id='trackasset' type="submit" class="registerbtn">Track
Asset</button>
</form>
</div>
</br>

<div id = "response" style="text-align: center;">


<p><b>Name:</b><span id="name">??</span></p>
<p><b>Description:</b><span id="description">??</span></p>
<p><b>Manufacturer:</b><span id="manufacturer">??</span></p>
<p><b>Current Location:</b><span id="location">??</span></p>
</div>

<div id="log" style="text-align: center;"></div>

<link rel="stylesheet" href="index.css">


<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<link href="vendor/bootstrap/dist/css/bootstrap.min.css"
rel="stylesheet">
<script
src="https://cdn.jsdelivr.net/npm/@truffle/contract@4.3.5/dist/truffle-
contract.js"></script>
<script src= "app.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"><
/script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/web3/1.6.1/web3.min.js"
integrity="sha512-
5erpERW8MxcHDF7Xea9eBQPiRtxbse70pFcaHJuOhdEBQeAxGQjUwgJbuB
DWve+xP/u5IoJbKjyJk50qCnMD7A==" crossorigin="anonymous"
referrerpolicy="no-referrer"></script>
</body>
</html>
- index.css
#band {
width: 100%;
height: 15px;
margin-bottom: 50px;}
img {
display: block;
margin-left: auto;
margin-right: auto;
width: 40%;
border: 1px solid green;}
h3,h2,h4 {
font-family: sans-serif;
margin: 0;
color: green;
text-align: center;}
button {
width: 10%;
background-color: #4caf50;
color: white;
padding: 10px 8px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;}
input[type="text"],input[type="number"] {
padding: 12px 20px;
margin: 8px 0; display:
inline-block; border: 1px
solid #ccc;
border-radius: 4px;
box-sizing: border-box;}
button:active {
background-color: rgb(0, 81, 125);}
button:hover {
opacity: 0.7;}
- app.js
console.log(web3.version);
function log(message) {
$('#log').append($('<p>').text(message));
$('#log').scrollTop($('#log').prop('scrollHeight'));
}
function error(message) {
$('#log').append($('<p>').addClass('dark-red').text(message));
$('#log').scrollTop($('#log').prop('scrollHeight'));
}
function waitForReceipt(hash, cb) {
web3.eth.getTransactionReceipt(hash, function (err, receipt) {
if (err) {
error(err);
}
if (receipt !== null) {
// Transaction went through
if (cb) {
cb(receipt);
}
} else {
// Try again in 1 second
window.setTimeout(function () {
waitForReceipt(hash, cb);
}, 1000);
}
});
}
App = {
loading: false,
contracts: {},

load: async () => { await


App.loadWeb3()
await App.loadAccount()
await App.loadContract()
await App.render()
},
loadWeb3: async () => {
if (typeof web3 !== 'undefined') {
App.web3Provider = web3.currentProvider
web3 = new Web3(web3.currentProvider)
} else {
window.alert("Please connect to Metamask.")
}
if (window.ethereum) {
window.web3 = new Web3(ethereum)
try {
await ethereum.enable()
web3.eth.sendTransaction({/* ... */})
} catch (error) {
}
}
else if (window.web3) {
App.web3Provider = web3.currentProvider
window.web3 = new Web3(web3.currentProvider)
web3.eth.sendTransaction({/* ... */})
}
else {
console.log('Non-Ethereum browser detected. You should consider trying
MetaMask!')
}
},

loadAccount: async () => {


// Set the current blockchain account
//App.account = await web3.eth.accounts[0]; var
accounts = await web3.eth.getAccounts();
App.account= accounts[0];
console.log(App.account);
},

loadContract: async () => {


// Create a JavaScript version of the smart contract
const AssetTracker = await $.getJSON('AssetTracker.json') App.contracts.AssetTracker
= TruffleContract(AssetTracker)
App.contracts.AssetTracker.setProvider(App.web3Provider)
// Hydrate the smart contract with values from the blockchain
App.AssetTracker = await App.contracts.AssetTracker.deployed()
},

render: async () => {


// Prevent double render
if (App.loading) {
return
}

// Update app loading state


App.setLoading(true)

// Render Account
// $('#account').html(App.account)

// Render Tasks

// Update loading state


App.setLoading(false)
},
transferAsset:async()=>{

await
App.AssetTracker.transferAsset(document.getElementById("address").value,
document.getElementById("Uuid").value,{from:App.account}).then(function
(err, result4) {
if (err) {
return error(err);
}
// The return value is a BigNumber object
console.log(result4);
});
console.log("shruti nft1");

},
createAsset:async()=>{
console.log(document.getElementById("assetName").value,document.get
ElementById("assetDescription").value,document.getElementById("assetUuid
").value);
await
App.AssetTracker.createAsset(document.getElementById("assetName").value
,document.getElementById("assetDescription").value,document.getElementB
yId("assetUuid").value,{from:App.account}).then(function (x) {
console.log(x);
// document.getElementById("location").innerHTML = result4;
});
console.log("shruti nft1");
},
getAssetDetails:async()=>{ console.log(document.getElementById("trackUuid").value);
const rs3= await App.AssetTracker.getAssetLocation2({from:App.account});
console.log(rs3);
const res = await
App.AssetTracker.getAssetDetails(document.getElementById("trackUuid").val
ue,{from:App.account});
console.log(res);
await
App.AssetTracker.getAssetDetails(document.getElementById("trackUuid").val
ue,{from:App.account}).then(function(x) {
console.log(x);
// The return value is a BigNumber object
// document.getElementById("location").innerHTML = result4;
document.getElementById("name").innerHTML = x[0];
document.getElementById("description").innerHTML = x[1];
document.getElementById("manufacturer").innerHTML = x[2];
// document.getElementById("location").innerHTML = result4;
});
await
App.AssetTracker.getAssetLocation(document.getElementById("trackUuid").v
alue,{from:App.account}).then(function(x) {
console.log(x);

document.getElementById("location").innerHTML = x;
});
console.log("shruti nft1");
},
setLoading: (boolean) => {
App.loading = boolean
const loader = $('#loader')
const content = $('#content')
if (boolean) {
loader.show()
content.hide()
} else {
loader.hide()
content.show()
}
}
}

$(() => {
$(window).load(() => {
App.load()
})
})
- truffle-config.js
module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*" // Match any network id
}
},
compilers: {
solc: {
version: '0.4.25',
optimizer: {
enabled: true,
runs: 200
}
}
}
};

- bs-config.js
{
"server": {
"baseDir": [
"./src",
"./build/contracts"
],
"routes": {
"/vendor": "./node_modules"
}
}
}

- package.json
{
"name": "election",
"version": "1.0.0",
"description": "",
"main": "truffle.js",
"directories": {
"test": "test"
},
"scripts": {
"dev": "lite-server",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"lite-server": "^2.3.0",
"truffle": "5.0.0-beta.0"
}
}
- 2_deploy_contracts.js
const AssetTracker = artifacts.require("AssetTracker");
module.exports = function (deployer) {
deployer.deploy(AssetTracker);
};
Output:

Creating an asset
Click confirm

Tracking the asset


Now if we transfer the asset to a different address

And then track the asset the current location is updated

Conclusion:
We successfully created Daps for voting and Supply chain management.
Mini – Project
Team Members:
1. Name: Prathamesh Indulkar
Roll No.: 22
2. Name: Shruti Naik
Roll No.: 40

Introduction:
A decentralized online marketplace is an eCommerce platform operated
on a blockchain.

These are the distinguishing characteristics:

● No middleman controls the trade between buyers and


sellers
● The terms of trade are determined by buyers and sellers, and
no middlemen intervene
● The terms of trade are open, transparent, and immutable
● No tampering of transactions is possible
● Payment between buyers and sellers is direct, no
intermediary has any role to play
● Transactions require no third-party payment system
● Transactions are instantaneous, without depending on a
third-party
● It‘s a permanent marketplace that can‘t be destroyed
● No personal sensitive data is needed

Existing System:
E-commerce provides tremendous benefits to traditional brick and
mortar stores by allowing businesses to exponentially expand their
reach and reach a much larger market. However, with such
convenience comes a cost; this cost is paid to the third party, which
essentially acts as insurance in mediating the
payment. eBay, Amazon, Ali Baba, and other well-known centralized
e-commerce platforms are examples. The issue with these e-commerce
websites is that they charge exorbitant fees. Furthermore, because the
dispute process is painfully slow, it could take weeks or even months to
get your money back when a dispute arises.

Proposed System:
Marketplace is not a fee-based intermediary platform for buyers and
sellers; it simply provides them with a client. Sellers create a listing on
the Marketplace, and other Marketplace buyer can view and buy it.
Payments are only made in Ether. Once a product is sold it cannot be
sold again.

Technologies/Software Used:

▪ Node.js:
This is used to install all the packages required for the project and
also to handle the client-side of the project

▪ Truffle Suite:

It is framework for creating Ethereum smart contracts using


solidity programming language write test against them and deploy
them to a blockchain

▪ Ganache:

It is blockchain used for this project where you and use it without
paying any thing for it.

▪ MetaMask:

It is an Ethereum Wallet that turns our browser into a blockchain


browser because most of the do not support blockchain out of the
box.

▪ React:

React is a JavaScript library for building user interfaces. React is


used to build single-page applications. React allows us to create
reusable UI components.
Code:
Marketplace.sol:
pragma solidity ^0.5.0;

// contract that handles the entire business logic (buying and selling)
contract Marketplace {
// state variable
string public name;

uint256 public productCount = 0;


mapping(uint256 => Product) public products;

struct Product {
uint256 id;
string name;
uint256 price;
address payable owner;
// owner - person who owns the product when the product is
// sold the owner gets changed to new buyer
bool purchased; //to check if the product is already purchased or not
}

event ProductCreated(
uint256 id,
string name,
uint256 price,
address payable owner,
bool purchased
);

event ProductPurchased(
uint256 id,
string name,
uint256 price,
address payable owner,
bool purchased
);

// constructor gets run 1 time only


constructor() public {
name = "Shruti Prathamesh Marketplace";
}
function createProduct(string memory _name, uint256 _price) public {
//making sure all parameters are correct
// require valid name
require(bytes(_name).length > 0);
// require valid price
require(_price > 0);

//increase product count


productCount++;
//create product
products[productCount] = Product(
productCount,
_name,
_price,
msg.sender,
false
);
//trigger event - to tell blockchain something happened
emit ProductCreated(productCount, _name, _price, msg.sender, false);
}

// payable is a modifier
function purchaseProduct(uint256 _id) public payable {
// fetch product
Product memory _product = products[_id];
// fetch owner
address payable _seller = _product.owner;

// make sure product is valid


// 1. product has valid id
require(_product.id > 0 && _product.id <=
productCount);
// 2. required that there is enough ether
intransaction require(msg.value >=
_product.price);
false)
// 3. product should not be already purchased
(purchased should be

require(!_product.purchased);
// 4. required that
buyer is not seller
require(_seller !=
msg.sender);

// transfer ownership to buyer


_product.owner = msg.sender;
// mark as purchase
_product.purchased = true; // update product
products[_id] = _product;

// pay the seller by sending ether


address(_seller).transfer(msg.value);

// trigger an event
emit ProductPurchased( productCount,
_product.name,
_product.price,
msg.sender, true
);
}
}

2_deploy_contracts.js:
const Marketplace = artifacts.require("Marketplace");

module.exports = function(deployer) {
deployer.deploy(Marketplace);
};
Marketplace.test.js:

const { assert } = require('chai')


const Marketplace = artifacts.require('./Marketplace.sol')
require('chai').use(require('chai-as-promised')).should()
contract('Marketplace', ([deployer, seller, buyer])=>{
let marketplace
before(async ()=>{
marketplace = await Marketplace.deployed()
})
describe('deployment', async()=>{ it('deploys
successfully', async()=>{
const address = await marketplace.address
assert.notEqual(address, 0x0)
assert.notEqual(address, '')
assert.notEqual(address, null)
assert.notEqual(address, undefined)
})

it('has a name', async()=>{


const name = await marketplace.name() assert.equal(name,
'Shruti Prathamesh Marketplace')
})
})

describe('products', async()=>{ let


result, productCount
before(async ()=>{
// web3.utils.toWei('2', 'Ether'
result = await marketplace.createProduct('Pixel 6', web3.utils.toWei('1',
'Ether'), { from: seller})
productCount = await marketplace.productCount()
})

// creating products it('creates


products', async()=>{
// success assert.equal(productCount,
1)
// console.log(result.logs)
const event = result.logs[0].args
assert.equal(event.id.toNumber(), productCount.toNumber(), 'id is Correct')
assert.equal(event.name , 'Pixel 6' , 'name is correct')
assert.equal(event.price , '1000000000000000000' , 'price is correct')
assert.equal(event.owner , seller , 'owner is correct')
assert.equal(event.purchased , false , 'purchased is correct')
// failed
// 1. product name wrong
await await marketplace.createProduct('', web3.utils.toWei('1', 'Ether'), { from:
seller}).should.be.rejected;
// 2. product price wrong
await await marketplace.createProduct('Pixel 6 ', 0 , { from:
seller}).should.be.rejected;
})

// listing our products it('lists


products', async()=>{
const product = await marketplace.products(productCount)

assert.equal(product.id.toNumber(), productCount.toNumber(), 'id is


Correct')
assert.equal(product.name , 'Pixel 6' , 'name is correct')
assert.equal(product.price , '1000000000000000000' , 'price is correct')
assert.equal(product.owner , seller , 'owner is correct')
assert.equal(product.purchased , false , 'purchased is correct')
})

// selling product
it('sells product', async()=>{

// track sellers balance before purchase


let oldSellerBalance
oldSellerBalance = await web3.eth.getBalance(seller)
oldSellerBalance = new web3.utils.BN(oldSellerBalance)

// success: buyer makes purchase


result = await marketplace.purchaseProduct(productCount, {from: buyer,
value: web3.utils.toWei('1', 'Ether')});
// checking logs
const event = result.logs[0].args
assert.equal(event.id.toNumber(), productCount.toNumber(), 'id is Correct')
assert.equal(event.name , 'Pixel 6' , 'name is correct')
assert.equal(event.price , '1000000000000000000' , 'price is correct')
assert.equal(event.owner , buyer , 'owner is correct') assert.equal(event.purchased ,
true , 'purchased is correct')

// checking seller receives funds


let newSellerBalance
newSellerBalance = await web3.eth.getBalance(seller) newSellerBalance =
new web3.utils.BN(newSellerBalance)
let price
price = web3.utils.toWei('1', 'Ether')
price = new web3.utils.BN(price)

// console.log(newSellerBalance)
// console.log(oldSellerBalance)
// console.log(price);

const expectedBalance = oldSellerBalance.add(price)


// let x = expectedBalance.toString()
// console.log(x);
assert.equal(newSellerBalance.toString(), expectedBalance.toString())

// failed
// 1. trying to buy product that does not exist (product should have a
valid id)
await marketplace.purchaseProduct(99, { from: buyer, value:
web3.utils.toWei('1', 'Ether') }).should.be.rejected;
// 2. buyer tries to buy without enough ethers
await marketplace.purchaseProduct(productCount, { from: buyer, value:
web3.utils.toWei('0.5', 'Ether') }).should.be.rejected;
// 3. deployer tries to buy the product, i.e product cant be purchased twice
(fake product)
await marketplace.purchaseProduct(productCount, { from: deployer, value:
web3.utils.toWei('1', 'Ether') }).should.be.rejected;
// 4. buyer tries to buy again, i.e buyer cant be the seller
await marketplace.purchaseProduct(productCount, { from: buyer, value:
web3.utils.toWei('1', 'Ether') }).should.be.rejected;

})
})
})
Client Side:

App.js:
import React, { Component } from 'react';
import Web3 from 'web3';
import logo from '../logo.png'; import
'./App.css';
import Navbar from './Navbar';
import Main from './Main'
import Marketplace from '../abis/Marketplace.json'

class App extends Component {

// lifecycle component - anytime the component gets called this function will be
executed first
async componentWillMount(){ await
this.loadWeb3()
// console.log(window.web3); await
this.loadBlockchainData()
}

async loadWeb3(){
if (window.ethereum) {
window.web3 = new Web3(window.ethereum); await
window.ethereum.enable();
}
else if (window.web3) {
window.web3 = new Web3(window.web3.currentProvider);
}
else {
window.alert('Non-Ethereum browser detected. You should consider trying
MetaMask!');
}
}

async loadBlockchainData(){
const web3 = window.web3
// load acct
const accounts = await web3.eth.getAccounts()
// console.log(accounts);
this.setState({account: accounts[0]})
// console.log(Marketplace.abi, Marketplace.networks[5777].address);
const networkId = await web3.eth.net.getId()
// console.log(networkId);
const networkData = Marketplace.networks[networkId]
if(networkData){
// const abi = Marketplace.abi
// const address = Marketplace.networks[networkId].address
// const marketplace = new web3.eth.Contract(abi, address)
// console.log(marketplace);
const marketplace = new web3.eth.Contract(Marketplace.abi,
networkData.address)
// console.log(marketplace);
this.setState({ marketplace })
const productCount = await marketplace.methods.productCount().call()
// console.log(productCount);
this.setState({productCount})
// fetching products
for(var i = 1; i<= productCount; i++)
{
const product = await marketplace.methods.products(i).call() this.setState({
products: [...this.state.products, product]
})
}
this.setState({ loading: false })
// console.log(this.state.products);
}
else{
window.alert("Marketplace Contract not deployed to detected network")
}
}

constructor(props){
super(props)
this.state = {
account: '',
productCount: 0,
products: [], loading:
true
}
this.createProduct = this.createProduct.bind(this)
this.purchaseProduct = this.purchaseProduct.bind(this)
}
createProduct(name, price){
this.setState({ loading : true })
this.state.marketplace.methods.createProduct(name, price).send({ from:
this.state.account })
.once('receipt', (receipt) => {
this.setState({loading: false})
})
}
purchaseProduct(id, price){
this.setState({loading: true})
this.state.marketplace.methods.purchaseProduct(id).send({from:
this.state.account, value: price})
.once('receipt', (receipt)=>{
this.setState({loading: false})
})
}
render() {
return (
<div>
<Navbar account={this.state.account}/>
<div className="container-fluid mt-5">
<div className="row">
<main role="main" className="col-lg-12 d-flex justify-content- center
text-center">
{ this.state.loading
? <div id="loader" className="text-center"><p className="text-
center">Loading ..</p></div>
: <Main
products = {this.state.products}
createProduct = {this.createProduct }
purchaseProduct = {this.purchaseProduct }
/>
}
</main>
</div>
</div>
</div>
);
}}
export default App;

Navbar.js:
import React, { Component } from 'react';

class Navbar extends Component {


render() {
return (
<nav className="navbar navbar-dark fixed-top bg-dark flex-md- nowrap p-0
shadow">
<a
className="navbar-brand col-sm-3 col-md-2 mr-0"
href="http://localhost:3000/"
rel="noopener noreferrer"
>
Marketplace
</a>
<ul className="navbar-nav px-3">
<li className="nav-item text-nowrap d-none d-sm-none d-sm-
block">
<small className="text-white"><span
id="account">{this.props.account}</span></small>
</li>
</ul>
</nav>
);
}
}

export default Navbar;


Main.js:
import React, { Component } from 'react';
class Main extends Component {
render() {
return (
<div id="content">
<h1>Add Products</h1>

<form onSubmit = { (event) => {


event.preventDefault()
const name = this.productName.value
const price = window.web3.utils.toWei(this.productPrice.value.toString(),
'Ether')
this.props.createProduct(name, price)
} }>
<div className="form-group mr-sm-2">
<input
id="productName"
type="text"
ref = { (input)=> { this.productName = input} }
className="form-control"
placeholder="Product Name"
required />
</div>
<div className="form-group mr-sm-2">
<input
id="productPrice"
type="text"
ref = { (input)=> { this.productPrice = input} }
className="form-control"
placeholder="Product Price"
required />
</div>
<button type="submit" className="btn btn-primary">Add Product</button>
</form>
<p> </p>
<h2>Buy Product</h2>
<table className="table">
<thead>
<tr>
<th scope="col">Sr.No</th>
<th scope="col">Name</th>
<th scope="col">Price</th>
<th scope="col">Owner</th>
<th scope="col"></th>
</tr>
</thead>
<tbody id="productList">
{ this.props.products.map((product,key)=>{
return(
<tr key={key}>
<th scope="row">{product.id.toString()}</th>
<td>{product.name}</td>
<td>{window.web3.utils.fromWei(product.price.toString(),
'Ether')} Eth</td> <td>{product.owner}</td>
<td>
{
!product.purchased
?
<button
name={product.id}
value={product.price}
onClick={(event)=>{
// console.log('Clicked');
this.props.purchaseProduct(event.target.name, event.target.value)
}}
>
Buy
</button>
: <strong>Already Purchased</strong>
}
</td>
</tr>
)
})}

</tbody>
</table>
</div>
);
}
}
export default Main;
Output:
1. truffle compile:

2. Open Ganache and start a new Workspace

3. truffle test:
4. truffle migrate:
Run the server to open frontend:
npm run start:

On Chrome: Through Sellers Account

Add Product:
Click Confirm

Product added:
Add 2 more products

Change Metamask account to Buyers:


On Chrome: Through Buyers Account
Buy Pixel 6: Owner address changes to Buyers and cannot be purchased
again
Sellers Metamask Account Buyers Metamask Account
Balance Balance

Owner trying to buy the product: Failure

Conclusion:
We have successfully created Marketplace using Blockchain.

You might also like