100% found this document useful (1 vote)
139 views86 pages

Internship Report

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
100% found this document useful (1 vote)
139 views86 pages

Internship Report

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/ 86

Internship on Blockchain technology and Web Technology

CHAPTER 1
BLOCKCHAIN TECHNOLOGY

1.1 Introduction, History, Basic terminologies and Pre-requisites of


blockchain technology
Introduction to Blockchain technology
Blockchain is an emerging technology platform for developing decentralized applications and
data storage, over and beyond its role as the technology underlying the cryptocurrencies. The
basic tenet of this platform is that it allows one to create a distributed and replicated ledger of
events, transactions, and data generated through various IT processes with strong cryptographic
guarantees of tamper resistance, immutability, and verifiability. Public blockchain platforms
allow us to guarantee these properties with overwhelming probabilities even when untrusted
users are participants of distributed applications with ability to transact on the platform. Even
though, blockchain technology has become popularly known because of its use in the
implementation of Cryptocurrencies such as Bit Coin, Ethereum, etc., the technology itself
holds much more promise in various areas such as time stamping, logging of critical events in
a system, recording of transactions, trustworthy e-governance etc. Many researchers are
working on many such use cases such as decentralized public key infrastructure, self-sovereign
identity management, registry maintenance, health record management, decentralized
authentication, decentralized DNS, etc. Also, corporations such as IBM and Microsoft are
developing their own applications in diverse fields such as the Internet of Things (IoT), etc.,
even enabling blockchain platforms on the cloud. Considering the need to disseminate the
emerging concepts for students, we decided to prepare a new course on blockchain technology
platforms and applications.

History of Blockchain technology

A blockchain was created by a person named Satoshi Nakamoto in 2008 to serve as the
public distributed ledger for bitcoin cryptocurrency transactions, based on previous work
by Stuart Haber, W. Scott Stornetta and Dave Bayer.

1
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Basic terminologies of Blockchain technology


1 Transparency: All transactions can be transparently viewed by downloading and
inspecting them or by using blockchain explorers that allow anyone to see transactions
occurring live.

2 Privacy: Technologies that embed fundamental data protection principles by minimizing


personal data use, maximizing data security.

3 Immutable: The ability of a blockchain ledger to remain unchanged, unaltered and


memorable.

4 Peer to peer: The direct exchange of an asset, such as virtual currency, between individual
parties without the involvement of a central authority.

5 Distributed ledger technology: Digital system for recording the transaction of assets
in which the transactions and their details are recorded in multiple places at the same time.

Pre-requisites of block chain technology


1 Network: Peer to peer computer network for use as a public distributed ledger, where nodes
collectively adhere to a consensus algorithm protocol to add and validate new transaction
blocks.

Types of computing system+


1 Centralized computing system:

In the blockchain, the concept of centralization refers to a system whereby all the
planning, decision making and action taking activities are controlled by a particular or single
authority or platform.

2 Distributed computing system:

Distributed computing is merely a network where different computers come together to


form one system.

3 Decentralized computing system:

A decentralized ledger of transactions that uses peer-to-peer network and a consensus


algorithm to verify transactions and maintain a distributed ledger.

2
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

2 Security: Each new block connects to all the blocks before it in a cryptographic chain in
such a way that it’s nearly impossible to tamper with. All transactions within the blocks are
validated and agreed upon by a consensus mechanism, ensuring that each transaction is true
and correct and cannot be tampered.

Encryption: This is used to protect data from being stolen, changed or compromised and
works by scrambling data into a secret code that can only be unlocked with a unique digital
key.

In encryption we have two types of keys:

1 Private key: A private key is a cryptographic variable that is used in conjunction with an
algorithm to encrypt and decrypt data. Private keys should be shared only with key’s generator
or parties authorized to decrypt the data.

2 Public key: Public key cryptography is a method of encrypting or signing data with two
different keys and making one of the keys, the public key, available for any-one to use.

1.2 Hash, Block and Blockchain

Hash

Hash is deterministic hexadecimal number. Bitcoin’s hashes are always 64 digits.

Fig 1.2.1 Hash value of some data

3
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Properties of Hash
1 Same data have same hash value, different data have different hash value.

2 The length of the hash is fixed.

Block
Blocks are files stored by a blockchain, where transaction data are permanently recorded. A
block records some or all of the most recent transactions not yet validated by the network. Once
the data are validated, the block is closed. Then, a new block is created for new transactions to
be entered into and validated.

Fig 1.2.2 A single block

Blockchain

Blockchain is a shared, immutable ledger that facilitates the process of recording transactions
and tracking assets in a business network.

An asset can be tangible (a house, car, cash, land) or intangible (intellectual property, patents,
copyrights, branding). Virtually anything of value can be tracked and traded on a blockchain
network, reducing risk and cutting costs for all involved.

4
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Fig 1.2.3 Blocks connected to blockchain

Fig 1.2.4 Hash value of block changed

5
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

1.3 Types and components of blockchain technology


Types of blockchain
1 Public block chain: A public blockchain is a non-restrictive, permission-less distributed
ledger system. A node or user which is a part of the public blockchain is authorized to access
current and past records, verify transactions or do proof-of-work for an incoming block and do
mining.

2 Private block chain: Private blockchains control who is allowed to participate in the
network. The owner or operator has the right to override, edit, or delete the necessary entries
on the blockchain as required or as they see fit or make changes to the programming.

3 Hybrid block chain: It is the combination of public and private block chains.

4 Consortium block chain: Consortium blockchains are managed and run by a number
of organizations or entities. As a permissioned blockchain, users must be asked to join and
have authorization before they can access the network.

Components of blockchain technology


1 Node: A blockchain node is a crucial part of a blockchain network, responsible for
maintaining the distributed ledger by processing transactions and validating new blocks. These
nodes are unique and identified through a unique identifier attached to them.

2 Peer-to-peer Network: Peer-to-peer technology is a critical component of blockchain’s


decentralized architecture, which enables participants to interact with each other and conduct
transactions without intermediaries or centralized authorities.

3 Public ledger: A public ledger is a digital record of transactions and data stored in a
distributed manner across several computers globally (decentralized). This ledger is a chain of
blocks, with each block containing a list of transactions.

4 Transactions: A blockchain transaction is nothing more than data transmission across a


blockchain system's network of computers.

5 Cryptocurrency: Cryptocurrencies run on a distributed public ledger called blockchain, a


record of all transactions updated and held by currency holders.

6
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Types of nodes
1 Full node: Full Nodes are the most essential type of node in the Blockchain network. These
nodes are able to independently verify the entire Blockchain history since they download and
store copies of every transaction and block that occurs on the network.

2 Light weight nodes: Light Nodes are a more lightweight variation of Full Nodes,
sometimes referred to as SPV (Simplified Payment Verification) nodes. They are designed to
operate on mobile devices such as smartphones and tablets with limited storage and processing
power.

