0% found this document useful (0 votes)
36 views60 pages

Sumit Project Reprt - 1

This document describes a minor project proposal for developing a cryptocurrency wallet using blockchain technology. The project is being submitted by Sumit in partial fulfillment of the requirements for a Bachelor of Technology degree in Computer Science and Engineering. The project will involve designing a cryptocurrency wallet application that allows users to store, send, and receive cryptocurrencies using blockchain technology. It will explore the technical specifications required to build the peer-to-peer network architecture and integrate key blockchain concepts such as hashes, blocks, and consensus protocols. The design approach, schedule, and future scope are also outlined in the proposal.

Uploaded by

dhruvkumar110040
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)
36 views60 pages

Sumit Project Reprt - 1

This document describes a minor project proposal for developing a cryptocurrency wallet using blockchain technology. The project is being submitted by Sumit in partial fulfillment of the requirements for a Bachelor of Technology degree in Computer Science and Engineering. The project will involve designing a cryptocurrency wallet application that allows users to store, send, and receive cryptocurrencies using blockchain technology. It will explore the technical specifications required to build the peer-to-peer network architecture and integrate key blockchain concepts such as hashes, blocks, and consensus protocols. The design approach, schedule, and future scope are also outlined in the proposal.

Uploaded by

dhruvkumar110040
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/ 60

MINOR PROJECT

CRYPTOCURRENCY WALLET USING BLOCKCHAIN

SUBMITTED IN THE PARTIAL FULFILLMENT OF THE REQUIREMENT FOR THE


AWARD OF THE DEGREE OF

BACHELOR OF
TECHNOLOGY IN
COMPUTER SCIENCE AND ENGINEERING

SUBMITTED BY:
SUMIT

20015001017

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING INTERNATIONAL INSTITUTE
OF TECHNOLOGY & MANAGEMENT
(MURTHAL)
(Affiliated to DCRUST University, Murthal, Haryana, India)
(DECEMBER - 2023)
DECLARATION

I hereby declare that the thesis entitled “Cryptocurrency Wallet Using Blockchain"
submitted by me, for the award of B.Tech in CSE is a record of bonafide work carried
out by me under the supervision of Miss Divya.

I further declare that the work reported in this thesis has not been submitted and will
not be submitted, either in part or in full, for the award of any other degree or diploma
in this institute or any other institute or university.

Place :Delhi
Date : 08/12/2023
Signature of the Candidate
CERTIFICATE

This is to certify that the thesis entitled “Cryptocurrency wallet using blockchain”
submitted by Sumit(20015001017) SITE , IITM Murthal, for the award of the B.Tech,
is a record of bonafide work carried out by him under my supervision during the
period, 01. 10. 2023 to 08.12.2023, as per the CSE code of academic and research
ethics.

The contents of this report have not been submitted and will not be submitted either in
part or in full, for the award of any other degree or diploma in this institute or any other
institute or university. The thesis fulfills the requirements and regulations of the
University and in my view meets the necessary standards for submission.

Place : Delhi
Date : 08/12/2023 Signature of the Guide

Internal Examiner External Examiner

1
ACKNOWLEDGEMENTS

The satiation and euphoria that accompany the successful completion of the capstone
project would be incomplete without the mention of the people who made it possible.

It was a great learning experience to exercise the theoritical knowledge into a real life
design and to explore the domain of blockchain solutions to expand my knowledge and
utilize the same to give something back to the field.

We take this opportunity to express my profound gratitude and deep regard to my mentor
and guide Miss Divya for their exemplary guidance, monitoring, and constant
encouragement throughout the course. I am greatly indebted to her for providing
valuable guidance at all stages of the study, advice, constructive suggestions, positive
attitude, and continuous encouragement, without which it would have not been possible
to complete the capstone project.

I want to express my gratitude to Miss Divay, School of Computer Science, to have an


atmosphere to work during the course.
In the jubilant mood, I express my sincere gratitude to Miss Divya, Head of Department
,all teaching staff and leaders serving as representatives of our university for their non-
self-centered excitement coupled with timely motivation showered with zeal on me,
which prompted the acquisition of the necessary information to successfully finalize my
course thesis. I want to thank my parents for their support.

We hope that we made a valuable contribution to the industry for future use.

Name: Sumit

2
Executive Summary
Any new record or transaction within the blockchain implies the building of a new
block. Each record is then proven and digitally signed to ensure its genuineness. Before
this block is added to the network, it should be verified by the majority of nodes in the
system.
The data stored inside each block depends on the type of blockchain. For instance, in
the Bitcoin blockchain structure, the block maintains data about the receiver, sender,
and the number of coins.
A hash is like a fingerprint (long record consisting of some digits and letters). Each
block hash is generated with the help of a cryptographic hash algorithm (SHA 256).
Consequently, this helps to identify each block in a blockchain structure easily. The
moment a block is created, it automatically attaches a hash, while any changes made in
a block affect the change of a hash too. Simply stated, hashes help to detect any changes
in blocks.
The final element within the block is the hash from a previous block. This creates a
chain of blocks and is the main element behind blockchain architecture’s security. The
very first block in a chain is a bit special - all confirmed and validated blocks are
derived from the genesis block.
Any corrupt attempts provoke the blocks to change. All the following blocks then carry
incorrect information and render the whole blockchain system invalid.

3
CONTENTS Page No.

Acknowledgement i

Executive Summary ii

Table of Contents Iii

List of Figures ix

Abbreviations xvi

1 INTRODUCTION 9

1.1 Objective 9

1.2 Motivation 9

1.3 Background 10

1.4 Literature survey 10

2 PROJECT DESCRIPTION AND GOALS 13

3 TECHNICAL SPECIFICATION 14

3.1 Proposed Architecture 14


3.2 Network Architecture 14
3.3 Peer-to-peer Architecture 15

4 DESIGN APPROACH AND DETAILS (as applicable) 16


.

4.1 Design Approach / Materials & Methods 16


.

4.2 Codes and Standards 23.


.

5 SCHEDULE, TASKS AND MILESTONES 44


.

4
6 PROJECT DEMONSTRATION 45

7 FUTURE SCOPE 52.

8 REFERENCES . 53

5
List of Figures

Figure No. Title Page No.

4.1 Centralized network vs P2P network 16

4.2 Blockchain Structure 17

4.3 Blockchain working 17

4.4 SHA 256 Architecture 19

4.5 Consensus protocol 20

6
List of Abbreviations

P2P Peer to Peer

SHA256 Secure Hash Algorithm 256

PoW Proof of Work

PoS Proof of Stake

7
1. INTRODUCTION

1.1. OBJECTIVE

Blockchain is the core technology used to create the cryptocurrencies, like bitcoin.
After years of tremendous development and research in digital currency, the most
famous Bitcoin industry chain has been gradually completed including mining,
exchange, currency exchange, ATM, pervasive digital wallet design, and so on.
Digitizing currency can solve many problems of physical currency, such as the
rampant, counterfeit, banknotes. Thus, not only the transparency can be cost-
effectively preserved in store’s ledger, but also customer’s rights and interests can
be protected while using the digital wallet. Digitized transaction details can be
much easier to audit by any computing device than manually audit the conventional
ledger books

1.2. MOTIVATION

In the traditional centralized financial system, we will encounter many problems


such as follows. First, we can do banking business only when bank's office hour,
though all banks have opened a few transaction services over pervasive Internet
with some limitations. Second, the transnational remittance will also encounter the
review in international wide transfer. For example, if sending a sum of money from
the local bank of United States to a bank in India, not only needs to wait for the
office hours in these two different national banks but also payee needs to wait three
working days even after the wire transfer to India and the submission of declaration
document to prove the source of this money. Among these many problems
mentioned above in conventional money transactions.

The emerging blockchain technology has become the best solution to solve the time
difference problem of transnational remittance. Based on the peer-to-peer (i.e. P2P)
architecture and anonymity in blockchain technology, so customers do not need to

8
go to the bank to declare the source of funds, do not need to pay a high amount of
cross-border wire transfer fee.

1.3. BACKGROUND

The traditional financial transaction system is composed of many traditional


financial organizations. Users have to trust the closed payment flow to use these
organizations’ financial services. However, the centralized financial transaction
system has some problems that need to be overcome. For example, since all
transaction information is managed centrally, customers are not authorized to freely
access their transaction information. These transactions are not publicly reviewed
and customers are forced to trust their financial companies in the safety of funds,
including the flow of funds. If these traditional central financial institutions apply
blockchain technology in their financial flow system. The blockchain technology
will be inherited to indicate that the transaction records will be transparent to all
the customers to review. So, there will be no unknown cash flow problems. It not
only preserves money flow transparent, but also ensures that consumers’
transaction records won’t be changed and deleted. That’s to say, the seller can
believe that the algorithm’s correctness by using blockchain technology to trust the
transaction and further grasp all the transaction details clearly, or even the
company's business status can be provided easily. Then, the human resources can
be reduced to efficiently generate financial statement and statistics reports. Finally,
the government can easily review and believe the correctness of all the business
transaction information. For the tax collection, it also can have a standardized,
trusted and fully automated operating procedure. It can reduce not only the labour
cost, but also the errors in government taxation procedure.

1.4. LITERATURE SURVEY

Guang Chen, Bing Xu1, Manli Lu1 and Nian-Shing Chen [1] Blockchain is the core
technology used to create the cryptocurrency, Bitcoin, through the maintenance of
immutable distributed ledgers in thousands of nodes proposed by Satoshi
Nakamoto in 2008 (Nakamoto 2008). It has been considered as part of the fourth

9
industrial revolution since the invention of steam engine, electricity, and
information technology (Chung and Kim 2016; Schwab 2017). The current paper
focused on its potential educational applications and explored how blockchain
technology can be used to solve some education problems. This article first
introduced the features and advantages of blockchain technology following by
exploring some of the current blockchain applications for education. Some
innovative applications of using blockchain technology were proposed, and the
benefits and challenges of using blockchain technology for education were also
discussed.
Hussein Hellani, Abed Ellatif, Maroun Chamoun, Hussein El, Ahmed Serhrouchni
[2] In this paper, we consider blockchain technology that enabled the existence of
digital currency and we investigate Bitcoin cryptocurrency application. This
technology nowadays represents a new feature that replaces existing client-server
core system on top of some distributed systems with many additional features such
as high availability, resistance to alteration, fault tolerance and cost reduction. After
overviewing how such technology is working, we highlight the requirements and
benefits related to the security, database and network. We mainly focus on
answering the most Bitcoin queries including privacy and double spending.
Furthermore, as blockchain has potential applications far beyond bitcoin, we draw
future insights where applications based blockchain are provisioned in the market
in order to be totally or partially independent of the centralized systems and we
provide a questionnaire helping organizations for better using the blockchain
feasibilities.
Guy Zyskind, Oz Nathan, Alex ‘Sandy’ Pentland [3] The recent increase in reported
incidents of surveillance and security breaches compromising users’ privacy call
into question the current model, in which third-parties collect and control massive
amounts of personal data. Bitcoin has demonstrated in the financial space that
trusted; auditable computing is possible using a decentralized network of peers
accompanied by a public ledger. In this paper, we describe a decentralized personal
data management system that ensures users own and control their data. We
implement a protocol that turns a blockchain into an automated access-control
manager that does not require trust in a third party. Unlike Bitcoin, transactions in
our system are not strictly financial – they are used to carry instructions, such as

10
storing, querying, and sharing data. Finally, we discuss possible future extensions
to blockchains that could harness them into a well-rounded solution for trusted
computing problems in society.
Ralph C. Merkle [4] A new Digital signature based only on a conventional
encryption function (such as DES) is described which is as secure as the underlying
encryption function, the security does not depend on the difficulty of factoring and
the computational costs of modular arithmetic are avoided. The signature system
can sign an unlimited number of messages and the signature size increases
logarithmically as function if the number of messages signed. Signature size in a
typical system might range from a few hundred bytes to a few kilobytes and the
generation of a signature might require a few hundred to a few thousand
computations of the underlying conventional encryption function.

11
2. PROJECT DESCRIPTION AND GOALS

In this project, we consider blockchain technology that enabled the existence of


digital currency and we investigate Bitcoin cryptocurrency application. This
technology nowadays represents a new feature that replaces the existing client-
server core system on top of some distributed systems with many additional
features such as high availability, resistance to alteration, fault tolerance, and cost
reduction. After overviewing how such technology is working, we highlight the
requirements and benefits related to the security, database, and network. We mainly
focus on answering the most Bitcoin queries including privacy and double-
spending. Furthermore, as blockchain has potential applications far beyond bitcoin,
we draw future insights where applications based blockchain are provisioned in the
market in order to be totally or partially independent of the centralized systems and
we provide a questionnaire helping organizations for better using the blockchain
feasibilities.

12
3. TECHNICAL SPECIFICATION

3.1 PROPOSED ARCHITECTURE

