Blockchain and IPFS based Mobile Health system

Here we shall be implementing a highly secure and high performance mHealth system as described in this research paper

https://www.ncbi.nlm.nih.gov/pmc/articles/PMC8073055/

Setting up an ipfs based file system

The InterPlanetary File System (IPFS) is a protocol and peer-to-peer network for storing and sharing data in a distributed file system. IPFS uses content-addressing to uniquely identify each file in a global namespace connecting all computing devices

Use the below provided docker-compose.yaml

version: '3'
services:
  ipfs:
    image: ipfs/go-ipfs:v0.8.0
    environment:
      - IPFS_PROFILE=server
      - IPFS_PATH=/ipfsdata
    volumes:
      - ./data/ipfs:/ipfsdata
    ports:
      - "4001:4001"
      - "127.0.0.1:8080:8080"
      - "127.0.0.1:8081:8081"
      - "127.0.0.1:5001:5001"

run the command

root@80:~/hello-eth/ipfs# docker-compose up

Create a python file with the below code to test our ipfs filesystem

import ipfshttpclient
client = ipfshttpclient.connect('/dns/0.0.0.0/tcp/5001/http')  # Connects to: /dns/localhost/tcp/5001/http
res = client.add('test.txt')
print(res)
print(res['Hash'])

Make sure you also create a test file say test.txt with a few lines of text to test the upload feature. Install ipfshttpclient and run

pip3 install ipfshttpclient==0.8.0a2
command-prompt# testipfs.py

You can also view the contents of the file locally using either

http://localhost:8080/ipfs/QmVyyENm5fk1NKw6MhAdb5d3AM4ecXkU22fdABBgdKkP7y/

where
QmVyyENm5fk1NKw6MhAdb5d3AM4ecXkU22fdABBgdKkP7y
is the hashcode returned by our testipfs python program

or using the webui

http://127.0.0.1:5001/webui

Basics of setting up and deploying a smart contract on Ethereum with Python, Truffle and web3py

Next we shall be setting up a smart contract on Ethereum blockchain to upload the contents of the text file to ipfs and store the hashcode in Truffle using python web3py library

Installing Truffle

$ mkdir hello-eth
$ cd hello-eth
npm install truffle
ro01180:~/hello-eth# ./node_modules/.bin/truffle init

Create a file called HelloWorld.sol inside the contracts/ folder with the following content

// mHealth Smart Contract 
pragma solidity >=0.5.0 <0.7.0;
contract HelloWorld {

    string public payload;   
                                                                                                                                                                                                                                                                                                                                function setPayload(string memory content) public {                                                                                                                            payload = content;                                                                                                                                                  }                                                                                                                                                                          

    function get()public pure returns (string memory){
        return 'Uploading File Contract';
    }
}

From the project root folder, use truffle to compile the contract:

ro180:~/hello-eth# ./node_modules/.bin/truffle compile

Deploying smart contract to the blockchain

To deploy our smart contract to the blockchain we first need:

  • a migration script
  • a blockchain to deploy the contract to

For the migration script, create a file named 2_deploy_contract.js inside migrations/ folder and add the following content to it:

var HelloWorld = artifacts.require("HelloWorld");

module.exports = function(deployer) {
	    deployer.deploy(HelloWorld);
};

spinup the personal blockchain of truffle to test. Open another terminal and run:

ro01180:~/hello-eth# ./node_modules/.bin/truffle develop

run migrate at the prompt

truffle(develop)> migrate

Python application to test the workflow by calling the deployed contract

Under the project root folder (hello-eth/) create a file named app.py with the following content

Make sure you replace the deployed_contract_adddress in the code with your custom contract address from local

import json
from web3 import Web3, HTTPProvider
import ipfshttpclient

# truffle development blockchain address
blockchain_address = 'http://127.0.0.1:9545'
# Client instance to interact with the blockchain
web3 = Web3(HTTPProvider(blockchain_address))
# Set the default account (so we don't need to set the "from" for every transaction call)
web3.eth.defaultAccount = web3.eth.accounts[0]

# Path to the compiled contract JSON file
compiled_contract_path = 'build/contracts/HelloWorld.json'
# Deployed contract address (see `migrate` command output: `contract address`)
deployed_contract_address = '0x1D1DC7C89dABDC0C415ddd2FeA98943284A23b7C'

with open(compiled_contract_path) as file:
    contract_json = json.load(file)  # load contract info as JSON
    contract_abi = contract_json['abi']  # fetch contract's abi - necessary to call its functions

# Fetch deployed contract reference
contract = web3.eth.contract(address=deployed_contract_address, abi=contract_abi)

# Call contract function (this is not persisted to the blockchain)
message = contract.functions.get().call()

print(message)

client = ipfshttpclient.connect('/dns/0.0.0.0/tcp/5001/http')  # Connects to: /dns/localhost/tcp/5001/http
res = client.add('test.txt')
print(res['Hash'])

# executes setPayload function
tx_hash = contract.functions.setPayload(res['Hash']).transact()
# waits for the specified transaction (tx_hash) to be confirmed
# (included in a mined block)
tx_receipt = web3.eth.waitForTransactionReceipt(tx_hash)
print('tx_hash: {}'.format(tx_hash.hex()))

We can verify that the contract was properly created by fetching the contract instance and checking for setPayload method existence, as well as the value of payload variable:

$ truffle(develop)> let instance = await HelloWorld.deployed()
$ truffle(develop)> instance.setPayload
$ truffle(develop)> instance.payload.call()

Executing a transaction on blockchain

We now execute a transaction that uploads our file to IPFS and gets back a hashcode which is then stored in our payload variable. For this we open a new terminal and execute our python script app.py

pip3 install web3
python3 app.py

Inorder to verify that the data was persisted on the blockchain go back to the Truffle console and call payload variable:

You then inspect the blockchain in detail

Finally you check if the file was uploaded on IPFS using the hashcode output by app.py

Conclusion

We are not done yet. Just scratched the surface. Our final objective will be implement the full workflow detailed in the paper for which we shall be modifying our HelloWorld.sol and app.py as per the directions in the diagram below.

We shall be using https://remix.ethereum.org/ ide for faster development and a cool ui library called https://streamlit.io/ for building some basic UI.

more on that when I find time over weekends.

Stay Tuned !

Until then Feed on IoT, Breathe in AI, Drink to Blockchain and keep Living Digital !!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: