1. Trang chủ
  2. » Luận Văn - Báo Cáo

Luận văn application of blockchain technology in verification of agriculture products identity

116 1 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 116
Dung lượng 5,35 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Cấu trúc

  • 1.1 Problem statement (19)
  • 1.2 Goal (20)
  • 1.3 Method (21)
  • 1.4 Report Layout (22)
  • 2.1 Provenance (23)
  • 2.2 AgriDigital (23)
  • 2.3 IBM Blockchain (24)
  • 3.1 Background knowledge (25)
    • 3.1.1 Blockchain (25)
    • 3.1.2 Smart contracts (25)
  • 3.2 Technology (25)
    • 3.2.1 Website application development (26)
    • 3.2.2 Mobile application development (26)
    • 3.2.3 Front-end development (27)
    • 3.2.4 Front-end programming (27)
    • 3.2.5 Hyperledger Fabric (27)
    • 3.2.6 Blockchain solution (28)
    • 3.2.7 IPFS (28)
    • 3.2.8 The Graph (29)
  • 4.1 Stakeholders (31)
    • 4.1.1 The production units (31)
    • 4.1.2 The processing units (31)
    • 4.1.3 The distribution units (31)
    • 4.1.4 The retailers (31)
    • 4.1.5 Consumers (32)
  • 4.2 System requirements (32)
    • 4.2.1 Functional requirements (32)
    • 4.2.2 Non-Functional requirements (33)
  • 5.1 Usecase design (34)
    • 5.1.1 System usecase diagram (34)
    • 5.1.2 Authenticate (35)
    • 5.1.3 Register (36)
    • 5.1.4 Add wallet for authenticate (37)
    • 5.1.5 Create and update business information (38)
    • 5.1.6 Update product’s diary (39)
    • 5.1.7 Register product (40)
    • 5.1.8 Verify product (41)
    • 5.1.9 Build contract (42)
  • 5.2 Activity diagram (43)
    • 5.2.1 Authenticate (43)
    • 5.2.2 Register (44)
    • 5.2.3 Add wallet for authenticate (45)
    • 5.2.4 Create and update business information (46)
    • 5.2.5 Update product’s diary (47)
    • 5.2.6 Register product (48)
    • 5.2.7 Verify product (49)
    • 5.2.8 Build contract (50)
  • 5.3 Architecture design (51)
    • 5.3.1 Build private contract Hyperledger Fabric (51)
    • 5.3.2 Build public Blockchain for recording diary of products (52)
  • 5.4 Class diagram (54)
    • 5.4.1 Product’s diary (54)
    • 5.4.2 Business’s Blockchain interaction (55)
    • 5.4.3 Write contracts (56)
    • 5.4.4 View, controller and database (56)
  • 5.5 Sequence diagram (57)
    • 5.5.1 Login Module (57)
    • 5.5.2 Verify the JWT (57)
    • 5.5.3 Update Product (58)
    • 5.5.4 View Product (59)
  • 5.6 Centralized database (60)
  • 6.1 Log out of all devices features (61)
    • 6.1.1 Introduction to Redis (61)
    • 6.1.2 Comparing Redis with Other Databases - Differences from RDBMS (relational database management system) (62)
    • 6.1.3 Comparing Redis with Other Databases - Differences from Other (63)
    • 6.1.4 Implementation (63)
  • 6.2 Using hash function to hash the passwords (64)
  • 6.3 The problem of keeping private_key for users (65)
    • 6.3.1 Key rotation (65)
    • 6.3.2 Password-based (66)
  • 7.1 Infrastructure (67)
  • 7.2 Smart contract (67)
    • 7.2.1 Usage and Deployment (67)
    • 7.2.2 Enums and Structs (67)
    • 7.2.3 Constructor and Modifiers (67)
    • 7.2.4 Mappings (68)
    • 7.2.5 Events (68)
    • 7.2.6 Functions (68)
  • 7.3 The Graph (69)
    • 7.3.1 Design Subgraph (69)
  • 7.4 API (73)
    • 7.4.1 Authentication web 2.0 (73)
    • 7.4.2 Smartcontract Backend (78)
  • 7.5 Redis (79)
    • 7.5.1 Redis Cloud (79)
    • 7.5.2 System Integration (81)
  • 7.6 Security (83)
    • 7.6.1 Password hashing (83)
    • 7.6.2 The private key encryption (84)
  • 7.7 IPFS (85)
  • 7.8 HyperLedger Fabric (87)
    • 7.8.1 Implementation (87)
    • 7.8.2 Create artifacts and running the network (88)
    • 7.8.3 Chaincode implementation and deploy (91)
    • 7.8.4 Fabric SDK in Nodejs (93)
    • 7.8.5 CouchDB UI (96)
  • 8.1 Authenticate (98)
  • 8.2 Sign in with wallet address (99)
  • 8.3 View and Update business information (100)
  • 8.4 Register new products (102)
  • 8.5 View and Update product diary (103)
    • 8.5.1 View product (103)
    • 8.5.2 Update product diary (104)
  • 8.6 View history of transactions (105)
  • 8.7 Verify product by QR code (106)
  • 9.1 Contribution (109)
    • 9.1.1 Week 2 (8/1) (109)
    • 9.1.2 Week 3 (15/1) (109)
    • 9.1.3 Week 4 (22/1) (109)
    • 9.1.4 Week 5 (29/1) (109)
    • 9.1.5 Week 9 (26/2) (109)
    • 9.1.6 Week 10 (4/3) (110)
    • 9.1.7 Week 12 (18/3) (110)
    • 9.1.8 Week 13 (25/3) (110)
    • 9.1.9 Week 14 (1/4) (110)
    • 9.1.10 Week 15 (8/4) (110)
    • 9.1.11 Week 16 (15/4) (110)
    • 9.1.12 Week 17 (22/4) (110)
    • 9.1.13 Week 18 (29/4) (111)
    • 9.1.14 Week 19 (6/5) (111)
    • 9.1.15 After week 19 (13/5) (111)
  • 10.1 Summary of Results (112)
  • 10.2 Challenges and troubles (112)
  • 10.3 Evaluation (113)
  • 10.4 Development (114)
  • 5.1 System Usecase diagram (0)
  • 5.2 Authenticate Usecase diagram (0)
  • 5.3 Authenticate Usecase description (0)
  • 5.4 Register Usecase diagram (0)
  • 5.5 Register Usecase description (0)
  • 5.6 Add wallet Usecase diagram (0)
  • 5.7 Add wallet Usecase description (0)
  • 5.8 Create and update information Usecase diagram (0)
  • 5.9 Create and update information Usecase description (0)
  • 5.10 Update product diary Usecase diagram (0)
  • 5.11 Update product diary Usecase description (0)
  • 5.12 Register product Usecase diagram (0)
  • 5.13 Register product Usecase description (0)
  • 5.14 Verify product Usecase diagram (0)
  • 5.15 Verify product Usecase description (0)
  • 5.16 Build contract Usecase diagram (0)
  • 5.17 Build contract Usecase description (0)
  • 5.18 Authenticate activity diagram (0)
  • 5.19 Register activity diagram (0)
  • 5.20 Add wallet activity diagram (0)
  • 5.21 Update information activity diagram (0)
  • 5.22 Update product diary activity diagram (0)
  • 5.23 Register product activity diagram (0)
  • 5.24 Verify product activity diagram (0)
  • 5.25 Build contract activity diagram (0)
  • 5.26 Architecture design for build private contract between two business (0)
  • 5.27 Architecture design for tracking product system (0)
  • 5.28 System class diagram (0)
  • 5.29 Product’s diary (0)
  • 5.30 Business’s Blockchain interaction (0)
  • 5.31 Write contracts (0)
  • 5.32 View, controller and database (0)
  • 5.33 Login Module (0)
  • 5.34 Verify the JWT (0)
  • 5.35 Update Product (0)
  • 5.36 View Product (0)
  • 5.37 Centralized database (0)
  • 6.1 How Redis is typpcially used (0)
  • 6.2 Hash function (0)
  • 6.3 How does an RSA work (0)
  • 7.1 The JWT’s content (0)
  • 7.2 The token is still valid (0)
  • 7.3 The JWT is blocked (0)
  • 7.4 Redis Cloud service (0)
  • 7.5 Password encrypted (0)
  • 7.6 Send the image to the IPFS and recieve a CID (0)
  • 7.7 Hyperledger Fabric (0)
  • 7.8 Create Artifact (0)
  • 7.9 Running the network with docker (0)
  • 7.10 Create the channel with shell scripts (0)
  • 7.11 Chaincode deploy (0)
  • 7.12 An example of our chaincode (0)
  • 7.13 Query a contract by stakeholder (0)
  • 7.14 Query a contract by its Id (0)
  • 7.15 CouchDB UI (0)
  • 7.16 CouchDB UI (0)
  • 8.1 Email and Password (0)
  • 8.2 Submit OTP (0)
  • 8.3 Connect wallet page (0)
  • 8.4 Enter business information (0)
  • 8.6 View profile of a company (0)
  • 8.5 View business information (0)
  • 8.7 Update business information page (0)
  • 8.8 Register new product (0)
  • 8.9 View product (0)
  • 8.10 Write diary (0)
  • 8.11 Transfer ownership to other company (0)
  • 8.12 History of all transactions (0)
  • 8.13 QR code (0)
  • 8.14 Consumers view product on their phones (0)
  • 8.15 Consumers view product on their phones (0)
  • 6.1 Comparison between Redis and RDBMS (0)
  • 6.2 Comparison between Redis and NoSQL Databases (0)
  • 6.3 Comparison between Redis and Traditional database (0)
  • 10.1 Evaluation Table (0)

Nội dung

Đầu đề luận án: Application of Blockchain Technology in Verification of Agriculture Products Identity.. HO CHI MINH UNIVERSITY OF TECHNOLOGY AbstractFACULTY OF COMPUTER SCIENCE AND ENGIN

Problem statement

Identifying a product’s origin is a major challenge for consumers, and it’s especially critical for agricultural goods with long, multi‑stage supply chains—from breed level and processing units to manufacturers, distributors, retailers, and finally end consumers These essential products are vulnerable to traceability gaps because their extended journey makes control difficult and increases the risk of counterfeit items entering the market An illustrative example can help explain how robust origin tracking—from farm to fork—improves transparency, authenticity, and trust across the entire supply chain.

Lan, a shopper seeking affordable, high-quality vegetables for her family’s dinner, encounters the problem of counterfeit consumer goods in the supply chain when she sees the VNVG brand at the supermarket with varying prices for the same vegetables The confusion arises because a single VNVG product can’t be guaranteed to come from the original company, forcing Lan to rely on retailers and, in turn, distributors to trust the chain The lack of visibility across each link—retailer, distributor, and beyond—leads to a fragile supply chain where information about products doesn’t flow from one unit to the next As businesses aim to protect product integrity and consumers demand origin-verified goods, these issues ripple through the entire market, affecting both companies and consumers.

To overcome these challenges, we need a transformative approach that goes beyond traditional methods The current lack of a robust, decentralized system for verifying the identity of agricultural products hampers fair trade and stalls progress toward a sustainable, trustworthy agricultural ecosystem Blockchain technology, with its immutability, transparency, and decentralized consensus, offers a secure and efficient solution to establish and validate product identity across the entire supply chain, enabling verifiable provenance and stronger trust among growers, traders, and consumers.

Goal

Our project aims to give vegetable buyers confidence that what they purchase is exactly what it claims to be by harnessing the integrity and transparency of blockchain technology The entire supply chain is transparent, with information about each enterprise visible to all stakeholders, including customers and suppliers Blockchain's data integrity ensures records cannot be altered, providing verifiable authenticity from farm to fork.

Blockchain makes every data change traceable by everyone, increasing reliability and security By aggregating comprehensive information for each link in the supply chain, manufacturers can provide a transparent, holistic view of a product’s origin and safety factors This technology enables end-to-end traceability of input processes, virtually eliminating counterfeit goods, enhancing quality control, and boosting the overall value and integrity of the entire supply chain.

Using blockchain in the food supply chain reduces the risk of fraud and dishonest practices, making the process smoother and more trustworthy at an affordable cost Blockchain technology also saves costs and eases manufacturers' burden in proving the origin of products For this verification to work effectively, banks, subsidiary companies, as well as relevant partners in the production process need to authenticate information for transactions within the chain.

Our solution enables enterprises within the supply chain to digitally sign contracts with one another and securely deposit these agreements on a private blockchain network This approach ensures tamper-proof contract records and robust validation of product information, thereby increasing reliability across the supply chain.

Blockchain enables manufacturers to manage the entire farm-to-shelf process with real-time visibility and precise product placement on shelves All data—from cultivation and care processes to transportation, storage, and processing—are recorded and continuously monitored by the system, giving manufacturers tighter control over every link in the supply chain This enhanced traceability helps reduce the risk of compromised food quality by enabling rapid action when issues arise.

Method

To unlock sustainable growth in the agricultural market, a transformative solution is needed to let customers verify product origin and prevent counterfeiting, safeguarding the market from substantial damage Not only customers, but many businesses are willing to pay a substantial fee to safeguard their goods from counterfeiters, because traditional verification solutions often deliver unreliable results.

Several existing solutions similar to our project have demonstrated positive results, which we summarize in the Related Works section; while most current systems rely on Web2-based, centralized authentication that can be vulnerable, our team aims to build a decentralized software application that bridges traditional Web2 with transformative Web3 technologies The resulting platform preserves familiar workflows while leveraging blockchain-driven capabilities, and it introduces features such as building and signing digital contracts with stakeholders’ digital signatures (optional due to the lack of widespread adoption of digital contracts) and authenticating users via the public keys of digital wallets for a more secure way to access the system.

Report Layout

This report presents an overview of the AgriDigital project, outlining its objectives, scope, and significance with contextual background to set the stage for subsequent chapters The Related Works section offers a thorough review of existing blockchain solutions for verifying agricultural product identity, highlighting their strengths and weaknesses The Foundation establishes the theoretical knowledge and essential concepts underpinning the project, creating a solid base for all discussions and the methods used to complete the work The System Analysis identifies all stakeholders of AgriDigital and defines functional and non-functional requirements to guide development The System Design outlines the necessary diagrams, rationale, and visual aids to convey design choices clearly The Security Problems section identifies potential threats and vulnerabilities and proposes mitigation strategies The System Implementation describes the backend code and implementation process in detail The System Demonstration illustrates the system’s functioning step by step, using visual aids and live execution The Project Schedule describes the timeline and road map for future activities Finally, the Evaluation and Conclusion assess the project’s efficacy, highlighting strengths, weaknesses, and recommendations for future research or development.

Blockchain technology is rapidly transforming agriculture, spurring the development of platforms tailored to diverse farming activities As adoption accelerates, three blockchain platforms stand out as the most common in smart agriculture, delivering enhanced traceability, data integrity, and operational efficiency across the supply chain By examining these leading platforms, we can see how farmers, processors, distributors, and consumers benefit from secure, transparent, and immutable records that streamline decision making and strengthen trust in agricultural ecosystems.

Provenance

Founded in 2013 by Jessi Baker, Provenance became the first blockchain-based platform for supply‑chain activities It enables producers, retailers, and consumers to track a product’s life cycle, giving each item a digital passport that verifies authenticity and helps prevent counterfeit goods Its trust engine allows participants to verify product information, strengthening supply‑chain integrity, while digital certifications become data‑backed marks for customer reviews, securely stored on the blockchain.

Provenance helps stakeholders share honest, verifiable stories about goods, strengthening trust across the supply chain Its tracking tool lets producers and consumers trace each product item from origin to end, boosting transparency and accountability By cutting traceability time from days to seconds, Provenance reduces fraud and protects brand value for all participants.

Provenance studies reveal and compare the strengths of each classification method, enabling thorough data analysis and better decision making Moreover, blockchain technology allows provenance data to be shared directly with customers, enhancing transparency and traceability across supply chains.

• Weakness: The weaknesses of Provenance may be related to challenges in data ac- curacy, potential vulnerabilities in supply chain traceability, or limitations in the im- plementation of Provenance systems [1]

AgriDigital

AgriDigital is a cloud-based blockchain platform launched in 2015 by Australian farmers and agribusiness experts It aims to simplify and secure the agricultural supply chain for farmers and consumers, enabling users to manage contracts, deliveries, orders, and payments in a single platform.

8 Chapter 2 Related Works one convenient and real-time location.

AgriDigital tokenizes farm goods by creating digital tokens that represent each physical asset, enabling end-to-end traceability from farm to consumer The tokens track the movement of goods as they flow through the supply chain, providing transparent and verifiable records of ownership and status The platform uses a secure protocol to generate immutable data for every asset, safeguarding the integrity of the data across the lifecycle Once a token is created, users can easily send and receive information via AgriDigital’s application layer, streamlining data exchange and improving efficiency in the agricultural supply chain.

• Strength: AgriDigital worked with Itoc, a technology company and AWS Advanced

A Consulting Partner was engaged to deploy a best-practice Cloud Foundation and migrate the company’s database environment from Microsoft SQL Server to Amazon Aurora PostgreSQL and Amazon DynamoDB This migration addressed scalability challenges and reduced Windows licensing costs, supporting the company’s ongoing modernization.

• Weakness: It’s worth considering that the weaknesses of AgriDigital may be related to areas such as operational challenges, market competition, regulatory constraints, or technology limitations [2]

IBM Blockchain

IBM Blockchain is a widely used platform in agricultural logistics, helping to optimize transactions and strengthen global trade networks It is trusted by more than 1,500 companies and experts for its high security, multi-cloud flexibility, and proven expertise IBM Blockchain unites suppliers, consumers, and professionals within its ecosystem, enabling transparent collaboration across the supply chain It provides equal visibility into agricultural activities, showing where an asset is, who owns it, and its condition at any moment.

IBM Blockchain offers several strengths, including the ability to create a blockchain ecosystem with IBM Blockchain Transparent Supply to securely share data with supply chain partners and enable more efficient, trust-based transactions It helps reinvent trade and trade finance, while IBM Food Trust supports a smarter, safer, and more sustainable food system The Trust Your Supplier solution accelerates supplier discovery and onboarding, and IBM’s Blockchain provides informational guides to help users understand how blockchain works and how to apply it in practice.

• Weakness: One of the weaknesses associated with IBM Blockchain, as mentioned in a commentary, is that one of Blockchain’s greatest strengths becomes a weakness in certain areas However, the specific weaknesses of IBM Blockchain are not explicitly mentioned in the provided search results It’s important to note that weaknesses can vary and may not always be readily available in public sources Further insights into potential weaknesses of IBM Blockchain may require additional research or direct insights from relevant experts in the field [3]

Background knowledge

Blockchain

Blockchain is a basic technical architecture that involves multiple disciplines and fields,including P2P networks, cryptography, mathematics, and economics[4] Based on the the- oretical basis of these disciplines, the blockchain implements a distributed autonomous system that does not rely on third parties and participates in multiple parties through spe- cific data structures, consensus algorithms, trust mechanisms, incentive mechanisms and security mechanisms Blockchain has the characteristics of decentralization, trust lessness and data cannot be tampered with[5] With its unique trust establishment mechanism, it has attracted extensive attention from academia and industry Blockchain can provide an immutable and transparent record of the entire supply chain process Each step in the production and distribution of agriculture products, from planting to harvesting, process- ing, and transportation, can be recorded on the Blockchain This creates a tamper-proof trail that allows consumers and stakeholders to trace the journey of the product back to its origin.

Smart contracts

Smart contracts are automated program code that are not designed to create artificial intelligence In agriculture, these contracts can automate a range of processes, including quality inspections, certifications, and payments, by triggering actions automatically when predefined conditions are met—for example, releasing funds to a farmer or supplier once a product meets quality standards.

Technology

Website application development

Web applications are the most popular choice for users when comparing mobile applications, desktop software, and web-based solutions, and website applications have certain advantages and disadvantages relative to other software types such as desktop or mobile applications; in our system scope, we will use web applications for both desktop and mobile users, while also providing a mobile application for those who prefer interacting on mobile devices, and this article outlines the advantages and disadvantages of a traceability web application that employs Blockchain technology.

Developing a responsive web application enhances accessibility by allowing users to access it from anywhere and on any device that has an internet connection and a web browser This universal access makes web apps convenient and flexible for users who need to reach information or services on the go or from different locations.

Cross‑platform web applications run across different operating systems and browsers without requiring installation or ongoing updates, delivering a consistent user experience across devices This approach reduces development and maintenance costs while ensuring users can always interact with the smart contract’s functionality, even if the mobile application is down.

Mobile application development

From their inception as entertainment tools, mobile apps now span virtually every sector—business, education, health, gaming, entertainment, social activities, and marketing—serving a wide range of customer needs Built to run on mobile devices with touchscreens, these apps must cope with smaller screens and simplified navigation, trading the richness of desktop interfaces for clarity and speed As a result, developers place a premium on user experience, since mobile users typically have limited time and patience.

The typical software development process still applies to mobile development, albeit at a quicker pace Some key aspects of mobile app development include the following:

• User experience: Mobile apps have specific UX requirements and practices that must be adhered to.

• Responsiveness: Ensuring consistent UX across various screen sizes and resolutions presents significant challenges.

Within our system, farmers and retailers—often with limited technical skills—primarily scan QR codes and update product status or log diaries, a workflow that is streamlined by a mobile application For end users who want to verify product traceability before purchase, simply activating the device’s camera and scanning the QR code reveals all verification information with no extra steps.

Front-end development

The front-end serves as the bridge between users and the system’s core business operations, delivering a user-friendly, interactive, and responsive interface Users spend substantial time on the front-end creating, modifying, and accessing data hosted on our Blockchain, making intuitive UI design essential for smooth data management and fast workflows A well-crafted front-end emphasizes usability and performance to ensure seamless interaction with Blockchain data across devices This role highlights how the front-end enables efficient operations and a positive user experience.

A well-crafted front-end design makes user actions feel dynamic and natural, preventing any sense of repetitiveness in everyday tasks Interactions flow smoothly and intuitively, with the interface providing prompt responses to even the smallest input Visual progress indicators enhance the user experience by offering clear feedback on task status In contrast, a poorly designed front-end feels static, forcing users to navigate through multiple screens to complete routine tasks.

Front-end programming

Next.js, a framework for building server-rendered React applications, will be used alongside Tailwind CSS to verify the identity of agricultural products This pairing delivers faster initial load times through server-side rendering, better search engine optimization, and a smoother development workflow Next.js enhances performance and SEO by rendering content on the server, while Tailwind CSS enables rapid, responsive styling with a utility-first approach Together, they create a scalable, SEO-friendly verification system for agricultural products’ identity.

