Practical File BT
Practical File BT
CSCSC04
Practical File
Submitted to-
Dr. Poonam Rani
Submitted by-
Kashish Verma- 2023PCS2014
Chirag Kushwaha- 2023PCS2018
Ashima Jain- 2023PCS2019
Harsh Jaiswal- 2023PCS2023
Harshikha- 2023PCS2028
M.Tech CSE, 2nd Sem
Index
S
No Title Sign
1.1 Set up an environment for Ethereum on Windows.
1.2 Set up an environment for Ethereum on Ubuntu.
1.3 Install and set up Ethereum wallet.
1.4 Send/ receive ether.
In this practical, we are going to set up the development environment for Windows with all the tools that
we need to develop smart contracts for Ethereum. Our toolbox is composed of the following tools: Geth,
Ganache, and Truffle.
Geth
Geth or go-ethereum, is a command line interface that allows you to run and operate a full Ethereum
node. Geth is implemented in Go and allows you to mine blocks, to generate ether, to deploy and interact
with smart contracts, to transfer funds, to inspect block history, to create accounts, and so on. Geth can be
used to connect the public Ethereum networks like the main net, or to create your own private network for
deployment purposes.
The benefit of using Geth, in development processes, is to let you fully test your application before
deploying. Installation of Geth can be found on Ethereum website.
Note: You will need Chrome or Firefox for blockchain testing. Edge or internet explorer are not suitable
for blockchain testing.
1. Go to https://geth.ethereum.org/downloads
2. Click Vx for Windows.
3. Open the downloaded, .exe file.
4. Follow the process.
5. Don’t forget to check the development tools checkbox.
6. Click Install.
Now once, Geth and Development tools are installed, open powershell.
Ganache is a blockchain emulator that you can use for development purposes. Ganache can be seen as a
replacement for TestRPC. The strength of Ganache is its UI that allows you to inspect blocks in-memory
Ethereum nodes that run faster and provide all the visual components you need to test your contacts
locally before deploying them to a real Ethereum. We can install ganache, by downloading the installation
package on
1. Go to “https://archive.trufflesuite.com/ganache/”.
2. Click the download button on the homepage.
3. Open the .appx file. And click Install.
Now, when you start Ganache, it creates a new ethereum node in memory on network identifier 5777. It
creates 10 accounts and puts 100 ethers in each account. Ganache always creates the same account, it uses
the same mnemonic.
The first view is “Accounts” view, and there you can find some information about the running node like
the current block, which is the number of the last block mined by the node, the gas price, which is the
minimum gas price, the gas limit, which is the maximum gas the node is willing to accept per block, the
network identifier, the RPC server is the endpoint for the RPC parts that we’ll connect, and the mining
status is important. By default, this fake node only mines a new block when it receives a new transaction.
That’s what Auto-mining means. Last but not least, you can see the mnemonic, which is the seed that
Ganache uses to generate the first accounts. Then you can see the list of 10 accounts generated by
Ganache, with the following information: the address of the account, its balance, with only two decimals,
the number of transactions that were sent by this account, the index of the account in the list of accounts
and a button that makes it possible for you to see the private key for the account.
Second view is the “Block” tab, that shows you a list of blocks mined by the node, here we only have one
block, which is the genesis block.
We also have the “Transaction” tab where we will see a list of all the transactions, and for now there
aren’t any. And at last we have a “Logs” tab, that shows you the logs of the running node.
There is also a search field, where you can search for blocks or transactions by their hash or number. And
finally there is a cog icon that accesses settings. There we can change the hostname, the port number, the
network, can also disable auto-mining to set a regular mining block time.
In “Account and Keys”, we can define the number of accounts that can be generated when it starts and
also change the mnemonic or generate a random one.
In “Chains” you can customize the gas limit and the gas price.
Whenever you change any setting make sure to restart to take those new settings into account.
So open Windows Powershell and `node -v` and `npm -v` to check the installed versions. NodeJS can be
installed with the MSI package which you can find in https://nodejs.org/en.
Truffle 4
Now to compile, test and deploy your smart contracts, you will need a build framework that will increase
your development velocity compared to doing it manually. We can find truffles on the website https://
archive.trufflesuite.com/.
So we will install truffle using the npm package, make sure to install all previous versions of truffle, as it
will collide.
Now all the steps are done, now we just need a text-editor that will be used to edit our smart contract and
other text files. We can use Atom, Visual Studio or an IntelliJ plugin, whichever you are comfortable with.
1.2. Setup Environment for Ethereum on Ubuntu
Here we are going to set up development for Ethereum on Linux, and will use all the tools that are
required to write smart contracts on Ethereum. Our tool box will contain everything as before: Geth,
Ganache and Truffle.
Geth
Geth or go-ethereum, is a command line interface that allows you to run and operate a full Ethereum
node. Geth is implemented in Go and allows you to mine blocks, to generate ether, to deploy and interact
with smart contracts, to transfer funds, to inspect block history, to create accounts, and so on. Geth can be
used to connect the public Ethereum networks like the main net, or to create your own private network for
deployment purposes.
The benefit of using Geth, in development processes, is to let you fully test your application before
deploying. Installation of Geth can be found on Ethereum website.
So in the terminal
$ geth version
Ganache
Ganache is a blockchain emulator that you can use for development purposes. Ganache can be seen as a
replacement for TestRPC. The strength of Ganache is its UI that allows you to inspect blocks in-memory
Ethereum nodes that run faster and provide all the visual components you need to test your contacts
locally before deploying them to a real Ethereum. We can install ganache, by downloading the installation
package on
1. Go to “https://archive.trufflesuite.com/ganache/”.
2. Click the download button on the homepage.
3. Open the app image file. And click Install.
$ node -v
$ npm -v
Truffle
Now to compile, test and deploy your smart contracts, you will need a build framework that will increase
your develop ment velocity compared to doing it manually. We can find truffles on the website https://
archive.trufflesuite.com/.
So we will install truffle using the npm package, make sure to install all previous versions of truffle, as it
will collide.
Now all the steps are done, now we just need a text-editor that will be used to edit our smart contract and
other text files. We can use Atom, Visual Studio or an IntelliJ plugin, whichever you are comfortable with.
1.3. Install and Setup Ethereum Wallet
Obtaining a wallet application is a necessary first step if you are excited to investigate Ethereum and
interact with its wide array of apps. A wallet allows you to engage with different protocols and acts as a
safe place to store your tokens. We'll walk you through setting up the MetaMask wallet in this guide,
which is a popular choice for interacting with Ethereum.
Install MetaMask for your browser, so you can click "Install MetaMask for Chrome."
In order to download a browser extension, this will direct you to the Chrome Web store. A browser
extension is a piece of code that adds more capability to interacting with webpages within your browser.
Make sure you are downloading from a reliable source by checking again.
After selecting "Add to Chrome," I'll click "Add Extension" to install the browser extension.
The extension is accessible in the top right corner with the puzzle piece icon, if you click that, you can
click the pin to make it easier to find.
You have the browser extension now that you have installed MetaMask. After that, a page similar to this
one will appear. This is our first attempt, therefore we'll choose "Create a Wallet."
You can select if you want them to gather analytics on the following stage. I'm going to say "No Thanks."
You now have to make a password. Your computer's MetaMask extension will become unlocked as a
result. After entering your password, select "Create."
It will then direct you to an instructional film that explains how MetaMask functions and what your key
is. I would advise seeing it.
You will lose access to your tokens if you misplace this phrase. Someone else can access your wallet if
they manage to decipher this phrase.
To see the hidden words, click. This sentence has 12 words in it.
You must have a backup copy of this phrase, and I suggest storing it in a password manager. It will verify
that you have backed it up by testing it on the screen that follows.
MetaMask will provide you with some security advice after it has been backed up, which I will reiterate
here:
You have now established your wallet and made a backup of your seed phrase. Well
done!
Using MetaMask
Use MetaMask to transmit and receive Ethereum (ETH) by doing the following steps:
Transferring ETH:
1. Make sure you are logged in and open your MetaMask wallet.
2. Select "Send" from the menu.
3. Fill in the "Recipient Address" field with the recipient's Ethereum address.
Receiving ETH:
1. Make sure you are logged in and open your MetaMask wallet.
2. If you have multiple accounts, click the "Account" button in the upper right corner and choose the one
you want.
3. Take a note of your Ethereum address in the "Account" area.
4. Give the sender this address so they can transfer ETH to your wallet.
Using Solidity
Receiving Ether
Sending Ether
Practical 2
2.1 Create smart contract using solidity.
In blockchain development, a smart contract is a self-executing contract with the terms of the agreement
directly written into code. These contracts are stored on a blockchain and automatically execute when
predetermined conditions are met. Smart contracts are a foundational concept in decentralized
applications (DApps) and are typically written in languages like Solidity for the Ethereum blockchain.
2.2 Create smart contract to connect with front end.
The connection between the smart contract and the front end is established using a web3.js library (for
Ethereum) or similar tools for other blockchains. Web3.js allows the front end to communicate with the
smart contract by providing an interface to interact with the blockchain. This interaction includes
deploying the contract, calling its functions, and listening to events emitted by the contract.
3. Contract Deployment:
● Compile the Solidity code using a Solidity compiler (e.g., Remix, Truffle).
● Deploy the compiled contract to the Ethereum blockchain, either on a testnet (like
Ropsten, Rinkeby) or the mainnet.
2. Deposit Function:
● Implement a function in the smart contract that allows users to deposit funds into their
accounts.
● Update the user’s balance accordingly.
3. Withdrawal Function:
● Implement a function to enable users to withdraw funds from their accounts.
● Ensure that sufficient funds are available before processing the withdrawal.
4. Contract Deployment:
● Compile the Solidity code using a Solidity compiler (e.g., Remix, Truffle).
● Deploy the compiled contract to the Ethereum blockchain, either on a testnet (e.g.,
Ropsten, Rinkeby) or the mainnet.
Practical 3
2. Select “Existing address generated outside this wallet.” Checkbox and enter the “bitcoin address
or private key” from the paper wallet and import.
3. Once bitcoin paper wallet is imported, it’ll be visible under imported bitcoin address
4. To transfer bitcoin from paper wallet to bitcoin wallet, click on “Transfer All” and fill the below
form and continue.
Practical 4
4.1. Write a program in Python to Simulate the blockchain
Theory:
Blockchain is a digital distributed constantly growing ledger that links the digital records called blocks in
a secure manner using cryptographic techniques.It has the property of being
immutable ,transparent ,traceable and decentralized.
Blocks - Blocks are the containers of data which are used to describe a digital information which contains
transactions with their timestamp and cryptographic hash functions.It also consist of a block header which
further have metadata that include hash of prev block ,timestamp,nonce and merkel Root and apart from
header consist of list of transactions.
A block is identified using its hash or height .Block hash is the hashId of block and height defines the
position of block in the blockchain.Merkle tree gives a digital fingerprint of entire set of transactions
Code:
#Creating a blockchain
import datetime
import hashlib
import json
from flask import Flask,jsonify
#building a blockchain
class Blockchain:
def __init__(self):
self.chain=[]
self.create_block(proof=1,previous_hash='0')
def create_block(self,proof,previous_hash):
block={'index':len(self.chain)+1,
'timestamp':str(datetime.datetime.now()),
'proof':proof,
'previous_hash':previous_hash}
self.chain.append(block)
return block
def get_previous_block(self):
return self.chain[-1]
def proof_of_work(self,previous_proof):
new_proof=1
check_proof=False
while check_proof is False:
hash_operation=hashlib.sha256(str(new_proof**2-previous_proof**2).encode()).hexdigest()
if hash_operation[:4]=='0000':
Output
4.2. Write a program of performing hash
Theory:
SHA-256 (Secure Hash Algorithm-256) is a cryptographic hash function designed by the National
Institute of Standards and Technology (NIST) in 2001. It takes an arbitrary message of any length and
outputs a fixed-size (256-bit) hash value. Here's a breakdown of key aspects of SHA-256:
Purpose:
● SHA-256 acts like a digital fingerprint for data. It ensures data integrity by detecting even the
slightest changes in the input message. The same message will always produce the same hash
value, while any alteration will result in a completely different hash.
Applications:
Security:
● SHA-256 is considered a secure hash function. It's resistant to collision attacks (where two
different messages produce the same hash) and preimage attacks (finding the original message
given only the hash). However, as computing power increases, the risk of such attacks grows.
Code:
import hashlib
def blockchain_hash(data):
"""Creates a blockchain hash function using SHA-256.
Args:
data: The data to be hashed.
Returns:
The hash of the data.
"""
sha256 = hashlib.sha256()
sha256.update(data.encode('utf-8'))
return sha256.hexdigest()
# Example usage:
print(hash)
Output
4.3. Write a program to Implement Merkle Tree hashing algorithm using python.
Theory:
Merkle Tree:
A Merkle tree, also called a hash tree, is a data structure used for efficient and secure verification of large
datasets. Here's a breakdown in 3 key points:
1. Structure: Imagine an upside-down tree. Leaves contain hashes of data blocks, and each non-leaf
node holds the hash of its children's hashes. Think of it like a layered summary.
2. Verification Power: The magic lies in hashes. A hash function takes any data and generates a
unique, fixed-size fingerprint. Even slight changes in the data drastically alter the hash. Merkle
trees allow verifying if a specific piece of data belongs to the original dataset without needing the
entire dataset.
3. Applications: Merkle trees find use cases in:
○ Blockchains: They ensure data integrity in blockchains like Bitcoin, where verifying
every transaction within a block would be slow. With a Merkle tree, you can confirm a
specific transaction's presence by checking its hash within the overall block hash.
○ Large File Distribution: They help verify the completeness and accuracy of downloaded
files. You can compare the downloaded file's hash with a verified Merkle tree root hash to
ensure no corruption occurred during transfer.
Code:
import hashlib
def merkle_tree_hash(data_list):
if not data_list:
return None
# Calculate the hash of each pair of elements and add it to the current level
for i in range(0, len(data_list), 2):
concatenated_data = str(data_list[i]) + str(data_list[i + 1])
hash_value = hashlib.sha256(concatenated_data.encode()).hexdigest()
current_level.append(hash_value)
# If there is only one hash value in the current level, return it as the Merkle root
if len(current_level) == 1:
return current_level[0]
Theory:
Mining Bitcoin involves using computer hardware to solve complex mathematical problems that validate
and secure transactions on the Bitcoin network. Miners compete to solve these problems, and the first one
to do so is rewarded with newly minted bitcoins as well as transaction fees.
➢ Hardware Setup: Miners use specialized hardware called ASICs (Application-Specific
Integrated Circuits) designed specifically for mining Bitcoin. These devices are optimized for
performing the necessary calculations efficiently.
➢ Joining a Mining Pool (Optional): Many miners join mining pools to combine their computing
power and increase their chances of successfully mining a block. Rewards are then distributed
among participants based on their contributions.
➢ Mining Software: Miners run mining software on their hardware, which connects them to the
Bitcoin network. This software helps them solve the mathematical problems required to validate
transactions and add them to the blockchain.
➢ Solving the Proof-of-Work Puzzle: The main task of a miner is to solve a cryptographic puzzle
known as the "proof-of-work." This involves repeatedly hashing the block's header in a way that
it meets a certain criteria (difficulty level). The difficulty adjusts regularly to ensure that blocks
are mined, on average, every 10 minutes.
➢ Broadcasting the Solution: Once a miner solves the puzzle, they broadcast the solution to the
rest of the network.
➢ Block Validation and Reward: Other nodes in the network verify the solution provided by the
miner. If it's correct, the new block is added to the blockchain, and the miner receives the block
reward (currently 6.25 bitcoins as of early 2024) along with any transaction fees included in the
block.
➢ Repeat: Mining is an ongoing process, with miners continually competing to solve new blocks
and add them to the blockchain.
Code:
import hashlib
import time
class Block:
def __init__(self, index, previous_hash, timestamp, data, nonce=0, current_hash=None):
self.index = index
self.previous_hash = previous_hash
self.timestamp = timestamp
self.data = data
self.nonce = nonce
self.current_hash = current_hash if current_hash else self.calculate_hash()
def calculate_hash(self):
data_string = f"{self.index}{self.previous_hash}{self.timestamp}{self.data}{self.nonce}"
return hashlib.sha256(data_string.encode()).hexdigest()
class SimpleMiner:
@staticmethod
Output
4.5. Write a program to create own cryptocurrency in python
Theory:
Steps to Create a Simple Cryptocurrency in Python:
1. Initialize Dependencies: Install required Python libraries (e.g., hashlib) for cryptographic
operations.
2. Define the Transaction Structure: Create a class to represent cryptocurrency transactions,
including sender, recipient, amount, and timestamp.
3. Implement the Blockchain Class: Define a class to represent the blockchain, which will contain
methods for adding blocks, validating transactions, and mining new blocks.
4. Implement Mining (Proof of Work): Implement a mining function that solves a computational
puzzle (PoW) to add new blocks to the blockchain.
5. Implement Wallets: Create a mechanism to manage user wallets, including generating public-
private key pairs for transactions.
#Create a Cryptocurrency
# Importing the libraries
import datetime
import hashlib
import json
from flask import Flask, jsonify, request
import requests
from uuid import uuid4
from urllib.parse import urlparse
class Blockchain:
def __init__(self):
self.chain = []
self.transactions = []
self.create_block(proof = 1, previous_hash = '0')
self.nodes = set()
def get_previous_block(self):
return self.chain[-1]
Practical 5
5.1. Write a python program to implement the Proof Of Work Algorithm (consensus Algorithm)
Theory:
Devised by Satoshi Nakamoto and utilized in Bitcoin, the Proof of Work (PoW) algorithm necessitates
miners to solve intricate mathematical problems.
➢ In PoW, miners compete to solve tough math problems, called hashes, to validate transactions and
add blocks to the blockchain. This process requires a lot of computational power. Miners compete
with each other to solve this problem, and the first miner to solve the problem gets rewarded with
new cryptocurrency.
➢ Each block in PoW comprises the hash value of the previous block, a record of transactions, a
nonce, and the current block's hash. The nonce, a specially generated number, is added to a
blockchain block to generate a unique hash that meets a predetermined difficulty level. It serves
to validate transactions and ensures the uniqueness of a block's hash, preventing malicious
alterations to the blockchain. Bitcoin miners endeavor to identify this nonce in a way that the
resulting hash value satisfies specific conditions, allowing them to mine a new block and receive
a block reward.
➢ In PoW, every network node calculates the hash value of the block header, aiming to find a hash
value equal to or smaller than a predefined threshold for consensus. Once a node discovers the
target value, it broadcasts the block to the entire network, and other nodes validate the correctness
of the hash value. If verified, all nodes append the new block to their respective chains.
➢ The security of this algorithm relies on the challenge of solving complex math problems (hashes).
This difficulty makes it costly for someone to attempt to control or take over the network. To do
so, an attacker would need to have a large share of the network's computational power, referred to
as the hash rate. This kind of attack, known as a 51% attack, is hard to execute because it
demands a huge amount of resources.
➢ Advantages of PoW include its decentralized structure, high-security levels, and acceptable
scalability.
➢ However, it comes with drawbacks such as it is energy-intensive, lower throughput, prolonged
block creation times, energy inefficiency, dependency on specialized hardware, high
computational costs, and substantial bandwidth requirements.
Code:
hashlib
import time
class Block:
def __init__(self, index, timestamp, prev_hash, data, nonce, difficulty):
self.index = index
self.timestamp = timestamp
self.prev_hash = prev_hash
self.data = data
self.nonce = nonce
self.difficulty = difficulty
self.hash = self.calculate_hash()
def calculate_hash(self):
return hashlib.sha256((str(self.index) + str(self.timestamp) + str(self.prev_hash) + str(self.data) +
str(self.nonce) + str(self.difficulty)).encode()).hexdigest()
def create_genesis_block(difficulty):
timestamp = int(time.time())
genesis_block = Block(
index=0,
timestamp=timestamp,
prev_hash="0",
data="Genesis Block",
nonce=0,
difficulty=difficulty
)
genesis_block.hash = genesis_block.calculate_hash()
return genesis_block
def generate_new_block_with_pow(prev_block, data, difficulty):
nonce = 0
timestamp = int(time.time())
Proof Of Stake
➢ In contrast to Proof of Work (PoW), where miners solve tough math problems, Proof of Stake
(PoS) uses validators who own a specific amount of cryptocurrency. These validators confirm
transactions and add new blocks to the blockchain.
➢ In a Proof of Stake (PoS) system, validators get picked to add blocks to the chain based on how
much cryptocurrency they own, which is called their "stake." The more cryptocurrency they have
(larger stake), the better chance they have of being chosen to add a block. Validators are
motivated to be honest because they could lose their stake if they validate fake transactions or
attempt to harm the network.
➢ Developed as a response to the drawbacks of Proof of Work (PoW), particularly its energy
inefficiency, Proof of Stake (PoS) operates on the principle that the creator of the next block
should be selected through a combination of random selection, stake supply, and age, promoting
effective scalability. Validators, chosen to add new blocks to the chain, are selected based on the
quantity of cryptocurrency they possess, referred to as their stake. A higher stake increases the
likelihood of being chosen to add a block to the chain. Validators have a strong incentive to
operate honestly since they risk losing their investment if they approve fraudulent transactions or
attempt to harm the network.
➢ Introduced in 2011 with the Peercoin cryptocurrency, PoS does face a challenge known as
"nothing at stake," wherein a node with no stake has no fear of losing anything while behaving
dishonestly. Unlike PoW, PoS does not demand significant computing power for transaction
validation, and miners solely receive transaction fees.
➢ Advantages of PoS include fast block creation times, high throughput, energy efficiency,
scalability (though less than PoW), and independence from specialized hardware.
➢ PoS vs PoW: Proof of Stake (PoS) is better than Proof of Work (PoW) because it uses less energy.
In PoW, miners need a lot of computer power to solve hard math problems, but in PoS, validators
just need to own cryptocurrency. This makes PoS better for the environment and cheaper to run.
➢ Another good thing about Proof of Stake (PoS) is that it encourages decentralization. In Proof of
Work (PoW), miners with the most computing power can have too much control, making the
network too centralized.
➢ In PoS, validators with the most cryptocurrency have more influence, but it's hard for just one or
a few validators to take over because they'd need to own a big amount of cryptocurrency.
➢ However, it has drawbacks such as susceptibility to some centralization and a lower cost
associated with misbehavior in blockchain networks. In a PoS network, validators with the largest
stake have more control over the network, which can lead to centralization.
➢ One possible downside of PoS is that it might create a rich-get-richer situation. This means
validators with the most cryptocurrency keep earning more, making it harder for smaller
validators to join and be a part of the network. Mechanisms to address this issue are: random
selection of validators or limiting the amount of cryptocurrency that a single validator can hold.
Code
import hashlib
import time
class Block:
def __init__(self, index, timestamp, data, prev_hash, nonce, difficulty, hash):
self.index = index
self.timestamp = timestamp
self.data = data
self.prev_hash = prev_hash
self.nonce = nonce
Output
Proof Of Work
Proof of Stake