Blog

How to Trace Assets on Supply Chain with Blockchain & IoT

Table of Contents

Read Time: 5 minutes

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.

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.

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?

  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

  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
    */
    
    #include 
    #include 
    
    #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()) {
    		return;
    	}
    
    	// Select one of the cards
    	if ( ! mfrc522.PICC_ReadCardSerial()) {
    		return;
    	}
    
    	// Dump debug info about the card; PICC_HaltA() is automatically called
    	 dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
       delay(2000);
    }
    
    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
     *
     */
    
    #include 
    #include 
    #include 
    #include 
    
    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;
      wifiManager.autoConnect("TECHFEST_NODE_AP");
    
      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**")) {
          Serial.println("connected");
        } else {
          Serial.println("can't connect... trying again in 5 seconds");
          delay(5000);
        }
      }
    }
    
    void loop() {
    
       if (!client.connected()) {
          reconnect();
       }
       client.publish("devices/esp8266_0BDAD6/messages/events/", "Test message");
        //publish an event every 5 seconds
        delay(5000);
     }
    

    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) {
      console.log(err.message);
    };
    
    var client = EventHubClient.fromConnectionString(connectionString);
    client.open()
        .then(client.getPartitionIds.bind(client))
        .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);
                });
            });
        })
        .catch(printError);
    
  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(
                  driver.Transaction.makeEd25519Condition(tetrapak.publicKey))
          ],
          tetrapak.publicKey
      )
    
      // Sign the transaction with private keys
      const txSigned = driver.Transaction.signTransaction(tx, tetrapak.privateKey)
    
      conn.postTransaction(txSigned)
        .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(
    
              assets[assetid],
    
              {what: "Transfer of the asset", time:Date.now(), asset_id:assetid},
              [
                  driver.Transaction.makeOutput(
                      driver.Transaction.makeEd25519Condition(tetrapak_facility1.publicKey)
                  )
              ],
              0
          )
    
          const txTransferSigned = driver.Transaction.signTransaction(txTransfer, tetrapak.privateKey)
          // send it off to BigchainDB
          conn.postTransaction(txTransferSigned)
              .then(() =>
                  conn.pollStatusAndFetchTransaction(txTransferSigned.id))
              .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);
      console.log(data);
      
      conn.getTransaction(o.transaction_id).then(details =>   {
        console.log(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.


At QuillHash, we understand the Potential of Blockchain and have a good team of developers who can develop any blockchain applications like Smart Contracts, dApps,Smart Coins, DeFi, DEX on the any Blockchain Platform like EthereumEOS and Hyperledger.

To be up to date with our work, Join Our Community :-

Telegram | Twitter | Facebook | LinkedIn

1,727 Views

Related Articles

View All

Trending

#Alert🚨
$NUWA failed to rug on BSC and was front-run by the MEV bot 0x286E09932B8D096cbA3423d12965042736b8F850.

The bot made ~$110,000 in profit.

Are you concerned about your enterprise's security in Web 3.0? Look no further!

Let's delve deeper into and learn effective solutions to mitigate them. Our experts have covered unconventional approaches, from Zero- Trust Security Model to Bug Bounty Programmes.

🔻🔻🔻

Hey folks👋,

Web3 security is like a game of whack-a-mole, except the moles are hackers who keep popping up no matter how hard you hit them. 🤦‍♀️

But fear not; we've got some tips to keep your crypto safe⬇️⬇️

Unlock the power of Web3 for your enterprise with enhanced security measures!

💪🌐 Our latest blog post delves into the world of Web3-powered enterprises and how to ensure maximum security in this new frontier.🔒

Read part 1 of our series now: 🚀https://blog.quillhash.com/2023/03/15/web3-security-for-enterprise-web3-powered-enterprises-part-1/

#Web3… https://twitter.com/i/web/status/1638154504154628096

Load More

Amidst FTX Saga, Hacker Swept More Than $25 Million in 2nd week of November

The contract reinvested (the earn function was not called) before the user pledged (depositAll function) without settling the reward, which means that when the user pledged, the contract did not settle the previous reward and instead conducted a new investment.

Become a Quiffiliate!
Join our mission to safeguard web3

Sounds Interesting, Right? All you have to do is:

1

Refer QuillAudits to Web3 projects for audits.

2

Earn rewards as we conclude the audits.

3

Thereby help us Secure web3 ecosystem.

Total Rewards Shared Out: $190K+