Currently, cash transfer between two different e-wallets is not allowed in India. An
architecture to solve this issue along with Blockchain an architecture wherein three
different banks are arranged as peers over a network. Each of these banks provides
an e-wallet to its customers. Each of the banks has one or more miner. This miner
is a high-end computation server that is granted access to certain attributes of the
customer table in the central database of the bank. Each of the banks has definite
trust agreements with each other. The idea is to use Proof of Stake (PoS) as the
consensus mechanism. Since the banks agree to collaborate, each of these shall
ensure that any malicious activity shall directly or indirectly harm their own
databases and transactions

3.2 NETWORK ARCHITECTURE

The proposed network architecture is swarm-based peer to peer network. Each of


the participating banks shall have a certain number of miners. These miners can be
considered as super-nodes that shall be persistent (permanent) and fault-tolerant.
Any customer seeking e-wallet from his bank shall be provided with the network
address of all the miners. This customer shall send the join message to the miners.
During the registration process, a public key and a private key shall get generated.
This public key gets updated with the miner. When any offline customer becomes
live for performing any transaction, the e-wallet app shall get synchronize the
cashbook of the customer with the entries of the Blockchain.
A transaction in this work represents a cash or amount or payment that is digitally
signed with the private key of the initiator who is making payment or vice versa
with the use of its public key specified in the transaction. Miners record these
transactions in a Blockchain and carry out the task for the following three major
scenarios:
a) Transferring cash from home bank account into the e- wallet,
b) Transfer of cash between two different e-wallets and

13
c) Transfer of cash from e-wallet to the bank account.

3.3. PEER TO PEER ARCHITECTURE

Blockchain trading system is based on P2P network architecture and inherited the
decentralized characteristics. Because of the P2P’de-centralized protocol, all nodes are
not only playing the role of clients, but also playing the role of servers. In such
decentralized network in the world, compared with the traditional centralized server
usually presented in the web service with a single-digit scale of the server hosts, Bitcoin
system can be expanded to more than six thousand nodes. So, Bitcoin network can do
better job to prevent from the denial-of service attacks. In recent years, because of the
Bitcoin prevalence and anonymity, it become the main way to pay off to the
ransomware. However, blockchain is based on the P2P network. Even a single node
data is locked by the attacker’s encryption from ransomware. Such an extortion to
decentralized Bitcoin network does not pose a big threat, after all, there are a lot of data
nodes in the Bitcoin network and will not have much impact from the damage of a
single node.

14
4. DESIGN APPROACH AND DETAILS

4.1 Design Approach

a) System Architecture
Client-Server: The traditional architecture of the World Wide Web uses a
client-server network. In this case, the server keeps all the required
information in one place so that it is easy to update, due to the server being
a centralized database controlled by number of administrators with
permissions.
Blockchain: The blockchain is a decentralized, distributed ledger (public
or private) of different kinds of transactions arranged into a P2P network.
This network consists of many computers, but in a way that the data cannot
be altered without the consensus of the whole network (each separate
computer).

4.1 Centralized network vs P2P network

The structure of blockchain technology is represented by a list of blocks with


transactions in a particular order. These lists can be stored as a flat file (txt. Format)
or in the form of a simple database.

15
4.2 Blockchain Structure

b) How Blockchain Works

4.3 Blockchain working


Any new record or transaction within the blockchain implies the building of a new
block. Each record is then proven and digitally signed to ensure its genuineness.
Before this block is added to the network, it should be verified by the majority of
nodes in the system.

16
The data stored inside each block depends on the type of blockchain. For instance,
in the Bitcoin blockchain structure, the block maintains data about the receiver,
sender, and the number of coins.
A hash is like a fingerprint (long record consisting of some digits and letters). Each
block hash is generated with the help of a cryptographic hash algorithm (SHA 256).
Consequently, this helps to identify each block in a blockchain structure easily. The
moment a block is created, it automatically attaches a hash, while any changes made
in a block affect the change of a hash too. Simply stated, hashes help to detect any
changes in blocks.
The final element within the block is the hash from a previous block. This creates
a chain of blocks and is the main element behind blockchain architecture’s security.
As an example, block 45 points to block 46. The very first block in a chain is a bit
special – all confirmed and validated blocks are derived from the genesis block.
Any corrupt attempts provoke the blocks to change. All the following blocks then
carry incorrect information and render the whole blockchain system invalid.

c) Algorithms Used:
SHA-256 The SHA (Secure Hash Algorithm) is one of a number
of cryptographic hash functions. A cryptographic hash is like a signature for a
data set. If you would like to compare two sets of raw data (source of the file,
text or similar) it is always better to hash it and compare SHA256 values. It is
like the fingerprints of the data. Even if only one symbol is changed the
algorithm will produce different hash values. SHA256 algorithm generates an
almost-unique, a fixed size 256-bit (32-byte) hash. Hash is a so called one-way
function. This makes it suitable for checking integrity of your data, challenge
hash authentication, anti-tamper, digital signatures, blockchain.

17
4.4 SHA 256 Architecture

d) Consensus algorithm

A consensus algorithm is a process in computer science used to achieve agreement


on a single data value among distributed processes or systems. Consensus
algorithms are designed to achieve reliability in a network involving multiple
unreliable nodes. Solving that issue known as the consensus problem, it is important
in distributed computing and multi-agent systems. To accommodate this reality,
consensus algorithms necessarily assume that some processes and systems will be
unavailable and that some communications will be lost. As a result, consensus
algorithms must be fault-tolerant. They typically assume, for example, that only a
portion of nodes will respond but require a response from that portion, such as 51%,
at a minimum.
Through a series of clever game theory incentives, cryptography, and distributed
consensus, a blockchain can achieve secure and accurate consensus on the state of
the ledger, just like a central clearinghouse, but over a decentralized network where
no single entity is in control.
Cryptography in blockchains makes the verification of data (i.e., transactions)
trivial, and nearly impossible to forge. This task is performed by network operators
that run nodes and automatically validate the blocks and transactions in the network

18
through a set of consensus rules, which can be run by anyone with a computer on a
public, permission less blockchain like Bitcoin.

4.5 Consensus protocol

e) Proof of Work(PoW)
In Blockchain, this algorithm is used to confirm transactions and produce new
blocks to the chain. With PoW, miners compete against each other to complete
transactions on the network and get rewarded.
In a network, users send digital tokens to each other. A decentralized ledger
gathers all the transactions into blocks. However, care should be taken to
confirm the transactions and arrange blocks. This responsibility bears on
special nodes called miners, and a process is called mining. The main working
principle is a complicated mathematical puzzle and a possibility to easily prove
the solution.
The most famous application of PoW is Bitcoin. It was Bitcoin that laid the
foundation for this type of consensus. The puzzle is Hashc ash. This algorithm
allow changing the complexity of a puzzle based on the total power of the

