How difficult is food traceability? Teach you to write a blockchain + IoT traceability system

What is the use to prove how hot the blockchain is?

Probably, the blockchain was put on the “two sessions” on the table to discuss, the demand for related posts increased by 400% in one year, and a listed company’s share price soared by 500% after adding “blockchain” to the company name.

The blockchain and the Internet of Things (IoT) have proven to be the most popular technologies of the moment, although their use has only just begun. At present, the integration of blockchain and IoT has become one of the priorities of some large companies, and a few companies have begun to use it in some projects to implement plans and develop solutions.

Just in this "everyone is chained", we need to seriously consider a few serious questions: In addition to digital currency, what are the valuable scenarios of blockchain technology for the real economy? How to follow industry rules and needs in the practice of technology grafting? How does the blockchain combine with the Internet of Things, cloud computing, and big data to achieve truly ideal results?

This article will address the current food safety transportation challenges and give you an in-depth introduction to how to design a solution architecture, namely how to use the blockchain to support distributed ledger network and IoT device requirements, and to implement process tracking.

Want to know what the food has gone through before it enters your stomach? Not much to say, look at the dry goods.

Design solution architecture

In this chapter, we review the food chain solution architecture based on the Internet of Things and blockchain and focus on the following topics:

  • Business: Review of business component composition and key players, as well as transaction processes between production and consumers
  • Technology: The architecture that will showcase our technology solutions
  • Software aspect: will show the solution details

Food industry

Modern food chains are large and complex, and participants directly or indirectly influence the production and transportation of food.

Let us first understand the modern food production process, what challenges the modern food chain faces, and propose a solution based on blockchain and IoT technology:

The above picture is a simplified version of the modern food chain business process, the actual chain is much larger than the above picture. For example, many supermarkets have their own sales centers, so there are no other participants such as ports and customs.

For our application case, we will try to explain the product as it is delivered to the manufacturer. The product is optional, here is the chicken leg as an example.

Suppose that the asset we manage is a box full of chicken legs, and the other asset is a handling tray filled with boxes with chicken legs. In the food chain, we will focus on the following participant processes: producers, distribution centers, and retailers.

As mentioned earlier, there are many participants in the modern food chain, but we follow a simpler process, not necessarily the actual process followed in real life, the goal is to understand how the Internet of Things and blockchain help food. The parties in the chain solve practical problems.

a) Food ecosystem challenges

There are many challenges in the food chain we choose to focus on, which are briefly listed here:

The challenges faced by farmers: Ensure the safety and reliability of key information about raw materials, including product descriptions, inspection dates, inventory information, etc.

Manufacturers face challenges: Ensure that the source of the product is safe; the product can be safely delivered and received; try to package the product with electronic devices, reduce manual participation; use barcodes and QR codes to provide information labels for regulators and consumers.

The challenges facing retailers: Check the integrity of the packaging, ensure the visualization of the product transportation process, and manage the production date, warehouse inspection and quality control.

The challenges facing consumers: Fully trust the information in the packaging of the product, such as the origin, to quickly identify the product and, if necessary, to exclude suspicious products.

b) Food processing

Let's start with our goal. In the case, after the raw materials of the product arrive at the factory, they are cut, packed, packed, and stored, and the box is placed on the carrying tray before delivery.

The handling pallet is a wooden, metal or plastic platform for transporting goods. We can see in the picture below:

Important data that must be registered for processing at the processing stage include:

  • Stock Keeping Unit (SKU)
  • Animal source
  • Manufacturer name
  • Animal information
  • QC
  • Date of emission reduction
  • Refrigeration
  • Technical supervisor information
  • Date of shipment
  • Temperature and logistics information

Record the following details when registering the box or carrying the pallet:

  • Inventory unit
  • date
  • Manufacturer address
  • Refrigerated temperature
  • Quality Records
  • Handling pallet code

Let's look at the next link:

c) Food distribution

After cutting, packaging and shipping, the product arrives at the distribution center where it is responsible for receiving the goods and checking the product storage. Depending on actual transportation needs, the product may be placed in a larger handling pallet to make it more suitable for train or truck transportation.

In order to avoid any problems with the product, the distribution center will check the data sent by the factory. If there are any additional changes, such as handling pallet transfers, you will need to add the appropriate information to the product package.

For the product, record the following information:

  • Receipt date
  • Handling tray number
  • Receiving temperature
  • Storage temperature
  • Shipping company name
  • Sealing situation

For handling pallets, record the following information:

  • Destination code
  • Handling pallet code
  • date
  • Distribution temperature
  • Shipping company name

After inspection, the product was sent to the retailer.

d) Food retail links

After the store receives the product, it needs to check whether the goods meet the requirements, unpack the handling tray, open the box, and the product inspection process ends:

In the retail segment, be sure to record the following information:

  • Receipt date
  • Handling tray number
  • Receiving temperature
  • Storage temperature
  • Shipping company name
  • Sealing situation

Now, the store can label the product, and the product will be sold on the shelf directly or over a period of time.

6.2 Technical solutions

Now that we understand the whole process of the food chain and the potential problems in each link, let's look at how the blockchain and IoT technologies work here. The following figure shows the standard blockchain Hyperledger Fabric architecture:

The above diagram shows us the three-tier architecture of the blockchain, including front-end applications (left), API/SDK (middle), Hyperledger Fabric, and IoT platforms (right).

The following is an explanation of each layer of architecture:

a) front-end application

This layer is responsible for data entry and can be a packet, such as a packet from SAP, Salesforce, or Siebel, or a custom application. It can also interact with IoT devices, collect data and register with blockchain accounts. Developing front-end applications consists of the following:

Ok, I know that there are a lot of tools for each layer of architecture. I only use tools that I am familiar with here.

This front-end architecture allows us to separate services from a single interface so that we can extend the user experience (User eXperience, UX) to other platforms without rebuilding the service content.

b) Asset tracking technology based on the Internet of Things

The Internet of Things plays an important role in the food chain. IoT devices can track assets and there are many models to choose from. There are sensors for measuring temperature, GPS for tracking, position tracking, SigFox, Wi-Fi, 4G and Sub1Ghz. These devices and networks can be used in a wide range of farms, factories, transportation companies, distribution centers and retail outlets, covering all participants in the food chain.

The main challenge in the food chain comes from the transportation sector. Many foods require a specific environment because some foods are perishable, and temperature control is critical to preventing food contamination and decay.

Let's take a look at how to use IoT devices to solve this problem. The Particle Electron Asset Tracker (shown below) can be used to collect temperature and environmental data, identify GPS locations, and perform cellular triangulations, etc.:

This tracker allows us to connect the u-blox M8 GNSS GPS receiver to the Adafruit LIS3DH triaxial accelerator. We can also connect the Grove sensor to it.

Let me take a look at the architecture of this IoT platform:

The above diagram shows us the key components of the solution, including:

Message Queuing Telemetry Transport (MQTT): This refers to a TCP-based delivery-subscribe message delivery protocol; dedicated to remote connections, requiring a small amount of code, or requiring network bandwidth; publish-subscribe The messaging model requires a message broker.

Node-RED: This is a programming tool that connects hardware devices, APIs, and online services in a simple way using a stream editor that creates JavaScript functions.

IBM Cloud: This is a set of cloud computing services.

Bosch IoT Rollouts: This is a cloud service in the Bosch IoT Suite that enables users to manage software updates for edge devices, controllers and gateways.

So how do these components work together to help the food chain work?

  • The Node-RED Control Panel dashboard allows us to select an asset tracker and check location, data, device status and other information
  • Asset Tracker can be activated or updated on the mobile network
  • Geographical data can be transmitted periodically and tracked via the Node-RED dashboard
  • The asset tracker device queries the temperature data and then queries the location or speed data
  • Node-Red can write temperature, position and velocity data to the Hyperledger Fabric
  • The Node-Red dashboard queries various task information in the Hyperledger structure, such as transaction history, date and time data, and geographic sensor data.


API/SDK is the integration layer of connections in a blockchain network, usually developed using Node.js, which plays an important role in calling smart contracts. Today, we can find API/SDK documentation using Go and Java, as well as Python documentation.

For information on how to integrate your application with the blockchain network using the API/SDK, you can refer to this link:


The following image shows an application that integrates with the API/SDK and interacts with the Hyperledger Fabric:

The Composer Java Script SDK is derived from Node.js and allows developers to integrate applications with their business network. Includes two npm modules:

Composer-client: This module is usually a local prerequisite for the application. It provides APIs for connecting business applications to the business network in order to access assets and participants and submit transactions. For the manufacturer, this is the only module that the application needs to add.

Composer-admin: This module is typically used as a local prerequisite for managing applications. This API allows for the creation and definition of business networks.

Now let's move on to the last layer in the solution.

d) Hyperledger Composer – Advanced Overview

Hyperledger Composer is an easy way to create a blockchain network that integrates a full-stack work solution, as provided by the Hyperledger Composer architecture site.

At a higher level, Hyperledger Composer consists of the following components:

  • Execute runtime
  • JavaScript SDK
  • Command line interface (CLI)
  • REST server
  • Loopback connector
  • Playground web user interface
  • Yeoman code generator
  • VS Code and Atom Editor plugin

A detailed description of these plugins is beyond the scope of this book. You can visit this link to get a glimpse of these components: https:// hyperledger. github. io/composer/latest/introduction/solution-architecture

6.3 Software Components

Now, we will look at the software components of the solution from the perspective of the architect. This is a great way to get familiar with all the components and better understand how they are integrated.

First, we explore one of the most important components: the authentication process.

How do you ensure that every member of the food chain has the right access rights in the front-end application? After answering this question, we will delve into the most important components of Hyperledger Composer: the modeling language and transaction processor capabilities.

a) Composer REST server

To authenticate the client, we need to set up a REST server. With this option, the client should be authenticated before it is allowed to make calls in the REST API.

The REST server uses an open source software called PASSPORT, which is the authentication middleware for Node.js. It is flexible and modular, and supports authentication via username and password, Facebook, Twitter, Google, and Lightweight Directory Access Protocol (LDAP). In Chapter 7, we will elaborate on this. Now let's review how the component will work.

In the figure below, we can see the advanced authentication architecture using the Composer REST server:

The following components are described in the figure: Front End Application, Composer REST Server, LDAP, and Cloud (Cloudant, NoSQL Database).

If you are testing, or need to quickly create a proof of identity, it is recommended to use Facebook, Google or Twitter for authentication, which will be easier and faster than other methods.

To use the previous method and take advantage of the Composer REST server, we need to do some customization, which requires the following steps:

1) The following line is the command that needs to be executed before the line when composer-rest-server is installed:

  Apk del make gcc g++ python git 

Before using this method, make sure you have a clean environment and clean up all previous installations.

2) To customize the Composer REST server Dockerfile, add the following command to the Run statement:

  Su -c "npm install -g passport-ldapauth" - composer && \ 

3) Create the following environment variables:

4) If you are checking the API call and receiving 404, this means there is no login:

5) Check if there is an API in the wallet:

To better understand the authentication process, let's take a look at this execution process:

Authentication requires that each API call to composer-rest-server must include an access_token. For more information, please visit:


Some examples of using curl include:

Another example:

6) This is the final step in setting up composer-rest-server: Create a business card using Cloudant.

Create a member card with the next few properties:

Upload the attachment as follows:

In Chapter 7, we will deploy this.

b) Hyperledger Composer model

There are many ways to identify blockchain application cases, let us remember the important metrics of some good application cases mentioned in Chapter 3.

  • Does it involve a business network?
  • If so, is there a transaction that needs to be verified and auditable?
  • Is data transparency and data changes important?

After identifying the answers to these questions, brainstorming sessions are a good way to communicate, detailing the solution, identifying the best solution platform (such as IBM Food Security), or starting to create a custom application case.

The resource structure can be easily defined using the Hyperledger Composer modeling language, which is processed as a transaction and recorded on the ledger.

The CTO file uses three main elements to create a domain model for the business network definition:

  • a single namespace that contains all resource declarations in the file
  • A set of resource definitions that contain assets, transactions, participants, and events
  • Optional import declaration to import resources from other namespaces

In Chapter 7 of this book, we created a business network when creating blockchain and IoT solutions. Let's examine the code we use in more detail: namespaces are the basic definition of assets, events, participants, and transactions, as shown below.

The declaration of resources and enumerated types is shown in the following code:

The transaction process function is automatically called by the runtime when submitting a transaction using the Business Network Connection API;

For more information on the Hyperledger Composer modeling language, please visit the following link:

  • Https://
  • Https://

c) Hyperledger Composer Access Control Language

Hyperledger Composer has an access control file (.acl) that can be used to program business access control and network access control. Service access control is used for resources in a business network, while network access control refers to control of management network changes.

The following is an example of granting network access control:

Another example:

You can get more information about the Hyperledger Composer access control language by visiting the following link:


d) Hyperledger Composer transaction processing function

The Hyperledger Composer business network definition consists of a set of model files and a set of scripts. The script can contain transaction processing functions that execute the transaction process, which are defined in the template file of the business network.

The following is an example of a transaction execution script file:

As we have seen, when a transaction is submitted using the BusinessNetworkConnection API, the transaction handler function is automatically called by the runtime. The Decorators in the document are used to annotate the metadata functions required for runtime processing, and each transaction type has an associated registry for storing transactions.


The architecture described in this chapter involves many components and is somewhat complicated to implement. So far, we have determined that the combination of the Internet of Things and the blockchain can alleviate several problems and change the way modern food chains operate.

For example: increasing the transparency of information between members, enabling them to control data more effectively; improving data security; making processes more automated; minimizing intermediate links; and simplifying the chain as a whole.

We also see extensions to IoT devices and sensor capabilities that enable machine-to-machine interactions with minimal or no human intervention. These technology components bring unprecedented automation, reducing both supply costs and energy.

The integration of the blockchain with the Internet of Things will enable data exchange between edge devices such as sensors, barcodes and QR code scanning events and assets based on video recognition. Assets connected to the sensor will be able to record sensitive information such as the location and temperature of a particular warehouse, and can automatically record or update this information across the blockchain.

With a better understanding of the architecture and its technical components, we will be able to fully realize a solution for the use of the Internet of Things and blockchain for the modern food chain.

In the next chapter, we will learn how to create your own blockchain using the Internet of Things.

Source | "blockchain-based IoT project development"

Author | Maximilian Santos, Enio Mora

Editor | Carol

Produced | Blockchain Base Camp (blockchain_camp)