August 2019

Volume 34 Number 8

[Blockchain]

Secure Your Supply Chain with the Azure IoT and Blockchain Cloud

By Stefano Tempesta | August 2019

The adoption of blockchain and IoT technologies has the potential to help the manufacturing industry in making supply chains more secure and the associated processes more transparent. Chances are, you’ve heard of blockchain only in the context of cryptocurrency, so how is blockchain relevant to supply chains?

A Distribution Supply Chain Example

The traditional supply chain management structure has limitations in the reliability and accuracy of measurements, and in the transparency of processes among all parties involved. IoT and blockchain technologies represent a potential solution to address these challenges by introducing devices to automate the collection of metrics at any stage of the supply chain, as well as a distributed digital ledger for storing transaction logs in an immutable way. In addition, blockchain smart contracts can use rule-based intelligence to perform validation on this data and update the state of each supply chain stage for all parties involved, in a completely trustworthy and transparent manner. For example, terms, conditions and any other logic can be coded into a smart contract for verifying the correct execution of a transaction of goods between two stages of the supply chain.

Figure 1 simplifies a distribution supply chain in which a food producer transfers goods to a food processing company for packaging and shipping. The produce is sealed at a set temperature and humidity level, and these or similar conditions must be maintained during transportation to the warehouse and retail store.

A Distribution Supply Chain Using a Smart Contract
Figure 1 A Distribution Supply Chain Using a Smart Contract

These conditions are coded in a blockchain smart contract, as illustrated later in this article. IoT devices with sensors for measuring temperature and humidity are installed in the containers and carriers storing and shipping goods. Telemetry data is captured at regular intervals during the storage and distribution phases, and the actual metrics validated against the set levels in the smart contract. If the values for temperature or humidity exceed such levels, the state of the transport of the goods changes to “out of compliance” and this state is reflected in the transaction log stored inside the blockchain digital ledger. All participants in the supply chain can view the state and details of the contract at any point in time. The counterparty responsible for storage or transportation of goods will specify the next counterparty handling the parcels as the next stage, and the registered IoT devices will forward telemetry data to a central IoT hub. This allows the initiator of the supply chain and all its participants to identify which counterparty didn’t fulfill the compliance regulations if at any point in the process either the temperature or humidity requirements weren’t met.  

A supply chain requires a state transition diagram to articulate the possible flows, and the various transition functions at each state. Each party in the supply chain is only allowed to take certain actions depending on their role and the state of the products being transported. States, workflows and involved parties are described in a smart contract and deployed in Azure Blockchain Workbench, as described later in the article. The example provided here implements the four states shown in Figure 2.

Figure 2 The Four States of the Example Supply Chain

State Description
Created Indicates that the contract has initiated, and tracking is in progress.
InTransit Indicates that a counterparty currently is in possession and responsible for goods being transported.
Completed Indicates the product has reached its intended destination.
OutOfCompliance Indicates that the agreed upon terms for temperature and humidity conditions weren’t met.

Azure IoT Central

The example in this article uses Azure IoT Central (bit.ly/2X6Jlwe) to connect the IoT devices. IoT Central is a fully managed Software-as-a-Service (SaaS) solution that makes it easy to connect, monitor and manage devices at scale. The initial setup of devices is simplified by adopting device templates for a variety of platforms, and the project implementation of the IoT component of the supply chain solution can benefit from device simulation for testing purposes.

The IoT solution implemented for the distribution supply chain in the current example consists of a cloud-based gateway that receives telemetry data from device sensors and the devices themselves that connect to IoT Central. Before being allowed to stream any data, IoT devices are registered with the cloud platform and are assigned an identity. When connecting to IoT Central, a device sends its identity information, along with sensor data. If the device fails to send this identity information, the connectivity will fail. Once a successful connection is established between the devices and the cloud gateway, data is ingested at set intervals. Azure IoT Central facilitates this flow by providing device registration and data ingestion capabilities, as well as visualization of telemetry points on a dashboard, as shown in Figure 3.

The Azure IoT Central Dashboard
Figure 3 The Azure IoT Central Dashboard

Figure 3 shows measurements produced by a simulated device. In Azure IoT Central you can define a device template for the devices that connect to your application, a sort of blueprint that defines the characteristics and behavior of a type of device. A template can be used for connecting a physical device or for simulating the streaming of data within certain boundaries. Simulated data includes:

  • Device properties that are set by a device and are read-only in the application.
  • The status, which determines the behavior of the device.
  • Measurements specific to the installed sensors.

The setup of an application in IoT Central starts by defining at least one device template and then adding a device, either real or simulated. You can access the IoT Central dashboard at bit.ly/2RBtWD6, and then navigate to the Azure IoT Central Application Manager page to start creating a new Azure IoT Central application. Once you create an application, access the Device Explorer section to add a real or simulated device associated with each device template in the application. When you create a device template, Azure IoT Central generates a simulated device from the template. The simulated device generates telemetry that enables you to test the behavior of your application before you connect a real device. From the Measurements tab, you can specify the measurements, such as telemetry, event, and state, sent by the device, and define the rules associated with the device.

After setting up a device and its measurements, you can use events to define point-in-time data the device should send when an event such as an error or a component failure occurs. Azure IoT Central can simulate device events to enable you to test the behavior of your application before you connect a real device. After a short while, the Measurements tab will show a chart of the events randomly generated from your simulated connected device.

Finally, you create a rule that runs a custom action when the measured temperature or humidity exceeds the specified conditions. In this case, I configured a Microsoft Flow action, as shown in Figure 4, to run when the humidity level is greater than 60 and the temperature greater than 8.

Configuring a Microsoft Flow Action
Figure 4 Configuring a Microsoft Flow Action

Microsoft Flow

Why Flow? Blockchain networks are isolated from the outside world, meaning that no data produced “off-chain” can be brought in. Smart contracts operate on data stored within the blockchain itself. The Azure Blockchain Development Kit (bit.ly/2TkG23Z) is an extension to the capabilities of Azure Blockchain Workbench (more on that in a moment). The Blockchain Dev Kit incorporates Azure services for key management, off-chain identity and data, monitoring, and messaging APIs into a reference architecture that can be used to rapidly build blockchain-based applications that integrate with any external system. With Flow, it’s possible to send a message to the Azure Service Bus deployed as part of Azure Blockchain Workbench and transfer data, securely, to a blockchain digital ledger. Figure 5 shows the trigger of the flow when a rule is fired in IoT Central.

How a Flow Is Triggered in IoT Central
Figure 5 How a Flow Is Triggered in IoT Central

A message is then prepared and eventually placed onto the Azure Blockchain Workbench Service Bus, in accordance to the REST API-based integration pattern described at bit.ly/31WqmIs. In preparing the message to send to Service Bus, the following parameters are created as part of the flow itself:

  • requestId: This is a unique value to identify a request; in Flow, this can be implemented by a variable with the expression guid.
  • timestamp: This is the date and time of the request; in Flow, this can be obtained by extracting the current time instant’s ticks. However, as there are 10 million ticks in a second, this would result in a really big number, so I typically calculate the current Unix epoch time, which is the number of seconds that have elapsed since Jan. 1, 1970 (midnight UTC).

In Flow, a timestamp can be easily calculated with the subtraction expression:

sub(variables('TicksNow'), variables('TicksUnixEpoch'))

Here, TicksNow is an integer variable defined as ticks(utcNow()), and TicksUnixEpoch is another variable defined as ticks(‘1970-01-01’).

The Service Bus message also requires:

  • userChainIdentifier: The blockchain address of the user or device that was created on the blockchain network.
  • contractLedgerIdentifier: The blockchain address of the contract on the ledger.
  • workflowFunctionName: The name of the smart contract’s function to invoke.
  • Parameters: An array of objects identifying telemetry data.

The JSON format of this message is as follows:

