0% found this document useful (0 votes)
14 views20 pages

S-5 Finaltxt

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

S-5 Finaltxt

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

Consensus Mechanisms

- Jay Dave
1
Blockchain Technology (BITS F452)

Outline
Mining in Bitcoin
2

Mining in Bitcoin
Mining is the process of hashing the candidate block header repeatedly, changing
one parameter, until the resulting hash matches a specific target.
Hash function's features: Oneway, Collision Resistant, Fixed size output, Avalanche
effect.
echo "Hello, world" | sha256sum
Proof of work Algorithm:
Nonce: A variable, that is used to vary the output.
Let us make challenge.
Find a phrase that produces a hexadecimal hash that starts with a zero. Message is
"Hello, World!".
for nonce in $( seq 100 ); do
echo "$nonce: $(echo "Hello, world! $nonce" | sha256sum)"
done
3

Mining in Bitcoin
Imagine a game where players throw a pair of dice repeatedly, trying to throw less
than a specified target.
Target 1: 12, then Prob: 35/36
Target 2: 11, then Prob: 33/36
Target 3: 5, then Prob: 6/36
Now, let us look at our PoW challenge: “Find a phrase that produces a hexadecimal
hash that starts with a zero.”
In numerical terms, that means finding a hash value that is less than
0x1000000000000000000000000000000000000000000000000000000000000000.
To increase difficulty and decrease winning probability, we need to increase more
prefix zeros as a target.
In other words, finding less than a smaller target.
4

Mining in Bitcoin
https://www.blockchain.com/explorer/blocks/btc/866903
Target Representation
0x1702F128 (i.e., 386,068,776)
target = coefficient * (2^(8 * (exponent - 3)))
exponent: First two hex digits. E.g. 0x17
coefficient: Other digits. E.g. 0x02F128
target = 0x02F128 * (2^(8 * (0x17 - 3)))
It is 192808 * (2^(8*(23-3))) = 192808 * (2^(160)) = (2^17) * (2^160). Almost 256 -
167 = 89 zeros are needed.
5

Mining in Bitcoin
Proof of work formula:

Hash(Block Header + Nonce) < Target


6

Mining in Bitcoin
Adjust Difficulty:
Why is the difficulty adjustable, who adjusts it, and how?
Bitcoin’s heartbeat: Blocks are generated every 10 minutes, on average.
It remained constant for decades.
Over this time, it is expected that computer power will continue to increase at a
rapid pace.
No. of participants in mining and computers they use will also constantly change.
To keep the block generation time at 10 minutes, the difficulty of mining must be
adjusted to account for these changes.
Every 2,016 blocks, all nodes retarget the PoW.
New Difficulty = Old Difficulty * (20,160 minutes / Actual Time of Last 2015
Blocks)
If network is finding blocks faster than every 10 min, difficulty increases (target
decreases). If block discovery is slower than expected, difficulty decreases
(target increases).
Current Target = Target of Genesis Block/Difficulty
https://www.blockchain.com/explorer/blocks/btc/864887
7

Mining in Bitcoin
Median Time Past (MTP):
difference between wall time and consensus time
Bitcoin is a decentralized network, which means that each participant has his or
her own perspective of time.
Events on network do not occur instantaneously everywhere.
Network latency
Bitcoin reaches consensus every 10 minutes about state of blockchain as it existed
in past.
Timestamps in block headers are set by miners.
Certain degree of latitude allowed by consensus rules to account for differences in
clock accuracy between decentralized nodes.
However, it creates an unfortunate incentive for miners to lie about time in a
block.
For example,
if a miner sets their time in the future, they can lower difficulty, allowing them
to mine more blocks and claim some of the block subsidy reserved for future miners.
If they can set their times in the past for some blocks, they can use the current
time for some other blocks, and so again make it look like there’s a long time
between blocks for the purpose of manipulating difficulty.
8

Mining in Bitcoin
Median Time Past (MTP):
Mitigation: Two consensus rules
1) no node will accept any block with a time further in the future than two hours.
2) no node will accept a block with a time less than or equal to the median time of
the last 11 blocks, called median time past (MTP).
MTP became the consensus time used for all timelock calculations.
By taking the midpoint from approximately two hours in the past, the influence of
any one block’s timestamp is reduced.
By incorporating 11 blocks, no single miner can influence the timestamps in order
to gain fees from transactions with a timelock that hasn’t yet matured.
MTP changes the implementation of time calculations for lock time, CLTV, sequence,
and CSV.
9

Mining in Bitcoin
Successfully Mining the Block
Jing’s node has constructed a candidate block and prepared it for mining.
Almost 11 minutes after starting to mine a particular block, one of the hardware
mining machines finds a solution and sends it back to the mining node.
Immediately, Jing’s mining node transmits the block to all its peers. They receive,
validate, and then propagate the new block.
As the block ripples out across the network, each node adds it to its own copy of
the blockchain, extending it to a new height.
As mining nodes receive and validate the block, they abandon their efforts to find
a block at the same height.
10

Mining in Bitcoin
Validating a New Block
Independent validation of each new block by every node on the network.
Independent validation ensures that only blocks that follow the consensus rules are
incorporated in blockchain.
Blocks that violate the rules are rejected and lose their miners the reward.
When a node receives a new block, it will validate through CheckBlock and
CheckBlockHeader.
11

Mining in Bitcoin
Validating a New Block
The block data structure is syntactically valid.
The block header hash is less than the target (enforces the proof of work).
The block timestamp is between the MTP and two hours in the future (allowing for
time errors).
The block weight is within acceptable limits.
The first transaction (and only the first) is a coinbase transaction.
12

