19

Blockchain – Outside of Currencies

Digital currencies were the first-ever application of blockchain, which arguably didn't realize the technology's full potential. Although Bitcoin, the first major blockchain conceptualization, was introduced in 2008, it was not until years later that blockchain technology's possible applications in industries other than cryptocurrencies were realized. In 2010, discussion started regarding BitDNS, a decentralized naming system for domains on the internet. Then, Namecoin (https://en.bitcoinwiki.org/wiki/Namecoin) started in April 2011 with a different vision to Bitcoin, the sole purpose of which was to provision electronic cash. This can be considered the first example of blockchain usage other than purely as a cryptocurrency.

Next, in 2013, the first initial coin offering (ICO), MasterCoin, emerged, which paved the way for more ICOs. After that, Ethereum's ICO was hugely successful. With the availability of Ethereum in 2015, a general-purpose smart contract platform, more ideas started to emerge around various applications of blockchain technology. Since then, many use cases of blockchain technology in various industries have been proposed. In this chapter, five main industries have been selected, with the aid of use cases, for discussion:

  • The Internet of Things
  • Government
  • Health
  • Finance
  • Media

Let's begin with one of the most exciting use cases of blockchain technology: the Internet of Things.

The Internet of Things

The Internet of Things (IoT) has recently gained much traction due to its potential for transforming business applications and everyday life. IoT can be defined as a network of computationally intelligent physical objects (any objects, such as cars, fridges, and industrial sensors) that are capable of connecting to the internet, sensing real-world events or environments, reacting to those events, collecting relevant data, and communicating this over the internet.

This simple definition has enormous implications and has led to exciting concepts, such as wearables (such as health trackers or watches), smart homes, smart grids, smart connected cars, and smart cities, which are all based on this basic concept of an IoT device. After dissecting the definition of IoT, four functions come to light as being performed by an IoT device: sensing, reacting, collecting, and communicating. All of these functions are performed by using various components on the IoT device.

Sensing is performed by sensors. Reacting or controlling is performed by actuators; collection is a function of various sensors, and communication is performed by chips that provide network connectivity. One thing to note is that all of these components are accessible and controllable over the internet, via the IoT. An IoT device on its own is useful to some extent, but if it is part of a broader IoT ecosystem, it is more valuable.

In the next section, we'll introduce the typical architecture of an IoT-based ecosystem.

Internet of Things architecture

A typical IoT can consist of many physical objects connected to each other, and to a centralized cloud server. This is shown in the following diagram:

Figure 19.1: A typical IoT network

Elements of the IoT are spread across multiple layers, and various existing reference architectures can be used to develop IoT systems. A five-layer model can be used to describe IoT, which contains a physical object layer, device layer, network layer, services layer, and application layer. Each layer or level is responsible for various functions and includes multiple components. These are shown in the following table:

Application layer

Transportation, financial, insurance, and many others

Management layer

Data processing, analytics, security management

Network layer

LAN, WAN, PAN, routers

Device layer

Sensors, actuators, smart devices

Physical objects

People, cars, homes

Now, let's examine each layer in detail.

Physical object layer

This layer includes any real-world physical objects. It includes objects like cars, fridges, trains, and homes. In fact, anything that is required to be monitored and controlled can be connected to the IoT.

Device layer

This layer contains things that make up the IoT, such as sensors, transducers, actuators, smartphones, smart devices, and Radio-Frequency Identification (RFID) tags. There can be many categories of sensors, such as body sensors, home sensors, and environmental sensors, based on the type of work they perform. This layer is the core of an IoT ecosystem where various sensors are used to sense real-world environments. This layer includes sensors that can monitor temperature, humidity, liquid flow, chemicals, air, pressure, and much more. Usually, an Analog to Digital Converter (ADC) is required on a device to turn the real-world analog signal into a digital signal that a microprocessor can understand.

Actuators in this layer provide the means to enable control of external environments; for example, starting a motor or opening a door. These components also require digital to analog converters to convert a digital signal into analog. This method is especially relevant when control of a mechanical component is required by the IoT device.

Network layer

This layer is composed of various network devices that are used to provide internet connectivity between devices and to the cloud, or servers that are part of the IoT ecosystem. These devices can include gateways, routers, hubs, and switches. This layer can include two types of communication.

First, there is the horizontal means of communication, which includes radio, Bluetooth, Wi-Fi, Ethernet, LAN, Zigbee, and PAN, and can be used to provide communication between IoT devices. This layer can optionally be included in the device layer as it physically resides on the device layer where devices can communicate with each other.

Second, we have communication to the next layer, which is usually through the internet and provides communication between machines and people or other upper layers.

Management layer

This layer provides the management layer for the IoT ecosystem. This includes platforms that enable the processing of data gathered from the IoT devices and turning it into meaningful insights. Device management, security management, and data flow management are included in this layer. It also manages communication between the device and application layers.

Application layer

This layer includes applications running on top of the IoT network. This layer can consist of many applications, depending on the requirements, such as transportation, healthcare, financial, insurance, or supply chain management. This list, of course, is not an exhaustive list by any stretch of the imagination; there is a myriad of IoT applications that can fall into this layer.

With the availability of cheap sensors, hardware, and bandwidth, IoT has gained popularity in recent years and currently has applications in many different areas, including healthcare, insurance, supply chain management, home automation, industrial automation, and infrastructure management. Moreover, advancements in technology such as the availability of IPv6, smaller and more powerful processors, and better internet access have also played a vital role in the popularity of IoT.

IPv6 is the latest version of the internet protocol, which, with a size of 128 bits, offers more address space compared to the 32-bit IPv4. More information on IPv6 is available here: https://en.wikipedia.org/wiki/IPv6

In the next section, we'll discuss some advantages of IoT and blockchain convergence.

Benefits of IoT and blockchain convergence

The benefits of IoT with blockchain technology range from saving costs to enabling businesses to make vital decisions, and thus improve performance based on the data provided by the IoT devices. Even in domestic usage, IoT-equipped home appliances can provide valuable data for cost savings. For example, smart meters for energy monitoring can provide valuable information on how the energy is being used and can convey that back to the service provider. Raw data from millions of IoT devices is analyzed and provides meaningful insights that help in making timely and efficient business decisions.

