EVRYTHNG Developer Hub

Welcome! Here's where you'll find what you need to start working with EVRYTHNG as quickly as possible. There are comprehensive guides, documentation, and support if you get stuck. We encourage you to dive in and explore.

Create Free Account Read Documentation Get Support

Chainpoint

This tutorial will demonstrate how to leverage the value of a blockchain to add extra degrees of trust to EVRYTHNG actions. By associating an action with a blockchain transaction the action becomes more trustworthy, due to the immutability of the blockchain. In particular, the public Bitcoin blockchain will be used via the Chainpoint protocol and Tierion API.

After you have completed the steps outlined below, you will have a working proof-of-concept solution in place that allows validation of the journey of events and origins of your products using a public blockchain and key EVRYTHNG Platform features.


The Problem of Proof

A common concern with off-the-shelf products in the market today is one of trust when it comes to product origin, traceability, and provenance. When a consumer buys a product, they want to be confident that it is from the origin it says it is from, or that it actually contains the ingredients listed on the label. Specific examples include organic foods, or those claiming to come from a sustainable source. Why should a consumer place their trust in the claims of a brand if they can’t independently verify those claims themselves, or be provided with reasonable proof? Similarly, transparency between supply chain partners along the product’s journey to the hands of customers can also be improved along these lines.

As mentioned above, the value of a blockchain in this context is that it enables extra trust on the behalf of the consumer to be placed in a brand if it uses blockchain transactions to verify the origins or provenance chain of their products. A consumer should be able to view and understand the blockchain transactions related to their purchase and feel more confident that the claims of the manufacturer are valid.

For all products that are integrated with the EVRYTHNG Platform, they are likely to have a history of actions created that detail their journey from birth to the shop shelf and then the consumer’s home. Therefore an easy way to add this much-needed proof for trust is to be able to ensure that these actions describe events that can be reliably verified by an immutable and publicly auditable record.

Sounds like a job for the blockchain - the only problem is that of scale. Many thousands of such actions may occur across a global supply chain every minute in a large-scale deployment, but only a much smaller number are actually able to be verified on the blockchain in the same amount of time.


Overview of Solution

Chainpoint protocol using Merkle trees to scale the proofing solution (source https://chainpoint.org)

Chainpoint protocol using Merkle trees to scale the proofing solution (source https://chainpoint.org)

Our solution to this problem is based on a protocol called Chainpoint. Simply put, Chainpoint provides two things: first, it provides a more optimized way of linking transactions to a public blockchain by allowing us to batch them. In short, instead of sending one transaction for each supply chain operation you wish to verify, it allows us to batch thousands of them in a single transaction on the blockchain. The transactions are not directly transmitted to the blockchain but first aggregated into a Merkle Tree which root is then sent to the Bitcoin or Ethereum blockchain.

The proposed solution will be using the EVRYTHNG Platform, and will involve a few key parts:

  • A Thng representing an individual physical product.
  • An action type representing a stage in the product’s journey that must be publicly verifiable.
  • Another action type representing the creation of the blockchain transaction and proof.
  • A Reactor script that contains the code enabling the automation of the blockchain transactions.
  • An account with the Tierion API, used to add transactions to the Bitcoin blockchain.

In short, each action created on the product’s Thng must be automatically verified with an equivalent blockchain transaction. The use of the EVRYTHNG Reactor allows this to happen using the onActionCreated() and onScheduledEvent() handlers. The former will be used to detect the creation of an action that requires a blockchain transaction (by the presence of the blockchainValidate custom field), and the latter to run one hour later to obtain the finalized transaction ID when it has been publicly verified and added to the blockchain. This transaction ID will then be attached to a new action on the same Thng representing the end of the process, and to serve as a record resource.

The entire process is summarized in the sequence diagram below:


EVRYTHNG Account Setup

To get started, create your EVRYTHNG account (or log into an existing one) via the EVRYTHNG Dashboard.

Once logged in, create a new project using the ‘Create project’ button at the top of the left-hand navigation. Give the project a suitable name (such as ‘Chainpoint Tutorial’), and then save it with the modal’s ‘Create project’ button.

Next, with the new project selected in the drop-down on the left hand side, choose ‘Applications’, then ‘Add new’ at the top of the page to create an application with the project. It is this application that will house the Reactor script itself. Choose a suitable name (such as ‘Chainpoint Reactor’) and save it.

Create a Thng to represent the product whose journey will be blockchain validated on the ‘Thngs’ page, and choosing ‘Add new’. Give the Thng a suitable name (such as ‘Bag of Organic Coffee’), and optionally a description.

Finally, create two new custom action types using the ‘Action Types’ section of the left-hand navigation:

  • _movement - representing a real-world movement of the product through its supply chain.
  • _blockchainValidated - representing the completed addition of a blockchain transaction to add proof to an _movement action.

Now all the required resources in your EVRYTHNG account are in place, it is time to install the Reactor script that will perform the interactions with the blockchain.


Reactor Script Overview

The key piece of this solution is the use of a Reactor script - allowing developer-written rules and logic to be executed in response to various other events that take place within the Platform. In this case, contacting the Tierion blockchain API when an EVRYTHNG action is created (with certain criteria), and on a timed schedule later on. It is the custom Reactor script that allows the integration to take place in such an automated fashion, right from within the account.

The script in question is located in the reactor-chainpoint repository, and comes fully packaged for re-use, with only minimal configuration required. Each of the phases of the script is explained below.

When an action is created with the blockchainValidate custom field set to true, add the action to the blockchain with the hashapi-lib-node npm library. This logical condition is specified using a Reactor filter, a special comment positioned above the event handler definition:

// @filter(onActionCreated) action.customFields.blockchainValidate=true
function onActionCreated(event) {
  logger.info('Blockchain validation for action requested!');

  authenticate()
    .then(() => submitHashToBlockchain(event.action))
    .then(schedule => logger.info(`Reactor scheduled for ${schedule.executeAt}`))
    .catch(handleError)
    .then(done);
}

The submitHashToBlockchain() method uses a hash of the action itself to be added to the blockchain, and makes the request to the Tierion API. At the same time, it will create a Reactor schedule one hour in the future to get the verified transaction ID:

const submitHashToBlockchain = (action) => {
  const hash = sha256.update(JSON.stringify(action), 'utf8').digest('hex');
  logger.debug(`Action SHA256: ${hash}`);

  return submitHashItem(hash).then((result) => {
    const receipt = result.receiptId;

    // Set the receipt ID
    app.thng(action.thng).property('receiptid').update(receipt);

    // Schedule reactor check in 1 hour
    const event = { receipt, action: action.id, thng: action.thng };
    logger.debug(`event: ${JSON.stringify(event)}`);
    return app.reactor.schedule().create({
      event,
      executeAt: Date.now() + VALIDATION_WAIT_MS,
      description: 'Initial check for blockchain trx',
    });
  });
};

When that schedule occurs, use the receipt ID obtained in step 1 to retrieve the blockchain transaction ID (now that the transaction has been accepted into the blockchain by peers):

function onScheduledEvent(event) {
  logger.info('Checking for confirmed actions on blockchain...');

  authenticate()
    .then(() => createValidationAction(event))
    .then(action => logger.info(`Created action: ${action.id}`))
    .catch(handleError)
    .then(done);
}

Using the transaction ID, the createValidationAction() method creates the final action on the same Thng, and includes the bitcoinTrxId from Tierion:

const createValidationAction = (event) => {
  getReceipt(event.receipt).then((transaction) => {
    logger.info(`Blockchain transaction: ${JSON.stringify(transaction)}`);
    const receiptObj = JSON.parse(transaction.receipt);

    return app.action(ACTION_TYPE_VALIDATION).create({
      thng: event.thng,
      customFields: {
        actionId: event.action,
        bitcoinTrxId: receiptObj.anchors[0].sourceId,
        receiptId: event.receipt,
        fullReceipt: transaction,
      },
    });
  });
};

Reactor Script Installation

To install the Reactor script in your account, open the reactor-chainpoint repository and copy the contents of main.js into the ‘Reactor’ field on the application’s page in the Dashboard. At the same time, add the required dependencies from package.json to the right hand side panel of the same section of the page:

Save the new Reactor script and its dependencies with the ‘Update’ button at the bottom of the section. The Platform will build the script and make it ready to run whenever either of the two events are called.

Notice that there are two configurable values that are currently blank - USERNAME and PASSWORD. These are the only two values you will need to update, and will be given values in the next section after registering with Tierion. Everything else must be left as-is.


Tierion Account Setup

We will use the Tierion API to create transactions on the blockchain. The first step is to create a new Tierion account, in order to generate the credentials required by the Reactor script. Do this now at https://tierion.com/signup and make a note of your elected username and password.

Once this is done and you can log into your new Tierion account, go back to the ‘Reactor’ section of the application page in the EVRYTHNG Dashboard. Insert your Tierion email address as USERNAME, and your password as PASSWORD. Choose ‘Update’ to save and build the new Reactor script.

Everything is now in place for this blockchain integration to be tested with a real action, in the next section.


Testing It Out

In order to test the integration, we must create an action on the Thng that meets the filter applied to the onActionCreated() event handler inside the Reactor script. As you can see, this criteria is that the action itself contains a custom field with a key blockchainValidate and a value of true. An API request that creates such an action is shown below using the application’s Trusted Application API Key (available from the application’s page on the Dashboard). The value of thng should be the ID of the Thng you created earlier:

Substitutions: :thngId

curl -H "Content-Type: application/json" \
  -H "Authorization: $TRUSTED_APPLICATION_API_KEY" \
  -X POST 'https://api.evrythng.com/actions/_movement' \
  -d '{
  "type": "_movement",
  "thng": ":thngId",
  "customFields": {
    "blockchainValidate": true
  }
}'

Create one of these actions now using your own Thng ID. After a few seconds you should see some entries in the ‘Logs’ section of the ‘Reactor’ section of the application’s page in the Dashboard, showing the receipt ID obtained from Tierion, which will be used in an hour’s time to retrieve the actual verified blockchain transaction ID:

Wait one hour, so that the blockchain peers have time to verify your transaction, and for the Reactor schedule to run. Once it has done so, you should see some more logs in the ‘Reactor’ section like the ones below. These are the results of waiting an hour, with the final transaction ID now known.

A new action of type _blockchainValidated should also now be visible on the Thng. Go to the ‘Thngs’ section of the Dashboard, choose the Thng, then choose the button on the right of the ‘Activity’ section to see the actions performed on it. There should be two - the original movement action, and the blockchain validation action containing the verified transaction ID.

You can find the complete transaction record online using any blockchain viewer website, such as blockexplorer.com. So the example action above contains the verified transaction ID of 13d2b02f24670c7e76e401840710e8808732d4fbedc400d2d9fbfa12e21a05ec. The full details on the blockexplorer.com website show the confirmations added by all the peers on the blockchain network:


Conclusions

If you have followed along with this tutorial in your own EVRYTHNG account - congratulations! You now have a fully working prototype blockchain integration that will keep a permanent, immutable, publicly auditable record of important events that happen to Thngs in your account.

As an extension, you could add more action types representing the journey of the product, or even integrate what you have learned here with a real-life device or use-case that you have already set up.

You can learn more about the Reactor here, the Chainpoint protocol here, and the Tierion API here.