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

Blockchain Assignment

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Blockchain Assignment

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Blockchain Assignment

Q.1) Demonstration of Blockchain

Q.2) Installation of Ganache, Flask and Postman


$ npm install --global --production windows-build-tools

$ git clone https://github.com/trufflesuite/ganache.git

$ cd ganache

$ npm install
Q.3) Write a Simple Python program to create a Block class that contains
index, timestamp, and previous hash. Connect the blocks to create a
Blockchain.

# For timestamp
import datetime

# Calculating the hash


# in order to add digital
# fingerprints to the blocks
import hashlib

# To store data
# in our blockchain
import JSON

# Flask is for creating the web


# app and jsonify is for
# displaying the blockchain
from flask import Flask, jsonify

class Blockchain:

# This function is created


# to create the very first
# block and set its hash to "0"
def _init_(self):
self.chain = []
self.create_block(proof=1, previous_hash='0')

# This function is created


# to add further blocks
# into the chain
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

# This function is created


# to display the previous block
def print_previous_block(self):
return self.chain[-1]

# This is the function for proof of work


# and used to successfully mine the block
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[:5] == '00000':
check_proof = True
else:
new_proof += 1

return new_proof

def hash(self, block):


encoded_block = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(encoded_block).hexdigest()

def chain_valid(self, chain):


previous_block = chain[0]
block_index = 1

while block_index < len(chain):


block = chain[block_index]
if block['previous_hash'] != self.hash(previous_block):
return False

previous_proof = previous_block['proof']
proof = block['proof']
hash_operation = hashlib.sha256(
str(proof*2 - previous_proof*2).encode()).hexdigest()

if hash_operation[:5] != '00000':
return False
previous_block = block
block_index += 1

return True

# Creating the Web


# App using flask
app = Flask(_name_)

# Create the object


# of the class blockchain
blockchain = Blockchain()

# Mining a new block


@app.route('/mine_block', methods=['GET'])
def mine_block():
previous_block = blockchain.print_previous_block()
previous_proof = previous_block['proof']
proof = blockchain.proof_of_work(previous_proof)
previous_hash = blockchain.hash(previous_block)
block = blockchain.create_block(proof, previous_hash)

response = {'message': 'A block is MINED',


'index': block['index'],
'timestamp': block['timestamp'],
'proof': block['proof'],
'previous_hash': block['previous_hash']}

return jsonify(response), 200

# Display blockchain in json format


@app.route('/get_chain', methods=['GET'])
def display_chain():
response = {'chain': blockchain.chain,
'length': len(blockchain.chain)}
return jsonify(response), 200

# Check validity of blockchain


@app.route('/valid', methods=['GET'])
def valid():
valid = blockchain.chain_valid(blockchain.chain)

if valid:
response = {'message': 'The Blockchain is valid.'}
else:
response = {'message': 'The Blockchain is not valid.'}
return jsonify(response), 200

# Run the flask server locally


app.run(host='127.0.0.1', port=5000)
Output (mine_block):
{
"index":2,
"message":"A block is MINED",
"previous_hash":"2d83a826f87415edb31b7e12b35949b9dbf702aee7e383cba
b119456847b957c",
"proof":533,
"timestamp":"2020-06-01 22:47:59.309000"
}
Output (get_chain):

{
"chain":[{"index":1,
"previous_hash":"0",
"proof":1,
"timestamp":"2020-06-01 22:47:05.915000"},{"index":2,
"previous_hash":"2d83a826f87415edb31b7e12b35949b9dbf702aee7e383cba
b119456847b957c",
"proof":533,
"timestamp":"2020-06-01 22:47:59.309000"}],
"length":2
}
Output(valid):

{"message":"The Blockchain is valid."}


Like
11
Previous
Next
RECOMMENDED ARTICLES
Page :
1
2
3
4
5
6
Python | Create a simple assistant using Wolfram Alpha API.
18, Oct 19
Create a Simple Two Player Game using Turtle in Python
20, Aug 20
Create a simple Animation using Turtle in Python
11, May 20
Decentralized Voting System using Blockchain
22, May 20
Python | Create simple animation for console-based application
16, Apr 19
How to create a simple drawing board in Processing with Python Mode?
25, Nov 21
Blockchain vs Bitcoin
09, Nov 18
Flutter and Blockchain - Hello World Dapp
09, Mar 21
How to use GANACHE Truffle Suite to Deploy a Smart Contract in Solidity
(Blockchain)?
11, Oct 20
Introduction to Blockchain technology | Set 1
18, Jul 18
Introduction to Blockchain technology | Set 2
24, Jul 18
How Does the Blockchain Work?
14, Aug 18
Blockchain Forks
07, Jan 19
Types of Blockchain and Chain Terminology
14, Feb 19
Blockchain to Secure IoT Data
01, Aug 19
Difference between Blockchain and a Database
06, Nov 19
What Are Cryptoasssets in Blockchain
14, Nov 19
Blockchain in Brief
14, Nov 19
Basics of the Blockchain and its various applications
02, Dec 19
Proof of Stake (PoS) in Blockchain
11, Dec 19
Features of Blockchain
05, Feb 20
How does BlockChain support Crowdfunding ?
17, Feb 20
Demur-rage currencies in Blockchain
17, Feb 20
Blockchain Gaming : Part 1 (Introduction)
19, Feb 20
Article Contributed By :
https://media.geeksforgeeks.org/auth/avatar.png
gluttony777
@gluttony777
Vote for difficulty
Current difficulty : Hard
Easy
Normal
Medium
Hard
Expert
Improved By :
simranarora5sos
nikunjbaid
punamsingh628700
Article Tags :
BlockChain
python-utility
Python
Improve Article
Report Issue
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and
share the link here.

Load Comments

WHAT'S NEW

Python Programming Foundation -Self Paced Course


View Details

Complete Interview Preparation


View Details

System Design-Live Classes for Working Professionals


View Details

MOST POPULAR IN PYTHON


How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python Lists
sum() function in Python
Convert integer to string in Python

MORE RELATED ARTICLES IN PYTHON


Print lists in Python (4 Different Ways)
*args and **kwargs in Python
Python | Get a list as input from user
Defaultdict in Python
Python Classes and Objects

Q.4) Demo of Remix-Ethereum IDE and Test Networks

Q.5) Write a Simple Smart Contract for Bank with withdraw and deposit
functionality.

Open code in remix IDE

// SPDX-License-Identifier: MIT

pragma solidity >=0.4.22 <0.7.0;


contract banking{

mapping(address=>uint) public userAccount;

mapping(address=>bool) public userExists;

function createAcc() public payable returns(string memory){

require(userExists[msg.sender]==false,'Account Already Created');

if(msg.value==0){

userAccount[msg.sender]=0;

userExists[msg.sender]=true;

return 'account created';

require(userExists[msg.sender]==false,'account already created');

userAccount[msg.sender] = msg.value;

userExists[msg.sender] = true;

return 'account created';

function deposit() public payable returns(string memory){

require(userExists[msg.sender]==true, 'Account is not created');

require(msg.value>0, 'Value for deposit is Zero');


userAccount[msg.sender]=userAccount[msg.sender]+msg.value;

return 'Deposited Succesfully';

function withdraw(uint amount) public payable returns(string memory){

require(userAccount[msg.sender]>amount, 'insufficeint balance in


Bank account');

require(userExists[msg.sender]==true, 'Account is not created');

require(amount>0, 'Enter non-zero value for withdrawal');

userAccount[msg.sender]=userAccount[msg.sender]-amount;

msg.sender.transfer(amount);

return 'withdrawal Succesful';

function TransferAmount(address payable userAddress, uint amount)


public returns(string memory){

require(userAccount[msg.sender]>amount, 'insufficeint balance in


Bank account');

require(userExists[msg.sender]==true, 'Account is not created');

require(userExists[userAddress]==true, 'to Transfer account does not


exists in bank accounts ');

require(amount>0, 'Enter non-zero value for sending');

userAccount[msg.sender]=userAccount[msg.sender]-amount;
userAccount[userAddress]=userAccount[userAddress]+amount;

return 'transfer succesfully';

function sendAmount(address payable toAddress , uint256 amount)


public payable returns(string memory){

require(amount>0, 'Enter non-zero value for withdrawal');

require(userExists[msg.sender]==true, 'Account is not created');

require(userAccount[msg.sender]>amount, 'insufficeint balance in


Bank account');

userAccount[msg.sender]=userAccount[msg.sender]-amount;

toAddress.transfer(amount);

return 'transfer success';

function userAccountBalance() public view returns(uint){

return userAccount[msg.sender];

function accountExist() public view returns(bool){

return userExists[msg.sender];

}
Q.6) Write a Smart Contract for storing and retrieving information of
Degree Certificates.

Smart contracts are self-executing contracts in which the contents of the


buyer-seller agreement are inscribed directly into lines of code.
According to Nick Szabo, an American computer scientist who devised a virtual
currency called "Bit Gold" in 1998, Smart contracts are computerized
transaction protocols that execute contract conditions.

Using it makes the transactions traceable, transparent, and irreversible.

Blockchain Certification Training Course

Gain expertise in core Blockchain conceptsVIEW COURSE

Benefits of Smart Contracts

Accuracy, Speed, and Efficiency

The contract is immediately executed when a condition is met.

Because smart contracts are digital and automated, there is no paperwork to


deal with, and

No time was spent correcting errors that can occur when filling out
documentation by hand.

Trust and Transparency

There's no need to worry about information being tampered with for personal
gain because there's no third party engaged and
Encrypted transaction logs are exchanged among participants.

Security

Because blockchain transaction records are encrypted, they are extremely


difficult to hack.

Furthermore, because each entry on a distributed ledger is linked to the


entries before and after it, hackers would have to change the entire chain to
change a single record.

Savings

Smart contracts eliminate the need for intermediaries to conduct transactions,


as well as the time delays and fees that come with them.

How Do Smart Contracts Work?

A smart contract is a sort of program that encodes business logic and operates
on a dedicated virtual machine embedded in a blockchain or other distributed
ledger.
Step 1: Business teams collaborate with developers to define their criteria for
the smart contract's desired behavior in response to certain events or
circumstances.
Step 2: Conditions such as payment authorization, shipment receipt, or a utility
meter reading threshold are examples of simple events.
Step 3: More complex operations, such as determining the value of a derivative
financial instrument, or automatically releasing an insurance payment, might
be encoded using more sophisticated logic.
Step 4: The developers then use a smart contract writing platform to create
and test the logic. After the application is written, it is sent to a separate team
for security testing.
Step 5: An internal expert or a company that specializes in vetting smart
contract security could be used.
Step 6: The contract is then deployed on an existing blockchain or other
distributed ledger infrastructure once it has been authorized.
Step 7: The smart contract is configured to listen for event updates from an
"oracle," which is effectively a cryptographically secure streaming data source,
once it has been deployed.
Step 8: Once it obtains the necessary combination of events from one or more
oracles, the smart contract executes.

FREE Course: Blockchain Developer

Learn Blockchain Basics with the FREE CourseENROLL NOW

Smart Contacts and Flight Insurance

Let's consider a real-life scenario in which smart contracts are used. Rachel is
at the airport, and her flight is delayed. AXA, an insurance company, provides
flight delay insurance utilizing Ethereum smart contracts. This insurance
compensates Rachel in such a case. How? The smart contract is linked to the
database recording flight status. The smart contract is created based on terms
and conditions.
The condition set for the insurance policy is a delay of two hours or more.
Based on the code, the smart contract holds AXA's money until that certain
condition is met. The smart contract is submitted to the nodes on EMV (a
runtime compiler to execute the smart contract code) for evaluation. All the
nodes on the network executing the code must come to the same result. That
result is recorded on the distributed ledger. If the flight is delayed in excess of
two hours, the smart contract self-executes, and Rachel is compensated. Smart
contracts are immutable; no one may alter the agreement.

Voting and Blockchain Implementation of Smart Contracts

Using Blockchain in the voting process can eliminate common problems. A


centralized voting system faces difficulties when it comes to tracking votes –
identity fraud, miscounts, or bias by voting officials. Using a smart contract,
certain predefined terms and conditions are pre-set in the contract. No voter
can vote from a digital identity other than his or her own. The counting is
foolproof. Every vote is registered on a blockchain network, and the counting is
tallied automatically with no interference from a third party or dependency on
a manual process. Each ID is attributed to just one vote. Validation is
accomplished by the users on the blockchain network itself. Thus, the voting
process can be in a public blockchain, or it could be in a decentralized
autonomous organization-based blockchain setup. As a result, every vote is
recorded on the ledger, and the information cannot be modified. That ledger is
publicly available for audit and verification.
Smart contracts allow you to create voting systems in which you can add and
remove members, change voting rules, change debating periods, or alter the
majority rule. For instance, you can create a vote for a decision within a
decentralized autonomous organization. Rather than a central authority
making a decision, a voting mechanism within the organization can determine
whether the proposal is accepted or rejected.

You might also like