You are on page 1of 73

BLOCK CHAIN BASED PAYMENT SOLUTION

A PROJECT REPORT

Submitted by
Sourabh Naidu [Reg No:RA1611008010174]
Rahul Ranjan Sinha [Reg No: RA1611008010338]
Pawan Dhanwani [Reg No: RA1611008010234]
Vardhman Hundia [Reg No: RA1611008010541]

Under the Guidance of


P. Gouthaman
(Asst Professor, Department of Information Technology)
In partial fulfillment of the Requirements for the Degree
of
BACHELOR OF TECHNOLOGY

DEPARTMENT OF INFORMATION TECHNOLOGY


FACULTY OF ENGINEERING AND TECHNOLOGY
SRM INSTITUTE OF SCIENCE AND TECHNOLOGY
KATTANKULATHUR – 603203

APRIL 2020

SRM INSTITUTE OF SCIENCE AND TECHNOLOGY


KATTANKULATHUR-603203
BONAFIDE CERTIFICATE

Certified that this project report titled “BLOCK CHAIN BASED PAYMENT
SOLUTION” is the bonafide work of “Sourabh Naidu [Reg No:
RA1611008010174],Rahul Ranjan Sinha [Reg No: RA1611008010338],Pawan
Dhanwani [Reg No: RA1611008010234],Vardhman Hundia [Reg No:
RA1611008010541], who carried out the project work under my supervision. Certified
further, that to the best of my knowledge the work reported herein does not form part of any
other thesis or dissertation on the basis of which a degree or award was conferred on an
earlier occasion for this or any other candidate.

P.GOUTHAMAN Dr. G. VADIVU


GUIDE HEAD OF THE DEPARTMENT
Assistant Professor Dept. of Information Technology
Dept. of Information Technology

Signature of Internal Examiner Signature of External Examiner


ACKNOWLEDGEMENT

I would like to express my deepest gratitude to my guide, MR P.GOUTHAMAN with his

valuable guidance, consistent encouragement, personal caring, timely help and providing me

with an excellent atmosphere for doing research. All through the work, in spite of his busy

schedule, he has extended cheerful and cordial support to me for completing this research

work.

SOURABH NAIDU
RAHUL RANJAN SINHA
PAWAN DHANWANI
VARDHMAN HUNDIA
TABLE OF CONTENTS
CHAPTER NO. TITLE PAGE NO.
ABSTRACT i
LIST OF FIGURES ii
LIST OF ABBREVIATIONS iii
1 INTRODUCTION 1
1.1 OVERVIEW 1
1.2 EVOLUTION DETAILS 1
1.2.1 BLOCK CHAIN IN FINTECH 1
1.2.2 BLOCK CHAIN WITH IoT 2
1.3 BACKGROUND AND MOTIVATION 3
1.4 PROBLEM STATEMENT 5
1.5 RESEARCH OBJECTIVES 5
2 LITERATURE REVIEW 6
2.1 BLOCKCHAIN IN THE CARD PAYMENT INDUSTRY 6
2.2 SECURITY AND PRIVACY ON BLOCKCHAIN 7
2.3 BLOCKCHAIN AND SMART CARD TECHNOLOGY 8
2.4 CHIP AND PIN IS BROKEN 9
2.5 CREDIT CARD FRAUD DETECTION 10
2.6 SECURITY ASPECTS OF BLOCKCHAIN 11
2.7 NFC BASED SMART CAMPUS PAYMENT SYSTEM 12
2.8 ATOMIC CROSS CHAIN TRANSACTIONS 13
2.9 CONGESTION ATTACKS IN PAYMENT CHANNEL 14
NETWORKS
2.10 BLOCKCHAIN USING PROOF-OF-INTERACTION 15
3 PROPOSED METHODOLOGY 16
3.1 FUNCTIONAL REQUIREMENTS 16
3.2 NON-FUNCTIONAL REQUIREMENTS 16
3.3 SOFTWARE REQUIREMENTS 17
3.4 HARDWARE REQUIREMENTS 17
3.5 MAIN OBJECTIVES 17
3.6 ARCHITECTURE STRUCTURE 18
3.6.1 BLOCK CHAIN SERVER 18
3.6.2 POINT OF SALE(POS) 19
3.7 PROCEDURE 23
3.7.1 WEB APP 23
3.7.2 MOBILE APP 23
3.7.3 POS DEVICE 25
3.7.4 PAYELIXIR SERVERS 26
4 RESULTS 27
4.1 RESULTS OBTAINED 27
4.1.1 WEB RESULTS 27
4.1.2 APP RESULTS 30
4.1.3 POS RESULTS 32
4.2 COMPARISON WITH EXISTING SYSTEM 35
4.3 GRAPHICAL COMPARISON 36
5 CONCLUSION 37
6 FUTURE ENHANCEMENTS 38
7 REFERENCES 39
APPENDIX 41
PAPER PUBLICATION STATUS 66
PLAGIARISM REPORT 67
ABSTRACT

In the modern era, the word Blockchain is thrown around constantly and most people have little
idea about what it really is. Blockchain has become a buzzword and the debate continues over
the use of a decentralized technology in various industries to provide better service to the users.
Blockchain has decentralized and distributed technology that records all the transactions
without the need for intermediaries. The emerging technology has the capability of changing
the way of immutable identity storage and processing of payment in a faster environment.
Scalability, user-controlled network, flexibility, enhanced transparency, faster cross border
transactions, reduced transaction costs, and decentralization are the biggest advantages of the
use of technology in financial services and other industries. The Online payment transactions
has been a boom over all parts of the world but having about 180 current currencies across the
world produce a big challenge for online payments. The person has to undergo multiple
conversion for buying or selling of goods and services across the world and banks on average
charge them about a 13% tax over the currency conversion. With that high currency
conversions leads to big losses. Current payment technology does not allow seamless payment
across the country borders. Each country has their own currency, so it is difficult to pay digitally
if you are abroad. Our system tries to solve this problem using blockchain technology which
provides currency conversions worldwide and to revive non plastic payments (Net-Banking,
RTGS, NEFT) and plastic payments (debit & credit cards) across borders, to make inter
currency payments faster, secure and hassle free.

i|P a g e
LIST OF FIGURES

Figure 1 COMPARISON PAYMENT MODES Page:03


Figure 2 WORLDWIDE COMPARISON Page:04
Figure 3 SYSTEM ARCHITECTURE Page:18
Figure 4 BLOCKCHAIN ARCHITECTIRE Page:18
Figure 5 POS ARCHITECTURE Page:19
Figure 6 ESP32 ARCHITECTURE Page:20
Figure 7 PN532 NFC READER WRITER Page:21
Figure 8 4x4 KEYPAD Page:22
Figure 9 OLED DISPLAY Page:22
Figure 10 SEQUENCE DIAGRAM Page:23
Figure 11 ACTIVITY DIAGRAM Page:24
Figure 12 POS CIRCUIT CONNECTION Page:25
Figure 13 BLOCKCHAIN USE CASE DIAGRAM Page:26
Figure 14 Graphical Comparison with Existing System Page:36

ii | P a g e
ABBREVIATIONS

IoT Internet of Things

POS Point of Sale

UUID Universally unique Identifier

iii | P a g e
CHAPTER 1

INTRODUCTION

1.1 OVERVIEW

We are developing a blockchain solution for performing payments with a higher order of
transparency. (foot notes: A transparent system is where every bit of details is being shared
by everyone who is a part of a process). In blockchain the chain of blocks is stored in a way
that every person has a clone copy of data. When we want to add some data to it, referencing
is done to avoid adding fraudulent data. Blockchain is of the people, by the people and from
the people.

This decade will be a mocktail of various technologies and bound to bring new solutions to
our existing system. Thus, we are also experimenting with IOT and blockchain together
where blockchain solves the problem of double spending and IOT can bring a full payment
system to the table and do wonders.

1.2 EVOLUTION DETAILS

Many people have heard the term blockchain, but only a few are aware of this or have a
little idea about it in the innovative world. Blockchain could be defined as the chain of blocks
that cannot be modified, reversed or manipulated once they are formed.

1.2.1 BLOCK CHAIN IN FINTECH

Over the past few years, Blockchain and Crypto-currency have scavenged attention from
governments, financial officials, investors and researchers across the world. It is an
encrypted digitally distributed ledger that helps participants to make transactions without
any interruption from any third party. According to an IBM report[1], Blockchain
technology revolutionizes various industries by developing processes smarter; enhancing
security and transparency in business operations as compared to traditional business

1|P a g e
processes. Blockchain is disrupting the financial services sector through encrypting the
identified information and reduces the possibilities of cyber-attacks. Blockchain provides a
way to execute transactions between parties in an easy and transparent manner [2]. The
approach of sharing multiple copies of the same database and independently recorded
transaction in block makes it challenging for the attackers. Distributed ledgers,
Cryptography, smart contracts and consensus are the crucial parts of a Blockchain
ecosystem. This distributed technology has the capability to change the way of storing data
and carrying out transactions in a more secure manner. Decentralization, transparency and
the lack of need for financial intermediaries make blockchain as one of the most lucrative
technologies in the finance and the payment industry. Payment innovation, security, speed,
high transaction fees and settlement charges are the backbone causes behind the adoption of
blockchain into the payment industry.

1.2.2 BLOCK CHAIN WITH INTERNET OF THINGS

The Internet of things (IoT) and faster cross border payments are changing the way the
payments are handled [3]. Blockchain is getting more attention after the acceptance of the
new legislation in the European Union. The new ecosystem contains a consolidated and a
collaborative environment and is emphasizing on funding research and exploring blockchain
applications. According to an ACI Worldwide report (2016), blockchain has capability to
support and improve the current payments and processing infrastructure [4]. In an electronic
world, demands of customers are changing fast and the internet of things is increasing their
reach into the consumers lives. Along with this, rapid change in technologies and exposure
to smart devices are enhancing the needs of ubiquitous payment systems. In order to meet
the expectations of the techno-savvy customers and accelerating the transaction processes,
blockchain technology could play an important role.

2|P a g e
1.3 BACKGROUND AND MOTIVATION

The use of mobile payments is set to continue its inexorable rise and become the second
most common payment method after debit cards by 2022 [5]. These global stats mask a lot
of variability between regions as shown below (refer figure 1).

Figure 1 COMPARISON PAYMENT MODES

The stats found that that 37% of the merchants that participated already supported mobile
payments at the Point of Sale (i.e. via NFC, Mobile Web, Mobile Wallets, etc.) and 31.4%
planned to add to this feature or increase it [6]. The survey had 600 participants with 70%
doing business in the US, 44% doing business in Canada, 45% doing business in Western
Europe, 40% doing business in Asia and compared to 33% in Eastern Europe refer figure 2.

3|P a g e
Figure 2 WORLDWIDE COMPARISON

With the current payment technology, we aren't able to provide seamless transactions across
the country border. With about 180 different current currencies existing in the world brings
a big challenge to online payments. A transaction processed country to country has to be
dealt with a lot of tedious efforts from the users and eventually paying almost 13% of the
amount to be sent which leads to great losses as table shown below.

Country Bank name Example Round-trip


currency fees

International PayPal AUD/USD 3-9%

U.S.A. Wells Fargo USD/EUR 2%

U.S.A. Citibank AUD/USD 2.1%

Australia NAB AUD/EUR 10%

Australia Westpac AUD/EUR 11%

4|P a g e
United Kingdom Barclays GBP/EUR 13%

United Kingdom Lloyds GBP/EUR 5%

Canada Toronto Bank CAD/USD 6%

Canada RBC CAD/EUR 8%

1.4 PROBLEM STATEMENT

The Online payment transactions has been a boom over all parts of the world but having
about 180 current currencies across the world produce a big challenge for online payments.
The person has to undergo multiple conversion for buying or selling goods and services
across the world and banks on an average charge them about a 13% tax over the currency
conversion. With that high currency conversions leads to big losses. Current payment
technology does not allow seamless payment across the country borders. Each country has
their own currency, so it is difficult to pay digitally if you are abroad.

1.5 RESEARCH OBJECTIVES

1. How blockchain can help in other banking areas like KYC etc...

2. Can IOT be in future can work as a standalone application without any native interface
being made

3. Can blockchain and its consensus algorithm can be used to detect fraud

4. Can modern-day front-end frameworks can be integrated with blockchain and IOT.

5|P a g e
CHAPTER 2

LITERATURE STUDY

2.1 Blockchain – Creating positive vibes in the Card payment industry

The survey provides an elaborated description of the challenges faced by the card payment
industry. The survey also provides proper results on how new ubiquitous decentralized
payment systems could help over the existing payment ecosystem [7].

Benefits

Accurate Decentralization of payment technology. Decentralization of payment technology


is very important. User-friendly business model. One of the most important aspects of any
proposed technology is how interactive a model is. Being user friendly makes the whole
system easily understandable and usable. Interactive and easy to use applications are more
likely to reach a bigger scope of audience. Inclusion of multiple authorities in payment as
delegator/bakers. Inclusion of multiple authorities in payments as bakers refers to the
flexibility of the system. If the system is flexible enough for the need of the user, it is more
likely to be liked and used commonly by the users.

Challenges

No on-chain governance model proposed. On-chain governance model refers to the code
which is available on the block-chain server which authenticates the payment. If there is no
on-chain governance model then the centralization of the code would not be there which
means the chances of failure of the model increases. No clear idea of how crypto-currency
will be managed for processing transactions. Transactions of crypto-currency is itself a very
complex and tedious process and mining takes weeks too. No clear idea proposed to solve
the problem of cross border payments. Cross-border payments require a lot of permissions
and real-time currency conversions is a very important aspect too.

6|P a g e
How we improvised this:

Using harvester over BabyLonnet to use Cryptocurrency just to aid transaction. Smart
contract based on chain governance.

2.2 Security and Privacy on Blockchain

This survey provides a comprehensive review of the security and privacy of block-chains. It
provides over the basic and additional security attributes needed for the block-chain system.
It also provides corresponding security techniques especially cryptographic solutions for
security goals [8].

Benefits

Transactions are confidential. This maintains the atomicity of the transaction. However,
atomicity means that the data is centralized and is less prone to disturbances and
manipulations. Confidentiality is very important as the transactions are not public in nature.
No one would want their transaction details and credentials being public, it just increases the
security risks. Transactions are unlike each other. The patterns of each and every transaction
is generated differently so that the tracing is not possible. If the transactions are traceable, it
highly increases the chances of data getting hacked.

Each node receives the latest copy of data. Since every node should be updated with the
latest copy, it prevents data redundancy and helps restore the atomicity of the data.

Challenges

Consensus Algorithm based on voting rather than staying power based on computational
power. Voting algorithms are fairer but it takes a lot of time. Voting algorithms take more
time to determine the output which reduces the processing power of the algorithm. Proof of
work-based algorithm rather than Proof of stake. Proof of work-based algorithms are
referred to be first generation algorithms which were very primitive in nature, also the results
yielded by these algorithms were less accurate than the expected rate. It works slow and
takes up more processing power yet yielding inaccurate results.

7|P a g e
How we improvised this:

Since the above model uses a proof of work algorithm which is assumed to be inefficient
and primitive, we are using the latest, third generation of algorithms which is called proof of
stake. The chain governance will be guided by the proof of stake algorithms. Secondly, the
governance is based on multi-party computations. What multi-party computation means is
that the processing will be done and authorized by multiple parties which increases the
security factor as well as the time taken and makes the system faster.

2.3 Blockchain and smart card technology

The paper discusses a primer on block-chain technology, including the role of the secure
element and of smart card technology in securing transactions. It describes use cases that are
currently commercially available or being piloted and discusses common implementation
considerations [9].

Benefits

The benefit of this technology is that plastic payment is easily explained and the clear idea
of implementation is mentioned. The paper is based on implementing the plastic payment
based on crypto-currency. In India, the crypto-currency usage is banned by the government
as it takes a lot of computations for processing. This paper discusses the payment using
crypto-currency directly using a card which will be linked to an account containing the
amount and will be deducted in the form of crypto-currency. Second benefit of the paper is
that it uses asset tracking which means one can track the status of the payment / transaction.
It implements asset tracking in order to maintain atomicity of the transaction.

Challenges

The first challenge mentioned in the paper is that it does not elaborate on liquidity
management. What liquidity management means is the organization of the liquid assets. The
assets which are loosely available to the customers. It comes as a big challenge for this
proposed system. The paper also is very much dependent on crypto-currency for its

transaction to succeed. The usage of crypto-currency being banned in many countries comes
as a huge setback for the idea. Also, crypto-currencies have not been legalized and are less
secure and more complex to operate with. The third challenge comes as the paper is
8|P a g e
dependent on too many third-parties for the successful completion of the transaction. Too
many third-parties increase the chances of extra time consumption and the number of nodes
of failure also increases with increasing number of third-parties.

How we improvised this:

We are using no additional 3rd party apps which would help in easy and secure transactions.
As discussed, we are acting as a bank or fund provider. We will be eliminating the third-
party and provide the customers a wallet service and a card service through which they will
be able to do transactions. Our node works on tezos node which is a third-gen block-chain
implementation. Also, the papers have not discussed the problem called double spending.
Double spending means if the same transaction is initiated twice and the money is deducted
twice from the account of the customer or the bank, it results in great inconvenience to the
customers and comes as a big setback for the proposed idea. We have implemented our
system in such a way that it does batch processing, which means the transaction will not be
approved until all the necessary steps have been taken, which eliminates the double
spending.

2.4 Chip and PIN is Broken

The paper describes and demonstrates a protocol flaw which allows criminals to use a
genuine card to make a payment without knowing the card’s PIN, and to remain undetected
even when the merchant has an online connection to the banking network. It also considers
how the flaws arose, why they remained unknown despite EMV’s wide deployment for the
best part of a decade, and how they might be fixed. It concludes that the protocol is broken
[10].

Benefits

Terminal to parse the IAD, which does include the result of PIN verification. The multiple
authorization takes much longer time to parse the code further for processing, the card gets
verified itself using the IAD which is passed by the terminal. The card can change its CDOL
to request that the CVMR (cardholder verification method results) be included in the payload
to Generate AC command. Design principles for robust security protocols.

9|P a g e
Challenges

TC requests. Encoding of the CVM list Algorithm for selecting cardholder verification
method. Transaction flow. Values of the TVR for Lack of authentication in transport layer.
Encoding of Verify Encoding of the TVR. Recommended generation algorithm for the
ARPC. Recommended transaction data items to be included in the ARQC and TC. Absence
of cardholder verification results in ARQC and signature transaction. Whether the actual
cardholder verification method used is included in the CDOL. Whether the issuer checks the
value of IAD in online transactions. Encoding of the IAD.

How we improvised this:

We are using an NFC system which has a dynamic value of its own which is been modified
over each transaction. Our system also prompts us to request user to provide a One Time
Verification over mobile application which restricts unwanted users.

2.5 Credit Card Fraud Detection

The main aim is to detect fraudulent transactions and to develop a method of generating test
data. Nowadays the plastic payment methods have been in risks of failures and hackings.
Malicious attempts are being made to attempt fraud and forgery with the users of credit
cards. Plastic payments can be tracked down and can be infected with code so that the user’s
credentials are public and is prone to further attacks. In this paper the methods of fraud
detections are studied and measures are discussed [11].

Benefits

The measures discussed in the paper turn out to be accurate in finding out the fraudulent
transactions. It is based on the basis of false alerts too. Sometimes due to unwanted glitches
in the stream, false attempts are raised and which can lead to termination of on-going
transactions and then the problem of double-spending comes into play. Sometimes, the
transactions are traced by the frauds to embed malicious code in the transaction to show a
false completion acknowledgement and the amount debited goes to the frauds. So,
minimization of the number of false alerts is really beneficial. There are many methods and
algorithms which are combined and used as test cases for the proposed ideas to work. Also,
given the circumstances the system is able to detect the frauds and also predict the frauds on
the basis of the dataset it has been learning with.
10 | P a g e
Challenges

The first challenge to the above proposed system is that it is not able to handle skewed
distributions and transactions. Skewed transactions mean a sudden change in the course of
stream of the data during the ongoing transaction. The system is able to predict the fraudulent
attempts and also detect them but it lacks the decision-making power. The lack of decision-
making power leads to failure of transactions where the stream of data is changing path
suddenly. The second challenge to this model is that the noise is not handled properly. The
proper implementation of noise handling is not done properly, which may lead to distortions
in data streams. One more challenge that the above system faces is that it fails to classify the
overlapping data. Many genuine transactions are labelled as fraudulent when they are
genuine transactions. This can lead to an inaccurate result. The classifier system which
determines which is a fraudulent transaction and classifies then apart need to more accurate
and this can be achieved using good metrics for evaluation.

How we improvised this:

The overlapping of data is recovered by providing a one-time verification feature at the time
of transaction on mobile application. The OTP verification adds to the security as well as the
double spending problems.

2.6 Security Aspects Of Blockchain

This paper elaborates over the basic blockchain technology with in depth study over the
security models of blockchain. It provides respective countermeasures for the threats in the
blockchain environment [12].

Benefits

There is minimal loss of data. Loss here refers to the amount of distortions and disturbances
in the data stream which cause data to get affected. The minimal loss means more efficient
results, it makes it more suitable for the customers to use because the success rate is more.
Also, this system is designed to maintain the atomicity of the transaction. Maintaining the

11 | P a g e
atomicity of the transaction is important because it keeps all the data intact. No external
manipulation can alter the system code. It makes the whole system modular and organized.

Challenges

Transactions are added in the pool which makes the system relatively slower. The adding of
transactions in a pool, makes the processing slower because in a pool of processes, until and
unless an algorithm is implemented to give preference to a certain process, the most
important processes get left out and small requests are processed first. This actually makes
the arrangement rather disorganized. There is no mention of techniques to maintain privacy
in the paper. If the privacy is not maintained, important credentials will be jeopardized. Third
challenge to the idea is that it lacks security. It makes the block-chain part prone to DDOS.
Skewed transactions mean a sudden change in the course of stream of the data during the
ongoing transaction. The system is able to predict the fraudulent attempts and also detect
them but it lacks the decision-making power. The lack of decision-making power leads to
failure of transactions where the stream of data is changing path suddenly.

How we improvised this:

No loss of data as we are using the concept of proof of stake which maintains the whole
block in a transaction specific format. Smart contracts are entry points specific in nature.
Smart contract is a logically contract which contains all the constraints of a use case for
which blockchain is being. In simple words it contains business logic of the blockchain and
defines the storage of data.

2.7 NFC based Smart Campus Payment System

This paper focuses on payments using IoT using traditional methods and is confined to an
organization [9]. Transactions are based on traditional databases. The transaction details are
stored in the traditional schema-based databases like MySQL Databases. The paper
discusses how the new IoT enhancements can bring revolution in the payment methods. This
paper is based on the idea of a smart-payment system inside a given campus, the campus
maybe a college or an institution or an office campus. This mode of payment system depends
upon a Near Field Communication (NFC) system and a RFID Card. The payment is
controlled by a microcontroller called Arduino [13].
12 | P a g e
Benefits

It is a cost-effective way of doing plastic payments. The whole system is based on the most
common technologies in IoT. It enhances the reachability and scope of the system to the
people. Also, the availability of the parts of the proposed system is very common. The
financial aspect of the system is also not a burden to the developers as well as the customers.
All the modules used in the system are easily accessible too. Uno is a tested device with
open source support and has high feasibility. Arduino is the microcontroller used in the
system, which is a very common yet tried and tested microcontroller. It is used in basically
every other IoT device nowadays.

Challenges

Transactions are based on traditional databases. The transaction details are stored in the
traditional schema-based databases like MySQL Databases. The schema has to be fixed and
t cannot be changed, even the data has to be the same as schema. Non-schematic databases
are difficult to integrate. Scope is limited to organization. The above paper proposes a
payment system which is limited to a campus because of limited resources. Uses Arduino
uno which has technology-based issues. Arduino UNO is the most common Arduino in the
market. It has a limited number of pins and it is also the most basic of all the Arduinos. It
has connectivity issues as well as it is limited in processing power too. IoT system cannot
act as a standalone device. IoT devices always need to be connected with a operating system
and a connection. It at least needs a power source to power up.

How we improvised this:

We are using ESP32 over Arduino Uno. ESP32 is an advanced microcontroller than
Arduino. It is faster in processing as well has more functionalities too. It can use Bluetooth
Connections for wireless connections. Wi-Fi is also supported by ESP32. We are using
blockchain for storage of data rather than traditional databases. Block-chain is a safer and
more efficient way of storing data rather than traditional schematic databases.

2.8 Atomic Cross Chain Transactions

This paper is based on nested transaction technology using 1st generation block-chain
Ethereum. The nested technology is based on proof of stake, the first-generation block-chain.

13 | P a g e
The paper is based on maintaining the atomicity of the transactions using the nested
technology [14].

Benefits

The proposed system has been embedded with special sections of. Has been designed to
shield application developers from the complexity of cross chain transaction. Has timers to
create an abandon message in case a node does not respond in the set time.

Challenges

Uses Ethereum. Usage of Ethereum is firstly illegal in many countries and also it is the first-
generation technology. Some of the information in the standard Ethereum transaction is
exposed. The exposure of data can compromise privacy. Limited number of nodes can be
used.

How we improvised this:

We use Tezos Node which is a third-generation block chain and is much secure. We maintain
atomicity and prohibit double-spending. Double spending means if the same transaction is
initiated twice and the money is deducted twice from the account of the customer or the
bank, it results in great inconvenience to the customers and comes as a big setback for the
proposed idea. We have implemented our system in such a way that it does batch processing,
which means the transaction will not be approved until all the necessary steps have been
taken, which eliminates the double spending.

2.9 Congestion Attacks in Payment Channel Networks

This paper is based on the study of how payments systems malfunction when there is
congestion of requests from servers. Congestion can cause the processes to get pooled and
due to a lack of preference algorithm the processing time increases and congestion causes
malfunction [15].

Benefits

Node tagging makes it easier to find faults. Finding faults is called troubleshooting. Making
troubleshooting easy, makes it very easy to identify problems and correct them. Attacking
14 | P a g e
the entire network is not possible. Solves the problem of route hijacking. Route hijacking
means tracing back the data and then adding malicious code to it.

Challenges

Multiple channels for sending requests. Hub being exposed to the real world. If the hub is
being exposed to the real world, it can fall prey to hackers and it may cause harm to the
whole system. No priority queue implementation for managing request

How we improvised this:

Single channel based on first come first serve. FCFS is an algorithm which facilitates the
processing time in a swift manner. Hub not exposed to the real world.

2.10 Blockchain using Proof-of-Interaction

This paper is based on the study of how payments system malfunction when there is
congestion of requests from servers [16].

Benefits

Highly secure way of block generation. Self-mining is not possible. Shared mining makes
the process faster.
Challenges

Proof of Interaction is a very inefficient way of block generation. Double Touring makes the
system slow.

How we improvised this:

Block generation based on proof of stake. Proof of stake is the latest, third generation block-
chain technology, it is more secure and more powerful in processing. Implementation of
single touring makes the system faster.

15 | P a g e
CHAPTER 3

PROPOSED METHODOLOGY

3.1 Functional Requirements

The functional Requirements for our system are:

● System should be able to sign up and login to the various users in the system.

● System should always be allowed to transfer money from one account to another.

● System should fetch and show various transactional history of the users.

● System should allow user the pay through his or her wallet card

● System should allow change of access credentials

3.2 Non-Functional Requirements

The Non-functional Requirements for our system are:

● System should be disaster proof and should easily get mitigated if disaster happens

● The system should depict a small life cycle

● Maintenance life cycle should be similar to development life cycle

● Systems should be portable in nature

● System should be made with keeping all privacy laws in mind.

16 | P a g e
3.3 Software Requirements
The software Requirements for our system are:

1. Arduino IDE
2. Vanilla JavaScript
3. Android Studio
4. Tezos Framework
5. Node.js

3.4 Hardware Requirements


The hardware Requirements for our system are:

1. ESP32
2. PN532 - NFC READER WRITER

3. 4x4 KEYPAD
4. OLED DISPLAY
5. NFC CARD (READ WRITE COMPATIBLE)
6. JUMPER WIRES

3.5 Main Objectives

Main Objectives of our system are:

● Cross Border Payment

● Remove Double Spending

17 | P a g e
3.6 Architecture Structure
Acc to figure below Architectural components include the following:

Figure 3 SYSTEM ARCHITECTURE

3.6.1 Blockchain Server

Figure 4 BLOCKCHAIN ARCHITECTIRE

⇨ Web – Application:

We are using a remote Tezos sandbox for application. We have already deployed our smart
contract on sandbox and are referencing it using an address. On our server we are using a
conceal web pack to interact with the smart contract. On our server we are using Node.js to

18 | P a g e
interact with clients which aids the connection between front-end and backend. At backend
using web packs we send data to the smart contract. All the validations are being done by
delegators on the blockchain network. For fetching details of each transaction, we are
using EZTZ for referencing storage of blockchain.

⇨ Android – Application:

The architecture is very much similar to web applications. We are using REST APIs to
send and retrieve data from our server which have all the web packs to interact with
blockchain.

3.6.2 Point of Sale (POS)

Figure 5 POS ARCHITECTURE

Point of Sale is an IoT assisted device for efficient and payment options at ease. The POS
device has been created with four main devices as shown in figure (fig 4):

1. DEVKIT ESP32 DEVICE


2. PN532 – NFC CARD READER WRITER
3. OLED DISPLAY
4. 4x4 KEYPAD

19 | P a g e
1. DEVKIT ESP32 SoC:

ESP32 is a low-cost, low-power SoC (System on a Chip) series with Wi-Fi & dual-mode
Bluetooth capabilities. It is a dual-core or single-core Tensilica Xtensa LX6
microprocessor with a clock rate up to 240 MHz ESP32 is highly integrated with:

✔ built-in antenna switches,

✔ RF balun, power amplifier,

✔ low-noise receive amplifier,

✔ filters, and power management modules.

Figure 6 ESP32 ARCHITECTURE

The ESP32 acts as the central processor for the system. The additional modules like NFC
reader writer, keypad used for getting input from the users to ESP32 for the transaction to
process. The OLED display acts as an output module which is rendered through ESP32
according to the system functioning. The ESP32 also provides Serial output for
developing purposes. The processed data is been sent as a http post request with the
available WIFI module in ESP32. The server response is then shown over the display
accordingly [17].

20 | P a g e
2. PN532 – NFC Card Reader Writer:

The PN532 NFC RFID module is an affordable NFC and RFID module which is built
around NXP PN532, and with almost all of the I/O pins of the NXP532 chip on this little
module. It even works with 1443-A virtual card and NFC with android phone[18]. It
supports three modes such as:

a. IC2,
b. SPI,
c. and high-speed UART (HSU)

Figure 7 PN532 NFC READER WRITER

The PN532 acts as an input interface for accessing the user identification. It takes Unique
UUID as an identification of users for payment purposes which authentication is followed
with a security pin.

21 | P a g e
3. 4X4 keypad

Figure 8: 4x4 KEYPAD

It acts as a second input interface for the system. It is a keypad system with 0-9 digits plus
6 additional characters for multiple features. The keypad is used for majorly two inputs:
amount to be sent and Security Pin for the NFC card. It also takes confirmation from the
user for proceeding the transaction process.

4.OLED display

Figure 9: OLED DISPLAY

22 | P a g e
The OLED display is the main output component for the system. It provides an user
interactive display for using the device at ease. The display is rendered according to the
functionality needed.

5.NFC card

This is an identification card for the PayElixir users for payment purposes worldwide. The
user identification is done by the UUID inside the NFC card which has been re-
authenticated with a user security pin which could be dynamically changed from the user
website.

3.7 Procedure

