End to end tutorial to Trace Asset on Supply Chain with Blockchain and IoT
End to end tutorial to Trace Asset on Supply Chain with Blockchain and IoT

End-to-end tutorial to Trace Asset on Supply Chain with Blockchain and IoT

End to end tutorial to Trace Asset on Supply Chain with Blockchain and IoT 2

Before diving into the theoretics and hands-on knowledge to trace an asset on the supply chain, I’ll briefly go through the course of the article so that it’s easier for you to navigate through it.

First of all, we’ll touch the current challenges which a supply chain faces. Secondly, we’ll see how the famous duo of ‘Blockchain + IoT’ come to the rescue along with a brief architecture for the same. Then we’ll dive into hands-on practice.


For hands-on knowledge — we’ll use ESP8266 module, RFID scanner, Microsoft Azure IoT Hub, BigChainDB.

End to end tutorial to Trace Asset on SupplyChain with Blockchain and IoT 3


Supply chain management is not as easy as one might think to see from a bird’s eye. Mismanagement of a supply chain may cost firms millions of dollars, along with a dented reputation. Hence, there is a need to address the problems that revolve around the supply chain. With the advent of Distributed Ledger Technology (like the Blockchain) and IoT, efficient management of supply chain is possible.

Also, Read Our Next Article on Healthcare

Supply chain challenges in today’s world can be summarised as follows:

  1. Increase in globalization and global connectivity has lead to more complex supply chains.
  2. There are sudden and rapid changes in market environments. Businesses have to quickly react to them, and it becomes tough to align supply chain that quickly.
  3. There are multiple parties of suppliers, producers, distributors, consumers make the supply chain more complex, thereby making it tougher to coordinate.
  4. Presently there are very few firms who have employed the tools to predict and manage risks to react aptly.
  5. There is no clear transparency. One can’t be sure if the basic code of conduct is being followed.
  6. There is lacking trust among various stakeholders, so not all data is shared which makes reconciliation of data a tedious task.

Blockchain has become a hallmark for ‘trust economy’. Effectively, it is the lifeblood for the supply chain. The blockchain technology offers a decentralized way to record digital moments which is designed the be secure, transparent, robust, auditable, and efficient. Which is in a way perfect for supply chain management! The picture would be complete when IoT would be infused with it. IoT would provide a medium to connect the physical world with the digital world via the means of hardware. IoT sensors are capable of recording speed, temperature, humidity, and all other physical parameters and then convey them efficiently over the network so that analytics can be drawn out of the same.

End to end tutorial to Trace Asset on SupplyChain with Blockchain and IoT 4

Initiation triggers source of information through attached sensors. The raw information gathered from the sensors is transmitted over the network to the IoT hub where integration and consolidation of data take place. In the analysis section, risk prediction and management are done. According to the insights derived, human/machine behavior is triggered.

So what are the features of an ideal supply chain?

End to end tutorial to Trace Asset on SupplyChain with Blockchain and IoT 5

  1. Transparency: Equal and 100% information should be available and visible to every stakeholder.
  2. Elasticity: The solution should empower the stakeholders to take rapid actions to quickly changing environments.
  3. Increased trust: There would be enhanced trust not between various stakeholders but upon the system upon which they’d be commonly operating.

Bird’s eye view

End to end tutorial to Trace Asset on Supply Chain with Blockchain and IoT 6

  1. Install Arduino inside ESP8266 module.
  2. Setup MFRC522 on ESP8266 module.
    	/* READ AN RFID TAG */
    /*Use this sketch to verify that you have a working installation of the NodeMCU + MFRC522
    * ---------------------------------------
    *             MFRC522      Arduino
    *             Reader/PCD   Uno/101
    * Signal      Pin          Pin
    * ---------------------------------------
    * RST/Reset   RST          D3
    * SPI SS      SDA(SS)      D8
    * SPI MOSI    MOSI         D7
    * SPI MISO    MISO         D6
    * SPI SCK     SCK          D5
    #define RST_PIN         D3
    #define SS_PIN          D8
    MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
    void setup() {
    	Serial.begin(9600);		// Initialize serial communications with the PC
    	SPI.begin();			// Init SPI bus
    	mfrc522.PCD_Init();		// Init MFRC522
    void loop() {
    	// Look for new cards
    	if ( ! mfrc522.PICC_IsNewCardPresent()) {
    	// Select one of the cards
    	if ( ! mfrc522.PICC_ReadCardSerial()) {
    	// Dump debug info about the card; PICC_HaltA() is automatically called
    	 dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
    void dump_byte_array(byte *buffer, byte bufferSize) {
      for (byte i = 0; i < bufferSize; i++) {
        Serial.print(buffer[i] < 0x10 > " 0" : " ");
        Serial.print(buffer[i], HEX);
  3. To connect with Azure IoT Hub, register your device on it and then get the connection string. After that, get your SAS token.
    	$ npm install iothub-explorer -g
    $ iothub-explorer login "*connection string*" 
    $ iothub-explorer sas-token *registeredDeviceName* -d 600000
  4. Arduino Sketch MQTT using PubSub client
     * Install PubSubClient and WiFiManager libraries
     * Register your IoT devices on Azure IoT Hub
     * Open a SAS token with the iothub-explorer
    const char* mqtt_server = "technetwork.azure-devices.net";
    WiFiClientSecure espClient;
    PubSubClient client(espClient);
    long lastMsg = 0;
    char msg[50];
    int value = 0;
    void setup() {
      Serial.begin(115200);    // Initialize serial communications
      WiFiManager wifiManager;
      client.setServer(mqtt_server, 8883);
    void reconnect() {
      // Loop until we're reconnected
      while (!client.connected()) {
        Serial.print("Attempting MQTT connection...");
        // Attempt to connect
        if (client.connect("**your_registered_device_id**", "**your_iot_hub_name**.azure-devices.net/**your_registered_device_id**","**your_sas_token**")) {
        } else {
          Serial.println("can't connect... trying again in 5 seconds");
    void loop() {
       if (!client.connected()) {
       client.publish("devices/esp8266_0BDAD6/messages/events/", "Test message");
        //publish an event every 5 seconds

    To verify that your messages are going through, do the following:

    $ iothub-explorer monitor-events *your registered device* --login "*your connection string*"
  5. Getting MQTT messages from Azure IoT Hub
    	var EventHubClient = require('azure-event-hubs').Client;
    var connectionString = 'HostName=technetwork.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=T70OrqQPOP26k/Izl7d1nrRpnmYxkolYIDAk4GtXTvk=';
    var printError = function (err) {
    var client = EventHubClient.fromConnectionString(connectionString);
        .then(function (partitionIds) {
            return partitionIds.map(function (partitionId) {
                return client.createReceiver('$Default', partitionId, { 'startAfterTime' : Date.now()}).then(function(receiver) {
                    console.log('Connected to Azure IoT hub');
                    receiver.on('errorReceived', printError);
                    receiver.on('message', receivedTransaction);
  6. Create transaction in BigchainDB
    	function create_asset(assetid){
      const tx = driver.Transaction.makeCreateTransaction(
          { asset_id: assetid },
          { what: 'Creation of the asset' , time: Date.now(), asset_id: assetid},
          [ driver.Transaction.makeOutput(
      // Sign the transaction with private keys
      const txSigned = driver.Transaction.signTransaction(tx, tetrapak.privateKey)
        .then(() => conn.pollStatusAndFetchTransaction(txSigned.id))
        .then(retrievedTx => {
          console.log('Transaction', retrievedTx, 'successfully posted.')
          assets[assetid] = retrievedTx;
          assets[retrievedTx] = assetid;
  7. Transfer asset in bigchainDB
    	function transfer_asset(assetid){
      console.log('Transaction',   assets[assetid].id, 'successfully posted, now transferring')
      // (tx, fromPublicKey, fromPrivateKey, toPublicKey, metadata)
          const txTransfer = driver.Transaction.makeTransferTransaction(
              {what: "Transfer of the asset", time:Date.now(), asset_id:assetid},
          const txTransferSigned = driver.Transaction.signTransaction(txTransfer, tetrapak.privateKey)
          // send it off to BigchainDB
              .then(() =>
              .then( txTransferSigned => console.log(util.inspect(txTransferSigned)))
  8. Listening to transactions on bigchainDB
    	const ws = new WebSocket('wss://test.ipdb.io/api/v1/streams/valid_transactions');
    const driver = require('bigchaindb-driver')
    let conn = new driver.Connection('https://test.ipdb.io/api/v1/', {
        app_id: '95a772f7',
        app_key: '247aebb45369a85075dc79f7013353d0'
    const ws = new WebSocket('wss://test.ipdb.io/api/v1/streams/valid_transactions');
    ws.on('open', function open() {
      console.log('WebSocket connection to IPDB opened');
    ws.on('message', function incoming(data) {
      var o = JSON.parse(data);
      conn.getTransaction(o.transaction_id).then(details =>   {
        if (details.metadata.asset_id != null)
          io.emit('transactionCreated', details);

And then run the express server!

Launch your blockchain project with Quillhash: https://quillhash.typeform.com/to/KQ5Hhm

Thanks for reading. Also, do check out our earlier blog posts.