Blockchain Practical 5-8
Blockchain Practical 5-8
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
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 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()
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>
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
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
@staticmethod
def check_validity(block, prev_block):
if prev block.index +1!= block.index:
return False
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]
@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()
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
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
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
Page l
(SESEM-V/BCF/PR07
& Technology, Amravn4:
Sipna College of Engineering Science
Department of Computer & Engineering
Session 2022-2023
Implementation:
NA
contract HelloWorld
string public greet= "Hello World!";
NC
rovi
lo
"inputs'": [1,
"name": "greet",
log "outputs": [
"internalType'": "string",
"name'"; ".
"type'": "string"
"stateMutability": ""view",
"type'": ""function'"
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
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
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:
verify
Oxdca33226ad7e81121bf9cf9c12333e6b227l
3rdleaf abe823ec9edfe42f813ble768fa57b
root
Page 3
(SE<EM-V/BCF/PRO8
Oxcc086fcc038189h4641db2cc4f de3bb132aefbd65d510d817591550937818c7
index
2
proof
UXBda9elc820f9dbd1589fd6585872bc1063588625 729e7ab0797cfc63a00bd950
Ox995788ffc103b987ad50fSes707fdo94419eb12d9552cc423bdOcd86a3861433
*/
"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"