You are on page 1of 6

ASSIGNMENT - II

IN
Invention And Innovation
In Computing

Submitted To: Submitted By:


Taruna Sharma Sahil Dubey
Assistant Professor Roll No. 2055991625
Class: B.Tech -IT 7th Sem

DEPARTMENT OF APPLIED ENGINEERING


CHITKARA UNIVERSITY
PUNJAB
Question: Implementation of the Blockchain Concept
Smart Contract?
Solution:
Implementing a full-fledged blockchain and a smart contract system from
scratch is a complex task that requires significant expertise in blockchain
technology and programming.
Implementation of the concept by the sample code:
Language: (PYTHON)
import hashlib

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

def calculate_hash(self):
sha = hashlib.sha256()
sha.update((str(self.index) + self.previous_hash + self.data + str(self.timestamp) +
str(self.nonce)).encode())
return sha.hexdigest()

def create_genesis_block():
return Block(0, "0", "Genesis Block", "01/01/2023")

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

def add_block(self, new_block):


new_block.index = len(self.chain)
new_block.previous_hash = self.chain[-1].hash
new_block.hash = new_block.calculate_hash()
self.chain.append(new_block)

def mine_block(block, difficulty):


while block.hash[:difficulty] != "0" * difficulty:
block.nonce += 1
block.hash = block.calculate_hash()

my_blockchain = Blockchain()
block1 = Block(1, my_blockchain.chain[-1].hash, "Transaction 1", "02/01/2023")
mine_block(block1, my_blockchain.difficulty)
my_blockchain.add_block(block1)

for block in my_blockchain.chain:


print(f"Block #{block.index}")
print(f"Previous Hash: {block.previous_hash}")
print(f"Data: {block.data}")
print(f"Timestamp: {block.timestamp}")
print(f"Hash: {block.hash}\n")

Explanation:
import hashlib

# This line imports the ‘hashlib’ library, which is used to perform cryptographic hashing operations,
specifically SHA-256 hashing in this code.

class Block:

# Here, a ‘Block’ class is defined to represent a block in the blockchain.

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

# This is the constructor method for the Block class, which is called when a new block object is
created. It takes four parameters: index (block's position in the blockchain), previous_hash (hash of
the previous block), data (the content of the block, such as transactions), and timestamp (the time
when the block is created).

self.index = index

self.previous_hash = previous_hash

self.data = data

self.timestamp = timestamp

self.nonce = 0 # Proof of Work variable

# In this part of the constructor, the provided parameters are assigned to instance variables of the
‘Block’ object. The ‘nonce’ is set to 0 initially, which is a variable used in the proof-of-work (PoW)
process.

self.hash = self.calculate_hash()

# This line calls the ‘calculate_hash’ method to compute the hash of the block using its attributes
(index, previous hash, data, timestamp, and nonce) and stores it in the hash attribute.

def calculate_hash(self):

# This is the ‘calculate_hash’ method, responsible for generating the SHA-256 hash of the block.
sha = hashlib.sha256()

# Here, a SHA-256 hashing object is created using ‘hashlib.’

sha.update((str(self.index) + self.previous_hash + self.data + str(self.timestamp) +


str(self.nonce)).encode())

# The method updates the hash object with the concatenated string of the block's attributes. Each
attribute is converted to a string, and the entire string is encoded to bytes before being hashed.

return sha.hexdigest()

# The method returns the hexadecimal representation of the hashed value as the block's hash.

def create_genesis_block():

# This function, ‘create_genesis_block’, is used to create the first block in the blockchain, known as
the "genesis block."

return Block(0, "0", "Genesis Block", "01/01/2023")`

# It returns a ‘Block’ object with index 0, a previous hash of "0" (indicating it's the first block), the
data "Genesis Block," and a timestamp of "01/01/2023."

self.chain = [create_genesis_block()]

# A list called ‘chain’ is created, and the first block (genesis block) is added to it using the
‘create_genesis_block’ function.

self.difficulty = 4

The difficulty attribute is set to 4, which represents the number of leading zeros required in a mined
block's hash to satisfy the proof-of-work.

def add_block(self, new_block):

This method allows adding a new block to the blockchain.

new_block.index = len(self.chain)

The ‘index’ of the ‘new_block’ is set to the current length of the blockchain, which effectively assigns
the next sequential index to the new block.

new_block.previous_hash = self.chain[-1].hash

The ‘previous_hash’ of the ‘new_block’ is set to the hash of the last block in the chain, ensuring the
blockchain's integrity.

new_block.hash = new_block.calculate_hash()

The ‘calculate_hash’ method is called on the new_block to compute its hash, effectively mining the
block.

self.chain.append(new_block)

# The new block is added to the blockchain's chain list.


def mine_block(block, difficulty):

# This function takes a Block object and a difficulty value as parameters and is responsible for mining
the block until its hash meets the proof-of-work requirements.

while block.hash[:difficulty] != "0" * difficulty:

This loop continues until the block's hash has the required number of leading zeros (determined by
difficulty).

block.nonce += 1

The ‘nonce’ of the block is incremented with each iteration of the loop, which changes the block's
content and, therefore, the hash.

block.hash = block.calculate_hash()

# The ‘calculate_hash’ method is called to recompute the block's hash after modifying the nonce.

my_blockchain = Blockchain()

# An instance of the Blockchain class is created to represent the blockchain.

block1 = Block(1, my_blockchain.chain[-1].hash, "Transaction 1", "02/01/2023")

# A new Block object is created with index 1, the previous hash is set to the hash of the last block in
the chain, the data is set to "Transaction 1," and the timestamp is "02/01/2023."

mine_block(block1, my_blockchain.difficulty)

# The ‘mine_block’ function is called to mine the block1 with the blockchain's specified difficulty.

my_blockchain.add_block(block1)

# The mined block1 is added to the blockchain.

for block in my_blockchain.chain:

# This loop iterates through each block in the blockchain.

print(f"Block #{block.index}")

print(f"Previous Hash: {block.previous_hash}")

print(f"Data: {block.data}")

print(f"Timestamp: {block.timestamp}")

print(f"Hash: {block.hash}\n")

# It prints the index, previous hash, data, timestamp, and hash of each block in the blockchain.

# This code represents a simplified blockchain implementation with proof of work in Python. It is
essential to understand that this is a basic demonstration, and real-world blockchain systems involve
many more complexities, including network communication, consensus algorithms, transaction
validation, and security considerations.
OUTPUT:

You might also like