The usual IoT model is based on a centralized paradigm, where IoT devices usually connect to a cloud infrastructure or central servers to report and process the relevant data back. This centralization poses certain possibilities of exploitation, including hacking and data theft. Moreover, not having control of personal data on a single, centralized service provider also increases the possibility of security and privacy issues. While there are methods and techniques to building a highly secure IoT ecosystem based on the normal IoT model, there are much more specific and desirable benefits that a blockchain-based model can bring to the IoT.

Blockchain for IoT can help to build trust, reduce costs, and accelerate transactions. Additionally, decentralization, which is at the very core of blockchain technology, can eliminate single points of failure in an IoT network. For example, perhaps a central server might be unable to cope with the amount of data that billions of IoT devices (things) produce at high frequency, whereas a decentralized blockchain serving as a communication layer between these IoT devices enables all the IoT devices on the blockchain to maintain a copy of the data store of their own, which means that this architecture is inherently highly available and resilient.

Some IoT devices losing their database does not result in the entire network coming to a standstill, as might be the case with a centralized server, even with a disaster recovery solution. Also, the peer-to-peer (P2P) communication model provided by blockchain can help reduce costs because there is no need to build high-cost centralized data centers, nor implement complex public key infrastructure for security. Devices can communicate with each other directly or via routers.

As an estimate made by various researchers and companies, by 2020, there will be roughly 22 billion devices connected to the internet. With this explosion of billions of devices connecting to the internet, it is hard to imagine that centralized infrastructures will be able to cope with the high demands of bandwidth, services, and availability without incurring excessive expenditure. A blockchain-based IoT will be able to solve scalability, privacy, and reliability issues in the current IoT model.

Blockchain enables things to communicate and transact with each other directly, and with the availability of smart contracts, negotiation and financial transactions can also occur directly between the devices instead of requiring an intermediary, an authority, or human intervention. For example, if a room in a hotel is vacant, it can rent itself out, negotiate the rent, and can open the door lock for a human who has paid the required fee. Another example could be that if a washing machine runs out of detergent, it could order it online after finding the best price and value based on the logic programmed into its smart contract.

The aforementioned five-layer IoT model can be adapted to a blockchain-based model by adding a blockchain layer on top of the network layer. This layer will run smart contracts and provide security, privacy, integrity, autonomy, scalability, and decentralization services to the IoT ecosystem. The management layer, in this case, can consist of only software related to analytics and processing, and security and control can be moved to the blockchain layer.

This model can be visualized in the following table:

Application layer

Transportation, financial, insurance, and many others

Management layer

Data processing, analytics, security management

Blockchain layer

Security, consensus, P2P (M2M) autonomous transactions, decentralization, smart contracts

Network layer

LAN, WAN, PAN, routers

Device layer

Sensors, actuators, smart devices

Physical objects

People, cars, homes

In this model, other layers are expected to remain the same, but an additional blockchain layer will be introduced as middleware between all participants of the IoT network.

It can also be visualized as a P2P IoT network after abstracting away all the layers mentioned earlier. This model is shown in the following diagram, where all the devices are communicating and negotiating with each other without a central command and control entity:

Figure 19.2: Blockchain-based direct (P2P, or machine-to-machine (M2M)) communication model

An IoT-based blockchain can also result in cost savings, due to the easier device management offered by a blockchain-based decentralized approach. The IoT network can also be optimized for performance by using blockchain. In this case, there will be no need to store IoT data centrally for millions of devices. This is because storage and processing requirements can be distributed to all IoT devices on the blockchain. This can result in completely removing the need for large data centers for processing and storing the IoT data.

A blockchain-based IoT can also thwart denial of service (DoS) attacks: hackers can target a centralized server or data center more efficiently, but with blockchain's distributed and decentralized nature, such attacks are no longer possible. Additionally, if, as estimated, there will soon be billions of devices connected to the internet, it will become almost impossible to manage security and updates for all those devices from traditional, centrally owned servers. Blockchain can provide a solution to this problem by allowing devices to communicate with each other directly in a secure manner, and even request firmware and security updates from each other. On a blockchain network, these communications can be recorded immutably and securely, which will provide auditability, integrity, and transparency to the system. This mechanism is not possible with traditional P2P systems.

In summary, there are clear benefits that can be reaped with the convergence of IoT and blockchain, and a lot of research and work in academia and the industry are already in progress. Practical use cases and platforms have emerged in the form of Platform as a Service (PaaS) for blockchain-based IoT, such as the IBM Watson IoT blockchain. There are various projects that have already been proposed that provide blockchain-based IoT solutions, such as IBM Blue Horizon and IBM Bluemix, two examples of IoT platforms that support blockchain IoT. Various start-ups, such as Filament, have already proposed novel ideas on how to build a decentralized network that enables devices on the IoT to transact with each other directly and autonomously, driven by smart contracts.

In the following section, a practical example will be provided on how to build a simple IoT device and connect it to the Ethereum blockchain. This IoT device is connected to the Ethereum blockchain and is used to open a door (in this case, the door lock is represented by an LED) when the appropriate amount of funds is sent by a user on the blockchain. This is a simple example and requires a more rigorously tested version to implement it in production. Nevertheless, it demonstrates how an IoT device can be connected to a blockchain. We will demonstrate how it can be controlled and responded to in response to certain events on an Ethereum blockchain.

Implementing blockchain-based IoT in practice

This example makes use of a Raspberry Pi device, which is a Single Board Computer (SBC). The Raspberry Pi is an SBC developed as a low-cost computer to promote computer education, but it has also gained much more popularity as a tool of choice for building IoT platforms. A Raspberry Pi 3 Model B is shown in the following image.

You may be able to use earlier models too, but those have not been tested:

Figure 19.3: Raspberry Pi Model B

In the following section, an example will be discussed where a Raspberry Pi will be used as an IoT device connected to the Ethereum blockchain, and it will act in response to a smart contract invocation.