Mining in Bitcoin
Validating a New Block
All txns within the block are valid using the txn checklist.
The txn’s syntax and data structure must be correct.
Neither lists of inputs nor outputs are empty.
The txn weight is low enough to allow it to fit in a block.
Each output value, as well as the total, must be within the allowed range of values
(zero or more, but not exceeding 21 million bitcoins).
Lock time is equal to INT_MAX, or lock time and sequence values are satisfied
according to the lock time and BIP68 rules.
The number of signature operations (SIGOPS) contained in the txn is less than the
signature operation limit.
The outputs being spent match outputs in the mempool or unspent outputs in a block
in the main branch.
For each input, if the referenced output txn is a coinbase output, it must have at
least COINBASE_MATURITY (100) confirmations. Any absolute or relative lock time
must also be satisfied. Nodes may relay txns a block before they mature since they
will be mature if included in the next block.
Reject if the sum of input values is less than sum of output values.
The scripts for each input must validate against the corresponding output scripts.
13

Mining in Bitcoin
Validating a New Block
Independent validation of each new block by every node on network ensures that
miners cannot cheat.
Why don’t miners write themselves a transaction for a thousand bitcoins instead of
the correct reward?
Because every node validates blocks according to same rules.
An invalid coinbase transaction would make the entire block invalid, which would
result in block being rejected and, therefore, that transaction would never become
part of the blockchain.
Miners have to construct a block, based on the shared rules that all nodes follow,
and mine it with a correct solution to the PoW.
14

Mining in Bitcoin
The Extra Nonce Solution
Initially, miners used a small number (called a "nonce") to change the input of the
mining process to try to find a valid block.
As Bitcoin mining became more difficult, miners started cycling through all
possible nonce values (4 billion possibilities) without finding a valid block.
As mining hardware got faster (especially with ASICs), it became so quick that
miners would run through all possible nonce values in less than a second, making it
harder to find valid blocks.
Miners needed more space to keep changing things in the block header so they could
continue mining efficiently.
That’s where the idea of an "extra nonce" came in—an additional space to modify,
giving miners more combinations to try without running into the same limitations as
before.
In short, as mining hardware got faster, miners ran out of numbers (nonces) to try
in a short amount of time.
The extra nonce was introduced to give them more flexibility to continue finding
valid blocks.
15

Mining in Bitcoin
The Extra Nonce Solution (Solution 1):
Coinbase Transaction: The coinbase transaction has some extra space (2 to 100
bytes) where miners can store data.
More Possibilities: By adding 8 bytes of extra nonce (along with the standard 4
bytes of nonce), miners now have 2^96 possible combinations to try each second
without needing to adjust the block’s timestamp.
Merkle Tree and Root: When miners change the coinbase transaction, it also changes
something called the "merkle root," which is part of the block’s header. This means
any small change to the extra nonce creates a new version of the block that can be
tested by miners.
In short, by using extra space in the coinbase transaction to store more nonce
values, miners can test far more combinations to find valid blocks without having
to mess with the block’s time settings.
This made mining much more efficient.
16

Mining in Bitcoin
The Extra Nonce Solution (Solution 2):
If miners only used the coinbase transaction to change the extra nonce, they’d have
to update the whole "merkle tree" (a structure that organizes all transactions in
the block) every time they ran out of nonce values (every 4 billion hashes).
This is a more complicated process. By using the versionbits field instead, miners
can avoid this complexity, keeping the process simpler and faster.
Using the versionbits field allows miners to test more combinations (hashes)
without needing to change and recalculate other parts of the block, making mining
more efficient and straightforward.
17

Mining in Bitcoin
Mining Pools:
Group of miners who combine their computing power to increase their chances of
solving a cryptographic puzzle (i.e., finding a valid block) and earning a reward.
Instead of working alone (solo mining), where the chances of finding a block can be
very low, especially with high mining difficulty, miners in a pool share their
resources and split the rewards according to each participant's contribution to the
total pool’s effort.
Important in networks like Bitcoin, where the difficulty of mining has grown
tremendously, making solo mining less feasible for most individuals.
18

Mining in Bitcoin
Mining Pools:
How it works
Pooling Resources: Miners in a pool contribute their hashing power (computing
power) to work on finding a block. The pool’s total hashing power increases, making
it more likely that the pool, as a whole, will find a block and earn the mining
reward.
Splitting Rewards: When a mining pool successfully mines a block, the reward (which
includes the block subsidy and transaction fees) is distributed among all the
participants based on their contribution to the pool’s total hashing power.
Pool Operator: Most mining pools are managed by a pool operator, who coordinates
the distribution of work among miners and ensures that the rewards are shared
fairly. Takes a small fee from the mining rewards for managing the pool.
Examples: F2Pool, Braiins Pool, ViaBTC, BTC.com.
Possible threats: 51% attack, Dependence on Pool Operator
19

Mining in Bitcoin
Hashrate Attacks
majority attack or 51% attack
controlling a majority of the total network’s hashing power (such as 51%), collude
to attack Bitcoin.
With the ability to mine the majority of the blocks, the attacking miners can cause
deliberate “forks” in the blockchain and double-spend transactions or execute
denial-of-service attacks against specific transactions or addresses.
A fork/double-spend attack is where the attacker causes previously confirmed blocks
to be invalidated by forking below them and reconverging on an alternate chain.
With sufficient power, an attacker can invalidate six or more blocks in a row,
causing transactions that were considered immutable (six confirmations) to be
invalidated.
20

Mining in Bitcoin
Scenario 1: Double Spending
Malicious attacker Mallory goes to Carol’s gallery and purchases a set of beautiful
paintings. Say $250,000 in bitcoins.
Instead of waiting for six or more confirmations on the transaction, Carol wraps
and hands the paintings to Mallory after only one confirmation.
Mallory works with an accomplice, Paul, who operates a large mining pool, and
accomplice launches an attack as soon as Mallory’s transaction is included in a
block.
Paul directs mining pool to remine the same block height as the block containing
Mallory’s transaction, replacing Mallory’s payment to Carol with a transaction that
double-spends the same input as Mallory’s payment.
21

Mining in Bitcoin
Scenario 1: Double Spending
The double-spend transaction consumes the same UTXO and pays it back to Mallory’s
wallet instead of paying it to Carol.
Paul then directs the mining pool to mine an additional block, so as to make the
chain containing the double-spend transaction longer than the original chain,
When the blockchain fork resolves in favor of the new (longer) chain, the double-
spent transaction replaces the original payment to Carol.
To protect against this kind of attack, a merchant selling large-value items must
wait at least six confirmations before giving the product to the buyer. Waiting for
more than six confirmations may sometimes be warranted.
The more confirmations elapse, the harder it becomes to invalidate a transaction by
reorganizing the blockchain.
For high-value items, payment by bitcoin will still be convenient and efficient
even if the buyer has to wait 24 hours for delivery, which would correspond to
approximately 144 confirmations.
22

Mining in Bitcoin
Scenario 2: Deny service to specific participants (specific Bitcoin addresses).
An attacker with a majority of the mining power can censor transactions.
If they are included in a block mined by another miner, the attacker can
deliberately fork and remine that block, again excluding the specific transactions.
This type of attack can result in a sustained denial-of-service against a specific
address or set of addresses for as long as the attacker controls the majority of
the mining power.
23

Mining in Bitcoin
MINING POOLS: How pool divides work?
Receiving Block Information: Pool manager prepares a new block template, which
includes unconfirmed transactions that miners will try to include in the next
block.
Dividing the Work:
Pool manager assigns work to each miner by giving them the block header and a
portion of the nonce space to search for a valid solution.
Pool also provides each miner with a unique extranonce, which is a special field
used to extend the range of nonces each miner can work on.
This ensures that multiple miners aren't working on the exact same range of nonces.
Setting a Share Difficulty:
Pool manager sets a share difficulty, which is lower than the full network
difficulty.
This allows miners to submit "shares" more frequently, demonstrating that they are
working without needing to solve the full puzzle.
Each miner’s job is to find a hash that meets the share difficulty (an easier
target) and submit it as a proof of work to the pool.
Adjusting Work Based on Miner Capacity: Pool manager can distribute more or less
work to each miner based on their hash rate (computational power).
24

Mining in Bitcoin
MINING POOLS
Everybody trusts pool manager.
But, how pool manager confirms that all are working?
1. Pool manager generates and shares a block template based on current blockchain
state, which includes:
- Latest block header,
- A list of pending transactions,
- Target difficulty,
- A unique identifier for pool's work ("job").
2. Regular Submissions (Proof of Effort):
- Miners submit "shares" to pool manager.
- A share is a valid solution to pool’s lower difficulty.
- Even though share is not likely to be a valid block for Bitcoin network (since it
meets pool’s lower difficulty), it proves that miner is doing work.
25

Mining in Bitcoin
MINING POOLS
3. Verification of Work: Pool manager verifies each submitted share to check:
- Whether share meets pool’s difficulty.
- If share has correct block template.
- If miner is using correct nonce or extra nonce range provided by pool.
4. Tracking Miner Performance:
- Pool manager tracks how many shares each miner submits.
- Since number of shares a miner submits correlates with their hashing power, this
allows pool to monitor which miners are actively contributing and how much.
- If a miner stops submitting shares (for example, due to a malfunction), pool
manager can detect this and take appropriate action, like flagging miner or halting
payouts.
26

Mining in Bitcoin
Mining Shares
Miners can prove probabilistically how much work they’re doing by outputting
shares, or near-valid blocks.
Suppose the target is a number beginning with 67 zeros.
A block’s hash must be lower than the target for the block to be valid.
In the process of searching for such a block, miners will find some blocks with
hashes beginning with a lot of zeros, but not quite 67.
Miners can show these nearly valid blocks to prove that they are indeed working.
A share might require say 40 or 50 zeros, depending on the type of miners the pool
is geared for.
27

Mining in Bitcoin
Mining Shares
The pool manager will also run a Bitcoin node on behalf of participants, collecting
transactions and assembling them into a block.
The manager will include her own address in the coinbase transaction and send the
block to all participants in the pool.
All pool participants work on this block, and they prove that they’ve been working
on it by sending in shares.
When a member of the pool finds a valid block, he sends it to the pool manager, who
distributes the reward in proportion to the amount of work done.
The miner who actually finds the block is not awarded a special bonus, so if
another miner did more work, the latter miner will be paid more, even though he
wasn’t the one who found the valid block.
There are a few options for how exactly the pool manager calculates how much to pay
each miner based on the shares they submit.
28

Mining in Bitcoin
Pay-per-Share model (PPS)
Pool manager pays a flat fee for every share above a certain difficulty for the
block that the pool is working on, regardless of whether pool successfully finds a
block.
Miners can send their shares to the pool manager right away and get paid without
waiting for the pool to find a block.
Pay-per-share model is the best for miners.
They are guaranteed a certain amount of money every time they find a share.
Pool managers essentially absorb all risk, as they pay rewards even if a block is
not found.
As a result of the increased risk, pool manager will probably charge higher fees
compared with other models.
29

Mining in Bitcoin
Pay-per-Share model (PPS)
Example:
Imagine a Bitcoin pool that sets its pool difficulty level, allowing miners to
submit a share roughly every 10 seconds.
Let’s say a miner submits 1000 shares in an hour.
Pool has calculated that each share is worth 0.0001 BTC.
After submitting 1000 shares, the miner would receive:
Payout = 1000 shares * 0.0001 BTC/share = 0.1 BTC
Issue:
One problem with the pay-per-share model is that miners don’t actually have any
incentive to send valid blocks to the pool manager.
That is, they can discard valid blocks but still be paid the same rewards, which
will cause a big loss to the pool.
30

Mining in Bitcoin
Proportional
In the proportional model, instead of paying a flat fee per share, the amount of
payment depends on whether the pool actually finds a valid block.
Every time a valid block is found, the rewards from that block are distributed to
the members proportional to how much work they actually did.
Less risk for pool manager
Example:
Suppose a mining pool is working on a block and has a total of 10,000 shares
submitted by all miners during the round. The pool successfully finds the block,
which gives a reward of 6.25 BTC.
Let’s say Miner A submitted 1,000 shares, Miner B submitted 2,000 shares, and Miner
C submitted 7,000 shares during this mining round. Total = 10000 shares
Miner A’s share of the total = 1,000 / 10,000 = 0.10. Miner B’s share of the total
= 2,000 / 10,000 = 0.20. Miner C’s share of the total = 7,000 / 10,000 = 0.70.
Miner A’s reward = 6.25 BTC * 0.10 = 0.625 BTC. Miner B’s reward = 6.25 BTC * 0.20
= 1.25 BTC. Miner C’s reward = 6.25 BTC * 0.70 = 4.375 BTC.
31

Mining in Bitcoin
Proportional:
Issues:
No Guaranteed Income
Unpredictable Earnings
Pooling Risks: Pool-hoppers issue.
Pool-hopping is a strategy used by some miners to maximize their profits by
switching between different mining pools based on their perceived chances of
receiving higher payouts.
A pool-hopper closely monitors the mining rounds of several mining pools. They
focus on pools that are using the Proportional payout system.
They look for signs that a pool is nearing the end of a mining round, which could
indicate that a block might soon be found.
When a mining round has already accumulated a large number of shares but has not
yet found a block, pool-hoppers will start mining in that pool.
They submit shares toward the end of the round.
If the pool does not find a block soon after the pool-hopper joins, they leave the
pool and switch to another one.
By hopping from pool to pool, they avoid contributing to longer mining rounds,
where the reward per share would be lower.
32

Mining in Bitcoin
Pay-Per-Last-N-Shares (PPLNS)
Rewards miners for their contributions based on the last number of shares they
submitted, leading to the solution of a block.
Unlike other schemes like Pay-Per-Share (PPS), PPLNS ties payouts directly to
successful block mining, and rewards are based on how much miners contributed to
solving a specific block rather than over a set period.
Steps:
Each miner continues submitting shares as they work on solving the block.
When one of the miners in the pool successfully solves the block (by finding a hash
below the network difficulty target), the block reward (such as 3.125 BTC in
Bitcoin) is awarded to the pool.
Instead of paying miners based on all the shares submitted since the last block,
the pool only considers the last N shares submitted up to the point when the block
was mined.
Each miner’s reward is proportional to the number of shares they contributed to
this set of N shares. The more shares a miner submitted within this window, the
higher their reward.
Miner’s Reward = (Miner’s Shares in N / Total N Shares) * Block Reward
Anti-Pool-Hopping: Since only the last N shares are rewarded, miners are
incentivized to stay in the pool consistently to maximize their share of the
rewards.
33

Mining in Bitcoin
Full Pay-Per-Share (FPPS)
An enhanced version of PPS.
In traditional PPS model, miners are paid a fixed amount for each share they
submit, regardless of whether pool finds a block.
However, FPPS goes a step further by including both the block reward and the
transaction fees in the calculation of payouts.
Miners submit shares to the pool.
When a block is successfully mined, the miner or mining pool receives a block
reward, which is a fixed amount of cryptocurrency.
In a typical PPS system, the pool would pay miners based on the block reward alone,
meaning each share would have a fixed payout based on the value of the block
reward.
With FPPS, the pool also calculates the average transaction fees over time and
includes these fees in the payout structure.
This gives miners a share of the transaction fees that are included in each block,
which can significantly increase the payout.
Like PPS, FPPS provides miners with consistent payouts because miners are paid for
each share they submit, regardless of whether the pool finds a block. However, FPPS
adds more value to each share by including the transaction fees.
Higher Payouts, Consistent and Predictable, Transaction Fee Inclusion, Less Risk
for Miners.
Pool Operator’s Risk
34

Mining in Bitcoin
Score based
Ensures that miners are rewarded fairly based on their contribution during a mining
round.
This method addresses some of the issues associated with traditional payout models
like Proportional by discouraging certain behaviors, such as pool-hopping.
Steps:
When a miner submits a share, the pool assigns it a score based on how recently the
share was submitted.
Shares submitted later in the round have lower scores.
When the mining pool successfully solves the block, the pool stops the round and
calculates the payouts based on the scores of the miners.
Each miner’s reward is proportional to the total score they have accumulated during
the round.
Example
Miner A starts mining early in the round and contributes 100 shares.
Miner B starts midway through the round and submits 80 shares.
Miner C joins toward the end of the round and submits 60 shares.
Now, since the score-based system gives higher weight to shares submitted later in
the round:
Miner A’s early shares receive a higher score because of the decay factor.
Miner B’s shares receive a moderate score, as they were submitted midway.
Miner C’s shares receive the lower score, as they were submitted closest to the
block discovery.
35

Mining in Bitcoin
Capped Pay-Per-Share with Recent Backpay (CPPSRB)
It is designed to ensure that miners receive stable and predictable payouts while
also addressing the financial risks that pools face in Pay-Per-Share (PPS) models.
Combines Pay-Per-Share (PPS) and backpay.
It caps payouts based on the mining pool’s current balance, ensuring the pool never
overpays miners even if it experiences a period of bad luck (not finding blocks
quickly).
CPPSRB introduces a cap on payments to miners, meaning the pool only pays out
miners as long as it has a positive balance.
If the pool’s balance is low (e.g., during a streak of bad luck where no blocks are
found), the payouts to miners are capped, preventing the pool from running out of
funds.
When the pool’s balance recovers (e.g., after finding blocks and receiving
rewards), miners are paid any backpay they are owed for shares they submitted when
payments were capped.
This ensures that miners eventually get paid for all their valid work, even if they
weren’t paid immediately.
36

Mining in Bitcoin
Capped Pay-Per-Share with Recent Backpay (CPPSRB)
Steps:
As miners contribute hashing power to the pool, they submit shares proving their
work.
Miners are paid a fixed amount per share, just like in a PPS system. However, the
total amount the pool can pay out is limited by its current balance. If the pool
has sufficient funds, it pays out miners in full for each share.
If the pool’s balance falls below a certain threshold, the pool begins to cap
payments. This means miners may not receive their full payouts immediately. For
example, if the pool’s balance is low, miners might only receive 50% or less of the
usual PPS rate.
Any amount that miners are not paid due to the cap is recorded as backpay. This
means that even though miners aren’t receiving their full payout right away, the
pool keeps track of how much it owes them.
Once the pool finds new blocks and its balance improves, it starts paying out the
accumulated backpay to miners. This ensures that miners eventually receive full
payment for the work they’ve done, even if there was a delay.
Constant Payouts and Pool Solvency: The key advantage of CPPSRB is that it combines
the steady payouts of PPS with a safeguard against the pool running out of funds.
The capping mechanism ensures that the pool remains solvent during periods of bad
luck, while the backpay mechanism ensures that miners don’t lose out on payments
long-term.
37

Mining in Bitcoin
Chains and Proof of Work:
The best blockchain is the one with the most Proof of Work (PoW), meaning it
requires the most computational effort to create.
This effort secures the chain and makes it trustworthy.
Main Chain and Branches:
Sometimes, multiple valid chains (branches) can exist temporarily, with blocks that
are “siblings” to those on the main chain.
These sibling blocks are valid but are not on the main chain because they have less
cumulative PoW.
These branches are saved just in case they later outgrow the main chain.
This branching often happens when two blocks are mined almost simultaneously.
38

Mining in Bitcoin
How Nodes Handle New Blocks:
When a node receives a new block, it checks if the block connects to the end (tip)
of the main chain. If it does, the block is added, extending the best chain.
If the new block doesn’t connect to the main chain, it might start or extend a
secondary chain. The node compares this secondary chain’s PoW with the main
chain’s.
If the secondary chain has more PoW than the main chain, the node switches to the
secondary chain as the new main chain and updates its records of confirmed
transactions.
Reaching Consensus:
By always choosing the chain with the most PoW, all nodes eventually agree on the
same main chain.
Differences between branches are resolved as new blocks are added to one chain,
making it the longest and most reliable.
39

Mining in Bitcoin
Forks and Resolution:
Forks (when two chains exist at once) are typically resolved quickly, usually
within a block.
If two blocks are mined at the same height on different branches, they’ll both try
to extend their branch.
However, as soon as a new block is added to one branch, it becomes the longest and
is accepted as the main chain.
Forks extending beyond one block are rare but can happen if two blocks are mined
simultaneously by miners who don’t yet know about each other’s blocks.
Block Time and Forks:
Bitcoin’s 10-minute block time balances quick transaction confirmations and fork
frequency.
Faster blocks would confirm transactions more quickly but lead to more frequent
forks, while slower blocks reduce forks but slow down transaction settlement.
40

Mining in Bitcoin
Hard Fork:
a significant change to the rules of a blockchain protocol that is not backward-
compatible, meaning the updated version of the blockchain will follow a new set of
rules and diverge from the previous version.
causes a permanent split in the blockchain, leading to two separate chains: one
that follows the old rules and one that follows the new, updated rules.
Developers propose a set of changes to the blockchain’s protocol, often to improve
functionality, add new features, or address security vulnerabilities.
Once the changes are agreed upon by a portion of the community, the new protocol
version is implemented, resulting in a permanent fork in the chain.
Nodes that upgrade to the new version recognize and validate only the blocks
following the new rules, while nodes that don’t upgrade recognize only the blocks
following the old rules.
Reasons for a Hard Fork: 1) Feature Enhancements, e.g., increase the block size and
improve transaction speed, 2) Bug Fixes or Security Patches, 3) Community
Disagreements
Types: 1) Planned Hard Fork: A planned hard fork is when a fork is scheduled in
advance and agreed upon by the majority of the community, 2) Contentious Hard Fork:
A contentious hard fork happens when there is disagreement within the community.
This typically results in a permanent split, with one part of the community
supporting the old version and another part supporting the new version.
41

Mining in Bitcoin
Hard Fork Example: Bitcoin and Bitcoin Cash:
Reason: The Bitcoin community was divided over how to handle scalability. Some
wanted to increase the block size limit (allowing more transactions per block),
while others wanted to keep the block size small to maintain decentralization.
Outcome: Unable to agree, a hard fork was implemented. Bitcoin Cash was created
with a larger block size, allowing faster and cheaper transactions, while Bitcoin
retained its smaller block size and layered scaling approach.
Result: Two separate blockchains and cryptocurrencies were created. Bitcoin
remained the primary chain with BTC, and Bitcoin Cash continued on a new chain with
BCH as its currency.
42

Mining in Bitcoin
Hard Fork Effects:
When a hard fork happens, miners can choose to work on either the old or the new
chain, which divides the total mining power (hashing power) between them.
Split in Mining Power: After a fork, miners are split between two chains. For
example, let’s say 80% of miners switch to the new chain while 20% stick with the
old one. This results in an 80/20 split of the total mining power.
Impact on Block Time for Each Chain:
New Chain (80% Mining Power): With 80% of the original mining power, block creation
on this chain will be a bit slower, averaging 12.5 minutes per block (since there’s
less power than before). This slower rate will continue for 2,016 blocks (about
17.5 days).
Old Chain (20% Mining Power): The old chain has only 20% of the original power, so
it will take much longer to mine blocks. Block times will average 50 minutes per
block (5 times slower). This longer block time will last for the full 2,016 blocks,
which would take about 10 weeks before the next difficulty adjustment.
43

Mining in Bitcoin
Hard Fork Effects:
If 100% power can complete work in 10 minutes, then 80% power can complete work in
___ minutes.
Total Work = Work Rate of 100% Power × 10 minutes
Work Rate of 100% Power = Total Work/ 10 minutes
Work Rate of 100% Power = 1 job/10 minutes = 0.1 job per minute
Work Rate of 1% Power = 0.1 job per minute/100 = 0.001 job per minute
(New) Work Rate of 80% Power = 80×0.001 = 0.08 job per minute
Time = 1 job/0.08 job per minute = 12.5 minutes
(Old) Work Rate of 20% Power = 20×0.001 = 0.02 job per minute
Time = 1 job/0.02 job per minute = 50 minutes

44

Mining in Bitcoin
45

Mining in Bitcoin
Soft Fork
A type of upgrade or modification to a blockchain protocol that is backward
compatible.
This means that even nodes that do not upgrade to the new version of the software
can still communicate and operate with nodes that have adopted the update.
Characteristics of Soft Forks: Backward Compatibility, Less Risky, Minor Changes
How Soft Forks Work
Implementation: A soft fork is initiated by proposing changes to the existing
protocol. This is usually done through a community consensus or a proposal by
developers.
Signaling and Activation: Soft forks often utilize a signaling mechanism, where
nodes can indicate their support for the proposed changes. Once a sufficient
majority of nodes signal support, the new rules are activated.
Examples of Soft Forks: Bitcoin's BIP 66 (Strict DER Signatures), Bitcoin's
Segregated Witness (SegWit)
46

Mining Hardware
Central Processing Unit (CPU) Mining
Graphics Processing Unit (GPU) Mining
Field-Programmable Gate Arrays (FPGAs)
Application-Specific Integrated Circuits (ASICs)
Next-Generation Mining Hardware
47

Mining Hardware
Central Processing Unit (CPU) Mining:
Early 2009–2011
As simple as running this code.
TARGET = (65535 << 208) / DIFFICULTY;
coinbase_nonce = 0;
while (1) {
header = makeBlockHeader (transactions, coinbase_nonce);
for (header_nonce = 0; header_nonce < (1 << 32); header_nonce++) {
if (SHA256(SHA256 (makeBlock (header, header_nonce))) < TARGET)
break; //block found!
}
coinbase_nonce++;
}
48
For Bitcoin, the maximum target is the constant:
0x00000000FFFF0000000000000000000000000000000000000000000000000000
65535 is FFFF. That is left shifted with 208 zeros in binary i.e., 52 zeros hex.
The remaining 8 zeros are as prefix.
makeBlockHeader() is assumed as a function that constructs the block header using
the current set of transactions and the coinbase_nonce. The block header contains
important information such as the hash of the previous block, the Merkle root of
the transactions, a timestamp, the target, and the header_nonce.
Header Nonce, trying all possible 32 bits values
A hypothetical function that creates the complete block (block header +
transactions) using the header and header_nonce.

Mining Hardware
Central Processing Unit (CPU) Mining:
On a desktop/laptop, you are expected to compute about 20 million hashes per
second.
CPU mining quickly became inefficient as the network’s difficulty increased and
miners began seeking more powerful hardware.
No longer profitable at the current level of difficulty.
49

Mining Hardware
Graphics Processing Unit (GPU) Mining:
2011–2013
GPUs—designed to handle parallel processing—could perform SHA-256 computations much
faster than CPUs.
GPUs have more cores and are optimized for tasks like image rendering, but they
also proved useful for Bitcoin mining.
Built for video processing, Consumes large amount of power.

50

Mining Hardware
Field-Programmable Gate Arrays (FPGAs):
2012–2013
After GPU mining became widespread, some miners moved to FPGAs, which are custom-
built circuits that can be reprogrammed to optimize mining performance.
FPGAs are more efficient and use less power than GPUs.
51

Mining Hardware
Application-Specific Integrated Circuits (ASICs):
2013–Present
ASICs are specialized hardware designed specifically for mining Bitcoin.
Unlike CPUs, GPUs, and FPGAs, ASICs are custom-designed for one specific task:
mining the SHA-256 algorithm.
They are much more efficient than previous mining hardware, both in terms of power
consumption and processing speed.
52

Mining Hardware
Next-Generation Mining Hardware:
Ongoing advancements
The evolution of ASIC mining hardware continues, with manufacturers developing more
powerful and efficient chips.
53

Mining Hardware
ENERGY CONSUMPTION AND ECOLOGY
Bitcoin is not quite at that level yet, but it is starting to use a significant
amount of energy, which has become a topic of discussion.
Landauer's Principle: Erasing one bit of information (changing a bit from 1 to 0 or
vice versa) in any physical system must dissipate at least a minimum amount of
energy, given by the formula:
Emin = kBT ln (2)
Emin is the minimum energy required to erase one bit of information.
kB is the Boltzmann constant (1.38 x 10-23 Joules/Kelvin).
T is temperature of computing system in Kelvin.
ln(2) accounts for the binary nature of information storage (bit values of 0 or 1).
54

Mining Hardware
ENERGY CONSUMPTION AND ECOLOGY
Energy is never destroyed; it’s converted from one form to another. Electricity to
Heat.
How does Bitcoin mining use energy?
Embodied energy: Bitcoin mining equipment needs to be manufactured. This requires
physical mining of raw materials as well as turning these raw materials into a
Bitcoin mining ASIC, both of which require energy. This is the embodied energy.
Electricity: When your ASIC is powered on and mining, it consumes electricity. This
is the step that we know has to consume energy due to Landauer’s principle.
As mining rigs become more efficient, the electrical energy costs will go down. But
because of Landauer’s principle; electrical energy consumption will be a fact of
life for Bitcoin miners forever.
Cooling: Bitcoin mining equipment needs to be cooled to prevent it from
malfunctioning. Generally, the energy used to cool off mining equipment will also
be in the form of electricity.
55

Mining Hardware
Estimating Energy Usage
How much energy is the entire Bitcoin system using? Of course, we can’t compute
this precisely, because it’s a decentralized network with miners operating all over
the place without documenting exactly what they’re doing.
But there are two basic approaches to estimating how much energy Bitcoin miners are
using collectively.
TOP-DOWN APPROACH
We start with the simple fact that every time a block is found today, 3.125
bitcoins. It is roughly 215561.8125 USD, 18131011.83 INR at 4-Nov-2024. Means 30218
INR per second.
Now let’s ask this question: if the miners were turning all of that 30218 INR per
second into electricity, how much can they buy?
6.29 INR for 1 kilowatt-hour, then 30218 INR can buy 4804.13 kilowatt-hour, i.e.,
2,88,247.8 kilowatt-minutes.
Assuming 120 TWh/year (as an average estimate for the Bitcoin network's power
consumption),
Energy per block = 120TWh / 52,560 blocks = 2.28MWh/block = 1,36,800 kilowatt-
minutes
56

Mining Hardware
BOTTOM-UP APPROACH
Let us assume that the best-claimed efficiency among commercially available mining
rigs is about 3 gigahashes per second per watt.
That is, the most cutting-edge ASICs claim to perform 3 billion hashes per second
while consuming 1 watt of power.
The total network hash rate is about 350,000,000 gigahashes per second, or
equivalently, 350 petahashes per second.
Multiplying these two together, we see that it takes about 117 megawatts to produce
that many hashes per second at that efficiency.
Of course this figure excludes all of the cooling energy and all of the embodied
energy that’s in those chips, but we’re doing an optimal calculation and deriving a
lower bound, so that’s okay.
According to our estimates then, the whole Bitcoin network is consuming perhaps 10
percent of a large power plant’s output.
Although this is a significant amount of power, it’s still small compared to all
the other things that people are using electricity for on the planet.
57
Mining Hardware
Is Bitcoin Mining Wasteful?
It’s often said Bitcoin wastes energy, because the energy expended on SHA-256
computations does not serve any other useful purpose.
With traditional currency, considerable energy is consumed printing currency and
running ATM machines, coin-sorting machines, cash registers, and payment processing
services, as well as transporting money and gold bullion in armored cars.
You could equally argue that all of this energy is wasted, in that it doesn’t serve
any purpose besides maintaining the currency system.
58

Mining Hardware
Repurposing Energy
This model of capturing waste heat from computation is called the data furnace
approach.
Instead of buying a traditional electric heater to heat your home, or to heat water
in your home, you could buy a heater that doubled as a Bitcoin mining rig, mining
bitcoins and heating up your home as a by-product of that computation.
Of course, it is less efficient than conventional heaters. And also mining hash
power might go down seasonally based on how much heat people need.
59

PoW in Ethereum
60

PoW in Ethereum
1. Transaction Broadcast: Users initiate transactions on the Ethereum network.
These transactions are propagated to all nodes and collected into a transaction
pool (also called the mempool).
2. Block Construction: A miner picks pending transactions from the mempool and
assembles them into a candidate block. The miner ensures transactions are valid by
checking digital signatures and verifying balances.
3. Block Header: The miner creates a block header that contains:
Parent Hash: The hash of the previous block.
Merkle Root: The hash of all transactions in the block, organized in a Merkle tree.
Nonce: A value miners adjust to find a valid block hash.
Difficulty: The target level of difficulty for mining this block.
Timestamp: The time the block was created.
61

PoW in Ethereum
4. Mining Puzzle: Miners must find a hash of the block header that is less than or
equal to the target value (determined by the difficulty level).
The hashing algorithm used in Ethereum's PoW is Ethash, which is specifically
designed to be memory-intensive to reduce the advantage of ASICs over GPUs.
5. Difficulty Adjustment
The difficulty is dynamically adjusted based on the network’s total computational
power (hashrate) to maintain a block time of approximately 15 seconds. If blocks
are mined too quickly, the difficulty increases, and vice versa.
Key issue: Mining requires significant computational power and energy consumption,
contributing to environmental concerns.
62

Proof of Stake
Proof of Stake (PoS) is a consensus mechanism used in Ethereum (post-merge) and
other blockchains to achieve agreement among network participants (validators) on
the state of the blockchain.
Unlike Proof of Work (PoW), where miners solve complex puzzles to add blocks, PoS
relies on validators who are selected based on the amount of cryptocurrency they
"stake" (lock up as collateral).
Key Concepts of Proof of Stake
1) Staking: Participants (validators) lock up a certain amount of cryptocurrency
(stake) to gain the right to validate blocks. The stake acts as collateral, which
can be penalized (slashed) for malicious behavior.
2) Validators: Validators are responsible for proposing and validating new blocks.
They are incentivized with rewards in the form of transaction fees or newly minted
cryptocurrency.
3) Selection Process: Validators are chosen to propose a block based on a
combination of factors such as the size of their stake and a pseudorandom selection
algorithm.
4) Finality: Transactions are finalized when enough validators have agreed on the
block, making it immutable.
63

Proof of Stake
Step 1: Stake Deposits
Participants become validators by depositing a specified amount of cryptocurrency
(e.g., 32 ETH in Ethereum).
The stake is locked in a smart contract, “Beacon Chain Deposit Contract” on the
blockchain.
Validators enter an activation queue before they can participate in block
validation.
Example: Alice deposits 32 ETH to become a validator in the Ethereum network.
Step 2: Block Proposal
1) The blockchain protocol selects a validator to propose a new block.
Selection is pseudorandom and weighted by the amount staked.
Larger stakes increase the chances of being selected but do not guarantee
selection.
2) The chosen validator creates a block with:
Transactions to be included.
A reference to the previous block (linking the chain).
Other metadata (e.g., proposer’s ID).
Example: Alice is randomly chosen to propose a block. She assembles valid
transactions from the mempool into a block.
64

Proof of Stake
Step 3: Block Validation
After the block is proposed, other validators check its validity by:
Verifying transactions.
Ensuring the block adheres to protocol rules.
Validators then "vote" on the block by signing it with their cryptographic keys.
Example: Bob, Charlie, and other validators review Alice's proposed block. They
validate the transactions and sign off if the block is valid.
Step 4: Attestation
Validators submit their attestations (votes) for the proposed block.
Attestations are aggregated and added to the blockchain as evidence of consensus.
A block is considered valid once it receives enough attestations (based on a
supermajority rule, typically two-thirds of validators).
Example: Bob and Charlie attest that Alice's block is valid. Their signatures are
aggregated to finalize the block.
65

Proof of Stake
Step 5: Rewards and Penalties
Rewards:
Validators receive rewards for: Proposing a valid block, Attesting to valid blocks,
Staying online and actively participating in the network.
Penalties:
Validators lose part of their stake for: Being offline (inactivity leak), Proposing
invalid or conflicting blocks (double-signing).
Example: Alice earns rewards for successfully proposing a block. Bob and Charlie
earn rewards for attesting to the block.
Step 6: Finalization
Once a block has been validated and attested by a supermajority of validators, it
is considered finalized.
Finalized blocks cannot be reverted unless a catastrophic event occurs (e.g., a 51%
attack).
Validators continue to propose and validate subsequent blocks.
Example: After receiving attestations from a supermajority of validators, Alice's
block is finalized and added to the chain.
66

Proof of Stake
Example Workflow of PoS in Ethereum
Alice, Bob, and Charlie are validators on Ethereum.
Alice stakes 32 ETH, Bob stakes 64 ETH, and Charlie stakes 32 ETH.
Steps:
1) Block Proposal: The protocol selects Bob to propose a block because his stake is
larger (64 ETH vs. 32 ETH). Bob proposes a block with valid transactions.
2) Validation: Alice and Charlie validate Bob's block and find it valid. They
submit attestations (votes) for the block.
3) Rewards: Bob earns a reward for proposing the block. Alice and Charlie earn
rewards for attesting to the block.
4) Penalties: If Charlie had been offline during validation, he would lose part of
his stake as a penalty.
67

Is proof of stake introduced in Ethereum?


Yes, Proof of Stake (PoS) was officially introduced in Ethereum as part of a major
upgrade called The Merge, which occurred on September 15, 2022.
The Merge transitioned Ethereum from its original consensus mechanism, Proof of
Work (PoW), to the more energy-efficient Proof of Stake (PoS).
The Merge was a long-anticipated upgrade that combined Ethereum's original
execution layer (the Ethereum mainnet, which ran on PoW) with the Beacon Chain, a
separate PoS-based consensus layer.
What Is the Merge?
The Merge was a long-anticipated upgrade that combined Ethereum's original
execution layer (the Ethereum mainnet, which ran on PoW) with the Beacon Chain, a
separate PoS-based consensus layer.
Pre-Merge: Ethereum used Proof of Work (PoW), where miners competed to solve
computational puzzles to validate blocks.
Post-Merge: Ethereum uses Proof of Stake (PoS), where validators are selected to
propose and attest blocks based on their staked Ether (ETH).
68

Is proof of stake introduced in Ethereum?


Key Features of Ethereum's Proof of Stake
Validators Instead of Miners
Energy Efficiency
Deterministic Block Production
Rewards and Penalties
69

FAQs
Who Executes the Random Algorithm and Selects the Validator in Ethereum Proof of
Stake (PoS)?
In Ethereum's Proof of Stake (PoS) system, the selection of a validator (equivalent
to a miner in Proof of Work) to propose a block is managed by the Beacon Chain
using a pseudorandom algorithm (RANDAO). The process is decentralized and
transparent, ensuring fairness and resistance to manipulation.
Why Validators Do Not Falsely Declare a Mined Block as Invalid in Ethereum Proof of
Stake?
Validators in Ethereum’s Proof of Stake (PoS) are economically and protocolically
incentivized to behave honestly and validate blocks accurately. Falsely declaring a
mined block as invalid would not only be penalized but also undermine their
economic interest.
What Happens If a Validator Fails to Propose a Block?
If a validator misses their opportunity to propose a block during their assigned
slot:
The network skips that slot.
The validator loses the reward they would have earned for proposing the block.
Repeated inactivity leads to inactivity penalties, reducing the validator's stake
over time.
70

FAQs
What If Two Validators Propose Blocks for the Same Slot?
This situation, called a fork, occurs when two blocks are proposed for the same
slot. Ethereum resolves forks using the LMD-GHOST (Latest Message Driven -
Greediest Heaviest Observed Subtree) rule:
Validators attest to the chain with the most cumulative attestations (the heaviest
chain).
The block with the most support becomes part of the canonical chain.
How Are Validators Penalized for Misbehavior?
Answer: Validators face penalties for different types of misbehavior:
Inactivity: Validators who fail to participate (e.g., offline) lose rewards and
suffer inactivity leaks over time.
Malicious Actions:
Double-Signing: Proposing or attesting to two conflicting blocks.
Surround Voting: Voting inconsistently to create forks.
Penalty: These actions result in slashing, where a portion of the validator’s stake
is permanently forfeited, and the validator is removed from the network.
71

FAQs
Can Validators Collude to Attack the Network?
Answer: It’s theoretically possible if a majority of validators (more than two-
thirds) collude. However:
Such an attack is prohibitively expensive because validators must lock a
significant amount of ETH (32 ETH per validator) to participate.
Economic deterrents: The value of ETH would likely plummet if trust in the network
is lost, making such an attack financially self-destructive.
The Ethereum community could intervene through protocol updates or a hard fork to
mitigate the attack.
How Do Validators Earn Rewards in PoS?
Answer: Validators earn rewards for:
Proposing Blocks: Rewards include the base reward and transaction fees.
Attestations: Validators earn rewards for voting on the correct canonical chain.
Inclusion Rewards: Aggregating attestations and including them in blocks.
Helping Finalize Blocks: Participating in finality votes.
72

FAQs
How Is Ethereum PoS Environmentally Friendly?
Answer: Unlike Proof of Work (PoW), PoS does not require energy-intensive
computations. Validators participate by staking ETH rather than solving
cryptographic puzzles, reducing Ethereum’s energy consumption by ~99.95% post-
Merge.
Can Validators Stop Staking Anytime?
Answer: Validators can voluntarily exit the network. However:
Once exited, they cannot rejoin without re-staking.
Withdrawals of staked ETH are not yet possible until the Shanghai upgrade.
Can More Than One Validator Be Selected for Mining in Ethereum Proof of Stake
(PoS)?
In Ethereum PoS, only one validator is selected to propose a block for each slot.
However, scenarios can arise where multiple validators attempt to propose a block
for the same slot. This situation occurs not because multiple validators are
"selected" by design, but due to network delays, synchronization issues, or
malicious behavior.
73

References
Bitcoin Whitepaper (http://www.bitcoin.org/bitcoin.pdf)
Bashir, I. (2017). Mastering blockchain. Packt Publishing Ltd.
https://developer.bitcoin.org/devguide/transactions.html
https://developer.bitcoin.org/examples/transactions.html
https://developer.bitcoin.org/reference/transactions.html
https://btcscan.org/block/
0000000000000000000249cf37700e1e1e72ad6dbdca70d23f3f4167ca7cf40a?expand
https://learnmeabitcoin.com/technical/transaction/

74

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy