Blockchain Technologies Lab Manual
Blockchain Technologies Lab Manual
PREREQUISITE:
Basic programming knowledge and command-line skills, Understanding of blockchain
concepts and decentralized systems, Familiarity with data management and machine learning
basics, Knowledge of security concepts and IoT principles.
COURSE OUTCOME:
Ability to set up blockchain development environments, write and deploy smart
contracts, and manage Hyperledger Fabric networks.
Proficiency in using IPFS for decentralized storage and integrating blockchain to
ensure data integrity in machine learning models.
Capability to implement blockchain-based data provenance systems and develop
decentralized data marketplaces.
Skills to deploy chain-code on Hyperledger Fabric, create secure blockchain-based
voting systems, and integrate blockchain with IoT for secure data management.
1
2
INDEX
S. PAGE DATE OF
PROGRAM
No NO EXECUTION
Installation of Ethereum, Truffle, Ganache, and
1
other tools
Writing and deploying basic smart contracts on
2
Ethereum
Configuring and running a Hyperledger Fabric
3
network
4 Storing and retrieving data using IPFS
3
PROGRAM 1: INSTALLATION OF ETHEREUM, TRUFFLE, GANACHE AND
OTHER TOOLS
OBJECTIVE
The objective of this lab exercise is to set up a complete development environment for
Ethereum blockchain application development. This includes installing the core tools and
frameworks such as:
Ethereum client (Ganache as a personal blockchain for testing)
Truffle Suite (development framework for smart contracts)
Node.js and npm (JavaScript runtime and package manager)
MetaMask (browser-based crypto wallet and blockchain interaction tool)
Git Bash (command-line shell for Windows users)
Other dependencies as required.
KEY CONCEPTS
1. Ethereum: A decentralized blockchain platform supporting smart contracts. It enables
the creation of decentralized applications (DApps).
2. Ganache: A personal, local Ethereum blockchain designed for development and
testing. It simulates the blockchain environment locally and allows rapid testing
without real ETH costs.
3. Truffle: A popular Ethereum development framework that provides tools for
compiling, deploying, and testing smart contracts.
4. Node.js & npm: Node.js is a JavaScript runtime environment; npm is its package
manager used to install dependencies including Truffle.
5. MetaMask: A browser extension wallet that allows users to manage Ethereum
accounts and interact with decentralized applications.
6. Git Bash: Provides a Unix-like shell environment on Windows, useful for running
blockchain commands.
7. Docker (optional): Can be used to containerize blockchain networks such as
Hyperledger Fabric but is not strictly necessary for Ethereum setups.
4
CODE: INSTALLATION OF ETHEREUM, TRUFFLE, GANACHE, AND OTHER
TOOLS
Below are the commands and instructions you can run in your terminal (Git Bash or any
terminal with Node.js/npm installed) to verify the installations and initialize a basic Truffle
project:
This prints the installed versions of Node.js and npm. If not installed, download and install
from https://nodejs.org/.
5
STEP 6: CONFIGURE TRUFFLE TO CONNECT TO GANACHE
Edit truffle-config.js to add the following network configuration:
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*" // Match any network id
}
}
CODE EXPLANATION:
node -v and npm -v verify that Node.js and npm are installed, which are prerequisites
for running Truffle and Ganache.
npm install -g truffle installs the Truffle framework globally, allowing you to run the
truffle command anywhere.
truffle init sets up a new Ethereum project skeleton with folders for contracts,
migrations, and tests.
Ganache acts as a local blockchain for development and testing so you don’t need to
use public testnets or mainnet.
The network configuration in truffle-config.js tells Truffle to deploy contracts on your
local Ganache blockchain.
MetaMask serves as your wallet and connection interface to the Ethereum blockchain,
allowing you to interact with your deployed smart contracts from the browser.
6
PROGRAM 2: WRITING AND DEPLOYING BASIC SMART CONTRACTS ON
ETHEREUM
OBJECTIVE
The goal of this lab exercise is to introduce you to writing basic smart contracts in Solidity,
the most widely used programming language for Ethereum smart contracts and deploying
these contracts to a blockchain environment (local Ganache blockchain). This hands-on
experience will help you understand the fundamentals of smart contract development,
deployment, and interaction.
KEY CONCEPTS
1. What is a Smart Contract?
A smart contract is a self-executing program with the terms of the agreement directly written
into code. It runs on a blockchain, ensuring transparency, immutability, and decentralized
execution without relying on intermediaries.
Smart contracts can:
Store and manage digital assets.
Automate workflows based on pre-defined rules.
Provide decentralized applications (DApps) functionality.
EXAMPLE SKELETON:
pragma solidity ^0.8.0;
contract SimpleStorage {
uint storedData;
7
function set(uint x) public {
storedData = x;
}
function get() public view returns (uint) {
return storedData;
}
}
4. CONTRACT DEPLOYMENT
Deploying a smart contract means publishing the contract bytecode on the blockchain
so it can be executed and interacted with by users.
Deployment costs gas (Ethereum transaction fee), but on local Ganache, gas is
simulated and free.
Truffle provides scripts and commands to automate deployment.
6. Migration Scripts
Migration scripts are JavaScript files that handle deployment logic.
Located in the migrations folder, they define which contracts to deploy and in what
order.
Example: 2_deploy_contracts.js deploys your smart contracts.
8
After deployment, contracts have an address.
You interact with the contract by calling its functions using tools like Truffle Console,
web3.js, or ethers.js.
Functions can be:
o Read-only (view/pure) — no state change, no gas cost.
o State-changing — update state, cost gas.
contract SimpleStorage {
uint private storedData;
9
STEP 4: DEPLOY THE CONTRACT
Make sure Ganache is running locally. Deploy the contract to Ganache by running:
// Set a value
await instance.set(42);
CODE EXPLANATION:
The SimpleStorage contract contains a private state variable storedData.
The set function updates storedData with the input value.
The get function returns the current value of storedData.
The migration script 2_deploy_simple_storage.js tells Truffle to deploy the
SimpleStorage contract to the configured network.
The Truffle console allows you to interact with the deployed contract instance
asynchronously.
When you call set(42), it creates a transaction on the blockchain that modifies the
contract’s state.
When you call get(), it reads the stored value without consuming gas (because it’s a
view function).
The output 42 confirms the contract works as intended.
10
PROGRAM 3: CONFIGURING AND RUNNING A HYPERLEDGER FABRIC
NETWORK
OBJECTIVE
The objective of this lab exercise is to understand how to set up and configure a private
permissioned blockchain network using Hyperledger Fabric — an enterprise-grade, modular
blockchain framework. You will learn the architecture, key components, and steps to launch a
Fabric network, enabling secure, scalable, and permissioned decentralized applications.
KEY CONCEPTS
11
5. STEPS TO CONFIGURE AND RUN A BASIC FABRIC NETWORK:
Step 1: Download Fabric samples and binaries from the official Hyperledger Fabric
repository.
Step 2: Generate cryptographic material and certificates using cryptogen or Fabric CA.
Step 3: Create channel artifacts including genesis block and channel configuration
transactions.
Step 4: Launch network components (peers, orderers, CA, CLI) using Docker Compose
files.
Step 5: Create and join a channel where organizations communicate.
Step 6: Install and instantiate chaincode on peers.
Step 7: Invoke and query chaincode functions to interact with the ledger.
PREREQUISITES:
Docker and Docker Compose installed and running
cURL installed
12
Git installed
At least 8 GB RAM recommended
Query example:
docker exec -it cli bash
13
EXPLANATION:
Step 1: The script downloads everything needed for Fabric setup including Docker
images.
Step 3: The network.sh script automates starting orderers, peers, and certificate
authorities inside Docker containers, creating a channel for communication.
Step 4: Deploys chaincode (smart contract) to peers in the network.
Step 5: Uses Fabric CLI inside a container to invoke chaincode functions, allowing
you to test transactions.
Step 6: Stops and cleans up all running containers to free resources.
This approach uses the official Fabric sample test network for rapid setup and testing, which
is ideal for learning and prototyping.
14
PROGRAM 4: STORING AND RETRIEVING DATA USING IPFS
OBJECTIVE
This lab exercise aims to familiarize you with the InterPlanetary File System (IPFS) — a
decentralized peer-to-peer storage protocol. You will learn how to store files on IPFS, retrieve
them using content-based addressing, and understand its integration potential with blockchain
for secure, immutable, and distributed data storage.
KEY CONCEPTS:
1. WHAT IS IPFS?
IPFS is a distributed file system protocol designed to make the web faster, safer, and more
open. Instead of addressing data by location (like HTTP URLs), IPFS addresses data by its
content hash.
It forms a decentralized network where peers store and share content.
Files are split, hashed, and stored across nodes.
Content is immutable and verifiable via its cryptographic hash.
15
Files can be added via command line or API calls.
16
ipfs add example.txt
addAndRetrieve();
CODE EXPLANATION:
ipfs init sets up your local IPFS node’s repository.
ipfs daemon launches your node to participate in the IPFS network.
ipfs add uploads a file, returning a CID which uniquely identifies the content.
ipfs cat fetches content from the network using the CID.
Pinning keeps the content persistently available on your node.
The JavaScript example shows how to add and retrieve data programmatically via
IPFS HTTP API, enabling integration in apps.
17
PROGRAM 5: USING BLOCKCHAIN TO ENSURE DATA INTEGRITY IN
MACHINE LEARNING MODELS
OBJECTIVE:
This lab exercise focuses on how blockchain technology can be leveraged to ensure data
integrity, provenance, and auditability in machine learning (ML) pipelines. You will
understand how blockchain’s immutable ledger can provide trustworthy data management
crucial for building reliable, transparent, and tamper-proof ML models.
KEY CONCEPTS:
1. Data Integrity in Machine Learning
ML models heavily depend on the quality and integrity of training data.
Data tampering, corruption, or unauthorized modifications can lead to biased,
inaccurate, or malicious models.
Verifying data provenance and ensuring data immutability is critical for trustworthy
AI.
4. Workflow Integration
Typical workflow to ensure ML data integrity using blockchain:
Data Collection: Raw data is collected from trusted sources.
Hashing Data: Generate cryptographic hashes (fingerprints) of datasets or data
batches.
Blockchain Recording: Store the hashes, timestamps, and metadata as transactions on
the blockchain.
Model Training: ML pipelines reference these hashes to confirm the training data has
not changed.
Audit and Verification: Any party can verify data integrity by comparing dataset
hashes against the blockchain records.
5. Advantages
Immutability: Blockchain records are unalterable.
18
Transparency: All stakeholders can access the data provenance.
Decentralization: No single point of failure or control.
Auditability: Enables compliance with data regulations and ethical AI standards.
6. Technical Considerations
Storing large datasets directly on-chain is infeasible; instead, store hashes on-chain
and actual data off-chain (e.g., IPFS or secure databases).
Use smart contracts to automate validation, access control, or alerts on data
inconsistencies.
Integrate blockchain verification steps into ML pipelines to ensure only verified data
is used.
9. Challenges
Latency and throughput limits of blockchains.
Balancing privacy and transparency (sensitive data should not be exposed on-chain).
Integration complexity between ML workflows and blockchain infrastructure.
contract DataIntegrity {
// Event emitted when a new data hash is registered
event DataHashRegistered(address indexed sender, bytes32 dataHash, uint256 timestamp);
19
mapping(bytes32 => uint256) public dataHashes;
INSTALL DEPENDENCIES:
20
// Read dataset file
const data = fs.readFileSync('dataset.csv');
// Instantiate contract
const contract = new web3.eth.Contract(contractABI, contractAddress);
main().catch(console.error);
CODE EXPLANATION:
The Solidity contract stores hashes of datasets as bytes32 keys mapped to timestamps.
The registerDataHash function adds a new hash with the current block timestamp,
preventing duplicates.
The Node.js script hashes the data file off-chain using SHA-256 and then records this
hash on-chain.
Later, the same hash can be verified to ensure the dataset has not been modified since
registration.
This workflow integrates blockchain immutability with ML data integrity guarantees.
21
PROGRAM 6: IMPLEMENTING A BLOCKCHAIN-BASED DATA PROVENANCE
SYSTEM
OBJECTIVE:
This lab exercise aims to develop an understanding of how blockchain technology can be
used to implement a data provenance system—a system that tracks the origin, history, and
lifecycle of data throughout its existence. Provenance ensures trust, accountability, and
transparency in data management, which is essential for sensitive or regulated domains.
Key Concepts:
1. What is Data Provenance?
Data provenance refers to the detailed history of data, including where it originated,
how it was created, processed, modified, and by whom.
It helps establish data authenticity, lineage, and audit trails.
Provenance is critical for verifying data quality, compliance, and reproducibility.
22
Allow querying of provenance history for any data item.
Use access controls to protect sensitive provenance details.
7. Use Cases
Scientific research data reproducibility.
Healthcare records lifecycle management.
Supply chain product origin and processing history.
Data marketplaces verifying provenance before transactions.
contract DataProvenance {
struct ProvenanceEvent {
address actor;
uint256 timestamp;
string operation; // e.g., "CREATE", "UPDATE", "DELETE"
string description;
}
23
event ProvenanceRecorded(bytes32 indexed dataId, address indexed actor, string
operation, uint256 timestamp);
24
STEP 3: EXAMPLE INTERACTION USING TRUFFLE CONSOLE
CODE EXPLANATION:
DataProvenance contract records multiple provenance events per data item, identified
by a hash (dataId).
Each event stores the actor’s address, timestamp, operation type, and a descriptive
note.
Events are stored in arrays mapped to the data identifier, enabling full lifecycle
tracking.
Functions allow recording new events and retrieving event history by index.
Example interaction shows how to record and query provenance events in a real
blockchain environment.
This smart contract provides an immutable, auditable provenance ledger accessible to
all network participants.
25
PROGRAM 7: DEVELOPING A DECENTRALIZED MARKETPLACE FOR DATA
EXCHANGE
OBJECTIVE:
This lab exercise aims to explore the design and implementation of a decentralized
marketplace for data exchange using blockchain technology. You will learn how blockchain
enables secure, transparent, and trustless buying, selling, and sharing of datasets without
relying on centralized intermediaries.
KEY CONCEPTS:
1. What is a Decentralized Data Marketplace?
A platform where data providers and consumers transact directly over a blockchain
network.
Removes middlemen, reducing costs and censorship risks.
Participants retain control over their data and transactions are transparent and
verifiable.
3. Marketplace Components:
Data Listings: Metadata describing datasets for sale (size, type, quality).
Smart Contracts: Facilitate listing, bidding, payment, and delivery.
Payment Mechanisms: Often use cryptocurrencies or tokens.
Access Management: Controls who can download or use data post-purchase.
Reputation Systems: Evaluate trustworthiness of sellers and buyers.
4. Architecture Overview:
On-chain Components:
o Smart contracts handling listings, bids, payments, and dispute resolution.
o Token contracts for payments or incentives.
Off-chain Components:
o Actual data storage on decentralized storage (e.g., IPFS).
o User interfaces (web/mobile apps).
o Data encryption and key management.
5. Workflow Example:
Seller uploads dataset to IPFS and pins it.
Seller creates a listing on blockchain marketplace contract with dataset CID and price.
Buyer browses listings, chooses dataset, and sends payment via smart contract.
Upon payment confirmation, buyer receives decryption key or access rights.
26
Smart contract releases funds to seller.
Both parties may rate the transaction to build reputation.
7. Challenges:
Ensuring data privacy while sharing on a public blockchain.
Managing off-chain data storage reliability.
Handling disputes and refunds fairly.
Scalability for large user bases and datasets.
Regulatory and compliance considerations.
9. Use Cases:
Scientific data sharing marketplaces.
IoT sensor data exchanges.
Healthcare data sharing with patient consent.
Financial data subscription services.
contract DataMarketplace {
struct Listing {
address payable seller;
string dataCID; // IPFS CID of the dataset
27
uint256 price; // Price in wei
bool sold;
}
event DataListed(uint256 listingId, address indexed seller, string dataCID, uint256 price);
event DataPurchased(uint256 listingId, address indexed buyer, uint256 price);
listing.sold = true;
listing.seller.transfer(msg.value);
emit DataPurchased(listingId, msg.sender, msg.value);
}
28
Step 2: Migration Script
Create 2_deploy_data_marketplace.js:
const DataMarketplace = artifacts.require("DataMarketplace");
CODE EXPLANATION:
The contract maintains an array of Listing structs representing datasets for sale.
Sellers list data by providing an IPFS CID and a price.
Buyers purchase by sending the exact amount of Ether; payment is immediately
transferred to the seller.
Events notify off-chain apps of listing and purchase actions.
This simple contract does not handle access control or encrypted data delivery; those
are handled off-chain or in extended implementations.
29
PROGRAM 8: WRITING AND DEPLOYING CHAINCODE ON HYPERLEDGER
FABRIC
OBJECTIVE:
This lab exercise aims to teach you how to write, package, install, and instantiate chaincode
(smart contracts) on a Hyperledger Fabric network. Chaincode defines the business logic and
transaction rules that run on the Fabric peers, enabling decentralized applications with trusted
workflows.
KEY CONCEPTS:
1. What is Chaincode?
Chaincode is Fabric’s equivalent of smart contracts.
It is a program, typically written in Go, Java, or JavaScript (Node.js), executed by
peers to validate and update the ledger state.
Chaincode handles transaction proposals and endorses them according to predefined
logic.
2. Chaincode Lifecycle
Fabric v2.x introduces a new lifecycle process:
Packaging: Chaincode is packaged into a tarball.
Installation: Installed on peers.
Approval: Each organization approves the chaincode definition.
Commitment: The chaincode is committed to the channel.
Instantiation: The chaincode is ready for use.
This process ensures decentralized governance and versioning.
3. Chaincode Structure
A typical chaincode has:
Init function: Initialization logic called during instantiation.
Invoke function: Handles different transaction functions.
State interactions: Uses the ledger APIs to read/write key-value pairs.
Error handling and validation.
4. Writing Chaincode (Go Example)
Use the Fabric Chaincode Shim API to interact with the ledger.
Define functions for create, update, delete, query operations.
Manage composite keys for complex data.
5. Packaging Chaincode
Chaincode source code is packaged into a .tar.gz format.
Metadata specifies name, version, language, and endorsement policy.
6. Installing Chaincode
Chaincode package is installed on each peer using CLI or SDK.
Installation verifies code integrity and prepares it for endorsement.
7. Approving Chaincode
Each org must approve the chaincode definition specifying version, sequence,
endorsement policy, and collections config.
8. Committing Chaincode
Once all necessary approvals are obtained, the chaincode is committed to the channel.
This activates the chaincode for transactions.
30
9. Invoking Chaincode
Clients submit transaction proposals to invoke chaincode functions.
Endorsing peers simulate and sign proposals.
Orderer packages endorsed transactions into blocks.
Peers validate and commit transactions to the ledger.
10. Testing and Debugging
Use Fabric test networks or development environments.
Logs and lifecycle commands help debug deployment and execution.
11. Use Cases
Asset transfer and tracking.
Supply chain provenance.
Healthcare data management.
Decentralized finance.
12. Tools
Fabric samples repo includes example chaincode.
Fabric CLI, SDKs, and APIs facilitate interaction.
VSCode extensions support chaincode development.
import (
"encoding/json"
"fmt"
"github.com/hyperledger/fabric-contract-api-go/contractapi"
)
31
func (c *AssetTransferContract) InitLedger(ctx contractapi.TransactionContextInterface)
error {
assets := []Asset{
{ID: "asset1", Value: "100"},
{ID: "asset2", Value: "200"},
}
asset := Asset{
ID: id,
Value: value,
}
assetJSON, err := json.Marshal(asset)
if err != nil {
return err
}
32
func (c *AssetTransferContract) ReadAsset(ctx contractapi.TransactionContextInterface, id
string) (*Asset, error) {
assetJSON, err := ctx.GetStub().GetState(id)
if err != nil {
return nil, fmt.Errorf("failed to read asset %s from world state: %v", id, err)
}
if assetJSON == nil {
return nil, fmt.Errorf("asset %s does not exist", id)
}
// AssetExists returns true when asset with given ID exists in world state
func (c *AssetTransferContract) AssetExists(ctx contractapi.TransactionContextInterface, id
string) (bool, error) {
assetJSON, err := ctx.GetStub().GetState(id)
if err != nil {
return false, err
}
return assetJSON != nil, nil
}
func main() {
contract := new(AssetTransferContract)
33
Install on peers, approve, commit (requires Fabric CLI and proper environment
variables set).
For a test network, you can use scripts from Fabric samples (test-network folder) to deploy
the sample chaincode.
CODE EXPLANATION:
The Go chaincode defines an AssetTransferContract with basic CRUD functions for
assets.
InitLedger seeds the ledger with initial data.
Chaincode interacts with the ledger state through PutState and GetState.
The Fabric chaincode shim API handles transaction contexts and world state.
Packaging and lifecycle commands deploy the chaincode to the Fabric network.
Invokes modify ledger state; queries read data without modification.
34
PROGRAM 9: IMPLEMENTING A SECURE VOTING SYSTEM USING
BLOCKCHAIN
OBJECTIVE:
This lab exercise focuses on designing and implementing a secure, transparent, and
tamper-proof voting system using blockchain technology. The aim is to leverage
blockchain’s immutable ledger and cryptographic properties to ensure election integrity, voter
privacy, and trust in the electoral process.
KEY CONCEPTS:
1. Why Use Blockchain for Voting?
Transparency: All votes are recorded on a public, immutable ledger accessible to
stakeholders.
Immutability: Once recorded, votes cannot be altered or deleted, preventing fraud.
Decentralization: Removes the need for a central trusted authority.
Verifiability: Voters can independently verify their votes.
Security: Cryptographic techniques ensure voter anonymity and data integrity.
35
6. Challenges
Balancing transparency and privacy.
Scalability to handle large voter bases.
Prevention of coercion and vote-buying.
User-friendly interfaces and accessibility.
8. Real-World Examples
Estonia’s e-voting system leveraging blockchain.
West Virginia’s pilot mobile voting app.
Research projects combining blockchain with advanced cryptography.
contract Voting {
struct Candidate {
uint id;
string name;
uint voteCount;
}
modifier onlyAdmin() {
require(msg.sender == admin, "Only admin can perform this action");
36
_;
}
constructor() {
admin = msg.sender;
}
voters[msg.sender] = true;
candidates[_candidateId].voteCount++;
37
await voting.addCandidate("Alice", { from: accounts[0] });
await voting.addCandidate("Bob", { from: accounts[0] });
CODE EXPLANATION:
The contract maintains a list of candidates with vote counts.
The admin (deployer) can add candidates before voting begins.
Each Ethereum address can vote once, enforced by the voters mapping.
Votes increment the selected candidate’s count.
The contract emits an event on each vote for transparency.
This simple model lacks anonymity and advanced privacy but demonstrates core
voting logic.
38
PROGRAM 10: COMBINING BLOCKCHAIN WITH IOT FOR SECURE DATA
MANAGEMENT
OBJECTIVE:
This lab exercise aims to explore how blockchain technology can be integrated with Internet
of Things (IoT) systems to ensure secure, tamper-proof, and transparent management of IoT
data. You will understand the challenges of IoT data security and how blockchain’s
decentralized ledger can provide solutions.
KEY CONCEPTS:
1. IoT Data Challenges
Massive volumes of data generated by distributed IoT devices.
Data integrity risks due to device vulnerabilities and potential tampering.
Centralized IoT architectures face single points of failure and trust issues.
Need for reliable audit trails and provenance for IoT sensor data.
2. Why Blockchain for IoT Data Management?
Decentralization: Eliminates single points of failure.
Immutability: Ensures data recorded is tamper-proof.
Transparency and Auditability: All transactions logged and verifiable.
Trustless Environment: Devices can interact without centralized trust.
Automated Agreements: Smart contracts enable automatic actions on predefined
conditions.
3. Architecture for Blockchain-IoT Integration
IoT Devices: Sensors, actuators collecting and sending data.
Edge Gateways: Aggregate and preprocess data; interface with blockchain.
Blockchain Network: Stores hashes or summaries of IoT data and controls access.
Smart Contracts: Automate data validation, alerting, and workflows.
Off-chain Storage: Due to data volume, raw data often stored off-chain (e.g., IPFS),
with blockchain storing references.
4. Data Flow
IoT device captures data → data sent to gateway → data hashed and/or encrypted →
hash and metadata sent to blockchain → data stored off-chain → smart contracts
triggered for rules (e.g., alerts).
5. Security Benefits
Detect tampering by comparing on-chain hash with off-chain data.
Authenticate devices via blockchain-based identity management.
Enable secure firmware updates via blockchain verification.
6. Consensus and Scalability Considerations
Lightweight consensus mechanisms or permissioned blockchains suit IoT constraints.
Edge computing reduces latency and bandwidth needs.
Layer-2 solutions and sidechains can help scale.
39
7. Use Cases
Supply chain monitoring with sensor data provenance.
Smart grids and energy management.
Healthcare wearables securely sharing data.
Environmental monitoring with trusted data logging.
8. Challenges
Resource constraints on IoT devices.
Latency and throughput of blockchain.
Privacy concerns for sensitive IoT data.
Complex integration and standardization.
9. Technologies
Ethereum, Hyperledger Fabric, IOTA (specialized for IoT).
IPFS and other decentralized storage.
Blockchain SDKs tailored for IoT.
contract IoTDataRegistry {
struct DataRecord {
bytes32 dataHash;
uint256 timestamp;
address device;
}
40
// Register IoT data hash on blockchain
function registerData(bytes32 _dataHash) public {
DataRecord memory record = DataRecord({
dataHash: _dataHash,
timestamp: block.timestamp,
device: msg.sender
});
records.push(record);
emit DataRegistered(_dataHash, block.timestamp, msg.sender);
}
41
deployer.deploy(IoTDataRegistry);
};
Deploy with:
truffle migrate --network development
42
// Register hash on blockchain
const receipt = await contract.methods.registerData('0x' + hash).send({ from:
deviceAccount, gas: 300000 });
console.log('Data registered in transaction:', receipt.transactionHash);
}
registerIoTData('sensor_data.json').catch(console.error);
CODE EXPLANATION:
The IoTDataRegistry smart contract records hashes of IoT data submissions with
timestamps and device addresses.
Each IoT device (simulated by Ethereum accounts) registers data hashes immutably
on-chain.
The Node.js script simulates an IoT device reading sensor data, hashing it, and
registering the hash on Ethereum.
This provides a tamper-proof, verifiable record of IoT data collection events.
Actual sensor data can be stored off-chain (e.g., IPFS), referenced securely via the
blockchain hash.
43