Cwe Unit 2 (Part 1)
Cwe Unit 2 (Part 1)
CREATION OF COINS
A cryptocurrency is a digital currency, which uses cryptography for secure transactions. It is designed
to act as a medium of exchange on a computer network without relying on a central authority such as
a government or a bank to manage it. Since cryptocurrencies have no central issuing or regulatory
authority, they use a decentralized system to record transactions and issue new units. Cryptocurrency
uses blockchain technology. Cryptocurrency units are created through a process called mining, which
uses computer hardware to solve complex mathematical problems that produce coins. There are many
cryptocurrencies in the market like Dogecoin, Bitcoin, and many more.
Cryptocurrencies are broadly divided into two groups – coins and tokens. A coin is a cryptocurrency
application that runs on its own blockchain, where all transactions take place. Tokens, on the other
hand, work on existing blockchain infrastructure and are typically used for physical objects like smart
contracts. digital services, etc.
S
Coins Tokens
No.
Due to the creation of a new blockchain, the Creating tokens is faster and
3.
investment can be significant. cheaper.
1. Choose a Consensus Mechanism: Consensus mechanisms are the protocols that consider a
particular transaction legitimate and add to the block.
2. Pick a Blockchain Platform: Choosing the right blockchain platform for your business depends on
the consensus mechanism you choose.
3. Design The Nodes: You need to determine how your blockchain will work and function, and design
your nodes accordingly.
4. Establish Blockchain’s Internal Architecture: Set up the internal architecture of the blockchain. Be
sure about all the aspects before the launch as you won’t be able to change several parameters of the
blockchain after it’s launched and running.
5. Integrate APIs: Some platforms don’t offer pre-built APIs. Don’t worry, there are several third-party
blockchain API providers like ChromaWay, Gem, Colu, BlockCypher, etc.
6. Designing the UI: Building a top-notch cryptocurrency is useless if your UI is bad. You need to ensure
that the web, FTP server, and external databases are up-to-date and that front-end and back-end
programming is done with future upgrades in mind.
7. Legalize your cryptocurrency: Make sure your cryptocurrency is ready and compliant with upcoming
international cryptocurrency regulations. That way, your work is preserved, and no sudden surprises
can sabotage your efforts to create a new cryptocurrency.
Cryptocurrency miners need money. They receive a small fraction of new units of cryptocurrency for
completing “blocks” of verified transactions that are added to the blockchain.
• Miners are paid in the cryptocurrency they wish to mine.
• So when miners decide to decrypt a block of bitcoins, they get paid in bitcoins.
• By pooling resources, miners increase their chances of success and share the cost, but only
receive a portion of the reward. This is known as a Cryptocurrency mining reward.
Pricing Cryptocurrencies
To understand cryptocurrency pricing, let’s take the most famous example of Bitcoin.
• Like most other commodities in the market, the price of Bitcoin is determined by the
interaction of supply and demand and expectations of future prices.
• For cryptocurrencies, pricing is entirely based on market dynamics.
• If the market believes that the price of Bitcoin will rise in the future, they will now be more
people who are ready to pay more for it.
• On the other hand, if the market believes that the price will fall in the future, there will be
more people selling cryptocurrencies now, and the price will be higher than at the future
level.
• When selling, there are many people who accept lower prices than usual and expect lower
prices in the future.
• Many Individual influencers can also significantly influence the price of cryptocurrencies.
Bitcoin Halving
The reward for mining, i.e. the amount of bitcoins a miner earns through successful authentication, is
fixed. However, this reward is numerically halved every four years. So, when Bitcoin was introduced,
miners could earn 50 BTC as a reward for successfully processing a block. This is called the Bitcoin
halving. After the first halving, this number was reduced to 25, followed by 12.5, and the last halving
as of 2020, which is currently 6.25. The next halving is planned for 2024.
Advantages of Cryptocurrency
Disadvantages of Cryptocurrency
1. Decentralized but still operated by some organizations: Cryptocurrencies are known for
their decentralized nature. However, the circulation and quantity of some currencies in
the market are still controlled by their creators and some organizations.
2. Can be used for illegal transactions: Due to the high privacy and security of
cryptocurrency transactions, it is difficult for governments to track users by wallet address
or track their details. Bitcoin has historically been used as a currency exchange for many
illegal businesses, such as buying drugs on the dark web.
3. Data losses can cause financial losses: Developers want to create virtually untraceable
source code, strong protection from hackers, and authentication protocols that are hard
to penetrate. This makes investing in cryptocurrencies safer than investing in physical
cash or bank vaults. However, if the user loses the wallet’s private key, it cannot be
retrieved. The wallet remains locked along with the number of coins in it. This will bring
financial losses to users.
4. Cryptocurrencies are highly volatile: Cryptocurrency markets are volatile and fluctuate
frequently, even for famous cryptocurrencies like Bitcoin. Investing in cryptocurrencies is
risky because you never know if it will be a profitable investment or not.
5. Cryptocurrencies Transactions are irreversible: If you enter an incorrect cryptocurrency
address then there is no way to reverse a transaction.
6. Cryptocurrency storage:- If the user loses the wallet’s private key, it cannot be
retrieved. The wallet remains locked along with the number of coins inside. This will result
in the financial loss of the user.
BITCOIN WALLETS
• A Bitcoin wallet is a digital tool that facilitates secure storage, sending, and receiving of
bitcoins.
• Wallets are secured through private and public keys.
• Both software (hot) and hardware (cold) wallets are available.
• Selecting an appropriate Bitcoin wallet involves considering factors like security, user-
friendliness, compatibility, and reputation, with hardware wallets generally seen as the most
secure option.
• Implementing strong passwords, enabling two-factor authentication (2FA), updating software
regularly, and creating backups are crucial security measures to protect Bitcoin wallets.
A Bitcoin wallet is a digital tool that allows users to securely store, send, and receive Bitcoin, the
world’s most popular cryptocurrency. Essentially, it is a software programme that interacts with the
Bitcoin blockchain, enabling users to manage their Bitcoin holdings. Unlike traditional wallets that
hold physical currency, Bitcoin wallets store a user’s private and public keys, which are essential for
conducting transactions on the blockchain.
In general, wallets that store Bitcoin also store many other cryptocurrencies. Bitcoin wallets come in
various forms, including software and hardware wallets.
Each type has its own advantages and disadvantages, and choosing the right one depends on a user’s
specific needs and preferences. Regardless of the type, all Bitcoin wallets function on the same basic
principles of encryption and blockchain technology.
These are apps that allow holders to manage their Bitcoin on the go. Known as ‘hot wallets’, since
they are connected to the internet, these wallets are convenient and easy to use but carry potential
risks since computer networks have hidden vulnerabilities that can be targeted by hackers or
malware programmes to break into the system. A popular and secure software wallet is
the Crypto.com DeFi Wallet.
Considered the most secure option, hardware wallets store a user’s private keys offline on a physical
device, offering protection against malware and hacking attempts compared to hot wallets. As these
devices keep a user’s Bitcoin offline, they are considered ‘cold wallets’. Popular cold wallets include
Trezor, Ledger, and KeepKey.
Custodial wallets
Typically offered on cryptocurrency exchanges, custodial wallets are known for their convenience
and ease of use, and are especially popular with newcomers, as well as experienced day traders. The
main difference between custodial and other wallets is that users are no longer in full control of
their tokens, and the private keys needed to sign for transactions are held only by the exchange.
The implication here is that users must trust the service provider to securely store their tokens and
implement strong security measures to prevent unauthorised access. These measures include two-
factor authentication (2FA), email confirmation, and biometric authentication.
Reputable cryptocurrency exchanges also take further steps to ensure the safety of users’ tokens. For
example, a portion of the funds is generally transferred to the company’s cold wallet, safe from
online attackers.
Non-custodial wallets
Non-custodial wallets, on the other hand, allow a user to retain full control of their funds, since the
private key is stored locally with the user.
When starting a non-custodial wallet, the user is asked to write down and safely store a list of 12
randomly generated words, known as a ‘recovery’, ‘seed’, or ‘mnemonic’ phrase. From this phrase,
the user’s public and private keys can be generated. This acts as a backup or recovery mechanism in
case the user loses access to their device.
A main pro of non-custodial wallets is that the private keys and funds are fully in the user’s control.
As the popular saying within the crypto community goes, ‘not your keys, not your coins!’.
On the flip side, this means that users must be in charge of their own security with regard to the
storage of passwords and seed phrases. Anyone with the seed phrase is able to gain full control of
the funds held in that wallet. In a case scenario where the seed phrase is lost, the user also loses
access to their funds.
Note that hardware wallets are inherently non-custodial, since private keys are stored on the device
itself. There are also software-based non-custodial wallets, such as the Crypto.com DeFi Wallet.
Choosing a Bitcoin Wallet
Selecting the appropriate Bitcoin wallet requires careful consideration of several factors. Below are a
few key points to keep in mind:
Security
Security should be a user’s top priority when choosing a Bitcoin wallet. Look for wallets that offer
features like two-factor authentication (2FA), encryption, and backup options. Hardware wallets are
generally considered the most secure option.
User-friendliness
Consider how user-friendly the wallet is, especially for those new to Bitcoin. Look for wallets with
intuitive interfaces and clear instructions for setting up and using the wallet.
Intended use
For users making frequent trades, a hot wallet is more convenient, as it stays connected to the
internet. For HODLers of Bitcoin holding for the long term, a cold wallet might be the better choice to
keep their cryptocurrency securely tucked away.
Reputation
Research the reputation of the wallet provider to ensure it has a history of security and positive user
reviews. Look for wallets that have been around for a while and have a large user base.
Create a unique and complex password. Avoid using easily guessable passwords or reusing
passwords from other accounts.
2FA adds an extra layer of security by requiring the user to provide a second verification to access
their wallet, such as a fingerprint scan or a code sent to their mobile device.
Holders should regularly update their Bitcoin wallet software to ensure they have the latest security
patches. Outdated software may contain vulnerabilities that can be exploited by hackers.
Create regular backups for the wallet and store them in secure locations, such as encrypted USB
drives or offline storage devices. This helps ensure recovery of funds in case of theft, loss, or
hardware failure.
Users should be aware of suspicious emails, websites, or links that may try tricking them into
revealing their wallet’s private keys or login credentials. Always verify the authenticity of the source
before providing any sensitive information. Take a look at this list of scams to watch out for.
Setting up a Bitcoin wallet is a straightforward process. Below is a general guideline to get started:
1. Choose the type of wallet: Determine which type of Bitcoin wallet adheres to your
preferences like security, convenience, and intended use.
2. Research wallet options: Explore different wallet providers and compare their features,
reputation, and user reviews. Look for wallets that align with appropriate security
requirements and have positive feedback from the community.
3. Download or access the wallet: Once a wallet is chosen, download the app (for hot wallets).
4. Set up the wallet: Follow the instructions provided by the wallet provider to set the wallet up.
This typically involves creating a password, knowing KYC procedures, and generating a wallet
address.
5. Secure the wallet: Implement the security measures discussed earlier, such as enabling 2FA,
backing the wallet up, and keeping software up to date.
Once the Bitcoin wallet is set up and secured, users are ready to securely send, receive, and store
Bitcoin.
A Bitcoin wallet address is a unique identifier that allows individuals or entities to send Bitcoin to
others’ wallets, similar to sending money to a bank account. Below is how users can create a Bitcoin
wallet address:
1. Open the Bitcoin wallet: Launch the Bitcoin wallet software or app and navigate to the
‘Receive’ or ‘Receive Bitcoin’ section.
2. Generate a new address: Click on the ‘Generate New Address’ or similar option to create a
new Bitcoin wallet address. The wallet will automatically generate a unique address.
3. Copy the address: Once the address is generated, copy it to the clipboard or share it with
others using the provided options. Make sure to double-check the address to avoid any
mistakes.
4. Use the address to receive Bitcoin: Share the Bitcoin wallet address with the person or entity
who wants to send Bitcoin. They can then use this address to initiate the transaction.
Remember to generate a new address for each transaction to enhance privacy and security.
Hardware wallets are physical devices that need to be safely and correctly stored, and both software
and hardware wallets require passwords and seed phrases. Below are tips on how to store this
information safely.
Hardware wallets
Consider using a hardware wallet for long-term Bitcoin storage. Hardware wallets store a user’s
private keys offline, making them less vulnerable to hacking or malware attacks. Keep the hardware
wallet in a safe place and ensure it is protected from physical damage.
Backing up wallets
Create regular backups of the wallet and store them securely. This ensures that even if a holder’s
device is lost, stolen, or damaged, they can still recover their funds. Encrypt the backup files and keep
them in multiple secure locations.
When accessing the Bitcoin wallet, ensure it is a secure and trusted computer or mobile device.
Avoid using public or shared devices that may be compromised.
Keep private keys offline
Never store private keys or wallet recovery phrases on any online platform or in digital format. Write
them down on paper and keep them in a secure location, such as a safe deposit box or a fireproof
safe.
By following these storage practices, holders can protect their Bitcoin wallet from unauthorised
access and potential loss.
GENESIS BLOCK
In proof-of-work (PoW) chains, the genesis block is the first block ever mined on a blockchain network
and serves as the foundation for all blocks that follow. It is typically hard-coded into the protocol and
created by the creator of the blockchain. Since there are no previous blocks to reference or mine
against, it doesn’t involve the traditional mining process.
In contrast, the genesis block is usually created by the network’s developers and/or validators who
initiate the PoS chain. Validators might be selected based on specific criteria outlined in the protocol
rather than through the staking process since there are no previous transactions or stakes to
reference.
The origin of the genesis block dates back to the launch of the Bitcoin network in 2009. Bitcoin’s
pseudonymous creator, Satoshi Nakamoto, generated the first block on the chain that became the
world’s most valuable cryptocurrency with the highest market capitalization, even briefly surpassing
the market cap of silver. This established the genesis block as an integral part of launching a
functional, decentralized blockchain ledger.
The core purpose of the genesis block is to initialize the blockchain by cryptographically linking to the
blocks that follow it. It is the starting point that anchors the blockchain and enables trust in the
immutable ledger. The genesis block sets initial parameters, such as mining difficulty and block
rewards, that govern the network’s operation and incentive structure. Without the genesis block
providing this foundation, the blockchain would not have a secure and reliable beginning to build
upon.
All cryptocurrency networks require a genesis block to start their ledger. For example, Ethereum’s
genesis block contains instructions for initial Ether (ETH) allocation and core network parameters.
The genesis block provides a starting point upon which the rest of the ever-growing blockchain can
build. Without the genesis block, a blockchain would have no foundation to permanently record
transactions through cryptographic hashes.
The genesis block in Bitcoin
Satoshi Nakamoto pioneered the genesis block to launch Bitcoin’s blockchain, establishing technical
attributes and an issuance model still followed by cryptocurrencies today.
The Bitcoin genesis block was mined on Jan. 3, 2009, and is famously known as block 0. It was created
by Satoshi Nakamoto as a way to launch the network and initiate the first cryptocurrency.
Nakamoto designed the Bitcoin genesis block to establish the core technical elements of the protocol
and set certain launch parameters.
The block contains a reference to the headline “The Times 03/Jan/2009 Chancellor on brink of second
bailout for banks,” which was published in the London-based newspaper The Times on Jan. 3, 2009.
By including this headline, Nakamoto timestamped the block and provided poetic context for Bitcoin’s
mission as a decentralized alternative to the traditional financial system.
The genesis block’s nonce field has a specific value of 2083236893, which was found by Satoshi
Nakamoto through a mining process to satisfy the difficulty target at the time of the Bitcoin network’s
launch. Although the difficulty was much lower compared to today’s standards, creating the genesis
block still involved varying the nonce value until a valid block hash meeting the target was discovered.
All subsequent blocks build on the hash of the genesis block, creating a chain linking each block to the
originating one.
One of Nakamoto’s most pivotal decisions was setting the mining reward for adding new blocks to the
blockchain. The genesis block includes a coinbase transaction that grants a 50-Bitcoin (BTC) reward,
establishing the Bitcoin issuance model. However, this particular reward is a special case and cannot
actually be spent due to the unique way the genesis block is hardcoded into the Bitcoin software. The
50-BTC reward sets a precedent for block rewards, which halve approximately every four years until
the total 21 million supply cap is reached.
The hardcoded design of the Bitcoin genesis block established the core technical and monetary
attributes of Bitcoin. As the first-ever block on the Bitcoin blockchain, it enabled the launch of the
network’s distributed ledger, setting the stage for innovation across blockchain technology,
cryptocurrency and finance.
Components and structure of the genesis block
The genesis block sets the foundation for the blockchain by establishing the format for data and
structure that all future blocks will follow.
The genesis block contains foundational data that sets the stage for the remainder of the blockchain.
This inaugural block is hardcoded with an index of 0 and establishes the structure that subsequent
blocks will follow.
The data embedded in the genesis block includes the timestamp, block hash, previous block hash,
nonce and block reward address. The timestamp represents when the block was created, while the
previous block hash is a series of zeros since no prior block exists.
In PoW blockchains like Bitcoin, the nonce is a value that is varied to find a valid block hash meeting
the network’s difficulty target. However, the significance and use of the nonce can vary across
different blockchain implementations, especially those that do not use PoW consensus. The block
reward address indicates where to send the block reward, although this functions differently in the
genesis block compared to subsequent blocks.
Notably, the concept of a block reward address is more nuanced in the genesis block, as it doesn’t
function in the traditional sense seen in subsequent blocks, especially in networks like Bitcoin, where
the genesis block’s reward is not spendable.
Additional genesis block events may designate initial conditions or distribute tokens. For example, the
Ethereum genesis block executed smart contracts that assigned the starting supply of ETH. It’s also
not uncommon for genesis blocks to carry encrypted messages or references, adding a symbolic or
commemorative layer to the block.
The genesis block’s structure contains a block header and body. The header includes metadata like
the version, timestamp, target difficulty, Merkle root hash (summarizing transactions) and nonce. The
body contains all transactions in that block, which is only the reward transaction for the genesis block
creator in newly launched networks.
This standard structure forms the template for the chronological sequence of blocks that follow. The
fixed composition of the genesis block establishes the blueprint for validating transactions, adding
new blocks, achieving consensus and growing the chain. This pioneering first block boots up the
blockchain’s functionality.
Events after the genesis block
The genesis block launches the network. Then confirmation, incentives and difficulty adjustments
enable decentralized propagation, consensus and mining to grow the blockchain.
Once the genesis block is established, the blockchain network can be formally launched. This
milestone opens participation to the public and kickstarts the process of consensus and
decentralization.
After launch, the blockchain begins building on top of the genesis block. As the inaugural block, the
genesis block is automatically accepted as valid by the network nodes, but it does not require
confirmations in the traditional sense that transactions or later blocks do. Subsequent blocks
reference the genesis block’s hash, establishing an unbroken chain linking back to the network’s origin
point.
With the genesis block confirmed, miners compete to add new blocks. As blocks get appended, more
confirmations accumulate for preceding blocks, hardening the permanence of the blockchain. New
coins are issued through block rewards, and transactions are validated.
The network difficulty adjusts dynamically based on activity to maintain the cadence of block
creation. More miners and higher participation increase competition and difficulty, while lower
activity decreases the difficulty target. This fluctuation ensures the blockchain’s self-regulation.
After the genesis block, the blockchain grows organically through decentralized propagation,
consensus mechanisms and incentivized mining. The activity solidifies the genesis block as the
immovable anchor point. Transactions multiply rapidly as adoption spreads.
In the case of cryptocurrency blockchains, value accrues as trust in the network takes hold. Coins gain
monetary value according to the market dynamics of supply and demand. Speculation, trading and
real-world utility drive investment and participation.
The genesis block thus graduates from its honorary position as the network activates. The launch it
facilitated gives rise to a bustling ecosystem governed by participants aligned in economic interest by
the blockchain’s incentive structures.
MERKEL TREE
Merkle tree is a fundamental part of blockchain technology. It is a mathematical data
structure composed of hashes of different blocks of data, and which serves as a summary of all the
transactions in a block. It also allows for efficient and secure verification of content in a large body of
data. It also helps to verify the consistency and content of the data. Both Bitcoin and Ethereum use
Merkle Trees structure. Merkle Tree is also known as Hash Tree.
The concept of Merkle Tree is named after Ralph Merkle, who patented the idea in 1979.
Fundamentally, it is a data structure tree in which every leaf node labelled with the hash of a data
block, and the non-leaf node labelled with the cryptographic hash of the labels of its child nodes. The
leaf nodes are the lowest node in the tree.
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.
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
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.
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.
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.
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
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.
1. H(a) = Ha as per the diagram.
2. The hash of Ha and Hb will be Hab, which will be stored in an upper-level node.
3. Finally hash of Hab and Hcd will give Habcd. This is the Merkle root obtained by us.
4. 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.
• 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.
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.
BITCOIN SCRIPTS
What Is Bitcoin Script?
Bitcoin Script serves as the scripting language behind Bitcoin transactions, allowing users to define
the conditions under which funds can be spent. Unlike traditional financial transactions, Bitcoin
transactions are not just about transferring value; they are also about executing specific conditions
encoded in scripts.
It operates by manipulating items on a stack, with various opcodes representing operations that can
be performed. This scripting language is deliberately limited and designed to be non-Turing complete
for security reasons, preventing potentially malicious or infinite loops from being executed on the
Bitcoin network.
Features
The Bitcoin script language has several characteristics and qualities, among which we can mention:
Stack-based Architecture
Bitcoin Script employs a stack-based architecture, where data is organized and processed using a Last-
In-First-Out (LIFO) structure. The stack serves as a temporary storage mechanism for operands and
results of operations, allowing the script to manipulate and operate on these values efficiently. As
transactions unfold, the stack dynamically changes, reflecting the state of the script's execution.
The scripting language is stack-based. This means that every instruction is executed exactly
once, in a linear manner. In particular, there are no loops in the Bitcoin scripting language.
So the number of instructions in the script gives us an upper bound on how long it might
take to run and how much memory it could use. The language is not Turing-complete, which
means that it doesn’t have the ability to compute arbitrarily powerful functions. And this is
by design — miners have to run these scripts, which are submitted by arbitrary participants
in the network. We don’t want to give them the power to submit a script that might have an
infinite loop.
<pubKeyHash?>
OP_EQUALVERIFY
OP_CHECKSIG
Figure 3.5. To check if a transaction correctly redeems an output, we create a combined script
by appending the scriptPubKey of the referenced output transaction (bottom) to the scriptSig
of the redeeming transaction (top). Notice that <pubKeyHash?> contains a ‘?’. We use this
notation to indicate that we will later check to confirm that this is equal to the hash of the
public key provided in the redeeming script.
OP_EQUALVERIFY Returns true if the inputs are equal. Returns false and marks the
transaction as invalid if they are unequal
OP_CHECKSIG Checks that the input signature is a valid signature using the input
public key for the hash of the current transaction
OP_CHECKMULTISIG Checks that the k signatures on the transaction are valid signatures
from
k of the specified public keys.
Executing a script
To execute a script in a stack-based programming language, all we’ll need is a stack that we
can push data to and pop data from. We won’t need any other memory or variables. That’s
what makes it so computationally simple. There are two types of instructions: data
instructions and opcodes. When a data instruction appears in a script, that data is simply
pushed onto the top of the stack. Opcodes, on the other hand, perform some function, often
taking as input data that is on top of the stack.
Now let’s look at how the Bitcoin script in Figure 3.5 is executed. Refer to Figure 3.7, where
we show the state of the stack after each instruction. The first two instructions in this script
are data instructions — the signature and the public key used to verify that signature —
specified in the scriptSig component of a transaction input in the redeeming transaction. As
we mentioned, when we see a data instruction, we just push it onto the stack. The rest of the
script was specified in the scriptPubKey component of a transaction output in the referenced
transaction.
First we have the duplicate instruction, OP_DUP, so we just push a copy of the public key onto
the top of the stack. The next instruction is OP_HASH160, which tells us to pop the top value,
compute its cryptographic hash, and push the result onto the top of the stack. When this
instruction finishes executing, we will have replaced the public key on the top of the stack
with its hash.
Figure 3.7 Execution of a Bitcoin script. On the bottom, we show the instruction in the script.
Data instructions are denoted with surrounding angle brackets, whereas opcodes begin with
“OP_”. On the top, we show the stack just after that instruction has been executed.
Next, we’re going to do one more push of data onto the stack. Recall that this data was
specified by the sender of the referenced transaction. It is the hash of a public key that the
sender specified; the corresponding private key must be used to generate the signature to
redeem these coins. At this point, there are two values at the top of the stack. There is the
hash of the public key, as specified by the sender, and the hash of the public key that was
used by the recipient when trying to claim the coins.
At this point we’ll run the EQUALVERIFY command, which checks that the two values at the top
of the stack are equal. If they aren’t, an error will be thrown, and the script will stop executing.
But in our example, we’ll assume that they’re equal, that is, that the recipient of the coins
used the correct public key. That instruction will consume those two data items that are at
the top of the stack, And the stack now contains two items — a signature and the public key.
We’ve already checked that this public key is in fact the public key that the referenced
transaction specified, and now we have to check if the signature is valid. This is a great
example of where the Bitcoin scripting language is built with cryptography in mind. Even
though it’s a fairly simple language in terms of logic, there are some quite powerful
instructions in there, like this “OP_CHECKSIG” instruction. This single instruction pops those
two values off of the stack, and does the entire signature verification in one go.
But what is this a signature of? What is the input to the signature function? It turns out there’s
only one thing you can sign in Bitcoin — an entire transaction. So the “CHECKSIG” instruction
pops the two values, the public key and signature, off the stack, and verifies that is a valid
signature for the entire transaction using that public key. Now we’ve executed every
instruction in the script, and there’s nothing left on the stack. Provided there weren’t any
errors, the output of this script will simply be true indicating that the transaction is valid.
What’s used in practice. In theory, Script lets us specify, in some sense, arbitrary conditions that
must be met in order to spend coins. But, as of today, this flexibility isn’t used very heavily. If we
look at the scripts that have actually been used in the history of Bitcoin so far, the vast majority,
99.9 percent, are
exactly the same script, which is in fact the script that we used in our example. As we saw, this
script just specifies one public key and requires a signature for that public key in order to
spend the coins. There are a few other instructions that do get some use. MULTISIG gets used
a little bit as does a special type of script called Pay-to-Script-Hash which we’ll discuss shortly.
But other than that, there hasn’t been much diversity in terms of what scripts get used. This is
because Bitcoin nodes, by default, have a whitelist of standard scripts, and they refuse to
accept scripts that are not on the list. This doesn’t mean that those scripts can’t be used at all;
it just makes them harder to use. In fact this distinction is a very subtle point which we’ll
return to in a bit when we talk about the Bitcoin
peer-to-peer network.
Proof of burn. A proof-of-burn is a script that can never be redeemed. Sending coins to a
proof-of-burn script establishes that they have been destroyed since there’s no possible way
for them to be spent. One use of proof-of-burn is to bootstrap an alternative to Bitcoin by
forcing people to destroy Bitcoin in order to gain coins in the new system. We’ll discuss this in
more detail in Chapter
10. Proof-of-burn is quite simple to implement: the OP_RETURN opcode throws an error if it’s
ever reached. No matter what values you put before OP_RETURN, that instruction will get
executed eventually, in which case this script will return false.
Because the error is thrown, the data in the script that comes after OP_RETURN will not be
processed. So this is an opportunity for people to put arbitrary data in a script, and hence into
the block chain. If, for some reason, you want to write your name, or if you want to timestamp
and prove that you knew some data at a specific time, you can create a very low value
Bitcoin transaction. You can destroy a very small amount of currency, but you get to write
whatever you want into the block chain, which should be kept around forever.
Pay-to-script-hash. One consequence of the way that Bitcoin scripts works is that the sender
of coins has to specify the script exactly. But this can sometimes be quite a strange way of
doing things. Say, for example, you’re a consumer shopping online, and you’re about to order
something. And you say, “Alright, I’m ready to pay. Tell me the address to which I should send
my coins.” Now, say that the company that you’re ordering from is using MULTISIG addresses.
Then, since the one spending the coins has to specify this, the retailer will have to come back
and say, “Oh, well, we’re doing something fancy now. We’re using MULTISIG. We’re going to
ask you to send the coins to some complicated script.” You might say, “I don’t know how to
do that. That’s too complicated. As a consumer, I just want to send to a simple address.”
Bitcoin has a clever solution to this problem, and it applies to not just multi-sig addresses but
to any complicated condition governing when coins can be spent. Instead of telling the sender
“send your coins to the hash of this public key”, the receiver can instead tell the sender
“send your coins to the hash of this script. Impose the condition that to redeem those coins,
it is necessary to reveal the script that has the given hash, and further, provide data that will
make the script evaluate to true.” The sender achieves this by using the Pay-to-script-hash
(P2SH) transaction type, which has the above semantics.
Specifically, the P2SH script simply hashes the top value on the stack, checks if it matches the
provided hash value, then executes a special second step of validation: that top data value
from the stack is reinterpreted as a sequence of instructions, and executed a second time as
a script, with the rest of the stack as input.
Getting support for P2SH was quite complicated since it wasn’t part of Bitcoin’s initial design
specification. It was added after the fact. This is probably the most notable feature that’s
been added to Bitcoin that wasn’t there in the original specification. And it solves a couple of
important problems. It removes complexity from the sender, so the recipient can just specify
a hash that the sender sends money to. In our example above, Alice need not worry that Bob
is using multisig; she just sends to Bob’s P2SH address, and it is Bob’s responsibility to specify
the fancy script when he wants to redeem the coins.
P2SH also has a nice efficiency gain. Miners have to track the set of output scripts that haven’t
been redeemed yet, and with P2SH outputs, the output scripts are now much smaller as they
only specify a hash. All of the complexity is pushed to the input scripts.
There are several Bitcoin Script types. Here are a few examples.
Pay-to-PubKey (P2PK)
• Sends bitcoins to a public key directly.
• ScriptPubKey: OP_CHECKSIG
• Usage: Early Bitcoin transactions.
Pay-to-PubKey-Hash (P2PKH)
• Sends bitcoins to a Bitcoin address (hash of a public key).
• ScriptPubKey: OP_DUP OP_HASH160 <PubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
• Usage: Standard transactions, most common script type.
Pay-to-Script-Hash (P2SH)
• Sends bitcoins to a script hash, enabling more complex transactions.
• ScriptPubKey: OP_HASH160 <ScriptHash> OP_EQUAL
• Usage: Multisig, escrow, and other complex transaction types.
Multisignature (Multisig)
• Requires multiple signatures to authorize spending.
• ScriptPubKey: OP_n <PubKey1> <PubKey2> ... <PubKeyN> OP_m OP_CHECKMULTISIG
• Usage: Joint accounts, corporate accounts.
Pay-to-Witness-PubKey-Hash (P2WPKH)
• Part of Segregated Witness (SegWit), sends to a hashed public key in witness data.
• ScriptPubKey: 0 <PubKeyHash>
• Usage: Reduces transaction size, lowers fees, improves scalability.
Pay-to-Witness-Script-Hash (P2WSH)
• Part of SegWit, sends to a script hash in witness data.
• ScriptPubKey: 0 <ScriptHash>
• Usage: Complex scripts and multisig transactions in SegWit format.
Pay-to-Taproot (P2TR)
• Part of the Taproot upgrade, enabling more privacy and complex scripts.
• ScriptPubKey: OP_1 <TaprootPubKey>
• Usage: Enhanced privacy, efficiency, and flexibility for smart contracts.
OP_RETURN
• Allows embedding data in the blockchain; marked as unspendable.
• ScriptPubKey: OP_RETURN <Data>
• Usage: Data storage, proof of existence, colored coins.
Now that we understand how Bitcoin scripts work, let’s take a look at some of the powerful
applications that can be realized with this scripting language. It turns out we can do many neat
things that will justify the complexity of having the scripting language instead of just
specifying public keys.
• Escrow transactions. Say Alice and Bob want to do business with each other — Alice
wants to pay Bob in Bitcoin for Bob to send some physical goods to Alice. The problem
though is that Alice doesn’t want to pay until after she’s received the goods, but Bob
doesn’t want to send the goods until after he has been paid. What can we do about
that? A nice solution in Bitcoin that’s been used in practice is to introduce a third party
and do an escrow transaction.
Escrow transactions can be implemented quite simply using MULTISIG. Alice doesn’t send the
money directly to Bob, but instead creates a MULTISIG transaction that requires two of
three people to sign in order to redeem the coins. And those three people are going to be
Alice, Bob, and some third party arbitrator, Judy, who will come into play in case there’s any
dispute. So Alice creates a 2-of-3 MULTISIG transaction that sends some coins she owns and
specifies that they can be spent if any two of Alice, Bob, and Judy sign. This transaction is
included in the block chain, and at this point, these coins are held in escrow between Alice,
Bob, and Judy, such that any two of them can specify where the coins should go. At this point,
Bob is convinced that it’s safe to send the goods over to Alice, so he’ll mail them or deliver
them physically. Now in the normal case, Alice and Bob are both honest. So, Bob will send over
the goods that Alice is expecting, and when Alice receives the goods, Alice and Bob both sign a
transaction redeeming the funds from escrow, and sending them to Bob. Notice that in this
case where both Alice and Bob are honest, Judy never had to get involved at all. There was no
dispute, and Alice’s and Bob’s signatures met the 2-of-3 requirement of the MULTISIG
transaction. So in the normal case, this isn’t that much less efficient than Alice just sending Bob
the money. It requires just one extra transaction on the block chain.
But what would have happened if Bob didn’t actually send the goods or they got lost in the
mail? Or perhaps the goods were different than what Alice ordered? Alice now doesn’t want
to pay Bob because she thinks that she got cheated, and she wants to get her money back.
So Alice is definitely not going to sign a transaction that releases the money to Bob. But Bob
also may deny any wrongdoing and refuse to sign a transaction that releases the money back
to Alice. This is where Judy needs to get involved. Judy’s going to have to decide which of
these two people deserves the money. If Judy decides that Bob cheated, Judy will be willing to
sign a transaction along with Alice, sending the money from escrow back to Alice. Alice’s and
Judy’s signatures meet the 2-of-3 requirement of the MULTISIG transaction, and Alice will get
her money back. And, of course, if Judy thinks that Alice is at fault here, and Alice is simply
refusing to pay when she should, Judy can sign a transaction along with Bob, sending the
money to Bob. So Judy decides between the two possible outcomes. But the nice thing is that
she won’t have to be involved unless there’s a dispute.
• Green addresses.
• Efficient micro-payments
• Smart contracts
Understanding OP_CODE
• At the heart of Bitcoin Script are operation codes, commonly known as OP_CODES. These are
the basic building blocks of a script, instructing the network on how to process transactions.
• Each OP_CODE represents a specific operation, ranging from mathematical calculations to
data manipulation and transaction validation.
• They are the equivalent of verbs in a programming language, defining actions that manipulate
the stack during the execution of a script.
• Understanding OP_CODES is crucial because they define the conditions under which a
transaction is considered valid and can be added to the blockchain.
Overview Of Common Opcodes in Bitcoin Script
The following section delves into common OP_CODES in Bitcoin Script, shedding light on their
functions and significance in transaction processing.
• OP_ADD: Pops two items off the stack, adds them together, and pushes the result back onto
the stack.
• OP_EQUAL: Pops two items from the stack and compares them to check if they are equal. if
they are equal, then it pushes the result TRUE back onto the stack.
• OP_RETURN: Can be used to store up to 80 bytes of arbitrary data on the Bitcoin blockchain
and also to mark a transaction output as invalid. OP_RETURN transaction outputs are provably
unspendable, making this opcode an efficient way to burn BTC. It also makes
Komodo's delayed Proof of Work (dPoW) security mechanism possible.
• OP_CHECKSIG: Verifies that the signature for a transaction input is valid.
• OP_CHECKMULTISIG: Commonly used in Pay To Script Hash
(P2SH) transactions. OP_CHECKMULTISIG looks at 3 public keys and 2 signatures in the stack
and compares them one-by-one. Funds become spendable only when the order of the
signatures matches the order in which the public keys were provided.
BITCOIN TRANSACTIONS
Bitcoin is basically a digital currency that is currently used as a form of payment. Bitcoin is a
cryptocurrency and the transactions related to bitcoins take place in the blockchain network.
Every bitcoin is stored in a virtual wallet and transaction involves the transfer of bitcoin from
one wallet to another. Bitcoins can be sent from peer to peer irrespective of geographical
location without any intermediator in between(for example bank per se). it works in a
decentralized way, meaning nobody can interfere with your digital money, only you are
responsible for your bitcoins.
Bitcoin Transaction
Bitcoin transaction means sending bitcoin from one person to the other in the secured
blockchain network. These are messages that are digitally signed using cryptography and are
verified by the miners that are present in the blockchain network. The miner is the person
who solves mathematical puzzles(also called proof of work) to validate the transaction.
Anyone with mining hardware and high processing power can take part in this. Numerous
miners take part simultaneously to solve the complex mathematical puzzle, the one who
solves it first, wins 12.5 bitcoin as a reward. miner verifies the transactions(after solving the
puzzle) and then adds the block to the blockchain when confirmed. The transaction input is
the bitcoin address from which the money was sent, and the transaction output is the
bitcoin address to which the money was sent. Generally, a bitcoin transaction takes 10 to 20
minutes to confirm any transactions. if network congestion takes place, then time might take
even 60 minutes.
Transaction Fees
The transaction rate or speed is dependent on the amount the user pays for it. If a user pays
a small amount, the transaction rate will be slow, the transaction will take more time to
happen, vice versa is applicable here. Due to limited space, only a limited number of
transactions are possible at one point in time.
Consider a case where heavy network traffic occurs, then the miners prioritize those
transactions that have the highest fees so that even in the hectic congestion, the highest-
paid transaction gets executed.
Many bitcoin wallets allow users to set transaction fees manually. The fees are directly sent
to the miners. When the bitcoin hits a bull run, the transaction fees shoot up to an all-time
high. there is no such minimum transaction fee a user must pay, but the highest transaction
fees mainly lie between $24 to $31. as the highest-paid transaction gets confirmed first,
therefore the fees tend to fluctuate based on the demand of the user.
• Transaction fees: As discussed above, if the user pays minimal transaction fees, then
the time taken for confirmation of a particular transaction would take a longer time.
the mining process needs significant technology and efforts, therefore the importance
of transaction fees comes into play.
• Network load: Every transaction gets stored temporarily in the memory pool till the
miners confirm it. When the transaction activities reach a certain high threshold, the
memory pool gets jammed thereby slowing the confirmation time of the transaction
even more. Due to this, all the subsequent transactions become susceptible to delay.
Sending or exchanging bitcoins undergoes lots of procedures underneath. The bitcoin wallet
and the network ensures that the digital currency reaches the receiver properly. There are
two basic terminologies related to this-
• Public key: Also known as a bitcoin address, these are publicly known to all like your
username in social media handles. In order to receive bitcoins, the user must share his
public key with the other user.
• Private key: These are kept secret and must not be shared with anyone, similar to the
user’s password of social media accounts. Private keys are the most important thing in
the whole cryptocurrency concept. The private key allows the user to have access to
bitcoins, if the user forgets the private keys, there’s no way to recover the bitcoins or
the private key. Therefore, it is advised to make a proper backup of the private key in
a safe place.
Transaction input is nothing but the address of the sender which gets registered in the
network and remains in an encrypted and inaccessible state. Transaction output is the
receiver’s address which is registered on the bitcoin network.
Example- Hari opens his bitcoin account and signs a transaction detail with his private key,
and then broadcasted to a bitcoin network called blockchain, where miners compete with
each other to find a hash value called nonce which solves the mathematical puzzle thereby
verifying the transaction. The miners create new blocks by abiding by the fact that the
transaction volume must be less than 21 million. 21 million is the total number of bitcoins
that can be generated. The verified transaction gets a unique identification code and is
linked with the previous verified transaction.
In the bitcoin network, every transaction is traceable via linked blocks. Anyone can
understand who sent it to who at any point in time. thus, bitcoin works in a transparent
manner.
How To Send Bitcoin
• In order to send or receive bitcoins, one must possess a bitcoin wallet application.
• After installing the bitcoin wallet app, select the type of currency you want to send. For
example ethereum, bitcoin, etc.
• Write in the receiver’s address.
• Type the amount of bitcoin you wish to send.
• Pay the required transaction fee.
• Press the “send bitcoin” button and the cryptocurrency will be transferred.
How to Receive Bitcoin?
In order to receive bitcoins, do the following steps:
Let’s start with transactions, Bitcoin’s fundamental building block. We’re going to use a
simplified model of a ledger for the moment. Instead of blocks, let’s suppose individual
transactions are added to the ledger one at a time.
Figure 3.1 an account-based ledger
How can we build a currency on top of such a ledger? The first model you might think of,
which is actually the mental model many people have for how Bitcoin works, is that you have
an
account-based system. You can add some transactions that create new coins and credit them
to somebody. And then later you can transfer them. A transaction would say something like
“we’re moving 17 coins from Alice to Bob”, and it will be signed by Alice. That’s all the
information about the transaction that’s contained in the ledger. In Figure 3.1, after Alice
receives 25 coins in the first transaction and then transfers 17 coins to Bob in the second,
she’d have 8 Bitcoins left in her account.
The downside to this way of doing things is that anyone who wants to determine if a
transaction is valid will have to keep track of these account balances. Take another look at
Figure 3.1. Does Alice have the 15 coins that she’s trying to transfer to David? To figure this
out, you’d have to look backwards in time forever to see every transaction affecting Alice,
and whether or not her net balance at the time that she tries to transfer 15 coins to David is
greater than 15 coins. Of course we can make this a little bit more efficient with some data
structures that track Alice’s balance after each transaction. But that’s going to require a lot of
extra housekeeping besides the ledger itself.
Because of these downsides, Bitcoin doesn’t use an account-based model. Instead, Bitcoin
uses a ledger that just keeps track of transactions similar to ScroogeCoin in Chapter 1.
Figure 3.2 a transaction-based ledger, which is very close to Bitcoin
Let’s now work our way through Figure 3.2. Transaction 1 has no inputs because this
transaction is creating new coins, and it has an output of 25 coins going to Alice. Also, since
this is a transaction where new coins are being created, no signature is required. Now let’s say
that Alice wants to send some of those coins over to Bob. To do so, she creates a new
transaction, transaction 2 in our example. In the transaction, she has to explicitly refer to the
previous transaction where these coins are coming from. Here, she refers to output 0 of
transaction 1 (indeed the only output of transaction 1), which assigned 25 bitcoins to Alice.
She also must specify the output addresses in the transaction.
In this example, Alice specifies two outputs, 17 coins to Bob, and 8 coins to Alice. And, of
course, this whole thing is signed by Alice, so that we know that Alice actually authorizes this
transaction.
Change addresses. Why does Alice have to send money to herself in this example? Just as
coins in ScroogeCoin are immutable, in Bitcoin, the entirety of a transaction output must be
consumed by another transaction, or none of it. Alice only wants to pay 17 bitcoins to Bob,
but the output that she owns is worth 25 bitcoins. So she needs to create a new output where
8 bitcoins are sent back to herself. It could be a different address from the one that owned
the 25 bitcoins, but it would have to be owned by her. This is called a change address.
Efficient verification. When a new transaction is added to the ledger, how easy is it to check if
it is valid? In this example, we need to look up the transaction output that Alice
referenced, make sure that it has a value of 25 bitcoins, and that it hasn’t already been spent.
Looking up the transaction output is easy since we’re using hash pointers. To ensure it hasn’t
been spent, we need to scan the block chain between the referenced transaction and the
latest block. We don’t need to go all the way back to the beginning of the block chain, and it
doesn’t require keeping any additional data structures (although, as we’ll see, additional data
structures will speed things up).
Consolidating funds. As in ScroogeCoin, since transactions can have many inputs and many
outputs, splitting and merging value is easy. For example, say Bob received money in two
different transactions
— 17 bitcoins in one, and 2 in another. Bob might say, I’d like to have one transaction I can
spend later where I have all 19 bitcoins. That’s easy — he creates a transaction with the two
inputs and one output, with the output address being one that he owns. That lets him
consolidate those two transactions.
Joint payments. Similarly, joint payments are also easy to do. Say Carol and Bob both want to
pay David. They can create a transaction with two inputs and one output, but with the two
inputs owned by two different people. And the only difference from the previous example is
that since the two outputs from prior transactions that are being claimed here are from
different addresses, the transaction will need two separate signatures — one by Carol and
one by Bob.
Transaction syntax. Conceptually that’s really all there is to a Bitcoin transaction. Now let’s
see how it’s represented at a low level in Bitcoin. Ultimately, every data structure that’s sent
on the network is a string of bits. What’s shown in Figure 3.3 is very low-level, but this
further gets compiled down to a compact binary format that’s not human-readable.
Figure 3.3 An actual Bitcoin transaction.
As you can see in Figure 3.3, there are three parts to a transaction: some metadata, a series of
inputs, and a series of outputs.
● Metadata. There’s some housekeeping information — the size of the transaction, the
number of inputs, and the number of outputs. There’s the hash of the entire
transaction which serves as a unique ID for the transaction. That’s what allows us to
use hash pointers to reference transactions. Finally there’s a “lock_time” field, which
we’ll come back to later.
● Inputs. The transaction inputs form an array, and each input has the same form. An
input specifies a previous transaction, so it contains a hash of that transaction, which
acts as a hash pointer to it. The input also contains the index of the previous
transaction’s outputs that’s being claimed. And then there’s a signature. Remember
that we have to sign to show that we actually have the ability to claim those previous
transaction outputs.
● Outputs. The outputs are again an array. Each output has just two fields. They each
have a value, and the sum of all the output values has to be less than or equal to the
sum of all the input values. If the sum of the output values is less than the sum of the
input values, the difference is a transaction fee to the miner who publishes this
transaction.
And then there’s a funny line that looks like what we want to be the recipient address.
Each output is supposed to go to a specific public key, and indeed there is something
in that field that looks like it’s the hash of a public key. But there’s also some other stuff
that looks like a set of commands. Indeed, this field is a script, and we’ll discuss this
presently.
2. HARD FORK: When the blockchain protocol is altered in a non backwards-compatible way.
Hard fork is opposite of Soft fork, here the rules are loosened. When there is a change in the
software that runs on the full nodes to function as a network participant, the change is such
that the new blocks mined on the basis of new rules (in the Blockchain protocol) are not
considered valid by the old version of the software. When hard forks occur, new currency
come into existence (with valid original currency) like in the case of Ethereum (original :
Ethereum, new : Ethereum Classic) and Bitcoin (original : Bitcoin, new : Bitcoin cash).
Equivalent quantity of currency is distributed to the full nodes who choose to upgrade their
software so that no material loss occurs. Such hard forks are often contentious (generating
conflicts in the community). The final decision to join a particular chain rests with the full
node. If chosen to join the new chain, the software has to be upgraded to make newer
transactions valid while the nodes who do not choose to upgrade their software continue
working the same. Example (HARD FORK): The new Casper update in the Ethereum
Blockchain in which the consensus protocol will change from a type of Proof of Work (PoW) to
a type of Proof of Stake (PoS). The nodes which install the Casper update will use the new
consensus protocol. Full nodes that do not choose to install the Casper update will become
incompatible with the full nodes that do.
Reasons for the occurrence of a blockchain fork:
• Add new functionality: The Blockchain code is upgraded regularly. Since most public
blockchains are open source, it is developed by people from around the world. The
improvements, issues are created, resolved and new versions are released when the time is
suitable.
• Fix security issues: Blockchain (and cryptocurrency on top of it) is a relatively new technology
as compared to the traditional currency (notes, coins, cheque), research is still underway to
fully understand it. So, versions are bumped and updates are released to fix the security issues
that arise in the way.
• Reverse transactions: The community can actually void all the transaction of a specific period
if they are found to be breached and malicious.
Short Overview of the Differences
Backward-compatible Backward-incompatible
Tightens the rules (e.g., from 1 MB to 0.5 MB) Expands the rules (e.g., from 1 MB to 2 M
Anonymity
The concept of anonymity within cryptocurrency is particularly significant in the cryptocurrency space
due to the nature of blockchain technology, which underpins most cryptocurrencies.
DEFINITION:
Anonymity in the context of cryptocurrencies refers to the ability to conduct transactions or hold
assets without revealing one's personal identity.
At a literal level, anonymous means “without a name.” When we try to apply this definition to Bitcoin,
there are two possible interpretations: interacting without using your real name, or interacting
without using any name at all. These two interpretations lead to very different conclusions as to
whether Bitcoin is anonymous. Bitcoin addresses are hashes of public keys. You don't need to use
your real name in order to interact with the system, but you do use your public key hash as your
identity. Thus, by the first interpretation, Bitcoin is anonymous as you do not use your real name.
However, by the second interpretation, it is not; the address that you use is a pseudo-identity. In the
language of computer science, this middle ground of using an identity that is not your real name is
called pseudonymity.
Unlinkability. To understand unlinkability in the Bitcoin context more concretely, let’s enumerate
some key properties that are required for Bitcoin activity to be unlinkable: 1. It should be hard to link
together different addresses of the same user. 2. It should be hard to link together different
transactions made by the same user. 3. It should be hard to link the sender of a payment to its
recipient. The first two properties are intuitive, but the third one is a bit tricky. If you interpret “a
payment” as a Bitcoin transaction, then the third property is clearly false. Every transaction has
inputs and outputs, and these inputs and outputs are inevitably going to be in the block chain and
publicly linked together. However, what we mean by a payment is not a single Bitcoin transaction, but
rather anything that has the effect of transferring bitcoins from the sender to the recipient. It might
involve a roundabout series of transactions. What we want to ensure is that it’s not feasible to link
the sender and the ultimate recipient of the payment by looking at the block chain.
Here's a breakdown of what anonymity means in this context:
• Pseudonymous Transactions: Cryptocurrencies like Bitcoin are often described as
pseudonymous rather than fully anonymous. When a transaction occurs,
the blockchain records the transaction details, including the wallet addresses involved. While
these addresses do not directly reveal the identity of the users, they are unique and can be
traced. If a wallet address can be linked to an individual's identity, their transactions can
potentially be tracked.
• Anonymity-Enhanced Cryptocurrencies: Some cryptocurrencies, like Monero and Zcash, have
been designed specifically to enhance user anonymity. They employ advanced cryptographic
techniques to hide transaction details, such as the identity of senders and receivers, and the
amount of cryptocurrency transacted. These privacy-focused cryptocurrencies are often
favored by those seeking higher levels of privacy and anonymity.
• Decentralization and Privacy: The decentralized nature of blockchain technology means that
there is no central authority (like a bank) that holds comprehensive records of individual
identities linked to transactions. This inherently supports a level of privacy not typically found
in traditional financial systems.
• Challenges and Limitations: Complete anonymity is challenging to achieve. Techniques
like blockchain analysis can sometimes de-anonymize transactions, especially when combined
with data from external sources. Regulatory efforts in various countries also aim to link
identities with cryptocurrency wallets, particularly for anti-money laundering (AML) and
combating the financing of terrorism (CFT).
• Use Cases and Concerns: Anonymity in cryptocurrencies is a double-edged sword. While it
offers privacy and protection from government surveillance and data collection by
corporations, it also can facilitate illicit activities like money laundering, tax evasion, and
financing illegal activities.
Anonymity in cryptocurrencies is about the ability to transact or hold digital assets without revealing
personal identity. While true anonymity is hard to achieve, some cryptocurrencies offer enhanced
privacy features, but these also raise regulatory and ethical concerns.
Figure 6.1: Snippet from Wikileaks donation page. Notice the refresh icon next to the Bitcoin
address. Wikileaks follows the Bitcoin best practice of generating a new receiving address for every
donation.
At first you might think that these different addresses must be unlinkable. Wikileaks receives each
donation separately, and presumably they can also spend each of those donations separately. But
things quickly break down.
Linking. Suppose Alice wants to buy a teapot that costs 8 bitcoins (more likely 8 centi-bitcoins, at 2015
exchange rates). Suppose, further, that her bitcoins are in three separate unspent outputs at different
addresses whose amounts are 3, 5, and 6 bitcoins respectively. Alice doesn't actually have an address
with 8 bitcoins sitting in it, so she must combine two of her outputs as inputs into a single transaction
that she pays to the store.
But this reveals something. The transaction gets recorded permanently in the block chain, and anyone
who sees it can infer that the two inputs to the transaction are most likely under the control of the
same user. In other words, shared spending is evidence of joint control of the different input
addresses. There could be exceptions, of course. Perhaps Alice and Bob are roommates and agree to
jointly purchase the teapot by each supplying one transaction input. But by and large, joint inputs
imply joint control.
Figure 6.2 : To pay for the teapot, Alice has to create a single transaction having inputs that are at two
different address. In doing so, Alice reveals that these two addresses are controlled by a single entity.
But it doesn't stop there. The adversary can repeat this process and transitively link an entire cluster
of transactions as belonging to a single entity. If another address is linked to either one of Alice’s
addresses in this manner, then we know that all three addresses belong to the same entity, and we
can use this observation to cluster addresses. In general, if an output at a new address is spent
together with one from any of the addresses in the cluster, then this new address can also be added
to the cluster.
Later in this chapter we’ll study an anonymity technique called CoinJoin that works by violating this
assumption. But for now, if you assume that people are using regular Bitcoin wallet software without
any special anonymity techniques, then this clustering tends to be pretty robust. We haven't yet seen
how to link these clusters to real-world identities, but we’ll get to that shortly.
Sidebar: Change address randomization. An early version of the bitcoin-qt library had a bug which
always put the change address as the first output in a transaction with two outputs. This meant that
it was trivial to identify the change address in many transactions. This bug was fixed in 2012 but
highlights an important point: wallet software has an important role to play in protecting
anonymity. If you’re developing wallet software, there are many pitfalls you should be aware of; in
particular, you should always choose the position of the change address at random to avoid giving
too much away to the adversary!
Going back to our example, suppose the price of the teapot has gone up from 8 bitcoins to 8.5
bitcoins. Alice can no longer find a set of unspent outputs that she can combine to produce the exact
change needed for the teapot. Instead, Alice exploits the fact that transactions can have multiple
outputs, as shown in Figure 6.3. One of the outputs is the store’s payment address and the other is a
“change” address owned by herself.
Now consider this transaction from the viewpoint of an adversary. They can deduce that the two
input addresses belong to the same user. They might further suspect that one of the output addresses
also belongs to that same user, but has no way to know for sure which one that is. The fact that the
0.5 output is smaller doesn’t mean that it’s the change address. Alice might have 10,000 bitcoins
sitting in a transaction, and she might spend 8.5 bitcoins on the teapot and send the remaining
9,991.5 bitcoins back to herself. In that scenario the bigger output is in fact the change address.
Figure 6.3: Change address. To pay for the teapot, Alice has to create a transaction with one output
that goes to the merchant and another output that sends change back to herself.
Mixing
There are several mechanisms that can make transaction graph analysis less effective. One such
technique is mixing, and the intuition behind it is very simple: if you want anonymity, use an
intermediary. This principle is not specific to Bitcoin and is useful in many situations where anonymity
is a goal. Mixing is illustrated in Figure 6.7.
Figure 6.7 : Mixing. Users send coins to an intermediary and get back coins that were deposited by
other users. This makes it harder to trace a user’s coins on the block chain.
Online wallets as mixes. If you recall our discussion of online wallets, they may seem to be suitable as
intermediaries. Online wallets are services where you can store your bitcoins online and withdraw
them at some later date. Typically the coins that you withdraw won’t be the same as the coins you
deposited. Do online wallets provide effective mixing, then?
Online wallets do provide a measure of unlinkability which can foil attempts at transaction graph
analysis — in one case, prominent researchers had to retract a claim that had received a lot of
publicity because the link they thought they’d found was a spurious one caused by an online wallet.
On the other hand, there are several important limits to using online wallets for mixing. First, most
online wallets don’t actually promise to mix users’ funds; instead, they do it because it simplifies the
engineering. You have no guarantee that they won’t change their behavior. Second, even if they do
mix funds, they will almost certainly maintain records internally that will allow them to link your
deposit to your withdrawal. This is a prudent choice for wallet services for reasons of both security
and legal compliance. So if your threat model includes the possibility of the service provider itself
tracking you, or getting hacked, or being compelled to hand over their records, you’re back to square
one. Third, in addition to keeping logs internally, reputable and regulated services will also require
and record your identity (we’ll discuss regulation in more detail in the next chapter). You won’t be
able to simply create an account with a username and password. So in one sense it leaves you worse
off than not using the wallet service. That’s why we called out the tension between centralization and
anonymity in the previous section.
The anonymity provided by online wallets is similar to that provided by the traditional banking
system. There are centralized intermediaries that know a lot about our transactions, but from the
point of view of a stranger with no privileged information we have a reasonable degree of privacy. But
as we discussed, the public nature of the block chain means that if something goes wrong (say, a
wallet or exchange service gets hacked and records are exposed), the privacy risk is worse than with
the traditional system. Besides, most people who turn to Bitcoin for anonymity tend to do so because
they are unhappy with anonymity properties of the traditional system and want a better (or a
different kind of) anonymity guarantee. These are the motivations behind dedicated mixing services.
Dedicated mixing services. In contrast to online wallets, dedicated mixes promise not to keep records,
nor do they require your identity. You don’t even need a username or other pseudonym to interact
with the mix. You send your bitcoins to an address provided by the mix, and you tell the mix a
destination address to send bitcoins to. Hopefully the mix will soon send you (other) bitcoins at
address you specified. It’s essentially a swap.
While it’s good that dedicated mixes promise not to keep records, you still have to trust them to keep
that promise. And you have to trust that they’ll send you back your coins at all. Since mixes aren’t a
place where you store your bitcoins, unlike wallets, you’ll want your coins back relatively quickly,
which means that the pool of other coins that your deposit will be mixed with is much smaller —
those that were deposited at roughly the same time.
A group of researchers, including four of the five authors of this textbook, studied mixes and proposed
a set of principles for improving the way that mixes operate, both in terms of increasing anonymity
and in terms of the security of entrusting your coins to the mix. We will go through each of these
guidelines.
Use a series of mixes. The first principle is to use a series of mixes, one after the other, instead of just
a single mix. This is a well-known and well-established principle — for example, Tor, as we’ll see in a
bit, uses a series of 3 routers for anonymous communication. This reduces your reliance on the
trustworthiness of any single mix. As long as any one of the mixes in the series keeps its promise and
deletes its records, you have reason to expect that no one will be able to link your first input to the
ultimate output that you receive.
Figure 6.8. Series of mixes. We begin with a user who has a coin or input address that we
assume the adversary has managed to link to them. The user sends the coin through various
mixes, each time providing a freshly generated output address to the mix. Provided that at
least one of these mixes destroys its records of the input to output address mapping, and
there are no side-channel leaks of information, an adversary won’t be able to link the user’s
original coin to their final one.
Instead, we want mix transactions to be uniform in value so that linkability is minimized. All
mixes should agree on a standard chunk size, a fixed value that incoming mix transactions
must have. This would increase the anonymity set as all transactions going through any mix
would look the same and would not be distinguishable based on their value. Moreover,
having a uniform size across all mixes would make it easy to use a series of mixes without
having to split or merge transactions.
In practice, it might be difficult to agree on a single chunk size that works for all users. If we
pick it to be too large, users wanting to mix a small amount of money won’t be able to. But
if we pick it to be too small, users wanting to mix a large amount of money will need to
divide it into a huge number of chunks which might be inefficient and costly. Multiple
standard chunk sizes would improe performance, but also split the anonymity sets by
chunk size. Perhaps a series of two or three increasing chunk sizes will provide a reasonable
tradeoff between efficiency and privacy.
DOUBLE SPENDING
Although Blockchain is secured, still it has some loopholes. Hackers or malicious users take
advantage of these loopholes to perform their activities.
• Double spending means the expenditure of the same digital currency twice or more
to avail the multiple services. It is a technical flaw that allows users to duplicate
money.
• Since digital currencies are nothing but files, a malicious user can create multiple
copies of the same currency file and can use it in multiple places.
• This issue can also occur if there is an alteration in the network or copies of the
currency are only used and not the original one.
• There are also double spends that allow hackers to reverse transactions so that
transaction happens two times.
• By doing this, the user loses money two times one for the fake block created by the
hacker and for the original block as well.
• The hacker gets incentives as well for the fake blocks that have been mined and
confirmed.
How Does Double Spending Happen?
Double spending can never arise physically. It can happen in online transactions. This mostly
occurs when there is no authority to verify the transaction. It can also happen if the user’s
wallet is not secured. Suppose a user wants to avail of services from Merchant ‘A’ and
Merchant ‘B’.
• The user first made a digital transaction with Merchant ‘A’.
• The copy of the cryptocurrency is stored on the user’s computer.
• So the user uses the same cryptocurrency to pay Merchant ‘B’
• Now both the merchants have the illusion that the money has been credited since
the transactions were not confirmed by the miners.
This is the case of double spending.
Example: Suppose a user has 1 BTC. He/She wants to avail of services from merchant A and
merchant B. The user creates multiple copies of the same BTC and stores it. The user first
sends the original BTC to Merchant A and gets the service. Simultaneously, the user sends
the copied version of 1 BTC to Merchant B. Since the second transaction was not confirmed
by other miners, the merchant accepts the bitcoin and sends the service. But the
cryptocurrency that was sent is invalid. This is the case of Double Spending.
Purpose of PoW
The purpose of a consensus mechanism is to bring all the nodes in agreement, that is,
trust one another, in an environment where the nodes don’t trust each other.
• All the transactions in the new block are then validated and the new block is
then added to the blockchain.
• The block will get added to the chain which has the longest block height
• Miners(special computers on the network) perform computation work in
solving a complex mathematical problem to add the block to the network,
hence named, Proof-of-Work.
• With time, the mathematical problem becomes more complex.
Features of PoW
There are mainly two features that have contributed to the wide popularity of this
consensus protocol and they are:
• It is hard to find a solution to a mathematical problem.
• It is easy to verify the correctness of that solution.
How Does PoW Work?
The PoW consensus algorithm involves verifying a transaction through the mining process.
This section focuses on discussing the mining process and resource consumption during
the mining process.
Mining:
The Proof of Work consensus algorithm involves solving a computationally challenging
puzzle in order to create new blocks in the Bitcoin blockchain. The process is known as
‘mining’, and the nodes in the network that engages in mining are known as ‘miners’.
• The incentive for mining transactions lies in economic payoffs, where
competing miners are rewarded with 6.25 bitcoins and a small transaction fee.
• This reward will get reduced by half its current value with time.
Energy and Time consumption in Mining:
The process of verifying the transactions in the block to be added, organizing these
transactions in chronological order in the block, and announcing the newly mined block to
the entire network does not take much energy and time.
• The energy-consuming part is solving the ‘hard mathematical problem’ to link
the new block to the last block in the valid blockchain.
• When a miner finally finds the right solution, the node broadcasts it to the
whole network at the same time, receiving a cryptocurrency prize (the reward)
provided by the PoW protocol.
Mining reward:
• Currently, mining a block in the bitcoin network gives the winning miner 6.25
bitcoins.
• The amount of bitcoins won halves every four years. So, the next deduction in
the amount of bitcoin is due at around 2024(with the current rate and growth).
• With more miners comes the inevitability of the time it takes to mine the new
block getting shorter.
• This means that the new blocks are found faster. In order to consistently find 1
block every 10 minutes. (That is the amount of time that the bitcoin developers
think is necessary for a steady and diminishing flow of new coins until the
maximum number of 21 million is reached (expected some time with the
current rate in around 2140)), the Bitcoin network regularly changes the
difficulty level of mining a new block.
Bitcoin’s PoW System
Bitcoin uses the Hashcash Proof of Work system as the mining basis. The ‘hard
mathematical problem’ can be written in an abstract way like below :
Given data A, find a number x such as that the hash of x appended to A results is a number
less than B.
• The miners bundle up a group of transactions into a block and try to mine. To
mine it, a hard mathematical problem has to be solved.
• This problem is called the proof of work problem which has to be solved to
show that the miner has done some work in finding out the solution to the
problem and hence the mined block must be valid.
• The answer to the problem needs to be a lower number than the hash of the
block for it to be accepted, known as the ‘target hash’.
A target hash is a number that the header of a hashed block must be equal to or less than
for a new block, along with the reward, to be awarded to a miner.
The lower a target is, the more difficult it is to generate a block.
• A miner continues testing different unique values (known as a nonce(s)) until a
suitable one is produced.
• The miner who manages to solve the problem gets the bitcoin reward and adds
the block to the blockchain by broadcasting that the block has been mined.
Note: The target hash adjusts once every 2016 block or approximately once every 2
weeks. All the miners immediately stop working on the said block and start mining the
next block.
Common cryptographic protocols used in PoW: The most widely used proof-of-work
consensus is based on SHA-256 and was introduced as a part of Bitcoin. Others include
Scrypt, SHA-3, scrypt-jane, scrypt-n, etc.
Challenges With PoW
The Proof-of-Work consensus mechanism has some issues which are as follows:
• The 51% risk: If a controlling entity owns 51% or more than 51% of nodes in the
network, the entity can corrupt the blockchain by gaining the majority of the
network.
• Time-consuming: Miners have to check over many nonce values to find the
right solution to the puzzle that must be solved to mine the block, which is a
time-consuming process.
• Resource consumption: Miners consume high amounts of computing power in
order to find the solution to the hard mathematical puzzle. It leads to a waste
of precious resources(money, energy, space, hardware). It is expected that
0.3% of the world’s electricity will be spent to verify transactions by the end of
2028.
• Not instantaneous transaction: Transaction confirmation takes about 10–60
minutes. So, it is not an instantaneous transaction; because it takes some time
to mine the transaction and add it to the blockchain thus committing the
transaction.
2.Proof of Stake (PoS)
As understandable from the name, nodes on a network stake an amount
of cryptocurrency to become candidates to validate the new block and earn the fee from it.
Then, an algorithm chooses from the pool of candidates the node which will validate the
new block. This selection algorithm combines the quantity of stake (amount of
cryptocurrency) with other factors (like coin-age based selection, randomization process) to
make the selection fair to everyone on the network.
• Coin-age based selection:
The algorithm tracks the time every validator candidate node stays a validator. The
older the node becomes, the higher the chances of it becoming the new validator.
• Random Block selection:
The validator is chosen with a combination of ‘lowest hash value’ and ‘highest stake’.
The node having the best weighted-combination of these becomes the new validator.
A typical PoS based mechanism workflow:
1. Nodes make transactions. The PoS algorithm puts all these transactions in a pool.
2. All the nodes contending to become validator for the next block raise a stake. This
stake is combined with other factors like ‘coin-age’ or ‘randomized block selection’ to
select the validator.
3. The validator verifies all the transactions and publishes the block. His stake still
remains locked and the forging reward is also not granted yet. This is so that the
nodes on the network can ‘OK’ the new block.
4. If the block is ‘OK’-ed, the validator gets the stake back and the reward too. If the
algorithm is using a coin-age based mechanism to select validators, the validator for
the current block’s has its coin-age reset to 0. This puts him in a low-priority for the
next validator election.
5. If the block is not verified by other nodes on the network, the validator loses its stake
and is marked as ‘bad’ by the algorithm. The process again starts from step 1 to forge
the new block.
Features:
• Fixed coins in existence:
There is only a finite number of coins that always circulate in the network. There is
no existence of bringing new coins into existence(as in by mining in case of bitcoin
and other PoW based systems). Note that the network starts with a finite number of
coins or ‘initially starts with PoW, then shifts to PoS’ in some cases. This initiation
with PoW is meant to bring coins/cryptocurrency in the network.
• Transaction fee as reward to minters/forgers:
Every transaction is charged some amount of fee. This is accumulated and given to
the entity who forges the new block. Note that if the forged block is found
fraudulent, the transaction fee is not rewarded. Moreover, the stake of the validator
is also lost(which is also known as slashing).
• Impracticality of the 51% attack:
To conduct a 51% attack, the attacker will have to own 51% of the total
cryptocurrency in the network which is quite expensive. This deems doing the attack
too tedious, expensive and not so profitable. There will occur problems when
amassing such a share of total cryptocurrency as there might not be so much
currency to buy, also that buying more and more coins/value will become more
expensive. Also validating wrong transactions will cause the validator to lose its
stake, thereby being reward-negative.
Advantages of PoS:
• Energy-efficient:
As all the nodes are not competing against each other to attach a new block to the
blockchain, energy is saved. Also, no problem has to be solved( as in case of Proof-of-
Work system) thus saving the energy.
• Decentralization:
In blockchains like Bitcoin(Proof of Work system to achieve distributed consensus),
an extra incentive of exponential rewards are in place to join a mining pool leading to
a more centralized nature of blockchain. In the case of a Proof-of-Stake based
system(like Peercoin), rewards are proportional(linear) to the amount of stake. So, it
provides absolutely no extra edge to join a mining pool; thus promoting
decentralization.
• Security:
A person attempting to attack a network will have to own 51% of the stakes(pretty
expensive). This leads to a secure network.
Weakness of a PoS mechanism:
• Large stake validators:
If a group of validator candidates combine and own a significant share of total
cryptocurrency, they will have more chances of becoming validators. Increased
chances lead to increased selections, which lead to more and more forging reward
earning, which lead to owning a huge currency share. This can cause the network to
become centralized over time.
• New technology:
PoS is still relatively new. Research is ongoing to find flaws, fix them and making it
viable for a live network with actual currency transactions.
• The ‘Nothing at Stake’ problem:
This problem describes the little to no disadvantage to the nodes in case they
support multiple blockchains in the event of a blockchain split(blockchain forking). In
the worst-case scenario, every fork will lead to multiple blockchains and validators
will work and the nodes in the network will never achieve consensus.
Blockchains using Proof-of-Stake:
• Ethereum(Casper update)
• Peercoin
• Nxt
3.Proof of Burn Consensus Algorithm in Blockchain
Proof of Burn (PoB): With PoB, instead of investing in expensive hardware equipment, the
validators follow the following approach:
• They burn coins by sending them to an address from where they are
irretrievable.
• By committing the coins to an unreachable address, validators earn a privilege
to mine on the system based on a random selection process.
• Thus, burning coins means that validators have a long-term commitment in
exchange for their short-term loss.
• Depending on how the PoB is implemented, miners may burn the native currency
of the Blockchain application or the currency of an alternative chain, such as
bitcoin.
• The more coins validators burn, the better are their chances of being selected to
mine the next block.
While PoB is an interesting alternative to PoW, the protocol still wastes resources
needlessly. It is also questioned that mining power simply goes to those who are willing to
burn more money.
Why Proof of Burn Required?
There were some drawbacks in the PoW consensus algorithm which made researchers
work towards a new consensus algorithm i.e PoB.
• The first drawback is that the power consumption of PoW is very high. Miners
are awarded by upgrading the ledger under a POW model. Computational power
is employed to solve a math problem in exchange for remuneration. Greater the
money a miner spends to solve the problem, the greater the chances that they
will be allowed to mine blocks.
• PoW requires very high capital investments.
How PoB Works?
1. As the name itself suggests, there is something which should be burned. Here as
we are talking in the context of virtual currency so it’s obvious that in PoB virtual
currency is burned. The more the currencies are burned by miners the more they
have the power to create blocks.
2. By burning we don’t exactly mean burning. It means not using that coin. This may
be done if it is sent to somewhere where it can’t be spent. So miners send these
coins to such addresses from where they can’t be used. It is sent to a public
verifiable address where it cannot be accessed and thus can not be used.
3. When the coin is burnt its availability decreases leading to a potential increase
in the value of the coin.
4. Now the question is why do we need to burn the coin? The basic explanation for
this is that by destroying the currency, the consumer is displaying a big
commitment to the currency by foregoing a narrow profit in exchange for a long-
term profit.
5. To avoid any undue advantages for early adopters, the PoB has devised a method
that allows for the periodic burning of crypto coins in order to maintain mining
capacity. Any time a fresh block is mined, the energy of burned coins decreases
slightly.
6. It is a deflationary idea in which the quantity of currencies reduces over time,
increasing deficiency and, as a result, the currency holders’ value. Coins that
grow their quantity over time, on the other hand, tend to lose value.
Advantages of PoB Over PoS: In Pos blockchain, market scarcity is not permanent. The
scarcity is only for a certain amount of time i.e. until the forger stakes their coin which is
usually done by locking them up. But the coins come back into circulation if the forger who
is leaving takes those coin and sell them in the market. While in the case of PoB the coins
are destroyed thus the scarcity is permanent.
Advantages of PoB:
• It required very little power compared to PoW.
• It reduces energy consumption by wasting insignificant resources when coins are
burned.
• It encourages long-term involvement in a project as a consumer is displaying a
big commitment to the currency by foregoing a narrow profit in exchange for a
long-term profit.
• The coin distribution is more fair compared to all other consensuses.
Disadvantages Of PoB:
• It is risky because one doesn’t know that will they gain the wealth they have
burnt in the future or not.
• As coins are burnt, so technically if we see then resources are wasted.
• It may suffer from rich getting richer phenomena. In which those who are
wealthy are getting wealthier by having more coins.
• The primary(leader) node is changed during every view(pBFT consensus rounds) and
can be substituted by a
• view change protocol
• if a predefined quantity of time has passed without the leading node broadcasting a
request to the backups(secondary). If needed, a majority of the honest nodes can
vote on the legitimacy of the current leading node and replace it with the next
leading node in line.
• Limitations of pBFT:
• The pBFT consensus model works efficiently only when the number of nodes in the
distributed network is small due to the high communication overhead that increases
exponentially with every extra node in the network.
•
o Sybil attacks : The pBFT mechanisms are susceptible to Sybil attacks, where
one entity(party) controls many identities. As the number of nodes in the
network increase, sybil attacks become increasingly difficult to carry out. But
as pBFT mechanisms have scalability issues too, the pBFT mechanism is used
in combination with other mechanism(s).
o Scaling : pBFT does not scale well because of its communication(with all the
other nodes at every step) overhead. As the number of nodes in the network
increase(increases as O(n^k), where n is the messages and k is the number of
nodes), so does the time taken to respond to the request.
• Platforms using pBFT variants:
o Zilliqa – pBFT in combination with PoW consensus
o Hyperledger Fabric – permissioned version of pBFT
o Tendermint – pBFT + DPoS(Delegated Proof-of-Stake)