Module3-BCT-2021Batch
Module3-BCT-2021Batch
2
Introduction
• The Bitcoin consensus mechanism provides an append-only ledger—a data
structure that can only be written to, making entries permanent.
• Together, the protocol and miners ensure that transactions are valid, bitcoins
aren’t double-spent, and the ledger operates effectively as a currency system.
3
BITCOIN transactions
•
Ø Assume that individual transactions are added to the ledger one at a time.
Eg: Transaction: “Move 17 coins from Alice to Bob,” signed by Alice.
• The ledger records only basic transaction details (sender, receiver, and amount).
• After Alice receives 25 coins and sends 17 to Bob, her balance would be 8 coins.
4
BITCOIN transactions
Challenges with Balance Validation
• Validating Transactions: To check if Alice has enough coins for a new transaction
(E.g., transferring 15 coins to David), need to review all her previous transactions.
• Possible Solution is to use Data structures to store updated balances, but this adds
significant extra management beyond the ledger.
• Bitcoin uses a ledger that just keeps track of transactions, similar to Scroogecoin.
5
BITCOIN transactions
• Transaction Structure in Bitcoin
• Inputs represent coins being used,
previously created in past transactions.
• Outputs represent new coins created by
the transaction.
•Minting New Currency:
•When new currency is minted, there are no
inputs (similar to “CreateCoins” in
Scroogecoin).
6
Transaction Details and Identification
• Each transaction has a unique ID.
• Outputs are indexed starting from 0, with the first output labeled “output 0.”
ØSuppose that Alice wants to send some of those coins to Bob. She creates a new
transaction, transaction 2 .
ØIn the transaction, she has to explicitly refer to the previous transaction where these coins
are coming from.
7
BITCOIN transactions
• Alice 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.
• The entire content of the transaction is signed by Alice, indicates Alice actually
authorizes it.
8
1. Change Addresses in Bitcoin Transactions
• Why Send Money to Herself?
9
BITCOIN transactions
2. Efficient Transaction Verification
• Validating a New Transaction:
• Check if the referenced output (e.g., Alice’s 25 bitcoins) exists and hasn’t been spent.
• Using Hash Pointers:
• Hash pointers make it easy to locate the referenced transaction output.
• Scan the blockchain from the referenced transaction up to the latest block to confirm the
output hasn’t been used.
• No need to scan the entire blockchain or use additional data structures, though extra data
structures can improve speed.
10
BITCOIN transactions
4. Consolidating Funds with Multiple Inputs
• Flexible Transaction Structure:
• Transactions can have multiple inputs and outputs, allowing for easy splitting
and merging of funds.
Eg: Bob received two transactions: 17 and 2 bitcoins. He can combine these as
inputs in a new transaction.
5. Merging Funds into a Single Output
• Creating a Single Output:
• Bob’s new transaction takes his two inputs (17 and 2 bitcoins) and combines
them into one output.
• Result is Bob now has a single 19-bitcoin output, ready for future transactions.
11
BITCOIN transactions
• A transaction consists of three parts: some metadata, a series of inputs, and a series of
outputs.
• Unique Transaction ID which is the hash of the entire transaction allowing hash
pointers to reference transactions.
• If the sum of output values is less than the input values, the difference becomes a
transaction fee. This fee is awarded to the miner who successfully includes the transaction
in a block, incentivizing transaction processing.
14
3.2. BITCOIN SCRIPTS
• Bitcoin uses a simple, stack-based scripting language to define conditions for
spending bitcoins.
• Scripts allow for customizable rules on how and when a transaction’s outputs can be
claimed.
• Components of a Bitcoin Script:
• ScriptPubKey (locking script): Attached to each output; defines conditions that must
be met to spend the output.
• ScriptSig (unlocking script): Provided by the spender in the input; must satisfy the
conditions set by the ScriptPubKey.
• Script Execution:
• Scripts execute by combining ScriptSig and ScriptPubKey, running them together in
a stack-based process.
• If the script successfully completes with a “true” output, the transaction is considered
valid.
15
3.2. BITCOIN SCRIPTS
• Types of Bitcoin Scripts:
• Script was designed to be simple and compact, with built-in support for cryptographic
operations like hash computations and signature verification.
17
BITCOIN Scripts
•
18
Scripting Language
• 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.
• 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 it lacks the capability to compute
complex, arbitrarily powerful functions, such as those that could lead to infinite loops or
unbounded computations.
19
BITCOIN Scripts
• Miners in the Bitcoin network must execute these scripts, which are created and submitted
by any participant.
• If the scripting language allowed for Turing completeness, it could enable scripts with
infinite loops or excessive computational demands.
• This would create a risk, as miners could be forced to run endlessly or face high
computational costs, affecting the efficiency and security of the network.
• By restricting the scripting language to non-Turing completeness, Bitcoin ensures that all
scripts are predictable and can be executed in a finite amount of time, which is essential
for maintaining network stability and miner efficiency.
20
BITCOIN Scripts
• When a Bitcoin script is executed, there are only two possible outcomes:
1.Successful Execution: If the script completes without errors, the transaction is considered
valid.
2.Error During Execution: If any error occurs while the script is running, the entire
transaction is deemed invalid and should not be accepted into the blockchain.
• This binary outcome ensures clarity and reliability in transaction validation.
• The Bitcoin scripting language is very small.
• There’s only room for 256 instructions, because each one is represented by one byte.
• Of those 256, 15 are currently disabled, and 75 are reserved.
21
BITCOIN transactions
• Bitcoin's scripting language includes many standard programming instructions:
• Basic Operations: Arithmetic functions, logical statements (e.g., "if" and "then"), error
handling, and early return capabilities.
22
BITCOIN Scripting
•
23
BITCOIN Scripting
• The CHECKMULTISIG instruction requires specifying n public keys and a parameter t
for a threshold. For this instruction to execute successfully, at least t signatures from t out
of n of those public keys must be present and valid.
Eg: Assume Alice, Bob, and Carol create a shared Bitcoin wallet.
They decide that any transaction from this wallet will require approval from at least
two out of the three of them.
n = 3: There are three public keys involved (one for each of Alice, Bob, and Carol).
t = 2: The threshold is set to two signatures, meaning any two of the three parties must
approve a transaction.
Ø To successfully execute a transaction, at least two valid signatures (from Alice, Bob, or
Carol) must be provided, corresponding to their public keys.
24
Executing a script
• Executing a script in a stack-based programming language only requires a stack, where
data can be pushed onto or popped from the top.
1.Data Instructions - When encountered, the data is simply pushed onto the stack.
2.Opcodes - These are operations that manipulate the stack, performing specific
functions on the data stored within it.
25
Executing a script
26
• Figure illustrates the state of the stack after each instruction in a Bitcoin
script:
1. The first two items are data instructions—the signature and the public key used for
signature verification.
à These are specified in the scriptSig part of the transaction input and are simply
pushed onto the stack.
2. The remaining instructions are part of the scriptPubKey from the transaction
output being redeemed.
3. This opcode(OP_DUP) duplicates the top item on the stack, creating a copy of the
public key and pushing it onto the top.
4.OP_HASH160 instruction pops the top value from the stack (the public key),
computes its hash (using SHA-256 followed by RIPEMD-160), and pushes the resulting
hash back onto the stack.
à After executing this instruction, the original public key on the top of the stack is
replaced by its cryptographic hash.
27
• Bitcoin script example in steps:
1.Data Push of Hash (from scriptPubKey):
1. A public key hash specified by the sender of the referenced transaction is pushed onto the
stack. This represents the public key hash required to redeem the coins.
2.The stack has two values at the top:
1.The hash of the public key specified by the sender (from scriptPubKey).
2.The hash of the public key derived from the recipient’s public key when attempting to
redeem the coins (from OP_HASH160).
3.OP_EQUALVERIFY Execution command checks if the two top values on the stack (the two
public key hashes) are equal.
1. If match the recipient has used the correct public key, so the script continues.
2. If no match an error is thrown, and the script terminates, making the transaction invalid.
28
4. Result of OP_EQUALVERIFY:
àAssuming the hashes match, OP_EQUALVERIFY removes these two values from the
stack, leaving the signature and public key of the recipient.
5. Next Steps:
à Now, with the public key verified as correct, the script can proceed to verify the
signature against the public key, ensuring the recipient’s authority to claim the coins.
• OP_EQUALVERIFY confirms that the public key hash used by the recipient matches the
hash specified by the sender, establishing that the recipient has the correct public key to
redeem the transaction.
29
Executing a script
à The CHECKSIG instruction pops the two values (the public key and signature) off the
stack and verifies that the signature is valid for the entire transaction using that public
key.
à Once every instruction in the script is executed , and nothing is left on the stack.
Provided no errors occurred, the output of this script will simply be true, indicating that
the transaction is valid.
30
Proof of Burn
• A proof of burn is a type of Bitcoin script that makes coins unspendable, effectively
“destroying” them.
• One use of proof of burn is in launching a new cryptocurrency: people "burn" bitcoins to
earn coins in the new system, creating a mechanism to bootstrap the new currency.
• The script uses the OP_RETURN opcode, which always throws an error when reached.
31
Proof of Burn
• Regardless of any values before OP_RETURN, executing this instruction forces the script
to return false, making the coins permanently unspendable.
• Since OP_RETURN throws an error, any data following it in the script is not processed.
• By creating a small Bitcoin transaction and using OP_RETURN, users can permanently
store information on the blockchain—such as their name, a timestamp, or proof that they
knew certain data at a specific time.
• Although this destroys a tiny amount of currency, the data becomes part of the blockchain
and remains there for the lifetime of the Bitcoin system.
32
Pay-to-Script-Hash
Ø One outcome of Bitcoin’s script system is that the sender must specify the exact script for
the transaction. This can lead to complexities.
Eg: if you’re shopping online and ready to pay, you request the address to send your
payment.
ØIf the retailer uses a MULTISIG address, they would need to inform you, saying something
like, “We’re using a MULTISIG setup, so please send the coins to a more complex script.”
ØThis can be confusing for consumers who expect a simple address and may not know how
to handle complex scripts.
ØAs a consumer, you might just want an easy, straightforward address to send your payment.
33
Pay-to-Script-Hash
Ø The P2SH script works by first hashing the top value on the stack and verifying if it
matches the provided hash.
ØIf it matches, it proceeds to a second validation step: the top stack value is reinterpreted as
a series of instructions and executed as a new script, with the remaining stack values used
as input.
Eg: illustrate how a Pay-to-Script-Hash (P2SH) transaction works in Bitcoin:
1.Transaction Creation (Funding):
Suppose Alice wants to create a multi-signature address that requires two out of three
possible signatures to spend funds. She sets up a script that requires signatures from any
two of the three public keys belonging to herself, Bob, and Carol.
34
Pay-to-Script-Hash
à This multisig script looks something like this:
2<Alice's public key> <Bob's public key> <Carol's public key> 3 OP_CHECKMULTISIG
• This script is hashed, and the hash is used to create a P2SH address. Alice then funds
this P2SH address with bitcoins.
Spending Transaction (Redemption):
To spend the funds, Alice and Bob decide to redeem the funds together, meeting the
two-signature requirement.
• Alice and Bob each provide a signature to authorize the transaction.
• The redeeming transaction includes the original multisig script (not its hash) as part of
the scriptSig.
• The scriptSig (unlocking script) in this case contains:
<Signature of Alice> <Signature of Bob> <2 <Alice's public key> <Bob's public key> <Carol's
public key> 3 OP_CHECKMULTISIG>
35
1.Script Execution: When this transaction is broadcast to the Bitcoin network, the
script verification process works as follows:
1. The scriptPubKey (locking script) on the funded transaction simply checks that
the hash of the redeem script matches the hash originally provided.
2. If it matches, the redeem script (multisig script) is re-executed using the
provided signatures and public keys.
2.Since Alice and Bob’s signatures satisfy the script’s “2-of-3” requirement, the script
successfully completes, and the transaction is validated, allowing Alice and Bob to
spend the funds.
• This two-step verification process in P2SH ensures that the redeem script itself is
only revealed and executed at the time of spending, maintaining privacy and
flexibility in transaction conditions. 36
APPLICATIONS OF BITCOIN SCRIPTS
àConsider some of the powerful applications that can be realized with this scripting
language.
1. Escrow Transactions:
ØSuppose Alice wants to buy physical goods from Bob, paying him in Bitcoin.
ØHowever, Alice doesn’t want to pay until she receives the goods, and Bob doesn’t
want to ship the goods until he’s been paid.
ØA practical solution in Bitcoin is to introduce a third party to facilitate an escrow
transaction, ensuring security for both parties.
37
Escrow Transaction Setup with MULTISIG
• Problem: Alice wants to pay Bob for goods but only after receiving them, while Bob wants
payment upfront.
• Use 2-of-3 MULTISIG Transaction which requires signatures from any two of the three parties to
release funds.
• Alice funds the escrow, held on the blockchain until any two parties sign to release.
• Upon receiving the goods, Alice and Bob both sign to release funds to Bob.
• If a dispute arises, Judy can step in as the deciding signer, releasing funds to the rightful party.
38
Handling Disputes in Escrow with MULTISIG
• Potential Issues: Bob may not send the goods or send incorrect items.
• Goods could be lost, or Alice may claim they weren’t received.
• In these cases, Alice won’t want to release funds to Bob, and Bob won’t agree to return funds to
Alice.
• Judy only gets involved if a dispute arises, saving time and resources for all parties.
39
Green Addresses
1. The Challenge of Offline or Instant Bitcoin Transactions:
à Consider a Problem: Bob, a vendor, wants immediate payment from Alice but Bob is
offline or can’t access the blockchain.
• Confirmation delays: Bitcoin transactions typically need six confirmations (up to an hour)
for trustworthiness.
Eg: A street vendor like Bob selling hot dogs can’t wait an hour for blockchain
confirmation.
• Solution is to Use a third party, called a “bank,” to facilitate trusted instant transactions.
40
Green Addresses: Concept
à Assume Alice’s transaction is sent from an address controlled by the bank.
• Since Bob trusts this bank, he trusts any transaction coming from its green address as
“pre-approved”.
How Green Addresses Work
1. Alice funds her account with the bank.
2. The bank sends the payment to Bob on Alice’s behalf from its green address,
guaranteeing future blockchain confirmation.
3. Bob receives the payment instantly from a trusted source without needing blockchain
access.
41
Advantages of Green Addresses
1. Bob accepts the payment immediately, confident the bank will ensure eventual
confirmation.
3. No need for multiple block confirmations or blockchain access for the recipient thus
reducing wait time.
42
Efficient Micropayments
• Alice needs to pay Bob small, frequent amounts for a service( such as phone usage billed
per minute).
Consolidating Micropayments
• Goal is to Combine multiple small payments into one final transaction to reduce fees.
• Approach is to use a MULTISIG transaction involving both Alice and Bob, holding the
maximum amount Alice may spend.
43
How the Micropayment Scheme Works
1. Alice funds a MULTISIG address that requires both Alice’s and Bob’s signatures to spend.
2.Incremental Payments:
1. After each usage (Eg: Each minute), Alice signs an updated transaction.
2. This transaction sends Bob one unit of payment & returns the remaining funds to Alice.
3. At the end, Bob can co-sign the latest transaction to claim his cumulative payment.
• Benefits:
• Minimizes transaction fees by consolidating payments.
• Efficient for services requiring small, frequent payments.
• Reduces blockchain congestion by using only one final transaction.
44
Lock Time
• To address potential issues, before beginning the micropayment protocol, Alice and Bob
create a safety mechanism:
2.Lock Mechanism:
1. The refund transaction uses Bitcoin’s lock_time parameter, set to t, which instructs
miners not to process the transaction until this specified time.
45
Lock Time
3. Alice’s Security:
1. Before Alice funds the escrow for the micropayment protocol, she holds on to this
pre-signed refund transaction.
2. This ensures that if Bob doesn’t cooperate or sign the incremental payments by time
t, Alice can broadcast the refund transaction to reclaim her funds without Bob’s
further involvement.
• This approach provides Alice with security, allowing her to start the micropayment
process without risking her funds if Bob becomes unresponsive.
46
Smart Contracts & Key features
• Smart contracts are self-executing agreements with terms directly written into code.
• Initially popularized by blockchain platforms like Bitcoin and later Ethereum, smart
contracts have become a powerful tool in decentralized systems.
1.Self-Executing: When certain predefined conditions are met, the contract automatically
executes.
48
BITCOIN BLOCKS
• We’ve seen how individual transactions are created and redeemed.
• If miners had to reach consensus on each transaction individually, the system would
process transactions much more slowly.
• Additionally, using a hash chain of blocks is more efficient than a hash chain of individual
transactions, as each block can hold many transactions.
1.Hash Chain of Blocks: Each block contains a block header, a hash pointer to the
previous block, and a hash pointer to its transaction data, linking blocks sequentially.
2.Merkle Tree per Block: Inside each block, transactions are organized in a Merkle tree,
which provides a compact and efficient digest of all transactions within the block,
enabling quick verification.
àThe block header primarily contains data relevant to the mining puzzle.
àFor a block to be valid, the hash of its header must begin with a specified number of
zeros, representing the difficulty level. 50
BITCOIN Blocks
• Key components of the header include:
• Therefore, to verify an entire blockchain, we only need to examine the headers of each block,
rather than all transaction data.
• The header contains a field called mrkl_root, representing the Merkle root—the root of the
transaction tree for that block. This is the only transaction-related data included in the header,
allowing efficient verification of transaction integrity. 51
BITCOIN Blocks
52
BITCOIN Blocks
• An interesting feature of Bitcoin blocks is the coinbase transaction in the Merkle tree Similar to the
CreateCoins function in Scroogecoin, this transaction is how new bitcoins are generated.
3. The value of the output is currently a little more than 25 BTC. The output value is the miner’s
revenue from the block. This revenue consists of two components: a flat mining reward, which is set
by the system and which halves every 210,000 blocks (about 4 years), and the transaction fees
collected from every transaction included in the block.
4. It has a special “coinbase” parameter, which is completely arbitrary—miners can put whatever they
want in it. 53
54
THE BITCOIN NETWORK
• The Bitcoin network is a peer-to-peer (P2P) network, inspired by other P2P systems developed for various
purposes. In the Bitcoin network:
1. All nodes are equal, with no hierarchy or special roles like master nodes. Every node has the same rights and
capabilities.
2. The network operates over TCP with a random topology, where each node connects to other random nodes.
New nodes can join anytime, and setting up a node is as simple as downloading a Bitcoin client.
3. The network is constantly changing, as nodes can enter and leave freely. There is no formal process for leaving
the network; nodes are simply forgotten if inactive for a set period (typically 3 hours, as hardcoded in common
clients).
4. The network does not follow any geographic topology, allowing nodes to connect randomly across different
locations. This design enhances the decentralized and resilient nature of the network.
55
Joining the Bitcoin Network
• To join, a new node needs to contact just one existing node, called a seed node.
• The new node requests a list of other known nodes from the seed.
• The node repeats this process with additional nodes, gradually forming connections with a
random set of peers.
• Random Peering: Through this randomized process, each new node achieves a decentralized
and random network topology.
• After peering with a few nodes, the new node becomes a full participant in the Bitcoin
network.
• To publish a transaction (e.g., Alice paying Bob), nodes use a flooding algorithm (gossip
protocol).
• Gossip Protocol: Each node sends the transaction to all its peers, ensuring rapid propagation
across the network to update the blockchain efficiently. 56
Transaction Propagation: Node Checks
• When nodes receive a new transaction, they decide whether to propagate it based on four
checks:
1.Transaction Validation: Ensures the transaction follows blockchain rules; nodes verify each
input’s script and confirm it returns true.
2.Double-Spend Prevention: Confirms the outputs being spent haven’t already been used in
another transaction.
3.No Duplicate Transactions: Nodes won’t relay transactions they’ve already seen.
4.Standard Script Check: Only standard scripts from a whitelist are accepted and relayed by
default.
57
Purpose of Node Checks
• Sanity Checks: These checks help maintain network health by filtering out invalid or
harmful transactions.
• Flexibility: While these checks are recommended, nodes are not required to follow them, as
it’s a peer-to-peer network anyone can join.
• Node Independence: Each node checks transactions individually to guard against double
spends and nonstandard transactions.
• Different Versions of Transaction Pools: Due to network latency, nodes may have slightly
different pools of pending transactions, particularly relevant in cases of double spending.
58
Handling Double-Spends and Conflicting Transactions
• Conflict Resolution by Mining: The next block mined determines which transaction is
accepted.
Eg: if Alice’s transaction to Charlie is added to the block, nodes will drop her
transaction to Bob from their memory pools as a double spend.
• Consensus Across the Network: Once the new block is broadcast, all nodes sync, and only
the accepted transaction remains, eliminating any disagreement.
• Network Position and Propagation Behavior
• Network Position Impact: Nodes retain the first transaction or block they hear, so network
position affects which conflicting transaction is accepted first.
59
• Decentralized Decision-Making: While the standard logic is to keep the first transaction
heard, nodes aren’t centrally regulated and can use their own logic for deciding which
transactions to keep.
• Block Propagation Similarities: The process for announcing new blocks is similar to
transactions, and it faces similar race conditions, such as two blocks being mined
simultaneously.
https://youtu.be/JuWYLAtz3Y4
60
Latency of the Flooding Algorithm in Bitcoin
1. Propagation time increases with block size due to network bandwidth
limitations.
2. Larger blocks can take over 30 seconds to reach most network nodes.
3. 25th, 50th, and 75th percentiles reflect the variability in propagation speeds/time.
4. Longer propagation for larger blocks indicates inefficiency in block distribution.
1.Network Design Trade-Offs
1. Prioritized Simplicity:
1.Nodes are equal and can enter/leave freely.
2.Minimal structure emphasizes resilience over speed.
2. Efficiency Implications:
1.Long propagation paths; blocks may pass through many nodes.
2.A top-down design could shorten paths but reduce flexibility.
2.Implications for Bitcoin’s Networks 30 seconds is relatively long for Internet
standards, revealing the cost of prioritizing decentralization over optimal
propagation efficiency.
61
Size of the Network
1.Dynamic Network with No Central Authority
1. The network size is difficult to measure due to its decentralized, ever-changing nature.
• Block propagation time refers to the duration it takes for a newly mined block to
be disseminated across the entire network of nodes.
• Recent data indicates that the median block propagation time is approximately 6.5
seconds, with the mean around 12.6 seconds.
• This distribution suggests that while most nodes receive new blocks within a few
seconds, some may experience delays, with full propagation taking up to 40
seconds in certain cases.
65
Lightweight Nodes
• Types of Bitcoin Nodes
1.Fully Validating Nodes vs. Lightweight (SPV) Nodes
1. Fully Validating Nodes: Store the entire blockchain, validate all transactions, and
provide higher security.
2. Lightweight (SPV) Nodes: Only download block headers and transactions
relevant to their addresses, enabling faster operation with less storage.
2. Current State: Most nodes on the network still rely on a single implementation,
posing potential risks.
67
Changing the Protocol
• Introducing New Features into the Bitcoin Protocol
1.Challenges of Upgrading the Network
1. Upgrading Bitcoin isn't as simple as releasing new software.
2. Not all nodes will update promptly, resulting in version fragmentation.
3. The effect of upgrades depends on the type of change introduced.
• Types of Protocol Changes
1.Hard Forks
1. Changes that make previously invalid blocks valid.
2. Causes a permanent split if some nodes don’t upgrade.
3. Nodes running old software will reject the new blocks and create a separate chain.
2.Soft Forks
1. Changes that make previously valid blocks invalid.
2. Old nodes can still accept the updated blocks, ensuring chain continuity.
3. Requires majority adoption but avoids network splits.
68
69
Hard Fork & its Characteristics:
• A hard fork is a change to the protocol that makes previously invalid blocks or
transactions valid. This requires all nodes to upgrade; otherwise, they risk working on a
separate chain.
1. Backward-Incompatible: Nodes running old software won’t recognize the new
blocks, leading to a split in the blockchain.
2. Permanent Split: If a substantial number of nodes don’t upgrade, the network can
split into two separate chains with their own transaction histories and rules.
Eg: Bitcoin Cash (BCH): In 2017, a group of Bitcoin developers disagreed over Bitcoin’s 1
MB block size limit. They proposed a hard fork to increase the block size to 8 MB,
enabling more transactions per block. Not all nodes agreed to the change, so the network
split, creating Bitcoin Cash (BCH) as a separate cryptocurrency with its own chain. 70
Soft Fork & its characteristics
• A soft fork is a change that makes previously valid transactions or blocks invalid. Soft forks are
backward-compatible, meaning old nodes still recognize new blocks as valid, though some
restrictions have changed.
1. Backward-Compatible: Old nodes continue to recognize the updated chain, even if they
haven't upgraded.
2. No Split if Majority Agrees: If a majority of the network adopts the soft fork, the chain
doesn’t split, as old nodes will still follow the new rules.
Eg: Segregated Witness (SegWit): In 2017, SegWit was introduced as a soft fork to improve
Bitcoin’s transaction capacity.
• SegWit changed how transaction data was stored, separating transaction signatures (witness
data) from the main transaction data, thereby reducing the size of each transaction.
• Since old nodes still recognized SegWit transactions, no split occurred, and the Bitcoin network
remained unified. 71
CHAPTER 4
72
SIMPLE LOCAL STORAGE
• Storing bitcoins is all about storing and managing Bitcoin secret keys.
• To spend a bitcoin, both public and private information is needed.
• The public information includes details like the identity of the coin and its value.
• This information is stored on the blockchain, so can be accessed anytime when needed.
• The private information is the private key, and it’s what you own the bitcoin and to
authorize spending it.
• This key is unique and it’s very important to keep it safe and secure.
• If you lose this private key, won’t be able to access your bitcoin, and there’s no way to
reset or recover it.
• Storing bitcoins means securely managing the private key.
• While the public information is always available on the blockchain.
• The private key is what allows you to control your bitcoin.
• To protect the BitCoin , keeping track of Private key is essential. 73
SIMPLE LOCAL STORAGE
• When deciding how to store and manage your private keys, three main goals are essential.
1. Availability: You need to be able to access and spend your coins whenever you want.
2. Security: It's crucial to ensure that only you can spend your coins. If someone else gains
access to your private key, they could transfer your coins to themselves, leaving you with
nothing.
3. Convenience: Managing your keys should be simple and straightforward.
àBalancing these three goals can be challenging, as they sometimes conflict with one
another.
àDifferent approaches to key management offer different trade-offs between availability,
security, and convenience.
74
SIMPLE LOCAL STORAGE
• The simplest way to manage private keys is to store them on a local device(Computer or
smartphone). Using a smartphone app, which allows you to spend coins with just a few
taps.
• However, this method falls short in terms of availability and security. If the device is lost,
damaged, or corrupted, keys ( and coins) are also lost.
• If your device is hacked, infected with malware, or physically stolen, someone could access
keys and transfer coins to themselves.
• Keeping private keys on a local device (mobile device), is like carrying cash in your wallet.
• It’s convenient for small amounts to spend regularly, but it’s risky for storing large
amounts. Like how we won’t carry all savings in the hewallet, it’s wise to limit the
amount of bitcoin you store on a single device to reduce the risk of loss or theft.
75
Wallets
• When storing bitcoins locally, wallet software is used. This software keeps track of your
coins, manages keys, and provides a user-friendly interface for easy transactions.
Eg: if you want to send $4.25 in bitcoin to a coffee shop, the wallet software makes it
simple.
ØWallets are also useful to create multiple addresses, each with its own public/private key
pair, which helps maintain privacy.
Ø The software displays your balance and handles all the details—like which keys to use
and how to create new addresses—so spending bitcoins is convenient and secure.
76
Encoding Keys: Base 58 and QR Codes
• To spend or receive bitcoins, you need a way to share the address for transactions.
• Text String: Encodes the address in a readable format.
• QR Code: Provides a scannable option for ease of use.
Ø The advantage of a QR code is that you can take a picture of it with a smartphone, and
wallet software can automatically turn the barcode into a sequence of bits that represents the
corresponding Bitcoin address which is useful in a store.
Eg: Checkout system might display a QR code, and you can pay with your phone by scanning
the code and sending coins to that address.
79
VANITY ADDRESSES
• Vanity addresses in Bitcoin are customized addresses that contain specific, desired
characters within them, often for branding or personal identity purposes.
• These addresses can contain words or patterns, making them visually distinctive.
• Vanity addresses are created from public keys through hashing, and addresses are
generated by iterating through random keys until a desired pattern appears in the
resulting address.
• The longer the desired string, the more difficult it becomes to find a matching address.
1. Human-Readable Addresses:
1. Some users and merchants prefer addresses with meaningful text (Eg., "bones" in
positions 2-6).
Eg: 1bonesEeT-cABPjLzAb1VkFgySY6Zqu3sX
81
Vanity Bitcoin Addresses
Address structure:
2. Effort Required:
à Finding a k-character prefix requires generating 58^k addresses.
Eg: Finding "bones" (~5 characters) would mean generating 600+ million addresses.
à Short patterns are achievable on a laptop, but longer prefixes require exponential effort.
82
Hot and Cold Storage
1. Hot Storage:
•Storing bitcoins on an internet-connected device (Eg:Computer, Smartphone).
•Convenient for quick access and spending.
• More vulnerable to hacking or theft, like carrying cash in a wallet.
2. Cold Storage:
•Offline storage, not connected to the internet (Eg: Hardware wallets, Paper wallets).
• More secure, protects large amounts of funds.
• Less convenient, like storing life savings in a secure place.
•Advantages:
1. Reduces the risk of online hacking and malware attacks.
2. Best suited for long-term storage of large amounts of bitcoin.
3. Protecting significant holdings while keeping minimal funds in hot storage for
spending. 83
Hot and Cold Storage
Separate Keys for Hot and Cold Storage
•Separate Secret Keys:
• Hot and cold storage should have separate keys to isolate funds.
• Protects cold storage even if hot storage is compromised.
•Interaction Between Hot and Cold Storage:
• Both need knowledge of the other’s public keys to transfer funds between them.
•Offline, Yet Accessible:
• Cold storage doesn’t need to be online to receive coins.
• Hot storage can send coins to cold storage using its public address, maintaining
security.
84
Managing Funds with Hot and Cold Storage
• Suppose Alice, a cryptocurrency investor, wants to secure her assets. She has two types of
storage:
1.Hot Storage: This is a wallet on her smartphone that she uses for daily transactions. She
keeps a small amount of cryptocurrency here for quick access.
2.Cold Storage: This is an offline hardware wallet where she stores most of her funds. This
wallet is not connected to the internet, making it highly secure.
• The hot storage can then use these addresses one by one as needed.
• The downside is that the cold storage will need to be reconnected periodically to transfer
additional addresses, which can be inconvenient and may temporarily expose the cold
storage to security risks.
86
Hierarchical Deterministic Wallets
• Solution for Managing Addresses - Hierarchical Deterministic (HD) Wallet
• HD Wallet:
• Allows the cold storage to create an unlimited number of addresses.
• Requires only a one-time communication between cold and hot storage to share necessary
information and reduces the need for repeated connections, improving security.
• Key Generation :
• Instead of individual addresses, cold storage generates “address generation info.”
• This info allows hot storage to generate addresses as needed without reconnecting.
• Similarly, generates “private key generation info” for creating a sequence of private keys in
sync with addresses.
87
Generating Address and Key Sequences
• A function takes the address generation info and integer i to generate the ith address.
• A similar function uses private key generation info to create the ith private key.
• Matching Keys:
• For each integer i, the ith address and ith private key are cryptographically linked.
• Ensures that each address has a corresponding private key, allowing secure
transactions.
Eg: Assume Bob wants to manage his cryptocurrency securely. He uses both cold
storage (an offline hardware wallet) and hot storage (an online software wallet) for
convenience and security.
à Bob decides to set up an HD wallet to manage addresses and private keys seamlessly.
88
1.Address Generation Info (Cold Storage):
1. Bob’s cold storage device generates "address generation info," which is a seed that
enables the creation of a series of public addresses.
2. This information is securely transferred once to the hot storage, allowing it to
generate new addresses on demand without reconnecting to the cold storage.
1. Bob’s cold storage also generates "private key generation info," which allows the
generation of private keys in sync with the public addresses.
2. This info is kept exclusively in cold storage, ensuring private keys are never exposed
online.
89
How It Works in Practice:
1. Bob wants to receive multiple payments over time, so he uses the hot storage wallet to create
new addresses from the address generation info. Each address is unique, keeping his
transactions private.
2. When Bob is ready to spend his funds, he reconnects with the cold storage. The cold storage
uses the private key generation info to derive the private keys needed for the corresponding
addresses, allowing him to sign transactions securely.
• Security: The private keys remain offline in cold storage, safe from online threats.
• Convenience: Bob can generate as many addresses as needed from his hot wallet without
repeatedly accessing the cold storage.
• Synchronization: The cold storage can always produce the correct private keys for any address
created by the hot storage, ensuring a seamless experience.
90
Hierarchical Deterministic Wallets
• Not all digital signature schemes support hierarchical deterministic (HD) key generation,
but the good news is that the scheme used by Bitcoin, ECDSA (Elliptic Curve Digital
Signature Algorithm), does.
• This means the cold storage can generate an unlimited number of private keys, while the
hot storage can generate the corresponding addresses.
• This setup allows for a secure, scalable way to manage keys and addresses with minimal
interaction between hot and cold storage.
91
Hierarchical Deterministic Wallets
• ECDSA private key is a random number x, and the corresponding public key is gx.
• For hierarchical deterministic key generation, need two other random values k and y:
Ø This scheme provides all the desired features: Each side can
• generate its own sequence of keys, and the corresponding
keys match up correctly (since the public key corresponding
to a private key x is g^x).
Ø The generated public keys are not linkable to each other,
meaning it’s impossible to infer that they originate from the
same wallet.
Ø While the basic approach of having the cold storage generate a
batch of addresses also has this property, extra care was
needed in this new technique to maintain privacy, as the keys
are not independently generated.
Ø This non-linkability is essential for protecting user privacy
and anonymity. 92
Hierarchical Deterministic Wallets
•
93
Hierarchical Security Levels in HD Wallets
• Two Levels of Security:
• Hot Storage: Lower security level, convenient for transactions but more vulnerable.
• Cold Storage: Higher security level, protects private keys and bitcoins even if hot
storage is compromised.
• Unlinkability:
• If hot storage is compromised, the unlinkability of public keys is lost, but private keys
remain safe.
• Hierarchical Security:
• Supports multiple security levels, making it useful for companies with complex access
needs.
• Enables secure delegation across different levels.
94
Hierarchical Security Levels in HD Wallets
• Storing Cold Information Securely: Cold Storage Options:
• Store cold information (keys or key generation info) on a device kept offline.
• Options include laptops, mobile phones, tablets, or USB drives.
95
Brain Wallet
• A brain wallet is a type of cryptocurrency wallet that allows users to generate a private key
from a passphrase instead of storing the private key on a device.
• This can be convenient for portability, as the user only needs to remember the passphrase
to recreate the wallet on any device.
96
Brain Wallet
Working: 1. Key Generation:
• A predictable algorithm converts the passphrase into a private key.
• If an attacker guesses the passphrase, they can derive all associated private keys and
addresses.
97
Security Risks of Brain Wallets
• Attackers may try various passphrases and scan the blockchain for unspent transactions at
generated addresses.
• No need for physical access, and attacks leave no trace.
• To Mitigating Risks in Brain Wallets choose a Strong, unique Passphrase to reduce the
risk of guessing attacks.
• Awareness:
• Understand the trade-off between convenience and security when using a brain wallet.
98
Creating a Brain Wallet:
• Alice wants a simple way to access her cryptocurrency without relying on hardware or
software to store her private key.
• Using a predictable algorithm (often involving a cryptographic hash function like SHA-
256), Alice’s chosen passphrase is converted into a 256-bit private key.
• Consider Trade-Offs between convenience and security when choosing a brain wallet.
à Passphrase is a string of words or characters that serves as an extra layer of security for wallets
and private keys. It’s often used to generate or protect private keys, enhancing the security of
102
cryptocurrency funds.
Brain Wallets: Generating Memorable Passphrases
• One passphrase-generation procedure that gives about 80 bits of entropy is to pick a
random sequence of six words from among the 10,000 most common English words.
• Many people find these easier to memorize than a random string of characters. Here are a
couple of passphrases generated by this method:
àPassphrases are frequently used to create “brain wallets” or to add an additional level of
protection on top of the private key.
àIn case someone gains access to your wallet file or hardware device, they would still need
the passphrase to access your funds.
103
Brain Wallet
•
104
PAPER Wallet
• The third option for securing a wallet is called a paper wallet. In this method, the key
information is printed onto paper, which is then stored in a secure physical location.
• The security of a paper wallet depends entirely on the physical protection of the paper
itself.
• Paper wallets display both the public and private keys in two formats: a two-dimensional
barcode (QR code) and in base-58 notation for readability.
• Similar to a brain wallet, storing a small amount of key material on paper is enough to
recreate the wallet when needed.
105
Tamper-Resistant Device
• The fourth method for offline storage is using a tamper-resistant device.
106
Tamper-Resistant Device
Combining Key Storage Methods
• Security Strategy:
• Users often mix methods, such as paper wallets, cold storage, and tamper-resistant
devices.
• Customized combinations enhance security for large or hot storage.
• For managing large amounts, additional security schemes are implemented to protect
funds.
107
SPLITTING AND SHARING KEYS
• While backups improve availability, they also increase the risk of theft.
• Cryptography offers a solution that enhances both security and availability simultaneously:
1. Secret Sharing Main goal is to Split a secret key into N shares so that:
• K out of N shares are needed to reconstruct the secret.
• Benefit is Increases security and availability without creating a single point of failure.
108
SPLITTING AND SHARING KEYS
• Why Not Just Divide the Secret?
• Challenge:
• Simple splitting reveals partial information with each piece.
• Use “shares” rather than direct pieces of the key.
• Example of Secret Sharing (N=2, K=2)
• Setup:
• Let S be the secret (e.g., a 128-bit number).
• Generate a random 128-bit number R.
• Shares:
• Share 1: R
• Share 2: S ⊕ R (bitwise XOR of the secret and R)
• Both R and S ⊕ R are needed to reconstruct S.
• By storing R and S ⊕ R separately, neither share alone reveals anything about the
original secret.
109
SPLITTING AND SHARING KEYS
110
Secrete sharing key
• When N = K, generate N – 1 random numbers as shares.
• Final share = Secret XOR’d with all N – 1 shares.
• Limitation is this approach doesn’t work if N > K.
• Secret Sharing with N > K (Algebraic Method)
• For N > K, use algebra to create shares.
Eg: Generate (0, S) on the y-axis, then draw a line with a random slope through this
point.
Eg: Secret Sharing with a Line (N > K, K=2)
• Create point (0, S) (the secret).
• Draw a line with a random slope through this point.
• Generate additional points on this line as shares.
111
Secrete Key
• Reconstruction:
• Two Points: Allow reconstructing the line to find the y-intercept, which reveals S.
• One Point: Reveals nothing about S since the random slope makes any y-intercept
equally probable.
112
• In this method, the secret corresponds to the point at x = 0, y = S on the y-axis.
• This approach allows us to share a secret with K = 2 and any value of N by using a line
with a random slope that passes through the secret point.
Eg: For N = 4, we could split the secret key into four shares and store each on a different
device.
• If someone gains access to one of these devices, they gain no information about the key.
• If two devices are lost or destroyed, the key can still be reconstructed from the remaining
two.
113
• To create flexible secret sharing with any N and K, where K ≤ N, we use higher-degree
polynomials.
Eg: For K = 3, we would use a quadratic polynomial (a parabola), which requires exactly
three points to reconstruct.
• By selecting a polynomial of degree K-1, we ensure that K points are needed to retrieve
the secret, enhancing flexibility while maintaining security.
114
Threshold Cryptography
• A challenge with secret sharing is that, to use the key for signing, we still need to bring all shares
together to reconstruct the original key.
• This creates a single point of vulnerability, where an adversary could potentially steal the key.
• Cryptography offers a solution: threshold signatures.
• With this approach, the shares are distributed across different devices, allowing for the creation
of signatures in a decentralized manner without ever reconstructing the private key on any single
device.
• A practical use case is a wallet with two-factor security, where N = 2 and K = 2.
• For instance, a wallet could split its key material between a desktop and a phone.
• To initiate a payment, the desktop generates a partial signature, which it sends to the phone.
115
Threshold Signatures
• The phone then alerts the user with payment details for confirmation.
• If the user approves, the phone completes the signature, allowing for a secure,
multi-device signing process without exposing the private key.
• Threshold signatures are a cryptographic technique to take a single key, split it into
shares, store them separately, and sign transactions without reconstructing the key.
• Multisignatures are a feature of Bitcoin script by which you can specify that control
of an address is split among multiple independent keys.
• Although there are some differences between the two techniques, they both increase
security by avoiding single points of failure.
116
Multisignatures
• Instead of splitting a single key, Bitcoin’s scripting language allows for multisignature
addresses that require multiple distinct keys to authorize transactions.
• Each key can be stored separately, and signatures are produced independently.
Eg : Suppose the authors of this book—Andrew, Arvind, Ed, Joseph, and Steven—cofound a
company holding a substantial amount of bitcoins.
117
Ø To secure these funds, they set up a 3-out-of-5 multisignature address, meaning
any three of the five cofounders must sign to authorize a transaction.
ØThis setup ensures security, as an attacker would need to compromise at least three
of their separate, securely stored keys to gain control over the funds
Eg: Consider a scenario where Alice wants to secure her cryptocurrency wallet by splitting
her private key and sharing it with three trusted parties. She decides to use a 2-out-of-3
secret sharing scheme, where any two of the three shares are sufficient to reconstruct the
private keys
• This type of wallet offers convenience, as it’s accessible from any internet-
connected device.
120
ONLINE WALLETS:Security and Functionality
• The online wallet service provides the code that runs in your browser or app.
• It stores and manages keys, often encrypted under a password only you know.
• Requires trust in the service provider to .secure and not expose keys or password.
Advantages are:
• Accessible from any internet-connected device (desktop, smartphone).
• No need to install blockchain data or complex software.
• A single wallet can be used across multiple devices, as the wallet is cloud-based.
Eg: Coinbase
• It allows users to store, send, and receive bitcoin through a web interface or app.
• Users can access the same wallet on both desktop and mobile devices.
121
ONLINE WALLETS:Security and Functionality
• Security Concerns: Requires trust in the service to encrypt and protect keys.
• Risk of Compromise: If the service or operators are compromised, funds are at risk.
• Trust Dependency: Users rely on the wallet provider’s integrity and security practices.
Understanding Bitcoin Exchanges:
• Bitcoin exchanges act similarly to banks, allowing users to deposit and withdraw funds.
• Users can deposit bitcoins or fiat currency (Eg. dollars, euros).
• Withdraw funds on demand (both BTC and fiat).
• Make or receive Bitcoin payments.
• Exchange Mechanism is
Eg: One customer buys Bitcoin with dollars, another sells Bitcoin for dollars.
• Transactions occur when both parties agree on a price. 122
Banking vs. Bitcoin Exchanges
Eg: Consider an Account Balance of $5,000 and 3 BTC in the exchange account.
•Placing an Order:
• Order to buy 2 BTC at $580 each.
• Total cost = 2×580=1,160 USD
•Exchange Process:
• The exchange finds a seller willing to sell 2 BTC at $580.
• The transaction is matched, and:
• 1,160 USD is deducted from the account balance.
• 2 BTC is added to the account.
123
Post-Transaction Account Balance
• Updated Balances:
• Fiat Currency: 5,000−1,160=3,840 USD.
• Bitcoin: 3+2=5 BTC.
• The exchange handles the transaction by matching buyers and sellers.
• Balances are updated seamlessly in the user’s account.
• Fiat currency refers to a government-issued currency that is not backed by a physical commodity,
such as gold or silver, but rather by the government that issued it. Its value is derived from the trust
and confidence people have in the government and its economy.
124
• When a transaction occurs between you and another customer within the same Bitcoin
exchange, no transaction is recorded on the Bitcoin blockchain.
• Instead the exchange updates its internal records to reflect the new account balances.
Eg: If your account initially held $5,000 and 3 BTC, and you purchase 2 BTC for $580 each,
the exchange doesn’t move money or bitcoins externally.
Balance will be $3,840 and 5 BTC, while the other customer’s balance is
updated accordingly.
àThe disadvantage is risk with banks. Those risks fall into three categories.
125
1. The risk of a bank run
• A run happens when a large number of people attempt to withdraw their funds
simultaneously.
• Institutions operating on fractional reserves may not have enough cash to meet all
demands at once.
126
The first risk is the risk of a bank run
127
2. The risk is Ponzi Scheme
• With financial institutions, including banks and exchanges is the potential for fraud, such
as operating a Ponzi scheme.
àIn a Ponzi scheme the organizers promise future profits to investors but use the money
from new investors to pay returns to earlier ones.
• The scheme is unsustainable and eventually collapses when there are no new investors to
fund the pay outs, leading to massive financial losses for participants.
Eg: A notable of this type of fraud is Bernie Madoff, who orchestrated one of the largest
Ponzi schemes in history, resulting in significant financial devastation for his victims.
128
3. Major risk is a hack
• Hacking is Unauthorized access to an exchange’s systems, potentially by external attackers
or insiders.
àA 2013 study revealed that 18 out of 40 Bitcoin exchanges closed due to failures or their
inability to fulfill withdrawal requests.
àThe most notorious example is Mt. Gox, once the largest Bitcoin exchange, which became
insolvent and unable to pay out the funds it owed to its users.
àBased in Japan, Mt. Gox declared bankruptcy, leaving many users without their money.
130
The third major risk is a hack: Consequences
• As of 2014, Mt. Gox's bankruptcy proceedings were ongoing in Japanese and American
courts, with the exact location of the missing funds still unknown.
• This highlights the risks of relying on exchanges, where failures can result in significant
financial losses for users.
• In contrast, traditional banks in developed countries seldom face such high failure rates.
• This difference is largely attributed to strict government regulations that protect depositors
and ensure the stability of the banking system.
• These safeguards reduce the likelihood of insolvency and enhance public trust in
traditional financial institutions.
131
Government Regulations on Banks
• Reserve Requirements:
• Banks must maintain 3–10% of demand deposits in liquid form.
• Ensures banks can handle a surge in withdrawals.
• Regulated Investments:
• Governments restrict the types of investments banks can make.
• Goal is to minimize risk to protect depositors' funds.
• Government Support for Banks
• Deposit Insurance:
• Governments promise to cover part of deposits if a bank collapses.
• Provides confidence to depositors.
• Lender of Last Resort:
• Governments may provide loans to solvent banks facing short-term liquidity issues.
• Helps stabilize banks during financial difficulties.
132
Why Regulation Matters
• For Banks:
• Encourages responsible asset management.
• Reduces risk of insolvency.
• For Depositors:
• Protects funds through insurance and stable banking practices.
• Builds trust in the financial system.
133
Proof of Reserve
• A cryptographic method used by Bitcoin exchanges to reassure customers about their
reserves.
• Proves that the exchange controls a certain percentage (25% or 100%) of customer
deposits.
• Steps to Prove Reserves
1.Claim Reserves:
1. The exchange declares the amount of Bitcoin it holds (100,000 BTC).
1. The exchange signs a random challenge string using the same private key from the
payment-to-self transaction.
2. This proves ownership of the private key used for the transaction.
• For Customers it builds trust and transparency regarding the safety of their
deposits.
136
Proof of Liabilities
• Proving Demand Deposits - What Needs to Be Proven?:
• Reserves the amount of Bitcoin the exchange controls.
• Demand Deposits: Total liabilities (deposits owed to customers).
• Calculating total demand deposits requires balancing transparency with customer
privacy.
• Fractional Reserve Calculation:
Fractional Reserve = Reserves/Demand Deposits
•What Proof Achieves:
• Proves a lower bound on fractional reserves.
• Ensures reserves meet or exceed a certain amount while liabilities do not exceed a
claimed amount. 137
• Reserves (R): Total Bitcoin held by the exchange in its wallets (verifiable via
blockchain).
Eg: The exchange controls 1,000 BTC.
à The fractional reserve ratio is 1.11, meaning the exchange holds 111% of the Bitcoin
required to meet customer liabilities.
138
A Basic Scheme to Prove Liabilities
• Complete Transparency (Privacy Risk):
• Publish a list of usernames and their respective deposits.
• Anyone can sum up these amounts to calculate total liabilities.
• If any customers are omitted or misrepresented, they can expose the fraud.
• Over-Claim but Not Under-Claim:
• The company could add fake users to inflate liabilities but cannot under-claim the
actual total owed to customers.
• Customer complaints prevent under-claiming, ensuring liability transparency.
139
Balancing Transparency and Privacy
• Drawbacks is Publishing records (such as transaction details, account balances, or personal data) are
made publicly available, user privacy may be exposed. Potential Solution is to use Cryptographic
techniques (Eg.Merkle Trees) could be used to provide verifiable proof of liabilities while
preserving customer anonymity.
140
Merkle Tree Structure:
• The exchange creates a Merkle tree, where each leaf node represents a user's account balance
(Eg. user1 acct, user2 acct ……..Usern acct)
• Each intermediate node in the tree is a hash of its two child nodes.
• The root node is a single hash that represents the entire tree.
• The exchange publishes the Merkle root (top of the tree) to provide a cryptographic proof of
the total liabilities (sum of all user balances).
Verification Process:
• If the hash matches the published root, User1 can confirm their inclusion without
seeing other users' balances.
142
• To improve transparency while maintaining user privacy, the exchange adds an
additional attribute to each hash pointer in a Merkle tree structure.
• This attribute represents the total monetary value (in bitcoins) of all deposits within the
subtree beneath that hash pointer.
• For this to work, the value associated with each hash pointer must equal the sum of the
values of the two hash pointers below it in the tree.
• The exchange constructs this Merkle tree, where the leaves represent individual user
deposits, and the root pointer contains the total liabilities (the total value of all user
deposits).
143
• The exchange then cryptographically signs the root pointer along with its associated
total value and publishes it.
• By doing so, the exchange claims that all users are included in the tree, that their
deposit values are accurate, and that these values are correctly propagated up the tree to
compute the total liabilities at the root.
• Customers can independently verify their inclusion in the tree without revealing other
users' deposit amounts.
• To do this, each customer can request a proof of correct inclusion from the exchange.
144
• The exchange must provide a partial tree path, starting from the user's deposit leaf and
extending up to the root.
• This allows the customer to verify that their deposit amount was accurately included and
correctly aggregated into the root value, ensuring the exchange’s claim of total liabilities is
accurate.
• This method balances transparency and privacy by enabling verifiable proof without
exposing sensitive user data.
145
•
146
1. The root hash pointer and root value are the same as what the exchange signed and
published.
2. The hash pointers are consistent all the way down, i.e each hash value is the
cryptographic hash of the node it points to.
3. The leaf contains the correct user account information (Eg.username/user ID and
deposit amount).
4. Each value is the sum of the values of the two values beneath it.
5. Neither of the values is a negative number.
à If every customer verifies their deposit in the Merkle tree, all branches of the tree will
be checked, ensuring that each hash pointer’s value matches the sum of its children.
147
To summarize:
1.The exchange proves it holds at least X bitcoins by creating a self-transaction for that
amount.
2.It proves customer deposits total at most Y bitcoins using the Merkle tree.
3.This shows the exchange’s reserve ratio is at least X/Y, allowing them to prove they hold a
certain percentage of reserves (25% or 100%) in a way that is independently verifiable by
anyone, without needing a central regulator.
148
Accepting Bitcoin Payments - Merchant Overview
• Why Merchants Support Bitcoin:
• To meet customer demand for Bitcoin payments.
• Provide an alternative payment method for online or in-store purchases.
• Merchant Goal:
• Receive local fiat currency (Eg. dollars) at the end of the day, not necessarily hold
Bitcoin.
Practical Requirements for Merchants
• Ease of Integration:
• Minimal changes to websites or point-of-sale systems.
• Avoid complex technical setups.
• Low-Risk Implementation:
• Protect against technology failures, security breaches, and financial risks.
149
Risks for Merchants
1.Technology Risk:
1. New systems could cause website downtime, leading to revenue loss.
2.Security Risk:
1. Vulnerability to theft from hot wallets.
2. Potential for employee fraud.
3.Exchange Rate Risk:
1. Fluctuations in Bitcoin value could result in financial loss.
2. Merchants need assurance of receiving a stable fiat equivalent (Eg. $12 for a pizza).
Solutions for Merchants
• Payment Processors:
• Use third-party services to instantly convert Bitcoin payments into fiat currency.
• Reduce exposure to exchange rate volatility and security risks.
• Secure Wallet Management:
• Implement cold storage for larger holdings and use trusted services for handling hot
wallets.
150
• The process of receiving Bitcoin payments through a payment service might look like this
to the merchant:
1. The merchant goes to a payment service website and fills out a form describing the item,
price, and presentation of the payment widget.
2. The payment service generates HTML code that the merchant can drop into her website.
3. When the customer clicks the payment button, various things happen in the background
and eventually the merchant gets a confirmation saying, “a payment was made by customer
[customer-id] for item [item-id] in amount [value].
151
•
152
•
153
• What happens when the customer makes a purchase with Bitcoin
Step1. The user picks out an item to buy on the merchant website, and when payment need to be
made, the merchant delivers a webpage that contains the “Pay with Bitcoin” button, which is the
HTML snippet provided by the payment service.
à The page also contains a transaction ID—an identifier that’s meaningful to the merchant
and allows her to locate a record in her own accounting system—along with an amount the
merchant wants to be paid.
Step2. If the user wants to pay with bitcoins, he clicks that button. That will trigger an HTTPS
request to the payment service saying that the button was clicked and passing on the identity of
the merchant, the merchant’s transaction ID, and the amount.
154
3. The payment service pops up some kind of box or initiates some interaction with the user. This
gives the user information about how to pay, and the user will then initiate a Bitcoin transfer to
the payment service through his preferred wallet.
4. Once the user has created the payment, the payment service will redirect the browser to the
merchant, passing on the message from the payment service.
à The payment service may detect the transaction broadcast on the peer-to-peer network,
even if it hasn’t yet received sufficient confirmations.
à The merchant proceeds with shipping the goods once the payment service provides
final confirmation.
155
5. The payment service later directly sends a confirmation to the merchant containing the
transaction ID and amount. The merchant then ships the goods to the user.
àThe final step involves the payment service transferring funds to the merchant in the form
of fiat currency, such as dollars. This is done via a deposit into the merchant's bank
account at the end of fixed settlement periods, such as once a day, rather than after every
individual purchase.
àThe payment service charges a small percentage of the transaction as a fee, which is their
primary source of revenue.
156
TRANSACTION FEES
• Transaction Fee is the difference between
• Total Inputs: The total value of coins used in the transaction.
• Total Outputs: The total value of coins sent to recipients.
Transaction Fee = Inputs - Outputs.
• Fees are rewarded to the miner who includes the transaction in a block.
• To cover the costs incurred by nodes and miners for processing transactions, transaction
fee exists.
• Key Costs include : Relaying the transaction across the Bitcoin network.
• Including the transaction in a block (increases block size).
• Risk: A larger block propagates slower, increasing the risk of block orphaning.
157
TRANSACTION FEES: Benefits
1.. For Miners:
• An incentive to include transactions in their blocks.
• A source of income, especially as block rewards decrease over time.
2. For the Network:
• Helps prioritize transactions, as users can pay higher fees for faster inclusion.
Eg: Inputs: 1.2 BTC Outputs: 1.15 BTC Transaction Fee: 1.2 BTC - 1.15 BTC = 0.05 BTC.
• The miner who successfully mines the block containing this transaction.
• The default transaction fees are as follows.
à No fee is charged if a transaction meets all three of the following conditions:
1. The transaction is less than 1000 bytes in size
2. All outputs(The amounts of Bitcoin being sent to one or more recipients) are 0.01 BTC or
larger(Every individual output in the transaction must be at least 0.01 BTC.)
3. The priority is high enough. 158
TRANSACTION FEES
• Priority in Bitcoin transactions determines the likelihood of a transaction being included
in a block without paying a fee. It is calculated as:
à Where Input Age: The amount of time (in blocks) that the input has remained unspent.
à Input Value: The value of the input in bitcoins.
Transaction Size: The size of the transaction in bytes.
• The longer an input remains unspent and the higher its value, the greater its contribution to
the transaction's priority.
• A transaction with a high priority is more likely to be processed quickly without requiring
a fee.
159
Eg: Input 1: Age = 100 blocks, Value = 2 BTC
Input 2: Age = 50 blocks, Value = 1 BTC
Transaction Size = 250 bytes
• Priority Calculation:
1. Calculate Input Age × Input Value for each input
1. Input 1: 100×2=200 BTC
2. Input 2: 50×1=50 BTC
2. Add up the products: 200+50=250BTC
3.Divide by the transaction size: Priority=250/250=1.0
Note: A higher priority means a better chance of the transaction being included in a block
without paying a fee.
160
• If your transaction meets specific criteria, it can be relayed and recorded on the blockchain
without a fee.
• Otherwise, a fee is charged—typically around 0.0001 BTC per 1,000 bytes, which was less
than a U.S. penny per 1,000 bytes in 2015.
• The size of a transaction depends on its inputs and outputs: it is approximately 148 bytes
per input, 34 bytes per output, plus 10 bytes for additional information.
Eg: A transaction with two inputs and two outputs would be about 400 bytes.
à As of November 20, 2024, 1 Bitcoin (BTC) is approximately ₹7,665,910.68 INR.
Therefore, a fee of 0.0001 BTC per 1,000 bytes equates to about ₹766.59 INR.
161
CURRENCY EXCHANGE MARKETS
• Currency exchange in the Bitcoin world involves trading bitcoins for fiat currencies like
dollars and euros.
• Similar to traditional currency markets, the exchange rate fluctuates based on supply and
demand—how much people want to buy one currency over another.
• Websites like bitcoincharts.com display real-time Bitcoin exchange rates for various fiat
currencies across multiple exchanges, reflecting a highly liquid market.
• For instance, in March 2015, Bitfinex, the largest Bitcoin–dollar exchange, saw a 24-hour
trading volume of about 70,000 BTC, equivalent to $21 million.
• Additionally, platforms like localbitcoins.com facilitate in-person Bitcoin trading for those
who prefer face-to-face transactions.
162
Supply and Demand: Introduction to Bitcoin Exchange Market
• Bitcoin Exchange market matches buyers and sellers with opposing needs.
• Market size: Millions of U.S. dollars traded daily.
• Comparison:
• Smaller than the NYSE or dollar–euro market.
• Large enough to establish a consensus price.
• Key feature: Liquid market where participants can reliably trade modest
amounts.
• How the Consensus Price is Determined
• Market dynamics: Price is set by supply and demand.
• Supply: Bitcoins available for sale.
• Demand: Desire for bitcoins from people holding fiat currencies (e.g., dollars).
• Mechanism: Price adjusts to balance supply and demand in real time.
163
• The Supply of Bitcoins is the number of bitcoins currently in circulation.
• Availability: Represents the potential bitcoins that can be bought or sold in the market.
àThe supply of bitcoins in a market can vary depending on how demand deposits are
considered.
àDemand deposits should be included in market analysis when they can be redeemed or
sold in that market.
Eg: Exchanging dollars for bitcoins stored as demand deposits that are redeemable for
dollars.
164
Economists’ Perspective on Money Supply
• What’s included:
• Physical currency (paper and coins).
• Demand deposits (spendable money in accounts).
• Reason: Demand deposits function as spendable money in the economy.
165
• Two Main Sources of Bitcoin Demand
1.Mediating Fiat Currency Transactions
1. Use of Bitcoin as an intermediary for transferring fiat currency (e.g., dollars).
2. Neither party (buyer or seller) intends to hold bitcoins long-term.
2.Bitcoin as an Investment
1. Holding bitcoins in the hope of future price appreciation and profit.
• Bitcoin Demand: Mediating Fiat Transactions
• Consider a Scenario:- Alice wants to send dollars to Bob using Bitcoin for
convenience.
• Process:
• Alice buys bitcoins with dollars.
• Alice transfers bitcoins to Bob.
• Bob waits for confirmations, then sells the bitcoins for dollars.
• Key Point here is Bitcoins used in the transaction are temporarily taken out of
circulation, creating demand.
166
Bitcoin Demand: Investment
• Scenario:
• Individuals buy bitcoins and hold them, expecting future price increases.
• Effect on Circulation is held bitcoins are removed from the circulating supply.
• Outcome is Increased demand as more people buy and hold.
Impact of Bitcoin Demand on Supply
• Mediated Transactions:
• Short-term removal from circulation during transactions.
• Investment Holding:
• Long-term removal as investors hold bitcoins.
• Result is both use cases contribute to overall Bitcoin demand and influence its market
dynamics. 167
A Simple Model of Market Behavior
• Key Parameters:
• T (Transaction Value): Total dollar value of transactions mediated via Bitcoin
(measured in dollars per second).
• D (Transaction Duration): Time bitcoins are held out of circulation during a
transaction (measured in seconds).
• S (Supply): Total bitcoins available for transactions, excluding long-term investments.
168
A Simple Model of Market Behavior
Effect of Transaction-Mediation on Demand
• Mechanism:
• Payer purchases bitcoins to mediate a fiat transaction.
• Bitcoins are temporarily removed from circulation.
• Recipient sells bitcoins, returning them to the market.
• Impact:
• Higher transaction values (T) or longer durations (D) increase demand.
• Lower available supply (S) amplifies price effects.
• Price Determinants:
• Demand increases with higher T or longer D.
• Limited supply (S) causes price fluctuations based on transaction demand.
• Practical Implication:
• Transaction-mediation demand directly influences Bitcoin’s short-term price dynamics.
169
Bitcoin price fluctuates to balance supply and demand.
• Supply Calculation:
• Total bitcoins available: S.
• Duration bitcoins are held out of circulation: D seconds.
• Bitcoins available per second: S/D.
• On average, S/D bitcoins become newly available every second as they exit the out-of-
circulation state.
170
Demand Dynamics & Market Equilibrium
• Demand Calculation:
• Total transaction value: T dollars/second.
• Bitcoins needed to mediate $1: 1/P (where P is the price in dollars per bitcoin).
• Bitcoins needed per second: T/P.
• As transaction value (T) or price (P) changes, the demand for bitcoins adjusts.
• Equilibrium Condition: Supply equals demand:
• S/D = T/P
• Price Adjustment Mechanism:
• Supply > Demand:
• Excess bitcoins go unsold.
• Sellers lower prices, increasing demand until equilibrium is reached.
• Supply < Demand:
• Not enough bitcoins available for transactions.
• Buyers bid higher, raising prices and reducing demand until equilibrium is
achieved.
171
Key Takeaways
• Supply (S/D): Dictated by the number of circulating bitcoins and transaction duration.
• Demand (T/P): Driven by transaction value and bitcoin price.
• Price Fluctuation: Balances supply and demand to achieve equilibrium.
• Formula: S/D = T/P captures the relationship between supply, demand, and price.
172