Setting up Raspberry Pi

First, the Raspberry Pi needs to be set up. This can be done by using NOOBS, which provides an easy method of installing Raspbian or any other operating system.

NOOBS is an abbreviation of New Out Of Box Software. It is a user-friendly and easy-to-use operating system installation manager for the Raspberry Pi.

NOOBS can be downloaded and installed from https://www.raspberrypi.org/downloads/noobs/.

Alternatively, you can only install Raspbian, from https://www.raspberrypi.org/downloads/raspbian/.

Another alternative, available at https://github.com/debian-pi/raspbian-ua-netinst, can also be used to install a minimal non-GUI version of Raspbian OS.

For this example, NOOBS has been used to install Raspbian. As such, the rest of the exercise assumes Raspbian is installed on the SD memory card of the Raspberry Pi. The command output in the following screenshot shows which architecture the operating system is running on. In this case, it is armv71; therefore, the ARM-compatible binary for Geth will be downloaded.

The platform can be confirmed by running the command uname -a in a Terminal window in the Raspberry Pi Raspbian operating system:

Figure 19.4: Raspberry Pi architecture

Once the Raspbian operating system has been installed, the next step is to download the appropriate Geth binary for the Raspberry Pi ARM platform.

The download and installation steps are described in detail as follows:

  1. First, download the Geth binary in Raspberry Pi. We use wget to download the geth client images:
    $ wget https://gethstore.blob.core.windows.net/builds/geth-linux- arm7-1.5.6-2a609af5.tar.gz
    

    Note that, in this example, a specific version of Geth is being downloaded. Other versions are available that can be downloaded from https://geth.ethereum.org/downloads/. However, it's recommended that you download the version that has been used in the examples in this chapter.

  2. Unzip and extract this into a directory. The directory named geth-linux-arm7-1.5.6-2a609af5 will be created automatically with the tar command, as shown here:
    $ tar -zxvf geth-linux-arm7-1.5.6-2a609af5.tar
    

    This command will create a directory named geth-linux-arm7-1.5.6-2a609af5 and will extract the Geth binary and related files into that directory. The Geth binary can be copied into /usr/bin or the appropriate path on Raspbian to make it available from anywhere in the operating system. When the download is finished, the next step is to create the genesis block.

  3. The same genesis block should be used that we created previously in Chapter 13, Ethereum Development Environment. The genesis file can be copied from the other node on the network. This is shown in the following code segment. Alternatively, an entirely new genesis block can be generated. Elements of the genesis file were explained in Chapter 13, Ethereum Development Environment, under the section entitled The genesis file, which you can refer to as a refresher:
    {
         "nonce": "0x0000000000000042",
         "timestamp": "0x00",
         "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
         "extraData": "0x00",
         "gasLimit": "0x8000000",
         "difficulty": "0x0400",
               "mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000",
         "coinbase": "0x3333333333333333333333333333333333333333",
         "alloc": {
         },
         "config": {
             "chainId": 786,
             "homesteadBlock": 0,
             "eip155Block": 0,
             "eip158Block": 0
         }
    }
    
  4. Once the genesis.json file has been copied onto the Raspberry Pi, the following command can be run to generate the genesis block. It is important that the same genesis block is used that was generated previously; otherwise, the nodes will effectively be running on separate networks:
    $ ./geth init genesis.json
    

    This will show an output similar to the one shown in the following screenshot:

    Figure 19.5: Initializing the genesis file

  5. After genesis block creation, we add peers to the network. This can be achieved by creating a list of nodes on our private network. In order to define the list, we create a file named static-nodes.json using any text editor, and add the enode of the peer that geth, on the Raspberry Pi, will connect to for synchronizing.
  6. The enode URL can be obtained from the Geth JavaScript console by running the following command, which should be run on the peer to which Raspberry Pi is going to connect:
    > admin.nodeInfo
    

    This will show an output similar to the one shown in the following screenshot:

    Figure 19.6: Geth nodeInfo

  7. The static-nodes.json file should contain the enode value, as shown in the following screenshot. We can view the contents using the cat command:
    $ cat static-nodes.json
    

    This command will produce the output shown here:

Figure 19.7: Static nodes configuration

After this step, further instructions presented in the following sections can be followed to connect Raspberry Pi to the other node on the private network. In this example, the Raspberry Pi will be connected to the network ID 786 that we created in Chapter 13, Ethereum Development Environment. The key is to use the same genesis file created previously and different port numbers. Using the same genesis file will ensure that clients connect to the same network in which the genesis file originated. Different ports are not a strict requirement; however, if the two nodes are running under a private network and access from an environment external to the network is required, then a combination of DMZ, router, and port forwarding will be used. Therefore, it is recommended to use different TCP ports to allow port forwarding to work correctly.

The --identity switch shown in the following section, Setting up the first node, which hasn't been introduced previously, allows for an identifying name to be specified for the node.

Setting up the first node

First, the geth client needs to be started on the first node using the following command:

$ geth --datadir .ethereum/privatenet/ --networkid 786 --maxpeers 5 --rpc --rpcapi web3,eth,debug,personal,net --rpcport 9001 --rpccorsdomain "*" -- port 30301 --identity "drequinox"

This will give an output similar to the following:

Figure 19.8: Geth on the first node

Once this has been started up, it should be kept running, and another geth instance should be started from the Raspberry Pi node.

Setting up the Raspberry Pi node

On Raspberry Pi, the following command is required to be run to start geth and to sync it with other nodes (in this case, only one node). The following is the command:

$ ./geth --networkid 786 --maxpeers 5 --rpc --rpcapi web3,eth,debug,personal,net --rpccorsdomain "*" --port 30302 --identity "raspberry"

This should produce an output similar to the one shown in the following screenshot. When the output contains a row displaying Block synchronisation started, this means that the node has connected successfully to its peer:

Figure 19.9: Geth on the Raspberry Pi

This can be further verified by running commands in the geth console on both nodes, as shown in the following screenshot. The geth client can be attached by simply running the following command on the Raspberry Pi:

$ geth attach

This will open the JavaScript geth console for interacting with the geth node. We can use the admin.peers command to see the connected peers:

Figure 19.10: Geth console admin peers command running on the Raspberry Pi

Similarly, we can attach to the geth instance by running the following command on the first node:

$ geth attach ipc:.ethereum/privatenet/geth.ipc

Once the console is available, admin.peers can be run to reveal the details about other connected nodes, as shown in the following screenshot:

Figure 19.11: Geth console admin peers command running on the other peer

Once both nodes are up and running, further prerequisites can be installed to set up the experiment. Installation of Node.js and the relevant JavaScript libraries is required.

Installing Node.js

The required libraries and dependencies are listed here. First, Node.js and npm need to be updated on the Raspberry Pi Raspbian operating system. For this, the following steps can be followed:

  1. Install Node.js on the Raspberry Pi using the following command:
    $ curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -
    

    Note that we are using Node version 7.x for this example, simply for demonstration. You can use a later version if desired.

    This should display an output similar to the following. The output is quite large; therefore, only the top part of the output is shown in the following screenshot:

    Figure 19.12: Node.js installation

  2. Run the update via apt-get:
    $ sudo apt-get install nodejs
    

    Verification can be performed by running the following command to ensure that the correct versions of Node.js and npm are installed, as shown in the following screenshot:

    Figure 19.13: npm and node installation verification

    It should be noted that these versions are not a necessity; any of the latest versions of npm and Node.js should work. However, the examples in this chapter make use of npm 4.0.5 and node v7.4.0 simply for demonstration, so it is recommended that you use the same versions in order to avoid any compatibility issues.

  3. Install Ethereum web3 npm using the following command:
    $ npm install [email protected]
    

    Web3 is required to enable JavaScript code to access the Ethereum blockchain.

    Make sure that the specific version of web3 shown in the screenshot, or a version similar to this (for example, 0.20.2), is installed, instead of the default, version 1.2.11 (at the time of writing). As this example was originally developed and tested using version 0.18.0, it is recommended that web3 0.20.2 or 0.18.0 stable version should be used for this example. The aim of this example, which is to show how Ethereum-based IoT networks can be created, doesn't change regardless of whether a newer or older version of Web3 is used. You can install the recommended version by using $ npm install [email protected].

    The output of the command will be similar to the one shown here:

    Figure 19.14: npm install web3

  4. Similarly, npm onoff can be installed, which is required to communicate with the Raspberry Pi and control GPIO:
    $ npm install onoff
    

    This will result in the following output, indicating successful installation of onoff:

Figure 19.15: Onoff installation

In this section, we set up a private network with our Raspberry Pi, and another node with geth, nodejs, web3, and the onoff library to run our example on.

When all the prerequisites are installed, hardware setup can be performed. For this purpose, a simple circuit is built using a breadboard and a few electronic components.

Hardware prerequisites

The hardware components are listed as follows:

  • LED: A Light Emitting Diode (LED), can be used as a visual indication for an event.
  • Resistor: A 330-ohm component is required, which provides resistance to the passing current based on its rating. It is not necessary to understand the theory behind it for this experiment; any standard electronics engineering text covers all these topics in detail.
  • Breadboard: This provides a means of building an electronic circuit without requiring soldering.
  • T-Shaped Cobbler: This is inserted on the breadboard, as shown in the following image, and provides a labeled view of all General-Purpose I/O (GPIO) pins for the Raspberry Pi.
  • Ribbon cable connector: This is simply used to provide connectivity between the Raspberry Pi and the breadboard via GPIO.

All these components are shown in the following figure:

Figure 19.16: Required components

Building the electronic circuit

As shown in the following image, the positive leg (long leg) of the LED is connected to pin number 21 of the Breadboard, and the negative (short leg) is connected to the Resistor, which is then connected to the ground (GND) pin of the Breadboard. Once the connections have been set up, the Ribbon cable can be used to connect to the GPIO connector on the Raspberry Pi:

Figure 19.17: Connections for components on the breadboard

Once the connections have been set up correctly and the Raspberry Pi has been updated with the appropriate libraries and Geth, the next step is to develop a simple smart contract that expects a value. If the value provided is not what it expects, it does not trigger an event; otherwise, if the value passed matches the correct value, the event triggers, which can be read by the client JavaScript program running via Node.js.

Of course, the Solidity contract can be very complicated and can also deal with the ether sent to it. If the amount of ether is equal to the required amount, then the event can trigger. However, in this example, the aim is to demonstrate the usage of smart contracts to trigger events that can then be read by JavaScript running on Node.js, which then, in turn, can trigger actions on IoT devices using various libraries.

The smart contract source code is shown as follows:

pragma solidity ^0.4.0;
contract simpleIOT {
    uint roomrent = 10;
    event roomRented(bool returnValue);
    function getRent (uint8 x) public returns (bool) {
        if (x == roomrent) {
            emit roomRented(true);
            return true;
        }
    }
}

The online Solidity compiler (Remix IDE) can be used to run and test this contract. The Application Binary Interface (ABI) required for interacting with the contract is also available in the Remix IDE's solidity compiler section, as shown in the following screenshot:

Figure 19.18: ABI from Remix IDE

The following is the ABI of the contract:

[ 
    { 
        "constant": false, 
        "inputs": [ 
            { 
                "name": "x", 
                "type": "uint8" 
            } 
        ], 
        "name": "getRent", 
        "outputs": [ 
            { 
                "name": "", 
                "type": "bool" 
            } 
        ], 
        "payable": false, 
        "stateMutability": "nonpayable", 
        "type": "function" 
    }, 
    { 
        "anonymous": false, 
        "inputs": [ 
            { 
                "indexed": false, 
                "name": "returnValue", 
                "type": "bool" 
            } 
        ], 
        "name": "roomRented", 
        "type": "event" 
    } 
] 

There are two methods by which the Raspberry Pi node can connect to the private blockchain via the web3 interface. The first is where the Raspberry Pi device is running its own geth client locally and maintains its ledger, as shown in the following diagram:

Figure 19.19: Application architecture of the room rent IoT application (IoT device with local ledger)

Sometimes, with resource-constrained devices, it is not possible to run a full geth node or even a light node. In that case, the second method, which uses a web3 provider (via HTTP-RPC server), can be used to connect to the appropriate RPC channel. The following diagram shows the high-level architecture of an IoT application where the Raspberry Pi does not run a Geth instance. Instead, it runs only the minimum software required to provide IoT application functionality to the IoT device. For blockchain-relevant operations, it connects to another blockchain node running on the network via HTTP-RPC:

Figure 19.20: Application architecture of the room rent IoT application (IoT device without local ledger)

There are obvious security concerns that arise from exposing RPC interfaces publicly; therefore, it is recommended that this option is used only on private networks. If required to be used on public networks, appropriate security measures need to be put in place, such as allowing only the known IP addresses to connect to the geth RPC interface. This can be achieved by a combination of disabling peer discovery mechanisms and HTTP-RPC server listening interfaces.

More information about this can be found using geth help. The traditional network security measures such as firewalls, Transport Layer Security (TLS), and certificates can also be used but have not been discussed in this example for brevity. Now, Truffle can be used to deploy the contract on the private network ID 786 to which, at this point, the Raspberry Pi is connected.

Truffle deploy can be performed simply by using the following command; it is assumed that truffle init and other preliminaries discussed in Chapter 15, Introducing Web3, have already been performed:

$ truffle migrate

This should produce an output similar to the following:

Figure 19.21: Truffle deploy

Once the contract has been deployed correctly, JavaScript code can be developed that will connect to the blockchain via web3, listen for the events from the smart contract in the blockchain, and turn the LED on via the Raspberry Pi. The JavaScript code required for this example is shown here. Simply write or copy and paste the code shown here into a file named index.js:

var Web3 = require('web3');
if (typeof web3 !== 'undefined')
{
    web3 = new Web3(web3.currentProvider);
}else
{
    web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:9002")); 
    //http-rpc-port
}
var Gpio = require('onoff').Gpio; 
var led = new Gpio(21,'out');
var coinbase = web3.eth.coinbase;
var ABIString = '[{"constant":false,"inputs":[{"name":"x","type":"uint8"}],"name":"getRent","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"returnValue","type":"bool"}],"name":"roomRented","type":"event"}]';
var ABI = JSON.parse(ABIString);
var ContractAddress = '0x975881c44fbef4573fef33cccec1777a8f76669c';
web3.eth.defaultAccount = web3.eth.accounts[0];
var simpleiot = web3.eth.contract(ABI).at(ContractAddress);
var event = simpleiot.roomRented( {}, function(error, result) { if (!error)
{
    console.log("LED On");
    led.writeSync(1);
}
});

Note that, in the preceding code example, the contract address '0x975881c44fbef4573fef33cccec1777a8f76669c' for the variable var ContractAddress is specific to the deployment; it will be different when you run this example. Simply change the address in the file to what you see after deploying the contract.

Also, note the HTTP-RPC server listening port on which Geth has been started on Raspberry Pi. By default, it is TCP port 8545. Remember to change this according to your Raspberry Pi setup and Geth configuration. It is set to 9002 in the preceding example code because Geth running on Raspberry Pi is listening on 9002 in the example. If it's listening on a different port on your Raspberry Pi, then change it to that port:

web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:9002"));

When Geth starts up, it shows which port it has HTTP endpoint listening on. This is also configurable with --rpcport in geth by specifying the port number value as a parameter to the flag.

This JavaScript code can be placed in a file on the Raspberry Pi; for example, index.js. It can be run by using the following command:

$ node index.js

This will start the program, which will run on Node.js and listen for events from the smart contract. Once the program is running correctly, the smart contract can be invoked by using the Truffle console, as shown in the following screenshot.

In this case, the getRent function is called with the parameter 10, which is the expected value:

Figure 19.22: getRent function invocation

After the contract has been mined, roomRented will be triggered, which will turn on the LED.

In this example, it is a simple LED, but it can be any physical device, such as a room lock, that can be controlled via an actuator. If all works well, the LED will be turned on as a result of the smart contract's function invocation, as shown in the following image:

Figure 19.23: Raspberry Pi with LED control

Also, on the node side, it will display an output similar to the one shown here:

$ node index.js
LED On 

As demonstrated in the preceding example, a private network of IoT devices can be built that runs a geth client on each of the nodes, listens for events from smart contracts, and triggers an action accordingly. The example shown is simple by design but demonstrates the underlying principles of an Ethereum network that can be built using IoT devices, along with smart contract-driven control of the physical devices.

In the next few sections, other applications of the blockchain will be discussed, such as in government, finance, and health.

Government

There are various applications of blockchain being researched currently that can support government functions and take the current model of e-government to the next level. First, in this section, some background for e-government will be provided, and then a few use cases such as e-voting, homeland security (border control), and electronic IDs (citizen ID cards) will be discussed.

Government, or electronic government, is a paradigm where information and communication technology are used to deliver public services to citizens. The concept is not new and has been implemented in various countries around the world, but with blockchain, a new avenue of exploration has opened up. Many governments are researching the possibility of using blockchain technology for managing and delivering public services, including, but not limited to, identity cards, driving licenses, secure data sharing among various government departments, and contract management. Transparency, auditability, and integrity are attributes of blockchain that can go a long way in effectively managing various government functions.

Border control

Automated border control systems have been in use for decades now to thwart illegal entry into countries and prevent terrorism and human trafficking.

