BlockChain IITKGP
BlockChain IITKGP
IIT KHARAGPUR
Theory
What is Blockchain?
Key Concepts:
• Block: A container of data in the blockchain. Each block typically contains a set of
transactions.
• Chain: A series of blocks connected in a linear, immutable way. Each block is linked
to the previous one through a cryptographic hash.
• Decentralization: The distribution of data across a network of nodes, eliminating the
need for a centralized authority.
• Distributed Ledger Technology (DLT): A type of database where data is shared and
synchronized across multiple locations.
• Transaction Initiation: When a transaction is initiated, the details are captured into a
block.
• Validation: Network participants (nodes) validate the transaction to ensure its
legitimacy (via consensus algorithms such as Proof of Work, Proof of Stake, etc.).
• Block Creation: After validation, the transaction is added to a block along with a
timestamp.
• Consensus: Nodes in the network reach a consensus to ensure the block is added to
the chain. Consensus mechanisms such as Proof of Work (PoW) or Proof of Stake
(PoS) ensure that the majority of the network agrees with the block addition.
• Immutability: Once a block is added to the chain, it cannot be altered without
altering every subsequent block, which would require the consensus of the majority of
the network.
Importance of Blockchain:
1. Security and Transparency: Blockchain provides transparency and security in
transactions due to its cryptographic nature. Data is encrypted and decentralized,
making it nearly impossible for hackers to alter transaction records.
2. Decentralization: No central authority controls the blockchain, which means that it
removes the risk of a single point of failure.
3. Efficiency: Blockchain enables faster transactions and lowers the need for
intermediaries like banks or clearing houses, leading to reduced costs.
4. Trust and Accountability: The decentralized and transparent nature of blockchain
fosters trust between parties, as they can independently verify the information.
5. Automation: Blockchain facilitates smart contracts, which are self-executing
contracts with the terms of the agreement written into code. This eliminates manual
processing, reducing errors and costs.
Technical Insights
Code
python
Copy code
import hashlib
import time
class Block:
def __init__(self, index, previous_hash, timestamp, data, hash):
self.index = index
self.previous_hash = previous_hash
self.timestamp = timestamp
self.data = data
self.hash = hash
def __str__(self):
return f"Block #{self.index} [Timestamp: {self.timestamp}, Hash:
{self.hash}]"
def create_genesis_block():
return Block(0, "0", int(time.time()), "Genesis Block",
calculate_hash(0, "0", int(time.time()), "Genesis Block"))
# Testing Blockchain
genesis_block = create_genesis_block()
blockchain = [genesis_block]
# Display blockchain
for block in blockchain:
print(block)
Explanation:
Expected Output:
less
Copy code
Block #0 [Timestamp: 1603085199, Hash:
3f8d9c6c423b8e0d2f98c4d09a21a7d0be4310c70d9c2c957d7f79ec346c2b09]
Block #1 [Timestamp: 1603085200, Hash:
2f59b0c1c74fa4a0188a32ac8d8b66ea7fa7f68db647ce1e8d4f4014505fe9f0]
Block #2 [Timestamp: 1603085201, Hash:
4a7581c34ee6e0ed3f9068cd7f03860367460d00ea7b1fdfeb65768c4700f849]
Block #3 [Timestamp: 1603085202, Hash:
4c0eae49d200337c6f086bb48f1a6c14b217feb63ac1793885c8ef65f35418de]
Block #4 [Timestamp: 1603085203, Hash:
bde924f8ff33f3fbe7b4e3b8d5de5f09bfaad83e6f5a1bbaf22372da3a22a13e]
Block #5 [Timestamp: 1603085204, Hash:
c38aeb6d6a45a06b416b0d75ad1d0cc4e3eeb92b06099e30e30619f7b537f340]
Applications
Conclusion
In subsequent weeks, we will delve deeper into consensus mechanisms, smart contracts, and
more complex applications of blockchain technology.
Week 2: Basic Crypto Primitives I – Cryptographic Hash
Theory
1. Deterministic: For a given input, the output (hash) will always be the same.
2. Fixed Output Length: No matter the size of the input, the output hash will always
have a fixed length. For example, SHA-256 produces a 256-bit hash.
3. Fast Computation: It is computationally efficient to calculate the hash of an input.
4. Pre-image Resistance: Given a hash value, it is computationally infeasible to find the
original input that produced that hash.
5. Small Changes in Input Yield Drastic Changes in Output: Even a tiny change in
the input will produce a completely different hash, making it difficult to predict output
values.
6. Collision Resistance: It is computationally infeasible to find two different inputs that
hash to the same output (i.e., no collisions).
7. Puzzle Friendliness: Cryptographic hash functions are used to create puzzles in Proof
of Work (PoW) systems, such as Bitcoin, where miners must find the correct hash for
a block to be added to the blockchain.
Technical Insights
• SHA-256 Algorithm: The SHA-256 algorithm is part of the SHA-2 family and
outputs a fixed 256-bit hash. The algorithm performs multiple rounds of operations on
the input data, including logical operations and modular arithmetic, to produce the
hash.
• Block Size: In SHA-256, the input data is divided into 512-bit blocks, and each block
is processed individually. Padding is added to the input data to make sure that it is a
multiple of 512 bits.
• Hashing Process:
0. Message Padding: The original message is padded to ensure its length is a
multiple of 512 bits.
1. Message Parsing: The padded message is divided into 512-bit blocks.
2. Initialize Hash Values: SHA-256 initializes eight 32-bit words, which are
used during the hash calculation.
3. Compression Function: Each block is processed in a loop using bitwise
operations like XOR and AND.
4. Final Hash: After all blocks are processed, the final hash is obtained by
combining the intermediate results.
• Speed vs Security: Cryptographic hash functions like SHA-256 are designed to be
fast, but not so fast that they are vulnerable to brute-force attacks. This makes them
efficient for blockchain applications, where large numbers of hash computations need
to be performed quickly.
Code
python
Copy code
import hashlib
def hash_message(message):
# Encode the message as bytes
message_bytes = message.encode('utf-8')
Explanation:
• The function hash_message accepts a message string, encodes it into bytes, and then
hashes it using SHA-256.
• The update() method of the SHA-256 hash object processes the input message, and
hexdigest() provides the resulting hash as a hexadecimal string.
Expected Output:
mathematica
Copy code
Original Message: Blockchain is revolutionary!
SHA-256 Hash:
7a5d8fcb209b1207f19ebf1a594d37c907e93792b32d2b43f4649b05237ec5a9
• Message Integrity: If even a single character of the original message changes, the
output hash will be completely different.
o For example, changing the message to "Blockchain is awesome!" will
produce a different hash.
Applications
1. Blockchain:
o Transaction Verification: In a blockchain, when a transaction is made, the
transaction's details are hashed, and the resulting hash is included in the block.
The hash is then used to verify that the transaction has not been tampered
with.
o Mining: In Proof of Work (PoW) blockchains like Bitcoin, miners must find a
hash that meets certain criteria (e.g., starting with a certain number of leading
zeros). This requires trying many different nonce values until a valid hash is
found.
o Block Integrity: Each block in the blockchain contains a hash of the previous
block. This ensures that the entire chain is tamper-resistant; if any block is
altered, the hash will change, and the tampered block will be detected.
2. Digital Signatures: Cryptographic hash functions are used in digital signature
algorithms (e.g., RSA, ECDSA). A message is hashed, and the hash is then signed.
The recipient verifies the signature by hashing the message again and checking that
the signature matches.
3. File Integrity: Hash functions are used to verify the integrity of files. When
downloading files from the internet, the website might provide a hash of the file. After
downloading, users can compute the hash of the file themselves and compare it to the
provided hash. If the hashes match, the file is intact; if not, the file may have been
corrupted or tampered with.
4. Password Storage: Instead of storing plaintext passwords, systems can store the hash
of the password. When a user attempts to log in, the system hashes the entered
password and compares it to the stored hash. This way, even if the password database
is compromised, the passwords remain secure.
5. Merkle Trees: In blockchain, Merkle Trees use hash functions to create a tree of
hashes where each leaf node is a hash of the data, and each internal node is a hash of
its children. This structure allows for efficient and secure verification of large sets of
data, making it useful for validating transactions in a blockchain.
Conclusion
In Week 2, we've explored cryptographic hash functions, which are foundational to many
blockchain protocols and applications. We've examined how these functions work, their key
properties, and their relevance in securing data. Through the code example, we learned how
to hash messages in Python using SHA-256, a widely used hash function in blockchain.
Hashing serves a critical role in ensuring data integrity, enabling decentralized security, and
facilitating efficient verification processes in blockchain systems and other domains.
In the next week, we will continue to explore more cryptographic primitives that are essential
in the broader landscape of blockchain technology.
Week 3: Basic Crypto Primitives II – Digital Signature
Theory
1. Signing Process:
o The sender creates a message (or document) that they wish to send.
o The sender uses their private key to generate a digital signature for the
message. The digital signature is typically a hash of the message encrypted
with the sender's private key.
2. Verification Process:
o The recipient gets the message and the accompanying digital signature.
o The recipient uses the sender's public key to decrypt the signature and obtain
the hash of the original message.
o The recipient also computes the hash of the received message.
o If the computed hash matches the decrypted hash from the digital signature,
the recipient knows that the message is authentic and unaltered.
Technical Insights
Code
Here is an implementation of RSA and ECDSA for generating and verifying digital
signatures using Python's cryptography library.
python
Copy code
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
# Message to be signed
message = b"Blockchain is changing the world"
Explanation:
Expected Output:
csharp
Copy code
The signature is valid!
python
Copy code
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
# Message to be signed
message = b"Blockchain technology is revolutionary!"
Explanation:
Expected Output:
csharp
Copy code
The ECDSA signature is valid!
Applications
1. Blockchain Applications:
o Bitcoin: Digital signatures in Bitcoin ensure that transactions are authentic and
that only the owner of a private key can authorize spending from their wallet.
o Ethereum: Ethereum uses digital signatures for transactions in smart
contracts, ensuring that only authorized participants can execute actions on the
blockchain.
2. Email Security:
o PGP (Pretty Good Privacy): Digital signatures in PGP encrypt and sign
emails to ensure that the email content is authentic and hasn’t been tampered
with. PGP is widely used for email encryption and digital signatures.
3. Software Distribution:
o Software developers use digital signatures to ensure that the software being
distributed has not been altered. Users can verify that they are downloading
the correct, unmodified version of software by checking the digital signature.
4. Authentication:
o SSH: In SSH, digital signatures are used to authenticate the identity of the user
or server. This ensures secure communication between remote systems and
verifies that they are the entities they claim to be.
5. Digital Contracts:
o Smart contracts in blockchain technology often use digital signatures to verify
that both parties have agreed to the contract terms. These signatures ensure
that a contract is enforceable and that no party can deny their participation.
Conclusion
In Week 3, we delved into the concept of digital signatures, which provide authentication,
integrity, and non-repudiation in digital communications. We explored how RSA and
ECDSA algorithms work for signing and verifying messages, and we implemented both in
Python. Digital signatures are crucial in blockchain systems, email security, software
distribution, and many other applications. They ensure that data is authentic, secure, and
tamper-proof, thus playing a pivotal role in the integrity of blockchain-based systems and
cryptographic protocols.
In the upcoming week, we will continue with more cryptographic primitives, focusing on
topics related to encryption and security in blockchain systems.
Week 4: Evolution of Blockchain Technology
Theory
Technical Insights
1. Consensus Mechanisms:
o Blockchain relies on consensus mechanisms to validate transactions. Initially,
Proof-of-Work (PoW) was used, where miners solve complex mathematical
problems to add blocks to the blockchain (used by Bitcoin).
o Later, Proof-of-Stake (PoS) was introduced, where validators are selected
based on the amount of cryptocurrency they hold and are willing to "stake" as
collateral (used by Ethereum 2.0).
o Newer consensus mechanisms, like Delegated Proof-of-Stake (DPoS),
Proof-of-Authority (PoA), and Byzantine Fault Tolerance (BFT), are also
used in various blockchain systems to enhance scalability, efficiency, and
security.
2. Smart Contracts:
o Smart contracts are self-executing contracts where the terms are directly
written into lines of code.
o These contracts are executed by blockchain nodes and automatically enforce
the rules encoded in the contract. Ethereum’s Solidity programming language
is the most popular tool for creating smart contracts.
o Smart contracts eliminate intermediaries, making transactions faster, cheaper,
and more secure. They enable a wide range of decentralized applications
(dApps) in finance, insurance, real estate, and beyond.
3. Sharding:
o Sharding is a technique used to improve the scalability of blockchains. It
involves splitting the blockchain into smaller "shards," each of which
processes a subset of the total transactions, allowing multiple transactions to
occur in parallel.
o Ethereum 2.0 plans to implement sharding to increase throughput and reduce
congestion on the network.
4. Layer-2 Solutions:
o Layer-2 solutions work on top of the main blockchain (Layer-1) to increase
scalability without compromising security. These include:
State Channels: Allowing users to transact off-chain, with only the
final state recorded on the blockchain.
Rollups: Bundling multiple transactions into a single batch for
processing on the main blockchain, reducing transaction fees and
congestion.
Plasma: A framework for creating child blockchains connected to the
main blockchain to improve scalability and reduce costs.
Code Example
solidity
Copy code
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SimpleStorage {
uint256 private storedData;
Explanation:
• This contract stores an unsigned integer (storedData) and provides two functions:
0. set(uint256 x) allows users to set a value.
1. get() returns the stored value.
Deployment: To deploy this contract, you can use tools like Remix or Truffle for
development, testing, and deployment.
Applications
1. Cryptocurrency:
o Bitcoin: The first application of blockchain technology, Bitcoin,
revolutionized digital payments by allowing peer-to-peer transactions without
intermediaries.
o Ethereum: Beyond cryptocurrency, Ethereum enabled the development of
decentralized applications (dApps) and smart contracts, creating new
possibilities for financial services, gaming, and other industries.
2. Supply Chain Management:
o Blockchain ensures the transparency and traceability of goods as they move
through the supply chain. IBM’s Food Trust Blockchain helps track food
products from farm to table, ensuring the authenticity of the products.
3. Decentralized Finance (DeFi):
o Platforms like Uniswap, Aave, and Compound use blockchain technology to
provide decentralized financial services, such as lending, borrowing, and
trading, without the need for intermediaries like banks.
4. Voting:
o Blockchain-based voting systems, such as Follow My Vote, aim to provide
secure, transparent, and tamper-proof voting mechanisms, reducing the
potential for election fraud.
5. Healthcare:
o Blockchain ensures the privacy and security of patient records while enabling
easy sharing of medical data across different healthcare providers. Solve.Care
is one such platform that uses blockchain for healthcare administration.
6. Digital Identity:
o Blockchain can be used to create secure and verifiable digital identities. Sovrin
is an example of a platform that provides decentralized digital identity solutions,
where individuals control access to their personal data.
Week 5: Elements of a Blockchain
Theory
1. Block:
o A block is a container that holds a list of transactions. It is the basic unit of a
blockchain.
o A typical block contains:
Block header: Contains metadata such as the hash of the previous
block, timestamp, and a reference to the block's content.
Transaction data: The actual data that describes the transactions
made, such as sender, receiver, amount, and any additional metadata.
o Blocks are linked together to form a continuous, immutable chain of records.
2. Chain:
o The chain refers to the interconnected sequence of blocks, where each block is
linked to its predecessor using a hash pointer.
o The linkage ensures the integrity of the blockchain, making it tamper-evident.
If an attacker attempts to modify a block, the hash of the block changes,
breaking the chain and alerting the network.
3. Cryptographic Hash:
o Each block contains a cryptographic hash of its contents, which is a fixed-
size output derived from a mathematical function.
o The hash of a block is used to uniquely identify it and link it to the previous
block. This ensures that any changes to the data within a block will result in a
different hash, which is easily detectable.
o The most common cryptographic hash function used in blockchain systems is
SHA-256 (Secure Hash Algorithm 256-bit).
4. Distributed Ledger:
o A distributed ledger is a database that is shared and synchronized across
multiple participants, often in different geographical locations.
o The distributed nature of the blockchain ensures that no single entity has
control over the data. Each participant has a copy of the entire blockchain, and
all transactions are verified by the network.
o This decentralized structure eliminates the need for trusted intermediaries, like
banks or governments, to validate transactions.
5. Consensus Mechanism:
o A consensus mechanism is the process used to achieve agreement among
participants in the network about the validity of transactions and the order in
which they are added to the blockchain.
o Common consensus algorithms include:
Proof of Work (PoW): Miners solve complex mathematical problems
to add new blocks to the chain (used in Bitcoin).
Proof of Stake (PoS): Validators are selected based on the amount of
cryptocurrency they hold and are willing to "stake" as collateral (used
in Ethereum 2.0).
Delegated Proof of Stake (DPoS), Proof of Authority (PoA), and
Byzantine Fault Tolerance (BFT) are also used in various
blockchains.
6. Public and Private Keys:
o Blockchain uses public key cryptography to secure transactions.
o Each user has a public key (which can be shared with others) and a private
key (which must remain secret).
o When a user wants to send a transaction, they use their private key to sign the
transaction. This ensures that only the owner of the private key can initiate a
transaction and that the transaction cannot be altered once it is signed.
o The recipient can verify the authenticity of the transaction using the sender’s
public key.
7. Nodes:
o Nodes are the individual participants or computers that form the blockchain
network. Each node stores a copy of the blockchain and plays a role in
validating transactions.
o There are different types of nodes:
Full nodes: These store the entire blockchain and validate all
transactions.
Lightweight nodes: These store only part of the blockchain and rely
on full nodes to validate transactions.
Mining nodes: In networks that use Proof of Work, mining nodes
participate in solving cryptographic puzzles to add new blocks to the
chain.
8. Transaction:
o A transaction is a record of an action or exchange between users on the
blockchain. It typically involves the transfer of cryptocurrency or assets but
can also represent other forms of data exchange.
o Transactions are grouped together and added to a block, which is then verified
by the blockchain network.
9. Immutability:
o One of the defining features of blockchain is its immutability. Once a block is
added to the chain, it is nearly impossible to alter or delete. This is due to the
cryptographic linking of blocks and the consensus mechanism used to validate
them.
o The immutability of blockchain ensures that the record of transactions is
tamper-proof, making it highly reliable for applications that require integrity
and trust.
10. Smart Contracts (Optional):
o A smart contract is a self-executing contract with the terms of the agreement
directly written into code. Smart contracts automatically execute actions when
predefined conditions are met, reducing the need for intermediaries.
o Ethereum is the most popular blockchain platform for deploying smart
contracts, enabling decentralized applications (dApps).
Technical Insights
python
Copy code
import hashlib
2. Consensus Algorithms:
o Proof of Work (PoW):
In PoW, miners compete to solve complex mathematical puzzles to
validate transactions and add new blocks. The first miner to solve the
puzzle is rewarded with cryptocurrency.
o Proof of Stake (PoS):
In PoS, validators are chosen to create new blocks based on the amount
of cryptocurrency they hold and are willing to stake. PoS is considered
more energy-efficient than PoW.
3. Smart Contract Execution:
o Smart contracts are executed by nodes on the blockchain network. Each time a
smart contract is invoked, the code within the contract is executed, and the
transaction is validated by the network.
o Example of Solidity code for a simple smart contract:
solidity
Copy code
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SimpleStorage {
uint256 public storedData;
o This contract stores and retrieves a value, and it is executed on the Ethereum
blockchain.
Code Example
python
Copy code
import hashlib
# Sample data
data = "Blockchain is amazing"
Explanation:
Applications
1. Cryptocurrency:
o Bitcoin: Bitcoin uses blockchain for secure and transparent transactions
without the need for a centralized authority. The blockchain ensures the
integrity of transactions through cryptographic hashes and consensus
mechanisms like Proof of Work.
o Ethereum: Ethereum’s blockchain is used for decentralized applications and
smart contracts, expanding the potential of blockchain beyond just currency.
2. Supply Chain Management:
o Blockchain can be used to track goods as they move through a supply chain,
ensuring transparency and preventing fraud. IBM’s Food Trust Blockchain is
an example of a blockchain solution that enables companies to trace food
products from farm to table.
3. Voting Systems:
o Blockchain-based voting systems aim to eliminate election fraud by providing
transparent and tamper-proof voting records. Voters can cast their votes on the
blockchain, and the results are publicly verifiable and immutable.
4. Healthcare:
o Blockchain can securely store patient records and ensure that healthcare
providers have access to up-to-date and accurate information. Platforms like
Solve.Care are developing blockchain-based solutions for healthcare
administration.
5. Digital Identity:
o Blockchain is also being used to create decentralized digital identities, where
users control their personal information. Sovrin is an example of a
decentralized identity platform based on blockchain.
Conclusion
Theory
A permissionless blockchain is one in which anyone can participate in the network without
requiring permission from a central authority. These blockchains are typically decentralized,
open-source, and trustless, meaning participants don't need to trust any central entity.
• Open Participation: Anyone can join the network as a node without restrictions.
• Decentralization: No central authority controls the network. The control is
distributed across all participants.
• Trustless: Participants don't need to trust any single entity or institution; trust is
distributed across the network.
• Immutability: Once data is added to the blockchain, it cannot be altered without
detection.
Technical Insights
python
Copy code
import hashlib
import time
Explanation:
The mining process iteratively increments the nonce until the resulting
hash begins with a certain number of leading zeros, defined by the
difficulty.
This simulation represents the Proof of Work concept and shows how
mining works in a blockchain network.
2. Proof of Stake (PoS) - Validator Selection:
o In PoS, validators are chosen based on the amount of cryptocurrency they hold
and are willing to stake. This incentivizes honest behavior since validators risk
losing their staked funds if they validate fraudulent transactions.
o Example PoS validator selection mechanism:
python
Copy code
import random
validators = [
{'name': 'Validator1', 'stake': 1000},
{'name': 'Validator2', 'stake': 5000},
{'name': 'Validator3', 'stake': 3000},
]
total_staked = sum(validator['stake'] for validator in
validators)
Explanation:
python
Copy code
def elect_delegate(candidates, votes):
"""Selects a delegate based on votes"""
sorted_candidates = sorted(candidates, key=lambda x:
votes[x], reverse=True)
return sorted_candidates[0]
Explanation:
The delegate with the most votes is selected. This model allows for
faster block production and is more scalable compared to PoW and
PoS.
Code Example
Mining a Block with Proof of Work (Simulating PoW):
python
Copy code
import hashlib
Applications
1. Cryptocurrency:
o Bitcoin: Bitcoin uses Proof of Work as its consensus mechanism, where
miners compete to solve cryptographic puzzles in order to add blocks to the
chain.
o Ethereum 2.0: Ethereum switched from Proof of Work to Proof of Stake to
increase scalability and reduce energy consumption.
2. Decentralized Finance (DeFi):
o Many DeFi platforms use blockchain networks that rely on consensus
mechanisms like PoW or PoS to ensure security and decentralization.
Conclusion
Theory
• Access Control: Only authorized participants can join the network, ensuring that only
trusted entities can validate transactions.
• Centralized Control: While permissioned blockchains maintain some decentralized
aspects, they are often governed by a central authority or consortium.
• Scalability: Due to the limited number of participants, permissioned blockchains can
offer better scalability and faster transaction processing compared to permissionless
blockchains.
• Privacy: Transaction details may be kept private between participants, unlike in
permissionless blockchains where transaction data is public.
Technical Insights
python
Copy code
# A basic PBFT-like consensus process
from collections import Counter
pbft_consensus(block, validators)
Explanation:
class RaftNode:
def __init__(self, name):
self.name = name
self.state = 'Follower'
def become_leader(self):
self.state = 'Leader'
print(f"{self.name} is now the leader.")
Explanation:
o In this example, one node is randomly elected as the leader from a set of
nodes. The leader is responsible for transaction proposals and log replication.
3. Proof of Authority (PoA):
o PoA selects pre-approved validators to create blocks. A common approach in
PoA is to have a list of trusted validators and allow them to validate and
propose blocks.
python
Copy code
class Validator:
def __init__(self, name):
self.name = name
Explanation:
o In this example, the first validator in the list is pre-approved to create blocks.
PoA ensures that only a small set of trusted validators are responsible for
block creation.
Code Example
class RaftNode:
def __init__(self, name):
self.name = name
self.state = 'Follower'
def become_leader(self):
self.state = 'Leader'
print(f"{self.name} is now the leader.")
Explanation:
• This code simulates a leader election in a Raft-based consensus model. One of the
nodes is randomly elected as the leader, and that node will manage block creation and
transaction log replication.
Applications
Conclusion
Permissioned blockchains offer tailored solutions for enterprises that need more control over
their network participants. Consensus mechanisms like PBFT, Raft, and PoA help achieve
high throughput, fault tolerance, and privacy while maintaining efficiency in controlled
environments. By understanding the technical nuances of these mechanisms, developers can
implement robust blockchain systems suitable for a variety of industries
Week 8: Smart Contract Hands-On I – Ethereum Smart Contracts
(Permissionless Model)
Theory
A smart contract is a self-executing contract with the terms of the agreement directly written
into code. They run on a blockchain, ensuring that once deployed, the contract cannot be
altered, providing security and transparency. Smart contracts are designed to automatically
execute transactions when predefined conditions are met.
• Ethereum is the most widely used permissionless blockchain for deploying smart
contracts.
• It is a decentralized platform that enables developers to create decentralized
applications (dApps) by writing smart contracts in Solidity, the most popular
language for Ethereum smart contracts.
• Ethereum's permissionless model allows anyone to participate in the network, which
is vital for decentralized applications (dApps) and decentralized finance (DeFi)
protocols.
Technical Insights
1. Solidity:
o Solidity is the programming language used to write smart contracts for the
Ethereum blockchain. It is a contract-oriented, high-level programming
language designed to target the EVM.
o Solidity Syntax:
State Variables: These variables are used to store data on the
blockchain.
Functions: Functions define the logic of the smart contract.
Modifiers: Modifiers are used to add extra functionality to functions.
solidity
Copy code
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SimpleStorage {
uint256 storedData;
Explanation:
Code Example
Here’s a simple smart contract for managing a list of stored values using Solidity.
solidity
Copy code
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract ValueManager {
uint[] public values;
Explanation:
1. Install Hardhat:
bash
Copy code
npm install --save-dev hardhat
2. Set up Hardhat Project:
bash
Copy code
npx hardhat
js
Copy code
async function main() {
const [deployer] = await ethers.getSigners();
console.log("Deploying contracts with the account:",
deployer.address);
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
To deploy your contract on a test network (e.g., Goerli), configure your Hardhat
project with your wallet's private key and the Infura or Alchemy URL for the test
network. Then, run:
bash
Copy code
npx hardhat run scripts/deploy.js --network goerli
After deployment, you can interact with the smart contract using Web3.js or
Ethers.js.
js
Copy code
const Web3 = require('web3');
const web3 = new
Web3('https://goerli.infura.io/v3/YOUR_INFURA_PROJECT_ID');
const contractAddress = 'YOUR_CONTRACT_ADDRESS';
const abi = [ /* Contract ABI */ ];
interact();
Applications
Conclusion
Ethereum smart contracts are a powerful tool in the world of permissionless blockchains,
enabling decentralized applications across various domains such as finance, governance,
supply chain, and NFTs. By understanding the Solidity programming language and how to
deploy and interact with smart contracts on the Ethereum network, developers can harness the
full potential of blockchain technology to create decentralized solutions. The hands-on
experience of deploying and interacting with these contracts will provide foundational
knowledge for building advanced decentralized applications.
Week 9: Smart Contract Hands-On II – Hyperledger Fabric (Permissioned
Model)
Theory
Technical Insights
1. Chaincode:
o Chaincode in Hyperledger Fabric is the equivalent of a smart contract in
permissioned blockchains. Chaincode is executed by peers in the network, and
it defines the business logic for transactions.
o Chaincode can be written in Go, Java, or JavaScript (Node.js), and it interacts
with the Fabric ledger to record the transaction state.
Structure of Chaincode:
go
Copy code
package main
import (
"fmt"
"github.com/hyperledger/fabric-contract-api-go/contractapi"
)
switch function {
case "set":
return s.set(ctx, args)
case "get":
return s.get(ctx, args)
default:
return fmt.Errorf("Invalid function name")
}
}
func main() {
chaincode, err := contractapi.NewChaincode(&SimpleChaincode{})
if err != nil {
fmt.Printf("Error creating chaincode: %s", err.Error())
return
}
Explanation:
1. Prerequisites:
o Docker: Hyperledger Fabric uses Docker containers to simulate a network of
peers and orderers.
o Go: Used to write the chaincode.
o Node.js: To interact with the Hyperledger Fabric network.
2. Install Fabric Samples:
bash
Copy code
git clone https://github.com/hyperledger/fabric-samples.git
cd fabric-samples
3. Run the Fabric Test Network: Hyperledger Fabric provides a test network to get
started quickly. Navigate to the test network directory:
bash
Copy code
cd fabric-samples/test-network
bash
Copy code
./network.sh up
This will start the network with several organizations and peers running in Docker
containers.
4. Deploy Chaincode:
bash
Copy code
./network.sh deployCC -ccn mychaincode -ccp ../chaincode/simple -ccl
go
Applications
Conclusion
Hyperledger Fabric provides a robust, flexible, and secure platform for developing smart
contracts on permissioned blockchains. The hands-on approach with Chaincode allows
developers to gain practical experience in creating business logic that drives enterprise
applications. With its modular architecture, privacy features, and custom consensus
mechanisms, Hyperledger Fabric is an excellent choice for applications that require private,
permissioned blockchain networks. By mastering Hyperledger Fabric, developers can
contribute to the growing ecosystem of decentralized solutions for industries ranging from
finance and supply chain to healthcare and governance.
Week 10: Decentralized Identity Management
Theory
Decentralized Identity (DID) refers to a new model for managing digital identities where
individuals, organizations, or things control their own identities without relying on a central
authority. In traditional identity management systems, identities are controlled and verified
by central entities (like governments, corporations, or service providers), leading to privacy
issues and single points of failure. Decentralized identity aims to give individuals control
over their data and allow them to share only the necessary information, thus enhancing
privacy and security.
1. Self-sovereign identity (SSI): The concept that individuals or organizations own and
control their identity, without needing to rely on a central authority.
2. Decentralized Identifiers (DIDs): Unique identifiers that are created, owned, and
controlled by the subject of the identifier (e.g., a person or an organization).
3. Verifiable Credentials (VCs): These are tamper-evident claims about an entity that
are digitally signed by an issuer, and the recipient can use them to prove their identity
without revealing additional information.
• Issuer: The entity that creates and signs a verifiable credential (e.g., a government
issuing a driver’s license).
• Holder: The individual or entity that controls the DID and associated credentials
(e.g., a person holding a driver’s license).
• Verifier: The entity that checks the validity of a DID or verifiable credential (e.g., a
bank checking an identity for account opening).
Technical Insights
ruby
Copy code
did:<method>:<identifier>
Where method is the DID method (such as ethereum, sov, ipfs) and
identifier is a unique string.
2. Example:
o did:example:123456789abcdefghi
3. Verifiable Credentials (VCs):
o Verifiable Credentials are digital statements made by an issuer about a subject,
and they are cryptographically signed to ensure their authenticity and integrity.
o The credential format is based on JSON-LD (Linked Data), allowing for easy
integration with web technologies.
o Example: A university might issue a verifiable credential stating that a person
has earned a degree. This credential can be verified by anyone without
revealing unnecessary information.
VC Example:
json
Copy code
{
"@context": ["https://www.w3.org/2018/credentials/v1"],
"type": ["VerifiableCredential", "DegreeCredential"],
"issuer": "did:example:123",
"issuanceDate": "2024-10-10T12:00:00Z",
"credentialSubject": {
"id": "did:example:456",
"degree": {
"type": "BachelorDegree",
"degreeDate": "2024-06-15"
}
}
}
4. Blockchain as the Backbone:
o Blockchain serves as the backbone for decentralized identity systems because
of its immutability and distributed nature. A blockchain-based DID is secured
using the cryptographic features of the blockchain, making it tamper-resistant
and providing proof of ownership and control.
o Various blockchains and distributed ledger technologies (DLTs) are used for
DID management, such as Ethereum, Sovrin, Hyperledger Indy, and
Bitcoin.
5. DID Methods and Interoperability:
o DID methods specify the rules for creating and managing DIDs. Each DID
method is governed by a specific blockchain or distributed ledger, ensuring
interoperability across different networks.
o For example:
Ethereum: did:ethr:0x...
Sovrin: did:sov:...
IPFS: did:ipfs:...
Example: A person could prove they are eligible to vote using a ZKP, without
revealing their full name, address, or any other sensitive information.
Code Example
To create a simple decentralized identity using the Sovrin network (one of the popular DID
implementations), we can use the indy-sdk in Python. This example demonstrates creating a
DID and issuing a credential.
Prerequisites:
• Install indy-sdk:
bash
Copy code
pip install indy-sdk
Python Example:
python
Copy code
import asyncio
from indy import did, anoncreds, wallet, pool
# Create DID
(did_info, verkey) = await did.create_and_store_my_did(wallet_handle,
"{}")
print("Credential Issued")
if __name__ == "__main__":
asyncio.run(main())
Explanation:
1. Create DID: The script first creates a wallet and a decentralized identifier (DID) on
the Sovrin network.
2. Issue Verifiable Credential: It then creates a credential for the DID and stores it in
the wallet.
3. Issuing Credentials: A verifiable credential (in this case, a degree credential) is
created and associated with the DID.
Applications
Conclusion
Theory
Technical Insights
1. Atomic Swaps:
o Atomic Swaps enable the exchange of cryptocurrencies between different
blockchain networks without the need for an intermediary. This allows for
peer-to-peer trading between different blockchains by using smart contracts.
o Example: A user could exchange Bitcoin (BTC) for Ethereum (ETH) using
atomic swaps without needing a centralized exchange. The transaction is
either completed successfully or not at all, ensuring trustless transactions.
o How It Works: Atomic swaps use a combination of hash time-locked
contracts (HTLCs) and public keys to facilitate exchanges. A hash lock
ensures that the transaction is only valid if the second party can provide the
correct key, and a time lock prevents the transaction from being executed after
a certain period.
2. Relay Chains and Sidechains:
o Relay Chains: These are central chains that connect multiple blockchains. A
relay chain allows different blockchains to communicate by acting as a
mediator. For example, the Polkadot network uses a relay chain to facilitate
interoperability between different blockchains in its ecosystem.
o Sidechains: A sidechain is a blockchain that runs parallel to the main
blockchain and can facilitate the movement of assets between the two.
Sidechains can be used to implement features such as scalability, privacy, or
interoperability between chains. For example, the Liquid Network is a
sidechain built on top of Bitcoin that allows for faster and more private
Bitcoin transactions.
3. Cross-Chain Bridges:
o Cross-chain bridges are mechanisms that allow the transfer of tokens and data
between different blockchain networks. These bridges can be centralized or
decentralized.
Centralized Bridges: In this model, a central authority is responsible
for locking tokens on the source chain and issuing equivalent tokens on
the destination chain.
Decentralized Bridges: These use smart contracts and consensus
protocols to ensure that tokens are moved between chains in a trustless
manner. Examples of decentralized bridges include the Thorchain
network, which facilitates cross-chain liquidity without relying on
centralized exchanges.
4. Interledger Protocol (ILP):
oThe Interledger Protocol (ILP) is designed to facilitate payments between
different payment networks, including blockchains. It is an open protocol for
transferring payments across different ledgers and networks.
o ILP allows for atomic swaps across various types of ledgers, such as
blockchains, traditional financial systems, and other distributed ledgers. The
protocol enables interoperability between blockchains by using "connector
accounts," which allow users to move payments across chains using a series of
intermediaries.
5. Blockchain as a Service (BaaS) Interoperability:
o Several companies offer Blockchain-as-a-Service (BaaS) solutions that
enable interoperability between blockchains and other enterprise systems. By
offering APIs, tools, and frameworks to connect different blockchain
networks, BaaS providers facilitate seamless cross-chain communication for
businesses and developers.
o Example: Microsoft Azure Blockchain Service and IBM Blockchain
provide BaaS solutions that allow businesses to connect their private
blockchains with public blockchains or even with other private blockchains.
In this example, we'll simulate the process of transferring a token between two Ethereum-
based blockchains using a cross-chain bridge. The implementation focuses on the smart
contract deployment that locks tokens on the source blockchain and mints them on the
destination blockchain.
solidity
Copy code
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract LockingContract {
address public owner;
mapping(address => uint256) public balances;
constructor() {
owner = msg.sender;
}
solidity
Copy code
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MintingContract {
address public owner;
mapping(address => uint256) public balances;
constructor() {
owner = msg.sender;
}
Applications
Conclusion
Theory
Blockchain technology has evolved from being a simple solution for cryptocurrencies to a
powerful tool with diverse applications in various industries. The decentralized, secure, and
transparent nature of blockchain enables it to address problems in multiple sectors, such as
finance, supply chain, healthcare, real estate, and more.
Technical Insights
In this example, we'll implement a basic blockchain-based voting system using smart
contracts in Solidity. The system allows voters to cast their votes securely and immutably,
and only authorized users can vote.
solidity
Copy code
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Voting {
address public owner;
mapping(address => bool) public voters;
mapping(string => uint256) public votes;
modifier onlyOwner() {
require(msg.sender == owner, "Only the owner can perform this
action");
_;
}
modifier hasNotVoted() {
require(voters[msg.sender] == false, "You have already voted");
_;
}
constructor() {
owner = msg.sender;
}
Explanation:
You can deploy this contract to an Ethereum network (testnet or mainnet) using Remix IDE
or Truffle.
1. Add Voters: The contract owner can add eligible voters using the addVoter function.
2. Casting Votes: Voters can cast their votes using the vote function.
3. View Results: Anyone can view the total votes for a candidate using the getVotes
function.
Applications
Conclusion