19
network. The average time of block formation is 10 minutes. Bitcoin-based
cryptocurrencies, such as Litecoin, have similar system. Another large project
with PoW is Ethereum. Given that almost three of four projects are
implemented on Ethereum platform, it’s safe to say that the majority of
Blockchain applications use PoW consensus model.
The main benefits are the anti-DoS attacks defense and less impact of stake on
mining possibilities. Defense from DoS attacks. PoW imposes some limits on
actions in the network. The efficient attack requires a lot of computational
power and a lot of time to do the calculations. Therefore, the attack is possible
but kind of useless since the costs are too high.
Mining possibilities. It doesn’t matter how much money you have in your
wallet. What matters is to have large computational power to solve the puzzles
and form new blocks. Thus, the holders of huge amounts of money are not in
charge of making decisions for the entire network.

f) Proof of Stake (PoS)


The proof of stake was created as an alternative to the proof of work (PoW), to
tackle inherent issues in the latter. When a transaction is initiated, the
transaction data is fitted into a block with a maximum capacity of 1 megabyte,
and then duplicated across multiple computers or nodes on the network. The
nodes are the administrative body of the blockchain and verify the legitimacy
of the transactions in each block. To carry out the verification step, the nodes
or miners would need to solve a computational puzzle, known as the proof of
work problem. The first miner to decrypt each block transaction problem gets
rewarded with coins. Once a block of transactions has been verified, it is added
to the blockchain, a public transparent ledger.
Mining requires a great deal of computing power to run different cryptographic
calculations to unlock the computational challenges. The computation power
translates into a high amount of electricity. The proof of stake (PoS) seeks to
address this issue by attributing mining power to the proportion of coins held
by a miner. This way, instead of utilizing energy to answer PoW puzzles, a PoS
miner is limited to mining a percentage of transactions that are reflective of his
or her ownership stake. For instance, a miner who owns 3% of the Bitcoin

20
available can theoretically mine only 3% of the blocks. city and power needed
for the proof of work.

g) Bitcoin Mining

Bitcoin mining is performed by high-powered computers that solve complex


computational math problems (that is, so complex that they cannot be solved
by hand, and indeed complicated enough to tax even incredibly powerful
computers). The luck and work required by a computer to solve one of these
problems is the equivalent of a miner striking gold in the ground — while
digging in a sandbox. At the time of writing, the chance of a computer solving
one of these problems is about 1 in 13 trillion, but more on that later.
The result of “bitcoin mining” is two-fold. First, when computers solve these
complex math problems on the Bitcoin network, they produce new bitcoin
(when referring to the individual coins themselves, "bitcoin" typically appears
without capitalization), not unlike when a mining operation extracts gold from
the ground. And second, by solving computational math problems, bitcoin
miners make the Bitcoin payment network trustworthy and secure, by verifying
its transaction information.

21
4.2) Codes and Standards
4.2.1) Creating Blockchain
a) Libraries for blockchain nodes

from flask import Flask, request, jsonify, render_template


from time import time
from flask_cors import CORS
from collections import OrderedDict
import binascii
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
from uuid import uuid4
import json
import hashlib
import requests
from urllib.parse import urlparse

MINING_SENDER = "The Blockchain"


MINING_REWARD = 1
MINING_DIFFICULTY = 2

b)Creating blockchain
class Blockchain:

def init (self):


self.transactions = []
self.chain = []
self.nodes = set()
self.node_id = str(uuid4()).replace('-',
'') # Create the genesis block
self.create_block(0, '00')

def register_node(self, node_url):


parsed_url =
urlparse(node_url) if
parsed_url.netloc:
self.nodes.add(parsed_url.netloc)
elif parsed_url.path:
self.nodes.add(parsed_url.path)
else:
raise ValueError('Invalid URL')

def create_block(self, nonce, previous_hash):


"""
Add a block of transactions to the blockchain
"""
block = {'block_number': len(self.chain) + 1,
'timestamp': time(),
'transactions': self.transactions,
22
'nonce': nonce,
'previous_hash': previous_hash}

# Reset the current list of transactions


self.transactions = []
self.chain.append(block)
return block

def verify_transaction_signature(self, sender_public_key, signature,


transaction):
public_key = RSA.importKey(binascii.unhexlify(sender_public_key))
verifier = PKCS1_v1_5.new(public_key)
h = SHA.new(str(transaction).encode('utf8'))
try:
verifier.verify(h, binascii.unhexlify(signature))
return True
except
ValueError:
return False

@staticmethod
def valid_proof(transactions, last_hash, nonce,
difficulty=MINING_DIFFICULTY):
guess = (str(transactions) + str(last_hash) +
str(nonce)).encode('utf8')
h = hashlib.new('sha256')
h.update(guess)
guess_hash =
h.hexdigest()
return guess_hash[:difficulty] == '0' * difficulty

def proof_of_work(self):
last_block = self.chain[-1]
last_hash =
self.hash(last_block) nonce = 0
while self.valid_proof(self.transactions, last_hash, nonce) is
False:
nonce += 1

return nonce

c)Defining hash function

@staticmethod
def hash(block):
# We must to ensure that the Dictionary is ordered, otherwise
we'll get inconsistent hashes
block_string = json.dumps(block, sort_keys=True).encode('utf8')
h = hashlib.new('sha256')
h.update(block_string)
return h.hexdigest()

def
resolve_conflicts(self)
: neighbours =
self.nodes new_chain =
None

23
max_length = len(self.chain)
for node in neighbours:

24
response = requests.get('http://' + node + '/chain')
if response.status_code == 200:
length = response.json()['length']
chain = response.json()['chain']

if length > max_length and self.valid_chain(chain):


max_length = length
new_chain = chain

if new_chain:
self.chain = new_chain
return

True return

False

def valid_chain(self, chain):


last_block = chain[0]
current_index = 1

while current_index <


len(chain): block =
chain[current_index]
if block['previous_hash'] != self.hash(last_block):
return False

transactions = block['transactions'][:-1]
transaction_elements = ['sender_public_key',
'recipient_public_key', 'amount']
transactions = [OrderedDict((k, transaction[k]) for k in
transaction_elements) for transaction in
transactions]

if not self.valid_proof(transactions, block['previous_hash'],


block['nonce'], MINING_DIFFICULTY):
return False

last_block = block
current_index += 1

return True

def submit_transaction(self, sender_public_key, recipient_public_key,


signature, amount):
transaction = OrderedDict({
'sender_public_key': sender_public_key,
'recipient_public_key': recipient_public_key,
'amount': amount
})

# Reward for mining a block


if sender_public_key == MINING_SENDER:
self.transactions.append(transaction)
return len(self.chain) + 1
else:
# Transaction from wallet to another wallet
signature_verification =
self.verify_transaction_signature(sender_public_key, signature, transaction)
if signature_verification:
25
self.transactions.append(transaction)
return len(self.chain) + 1

26
else:
return False

# Instantiate the Blockchain


blockchain = Blockchain()

d) Instantiate the Node


app = Flask( name )
CORS(app)

@app.route('/')
def index():
return render_template('./index.html')

@app.route('/configure')
def configure():
return render_template('./configure.html')

@app.route('/transactions/get', methods=['GET'])
def get_transactions():
transactions = blockchain.transactions
response = {'transactions': transactions}
return jsonify(response), 200

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

return jsonify(response), 200

@app.route('/mine', methods=['GET'])
def mine():
# We run the proof of work algorithm
nonce = blockchain.proof_of_work()

blockchain.submit_transaction(sender_public_key=MINING_SENDER,

recipient_public_key=blockchain.node_id,
signature='',
amount=MINING_REWARD)

last_block = blockchain.chain[-1]
previous_hash = blockchain.hash(last_block)
block = blockchain.create_block(nonce, previous_hash)

response = {
'message': 'New block created',
'block_number': block['block_number'],

27
'transactions': block['transactions'],
'nonce': block['nonce'],
'previous_hash': block['previous_hash'],
}
return jsonify(response), 200

@app.route('/transactions/new', methods=['POST'])

e) Creating Transaction block


def new_transaction():
values = request.form
required = ['confirmation_sender_public_key',
'confirmation_recipient_public_key', 'transaction_signature',
'confirmation_amount']
if not all(k in values for k in required):
return 'Missing values', 400

transaction_results =
blockchain.submit_transaction(values['confirmation_sender_public_key'],

values['confirmation_recipient_public_key'],

values['transaction_signature'],

values['confirmation_amount'])
if transaction_results == False:
response = {'message': 'Invalid transaction/signature'}
return jsonify(response), 406
else:
response = {'message': 'Transaction will be added to the Block ' +
str(transaction_results)}
return jsonify(response), 201

@app.route('/nodes/get', methods=['GET'])
def get_nodes():
nodes =
list(blockchain.nodes)
response = {'nodes': nodes}
return jsonify(response), 200

@app.route('/nodes/resolve', methods=['GET'])
def consensus():
replaced = blockchain.resolve_conflicts()

if replaced:
response = {
'message': 'Our chain was replaced',
'new_chain': blockchain.chain
}
else:
response = {
'message': 'Our chain is
authoritative', 'chain':
blockchain.chain

28
}

29
return jsonify(response), 200

@app.route('/nodes/register', methods=['POST'])
def register_node():
values = request.form
# 127.0.0.1:5002,127.0.0.1:5003, 127.0.0.1:5004
nodes = values.get('nodes').replace(' ', '').split(',')

if nodes is None:
return 'Error: Please supply a valid list of nodes', 400

for node in nodes:


blockchain.register_node(node)

response = {
'message': 'Nodes have been added',
'total_nodes': [node for node in
blockchain.nodes]
}
return jsonify(response), 200

if name == ' main ':


from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument('-p', '--port', default=5001, type=int, help="port
to listen to")
args = parser.parse_args()
port = args.port

app.run(host='127.0.0.1', port=port, debug=True)

4.2.2) Client Side Code

a)Libraries
from flask import Flask, request, jsonify, render_template
import Crypto
import Crypto.Random
from Crypto.PublicKey import RSA
import binascii
from collections import OrderedDict
from Crypto.Signature import
PKCS1_v1_5 from Crypto.Hash import SHA

b) Creating Transaction block


class Transaction:

def init (self, sender_public_key, sender_private_key,


recipient_public_key, amount):
self.sender_public_key = sender_public_key
self.sender_private_key =
30
sender_private_key

31
self.recipient_public_key = recipient_public_key
self.amount = amount

def to_dict(self):
return OrderedDict({
'sender_public_key': self.sender_public_key,
'recipient_public_key': self.recipient_public_key,
'amount': self.amount,
})

def
sign_transaction(self)
: private_key =
RSA.importKey(binascii.unhexlify(self.sender_private_key))
signer = PKCS1_v1_5.new(private_key)
h = SHA.new(str(self.to_dict()).encode('utf8'))
return binascii.hexlify(signer.sign(h)).decode('ascii')

app = Flask( name )

@app.route('/')
def index():
return render_template('index.html')

c) Generate Transaction
@app.route('/generate/transaction', methods=['POST'])
def generate_transaction():
sender_public_key = request.form['sender_public_key']
sender_private_key = request.form['sender_private_key']
recipient_public_key = request.form['recipient_public_key']
amount = request.form['amount']

transaction = Transaction(sender_public_key, sender_private_key,


recipient_public_key, amount)

response = {'transaction': transaction.to_dict(),


'signature': transaction.sign_transaction()}

return jsonify(response), 200

@app.route('/make/transaction')
def make_transaction():
return render_template('make_transaction.html')

@app.route('/view/transactions')
def view_transactions():
return render_template('view_transactions.html')

@app.route('/wallet/new')
def new_wallet():
random_gen = Crypto.Random.new().read
private_key = RSA.generate(1024, random_gen)
public_key = private_key.publickey()

32
response = {
'private_key':
binascii.hexlify(private_key.export_key(format('DER'))).decode('ascii'),
'public_key':
binascii.hexlify(public_key.export_key(format('DER'))).decode('ascii')
}

return jsonify(response), 200

if name == ' main ':


from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument('-p', '--port', default=8081, type=int, help="port
to listen to")
args = parser.parse_args()
port = args.port

app.run(host='127.0.0.1', port=port, debug=True)

4.2.3) Front end of Blockchain


<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0,
maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Blockchain Frontend</title>

<link rel="stylesheet"
href="/static/vendor/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet"
href="/static/vendor/DataTables/css/datatables.min.css">
<link rel="stylesheet"
href="/static/vendor/font-awesome/font- awesome.min.css">
<link rel="stylesheet" href="/static/css/custom.css">

</head>
<body>

<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">


<div class="container">
<a href="#" class="navbar-brand">Blockchain Frontend</a>

<div class="collapse navbar-collapse">


<ul class="navbar-nav ml-auto">
<li class="nav-item active">
<a href="/" class="nav-link">Home</a>
</li>
<li class="nav-item">
<a href="/configure" class="nav-link">Configure</a>
</li>
</ul>
</div>