3 Miner nodes: Miner Nodes are responsible for validating transactions and generating new
blocks on the Blockchain. These nodes execute complex calculations to solve mathematical
problems, allowing them to create new blocks and receive rewards in the form of
cryptocurrency. Miner Nodes require specialized hardware and software to perform mining
calculations.

1.4 Transaction of ETH from one account to another

Install MetaMask a chrome extension

Fig 1.4.1 Installing MetaMask


Click on “Add to chrome” and meta mask chrome extension will be added

7
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Installation of Node.js

Fig 1.4.2 Installing Node.js


Click on download Node.js After downloading the node.js install in your system

Create an account in meta mask

Fig 1.4.3 Creating account in MetaMask


Click on Import an existing wallet, then agree for all the terms and conditions.

8
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Now open command prompt and run the below code

npm install -g ganache

After running the above code, type one more line

ganache-cli

Fig 1.4.4 Command prompt running

There are twelve words in mnemonic copy those words to clipboard

Fig 1.4.5 MetaMask account creation

9
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Paste these words in the meta mask and click on confirm secret recovery phase.

Create a password and your meta mask account will be created

Adding accounts to transfer ETH

Fig 1.4.6 Adding account from ganache app

Click on import account

Fig 1.4.7 Adding account by private key

10
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Now in the command prompt copy any one of the private key and paste it in the above place
provided. And click on import

Similarly, you can import ten accounts and private key are available in the command prompt.

Each account will have 1000ETH, now you can transfer the digital currency from one account
to another.

Transferring ETH from one account to another

Fig 1.4.8 Transferring ETH

Click on Send button

Fig 1.4.9 Transfer 50ETH in Meta mask

11
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Fig 1.4.10 Transferring 50 ETH

Click on confirm 50ETH will be transferred successfully

Fig 1.4.11 Successful transfer of 50ETH

12
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

1.5 Cryptography in Blockchain.

It provides the tools needed to encrypt data, record transactions, and send cryptocurrency
securely, all without a centralised authority.

Cryptography is a technique or a set of protocols that secure information from any third party
during a process of communication.

Some terminologies in cryptography.

1 Encryption: A process of transforming Plain Text into Cipher Text is known as


Encryption. Cryptography needs the encryption approach to send confidential messages
through an insecure channel.

2 Key: A Key is a numeric or alpha numeric text or can be a unique symbol. The Key can be
used at the time of encryption takes place on the Plain Text and at the time of decryption create
place on the Cipher text. The selection of key in Cryptography is essential because the security
of encryption algorithm depends precisely on it.

3 Decryption: A reverse process of encryption is known as Decryption. It is a procedure of


transforming Cipher Text into Plain Text. Cryptography needs the decryption approach at the
receiver side to acquire the original message from non-readable message

4 Cipher: The message that cannot be learned by anyone or meaningless message is what it
can call as Cipher Text. In Cryptography the original message is changed into non-readable
message before the communication of actual message.

Types of cryptography

1 Symmetric key cryptography: Symmetrical Key Cryptography also known as


conventional or single-key encryption was the primary method of encryption before the
introduction of public key cryptography in the 1970s. In symmetric-key algorithms, the same
keys are used for data encryption and decryption. This type of cryptography plays a crucial role
in securing data because the same key is used for both encryption and decryption.

2 Asymmetric key cryptography: In asymmetric Key cryptography, there are two keys,
also known as key pairs: a public key and a private key. The public key is publicly distributed.
Anyone can use this public key to encrypt messages, but only the recipient, who holds the

13
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

corresponding private key, can decrypt those messages. “Public-key cryptography” is another
representation used to refer to Asymmetric Key cryptography.

RSA Algorithm

RSA (Rivest Shamir Adleman) algorithm has four phases:

1 Key generation

2 Key distribution

3 Encryption

4 Decryption

Key generation

 Generate two large prime numbers, p and q


 Compute n=p*q. This n is used as the modulus for both the public and private key
 Compute totient function ϕ (n)=(p-1)*(q-1)
 Choose an integer e such that 1<e<ϕ(n) and gcd(e, ϕ(n))=1. Common choices for e are
3 and 65537
 Compute d, the modular multiplicative inverse of e modulo ϕ(n). This means
d*e=1(modϕ(n))
 Public key is (e,n) and private key is (d,n)

Encryption

 Convert the plain text message into an integer m


 Compute the cipher text C using C=me(modn)

Decryption

 Compute the plain text message M=cd(modn)

Example 1 for RSA algorithm

Choose p=3 and q=11

n=3*11=33

ϕ(n)=(3-1)*(11-1)=2*10=20

Choose e=7 such that gcd (e, ϕ(n)) = 1

14
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

D*e=1(mod ϕ(n)) One solution is d=3; [(3*7)%20=1]

Public key is (e, n) = (7,33)

Private key is (d, n) = (3,33)

Encryption of m = 2  C=27%33=29

Decryption of c = 29 M=293%33=2

Python code for implementing RSA algorithm


import math

p=3

q=11

n=p*q

phi=(p-1)*(q-1)

e=2

while (e<phi):

if (math.gcd(e,phi)==1):

break

else:

e+=1

print(f'e={e}')

d=pow(e,-1,phi)

print(f'Private key = ({d},{n})')

print(f'Public key = ({e},{n})')

m=2

print(f'Original message={m}')

c=m**e%n

15
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

print(f'Encrypted message={c} ')

M=c**d%n

print(f'Decrypted message ={M}')

Fig 1.5.1 Implementing RSA algorithm using python with output

1.6 Digital Signature in blockchain

This is a mathematical scheme that is used to verify the integrity and authenticity of
digital messages and documents. Digital signature in block chain is considered as digital
version of the handwritten signature or stamped seal. Digital signature uses asymmetric key
cryptography.

How do digital signature work?

 Signing the message with private key


 Verifying the message with public key

Digital signature is used to validate the origin of a transaction and prevent non-repudiation

Bitcoin uses Elliptic Curve Digital Signature Algorithm (ECDSA)

16
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

1.7 Transferring ETH using ganache app

Fig 1.7.1 Download the ganache app

After downloading the ganache app Install it and open the app and click on quick start

Fig 1.7.2 Ganache app

Copy the “MNEMONIC” and paste it in the Meta Mask

17
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Fig 1.7.3 Account opened through ganache app

Fig 1.7.4 Transferring 50 ETH through ganache app

18
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Fig 1.7.5 Transferring 50ETH

Fig 1.7.6 Successfully transferred 50ETH from ganache app

19
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

1.8 Smart contract

What is smart contract?

Smart contracts are digital contracts stored on a blockchain that are automatically executed
when predetermined terms and conditions are met.

Basic principles of smart contract

1 Observability: Observability refers to the “ability of principals to observe each other’s


performance of the contract, or to prove their performance to the other principals.” Each party
examines the opposing party’s performance of their obligations to ensure the terms of the
contract are being followed.

2 Verifiability: Due to the immutable nature of blockchain, any bugs or errors will become
permanent once published and could lead to huge economic losses. To avoid such
problems, verification is required to check the correctness and the security of the smart
contract.

3 Privity: Privity of contract refers to the relationship between parties in a contract. It


stipulates that only the parties who are directly involved have legal rights and obligations under
that contract.

4 Enforceability: Smart contract code must be unambiguous and accurately reflect the
parties' intentions. Ambiguities or errors in the code can lead to unintended consequences,
challenging the enforceability of the contract.

Types of smart contract

1 Smart legal contract: There are legal guarantees for smart contracts. They follow the
format seen in contracts: “If this occurs, then this will occur.” Legal smart contracts provide
more openness between contracting entities than traditional documents because they are stored
on blockchain and cannot be altered. Contracts are executed by the parties using digital
signatures. If certain conditions are met, such as paying a debt when a predetermined date is
reached, smart legal contracts may operate on their own. If stakeholders don’t comply, there
may be serious legal ramifications.

20
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

2 Decentralized Autonomous organization: DAOs are democratic organisations with


voting powers granted by a smart contract. A decentralised autonomous organisation, or DAO,
is a blockchain-based entity with a shared goal under collective governance. There is no such
thing as an executive or president. Instead, the organization’s operations and the distribution
of assets are governed by blockchain-based principles that are incorporated into the contract’s
code.

3 Application logic contracts: Application-based code that usually keeps up with


multiple other blockchain contracts makes up application logic contracts, or ALCs. It permits
device-to-device interactions such as blockchain integration and the Internet of Things. These
are signed between computers and other contracts rather than between people or organisations
like other kinds of smart contracts.

Smart contract process

 Pre-defining the contract


 Events
 Execution and the transfer of value
 Settlement of the contract

Tools for writing and deploying smart contracts

1 Mist browser: If you are looking for the best Ethereum wallet in the existing market, Mist
would be one of the top picks for you. The best part about Mist that helped it to make it to the
list is the tag of Ethereum with it. However, you must have a designated place to store your
ETH tokens and smart contracts before using Mist. You need to remember your password
always because it’s one-time, you can never change it.

2 Truffle framework: Truffle is surely one of the best smart contract development tools
for deploying and developing Ethereum applications. Simply put, this tool offers a complete
ecosystem for your dApp development. Here you can code, create projects, run automated tests,
compile smart contracts, migrate, and interact with the contracts.

3 Meta mask: Meta mask has gained much popularity among common users over the past
few years. Convenience and simplicity are the two key features that made Meta mask one of
the most popular smart contract development tools. It offers login security, key vault, exchange
facilities, and token wallet- all under one roof. Moreover, you can also connect with the

21
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

blockchain application and browse things without threatening their privacy and security.
Additionally, this blockchain application gateway serves as a web browser extension and it also
has a mobile app. So you can easily have a handy little extension on your mobile or computer
browsers- Firefox, Opera, Chrome, Brave, and others.

4 Remix: Remix IDE will be the ultimate ETH development. It is a JavaScript-based, open-
source compiler that lets you code straight from your mobile web browser. If you are
wondering, it has a different desktop application as well. You can use this tool for writing,
testing, unravelling, and deploying smart contracts either in the browser or locally. While using
Remix, you can seamlessly connect to the ETH blockchain through Meta mask as well. If the
process seems too complicated, you can always enrol in a smart contracts course for in-depth
understanding and knowledge.

Programming languages for writing Ethereum smart contracts

Solidity

Serpent

Viper

Lisk

Chain

1.9 Consensus mechanism

What is consensus?

In the blockchain, a consensus mechanism is a system that validates a transaction and marks it
as authentic. This mechanism lists all valid transactions of a coin in a blockchain to build trust
in the coin among traders. Several currencies, such as Bitcoin, Ethereum etc., use this system
for security purposes.

Need of consensus

 To reduce crash faults


 To reduce network faults
 To reduce byzantine faults

22
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Objective of consensus mechanism

 Unified agreement
 Align economic incentre
 Fair and equitable
 Prevent double spending
 Fault tolerant

Types of consensus mechanism

1 Proof of Work (PoW): This consensus algorithm is used to select a miner for the next
block generation. Bitcoin uses this PoW consensus algorithm. The central idea behind this
algorithm is to solve a complex mathematical puzzle and easily give out a solution. This
mathematical puzzle requires a lot of computational power and thus, the node who solves the
puzzle as soon as possible gets to mine the next block. For more details on PoW,

2 Proof of stake (PoS): This is the most common alternative to PoW. Ethereum has shifted
from PoW to PoS consensus. In this type of consensus algorithm, instead of investing in
expensive hardware to solve a complex puzzle, validators invest in the coins of the system by
locking up some of their coins as stakes. After that, all the validators will start validating the
blocks. Validators will validate blocks by placing a bet on them if they discover a block that
they think can be added to the chain. Based on the actual blocks added in the Blockchain, all
the validators get a reward proportionate to their bets, and their stake increase accordingly. In
the end, a validator is chosen to generate a new block based on its economic stake in the
network. Thus, PoS encourages validators through an incentive mechanism to reach to an
agreement.

3 Delegated Proof of Stake: consensus algorithm which is an advancement of the


fundamental concepts of Proof of Stake. Delegated Proof of Stake (DPoS) consensus algorithm
was developed by Daniel Larimer, founder of Bit Shares, Steemit and EOS in 2014. In Proof
of Stake consensus system, each person who stakes a token can participate to
the “mintage” process which means that they get a chance to select layer two nodes which
further validates block and be rewarded for adding blocks to blockchain. DPos system is

23
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

maintained by an election system for choosing nodes which verify blocks. These nodes are
called “witnesses” or “block producers”

4 Proof of Burn (PoB): With PoB, instead of investing in expensive hardware equipment,
validators ‘burn’ coins by sending them to an address from where they are irretrievable. By
committing the coins to an unreachable address, validators earn the privilege to mine on the
system based on a random selection process. Thus, burning coins here means that validators
have a long-term commitment in exchange for their short-term loss. Depending on how the
PoB is implemented, miners may burn the native currency of the Blockchain application or the
currency of an alternative chain, such as bitcoin. The more coins they burn, the better their
chances of being selected to mine the next block. While PoB is an interesting alternative to
PoW, the protocol still wastes resources needlessly. And it is also questioned that mining power
simply goes to those who are willing to burn more money.

5 Proof of Capacity: In the Proof of Capacity consensus, validators are supposed to invest
their hard drive space instead of investing in expensive hardware or burning coins. The harder
drive space validators have, the better their chances of getting selected for mining the next
block and earning the block reward.

6 Proof of Elapsed Time: PoET is one of the fairest consensus algorithms which chooses
the next block using fair means only. It is widely used in permissioned Blockchain networks.
In this algorithm, every validator on the network gets a fair chance to create their own block.
All the nodes do so by waiting for a random amount of time, adding proof of their wait in the
block. The created blocks are broadcasted to the network for others’ consideration. The winner
is the validator which has the least timer value in the proof part. The block from the winning
validator node gets appended to the Blockchain. There are additional checks in the algorithm
to stop nodes from always winning the election, and stop nodes from generating the lowest
timer value.

7 Practical byzantine fault tolerance: The Byzantine Generals Problem describes the
complexity of reaching an agreement if there are disloyal generals. The pBFT consensus
mechanism is a secure model that can withstand dishonest validators. It reaches a consensus
when there is ⅔ agreement from the honest nodes. Hyperledger, Fabric, and other prominent
blockchains are utilizing this mechanism. However, the security of pBFT will be breached if
the dishonest nodes are more than ⅓ of all the nodes in the network. The nodes in pBFT are
divided into primary and secondary nodes. The primary nodes are the leader nodes, while the

24
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

secondary nodes are the backup nodes. The primary nodes are changed at every consensus
round.

8 Proof of Weight: Each user in this mechanism exists in weights, and how much they have
in their accounts determines their weight. The algorithm picks committee members randomly
among the users based on their weight. This randomness checkmates the possibility of having
one or many dishonest users. Honest users must have up to ⅔ of the total money in the network.
Otherwise, dishonest nodes can take over. Although the design of PoWeights might look
similar to PoS, each is different. The users only have to have tokens in PoWeights and do not
need to lock or stake them.

9 Proof of Capacity: Miners need to prove that they have the storage capacity to mine
crypto. The most recommended storage device in the instant case is a hard disk. The miner
needs to get ready before the mining kicks off. They get ready by plotting nonces. A miner can
only create as many nonces as they have space for. The network frequently broadcasts puzzles.
Any miner who has the closest hash in their nonce wins the puzzle.

10 Proof of Authority: There must be thorough due diligence on the miners for a
blockchain to be ultimately secure. Some consensus mechanisms skip this process and fall into
the hands of dishonest miners. Proof of Authority, a consensus mechanism in which validators
stake their identity, fixes this loophole in its design. Firstly, the real-life identity of each
validator is ascertained within a PoA consensus model. The network managers will check how
trustworthy the prospective validator is. This also makes it easy to track any validator in case
of foul play. Secondly, each validator must stake a certain amount of assets as a sign of
commitment. Basically, PoA validators stake their reputation and their coins.

11 Proof of Importance: NEM blockchain introduced the Proof of Importance consensus


algorithm to improve the Proof of Stake mechanism. First, the Proof of Stake mechanism
makes validators lock up their assets and not transact with them. Secondly, it only rates
validators based on their staking’s.

25
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

1.9 Creating a conceptual secure blockchain-based electronic voting system

Lately, electronic voting systems have begun being used in many countries. Estonia was the
first in the world to adopt an electronic voting system for its national elections. Soon after,
electronic voting was adopted by Switzerland for its state-wide elections, and by Norway for
its council election. For an electronic voting system to compete with the traditional ballot
system, it has to support the same criteria the traditional system supports, such as security and
anonymity. An e-Voting system has to have heightened security in order make sure it is
available to voters but protected against outside influences changing votes from being cast, or
keep a voter’s ballot from being tampered with. Many electronic voting systems rely on Tor to
hide the identity of voters. However, this technique does not provide total anonymity or
integrity since many intelligence agencies around the world control different parts of the
Internet which can allow them to identify or intercept votes.

Running an electronic voting system dApp

Run the below code one by one in command prompt

git --version

git clone https://github.com/adhikarir/E-voting-system-using-blockchain-and-python.git

Now create a directory of E-voting-system-using-blockchain-and-python in cmd

cd E-voting-system-using-blockchain-and-python

pip install -r requirements.txt

Start a blockchain node server,

export FLASK_APP=service.py

OR

set FLASK_APP=service.py

26
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Fig 1.9.1 Flask server running in command prompt

Now open another terminal session in command prompt

Create a directory of E-voting-system-using-blockchain-and-python

After flask server is running in the port 8000

Now run python app.py in another terminal

Fig 1.9.2 Running an overall dApp

27
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Fig 1.9.3 Output of e-voting dApp

Fig 1.9.4 Result of e-voting in the same dApp

28
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Fig 1.9.5 Blockchain of e-voting dApp

Fig 1.9.6 Request to mine in dApp

29
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Fig 1.9.7 Backend of Flask server

Fig 1.9.8 Backend of the overall dApp

30
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

1.10 Making a transaction through Remix IDE and solidity programming

Run the below codes in command prompt to start backend ganache app

npm install -g ganache

ganache-cli

Now in web search for Remix IDE and open the compiler and write a smart contract code using
solidity programming language.

Fig 1.10.1 Smart contract code using solidity programming

Fig 1.10.2 Backend codes in command prompt

31
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Fig 1.10.3 Backend ganache app running

Fig 1.10.4 Information of the transaction in backend

32
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

CHAPTER 2

Web technology

2.1 Introduction to Web, Web protocols, Basics of HTML

1 Web: The World Wide Web (WWW or simply the Web) is an information system that
enables content sharing over the Internet through user-friendly ways meant to appeal to users
beyond IT specialists and hobbyists. It allows documents and other web resources to be
accessed over the Internet according to specific rules of the Hypertext transfer
protocol (HTTP).

2 Web protocols: The Internet Protocol (IP) is a protocol, or set of rules, for routing and
addressing packets of data so that they can travel across networks and arrive at the correct
destination. Data traversing the Internet is divided into smaller pieces, called packets. IP
information is attached to each packet, and this information helps routers to send packets to the
right place. Every device or domain that connects to the Internet is assigned an IP address, and
as packets are directed to the IP address attached to them, data arrives where it is needed.

Basics of HTML (Hyper Text Markup Language)

1. HTML Document: An HTML document is a text file that contains a set of HTML
elements or

tags. These tags define the structure and content of a webpage.

2. HTML Tags: HTML tags are used to define elements within an HTML document. Tags
are enclosed in angle brackets, such as `<tag>`. For example, `<h1>` defines a top-level
heading, and

`<p>` defines a paragraph.

3. Attributes: HTML tags can have attributes that provide additional information about an
element.

For example, the `<a>` tag for links has an `href` attribute to specify the link's destination.

33
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

4. Document Structure: HTML documents typically have a standard structure, which


includes the `<html>`, `<head>`, and `<body>` elements. The `<html>` element contains all
the other elements on the page, the `<head>` element includes metadata like the page title, and
the `<body>` element contains the visible content.

5. Text and Links: HTML is used to structure text content, create headings, paragraphs, and
lists.

It's also used to create hyperlinks using the `<a>` tag.

Fig 2.1.1 Basic HTML code with output

34
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

2.2 HTML Tags and Attributes

HTML (Hypertext Markup Language) uses tags and attributes to structure content on web

pages. Tags define different elements, while attributes provide additional information about
those elements. Here are some commonly used HTML tags and attributes:

HTML Tags:

1. <!DOCTYPE html>: This declaration defines the document type and version of HTML being
used.

2. <html>: The root element that wraps the entire HTML document.

3. <head>: Contains metadata about the document, such as the title, character set, and links to

external resources.

4. <title>: Sets the title of the web page, which appears in the browser's title bar or tab.

5. <meta>: Provides metadata like character encoding, author, and description.

6. <link>: Links to external resources, such as stylesheets or icons.

7. <style>: Defines the document's internal CSS styles.

8. <script>: Contains JavaScript code or links to external script files.

9. <body>: Contains the visible content of the web page.

10. <h1>, <h2>, <h3>, <h4>, <h5>, <h6>: Headings, with <h1> being the most significant
and<h6> the least.

11. <p>: Defines a paragraph of text.

12. <a>: Creates hyperlinks, linking to other web pages or resources. It has attributes like `href`
to specify the link's destination.

13. <img>: Embeds images on the page and uses the `src` attribute to specify the image source.

14. <ul>: Defines an unordered list, typically used with <li> (list item) elements.

15. <ol>: Defines an ordered list, also used with <li> elements.

16. <li>: Represents a list item within <ul> or <ol>.

35
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

17. <div>: A container used for grouping and styling content.

18. <span>: A container used for applying styles or scripting to inline content.

19. <table>: Creates a table, used with various elements like <tr> (table row), <th> (table
header), and <td> (table data).

20. <form>: Defines an input form for user data input.

HTML Attributes:

1. id: Provides a unique identifier for an HTML element, allowing CSS and JavaScript to target
specific elements.

2. class: Assigns one or more class names to an element, enabling CSS to target elements with
the same class.

3. style: Adds inline CSS styles to an element.

4. src: Specifies the source location for elements like images, scripts, or iframes.

5. href: Defines the URL for hyperlinks.

6. alt: Provides alternative text for images, which is displayed if the image cannot be loaded.

7. width and height: Set the dimensions of images or other elements.

8. target: Specifies how links should be opened, such as in the same window or a new tab or

window.

9. disabled: Disables an input element in a form.

10. value: Defines the initial value for input elements, like text fields.

36
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Fig 2.2.1 HTML code with output for tags

Fig 2.2.2 HTML code for creating table using collapse

37
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Fig 2.2.4 HTML code for text fields

Fig 2.2.8 Using grid in HTML

38
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Fig 2.2.9 Using Radio tag in HTML

Fig 2.2.10 Adding borders for text in HTML

39
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Fig 2.2.11 HTML code for input type date and time

40
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

2.3 CSS (Cascading Style Sheets)


CSS (Cascading Style Sheets) is a stylesheet language used to describe the presentation and
layout of HTML documents. It allows you to control the visual design of web pages. Here are
the basics of CSS:

1. Selectors: Selectors are patterns used to select the HTML elements you want to style. They
can be element names (e.g., `p` for paragraphs), class names (e.g., `.my-class`), IDs (e.g., `#my-
id`), and more.

Example:

css