{
  "requestId": "",
  "userChainIdentifier": "",
  "contractLedgerIdentifier": "",
  "workflowFunctionName": "ReadTelemetry",
  "Parameters": [
    { "name": "humidity", "value": "" },
    { "name": "temperature", "value": "" }
    { "name": "timestamp", "value": "" }
  ]
}

Azure Blockchain Workbench

The initial objective of blockchain technology was to facilitate trusted fiscal transactions between two parties without the need for a third party, such as a bank, to be involved. Because blockchain relies on a decentralized, networked system, it’s harder to corrupt. If the information on one of the blocks is edited, all others viewing that block can see the edits that have been made. The introduction of blockchain technology into supply chains can help prevent issues such as fraud and counterfeiting. Transactions on the blockchain are stored and distributed across multiple nodes within the network. These transactions, or records, are very secure due to how the blockchain works (see my article at bit.ly/2ZQcm16 for more information about cybersecurity with blockchain), which makes this technology the perfect method for transparently and securely recording transactions in an independent and immutable log. In the context of a supply chain, in addition to a transaction log, blockchain smart contracts verify and enforce an agreement between two or more parties involved in a transaction. Smart contracts allow for credible transactions to happen without authorization and verification by a central authority. Also, these transactions are trackable and irreversible.

The blockchain ledger in this solution is hosted in Azure; specifically, it’s an Ethereum installation deployed as part of Azure Blockchain Workbench. With Azure Blockchain Workbench (bit.ly/2XBhWqw), you can configure and deploy a consortium network in just a few minutes, thanks to automatic ledger deployment, network construction and pre-built blockchain commands that greatly reduce infrastructure deployment time. Once the necessary infrastructure is provisioned, you can code your smart contracts and then deploy them in Blockchain Workbench for execution. Blockchain Workbench builds a Web UI automatically, with no coding, after your smart contract’s workflow, and allows you to keep track of any status change. For example, the message sent by IoT Central using Flow sends the measured values for temperature and humidity. A smart contract validates these values, and if they don’t meet the conditions coded in the smart contract itself, it will set the status of this transaction to Out of Compliance. This stage of the supply chain is then invalid, and the process won’t (or shouldn’t) progress to the next stage. Figure 6 shows the first stage of execution of the Telemetry smart contract used in this supply chain solution: A new contract is created between two parties involved; a device is registered for capturing telemetry data; and the initial conditions for humidity and temperature are set.

The First Stage of Execution of the Telemetry Smart Contract
Figure 6 The First Stage of Execution of the Telemetry Smart Contract

The Telemetry smart contract in Figure 7 implemented in Solid­ity programming language (solidity.readthedocs.io) for the Ethereum platform, defines parties, properties and states, which all together are a representation of the status of the contract at any given time. Supply chain parties are identified by a blockchain address; in Azure Blockchain Workbench, this is the user or device address as registered on the platform. To access Blockchain Workbench, parties have to be registered in Azure Active Directory. States represents an enumeration of stages in the supply chain process (contract created, goods in transit, transaction completed or out of compliance recorded), as well as the two different types of sensors in use in this example (humidity and temperature). Enumeration allows for more entries to be added easily, should the supply chain process require additional stages or introduce different sensor types.

Figure 7 The Telemetry Smart Contract

contract Telemetry
{
  // States
  enum StateType { Created, InTransit, Completed, OutOfCompliance }
  enum SensorType { None, Humidity, Temperature }
  // Parties
  address public Owner;
  address public InitiatingCounterparty;
  address public Counterparty;
  address public PreviousCounterparty;
  address public Device;
  address public SupplyChainOwner;
  address public SupplyChainObserver;
  // Properties
  StateType public State;
  SensorType public ComplianceSensorType;
  int public MinHumidity;
  int public MaxHumidity;
  int public MinTemperature;
  int public MaxTemperature;
  int public ComplianceSensorReading;
  bool public ComplianceStatus;
  string public ComplianceDetail;
  int public LastSensorUpdateTimestamp;

The UI for entering a new contract in Blockchain Workbench is generated automatically based on the constructor of the Telemetry smart contract in Figure 8. This constructor sets the initial conditions for the transportation process that have to be met by all parties involved in the supply chain. It also sets the initial state to StateType.Created.

Figure 8 The Telemetry Smart Contract Constructor

constructor(address device, address supplyChainOwner, address supplyChainObserver,
  int minHumidity, int maxHumidity, int minTemperature, int maxTemperature) public
{
  ComplianceStatus = true;
  ComplianceSensorReading = -1;
  InitiatingCounterparty = msg.sender;
  Owner = InitiatingCounterparty;
  Counterparty = InitiatingCounterparty;
  Device = device;
  SupplyChainOwner = supplyChainOwner;
  SupplyChainObserver = supplyChainObserver;
  MinHumidity = minHumidity;
  MaxHumidity = maxHumidity;
  MinTemperature = minTemperature;
  MaxTemperature = maxTemperature;
  State = StateType.Created;
  ComplianceDetail = "N/A";
}

Finally, when telemetry data is streamed and a rule exception occurs in IoT Central, the flow described earlier is executed, which in turn sends a message to Blockchain Workbench to invoke the ReadTelemetry function in Figure 9. This function validates the input values for humidity or temperature recorded by the IoT device, and raises an out-of-compliance state if the conditions set in the first stage aren’t met.

Figure 9 The ReadTelemetry Function

function ReadTelemetry(int humidity, int temperature, int timestamp) public
{
  if (Device != msg.sender)
  {
    revert();
  }
  if (State == StateType.Completed || State == StateType.OutOfCompliance)
  {
    revert();
  }
  LastSensorUpdateTimestamp = timestamp;
  if (humidity < MinHumidity || humidity > MaxHumidity)
  {
    ComplianceSensorType = SensorType.Humidity;
    ComplianceSensorReading = humidity;
    ComplianceDetail = "Humidity value out of range.";
    ComplianceStatus = false;
  }
  else if (temperature < MinTemperature || temperature > MaxTemperature)
  {
    ComplianceSensorType = SensorType.Temperature;
    ComplianceSensorReading = temperature;
    ComplianceDetail = "Temperature value out of range.";
    ComplianceStatus = false;
  }
  if (ComplianceStatus == false)
  {
    State = StateType.OutOfCompliance;
  }
}

From a UI perspective, Blockchain Workbench automatically records each state change and updates the overall status of the Telemetry contract accordingly, as shown in Figure 10.

The Updated Telemetry Contract
Figure 10 The Updated Telemetry Contract

Wrapping Up

The Azure platform offers a collection of services for building fully integrated solutions for the needs of Industry 4.0, including the IoT platform and managed blockchain services. In this article, I described a common blockchain pattern for IoT-enabled monitoring of goods as they move along a multi-party supply chain. Specific compliance rules must be met throughout the transportation process. In this scenario, an initiating party specifies contractual conditions, such as a required humidity and temperature range, to which a carrier on the supply chain must adhere. At any point, if the device takes a temperature or humidity measurement that’s out of range, the smart contract state will be updated to indicate that it’s out of compliance, recording a transaction on the blockchain and triggering remediating events downstream.

For those interested in learning more, a great starting point is the Azure reference architecture for supply chain, which you’ll find at bit.ly/2X7NIr7.


Stefano Tempesta is a Microsoft Regional Director, MVP on Azure, AI and Business Applications, and a member of Blockchain Council. A regular speaker at international IT conferences, including Microsoft Ignite and Tech Summit, Tempesta’s interests extend to blockchain and AI-related technologies. He created Blogchain Space (blogchain.space), a blog about blockchain technologies, writes for MSDN Magazine and MS Dynamics World, and publishes machine learning experiments on the Azure AI Gallery (gallery.azure.ai).

Thanks to the following Microsoft technical expert for reviewing this article: Danilo Diaz


Discuss this article in the MSDN Magazine forum