Download as pdf or txt
Download as pdf or txt
You are on page 1of 86

UNIVERSITY OF JAMMU

MAJOR PROJECT REPORT


ON

“FOOD SUPPLY CHAIN USING


BLOCKCHAIN”

Submitted to: Project guide


Department of Computer Engg, Mr. Hargobind Singh
GCET, Jammu

Submitted by:
Mr. Pranav Sharma (GCET/168/18)

DEPARTMENT OF COMPUTER ENGINEERING


GOVERNMENT COLLEGE OF ENGINEERING AND TECHOLOGY, JAMMU
JULY 2022

`
DEPTT. OF COMPUTER ENGINEERING, GCET 1
MAJOR PROJECT REPORT
ON

“FOOD SUPPLY CHAIN USING


BLOCKCHAIN”

Submitted in partial fulfillment of the requirement for the degree of


Bachelor of Engineering in Computer Engineering from Jammu
University.

Submitted by:
Mr. Pranav Sharma (GCET/168/18)

DEPARTMENT OF COMPUTER ENGINEERING


GOVERNMENT COLLEGE OF ENGINEERING AND TECHOLOGY, JAMMU
JULY 20212
`
DEPTT. OF COMPUTER ENGINEERING, GCET 2
CERTIFICATE

We hereby declare that the work which is being presented in the B.E.
Major Project Report entitled "Food Supply Chain using Blockchain”
in partial fulfilment of the requirements for the award of the Bachelor of
Engineering in Computer Engineering and submitted to the Department
Computer Engineering of Government college of Engineering and
Technology Jammu is an authentic record of our own work carried out
during a period from April 2022 to August 2022 under the supervision of
our Project Guide Mr. Hargobind Singh

The matter presented in this thesis has not been submitted by me for the
award of any other degree elsewhere.

This is to certify that the above statement made by the candidate is correct
to the best of my knowledge.

Dr. Sameru Sharma Dr. Simmi Dutta


(Principal, GCET) (HoD, Deptt. Of Comp.Engg)

`
DEPTT. OF COMPUTER ENGINEERING, GCET 3
ACKNOWLEDGEMENT

We take this opportunity to express our profound gratitude and deep


regards to my Project Supervisor Mr.Hargobind Singh along with our
principal Dr. Sameru Sharma for their exemplary guidance, monitoring
and constant encouragement throughout the course of the project.

We also take this opportunity to express a deep sense of gratitude to the


entire teaching and non-teaching faculty of the Computer Engineering
Department for their support and appreciation.

Last but not the least we are thankful to our family members and friends
for their much-needed moral support and encouragement

Submitted by:

Mr. Pranav Sharma (GCET/168/18)

`
DEPTT. OF COMPUTER ENGINEERING, GCET 4
ABSTRACT

Today’s food supply chain faces problems such as disconnection


between its various stakeholders, lack of transparency in food
production and distribution. Complete traceability of the product to its
original source is also not available. Keeping track of such
information can eradicate the limitations of the current supply chain.
A blockchain based transparent network will ensure digital ledger of
transactions and movement for all stakeholders in their supply chain
network. Also, the suicide rate of farmers is increasing at an alarming
rate due to high debts and poor yield from farming. Micro finance
with blockchain can help these farmers out of debt and avoid
dependency of farmers on bank loans with high interest.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 5
TABLE OF CONTENTS

S.NO CONTENT PAGE NO

1 CHAPTER 1:Introduction 1-7


1.1 Objective 6
1.2 Motivation 7

2 CHAPTER 2:Blockchain 8-20


2.1 Literature survey 8
2.2 Application of Blockchain 11
2.3 Elements of Blockchain 15
2.4 Hashing 19
2.5 Public Key Infrastructure 20

3 CHAPTER 3:Smart Contract 21-30


3.1 What are Smart Contracts? 21
3.2 Implementation of Smart Contracts 22
3.2.1 Digital Asset Transfer 22
3.2.2 A Scenario for Purchasing a Service 23
3.3 Applications of Smart Contracts 24
3.3.1 Accuracy 25
3.3.2 Transparency 26
3.3.3 Speed and Efficiency 27
3.3.4 Security 27
3.3.5 Cost Reduction 28
3.4 Limitations of Smart Contrcts 28
3.4.1 Immutability 29
3.4.2 Contractual Secrecy 29
3.4.3 Legal Adjudications and Enforceability 30

4 CHAPTER 4: USE CASE SELECTION AND 31-33


DESIGN PROCESS
4.1 USE CASE SELECTION 31
4.2 Design 32

`
DEPTT. OF COMPUTER ENGINEERING, GCET 6
5 CHAPTER 5: Blockchain in Supply Chain 34-40
5.2 Blockchain in Agri-Food Supply Chain 37
5.3 Walmart – Food Traceability 39

6 CHAPTER 6: Project Methodology 41


6.1 Architecture 42
6.2 Network Design 43
6.3 Smart Contract System 45
6.4 Algorithms 48
6.4.1 Algorithm 1 Farmer Sell Crops 49
6.4.2 Algorithm 2 Processor Sells agri-food 50
6.4.1 Algorithm 1 Customer Buys 52

7 CHAPTER 7: Implementation 54
7.1 Software Requirements 54
7.2 Software Tools Used 54
7.2.1 Python 54
7.2.2 Solidty 57
7.2.3 Ganache 61
7.2.4 Remix IDE 62
7.2.5 Anaconda Navigator 63
7.3 Code 64
8 CHAPTER 8: SYSTEM STUDY 70

9 CHAPTER 9 SYSTEM TESTING 72


10 Conclusion 75

11 References 76

`
DEPTT. OF COMPUTER ENGINEERING, GCET 7
LIST OF FIGURES

S.NO CONTENT PAGE NO


1 Figure 1.1: Cyber Physical System 1
2 Figure 1.2:Centralized Ledger and Distributed Ledger 2
3 Figure 1.3:Proposed Solution 6
4 Figure 2.1 A simplified blockchain 9
5 Figure 2.2 Real Life Applications 11
6 Figure 2.3 Uses in Governance 14
7 Figure 2.4 Basic Working of Blockchain 15
8 Figure 2.5 Types of Consensus Algorithms 18
9 Figure 3.1 Smart Contract 21
10 Figure 3.3 Benefits of Smart Contracts 26
11 Figure 3.4 Disadvantages of Smart Contract 30
12 Figure 4.1 Framework for blockchain use case 31
13 Figure 4.2 Design Process for blockchain 33
14 Figure 5.1 Blockchain in supply chain 36
15 Figure 5.2 Food Supply Chain System 38
16 Figure 5.3 Walmart 40
17 Figure 5.4 Walmart Food Traceability 40
18 Figure 6.1 Supply Chain Process 41
19 Figure 6.2 Architecture 42
20 Figure 6.3 Network Design 43
21 Figure 6.4 Entity Relationship Diagram 45
22 Figure 6.5 Sequence Diagram 1 46
Figure 6.6 Sequence diagram 2 47
23
Figure 6.7 Sequence diagram 48
24
25 Figure 7.1 Features of Python 55
26
Figure 7.2 Ganache GUI 61
27
28 Figure 7.3 Aanaconda Navigator
63
29

`
DEPTT. OF COMPUTER ENGINEERING, GCET 8
LIST OF TABLES

CONTENT PAGE NO
Table 1.1 4
Table 2.1 10
Table 2.2 11
Table 2.3 12
Table 2.4 16
Table 2.5 19
24
Table 3.2.1

`
DEPTT. OF COMPUTER ENGINEERING, GCET 9
CHAPTER 1: INTRODUCTION

Industrial Revolutions have been transforming industrial processes to facilitate mass


production and large numbers of business transactions. New technologies are being
introduced to disrupt previous ones to make the lives of people easier and more
productive. We are witnessing the fourth industrial revolution, which primarily represents
Industrial cyber physical systems loaded with technologies like Big Data, AI, IoT, and
cloud computing. These systems have potential to bring disruptions for all traditional
business models and hence there is an imperative need for a redesign and digitization of
activities

A cyber-physical system (CPS) is an automation of physical systems where sensors based


computers monitor and control physical processes. CPS is about building computation,
communication and control interface between physical processes and the cyber systems
as shown in figure 1.1. CPS may include many sensor based components that capture real
world data of events and pass that data to cyberspace having computation and storage
capabilities. Computation function directs actuators with necessary information and
corresponding events are executed.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 1
Figure 1.1: Cyber Physical System

CPS systems include Data driven transaction processing and decision making, this
requires complete assurance over processing, integrity and availability of data. CPSs have
been using databases from quite some time now for these data management operations.
Though databases provide many features but risk of unauthorized changes, single point
of failure and dependencies on third parties are still matters of concern for CPSs.
Blockchain can be used to solve these problems effectively. Blockchain is an innovative
way of storing data about transactions and quite different from databases. The Blockchain
technology was first presented by Satoshi Nakamoto in 2008 and later he implemented
the technology in 2009 as a core component of bitcoin (a popular crypto currency).

The blockchain is a distributed ledger that records transactions in chronological order [3].
The ledger is maintained by every participating node in a blockchain network unlike
centralized ledger where ledger is maintained on a server and all nodes update
transactions on that server as shown in figure 1.2.

Figure 1.2: Centralized Ledger and Distributed Ledger

Blockchain has the following features which makes it a better alternative for business
processes.
`
DEPTT. OF COMPUTER ENGINEERING, GCET 2
● Immutability: Immutability means no change after the transaction gets completed.
Blockchain is based on hashing that generates unique hash code for block of transactions
and any change in transaction results in change in hash code hence any change can be
detected and discarded immediately.

Immutability is achieved by making verification and validation computational intensive


so that it reduces the feasibility of any attacks on manipulation of blockchain data.

● Secure: Blockchain is secure as it involves extensive use of cryptography to ensure


confidentiality and transactions are mapped with unique and secure identity of users. This
is achieved by using the private key of users.

● Privacy: Privacy is about protecting personal identity information of users and


blockchain ensure that using cryptography.

● Distributed: Transactional data in blockchain is stored in distributed manner and all


network nodes have a copy of complete chain of data to ensure no single point of failure.
Whenever a transaction is initiated by a node the copy of that transaction is sent to all the
nodes on the network.

● Transparency: Transparency is ensured by involving all nodes in transaction


verification and all participating nodes have a copy of the complete blockchain.

Blockchain enforces trust by making transaction processing transparent and the


verification process of the transaction with hashing (Merkle tree) makes it immutable.
Blockchain eliminates the risk of a single point of failure as it is distributed in nature and
all network nodes carry a copy of transactional data. A blockchain enables the quick
transactions between parties without the need of intermediary to provide assurance as it
ensures integrity of transactions. Blockchain technology primarily has two classifications
i.e., Permission less and Permissioned. A permission less blockchain often referred to as

`
DEPTT. OF COMPUTER ENGINEERING, GCET 3
public blockchain is open for all users. Though it has huge potential like Bitcoin but may
not be suitable for business owners who want to have control on the system of transaction
processing. Business processes may have specific requirements and complex operations
that need customizable solutions that restrict involvement of outsiders. Permissionless
blockchain also suffers from some challenges like scalability, regulatory institutions and
control over evolution. This has given organizations to explore other alternatives like
permissioned blockchain, which can be controlled privately and can restrict participation
in the blockchain network to only trusted participants. Permissioned blockchain is also
referred to as a private blockchain. This will revolutionize the way transactions are
performed, thereby ensuring effectiveness of the system in handling business
processes. Comparison of Permission less and Permissioned blockchain is presented in
table 1.1

Table 1.1 Comparison of Permission less and Permissioned Blockchain

Permission less Blockchain Permissioned Blockchain


blockchain with no blockchain that allow only selected
restrictions and truly
transparent, participants
follows to
governance structure and
decentralized
bring and all users
trust among allow private
anyone canhigh
and offers join join
possible use security
cases digital possible use cases supply chain
immutable
currency, transactions
fast, scalablethrough
management, authentication
and more energy
process
efficient

But, before we get etc.,


fundraising deeper into Blockchain, let’s consider
banking a simple use case to understand
and payments
the concept. Think of a metallurgy supply chain Cyber physical system which maintains
a database of transactions. It maintains information related to transactions like supplier’s
personal information, address, payment methods, grade, rate, quantity, total, tax, type of
ore and total amount. It also holds personal emails and phone numbers. There is risk of
inappropriate manipulation of the data during and after the transaction has taken place.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 4
There is risk of data privacy loss as well and confidential information may be exposed to
theft or leakage due to employee collusion.

We trust operators and assume that they process and maintain transaction records
accurately and securely. As the operations are human operator based and hence there are
vulnerabilities and possibilities of fraudulent practices during everyday transactions.
Hence, there is no assurance on integrity and reliability of operations. So, basically the
whole supply chain Cyber physical system depends completely on a centralized system
handled by human operators. Now, the question is can we imagine the above scenarios
without these centralized systems involved in the transactions?

Blockchain technologies can address these issues. Blockchain is fundamentally a


transition from centralized trust-based systems to decentralized trust-free systems. It
provides a system between any numbers of involved parties without the need for an
intermediary involved in the transactions. In recent Project it has been observed that a
key factor for the success of blockchain based systems is the number of transactions.

Hence systems with higher transaction volume shall be the right business case.
Blockchain technology can help in automating various decision functions that are
executed manually to increase net benefits.

Considering a supply chain process scenario involving buyers and suppliers, with
blockchain based system Suppliers would have more benefit if fee per transaction is less.
Buyers' benefit depends on the extension in the date of payment. From the funder’s
perspective benefits are achieved as a shorter processing time so as to complete more and
more transactions in the same time frame using blockchain based solutions. All these
factors are critical for the success of Blockchain in metallurgy supply chain Cyber
physical systems. But if the cost of the system is more than the benefits to be realized
then Reengineering based restructuring is a better option as compared to complete system
development based on blockchain.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 5
Reengineering approach can be used to prepare a blockchain framework that can help in
integrating blockchain capabilities into existing CPS rather than developing a new
blockchain based system, as it could be quite costly and existing systems would be
discarded. Applying Reengineering to redesign the Process of CPS using blockchain is
not a trivial task. Hybrid models are required to redesign inter-organizational transactions
for blockchain based solutions based on smart contracts.

1.1 Objective:

Today’s food supply chain faces problems such as disconnection between its various
stakeholders, lack of transparency in food production and distribution. Complete
traceability of the product to its original source is also not available. Keeping track of
such information can eradicate the limitations of the current supply chain. A blockchain
based transparent network will ensure digital ledger of transactions and movement for all
stakeholders in their supply chain network. Also, the suicide rate of farmers is increasing
at an alarming rate due to high debts and poor yield from farming. Micro finance with
blockchain can help these farmers out of debt and avoid dependency of farmers on bank
loans with high interest.

The goal of the Project work is to study and understand blockchain suitability for
Agri-Food supply chain and design an efficient and cost effective blockchain framework
that can be integrated into existing systems with minimal changes in existing systems. To
achieve this goal following objectives have been considered.

 Feasibility and Cost Analysis of blockchain in selected supply chain use cases.
 To design Traceability and Optimization for supply chain management.
 Design and Implementation of blockchain framework in supply chain
management.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 6
Figure 1.3 Proposed Solution

1.2 Motivation:

Every industrial revolution impacts labor markets with machines replacing human
labor. Hence the introduction of CPS in the supply chain with advanced automation will
replace existing information systems and human resources. Small and Medium Sized
enterprises (SMEs) would be affected financially and socially. SMEs use Cyber
Physical Systems (CPS) that don't have high transaction volumes so a complete
blockchain based system is not going to be a genuine business case for them to invest
in.

Blockchain solutions need to be evaluated in terms of their scalability and cost-


effectiveness to address concerns of business managers. This is a serious challenge
and a big question is what would happen to the existing operational system and
how much time it would take to develop a new blockchain based system. The
motivation of doing this Project is to understand and analyze the Blockchain
technology, and explore its applicability in addressing challenges of existing supply
chain cyber physical systems in a cost effective manner.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 7
CHAPTER 2: Blockchain

2.1 Literature Survey:

Blockchain adoption is gaining huge momentum as industry is evolving at a fast pace.


Many startups have initiated use cases and there is significant rise in investments in
blockchain projects as well. Although blockchain is still evolving in terms of
technological maturity, innovative experimental adoption and customization are
continuously rising. Blockchain has the potential of displacing an established technology
and shakes up the industry or a ground-breaking product that creates a completely new
industry and initial trends with the rise of crypto currencies has signaled that blockchain
has been disruptive for the banking industry and financial services.

Crypto currency has the potential of shaking a centralized banking system by eliminating
the need to pay fees for using credit or debit cards. Recent Trends have shown that
blockchain is turning out to be a sustaining technology rather disruptive and has huge
potential in supply chain , healthcare , Internet of Things (IoT), education and public
services .Commercial viability and acceptability of blockchain are on the rise and 3021
patent families related to blockchain applications are divided into four sub-categories
based on different types of application like Payments and Transaction systems,
Financial services business, Administration and E-commerce.

Extensive use of cryptography and decentralization makes it highly secure. Privacy issues
over public blockchains can be addressed by implementing blockchain in a controlled
manner (permissioned blockchain). Blockchains can be classified as public, private or
hybrid variants, depending on their application.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 8
 Public – No one owns Public blockchains, they are fully decentralized and are
visible by anyone.

 Private – These are also referred to as permissioned blockchains and uses


privilege to control who can read from and write to the blockchain.

 Hybrid – These blockchains are public only to a privileged group. Consensus


process is controlled by privileged servers using a set of rules agreed to by all
parties. The network is partly decentralized and copies of the blockchain are only
distributed among limited participants.

Although a public blockchain distributes itself in a decentralized peer-to-peer


fashion, this isn’t necessarily true for a private blockchain. Private blockchains are
those used by enterprises to record asset transactions within a limited user base
(restricted scope). Hybrid blockchains can be visualized as very small scale public
blockchains; they are decentralized only across a limited participant base.
The blockchain is a distributed ledger with records grouped together in the form of blocks
and are stored along with hash values that are cryptographically verifiable. Now, these
blocks are connected together to form the blockchain that provides a way for information to
be recorded and shared by a community. Each member maintains a copy of the
blockchain and all members must validate any updates collectively [3]. Figure 2.1
represents a simplified blockchain with each block connected to its previous block.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 9
Figure 2.1: A simplified blockchain

Blockchain may record transactions, contracts, information assets or practically


anything that can be stored in digital form. Blockchain records are permanent,
tamper-proof, transparent, and searchable. Each new “block” generated is added to
the end of a "chain."
Initiation, validation, storage, and distribution of each new block is managed by a
protocol. Blockchain replaces the need of third-party intermediaries and participants
of blockchain run complex algorithms to certify the integrity of records in the block.
Blockchain hence is an interesting alternative to how data is stored. Databases have
been the way to store data in databases. Though databases are quite fast and user
friendly, they too have limitations and issues like lack of immutability. Following
table highlights key differences between blockchain and databases.

Table 2.1. Comparison of Databases with Blockchain

Criteria Databases Blockchain


Data Integrity Records and Data items can be changed. Transaction data is immutable, can’t be
changed after the transaction.
Authority Administrator or selected people have No central authority.
authoritative control
Transparency All transactional data is hidden from each other. All transactional data is open for everyone.
Cost Implementation Process is costly. It can help in cutting down excessive costing.
Performance They are comparatively faster. They are slow.
Trust Suitable for organizations having mutual trust. Suitable for organizations where people don’t
trust each other.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 10
2.2 APPLICATIONS OF BLOCKCHAIN

Blockchain with its characteristics is suitable for almost every application that
involves transfer of anything that carries value. Last decade has witnessed substantial
rise in its adoption and various blockchain solution providers that emerged are listed in
table 2.2.

Table 2.2. Leading Blockchain Solutions


Providers

Names Headquarters Founded Services


Ripple Lab San Francisco 2012 Decentralized Financial Tool.
LeewayHertz San Francisco 2007 Building Blockchain Application.
Blockchangers Oslo, Norway 2015 Blockchain Development & Consulting.
Techracers Wilmington, Delaware 2012 Information Technology services.
Chromaway Stockholm, Sweden 2014 Building Smart Contracts and Dapps.
OpenLedgerApS Denmark 2014 Building Blockchain Solutions and Products.
Ezetech New York, USA 2015 Web Development and Tech Consulting.
LimeChain Bulgaria 2017 Blockchain Development and Consulting.
Chain San Francisco USA 2014 Building Cryptographic Ledger.
Intellectsoft Palo Alto, USA 2007 Distributed Ledger and Smart Contract Protocol.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 11
Figure 2.2 Real Life Applications

Adoption of blockchain is not limited to a particular industry and has encouraged huge investments
in almost every sector. Following table lists some ongoing projects using blockchain in various
sectors with exciting business cases.

Table 2.3. Applications of Blockchain in various sectors

SECTOR Name Year Description


Digital ledger for ensuring integrity of transactions involving
DHL 2016
shipping of products.
Block Array is a blockchain platform designed for logistics
BLOCK 2017 operation and helps businesses safely ship goods from point of
ARRAY origin to destination with robust payment, monitoring and
Supply Chain, tracing features.
Logistics
Maersk is working with IBM to better understand supply chain
MAERSK 2018 and for real time tracking of goods digitally across international
borders.

SHIPCHAIN 2017 ShipChain is a blockchain system to cover all operations and


transactions for shipping process.

Banking Santander 2018 Blockchain-based Money Transfer Service Across countries

Healthcare Burstiq 2014 Secure transmission of sensitive data related to patients and
doctors using big data blockchain contracts

Real Estate Propy 2016 Decentralized title registry system and facilitates
cryptocurrency based property purchases.
Circle is a blockchain platform that facilitates money transfer
Circle 2013 and investment services with support to cryptocurrencies, like
Bitcoin, Monero and Zcash.
Fintech, Software monitors and detects fraudulent trading, laundering
Cryptocurrency Chainalysis 2014
and compliance violations, and builds trust in blockchain.

Chain 2014 Chain builds cloud blockchain infrastructures for financial


services and efficiently handle the transfer of cryptocurrencies.

Filament 2012 Filament has blockchain software and microchip hardware to


store all events and transactions.
Internet of
Things, Decentralized credential solutions making IoT devices virtually
Hardware, Hypr 2014
unhackable.
Software
Xage Security 2016 Xage is blockchain-enabled cybersecurity platform for IoT.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 12
Evernym’s Sovrin is an identity ecosystem that offers storage
services for private data, and facilitate secure access for
IT, Software Evernym 2012
verification and validation between the individual and entities
who need private data in real-time.

Cybersecurity, Anti-money laundering compliance platform to catch identity


Ocular 2015
Fintech thieves foraging fake passports, certificates & IDs.
Illinois Distributed blockchain ledger to enhance the security of birth
Blockchain 2017
certificates, death certificates, voter cards, SSN and much more.
Initiative
Voatz is a mobile voting platform using encrypted biometric
Voatz 2016
Government, security system.
Technology Blockchain system to store public documents and private
State Of 2017 records. It also uses smart contracts for transactions between the
Delaware
government and corporations.
Tool for elections ensuring security and transparency in the
Follow My Vote 2015
voting process.
Using decentralized, transparent contracts, artists can agree to
Mediachain 2016
higher royalties and actually get paid in full and on time.
Blockchain system to facilitate direct interaction of video
Eluvio 2019
Content producers to consumers & business partners directly.
MadHive is a blockchain-based advertising and data solution
MADHIVE 2016
for digital marketers.
Media
SteemIt is a social media platform uses tokens as incentives,
STEEMIT 2016
encouraging people to create original content.

This tool allows independent journalism through blockchain


CIVIL 2016
where users can manage their own independent newsrooms.

OPEN MUSIC 2016 Blockchain based protocol to facilitate identification of original


INITIATIVE creators and music rights holders.

India’s government sector has shown proactive approach towards Blockchain by


understanding its potential and already Project and development has been initiated in many
states in India. Andhra Pradesh has been the front runner when it comes to embracing
blockchain in India. Many projects have been initiated in the areas like Cyber security,
Healthcare, Vehicle Title Registration and Land Registry.

Land registry system is perhaps one of major transformations that is required as data entry
operators are involved in collusion practices and that lead to land disputes. With the

`
DEPTT. OF COMPUTER ENGINEERING, GCET 13
implementation of blockchain this risk would be mitigated effectively and it will be
impossible to tamper the land records. Smart contracts have been programmed to issue
notification and alerts in the event of any change in any property record. Property owners
get notified and provision of complaints against fraudulent transactions is also available.

West Bengal and Maharashtra also have initiated blockchain based e governance projects
for use cases related to Land Registry, Organ Transplants, Rationing Distribution, Digital
Certifications and Digital Birth Certificates. Other states like Delhi, Goa, Assam, Gujarat,
Rajasthan, Karnataka, Tamil Nadu, Uttar Pradesh and Kerala have also rolled projects for
implementing blockchain to strengthen e-governance services.

Figure 2.3 Uses in Governance

`
DEPTT. OF COMPUTER ENGINEERING, GCET 14
2.3 ELEMENTS OF BLOCKCHAIN

Blockchain is a system having various components that work together to perform


transactions of business operations. Each element in the blockchain has a specific role to
play as listed below.

● Node: Node is a computing device within a blockchain that can initiate, receive or validate
a transaction. A node operates with the help of a software application that offers various
functionalities related to the business use case. Blockchain typically has two kinds of
nodes i.e., validator nodes and member nodes. Validator nodes have more capabilities
as compared to member nodes as they can initiate, receive and validate a transaction
whereas member nodes can only initiate and receive a transaction.

Figure 2.4 Basic Working of Blockchain

`
DEPTT. OF COMPUTER ENGINEERING, GCET 15
● Transaction — Transaction in a blockchain is a collection of various data items that
carries facts about the exchange of something like product, service, entity, event or
anything that carries value. For example, it could be transfer of ownership, issue of
certificate etc.
● Block — A Block is a data structure that keeps a set of transactions. Every block on
successful verification is distributed to all nodes of the blockchain network. A block
contains various elements as shown in Table 2.4. Block number can be used for unique
identification of blocks in a chain of blocks. Nonce is a random number that helps
generate a hash code with reasonably difficult mathematical computation. Previous
represents the hash code of the previous block and Hash represents hash code of current
block.

Table 2.4. Block structure in a Blockchain

Block #1 #2

Nonce 36584 82549

Rs 65 from Ravi to Mohit Rs 25 from Mohit to Priya

Rs 30 from to Vishal Rs 30 from Sonu to Reena


Pankaj

Transaction Rs 45 from Ravi to Mohit Rs 15 from Kunal to Ravi

Rs 50 from Rohit to Sonu Rs 25 from Ravi to Sonu

Rs 30 from Mohit to Kunal Rs 30 from Pankaj to Kunal

Previous 0000000000000000000000000 0000ab2des234f453f4r5tfe34

Hash 0000ab2des234f453f4r5tfe34 0000rgtf3r4r45t6y6hfrett56y5

● Chain — Chain in a Blockchain is an interconnected sequence of blocks in


chronological order with the latest block in the last with each block having reference
to its previous block to trace back the complete blockchain.
● Miners — a blockchain may have two kinds of nodes Miner nodes (also called Network
nodes) and User Nodes. Miners are the one who have the copy of the blockchain and
they also participate in the block verification process, whereas User nodes can only
initiate a transaction
`
DEPTT. OF COMPUTER ENGINEERING, GCET 16
Consensus— Consensus algorithms are used to assure necessary conformity on a
single state of the network consisting of distributed machines or network nodes in a
blockchain system. The consensus is assessed by comparing the hash codes of all
copies of the chain. This assessment involves mathematical problem solving that
requires a lot of computing power. For this provision of reward is required for people
to contribute resources for maintaining the network. Following are some popular
consensus algorithms:

o Proof of work (PoW) mechanism: In this mechanism all the network nodes
or participants on the network fetch recent transactions as a block. Each
block within the chain must have hash code of the previous block. To select a
network node who will be assigned to process the block, a reasonably
complex mathematical problem is created. The node that solves the given
mathematical problem first is allowed to process the block. For doing
this job, the network node is rewarded that could be transaction fee or
some bitcoin. The complexity of the mathematical problem increases after
every successful transaction i.e. the network node needs to compute larger
hash codes. The complexity of the mathematical problem is also determined
by the number of network nodes in the blockchain network.

o Proof of stake is a mechanism that requires network nodes to invest a native


currency to perform a transaction i.e. users need to possess stake in the
transaction. For example ether is the native currency in Ethereum
blockchain, and a fraction of ether is invested by network nodes for
processing of transactions and achieving consensus.

o Proof of activity this scheme of consensus combines proof of work and


proof of stake mechanisms. A random number of network nodes have to
perform complex mathematical problems and need to digitally sign the block
using a crypto key to make a block official.
o Proof of capacity This scheme is based on the concept of contribution
of storage and computation resources by all network nodes. This requires
network nodes to allocate a portion of their hard drive for block verification,
while proof of storage requires network nodes to reserve a portion of disk
space either in machine or a distributed cloud.

o Ripple (XRP) Ripple follows a different approach and involves social


networks for achieving consensus [63] on the basis of value of network
nodes. This value is computed on the basis of the number of unique nodes
one connects to. This may encourage biasing where newcomers need
social intelligence and reputation to participate. This scheme is more
suitable for permissioned or private blockchain systems.

Figure 2.5 Types of Consensus Algorithms

`
DEPTT. OF COMPUTER ENGINEERING, GCET 18
2.4 HASHING

Hashing is one of the important techniques under modern cryptography. Hashing is the process
of converting data into a message called hash code using a mathematical function referred as Hash
function. Hashing is based on one way encryption and hence is irreversible that means one can't
retrieve data from hash code. The ideal cryptographic hash function has the following main
properties:

● Deterministic: A message will always result in the same hash code.


● Quick: Hash function is fast to compute the hash value.
● Irreversible: It is not possible to generate a message from hash code.
● No collision: It ensures that two different messages should not have the same hash
value.
● Unique: It ensures that a small change to a message extensively changes the hash
value.

Since the introduction of modern cryptography there has been continuous development and
improvement in hashing algorithms to ensure security and protection from attacks on hashed data.
Comparison of various hashing mechanisms is shown in Table 2.5 and SHA256 has been a
popular hashing algorithm widely used for Digital certificates under HTTPs for web applications.

Table 2.5 Comparison of various hashing mechanisms

Algorithm Hash Size Message size Block size Word size No. of steps
MD5 128 <264 512 32 64
64
SHA-1 160 <2 512 32 80
SHA-256 256 <264 512 32 64
128
SHA-384 384 <2 1024 64 80
128
SHA-512 512 <2 1024 64 80

`
DEPTT. OF COMPUTER ENGINEERING, GCET 19
2.5 Public Key Infrastructure
Public Key Infrastructure (PKI) is asymmetric cryptography used for authenticating users and
devices involved in network based communication. PKI is based on the concept of
Key pair that includes reciprocal keys namely Public Key and Private Key. Anyone of these can
be used for encryption and the other one is used for decryption. The key pair is generated by
Certifying Authority and the private key is issued to the user and public key is kept by certifying
authority to validate or verify the identity of the user involved in the transaction.
PKI is the most popular cryptographic technique under modern cryptography and is widely
used for ensuring authenticity of remote servers using digital certificates. Hence users can be aware
of and trust the remote server it is connected to. Since SSL 1.0 to TLS 1.3 there has been a continuous
enhancement in how PKI ensures secure communication in web applications across the internet. PKI
has following applications area,

Authentication: Authentication mechanism involves verification where the identity of a user or


person is proven by possession of a private key and password can be used to protect the private key
managed locally by the user rather than storing it on the server.

Digital signature: Digital signatures enable a user to put their digital identity on digital assets
similar to signing a paper document. This assures that only the owner of the private key could have
signed and also facilitated tampering detection.

Encryption: Encryption induces elements of confusion and diffusion into data to codify it. This can
be used in any scenario where the receiver intends that data to be read by himself only and data can
be encrypted by the sender using the public key of receiver. Here privacy is assured by the security
of the receiver's private key.

In blockchain, the private key of the user is used to sign the message and the public key is used to
validate the identity of the user to achieve authenticity. PKI can significantly enhance security and
immutability in the blockchain system.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 20
CHAPTER 3: Smart Contract

3.1 What are Smart Contracts?

Smart contracts are pieces of program code based on business process logic to process the
transaction based covering compliances and settlement of a contract between involved
stakeholders. The term Smart contract was first presented by Nick Szabo in 1994. Blockchain has
used the concept of smart contract to eliminate the need of intermediaries in the business processes.
The blockchain allows integration of complex rules in the form of smart contracts and transactions
can be validated using multiple signature protocols using digital signatures of involved
stakeholders.

Figure 3.1 Smart Contract

A smart contract is an electronic transaction protocol intended to digitally facilitate, verify, or


enforce the negotiation and execution of the terms of an underlying legal contract designed to fulfil
common contractual conditions comprising payments, legal obligations, and enforcement without
third parties. Thus, by following the traditional perception, smart contracts target to reduce
transaction costs including arbitration and enforcement costs by realising trackable and irreversible
transactions by using blockchain technology for distributed databases. However, the potential of
smart contracts goes far beyond cost reductions by facilitating the entrepreneurial collaboration of
`
DEPTT. OF COMPUTER ENGINEERING, GCET 21
cross-organisational business processes that are characteristic for smart supply chains. A closer
look to existing or ongoing smart contract projects reveals that the majority of smart-contract
applications in business life are linked to supply chain management, Internet of Things and
Industry 4.0 solutions.

3.2
3.2.1 Digital Asset Transfer

Smart contracts can be as well adapted in digital assets transfer. This is highly applicable to the
organization's dealings with customers and suppliers, especially where there is an exchange of
money. Smart contracts can be used to transform the traditional asset transfer to digital transfer.
For instance, in an organization that deals with customer credit cards, such as banks, the amount
spends and account balances in the credit cards, the organization would have an aggregate
database dedicated for the task. Such a database would have a typical table that would have
attributes such as "amount," "owner," and “asset type” among others [14]. In the database, the
table may have entries such as “Sam," “20”. On a different note, another record maybe “Tim,"
"0". Interpretation of the first record would indicate that Sam has a credit balance of $20, while
Tim has a credit balance of “$0. A transaction may be initiated by Sam to transfer the specified
amount to Tim. Suppose Sam transfers $10 to Tim, Sam’s account is debited $10, while Tim's
account is credited with $10.
After the transaction is committed, Sam would have $10, while Tim becomes $10. This is an
example of digital asset transfer since cash is considered to be an asset that can be expressed in
digital form. Logically, though the end users receive the updated account balance instantly, what
happens is the manipulation of the stored records in the database.

Multinational organizations usually interact with thousands of customers on a daily basis. While
some customers are physically served, others are served by automated systems, such as online
carts that are synced with check out systems. Essentially, the sale or purchase of a commodity by
an organization results in a specific form of contract, which may or may not be enforceable under
certain circumstances. Cong explains that a business organization owes the customers and
general stakeholders a duty of care, and therefore must ensure that activities are carried out with
`
DEPTT. OF COMPUTER ENGINEERING, GCET 22
reasonable care to ensure that both the interests of the customers and those of other stakeholders
are protected. Each sale or purchase by the organization can, therefore, be treated as a contract.
In the case of a business organization, the purchase of any service package by the customer or the
purchase of the products by the organization can, as a contract. Such contracts can be digitalized
and executed as digital tokenized assets. Digital transfer of assets between the organization and
its partners can be simplified just as in the example of Sam and Tim bank transfers and be
expressed easily through blockchain technology, that warrants cryptographic verifiability,
validity, and security through the use of the decentralized transactional model. In implementing
smart contracts through blockchain technology, a business organization can approach the latter
through a trust less environment approach.
This would require the implementation of a shared database, whereby each row of the respective
table in the database would represent the details of a specific entity, who may be a supplier or a
customer. However, rather than having the "owner' in the case of the banking example given, the
attribute would contain the public key of the node /user allowed to change the record.

3.2.2 A Scenario for Purchasing a Service Package

A shared database would exist between the company and all other parties in the blockchain
network, typically all the customers. Suppose Customer Y has five units of X [X may represent
credit card balance], the respective record in the database would contain Customer Y’s Public
key in the “owner” column of the respective table, as well as values 5 and X in the quantity and
asset type respectively. Assuming Customer Y knows the public key of Company B, then he/she
should be able to transfer a certain unit of the digital asset to Company B. In this case, Customer
Y would need to initiate a signed transaction using her private key that would reduce the specific
asset type by the specified units in the amount. Using the public key of B, Customer Y is then
able to credit Company B’s amount column with the specific units of the assets reduced.

However, unlike in the relational and object-oriented database systems whereby the manipulation
is done directly to the records, the blockchain technology entails the use of transaction blocks,
whereby the transactions are linked to another. Therefore, after customer Y purchases new
package and transfers the digital asset [money] to Company B, a new record/ row is created with
the updated information and a timestamp, while the old row/ record is deleted. According to
Greenspan, in smart contracts through the use of blockchain technology, rows are not modified;
`
DEPTT. OF COMPUTER ENGINEERING, GCET 23
rather, old records are deleted, and new records with updated information created. The asset
balance of both the Company B and the Customer Y can then be calculated through the
aggregation of the database record that corresponds to their respective public keys and whose
asset type matches the digital asset that as transferred.

Table 3.2.1 setting up smart contracts with partners by organizations.

Phase Description
Agreement This step entails the identification of cooperative opportunities
Identification and specific outcomes by multiple parties. The parties may
entail Company B and its business partners
The scope of the agreement is defined; it may include but not
limited to transfers, the right of use, asset swaps, and business
processes, among others.
Setting conditions The conditions act as the guiding principles for the contract
execution. The smart contract is triggered by the party to the
contracts or anything else defined in the contractual terms that
act as a trigger event. Triggers may be a specific date, GPS
location, a natural disaster occurrence, and specific financial
market indices. Again, temporary conditions such as religious
events, birthdays, and holidays can as well be used to trigger
smart contracts. For instance, in the case of Company B, a
promotion of smart contract to Customer X can be initiated if
the customers' birthday is near, with the contract purporting to
offer a more exclusive deal

Business Logic As already explained, smart contracts through blockchain


technology are scripted pieces of code that have been developed
to and organized in a manner that triggers execution upon the
happening of the trigger event or activity. In this step, a code is
written with the pre-set conditions; more often than not, the
conditional statement such as if, then, else is used to ensure
logical and automated execution of activities
Blockchain technology Encryption is a critical part of the blockchain technology.
Encryption using and Encryption cryptographic techniques is done to warrant the
security of the transactions and also ensure that verification and authentication of the
`
DEPTT. OF COMPUTER ENGINEERING, GCET 24
communication and messages being sent across the network. The program
development and encryption, however, must conform to the underlying blockchain
model that the smart parties' intent to use. For instance, if the parties plan to use the
Ethereum blockchain architecture, then the code must be written in Etherium based
blockchain programming language.

Execution and This entails the commitment of the initial contract transaction
processing and subsequent transaction. Upon verification of the set
conditions by each of the participating nodes in the blockchain
network, the nodes reach a consensus on the validity,
verification, and authenticity; the new smart contract is then
written to the current block. Afterward, the code is executed,
and outcomes are updated on each of the nodes in the network.
These new written instructions act as the base for verification
and controlling transaction processing to ensure validity.
Updating the Network After the execution of the contract. Each of the nodes is
updated on the new state. Essentially, once a transaction or a
new record and subsequently executed, no alteration can be
done; the only thing that can be done is appending and creating
a new record. This is one of the disadvantages mentioned earlier
on.

3.3 Benefits and Applications of Smart Contracts

3.3.1Accuracy

One of the advantages that business organizations would benefit from the implementation of
smart contracts is accuracy. As explained in the processes of setting up a smart contract, all the
information regarding the contract is expressed in a conditional format, using the if-then
statements. For instance, when ordering a specific service package if customer x pays x units of
y, then immediately credit the recipient of the amount and also open the service package for
customer x. Since the majority of the contracts entail the exchange of cash. Then the smart
contracts can be synced with cryptocurrencies such as Ethereum, Lite Coin or bitcoin, among
others, an aspect that would further enhance the robustness, accuracy, and performance of the
`
DEPTT. OF COMPUTER ENGINEERING, GCET 25
entire system. The expression of all terms and conditions in a smart contract must be explicitly
and accurate. Essentially, this is a critical requirement because transaction errors may emanate
from any omission. Therefore, the automation exhibit in the smart contracts avoid the majority
of the issues that are found in the traditional contracts.

Figure 3.3 Benefits of Smart Contracts

3.3.2 Clear Communication and Transparency

Virtually, the terms and conditions of the contract terms and conditions become explicitly visible
to the different network players of the specific blockchain. Therefore, once the contract is
established, changes cannot be easily implemented. Each of the transaction by either party to the
contract is monitored and controlled by other network nodes in the blockchain. As a result,
transparency is promoted, and issues of fraud are eliminated. In the modern era, various cases
have been reported whereby the organizational is accused of defrauding the customers and not
offering them the value of their money.

3.3.3 Speed and Efficiency


Essentially, smart contracts do not rely on human intervention, and their implementation is
guided and overseen by other nodes in the blockchain network. Therefore, once the contract is
triggered, the scripted contract self-executes. This is often achieved through the use of trigger

`
DEPTT. OF COMPUTER ENGINEERING, GCET 26
events when scripting the contact. For instance, a trigger event may be a date, time, or even an
activity initiated by a party to the contract, such as the transfer of certain units of cryptocurrency
from the customer’s wallet to that of the company. Once a trigger event happens, the contract
now starts executing itself. For instance, for online subscription-based organizations, once a
specific unit of the cryptocurrency is received, then the subscription for the customer is auto-
renewed.
Unlike in the traditional contracts that are less efficient and which require some form of human
verification, here, the verification of whether the correct amount has been paid, and whether the
correct subsection, service, and associated aspects have been given to the number is determined
by the nodes in the blockchain network. As such, there is no longer reliance on the organization's
developed system to determine the contracts with the customers. The organization also has no
sovereign authority over the transactions as well as over the contractual agreement with the
partners. Each contract is targeted as a separate entity, and each transaction, irrespective of its
origin is first validated. Overly, this results in a fast, resilient and robust way of contract
execution.

3.3.4 Security
The smart contracts have one of the highest security measures. Smart contracts implemented
through block chin technology entail the use decentralized network made of non-trusting parties.
The fact that the parties in the network are non- trusting makes them keep check of one another
to ensure each transaction is carried out effectively, and that there is a uniform worldview of the
status of all the transactions. Again, blockchain technology is implemented through cryptography
techniques. This technology entails high encryption of data and the use of both private and public
keys for reading the transactions in each blockchain, as well as executing any transaction. The
fact that before any node commits a transaction, the transaction must first be validated by all the
odes across the blockchain network enhances the security of the smart technology.
The data encryption and specifically, the use of cryptography techniques can greatly enhance the
security of communication and data exchange. As such, any contract that is implemented in an
encrypted manner enhances the security of the transaction and thwarts any malicious activities
that may be propagated to alter the execution sequence or execute invalid transactions.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 27
3.3.5. Cost Reduction
Essentially, top business managers are credited with the responsibility of coming up with
strategies and ways of reducing costs in an organization. The main aim of setting up a business
enterprise is to make profits; therefore, all the activities in an organization must be construed in a
manner that promotes the achievement of corporate objectives, as well as maximizing the wealth
of the shareholders. In the recent wold that has seen a vast technological revolution, the success
of the business enterprises is vested in their ability to keep tabs with the prevailing technologies
and adopt ensures and techniques that otherwise increase the employees' productivity and
performance.
The implementation of smart contracts through blockchain technology cuts the need for a
middleman, such as the legal personnel. This, in turn, aids in reducing the overall organizational
costs and maximizing the profit margins by an organization. In the case of multinational
corporations that deal with a huge number of contracts on a daily or weekly basis, the
implementation of smart contacts with its business partners and customers can greatly aid in
reducing the various costs incurred in the traditional forms of contracts. The contracts can further
bolster the efficiency of the organization, which is a critical ingredient for organizational success
and increased performance. It is, however, critical to note that despite the security, cost reduction
and efficiency aspects associated with the smart contracts, the latter is not by any chance
magical, and hence may be subject to flaws. For instance, the quality and execution of the
contract highly depend on the input, which is basically the coded version of the contract.
Therefore, if there are flaws in setting up the smart contracts, such flaws may trigger adverse
effects as well as poor quality of the output generated.

3.4 Limitations of Smart Contracts

Despite the various advantages noted and which emanate from the implementation of smart
contracts, it is also crucial to note that smart contracts are associated with various limitations, the
disadvantages of the smart contacts limit their application in various real-life scenarios. More
often than not, technology often outpaces the law and the regulatory framework. This has been a
noticeable trend with respect to smart contracts.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 28
3.4.1. Immutability
Essentially, since smart contracts are scripted as a piece of codes, once set up, the contacts
cannot be modified easily. In the traditional contracts, amendment of terms and conditions is
often used, especially in long-term contracts whose execution is depending on real-life dynamics,
and the conditions keep changing. Owing to the rigidity exhibited in the smart contracts after
being established, the latter results in a wide array of practical problems more so with respect to
the ease of modifying the contract terms in depending on various situations.
The implementation of smart contracts. To a greater extent, makes it literally impossible to
achieve analogous goals. Nevertheless, various actions can be taken in order to include aspects of
modification and contract annulment. For instance, an escape hatch can be included in the coded
contract. The escape hatch can be used to allow for the modification of the contract terms, in
order to cater for the real-life contracts which are characterized by vast dynamics. Nevertheless,
implementing such in the smart agreements may compromise the security apparatus, and hence
may require further tightening of the transaction controls in order to ensure that the escape hatch
is not used to initiate invalid transaction or transactions that are aimed at unauthorised
manipulation of records

3.4.2. Contractual Secrecy


Mostly, the blockchain technology entails the sharing of smart contract across all the nodes in the
blockchain network, since all the transaction is recorded on general ledger using encoded
permissions in each of the nodes. Essentially, the blockchain technology entails the use of
anonymity, whereby all the participants in a blockchain network are anonymous and secured.
However, there is no security of the contract execution. This is because though the nodes are
anonymous in their operations, the ledger is maintained public, and hence, the transactions are
visible, and there is no security of such
While the essence of the smart contracts is to maintain a public ledger that is visible to all parties
in the network and to monitor the validity and accuracy of the taxations, there is the need also to
develop a protocol, which can aid in the verification of the transactions without necessarily
reading the contents of the transaction. This is because though the participants and the origin of
the transaction may be anonymous, the contents are not; and actually, each node can read and
access the transaction contents. It is as well critical to developing measures to curb this privacy

`
DEPTT. OF COMPUTER ENGINEERING, GCET 29
issues since security is not all about anonymity and encryption, it also entails ensuring the
content of the transaction is protected against access by other parties. As such, this aspect of
smart contracts is yet to be fully addressed.

3.4.3. Legal Adjudications and Enforceability


Traditionally, the establishment of a valid contract covers various constructs, which make it
legally enforceable.
For instance, the financial sector exhibits immense regulations by the government, and specific
permissions and licensures are required for a form to engage in transactions execute don general
ledgers. However, despite the licensure and associated approvals, the legal enforceability of the
smart contracts is yet to be established and synced with the contract law as well as other laws
that give financial transactions. All elements of aspect contracts are expressed as segments of
code, and the aforementioned elements of a valid contract may not necessarily be identifiable.
This, therefore, necessitates the need for the translation of the legal framework governing the
contracts into the software logic to ensure that besides the smart contract being self-executing,
they also adhere to the legal regulations of formal contracts. Further, such tantalization should
take in to account the blockchain developer's point of view, the lower's point of view and the
transacting parties' points of view. Such an aspect would aid in enforcing the legality and validity
of the contracts.. Nevertheless, the upside of the smart contracts is that breaches of contracts are
rare to occur, as the execution of the contract is dependent on the pre-defined conditions which
are also triggered by an event that neither of the nodes in the network has control over.

Figure 3.4 Disadvantages of Smart Contracts.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 30
CHAPTER 4: USE CASE SELECTION AND DESIGN PROCESS

4.1 USE CASE SELECTION


Blockchain use case selection involves many decisions based on following criteria and NITI
Ayog has published a blockchain use case selection framework as shown in Figure 2.2 that
covers all these.
● Is there a compelling business case to reduce intermediaries?
● Are Multiple Stakeholders Involved?
● Are we working with digital assets instead of physical Assets?
● Do multiple parties require shared write access?
● Do we require high performance and rapid transactions?
● Do we intend to store non-transactional data as part of your solution?
● Do we need to rely on trusted parties for compliance reasons?
● Do we have a robust Token-omics Model?
● Do we need the ability to control functionality?
● Should transactions be public?

Figure 4.1. Framework for blockchain use case evaluation


`
DEPTT. OF COMPUTER ENGINEERING, GCET 31
The framework presents following four possible outcomes based on criteria,
● Do not use blockchain
● Blockchain can’t do this effectively yet solutions are in development
● Strong case for public blockchain
● Strong case for private blockchain

4.2 Design of Blockchain

Blockchain-based systems are developed in a step by step process and Figure 4.2 represents a
systematic design process for blockchain application. The whole procedure requires a clear
understanding of business processes and compliance requirements of the use case to facilitate
decision making.

The procedure starts with a question on whether to decentralize trust (authority) – or not. A
blockchain is more suitable where no single trusted authority is mandatory and the reliable
authority can be distributed or partially distributed. If the trust authority can be distributed then
rules and specifications regarding trust authority needs to be identified. Otherwise blockchain is
not applicable and systems can be built using traditional databases. Given the restrictions of
blockchains, critical concern is configuration of computation and data storage between on-chain
and off-chain components. It all depends on business requirements and volume of transactions
for a use case to decide about storage and computation infrastructure required for blockchain
application. A thorough assessment of workload and capacity requirements needs to be done.
Capacity planning is required to estimate storage and computation for a use case.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 32
Figure 4.2: Design Process for Blockchain System

`
DEPTT. OF COMPUTER ENGINEERING, GCET 33
CHAPTER 5: Blockchain in Supply Chain

Blockchain adoption is gaining huge momentum as industry is evolving at a fast pace. Many
startups have initiated use cases and there is significant rise in investments in blockchain projects
as well specially across diverse sectors such as supply chain and financial industry has been the
prime sector for blockchain adoption. There are many use cases that can apply Blockchain
technology for making processes more efficient and effective.

With the rise in digitization and process automation organizations need to maintain a competitive
advantage by adopting technological enhancements across their process that decrease
Turnaround time to address speed to market and the ability to rapidly navigate changing business
environments.

Supply chains have huge scope for blockchain adoption and involve complex operations and
transactions having product variety, global sourcing of components with strong emphasis on
efficiency and effectiveness.

Supply chains systems involve interaction of multiple stakeholders and participants across
various business processes like manufacturing, freight and logistics, financial, sales and
distribution. These systems may involve interaction with government entities and several third-
party service providers. There is a requirement of a robust system to ensure quick and effective
coordination with multiple stakeholders like freight forwarder, customs broker, banks and so on).
Supply chains can be significantly transformed by using smart contracts to facilitate trust with
the blockchain system and to ensure operations with minimal human intervention.

Supply chain management is to integrate all the supply chain operations that span all movement
and storage of raw materials, work-in-process inventory and finished goods from the point-of-
origin to the point-of-consumption. The critical challenge is to find the best supply chain
configuration such that operations can be performed in an efficient and responsive way.

Supply chains cover complex interactions of various stakeholders and complexity of operations
increase with time. There are many factors that contribute to the complexity of supply chain
systems as listed below
`
DEPTT. OF COMPUTER ENGINEERING, GCET 34
● Continuous innovation in product development and service delivery
processes.

● Regular change in regulatory and compliance requirements.

● Continuous expansion and geographically spread supplier and customer


networks.

● Process outsourcing, risk management practices and security


considerations.

● Rise of e-business and technological transformations to increase the speed


of change in supplier networks and customer expectations.

● Expected increase in the number of participants within the supply chains.

As supply chains become more complex, this leads to firm’s exposure to greater volume of data.
This leads to data management challenges to ensure data visibility and transparency for existing
and newly added operations in supply chains. There is risk of reduction of data accuracy as
information is obtained from multiple diverse sources.

Subsequently, keeping both visibility and value of data in spite of involvement of diverse
stakeholders is imperative for sustained efficiency and responsiveness in supply chain systems.
As supply chain management covers internal and external participants, appropriate and precise
information transfer is mandatory to achieve improved performance in supply chain systems.

Supply chain involves moving a product from a supplier to the customer that requires effective
coordination between human and mechanical inputs. Supply chains need to improve end-to-end
visibility, product tracking, fraud, regulatory compliance, delivery speed, and settlements.

A smart contract can be used to automate business rules related to transaction processing in the
supply chain. A Smart contract can encompass any set of rules, logics, decision criteria specified
in its programming language for example, a contract can process fund transfer when specific
events occur (e.g. payment of security amount in an escrow system). Therefore, smart contracts
can be implemented in a wide variety of applications, including financial processes (e.g., sub-
`
DEPTT. OF COMPUTER ENGINEERING, GCET 35
currencies, financial derivatives, savings wallets, wills) and self-enforcing or self-directed
governance applications (e.g., outsourced computation.

A smart contract is recognized by an address and its source code is stored on the blockchain.
Users invoke a smart contract by posting transactions to the contract address. Specifically, if a
new transaction is recognized by the blockchain directed towards smart contract address, then all
participants on the mining network execute the contract source code with the current state of the
blockchain and the transaction payloads as inputs.

The network then agrees on the output and the next state of the contract by participating in a
consensus protocol. Ethereum is a popular blockchain with a built-in full-fledged Turing-
complete programming language that can be used to create "contracts" that can be used to encode
arbitrary state transition functions, allowing users to create any of the systems described above,
as well as many others that we have not yet imagined, simply by writing up the logic in a few
lines of code.

Figure 5.1 Blockchain in Supply Chain

`
DEPTT. OF COMPUTER ENGINEERING, GCET 36
Though blockchain brings exciting benefits, every use case must customize blockchain systems
for their specific needs to achieve expected results. Extensive Project is required to understand
business requirements of a use case along with cost benefit analysis to build a genuine business
case. Thus, substantial exploration opportunities exist to contribute to this evolving technology,
considering its features and ability to strengthen supply chain processes. Blockchain can
certainly address supply chain challenges through its features as listed below.

● Auditability: The Auditability feature of blockchain can provide a full audit trail of data
throughout the supply chain that allows event monitoring to ensure traceability in the supply
chain.

● Immutability: Immutability features of blockchain can provide Single time stamped tamper-
proof source of data that helps in preserving evidence of Regulatory Conditions compliance to
ensure Compliance in a supply chain.

● Smart Contract: Smart contract feature of blockchain provides Real-time rule based
verification of multiparty confirmations that facilitates Cost effective adaptation to business
environment changes to ensure flexibility in the supply chain.

● Distributed: Blockchain allows direct interaction with a trusted digital signature based peer to
peer interactions that ensure risk reduction and trust building in the supply chain ensuring
stakeholder management.

5.2 Blockchain in agriculture and food supply chain

Cleaner supply chain management refers to activities across all stages of the supply chain that
significantly impact social well-being and the environment. Due to increased awareness, people are
more concerned about food safety and demands sustainable compliances. Blockchain adoption has
become a high priority to ensure such activities are in real practice. Supply chains are extensive
storage places to store larger data in cleaner mode. With a cleaner supply chain through blockchain,
the storing places are interconnected.

Organised data is necessary for an efficient and clean supply chain, which becomes harder if the data
is disorganised. Blockchain is the solution as it is decentralised in nature. With the help of
blockchain, information can easily be shared in a faster mode. It helps to remove inessential
establishments from the supply chain. It improves the data journey by providing the customer with
an opportunity for an enhanced experience. However, blockchain adoption is still. There is a need to
`
DEPTT. OF COMPUTER ENGINEERING, GCET 37
investigate the blockchain adoption benefits and solutions in agricultural supply chains. Identifying
these benefits and solutions would facilitate the adoption rate of blockchain, particularly in Pakistan
agricultural supply chains.

The domains of agriculture and the food supply chain are two significant and highly relevant
domains. These two domains are interlinked as in distributed supply chains. The agriculture products
are utilised as inputs, where consumers are often the ultimate clients. It is evident that immediately
after the emergence of blockchain technology, it began to be used in supply chain management.
Reuters repored that in supply chain management, the use of blockchain would nurture 87% of
yearly growth, increasing from $45 M in 2018 to $3314.6 M in 2023. As a popular example, the
company AgriDigital in December 2016, implemented the first-ever payment on a blockchain for the
grain sale. A cloud-based system is used to accomplish over 1300 users, in addition to the grain of
1.6 Mt. It includes $360 M in cultivator payments. The triumph of AgriDigital aided as motivation
for the prospective consumption of blockchain in the supply chain for agricultural products. The
company is presently targeting to construct reliable and effective supply chains through blockchain.
Louis Dreyfus Co (LDC), is another recent example, who is the principal foodstuffs trader,
collaborated with banks of France and Netherlands through blockchain for the foremost agriculture
product trade (such as a shipment of soybeans. Fig. 5.2 shows the use of blockchain for the
digitisation of the food supply chain. As shown in the figure, there are three layers: the top layer
(showing the physical flow), the middle layer (showing the digital flow), and the bottom layer
(showing the blockchain layer).

Fig. 5.2 Food supply chain system

Under the top layer, a digital flow layer consists of numerous digital technologies. The connecting
infrastructure is Internet/Web servers. Each accomplished action, sanctioned with the help of the
above-mentioned digital technologies, is logged to the bottom layer. This process supports
unchallengeable ways to stock information, acknowledged by all contributors. The information
`
DEPTT. OF COMPUTER ENGINEERING, GCET 38
captured during each transaction is validated by business companions, forming consent among all
accomplices. Once the blocks are validated, they are added to the transaction chain at the individual
level, becoming an eternal process record. As shown in Fig. 5.2, diverse information is transcribed to

Blockchain technology innovation has apprehended the imagination and provided both academics
and practitioners with challenges and opportunities. RFID can be used in blockchain for food
security and therefore develop an agricultural supply chain traceability system using blockchain and
the Internet of Things. The concept of land registration in the Indian sense was explored in Thakur et
al. (2020). The authors agree that such a system is genuine, manipulative, and gives absolute
property rights. They addressed numerous challenges in implementing blockchain-based
mechanisms, including high initial investment, confusion about regularity, and security concerns.

Even though blockchain has advanced considerably in recent years, there is a big gap regarding
conceptual considerations of the benefits and solutions offered by blockchain technology for
agricultural supply chains. The review of blockchain showed an interesting increase in the number of
published papers, mainly in 2018 and 2019. However, studies contemplating the interplay of
blockchain and agricultural supply chains remain at their developing stages. Based on the literature,
blockchain has lots of potential to bring reformation in agricultural supply chains.

5.3 Walmart – Food Traceability using Blockchain

In August 2017 – Walmart announced a Blockchain partnership with big names in the supply chain
industry such as Dole, Kroger, McCormick, Nestlé, Tyson Foods, and Unilever to collaborate and
find new applications that could help increase food traceability.

By September 2018, it was possible for the company to trace over 25 products from as many as
five different suppliers- including mangoes, leafy greens, strawberries, dairy products, meat and
poultry, packaged salads, and even baby food. The system was so efficient that one could take a
jar of a product or a salad box and trace the ingredients back to the farms from where they were
harvested.

In the same year, the retail giant announced: “a new, Blockchain-enabled Walmart Food
Traceability Initiative to increase transparency in the food system and create shared value for the
entire leafy green farm to table continuum.”

As a part of the initiative, all fresh leafy greens suppliers were expected to trace their products
back to the farms within seconds as opposed to days. To do so, the suppliers were required to
capture the data using the IBM Food Trust network using GS1 standard communication protocols
like EPCIS. The traceability data that needed capturing and sent to the Blockchain included -
`
DEPTT. OF COMPUTER ENGINEERING, GCET 39
product ID (GTIN-14), lot/batch codes, purchase orders, and date/time codes (harvesting,
processing, shipping, and receiving).

Figure 5.3 Walmart

By 2019, Walmart was already a pioneer in the food safety business.

One of the most significant piece of news arrived that year from the Walmart China Blockchain
Traceability Platform It introduced the first batch of 23 product lines tested and launched on the
platform, enabled by VeChain’s Blockchain technology.

The same year, the company piloted a Blockchain technology for the end-to-end traceability of
shrimp sourced in Andhra Pradesh, India, and shipped to select Sam's Club locations in the USA.
This was the first-ever known use of Blockchain supply chain technology to track shrimp exports
from farms to overseas retailers.

Figure 5.4 Walmart Food Traceability

`
DEPTT. OF COMPUTER ENGINEERING, GCET 40
CHAPTER 6: PROJECT METHODOLOGY

In the traditional supply chain models, the information about an entity is not fully transparent to
others, which leads to inaccurate reports and a lack of interoperability. Emails and printed
documents provide certain information, but still can’t contain fully detailed visibility and
traceability information since the products across the entire supply chain are hard to trace. It is
almost impossible for the consumer to know the true value of the product they purchased. Since
the blockchain is a transparent, immutable, and secure decentralized system, it is considered to
be a game-changing solution for traditional supply chain industries. It can help to build an
effective supply chain system by improving the following areas:

* Tracking the products in the entire chain

* Verifying and authenticating the products in the chain

* Sharing the entire chain information between supply chain actors

* Providing better auditability

Figure 6.1 Supply Chain Process


`
DEPTT. OF COMPUTER ENGINEERING, GCET 41
6.1 Architecture

Figure 6.2 System Architecture

● Our system enables companies to quickly track unsafe products back to their source and see
where else they have been distributed. This can prevent illness and save lives, as well as
reducing the cost of product recalls.

● Details of the quality reports (pushed to a blockchain network) cannot be tampered by any of
the stakeholders for their own benefit.

● The produce history can be traced right from the origin to the present situation in real time.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 42
● The consumers could get quality products at cheaper rates as they are funding the crops/fields
right from the time of cultivation.

● No need to have huge farmlands. Even the small scale farmers and household farmers can also
sell their products and yield better profit.

● Even the low income group consumers can fund the crops based on their needs and can escape
from the market fluctuations of the product prices.

6.2 Network Design

Farmer Processor Quality Logistics Retailer Customer


Check
Figure 6.3 Network Design

The agricultural food supply chain completes the entire production and transportation process "from
farm to fork", involving many participating entities, and forming long and complex characteristics that
make tracking the entire process very cumbersome. Therefore, for traceability purposes, we record the
information and add the unique identity and lot number of the food to each subsequent transaction
when the transaction is initiated, and record the hash value to ensure the authenticity of the transaction.
A batch is a group of foods in a warehouse whose batch number is the unique identifier. To address
the blockchain data explosion and SERVER limitations, the hash of the data is stored in the Ethereum,
and the transaction data is stored in the SERVER. Access control policy is adopted to restrict
blockchain reads and writes, ensuring that transactions are executed by authorized users and enhancing
data security. Similarly, smart contracts allow only specific entities to execute. Entities are registered
in the system and interact through the smart contracts. The processing of the entity in the agricultural
food supply chain is shown in Fig. 3, and the description of each entity is as follows:

`
DEPTT. OF COMPUTER ENGINEERING, GCET 43
Organization: The agriculture bureau is an organization that manages farmers, keeping records of
farmers’ information, seed information, plot information and yield information to ensure the
authenticity of source information. The information is stored in the SERVER, and its hash value is
stored on the chain.

Farmer: The farmer is responsible for planting crops, using sensors to monitor and record details
of crop growth, such as water, air, sunlight and soil quality in the growing environment, and storing
the information regarding the process of crop growth in SERVER in the form of images or MPEG
files. In addition, the farmer is responsible for creating smart contracts and storing SERVER data
hashes in smart contracts.

Processor: The farmer harvests crops and sells them to the processor, who processes the raw crops
into produce purchased by the final consumer, and stores the batch information, quantity, and
inspection information of the finished products in SERVER. The data hash is stored in the
blockchain, and the data label is finally generated and pasted on the product packaging.

Quality supervision: The quality supervision bureau mainly manages the processing and guides the
quality supervision and inspection, and is responsible for the implementation of product quality
supervision and compulsory inspection of the production enterprises. To investigate and punish
violations of laws and regulations concerning standardization, measurement and quality, and
crackdown on illegal activities related to counterfeiting and shoddy goods, its information is
recorded on the SERVER, and the hash value is stored on the blockchain.

Retailer: The retailer buys processed produce from the Processor and sells it in small quantities to
consumers. Basic information of the retailer, time of selling, quantity sold and other information is
recorded in SERVER, and the hash value is also recorded in the blockchain.

Customer: Consumers are the users who purchase and consume the final agricultural food, and can
obtain the complete supply chain information of the agricultural food according to the barcode,
RFID or QR code on the product package to realize the traceability function of the agricultural food
according to the barcode, RFID or QR code on the product package to realize the traceability
function of agricultural food information.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 44
6.3 Smart Contract System

Figure 6.4 Entity Relationship Diagram

The relationships between entities, as shown in Fig. 6.4, show some of the key properties and
capabilities of the smart contracts, as well as the relationships between entities and smart contracts.
Each participating entity in the agricultural food supply chain participates by calling a function in the
smart contracts. The smart contracts are created by the farmer, who grows the crop and uploads the
growing environment, details and images to the SERVER by calling updateGrowthInfo(), which is
stored in the SERVER hash, and updates the updateGrowthInfo() until the crop is ready for harvest.
When the crops are harvested, the trade begins between the farmer and the processor. Once the farmer
and the processor have negotiated the details of the agreement, the farmer agrees and sells the crop to
the processor.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 45
Figure 6.5 Sequence Diagram Showing interaction between Farmers, Smart Contracts and
Processors

Fig. 6.5 shows the sequence diagram of the farmer and processor executing the sellToProcessor() and
buyCropFromFarmer() functions, respectively. First, the processor executing the
buyCropFromFarmer() function, passing processor address, quantity and sales date parameters to
activate the smart contract trigger the CropRequested() event to notify the participants, and passing
and recording these parameters. Then, the farmer executing the sellToProcessor() function, passing
the farmer address, processor address, quantity and sales date parameters, the smart contract trigger
the CropSold() event to notify closing the transaction, and passing and recording these parameters.

Figure. 6.6 shows a sequence diagram of the processor and Processor collaboration using smart
contracts. The Processor is a warehouse that buys processed produce in bulk from various processors
and sells it to retailers. Firstly, the Processor trigger AgriFoodRequestedByProcessor() event, passing
Processor address, processor address, quantity and sales date parameters to notifies the processor
selling agricultural food to it, then the farmer performs the sellAgriFoodToProcessor() function,
passing processor address, Processor address, sales quantity and sales date parameters to activate
`
DEPTT. OF COMPUTER ENGINEERING, GCET 46
Processor Smart Contract Distributor

buyAgriFoodFromProcessor()

AgriFoodRequestedByDistributor()

sellAgriFoodToDistributor()

AgriFoodSoldToDistributor()

Functions
Events

Figure 6.6 Sequence diagram showing interactions among processors, smart contracts, and
Processors.

the AgriFoodSoldToProcessor() event to notify interaction entities. Retailers buy agricultural food
from Processors, executing the buyAgriFoodFromProcessor() function, and passing retailer address,
Processor address, quantity parameters. The activation AgriFoodRequestedByRetailer() event
notifies the Processor, the Processor then performs the sellAgriFoodToRetailer() function to sell
agricultural food to the retailer, and activated event AgriFoodSoldToRetailer() notifies the relevant
participant of this process. At the same time, passing the addresses of both parties, quantity, batch
number and sales date parameters. Finally, the retailer sells the agricultural food to the customer by
executing the sellAgriFoodToCustomer() function, passing retailer address, customer address, agri-
food name and sales date parameters, and broadcasts the process for the agricultural food via the
AgriFoodSold() event.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 47
Fig. 6.7 shows a sequence diagram of Processor, retailer and customer.

6.4 Algorithms

As mentioned above, the smart contracts are created by the farmer. In the initial state of establishing
the smart contracts, the smart contracts will check whether the farmer is registered. The processor then
issues a purchase request, at which time the contract status is buyCropFromFarmer, and two conditions
need to be checked:

(1) Whether the requested processor is a registered entity;

(2) Whether the processor has paid the fee.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 48
If these two conditions are satisfied, the contract status changes to CropRequestAgreed, the processor
status is now WaitForCropFromFarmer, the farmer status changes to SellCropToProcessor and all
active entities receive information from the farmer about selling crops to the processor. If the above
two conditions are not met, the contract state becomes CropRequestFailed, the processor state is
RequestFailed, and the farmer state is CancelRequestOfProcessor. Algorithm 1 describes the process
by which farmers sell their crops to processors.

Algorithm 1 Farmer Sell Crops To Processor

Input: s the list of registered Processors

Address of Processor,

Address of Farmer,

Quantity,DatePurchased,CropPrice

1 Contractstate is buyCropFromFarmer

2 State of the processor is CropRequested

3 Farmer state is WaitForSellCropToProcessor

4 Restrict access to only rp ę Processor

5 if CropSale is agreed and CropPrice = paid then

6 Contract state changes to CropRequestAgreed

7 Change State of the processor to

WaitForCropFromFarmer

8 Farmer state is SellCropToProcessor

9 Send a notification of crop sale to processor

10 end

11 else

12 Contract state changes to CropRequestFailed

13 State of processor is RequestFailed


`
DEPTT. OF COMPUTER ENGINEERING, GCET 49
14 Farmer state is CancelRequestOfProcessor

15 Send a notification stating request failure

16 end

17 else

18 Reset contract and displays an error message.

19 end

Algorithm 2 Processor Sell Agri-Food To Retailer

Input: r the list of registered Retailer

Address of Processor,

Address of Retailer,

DateManufactured, Quantity,

DatePurchase

1 Contractstate is AgriFoodSoldToProcessor

2Retailer state is ReadyToPurchase

3 Restrict access to only Retailer

4 if Sale is agreed and Price = paid then

5 Contract state changes to SaleRequestedSuccess

6 Change State of the Processor to AgriFoodSoldToRetailer

7 Retailer state is AgriFoodDeliveredSuccess

8 Send a þsuccessÿnotification to retailer .

9 end

10 else

11 Contract state changes to SaleRequestDenied

`
DEPTT. OF COMPUTER ENGINEERING, GCET 50
12 State of distributor is RequestFailed

13 Retailer state is AgriFoodDeliveryFailure

14 Send a þfailureÿnotification to all participants.

15 end

16 else

17 Reset contract and displays an error message.

18 end

The processor then sells the processed crop to a Processor, who in turn sells it to retailer, as shown in
algorithm 2. At this point, the production date, sales quantity and purchase date of the agricultural food
are important parameters of the current stage. First, with respect to recognition address and the states
of the Processor and retailer, due to the distributor having just finished the trade with the processor,
the smart contract status is AgriFoodSoldToDistributor, and the state of the distributor is
AgriFoodReceivedFromProcessor. The status of the retailer is ReadyToPurchase, which must satisfy
two conditions: (1) Whether the requested retailer is a registered entity; (2) Whether to agree to the
sales agreement and whether the agricultural food payment has been completed. If these two
conditions are satisfied, the contract will automatically execute the transaction with the contract status
changed to SaleRequestedSuccess, distributor status changed to AgriFoodSoldToRetailer, and retailer
status changed to AgriFoodDeliveredSuccess. Upon completion of the transaction, the deed will send
a notification of successful delivery to the retailer. If the above two conditions are not satisfied, the
contract status is changed to SaleRequestDenied, the distributor status is changed to RequestFailed,
the retailer status is changed to AgriFoodDeliveryFailure, and the contract sends a notification of
failure to all participants.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 51
Algorithm 3: Customer Buys From Retailer

Input: Address of Retailer,

Address of Customer,

SalesID, AgriFoodID,

DatePurchased

1 Contractstate is SaleRequestAgreedSuccess

2 State of the retailer is AgriFoodDeliveredSuccess

3 Customer state is ReadyToBuy

4 Restrict access to only Customers

5 if Price = paid then

6 Contract state changes to AgriFoodSoldToCustomer

7 Change State of the retailer to

SuccessfulPurchaseAgriFoodSaleSuccess

8 Customer state is SuccessfulPruchase

9 Send a purchase success notification.

10 end

11 else

12 Contract state changes to SaleOfAgriFoodDenied

13 State of retailer is AgriFoodSaleFailure

14 Customer state is FailedPurchase

15 Send a purchase failurenotification.

16 end

17 else

18 Reset contract and displays an error message.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 52
19 end

Algorithm 3 describes the algorithm for consumers to purchase agricultural food from retailers.
First, the consumer’s initial state is ReadyToBuy. Thanks to the successful dealings between
retailers and distributors, the smart contract state is SaleRequestAgreedSuccess, while retailer
status is AgriFoodDeliveredSuccess. Similarly, smart contracts restrict customers who register
with retailer to make purchase requests. The important parameters at this stage are customer
address, retailer address, purchase date, sales ID, and AgriFood ID. When consumers successfully
pay agricultural food prices, contract status changes to AgriFoodSoldToCustomer, retailer status
to SuccessfulPurchaseAgriFoodSaleSuccess, and customer status to SuccessfulPurchase. If the
payment is not successful or the paid price is incorrect, the contract status will be changed to
SaleOfAgriFoodDenied, the retailer status will be AgriFoodSaleFailure, and then the customer
status will be changed to FailedPurchase.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 53
CHAPTER 7: IMPLEMENTATION

7.1 SOFTWARE REQUIREMENTS

 Operating system : Windows/ MacOS/ Linux


 Coding Language : Solidity, Python,
 Tool : Anaconda Navigator
 Database : SQL
 Ganahce : Ethereum Blockchain
 Remix IDE : Deploying Smart Contracts

7.2 SOFTWARE TOOLS USED

7.2.1 ABOUT PYTHON:

Dating from 1991, Python is a relatively new programming language. From the start, Python
was considered a gap-filler, a way to write scripts that “automate the boring stuff” (as one
popular book on learning Python put it) or to rapidly prototype applications that will be
implemented in one or more other languages.
However, over the past few years, Python has emerged as a first-class citizen in modern
software development, infrastructure management, and data analysis. It is no longer a back-
room utility language, but a major force in web application development and systems
management and a key driver behind the explosion in big data analytics and machine
Perfect for IT, Python simplifies many kinds of work, from system automation to working in
cutting-edge fields like machine learning.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 54
Python is easy to learn. The number of features in the language itself is modest, requiring
relatively little investment of time or effort to produce one’s first programs. Python syntax is
designed to be readable and straightforward. This simplicity makes Python an ideal teaching
language, and allows newcomers to pick it up quickly. Developers spend more time thinking
about the problem they’re trying to solve, and less time thinking about language complexities or
deciphering code left by others.

Python is broadly used and supported. Python is both popular and widely used, as the high
rankings in surveys like the Tiobe Index and the large number of GitHub projects using
Python attest. Python runs on every major operating system and platform, and most minor
ones too. Many major libraries and API-powered services have Python bindings or wrappers,
allowing Python to interface freely with those services or make direct use of those libraries.
Python may not be the fastest language, but what it lacks in speed, it makes up for in
versatility.

Python is not a “toy” language. Even though scripting and automation cover a large chunk of
Python’s use cases (more on that below), Python is also used to build robust, professional-
quality software, both as standalone applications and as web services.

Figure 7.1 Features of Python


`
DEPTT. OF COMPUTER ENGINEERING, GCET 55
What is Python used for?

The most basic use case for Python is as a scripting and automation language. Python isn’t
just a replacement for shell scripts or batch files, but is also used to automate interactions
with web browsers or application GUIs or system provisioning and configuration in tools
such as Ansible and Salt. But scripting and automation represent only the tip of the iceberg
with Python.

 Python is used for general application programming. Both CLI and cross-platform GUI
applications can be created with Python and deployed as self-contained executables.
Python doesn’t have the native ability to generate a standalone binary from a script, but
third-party packages like cx_Freeze or PyInstaller can be used to accomplish that.

 Python is used for data science and machine learning. Sophisticated data analysis has
become one of fastest moving areas of IT and one of Python’s star use cases. The vast
majority of the libraries used for data science or machine learning have Python interfaces,
making the language the most popular high-level command interface to for machine
learning libraries and other numerical algorithms.

 Python is used for web services and RESTful APIs. Python’s native libraries and third-
party web frameworks provide fast and convenient ways to create everything from
simple REST APIs in a few lines of code, to full-blown, data-driven sites. Python’s
latest versions have powerful support for asynchronous operations, allowing sites to handle
up to tens of thousands of requests per second with the right libraries.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 56
7.2.2 About Solidity

● Solidity is a statically-typed programming language with a similar syntax to JavaScript built


for writing smart contracts. It is the primary choice language for implementing smart
contracts on the Ethereum platform.

● Ethereum is an open source, decentralized platform for building smart contracts. It


facilitates the development and execution of complex applications such as financial
exchanges and insurance contracts on a distributed platform. The core of Ethereum is the
Ethereum Virtual Machine (EVM), which executes code of random algorithmic complexity.

● Solidity is designed for developing smart contracts that run on the EVM. Solidity contracts
are first compiled to bytecode which is ultimately executed on the EVM.

● Like other blockchains, Ethereum includes a peer-to-peer network protocol. The Ethereum
blockchain database is maintained and updated by several nodes connected to the network.
Every node on the network runs the EVM and executes the same set of instructions. The
Ethereum platform itself is featureless or value-agnostic. It is up to organizations and
developers to decide what it should be used for. However, certain application types benefit
more than others from Ethereum’s capabilities.

● Specifically, Ethereum is suited for applications that automate direct interaction between
peers or facilitate coordinated group action across a network. For instance, applications for
coordinating peer-to-peer marketplaces, or the automation of complex financial con-tracts.
When it comes to programming on Ethereum, there are some key points to notice from the
Ethereum Design Rationale document.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 57
Solidity - Basic Syntax

A Solidity source files can contain an any number of contract definitions, import directives
and pragma directives.
Let's start with a simple source file of Solidity. Following is an example of a Solidity file −

pragma solidity >=0.4.0 <0.6.0;


contract SimpleStorage {
uint storedData;
function set(uint x) public {
storedData = x;
}
function get() public view returns (uint) {
return storedData;
}
}

Pragma

The first line is a pragma directive which tells that the source code is written for Solidity
version 0.4.0 or anything newer that does not break functionality up to, but not including,
version 0.6.0.

A pragma directive is always local to a source file and if you import another file, the
pragma from that file will not automatically apply to the importing file.

So a pragma for a file which will not compile earlier than version 0.4.0 and it will also not
work on a compiler starting from version 0.5.0 will be written as follows −

pragma solidity ^0.4.0;

Here the second condition is added by using ^.

Value Types

Solidity offers the programmer a rich assortment of built-in as well as user defined data
types. Following table lists down seven basic C++ data types –

`
DEPTT. OF COMPUTER ENGINEERING, GCET 58
Type Keyword Values

Boolean bool true/false

Integer int/uint Signed and unsigned integers of varying sizes.

Integer int8 to int256 Signed int from 8 bits to 256 bits. int256 is the
same as int.

Integer uint8 to Unsigned int from 8 bits to 256 bits. uint256 is the
uint256 same as uint.

Fixed fixed/unfixed Signed and unsigned fixed point numbers of


Point varying sizes.
Numbers

Fixed fixed/unfixed Signed and unsigned fixed point numbers of


Point varying sizes.
Numbers

Fixed fixedMxN Signed fixed point number where M represents


Point number of bits taken by type and N represents the
Numbers decimal points. M should be divisible by 8 and
goes from 8 to 256. N can be from 0 to 80. fixed
is same as fixed128x18.

Fixed ufixedMxN Unsigned fixed point number where M represents


Point number of bits taken by type and N represents the
Numbers decimal points. M should be divisible by 8 and
goes from 8 to 256. N can be from 0 to 80. ufixed
is same as ufixed128x18.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 59
Contract

A Solidity contract is a collection of code (its functions) and data (its state) that resides at a
specific address on the Ethereum blockchain.
The line uintstoredData declares a state variable called storedData of type uint and the
functions set and get can be used to modify or retrieve the value of the variable.

Importing File

Though above example does not have an import statement but Solidity supports import
statements that are very similar to those available in JavaScript.

The following statement imports all global symbols from "filename".


import "filename";
The following example creates a new global symbol symbolName whose members are all the
global symbols from "filename".
import * as symbolName from "filename";
To import a file x from the same directory as the current file, use import "./x" as x;. If you use
import "x" as x; instead, a different file could be referenced in a global "include directory".

Following are the reserved keywords in Solidity −

abstract after alias apply

auto case catch copyof

default define final immutable

implements in inline let

macro match mutable null

of override partial promise

`
DEPTT. OF COMPUTER ENGINEERING, GCET 60
7.2.3 Ganache

 Ganache is a personal blockchain for rapid Ethereum and Corda distributed application
development. You can use Ganache across the entire development cycle; enabling you to
develop, deploy, and test your dApps in a safe and deterministic environment.

 Ganache comes in two flavors: a UI and CLI. Ganache UI is a desktop application


supporting both Ethereum and Corda technology. The command-line tool, ganache-cli
(formerly known as the TestRPC), is available for Ethereum development. Prefer using the
command-line? This documentation will focus only on the UI flavor of Ganache. Please see
the Ganache CLI Readme for command-line documentation.

 All versions of Ganache are available for Windows, Mac, and Linux.

 Downloading Ganache : You may download Ganache from the following URL
https://truffleframework.com/ganache

 Ganache is available on several platforms. We developed and tested this entire tutorial on
Mac. Thus, the screenshots below will show Mac installation. When you open the
installation URL given above, it automatically detects your machine’s OS and directs you to
the appropriate binary installation. The screenshot below shows the Mac installation.

Create a Workspace

When you open Ganache for the first time, you'll see the home screen. On this screen you're
prompted to load an existing workspace (if any exist), create a new custom workspace, or
quickstart a one-click blockchain with default options. For now, let's go with a quickstart
workspace. Select the desired blockchain from the QUICKSTART drop down; you can choose to
start an Ethereum node or Corda network, then click the QUICKSTART button.

Figure 7.2 Ganache GUI

`
DEPTT. OF COMPUTER ENGINEERING, GCET 61
7.2.4 About Remix IDE

 Remix IDE is used for the entire journey of smart contract development by users at every
knowledge level.

 It requires no setup, fosters a fast development cycle and has a rich set of plugins with
intuitive GUIs. The IDE comes in 2 flavors (web app or desktop app) and as a VSCode
extension.

 Remix Online IDE, see: https://remix.ethereum.org.

 Supported browsers: Firefox, Chrome, Brave. We do not support Remix’s use on tablets or
mobile devices.

 Remix Desktop IDE, see releases: https://github.com/ethereum/remix-desktop/releases

 Ethereum-Remix a VSCode extension, see here. The documentation for the VSCode
extension is located here.

7.2.5 Anaconda Navigator

 Anaconda Navigator is a desktop graphical user interface (GUI) included in Anaconda®


distribution that allows you to launch applications and easily manage conda packages,
environments, and channels without using command-line commands.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 62
 Navigator can search for packages on Anaconda.org or in a local Anaconda Repository. It is
available for Windows, macOS, and Linux.
 To get Navigator, get the Anaconda Cheat Sheet and install Anaconda.

 In order to run, many scientific packages depend on specific versions of other packages. Data
scientists often use multiple versions of many packages and use multiple environments to
separate these different versions.

 The command-line program conda is both a package manager and an environment manager.
This helps data scientists ensure that each version of each package has all the dependencies it
requires and works correctly.

 Navigator is an easy, point-and-click way to work with packages and environments without
needing to type conda commands in a terminal window. You can use it to find the packages
you want, install them in an environment, run the packages, and update them – all inside
Navigator

Figure 7.3 Anaconda Navigator GUI

`
DEPTT. OF COMPUTER ENGINEERING, GCET 63
7.3 CODE

#1 Smart Contract

#2 Code added to main File and importing necessary libraries

`
DEPTT. OF COMPUTER ENGINEERING, GCET 64
#3 Setting Up Ganache – Quickstart Ethereum Blockchain

`
DEPTT. OF COMPUTER ENGINEERING, GCET 65
#4 RemixIDE (online) > Uploading Smart Contracts > Compile > Deploying using
Ganache in RemixIDE for Development Purposes

#5 Anaconda Navigator with the Appropriate Environment > Command Prompt

`
DEPTT. OF COMPUTER ENGINEERING, GCET 66
#7 Running Command to Start Development Server : Python manage.py runserver

Opening the desired http in Browser

7.4 Project GUI

#8 Sign Up Page

`
DEPTT. OF COMPUTER ENGINEERING, GCET 67
#9 Sign in Page

#10 Farmer’s Page UI

`
DEPTT. OF COMPUTER ENGINEERING, GCET 68
#11 Processor’s Page

#12 Transactions recorded on blockchain

`
DEPTT. OF COMPUTER ENGINEERING, GCET 69
CHAPTER 8: SYSTEM STUDY

FEASIBILITY STUDY

The feasibility of the project is analyzed in this phase and business proposal is put forth with a
very general plan for the project and some cost estimates. During system analysis the feasibility
study of the proposed system is to be carried out. This is to ensure that the proposed system is not
a burden to the company. For feasibility analysis, some understanding of the major requirements
for the system is essential.

Three key considerations involved in the feasibility analysis are

 ECONOMICAL FEASIBILITY

 TECHNICAL FEASIBILITY

 SOCIAL FEASIBILITY

ECONOMICAL FEASIBILITY

This study is carried out to check the economic impact that the system will have on the
organization. The amount of fund that the company can pour into the research and development
of the system is limited. The expenditures must be justified. Thus the developed system as well
within the budget and this was achieved because most of the technologies used are freely available.
Only the customized products had to be purchased.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 70
TECHNICAL FEASIBILITY

This study is carried out to check the technical feasibility, that is, the technical requirements
of the system. Any system developed must not have a high demand on the available technical
resources. This will lead to high demands on the available technical resources. This will lead to
high demands being placed on the client. The developed system must have a modest requirement,
as only minimal or null changes are required for implementing this system

SOCIAL FEASIBILITY

The aspect of study is to check the level of acceptance of the system by the user. This
includes the process of training the user to use the system efficiently. The user must not feel
threatened by the system, instead must accept it as a necessity. The level of acceptance by the users
solely depends on the methods that are employed to educate the user about the system and to make
him familiar with it. His level of confidence must be raised so that he is also able to make some
constructive criticism, which is welcomed, as he is the final user of the system.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 71
CHAPTER 9 SYSTEM TESTING

The purpose of testing is to discover errors. Testing is the process of trying to discover every
conceivable fault or weakness in a work product. It provides a way to check the functionality
of components, sub assemblies, assemblies and/or a finished product It is the process of
exercising software with the intent of ensuring that the Software system meets its
requirements and user expectations and does not fail in an unacceptable manner. There are
various types of test. Each test type addresses a specific testing requirement.

TYPES OF TESTS

Unit testing
Unit testing involves the design of test cases that validate that the internal program logic is
functioning properly, and that program inputs produce valid outputs. All decision branches
and internal code flow should be validated. It is the testing of individual software units of the
application .it is done after the completion of an individual unit before integration. This is a
structural testing, that relies on knowledge of its construction and is invasive. Unit tests
perform basic tests at component level and test a specific business process, application,
and/or system configuration. Unit tests ensure that each unique path of a business process
performs accurately to the documented specifications and contains clearly defined inputs and
expected results.

Integration testing

Integration tests are designed to test integrated software components to determine if they
actually run as one program. Testing is event driven and is more concerned with the basic
outcome of screens or fields. Integration tests demonstrate that although the components
were individually satisfaction, as shown by successfully unit testing, the combination of
components is correct and consistent. Integration testing is specifically aimed at exposing
the problems that arise from the combination of components

`
DEPTT. OF COMPUTER ENGINEERING, GCET 72
Functional test

Functional tests provide systematic demonstrations that functions tested are available as specified by
the business and technical requirements, system documentation, and user manuals.
Functional testing is centred on the following items:
Valid Input : identified classes of valid input must be accepted.
Invalid Input : identified classes of invalid input must be rejected.
Functions : identified functions must be exercised.
Output : identified classes of application outputs must be exercised.
Systems/Procedures: interfacing systems or procedures must be invoked.

Organization and preparation of functional tests is focused on requirements, key functions, or special
test cases. In addition, systematic coverage pertaining to identify Business process flows; data fields,
predefined processes, and successive processes must be considered for testing. Before functional
testing is complete, additional tests are identified and the effective value of current tests is
determined.

System Testing
System testing ensures that the entire integrated software system meets requirements. It tests a
configuration to ensure known and predictable results. An example of system testing is the
configuration oriented system integration test. System testing is based on process descriptions and
flows, emphasizing pre-driven process links and integration points.

White Box Testing


White Box Testing is a testing in which in which the software tester has knowledge of the inner
workings, structure and language of the software, or at least its purpose. It is purpose. It is used to
test areas that cannot be reached from a black box level.

Black Box Testing


Black Box Testing is testing the software without any knowledge of the inner workings, structure or
language of the module being tested. Black box tests, as most other kinds of tests, must be written
from a definitive source document, such as specification or requirements document, such as
specification or requirements document. It is a testing in which the software under test is treated, as a
black box .you cannot “see” into it. The test provides inputs and responds to outputs without
considering how the software works.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 73
8.1 Unit Testing:

Unit testing is usually conducted as part of a combined code and unit test phase of the software
lifecycle, although it is not uncommon for coding and unit testing to be conducted as two distinct
phases.

Test strategy and approach


Field testing will be performed manually and functional tests will be written in detail.

Test objectives
• All field entries must work properly.
• Pages must be activated from the identified link.
• The entry screen, messages and responses must not be delayed.

Features to be tested
• Verify that the entries are of the correct format
• No duplicate entries should be allowed
• All links should take the user to the correct page.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 74
CONCLUSION

We propose a framework for tracking and executing transaction by using Ethereum smart
contracts, which changes the centralized model, eliminates intermediaries and intermediate
nodes, and realizes the decentralized model of the agricultural food supply chain, thus meeting
the demand for traceability of agricultural food. With respect to agricultural food safety
problems, this paper expounds the importance of food safety traceability, summarizes related
research, introduces blockchain and consortium chain, and presents a framework using
Ethereum smart contracts to track and implement the agricultural food trade; it presents system
architecture design and describes the relationship between the agricultural food supply chain
entities and the interaction between entities. In the end, the smart contracts algorithms are
implemented in order to realize tracking and tracing of the agricultural food supply chain, and
the practical application in HYASR PVT LTD., is introduced, cost analysis and problem
discussion.

However, regarding the existing problems of blockchain scalability, privacy and regulation,
we have presented a solution which does not take into account the reliability and auditability
of data transactions and payments, and with the development of the agricultural food supply
chain, the decentralized automatic payment mechanism is needed to ensure that all system
entities abide by the promise of deficiencies in the deal. As a goal of our future work, we plan
to study related problems and to be able to ameliorate and solve them

`
DEPTT. OF COMPUTER ENGINEERING, GCET 75
REFERENCES

• M. Thakur and K. A.-M. Donnelly, ‘‘Modeling traceability information in


Agriculture value chains,’’ J. Food Eng., vol. 99, no. 2, pp. 98–105, 2010.
• M. Thakur and C. R. Hurburgh, ‘‘Framework for implementing traceability
system in the bulk grain supply chain,’’ J. Food Eng., vol. 95, no. 2, pp. 617–
626, 2009.
• F. Tian, ‘‘A supply chain traceability system for food safety based on HACCP,
blockchain & Internet of Things,’’ in Proc. Int. Conf. Service Syst. Service Manage.
(ICSSSM), Jun. 2017, pp. 1–6.
• F. Tian, ‘‘An agri-food supply chain traceability system for China based on
RFID & blockchain technology,’’ in Proc. 13th Int. Conf. Service Syst. Service
Manage. (ICSSSM), Jun. 2016, pp. 1–6.
• Y. P. Lin, J. R. Petway, J. Anthony, H. Mukhtar, S.-W. Liao, C.-F. Chou, and Y.-
F. Ho, ‘‘Blockchain: The evolutionary next step for ICT e-agriculture,’’
Environments, vol. 4, no. 2, p. 50, 2017.
• M. Tripoli and J. Schmidhuber. (Aug. 2018). Emerging Opportunities for the
Application of Blockchain in the Agri–Food Industry. [Online].
• Available: FAO.org
• D. Mao, F. Wang, Z. Hao, and H. Li, ‘‘Credit evaluation system based on
blockchain for multiple stakeholders in the food supply chain,’’ Int. J. Environ. Res.
Public Health, vol. 15, no. 2, p. 1627, 2018.
• J. F. Galvez, J. C. Mejuto, and J. Simal-Gandara, ‘‘Future challenges on the use
of blockchain for food traceability analysis,’’ TrAC Trends Anal. Chem., vol. 107,
pp. 222–232, Oct. 2018.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 76
• D. Mao, Z. Hao, F. Wang, and H. Li, ‘‘Innovative blockchain-based approach
for sustainable and credible environment in food trade: A case study in Shandong
Province, China,’’ Sustainability, vol. 10, no. 2, p. 3149, 2018.
• P. Lucena, A. P. Binotto, F. da Silva Momo, and H. Kim, ‘‘A case study for
grain quality assurance tracking based on a blockchain business network,’’ (2018),
arXiv:1803.07877. [Online]. Available: https:// arxiv.org/abs/1803.07877
• M. Chinaka, ‘‘Blockchain technology—Applications in improving financial
inclusion in developing economies: Case study for small scale agriculture in
Africa,’’ Ph.D. dissertation, Sloan School Manage., Massachusetts Inst. Technol.,
Cambridge, MA, USA, 2016.
• M. Schneider, ‘‘Design and prototypical implementation of a blockchainbased
system for the agriculture sector,’’ M.S. thesis, Fac. Bus., Econ. Inform., Univ.
Zurich, Zürich, Switzerland, 2017.
• A. Holmberg and R. Aquist, ‘‘Blockchain technology in food supply chains: A
case study of the possibilities and challenges with an implementation of a
blockchain technology supported framework for traceability,’’
• M.S. thesis, Fac. Health, Sci. Technol., Karlstad Univ., Karlstad, Sweden, 2018.
• R. Kamath, ‘‘Food traceability on blockchain: Walmart’s pork and mango pilots
with IBM,’’ J. Brit. Blockchain Assoc., vol. 1, no. 2, p. 3712, 2018.
• (2018). Bloomberg. [Online]. Available: https://www.bloomberg.
com/news/articles/2018-01-22/dreyfus-teams-with-banks-for-firstagriculture-
blockchain-trade
• N. Nizamuddin, H. Hasan, and K. Salah, ‘‘IPFS-blockchain-based authenticity
of online publications,’’ in Proc. Int. Conf. Blockchain (ICBC) (Lecture Notes in
Computer Science). Seattle, WA, USA: Springer, 2018.

`
DEPTT. OF COMPUTER ENGINEERING, GCET 77

You might also like