33
</div>
</nav>

<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<div class="card-body">
<h4 class="card-title">Transactions to be added to the
next block</h4>
<button type="submit" id="refresh_transactions"
class="btn btn-primary">
<i class="fa fa-refresh"></i>
</button>

</div>
</div>
</div>
</div>

<div class="container">
<table id="unmined_transactions_table" class="table table-bordered"
cellspacing="0" width="100%">

</table>

<div class="col-lg-12 text-center">


<input type="button" id="mine_button" class="btn btn-
primary btn-lg" value="Mine">
</div>
</div>

<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<div class="card-body">
<h4 class="card-title">Transactions on the
blockchain</h4>
<button type="submit" id="refresh_blockchain" class="btn
btn-primary">
<i class="fa fa-refresh"></i>
</button>

</div>
</div>
</div>
</div>

<div class="container">
<table id="transactions_table" class="table table-bordered"
cellspacing="0" width="100%">

</table>
</div>

<script src="/static/vendor/jquery/jquery.min.js"></script>
<script
src="/static/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="/static/vendor/DataTables/js/datatables.min.js"></script>

34
<script src="/static/vendor/DataTables/js/ellipsis.js"></script>

<script>
$(function() {

$.ajax({
url: "/chain",
type: "GET",
success: function(response)
{ let transactions = []
let count = 1

for (i=0; i<response['length']; i++)


{ for (j=0;
j<response['chain'][i]['transactions'].length; j++) {
let options = { year: "numeric", month:
"short", day: "numeric", hour: "2-digit", minute: "2-digit", second: "2-
digit" };
let date = new Date(response["chain"][i]
["timestamp"] * 1000);
formattedTimestamp
= date.toLocaleTimeString('en-US', options);

let transaction = [
count,

response['chain'][i]['transactions'][j]['sender_public_key'], response['chain'][i]

['transactions'][j]['recipient_public_key'], response['chain'][i]['transactions'][j]

['amount'],
formattedTimestamp,
response['chain'][i]['block_number']
]

transactions.push(transaction);
count += 1;
}
}

$('#transactions_table').dataTable({
data: transactions,
columns: [
{title: "#"},
{title: "Sender Public Key"},
{title: "Recipient Public Key"},
{title: "Amount"},
{title: "Timestamp"},
{title: "Block#"},

],
columnDefs: [{targets: [1,2,3,4,5], render:
$.fn.dataTable.render.ellipsis(25)}]
});
},
error: function(error) {
console.log(error);
}
});

35
$.ajax({
url:
"/transactions/get",
type: "GET",
success: function(response) {

let transactions =
[] let count = 1

for (i=0; i<response['transactions'].length; i++) {

let transaction = [
count,

response['transactions'][i]['sender_public_key'], response['transactions'][i]

['recipient_public_key'],
response['transactions'][i]['amount'],
]

transactions.push(transaction);

count += 1;
}

$('#unmined_transactions_table').dataTable({
data: transactions,
columns: [
{title: "#"},
{title: "Sender Public Key"},
{title: "Recipient Public Key"},
{title: "Amount"},
],
columnDefs: [{targets: [1,2,3], render:
$.fn.dataTable.render.ellipsis(25)}]
});
},
error: function(error) {
console.log(error);
}
});

$('#mine_button').click(function() {
$.ajax({
url: '/mine',
type: 'GET',
success: function(response) {
window.location.reload();
},
error: function(error) {
console.log(error);
}

});
});

$('#refresh_transactions').click(function() {
36
window.location.reload();
});

$('#refresh_blockchain').click(function() {
$.ajax({
url:
'/nodes/resolve',
type: 'GET',
success: function(response) {
window.location.reload();
},
error: function(error) {
console.log(error);
}
});
});

});

</script>

</body>
</html>

4.2.4)Client side frontend


<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0,
maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Blockchain Client</title>

<link rel="stylesheet"
href="/static/vendor/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet"
href="/static/vendor/DataTables/css/datatables.min.css">
<link rel="stylesheet"
href="/static/vendor/font-awesome/font- awesome.min.css">
<link rel="stylesheet" href="/static/css/custom.css">

</head>
<body>

<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">


<div class="container">
<a href="#" class="navbar-brand">Blockchain Client</a>

<div class="collapse navbar-collapse">


<ul class="navbar-nav ml-auto">
<li class="nav-item active">
<a href="/" class="nav-link">Wallet Generator</a>
</li>
<li class="nav-item">
<a href="/make/transaction" class="nav-link">Make
Transaction</a>
</li>
37
<li class="nav-item">
<a href="/view/transactions" class="nav-link"> View
Transactions</a>
</li>
</ul>
</div>
</div>
</nav>

<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<div class="card-body">
<h4 class="card-title"> Wallet Generator</h4>
<p class="card-text"> Click on the button below
generate your blockchain wallet</p> to
<input type="button" class="btn btn-primary btn-
lg"
value="Generate Wallet">
</div>
</div>
</div>
</div>

<div class="container">
<div class="row">
<label class="col-sm-2"> Public Key:</label>
<div class="col-sm-10">
<textarea id="public_key" rows="5" class="form-control"
readonly></textarea>
</div>
</div>

<br>

<div class="row">
<label class="col-sm-2"> Private Key:</label>
<div class="col-sm-10">
<textarea id="private_key" rows="5" class="form-control"
readonly></textarea>
</div>
</div>

<br>

<div class="row" id="warning" display:none">


style="
<div class="col-sm-12">
<div class="alert alert-danger" role="alert">
IMPORTANT
<ul>
<li> Save you private and public keys. These keys cannot be
recovered!</li>
<li> Don't share your private key with anyone!</li>
</ul>
</div>
</div>
</div>

</div>

38
<script src="/static/vendor/jquery/jquery.min.js"></script>
<script
src="/static/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="/static/vendor/DataTables/js/datatables.min.js"></script>
<script src="/static/vendor/DataTables/js/ellipsis.js"></script>

<script>
$(function() {
$('input').click(function() {

$.ajax({
url:
'/wallet/new',
type: 'GET',
success: function(response) {
document.getElementById("public_key").innerHTML =
response['public_key'];
document.getElementById("private_key").innerHTML =
response['private_key'];
document.getElementById("warning").style.display =
"block";
},

error: function(error) {
console.log(error);
}
});
});
});

</script>

</body>
</html>

4.2.5)Transaction Frontend
a) Make transaction <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0,
maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Blockchain Frontend</title>

<link rel="stylesheet"
href="/static/vendor/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet"
href="/static/vendor/DataTables/css/datatables.min.css">
<link rel="stylesheet"
href="/static/vendor/font-awesome/font- awesome.min.css">
<link rel="stylesheet" href="/static/css/custom.css">

39
</head>

40
<body>

<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">


<div class="container">
<a href="#" class="navbar-brand">Blockchain Client</a>

<div class="collapse navbar-collapse">


<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a href="/" class="nav-link">Wallet Generator</a>
</li>
<li class="nav-item active">
<a href="/make/transaction" class="nav-link">Make
Transaction</a>
</li>
<li class="nav-item">
<a href="/view/transactions" class="nav-link">View
Transactions</a>
</li>
</ul>
</div>
</div>
</nav>

<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<div class="card-body">
<h4 class="card-title">Send Coins:</h4>
<p class="card-text">Enter transaction details and
click on "Generate Transaction" button to generate your transaction</p>
</div>
</div>
</div>
</div>

<div class="container alert alert-secondary">


<form id="transaction_form">
<div class="row">
<label class="col-sm-2">Sender Public Key:</label>
<div class="col-sm-10">
<input type="text" name="sender_public_key"
id="sender_public_key" class="form-control">
</div>
</div>

<br>

<div class="row">
<label class="col-sm-2">Sender Private Key:</label>
<div class="col-sm-10">
<input type="text" name="sender_private_key"
id="sender_private_key" class="form-control">
</div>
</div>

<br>

41
<div class="row">
<label class="col-sm-2">Recipient Public Key:</label>
<div class="col-sm-10">
<input type="text" name="recipient_public_key"
id="recipient_public_key" class="form-control">
</div>
</div>

<br>

<div class="row">
<label class="col-sm-2">Amount:</label>
<div class="col-sm-10">
<input type="text" name="amount"
id="amount" class="form-control">
</div>
</div>

<br>

<div class="row">
<div class="col-sm-12 text-center">
<input type="button" name="generate_transaction"
id="generate_transaction" class="btn btn-primary btn-lg" value="Generate
Transaction">
</div>
</div>

</form>
</div>

<!-- Modal -->


<div class="modal modal-alert fade" id="basic_modal" tabindex="-1"
role="dialog" aria-labelledby="basicModal" aria-hidden="true">
<div class="modal-dialog">

<div class="modal-content">

<div class="modal-header">
<div class="modal-title col-md-10">Confirm transaction details,
enter a blockchain node url and click on "Confirm Transaction" to finalize
your transaction.</div>
<button type="button" class="close col-md-2" data-
dismiss="modal" aria-hidden="true">&times;</button>
</div>

<div class="modal-body">

<form id="confirmation_transaction_form">

<div class="row">
<label class="col-sm-12">Sender Public Key:</label>
<div class="col-sm-12">
<input type="text" name="confirmation_sender_public_key"
id="confirmation_sender_public_key" rows="2" class="form-control" readonly>

</div>
</div>

42
<div class="row">
<label class="col-sm-12">Recipient Public Key:</label>
<div class="col-sm-12">
<input type="text"
name="confirmation_recipient_public_key"
id="confirmation_recipient_public_key" rows="2" class="form-control"
readonly>
</div>
</div>

<div class="row">
<label class="col-sm-12">Amount to Send:</label>
<div class="col-sm-12">
<input type="text" name="confirmation_amount"
id="confirmation_amount" rows="2" class="form-control" readonly>
</div>
</div>

<div class="row">
<label class="col-sm-12">Transaction Signature:</label>
<div class="col-sm-12">
<input type="text" name="transaction_signature"
id="transaction_signature" rows="2" class="form-control" readonly>
</div>
</div>

</form>

<div class="row">
<label class="col-sm-12">Blockchain Node URL:</label>
<div class="col-sm-12">
<input type="text" name="node_url" id="node_url"
rows="2" class="form-control" value="http://127.0.0.1:5001">
</div>
</div>

</div>

<div class="modal-footer">
<button type="button" class="btn btn-danger" data-
dismiss="modal">Cancel</button>
<button type="button" id="button_confirm_transaction"
class="btn btn-success">Confirm Transaction</button>
</div>

</div>

</div>
</div>

<!-- Alert Message for successful transaction -->


<div class="modal modal-alert fade" id="success_transaction_modal"
tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-
hidden="true">
<div class="modal-dialog">
<div class="modal-content">

<div class="modal-header">
43
<button type="button" class="close" data-dismiss="modal" aria-
hidden="true">&times;</button>
</div>

<div class="modal-body">
<div class="alert alert-success" role="alert">
<h4 class="alert-heading">Successful Transaction!</h4>
<p>You successfully completed your transaction. It will be
added to the next block.</p>
</div>
</div>

<div class="modal-footer">
<button type="button" id="confirm_transaction" class="btn btn-
success" data-dismiss="modal">OK</button>
</div>

</div>
</div>
</div>

<script src="/static/vendor/jquery/jquery.min.js"></script>
<script
src="/static/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="/static/vendor/DataTables/js/datatables.min.js"></script>
<script src="/static/vendor/DataTables/js/ellipsis.js"></script>

<script>
$(function() {
$("#generate_transaction").click(function() {
$.ajax({
url: "/generate/transaction",
type: "POST",
dataType: 'json',
data: $('#transaction_form').serialize(),
success: function(response) {

document.getElementById('confirmation_sender_public_key').value =
response['transaction']['sender_public_key'];

document.getElementById('confirmation_recipient_public_key').value =
response['transaction']['recipient_public_key'];
document.getElementById('confirmation_amount').value
= response['transaction']['amount'];

document.getElementById('transaction_signature').value =
response['signature'];

$('#basic_modal').modal('show');
},
error: function(error) {
console.log(error);
}
});
});

$('#button_confirm_transaction').click(function() {

44
$.ajax({
url: document.getElementById('node_url').value +
'/transactions/new',
type: 'POST',
dataType:
'json',
header: {'Access-Control-Allow-Origin': '*'},
data: $('#confirmation_transaction_form').serialize(),
success: function(response) {
/*$('#sender_public_key').val('');
$('#sender_private_key').val('');
$('#recipient_public_key').val('');
$('#amount').val('');*/

$('#basic_modal').modal('hide');
$('#success_transaction_modal').modal('show');

},
error: function(error) {
console.log(error);
}

});
});

});

</script>

</body>
</html>

b) View Transaction <!doctype html>


<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0,
maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Blockchain Frontend</title>

<link rel="stylesheet"
href="/static/vendor/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet"
href="/static/vendor/DataTables/css/datatables.min.css">
<link rel="stylesheet"
href="/static/vendor/font-awesome/font- awesome.min.css">
<link rel="stylesheet" href="/static/css/custom.css">

