Blockchain FINAL
Blockchain FINAL
Key Concepts:
1. Prepare Phase:
fe a
Hash01 Hasho1
ie — ie!
@ Merkle Tree
e A Merkle Tree is a binary tree structure used in blockchain to efficiently and securely verify data
integrity.
e Parent nodes are created by hashing the concatenation of their child nodes, continuing up to
the root.
® The Merkle Root is the single hash at the top of the tree, representing the integrity of the entire
dataset.
* Any change in a transaction modifies its hash and propagates up, altering the Merkle Root.
Visual Example:
‘) Copy code
CatDogBirdFish
/ \
CatDog BirdFish
/ \ / \
Cat Dog Bird Fish
Key Idea:
In Blockchain:
2. Fault Tolerance: By replicating the state machine across multiple nodes, SMR ensures that even
if some nodes fail or act maliciously, the system continues to operate correctly (as long as a
majority of nodes are honest).
3. Data Consistency: In distributed blockchain environments, SMR ensures that all nodes maintain
an identical copy of the blockchain ledger, preventing forks and ensuring data consistency.
4. Security and Integrity: Replicating the state machine across different nodes adds resilience to
attacks, as consensus is required across many nodes, making it harder to corrupt the system or
alter data. Vv
3. Example of SMR in
Blockchain
1. Initial state:
© Alice: 10 coins
© Bob: 5 coins
2. Transactions:
« Working Mechanism:
® Once a block is successfully mined, the reward is distributed among the pool members
based on their contributed work.
Methods:
e Proportional Mining:
« Rewards are distributed based on the number of shares a miner contributes until the
block is found.
e Pay-Per-Share (PPS):
e Miners get a fixed reward for each valid share submitted, regardless of whether a block
is found.
e Pay-Per-Last-N-Shares (PPLNS):
e Rewards are distributed based on a miner's contribution to the last "N" shares before
the block is solved.
* Solo Mining:
e Asingle miner works independently without pooling resources. Higher risk but larger
reward for success.
* Merged Mining:
* Hybrid Pools:
Before Ethereum, blockchain apps could only be created to do a small number of tasks.
The only purpose for which crypto currencies were intended was to function as peer-to-peer digital currencies.
© This presented a challenge for programmers since they either had to increase the scope of operations that these
crypto currencies could do, which would be difficult and time-consuming, or they could create a new dass of
blockchain-based platform and programmes.
The EVM is a cutting-edge strategy created by the Ethereum creator.
The Ethereum virtual machine is the engine in which transaction code gets executed.
The Ethereum Virtua! Machine (EVM) is a global computer that anybody may utilize for a nominal fee paid in
Cryptocurrency
a Tock inasiedyt
peti al®
rig. 4.5.1
smart contracts are represented at a basic level by Ethereum Bytecode which is read by the EVM.
made up of |
is an as se mbly language in,
everal cocodes. On the Ethereum blockcha
the bytecode for Et he re um
ation.
each opcode carries out a specific oper
it is Turing-complete software that runs on the Ethereum network anc enables anybody, given enough
of the programming language it st eaiait ta: ‘iii
and time, to run any program they choose, independent
apps.
The EVM streamlines and improves the process of developing biockchain-based
to create
The EVM makes it possible to construct hundreds of distinct apps on a single plat‘orm rather than hanng
aunique blockchain for each application.
tel y iso lat ed and has no acc ess to file sys tem s or pro ces ses . So, eac h nod e in the system runs the EVM.
itis comple
That way it can maintain a consensus across the network
and faun ch the geth , parit y, or any other client , the EVM 1s launched and begins synchronimng.
When we install
verifying, and executing transactions.
Types of Nodes Used in Ethereum
e Full Node
* Stores the entire Ethereum blockchain and verifies all transactions and blocks
independently.
« Pruned Node
e Stores only the mast recent portion of the blockchain by discarding older data.
e Keeps the chain's current state and enough data for verification of new blocks.
e Reduces storage requirements while maintaining functionality for most use cases.
* Light Node
e Lightweight and suitable for devices with limited resources, like mobile phones.
e Archive Node
e Useful for developers, explorers, and anyone needing access to historical data.
e Used in Ethereum 1.0 to solve cryptographic puzzles and add blacks to the blackchain.
e Bootstrap Node
e Provides initial peer information to help new nodes connect with the network.
a
Sate
Nacthene
ro
Transactions
® Now let us discuss components of Ethereum
consensus on the longest chain. Proof of work and proof Of stake are the two consensus methods ' f
Public Blockchain
st
gees pata structures : The state of Ethereum is kept locally on each node in the form of a database, often Google's
6) DB, which keeps the system information and transactions in a senalized hashed data structure known as
Leve
F Merkle Patricia Tree
49 _
~7
Typesof test-networks used in Ethereum
A version of a project is deployed to an Ethereum Test Network ("testnet"), which replicates Ethereum, before it is
launched on the Ethereum blockchain (or before modifications are made to the blockchain itself).
This allows developers and the community to test the project before actual assets are engaged.
On a testnet, ether and tokens are simple to get and have no real-world value.
the are presently three testnets in use, and each perf
orms identically to the main blockchain where you'r
e real
ther and tokens
reside.
Th
- ;
Ropsten test network is an Ethereum Proof-of-Work testnet. One can mine on the Ropsten network to obtain
H.
Ww Blockchain (MU)
4-16 Public Blockchain
Kovan
The Parity team created the Kovan test network as a Proof-of-Authority testnet for Ethereum.
Rinkeby
The Rinkeby test network is an Ethereum Proof-of-Authority testnet that was founded by the Geth team 4,
Rinkeby, one may obtain ETH by requesting it through a faucet.
Visibility Specifiers of Functions in Solidity
1. Public
e Functions with public visibility can be called internally, externally, and via derived
contracts.
® Example:
solidity CY Copy code
contract PublicExample {
uint public data = 42;
// Public function
function getData() public view returns (uint) {
return data;
?. Private
e Functions with private visibility can only be accessed within the contract where they are
defined.
® Example:
contract PrivateExample {
uint private data = 42;
// Private function
function _getData() private view returns (uint) {
return data;
3. Internal
® Functions with internal visibility can be called within the contract where they are defined
and by derived contracts.
contract InternalExample {
function internalFunction() internal pure returns (string memory) {
return “Internal Function";
* Functions with external visibility can only be called from outside the contract.
contract ExternalExample {
function externalFunction() external pure returns (string memory) {
return "External Function";
Private Yes No No
Sender Address: The public address of the sender initiating the transaction.
Fee: The transaction fee paid to miners/validators for processing the transaction.
e A transaction is created by the sender, specifying recipient details, amount, and any
additional data.
* Broadcasting
* Validation
® Nodes validate the transaction by checking the signature, sender's balance, and other
parameters.
* Propagation
® Once validated, the transaction is propagated to other nodes in the network to ensure
visibility.
Inclusion in a Block
* Miners or validators collect valid transactions and include them in a new block.
Consensus
¢ The network reaches consensus to approve the new block containing the transaction.
Confirmation
e The transaction receives confirmations as subsequent blocks are added, increasing its
immutability and trustworthiness.
Completion
e The recipient's address is updated with the transferred value or data, and the transaction is
deemed complete.
Fixed Arrays in Solidity
« A fixed array has a predetermined size that cannot be changed.
« Example:
solidity O) Copy code
contract FixedArrayExample {
e —lts length is not fixed and can be madified using .push() or .pop() .
« Example:
solidi ty O) Copy py cade
contract DynamicArrayExample {
uint[] public dynamicArray; // Array with no predefined size
t
function getLength() public view returns (uint) {
return dynamicArray.length; // Get current length of the array
©) Proof of Work (PoW) solves the
double-spending problem by ensuring
the security and integrity of a
blockchain network through the
following mechanisms:
Key Points:
contract Example {
// Fallback function that is
called when no function matches
or when Ether is sent
fallback() external payable {
// Code to handle the
call or receive Ether
}
ee S@ ee &@ S&S & SB SS SB BE BS SR ee ee ee ee ee eB eB eB ee eB ee eee ew ew ee ee Se ES ==eee ee a
“eet eet & & &
Gea &
® By definition, blockchain is a decentralized computation and information sharing platform that enables multiple
authoritative domains, who do not trust each other, to cooperate, coordinate, and collaborate in a rational decision
Making Process
® The keyword that we have in the abovementioned
definition is decentralized, which is an important aspect
of blockchain.
* Computation and information sharing platform is the
next keyword that will help in specifying blockchain
broadly to be a decentralized database, which helps in
cooperation between multiple authoritative domains.
* This technology is useful when multiple parties or
individuals want to cooperate with each other and they
want to come to a common platform so that they can
share information amongst themselves. (iat)Fig. 1.1.1: Structure of a decentralized network
Problems Associated with Centralized Systems in Blockchain
Single Point of Failure: Centralized systems are vulnerable to downtime, outages, or attacks on
the central authority.
Lack of Transparency: Data control lies with a central entity, reducing trust and visibility for
users.
Data Breaches: Centralized storage of sensitive information makes the system an attractive
target for hackers.
Limited Access: Decisions about access and control are centralized, potentially excluding certain
participants.
Censorship Risk: A central authority can modify, censor, or remove transactions at its discretion.
High Dependency: Operations depend heavily on the central authority, which can lead to
inefficiencies or biased decision-making.
Scalability Bottlenecks: Central servers may struggle to handle large-scale operations, leading
to slow performance.
Data Storage Central server stores Data is stored across Data is spread across multiple
all data. multiple nodes. locations.
Fault Low; single point of High; no single point of High; redundancy ensures
Tolerance failure exists. failure. reliability.
Transparency Limited; controlled by High; all participants have Depends on the control
central entity. access. mechanism.
Performance Can be efficient but May be slower due to High efficiency with redundancy.
bottlenecks exist. consensus protocols.
Security Vulnerable to More secure but still risks Secure against single-point
centralized attacks. like 51% attacks, failures.
Transparency: Transactions are recorded on a public ledger, ensuring visibility and trust.
« Disadvantages:
Initial Costs: High expenses for developing and integrating blockchain solutions.
Types of Cryptocurrencies in Blockchain
¢ Bitcoin (BTC)
« Altcoins
* Stablecoins
e Pegged to stable assets like fiat currencies or commodities (e.g., USDT, USDC).
« Utility Tokens
Privacy Coins
Meme Coins
* Created as a joke or meme but gained popularity (e.g., Dogecain, Shiba Inu).
Governance Tokens
Countermeasures: Proof of Work (PoW), Proof of Stake (PoS), and identity verification.
Targets blockchain nodes or services with overwhelming traffic to render them unusable.
Distributed consensus is the process by which multiple nodes (or computers) in a distributed system
agree on a single data value or a consistent state, even in the presence of failures or network delays.
It ensures that all participants in a distributed system maintain the same view of shared data, despite
the decentralized and often unreliable environment. Algorithms like Paxos, Raft, and Byzantine Fault
Tolerance (BFT) are commonly used to achieve consensus.
«= Properties of a distributed consensus protocol |
Termination : Every correct individual decides some value at the end of the consensus protocol. In other words,
whosoever is the non-faulty node in the network, the non-faulty node must terminate the protocol and decide on one
value, which is the correct value.
© Validity : If all the individuals in the node proposes the same value, then all correct individuals decide on that value.
e Integrity : Every correct individual decides at most one value, and the decided value must be proposed by some
individual. This property ensures that the consensus value should not deviate from the values that are proposed by
individual nodes in the network.
e Agreement : Every correct individual must agree on the same value. All the individual nodes in the network must agree
same value. Whenever all nodes agree on the same value after termination, we declare that the system has
on the
reached consensus.
Quorum in Blockchain
® Quorum is a permissioned blockchain platform based on Ethereum, designed for enterprise use
cases.
e Uses a consensus mechanism like Raft or Istanbul BFT to enhance speed and scalability
compared to public Ethereum.
e Features private contracts and networks, enabling secure collaboration among businesses.
* Supports tokenization, data sharing, and decentralized applications (dApps) tailored for
enterprise needs.
e Integrates with existing systems seamlessly due to compatibility with Ethereum tools and smart
contracts.
« Commonly used in industries such as finance, supply chain, and healthcare for secure and
efficient processes.
Quorum Architecture
* Advantages:
« Enterprise Focus: Designed specifically for business use cases, with features like
permissioned access.
s Ethereum Compatibility: Supports Ethereum tools and smart contracts for easy integration.
* Disadvantages:
* Governance Challenges: Requires agreement among participants, which can slow decision-
making.
* Dependency on Trusted Nodes: Trust is required in specific validators for network integnty.
* Applications:
* Supply Chain Management: Tracks goods transparently while maintaining privacy for
sensitive data,
* Ecosystem players : A blockchain is only as strong as its community. If the players in the community are honest and
engaged, then only it leads to a robust and sustainable ecosystem. Various players that constitute a blockchain
ecosystem
are as follows :
° Developers : Blockchain developers develop, deploy, and maintain blockchain protocols, applications, and
interfaces. Different functionality levels (i.e., consensus design) are designed by them. They also work on
decentralized applications and smart contracts that run on blockchain. They not only monitor but also maintain
blockchain as per needs and requirements.
© Miners : They validate new transactions and record them on blockchain. A miner who can mine a specific block
can be fixed based on a particular consensus mechanism. Sometimes, miners compete for privileges. They put
forth their effort and computing power for solving a cryptographic problem and are awarded with block rewards
or transaction fees.
oO Users : He/she uses the blockchain/cryptocurrency for the purpose for which it is designed. Note that a user can.
also be a miner, validator, or investor. Users are epitomized as nodes that possess a copy of the ledger for
initiating, creating, or creating transactions.
Merchants : They are business entities that accept cryptocurrencies as a form of payment for their goods or
Services.
o Traders : They are sometimes also called as brokers. They buy or sell cryptocurrencies based on price
movements. They use a specific exchange method that is designed to compare and identify fixed cheapest
exchange rates between tokens.
explain some use cases of smart contract in industry in blockchain,
make it in short
< 2/72
L Finance (DeFi): Automate loans, insurance, and payments without intermediaries, reducing costs
and delays.
Supply Chain: Track product journeys from origin to consumer, ensuring transparency and
reducing fraud.
Real Estate: Simplify property sales by automating contracts, reducing paperwork, and speeding
up transactions.
Healthcare: Securely share patient data across providers while ensuring privacy and control.
. Legal: Automate contract execution (e.g., wills, agreements) when pre-set conditions are met,
reducing manual oversight.
Gaming: Enable decentralized game ecor ,|, es, in-game purchases, and rewards distribution
automatically.
Role of Smart Contracts in Decentralized Finance (DeFi)
Smart contracts are self-executing contracts with the terms directly written into code, enabling
trustless and automated financial transactions in DeFi.
They eliminate intermediaries like banks or brokers, allowing for peer-to-peer transactions,
lending, borrowing, and trading.
Smart contracts enable features such as automated market makers (AMMs), decentralized
exchanges (DEXs), and yield farming, ensuring transparency and efficiency.
They handle collateral management, ensuring that assets are locked and released according to
predefined conditions, such as in lending protocols.
Smart contracts facilitate staking and yield generation by automating the process of depositing
and earning rewards.
They also ensure security by enforcing the agreed-upon terms automatically, reducing the risk
of human error or fraud.
Smart contracts in DeFi are typically open-source, allowing anyone to audit, participate, or
create new financial products. sl
Ya. 3.1.2 Smart Contract
comp uter ized pro toc ol use d for digi tally facilitating, verifying. OF
‘Definition : A smart contract is an automate d
4 dating the
or perf orma nce of a legal cont ract by avoiding intermediates and directly vali
enforcing the negotiation
contract over a decentralized platform.
«= Smart contracts in other industries
There are many other use cases of smart contracts in other industries, as given below:
5 Legal : Smart contracts stored in a blockchain track contract parties, terms, transfer of ownership, and delivery of
g00ds or services in the absence of the disadvantageous need for a legal intervention.
Government : Smart contracts on a blockchain provides promise as a system to maintain personal identifying
information, criminal histories and “e-citizenship” authorized by biometrics.
Food : The blockchain concept may be utilized to trace a product's origin, batch, processing, expiration, storage
conditions, and shipment in the food supply chain business.
Insurance : When autonomous vehicles such as driverless automobiles and smart devices communicate status
updates with insurance carriers via the blockchain, overall costs are reduced because there is no need for auditing
and verifying data.
Education : Universities and educational institutions can use blockchain to record grade or credentials data related
to tests, degrees, and transcripts and to provide such data to the government or firms looking to hire students.
Centralized blockchain systems can face several problems, including:
Cyber attacks
Centralized networks are more vulnerable to cyber attacks and data breaches because
all data is stored in a single location, making it easier for hackers to target and steal
sensitive information.
Lack of transparency
Because centralized ledgers are maintained by a single institution, it might be difficult
for outsiders to verify the data’s correctness and completeness.
Trust
In a centralized blockchain, everything you do is monitored by someone else, which
can be a problem for trust.
Regulatory compliance
Another significant concern related to centralized databases is ensuring compliance
with data protection regulations. (4)
Basis Hot Wallet Cold Wallet
They are always connected to the There is a switch between the online
Connectivity | internet and all the transfer take place and offline modes with the transfer
via the online mode there. of coins taking place.
¢ ity They are less safer as the crypto is They are safer as the cryptos are
ecuri
stored on the exchange itself. stored in the offline mode.
Additional hardware is to be
. Hot wallets are cheaper as they store ; ; .
Price ; purchased for storing coins making it
crypto on the exchange itself. :
expensive.
If the exchange is closed then you will | Even if the exchange closes, the coins
Asset Loss ; ;
not be able to access your coins. are safe in the cold wallets.
1. Hyperledger Caliper
2. Hyperledger Cello
How it Works:
a. Decentralized Ledger: Shared, immutable ledger records all transactions across the supply chain
in real-time, ensuring data integrity.
e« Every movement or event is logged on the blockchain, tracking goods from production to
delivery.
Smart Contracts:
« Automated actions occur when pre-set conditions are met (e.g., automatic payments,
goods release).
« All participants have real-time access to the same data, increasing trust and reducing fraud.
Gas refers to the unit that measures the computational effort required to perform
operations on the Ethereum network.
Ensures the network processes transactions efficiently and prevents abuse (e.g., spam or
infinite loops).
Measured in “Gwei" (1 Gwei = 10° Wei; Wei is the smallest denomination of Ether).
The cost per unit of gas (gas price) is determined by the user and fluctuates based on
network demand.
Gas limit is the maximum amount of gas a user is willing to pay for a transaction. If
exceeded, the transaction fails.
Users can set higher gas prices for faster transaction processing or lower prices if time is
less critical.
e Ethers (ETH)
Pays for gas fees, incentivizing miners or validators to process transactions and execute
smart contracts.
No fixed supply; ETH is issued to validators for securing the network (proof-of-stake post-
Ethereum 2.0).
Use cases include transaction fees, executing smart contracts, and powering decentralized
applications (DApps) like DeFi and NFTs.
© Orphaned Block in Blockchain
e An orphaned block is a valid block that is not included in the main blockchain because a
competing chain with greater proof-of-work or a better consensus was chosen by the network.
* Occurs during temporary network forks when two miners solve a block almost simultaneously.
* Only one block becomes part of the main chain, while the other is discarded, even though it is
valid.
e Miners who produced the orphaned block do not receive the block reward, leading to wasted
computational effort.
® Helps maintain the integrity and consistency of the blockchain by ensuring only one chain is
recognized as valid.
* Common in proof-of-work blockchains like Bitcoin and Ethereum before the shift to proof-of-
stake.
® Orphaned blocks do not contribute to transaction validation but might still contain transactions,
which are usually reprocessed in the valid chain.
e ltuses a linearization process (C3 Linearization) to ensure a consistent and predictable order of
inheritance,
e Conflicts in functions or state variables from different base contracts are resolved using the
order specified in the inheritance list.
e The override keyword is mandatory when a function exists in multiple parent contracts,
ensuring clarity and avoiding ambiguity.
f= Mining difficulty
CS 78S e626 6282886886 eee eee ee ee ss. = = 7S 22f* 85-58
| GQ. How is the difficulty level of a block computed 7’
4
It is defined as a measure of how difficult it is to find a hash below a given
target. A bitcoin network has a global block
difficulty. The difficulty level changes for every 2016 blocks.
The desired rate is that one block should be generated for every 10 minutes
. Thus, it will take two weeks to generate
2016 blocks. The difficulty level is readjusted every two weeks. Note that the change
in difficulty is in proportion to the
amount of time over or under two weeks the previous 2016 blocks took to find.
For every two weeks, the difficulty level is computed as follows :
How It Solve puzzles with Validators chosen by Wait for a random Burn coins to eam
Works computation power their stake time (hardware- mining rights
based)
Rewards Block rewards and Block rewards and Block rewards and Rewards based on
Security Strong, but energy- Strong, depends on Secure if hardware is Strong. as burning
intensive stake distribution reliable is costly
* Raft is a consensus algorithm designed for distributed systems to achieve consistency, often
adapted for private or permissioned blackchains.
* [tuses a leader-based approach where one node is elected as the leader, and others act as
followers.
* The leader handlesall updates to the blackchain and replicates them to follower nodes,
ensuring data consistency.
1. Leader Election: Nodes vote to elect a leader when no leader exists or the current leader
fails.
2. Log Replication: The leader accepts transactions, appends them to its log, and replicates
the entries to follower nodes.
s Raft ensures fault tolerance by maintaining consistency even if some nodes fail, as long as a
majonty are operational.
* Unlike Proof-of-Work or Proof-of-Stake, Raft does not require computational power or staking,
making it energy-efficient and fast.
* Commonly used in permissioned blockchains where participants are known and trusted, such as
Hyperledger Fabric.
* Raft prioritizes simplicity and ease of implementation, making it suitable for private blockchain
networks with limited participants.
* However, it is less decentralized than algorithms like PoW or PoS, as it relies on a single leader at
any given time.
Ripple
Ripple is both a payment protocol and a digital currency, designed to enable fast, low-cost, and
cross-border transactions.
The native digital currency of the Ripple network is XRP, used to facilitate transactions and
maintain liquidity.
Unlike Bitcoin, Ripple doesn't use traditional mining or Proof-of-Work but relies on a consensus
algorithm for validating transactions.
It aims to solve issues in the global financial system, such as high transaction fees and long
processing times for cross-border payments.
Ripple is widely used by banks and payment providers, as it offers a secure, scalable, and
efficient alternative to traditional SWIFT networks.
Ripple has faced some legal challenges, esnecially from the U.S. SEC, regarding whether XRP
should be classified as a security. NT
18.5, Comparison between Public, Private and Consortium Blockchain
Accessibility Open to anyone Central Incharge or Single individual | More than one central Incharge.
Participants Everyone is | Known and trusted participants Known and trusted participants
anonymous
Consumption
1-18
apie a saat
align » Blockchain ere eee pete
ssoall
res | Public 8 - Fl | ‘i
ia
100
rrr bi
Limited Better
High Low
Consensus PoW, PoS, etc. Voting or different PoW/PoS | Voting or different PoW/P
Mechanism consensus Algorithms consensus Algorithms
UTXO Model of Bitcoin
UTXO (Unspent Transaction Output) refers to the amount of Bitcoin that remains unspent after a
transaction is executed, representing the output available for future transactions.
Each Bitcoin transaction consumes previous UTXOs as inputs and creates new UTXOs as outputs.
UTXQs are indivisible units of Bitcoin until spent, ensuring accurate tracking of ownership.
A wallet queries the blockchain to calculate the total balance by summing all UTXOs controlled
by the user's private keys.
When spending, a transaction specifies input UTXOs and generates new output UTXQs, ensuring
the total input equals the total output plus transaction fees.
Enhanced Privacy: UTXOs can be split or merged, making transaction patterns harder to trace.
Parallel Validation: UTXOs are independent, enabling efficient transaction validation across
nodes.
known as Ethe,
——
bl oc kc ha in wi th a un iq ue to ke n
ed in 20 15 by Vi ta li k Bu te ri n, is 2 unique
Ethereum, found o
is ver ifi ed by Bit coin yia the blockchain, the Ethereum play
l cur ren cy
While the ownership of digita ” cli ent -se rve r in te me t a, ; ena t
does away wit h the “ce ntr ali zed
developers to create fully distributed apps and t of applications, . _ ts
og ra mm ab il it y, whi ch ena ble s the de velopmen
The key feature of Ethereum is its pr |
all ows de ve lo pe rs to cre ate and dep io, , ‘ =
software platform that
Ethereum is a blockchain-based open |
applications. p distin, 7
has the abi lit y to pe rf or m tas ks and dev elo
rencies; it
It is more than simply a platform for cryptocur rng
applications.
lic ati ons kn ow n as Da pp s (de cen tra liz ed apps). It is the a
d app
Ethereum is a DIY platform for decentralize tte :
re
turat
ucope
infrastrfor ing Dapps.
Comparison of BFT and PBFT Consensus in Blockchain
PBFT (Practical Byzantine Fault
Definition Generic algorithm for achieving consensus Optimized BFT variant designed for
despite Byzantine faults. practical blockchain systems.
Fault Tolerance #1
Tolerates up to —- Byzantine nodes. Tolerates up to = faulty nodes.
Performance Lower efficiency in large networks. High efficiency for small to medium-
sized networks.
Scalability Less scalable for large networks. More scalable than traditional BFT but
Consensus Type Generalized agreement among participants. Leader-based approach with view
changes for fault tolerance.
Leader Election Not explicitly defined in all implementations. Leader is elected for each consensus
round.
Energy Comparatively efficient as it does not require Highly energy-efficient due to reduced
Efficiency mining. computational overhead.
Suitability Best for academic purposes and high-security Practical for enterprise-level
scenarios. + permissioned blockchains.
Address and Address peel difference introduced in Solidity version 0.5.0. The intention
was to separate
Lcinanapeninnidbeaiail those who can't (used for other purposes). Hence, an address payable can
senna hncancnileremdin Hence, in Solidity, Ether can be sent to a variable defined as address payable
et a siadveae Use the keyword payable before the variable name of an address
a
but cannota able *" de
be sent to a varime
type to enable it to receive ether.
For Example :
Contract Vaults {
// United States gold reserves (cannot receive ether)
address FortKnox:
i deposit ether here
address payable etherVault;
}
—
a a
bdr
The type returned by msg.sender is of address payable type. Therefore, the following : ethods
” become Mailable 4
an address defined as payable in Solidity: transfer() , send(), call(), delegatecall() and staticca
explain difi with its features in blockchain
2. Smart Contracts: Automated contracts that execute financial operations (e.g., lending, trading)
based on pre-defined conditions.
3. Permissionless Access: Anyone can participate in DeFi without needing approval from
intermediaries, ensuring inclusivity.
4, Transparency: All transactions and smart contracts are recorded on the blockchain, offering full
visibility to users.
5. Interoperability: DeFi platforms often interact seamlessly, allowing users to move assets and
data between different applications.
6. Liquidity Pools: DeFi allows users to contribute assets to liquidity pools, facilitating
decentralized trading while earning rewar. v
Cryptography in Blockchain
Hash Functions:
* Uses a pair of keys (private and public) for encryption and digital signatures.
Digital Signatures:
Secure Hashing:
¢ Double spending occurs when the same cryptocurrency token is spent more than once.
* Blockchain prevents double spending through a consensus mechanism like Proof of Work (PoW)
or Proof of Stake (PoS).
Example
¢ Auser sends 1 Bitcoin to Alice and attempts to send the same 1 Bitcoin to Bob.
¢ Both transactions enter the network, but only one will be confirmed and added to the
blockchain.
Unlike traditional blockchains, Corda does not broadcast all transactions to all participants;
Built to handle complex workflows in industries like finance, healthcare, and supply chain.
Supports smart contracts written in Java or Kotlin for ease of integration into existing systems.
Reduces transaction costs and settlement times by enabling direct peer-to-peer exchanges.
Prioritizes regulatory compliance with features like identity management and auditability.
Challenges in Implementing Blockchain
Scalability: Blockchain networks often face performance issues, with limited transactions per
second, especially in public blockchains like Bitcoin and Ethereum.
Interoperability: Different blockchain platforms often lack standardization, making it difficult for
systems to communicate or integrate seamlessly.
High Initial Costs: Development, deployment, and maintenance of blockchain solutions can be
expensive, deterring small and medium-sized enterprises.
User Adoption: Educating users and organizations about blockchain technology is required but
often met with resistance due to its complexity.
Security Risks: While blockchain is secure, vulnerabilities such as 51% attacks, smart contract
bugs, or phishing can compromise systems.
Integration Challenges: Incorporating blockchain into legacy systems and workflows requires
significant effort and resources.
Network Governance: Deciding how decisions are made and disputes are resolved in
decentralized systems can lead to conflicts and inefficiencies.
algorithm
. series
-—
ee
C
o
ea
, T
variable.
: Eventuall
y each COTeC
t process Set
s its d
7 - 7
ecision
t: The deci
. Agreemen
came.
sion value Of
all correct P
rocesses ig t
he
| .2ptional | Membership | optiona
Servic
es pa
Client
Sess ee - oe
Endorser
Application
a — P| Committer
Chaincode
as
Hyperledger Fabric is a platform for developing distributed ledger solutions, including a modular architecture that
delivers high degrees of confidentiality, flexibility, resiliency, and scalability.
The fabric provides components, such as consensus and membership services, to be plug-and-play. It has container
technology to host smart contracts called “chain code” that hold the business rules of the system. Fabric is designed to
support pluggable components.
Architecture of Hyperledger includes various components, shown in Fig. 5.10.3, that work together to execute multiple
transactions of users in a peer-to-peer network in a specific order.
Membership Services
transactions on ablockchain network.
They provide identity to users using and performing
l certificates to authorizea user and
y isis recognized in the form of} digital certificates. Users will use digita
identitity
This s ident
signatures.
authenticate transactions through digital
| |
Certification Authority (CA)
e can be
includes the attributes of standard digital certificates. The certificat
It issuesme digital certificates to a user, which
, ‘i fabric CA.
issued by a traditional external CA or 1a! which may be customized as per the need of an enterprise. These
le,
Fabric CA is an optional and pluggable modu com munication over the Internet.
vir ed for sec ure
key 18 rq
certificates will contain a public key. This used by clients to
edger Fabric Client SDK. It is
kchain u sing Hyperl
Client application is used to interact
: withi bloc
Perform translation on blockchain.
It configures the network, defines the endorsement policy, and manages the blockchain network.
& Ordering Service
It is run by an organization to arrange a set of transactions submitted
by users in order and returns a transaction in order.
* Events can be emitted once the transaction is complete. Peer nodes can perform functions
of anendorser, committer, o:
both.
' Endorser
¢ Endorser executes achain code on the network and validates the output. It maintains a copy of
thechain code which it
executes and verifies the correctness of the output.
¢ Legitimate transactions are submitted to the ordering service, which returns the order of transact
ions to be committed,
and finally these order transactions are committed by the committer node and recorded on the block.
Peers can be either
an endorser or a committer or can perform the role of both.
¢ In fabric, transaction flows from endorsement to ordering and then commit. Client proposes transact
ion for running
chain code and provides input.
Hyperledger Sawtooth in Blockchain
Hyperledger Sawtooth is an open-source blockchain platform designed for enterprise use.
It supports permissioned networks, making it suitable for businesses requiring controlled access.
Implements a unique consensus algorithm called Proof of Elapsed Time (PoET), which is energy-
efficient and scalable.
Ensures data integrity and confidentiality through features like private transactions.
Integrates easily with existing systems and supports smart contracts written in multiple
languages, such as Python and Go.
Commonly used in industries like supply chain, finance, and healthcare for secure and efficient
processes.
>i 5.13 MEMBERSHIP SERVICE PROVIDER (MSP)
an essential component
Hyperledger fabric applications run in permissioned blockchain networks; hence, MSPbecomes
of hyperledger fabric.
unknown entities to
It provides identity management services to the network participants and allows the registration of
join and participate in the network.
CA can use
Certification authority-based membership service can be implemented using the Fabric CA module. Fabric
any X.509-based PKI infrastructure to issue and manage digital certificates.
.
The certificate issued by CA provides information about permissions, roles, and attributes for the use of a channel
The ability of a user to query or invoke a transaction on any channel depends on the permissions, roles, or attributes
maintained in the issued certificate.
ementation is used.
To maintain a high degree of anonymity and unlinkability of transaction,identity mixer-based impl
ut
Identity mixed allows users to transact without revealing their identity and also send multiple transactions witho
revealing that the transactions are coming from the same user.
* Life of a miner
™.
The task of a miner is to validate transactions and construct a new block. Once
they have constructed a new block, rt
they employ their hash power to vote on consensus (i.¢., to identify who
will be finishing the work first and Propose the
block as a new block) and commit the transactions with a new block and
add the new block to an existing blockchain,
and then store and broadcast the new blockchain to the peers. So, this is now the
entire blockchain Bets propagated iq
the entire network
The entire procedure of mining bitcoins has six sleps :
|. Join the bitcoin network and listen for transactions and validate
the proposed transactions that are coming from the
chient
2. To listen for new blocks, i.e., validate new blocks and re-broadcast
a new block when it is proposed.
3. Collect the transactions for a pre-defined time and construct
a new block.
4. The miner needs to participate in the mining procedure where
nonce value needs to be obtained to make a new
block valid.
5. Broadcast the new block to the peers. If everyone accepts it,
then it is a part of the main chain,
6. Earn a reward for participating in the mining procedure.