0% found this document useful (0 votes)
28 views

Unit - 1 BCT Fin

Blockchain

Uploaded by

pvarshinibca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Unit - 1 BCT Fin

Blockchain

Uploaded by

pvarshinibca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 50

UNIT I INTRODUCTION TO

BLOCKCHAIN
1.)Block chain:
A blockchain is a distributed ledger with growing lists of records (blocks) that are
securely linked together via cryptographic hashes. Each block contains a
cryptographic hash of the previous block, a timestamp, and transaction data
(generally represented as a Merkle tree, where data nodes are represented by
leaves). Since each block contains information about the previous block, they
effectively form a chain (compare linked list data structure), with each additional
block linking to the ones before it. Consequently, blockchain transactions are
irreversible in that, once they are recorded, the data in any given block cannot be
altered retroactively without altering all subsequent blocks.

Blockchains are typically managed by a peer-to-peer (P2P) computer network for


use as a public distributed ledger, where nodes collectively adhere to a consensus
algorithm protocol to add and validate new transaction blocks. Although
blockchain records are not unalterable, since blockchain forks are possible,
blockchains may be considered secure by design and exemplify a distributed
computing system with high Byzantine fault tolerance.

A blockchain was created by a person (or group of people) using the name (or
pseudonym) Satoshi Nakamoto in 2008 to serve as the public distributed ledger for
bitcoin cryptocurrency transactions, based on previous work by Stuart Haber, W.
Scott Stornetta, and Dave Bayer. The implementation of the blockchain within
bitcoin made it the first digital currency to solve the double-spending problem
without the need of a trusted authority or central server. The bitcoin design has
inspired other applications and blockchains that are readable by the public and are
widely used by cryptocurrencies. The blockchain may be considered a type of
payment rail.

Private blockchains have been proposed for business use. Computerworld called
the marketing of such privatized blockchains without a proper security model
"snake oil";[8] however, others have argued that permissioned blockchains, if
carefully designed, may be more decentralized and therefore more secure in
practice than permissionless ones.
2.)Block chain as Public Ledgers
Introduction
Most businesses keep a “ledger”, a book that describes the important events
(transactions) that took place. A public ledger is a common use of the blockchain
concept In fact, supporting public ledgers is the main original motivator for
blockchain technology in the first place. The idea of a public ledger is to make all
of the transactions in the system public, so that the operations on the application
(all the transactions) are transparent to all parties.

Typical goals of a public ledger are to:

keep the identities of the parties in the transaction secure and anonymous, while
also confirming who they are. (If that seems contradictory, look again at the
section on public key cryptography.)

keep a record book of all genuine transactions between participants.

keep the state of all participants based on the transactions that have occurred

Consider the use case of debt between a groups of people. Instead of paying, debt
is recorded to resolve sometime in the future. The ledger would keep track of all
transactions. This allows the system to update the state (account balance) of those
involved by adding or subtracting from their money balance, and verify the
participants using public/private key pairs (which, by the way, keeps the real-life
identity of the participants secure). Because the ledger is made public, at all times,
all transactions are publicly known, verifiable, and immutable.

Account Balances
When a blockchain is used to maintain a public ledger, it is a big, long series of
transactions. Let’s repeat that: The blockchain is a Big, Long series of transactions.
Maybe millions of transactions, taking up hundreds of gigabytes of space for the
complete ledger. That is far too much information to process sequentially in order
to find all the additions and subtractions to a participant’s account, in order to
know their current account balance.

Fortunately, there is a fairly simple way to keep track of account balances even
within the paradigm of storing a series of transactions. This is the Unspent
Transaction Output (UTXO) model. Under this model, your total account balance
is reflected by the output of your transaction. For example, if you currently have a
total of 10 coins and you want to buy a product that is worth 2 coins, your
transaction must spend all your 10 coins. So, your transaction will actually send 2
coins to the seller address, and send the 8 remaining coins (back) to your account.
With the UTXO model, you don’t have to trace back through multiple transactions
in the history to find out the participant’s total balance, as their total balance is
stored at the latest transaction.

Distributed Public Ledgers


A basic public ledger is probably maintained by some central entity. A blockchain
is used to guarantee that the prior transactions have not been tampered with. So
long as the current start hash for the blockchain is publicly known, even the central
entity that controls updating the ledger cannot modify the contents of the ledger
without everyone realizing that something has gone wrong. However, this does not
stop the central keeper of the ledger from adding whatever transactions they want.
If everyone trusts the central keeper, that is fine. But there are applications where
the users of the system don’t want there to be a central keeper of the ledger.

Distributed ledgers are public ledgers that do not have a central controller who is in
charge of adding blocks to the system. A distributed ledger has all of the goals of
any public ledger. However, across a network of nodes, there are multiple copies
of the ledger (the blockchain and its contents). In fact, anyone is welcome to keep
their own copy. The challenge is how to add new data to the blockchain when there
is no trusted party to do this. This is where the Consensus Algorithm comes in.
Those are complicated (aside from the cryptography primitive functionality, they
are the only part of blockchain technology that is in fact complicated). We will talk
about these in detail in later modules. For now, you can just accept that there is an
agreed upon way by which some members of the community can propose new
blocks to be added to the blockchain, along with a mechanism for the community
to collectively accept the update.

Bitcoin
Bitcoin (BTC) is a cryptocurrency, a virtual currency designed to act as money and
a form of payment outside the control of any one person, group, or entity, thus
removing the need for third-party involvement in financial transactions. It is
rewarded to blockchain miners for verifying transactions and can be purchased on
several exchanges.

Bitcoin was introduced to the public in 2009 by an anonymous developer or group


of developers using the name Satoshi Nakamoto.1

It has since become the most well-known cryptocurrency in the world. Its
popularity has inspired the development of many other cryptocurrencies. These
competitors either attempt to replace it as a payment system or are used as utility or
security tokens in other blockchains and emerging financial technologies.

The Bitcoin blockchain is an amalgamation of Bitcoin and blockchain. A person


or a group of people known as Satoshi Nakamoto created the Bitcoin protocol in
2008 to decentralize control of money when centralized entities had failed the
world. A publication called the Bitcoin white paper outlined a set of computational
rules that determined a new type of distributed database: the blockchain. The
network was launched in January 2009.

The most well-known cryptocurrency, Bitcoin, is the one for which blockchain
technology was created. Like the United States dollar, a cryptocurrency is a digital
means of exchange that uses encryption techniques to oversee the establishment of
monetary units and verify financial transfers.

The Bitcoin blockchain refers to the data stored in “blocks” of information that are
then linked together in a permanent “chain.” A block is a collection of Bitcoin
transactions from a specific period. Stacks of blocks are stockpiled on top of each
other, with each new block relying on the previous ones. As a result, a chain of
blocks is formed, giving rise to the word “blockchain.”

Every time a new block is added, it makes the previous blocks unmodifiable. This
ensures that each block is more secure over time, and it is an example of how
Bitcoin technology is changing how banking and financial transactions are being
made.
Bitcoin blockchain, however, is much more than cryptocurrency: It is the
technology that most cryptocurrencies are built on, including Bitcoin. The Bitcoin
blockchain is unique because it ensures that all transactions are accurate. Every
action in the blockchain is recorded and there is nothing that is left out of the
network. Once an action is recorded and stored in one of the information blocks, it
is time-stamped and secured, and the entire record is available to anyone in the
system.

The Bitcoin blockchain is also decentralized, meaning it is not stored in one master
computer or controlled by one company. It is distributed on many computers that
are in the network.

