BCT Unit 2 Notes
BCT Unit 2 Notes
UNIT-II NOTES
Syllabus:
Decentralization mechanism of Bitcoin: Centralization verses Decentralization, Distributed Consensus, Consensus without
identity using a Bitcoin, Nakamoto consensus Incentives and proof of work, putting it all together. Bitcoin transaction,
Bitcoin Scripts, Proof of burn, Proof of stake, Application of Bitcoin script, Bitcoin block.
Key Features
1. Single Point of Control: A central authority or organization manages the application, data storage, and user access.
2. Server-Client Architecture: Users interact with the application through a client (e.g., web browser, mobile app)
communicating with a central server, which processes requests and returns responses.
3. Data Storage: All user data is typically stored in a central database, managed by the organization behind the
application.
4. Easier Maintenance and Updates: Since the application is controlled by a single entity, it can be updated and
maintained more easily, ensuring consistent performance and feature updates.
Advantages
1. Simplicity: Centralized applications are generally easier for users to navigate and use due to a straightforward
interface and consistent user experience.
2. Performance: Central servers can be optimized for speed and efficiency, providing faster response times for users.
3. Control: The central authority can enforce policies, security measures, and regulations effectively.
Disadvantages
1. Single Point of Failure: If the central server goes down or experiences issues, the entire application can become
inaccessible.
2. Privacy Concerns: Users must trust the central authority to handle their data responsibly, raising concerns about data
breaches and misuse.
3. Censorship and Control: The central authority has the power to control content, enforce rules, or restrict access,
potentially leading to censorship.
Use Cases
1. Social Media Platforms: Centralized control allows for user engagement, content moderation, and targeted
advertising. Examples include Facebook, Twitter, etc.
2. E-commerce: Centralized applications facilitate product listings, transactions, and customer service. They enable
seamless inventory management and payment processing. Examples include eBay, Amazon, etc.
3. Online Banking: Centralized banking apps allow users to manage accounts, transfer funds, and access financial
services securely from a single interface. Examples include Chase, Bank of America, etc.
4. Cloud Storage Services: Users can store, share, and collaborate on files with centralized management of data access
and synchronization across devices. Examples include Google Drive, Dropbox, etc.
5. Streaming Services: Centralized control allows for content delivery, user subscriptions, and personalized
recommendations based on user preferences. Examples include Netflix, Spotify, etc.
Key Features
1. Decentralization: DApps operate on distributed networks, reducing reliance on a single entity. Data and operations are shared across
multiple nodes.
2. Smart Contracts: Many DApps use smart contracts with the terms directly written into code. This automates processes and ensures that
transactions are executed as intended without intermediaries.
3. Transparency: All transactions and interactions within a DApp are recorded on the blockchain, allowing users to verify activities and
ensuring a transparent environment.
4. Immutability: Data stored on the blockchain cannot be easily altered or deleted, providing a permanent and verifiable record of all
transactions.
5. Token-based Economics: DApps often incorporate tokens for governance, transactions, and incentivizing user participation, enabling a
new economic model.
Advantages
1. Security: Enhanced security through cryptographic principles and distributed architecture, making it harder for malicious attacks to
succeed.
2. User Control: Users have greater control over their data and interactions, reducing reliance on centralized authorities.
3. Censorship Resistance: Difficult for any entity to censor or control the application, as it operates across multiple nodes.
Disadvantages
1. Complexity: DApps can be more complex to use than traditional applications, often requiring users to manage wallets and private keys,
which can be intimidating for non-technical users.
2. Performance Issues: DApps can suffer from slower transaction speeds and higher latency compared to centralized applications,
particularly when the underlying blockchain is congested.
3. Development Challenges: Building DApps requires specialized knowledge of blockchain technology and smart contract development,
which may limit the pool of available developers.
4. Lack of Regulation: The decentralized nature can lead to regulatory challenges, making it difficult for users and developers to navigate
the legal landscape.
5. Governance Issues: In decentralized networks, governance can be complicated. Reaching consensus among stakeholders can be slow
and contentious, potentially stalling development or changes.
Use Cases
1. Finance (DeFi): Enable users to trade, lend, and borrow assets without intermediaries, facilitating peer-to-peer financial services.
Examples include Uniswap, Aave, etc.
2. Non-Fungible Tokens (NFTs): Allow creators to tokenize and sell unique digital assets (art, collectibles) directly to buyers, ensuring
ownership verification. Examples include OpenSea, Rarible, etc.
3. Supply Chain Management: nhance transparency and traceability in supply chains, allowing stakeholders to verify product origins and
movements. Examples include VeChain, IBM Food Trust, etc.
4. Decentralized Autonomous Organizations (DAOs): Facilitate community-driven decision-making and governance without centralized
control, allowing members to vote on proposals. Examples include MakerDAO, Aragon, etc.
5. Identity Verification: Provide users with control over their digital identities, allowing secure and private verification without relying on
centralized authorities. Examples include uPort, Civic, etc.
There are various consensus algorithms, such as Proof of Work (PoW) and Proof of Stake (PoS), designed to achieve
this agreement. Each algorithm offers a different balance of security, efficiency, and scalability, depending on the needs
of the blockchain network.
Consensus mechanisms basically need to make sure that the distributed ledger of a blockchain stays true. This is done
through the following steps:
1) When a transaction is initiated, it is verified by a designated verifier such as a validator(PoS) or miner(PoW).
2) Then the verifier broadcasts the transaction to the network.
3) Multiple verifiers, other than the first verifier, also verify the transactions.
4) After the transaction is verified by a certain number of verifiers, it is added to a block.
5) The block is then added to a blockchain when it has sufficient numbers of transactions.
6) After a few blocks, the transaction is finalized.
1. Proof of Work (PoW): This was the first consensus mechanism to come into existence with Bitcoin’s blockchain. Here,
transaction verifiers, also called as miners, run complex calculations to guess the nonce value which is unique for every
transaction. These nonce values are obtained from the hashing function with the following inputs (non-exhaustive list):
1. Transaction amount
2. Public address of receiver
3. Private key of sender
4. Hash of previous transaction
Every computer (or “node”) participating in a crypto’s blockchain network has its own copy of this blockchain (which, again,
is a history of transactions bundled into blocks).
How does a new transaction get into a block? This is where proof of work comes in. Suppose you want to send someone a
certain amount of Bitcoin:
i.) Transactions are grouped. Your transaction is pooled with other non-verified transactions (people buying,
selling, or exchanging Bitcoin). These transactions are waiting to be placed into a block.
ii.) Miners compete to verify the next block. Crypto miners worldwide (basically, computers operating in the
network) work to solve a complex mathematical puzzle. Their goal is to spit out a 64-bit “hash” (like a
signature or a password) that matches Bitcoin’s “target hash.” Truth be told, it’s a huge guessing game.
Mining computers make trillions of guesses per second, which is why, as we’ll explore later, the process is
energy inefficient and costly. It takes, on average, around ten minutes for miners to mine a new block.
iii.) A new block is mined and the transactions are added to the blockchain. The first miner to reach the goal gets
to write the next page of blockchain transactions. The grouped transactions are placed in a block. That block
with its solution is sent to the entire Bitcoin network so that each computer can validate it and update their
copies of the ledger.
Every move in the Bitcoin network must happen in “consensus,” meaning that all computers must agree to the same data.
This is why proof of work is called a “consensus mechanism.” It’s also why the Bitcoin network is referred to as a “trustless
system.” The entire system is mechanized by computer consensus rather than relying on the trust of any single entity (as
opposed to a banker who might accidentally “lose” your paycheck deposit or misallocate your funds).
Examples of Proof of Work Blockchains:
i.) Bitcoin
ii.) Dogecoin
iii.) Ethereum Classic
[Link] of Stake(PoS): Proof of Stake (PoS) is a blockchain consensus mechanism that achieves distributed agreement by
selecting block validators based on the amount of cryptocurrency they hold and "stake" as collateral, rather than through
energy-intensive mining. It is energy-efficient, secure, and incentivizes honesty by allowing the network to "slash"
(confiscate) staked assets if a validator acts maliciously.
Proof-of-stake reduces the computational work needed for verifying blocks and transactions. While proof-of-work
relies on heavy computing for security, proof-of-stake allows coin owners to use their machines to verify blocks with
less computational effort. Owners stake their coins as collateral, earning the opportunity to validate blocks and
receive rewards.
Validators are chosen randomly to confirm transactions and validate block information. This setup randomizes fee
collection, unlike the competitive rewards system in proof-of-work.
To become a validator, a coin owner must "stake" a specific amount of coins. For example, Ethereum requires users
to stake 32 ETH to operate a node. Multiple validators must confirm a block's accuracy before it is finalized and
closed.1 Blocks are validated by multiple validators, and when a specific number of validators verify that the block is
accurate, it is finalized and closed.
[Link] of Burn(PoB): Proof-of-Burn (PoB) is a unique consensus mechanism in the world of cryptocurrencies. It
works by letting miners 'burn' or permanently destroy their crypto tokens.
This burning process gives miners the right to write blocks based on how many coins they burned. The concept
behind PoB requires miners to burn some of their digital currencies for the opportunity to mine a new block. This
process, known as burning, involves sending tokens to an unspendable address, often referred to as an "eater"
address.
These addresses can be checked by anyone, but no one can get to them. This means the coins sent there cannot be
gotten back or spent, so they are removed from [Link] a Proof of Burn (PoB) system, the amount of coins a miner
burns can affect their chances of being chosen to mine the next block.
This is because burning coins serves as a display of their virtual mining power. Therefore, the more coins they burn,
the greater their mining power becomes, and vice versa. As mining power increases, miners can find
new blocks more quickly, leading to more rewards.
Unlike the Proof of Work (PoW) system, PoB doesn't require expensive hardware or consume a lot of power,
making it an energy-efficient alternative.
[Link] of Delegated Stake (PoDS): Delegated Proof of Stake (DPoS) is a popular evolution of the PoS concept, whereby
users of the network vote and elect delegates to validate the next block. Delegates are also called witnesses or block
producers. Using DPoS, you can vote on delegates by pooling your tokens into a staking pool and linking those to a
particular delegate. You do not physically transfer your tokens to another wallet, but instead utilize a staking service provider
to stake your tokens in a staking pool.
A limited number of delegates (most protocols choose between 20 and 100) are chosen for each new block, so the
delegates of one block might not be the delegates of the next. Elected delegates receive the transaction fees from the
validated block, and that reward is then shared with users who pooled their tokens in the successful delegate’s pool.
The more you stake, the higher a share of the block reward you receive. The rewards are shared based on each user’s
stake; so if your stake represents 5% of the total staking balance, you would receive 5% of the block reward.
According to its proponents, DPoS is a more democratic way of choosing who verifies the next block, allowing a
more diverse group of people to participate in the process since it’s based on earned reputation as a lawful staker and
not overall wealth. Additionally, because there are a limited number of validators, DPoS allows the network to reach
consensus more quickly.
[Link] of Authority (PoA): Proof-of-Authority (PoA) consensus which provides high performance and fault tolerance.
Term was proposed in 2017 by co-founder of Ethereum and Parity Technologies Gavin Wood.
Working of PoA :
In PoA, rights to generate new blocks are awarded to nodes that have proven their authority to do so. These nodes are
referred to as "Validators" and they run software allowing them to put transactions in blocks. Process is automated
and does not require validators to be constantly monitoring their computers but does require maintaining the
computer uncompromised. PoA is suited for both private networks and public networks, like POA Network, where
trust is distributed.
PoA consensus algorithm leverages value of identities, which means that block validators are not staking coins but
their own reputation instead. PoA is secured by trust on the identities selected.
[Link] of Elapsed Time (PoET): Proof of Elapsed Time (PoET) is a network consensus algorithm that prevents high
resource utilization and energy consumption. It implements a fair lottery system to keep the process more efficient.
Here is an overview of how PoET works:
1. Initialization: Nodes set up secure hardware such as Intel SGX to enable trusted execution and random wait time
generation.
2. Random Wait Time Generation: Each node generates a random wait time using the secure hardware. The secure
hardware ensures that the wait time cannot be predicted or altered by the node itself, maintaining fairness in the
selection process.
3. Waiting Period: Each node waits for the duration of its randomly determined period before attempting to propose a
new block. Nodes do not perform any computational work during this period, which contrasts with Proof of Work
(PoW) where nodes perform intensive calculations.
4. Block Proposal: After the waiting period elapses, the node that has waited the longest is eligible to propose the next
block. The node that has waited the longest broadcasts its proposed block to the network.
5. Block Validation: Other nodes in the network verify the legitimacy of the proposed block and ensure that the
proposer adhered to the waiting time protocol. This verification involves checking that the proposer’s wait time was
indeed randomly generated and not manipulated.
6. Consensus Achievement: If the block proposal is valid and meets the network’s consensus rules, it is added to the
blockchain, and the network reaches consensus on the new state. The process then starts over with nodes generating
new random wait times for the next round of block proposals.
[Link] of Capacity (PoC): Proof of capacity allows the mining devices, also known as nodes, on the blockchain network
to use empty space on their hard drive to mine the available cryptocurrencies.
Instead of repeatedly altering the numbers in the block header and repeated hashing for the solution value as in a
PoW system, PoC works by storing a list of possible solutions on the mining device’s hard drive even before the
mining activity commences.
The larger the hard drive, the more possible solution values one can store on the hard drive, the more chances a
miner has to match the required hash value from his list, resulting in more chances to win the mining reward.
Permissioned/Private Network:
1. Practical Byzantine Fault Tolerance(PBFT)
2. Paxos
3. Raft
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.
[Link]: Paxos is an algorithm that enables a distributed set of computers (for example, a cluster of distributed
database nodes) to achieve consensus over an asynchronous network. To achieve agreement, one or more of the computers
proposes a value to Paxos. Consensus is achieved when a majority of the computers running Paxos agrees on one of the
proposed values.
In general terms, Paxos selects a single value from one or more of the values that are proposed, and then broadcasts
that value to all of the cooperating computers. Once the Paxos algorithm has run, all of the computers (or database
nodes)) agree upon the proposed value, and the cluster clocks forward.
Roles in PAXOS
PAXOS involves three distinct roles played by different nodes in the network:
1. Proposer: A node that initiates the consensus process by proposing a value. This value could be anything from a new data entry to
a configuration change.
2. Acceptor: A node that participates in the consensus process by responding to proposals from proposers. Acceptors play a crucial role in
validating proposals and ensuring agreement.
3. Learner (Optional): A node that observes the consensus process and eventually learns the decided value. This role is not always
explicitly defined in all variations of PAXOS. Learners can be any nodes in the system that need to be updated with the agreed-upon
value.
How Does the PAXOS Consensus Algorithm Work?
PAXOS is a complex algorithm with several variations. This explanation focuses on a basic version, highlighting the three key phases that
involve message exchanges between proposers and acceptors:
1. Prepare Phase
1. The proposer initiates the process by sending a "prepare" message with a unique proposal number to all acceptors.
2. This message inquires if the acceptors have previously accepted a value for the same round (identified by the proposal number).
3. The round number helps prevent conflicts arising from concurrent proposals. Imagine two proposers suggesting different values at
roughly the same time. The round number ensures that only proposals from the latest round are considered.
2. Promise Phase
If an acceptor has already accepted a value for the same round (perhaps from a previous proposal), it includes that value in its response. This
information is crucial for the proposer, as it helps identify any potential conflicts or ongoing consensus processes.
3. Accept Phase
1. Based on the promises received, the proposer broadcasts an "accept" message to all acceptors. This message contains the proposed
value and any previously accepted values learned from the promise phase. This allows all nodes to learn about the proposed value and
potential conflicts.
2. If a majority of acceptors respond with a promise indicating they haven't accepted a different value for the round, the proposer
considers the value accepted. This signifies that the proposed value has gained enough support to be considered the agreed-upon value.
Learning the Decided Value
1. Learners can passively observe the messages exchanged during the Accept phase to learn the decided value. By monitoring the
"Accept" messages, learners can identify the value being proposed by a majority and eventually converge on the agreed-upon value.
2. Alternatively, proposers can explicitly send "learn" messages to other nodes after a value is accepted. This approach actively informs
learners about the chosen value, ensuring faster synchronization.
[Link]: It’s designed to be easier to understand than previous algorithms like Paxos while providing strong fault
tolerance and leader election capabilities.
Core Concepts:
1. Nodes (Servers): In Raft, the network is composed of several nodes or servers.
2. Leader: One of the nodes in the Raft cluster is elected as the leader. The leader is responsible for managing
the replication of logs across the cluster.
3. Follower: All other nodes in the cluster are followers. They respond to requests from the leader and forward
client requests to the leader.
4. Candidate: When a leader fails, a new leader needs to be elected. Nodes transition to the candidate state
and initiate an election.
5. Term: Raft operates in terms, where each term begins with an election and ends with a new leader being
elected or re-elected.
6. Log Replication: Raft ensures that all logs across the cluster are replicated and maintained in the same
order.
Consensus and Leader Election:
The primary goal of Raft is to achieve consensus among nodes in the cluster regarding the state of the system.
Here’s how it works:
1. Leader Election:
At the beginning of each term, nodes start as followers.
If a follower doesn’t hear from the leader for a certain period (election timeout), it transitions to the candidate
state.
The candidate requests votes from other nodes. If it receives votes from the majority, it becomes the leader.
If no node receives a majority, a new election is started in the next term.
2. Log Replication and Consistency:
The leader accepts client requests and appends them to its log.
It then sends the log entry to followers, which replicate the log entry.
Once a majority of followers acknowledge the entry, it’s committed to the log and applied to the state
machine.
We can definitely elaborate more on the Raft consensus algorithm and its components for a deeper understanding.
Here’s a more detailed explanation of the components and syncing process:
Consensus in Raft
Raft’s approach to consensus is crucial for ensuring the integrity and consistency of the distributed system.
Consensus is achieved through a series of steps:
[Link] Replication:
When a client initiates an operation, such as setting a key-value pair, the leader node receives the request.
The leader appends the operation to its log and broadcasts this log entry to all other nodes in the cluster,
including peer nodes.
Each node in the cluster appends the log entry to its log.
2. Majority Agreement:
Raft operates on the principle of majority agreement. Before committing an operation to its state
machine, the leader node waits for acknowledgments from most nodes.
If most of the nodes (Say N/2 + 1) acknowledge the operation by replicating it in their logs, the leader
commits the operation to its state machine.
This ensures that the operation is officially part of the system’s state and will be applied consistently
across all nodes.
Additionally, the leader regularly sends updates to the other servers to keep them in sync. This ensures
that even if a server falls behind or crashes, it can quickly catch up with the latest state of the key-value
store.
2.3 Consensus without identity using a Bitcoin : Consensus without identity is a fundamental concept introduced by
Bitcoin to solve the problem of agreement in a decentralized network where participants are unknown and untrusted.
In traditional systems, consensus depends on verified identities, but in open networks identities can be easily faked,
leading to issues like Sybil attacks where a single user creates multiple identities to gain control. Bitcoin overcomes
this by replacing identity with computational effort through a mechanism called Proof of Work (PoW).
In this system, participants known as miners compete to solve complex cryptographic puzzles, and the first to solve
the puzzle gets the right to add a new block of transactions to the blockchain. Other nodes verify this block, and the
network accepts the chain that has the most accumulated work, commonly referred to as the longest chain.
This ensures that consensus is achieved based on the amount of computational power invested rather than the number
of participants or their identities. Since generating computational power requires significant resources such as
electricity and hardware, it becomes extremely difficult and expensive for an attacker to manipulate the system, even
if they create many fake identities.
Thus, Bitcoin establishes trust through mathematics, economic incentives, and distributed verification rather than
relying on central authorities or personal identities, making it a secure and decentralized solution for achieving
consensus in an open network.
Proof of Work (PoW) : Proof of Work is a key element of the Nakamoto Consensus. It involves solving
complex mathematical problems to add new blocks to the blockchain. Miners use computational power to
solve these problems, and the first one to solve it gets to add the next block and receive a block reward.
Block Difficulty : The difficulty of the mining mathematical problems adjusts automatically. This ensures
that new blocks are added at a steady rate, typically every 10 minutes for Bitcoin. If more miners join and
provide more computational power (hash rate), the difficulty increases to maintain the block creation rate.
Block Rewards and Incentives : Miners are rewarded for their efforts with newly created bitcoins and
transaction fees. These incentives motivate miners to contribute their computational power to the network,
ensuring its continuous operation and security.
Decentralization:The Nakamoto Consensus operates without a central authority. It relies on a
decentralized network of miners and nodes spread around the world. This decentralization is crucial for the
security and resilience of the blockchain.
Trustless environment: The Nakamoto Consensus allows participants to transact without trusting each
other or a central authority. The protocol ensures that only valid transactions are approved.
Security: The combination of Proof of Work, difficulty adjustment, and decentralization makes the
network highly secure. It is resistant to attacks and data tampering.
Transparency: The blockchain is a public ledger, making all transactions visible to anyone. This
transparency ensures the system's trustworthiness and allows anyone to verify transactions.
Financial inclusion: Anyone with internet access can participate in the network, promoting financial
inclusion.
The validity of a transaction depends on successful execution of the Bitcoin Script. You can confirm a successful
execution when the top item on the stack at the end of execution is a non-zero value. On the other hand, an error or a
‘FALSE’ result upon completing execution means that the transaction is invalid.
Script is a mini programming language used as a locking mechanism for outputs in bitcoin transactions.
A locking script (ScriptPubKey) is placed on every transaction output.
An unlocking script (ScriptSig or Witness) must be provided to unlock an output (i.e. when used as an input to a
transaction).
If a full script (unlocking + locking) is valid, the output is "unlocked" and can be spent.
Example:
P2PKH (Pay-to-Public-Key-Hash): P2PKH is the most common type of Bitcoin transaction script.
It means:
“Pay to the hash of a public key”.
Instead of sending Bitcoin directly to a public key, it is sent to a hashed version of the public key.
Adds an extra layer of security and privacy.
Key Components
Public Key
o Generated from private key.
Public Key Hash
o Hash of the public key (used as address).
Private Key
o Used to unlock/spend funds.
o Digital Signature Proves ownership.
Script:
Combining 2 scripts, first verify the public key vs. address of the signer, then check the signature using the public key of the
signer.
scriptSig: <sig> <pubKeyA>
scriptPubKey: OP_DUP OP_HASH160 <addressA> OP_EQUALVERIFY OP_CHECKSIG
1.OP_DUP (Duplicate)
Duplicates the top item on the stack.
Why?
We need the public key twice:
o One copy for hashing
o One copy for signature verification
2. OP_HASH160
Applies two hash functions:
o SHA-256
o Then RIPEMD-160
Converts the public key into a public key hash.
Output: Hashed version of the public key
3. <PubKeyHash>
This is the expected public key hash (from the Bitcoin address).
Hardcoded in the locking script.
Acts like: “Only this specific address can spend the funds”
4. OP_EQUALVERIFY
Compares:
o Hash from OP_HASH160
o Given <PubKeyHash>
If equal → continue
If not → transaction fails immediately
Ensures correct public key is provided.
5. OP_CHECKSIG
Verifies the digital signature using the public key.
Checks:
o Signature is valid
o Matches the transaction data
Confirms ownership of private key.
How It Works Together (Flow)
When spending, the user provides:
Signature
Public key
Then:
1. OP_DUP → duplicate public key
2. OP_HASH160 → hash it
3. Compare with <PubKeyHash>
4. OP_EQUALVERIFY → must match
5. OP_CHECKSIG → verify signature