Blockchain and Web 3.
0 Security
Prof. Gazy Abbas
Cyber security trainer
Unit - 1
Introduction to Blockchain Technology
Blockchain Overview
Blockchain is a decentralized
and distributed digital ledger
technology that records
transactions across multiple
computers. This ensures that the
recorded transactions cannot be
altered retroactively, providing
transparency and security.
What is Blockchain?
Definition:
A blockchain is a chain of blocks, where each block contains a list of
immutable transactions. These transactions are verified by multiple
nodes in the network, making blockchain a trustworthy system for
recording data.
Each block includes:
Data: Information about transactions.
Hash: A unique identifier for the block.
Previous Block's Hash: Links the current block to the previous one,
creating a chain.
Structure of Blockchain
Structure of Blockchain
Structure of Blockchain
Header: It is used to identify the particular block in the entire
blockchain. It handles all blocks in the blockchain. A block header is
hashed periodically by miners by changing the nonce value as part of
normal mining activity, also Three sets of block metadata are
contained in the block header.
Previous Block Address/ Hash: It is used to connect the i+1th block to
the ith block using the hash. In short, it is a reference to the hash of
the previous (parent) block in the chain.
Structure of Blockchain
Timestamp: It is a system verifying the data into the block and assigns
a time or date of creation for digital documents. The timestamp is a
string of characters that uniquely identifies the document or event
and indicates when it was created.
Nonce: A nonce number which uses only once. It is a central part of
the proof of work in the block. In the Bitcoin blockchain network,
miners compete to find a nonce that, when combined with the block’s
transactions and hashed using the SHA-256 cryptographic algorithm,
produces a hash value that meets the network’s difficulty target.
Structure of Blockchain
Merkel Root:
A Merkle root uses mathematical formulas to check if the data is
not corrupted, hacked, or manipulated. For example, Suppose one
block has 10 transactions, then to identify that block we need 10
transactions to combine and form one Hash Value, so it uses the
concept of the binary tree to create the hash of the block and that
value is called the Merkle Root
Quiz Time 1.1 !!
1. What is a blockchain? 3. What does decentralization in blockchain
A) A centralized database mean?
B) A decentralized ledger A) Data is stored in a single location
C) A type of cryptocurrency B) Control is distributed among many
D) A cloud storage system participants
C) One central authority has control
2. Which of the following is NOT D) None of the above
a key concept of blockchain
technology? 4. What is a "block" in blockchain
A) Decentralization terminology?
B) Immutability A) A fixedsize data storage unit
C) Centralized control B) A set of transactions grouped together
D) Transparency C) A type of consensus algorithm
D) A cryptographic hash
Class work 1.1 !!
1. What is required memory size to save blockchain locally?
2. What is nonce and why it is important?
3. what do you understood by the term Markle root?
4. How many transuctions a single block can store in blockchain?
5. what is the size of each block in blockchain?
6. what is block header and what it stores?
History of Blockchain
The concept of blockchain was introduced by an anonymous
person or group known as Satoshi Nakamoto in 2008 with
the invention of Bitcoin.
1991: Stuart Haber and W. Scott Stornetta introduced a
cryptographically secured chain of blocks.
2008: Satoshi Nakamoto published the Bitcoin
whitepaper, describing the blockchain technology for the
first time.
2009: Bitcoin was launched as the first cryptocurrency
using blockchain.
2015: Ethereum was launched, introducing smart
contracts and expanding blockchain use cases beyond
cryptocurrency.
Key Concepts of Blockchain
Blocks: Containers for transaction data. Each block has a unique hash and a hash of
the previous block.
Nodes: Individual computers that participate in the blockchain network by validating
and relaying transactions.
Miners: Special nodes that validate transactions, create new blocks, and add them to
the blockchain. They are rewarded with cryptocurrency.
Consensus Mechanisms: Protocols that ensure all nodes agree on the blockchain's
current state. Examples include Proof of Work (PoW) and Proof of Stake (PoS).
Smart Contracts: Self-executing contracts with the terms of the agreement directly
written into code, running on the blockchain (e.g., Ethereum).
Decentralization
Decentralization refers to the distribution of authority and control across the
network, rather than being concentrated in a central entity.
Decentralization
No single point of control: All nodes have equal power and can validate
transactions.
Increased security: The distributed nature makes it difficult for any single entity
to manipulate the system.
Enhanced transparency: All transactions are visible to all nodes, ensuring
accountability.
Example: In Bitcoin, anyone can become a miner or node and contribute to the
network's integrity without needing permission from a central authority.
Distributed Ledger Technology (DLT)
Distributed Ledger Technology (DLT) is the underlying technology that supports
blockchain. It refers to the digital system for recording the transaction of assets
where the transactions and their details are recorded in multiple places at the same
time. Unlike traditional databases, DLTs have no central data store.
Key Characteristics of DLT
Multiple Copies: Each participant (or node) in the network holds a copy of the
ledger.
Synchronization: All copies of the ledger are updated simultaneously with every
transaction.
Cryptography: Transactions are secured using cryptographic algorithms to ensure
data integrity and security.
Distributed Ledger Technology (DLT)
Examples:
Hyperledger Fabric, a permissioned DLT framework designed for enterprise use,
allows organizations to build private, scalable blockchain networks.
Bitcoin: The first and most well-known application of blockchain technology.
Bitcoin transactions are recorded on a public, decentralized blockchain.
Ethereum: A blockchain platform that enables developers to build and deploy
smart contracts and decentralized applications (DApps).
Supply Chain Management: Companies like IBM and Walmart use blockchain to
track the provenance of products, ensuring transparency and reducing fraud.
Finance: Ripple uses blockchain technology to enable real-time, cross-border
payments.
Quiz Time 1.2 !!
1. When was blockchain inveted 3. What does decentralization in blockchain
and by whom ? mean?
A) Satoshi nakamoto 2008 A) Data is stored in a single location
B) Stuart Haber& W. Scott B) Control is distributed among many
Stornetta in 1991 participants
C) denis ritche 1994 C) One central authority has control
D) Suntech 1996 D) None of the above
2. when and who invented 4. what is Distributed ledger?
bitcoin? A) A physical ledger with one owner
A) Satoshi nakamoto 2008 B) A digital ledger shared among all nodes
B) jeff bezos 1990 C) A ledger stored in single place
C) bilgates 1995 D) none
D) Stuart Haber& W. Scott
Stornetta in 1991
Section - 2
Cryptographic Foundations
Cryptographic Foundations
Cryptographic foundations refer to the principles and techniques used to secure
information and communications. Its core components include:
1. Encryption: Transforming readable
data (plaintext) into an unreadable
format (ciphertext) to protect it
from unauthorized access.
Cryptographic Foundations Contd..
• Symmetric encryption: The same
key is used for both encryption
and decryption. Example: AES
(Advanced Encryption Standard).
• Asymmetric encryption: Uses a
pair of keys, one for encryption
(public key) and one for
decryption (private key).
Example: RSA
(Rivest-Shamir-Adleman).
Cryptographic Foundations Contd..
2. Authentication: Verifying the identity of a user or device. Example: Using
digital certificates issued by a Certificate Authority (CA).
3. Non-repudiation: Ensuring that someone cannot deny the validity of their
digital signature on a document. Digital signatures provide this feature.
4. Integrity: Ensuring that data has not been altered. Achieved through
mechanisms like hash functions.
Hash Functions
e
A hash function is a mathematical
algorithm that converts an input (or
"message") into a fixed-size string of
bytes, typically a digest that appears
random. Hash functions are
fundamental to various
cryptographic operations because
they ensure data integrity.
A hash function is a mathematical function that converts any digital data into an
output string with a fixed number of characters. Hashing is the one-way act of
converting the data (called a message) into the output (called the hash).
Properties of hash functions:
Deterministic: The same input will always produce the same output.
Fast to compute: The hash value can be quickly calculated for any given input.
Preimage resistant: It should be difficult to reverse the hash function to find the
original input.
Small changes in input drastically change output: Even a tiny change in the input
should produce a significantly different hash.
Collision resistant: It should be very difficult to find two different inputs that produce
the same hash output.
Common Hashing Algorithms
Hashing vs Encryption
Encryption is the practice of taking data and creating a scrambled message in a
way that only someone with a corresponding key, called a cipher, can unscramble
and decode it. Encryption is a two-way function, designed to be reversible by
anyone who holds a cipher.
Hashing is using a formula that converts data of any size to a fixed length, that can
not be reversed that is why hashing is a one-way function.
Encryption is meant to protect data in transit, hashing is meant to verify that a file
or piece of data hasn’t been altered—that it is authentic. Hashing is more like a
security tamper seal that indicates if the contents of the data have been altered.
Digital Signatures
A digital signature is a cryptographic technique
used to validate the authenticity and integrity of
a message, software, or digital document. It
uses asymmetric cryptography and involves two
processes:
Signing: The sender uses their private key to create a signature on the message.
Verification: The recipient uses the sender’s public key to verify the signature.
Digital Signatures
Difference between Hash and Digital Signature
Hash Function:
Purpose: To ensure data integrity.
Output: Fixed-size string (hash value).
Not linked to a specific user.
Digital Signature:
Purpose: To ensure data integrity, authenticity, and
non-repudiation.
Involves: Encrypting a hash with a private key.
Linked to a specific user via their private key.
Consensus Algorithms
Consensus algorithms are a set of
rules or protocols that enable nodes
in a blockchain network to agree on
a shared state of the network. They
are used to ensure that all nodes in
the network come to a consensus on
the validity of transactions and the
order in which they are added to the
blockchain.
A consensus algorithm is responsible for maintaining the integrity of the
blockchain by ensuring that no single node or group of nodes can manipulate
the network.
Proof of Work (PoW)
Proof of Work (PoW)
Proof of Work is a consensus algorithm used in many blockchain networks to
validate transactions and add new blocks to the chain. PoW was first introduced by
Bitcoin’s creator, Satoshi Nakamoto, as a way to secure the network and prevent
double-spending.
The PoW algorithm requires miners to solve complex mathematical problems,
known as hashes, in order to validate transactions and add new blocks to the chain.
The hash function used in PoW algorithms is designed to be computationally
difficult to solve, which means that it requires a significant amount of
computational power to solve the problem and add a block to the chain. Miners
compete with each other to solve the problem, and the first one to solve it is
rewarded with newly minted cryptocurrency.
Proof of Stake (PoS)
Proof of Stake (PoS)
Proof of Stake is a consensus algorithm used in blockchain networks to validate
transactions and add new blocks to the chain. Unlike Proof of Work (PoW),
which requires miners to solve complex mathematical problems, PoS relies on
validators who hold a certain amount of cryptocurrency to validate transactions
and add new blocks to the chain.
In a PoS network, validators are chosen to add new blocks to the chain based on
the amount of cryptocurrency they hold, which is known as their stake. The
larger the stake, the greater the chance of being selected to add a block to the
chain. Validators are incentivized to act honestly because they risk losing their
stake if they validate fraudulent transactions or try to attack the network.
POV vs POS
Quiz Time 1.3 !!
1.What is the primary purpose of a 3. What is Proof of Work (PoW)?
hash function in blockchain? A) An algorithm that validates transactions based
A) To encrypt data on staking coins
B) To create a digital signature B) A consensus mechanism that requires solving
C) To map data of arbitrary size to a a cryptographic puzzle
fixed size C) A method of creating digital signatures
D) To generate public and private keys D) A type of public key infrastructure
2. Which of the following is true about 4. How does Proof of Stake (PoS) differ from
digital signatures? Proof of Work (PoW)?
A) They ensure the authenticity and A) PoS requires energy intensive calculations
integrity of a message B) PoS selects validators based on the number of
B) They encrypt the message content coins they hold
C) They are used only in Bitcoin C) PoS is less efficient than PoW
transactions D) PoS does not involve any consensus
D) They can be forged easily mechanism
Class work 1.2 !!
1. Differentiate Cryptography and Hashing?
2. Give three examples of cryptography algorithms and hashing algorithms?
3. Differentiate Hashing and Digital signature?
4. Breifly explain encryption and its types give one example for each type.
5. Differentiate POW & POS.
Section - 3
Smart Contract
Smart Contract
A Smart Contract (or cryptocontract) is
a computer program that directly and
automatically controls the transfer of
digital assets between the parties under
certain conditions. A smart contract
works in the same way as a traditional
contract while also automatically
enforcing the contract. Smart contracts
are programs that execute exactly as
they are set up(coded, programmed) by
their creators. Just like a traditional
contract is enforceable by law, smart
contracts are enforceable by code.
Smart Contract
• Smart contracts are self-executing contracts with the terms of the agreement
directly written into code. They run on blockchain networks, which are
decentralized and immutable, meaning once the contract is deployed, it cannot
be altered. Smart contracts automatically enforce and execute the terms of the
agreement when predefined conditions are met..
Key Characteristics:
• Autonomy: They execute automatically without the need for intermediaries.
• Trust: Transactions are transparent and immutable.
• Security: Encryption and decentralization provide robust security.
• Accuracy: Execution is exact, reducing human errors.
Working of Smart Contract
Smart Contract Use Cases
Finance and Banking
Escrow Services: Automated escrow accounts can release funds only when all
conditions are met.
Insurance: Smart contracts can automate insurance claims, ensuring timely and
accurate payouts.
Example: AXA's flight delay insurance uses Ethereum smart contracts to
automatically compensate policyholders for flight delays.
Real Estate:
Property Transfers: Automating the process of transferring ownership of property.
Rental Agreements: Handling rent payments and lease conditions.
Example: Propy uses smart contracts to facilitate real estate transactions, ensuring
secure and transparent property transfers.
Healthcare:
Patient Records: Managing patient
consent and sharing health data
securely.
Drug Supply Chain: Ensuring the
authenticity of drugs by tracking their
journey from manufacturer to
consumer.
Example: Medicalchain uses smart
contracts to manage patient records
and data sharing among healthcare
providers.
NFTs
$17 billion worth of Non-fungible tokens (NFTs) were traded in 2021, making it
one of the most impactful smart contract use cases. Even though the market has
cooled down in the 2nd quarter of 2022, NFTs have real-life use cases which can
lead to long-term use of NFTs.
Smart contracts have enabled the
creation of non-fungible tokens
(NFTs) by allocating ownership
and managing the transferability
of NFTs.
Logistics
Supply Chain Management:
Provenance Tracking: Tracking the origin
and journey of goods.
Automated Payments: Paying suppliers
when goods are delivered and verified.
Example: IBM and Maersk's TradeLens
uses smart contracts to manage and track
shipping information in real-time.
Programming Languages for Smart Contracts
Programming Languages for Smart Contracts
Solidity: Solidity is an object-oriented and
statically-typed programming language
that was designed to allow developers to
create smart contracts.
Solidity is designed based on existing
programming languages like C++,
Python, and JavaScript, so it uses similar
language structures found in these
languages, most likely to make it easy
for developer adoption.
Solidity:
Here is an example of a smart contract with Solidity:
pragma solidity ^0.8.7;
contract MyContract {
constructor() public{
value = "My value";
}
string public value;
function get() public view returns (string memory){
return value;
}
function set(string memory _value) public{
value = _value;
}
}
Solidity:
pragma solidity ^0.8.0;
contract CarEscrow {
// State variables to store car details and sale status
address payable public seller; // Seller's address (to receive funds)
address payable public buyer; // Buyer's address
uint public price; // Agreed-upon sale price
// Flag to indicate if the buyer has confirmed the car's condition
bool public carApproved;
// Constructor sets seller, buyer, and price upon deployment
constructor(address payable _seller, address payable _buyer, uint _price)
public {
seller = _seller;
buyer = _buyer;
price = _price;
}
Solidity:
// Function for buyer to confirm car condition and finalize the sale
function confirmCar() public payable {
require(msg.value == price, "Insufficient funds sent.");
require(!carApproved, "Car already approved.");
carApproved = true;
}
// Function for seller to withdraw funds if buyer doesn't approve
function withdraw() public {
require(msg.sender == seller, "Only seller can withdraw.");
require(!carApproved, "Car already approved.");
seller.transfer(address(this).balance); // Transfer all funds in the
contract to seller
}
// Function to check the current balance of the contract
function getBalance() public view returns (uint) {
return address(this).balance;
}
}
Vyper
Vyper is a Python-based programming
language that was created by Vitalik Buterin,
the co-founder of Ethereum. It is an
experimental language that was developed to
be an alternative to Solidity. Vyper is designed
to be more secure and readable than Solidity,
by reducing the risks of the contract getting
hacked.
Vyper
Here is an example of a smart contract with Vyper:
storedData: public(uint256)
@external
def __init__(_initialValue: uint256):
self.storedData = _initialValue
@external
def set(_value: uint256):
self.storedData = _value
@external
@view
def get() -> uint256:
return self.storedData
Rust, Move & Cario
Rust: A high-performance, memory-safe language used for developing secure
and efficient smart contracts, particularly on blockchains like Solana.
Move: A safe and flexible programming language designed for the Libra (now
Diem) blockchain to enable secure, verifiable, and deterministic transaction
execution.
Cairo: A language designed for writing provable and scalable smart contracts,
particularly utilized by the StarkNet platform to leverage zero-knowledge proofs
for scalability.
Quiz Time 1.4 !!
1. What is a smart contract? 3. In Which programming language is
A) A traditional legal contract stored on commonly used for writing smart contracts on
a computer Ethereum?
B) A selfexecuting contract with the A) Python
terms directly written into code B) Java
C) A type of cryptocurrency C) Solidity
D) A software program that manages D) C++
databases
4.Which is a use case of smart contracts?
2. Which blockchain platform A) Automated payments
introduced the concept of smart B) Voting systems
contracts? C) Supply chain management
A) Bitcoin D) All of the above
B) Ethereum
C) Litecoin
D) Ripple
Class work 1.3 !!
1. Why smart contracts are important ?
2. How and why smart contracts are used for NFT?
3. Give an example of smart contract with code.
4. Name 5 programming languages to write smart contracts
END
www.paruluniversity.ac.in