0% found this document useful (0 votes)
39 views12 pages

Blockchain Practical 5-8

Uploaded by

CHEDE AACHAL
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views12 pages

Blockchain Practical 5-8

Uploaded by

CHEDE AACHAL
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/ 12

Sipna College of

Department ofEngiComput
neering &
Technol&ogy, Amravati.
Session e2022-2023
r Science
Branch :- (
Subject :-Block
Computer Sci.
Chain
&
Engg- Engineering
FundamentalsTeacher
Lab manual
Manual
Class :- Final Year
Sem :- VII

AIM: Create a simple BlockChain


PRACTICAL NO 5
S/W REQUIRED: Phython
Block Chain

Lock chain is a
distributed
database, a block chain storesdatabase ledger that is shared amongthe nodes ofa
or
ir crucial role in information electronicallyin digital format. computer network. AS a
cyprocurrency
dof transactions. The systems, such as Block chains are best known for
Bitcoin, for maintaining a secure and
innovation with a block chain is that it decentral1zed
record of data and generates trust
without the need for atrusted guarantees the fidelity and security oT a
third party.
Implementation:
from hashlib import sha256
import time

class block:
def init (self, timestamp, data, previousHash ="):
self.timestamp = timestamp
self.data = data
self.previousHash previousHash
self.hash =self.calculateHash()

def calculateHash(self):
return sha256((str(self.timestamp) + str(self.data) +
str(self.previousHash)).encode()).hexdigest()

class blockchain:
def init (self):
self.chain = (self.createGenesis()]

def create Genesis(selt): "00000")


block(time.ctime(), "genesisBlock",
return
def mineBlock(self, data): self.chain[-1].hash)
block(time.ctime(), data,
node = blockchain
mining a new block to the
# self.chain.append(node)

def printBlockchain(self):
range(len(self.chain)): -\ntimestamp ="|
print("n-----Block ", i"---...
for iin timestamp."ndata=",i
self.chainfi].
,
previousHash =",\
self.chain[i].data, "\n ",\
self.chain[i].previousHash,"\n hash =
self.chain[i],hash)

CEVcoin = blockchain)

data = input()

# sending data to get mined


ECHN
-->")
print("\nln ---> Mining New Block
CEVCoin.mineBlock(data)
")
print("nln ----> New Block mined successfully -->
CEVcoin.printBlockchain()
ro

ci

Output:
- New Block mined successfully ->

-Block e
tÉmestamp = Thu Aug 18 13:42:34 2022
data = genesisBlock
previousHash = 00000
hash = d35695bf15937b88e66f362bff9ba94ea329cce7alb2b690127e38fd18b766d9

---Block 1
timestamp = Thu Aug 18 13:44:22 2022
data -
previousHash = d35695bf15937b88e66f362bff9ba94ea329cce7a1b2b690127e38Fdi8b765d9
hash = S46e3f89d05247109797e377309fedf1bSe89c2917a769ee7eff8fes44a949cd
S C:\Users\PC-1059\hello>
S C:\Users\PC-1059\hello>

CONCLUSION: Thus we have created a block chain

CSE/SEM-V/BCF/PROS
classmt
t*23
Sipna College of
Department ofEngiComputer
neering Science
&
Technol&ogy, Amravatl.
Session 2022-2023
Branch:- Computer Sci. &
Subject :-Block Chain Engg-
Engineering
FundamentalsTeacher
Lab manual
Manual
Class :- Final Year
Sem :- VII

PRACTICAL NO 6
AIM: Create Your Own
Cryptocurrency Using Python
SW REQUIRED: Phython

Cryptocurrency

Incomputer science, a cryptocurrency, crypto-currency, or crypto is adigital currency that does not rely on
anycentral authority to uphold or maintain it. Instead, transaction and ownership data is stored in a digital
ledger using distributed ledger technology, typically a blockchain.
ACryptocurrency is a system that meets six conditions:
1. The system does not require a central authority; its state is maintained through distributed consensus.
2. The system keeps an overview of cryptocurrency units and their ownership.
3. The system defines whether new cryptocurrency units can be created. If new cryptocurrency unts
can be created, the system defines the circumstances of their origin and how to determine the
ownership of these new units.
4. Ownership of cryptocurrency units can be proved exclusively cryptographically.
5. The system allows transactions to be performed in
which ownership of the cryptographic units is
entity proving the current ownership of
changed. A transaction statement can only be issued by an
these units. units are
different instructions for changing the ownership of the same cryptographic
6. If two one of them.
simultaneously entered, the system performs at most

Implementation:

import hashlib
import time

class Block:
timestamp=None):
index,proof no, prev hash, data,
def Init__(self,
self.index = index
self.proof no = proof no
self.prev hash = prev hash
self.data = data time.time)
timestamp or
self.timestamp=
@property self.proof no,
"0000"format(self.index,
def calculate hash(self):
self.prev hash,self.data,
block of string =
self.timestamp)
)
return

return hashlib.sha256(block of string.encode()).hexdigest() Qstati

defpro
def repr (self):
return "{} - -0--0".format(self.index, self.proof_no, "thi
self.prev hash, self.data, fis
self.timestamp) fis

pr
class BlockChain: w

def init (self):


self.chain =]
self.current data =[)
self.nodes = set()
self.construct genesis() def
def construct genesis(self):
self.construct block(proof no-0, prev hash-0)
def construct block(self, proof no, prev hash):
block Block(
index=len(self.chain),
proof no=proof no,
prev hash=prev hash,
data=self.current data)
self.current_data = ]
self.chain.append(block)
return block

@staticmethod
def check_validity(block, prev_block):
if prev block.index +1!= block.index:
return False

elif prev block.calculate hash != block.prev hash:


return False

elif not BlockChain.verifying proof(block.proof_no,


prev_block.proof no):
return False

elif block.timestamp <= prev_block.timestamp:


return False

return True

def new data(self, sender, recipient, quantity):


self.current data.append({
'sender': sender,
recipient': recipient,
'quantity': quantity
CSE/SEM-V/BCFPR06
return True

Qstaticmethod
def proof_of_work(last_proof:
"this simple algorithm identifies a number f such that hash(ff')
fis the previous f contain 4leading zeroes
fis the new proof

proof no =0
while BlockChain. verifying proof(proof no, last proof) is False:
proof no +=1

return proof no

Ostaticmethod
def verifying proof(last proof, proof):
#yerifying the proof: does hash(last proof, proof) contain 4 leading
zeroes?
guess = f{last proof {proof}".encode()
guess hash = hashlib.sha256(guess).hexdigest()
return guess hash:4]== "0000"

@property
def latest block(sel):
return self.chain[-1]

def block mining(self, details miner):


self.new data(
sender="Sipna COET", ##t implies that this node has created a new block
receiverFdetails miner,
quantity=
1, #creating a new block (or identifying the proof number) is awarded with1

last block = self.latest block

last proof no = last block.proofno


proof no = self.proof of work(last proofno)
last_hash= last block.calculate hash
block = self.construct block(proof no, last_hash)
return vars(block)
def create node(self, address):
self.nodes.add(address)
return True

@staticmethod
def obtain block object( block_data):
#obtains block object from the block data Page 3
Page2

CSE/SEM-V/BCE/PRO6
return Block(
block data['index'],
block data•'proof no'],
block data['prev hash'],
block data['data'],
timestamp=block_ data['timestamp')
blockchain = BlockChain()

print("***Mining fccCoin about to start***")


AIM
print(blockchain.chain)
last block = blockchain.latest block
last proof no = last block.proof_no A "
proofno = blockchain.proof of work(last proof_no) func

blockchain.new data Sm
sender='"Sipna COET", #it implies that this node has created a new block trar
recipient="SIPNA CSE Department", #let's send Sipna CSE some coins! pro
quantity=
1, #creating a new block (or identifying the proof number) is awarded with 1 aul
) the

last hash = last block.calculate hash B


block = blockchain.construct block(proof no, last_hash)
print("***Mining fccCoin has been successful***")
print(blockchain.chain)

Output:
PS CAUsers\PC-1059\hello> & 'C:APython3 10\python.exe c:\Users\PC-1059\.vscodelextensionst
python.python-2022. 14.0pythonFileslib\pythondebugpyladapter/./.\debugpy\launcher 'S1936
'c:\Users\PC-1059\hello\cryptocurrency.py'
***Mining fecCoin about to start***
[o -0 -0 -[]- 1662359736.2395442]
***Mining fccCoin has been successful***
0 88914
[0 1662359736.2395442,
cfDl d26b936ebe87a464b53979bbd9ceS l ebeSfdS0e6ba3b96cd6d4ae780dd80- [{f'sender': 'Sipna
recipient':'SIPNA CSEDepartment, 'quantity': 1}]- 1662359736.6053078]
PS CAUsers\PC-1059\hello>

CONCLUSION: Thus we have studied and created our own Cryptocurrency Using Python.

/SEM-V/BCF/PR06
Sipna College of
Department Engineering
of
Computer
&
Technology,
Science &
Amravati.
Session 2022-2023 Engineering
Branch :-Computer Sci. & Engo.
Subject :-Block Chain
FundamentalsTeacher
Lab manual
Manual
Class :- Final Y ear
Sem :- VII

PRACTICAL NO 7
AIM: Design a simple Smart contract

oW REQUIRED: Remix IDE


contract" is
A"smar simply a
data (its state) that program
iunctions) and
that runs on the
Ethereum blockchain. It's a collection of code (its
resides at aspecific address on the Ethereum blockchain.
Smart contracts are a type of Ethereum account, This means they have a balance and can be the target of
ASactions. However they're not controlled by a user. instead they are deploved to the
oorammed. User accounts can then interact with a smart contract by submitting network and run a
transactions that execut a
Mnction delned On tne smart contract. Smart contracts can define rules, like a regular contract, and
omatically enforce them via the code. Smart contracts cannot be deleted by default, and interactions Wim
tiem are irreversible.

Benefits of smart contracts

1. Speed, efficiency and accuracy: Once a condition is met, the contract is executed immediately.
Because smart contracts are digital and automated, there's no paperwork to process and no time
spent reconciling errors that often result from manually filling in documents.
2. Trust and transparency: Because there's no thírd party involved, and because encrypted records of
transactions are shared across participants, there's no need to question whether information has been
altered for personal benefit.
very hard to hack.
3. Security: Blockchain transaction records are encrypted, which makes them on adistributed
Moreover, because each record is connected to the previous and subsequent records
single record.
. ledger, hackers would have to alter the entire chain to change a transactions and, by extension.
intermediaries to handle
4. Savings:Smart contracts remove the need for
their associated time delays and fees.
for writing smart contracts:
Eihereum has developer-friendly languages

Solidity
Vyper

We will be using solidity

Solidity: buildingsmart contracts on Ethereum Blockchain. It's


for
most popular languages used code is encapsulated in contracts which means a
Solidity one
is of the
programming language.
Solidity's specific address
data(its state) that resides at a Ethereum.
also an object-oriented functions) and on
Contract in Solidity is a collection
of code (its
fundamental block of building an application
contract is a
on the Ethereum blockchain, A

Page l

(SESEM-V/BCF/PR07
& Technology, Amravn4:
Sipna College of Engineering Science
Department of Computer & Engineering
Session 2022-2023

Implementation:
NA

I/SPDX-License-Identifier: MIT than 0.9.0


compiler version must be greater than or equal to 0.8.13 and less
TECHNO
/
pragma solidity ^0.8.13;

contract HelloWorld
string public greet= "Hello World!";
NC
rovi

cier Output: Byte code generated as well as APIgenerated


ON
APIcode
eat
nt

lo
"inputs'": [1,
"name": "greet",
log "outputs": [
"internalType'": "string",
"name'"; ".
"type'": "string"

"stateMutability": ""view",
"type'": ""function'"

CONCLUSION: Thus we have created a simple Smart contract


claceste
Sipna College of
Department ofEngineering & Ttanl23
Computer Technol&ogy, Amravati.
Science
Session 2022-2023
Branch
;-Computer
Subject :-Block Sci. & Engineering
Chain Engg.
FundamentalsTeacher
Lab manual
Manual
Class :- Final Year
Sem :- VII

AIM: Create a smart PRACTICAL NO8


contract for Merkle tree
s/W REQUIRED: Remix
IDE
Merkle tree is a fundamental part of
bashes of different blocks blockchain technology. It is a mathematical data
of data, and
allows for efficient and secure which serves as a summary of all the structure composed of
verification of
consistency and content of the data. Both Bitcoincontent in transactions
a large body of data. It in a block. It also
also known as Hash Tree. and Ethereum use Merkle Trees also helps to verify the
structure. Merkle Tree is
The concept of Merkle Tree is named
after Ralph Merkle, who
every leaf node labelled with thepatented
is a data structure tree in which the idea in 1979. Fundamentally, it
labelled with the cryptographic hash of the labels of its child hash of a data block, and the non-leaf node
the tree. nodes. The leaf nodes are the lowest node in

How does merkle tree works?

AMerkle tree stores all the transactions in ablock by producing a digital fingerprint of the entire set of
transactions. It allows the user to verify whether a transaction can be included in a block or not.
Merkle trees are created by repeatedly calculating hashing pairs of nodes until there is only one hash left.
This hash is called the Merkle Root, or the Root Hash. The Merkle Trees are constructed in a bottom-up
approach.
Every leaf node is ahash of transactional data, and the non-leaf node is ahash of its previous hashes. Merkle
an odd number of
trees are in a binary tree, so it requires an even number of leaf nodes. If there is
transactions, the last hash will be duplicated once to create an even number of leaf nodes.
Merkle Root
Hasho123

Hasho1
Hasho1

Hash3
Hash2
Hash1
Hash0

TX4
TX3
TX2
TX1
The above example is the most common and simple form ofa Merkle tree, i.e.,
are four transactions in a block: TX1. TX2, TX3, Binary Merkle
and TX4. Here you can see, there is a top
hash of the entire tree, known hash Tree. There
stored in each leaf node, as the Root Hash. or the Merkle Root. Each of these is repeatedly
which is the if (ing
summarized resulting
in a parent node in Hash 0, 1, 2, and 3. Consecutive pairs of leaf
hashed, ha
hashing Hash0 and Hashl, resulting in Hash01, and nodes are thanden
Hash2 and Hash3, resulting inbyHash23. } els
separalely
produce the Root Hash or the Merkle Root. The (wo hashes (Hash01 and Hash23) are then hashed hashing
again to
h

Merkle Root is stored in the block inc


in the process of mining, It header. The block header is the part of the bitcoin block
contains hash of the last block, a Nonce, and the Root which gets hash
transactions in the current block in a the Tree. So having the Merkle root in block Hash of all the
transaction tamper-proof. As this Root Merkle Hash includes the hashes of all the transactions header makes the retu
these transactions may result in saving the disk space. within the block.
Block Header contrac

byte
Last
Block
Hash of Last Block Nonce New Con
Block
Merkle Root

The Merkle Tree maintains the integrity of the data. If any single
detail of transactions or order of h
transaction's changes, then these changes reflected in the hash of that
cascade up the Merkle Tree to the Merkle Root, changing the value of the transaction. This change wotà
the block. So everyone can see that Merkle tree allows for a Merkle root and thus invalidatine
transaction is included in the set or not. quick and simple test of whether a sDecifie

Merkle trees have three benefits:

It provides a means to maintain the integrity and


It helps in saving the memory or disk space as
validity of data.
the proofs, computationally easy and fast.
Their proofs and management require tiny amountsof
information to be transmitted across networks.
Implementation:

I| SPDX-License-ldentifier: MIT
pragma solidity ^0.8.13;
contract MerkleProof!
function verify
bytes32[] memory proof,
bytes32 root,
bytes32 leaf,
uint index
) public pure returns
(bool){
bytes32 hash = leaf;
for (uint i=0; i<
proof.length: it+) {
bytes32 proofElement = proofi];
hich the.
Ashed. aT0
$ are lhen
y hashing
if (index o2 = 0)
hash = 1ol23
1 again lo }else
hash = kec ak256(abi.encodePacked(hash, proofElement);
2etfalls hashthe kec ak256(abi.encodePacked(pro fElement,
index = index / 2:
hash)); 2

25
kes the eturn hash
36

block. root:
l6

TestMerkleProof is MerkleProof {
Hites32||public hashes:
constructor() {
suring[4] memory transactions =
"alice -> bob".
"bob -> dave".
"carol -> alice".
"dave ->> bob"
he
:
for (uint i= 0; i <transactions.length; it+) {
hashes.push(keccak256(abi.encodePacked(transactions[iD):

uint n = transactions.length;
uint offset = 0;

while (n> 0) {
-1;it=2){
for (uint i= 0; i<n
hashes.push(
keccak256(
abi.encodePacked(hashes[offset +i], hashes[offset +i+ 1])

oftset += n;
n =n/2:

function getRoot() public view returns (bytes32) {


returnhasheslhashes.length
- 1];

verify
Oxdca33226ad7e81121bf9cf9c12333e6b227l
3rdleaf abe823ec9edfe42f813ble768fa57b

root
Page 3
(SE<EM-V/BCF/PRO8
Oxcc086fcc038189h4641db2cc4f de3bb132aefbd65d510d817591550937818c7

index
2

proof
UXBda9elc820f9dbd1589fd6585872bc1063588625 729e7ab0797cfc63a00bd950
Ox995788ffc103b987ad50fSes707fdo94419eb12d9552cc423bdOcd86a3861433
*/

Output: Byte code generated as well as API generated


APIcode

"inputs": [
"internalType": "bytes32[]",
"name": "proof",
"type"; "bytes32[]"

"internalType"; "bytes32",
"name": "root",
"type": "bytes32"

"internalType": "bytes32",
"name": "leaf",
"type": "bytes32"

"internalType": "uint256",
"name": "index"
"type": "uint256"
}

"name": "verify",
"outputs": [

"internalType": "bool",
"name":
"type": "boo|"

"stateMutability": "pure",
"type": "function"

You might also like