In the Bitcoin blockchain, there are codes called a hash. A hash is unique to each
block in the blockchain. Hashing allows every network user to identify each block
and directs them to move in the chain since every block has its own hash and a
previous block's hash.

With the latter in mind, the critical parts of the blockchain include records, block,
hash and chain. Block records and transactional records are the two types of
records in the blockchain. A block contains the most recent Bitcoin transactions
that have not yet been recorded in any previous block. Transaction records include
the asset, price and ownership data that are recorded, approved and settled across
all nodes in seconds.

In essence, a hash is a fixed-length string generated after transforming any length


of input data in the blockchain network, a block is similar to a page in a ledger or
record book and a chain refers to blocks linked together in a network.

Short story of Bitcoin blockchain

The idea of blockchain technology was introduced in 1991 by Stuart Haber and W.
Scott Stornetta in their paper “How to Time-Stamp a Digital Document.” In this
paper, they explained the use of a continuous chain of timestamps to record
information securely.

Bitcoin was created largely to facilitate the exchange of Bitcoin cryptocurrency.


However, early adopters and inventors rapidly discovered that it had far greater
potential. With this in mind, they designed Bitcoin's blockchain to store more than
just data on the token's movement.
Bitcoin technology uses peer-to-peer (P2P) transactions, making it possible to
function without any bank or third party to manage each financial movement. It
allows online payments to be sent directly from one party to another without going
through any financial institution.

Related: The history of Bitcoin: When did Bitcoin start?

The term peer-to-peer means that the computers that are part of the network are
equal to each other, that there are no “special” nodes and that all nodes share the
burden of providing network services. It is made up of thousands of Bitcoin nodes
that run the protocol. The protocol is responsible for establishing and safeguarding
the blockchain.

The formation of a peer-to-peer network is possible because users' data is related to


the person or entity they are interacting with, and they are in charge of keeping the
distributed network up and running. The information regarding the individual or
entity is then passed from their Bitcoin wallet to their location and IP address,
which represents peer-to-peer Bitcoin interaction.

What is needed to make the Bitcoin blockchain work?

Bitcoin represents a digital, trustless form of money, alongside a movement to


decentralize financial services. Before Bitcoin, there was a need for a trusted third
party to keep a ledger — the record-keeping system of a company's or person's
financial data — to record who owned how much. Everyone has a copy of this
ledger with the Bitcoin network, so there is no need for third parties.

Every Bitcoin transaction happens in the Bitcoin blockchain network, which is the
digital space where Bitcoin mining and hash power generation occur. Hashing
power is the processing power used by your computer or hardware to perform and
solve various hashing algorithms. These algorithms are used to create new
cryptocurrencies and allow them to trade with one another. This process is called
mining.

Usually, Bitcoin owners purchase their cryptocurrency supply through a


cryptocurrency exchange, a platform that facilitates transactions of Bitcoin and
other cryptocurrencies. The decentralized ledger is what makes the blockchain
network. The latter shows that Bitcoin is a piece of software, a set of processes in
which participants perform different tasks.
A blockchain is a digital ledger of duplicated transactions distributed across the
blockchain's network of computer systems. Each block on the chain contains
several transactions, and whenever a new transaction occurs on the blockchain, a
record of that transaction is added to the ledger of each participant.

This distributed database is managed by multiple participants using a technology


called distributed ledger technology (DLT). Blockchain is a type of DLT in which
transactions are recorded using an immutable cryptographic signature known as a
hash. The transactions are then organized into blocks. Each new block includes a
hash of the preceding one, effectively chaining them together, which is why
distributed ledgers are commonly referred to as blockchains.

The blockchain works as a ledger, tracking every Bitcoin transaction, and is self-
verifying, meaning that the entire network of nodes — different computers
participating in the network — will constantly check and secure every movement.
Here is where the “miners” come into the game: Their computers do the heavy
lifting of maintaining the chain and thus, receive Bitcoin as a reward. These rules,
collectively, are the Bitcoin protocol.

OR

Bitcoin
Satoshi Nakamoto introduced the bitcoin in the year 2008. Bitcoin is a
cryptocurrency(virtual currency), or a digital currency that uses rules of
cryptography for regulation and generation of units of currency. A Bitcoin fell
under the scope of cryptocurrency and became the first and most valuable among
them. It is commonly called decentralized digital currency.

A bitcoin is a type of digital assets which can be bought, sold, and transfer between
the two parties securely over the internet. Bitcoin can be used to store values much
like fine gold, silver, and some other type of investments. We can also use bitcoin
to buy products and services as well as make payments and exchange values
electronically.

A bitcoin is different from other traditional currencies such as Dollar, Pound,


and Euro, which can also be used to buy things and exchange values
electronically. There are no physical coins for bitcoins or paper bills. When you
send bitcoin to someone or used bitcoin to buy anything, you don?t need to use a
bank, a credit card, or any other third-party. Instead, you can simply send bitcoin
directly to another party over the internet with securely and almost instantly.

How Bitcoin Works?

When you send an email to another person, you just type an email address and can
communicate directly to that person. It is the same thing when you send an instant
message. This type of communication between two parties is commonly known as
Peer-to-Peer communication.

Whenever you want to transfer money to someone over the internet, you need to
use a service of third-party such as banks, a credit card, a PayPal, or some other
type of money transfer services. The reason for using third-party is to ensure that
you are transferring that money. In other words, you need to be able to verify that
both parties have done what they need to do in real exchange.

For example,
Suppose you click on a photo that you want to send it to another person, so you can
simply attach that photo to an email, type the receiver email address and send it.
The other person will receive the photo, and you think it would end, but it is not.
Now, we have two copies of photo, one is a simple email, and another is an
original file which is still on my computer. Here, we send the copy of the file of the
photo, not the original file. This issue is commonly known as the double-spend
problem.

The double-spend problem provides a challenge to determine whether a transaction


is real or not. How you can send a bitcoin to someone over the internet without
needing a bank or some other institution to certify the transfer took place. The
answer arises in a global network of thousands of computers called a Bitcoin
Network and a special type of decentralized laser technology called blockchain.

In Bitcoin, all the information related to the transaction is captured securely by


using maths, protected cryptographically, and the data is stored and verified across
the entire network of computers. In other words, instead of having a centralized
database of the third-party such as banks to certify the transaction took place.
Bitcoin uses blockchain technology across a decentralized network of computers to
securely verify, confirm and record each transaction. Since data is stored in a
decentralized manner across a wide network, there is no single point of failure.
This makes blockchain more secure and less prone to fraud, tampering or general
system failure than keeping them in a single centralized location.
4.Smart Contracts
WHAT IS A SMART CONTRACT?
A "smart contract" is simply a program that runs on the Ethereum blockchain. It's a
collection of code (its functions) and data (its state) that resides at a specific
address on the Ethereum blockchain.

Smart contracts are a type of Ethereum account. This means they have a balance
and can be the target of transactions. However they're not controlled by a user,
instead they are deployed to the network and run as programmed. User accounts
can then interact with a smart contract by submitting transactions that execute a
function defined on the smart contract. Smart contracts can define rules, like a
regular contract, and automatically enforce them via the code. Smart contracts
cannot be deleted by default, and interactions with them are irreversible.

How smart contracts work

Smart contracts work by following simple “if/when…then…” statements that are


written into code on a blockchain. A network of computers executes the actions
when predetermined conditions have been met and verified. These actions could
include releasing funds to the appropriate parties, registering a vehicle, sending
notifications, or issuing a ticket. The blockchain is then updated when the
transaction is completed. That means the transaction cannot be changed, and only
parties who have been granted permission can see the results.

Within a smart contract, there can be as many stipulations as needed to satisfy the
participants that the task will be completed satisfactorily. To establish the terms,
participants must determine how transactions and their data are represented on the
blockchain, agree on the “if/when...then…” rules that govern those transactions,
explore all possible exceptions, and define a framework for resolving disputes.

Then the smart contract can be programmed by a developer – although


increasingly, organizations that use blockchain for business provide templates, web
interfaces, and other online tools to simplify structuring smart contracts.

Benefits of smart contracts

Speed, efficiency and accuracy


Once a condition is met, the contract is executed immediately. Because smart
contracts are digital and automated, there’s no paperwork to process and no time
spent reconciling errors that often result from manually filling in documents.

Trust and transparency

Because there’s no third party involved, and because encrypted records of


transactions are shared across participants, there’s no need to question whether
information has been altered for personal benefit.

Security

Blockchain transaction records are encrypted, which makes them very hard to
hack. Moreover, because each record is connected to the previous and subsequent
records on a distributed ledger, hackers would have to alter the entire chain to
change a single record.

Savings

Smart contracts remove the need for intermediaries to handle transactions and, by
extension, their associated time delays and fees.

Applications of smart
contracts
1.Safeguarding the efficacy of medications

2.Increasing trust in retailer-supplier relationships

3.Making international trade faster and more efficient

OR
What Is Smart Contract?

Smart contracts are computer programs or protocols for automated transactions


that are stored on a blockchain and run in response to meeting certain conditions.
In other words, smart contracts automate the execution of agreements so that all
participants can ascertain the outcome as soon as possible without the involvement
of an intermediary or time delay.

Smart contracts are self-executing contracts in which the contents of the buyer-
seller agreement are inscribed directly into lines of code.

According to Nick Szabo, an American computer scientist who devised a virtual


currency called "Bit Gold" in 1998, Smart contracts are computerized transaction
protocols that execute contract conditions.

Using it makes the transactions traceable, transparent, and irreversible.

Benefits of Smart Contracts

Accuracy, Speed, and Efficiency

The contract is immediately executed when a condition is met.

Because smart contracts are digital and automated, there is no paperwork to deal
with, and

No time was spent correcting errors that can occur when filling out documentation
by hand.

Trust and Transparency

There's no need to worry about information being tampered with for personal gain
because there's no third party engaged and

Encrypted transaction logs are exchanged among participants.

Security
Because blockchain transaction records are encrypted, they are extremely difficult
to hack.

Furthermore, because each entry on a distributed ledger is linked to the entries


before and after it, hackers would have to change the entire chain to change a
single record.

Savings

Smart contracts eliminate the need for intermediaries to conduct transactions, as


well as the time delays and fees that come with them.

How Do Smart Contracts Work?

A smart contract is a sort of program that encodes business logic and operates on a
dedicated virtual machine embedded in a blockchain or other distributed ledger.

Step 1: Business teams collaborate with developers to define their criteria for the
smart contract's desired behavior in response to certain events or circumstances.

Step 2: Conditions such as payment authorization, shipment receipt, or a utility


meter reading threshold are examples of simple events.

Step 3: More complex operations, such as determining the value of a derivative


financial instrument, or automatically releasing an insurance payment, might be
encoded using more sophisticated logic.

Step 4: The developers then use a smart contract writing platform to create and test
the logic. After the application is written, it is sent to a separate team for security
testing.

Step 5: An internal expert or a company that specializes in vetting smart contract


security could be used.

Step 6: The contract is then deployed on an existing blockchain or other distributed


ledger infrastructure once it has been authorized.
Step 7: The smart contract is configured to listen for event updates from an
"oracle," which is effectively a cryptographically secure streaming data source,
once it has been deployed.

Step 8: Once it obtains the necessary combination of events from one or more
oracles, the smart contract executes.

Smart Contacts and Flight Insurance

Let's consider a real-life scenario in which smart contracts are used. Rachel is at
the airport, and her flight is delayed. AXA, an insurance company, provides flight
delay insurance utilizing Ethereum smart contracts. This insurance compensates
Rachel in such a case. How? The smart contract is linked to the database recording
flight status. The smart contract is created based on terms and conditions.

The condition set for the insurance policy is a delay of two hours or more. Based
on the code, the smart contract holds AXA's money until that certain condition is
met. The smart contract is submitted to the nodes on EMV (a runtime compiler to
execute the smart contract code) for evaluation. All the nodes on the network
executing the code must come to the same result. That result is recorded on the
distributed ledger. If the flight is delayed in excess of two hours, the smart contract
self-executes, and Rachel is compensated. Smart contracts are immutable; no one
may alter the agreement.

Voting and Blockchain Implementation of Smart Contracts

Using Blockchain in the voting process can eliminate common problems. A


centralized voting system faces difficulties when it comes to tracking votes –
identity fraud, miscounts, or bias by voting officials. Using a smart contract,
certain predefined terms and conditions are pre-set in the contract. No voter can
vote from a digital identity other than his or her own. The counting is foolproof.
Every vote is registered on a blockchain network, and the counting is tallied
automatically with no interference from a third party or dependency on a manual
process. Each ID is attributed to just one vote. Validation is accomplished by the
users on the blockchain network itself. Thus, the voting process can be in a public
blockchain, or it could be in a decentralized autonomous organization-based
blockchain setup. As a result, every vote is recorded on the ledger, and the
information cannot be modified. That ledger is publicly available for audit and
verification.

Smart contracts allow you to create voting systems in which you can add and
remove members, change voting rules, change debating periods, or alter the
majority rule. For instance, you can create a vote for a decision within a
decentralized autonomous organization. Rather than a central authority making a
decision, a voting mechanism within the organization can determine whether the
proposal is accepted or rejected.

Blockchain Implementation of a Smart Contract and


Crowdfunding

Ethereum-based smart contracts may be used to create digital tokens for


performing transactions. You may design and issue your own digital currency,
creating a tradable computerized token. The tokens use a standard coin API. In the
case of Ethereum, there are standardizations of ERC 2.0, allowing the contract to
access any wallet for exchange automatically. As a result, you build a tradable
token with a fixed supply. The platform becomes a central bank of sorts, issuing
digital money.

Suppose you want to start a business requiring funding. But who would lend
money to someone they don't know or trust? Smart contracts have a major role to
play. With Ethereum, you can build a smart contract to hold a contributor's funds
until a given date passes or a goal is met. Based on the result, the funds are
released to the contract owners or sent back to the contributors. The centralized
crowdfunding system has many issues with management systems. To combat this,
a DAO (Decentralized Autonomous Organization) is utilized for crowdfunding.
The terms and conditions are set in the contract, and every individual participating
in crowdfunding is given a token. Every contribution is recorded on the
Blockchain.

Limitation of Smart Contracts

Because smart contracts can't send HTTP queries, they can't acquire information
about "real-world" events. This is by design.
Using external data could jeopardize consensus, which is critical for security and
decentralization.

Use Cases of Smart Contracts

The use cases for smart contracts range from simple to complex.

They can be used for simple economic transactions, such as moving money from
point A to point B, as well as for smart access management in the sharing
economy.

Smart contracts could disrupt many industries.

Banking, insurance, energy, e-government, telecommunications, the music


business, art, mobility, education, and many other industries have use cases

DISTRIBUTED CONSENSUS

A procedure to reach a common agreement in a distributed or decentralized multi-