3.7.1 Web Application

Figure 10 SEQUENCE DIAGRAM

Users login into web application using MySQL database authentication as user’s
data and the data in MYSQL database is verified Also Account balance could be
checked over the webpage and also provides currency conversion widget to check
23 | P a g e
real-time conversion rates which is very convenient for the user and makes web
application more flexible and handier. Previous Transactions could be accounted
for with Payers ID, Paying ID, amount sent, currency. User fills the PayElixir
account ID on which the payment needs to be sent which has been checked over the
database for verification and which also provides the paying currency then the
amount is to be entered according to paying account currency and then We
originate transaction on blockchain. On blockchain if the payer has enough amount
it gets deducted and the required amount gets credited to the payee in his/her
currency and also Customer is able to see the transaction and new amount on
his/her screen.

3.7.2 Mobile Application

Figure 11 ACTIVITY DIAGRAM

Representational state transfer (REST) is a software architectural style that defines a set of
constraints to be used for creating Web services so at first we consume REST APIs for
login server which returns either true or false and also, we can see balance and it gets
reverted from mobile application at the time of login. Now a user has many functionalities

24 | P a g e
like changing password, card management, passbook, Fund Transfer, MyAccount and all
which consume simple web APIs. For Transaction it is the same as the web but rather than
an inbound-call it consumes a REST API. Such that we originate the transaction using
REST to blockchain via our server such that we can Monitor all the activities. Monitoring
enables us to manage all flow and if error occurs it can be detected easily. It then
computes and does required action and validation like if the payer has enough balanced the
amount will get debited from his account and required amount will be credited to payee in
his currency. This conversion is done by the currency converter API as Currency
Converter API offers free web services for developers to convert one currency to another.

3.7.3 POS device:

Figure 12 POS CIRCUIT CONNECTION

1) The POS device is initiated with NFC card which fetches unique UUID for the
NFC card for account identification.

2) The amount to be sent is through a 4X4 keypad.

3) Security Pin is taken as input from the users through a 4X4 keypad for NFC
card authentication.

25 | P a g e
4) An http post request with www-url-encoded data which includes the user card
UUID, the security pin, the amount to be paid has been sent forward to the
Server for initiating the transaction.

5) The response of the user is been shown for the initiated transaction over the
display screen.

3.7.4 PayElixir Servers:

Figure 13 BLOCKCHAIN USE CASE DIAGRAM

We are using conceal libraries to interact with our Tezos server with contract
address as a primary parameter. When a UI action gets triggered it sends users'
input to the node application it then validates the data and sends to Tezos
Blockchain server using libraries.

26 | P a g e
CHAPTER 4

RESULTS

4.1 RESULTS OBTAINED

4.1.1 Web App Results

a. Login Page

This is the login page of our web application. A user must input a valid username and
password for authentication. Authentication is based on two factors here namely local
db. based and blockchain based, after authorization from both of them only you will be
able to accept dashboard.

b. SignUp Page

Sign up page allows a user to create a new account on our platform. Currency change is
not possible once submission is done. Users get a confirmation of signup on email and
also get card number of his new card.

27 | P a g e
c. Conversion Amount Widget

It allows a user to check current amount which be credited / debited subsequent to a


transaction.

d. Transaction Creator

You can originate a transaction by entering payee email address and amount to be paid in
your currency.

28 | P a g e
e. Transaction History

Shows details of each transaction so far. The data gets loaded from blockchain.

f. PayElixir NFC card support

Allows you to block/unblock card and change password any moment.

29 | P a g e
4.1.2 MOBILE APP RESULTS

a. Login Page

This is the login page of our web application. A user must input a valid username and
password for authentication. Authentication is based on two factors here namely local db
based and blockchain based, after authorization from both of them only you will be able to
accept dashboard.

b. Account Details

You can view your details like balance and currency here.

30 | P a g e
c. Fund Transfer

You can originate a transaction by entering payee email address and amount to be paid in
your currency.

d. Change password

You can change your account password from here.

31 | P a g e
4.1.3 POS RESULTS

a. NFC Initialize

When a card is brought near to POS machine it asks you whether to proceed for payment
or not ?

b. Amount To be sent

Enter the amount to be received in your currency our server will automatically convert
that into payers amount and process the payment

32 | P a g e
c. Enter Security Pin

Enter the security pin to authorize the payment.

d. Payment Initiation

It implies that we have sent request on server to process the payment.

33 | P a g e
e. Payment status – SUCCESS

Implies that the payment details were verified by the server and it has been originated on
blockchain

F. Payment status – FAILED

Implies that the details provided couldn't be verified and payment cannot be processed.

34 | P a g e
4.2 Comparison with Existing System

Let's see how PayElixir is better than other systems-

● Cross Border Payment: Various companies do not have the feature of providing
cross border but our system allows.
● Using Blockchain: Many platforms use SQL based systems to store and validate
data while ours use blockchain which is completely tamper proof
● Using Crypto Currency: We do not use crypto currency as it is not acceptable in
India.
● Faster: We are faster than any other platform compared.
● Double Spending: Ours is the only system which is double spending proof.

35 | P a g e
4.3 Graphical Comparison

Figure 14 Graphical Comparison with Existing System

36 | P a g e
CHAPTER 5

CONCLUSION

The proposed payment solution is based on block-chain which focuses on making the cross-
border online payment easier than ever before. The solution is called PayElixir. The project
aims to eliminate the third-party involvement in the online transfer of funds from one country
to another. In easier terms, the user can transfer funds to their relatives/acquaintances based
in other countries easily and in much less time than taken by the conventional payment
methods. Thus, the name PayElixir which means “Pay Magically”. The proposed system is
based on four important modules namely:

1. Tezos Blockchain

2. Web UI

3. Mobile UI

4. POS Device

The system serves better than the existing payment solutions because it eliminates “double
spending” and uses block-chain which minimizes the chances of transfer failures. The
system itself works as a bank which eliminates the buffer time for transfer of funds. Thus,
the system is secure and faster than the other existing systems and aims to make lives easier.

37 | P a g e
CHAPTER 6

FUTURE ENHANCEMENT

1. IoT Enhancements

The Internet of Things (IoT) is an emerging paradigm that enables the communication
between electronic devices and sensors through the internet in order to facilitate our lives.
IoT use smart devices and internet to provide innovative solutions to various challenges. To
meet current and future requirements it provided with a Bluetooth assisted POS also have
NFC assist from NFC supported phones as of now more than 90% phones comes with NFC
supported for security purpose it has Mobile authentication for confirmation and also provide
Easy Wi-Fi setup option of POS from app.

2. Blockchain Enhancements

The essence of blockchain consensus, and the consensus can form a recognized value. In
future, blockchain will liberate and improve the productivity of society by digitizing the
production relations. It has the Quick origination of transaction also it provides transaction
Acknowledgement as Blockchain Confirmations allow users to know that their
transactions over blockchain networks have been secured. Blockchain confirmation is a
number of times another block or transaction is placed chronologically after your
transaction block also it does Triggering off-chain events on-chain.

38 | P a g e
CHAPTER 7

REFERENCES

[1] IBM REPORT“Can blockchain revolutionize international trade”,By Emmanuelle


Ganne

[2] Blockchain-Based Security and Privacy in Smart Cities,Theodoru and Sklavos,2019

[3] Williamson, S., 2018. How Blockchain Technology Is Transforming Traditional


Payment Methods. [Online]. Available
through:<https://www.nasdaq.com/article/how-blockchain-technology-is-
transforming-traditional-payment-methods-cm1012647 >. Accessed: [03th
Jan’2020].

[4] ACI Worldwide report

[5] Worldpay’s 2018 Global Payment Report.

[6] sixth annual Mobile Payments and Fraud Survey conducted in 2018 by Kount

[7] Mr. Yuvraj Sharma, Miss Barkha Sharma , Dr. Dhiraj Jain Associate Professor,
Symbiosis Centre for Management Studies, "Blockchain – Creating positive vibes in
the Card payment industry",Annual Research Journal of SCMS, Pune

[8] RUI ZHANG and RUI XUE, LING LIU,"Security and Privacy on
Blockchain",ACM Comput Surv. 1,1,Article 1(Jan 2019)

[9] Secure Technology Alliance,"Blockchain and smart card technology",CB Insights


webinar, “The state of Blockchain”

[10] Steven J. Murdoch, Saar Drimer, Ross Anderson, Mike Bond University of
Cambridge Computer Laboratory Cambridge, UK, "Chip and PIN is Broken", 2010
IEEE Symposium on Security and Privacy

39 | P a g e
[11] Ishu Trivedi , Monika , Mrigya Mridushi Student, Dept. of Computer Science and
Engineering, Sikkim Manipal Institute of Technology, Rangpo, India,"Credit Card
Fraud Detection",International Journal Of Advanced Research in Computer and
Communication Engineering vol 5, Issue 1, January 2016

[12] Department of Telecommunications, Govt of India, "Security Aspects Of


BlockChain",Telecommunication Engineering Center, Ministry of communication
and information technology.

[13] Uday Kiran Ruttala*, M. S. Balamurugan and M. Kalyan Chakravarthi,"NFC based


Smart Campus Payment System",Indian Journal of Science and Technology, Vol
8(19), IPL0143, August 2015.

[14] Peter Robinson, Raghavendra Ramesh, John Brainard, Sandra Johnson “Atomic
Crosschain Transactions” ACEMS, Queensland University of Technology,
Australia

[15] Ayelet Mizrahi, Aviv Zohar (The Hebrew University of Jerusalem) “Congestion
Attacks in Payment Channel Networks” Israel Science Foundation (grant 1504/17)

[16] Jean-Philippe Abegg, Quentin Bramas , Thomas No¨el (University of Strasbourg,


ICUBE, Transchain, Strasbourg Transchain, Strasbourg ) “Blockchain using Proof-
of-Interaction” FUN with algorithms

[17] “The INTERNET of THINGS with ESP32”, [ONLINE] available


through:<http://esp32.net/> Accessed: [10th Feb 2020].

[18] PN5232 NFC RFID Module - A Quick Introduction, [ONLINE] available


through:<lectroschematics.com/nfc-rfid-module-pn532/> Accessed: [10th Feb
2020].

40 | P a g e
APPENDIX

Appendix 1: POS Integration Code

The code was developed and tested over Arduino IDE over ESP32 SOC

#include <ArduinoJson.h>
#include <SPI.h>
#include <PN532_SPI.h>
#include "PN532.h"
PN532_SPI pn532spi(SPI, 15);
PN532 nfc(pn532spi);
#include <Keypad.h>
#include <Wire.h>
#include "SSD1306.h"
#include<WiFi.h>
#include <HTTPClient.h>
//wifi credentials
const char* ssid = "Pawan";
const char* password = "qwerty5678";
// Initialize the OLED display using Wire library
SSD1306 display(0x3c, 21, 22);
// Initialize Keypad Settings
const byte ROWS = 4;
const byte COLS = 4;
char hexaKeys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[ROWS] = {12, 14, 27, 26}; //connect to the row pinouts of the keypad
41 | P a g e
byte colPins[COLS] = {25, 33, 32, 35}; //connect to the column pinouts of the keypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS,
COLS);
long timeSinceLastScreenUpdate = 0;
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println();
WiFi.begin(ssid,password);

while(WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.println("Connecting to wifi..");
}
Serial.println("Connected");
display.init();

display.flipScreenVertically();
nfc.begin();

uint32_t versiondata = nfc.getFirmwareVersion();


if (! versiondata) {
Serial.print("Didn't find PN53x board");
while (1); // halt
}
// Got ok data, print it out!
Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);
// Set the max number of retry attempts to read from a card
// This prevents us from waiting forever for a card, which is
// the default behaviour of the PN532.

42 | P a g e
nfc.setPassiveActivationRetries(0xFF);
// configure board to read RFID tags
nfc.SAMConfig();
Serial.println("Waiting for an ISO14443A card");
}
int userConfirmation(){
char am = customKeypad.getKey();
while(!am){
am = customKeypad.getKey();
Serial.println("Please Enter the key :");
}
Serial.println("entered key is:");Serial.print(am);
if(am == '#')
return 1;
else if(am == '*')
{
return 0;
}
}
void ServerRequest(char * uuid, char *p, char *am)
{
if(WiFi.status()== WL_CONNECTED){ //Check WiFi connection status
HTTPClient http;
http.begin("http://192.168.43.144:5000/iottransfer"); //Specify destination for HTTP
request

http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //Specify


content-type header
Serial.println("http created");
char JSONmessageBuffer[1000];
strcpy(JSONmessageBuffer,"receiverId=");
strcat(JSONmessageBuffer,"usd1@gmail.com");
strcat(JSONmessageBuffer,"&");

43 | P a g e
strcat(JSONmessageBuffer,"uuid=");
strcat(JSONmessageBuffer,uuid);
strcat(JSONmessageBuffer,"&");
strcat(JSONmessageBuffer,"pin=");
strcat(JSONmessageBuffer,p);
strcat(JSONmessageBuffer,"&");
strcat(JSONmessageBuffer,"amount=");
strcat(JSONmessageBuffer,am);
Serial.println(JSONmessageBuffer);
int httpCode = http.POST(JSONmessageBuffer); //Send the request
String payload = http.getString(); //Get the response payload

StaticJsonBuffer<300> JSONBuffer;//Memory pool


JsonObject& parsed = JSONBuffer.parseObject(payload);
if(parsed["IsSuccess"])
{
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
delay(2000);
}
else{
display.clear();
display.setFont(ArialMT_Plain_10);
display.setTextAlignment(TEXT_ALIGN_CENTER);
display.drawString(64, 22, "PAYMENT FAILED!");
display.display();
}
}
http.end(); //Free resources
}
else{
Serial.println("Error in WiFi connection");
}

44 | P a g e
void amountToBeSent(char* amount){
int count = 0;
char am;
while(1)
{
am = customKeypad.getKey();
if(am){
if(am == '#'){
break;
}
amount[count++] = am;
}
Serial.println("amount:");Serial.print(amount);
delay(1000);
}
}
void pin(char *PIN){
char dispPin[4];
int count = 0;
char am;
while(count<4)
{
am = customKeypad.getKey();

if(am){
if(am == '#'){
break;
}
PIN[count] = am;
dispPin[count] ='*';
count++;
}
Serial.println("PIN:");Serial.print(PIN);

45 | P a g e
delay(1000);
}
if(count<4)
{
Serial.println("Invalid Pin please re-enter 4 digit pin");
display.clear();
display.setTextAlignment(TEXT_ALIGN_CENTER);

display.drawString(64, 22, "Invalid PIN please enter re-enter 4 digit pin");


display.display();
pin(PIN);
}
}
void loop() {
boolean success;
uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 }; // Buffer to store the returned UID
uint8_t uidLength; // Length of the UID (4 or 7 bytes depending on ISO14443A
card type)

// Wait for an ISO14443A type cards (Mifare, etc.). When one is found
// 'uid' will be populated with the UID, and uidLength will indicate
// if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0],
&uidLength);

if (success) {
Serial.println("Found a card!");
Serial.print("UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
Serial.print("UID Value: ");
for (uint8_t i=0; i < uidLength; i++)
{
Serial.print(" 0x");Serial.print(uid[i], HEX);
}

46 | P a g e
Serial.println("");
char uuid[100]="";

for (uint8_t i=0; i < uidLength; i++)


{
char temp[10];
sprintf(temp,"%d", uid[i]); // <--- WORKS NOW
strcat(uuid,temp);
}
Serial.print(uuid);
Serial.println("done");
// Wait 1 second before continuing
delay(1000);
int option = userConfirmation();
if(option == 1)
{
Serial.println("success");
char amount[100]="";
amountToBeSent(amount);
Serial.println("amount done");
Serial.println(amount);

if(userConfirmation()==1)
{
char PIN[5]="";
pin(PIN);

if(userConfirmation()==1)
{
Serial.println("payment initialized");

ServerRequest(uuid,PIN,amount);

47 | P a g e
}
}
}
}
else
{
// PN532 probably timed out waiting for a card
Serial.println("Timed out waiting for a card");
}

delay(1000);

Appendix 2: Block chain code using Tezos

import smartpy as sp
class Proj(sp.Contract):
def __init__(self):
self.init(amtmap = sp.map(tkey = sp.TString, tvalue = sp.TRecord(curr = sp.TString , bal =
sp.TInt)),transmap = sp.map(tkey = sp.TString,tvalue = sp.TList(t = sp.TRecord(typ =
sp.TString, amt=sp.TInt, comt = sp.TString))))
@sp.entry_point
def createAccount(self,params):
sp.if ~(self.data.amtmap.contains(params.username)):
self.data.amtmap[params.username] = sp.record(curr = params.curr , bal = 0)
self.data.transmap[params.username]= []
@sp.entry_point
def addMoney(self,params):
sp.verify(params.amt>0)
self.data.amtmap[params.username].bal+=params.amt
rcd = sp.record(typ="CR",amt = params.amt , comt = "At Bank")
self.data.transmap[params.username].push(rcd)

48 | P a g e
@sp.entry_point
def transferMoney(self,params):
sp.verify(self.data.amtmap[params.snd].bal >= params.asnd)
srcd = sp.record(typ = "DB" , amt = params.asnd , comt = "Paid to "+ params.rcv)
rrcd = sp.record(typ="CR" , amt = params.arcv , comt = "Recieved from "+params.snd)
self.data.amtmap[params.snd].bal -= params.asnd
self.data.amtmap[params.rcv].bal += params.arcv
self.data.transmap[params.snd].push(srcd)
self.data.transmap[params.rcv].push(rrcd)
@sp.add_test(name="proj")
def test():
obj = Proj()
scenario = sp.test_scenario()
scenario +=obj
scenario += obj.createAccount(username="pawandhanwani",curr="INR")
scenario += obj.createAccount(username="vh9091",curr="USD")
scenario += obj.addMoney(username="vh9091",amt = 1)
scenario += obj.transferMoney(snd="vh9091",rcv="pawandhanwani",asnd=1,arcv=70)
scenario += obj.transferMoney(snd="vh9091",rcv="pawandhanwani",asnd=1,arcv=70)

Appendix 3: Server using Node.js

const express = require('express');


const app = express();
const path = require('path');
const request = require('request');
const bodyParser = require('body-parser');
var mysql = require('mysql');
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
let xmlHttp = new XMLHttpRequest();

var cors = require('cors')


app.use(cors())

49 | P a g e
const conseiljs = require('conseiljs');
const tezosNode = 'https://rpcalpha.tzbeta.net';
conseiljs.setLogLevel('debug');
const PORT = process.env.PORT || 5000;

var con = mysql.createConnection({


host : "localhost",
user : "root",
password : "",
database : "payelixir",
});

con.connect();

app.use(bodyParser.urlencoded({extended:false}));

app.use(express.static(path.join(__dirname, 'public')));

async function changePassword(finisher,email,oldpass,newpass) {


var sql = `UPDATE users SET password = "${newpass}" WHERE
email="${email}" AND password="${oldpass}" `;

con.query(sql,function(err,res,fields){
finisher(res);
});
}

async function verifyCard(finisher,pin,uuid) {


var sql = `SELECT currency,email FROM users WHERE uuid="${uuid}" and
pin="${pin}"`;

con.query(sql,function(err,res,fields){

50 | P a g e
finisher(res);
});
}

async function cardRecvCurrency(finisher,email) {


var sql = `SELECT currency FROM users WHERE email="${email}"`;

con.query(sql,function(err,res,fields){
finisher(res);
});
}

async function changePin(finisher,email,newpin) {


var sql = `UPDATE users SET pin = "${newpin}" WHERE email="${email}" `;
con.query(sql,function(err,res,fields){
finisher(res);
});
}

async function authenticate(finisher,email,password) {


var sql= `SELECT currency,name FROM users WHERE email="${email}"
AND password = "${password}"`;
con.query(sql,function(err,res,fields){
finisher(res);
});
}
var fbal;
var fcurr;
async function bc_auth(finisher,email) {
let xmlHttp = new XMLHttpRequest();

51 | P a g e
xmlHttp.open( "GET",
'https://rpcalpha.tzbeta.net/chains/main/blocks/head/context/contracts/KT1SKkZYri85EY
YHQ8AFxToeRYWfkcdcCrxs/storage', false ); // false for synchronous request
xmlHttp.send( null );
var data = JSON.parse(xmlHttp.responseText);
var lenUsers = data.args[0].length;
var i;
var found =0;
for(i=0;i<lenUsers;i++)
{
if(data.args[0][i].args[0].string === email)
{
fbal = data.args[0][i].args[1].args[0].int/1000;
fcurr = data.args[0][i].args[1].args[1].string;
found = 1;
}
}
console.log(found);
finisher(found);
}

async function bc_passbook(finisher,email) {


let xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET",
'https://rpcalpha.tzbeta.net/chains/main/blocks/head/context/contracts/KT1SKkZYri85EY
YHQ8AFxToeRYWfkcdcCrxs/storage', false ); // false for synchronous request
xmlHttp.send( null );
var data = JSON.parse(xmlHttp.responseText);
var lenUsers = data.args[0].length;
var i;
for(i=0;i<lenUsers;i++)
{
if(data.args[0][i].args[0].string === email)

52 | P a g e
{
transdata = data.args[1][i].args[1];
found = 1;
}
}
var trans = [];
if(found ==1)
{
for(i=0;i<transdata.length;i++)
{
trans[i]={};
trans[i].amt = transdata[i].args[0].args[0].int/1000;
trans[i].com = transdata[i].args[0].args[1].string;
trans[i].typ = transdata[i].args[1].string;
}
}
console.log(trans);
finisher(trans);
}

function call_ccapi(finishedAPI, ckey)


{
request('https://free.currconv.com/api/v7/convert?q='+ckey+'&compact=ultra&api
Key=a935d1bba82661b2b63b',{json : true},(err,res,body)=> {
if(err)
{
console.log(err);
}
if(res.statusCode === 200)
{
//console.log(body);
finishedAPI(body);
}

53 | P a g e
});
}
async function bc_transferMoney(finisher,arcv,asnd,snd,rcv) {
/*console.log(arcv);
console.log(asnd);
console.log(rcv);
console.log(snd);*/
const keystore = {
publicKey:
'edpku9fsTWSoioqdhoVVdWgokdgHmV2RZBG8fbWuCguQ64aDV43n9m',
privateKey:
'edskRzsEes8WGGknU8SCtUer7KDmBy1x4FHxdv8Tc5FaYRUJzHqXkQR4ChM2NrW
QKKVCGwaTg7sxyfaXFFLo6ez6vc5reF3JzY',
publicKeyHash: 'tz1fDhtjix9i2QEDDUZDugpo39CnZZ9HbBAB',
seed: '',
storeType: conseiljs.StoreType.Fundraiser
};
const contractAddress = 'KT1SKkZYri85EYYHQ8AFxToeRYWfkcdcCrxs';
const result = await
conseiljs.TezosNodeWriter.sendContractInvocationOperation(tezosNode, keystore,
contractAddress, 0, 100000, '', 1000, 750000, undefined, `(Right (Pair (Pair (Pair ${arcv}
${asnd}) "${rcv}") "${snd}"))`, conseiljs.TezosParameterFormat.Michelson);
console.log(`Injected operation group id ${result.operationGroupID}`);
finisher("Data inserted successfully in blockchain. Reference
id:"+result.operationGroupID);
//return result.operationGroupID;

async function getCurrency(finisher,email) {


var sql= `SELECT currency FROM users WHERE email="${email}"`;
con.query(sql,function(err,res,fields){
//console.log(res);

54 | P a g e
finisher(res);
});
//console.log("Connected..");*/
}

app.post('/login',function(req,res){
authenticate(function(localLoginResult){
if(localLoginResult.length > 0)
{
bc_auth(function(bcLoginResult){
if(bcLoginResult == 1)
{
var loginResult = {'IsLogin' : 1 , name :
localLoginResult[0].name , currency : fcurr , balance : fbal}
res.json(loginResult);
}
else
{
var loginResult = {'IsLogin' : 2 , name :
localLoginResult[0].name , currency : 'NA' , balance : 0}
res.json(loginResult);
}
},req.body.email);
}
else
{
var loginResult = {'IsLogin' : 3 , name : 'NA' , currency : 'NA' ,
balance : 0}
res.json(loginResult);
}
},req.body.email,req.body.password);
});

55 | P a g e
app.post('/passbook',function(req,res){
bc_passbook(function(passbookResult){
res.json(passbookResult);
},req.body.email);
});

app.post('/changePassword',function(req,res){
changePassword(function(changePwdRes){
if(changePwdRes.affectedRows > 0 )
{
var pwdinfo = {'isChanged' : 1};
res.json(pwdinfo);
}
else
{
var pwdinfo = {'isChanged' : 0};
res.json(pwdinfo);
}
},req.body.email,req.body.oldpass,req.body.newpass);
});

app.post('/changePin',function(req,res){
changePin(function(changePinRes){
if(changePinRes.affectedRows > 0)
{
var pwdinfo = {'isChanged' : 1};
res.json(pwdinfo);
}
else
{
var pwdinfo = {'isChanged' : 0};

56 | P a g e
res.json(pwdinfo);
}
},req.body.email,req.body.newpin);
})

app.post('/transfer',function(req,res){
getCurrency(function(currencyRes){
console.log(currencyRes[0].currency);
if(currencyRes.length>0)
{
console.log('Converter Started');
call_ccapi(function(ccres){
var value=0;
for (var key in ccres) {
value = ccres[key];
break;
}
console.log(value);
var convertedAmount = req.body.samt * value * 1000;
var finalAmount = Math.floor(convertedAmount);
console.log(finalAmount);

/*console.log("Values (");
console.log(finalAmount);
console.log(req.body.samt);
console.log(req.body.email);
console.log(req.session.userId);
console.log(")");*/
bc_transferMoney(function(tres){
var transferInfo = {'isTransfered' : 1}
res.json(transferInfo);

57 | P a g e
},finalAmount,req.body.samt*1000,req.body.sender,req.body.receiver);
/*var transferInfo = {'isTransfered' : 1}
res.json(transferInfo);*/
},req.body.scurr+'_'+currencyRes[0].currency);
}
else
{
var transferInfo = {'isTransfered' : 0}
res.json(transferInfo);
}
},req.body.receiver);
});

app.post('/iottransfer',function(req,res){
console.log(req.body.receiverId);
console.log(req.body.pin);
console.log(req.body.amount);
console.log(req.body.uuid);
verifyCard(function(res){
console.log(res[0].currency);
console.log(res[0].email);
cardRecvCurrency(function(ares){
console.log("receiver");
console.log(ares[0].currency);

call_ccapi(function(bres){
var value=0;
for (var key in bres) {
value = bres[key];
break;
}
console.log(value);

58 | P a g e
var convertedAmount = req.body.amount * value * 1000;
var finalAmount = Math.floor(convertedAmount);
console.log(finalAmount);
console.log('--');
console.log('receiver');
console.log(req.body.receiverId);
console.log('sender');
console.log(res[0].email);
console.log('receiver amount');
console.log(req.body.amount*1000);
console.log('sender amount');
console.log(finalAmount);
console.log('--');
bc_transferMoney(function(cres){
console.log(cres);

},req.body.amount*1000,finalAmount,res[0].email,req.body.receiverId);
},ares[0].currency+"_"+res[0].currency);
},req.body.receiverId);

},req.body.pin,req.body.uuid);
var info = {"IsSuccess" : true, paidTo : "pawan@gmail.com",amt:90};
res.json(info);
});

app.listen(PORT , () => console.log('Server Running'));

59 | P a g e
Appendix 4: Android App Code

4.1 Transfer Logic

package com.example.payelixir;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class fundtransfer extends AppCompatActivity {


EditText payField, amountField;
Button payBtn;
ProgressBar progressBar;

60 | P a g e
void transferUtil(final String payto, final String amount ,final String sender, final String
curr)
{
RequestQueue queue = Volley.newRequestQueue(this);

String url = "http://192.168.43.144:5000/transfer";


StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
/*Toast.makeText(login.this,response,Toast.LENGTH_LONG).show();*/
try {
JSONObject JO = new JSONObject(response);
int result = JO.getInt("isTransfered");
if(result == 1)
{
Toast.makeText(fundtransfer.this,"We have originated transaction on
blockchain. Please check back after few minutes.",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(fundtransfer.this,"Payment
failed.",Toast.LENGTH_LONG).show();
}
progressBar.setVisibility(View.GONE);
} catch (JSONException e) {
e.printStackTrace();
}

}
},
new Response.ErrorListener()

61 | P a g e
{
@Override
public void onErrorResponse(VolleyError error) {
// error
/*Log.d("Error.Response", response);*/

Toast.makeText(fundtransfer.this,error.getMessage(),Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
){
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("receiver", payto);
params.put("samt", amount);
params.put("sender",sender);
params.put("scurr",curr);

return params;
}
};
postRequest.setRetryPolicy(new DefaultRetryPolicy(
30000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(postRequest);

@Override
protected void onCreate(Bundle savedInstanceState) {

62 | P a g e
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fundtransfer);
Intent intent = getIntent();
final String name = intent.getStringExtra("name");
final String email = intent.getStringExtra("email");
final String currency = intent.getStringExtra("currency");
final String balance = "" + intent.getDoubleExtra("balance",0.0);
payField = (EditText) findViewById(R.id.payee);
amountField = (EditText) findViewById(R.id.amount);
progressBar = (ProgressBar) findViewById(R.id.progressBar3);
progressBar.setVisibility(View.GONE);
payBtn = (Button) findViewById(R.id.button2);
payBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double amount = Double.parseDouble(amountField.getText().toString());
String payto = payField.getText().toString();
if(amount>0)
{
transferUtil(payto,""+amount,email,currency);
progressBar.setVisibility(View.VISIBLE);
}
else
{
Toast.makeText(fundtransfer.this,"Invalid
Amount",Toast.LENGTH_LONG).show();
}
}
});
}
}

63 | P a g e
Appendix 5: Web App Code

5.1 Converter Section

<!--This is the nav bar-->


<div class="navbar-container">
<div class="burger-menu"> </div>
<div class="logo"> <p style="color: white;">PayElixir</p></div>

</div>
<!--Navbar ends here-->
<!-- The slider and coverter starts here-->
<div class="container-fluid">
<div class="row">
<div class="col converter">

</div>

<div id="particles-js" style=" width: 750px; height: 350px; background-image:


url(newimg1.png); margin-top: 10px; "> </div>
</div>
</div>
</div>

5.2 Transfer Section

<!--transfer-->

<div id="transfer" class="transfer">

<div class="inner_transfer">

<p>Enter Name/ ID</p>

<input type="text" name="transfer_name" class="input3">

<p>Enter Amount</p>

64 | P a g e
<input type="number" name="amount"class="input3">

<p>Converted Amount </p>

<input type="number"id="amount_converter" class="input3" readonly>

</div>

<input type="submit" value="Transfer" class="input4">

<a href="#">Recent Transfers</a>

</div>

<!--Transfer ends here-->

5.3 Passbook Section

<div id="passbook" class="passbook">


<h2>Recent Transactions</h2>
<div class="show_bal">
<h3 >Total Balance: </h3> &nbsp;&nbsp;
<h3 id="balance-show">XXXX</h3>
<p1><i class="fas fa-rupee-sign"></i>
<i class="fas fa-euro-sign"></i>
<i class="fas fa-pound-sign"></i>
<i class="fas fa-dollar-sign"></i></p1>
</div>
<div class="pass_table">
<ul> <li>S No.</li> <li>hi</li> </ul>
<ul> <li>Amount</li> </ul>
<ul> <li>Type</li> </ul>
<ul> <li>Time</li> </ul>
<ul> <li>Benefeciary</li> </ul>
</div>
</div>

65 | P a g e

You might also like