</head>
<body>

<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">


<div class="container">
<a href="#" class="navbar-brand">Blockchain Client</a>

45
<div class="collapse navbar-collapse">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a href="/" class="nav-link">Wallet Generator</a>
</li>
<li class="nav-item">
<a href="/make/transaction" class="nav-link">Make
Transaction</a>
</li>
<li class="nav-item active">
<a href="/view/transactions" class="nav-link">View
Transactions</a>
</li>
</ul>
</div>
</div>
</nav>

<!-- Blockchain Node URL Selector -->


<div class="container">
<div class="row">
<div class="col-lg-12">

<div class="card-body">
<h4 class="card-title">View Transactions</h4>
<p class="card-text">Enter a blockchain node URL and click on
"View Transactions" button to check all transactions</p>
</div>

</div>
</div>
</div>

<div class="container alert alert-secondary">

<div class="row">
<label class="col-sm-2">Node URL:</label>
<div class="col-sm-10">
<textarea id="node_url" rows="1" class="form-
control">http://127.0.0.1:5001</textarea>
</div>
</div>

<br>

<div class="row">
<div class="col-lg-12 text-center">
<input type="button" id="view_transactions" class="btn btn-
primary btn-lg" value="View Transactions">
</div>
</div>

</div>

<br>
<!-- Blockchain Transactions Table -->
<div class="container">
<table id="transactions_table" class="table table-striped table-
bordered" cellspacing="0" width="100%">

46
</table>
</div>

<script src="/static/vendor/jquery/jquery.min.js"></script>
<script
src="/static/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="/static/vendor/DataTables/js/datatables.min.js"></script>
<script src="/static/vendor/DataTables/js/ellipsis.js"></script>

<script>
$(function() {

$('#view_transactions').click(function(){

$.ajax({
url: document.getElementById("node_url").value + "/chain",
type: 'GET',
success: function(response){

console.log(response);
//Generate Transactions Table
var transactions = [];
count = 1;

for (i = 1; i < response.length; i++) {


for (j = 0; j <
response["chain"][i]["transactions"].length; j++) {

//format date
var options = { year: "numeric", month: "short",
day: "numeric", hour: "2-digit", minute: "2-digit", second: "2-digit"
};
var date = new Date(response["chain"][i]["timestamp"]
* 1000);
var formattedDateTime = date.toLocaleTimeString("en-
us", options);

transaction = [count, response["chain"][i]["transactions"][j]

["recipient_public_key"], response["chain"][i]["transactions"][j]

["sender_public_key"],

response["chain"][i]["transactions"][j]["amount"],
formattedDateTime, response["chain"][i]
["block_number"]];
transactions.push(transaction);

count += 1;
};
};

// Restrict a column to 10 characters, do split words


$('#transactions_table').dataTable( {
data: transactions,
columns: [{ title: "#" },
{ title: "Recipient Public Key"},
{ title: "Sender Public Key"},
{ title: "Amount"},
{ title: "Timestamp"},
47
{ title: "Block"}],
columnDefs: [ {targets: [1,2,3,4,5], render:
$.fn.dataTable.render.ellipsis( 25 )}]
} );

},
error: function(error)
{ console.log(error);
}
});
});

});

</script>

</body>
</html>

5. SCHEDULE, TASK AND MILESTONE

• Topic: First, finalize a topic that has some real-life application on the
problem area and which would enhance my skills is blockchain.
• Research: After finalizing the topic, a proper survey has to be done. A
lot of different websites were used to learn about blockchain, making
transaction using python, a study of academic papers was to learn about
different methods for cryptocurrency, bitcoins, and blockchain
• First Implementation: Creating the functions and blocks of blockchain
node using python and implementing transaction blocks. This was when
the first milestone was achieved that was to understand and implement
the idea of the project.
• As the idea of the transaction scenario grew, I decided to add more
functionalities to the project, such as making transactions, view
transactions.
• Second Implementation: Creating frontend for clients which have
options to generate a public key and private key, making transactions,
view transaction, mining, and more. Implementing the SHA 256 to
generate encrypted public and private keys and connect all blockchain

48
nodes. This was when the final milestone was achieved that the system
was completed.

6. PROJECT DEMONSTRATION
6.1) User 1 Alpha

6.2) User 2 Akash

6.3) Blockchain Node 1

49
6.4) User 1’s Public Key and Private Key

6.5) User 2’s Public Key and Private Key

50
6.6) Creating Transaction

6.7) Confirmation

51
6.8) Transaction Completion

52
6.9) Node 1 Before Transaction

6.10) Node 1 After Transaction

53
6.11) Node 1 After Mining

6.12) Connecting Nodes

54
6.13) Final Transaction

55
7. FUTURE SCOPE

a) For consumers: The transaction information is open and transparent, so the rights and
interests of consumers are protected. Since the transaction is credible and has clear
timestamp. When consumers need to appeal their transactions to their consumer rights,
they can have more effective and credible proofs from proposed system.
b) For business: Businesses can do statistics and calculations for their own business
purposes based on all the digitized transaction information. This can reduce the errors
in computing results from manual operation. The statistical data can be even combined
with store’s inventory management to make goods and funds in required balance, to
further improve the business in accounting accuracy and labour cost.
c) For government: In the process of resolving the transaction dispute, more credible
evidence can be provided for reference. The digital transaction receipts also can solve
the problem of the paper receipt faked or lost. Considering taxation, government can
review the details of the business transactions with high credibility as a tax calculation
procedure to find out the standards of taxing rates to reduce many disputes in tax
collection.

56
8. REFRENCES

[1] Guang Chen1,2, Bing Xu1, Manli Lu1 and Nian-Shing Chen3(2018) Exploring
blockchain technology and its potential applications for education. Chen et al. Smart
Learning Environments (2018) 5:1 DOI 10.1186/s40561-017-0050-x
[2] Hussein Hellani, Abed Ellatif, Maroun Chamoun, Hussein El, Ahmed
Serhrouchni(2018) On BlockChain Technology: Overview of Bitcoin and Future
Insights. IEEE International Multidisciplinary Conference on Engineering Technology.
[3] Ralph C. Merkle Elxsi (1998) A Digital Signature Based on a Conventional
Encryption. 2334 Lundy Place San Jone, CA 95131
[4] Guy Zyskind, Oz Nathan, Alex ‘Sandy’ Pentland (2015) Decentralizing Privacy:
Using Blockchain to Protect Personal Data. © 2015, Guy Zyskind. Under license to
IEEE. DOI 10.1109/SPW.2015.2

57

You might also like