agent platform. It is important for the message passing system.

Example –

A number of processes in a network decide to elect a leader. Each process begins


with a bid for leadership. In traditional or conventional distributed systems, we
apply consensus to ensure reliability and fault tolerance. It means, in a
decentralized environment when you have multiple individual parties, and they can
make their own decision, then it may happen that some node or some parties are
working maliciously or working as a faulty individual. So in those particular
cases, it is important to come to a decision or common point of view. So having a
common point of view in an environment where people can behave maliciously or
people can crash the work in a faulty way, is the main difficulty. So under this kind
of distributed environment, our objective is to ensure reliability which means to
ensure correct operation in the presence of faulty individuals. It ensures reliability
and fault tolerance in distributed systems.
In the presence of faulty individuals, it is Ensure correct operations.
Examples –
Commit a transaction in a database, State machine replication, Clock
synchronization.
How to achieve distributed consensus :
There are some conditions that need to be followed in order to achieve distributed
consensus.
 Termination – Every non-faulty process must eventually decide.
 Agreement – The final decision of every non-faulty process must be identical.
 Validity – Every non-faulty process must begin and ends with the same value.
 Integrity – Every correct individual decides at most one value, and the decided
value must be proposed by some individual.
Here is one validation criterion, So basically we should reach a decision with a
value that must be the initial value of some process because it is silly to reach an
agreement when the agreed value reflects nobody’s initial choice.
The correctness of Distributed Consensus Protocol :
It can be described by the following two properties as follows.
 Safety Property – It ensures that you will never converge to an incorrect value or
correct individuals in a network will never converge to an incorrect value.
 Liveness Property – It states that every correct value must be accepted
eventually which means something good will eventually happen.
 Termination Property – It guarantees that every correct process will eventually
decide on a value. This ensures that the protocol will eventually terminate.
 Agreement Property – It guarantees that all correct processes will eventually
agree on a single value. This ensures that all correct nodes in the network will
come to a consensus.
 Fault Tolerance – Distributed consensus protocols must be able to handle
failures and errors, both in the network and in the participating nodes. This
ensures that the system remains correct and functional even in the presence of
faults.
 Byzantine Fault Tolerance – Some distributed consensus protocols, like PBFT,
have the additional property of Byzantine Fault Tolerance (BFT). This means
they can tolerate up to a certain number of malicious nodes in the network
without compromising safety and liveness properties.
 Scalability – The protocol must be able to scale to handle large networks and
increasing numbers of nodes without sacrificing safety, liveness, or fault
tolerance. This ensures that the protocol can be used in real-world scenarios with
a large number of participants.
Application of Distributed Consensus :
 Leader election in a fault-tolerant environment for initiating some global action
without introducing a single point of failure.
 Maintaining consistency in a distributed network. Suppose you have different
nodes monitoring the same environment. If one of the nodes crashes, a
consensus protocol ensures robustness against such faults.
 Blockchain technology: Distributed consensus is a fundamental concept in
blockchain technology, which allows multiple nodes to agree on a shared
database without relying on a central authority.
 Distributed databases: Distributed consensus protocols can be used to maintain
consistency across multiple replicas of a distributed database.
 Load balancing: Consensus protocols can be used to dynamically distribute the
workload across multiple nodes in a distributed system to ensure that no node is
overloaded.
 Fault tolerance: Distributed consensus protocols can provide fault tolerance in
distributed systems by allowing nodes to recover from crashes or network
partitions.
 Agreement protocols: Consensus protocols can be used to achieve agreement
among multiple nodes in a distributed system on a particular course of action or
decision.

OR

What Are Consensus Mechanisms in


Blockchain and Cryptocurrency?
 A consensus mechanism is a program used in blockchain systems to achieve
distributed agreement about the ledger's state. Generally, it is implemented in a
network with many processes and users. Cryptocurrencies, blockchains, and
distributed ledgers benefit from their use because the consensus mechanism
replaces much slower human verifiers and auditing.
 For instance, the Bitcoin blockchain uses a mechanism called Proof-of-Work
(PoW), which requires computational power to solve an encrypted puzzle, called
the hash. After the hash is solved by one miner (or a group working together),
Bitcoin's PoW requires that every node on the network verifies the data that has
been changed by checking:
 The data structure
 The block header hash
 The block timestamp
 The block size
 The first transaction
 It then completes a long transaction verification checklist. This verification takes
much less time than the process of solving the hash, which is called mining, and
is orders of magnitude less time-consuming than human verification.1

History of Consensus Mechanisms


 When computers and networks began gaining popularity in the 1980s and 90s,
shared databases were created so that multiple users could access the
information they stored. Most had a centralized database with permissions that
users accessed from different stations. This setup evolved into centralized
networks with administrators who granted user rights and maintained the
integrity of the data.
 These shared databases became known as distributed ledgers because they
recorded information and were networked for many users in different locations
to access. One of the most significant issues that needed addressing was that of
preventing data tampering and unauthorized access, whether it was malicious or
not. A method to automate distributed database management was required to
ensure data was not changed.
 This need led to the creation of distributed autonomous consensus, where
programs on a network agreed on a database's state using cryptographic
techniques. Agreement was designed to be reached using encryption algorithms
to create long strings of alphanumeric numbers—called a hash—which were
then verified by programs running on the network. A hash only changes if the
information input into the hashing algorithm is changed, so the programs were
designed to compare hashes to ensure they matched.

Types of Consensus Mechanisms


 There are different kinds of consensus mechanism algorithms, each of which
works on different principles.
 The proof of work (PoW) is a common consensus algorithm used by the most
popular cryptocurrency networks like Bitcoin and Litecoin. It requires a
participant node to prove that the work done and submitted by them qualifies
them to receive the right to add new transactions to the blockchain. However,
the bitcoin mining mechanism requires high energy consumption and long
processing times.
 The proof of stake (PoS) is another common consensus algorithm that evolved
as a low-cost, low-energy consuming alternative to the PoW algorithm. It
involves allocating responsibility in maintaining the public ledger to a
participant node in proportion to the number of virtual currency tokens held.
However, this has the drawback that it incentivizes hoarding instead of
spending.

THE CHAIN AND THE LONGEST CHAIN

 The longest chain is what individual nodes accept as the valid version of
the blockchain. The rule that nodes adopt the longest chain of blocks allows
every node on the network to agree on what the blockchain looks like, and
therefore agree on the same transaction history.
 The longest chain is what individual nodes accept as the valid version of
the blockchain.
 The rule that nodes adopt the longest chain of blocks allows every node on the
network to agree on what the blockchain looks like, and therefore agree on the
same transaction history.
 In other words it means that computers acting independently over a network can
maintain a globally shared view of a file.

What is the longest chain?


 The longest chain is the chain of blocks that took the most effort to build.
 In short, to add a new block to the blockchain you need to use processing power,
which means that every block on the blockchain used up energy to get there.

Adding a new block requires energy.


 Therefore, a blockchain with more blocks in it will have taken more energy to
build than a chain with fewer blocks in it, and as a rule nodes will always adopt
this chain over a “shorter” one.

Longer chains take more work to build.


 As a result, nodes will always adopt the chain that took the most energy to build,
which is what we mean when we refer to the “longest chain”.

 The majority decision is represented by the longest chain, which has the greatest
proof-of-work effort invested in it. – Satoshi Nakamoto

Is the longest chain the one with the most blocks?


 Sounds about right, but actually the chain that required the most energy to build
is not necessarily the one with the most blocks in it. You see,
the difficulty changes mean that some blocks are going to require more energy
to mine than others.
 For example, within the same difficulty period every new block requires the
same amount of effort to mine, and therefore adds the same amount of “work” to
the chain:

The target is what blocks must get under to be added on to the chain.
 However, if the difficulty increases (because blocks were mined more quickly
than every 10 minutes on average), the blocks in the new difficulty period are
going to take more effort to mine on to the blockchain.

 Now, seeing as nodes adopt the chain with the most work, they wouldn’t
actually adopt a chain with more blocks in it if it didn’t require as much work to
build. For example, if two versions of the blockchain span multiple difficulty
periods, nodes will adopt the one that has the most cumulative “chainwork”, and
not simply the one with the most blocks in it:

 So in summary, the phrase “longest chain” refers to the blockchain that has
taken the most energy to build. For the most part this is usually the chain with
the most blocks in it, but to be more precise it’s the chain with the most amount
of work in it.
 Note: In the first version of Bitcoin Satoshi actually used the number of blocks
as the metric for determining the longest chain, believing this to be the chain
that would have taken the most work to build. However this is vulnerable to
manipulation, so it was later changed to using chainwork as the metric for the
longest chain instead.1

How do you calculate the longest chain?


 The longest chain is measured by a metric called “chainwork”.

 [Chainwork] is the total number of hashes that are expected to have been
necessary to produce the current chain.
– Pieter Wuille
 To work out chainwork, you just need to work out how many hashes you
would have needed to perform to mine each block in the chain, then add
them up.

The average expected number of hashes for each block depends on what the target was at the time.

Chainwork Calculation Explained

Why do nodes adopt the longest chain?


 Having nodes adopt the longest available chain allows computers across a
network to be able to share the same view of the blockchain.
 Here are two examples of where this rule comes in handy:

1. Resolving disagreements when two blocks are mined at the


same time.
 Due to the fact that bitcoin operates on a network, it’s possible that two
independent computers will mine a block at the same time. In this situation,
nodes across the network will end up being in disagreement about which of
these two blocks should be at the top of the blockchain.

Each nodes put the first block they receive at the top of their blockchain.
 However, this situation can be resolved by having nodes adopt the longest chain
of blocks. This is because the next block to be mined will build upon one of
these two blocks, creating a new longest chain that all nodes on the network will
be happy to adopt.

Nodes are happy to abandon the shorter chain in favour of the new longer one.
This is known as a chain reorganisation.
 So even though nodes can be in disagreement at any given time (due to the
unpredictability of mining and the speed of broadcasting data across a network),
adopting the longest available chain means that nodes will
always eventually agree on the same view of the blockchain.

2. Protecting blocks already mined on to the blockchain.


 The fact that nodes always adopt the longest chain as the valid version of the
blockchain means that it is very difficult to replace blocks (and therefore
transactions) in the chain.
 If anyone wanted to replace a transaction in the blockchain, they would need to
work to build a new longest chain to replace the current one. However, if the
majority of miners are continually working to extend the same current longest
known chain, an individual miner won’t be able to compete to outwork all of the
other miners.
You would need the majority of mining power to be able to out-run all other
miners and build a new longest chain (known as a 51% Attack).

 In effect, the combined effort of miners coordinating to extend the same chain
protects existing blocks and transactions from being replaced by a single miner.

Think of it as a cooperative effort to make a chain. – Satoshi Nakamoto

Why do miners build on the longest chain?


Because a miner can claim a block reward if they are able to mine a block.

Furthermore, the bitcoins from this block reward can only be spent if the block
becomes 100 blocks deep in the longest chain. Therefore, this block reward
incentivises miners to always try and mine new blocks that will become part of the
longest chain (by always trying to build on to the current longest one).
A block
reward can only be spent if the block is part of the longest chain.

Miners claim the block reward through the coinbase transaction.

What about transactions that are not part of the longest


chain?
A transaction inside a block that is not part of the longest chain is invalid.

If you tried to spend the bitcoins from a transaction that is not in the longest chain,
nodes would not accept it nor try to mine it in to a block. This is because nodes
only consider the longest chain the valid history history of transactions, and
anything outside of that is not a valid transaction.

The bitcoins in a transaction that is not part of the longest chain are unspendable.
So only the transactions inside the longest chain are considered to be part of the
valid transaction history, and any transactions outside of it effectively never took
place.

Permissioned Blockchain:
A permissioned blockchain is a distributed ledger that is not publicly accessible. It
can only be accessed by users with permissions. The users can only perform
specific actions granted to them by the ledger administrators and are required to
identify themselves through certificates or other digital means.

You might consider the addition of permissioned users as an extra blockchain


security system. Administrators maintain an access control layer to allow certain
actions to be performed only by certain identifiable participants. Records are kept
within the blockchain of who is involved in the transactions. This makes
permissioned blockchains different from public blockchains.

Understanding Permissioned Blockchains


A blockchain can be built and accessed in multiple ways. Some
blockchains need special permissions to read, access, and write information. Others
only require that you have the ability to connect and can conduct work for the
network. The intrinsic configuration of each blockchain controls the participants'
transactions and defines their roles in which each participant can access and
contribute to the blockchain.

It may also include maintaining the identity of each blockchain participant on the
network. Such blockchains are called permissioned blockchains.

Difference Between Permissionless and Permissioned


Blockchains
Permissioned blockchains are similar to permissionless blockchains because they
use the same technologies. However, permissioned blockchains do not allow users
to access the blockchain without identification.

For example, a bank may be running a permissioned blockchain operated through a


designated number of nodes internal to the bank to track money transfers. You
cannot access this blockchain because you don't have the permissions required. In
contrast, you could join a permissionless blockchain like a cryptocurrency mining
network once you have established a semi-anonymous account in that network.

What are Permissioned Blockchains Used for?


Permissioned blockchains are generally used to manage supply chains, create
contracts, verify payment between parties, and much more.

Introduction To Permissioned Blockchains


Not aware of the terms permissioned and permissionless in Blockchain? To help
you understand, here we bring a detailed introduction to Permissioned blockchains.
Let’s dive into!

Decentralized Ledger Technology (DLT) has opened up a slew of opportunities for


the companies that are looking to innovate. It is not new; Blockchain technology is
one of those technologies that have radically changed how industries work.
However, there cannot be one single solution for the whole industry.

Each startup, company, enterprise, or an industry is different when it comes to their


needs and requirements. It is evident that a privately held company just cannot use
a fully decentralized blockchain network. That’s where different types of DLTs
come in.

In this article, we will be exploring permissioned blockchain. Also, to get the best
possible picture, we will also go through some of the best permissioned
blockchains out there, type of DLTs and other vital topics related to the
permissioned blockchains. Let’s start with the definition of Permissioned
blockchain.

Build your identity as a certified blockchain expert with 101


Blockchains’ Blockchain Certifications designed to provide enhanced career
prospects.

What are the Permissioned Blockchains?


Permissioned blockchains are blockchain networks that require access to be part
of. In these blockchain types, a control layer runs on top of the blockchain that
governs the actions performed by the allowed participants. As you can see,
permissioned blockchains work entirely different than that of private and public
blockchains. They are crafted to take advantage of blockchains without sacrificing
the authority aspect of a centralized system.
So, basically, there is one big difference between a permissioned and a
premissionless one, i.e., the way the participants are going to interact with the
network. A permissioned system is also known to have a restriction on the
consensus participants, making permissioned networks highly configured and
controlled by the owners. However, it is not a bad thing, but it is all about building
a suitable blockchain network.
There are many popular permissioned blockchain frameworks out there. It
includes Hyperledger, Quorum, Corda, and others.
Start learning Blockchain with World’s first Blockchain Skill Paths with quality
resources tailored by industry experts Now!
Benefits of Permissioned Blockchains
There are many benefits of permissioned blockchains which makes it most
preferable to use when compared with the permissionless blockchains. Let’s
understand the beneficial features of permissioned blockchains with its benefits.
 Efficient performance:
When we compared permissioned blockchains to permissionless blockchains, they
offer better performance. The core reason behind this is the limited number of
nodes on the platform. This removes the unnecessary computations required to
reach consensus on the network, improving the overall performance. On top of
that, permissioned networks have their own pre-determined nodes for validating a
transaction.
 Proper governance structure:
Permissioned networks do come with an appropriate structure of governance. This
means that they are organized. Administrators also require less time to update the
rules over the network, which is considerably faster when compared to public
blockchains. The public blockchain network suffers from the consensus problem as
not all nodes work together to get the new update implemented. These nodes might
place their self-interest above the needs of the blockchain, which, in return, means
slower updates to the whole network. In comparison, permissioned blockchain
doesn’t have the problem, as the nodes work together to move the updates faster.
 Decentralized storage:
Permissioned networks also make proper use of blockchain, including utilizing its
decentralized nature for data storage.
 Cost-Effective:
There is no doubt that permissioned blockchains are more cost-effective when
compared with the permissionless blockchains.
Curious to learn about blockchain implementation and strategy for managing your
blockchain projects? Enroll Now in Blockchain Technology – Implementation And
Strategy Course!
Drawbacks of Permissioned blockchains
Permissioned blockchains are not free from disadvantages or drawbacks. Here are
te disadvantages of permissioned blockchains:
 Compromised security –
A public or private blockchain has better security as the nodes participate in a
consensus method properly. But, in the case of permissioned blockchains, this
might not hold true. The security of a permissioned network is as good as the
member’s integrity. This means that a small section of a permissioned system can
work together to modify the data stored within the network. In this way, the
integrity of the network can be compromised. To resolve it, the system should have
proper permissions set so those bad actors cannot merge together to cause the
desired effect.
 Control, Censorship, and Regulation –
In an ideal world, these permissioned blockchains should work as that of a public
blockchain, but with regulations. However, the regulations bring censorship to the
network, where the authority can restrict a transaction or control it from happening.
These are a threat to any business or organization that is using the permissioned
network. This approach also stops the permissioned network from making the most
out of the whole blockchain ecosystem.

Types of blockchain and distributed ledger technologies


The blockchain technology used in bitcoin was simple. It was a public peer-to-peer
network capable of doing transactions without any centralized authority, and each
node has its own copy of the ledger. However, it is not the only possible
blockchain or distributed ledger technology. There are many types of DLTs. Let’s
list them briefly to get a clear idea.
 Public blockchains
Public blockchains are the most common type of blockchain that allows anyone to
participate and do transactions or even participate in the consensus method. There
are many prominent public blockchains out there.
Bitcoin and Ethereum are two great examples. Bitcoin is the first generation
cryptocurrency that utilizes the most basic idea of blockchain. Ethereum brings
more to the table by providing the developers with the ability to develop
distributed apps(dApps) using smart contracts.
Public blockchains also utilize consensus algorithm that doesn’t support a
permissioned approach. They are open source, and anyone without any prior
permission can take part in the network.
Want to become a bitcoin expert? Enroll Now: Getting Started with Bitcoin
Technology
 Federated/Consortium blockchains – Permissioned
blockchains
When it comes to permissioned blockchain, Federated / Consortium blockchain
falls into the category. These blockchain doesn’t allow any external people to take
part in the blockchain. There are many benefits to it, including higher scalability
and is an excellent choice for enterprise companies. There are a lot of permissioned
blockchains, including R3, B3i, Hyperledger, and so on.
 Private blockchain
The last type of blockchain that we are going to discuss is private
blockchains. Private blockchains are “similar” to permissioned blockchains but
have some differences that bring them apart. The private blockchains are not open
to the “public” at all, whereas a permissioned blockchain might have some criteria
for the public to join. Both of them are restrictive in nature, but their approach
differs a little.

Difference between Permissioned and Permissionless


Blockchain
There are many differences between permissionless and permissioned blockchains.
We are comparing these two so that you can get a clear picture of how
permissioned blockchains and are implemented. The following table gives you a
quick insight of the permissioned blockchain vs permissionless blockchain

Cryptographic Hash Functions in Blockchain

Cryptographic hash function in Blockchain is a way to secure the message block


and is used to connect the blocks in a chain. Briefly, In the blockchain, each block
contains its own block hash and a hash of its previous block. Which helps them to
form a cryptographically secured linear chain of blocks

What is Hashing?
Hashing is converting an original piece of data into a digest or hash. The process
uses cryptographic hash functions for the irreversible conversion of the message.

What are Cryptographic Hash Functions?


The hash function applies to the message to generate a message digest, a fixed-size
hexadecimal output.
It takes an arbitrary size input as a message. INPUT M: The Message
Uses a Cryptographic hash function H to encrypt the message M.
Generates the output called Digest.
H(M) = Digest
Cryptographic hash functions are irreversible. That means it’s a 1-way
function, and one can’t generate the message back using the digest.
There are a bunch of cryptographic hash functions. For example, SHA-224, SHA-
256, SHA-512, KECCAK-256, Whirlpool, etc.

Properties of Cryptographic Hash Functions


The process of hashing secures the message and makes the computation easy. It
compresses the message into hash/digest, which is efficient for computation and
communication. Briefly,
Above all, below are the properties of cryptographic hash functions.
Deterministic
Cryptographic hash functions are deterministic. It always generates the same hash
for the same input data. However, even if a single letter changes, the hash changes
dramatically.
For instance:
M: Hello → SHA-256(M) → 185F8DB32271FE25F561A6FC938B2E2643……..
M: HellO → SHA-256(M) →
4FF7975B53DB6C029D88F6AC67BD78D1……….
Notice the difference in the output of both messages.
Moreover, the slightest change in either function or message can result in
significant changes in the digest. This property is known as the Avalanche effect.
Nearly Collision Free
Hash functions are one way. For a given X, it’s easy to calculate H(X)=D. In
contrast, using D, one can’t find X.
However, there’s a little possibility of getting H(X)=H(Y); where X is not equal to
Y. Yet, it’s difficult to find X and Y using the same hash.
For instance, if a hash function produces N bits of output. An attacker needs to
compute 2^(N/2) hash operations on random input to search for the second match
of the output.
Hence, for every 256 hash functions, the attacker must compute 2^128 hash
operations. Even if one computation takes 1 microsecond, it will require
approximately 10^25 years to match the output.
Note: The phrase used is “difficult to find” is because the collision can be possible.
However, it depends on the cryptographic function used and the digest size.
Information Hiding
Since the digest of a message is irreversible, and it’s nearly impossible to find the
same hash for different messages. Therefore, the only way to verify the message is
to hash the possible message. Then, check if its digest matches the original
message’s digest.
Hiding helps to commit a message and then check it later. Here, the commit means
to hash and store the digest of the message.
Test your inputs on: http://www.blockchain-basics.com/HashFunctions.html

SHA-256 Algorithm

SHA-256 stands for Secure Hash Algorithm that generates a 256-bit digest of a
message. This is one of the most renowned hashing algorithms used by several
cryptocurrencies. Another popular application of this algorithm is Digital Signing
Verification.
Let’s dig into the steps to process a message using the SHA-256 Algorithm.

Step 1: Pad the message such that the length of the message
size is a multiple of 512.

Here, pad the message means adding some extra bits to the original message.
Therefore, the total length is exactly 64 bits less than a multiple of 512.
For instance, the length of message M is L. It means L+P+64 =n*512, where L is
the length of the message and P is padded bits.
Note: The bits padded to the message should start with ‘1’. And the rest bits must
be ‘0’ till we are exactly 64 bits less than the multiple of 512.

Step 2: Add length bits (Padding Length)

We padded bits to the original message in Step 1. Now, we can append the length
bits ie, expressed as 64 bits previously, to make it exactly equal to a multiple of
512.
To calculate the 64 bits, L(the original length of the message) mod 2³²
So, to get the entire message block, L+P+[L mod 2³²] = n*512

Step 3: Initialize Chaining Variable

The entire message is broken into n blocks of 512 bits. Such as M1, M2,
M3……….Mn.
We need a few buffer values to use further. These 0-63 hexadecimal values are
called Keys and are denoted by ‘k’ afterwards.

Step 4: Process each Block

The entire message is broken into n blocks of 512 bits.


Each 512-bit block is broken into 16 sub-blocks of 32 bits each.
There are 64 rounds of operations. And the output generated will be input to the
next round of operations.
The K[i] in all the rounds are already initialized. W[i] is calculated individually for
each block depending on the number of iterations processed.
The entire cycle repeats itself till it reaches ‘n’. The number of 512-bit blocks.
Finally, The last result will consider as SHA-256 digest.
Blockchain Merkle Trees


A hash tree is also known as Merkle Tree. It is a tree in which each leaf node is
labeled with the hash value of a data block and each non-leaf node is labeled with
the hash value of its child nodes labels. This article focuses on discussing the
following topics in detail:
What is a Cryptographic Hash?
What is Hash Pointer?
Blockchain Structure
Block Structure
Merkle Tree Structure
How Do Merkle Trees Work?
Why Merkle Trees are Important For Blockchain?
Proof of Membership
Merkle Proofs
Simple Payment Verification(SPV)
Advantages of Merkle Tree
Let’s discuss each of these topics in detail.
What is a Cryptographic Hash?

A cryptographic hash is a function that outputs a fixed-size digest for a variable-


length input. A hash function is an important cryptographic primitive and
extensively used in blockchain. For example, SHA-256 is a hash function in which
for any variable-bit length input, the output is always going to be a 256-bit hash.
From the above picture, it is clear that even the slightest change in an alphabet in
the input sentence can drastically change the hash obtained. Therefore hashes can
be used to verify integrity.
Consider there is a text file with important data. Pass the contents of the text file
into a hash function and then store the hash in the phone. A hacker manages to
open the text file and changes the data.
Now when you open the file again, you can compute the hash again and compare
this hash with the one stored previously on the phone.
It will be clearly evident that the two hashes do not match and hence the file has
been tampered with.
What is Hash Pointer?

A regular pointer stores the memory address of data. With this pointer, the data can
be accessed easily. On the other hand, a hash pointer is a pointer to where data is
stored and with the pointer, the cryptographic hash of the data is also stored. So a
hash pointer points to the data and also allows us to verify the data. A hash pointer
can be used to build all kinds of data structures such as blockchain and Merkle
tree.
Blockchain Structure

The blockchain is a proficient combination of two hash-based data structures-


1. Linked list: This is the structure of the blockchain itself, which is a linked list of
hash pointers. A regular linked list consists of nodes. Each node has 2 parts- data
and pointer. The pointer points to the next node. In the blockchain, simply
replace the regular pointer with a hash pointer.
2. Merkle tree: A Merkle tree is a binary tree formed by hash pointers, and named
after its creator, Ralph Merkle.
Blockchain as linked list with hash pointers

Block Structure

1. Block header: The header data contains metadata of the block, i.e
information about the block itself. The contents of the block header include-
Hash of the previous block header.
Hash of the current block.
Timestamp.
Cryptographic nonce.
Merkle root.
2. Merkle tree: A Merkle tree is a binary tree formed by hash pointers, and
named after its creator, Ralph Merkle.
As mentioned earlier, each block is supposed to hold a certain number of
transactions. Now the question arises, how to store these transactions within a
block? One approach can be to form a hash pointer-based linked list of transactions
and store this complete linked list in a block. However, when we put this approach
into perspective, it does not seem practical to store a huge list of hundreds of
transactions. What if there is a need to find whether a particular transaction belongs
to a block? Then we will have to traverse the blocks one by one and within each
block traverse the linked list of transactions.
This is a huge overhead and can reduce the efficiency of the blockchain. Now, this
is where the Merkle tree comes into the picture. Merkle tree is a per-block tree of
all the transactions that are included in the block. It allows us to have a hash/digest
of all transactions and provides proof of membership in a time-efficient manner.
So to recap, the blockchain is a hash-based linked list of blocks, where each block
consists of a header and transactions. The transactions are arranged in a tree-like
fashion, known as the Merkle tree.
Each block comprises of block header + Merkle tree

Merkle Tree Structure

Structure of Merkle tree


1. A blockchain can potentially have thousands of blocks with thousands of
transactions in each block. Therefore, memory space and computing power are two
main challenges.
2. It would be optimal to use as little data as possible for verifying transactions,
which can reduce CPU processing and provide better security, and this is exactly
what Merkle trees offer.
3. In a Merkle tree, transactions are grouped into pairs. The hash is computed for
each pair and this is stored in the parent node. Now the parent nodes are grouped
into pairs and their hash is stored one level up in the tree. This continues till the
root of the tree. The different types of nodes in a Merkle tree are:
 Root node: The root of the Merkle tree is known as the Merkle root and this
Merkle root is stored in the header of the block.
 Leaf node: The leaf nodes contain the hash values of transaction data. Each
transaction in the block has its data hashed and then this hash value (also known
as transaction ID) is stored in leaf nodes.
 Non-leaf node: The non-leaf nodes contain the hash value of their
respective children. These are also called intermediate nodes because they
contain the intermediate hash values and the hash process continues till the root
of the tree.
4. Bitcoin uses the SHA-256 hash function to hash transaction data continuously
till the Merkle root is obtained.
0 seconds of 15 secondsVolume 0%is ad will end in 15
5. Further, a Merkle tree is binary in nature. This means that the number of leaf
nodes needs to be even for the Merkle tree to be constructed properly. In case
there is an odd number of leaf nodes, the tree duplicates the last hash and makes
the number of leaf nodes even.
How Do Merkle Trees Work?

 A Merkle tree is constructed from the leaf nodes level all the way up to the
Merkle root level by grouping nodes in pairs and calculating the hash of each
pair of nodes in that particular level. This hash value is propagated to the next
level. This is a bottom-to-up type of construction where the hash values are
flowing from down to up direction.
 Hence, by comparing the Merkle tree structure to a regular binary tree data
structure, one can observe that Merkle trees are actually inverted down.
Binary tree direction vs Merkle tree direction

 Example: Consider a block having 4 transactions- T1, T2, T3, T4. These four
transactions have to be stored in the Merkle tree and this is done by the
following steps-
 Step 1: The hash of each transaction is computed.
 H1 = Hash(T1).
 Step 2: The hashes computed are stored in leaf nodes of the Merkle tree.
 Step 3: Now non-leaf nodes will be formed. In order to form these nodes, leaf
nodes will be paired together from left to right, and the hash of these pairs will
be calculated. Firstly hash of H1 and H2 will be computed to form H12.
Similarly, H34 is computed. Values H12 and H34 are parent nodes of H1, H2,
and H3, H4 respectively. These are non-leaf nodes.
H12 = Hash(H1 + H2)
H34 = Hash(H3 + H4)
 Step 4: Finally H1234 is computed by pairing H12 and H34. H1234 is the only
hash remaining. This means we have reached the root node and therefore H1234
is the Merkle root.
H1234 = Hash(H12 + H34)
Merkle tree works by hashing child nodes again and again till only one hash remains.

Key Points:
 In order to check whether the transaction has tampered with the tree, there is
only a need to remember the root of the tree.
 One can access the transactions by traversing through the hash pointers and if
any content has been changed in the transaction, this will reflect on the hash
stored in the parent node, which in turn would affect the hash in the upper-level
node and so on until the root is reached.
 Hence the root of the Merkle tree has also changed. So Merkle root which is
stored in the block header makes transactions tamper-proof and validates the
integrity of data.
 With the help of the Merkle root, the Merkle tree helps in eliminating duplicate
or false transactions in a block.
 It generates a digital fingerprint of all transactions in a block and the Merkle root
in the header is further protected by the hash of the block header stored in the
next block.
Why Merkle Trees are Important For Blockchain?
 In a centralized network, data can be accessed from one single copy. This means
that nodes do not have to take the responsibility of storing their own copies of
data and data can be retrieved quickly.
 However, the situation is not so simple in a distributed system.
 Let us consider a scenario where blockchain does not have Merkle trees. In this
case, every node in the network will have to keep a record of every single
transaction that has occurred because there is no central copy of the information.
 This means that a huge amount of information will have to be stored on every
node and every node will have its own copy of the ledger. If a node wants to
validate a past transaction, requests will have to be sent to all nodes, requesting
their copy of the ledger. Then the user will have to compare its own copy with
the copies obtained from several nodes.
 Any mismatch could compromise the security of the blockchain. Further on,
such verification requests will require huge amounts of data to be sent over the
network, and the computer performing this verification will need a lot of
processing power for comparing different versions of ledgers.
 Without the Merkle tree, the data itself has to be transferred all over the
network for verification.
 Merkle trees allow comparison and verification of transactions with viable
computational power and bandwidth. Only a small amount of information
needs to be sent, hence compensating for the huge volumes of ledger data that
had to be exchanged previously.
 Merkle trees use a one-way hash function extensively and this hashing separates
the proof of data from data itself
Proof of Membership

 A very interesting feature of the Merkle tree is that it provides proof of


membership.
 Example: A miner wants to prove that a particular transaction belongs to a
Merkle tree Now the miner needs to present this transaction and all the nodes
which lie on the path between the transaction and the root. The rest of the tree
can be ignored because the hashes stored in the intermediate nodes are enough
to verify the hashes all the way up to the root.
Proof of membership: verifying the presence of transactions in blocks using the Merkle tree.

 If there are n nodes in the tree then only log(n) nodes need to be examined.
Hence even if there are a large number of nodes in the Merkle tree, proof of
membership can be computed in a relatively short time.
Merkle Proofs
 A Merkle proof is used to decide:
 If data belongs to a particular Merkle tree.
 To prove data belongs to a set without the need to store the whole set.
 To prove a certain data is included in a larger data set without revealing the
larger data set or its subsets.
 Merkle proofs are established by hashing a hash’s corresponding hash together
and climbing up the tree until you obtain the root hash which is or can be
publicly known.
 Consider the Merkle tree given below:
 Let us say we need to prove that transaction ‘a’ is part of this Merkle tree.
Everyone in the network will be aware of the hash function used by all Merkle
trees.
 H(a) = Ha as per the diagram.
 The hash of Ha and Hb will be Hab, which will be stored in an upper-level node.
 Finally hash of Hab and Hcd will give Habcd. This is the Merkle root obtained
by us.
 By comparing the obtained Merkle root and the Merkle root already available
within the block header, we can verify the presence of transaction ‘a’ in this
block.
 From the above example, it is clear that in order to verify the presence of ‘a’, ‘a’
does not have to be revealed nor do ‘b’, ‘c’, ‘d’ have to be revealed, only their
hashes are sufficient. Therefore Merkle proof provides an efficient and simple
method of verifying inclusivity, and is synonymous with “proof of inclusion”.
A sorted Merkle tree is a tree where all the data blocks are ordered using an
ordering function. This ordering can be alphabetical, lexicographical, numerical,
etc.
Proof of Non-Membership:
 It is also possible to test non-membership in logarithmic time and space using a
sorted Merkle tree. That is, it is possible to show that a given transaction does
not belong in the Merkle tree.
 This can be done by displaying a path to the transaction that is immediately
before the transaction in question, as well as a path to the item that is
immediately following it.
 If these two elements in the tree are sequential, this proves that the item in issue
is not included or else it would have to go between the two things shown if it
was included, but there is no room between them because they are sequential.
Coinbase Transaction:
 A coinbase transaction is a unique Bitcoin transaction that is included in the
Merkle tree of every block in the blockchain. It is responsible for creating new
coins and also consists of a coinbase parameter that can be used by miners to
insert arbitrary data into the blockchain.
Simple Payment Verification(SPV)
 SPV makes it extremely easy for a client to verify whether a particular
transaction exists in a block and is valid without having to download the
entire blockchain. The users will only require a copy of the block headers of
the longest chain.
 This copy of headers is stored in the SPV wallet and this wallet uses the SPV
client to link a transaction to a Merkle branch in a block. SPV client
requests proof of inclusion(Merkle proof), in the form of a Merkle branch. The
fact that the transaction can be linked to a Merkle branch is proof that the
transaction exists.
 Now by assessing the blocks which are being mined on top of the transaction’s
block, the client can also conclude that majority of the nodes have built more
blocks on top of this chain by using consensus mechanisms like Proof of Work,
and hence this is the longest, valid blockchain.
Advantages of Merkle Tree
1. Efficient verification: Merkle trees offer efficient verification of integrity and
validity of data and significantly reduce the amount of memory required for
verification. The proof of verification does not require a huge amount of data to
be transmitted across the blockchain network. Enable trustless transfer of
cryptocurrency in the peer-to-peer, distributed system by the quick verification of
transactions.
2. No delay: There is no delay in the transfer of data across the network. Merkle
trees are extensively used in computations that maintain the functioning of
cryptocurrencies.
3. Less disk space: Merkle trees occupy less disk space when compared to other
data structures.
4. Unaltered transfer of data: Merkle root helps in making sure that the blocks
sent across the network are whole and unaltered.
5. Tampering Detection: Merkle tree gives an amazing advantage to miners to
check whether any transactions have been tampered with.
 Since the transactions are stored in a Merkle tree which stores the hash of
each node in the upper parent node, any changes in the details of the
transaction such as the amount to be debited or the address to whom the
payment must be made, then the change will propagate to the hashes in upper
levels and finally to the Merkle root.
 The miner can compare the Merkle root in the header with the Merkle root
stored in the data part of a block and can easily detect this tampering.
6. Time Complexity: Merkle tree is the best solution if a comparison is done
between the time complexity of searching a transaction in a block as a Merkle
tree and another block that has transactions arranged in a linked list, then-
 Merkle Tree search: O(logn), where n is the number of transactions in a
block.
 Linked List search: O(n), where n is the number of transactions in a block.

You might also like