Next.js enables the development of interactive and dynamic user interfaces, a key capability for decentralized applications focusing on agricultural product identity verification Its server-rendered architecture delivers seamless interactions and intuitive interfaces, making user actions feel responsive and natural and enhancing the overall user experience For applications handling sensitive data such as agricultural product identity verification, this approach helps build trust and confidence in the system by reducing friction and ensuring reliable performance.

Hyperledger Fabric

A digital contract between two businesses needs to be private and confidential so the au- thors decide to implement Hyperledger Fabric for this feature Hyperledger Fabric is a

Chapter 3 discusses the Foundation platform, a versatile tool that helps create secure digital records across different industries It works like modular building blocks that can be adjusted to fit specific needs, offering a configurable and scalable solution The system is private and confidential, operating as a trusted environment managed by the Linux Foundation.

Designed for two businesses that require a private and confidential contract within a private channel, this solution is built for large enterprises and consists of multiple integrated components Its adaptable, modular architecture enables customization across diverse use cases, while a permitted network enforces access control to protect privacy The system leverages chaincode smart contracts to codify and enforce business rules securely.

Hyperledger Fabric is a permissioned blockchain network where each node assumes specific roles, such as validating transactions, maintaining the ledger, and executing chaincode Transactions are ordered, validated, and finalized through a consensus mechanism, ensuring the accuracy and consistency of records across the distributed ledger.

Blockchain solution

To develop a decentralized application for verifying agricultural product identity, we need a low-cost and fast transaction testnet, so we propose using Polygon (formerly Matic) as the Ethereum Virtual Machine (EVM) chain for user experimentation Choosing an EVM chain is advantageous because it is the most popular and reliable public blockchain, which helps build trust with end users The Polygon EVM also simplifies smart contract development and supports a wide range of libraries to interact with contract functionality, enabling rapid development and testing.

Polygon delivers a high-performance, low-cost Ethereum scaling solution and a generous developer faucet, making it well-suited for building and testing this system Its testnet environment enables fast, inexpensive transactions, allowing developers to experiment freely and users to explore features without significant costs.

Using the Polygon EVM chain for DApp development and testing provides an efficient, scalable infrastructure with low transaction costs and fast confirmations, while ensuring seamless integration with Ethereum This setup offers a user-friendly environment for experimenting with agricultural product identity verification on the blockchain, enabling rapid prototyping, testing, and iteration without sacrificing security or interoperability.

IPFS

Using IPFS (InterPlanetary File System) to store diaries—composed of text strings and images—on the Blockchain brings multiple benefits IPFS is a distributed file system that operates as a peer-to-peer network, enabling decentralized storage and efficient data sharing By storing diary content on IPFS and anchoring it to the Blockchain, you gain immutability, verifiable provenance, and resistance to single-point failures, while keeping data accessible and scalable This approach combines the strengths of IPFS for distributed storage with the Blockchain’s guarantees of integrity, making it a robust solution for securely storing and sharing diaries that include both text and images.

3.2 Technology 13 in a decentralized manner When it comes to storing images and other metadata related to the diaries, IPFS offers a practical and efficient way to store this information off-chain. This means that the actual content, such as images and structured metadata, can be stored on IPFS [10]

IPFS provides strong security and confidentiality, making it a solid choice for storing sensitive data such as diary entries and images in a decentralized way It enables content to be pinned to a Content Identifier (CID), delivering a reliable reference and fast retrieval of stored data Storing diaries on the blockchain with IPFS supports off‑chain storage of images and metadata while preserving data security and confidentiality and offering a practical method to reference and access the stored content.

The Graph

Before examining the advantages of using the graph in this system, we should understand the challenges of querying blockchain data directly Blockchain data is highly complex and distributed, stored in formats that resist straightforward queries, which can lead to slow performance, high resource consumption, and fragmented insights unless you rely on specialized indexing, data normalization, and off‑chain processing.

Querying blockchain data with a graph database offers faster, more flexible access and deeper analytics than querying the blockchain directly The graph’s structure enables complex, customizable queries by capturing the relationships between data points, making it easier to analyze interconnected information This capability is especially valuable in applications such as verifying the identity and provenance of agricultural products, where mapping and querying relationships across multiple data points is crucial for trusted traceability.

Using a graph database to query Blockchain data delivers faster performance through indexing and traversal, enabling efficient data retrieval This real-time or near-real-time access to Blockchain information can significantly improve the user experience in our system.

Using a graph database to query Blockchain data enables seamless integration of on-chain information with non-blockchain sources The graph model’s ability to connect diverse datasets makes it easy to combine Blockchain data with external data for comprehensive analysis and richer insights By contrast, querying directly from the Blockchain can involve greater query complexity, potential performance constraints, and more challenging integration with other data sources.

Chapter 3 lays the foundation for recognizing how blockchain technology, when integrated with graph databases, enables efficient data querying and analysis across diverse sectors, including agriculture and identity verification This integration strengthens data integrity and traceability while improving interoperability and analytics capabilities, illustrating the broad applicability and benefits of combining blockchain with graph databases as supported by references [12] and [13].

Stakeholders

The production units

Production units require tighter control over their products and must access information across large, complex supply chains To ensure transparency and traceability, they need comprehensive data on the aquaculture process, including details about farmers, farming practices, weather conditions, livestock status, and welfare regimes, enabling real-time visibility and informed decision-making throughout the supply chain.

The processing units

Processing units must maintain comprehensive records that cover the processing facility, the equipment used, and the processing methods, along with batch numbers assigned to products and all financial transactions between the processing unit and the distribution unit for each product This information supports product traceability, accountability, and efficient supply-chain operations, enabling quality control, regulatory compliance, and clear coordination across the processing and distribution stages.

The distribution units

Distribution units need to keep the information about transportation vehicles, routes, stor- age conditions (temperature, humidity), transportation time, and transactions between the distributor and the retailer.

The retailers

Retailers need a reliable way to trace the origin of agricultural products to ensure quality and authenticity on store shelves, while meeting stringent food safety and labeling regulations An effective traceability application provides transparent product information, enabling retailers to verify sourcing, track processing steps, and display compliant certifications By delivering clear provenance from farm to store, this solution helps retailers meet regulatory standards, build consumer trust, and differentiate their offerings through accurate, easily accessible product data.

Consumers

Consumers are increasingly demanding transparency and accountability from the brands they buy from, seeking clear, verifiable information about where products originate and how they are made They also want assurances that items are safe and produced under ethical practices, ensuring what they purchase aligns with their values.

System requirements

Functional requirements

Users should be able to create Ethereum wallet addresses securely Users should be au- thenticated using their Ethereum wallet private keys.

Manufacturers and authorized entities can register their products on the Ethereum blockchain, creating verifiable, immutable records from production to market The registration should include key details such as product name, serial number, manufacturing date, and relevant certifications, establishing a transparent trail that supports traceability, authenticity verification, and regulatory compliance.

Consumers and retailers can verify a product's identity and authenticity by scanning a unique product identifier, such as a QR code, which connects to the Ethereum blockchain The system delivers real-time verification results that clearly indicate whether the product is genuine or counterfeit, enhancing trust, traceability, and security across the supply chain.

Smart contracts on the Ethereum blockchain can automate key business processes, such as transferring product ownership and managing warranties By encoding clear rules for product verification and validation, these contracts enable transparent, verifiable transactions and reduce manual oversight This automation improves efficiency, trust, and security in product lifecycle management, making it easier for brands and customers to verify authenticity and warranty status.

All product verification transactions and smart contract interactions should be recorded on the Ethereum blockchain ledger to create an immutable, auditable record of each event Each entry must capture essential details, including the product identifier, the exact timestamp, and the verification outcome, enabling transparent traceability and validation across the supply chain.

The system should seamlessly integrate with popular Ethereum wallet applications to fa- cilitate user interactions with the Blockchain.

Non-Functional requirements

To safeguard user wallet keys, smart contracts, and the integrity of the Ethereum blockchain, the system must implement robust security measures It should rely on strong encryption, strict access controls, and ongoing security audits to identify and address vulnerabilities By layering these protections, the platform reduces risk, preserves asset security, and maintains trust across Ethereum-based transactions.

The system should be capable of handling a growing number of product registrations and verification requests without a significant drop in Ethereum network performance.

Verification requests should receive a response from the Ethereum Blockchain within a specified time frame The system should have minimal downtime and high availability.

To ensure data privacy and security, the system complies with applicable privacy regulations and implements strong data protection measures It provides users with clear control over their data, including easy access to review, update, or delete information, and requires explicit consent for any data collection or processing Transparent data handling, minimized data collection, and secure storage with encryption further safeguard user information and foster trust while enabling compliant, responsible use of data for legitimate purposes.

The system should be designed to work with Ethereum’s existing infrastructure and tools, such as wallets, Ethereum nodes, and developer frameworks.

Ensuring the Ethereum blockchain remains reliable and resistant to theft requires robust security and a resilient infrastructure Backups and disaster recovery plans must be in place for smart contracts and all data stored on the blockchain to minimize risk, reduce downtime, and enable rapid recovery after incidents.

The user interface should be designed with a focus on usability, ensuring that users can easily interact with Ethereum-based product verification processes.

Usecase design

System usecase diagram

The system consists of 2 Users: Supply User (Production Units, Processing Units, Distri- bution Units and Retailer) and Customer User

Authenticate

In order to login, Users are required to enter their correct email or phone number and password They must also enter the OTP code sent to their devices.

Register

In order to register, Users are required to enter their email or phone number and password.

If the email or phone number has been registered, they have to enter a different one They must also enter the OTP code sent to their devices.

Add wallet for authenticate

FIGURE5.6: Add wallet Usecase diagram

FIGURE5.7: Add wallet Usecase description

Users can log in quickly by selecting "login with your wallet," which allows sign-in without entering an email or phone number When logging in with a new wallet, users will be prompted to provide an email address or phone number to complete the setup.

Create and update business information

FIGURE5.8: Create and update information Usecase diagram

FIGURE5.9: Create and update information Usecase descriptionUsers can update their business information like their business name, tax code, descrip- tion, website, address or certificate.

Update product’s diary

FIGURE5.10: Update product diary Usecase diagram

FIGURE5.11: Update product diary Usecase descriptionUsers can update product diary by adding relevant data, images, time

Register product

FIGURE5.12: Register product Usecase diagram

FIGURE5.13: Register product Usecase descriptionThe production units can register their products by initialing their seed information, create blank diary and create QR code.

Verify product

FIGURE5.14: Verify product Usecase diagram

FIGURE5.15 illustrates the verify-product use case: customers can scan the QR code on a product to view its official information and confirm authenticity If the QR code is not recognized, the product is counterfeit, helping shoppers avoid purchasing counterfeit items.

Build contract

FIGURE5.16: Build contract Usecase diagram

FIGURE5.17: Build contract Usecase descriptionUsers can build a contract by go to the contract page, add stakeholders and product infor- mation and sign the contract

Activity diagram

Authenticate

To log in, users enter the credentials they registered with, including their password The system validates these credentials, and if they are correct, it sends a one-time password (OTP) via SMS or email for additional verification, which the user must provide to complete authentication If users forget their password, they can click the forgot password option to reset it, with OTP verification required to confirm the reset Upon successful login, the system issues a secure session token and grants access to the account.

JWT to the client, the browser will redirect to the homepage All JWT will expire in 1 hour from the time they were created.

Register

To register an account, users provide a valid email address or phone number The system then verifies the supplied credentials to determine whether the account already exists Once verified, a one-time password (OTP) is sent via SMS or email to complete the registration and secure the signup process.

Chapter 5, System Design: Users must provide an OTP to validate their credentials If validation succeeds, they can set a password for the account, which is confirmed and checked against policy requirements When the password meets the criteria, the system stores its hash and prompts the user to add additional information to the account.

Add wallet for authenticate

FIGURE5.20: Add wallet activity diagram

To authenticate, users connect with their public blockchain wallet by clicking the Connect Wallet button, after which the system presents a list of the user’s wallets to choose from; if the selected wallet has already been registered with the system, the home page is displayed and the authentication is complete, but if the wallet is not yet registered, the user is prompted to provide additional information—such as the company name, tax code, email address, and phone number—to finish onboarding.

Create and update business information

FIGURE5.21: Update information activity diagram

This use case begins when the user clicks the Company Information button, prompting the system to render the Company Information page All updates to company information require verification If the account uses password-based authentication, an OTP is sent via SMS or email to validate the update If the account uses wallet-based authentication, the system calls the relevant smart contract and awaits the user’s confirmation through the wallet Finally, the application notifies the user of a successful update or reports any error.

Update product’s diary

FIGURE5.22: Update product diary activity diagram

To update a product diary, enter the product’s ID in the search bar The product page appears; if the product belongs to your business, an Edit button is available, otherwise it’s hidden Clicking Edit opens the product’s diary page, where you can choose the available phase to update with relevant information such as images, times, and descriptions.

Register product

FIGURE5.23: Register product activity diagram

To register a product, the user clicks the register button, then on the product page adds basic information The system then presents the product diary page, a blank diary where the user must fill in details such as the seed source and planting time When saving, the save-data process follows the same flow as prior use cases, with verification performed via OTP or wallet according to the account's authentication Additionally, the system generates a unique ID and a QR code for product identification.

Verify product

FIGURE5.24: Verify product activity diagram

To verify a product, a customer simply scans the QR code printed on the packaging The system analyzes the QR code to retrieve the product’s verification data, including authenticity, batch details, and traceability, enabling quick confirmation of genuineness and origin.

On screen, the product page appears with a complete overview of production, logistics, sales, and processing enterprises, plus the product’s own information The page displays the ID and essential product details—name, unit, size, and other specifications—along with the full production diary, ensuring all relevant data is readily accessible in one place for users and search engines.

If there is any information missing or different, the user can click on the notify button to notify the system with detailed information.

Build contract

FIGURE5.25: Build contract activity diagram

This feature lets businesses create digital contracts authenticated with digital signatures Although digital signatures and digital contracts haven’t become widely popular yet and many businesses still rely on paper contracts, this use case remains optional The process starts when a user clicks the create contract button, after which they add the contract’s stakeholders The contract content is mandatory and must include details such as name, time, and terms and conditions The contract is validated and deployed on a private blockchain only after all stakeholders have confirmed, and notifications are sent to everyone involved to confirm before the contract becomes invalid.

Architecture design

Build private contract Hyperledger Fabric

FIGURE 5.26: Architecture design for build private contract between two business

We present an optional digital contract framework for a two-phase business model For illustration, Channel 1 links a logistics enterprise with a production enterprise, while Channel 2 connects a logistics enterprise with a sales enterprise In each channel, every participant maintains a digital contract that mirrors the corresponding paper contract and is stored on the ledger, as all channel peers run the ledger The MSP configuration restricts each channel to two peers, and both peers act as Endorsers.

In a channel, every transaction executed and needed to add data to Blockchain will follow

5.3 Architecture design 37 the steps here:

• A business interact with client application to interact with a function in chaincode, it propose transaction to two endorsers which are two business in the contract.

• Two endorsers will execute the proposed transaction None of these transactions will update the ledger.

• The client application will wait for the proposal response along with their signature from each endorser and also includes each record version number.

• In this step, the client application will submit the transaction to the Ordering-Service. Ordering happens across the fabric in parallel with transactions submitted by other application.

• Next, the Ordering-Service form a block and communicates with our 2 peers.

• Every committing peer validates against the endorsement policy.

• Finally, application will be notified when transactions succeed or fail.

Build public Blockchain for recording diary of products

FIGURE5.27: Architecture design for tracking product system

We propose an Ethereum blockchain-based system for agricultural product traceability that accurately records, shares, and provides end-users with a verifiable diary of each product By leveraging blockchain technology, the system increases transparency, fosters trust, and strengthens information security among all players in the agricultural supply chain.

38 Chapter 5 System Design system develops smart contracts and leverages IPFS decentralized storage technology to enhance the reliability of traceability results and system flexibility.

Our system prioritizes traceability transparency with a 100% decentralized architecture, so end users scanning a product’s QR code can truly trust the data Enterprises interact directly with the smart contract in our decentralized application, while the contract itself is deployed on a public blockchain where the code and every transaction are openly verifiable Since storing large files like images on the blockchain is cost-prohibitive, we store these files on IPFS and record their encrypted hashes on the blockchain, ensuring secure, verifiable access without excessive on-chain costs This approach is explained in detail in the IPFS section In short, this framework governs how our system stores and validates product diaries, delivering transparent, immutable traceability from production to end user.

We propose a decentralized protocol for indexing and querying blockchain data called The Graph In complex systems, when a smart contract function is called repeatedly—such as within a loop—the function can temporarily block or take a long time to respond The Graph captures every event emitted by smart contracts, allowing us to index and query data that matches our defined data schema By extracting data from these events, our web application can retrieve and display information on the user interface far more efficiently than querying the blockchain directly.

Class diagram

Product’s diary

The product class models a product in a real-world context by capturing key attributes such as ID, name, price, and unit At any given time, a product belongs to a single business—whether in production, distribution, processing, or retail—and is linked to a diary that records the full supply chain data The diary is organized into phases that represent the major stages of the supply chain, and each phase comprises multiple steps, each managed by a single business Each step records time, a description, and related media such as videos or images specific to that step.

Business’s Blockchain interaction

Interacting with the blockchain requires a caller at the upper layer to invoke smart contracts Each smart contract uses the wallet's public key as its identifier and requires a signature with the corresponding private key for verification This key pair identifies the wallet address and is generated when the wallet is created Any change to data on the chain is a transaction that records the source address initiating the mutation and the destination address affected Transactions incur a cost, typically paid in network tokens, except on test networks where fees may differ All transaction data and smart contract contents are transparent and readable by every node in the network A business may interact with a smart contract directly through a wallet, or indirectly control it via an account.

Write contracts

Businesses can create contracts and store all contract data on a private blockchain network, including the ID, stakeholders, terms and conditions, content, and other details, with the contract signed by the business for verification.

View, controller and database

FIGURE5.32: View, controller and database

Businesses will use the decentralized application as the view component to interact with smart contracts and controllers The controllers provide multiple methods, including account authentication, GraphQL queries to The Graph database, and Redis-based authentication, which will be explained later The architecture integrates both centralized and decentralized databases, with Redis included as part of the database layer.

Sequence diagram

Login Module

Upon clicking the login button, the client triggers a POST request to the server, and the controller reads the request body to extract the user’s email and password A middleware layer then performs credential processing before querying a centralized database for authentication, with the password handling details deferred to the security section The middleware executes the database lookup; if the query returns null, meaning the credentials aren’t in the database, it returns false to the controller If the query succeeds and the credentials are found, the middleware generates a JSON Web Token (JWT) and returns it to the controller, which writes the token into the browser’s cookies to establish the user session.

Verify the JWT

On each request from the view layer, the controller delegates authentication to middleware that verifies the JWT accompanying the request If the JWT is valid and not expired, the middleware then analyzes the user_id and created_at If the user_id is not present in Redis, the middleware returns true to the controller before any business logic executes; otherwise, it compares created_at against the Redis-stored value Any JWT with a created_at older than that Redis reference should be blocked, with the middleware returning an error to the controller The full reasoning and security implications of this approach are explained in the security section.

Update Product

When a user updates a product, the view layer of the decentralized application calls the smart contract to interact with the blockchain Any transaction or data mutation requires a public key to call and a private key to sign, so the view forwards the request to the controller to retrieve the public key from the centralized database, then uses that key to invoke the smart contract Before execution, the contract must be signed by the wallet, the layer that manages private keys After the smart contract is deployed to the blockchain, the network verifies its validity; on successful verification, it emits an event that records the data, and The Graph database listens to this event to index and expose media files and related assets.

44 Chapter 5 System Design such as videos or images should not be stored in the Blockchain Instead, they should be stored via the IPFS architecture.

View Product

Because a centralized database maintains a copy of data on the blockchain, the controller can query The Graph to retrieve information that users or businesses are authorized to view—such as product details While invoking smart contracts can work for individual requests, a surge in demand often overwhelms the blockchain network, causing blocks or delays, so using The Graph as an indexing layer enables scalable, fast access to authorized data without clogging the network.

Centralized database

To support credential and password authentication, our system relies on a centralized database to store user credentials and to manage wallet-based access, while storing public keys used to call smart contracts and interact with the blockchain This includes data on a public blockchain for product diaries and business information, and a private blockchain for inter‑business contracts, all maintained within the centralized database An account can be authenticated by password or by wallet, with wallet authentication being mandatory The wallets table stores the public keys of the public blockchain and the public keys of the private blockchain (which may be NULL if a user chooses not to use the contract feature) The accounts table stores password-authenticated users, where pb_key is the public key of the public blockchain, credentials may be an email or phone number, and HashPassword is the encrypted password Private keys needed to sign smart contracts are stored in the pr_key attribute, since the system manages wallet access for users.

Log out of all devices features

Introduction to Redis

FIGURE6.1: How Redis is typpcially used.

Source:https://backendless.com/redis-what-it-is-what-it-does-and-why-you-should-care/

Redis is a versatile NoSQL database that shines across a range of use cases Its primary applications include efficient caching, reliable session management, and real-time data processing, especially in Pub/Sub scenarios that enable instant data distribution When weighing Redis, its advantages include exceptional speed, in‑memory storage, and a rich set of data structures and operations, while its drawbacks encompass higher memory usage, persistence considerations, and the need for careful clustering and scaling in large deployments.

• Swift Read/Write Operations: Redis leverages in-memory storage, enabling lightning- fast read and write operations.

• Diverse Data Structures: Supporting various data structures like strings, hashes,lists, sets, and sorted sets provides flexibility in data storage.

• Session Management and Event-Driven Abilities: With support for Pub/Sub and transactions, Redis facilitates efficient session handling and real-time event process- ing.

• Storage Capacity Constraints: Dependency on memory size leads to limitations in storing large volumes of data persistently.

• Limited Complex Querying Abilities: Compared to some other NoSQL databases,Redis lacks advanced querying features [14]

Comparing Redis with Other Databases - Differences from RDBMS (relational database management system)

Data Structure Redis stores data using key- value pairs and offers ex- treme flexibility with sup- port for various data types (strings, hashes, lists, sets, etc.)

Relational databases struc- ture data into tables, rows, and columns They require a strict schema design before creating tables.

Redis provides transaction handling, but it does not fully guarantee ACID properties—Atomicity, Consistency, Isolation, and Durability Its transactional guarantees are selective, and it may encounter limitations when managing complex transactions.

RDBMS provides complete support for ACID transac- tions, ensuring data consis- tency, transaction rollbacks, and more.

Redis is an in-memory database that stores data in RAM, enabling high-speed read and write operations This in-memory design delivers low latency and high throughput, making Redis ideal for real-time data processing and caching use cases.

Relational databases com- monly store data on disks, which may lead to delays due to disk access Perfor- mance depends on query and index optimization.

TABLE6.1: Comparison between Redis and RDBMS

Source: https://dev.to/koshirok096/redis-a-comparison-with-other-databases-bite-size-article-2lip

6.1 Log out of all devices features 49

Comparing Redis with Other Databases - Differences from Other

Data Model Key-value pairs, support- ing diverse data structures (strings, lists, sets, etc).

Document-oriented, employ- ing flexible JSON-style docu- ments

Query Language Supports simpler queries, but with constraints compared to MongoDB.

Employs a robust query language enabling complex queries and aggregations.

Performance In-memory database ensures fast read/write access.

Persists data on disk, and its performance is impacted by data volume and query com- plexity.

TABLE6.2: Comparison between Redis and NoSQL Databases

Implementation

Our project uses token-based authentication for Web2 accounts (email or phone number and password) A major advantage of token-based approaches, particularly JSON Web Tokens (JWT), is improved database query performance and better scalability for future growth However, if credentials are not stored in the database, security risks can arise: a stolen, still-valid JWT could grant an attacker full access to an account To counter this threat, we provide a log out of all devices feature in our system, ensuring users can revoke active sessions across devices We’ll outline the mechanism from the ground up.

To revoke tokens across all devices, the system blocks any JWT that is still valid but has a created_at timestamp earlier than the time a user reports The time data is stored in Redis using a Redis hash, a fast hash-table-based data structure that maps user_id keys to time values Each Redis hash entry associates a user_id with a timestamp indicating the cutoff for token validity When a user chooses log out of all devices, the service writes a Redis row with the key user_id and the value equal to the current_time provided by the user, aligned with the tokens’ valid_time For example, if all JWTs are configured to be valid for 1 hour, every field used for the comparison is set to that same value, so any JWT created_before that timestamp gets blocked, effectively revoking access across devices.

Many developers wonder why use Redis with JWT instead of traditional session-based authentication In a system with one million users, every request would typically need to access a central session store, creating a bottleneck and higher latency as scale grows JWTs enable stateless authentication, but Redis enhances this setup by providing a fast in-memory layer for managing tokens, revocation lists, and auxiliary session data This combination reduces database reads, lowers latency, and simplifies horizontal scaling while preserving security controls like token expiration and revocation through Redis-backed mechanisms.

Security problems can shrink the system and hinder future scalability If, however, we assume that within a one-hour window—the valid time for a JWT and the Redis field set by the system—only 0.1% to 1% of users will use this feature, then the Redis database would require just 1,000 to 10,000 rows Even with this small footprint, Redis queries are faster than traditional databases, so the overall system performance improves and supports future growth.

Search with key (user_id = ‘123’) O(1) O(log n)

Search with content (user_name = ’Nguyen’) O(n) O(log n)

TABLE6.3: Comparison between Redis and Traditional database

In conclusion, our system provides a high performance solution to authenticate users,while having enough security just like the traditional session-based authentication.

Using hash function to hash the passwords

FIGURE6.2: Hash function Source:https://byjus.com/gate/hash-function-in-data-structure-notes/

A hash function converts input data of any length into a fixed-length string, typically a hexadecimal hash value For password security, passwords are hashed to these hash values, and systems store only the hash values rather than the original passwords, reducing the risk if a database is compromised However, this approach has limitations that will be explained and addressed in this session.

Consider a hacker who creates several accounts using common passwords such as 123456789, abc123, and qwerty If the attacker later gains access to the database, they can compare the password hashes and discover other accounts that use the same password, enabling them to compromise those accounts as well This attack is known as a rainbow table attack, where precomputed hash values are used to reverse passwords from their hashes.

To defend against this type of attack, hash both the password and a unique user attribute (such as user_id, email, or phone number) instead of hashing only the password For example, with user_id 123456 and password abc123, compute k = h("123456abc123") and store k in the database Because the user_id is unique, attackers cannot determine which password belongs to which account, making credential theft and account compromise far more difficult.

The problem of keeping private_key for users

Key rotation

To strengthen security, the solution updates the cryptographic key continuously at each time interval t, which also requires corresponding updates to the database If an attacker steals the key at time t1 and gains access to the database at t2, they cannot access any wallets when the time difference |t1 − t2| is greater than t, while the data will be revealed when the time difference |t1 − t2| is less than t.

• All the update are implicit to users, so the UX is not affected.

System security increases linearly as t decreases, but making t too small significantly degrades performance Under heavy user load, this method is not viable due to ongoing database modifications, which limit scalability.

• When the key got stolen, the attacker can access to all the wallet of users, so we will provide another method that protect each user’s wallet independently.

Password-based

With this approach, a password-derived key pair is generated, meaning keys are created only when encryption or decryption takes place Since passwords are typically unique to each user, the resulting keys remain independent and user-specific, strengthening security and reducing the risk of cross-user key reuse.

• The secure of system are confirmed, as long as the passwords are protected safely.

• Each user has their own sys_pri_key , therefore the method is indepedent secure.

• The system will not need too large power for computing, so the performance is bet- ter.

If a user forgets the password, neither the user nor the system can access the wallet, so a "Forgot Password" feature is not available A password update option remains possible, however, as long as the user can supply their current password for authentication.

• Every transaction need user provide his/her password again, therefore the UX is not good.

• This method is lack of ability to face Phising attacks.

Smart contract

Usage and Deployment

This contract runs on the Ethereum blockchain and leverages Subgraph Studio for efficient data querying, with on-chain events captured and stored in The Graph to enable fast, decentralized access to data for developers and applications Click here to see the contract on Etherscan.

The logic for capturing emitted events and storing them into our designed entities ensures a robust and transparent traceability system.

Enums and Structs

• CompanyType: Enumerates the types of companies involved in the supply chain, includingProduction,Process,Logistic, andSale.

• Company: Represents a company with various attributes such as ID, name, email, tax code, company type, phone, website, certificates, address, verification status, public key, description, and logo.

• Product: Represents a product with attributes like ID, name, size, unit, status, owner, description, media, and owner company details.

• Step: Represents a step in the product lifecycle with attributes including ID, descrip- tion, media, owner, product ID, phase ID, status, owner company details, and step name.

Constructor and Modifiers

• The constructor initializes the contract by setting the contract deployer as the owner.

• onlyOwner: A modifier that restricts certain functions to be callable only by the con- tract owner.

Mappings

• information: Maps an address to aCompanystruct, storing company information.

• isRegister: Tracks whether a company address is registered.

• productInfo: Maps product IDs toProductstructs, storing product information.

• currentPhaseOfProduct: Tracks the current phase of each product.

• stepInfo: Maps step IDs toStepstructs, storing step information.

Events

• CompanyEvent: Emitted when a company registers or updates its information.

• ProductEvent: Emitted when a product is created or transferred to a new phase.

• StepEvent: Emitted when a new step is documented for a product.

• newStakeholder: Emitted when a new stakeholder is associated with a product.

Functions

• transferOwner: Transfers contract ownership to a new address Only callable by the current owner.

• registerCompany: Allows a new company to register with various details Emits a

• verifyCompanies: Verifies a list of companies Only callable by the contract owner.

Emits aCompanyEventfor each verified company.

• modifyCompanyInfo: Updates a registered company’s information Emits aCompanyEvent.

• createProduct: Creates a new product and assigns it to the registering company.

• writeDiary: Records a new step for a product, ensuring the caller is the product owner Emits aStepEvent.

• NextPhase: Transfers product ownership to a new user and advances the product to the next phase Emits aProductEvent.

• deleteStep: Marks a step as inactive Emits aStepEvent.

The Graph

Design Subgraph

Our system uses Subgraph Studio to listen to events on-chain from the Ethereum blockchain and then adds them to our subgraph for faster and more efficient querying.

We designed our system with three core entities to keep things simple while effectively capturing all blockchain events In schema.graphql, we define the Company Entity to store information about registered companies, the Product Entity to hold general data on each product, and the Step Entity to record detailed information from every step documented by companies for robust traceability.

We introduced two new entities: The History Entity, which displays all system transactions on the frontend with a user-friendly interface synchronized to the transactions recorded by our deployed contract on the blockchain explorer, and The New Stakeholder Entity, which identifies the stakeholders tied to a specific product.

In the final step, we implement the logic to transfer data emitted by the blockchain’s emit function into our entities, capturing on-chain events and persisting them in a structured form for reliable querying We then deploy this setup on Subgraph Studio to enable fast, scalable data access and easy query building The accompanying code demonstrates how to store data in a decentralized manner using The Graph, illustrating end-to-end data handling—from event emission to indexed storage and query-ready results.

16 entity.step_ownerCompanyName = event.params.step.ownerCompanyName

17 entity.step_ownerCompanyId = event.params.step.ownerCompanyId

35 entity.step_ownerCompanyName = event.params.step.ownerCompanyName

36 entity.step_ownerCompanyId = event.params.step.ownerCompanyId

API

Authentication web 2.0

Our system uses token-based authentication powered by JSON Web Tokens (JWT) During login, users submit their registered email and password, then an OTP is sent to their email to help prevent phishing After entering the correct OTP, the server issues a JWT that is stored in localStorage This token is automatically attached as a bearer token to every request through Axios middleware, enabling seamless, authenticated communication with the server.

2 baseURL : " https :// agridigital - be.vercel.app " ,

The payload in the JWT includes the following fields:

• id: The user’s ID from the database.

• exp: The expiration time of the token in Unix format (the system sets the exp value to one hour after the token is created).

• publickey: The wallet address linked to the user’s account Since the public key cannot be changed, there is no need to query it from the database.

• isData: A field to determine whether the user has completed their company infor- mation.

• iat: The time the token was created.

Embedding a flag in the payload to indicate whether the user has completed their data can create issues, such as tokens remaining valid on other devices even after the user provides the company information, preventing data access These problems have been addressed by integrating Redis caching to manage token state across sessions We'll discuss this solution in the upcoming sections.

6 var document = { p u b l i c _ k e y : publickey , p r i v a t e _ k e y : e n c r y p t _ p r i v a t e k e y , c r e d e n t i a l : email , hash_password : hash_password , i s D a t a : f a l s e }

When users enter a correct OTP, the system creates a user account and generates an Ethereum wallet for interacting with the Ethereum blockchain In this authentication model, the system holds full wallet management authority rather than a third party, which requires storing the user’s public and private keys in the database and creates potential vulnerability if the database is compromised To mitigate this risk, the user’s private key is encrypted before storage Details will be discussed further in the security section.

There is also a little token of the test network sent to the wallet for creating any transaction(with the purpose of testing).

Our system provide a feature call "Sign out all other devices" by integrating a special cache call Redis The API will disable all the tokens until now if they still be valid (has not expired yes) by storing the time currently as the value and the key should be that user-id. The expiration of that row should be exactly the same as the expiration of the JWT, 1 hour. Then whenever a token is sent with the request, the system can check the "iat" field in the payload to see whether the token was created before the time store in the Redis cache or not If yes, the token will be blocked by the system Detailed of implementation will be explained in the Redis section.

FIGURE7.2: The token is still valid

Currently, the token has not expired, so the system still accepts it as valid To revoke access from all other devices, we send a "log out all other devices" request to the server After issuing this request, the system stores the current time in Unix format under a specific cache key.

FIGURE7.3: The JWT is blocked.

Although the token has not expired, the system has blocked it Consequently, all currently valid tokens for this account will be disabled, not just the one in question After one hour, the cached token data will be cleared since there will be no valid tokens remaining.

Smartcontract Backend

To call a smart contract from Node.js, you typically use the Ethers.js library Before interacting with the contract deployed on the blockchain, you must identify three key pieces: the contract provider, the contract’s public address, and its ABI These elements become the attributes of the contract variable in your code and are used to instantiate an Ethers Contract object, which connects to the network, allows you to read data, and enables you to send transactions The provider handles the network connection, the address specifies where the contract is deployed on that network, and the ABI describes the contract’s functions and events so you can call methods and decode results.

4 c o n s o l e l o g ( obj , typeof obj.companytype , typeof o b j c e r t i f i c a t e I m a g e )

5 s t a t e t x = await c o n n e c t o r r e g i s t e r C o m p a n y ( obj.name , o b j e m a i l , obj.companytype , obj.phone , o b j w e b s i t e , o b j c e r t i f i c a t e I m a g e , o b j a d d r e s s , o b j d e s c r i p t i o n , o b j l o g o ) ;

13 s t a t e t x = await c o n n e c t o r w r i t e D i a r y ( o b j p r o d u c t I d , o b j d e s c r i p t i o n , obj.media , obj.stepName )

16 s t a t e t x = await connector.modifyCompanyInfo ( obj.name , o b j e m a i l

Redis

Redis Cloud

There are several ways to implement a Redis cache, and we first evaluated a Docker-based solution by running a Redis container on a fixed port As the system moves toward deployment and future scalability, this approach could pose deployment and maintenance challenges Therefore, we opted for Redis Cloud, the hosted cache service from Redis Labs, to run our cache, gaining managed infrastructure, high availability, and easier scalability for future growth.

2 password : process.env.REDIS_TOKEN ,

4 h o s t : ’redis -10927 c252.ap - southeast -1 -1 ec2.redns.redis - cloud.com ’ ,

12 c o n s o l e e r r o r ( ‘An error occurred with Redis : ${ err } ‘)

To connect the Redis cloud, we use the Redis package, and provide the specific host and port for authenticate the connection.

System Integration

2 c o n s t checkBlock = await g e t e r ( ‘${ decoded.id } _block ‘ )

7 message : ’ Account has been blocked ’

This system uses a cache-based approach to invalidate tokens at logout, writing a Redis key in the format userId_logout with the Unix timestamp of the logout request as its value and requiring every server request to check Redis to see if the token has been blocked It follows a blacklist model rather than a session-based whitelist, so even with 100,000 users online, only a small subset—typically hundreds—needs to be tracked Redis, with its hash-table data structure, delivers extremely fast token lookups, enabling rapid validation at scale The architecture supports scaling by storing sessions in a database while maintaining robust security, a pattern we describe as semi-stateful authentication.

21 message : " Success register on blockchain " ,

During account verification, the system checks whether company information has been provided It uses a database flag named isData, but it does not query this field when validating a token When a user registers their company information, the system updates isData to true in the database and writes a corresponding key-value entry in Redis For every subsequent request containing a token whose payload isData is true, no further checks are required If the isData flag is false, the system performs a cache lookup to determine whether the account has registered its company information; if the information is still missing, the user is notified, and a new token may be issued once the company information has been supplied.

Security

HyperLedger Fabric

View and Update product diary

Contribution

Ngày đăng: 15/10/2025, 20:05

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

🧩 Sản phẩm bạn có thể quan tâm