0% found this document useful (0 votes)
24 views83 pages

Secure Med - Blockchain Enabled Medicine Record Management System

The document describes a blockchain enabled medicine record management system project. It aims to address counterfeit drugs using blockchain technology to provide a secure and transparent system for tracing medicines throughout the supply chain. The system would use smart contracts and a distributed ledger to record all transactions immutably and allow authorized entities to seamlessly transfer products.

Uploaded by

dhammumudigonda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views83 pages

Secure Med - Blockchain Enabled Medicine Record Management System

The document describes a blockchain enabled medicine record management system project. It aims to address counterfeit drugs using blockchain technology to provide a secure and transparent system for tracing medicines throughout the supply chain. The system would use smart contracts and a distributed ledger to record all transactions immutably and allow authorized entities to seamlessly transfer products.

Uploaded by

dhammumudigonda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 83

SECURE MED - BLOCKCHAIN ENABLED

MEDICINE RECORD MANAGEMENT SYSTEM


Project Report in partial fulfilment of requirements
for the award of the degree of
BACHELOR OF TECHNOLOGY
in
COMPUTER SCIENCE AND ENGINEERING
by
B. Pujitha Siva Sresta (20501A0517) Chenikala Rakesh (20501A0528)
G. Siva Kiran (20501A0548) G.N.S. Deepika (20501A0559)

Under the guidance of


Mr. Prashant Atmakuri, Assistant Professor

Department of Computer Science and Engineering


Prasad V Potluri Siddhartha Institute of Technology
(Permanently affiliated to JNTU-Kakinada, Approved by AICTE)
(An NBA & NAAC A+ accredited and ISO 9001:2015 certified institute)
Kanuru, Vijayawada-520 007
2023-24
PRASAD V POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY
(Permanently affiliated to JNTU-Kakinada, Approved by AICTE)
(An NBA & NAAC A+ accredited and ISO 9001:2015 certified institute)
Kanuru, Vijayawada-520 007

CERTIFICATE
This is to certify that the project report entitled “SECURE MED -
BLOCKCHAIN ENABLED MEDICINE RECORD MANAGEMENT
SYSTEM” that is being submitted by B. Pujitha Siva Sresta (20501A0517),
Chenikala Rakesh (20501A0528), G. Siva Kiran (20501A0548), G. Naga Subha
Deepika (20501A0559) in partial fulfillment of the requirements for the award of the
Degree of Bachelor of Technology in Computer Science and Engineering during
the academic year 2023-24.

Mr. Prashant Atmakuri, Dr. A. Jayalakshmi,


Assistant Professor, Professor and Head,
DECLARATION
We declare that project work entitled “ SECURE MED – BLOCKCHAIN ENABLED
MEDICNE RECORD SYSTEM” is composed by ourselves, that the work contained
herein is our own except where explicitly stated otherwise in the text, and that this
work has not been submitted for any other degree or professional qualification except
as specified.

Team Members:
B. Pujitha Siva Sresta (20501A0517)
Chenikala Rakesh (20501A0528)
G. Siva Kiran (20501A0548)
G.N.S. Deepika (20501A0559)
Acknowledgement

We sincerely thank the following distinguished personalities who have given their
advice and support for successful completion of the work.

We are deeply indebted to our most respected guide [guide name], designation,
Department of computer science and engineering for his/her valuable and inspiring
guidance, comments, suggestions and encouragement.

We extend our sincere thanks to Dr. A. Jayalakshmi, Professor & Head of the
department for extending her cooperation and providing the required resources.

We would like to thank our beloved Principal, Dr K Sivaji Babu for providing the
online resources and other facilities to carry out this work.

We would like to express our sincere thanks to our Project Coordinators of the
department for their helpful suggestions in preparing this document.

We extend our sincere thanks to all other teaching and non-teaching staff of the
department, for their cooperation and encouragement.

Student1 name (Reg. Name)

Student2 name (Reg. Name)

Student3 name (Reg. Name)

Student4 name (Reg. Name)

ABSTRACT
Counterfeit drugs pose a severe threat to public health due to a lack of security
in the medical supply chain. This project proposes a Secure Med-Blockchain Enabled
Medicine Record Management System as a secure solution. Utilizing decentralized,
transparent, and irreversible ledger technology, the system guarantees the safe supply
of medical pharmaceuticals. Authenticated entities within the supply chain can
seamlessly transfer products through an event request-response mechanism using
blockchain's core features. All transactions are recorded on the blockchain via smart
contracts, ensuring complete traceability. This project reviews literature on blockchain
in the pharmaceutical sector, emphasizing safety, security, monitoring, tracing, drug
distribution, and counterfeit drug prevention. The imperfect pharmaceutical supply
chain, a key contributor to counterfeit drugs, can be addressed by incorporating
blockchain technology, promising enhanced transparency, security, and efficiency.

Keywords: Blockchain, Ethereum, Supply-chain Management, Smart Contracts,


Product Traceability, Ganache, Truffle Suite, Metamask and Drug Counterfeiting.

TABLE OF CONTENTS
CH.NO. TITLE PAGE NO
LIST OF FIGURES viii
LIST OF TABLES x
LIST OF ABBREVATIONS xi
CHAPTER 1: INTRODUCTION 1-4
1.1 Introduction to Project 1
1.2 Motivation 1
1.3 Statement of the Problem and Solution to Problem 2
1.4 Objectives 2-3
1.4.1 General Objectives 2
1.4.2 Specific Objectives 3
1.5 Scope of the Work 3
1.6 Significance of the Work 3
1.7 Outlines of the Project 4
BACKGROUND AND LITERATURE
CHAPTER 2: 5-7
REVIEW
CHAPTER 3: SYSTEM ANALYSIS 8-12
3.1 Existing System 8
3.2 Proposed System 9
3.3 Feasibility Study 12
3.3.1 Technical Feasibility 12
3.3.2 Operational Feasibility 12
3.3.3 Economic Feasibility 12
SOFTWARE REQUIREMENT
CHAPTER 4: 13-17
SPECIFICATION
4.1 Functional Requirements 13
4.2 Non-functional Requirements 13
4.3 Software & Hardware Requirements 15-17
4.3.1 Software Requirements 15
4.3.2 Hardware Requirements 17
DESIGN AND METHODOLOGY
CHAPTER 5: 18-27
OF PROPOSED SYSTEM
5.1 System Architecture or Model 18
5.2 System Design 21
5.2.1 UML Diagrams 21
5.3 Methodology 25-29
5.3.1 Process Model/Methodology 25
5.3.2 Tools and Techniques 28
CHAPTER 6: IMPLEMENTATION OF BASE PAPER 30-43
6.1 Smart Contracts 30
6.2 Description of each Smart Contract 32
6.3 Blockchain Implementation 35
CHAPTER 7: TESTING 48-53
7.1 Testing Strategy 48
7.2 Test Cases 50
CHAPTER 8: RESULTS 54-56
CHAPTER 9: CONCLUSION AND FUTURE SCOPE 57
9.1 Conclusion 57
9.2 Future Scope 57
REFERENCES & BIBLIOGRAPHY 58-59
APPENDIX A
Full Code 60-72
LIST OF FIGURES
FIG NO NAME PAGE NO
3.1 Existing System 8

3.2 Entities of the System 10

3.3 Architecture of the System 11

5.2 Class diagram 22

5.3 Sequence Diagram 23

5.4 Block in a Blockchain 25

5.5 Hashes in Blockchain 26

5.6 Distributed Peer to Peer Network 26

5.7 Request Response Mechanism 26

6.1 Files Hierarchy 32

6.2 Process Work Flow 35

6.3 Successful Execution of Smart Contracts 38

6.4 Successful Execution of Smart Contracts 38

6.5 Supplychain.sol 38

6.6 RawMaterial.sol 39

6.7 Medicine.sol 39

6.8 MedicineW_D.sol 39

6.9 MedicineD_P.sol 40

6.10 Compiling the Smart Contracts 40

6.11 Deploying initial_migrations.js 40

6.12 Deploying deploy_contracts.js 41

6.13 Deploying Supplychain.sol, RawMaterial.sol 41


6.14 Deploying Medicine.sol, MedicineW_D.sol 41

6.15 Deploying MedicineD_P.sol 42

6.16 Creating instance of Smart Contract 42

6.17 Calling Owner 42

6.18 Register User 43

6.19 Moving to respective Stakeholder 43

6.20 Manufacturing Medicine 44

6.21 Transporting Medicine 44

6.22 Updating Medicine Status 45

6.23 Ganache Accounts 45

6.24 Deployed Smart Contracts 46

6.25 Supply chain Contract 46

6.26 Ganache Block Structure 47

8.1 Total Gas Used for a Drug movement in 54


Supply chain

8.2 Total Gas Used for a Drug movement in 55


Supply chain

8.3 Comparison of Gas used 56

8.4 Comparison of Actual Gas Cost in ETH 56


LIST OF TABLES
TABLE NO NAME PAGE NO
6.1 Process Work Flow 36
7.1 Test Cases for Micro-Investments 51-53
8.1 Cost of Smart Contracts 54
8.2 Cost of Smart Contracts deployed using 55
Truffle
LIST OF ABBREVIATIONS
S NO TERMS DESCRIPTION
1 ETH Ethers
2 PoW Proof of Work
3 GWei Giga Wei
4 EA Ethereum Address
5 Dapps Decentralised Applications
6 IDE Integrated Developed Environment
7 ERC Ethereum Request for Comment
8 PoS Proof of Stake
CHAPTER 1

INTRODUCTION

1.1 INTRODUCTION TO PROJECT:

The healthcare sector is experiencing a transformative shift by integrating


cutting-edge technologies to address challenges and enhance patient outcomes.
Blockchain, a revolutionary technology, is being explored for securing the
pharmaceutical supply chain, a complex network involving suppliers, manufacturers,
wholesalers, distributors, and pharmacies. Traditional supply chain systems face
vulnerabilities like counterfeiting and lack transparency, posing risks to medicine
distribution and patient safety. This project investigates how blockchain can
revolutionize healthcare supply chain management by ensuring the authenticity and
integrity of pharmaceutical products. Serving as a tamper-resistant ledger, blockchain
enhances traceability and transparency by documenting every transaction and
movement of medications. This real-time, secure information access minimizes fraud
and facilitates quick responses to recalls, preventing the distribution of harmful or
counterfeit drugs. Moreover, blockchain's smart contracts automate quality control,
compliance verification, and payment settlements, enhancing operational efficiency
and ensuring adherence to regulatory standards. The paper delves into case studies,
practical implementations, and challenges of integrating blockchain into medicine
supply chains, aiming to contribute to the ongoing dialogue about the digital
revolution in healthcare supply chain management. Ultimately, the secure medicine
ecosystem enabled by blockchain has the potential to redefine industry standards,
creating a safer and more reliable healthcare environment for providers and patients.

1.2 MOTIVATION

Counterfeit drugs pose a severe threat in the pharmaceutical industry, fueled by


a lack of transparency in the supply chain. This opacity makes it challenging for
consumers to discern the true value of purchased medicines, leading to potential risks
to public health. The intricate network of suppliers and distributors provides
opportunities for unscrupulous actors to introduce counterfeit drugs, compromising
the efficacy of medical treatments. Investigation into tampering within the supply
chain is hindered by the system's limitations, exacerbanumbersting the challenge of
holding responsible parties accountable. Recognizing the imperative to protect public
health, the pharmaceutical industry is increasingly exploring innovative solutions such
as blockchain to enhance transparency, traceability, and security in the supply chain.
Adopting these technologies becomes not just a strategic move for the industry but a
moral obligation to ensure the delivery of genuine and effective medications,
mitigating the profound impact of counterfeit drugs on human health.

1.3 STATEMENT OF PROBLEM AND SOLUTION TO PROBLEM

Problem Statement:

The pharmaceutical supply chain is confronted with substantial challenges


related to security and transparency, intensifying the pervasive issue of drug
counterfeiting and posing a severe threat to public health. The absence of a secure
record management system exacerbates vulnerabilities, creating opportunities for
fraudulent activities.

Problem Solution:

To address these critical issues, the proposed project, "SECURE MED :


Blockchain Enabled Medicine Record Management System," aims to leverage
blockchain technology to establish a secure and transparent medicine record supply
chain management system, mitigating the risks associated with counterfeit drugs and
safeguarding public health.

1.4 OBJECTIVES

1.4.1 General Objectives:

• To improve the pipeline visibility by notifying the actors regarding process


status

• To improve the level of trust amongst each chain's entities


• To mitigate the presence and impact of counterfeit drugs.

• To enhance authentication by deploying smart contracts.

• To ensure the well-being of public healthcare resources

• To improve the quality of service provided to customers

1.4.2 Specific Objective:

The specific objective of the project is to enhance transparency, increase


security, and optimize gas costs within the medical supply chain through the
implementation of blockchain technology.

1.5 SCOPE OF WORK

The project encompasses several pivotal facets. Firstly, it seeks to deploy


blockchain technology to fortify data security and privacy, safeguarding the medical
supply chain against counterfeit drugs and unauthorized access or breaches. Secondly,
the project strives to establish a dependable source of truth by upholding the integrity
and immutability of drugs data through blockchain, minimizing the risk of
unauthorized alterations and instilling trust in medicine information. Additionally, the
scope extends to fostering interoperability among diverse stakeholders in the supply
chain, creating a standardized platform for seamless communication and data sharing.
This, in turn, streamlines healthcare processes, ensures regulatory compliance, and
ultimately enhances the quality of drugs. Furthermore, considerations for supply chain
management, smart contracts in healthcare, and the flow of drugs through the supply
chain.

1.6 SIGNIFICANCE OF WORK:

Counterfeiting drugs is a complex and enduring form of misconduct that has


persisted for decades, presenting a substantial global public health challenge. Taking
proactive measures to address this issue is crucial for ensuring public safety. In this
context, the significance of the simulation project lies in its potential to identify
counterfeit drugs and enhance transparency, contributing to a safer pharmaceutical
landscape.

1.7 OUTLINE OF PROJECT

Our project aims to develop a blockchain-enabled medicine record


management system to enhance the security, transparency, and accessibility of medical
records. The system will utilize blockchain technology to securely store and manage
medicine-related data, including prescriptions, dosages, and patient information. Key
features include user authentication, medicine record creation and management,
access control mechanisms, and audit trails to ensure transparency and accountability.
The system will prioritize data privacy and compliance with healthcare regulations.
Through this project, we seek to address the challenges associated with traditional
medicine record management systems by leveraging the immutability and
decentralized nature of blockchain technology.
CHAPTER 2

BACKGROUND AND LITERATURE REVIEW


1) Blockchain technology in healthcare big data management: Benefits,
applications and challenges.

Authors: Bazel, M. A., Mohammed, F., & Ahmed, M.

The study offers a thorough examination of the blockchain's possible uses in resolving
the issues with centralized healthcare data systems. It delves into the various benefits
that blockchain technology provides for the healthcare industry, including improved
patient consents, enhanced data ownership, strengthened information governance,
robust data auditing capabilities, heightened privacy and security measures, reliable
traceability of data, immutability of records, and flexible data access. Furthermore, the
authors highlight the essential technical features of blockchain, such consensus
methods and distributed ledgers., and discuss how these features contribute to the
suitability of Blockchain for massive data management in healthcare. The paper also
sheds light on the opportunities and obstacles related to blockchain adoption in the
healthcare industry, offering insightful information to practitioners and researchers. By
enriching the existing literature with an expanded perspective in addressing the
function of blockchain in healthcare big data management, this study seeks to further
the field's understanding and offer a framework for further investigation and use in the
healthcare sector.

2) Blockchain-based framework for supply chain traceability: A case example of


textile and clothing industry.

Authors: Agrawal, T. K., Kumar, V., Pal, R., Wang, L., & Chen, Y.

The paper "Blockchain-based traceability framework for supply chain management in


the textile and clothing industry" offers a comprehensive framework for implementing
blockchain technology to improve the textile and apparel (T&C) supply chain's
traceability. It tackles issues like limited visibility and information asymmetry that the
T&C sector faces., by providing a solution for ensuring product authenticity and
ethical buying practices. The framework not only proposes a theoretical model but
also demonstrates the operationalization of blockchain technology in a intricate multi-
level supply chain system, showcasing its potential to establish technology-based trust
and guarantee data security. The paper's main contribution is its attention on the
significance of smart contracts in ensuring the provenance of raw materials. It
provides A simulation-based presentation of partner interaction and network
configuration protocols, offering practical insights into the operational aspects of
blockchain implementation in the T&C supply chain. Furthermore, the report
emphasizes the potential practical implications of the framework for ongoing
blockchain pilots in the T&C industry, offering valuable insights for the
implementation of blockchain-based traceability solutions. Overall, the paper not only
addresses the theoretical aspects of blockchain-based traceability but also gives a
practical demonstration of its applicability in the T&C supply chain. This makes it an
important addition to the body of knowledge on blockchain technology and supply
chain management, especially in the travel and tourism sector.

3) Smart contract diffusion in the pharmaceutical blockchain: the battle of


counterfeit drugs.

Authors: Kordestani, A., Oghazi, P., & Mostaghel, R.

The paper begins by offering an in-depth exploration of the complexities within the
pharmaceutical supply chain, shedding light on the prevalence of counterfeit drugs
and their detrimental impact on public health. Recognizing the limitations of
conventional supply chain mechanisms, the paper emphasizes the possible advantages
of using blockchain technology, specifically focusing on the unique attributes of smart
contracts. Key themes emerge regarding using smart contracts to battle fake
pharmaceuticals. The paper elucidates on how smart contracts contribute to enhancing
transparency, traceability, and security within the pharmaceutical supply chain. It
investigates the compatibility of smart contracts with other emerging technologies,
elucidating their seamless integration potential and the resulting synergies.
Furthermore, the systematic literature review delves into the real-time accessibility of
information throughout the supply chain facilitated by smart contracts on blockchain
platforms. This accessibility not only expedites decision-making processes but also
serves as a deterrent to counterfeiting activities, fostering a more resilient and secure
pharmaceutical supply ecosystem. Patient security, transparency, and trust are
paramount concerns in the healthcare sector, and the paper critically evaluates how the
diffusion of smart contracts on blockchain platforms positively impacts these factors
in the context of combating counterfeit drugs. Insights are drawn from the literature to
present a comprehensive understanding of the effects, highlighting instances where
smart contracts have proven instrumental in safeguarding patient interests and
bolstering trust within the pharmaceutical supply chain. In conclusion, this systematic
literature review synthesizes existing knowledge on the use of smart contracts on
blockchain platforms to combat counterfeit drugs in the pharmaceutical supply chain.
By elucidating key themes, identifying gaps in current research, and by suggesting
directions for further research, this study seeks to add to the current conversation.
surrounding the implementation of cutting-edge technologies to fortify the integrity of
pharmaceutical distribution systems.

4) Supply chain management. Strategy, planning & operation

Authors: Chopra, S., & Meindl, P.

The paper "Supply Chain Management: Strategy, Planning & Operation" by Sunil
Chopra and Peter Meindl provides a comprehensive overview of supply chain
management, including strategy, planning, and implementation of operations. It
discusses the importance of aligning business processes across internal functions and
external partners to optimize costs, lead times, and service quality for customers.
Various analytical methods and models are presented for strategic network design,
demand forecasting, inventory management, transportation planning, and cross-
functional collaboration. The authors highlight the challenges of coordinating complex
multi-entity supply chains in dynamic market environments. They emphasize the need
for integrated IT systems, joint decision making, information sharing, and minimizing
the bullwhip effect to achieve high product availability while keeping costs low.
Overall, the paper provides valuable insights and approaches for managing modern
global supply chains effectively.
CHAPTER 3

SYSTEM ANALYSIS

3.1 EXISTING SYSTEM:

The Existing system in the medical industry as shown in Fig 3.1 for combating
counterfeit drugs predominantly center around insufficient and limited visibility.
While these approaches offer varying levels of data security and control, they
frequently fall short in delivering the transparency and immutability crucial for
upholding the integrity of sensitive medical data.

Fig 3.1 Existing System

A promising alternative on the rise is the adoption of blockchain technology.


Both public and private blockchains are increasingly explored to establish a
decentralized, secure, and tamper-proof ledger for healthcare data management,
effectively addressing the limitations of existing methods. Additionally, the
incorporation of smart contracts within blockchain technology facilitates the
automation of diverse healthcare processes, leading to heightened operational
efficiency and decreased administrative overhead. These advancements signify a
noteworthy shift towards a more secure, transparent, and efficient supply of drugs in
the medical sector.

Problems with Existing System:

 Untrusted Supply Chain: It’s incredibly difficult for customers or buyers to


truly know the value of products because there is significant lack of
transparency in current system.
 Tampering within the Chain: In a similar way, it’s extremely difficult to
investigate supply chains when there is suspicion of illegal or unethical
practices. This existing system had failed to address the needs of all
stakeholders.
 Inefficiency in Delivery: They can be also be highly inefficient as vendors
and suppliers try to connect the dots on who needs what, when and how. This
also leads to the compromised authenticity of pharmaceutical products.
 Poor Customer Service: Customer experience should always be a top focus
for any business. Keeping existing customers happy gives business, a much
better return than having to constantly find new customers.
 Risk of Fraud: Without comprehensive stakeholder involvement, there is a
heightened risk of fraudulent activities within the supply chain, undermining
efforts to degrade product authenticity and safety.

3.2 PROPOSED SYSTEM:

A Blockchain is a Tamper-proof, distributed database that stores blocks of


information for cryptographically bound transactions via peer-to-peer networks. The
architecture of a block chain enables users to share validated and updated ledgers for
every transaction. Nodes receive copies of each transaction and validate them, and this
information is synchronized throughout the network. As such, the need for a central
validating authority is eliminated. The connections between transactions in separate
blocks are linked, which is what gave rise to the term blockchain. An essential focus
of the pharmaceutical industry is to ensure rapid and secure transactions, along with
supply chain fidelity.

The intention of implementing a supply chain medicine record management


system using blockchain technology is to address key challenges in the current
medicine supply chain, such as counterfeiting, lack of transparency, and inefficiencies
in tracking and tracing products. By leveraging blockchain, we aim to create a
transparent, secure, and immutable ledger that records every transaction and
interaction within the supply chain network.

To implement this system, we will utilize Ethereum blockchain due to its


robustness, smart contract functionality, and widespread adoption. Each participant in
the supply chain, including suppliers, manufacturers, distributors, and retailers, will
have their unique Ethereum account representing their identity within the network.
Smart contracts will be deployed to automate and enforce the execution of
predefined business rules and agreements, such as the validation of product
authenticity, tracking of product movements, and management of transactions. These
smart contracts will ensure transparency and trust among participants by enabling
tamper-proof record-keeping and eliminating the need for intermediaries.

Furthermore, the use of decentralized consensus mechanisms in Ethereum,


such as Proof-of-Work (PoW) or Proof-of-Stake (PoS), will ensure the integrity and
security of the data stored on the blockchain. This decentralized approach reduces the
risk of data manipulation, fraud, and unauthorized access, thus enhancing the overall
reliability and security of the medicine record management system.

Through the implementation of blockchain technology, we aim to create a


more secure, efficient, transparent, and trustworthy medicine supply chain ecosystem
that prioritizes human health.

Fig 3.2 – Entities of the System

A supply chain can be defined as the series of steps involved in acquiring a


product from the producer and distributing it to the end-user, in this case, the
customer. The Blockchain-Enabled Medicine Record Management System represents
a healthcare supply chain with several parties involved as shown in Fig 3.2, from the
source of Raw Materials to the Manufacturer, Distributor, Wholesaler, Pharmacist and
the Patient who is at the conclusion of the chain. The Proposed Solution is being
developed on the Ethereum Blockchain Platform, known for its Permission less and
Public nature, allowing open access to anyone. The Remix-IDE Environment and
Truffle suite framework are employed for compiling, deploying and testing the
Solidity-written smart contract, providing a group of instruments for drafting and
implementing smart contracts on the Blockchain. Each Participant in the System plays
a distinct role and has interactions with the smart contract, referred to as the Drug
Container. The roles and functionalities of each entity are elaborated upon Fig 3.3.
Additionally, an event request-response mechanism has been established to
authenticate the identity of all parties and verify the signature within the event,
ensuring the legitimacy of the event.

Blockchain provides complete secure and transparency, which also brings trust
between the various main entities of the Medicine Supply Chain, such as Suppliers
and Manufacturers, intermediaries like Wholesalers, Distributors and Pharmacies, at
last the end-users like Customers and Hospitals. Each product within the chain can be
transferred between the different authenticated entities of the chain using an event
request-response mechanism. All transactions between the different entities are
recorded into the blockchain using smart contracts.
Fig 3.3 – Architecture of the System

3.3 Feasibility Study:

3.3.1 Technical Feasibility:

The technical feasibility of implementing blockchain technology for the secure


supply of medical drugs is evident in its ability to efficiently record and verify
transactions between authenticated entities. Blockchains, being decentralized,
distributed, transparent, and immutable, offer a robust solution to counteract
counterfeit medicines. The proposed system utilizes an event request-response
mechanism for the seamless transfer of products within the supply chain, ensuring
transparency and traceability. The integration of smart contracts facilitates the
recording of all transactions on the blockchain, enhancing security. Experimental
results demonstrate the technical feasibility of the solution, showcasing its viability
and comparative security advantages over existing systems.

3.3.2 Operational Feasibility:

Operational feasibility is achieved through the proposed blockchain-based


system's ability to streamline the supply chain process. The event request-response
mechanism simplifies product transfers between authenticated entities, reducing
manual interventions. The system's transparency ensures easy access to medical
intelligence, contributing to improved customer service and loyalty. By minimizing
manual operations, the project aims to enhance the overall efficiency of the
pharmaceutical supply chain, making it operationally feasible and user-friendly for
stakeholders.

3.3.3 Economic Feasibility:

The economic feasibility of the project lies in its potential to improve customer
service, loyalty, and overall supply chain efficiency. While there may be initial
investment costs associated with implementing blockchain technology, the long-term
benefits, including reduced counterfeit medicines and operational efficiency,
contribute to the economic viability of the solution. The study emphasizes the
importance of a more secure system, demonstrating that the economic feasibility of
the proposed blockchain-enabled system outweighs the potential costs associated with
its implementation.

CHAPTER 4

SOFTWARE REQUIREMENT SPECIFICATION

4.1 FUNCTIONAL REQUIREMENTS:

1. Secure Product Transfer:


• Enable secure transfer of medical products within the supply chain.
• Implement an event request-response mechanism for product transfers.
2. Blockchain Integration:
• Integrate blockchain technology to securely record all transactions.
• Utilize smart contracts for the recording of transactions on the
blockchain.
3. Traceability:
• Ensure traceability of each product within the supply chain through the
blockchain.
4. User Authentication:
• Implement user authentication for entities involved in the supply chain
(manufacturers, distributors, retailers).
• Restrict modification privileges to the owner, ensuring that only the
owner has the authority to modify relevant information within the
supply chain.
5. Operational Efficiency:
• Minimize manual operations within the pharmaceutical supply chain to
enhance overall operational efficiency.

4.2 NON-FUNCTIONAL REQUIREMENTS:

These represent the quality limitations that the system must adhere to base on
the project agreement. The degree or priority of implementation of these factors may
differ from one project to another. They are alternatively referred to as non-
behavioural requirements.

Standard Features:
 Scalability: Scalability in a blockchain-enabled medicine record management
system can be attained through techniques like sharding, off-chain
transactions, and layer 2 solutions, ensuring efficient processing of a higher
volume of transactions while preserving decentralization and security.
Additionally, optimizing smart contract code and utilizing sidechains can
further enhance scalability by reducing congestion and allowing for parallel
processing of transactions.
 Maintainability: Maintainability in a blockchain-enabled medicine record
management system involves regular updates to smart contracts, ensuring
compatibility with evolving healthcare standards and regulations. Continuous
monitoring of the blockchain network's health and performance is vital,
alongside proactive bug fixes and security patches to uphold system reliability
and data integrity. Implementing modular architecture and clear documentation
facilitates easier maintenance and scalability as the system grows.
 Usability: Usability in a blockchain-enabled medicine record management
system emphasizes intuitive user interfaces and streamlined workflows for
stakeholders. Providing role-based access controls and clear navigation
enhances user experience, ensuring efficient interaction with the system.
Regular user feedback and iterative design improvements contribute to a user-
centric approach, fostering adoption and usability.
 Availability: Availability in a blockchain-enabled medicine record
management system is upheld by redundant network nodes and robust
consensus mechanisms, ensuring continuous access to critical medical data.
Implementing failover mechanisms and distributed storage solutions enhances
system resilience against downtime and ensures uninterrupted service delivery.
Regular monitoring and proactive maintenance practices further guarantee
high availability, minimizing disruptions to healthcare operations.
 Performance: Performance in a blockchain-enabled medicine record
management system is optimized through efficient consensus algorithms like
Proof of Authority or Proof of Stake, reducing transaction processing times
and network congestion. Employing scalable blockchain solutions such as
sidechains or off-chain computation helps handle increasing transaction
volumes without sacrificing speed or throughput. Continuous optimization of
smart contracts and network infrastructure ensures responsive data retrieval
and processing, enhancing overall system performance.

4.3 SOFTWARE & HARDWARE REQUIREMENTS

4.3.1 SOFTWARE REQUIREMENTS:

 Remix IDE: Remix IDE is a web-based Integrated Development Environment


(IDE) primarily used for developing, testing, and deploying smart contracts on
Ethereum and other blockchain platforms. It offers a user-friendly interface
with features like code editing, debugging, and deployment tools directly in
the browser. Remix supports multiple programming languages such as
Solidity, Vyper, and Yul, and provides a range of plugins and extensions for
enhanced functionality. It's widely used by blockchain developers, both
beginners and experienced, due to its convenience and accessibility for writing
and testing smart contracts efficiently.
https://remix.ethereum.org/

 Node v20.11.1: Node.js version 20 (Node.js v20.11.1) is a significant release


focusing on stability, performance, and developer productivity enhancements.
It includes updates to the V8 JavaScript engine, improvements in diagnostic
reporting, and enhanced support for ECMAScript modules. Node.js v20 also
features updated dependencies, security patches, and refinements to the
Node.js API, empowering developers to build scalable and efficient
applications.
https://nodejs.org/en/download/current

 Truffle v5.11.5: Truffle is a widely-used development framework for


Ethereum blockchain applications, offering tools for smart contract
compilation, deployment, and testing. This version introduces improvements
in smart contract compilation, debugging capabilities, and support for the latest
Solidity language features, enhancing the efficiency and reliability of
Ethereum development workflows.
https://trufflesuite.com/docs/truffle/quickstart
 Ganache v7.9.1: Ganache is a popular local Ethereum blockchain emulator,
facilitating rapid development and testing of Ethereum smart contracts and
decentralized applications (dApps). This version includes bug fixes,
performance enhancements, and support for the latest Ethereum network
upgrades, providing developer with a reliable and feature-rich environment for
Ethereum development.
https://trufflesuite.com/ganache/

 Solidity v0.8.21: Solidity v0.8.21 is a major release of the programming


language for Ethereum smart contracts, introducing significant syntax changes
and optimizations for better code readability and security. This version
introduces features like the "calldata()" keyword for improved memory
management and stricter checks for arithmetic operations, enhancing the
overall robustness and efficiency of Ethereum smart contract development.
Released as part of the Solidity compiler suite, previous versions 0.5.12
introduces various improvements, bug fixes, and optimizations to enhance the
development experience and ensure the reliability and security of smart
contracts. Developers can utilize Solidity 0.5.12 to create decentralized
applications (dApps), define smart contract logic, and deploy them onto the
Ethereum blockchain. It supports features like inheritance, libraries, modifiers,
events, and more, enabling developers to build complex and efficient
decentralized systems while adhering to best practices and standards in
blockchain development.
https://docs.soliditylang.org/

 Web3.js v1.10.0: Web3.js v1.10.0 is a JavaScript library that provides an


interface for interacting with Ethereum blockchain networks, enabling
developers to build decentralized applications (dApps) and integrate
blockchain functionality into web applications. This version introduces
enhancements such as support for EIP-1559 transactions and WebSocket
subscriptions, improving the efficiency and flexibility of Ethereum blockchain
interactions for developers.
4.3.2 HARDWARE REQUIREMENTS:

 Processor - I3/Intel Processor

 Hard Disk - 160GB

 Key Board - Standard Windows Keyboard

 Mouse - Two or Three Button Mouse

 Monitor - SVGA

 RAM - 8GB
CHAPTER 5

DESIGN AND METHODOLOGY OF PROPOSED


SYSTEM

5.1 SYSTEM ARCHITECTURE OR MODEL:

The Proposed System as described in Fig 5.1 operates within a Decentralized


Network, connecting various entities crucial to the medicine supply chain, including
Suppliers, Transporters, Manufacturers, Wholesalers, Distributors, Retailers, and End-
Customers. Each Entity in the network functions as a node and possesses its own
distinct Ethereum account (EA), serving as its Unique Representation of Identity
within the System.

This Decentralized Architecture enables secure and transparent interactions


among the participants, facilitated by Blockchain Technology. Through Smart
contracts and immutable transaction records, the system ensures the integrity and
traceability of medicine-related data at every stage of the supply chain. By leveraging
Ethereum's Blockchain, the system fosters trust, reduces the risk of fraud or
counterfeit medicines, and enhances overall efficiency and accountability within the
medicine supply ecosystem.

The proposed system Fig 5.1 defines specific roles and functionalities for each
entity to ensure smooth operation and accountability throughout the supply chain
process. The regulatory authority serves as the overseeing entity responsible for
ensuring the integrity, compliance, and safety of the entire process. The Regular
Authority/Owner possesses administrative privileges, enabling them to manage user
accounts for validating and approving the participation of each role in the supply
chain. This validation process involves verifying credentials, adherence to regulations,
and authorization for participation.

Once the regulatory authority approves the roles, the supply chain operations
commence. The supplier, as one of the primary stakeholders, initiates the process by
creating a new product or updating the status of an existing one. This information is
then relayed to the regulatory authority for documentation and oversight.
Transporters play a pivotal role in verifying and transporting packages,
ensuring the secure delivery of raw materials and medicines between entities.

Manufacturers receive Raw Materials from Suppliers via Transporters,


verifying their Source before creating new medicines using the received materials.

Wholesalers receive Medicines from Manufacturers, verify their Source, and


facilitate the transfer of Ownership before distributing them to distributors.

Distributors, in turn, receive Medicines from Wholesalers, verify their Source,


and transfer ownership before delivering them to pharmacies.

Pharmacies, the final recipients of medicines, verify their Source upon receipt
and ensure the legitimacy of the products before making them available to consumers.
Through these defined roles and functionalities, the system aims to enhance
transparency, traceability, and accountability within the medicine supply chain,
ultimately contributing to improved safety and quality of healthcare services.

Fig 5.1 – System Architecture


The detailed functionalities and specific roles of our entities in our proposed system
architecture Secure Med: Blockchain Enabled Medicine Record Management system
are discussed below:

1. Regular Authority/ Owner


a. CREATE a new user to be added to the chain.
b. READ the information of any user.
c. UPDATE the roles of a user.
d. DELETE a user from the chain.
2. Transporter
a. Verify the package (Raw Material or Medicine).
b. Pick the package from an entity (based on transporter type).
c. Deliver the product to an entity.
3. Supplier
a. CREATE a Raw Material.
b. GET the addresses of the Raw Materials created.
4. Manufacturer
a. Receive the Raw Material from the Supplier through the Transporter.
b. Verify the source of the product received.
c. CREATE a new Medicine using received raw materials.
5. Wholesaler
a. Receive the Medicine from the Manufacturer through the Transporter.
b. Verify the Source of the Medicine.
c. Transfer the Ownership of the Medicine.
6. Distributor
a. Receive the Medicine from the Wholesaler through the Transporter.
b. Verify the Source of the Medicine.
c. Transfer the Ownership of the Medicine.
7. Pharmacy
a. Receive the Medicine from the Distributor through the Transporter.
b. Verify the Source of the Medicine.

The presence of multiple dealers and intermediaries presents an opportunity


for malpractice that undermines supply chain efficiency. Blockchain has been hailed
for preventing the circulation of poor-quality pharmaceuticals. Ledger systems, chain
codes, and serialization, in which serial numbers are assigned to pharmaceutical
products to enable identification and differentiation, are used to facilitate
pharmaceutical distribution. Blockchain information is tightly regulated to avoid
unauthorized access that could jeopardize security systems. Significantly, the
medicine supply chain lacks the infrastructure to ensure comprehensive manufacturer-
to-end user tracking. The manufacturer first distributes drugs to wholesalers, who then
distribute the drugs to hospitals or pharmacies. Every transaction in this process
should be tracked. Blockchain is a suitable technology to solve distribution process
problems such as the circulation of counterfeit or illegal drugs.

5.2 SYSTEM DESIGN:

5.2.1 UML DIAGRAMS

Class Diagram:

A class diagram describes the static structure of a system by depicting classes,


their attributes, methods, and relationships. The Fig 5.2 is a simplified class diagram
illustrates the relationships and interactions between the various roles and entities in
our proposed system application Secure Med: A Blockchain Enabled Medicine Record
Management System. The class diagram represented in Fig 5.2 describes the following

 The Regulatory Authority class represents the regulatory body overseeing the
supply chain.
 Supplier, Manufacturer, Wholesaler, Distributor, and Pharma are the different
roles involved in the supply chain with specific associated attributes.
 Transporter class represents the entity responsible for transporting products
between different roles.

The Medicine product is always being tracked in the supply chain, with associated
attributes such as ID, name, expiry date, and references to the roles involved in its
lifecycle. Status of the medicine represents the various states a product can be in, such
as created, shipped, or received.
Fig 5.2 Class Diagram
Sequence Diagram:
Fig 5.3 Sequence Diagram

A sequence diagram depicts interactions between different components or


objects in a system over time. In the context of our proposed system application
Secure Med: A Blockchain Enabled Medicine Record Management System. A
sequence diagram as represented in Fig 5.3 gives the overall sequence of the activities
involved in the supply chain process between the various roles such as supplier,
manufacturer, wholesaler, distributor, pharma, and end user when interacting with
medicine details.

The supply chain starts from the supplier, as one of the primary stakeholders,
initiates the process by creating a new product or updating the status of an existing
one. This information is then relayed to the regulatory authority for documentation
and oversight. Following this, the manufacturer receives the product details from the
supplier and proceeds with the manufacturing process. Throughout these steps, the
regulatory authority remains informed, ensuring transparency and accountability.

As the product moves through the supply chain, each subsequent role interacts
with it, updating its status and forwarding relevant information to the regulatory
authority. The wholesaler receives the product from the manufacturer, the distributor
from the wholesaler, and finally, the pharma from the distributor. Concurrently, a
transporter facilitates the physical movement of the product between these roles,
updating its status as it progresses through the supply chain.

In parallel, end users, such as patients or consumers, interact with the system
to access medicine details. They request information about specific products, and the
system retrieves relevant data from the blockchain, including product status, batch
information, and expiration dates. This ensures transparency and allows end users to
make informed decisions regarding the products they handle or consume.

This process is secured using Blockchain technology so as to reduce and tackle


the issue of counterfeit drugs. Using Blockchain technology one can track their
package and also verify its authenticity.

Hence, Fig 5.3 demonstrates how each role interacts with the system and with
each other to track the movement and status of medicine products through the supply
chain.
5.3 METHODOLOGY

5.3.1 Process Model/Methodology:

The blockchain methodology in supply chain process model is composed of


several components and has important properties for the pharmaceutical supply chain:

The Block: A blockchain is composed of a Chain of a sequence of Blocks as in Fig


5.4. Each new Block is connected to the previous block to store data related to the
specific domain. For Example, A drug block contains data about the drugs, Name,
Type, Amount, and Ingredients.

Fig 5.4 Block in a Blockchain

Hash: Each block in the chain must have a hash that is used to identify a block and all
of its components. As shown in Fig 5.5, It is considered as a fingerprint for each block
in the supply chain.

Fig 5.5 Hashes in a Blockchain

Proof of Work: The concept of PoW is used to make blockchain more secure and
prevent tampering through including complex cryptography that takes time and effort
to solve.

Decentralized ledger: The pharmaceutical company has complete controls on data


and we cannot ensure 100% that the data that pharmaceutical companies are
introduced is 100% authentic or not. Blockchain technology plays a crucial role in
solving the problem of data isolation. Blockchain technology is used as a
Decentralized Ledger as shown in Fig. 5.6. Each participant in the network shares data
stored in the Blockchain network and one centralized person does not own it.

Fig 5.6 Distributed peer-to-peer network

Request Response Mechanism:

In the process, any node can have both the attributes of demand and supply. In
the product transaction formation process, an event response mechanism in Fig 5.7, is
designed in order to ensure that both parties of the transaction agree on the receipt and
delivery of medical drugs. The transaction data will be permanently stored in the
blockchain using smart contracts. The process of agreeing on the delivery and receipt
of goods by both parties of the transaction is shown using the event request response
mechanism.

Fig 5.7 Request Response Mechanism


As shown in the above Fig. 5.7, the process of agreeing on the delivery and
receipt of goods by both parties of the transaction is shown using the event request
response mechanism. It is discussed in detail below.

1. First, the buyer initiates a purchase request. The BuyEvent() event in the Supply
Chain contract is then triggered. The event includes the buyer's and seller's
Ethereum address (EA), the address of the raw material/medicine to be
purchased, along with the timestamp of the request. The signature is sent along in
the events to confirm the identity of both parties and the authenticity of the
request. The Seller addresses are indexed so that each seller can query their
records based on their Ethereum Address (EA).
2. Then, the Seller queries the log records related to himself according to his
Ethereum address and verifies the validity of the signature contained in the
events. If the verification is passed, an event RespondEvent() is triggered by the
seller to respond to the buyer’s request along with a signature which is signed
with the private key of the seller.
3. Next, the Seller sends the product to the buyer through the Transporter. An event
SendEvent() is triggered to prove that the raw materials/medicines have been
shipped, including the Seller's and buyer's Ethereum address, the product
address. along with the timestamp of the transfer of the product.
4. Finally, an event ReceivedEvent() is triggered by the buyer upon receipt of the
goods to certify that the goods have been received.

Transactions in blockchain are digitally signed data packages containing


sender and recipient addresses, amount transferred, and other details. They undergo
initiation, validation, inclusion in blocks, confirmation, execution, and propagation
stages. Once confirmed, transactions are immutable and irreversible, ensuring the
integrity of the blockchain ledger. Fees may be required for transaction processing,
incentivizing network participants.

Transaction migration in blockchain involves transferring data or assets from


one blockchain network to another. Steps include assessing requirements, designing a
migration strategy, preparing data, validating, executing migration, performing post-
migration activities, and documenting the process. Successful migration requires
careful planning, validation, and communication to ensure a smooth transition while
minimizing disruption and risk.

5.3.2 Tools and Techniques:

Technologies Used:

 The proposed system architecture/design is implemented using Blockchain


Technology and various tools like Truffle, Ganache, Solidity and Web3 JS.
 Blockchain technology is a decentralized digital ledger system that securely
records transactions across a network of computers. Its importance lies in its
ability to provide transparency, immutability, and security to data, making it
ideal for various applications such as financial transactions, supply chain
management, and voting systems. Additionally, blockchain eliminates the need
for intermediaries, reducing costs and increasing efficiency in processes.
 Remix IDE is a web-based Integrated Development Environment (IDE)
primarily used for developing, testing, and deploying smart contracts on
Ethereum and other blockchain platforms. It offers a user-friendly interface
with features like code editing, debugging, and deployment tools directly in
the browser. Remix supports multiple programming languages such as
Solidity, Vyper, and Yul, and provides a range of plugins and extensions for
enhanced functionality. It's widely used by blockchain developers, both
beginners and experienced, due to its convenience and accessibility for writing
and testing smart contracts efficiently.
 Truffle is a framework used for building blockchain based applications. It
eases the process of writing and deploying smart contracts. It also provides
other tools that can be used to develop, deploy and test smart contracts for
blockchain apps. It provides the necessary migration code that is required to
deploy the smart contracts and users can focus on smart contracts without the
need to worry about how to deploy them.
 Ganache is a tool, part of the truffle suite, that creates a private Ethereum
based blockchain on a local system and can be used for testing contracts and
development purposes. A workspace can be created for a project by linking the
configuration file of the truffle project. By default, it creates 10 accounts with
100 ETH each and these accounts can be used to make transactions on the
blockchain network.
 Solidity is the language that is used to write smart contracts. This language is
similar to other high-level languages and supports some of the object-oriented
features. It allows users to define their own data types according to the needs
of the application it is being used for.
 Web3.JS is another JavaScript library that is used to communicate with the
local Ethereum node. It has various tools that are required to run a blockchain
application like making transactions, fetching data, etc.
 Node JS is an open-source, cross-platform runtime environment for JavaScript
code. Another advantage of Node.js over others is that a developer only needs
to know and experience one language, JavaScript, whether he is developing
client-side or server-side scripts. The developer does not need to switch
between brain cycles for one language on the client side and another on the
server side.
 Visual Studio Code is a source-code editor made by Microsoft for Windows,
Linux, and macOS. Features contain aid for debugging, syntax highlighting,
intelligent code completion, snippets, code refactoring, and embedded Git.
CHAPTER 6

IMPLEMENTATION

6.1 SMART CONTRACTS:

A Smart contract is a self-executing contract with the terms of the agreement


directly written into code. They run on the blockchain, making them transparent,
traceable, and irreversible. It is a secure and unstoppable computer program
representing an agreement that is automatically executable and enforceable.

A smart contract is an electronic transaction protocol that executes the terms of


a contract. The general objectives are to satisfy common contractual conditions (such
as payment terms, liens, confidentiality, and even enforcement), minimize exceptions
both malicious and accidental, and minimize the need for trusted intermediaries.
Related economic goals include lowering fraud loss, arbitrations and enforcement
costs, and other transaction costs.

Smart contracts as part of the Ethereum deployment block within the


blockchain architecture can be defined as a computerized transaction protocol that
executes the terms of a contract. Smart contracts can be defined as follows: “smart
contracts are digital contracts allowing terms contingent on decentralized consensus
that are tamper-proof and typically self-enforcing through automated execution”.

Smart contracts are self-executing contracts with the terms of the agreement
directly written into code. They run on blockchain networks and automatically execute
actions when predefined conditions are met. Smart contracts eliminate the need for
intermediaries, such as lawyers or brokers and ensure transparency, security, and
efficiency in transactions. They are commonly used in various applications, including
finance, supply chain management, decentralized finance (DeFi), voting systems, and
more.

A smart contract consists of several key components:


 Participants: These are the entities that interact with the contract. Participants
can be people, systems, or other smart contracts.
 State: This is the current status of the contract. The state changes as
participants interact with the contract.
 Functions: These are the operations that the contract can perform. Functions
are triggered by participants and can change the state of the contract.
 Rules: These are the conditions that govern how the contract operates. Rules
are written into the contract's code and must be satisfied for functions to be
executed.

A smart contract's structure can vary depending on its purpose, but most smart
contracts follow a similar structure:
 Preamble: This section includes basic information about the contract, such as
the contract's name and version.
 State Variables: These are the variables that store the contract's state. For
example, in a smart contract for a sale, there might be state variables for the
buyer, seller, price, and item status.
 Functions: This section contains the functions that the contract can perform.
Functions might include actions like initiating the sale, confirming payment,
and delivering the item.
 Modifiers: These are conditions that must be met for functions to be executed.
For example, a function might only be executable if the item status is 'for sale'.
 Events: These are actions that trigger updates to the contract's state. Events are
logged in the blockchain, providing a transparent record of the contract's
activity.

Our proposed System Architecture “Secure Med: Blockchain Enabled


Medicine Record Management System” consists of five such Smart contracts. They
are,
1. Supply Chain Contract (Supplychain.sol)
2. Raw Materials Contract (RawMaterials.sol)
3. Medicine Contract (Medicine.sol)
4. MedicineW_D Contract (MedicineW_D.sol)
5. MedicineD_P Contract (MedicineD_P.sol)
6.2 DESCRIPTION OF EACH SMART CONTRACT:

The Smart contracts are typically written in programming languages such as


Solidity for Ethereum or chain code for Hyperledger Fabric. Here in our project, we
are using Ethereum blockchain. So, we written our contracts using Solidity language.
The file extension for Solidity is ‘.sol’. We also written required Migrations files in
java script with an extension ‘.js’. Fig 6.1 represents the detailed structure of our
project files.

Fig 6.1: Files Hierarchy.

 SupplyChain.sol: This contract is deployed by the Owner of the chain. It


consists of many entities associated with the supply chain, i.e., Owner,
Supplier, Transporter, Manufacturer, Wholesaler, Distributor, Customer. It also
consists of various Solidity events used to communicate with the front end in
real-time. Each function in the contract can only be accessed by its respective
role assigned to it. This is done with the help of "modifiers" in Solidity. Thus,
no entity without a particular role can access a specific function. This helps to
increase the security and accessibility of data stored or queried from the
blockchain.
 RawMaterials.sol: A respective Supplier deploys the Raw Material Contract.
Once a raw material is created physically, it is then added to the chain by the
supplier that created the raw material. While creating a raw material to be
added to the chain, data such as EA (Ethereum Address) of the Supplier, Date
and Time, EA of Transporter, Transaction Contract Address, etc. are requested
from the supplier. It also contains events that can compute the whereabouts of
the package in real-time. The EA of Receiver (Manufacturer) is later updated
based on the event request-response mechanism. It also stores the current
status of the medicine, i.e., which entity currently has the raw material.
 Medicine.sol: The respective manufacturer deploys the Medicine Contract.
Once a medicine is created physically, it is then added to the chain by the
manufacturer that created the medicine. While creating medicine to be added
to the chain, data such as EA (Ethereum Address) of Raw Material used to
create medicine, Date and Time, EA of Transporter, Transaction Contract
Address, etc., is requested from the manufacturer. It also contains events that
can compute the whereabouts of the package in real-time. The EA of
Wholesaler updated later based on the event request-response mechanism. It
also stores the current status of the medicine, i.e., which entity currently has
the package
 MedicineW_D.sol: The respective wholesaler deploys the MedicineW_D
Contract. Once a medicine is reached the wholesaler physically, it is then
added to the chain by the wholesaler. Later it transfers the medicine to the next
entity like distributor using Date and Time, EA of Transporter, EA of
Distributor, Transaction Contract Address, etc., It also creates the sub contract
Id for medicine batch.
 MedicineD_P.sol: The respective distributor deploys the MedicineD_P
Contract. Once a medicine is reached the distributor physically, it is then added
to the chain by the distributor. Later it transfers the medicine to the next entity
like Pharmacy using Date and Time, EA of Transporter, EA of Distributer,
Transaction Contract Address, etc., It also creates the sub contract Id for
medicine batch. Once it reached the Pharmacy, it is then added to the chain by
the Pharmacy. Finally, the medicine batch is ready for the sales. The updating
of medicine status is done by the pharmacy.
 _initial_migrations.js and _deploy_migrations.js: These files are part of the
migration scripts used with the Truffle framework. They help in deploying
smart contracts to the blockchain network in an organized manner. The initial
migrations file may contain setup tasks, while the deploy migrations file is
used for deploying contracts.
 truffle_config.js: This file is the configuration file for the Truffle framework.
It defines settings such as the network configuration, compilers, and plugins
required for testing and deploying the smart contracts. It ensures that the
development environment is properly configured for the project.

Each file in the hierarchy plays a crucial role in the development, deployment, and
testing of the blockchain-enabled medicine record management system, contributing
to its overall functionality and security.
6.3 BLOCKCHAIN IMPLEMENTATION:

Fig 6.2 Process Work Flow


Table 6.1 Description of Process Work Flow

S.No Explanation
1. Owner deploys the smart contracts to the Ethereum Block-chain.
2. The Owner authenticates and registers the entities of the chain.
3. Supplier registers in Supply chain.
4. Manufacturer registers in Supply chain.
5. Wholesaler registers in Supply chain.
6. Distributor registers in Supply chain.
7. Transporter registers in Supply chain.
8. Pharmacy registers in Supply chain.
9. Creates a new Raw package by Supplier in SupplyChain.sol
10. Raw Material Contract (RawMaterial.sol) is deployed for the newly created raw
material
11. Package Status is checked and Pick Package by Associate Transporter from
Supplier.
12. Load Consignment is initiated to transport from one location to another and check
for transporter type (=1)
13. Deliver the Raw Material Package to Manufacturer.
14. Verify the source of Drug.
15. Medicine Contract (Medicine. Sol) is deployed for the newly created medicine
16. Package Status is checked and picked by Associate Transporter from
Manufacturer.
17. Check for transporter type (=2).
18. Deliver the Medicine Batch to Wholesaler.
19. Verify the source of drug and transfer ownership of drug to Wholesaler.
20. Create a Subcontract (MedicineW_D.sol) for Medicine Transaction.
21. From Wholesaler, pick the Medicine Batch by Associated Transporter.
22. Check for transporter type (=3).
23. Deliver the Medicine Batch to Distributor.
24. Verify the source of drug and transfer ownership of drug to Distributor.
25. Create a Subcontract (MedicineD_P.sol) for Medicine Transaction.
26. From Distributor, pick the Medicine Batch by Associated Transporter.
27. Check for transporter type (=4).
28. Deliver the Medicine Batch to Pharmacy.
29. Verifies the source of the medicine through a temporary node
The Fig 6.2 represents the complete process of Supplychain work flow of our
medicine record management system. It comprises of all the Stakeholders from
Supplier to Pharmacy including Customer or Patient alongside the owner also referred
as Regulatory Authority of Blockchain. It also represents the interaction of
SupplyChain Smart contract with the stakeholders and other smart contracts like
RawMaterials and Medicine. The Patient can access the medicine data from the
Blockchain network. The Table 6.1 describes the entire work flow step by step in
detail.

Whole Table 6.1 focuses on the process, that begins with the owner deploying
smart contracts to the Ethereum blockchain and authenticating and registering entities
in the chain, including Suppliers, Manufacturers, Wholesalers, Distributors,
Transporters, and Pharmacies. The Supplier creates a new Raw package, which
triggers the deployment of the Raw Material Contract. Then, an associate Transporter
picks up the package and delivers it to the Manufacturer. After verifying the source of
the Raw material, the Medicine Contract is deployed, and a similar process follows for
the Medicine batch, with it being delivered from the Manufacturer to the Wholesaler
and then to the Distributor. At each step, ownership of the drugs is transferred
accordingly. Finally, the Medicine batch reaches the Pharmacy, where its source is
verified through a temporary node.

Implementation in RemixIDE:

Remix IDE is a web-based Integrated Development Environment (IDE)


primarily used for developing, testing, and deploying smart contracts on blockchain
platforms, particularly Ethereum. It provides a user-friendly interface that allows
developers to write, compile, debug, and deploy smart contracts directly from their
web browser. It offers features like syntax highlighting, code autocompletion, and
integrated debugging tools, streamlining the smart contract development process.
Remix also includes built-in plugins and extensions for enhanced functionality,
making it a popular choice among blockchain developers, both beginners and
experienced.

Fig 6.3 represents the successful deployment of SupplyChain smart contract in


RemixIDE, Meanwhile the Fig 6.4 shows the deployment of all other smart contracts.
We can observe the detailed execution of each smart contract separately from Fig 6.5
to Fig 6.9 to analysis the Gas used and also to estimate the cost for those successful
deployment.

Fig-6.3: Successful Execution of Smart Contracts

Fig-6.4: Successful Deployment of Smart Contracts


Fig-6.5: Supplychain.sol

Fig-6.6: RawMaterial.sol

Fig-6.7: Medicine.sol

Fig-6.8: MedicineW_D.sol
Fig-6.9: MedicineD_P.sol

Implementation using Truffle suite:

Truffle Suite is a comprehensive development framework for Ethereum smart


contracts, simplifying tasks like testing, compiling, and deploying. Its importance lies
in providing developers a cohesive toolkit for efficient and standardized blockchain
development. To enhance gas efficiency, we attempted deploying using Truffle within
the console environment, coupled with Ganache.

Fig-6.10: Compiling the Smart Contracts


Fig-6.11: Deploying initial_migrations.js

Fig-6.12: Deploying deploy_contracts.js

Fig-6.13: Deploying Supplychain.sol, RawMaterial.sol


Fig-6.14: Deploying Mediicne.sol, MedicineW_D.sol

Fig-6.15: Deploying MedicineD_P.sol

Fig-6.16: Creating instance of Smart Contract

Fig-6.17: Calling Owner


Fig-6.18: Register User

Fig-6.19: Moving to respective Stakeholder


Fig-6.20: Manufacturing Medicine

Fig-6.21: Transporting Medicine


Fig-6.22: Updating Medicine Status

Ganache is a tool, part of the truffle suite, that creates a private Ethereum
based blockchain on a local system and can be used for testing contracts and
development purposes. A workspace can be created for a project by linking the
configuration file of the truffle project. By default, it creates 10 accounts with 100
ETH each and these accounts can be used to make transactions on the blockchain
network.

Fig-6.23: Ganache Accounts


Fig-6.24: Deployed Smart Contracts

Fig-6.25: Supply chain Contract


Fig-6.26: Ganache Block Structure

We can clearly observe our 10 fake Ethereum accounts with 100 ETH each in
Fig 6.23, Meanwhile Fig 6.24 represents the successful deployments of each smart
contract with the addresses in the local blockchain ganache. Fig 6.26 describes the
structure of the block in the blockchain, we can observe the transaction in that block
with the complete details like from address, created contract address, Transaction hash
and Block hash. We also encounter the Gas used, Gas limit value and block Mined
time. While Fig 6.25 represents the structure of the SupplyChain contract with the
Storage of hash maps refers to mapping function to store the details of the medicine
record management.
CHAPTER 7

TESTING

7.1 TESTING STRATEGY:

Smart contract testing is the process of verifying that the code of a smart
contract works as expected. Testing is useful for checking if a particular smart contract
satisfies requirements for reliability, usability, and security.

Although approaches vary, most testing methods require executing a smart


contract with a small sample of the data it is expected to handle. If the contract
produces correct results for sample data, it is assumed to be functioning properly.
Most testing tools provide resources for writing and executing test cases to check if a
contracts execution matches the expected results.

Importance of Testing a Smart Contract

Testing Smart Contracts is a critical and significant process in the development


phase since it involves deploying it on the network every time and determining
whether it works as expected or whether it needs some fine-tuning to enhance and
satisfy its requirements.

 Helps estimating gas fees: As deploying smart contracts on the Ethereum


network would consume some block of space on the network, which would
necessitate the payment of some gas fees in order to mine on the network. Gas
Fees may seem to a small amount but it’s worth a lot, thus testing becomes an
important task.
 Helps to detect errors: Smart contracts frequently control high-value
financial assets, tiny programming errors can result in significant losses for
users. However, detailed testing can assist in detecting errors and loopholes in
smart contract code early on and fixing them before publishing on Mainnet.

METHODS FOR TESTING SMART CONTRACTS

Methods for testing Ethereum smart contracts fall under two broad categories
automated testing and manual testing. Automated testing and manual testing offer
unique benefits and tradeoffs, but we can combine both to create a robust plan for
analyzing our contracts.

 Automated Testing: Automated testing uses tools that automatically check a


smart contracts code for errors in execution. The benefit of automated testing
comes from using scripts(writing different test cases) to guide the evaluation
of contract functionalities. Scripted tests can be scheduled to run repeatedly
with minimal human intervention, making automated testing more efficient
than manual approaches to testing. Automated testing is particularly useful
when tests are repetitive and time-consuming; difficult to carry out manually;
susceptible to human error; or involve evaluating critical contract functions.
However, automated testing can have drawbacks such as missing specific
vulnerabilities and producing false positives. Hence, pairing automated testing
with manual testing for smart contracts is ideal.
 Unit Testing: Unit testing evaluates contract functions separately and checks
that each component works correctly. Good unit tests should be simple, quick
to run and provide a clear idea of what went wrong if tests fail. Unit tests are
useful for checking that functions return expected values and that contract
storage is updated properly after function execution. Moreover, running unit
tests after making changes to a contracts codebase ensures adding new logic
does not introduce errors.
 Integration Testing: While unit testing debugs contract functions in isolation,
integration tests evaluate the components of a smart contract as a whole.
Integration testing can detect issues arising from cross-contract calls or
interactions between different functions in the same smart contract. For
example, integration tests can help check if things like inheritance and
dependency injection are functioning properly.
 Manual Testing: When it comes to smart contract testing, manual testing
typically takes place in the later stages of the development cycle, following
automated tests. This form of testing examines the smart contract as a fully
integrated product, ensuring that it performs according to the specified
technical requirements. Manual testing is human-aided and involves executing
each test case in our test suite one after the other when analyzing a smart
contracts correctness. This is unlike automated testing where we can
simultaneously run multiple isolated tests on a contract and get a report
showing all failing and passing tests.

Testing Tools and Libraries:

Here are the tools and libraries those we used for the Unit Testing of our smart
contracts.

 Solidity-Coverage: A code coverage tool specifically designed for Solidity


smart contracts.
 Remix Tests: A tool integrated within the Remix IDE that allows you to write
and run test cases for Solidity smart contracts.
 Truffle Tests: An automated testing framework that simplifies the process of
testing your contracts.

7.2 TEST CASES:

The purpose of test cases in the deployment of smart contracts is to ensure that
the contracts function as intended and meet the specified requirements before being
deployed on the blockchain network. Specifically in the context of smart contracts,
test cases serve several critical purposes like Functional Verification, Security
Assurance, Gas Optimization.

Test cases play a crucial role in ensuring the quality, security, and reliability of
smart contracts before their deployment on the blockchain network. They help
mitigate risks, improve trust in the contract's performance, also contribute to the
successful deployment of our smart contracts and overall success of our proposed
system Secure Med: Blockchain Enabled Medicine Record Management System
application.

Our application comprises of owner, seven stakeholders and five smart


contracts having numerous functions results in a wide range of various test cases.
Table 7.1 describes such Test Cases with detailed insights and outcomes validating
upon all the functions in our smart contracts.
Table 7.1 Test Cases for Micro-Investments

Test
Test Case Expected
S.NO Role Description Status
Name Outcome
(P/F)
Test the adding
of new user Successful
1 registerUser Owner with specific Registration of P
role to the New User
Blockchain
Test the
Successful
2 revokeRole Owner revoking of P
Revoke of User
existing user
Test the reassign Successful
of addition of
3 reassignRole Owner existing/revoked changes to the P
user with existing/revoked
specific changes User
Test the
Successful
Obtaining of
4 getUserInfo Users Obtaining of P
registered User
User details
details
Test the count
Successful
of registered
5 getUsersCount Users Obtaining of P
Users in the
User Count
Blockchain
Test the
Successful
Creation of the
Creation of Raw
6 createRawPackage Supplier Raw Materials P
Materials
Package for
Package
medicine
Test the no.of
Successful
Packages
7 packagesCountS Supplier Obtaining of P
created at
Packages Count
supplier
Test the Successful
Transportation Transportation
of Consignment of Consignment
8 loadConsignment Transporter P
from specific from specified
sender to Sender to
specific receiver Receiver
9 rawPackage Manufacturer Test the Successful P
Received collection of Conformation
Raw Materials of Received
at Manufacturer Package
Test the no.of Successful
Packages Obtaining of
10 packagesCountM Manufacturer P
received at received
Manufacturer Packages Count
Test the
Successful
Manufacture of
Manufacture of
11 manufactureMedicine Manufacturer new Medicine P
New Medicine
batch at
Batch
Manufacturer
Test the no.of Successful
Medicine Obtaining of
12 batchesCountM Manufacturer P
Batches created Medicine
at Manufacturer Batches Count
Test the Successful
Medicine collection of Conformation
13 Wholesaler P
receivedAtW Medicine batch of Received
at Wholesaler Medicine batch
Test the
Successful
Transferring of
Transfer Transportation
14 Wholesaler Medicine batch P
medicineWtoD of Medicine
to Distributor by
batch
Transporter
Test the no.of
Successful
Batches
Obtaining of
15 batchesCountWD Wholesaler Transferred to P
transferred
Distributor from
Batches Count
Wholesaler
Test the
Obtaining of Successful
Sub Contract ID Obtaining of
16 getSubContractWD Wholesaler P
between Sub Contract
Wholesaler and WD ID
Distributor
Test the Successful
Medicine collection of Conformation
17 Distributor P
receivedAtD Medicine batch of Received
at Distributor Medicine batch
18 Transfer Distributor Test the Successful P
medicineDtoP Transferring of Transportation
Medicine batch of Medicine
to Pharma by batch
Transporter
Test the no.of
Successful
Batches
Obtaining of
19 batchesCountDP Distributor Transferred to P
transferred
Pharma from
Batches Count
Distributor
Test the
Obtaining of Successful
Sub Contract ID Obtaining of
20 getSubContractDP Distributor P
between Sub Contract
Wholesaler and DP ID
Distributor
Test the Successful
Medicine collection of Conformation
21 Pharma P
receivedAtPharma Medicine batch of Received
at Pharma Medicine batch
Successful
Test the total
Obtaining of
no.of Medicines
22 batchesCountP Pharma received P
batches received
Medicine
at Pharma
batches Count
Test the
Obtaining of Successful
Medicine record Obtaining of
23 getMedicineInfo Patient/Users details from Medicine record P
Supplier to details from the
Pharma in the Blockchain
Blockchain
Test the
Updating of Successful
Medicine batch Updating of
Update
24 Pharma to specific Medicine Status P
MedicineStatus
Status like details in the
Sold/Expired to Blockchain
the Blockchain
CHAPTER 8

RESULTS

Experimental results of Smart Contract Deployment:


Smart Contracts have been implemented and deployed using the Remix IDE
platform. The contracts themselves, along with the associated gas costs for deploying
them, are displayed below. This suggests that within Remix IDE, we have created
contracts, pieces of code that automatically execute predefined actions when certain
conditions are met and have deployed them onto a blockchain network. Gas costs refer
to the computational fees required to perform actions on a blockchain network, such
as deploying contracts, executing transactions, or running smart contract functions. By
displaying the contracts and their associated gas costs, developers can assess the
efficiency and feasibility of their contracts before deploying them onto the blockchain.

Table-8.1: Cost of Smart Contracts


Contract Gas Used Actual Cost ETH
Supply Chain 6135324 0.018405972
Raw Materials 859640 0.002578920
Medicine 1337217 0.004011651
MedicineW_D 468220 0.001404660
MedicineD_P 468206 0.001404618
Total 9268607 0.027805821 ETH

Fig-8.1: Total Gas Used for a Drug movement in Supply chain


Therefore, the Total Gas Cost required in the Supply chain is 0.027805821 ETH
(27805821 Wei).
In order to optimize gas consumption and efficiency, we endeavoured to
deploy our smart contracts using the Truffle framework within the VSCode
development environment, combined with Ganache for local blockchain simulation.
This approach allows us to leverage the capabilities of Truffle, a development
framework for Ethereum, to streamline the deployment process and potentially reduce
gas costs associated with deploying smart contracts. Ganache serves as a local
blockchain emulator, enabling us to test and debug our contracts in a controlled
environment before deploying them onto the live Ethereum network. By utilizing
these tools together, we aim to enhance the overall efficiency and performance of our
smart contract deployment process.

Table-8.2: Cost of Smart Contracts deployed using Truffle


Contract Gas Used Actual Cost ETH
Supply Chain 5054069 0.01605
Raw Materials 712985 0.00229
Medicine 1056456 0.003325
MedicineW_D 414566 0.00128
MedicineD_P 414544 0.001255
Total 7652620 0.024212 ETH

Fig-8.2: Total Gas Used for a Drug movement in Supply chain


Therefore, the Total Gas Cost required in the Supply chain is 0.024212 ETH
(24212000 Wei)

Fig-8.3: Comparison of Gas used

Fig-8.4: Comparison of Actual Gas Cost in ETH

By deploying our smart contracts using the Truffle environment, we managed


to reduce gas costs by 13.82%. This optimization underscores the effectiveness of
utilizing Truffle for enhancing efficiency in deploying smart contracts.
CHAPTER 9
CONCLUSION AND FUTURE SCOPE

9.1 CONCLUSION:

This project presents a thorough plan for resolving contemporary problems in


the pharmaceutical supply chain, with a focus on leveraging blockchain technology to
increase transparency and empower stakeholders. The study predicts substantial
advancements for the pharmaceutical sector as well as the larger healthcare system.
The approach seamlessly blends blockchain technology bringing about a
transformative shift in the medicine supply chain. It adeptly tackles challenges related
to transparency and assurance in quality. Remix IDE facilitates streamlined smart
contract development, Solidity serves as the programming language, and Truffle
expedites testing and deployment. Their collaborative prowess optimizes efficiency,
establishing a secure, transparent, and tamper-resistant medicine supply chain. This
achievement fosters trust among stakeholders, signifying a notable leap in the
operational integrity of the pharmaceutical industry.

9.2 FUTURE SCOPE:

Our study can be expanded further in order to keep track of medicine


inventory in real time through the blockchain data comprising of the number of units
of a particular medicine dispatched each day. Through analysis on the various drugs
and the assessment of their demand supply mapping along with the application of
predictive analytics can help us identify the medicines which are fast moving and have
a high market demand and those which have a low market demand. This can help us
minimize inventory. Additionally, the barcode scanner which can be accessed through
the distributor phone can also have the face recognition feature through which we can
re-check that the drug is with the designated distributor, this could lead to more
efficient distribution channels and better patient outcomes. Overall, the future of
blockchain-based pharmacy supply chains looks bright, with the potential to bring
significant benefits to patients, healthcare providers, and the pharmaceutical industry
as a whole.
REFERENCES & BIBLIOGRAPHY

[1] Bazel, M. A., Mohammed, F., & Ahmed, M. (2021, August). Blockchain
technology in healthcare big data management: Benefits, applications and challenges.
In 2021 1st International Conference on Emerging Smart Technologies and
Applications (eSmarTA) (pp. 1-8). IEEE.

[2] Kordestani, A., Oghazi, P., & Mostaghel, R. (2023). Smart contract diffusion in
the pharmaceutical blockchain: the battle of counterfeit drugs. Journal of Business
Research, 158, 113646.

[3] Gupta, S., Malhotra, V., & Singh, S. N. (2020). Securing IoT-driven remote
healthcare data through blockchain. In Advances in Data and Information Sciences:
Proceedings of ICDIS 2019 (pp. 47-56). Springer Singapore.

[4] Chopra, S., & Meindl, P. (2007). Supply chain management. Strategy, planning
& operation (pp. 265-275). Gabler.

[5] Helo, P., & Shamsuzzoha, A. H. M. (2020). Real-time supply chain—A


blockchain architecture for project deliveries. Robotics and Computer-Integrated
Manufacturing, 63, 101909.

[6] Alshehhi, R., Marpu, P.R., Woon, W.L., Mura, M.D., 2017. Simultaneous
extraction of roads and buildings in remote sensing imagery with convolutional neural
networks. ISPRS J. Photogramm. Remote Sens. 130, 139–149.

[7] S. Tanwar, K. Parekh, and R. Evans, “Blockchain-based Electronic Healthcare


Record System for healthcare 4.0 applications,” Journal of Information Security and
Applications, vol. 50, p. 102407, 2020.

[8] H. Han, M. Huang, Y. Zhang, and U. A. Bhatti, “An architecture of secure


health information storage system based on Blockchain technology,” Cloud
Computing and Security, pp. 578–588, 2018. doi:10.1007/978-3-030-00009-752

[9] A. Zhang and X. Lin, “Towards secure and privacy-preserving data sharing in
e-health systems via consortium blockchain,” Journal of Medical Systems, vol. 42, no.
8, 2018. doi:10.1007/s10916-018-0995-5

[10] X. Zheng, R. R. Mukkamala, R. Vatrapu, and J. Ordieres-Mere, “Blockchain-


based personal health data sharing system using cloud storage,” 2018 IEEE 20th
International Conference on e-Health Networking, Applications and Services
(Healthcom), 2018. doi:10.1109/healthcom.2018.8531125

[11] S. Wang, D. Zhang, and Y. Zhang, “Blockchain-based personal health records


sharing scheme with data integrity verifiable,” IEEE Access, vol. 7, pp.102887–
102901, 2019. doi:10.1109/access.2019.293153150

[12] Q. Xia, E. Sifah, A. Smahi, S. Amofa, and X. Zhang, “BBDS:Blockchain-


based data sharing for electronic medical records in Cloud Environments,”
Information, vol. 8, no. 2, p. 44, 2017. doi:10.3390/info8020044

[13] A. Shahnaz, U. Qamar, and A. Khalid, “Using blockchain for Electronic


Health Records,”IEEE Access,vol. 7, pp. 147782–147795,
2019.doi:10.1109/access.2019.2946373

[14] A. Buzachis, A. Celesti, M. Fazio, and M. Villari, “On the design of a


blockchain-as-a-service-based health information exchange (BaaS-HIE) system for
patient monitoring,” 2019 IEEE Symposium on Computers and Communications
(ISCC), 2019. doi:10.1109/iscc47284.2019.8969718

[15] A. Azaria, A. Ekblaw, T. Vieira, and A. Lippman, “MedRec: Using blockchain


for Medical Data Access and permission management,” 2016 2nd International
Conference on Open and Big Data (OBD), 2016. doi:10.1109/obd.2016.11

[16] K. N. Griggs et al., “Healthcare blockchain system using smart contracts for
secure Automated Remote Patient Monitoring,” Journal of Medical Systems, vol. 42,
no. 7, 2018. doi:10.1007/s10916-018-0982-x

[17] G. G. Dagher, J. Mohler, M. Milojkovic, and P. B. Marella, “Ancile: Privacy-


preserving framework for access control and interoperability of electronic health
records using Blockchain Technology,” Sustainable Cities and Society, vol. 39, pp.
283–297, 2018. doi:10.1016/j.scs.2018.02.014
APPENDIX A

Full Code:

SupplyChain.sol:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
import './RawMaterials.sol';
import './Medicine.sol';
import './MedicineW_D.sol';
import './MedicineD_P.sol';
// Title Secure Med : Blockchain Enabled Medicine Record Management System
// Author : Chenikala Rakesh
contract SupplyChain {
address public Owner;
constructor () {
Owner = msg.sender;
}
/********* Owner Section *********/
modifier onlyOwner() {
require(
msg.sender == Owner,
"Only owner can call this function."
);
_;
}
enum roles {
norole,
supplier,
transporter,
manufacturer,
wholesaler,
Distributor,
pharma,
revoke
}
//////////////// Events ////////////////////
event UserRegister(address indexed EthAddress, string Name);
event UserRoleRevoked(address indexed EthAddress, string Name, uint Role);
event UserRoleReassign(address indexed EthAddress, string Name, uint Role);
struct UserInfo {
string name;
string location;
address ethAddress;
roles role;
}
mapping(address => UserInfo) public UsersDetails;
address [] users;
// Register New user by Owner
function registerUser(
address EthAddress,
string memory Name,
string memory Location,
uint Role
) public
onlyOwner
{
require(UsersDetails[EthAddress].role == roles.norole, "User Already registered");
UsersDetails[EthAddress].name = Name;
UsersDetails[EthAddress].location = Location;
UsersDetails[EthAddress].ethAddress = EthAddress;
UsersDetails[EthAddress].role = roles(Role);
users.push(EthAddress);
emit UserRegister(EthAddress, Name);
}
function revokeRole(address userAddress) public onlyOwner {
require(UsersDetails[userAddress].role != roles.norole, "User not registered");
emit UserRoleRevoked(userAddress,
UsersDetails[userAddress].name,uint(UsersDetails[userAddress].role));
UsersDetails[userAddress].role = roles(7);
}
function reassignRole(address userAddress, uint Role) public onlyOwner {
require(UsersDetails[userAddress].role != roles.norole, "User not registered");
UsersDetails[userAddress].role = roles(Role);
emit UserRoleReassign(userAddress,
UsersDetails[userAddress].name,uint(UsersDetails[userAddress].role));
}
/********* User Section *********/
// Get User Information/ Profile
function getUserInfo(address User) public view returns(
string memory name,
string memory location,
address ethAddress,
roles role
){
require(UsersDetails[User].role != roles.norole, "User not registered");
return (
UsersDetails[User].name,
UsersDetails[User].location,
UsersDetails[User].ethAddress,
UsersDetails[User].role);
}
function getUsersCount() public view returns(uint count){
return users.length;
}
/********* Supplier Section *********/
mapping(address => address[]) supplierRawProductInfo;
event RawSupplyInit(
address indexed ProductID,
address indexed Supplier,
address Shipper,
address indexed Receiver
);
// Create new raw package by Supplier
function createRawPackage(
string memory Des,
string memory FN,
string memory Loc,
uint Quant,
address Shpr,
address Rcvr
) public {
require(
UsersDetails[msg.sender].role == roles.supplier,
"Only Supplier Can call this function "
);
RawMaterials rawData = new RawMaterials(
msg.sender,
Des,
FN,
Loc,
Quant,
Shpr,
Rcvr
);
supplierRawProductInfo[msg.sender].push(address(rawData));
emit RawSupplyInit(address(rawData), msg.sender, Shpr, Rcvr);
}
function getPackagesCountS() public view returns (uint count){
require(
UsersDetails[msg.sender].role == roles.supplier,
"Only Supplier Can call this function "
);
return supplierRawProductInfo[msg.sender].length;
}
/********* Transporter Section *********/
// Load Consingment fot transport one location to another.
function loadConsingment(
address pid, //Package or Batch ID
uint transportertype,
address cid
) public {
require(
UsersDetails[msg.sender].role == roles.transporter,
"Only Transporter can call this function"
);
require(
transportertype > 0,
"Transporter Type must be define"
);
if(transportertype == 1) { // Supplier to Manufacturer
RawMaterials(pid).pickPackage(msg.sender);
} else if(transportertype == 2) { // Manufacturer to Wholesaler
Medicine(pid).pickPackage(msg.sender);
} else if(transportertype == 3) { // Wholesaler to Distributor
MedicineW_D(cid).pickWD(pid,msg.sender);
} else if(transportertype == 4) { // Distrubuter to Pharma
MedicineD_P(cid).pickDP(pid,msg.sender);
}
}
/********* Manufacturer Section *********/
mapping(address => address[]) RawPackagesAtManufacturer;
function rawPackageReceived(
address pid
) public {
require(
UsersDetails[msg.sender].role == roles.manufacturer,
"Only manufacturer can call this function"
);
RawMaterials(pid).receivedPackage(msg.sender);
RawPackagesAtManufacturer[msg.sender].push(pid);
}
function getPackagesCountM() public view returns(uint count){
require(
UsersDetails[msg.sender].role == roles.manufacturer,
"Only manufacturer can call this function"
);
return RawPackagesAtManufacturer[msg.sender].length;
}
mapping(address => address[]) ManufactureredMedicineBatches;
event MedicineNewBatch(
address indexed BatchId,
address indexed Manufacturer,
address shipper,
address indexed Receiver
);
// Create Medicine Batch
function manufacturMedicine(
string memory Des,
string memory RM,
uint Quant,
address Shpr,
address Rcvr
//uint RcvrType
) public returns (string memory){
require(
UsersDetails[msg.sender].role == roles.manufacturer,
"Only manufacturer can call this function"
);
Medicine m = new Medicine(
msg.sender,
Des,
RM,
Quant,
Shpr,
Rcvr
);
ManufactureredMedicineBatches[msg.sender].push(address(m));
emit MedicineNewBatch(address(m), msg.sender, Shpr, Rcvr);
return "Medicine created!";
}
function getBatchesCountM() public view returns (uint count){
require(
UsersDetails[msg.sender].role == roles.manufacturer,
"Only Manufacturer Can call this function."
);
return ManufactureredMedicineBatches[msg.sender].length;
}
/********* Wholesaler Section *********/
mapping(address => address[]) MedicineBatchesAtWholesaler;
// Medicine Batch Received
function MedicineReceivedAtW(
address batchid,
address cid
) public {
require(
UsersDetails[msg.sender].role == roles.wholesaler,
"Only Wholesaler can call this function"
);
MedicineBatchesAtWholesaler[msg.sender].push(batchid);
}
mapping(address => address[]) MedicineWtoD;
mapping(address => address) MedicineWtoDTxContract;
function transferMedicineWtoD(
address BatchID,
address Shipper,
address Receiver
) public {
require(
UsersDetails[msg.sender].role == roles.wholesaler &&
msg.sender == Medicine(BatchID).getWDP()[0],
"Only Wholesaler can call this function"
);
MedicineW_D wd = new MedicineW_D(
BatchID,
msg.sender,
Shipper,
Receiver
);
MedicineWtoD[msg.sender].push(address(wd));
MedicineWtoDTxContract[BatchID] = address(wd);
}
function getBatchesCountWD() public view returns (uint count){
require(
UsersDetails[msg.sender].role == roles.wholesaler,
"Only Wholesaler Can call this function."
);
return MedicineWtoD[msg.sender].length;
}
// Get Sub Contract ID of Medicine Batch Transfer in between Wholesaler to Distributor
function getSubContractWD(address BatchID) public view returns (address
SubContractWD) {
return MedicineWtoDTxContract[BatchID];
}
/********* Distributor Section *********/
mapping(address => address[]) MedicineBatchAtDistributor;
// Medicine Batch Recieved
function MedicineReceivedAtD(
address batchid,
address cid
) public {
require(
UsersDetails[msg.sender].role == roles.Distributor,
"Only Distributor Can call this function."
);
MedicineW_D(cid).recieveWD(batchid, msg.sender);
MedicineBatchAtDistributor[msg.sender].push(batchid);
}
mapping(address => address[]) MedicineDtoP;
mapping(address => address) MedicineDtoPTxContract;
// Transfer Medicine BatchID in between Distributor to Pharma
function transferMedicineDtoP(
address BatchID,
address Shipper,
address Receiver
) public {
require(
UsersDetails[msg.sender].role == roles.Distributor &&
msg.sender == Medicine(BatchID).getWDP()[1],
"Only Distributor can call this function"
);
MedicineD_P dp = new MedicineD_P(
BatchID,
msg.sender,
Shipper,
Receiver
);
MedicineDtoP[msg.sender].push(address(dp));
MedicineDtoPTxContract[BatchID] = address(dp);
}
function getBatchesCountDP() public view returns (uint count){
require(
UsersDetails[msg.sender].role == roles.Distributor,
"Only Distributor Can call this function."
);
return MedicineDtoP[msg.sender].length;
}
// Get SubContract ID of Medicine Batch Transfer in between Distributor to Pharma
function getSubContractDP(address BatchID) public view returns (address SubContractDP)
{

return MedicineDtoPTxContract[BatchID];
}
/********* Pharma Section *********/
mapping(address => address[]) MedicineBatchAtPharma;
// Medicine Batch Recieved
function MedicineReceivedAtPharma(
address batchid,
address cid
) public {
require(
UsersDetails[msg.sender].role == roles.pharma,
"Only Pharma Can call this function."
);
MedicineD_P(cid).recieveDP(batchid, msg.sender);
MedicineBatchAtPharma[msg.sender].push(batchid);
sale[batchid] = saleStatus(1);
}
function getBatchesCountP() public view returns(uint count){
require(
UsersDetails[msg.sender].role == roles.pharma,
"Only Pharma or current owner of package can call this function"
);
return MedicineBatchAtPharma[msg.sender].length;
}
enum saleStatus {
notfound,
atpharma,
sold,
expire,
damaged
}
mapping(address => saleStatus) sale;
event MedicineStatus(
address BatchID,
address indexed Pharma,
string status
);
/// a helper function to convert `saleStatus` to a string:
function getStatusString(saleStatus Status) internal pure returns (string memory) {
if (Status == saleStatus.notfound) return "Medicine Batch is Not Found";
if (Status == saleStatus.atpharma) return "Medicine Batch is At Pharma";
if (Status == saleStatus.sold) return "Medicine Batch is Sold";
if (Status == saleStatus.expire) return "Medicine Batch is Expired";
if (Status == saleStatus.damaged) return "Medicine Batch is Damaged";
revert("Invalid status");
}
// Get Medicine Batch status
function getMedicineInfo(
address BatchID
) public
view
returns(
string memory Status
){
return getStatusString(sale[BatchID]);
}
// Update Medicine Batch status
function updateMedicineStatus(
address BatchID,
uint Status
) public {
require(
UsersDetails[msg.sender].role == roles.pharma &&
msg.sender == Medicine(BatchID).getWDP()[2],
"Only Pharma or current owner of package can call this function"
);
require(sale[BatchID] == saleStatus(1), "Medicine Not Found at Pharma");
sale[BatchID] = saleStatus(Status);
emit MedicineStatus(BatchID, msg.sender, getStatusString(sale[BatchID]));
}
}
Deploy_Contracts.js:

var SupplyChain = artifacts.require('SupplyChain');


var RawMaterials = artifacts.require('RawMaterials');
var Medicine = artifacts.require('Medicine');
var MedicineW_D = artifacts.require('MedicineW_D');
var MedicineD_P = artifacts.require('MedicineD_P');

module.exports = function(deployer) {
deployer.deploy(SupplyChain);
deployer.deploy(RawMaterials);
deployer.deploy(Medicine);
deployer.deploy(MedicineW_D);
deployer.deploy(MedicineD_P);
};

Truffle_Config.js:

module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*",
gas: 30000000,
from: '0x84AED190Dfdd1C3D50bCC10298fd39773FAb4AA8',
},
},
compilers: {
solc: {
version: "0.8.21",
docker: true,
settings: {
optimizer: {
enabled: true,
runs: 200
}
}
}
}
}

You might also like