0% found this document useful (0 votes)
8 views

Practical 02 FBC

The document outlines practical exercises aimed at understanding blockchain concepts, including creating a Merkle tree, a block for blockchain, and implementing blockchain programming code. It provides sample Python code for building a Merkle tree and a simple blockchain structure, demonstrating how to create blocks and calculate hashes. Additionally, it includes examples of adding blocks to the blockchain and displaying the chain.

Uploaded by

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

Practical 02 FBC

The document outlines practical exercises aimed at understanding blockchain concepts, including creating a Merkle tree, a block for blockchain, and implementing blockchain programming code. It provides sample Python code for building a Merkle tree and a simple blockchain structure, demonstrating how to create blocks and calculate hashes. Additionally, it includes examples of adding blocks to the blockchain and displaying the chain.

Uploaded by

maitrikjoshi2007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

4361603 Foundation of Black Chain 226370316001

Practical: - 02
Aim: - Implement following concept to understand the
Blockchain and its implementation.
2.1 Creating a Merkle tree.
2.2 Creation of a block for Blockchain.
2.3 Block chain Implementation Programming code.
2.4 Creating ERC20 token.
2.5 Java code to implement Blockchain in Merkle Trees.
2.6 Java Code to implement Mining using Blockchain.
4361603 Foundation of Black Chain 226370316001

Practical: - 02
Aim: - Implement following concept to understand the
Blockchain and its implementation.
2.1 Creating a Merkle tree.

from typing import List


import hashlib

class Node:
def __init__(self, left, right, value: str, content, is_copied=False) -> None:
self.left: Node = left
self.right: Node = right
self.value = value
self.content = content
self.is_copied = is_copied

@staticmethod
def hash(val: str) -> str:
return hashlib.sha256(val.encode('utf-8')).hexdigest()

def __str__(self):
return (str(self.value))

def copy(self):
"""
class copy function
"""
return Node(self.left, self.right, self.value, self.content, True)

class MerkleTree:
4361603 Foundation of Black Chain 226370316001

def __init__(self, values: List[str]) -> None:


self.__buildTree(values)

def __buildTree(self, values: List[str]) -> None:

leaves: List[Node] = [Node(None, None, Node.hash(e), e)


for e in values]
if len(leaves) % 2 == 1:

leaves.append(leaves[-1].copy())
self.root: Node = self.__buildTreeRec(leaves)

def __buildTreeRec(self, nodes: List[Node]) -> Node:


if len(nodes) % 2 == 1:

nodes.append(nodes[-1].copy())
half: int = len(nodes) // 2

if len(nodes) == 2:
return Node(nodes[0], nodes[1], Node.hash(nodes[0].value +
nodes[1].value), nodes[0].content+"+"+nodes[1].content)

left: Node = self.__buildTreeRec(nodes[:half])


right: Node = self.__buildTreeRec(nodes[half:])
value: str = Node.hash(left.value + right.value)
content: str = f'{left.content}+{right.content}'
return Node(left, right, value, content)

def printTree(self) -> None:


self.__printTreeRec(self.root)
4361603 Foundation of Black Chain 226370316001

def __printTreeRec(self, node: Node) -> None:


if node != None:
if node.left != None:
print("Left: "+str(node.left))
print("Right: "+str(node.right))
else:
print("Input")

if node.is_copied:
print('(Padding)')
print("Value: "+str(node.value))
print("Content: "+str(node.content))
print("")
self.__printTreeRec(node.left)
self.__printTreeRec(node.right)

def getRootHash(self) -> str:


return self.root.value

def mixmerkletree() -> None:


elems = ["Jai ", "Shree", "Ram"]
print("Inputs: ")
print(*elems, sep=" | ")
print("")
mtree = MerkleTree(elems)
print("Root Hash: "+mtree.getRootHash()+"\n")
mtree.printTree()

mixmerkletree()
4361603 Foundation of Black Chain 226370316001

Output: -
4361603 Foundation of Black Chain 226370316001

Practical: - 02
Aim: - Implement following concept to understand the
Blockchain and its implementation.
2.2 Creation of a block for Blockchain.

import hashlib
import time

class Block:
def __init__(self, index, data, previous_hash=''):
self.index = index
self.timestamp = time.time()
self.data = data
self.previous_hash = previous_hash
self.hash = self.calculate_hash()

def calculate_hash(self):
return hashlib.sha256(f'{self.index}{self.timestamp}{self.data}
{self.previous_hash}'.encode()).hexdigest()

block = Block(0, "Genesis Block", "0")

print(f'Index: {block.index}')
print(f'Timestamp: {block.timestamp}')
print(f'Data: {block.data}')
print(f'Previous Hash: {block.previous_hash}')
print(f'Hash: {block.hash}')

Output: -
4361603 Foundation of Black Chain 226370316001

Practical: - 02
4361603 Foundation of Black Chain 226370316001

Aim: - Implement following concept to understand the


Blockchain and its implementation.
2.3 Block chain Implementation Programming code.

import hashlib
import time

class Block:
def __init__(self, index, previous_hash, timestamp, data, hash_value):
self.index = index
self.previous_hash = previous_hash
self.timestamp = timestamp
self.data = data
self.hash_value = hash_value

def __repr__(self):
return f"Block(index={self.index}, timestamp={self.timestamp}, data={self.data},
hash={self.hash_value}, prev_hash={self.previous_hash})"

class Blockchain:
def __init__(self):
self.chain = []
self.create_genesis_block()

def create_genesis_block(self):
genesis_block = Block(0, "0", int(time.time()), "Hello World",
self.calculate_hash(0, "0", int(time.time()), "Hello World"))
self.chain.append(genesis_block)

def calculate_hash(self, index, previous_hash, timestamp, data):


"""
4361603 Foundation of Black Chain 226370316001

Create a SHA-256 hash of a block


"""
block_string = f"{index}{previous_hash}{timestamp}{data}"
return hashlib.sha256(block_string.encode('utf-8')).hexdigest()

def add_block(self, data):


"""
Add a new block to the chain
"""
previous_block = self.chain[-1]
new_index = previous_block.index + 1
timestamp = int(time.time())
hash_value = self.calculate_hash(new_index, previous_block.hash_value,
timestamp, data)
new_block = Block(new_index, previous_block.hash_value, timestamp, data,
hash_value)
self.chain.append(new_block)

def display_chain(self):
"""
Print the entire blockchain
"""
for block in self.chain:
print(block)

if __name__ == "__main__":
blockchain = Blockchain()
blockchain.add_block("Jai Shree Ram")
blockchain.add_block("Information Techonology")
blockchain.display_chain()

Output: -
4361603 Foundation of Black Chain 226370316001

You might also like