p{

color: blue;

.my-class {

font-size: 18px;

2. Properties: CSS properties are the specific styles you want to apply to the selected elements.
They include attributes like `color`, `font-size`, `background-color`, and many more.

Example:

css

p{

color: blue;

font-size: 16px;

background-color: #f0f0f0;

41
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

3. Values: Values are assigned to properties to define the style. They can be units (e.g., `px`,
`%`), colors (e.g., `red`, `#00ff00`), and keywords (e.g., `bold`, `center`).

Example:

css

p{

font-size: 16px;

background-color: #f0f0f0;

5. External CSS: CSS can be included in a separate external file (usually with a `.css` extension)
and linked to an HTML document using the `<link>` tag in the document's `<head>`section

<head>

<link rel="stylesheet" type="text/css" href="styles.css">

</head>

6. Internal CSS: CSS can be placed directly within an HTML document using the `<style>`
tagin

the document's `<head>` section.

Example:

<head>

<style>

p{

color: blue;

</style>

</head>

7. Inline CSS: You can apply CSS styles directly to individual HTML elements using the `style`

42
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

attribute.

Example:

<html>

<p style="color: red; font-size: 14px;">This is a red and small text.</p>

</html>

Fig 2.3.1 CSS written in head of HTML for centre alignment

43
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Fig 2.3.2 CSS inside HTML for centre alignment of headings

Fig 2.3.3 CSS written externally and linking in HTML code

44
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

2.4 Introduction to JavaScript and using JavaScript in webpages


JavaScript is a versatile, high-level, and client-side scripting language that is primarily used for
web development. It allows you to add interactivity and dynamic behaviour to web pages. Here
are the basics of JavaScript:

JavaScript syntax for variables:

1. Variable Declaration: Variables in JavaScript are declared using the `var`, `let`, or `const`

keyword. For example:

JavaScript

var x; // Declares a variable named x using 'var'

let y; // Declares a variable named y using 'let'

const z = 10; // Declares a constant variable named z with an initial value of 10 using 'const'

- `var` is function-scoped, and its scope is not limited to blocks.

- `let` is block-scoped, which means it's confined to the block where it's defined.

How to Link JavaScript File in HTML?

JavaScript can be added to HTML file in two ways:

1 Internal JS: We can add JavaScript directly to our HTML file by writing the code inside the
<script> tag. The <script> tag can either be placed inside the <head> or the <body> tag
according to the requirement.

2 External JS: We can write JavaScript code in another files having an extension.js and then
link this file inside the <head> tag of the HTML file in which we want to add this code.

JavaScript Comments

JavaScript comments help explain code, making it easier to understand. You can also use them
to temporarily disable parts of your code. The JavaScript compiler ignores comments when
running the code.

45
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

1. Single Line Comments

A single-line comment in JavaScript is denoted by two forward slashes (//),

Syntax:

// your comment here

2. Multi-line Comments

A multiline comment in JavaScript is a way to include comments that span multiple lines in the
source code.

Syntax:

/*

This is a multiline comment

It can span multiple lines

*/

JavaScript Arrays

An array in JavaScript is a data structure used to store multiple values in a single variable. It
can hold various data types and allows for dynamic resizing. Elements are accessed by their
index, starting from 0.

Declaration of an Array

There are basically two ways to declare an array i.e. Array Literal and Array Constructor.

1. Creating an Array using Array Literal

Creating an array using array literal involves using square brackets [] to define and initialize
the array. This method is concise and widely preferred for its simplicity.

Syntax:

let arrayName = [value1, value2, ...];

46
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

2. Creating an Array using Array Constructor (JavaScript new Keyword)

The “Array Constructor” refers to a method of creating arrays by invoking the Array
constructor function. This approach allows for dynamic initialization and can be used to create
arrays with a specified length or elements.

Syntax:

let arrayName = new Array();

Functions in JavaScript

A JavaScript function is a block of code designed to perform a particular task. It encapsulates


a set of instructions that can be reused throughout a program. Functions can take parameters,
execute statements, and return values, enabling code organization, modularity, and reusability
in JavaScript programming.

Fig 2.4.1 Basic JavaScript code and linking externally to HTML

47
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Fig 2.4.2 Creating Login page using JavaScript and HTML

Fig 2.4.3 Using switch case statement in JavaScript

48
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Fig 2.4.4 Sorting the list Using JavaScript

Fig 2.4.5 Getting factors of a number using JavaScript

49
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

2.5 jQuery in designing webpages

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document
traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-
to-use API that works across a multitude of browsers. With a combination of versatility and
extensibility, jQuery has changed the way that millions of people write JavaScript.

Adding jQuery to your web page

1 Downloading jQuery

The jQuery library is a single JavaScript file, and you reference it with the HTML <script> tag
(notice that the <script> tag should be inside the <head> section):

<head>
<script src="jquery-3.7.1.min.js"></script>
</head>

2 jQuery CDN

If you don't want to download and host jQuery yourself, you can include it from a CDN
(Content Delivery Network).Google is an example of someone who host jQuery:

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>

jQuery Syntax

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on
the element(s).

Basic syntax is: $(selector).action()

 A $ sign to define/access jQuery

 A (selector) to "query (or find)" HTML elements

 A jQuery action() to be performed on the element(s)

50
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

jQuery Selectors

1 The element Selector


The jQuery element selector selects elements based on the element name.
You can select all <p> elements on a page like this:
Example:

$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});

2 The #id Selector

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.
An id should be unique within a page, so you should use the #id selector when you want to find
a single, unique element.
To find an element with a specific id, write a hash character, followed by the id of the HTML
element:
Example:
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});

3 The .class Selector


The jQuery .class selector finds elements with a specific class.
To find elements with a specific class, write a period character, followed by the name of the
class:
Example:
$(document).ready(function(){
$("button").click(function(){
$(".test").hide(); });
});

51
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

jQuery Event methods


What are Events?

All the different visitors' actions that a web page can respond to are called events.

An event represents the precise moment when something happens.

Examples:

 moving a mouse over an element

 selecting a radio button

 clicking on an element

Here are some common DOM events:

Mouse Event Keyboard Event Form Event Window Event


Click Keypress Submit Load

dblclick Keydown Change Resize

mouseenter Keyup Focus Scroll

mouseleave blur Unload

jQuery Syntax For Event Methods

In jQuery, most DOM events have an equivalent jQuery method.

To assign a click event to all paragraphs on a page, you can do this:

$("p").click();

The next step is to define what should happen when the event fires. You must pass a function
to the event:

$("p").click(function(){
// action goes here!!
});

52
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Commonly used jQuery Event methods


1 click()

The click() method attaches an event handler function to an HTML element.

The function is executed when the user clicks on the HTML element.

The following example says: When a click event fires on a <p> element; hide the
current <p> element:

Example

$("p").click(function(){
$(this).hide();
});

2 dblclick()

The dblclick() method attaches an event handler function to an HTML element.

The function is executed when the user double-clicks on the HTML element:

Example

$("p").dblclick(function(){
$(this).hide();
});

3 mouseenter()

The mouseenter() method attaches an event handler function to an HTML element.

The function is executed when the mouse pointer enters the HTML element:

Example

$("#p1").mouseenter(function(){
alert("You entered p1!");
});

53
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

4 mouseleave()

The mouseleave() method attaches an event handler function to an HTML element.

The function is executed when the mouse pointer leaves the HTML element:

Example

$("#p1").mouseleave(function(){
alert("Bye! You now leave p1!");
});

5 mousedown()

The mousedown() method attaches an event handler function to an HTML element.

The function is executed, when the left, middle or right mouse button is pressed down, while
the mouse is over the HTML element:

Example

$("#p1").mousedown(function(){
alert("Mouse down over p1!");
});

6 mouseup()

The mouseup() method attaches an event handler function to an HTML element.

The function is executed, when the left, middle or right mouse button is released, while the
mouse is over the HTML element:

Example

$("#p1").mouseup(function(){
alert("Mouse up over p1!");
});

7 hover()

The hover() method takes two functions and is a combination of


the mouseenter() and mouseleave() methods.

54
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

The first function is executed when the mouse enters the HTML element, and the second
function is executed when the mouse leaves the HTML element:

Example

$("#p1").hover(function(){
alert("You entered p1!");
},
function(){
alert("Bye! You now leave p1!");
});

8 focus()

The focus() method attaches an event handler function to an HTML form field.

The function is executed when the form field gets focus:

Example

$("input").focus(function(){
$(this).css("background-color", "#cccccc");
});

9 blur()

The blur() method attaches an event handler function to an HTML form field.

The function is executed when the form field loses focus:

Example

$("input").blur(function(){
$(this).css("background-color", "#ffffff");
});

10 The on() Method

The on() method attaches one or more event handlers for the selected elements.

Attach a click event to a <p> element:

55
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Example

$("p").on("click", function(){
$(this).hide();
});

Fig 2.5.1 Hide and show button in jQuery

Fig 2.5.2 Mouse functions in jQuery code

56
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Fig 2.5.3 Focus and blur functions in jQuery

Fig 2.5.4 Hiding paragraph in jQuery

57
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Fig 2.5.5 Click and alert function in jQuery

58
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

2.6 API’s (Application Program Interface)


What is Web API?

API stands for Application Programming Interface.

A Web API is an application programming interface for the Web.

A Browser API can extend the functionality of a web browser.

A Server API can extend the functionality of a web server.

A Web API (Application Programming Interface) is a set of protocols and tools for building
software applications. Specifically, a web API is a type of API that is accessed through the
internet, typically using HTTP requests. Web APIs allow developers to interact with remote
systems or services over the internet, and to access and manipulate data that is stored on those
systems. For instance, a web API might allow a developer to access information about a user’s
social media profile, or to retrieve data from a remote database.

Browser API’s

All browsers have a set of built-in Web APIs to support complex operations, and to help
accessing data.

For example, the Geolocation API can return the coordinates of where the browser is located.

Fig 2.6.1 Getting your coordinates using browser API’s

59
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Third party API’s


Third party APIs are not built into your browser. To use these APIs, you will have to download
the code from the Web.
Examples: YouTube API - Allows you to display videos on a web site.
Google maps – Allows you to display maps on website.

Fig 2.6.2 Uploading YouTube video and google maps using Third party API
JavaScript validation API

Fig 2.6.3 JavaScript Validation API

60
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Web History API’s


The Web History API provides easy methods to access the windows.history object.

The window.history object contains the URLs (Web Sites) visited by the user.

1 The History back() Method

The back() method loads the previous URL in the windows.history list.

It is the same as clicking the "back arrow" in your browser.

Fig 2.6.4 Use of History back method


2 The History go() method

Fig 2.6.5 Use of History go method

61
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Web Storage API


The localStorage Object

The localStorage object provides access to a local storage for a particular Web Site. It allows
you to store, read, add, modify, and delete data items for that domain.

The data is stored with no expiration date, and will not be deleted when the browser is closed.

The data will be available for days, weeks, and years.

The setItem() Method

The localStorage.setItem() method stores a data item in a storage.

Fig 2.6.6 Storing data locally and retrieving

Web worker API

What is a Web Worker?

When executing scripts in an HTML page, the page becomes unresponsive until the script is
finished.

A web worker is a JavaScript that runs in the background, independently of other scripts,
without affecting the performance of the page. You can continue to do whatever you want:
clicking, selecting things, etc., while the web worker runs in the back

62
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Fig 2.6.7 Web worker API

63
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

2.7 Introduction to PHP (Hypertext Preprocessor)

PHP, which stands for "Hypertext Preprocessor," is a widely used server-side scripting
language designed for web development. It is an open-source language, and it is embedded
within HTML to create dynamic web pages. PHP is known for its simplicity, versatility, and
powerful features, making it a preferred choice for building web applications and websites.
Here's an overview of PHP and its basic syntax:

Basic Syntax of PHP:

1. PHP Tags: PHP code is embedded within HTML using special tags. The most common way
to enclose PHP code is with `<?php` to start and `?>` to end. For example:

php

<?php

// PHP code here

?>

Alternatively, short tags `<?` and `?>` can be used but are less recommended due to
compatibility

concerns.

2. Comments: Comments in PHP can be either single-line or multi-line. Single-line comments


start with `//`, while multi-line comments are enclosed within `/` and `/`.

php

// This is a single-line comment

This is a multi-line comment

3. Variables: PHP variables are declared with a dollar sign (`$`) followed by the variable name.

Variables are case-sensitive.

php

$name = "John";

$age = 30;

64
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

4. Data Types: PHP supports various data types, including strings, numbers, Booleans, arrays,
and objects. Data types are dynamically determined based on the assigned value.

php

$string = "Hello, World!";

$number = 42;

$isTrue = true;

$myArray = array("apple", "banana", "cherry");

5. Operators: PHP supports a wide range of operators, including arithmetic, comparison, and

logical operators. For example, `+`, `-`, `==`, `!=`, `&&`, and `||`.

php

$x = 5;

$y = 3;

$sum = $x + $y; // $sum now contains 8

6. Conditional Statements: PHP allows you to use conditional statements like `if`, `else`, and

`elseif` to make decisions in your code based on conditions.

php

if ($age < 18) {

echo "You are a minor.";

} else {

echo "You are an adult.";

7. Loops: You can create loops using `for`, `while`, and `foreach` to iterate over arrays, execute

code multiple times, and perform repetitive tasks.

php

65
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

for ($i = 0; $i < 5; $i++) {

echo $i;

8. Functions: Functions are reusable blocks of code that perform specific tasks. You can create

your own functions or use built-in PHP functions.

php

function greet($name) {

echo "Hello, $name!";

greet("John");

9. Include and Require: PHP allows you to include external files using `include` and `require`.

This is useful for modularizing your code.

php

include "header. php";

require "config. php";

PHP is a versatile language used for web development, offering support for databases, session

management, and interacting with web servers. It is widely used for creating dynamic websites

and web applications, and it can be seamlessly integrated with HTML to build interactive and
data-driven web solutions.

PHP code blocks

In PHP, code blocks are sections of code enclosed within PHP tags (`<?php` and `?>`). Code
blocks allow you to execute PHP code within an HTML or text document. Here's how PHP
code blocks work, including examples of using strings within code blocks:

1. Basic Code Blocks:

To create a code block in PHP, you use the opening `<?php` tag to start the block and the

66
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

closing `?>` tag to end it. Everything between these tags is considered PHP code and is

executed on the server when the page is requested.

Example of a basic PHP code block:

php

<?php

// PHP code here

?>

2. Using Strings in PHP Code Blocks:

Strings are a common data type in PHP used to store and manipulate text. You can work

with strings within PHP code blocks as follows: - Declaring Strings:

You can declare strings by enclosing text within single quotes (`'`) or double quotes (`"`).

php

$singleQuoted = 'This is a single-quoted string.';

$doubleQuoted = "This is a double-quoted string.";

Fig 2.7.1 Basic PHP code and it’s syntax

67
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Fig 2.7.2 PHP code written externally and connected to HTML

Fig 2.7.3 Application form using PHP

68
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

CHAPTER 3

Hackathon

3.1 Problem statement and explanation

Problem Statement:

To create a conceptual secure blockchain based electronic voting system

Objectives

1. Transparency: Blockchain's public ledger allows for all transactions to be visible and
verifiable by all participants, reducing the likelihood of tampering and increasing transparency
in the voting process.

2. Security: Blockchain technology uses cryptographic methods to secure data. This helps
to protect votes from being altered or falsified, ensuring that the integrity of the voting process
is maintained.

3. Immutability: Once a vote is recorded on a blockchain, it cannot be changed or deleted.


This immutability ensures that votes are permanent and cannot be tampered with after
submission.

4. Anonymity: Blockchain can provide privacy for voters by using cryptographic techniques
to anonymize their identities while still allowing votes to be counted accurately.

5. Accessibility: E-voting systems based on blockchain can be accessed remotely, allowing


people to vote from anywhere, which can increase participation rates, especially among those
who are unable to attend physical polling stations.

6. Efficiency: Blockchain can streamline the voting process by automating vote counting
and results reporting, which can reduce the time and costs associated with traditional voting
methods.

7. Auditability: Blockchain provides a clear and traceable record of votes, enabling


comprehensive audits to ensure that the voting process was conducted correctly and that results
are accurate.

69
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

3.2 Execution
Backend
App.py
import time
import json
from hashlib import sha256
class Block:
def __init__(self, index, votes, timestamp, previous_hash):
self.index = index
self.votes = votes
self.timestamp = timestamp
self.previous_hash = previous_hash
self.nonce = 0
def compute_hash(self):
block_string = json.dumps(self.__dict__, sort_keys=True)
return sha256(block_string.encode()).hexdigest()
class Blockchain:
difficulty = 2
def __init__(self):
self.unconfirmed_votes = []
self.chain = []
self.create_genesis_block()
def create_genesis_block(self):
genesis_block = Block(0, [], time.time(), "0")
genesis_block.hash = genesis_block.compute_hash()
self.chain.append(genesis_block)
@property
def last_block(self):
return self.chain[-1]
def proof_of_work(self, block):

70
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

block.nonce = 0
computed_hash = block.compute_hash()
while not computed_hash.startswith('0' * Blockchain.difficulty):
block.nonce += 1
computed_hash = block.compute_hash()
return computed_hash
def add_block(self, block, proof):
previous_hash = self.last_block.hash
if previous_hash != block.previous_hash:
return False
if not Blockchain.is_valid_proof(block, proof):
return False
block.hash = proof
self.chain.append(block)
return True
@staticmethod
def is_valid_proof(block, block_hash):
return (block_hash.startswith('0' * Blockchain.difficulty) and block_hash ==
block.compute_hash())
def add_new_vote(self, vote):
self.unconfirmed_votes.append(vote)
def mine(self):
if not self.unconfirmed_votes:
return False
last_block = self.last_block
new_block = Block(index=last_block.index + 1,
votes=self.unconfirmed_votes,
timestamp=time.time(),
previous_hash=last_block.hash)
proof = self.proof_of_work(new_block)
self.add_block(new_block, proof)

71
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

self.unconfirmed_votes = []
return new_block.index
from flask import Flask, request, redirect, render_template, jsonify
import requests
import json
app = Flask(__name__)
# Initialize the Blockchain
blockchain = Blockchain()
@app.route('/new_vote', methods=['POST'])
def new_vote():
vote_data = request.get_json()
required_fields = ['voter_id', 'candidate']
for field in required_fields:
if not vote_data.get(field):
return "Invalid vote data", 404
vote_data['timestamp'] = time.time()
blockchain.add_new_vote(vote_data)
return jsonify({"message": "Vote successfully added to the pool"}), 201
@app.route('/chain', methods=['GET'])
def get_chain():
chain_data = []
for block in blockchain.chain:
chain_data.append(block.__dict__)
return json.dumps({"length": len(chain_data), "chain": chain_data})
@app.route('/mine', methods=['GET'])
def mine_unconfirmed_votes():
result = blockchain.mine()
if not result:
return "No votes to mine"
return f"Block #{result} is mined."

72
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

@app.route('/pending_votes', methods=['GET'])
def get_pending_votes():
return json.dumps(blockchain.unconfirmed_votes)

@app.route('/')
def index():
return render_template('index.html', posts=blockchain.chain)
@app.route('/submit_vote', methods=['POST'])
def submit_vote():
voter_id = request.form['voter_id']
candidate = request.form['candidate']
vote_object = {
'voter_id': voter_id,
'candidate': candidate
}
# Submit a vote
new_vote_address = "{}/new_vote".format("http://127.0.0.1:8000")
try:
response = requests.post(new_vote_address, json=vote_object, headers={'Content-type':
'application/json'})
response_data = response.json()
message = response_data.get('message', 'Vote failed')
except requests.exceptions.RequestException as e:
# Handle request exceptions
message = f"An error occurred: {e}"
# Redirect to the result page to show the vote details
return
redirect(f'/result?voter_id={voter_id}&candidate={candidate}&message={message}')
@app.route('/result', methods=['GET'])
def result():
voter_id = request.args.get('voter_id')

73
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

candidate = request.args.get('candidate')
message = request.args.get('message')
return render_template('result.html', voter_id=voter_id, candidate=candidate,
message=message)
if __name__ == "__main__":
app.run(debug=True, port=8000)

Frontend
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Online Voting</title>
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
<script src="{{ url_for('static', filename='scripts.js') }}" defer></script>
</head>
<body>
<header>
<div class="container">
<h1>Online Voting System</h1>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/pending_votes">Pending Votes</a></li>
<li><a href="/chain">Blockchain</a></li>
<li><a href="/mine">Mine Votes</a></li>
</ul>
</nav>
</div>
</header>
<main class="container">
<h2>Submit a Vote</h2>

74
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

<form action="/submit_vote" method="post">


Voter ID: <input type="text" name="voter_id" required><br>
Candidate: <input type="text" name="candidate" required><br>
<input type="submit" value="Submit Vote">
</form>
<h2>Voting Chain</h2>
<ul>
{% for block in posts %}
<li>
<strong>Block Index:</strong> {{ block.index }}<br>
<strong>Votes:</strong> {{ block.votes }}<br>
<strong>Timestamp:</strong> {{ block.timestamp }}<br>
<strong>Previous Hash:</strong> {{ block.previous_hash }}<br>
<strong>Hash:</strong> {{ block.hash }}<br>
</li>
{% endfor %}
</ul>
</main>
</body>
</html>
Result.html
<!DOCTYPE html>
<html>
<head>
<title>Vote Result</title>
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
<script src="{{ url_for('static', filename='scripts.js') }}" defer></script>
</head>
<body>
<header>

75
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

<div class="container">
<h1>Vote Result</h1>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/pending_votes">Pending Votes</a></li>
<li><a href="/chain">Blockchain</a></li>
<li><a href="/mine">Mine Votes</a></li>
</ul>
</nav>
</div>
</header>
<main class="container">
<h2>Vote Result</h2>
<p><strong>Voter ID:</strong> {{ voter_id }}</p>
<p><strong>Candidate:</strong> {{ candidate }}</p>
<p>{{ message }}</p>
<a href="/">Go Back</a>
</main>
</body>
</html>
Script.js
document.addEventListener('DOMContentLoaded', () => {
// Example of dynamic behavior (e.g., form validation)
const form = document.querySelector('form');
if (form) {
form.addEventListener('submit', (event) => {
const voterId = document.querySelector('input[name="voter_id"]').value;
const candidate = document.querySelector('input[name="candidate"]').value;
if (!voterId || !candidate) {

76
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

alert('Please fill in all fields');


event.preventDefault(); // Prevent form submission if validation fails
}
});
}
});
Style.css
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* Body Styling */
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
color: #333;
}
.container {
width: 80%;
margin: auto;
overflow: hidden;
}
header {
background: #333;
color: #fff;
padding-top: 20px;
min-height: 70px;
border-bottom: #bbb 1px solid;
}

77
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

header h1 {
text-align: center;
margin: 0;
}
nav ul {
list-style: none;
padding: 0;
}
nav ul li {
display: inline;
margin: 0 10px;
}
nav ul li a {
color: #fff;
text-decoration: none;
}
main {
padding: 20px;
background: #fff;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
form {
margin: 20px 0;
}
form input[type="text"] {
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
width: calc(100% - 22px);

78
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

margin-bottom: 10px;
}
form input[type="submit"] {
background: #333;
color: #fff;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
}
form input[type="submit"]:hover {
background: #555;
}
ul {
list-style: none;
}
li {
background: #fff;
padding: 10px;
margin-bottom: 10px;
border-radius: 5px;
box-shadow: 0 0 5px rgba(0,0,0,0.1);
}
a{
color: #333;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}

79
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

OUTPUT
Open project directory in command prompt and run python app.py

Fig 3.2.1 Running app.py in cmd

Fig 3.2.2 Output

80
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Fig 3.2.3 Voted successfully

Fig 3.2.4 Votes before mining

81
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Fig 3.2.5 Votes stored in a blockchain

Fig 3.2.6 Mining in Blockchain

82
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

CERTIFICATIONS
Blockchain in depth:

83
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

JavaScript:

84
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

HTML 5 and CSS 3 advanced training:

85
B.E/Dept. of AIML/BNMIT 2024-2025
Internship on Blockchain technology and Web Technology

Introduction to PHP programming:

86
B.E/Dept. of AIML/BNMIT 2024-2025

You might also like