How to Trace Assets on Supply Chain with Blockchain & IoT

How to Trace Assets on Supply Chain with Blockchain & IoT

How to Trace Assets on Supply Chain with Blockchain & IoT

How to Trace Assets on Supply Chain with Blockchain & IoT

How to Trace Assets on Supply Chain with Blockchain & IoT

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!

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

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

Telegram | Twitter | Facebook | LinkedIn

3,651 Views

Blockchain for dog nose wrinkles' Ponzi makes off ~$127M🐶

Project promised up to 150% returns on investment in 100 days, raising about 166.4 billion South Korean won — or about $127 million — from 22,000 people.

Latest blogs for this week

Understanding Fuzzing and Fuzz Testing: A Vital Tool in Web3 Security

Read Time: 5 minutes When it comes to smart contracts, ensuring the robustness and security of code is paramount. Many techniques are employed to safeguard these contracts against vulnerabilities
Read More

How EigenLayer’s Restaking Enhances Security and Rewards in DeFi

Read Time: 7 minutes Decentralized finance (DeFi) relies on Ethereum staking to secure the blockchain and maintain consensus. Restaking allows liquid staking tokens to be staked with validators in
Read More

ERC 404 Standard: Everything You Need to Know

Read Time: 7 minutes Introduction Ethereum has significantly shaped the crypto world with its introduction of smart contracts and decentralized applications (DApps). This has led to innovative developments in
Read More

DNS Attacks:  Cascading Effects and Mitigation Strategies

Read Time: 8 minutes Introduction DNS security is vital for a safe online space. DNS translates domain names to IP addresses, crucial for internet functionality. DNS ensures unique name-value
Read More

EIP-4844 Explained: The Key to Ethereum’s Scalability with Protodanksharding

Read Time: 7 minutes Introduction  Ethereum, the driving force behind dApps, has struggled with scalability. High fees and slow processing have limited its potential. They have kept it from
Read More

QuillAudits Powers Supermoon at ETH Denver!

Read Time: 4 minutes Calling all the brightest minds and leaders in the crypto world! Are you ready to build, connect, and innovate at the hottest event during ETH
Read More

Decoding the Role of Artificial Intelligence in Metaverse and Web3

Read Time: 7 minutes Introduction  Experts predict a transformative shift in global software, driven by AI and ML, marking the dawn of a new era. PwC predicts AI will
Read More

Transforming Assets: Unlocking Real-World Asset Tokenization

Read Time: 7 minutes In the blockchain, real-world assets (RWAs) are digital tokens that stand for tangible and conventional financial assets, including money, raw materials, stocks, and bonds. As
Read More
Scroll to Top

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: $200K+