Machine-readable travel documents, specifically biometric passports, have paved the way for automated border control; however, current systems are limited to a certain extent and blockchain technology can provide solutions. A machine-readable travel document (MRTD) standard is defined in document ICAO 9303 (https://www.icao.int/publications/pages/publication.aspx?docnum=9303) by the International Civil Aviation Organization (ICAO) and has been implemented by many countries around the world.

Each passport contains various security and identity attributes that can be used to identify the owner of the passport, and also circumvent attempts at tampering with these passports. These include biometric features such as retina scan, fingerprints, facial recognition, and standard ICAO specified features, including machine-readable zone (MRZ) and other text attributes that are visible on the first page of the passport.

One key issue with current border control systems is data sharing, whereby the systems are controlled by a single entity and data is not readily shared among law enforcement agencies. This lack of ability to share data makes it challenging to track suspected travel documents or individuals. Another issue is related to the immediate implementation of blacklisting of a travel document; for example, when there is an immediate need to track and control suspected travel documents. Currently, there is no mechanism available to blacklist or revoke a suspicious passport immediately and broadcast it to the border control ports worldwide.

Blockchain technology can provide a solution to this problem by maintaining a blacklist in a smart contract that can be updated as required. Any changes will be immediately visible to all agencies and border control points, thus enabling immediate control over the movement of a suspected travel document. It could be argued that traditional mechanisms like Public Key Infrastructures (PKIs) and P2P networks can also be used for this purpose, but they do not provide the benefits that a blockchain can provide. With blockchain, the whole system can be simplified without the requirement of complex networks and PKI setups, which will also result in cost reduction. Moreover, blockchain-based systems will provide cryptographically guaranteed immutability, which helps with auditing and discourages any fraudulent activity.

The full database of all travel documents may not be stored on the blockchain currently due to inherent storage limitations, but a backend distributed database such as BigchainDB, IPFS, or Swarm can be used for that purpose. In this case, a hash of the travel document with the biometric ID of an individual can be stored in a simple smart contract, and a hash of the document can then be used to refer to the detailed data available on the distributed filesystem, such as IPFS. This way, when a travel document is blacklisted anywhere on the network, that information will be available immediately with the cryptographic guarantee of its authenticity and integrity throughout the distributed ledger. This functionality can also provide adequate support in anti-terrorism activities, thus playing a vital role in the homeland security function of a government.

A simple contract in Solidity can have an array defined for storing identities and associated biometric records. This array can be used to store the identifying information about a passport. The identity can be a hash of MRZ of the passport or travel document concatenated with the biometric record from the RFID chip. A simple Boolean field can be used to identify blacklisted passports. Once this initial check passes, further detailed biometric verification can be performed by traditional systems. Eventually, when a decision is made regarding the entry of the passport holder, that decision can be propagated back to the blockchain, thus enabling all participants on the network to immediately share the outcome of the decision.

A high-level approach to building a blockchain-based border control system can be visualized as shown in the following diagram. In this scenario, the passport is presented for scanning to an RFID and page scanner, which reads the data page and extracts machine-readable information, along with a hash of the biometric data stored in the RFID chip. At this stage, a live photo and retina scan of the passport holder is also taken. This information is then passed on to the blockchain, where a smart contract is responsible for verifying the legitimacy of the travel document by first checking its list of blacklisted passports, and then requesting more data from the backend IPFS database for comparison. Note that the biometric data, such as a photo or retina scan, is not stored on the blockchain; instead, only a reference to this data in the backend (IPFS or BigchainDB) is stored in the blockchain.

If the data from the presented passport matches with what is held in the IPFS as files or in BigchainDB and also passes the smart contract logical check, then the border gate can be opened:

Figure 19.24: Automated border control using blockchain

After verification, this information is propagated throughout the blockchain and is instantly available to all participants on the border control blockchain. These participants can be a worldwide consortium of homeland security departments of various nations.

Voting

Voting in any government is a key function and allows citizens to participate in the democratic election process. While voting has evolved into a much more mature and secure process, it still has limitations that need to be addressed to achieve a desired level of maturity. Usually, the limitations in current voting systems revolve around fraud, weaknesses in operational processes, and especially transparency. Over the years, secure voting mechanisms (machines) have been built that make use of specialized voting machines that promised security and privacy, but they still have vulnerabilities that could be exploited to subvert the security mechanisms of those machines. These vulnerabilities can lead to serious implications for the whole voting process and can result in mistrust in the government by the public.

Blockchain-based voting systems can resolve these issues by introducing end-to-end security and transparency in the process. Security is provided in the form of integrity and authenticity of votes by using public key cryptography, which comes as standard in a blockchain. Moreover, immutability guaranteed by blockchain ensures that votes cast once cannot be cast again. This can be achieved through a combination of biometric features and a smart contract maintaining a list of votes already cast. For example, a smart contract can maintain a list of already-cast votes with the biometric ID (for example, a fingerprint) and can use that to detect and prevent double casting. Secondly, zero-knowledge proofs (ZKPs) can also be used on the blockchain to protect voters' privacy. With ZKP, a voter can remain anonymous by hiding their identities, and the vote itself can be kept confidential.

Recently, presidential elections were held in Sierra Leone using blockchain technology, making it the first country to use blockchain technology for elections: https://www.coindesk.com/sierra-leone-secretly-holds-first-blockchain-powered-presidential-vote/.

Another example can be seen here: https://www.coindesk.com/swiss-city-plans-to-vote-on-blockchain-using-ethereum-digital-id.

Citizen identification (ID cards)

Electronic IDs or national ID cards are issued by various countries around the world at present. These cards are secure and possess many security features that thwart duplication or tampering attempts. However, with the advent of blockchain technology, several improvements can be made to this process.

Digital identity is not only limited to just government-issued ID cards; it is a concept that applies to online social networks and forums, too. There can be multiple identities being used for different purposes. A blockchain-based online digital identity allows control over personal information sharing. Users can see who used their data and for what purpose, as well as control access to it. This is not possible with the current infrastructures, which are centrally controlled.

The key benefit is that a single identity issued by the government can be used easily, and in a transparent manner, for multiple services via a single government blockchain. In this case, the blockchain serves as a platform where a government is providing various services such as pensions, taxation, or benefits and a single ID is being used to access all these services. Blockchain, in this case, provides a permanent record of every change and transaction made by a digital ID, thus ensuring integrity and transparency of the system. Also, citizens can notarize birth certificates, marriages, deeds, and many other documents on the blockchain tied with their digital ID as a proof of existence.

Currently, there are successful implementations of identity schemes in various countries that work well, and there is an argument that perhaps blockchain is not required in identity management systems. Although there are several benefits, such as privacy and controlling the use of identity information, due to the current immaturity of blockchain technology, perhaps it is not ready for use in real-world identity systems. However, research is being carried out by various governments to explore the use of blockchain for identity management.

Moreover, laws such as the right to be forgotten can be quite difficult to incorporate into blockchain due to their immutable nature.

Other government functions where blockchain technology can be implemented to improve cost and efficiency include the collection of taxes, benefits management and disbursement, land ownership record management, life event registration (marriages, births), motor vehicle registration, and licenses. This is not an exhaustive list and, over time, many functions and processes of a government can be adapted to a blockchain-based model. The key benefits of blockchain, such as immutability, transparency, and decentralization, can help to bring improvements to most of the traditional government systems.

Now, let's see how the health industry can benefit from blockchain technology.

Health

The health industry has also been identified as another major industry that can benefit by adapting blockchain technology. Blockchain can provide an immutable, auditable, and transparent system that traditional P2P networks cannot. Also, blockchain provides a simpler, more cost-effective infrastructure compared to traditional complex PKI networks. In healthcare, major issues such as privacy compromises, data breaches, high costs, and fraud can arise from a lack of interoperability, overly complex processes, transparency, auditability, and control. Another burning issue is counterfeit medicines; especially in developing countries, this is a major cause of concern.

With the adaptability of blockchain in the health sector, several benefits can be realized, including cost savings, increased trust, the faster processing of claims, high availability, no operational errors due to complexity in the operational procedures, and preventing the distribution of counterfeit medicines.

From another angle, blockchains that are providing a digital currency as an incentive for mining can be used to provide processing power to solve scientific problems. This helps to find cures for certain diseases. Examples include FoldingCoin, which rewards its miners with FLDC tokens for sharing their computer's processing power for solving scientific problems that require unusually large calculations.

FoldingCoin is available at http://foldingcoin.net/.

Another similar project is called CureCoin, which is available at https://www.curecoin.net/. It is yet to be seen how successful these projects will be in achieving their goals, but the idea is very promising.

In the next section, we'll explore one of the most talked about and anticipated industries that can benefit from blockchain technology: finance.

Finance

Blockchain has many potential applications in the finance industry. Blockchain in finance is currently the hottest topic in the industry, and major banks and financial organizations are researching to find ways to adopt blockchain technology, primarily due to its highly desired potential to cost-save.

These applications include, but are not limited to, insurance, post-trade settlements, financial crime prevention, and payments.

Insurance

In the insurance industry, blockchain technology can help to stop fraudulent claims, increase the speed of claim processing, and enable transparency. Imagine a shared ledger between all insurers that can provide a quick and efficient mechanism for handling intercompany claims. Also, with the convergence of IoT and blockchain, an ecosystem of smart devices can be imagined, where all these things can negotiate and manage their insurance policies, which are controlled by smart contracts on the blockchain.

Blockchain can reduce the overall cost and effort required to process claims. Claims can be automatically verified and paid via smart contracts and the associated identity of the insurance policyholder. For example, a smart contract, with the help of an oracle and possibly IoT, can make sure that when the accident occurred, it can record related telemetry data and, based on this information, release payment. It can also withhold payment if the smart contract, after evaluating conditions of payment, concludes that payment should not be released; for example, in a scenario where an authorized workshop did not repair the vehicle or was used outside a designated area and so on and so forth. There can be many conditions that a smart contract can evaluate to process claims and the choice of these rules depends on the insurer, but the general idea is that smart contracts, in combination with IoT and oracles, can automate the entire vehicle insurance industry.

Several start-ups, such as Dynamis, have proposed smart contract-based P2P insurance platforms that run on the Ethereum blockchain. This was initially proposed to be used for unemployment insurance and does not require underwriters in the model.

The Dynamis white paper is available at http://dynamisapp.com/.

Post-trade settlement

This is the most sought-after application of blockchain technology. Currently, many financial institutions are exploring the possibility of using blockchain technology to simplify, automate, and speed up the costly and time-consuming post-trade settlement process.

To understand the problem better, the trade lifecycle will be described briefly. A trade lifecycle contains three steps: execution, clearing, and settlement. Execution is concerned with the commitment of trading between two parties and can be entered into the system via front office order management terminals or exchanges. Clearing is the next step, whereby the trade is matched between the seller and buyer based on certain attributes, such as price and quantity. At this stage, accounts that are involved in payment are also identified. Finally, the settlement is where, eventually, security is exchanged for payment between the buyer and seller.

In the traditional trade lifecycle model, a central clearing house is required to facilitate trading between parties, which bears the credit risk of both parties. The current scheme is somewhat complicated, whereby a seller and buyer have to take a complicated route to trade with each other. This comprises various firms, brokers, clearing houses, and custodians, but with blockchain, a single distributed ledger with appropriate smart contracts can simplify this whole process and can enable buyers and sellers to talk directly to each other.

Notably, the post-trade settlement process usually takes two to three days, and has a dependency on central clearing houses and reconciliation systems. With the shared ledger approach, all participants on the blockchain can immediately see a single version of truth regarding the state of the trade. Moreover, P2P settlement is possible, which results in the reduction of complexity, cost, risk, and the time it takes to settle the trade. Finally, intermediaries can be eliminated by making use of the appropriate smart contracts on the blockchain. Also, regulators can view the blockchain for auditing and regulatory requirements.

This can be very useful in implementing MIFID-II regulation requirements (https://www.fca.org.uk/markets/mifid-ii).

Financial crime prevention

Know Your Customer (KYC) and Anti Money Laundering (AML) are the key enablers for the prevention of financial crime. In the case of KYC, currently, each institution maintains their own copy of customer data and performs verification via centralized data providers. This can be a time-consuming process and can result in delays in onboarding a new client.

Blockchain can provide a solution to this problem by securely sharing a distributed ledger between all financial institutions that contain verified and true identities of customers. This distributed ledger can only be updated by consensus between the participants, thus providing transparency and auditability. This can not only reduce costs but also enable regulatory and compliance requirements to be satisfied in a better and consistent manner.

In the case of AML, due to the immutable, shared, and transparent nature of blockchain, regulators can easily be granted access to a private blockchain where they can fetch data for relevant regulatory reporting. This will also result in reducing complexity and costs related to the current regulatory reporting paradigm. This is where data is fetched from various legacy and disparate systems, and then aggregated and formatted together for reporting purposes. Blockchain can provide a single shared view of all financial transactions in the system that are cryptographically secure, authentic, and auditable, thus reducing the costs and complexity associated with the currently employed regulatory reporting methods.

There are already several solutions available, two of which are listed here:

Crypto-kyc: https://www.crypto-kyc.com

KYC-Chain: https://kyc-chain.com

There are many other solutions that can be found with a simple search for Blockchain KYC on an internet search engine.

Payments

A payment is a transfer of money or its equivalent from one party (the payer) to another (the payee) in exchange for services, goods, or for fulfilling a contract. Payments are usually made in the form of cash, bank transfers, credit cards, and cheques. There are various electronic payment systems in use, such as Bacs Payment Schemes Limited (Bacs) and the Clearing House Automated Payment System (CHAPS).

All of these systems are, however, centralized and governed by traditional financial service industry codes and practices. These systems work adequately, but with the advent of blockchain, the potential of technology has arisen to address some of these limitations.

Some of the key advantages that blockchain technology can bring to payments are listed as follows.

Decentralization

Decentralization means that there is no requirement of a trusted third party to process payments. Payments can be made directly between parties without requiring any intermediary. This can result in reduced cost and faster (direct) payments between parties.

Faster settlement

Settlement can be much quicker compared to the traditional network due to the active presence of all parties on the network. Payment data can be shared and seen by all parties at the same time, and due to this settlement becomes quicker and more comfortable. Moreover, there is no requirement of running lengthy reconciliation processes because the data is all there on the blockchain, shared between all parties and readily available, which removes the requirement of the lengthy reconciliation process.

Better resilience

With a payment system running on a blockchain with potentially thousands of nodes around the world, the network becomes naturally resilient. It could also be argued that, with blockchain payments, there is no downtime because blockchain does not rely on traditional disaster recovery (DR) practices and is also better protected against malicious and denial of service attacks.

With all these advantages, it is easy to see how the payments industry can benefit from blockchain technology.

There is also another branch of payments that deals with international or cross-border payments, and comes with its own challenges. We'll discuss this next.

Cross-border payments

In traditional finance, cross-border payment is a complex process that can take days to process and involves multiple intermediaries. Current mechanisms suffer from delays incurred by multiple intermediaries, enforcement of regulations, differences in terms of regulations between different jurisdictions… the list goes on. All of these issues can be addressed by utilizing blockchain technology. The most significant advantage is decentralization, where, due to the lack of requirement of intermediaries, payments can be made directly between businesses or individuals. Also, due to P2P connectivity, the whole process becomes a lot faster—almost immediate, in fact—which results in more productivity and business agility.

Peer-to-peer loans

Blockchain also enables P2P loans, where lenders and borrowers can deal with each other directly instead of relying on a third party. Currently, in the decentralized finance (DeFi) landscape, there is a large percentage of lending DApps that deal with the lending and borrowing of crypto tokens.

In this section, we covered some common use cases of blockchain in the finance industry. Next, we'll discuss media, another use case where blockchain can provide a cheaper, fair, and transparent media ecosystem.

Media

Critical issues in the media industry revolve around content distribution, rights management, and royalty payments to artists. For example, digital music can be copied many times without any restrictions, and any attempts to apply copy protection have been hacked in some way or other. There is no control over the distribution of the content that a musician or songwriter produces; it can be copied as many times as needed without any restriction, and consequently has an impact on the royalty payments. Also, payments are not always guaranteed and are based on traditional airtime figures. All these issues revolving around copy protection and royalty payments can be resolved by connecting consumers, artists, and all players in the industry, allowing transparency and control over the process.

Blockchain can provide a network where digital music is cryptographically guaranteed to be owned only by the consumers who pay for it. This payment mechanism is controlled by a smart contract instead of a centralized media agency or authority. The payments will be automatically made based on the logic embedded within the smart contract and the number of downloads.

A recent example of such an initiative is Musicoin: https://musicoin.org.

Moreover, illegal copying of digital music files can be stopped altogether because everything is recorded and owned immutably in a transparent manner on the blockchain. A music file, for example, can be stored with owner information and a timestamp that can be traced throughout the blockchain network. Furthermore, the consumers who own a legal copy of some content are cryptographically tied to the content they have, and it cannot be moved to another owner unless permissioned by the owner. Copyrights and transfers can be managed easily via blockchain once all digital content is immutably recorded on the blockchain. Smart contracts can then control the distribution and payment to all concerned parties.

Summary

There are many applications of blockchain technology and, as discussed in this chapter, they can be implemented in various industries to bring about solutions to existing problems. In this chapter, five main industries that can benefit from blockchain have been discussed. First, IoT was discussed, which is another revolutionary technology in its own right. By combining it with blockchain, several fundamental limitations can be addressed, which brings about tremendous benefits to the IoT industry. More focus has been given to IoT in this chapter, as it is the most prominent and most ready candidate for adapting blockchain technology. Moreover, applications in the government sector were discussed, whereby various government processes such as homeland security, identification cards, and benefit disbursements can be made transparent, secure, and more robust.

Furthermore, issues in the finance sector were discussed, along with possible solutions that blockchain technology could provide. Although the finance sector is exploring the possibilities of using blockchain with high energy and enthusiasm, it is still far away from production-ready, blockchain-based systems. Finally, some aspects of the health sector and music industry were also discussed. All these use cases and much more in the industry stand on pillars provided the by core attributes of blockchain technology, such as decentralization, transparency, reliability, and security. However, certain challenges need to be addressed before blockchain technology can be adopted fully. These will be discussed in the next chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset