Professional Documents
Culture Documents
Final Report 2022
Final Report 2022
Submitted by:
Mr. Pranav Sharma (GCET/168/18)
`
DEPTT. OF COMPUTER ENGINEERING, GCET 1
MAJOR PROJECT REPORT
ON
Submitted by:
Mr. Pranav Sharma (GCET/168/18)
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.
`
DEPTT. OF COMPUTER ENGINEERING, GCET 3
ACKNOWLEDGEMENT
Last but not the least we are thankful to our family members and friends
for their much-needed moral support and encouragement
Submitted by:
`
DEPTT. OF COMPUTER ENGINEERING, GCET 4
ABSTRACT
`
DEPTT. OF COMPUTER ENGINEERING, GCET 5
TABLE OF CONTENTS
`
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
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
11 References 76
`
DEPTT. OF COMPUTER ENGINEERING, GCET 7
LIST OF FIGURES
`
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
`
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.
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.
`
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
`
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?
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.
`
DEPTT. OF COMPUTER ENGINEERING, GCET 7
CHAPTER 2: Blockchain
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.
`
DEPTT. OF COMPUTER ENGINEERING, GCET 9
Figure 2.1: A simplified blockchain
`
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.
`
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.
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.
`
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.
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.
`
DEPTT. OF COMPUTER ENGINEERING, GCET 14
2.3 ELEMENTS OF BLOCKCHAIN
● 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.
`
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.
Block #1 #2
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.
`
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:
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.
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,
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
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.
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.
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.
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
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.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.
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.
`
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.
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
`
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.
`
DEPTT. OF COMPUTER ENGINEERING, GCET 30
CHAPTER 4: USE CASE SELECTION AND DESIGN PROCESS
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.
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.
`
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.
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).
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.
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).
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.
`
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:
● 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.
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
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:
`
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.
Address of Processor,
Address of Farmer,
Quantity,DatePurchased,CropPrice
1 Contractstate is buyCropFromFarmer
WaitForCropFromFarmer
10 end
11 else
16 end
17 else
19 end
Address of Processor,
Address of Retailer,
DateManufactured, Quantity,
DatePurchase
1 Contractstate is AgriFoodSoldToProcessor
9 end
10 else
`
DEPTT. OF COMPUTER ENGINEERING, GCET 50
12 State of distributor is RequestFailed
15 end
16 else
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
Address of Customer,
SalesID, AgriFoodID,
DatePurchased
1 Contractstate is SaleRequestAgreedSuccess
SuccessfulPurchaseAgriFoodSaleSuccess
10 end
11 else
16 end
17 else
`
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
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.
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 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
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 −
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
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.
`
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.
`
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.
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.
`
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.
Supported browsers: Firefox, Chrome, Brave. We do not support Remix’s use on tablets or
mobile devices.
Ethereum-Remix a VSCode extension, see here. The documentation for the VSCode
extension is located here.
`
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
`
DEPTT. OF COMPUTER ENGINEERING, GCET 63
7.3 CODE
#1 Smart Contract
`
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
`
DEPTT. OF COMPUTER ENGINEERING, GCET 66
#7 Running Command to Start Development Server : Python manage.py runserver
#8 Sign Up Page
`
DEPTT. OF COMPUTER ENGINEERING, GCET 67
#9 Sign in Page
`
DEPTT. OF COMPUTER ENGINEERING, GCET 68
#11 Processor’s Page
`
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.
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.
`
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 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
`
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