Docsity

Blockchain and Distributed Ledger, Appunti di Sicurezza Dei Sistemi Informativi

Toggle sidebar
bg1
Blockchain and Distributed Ledger Technologies
Alessandro Dori
1 Blockchain and Distributed Ledger Technologies: Bitcoin in
2 Hours (or less) - #01
1.1 Fundamentals of the Bitcoin Network and Ledger
•The Ledger: The Bitcoin network is a network of nodes that aim to maintain the exact same
copy of data, which is known as the ledger.
•Network Objective: The system is designed to provide a guarantee that everyone can add entries
to the ledger, but no one can modify existing data.
•Transactions: A transaction is the specific kind of data that is recorded into the ledger.
1.2 Transactions and Digital Signatures
•A transaction represents the transfer of Xcoins from an account Ato an account B.
•All transactions are immutably recorded into the ledger.
•Authentication: Each transaction must be signed by the owner of the funds, who acts as the
sender of the transaction.
•Digital Signatures: A digital signature functions as the digital analog to a handwritten signature
on paper. It possesses two highly desired properties:
1. Only the owner can create their signature, but anyone who sees it can verify that it is valid.
2. The signature must be cryptographically tied to a particular document so that it cannot be
reused to indicate agreement or endorsement of a different document.
•The Paper Check Metaphor: A cryptocurrency transaction operates similarly to a bank check.
It includes a Sender, Recipient, Timestamp, Amount, Payload, Signature, and an ID. Just like a
check, no money exchanges hands until the transaction is processed, and it will be rejected (bounce)
if the sender’s account lacks sufficient funds.
1.3 Transaction Propagation and the Mempool
•When a user creates a new transaction, they forward it to a node.
•This node subsequently broadcasts the transaction to all other nodes in the Peer-to-Peer (P2P)
network.
•The Mempool: A mempool is a collection of unconfirmed Bitcoin transactions that are waiting
to be included in a block and permanently added to the blockchain.
•Each individual node on the Bitcoin network maintains its own independent mempool.
•The decentralized nature of the system raises fundamental questions regarding how the order of
transactions is decided and who determines which transactions are inserted into the ledger.
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22

Anteprima parziale del testo

Scarica Blockchain and Distributed Ledger e più Appunti in PDF di Sicurezza Dei Sistemi Informativi solo su Docsity!

Blockchain and Distributed Ledger Technologies

Alessandro Dori

1 Blockchain and Distributed Ledger Technologies: Bitcoin in

2 Hours (or less) -

1.1 Fundamentals of the Bitcoin Network and Ledger

  • The Ledger: The Bitcoin network is a network of nodes that aim to maintain the exact same copy of data, which is known as the ledger.
  • Network Objective: The system is designed to provide a guarantee that everyone can add entries to the ledger, but no one can modify existing data.
  • Transactions: A transaction is the specific kind of data that is recorded into the ledger.

1.2 Transactions and Digital Signatures

  • A transaction represents the transfer of X coins from an account A to an account B.
  • All transactions are immutably recorded into the ledger.
  • Authentication: Each transaction must be signed by the owner of the funds, who acts as the sender of the transaction.
  • Digital Signatures: A digital signature functions as the digital analog to a handwritten signature on paper. It possesses two highly desired properties: 1. Only the owner can create their signature, but anyone who sees it can verify that it is valid. 2. The signature must be cryptographically tied to a particular document so that it cannot be reused to indicate agreement or endorsement of a different document.
  • The Paper Check Metaphor: A cryptocurrency transaction operates similarly to a bank check. It includes a Sender, Recipient, Timestamp, Amount, Payload, Signature, and an ID. Just like a check, no money exchanges hands until the transaction is processed, and it will be rejected (bounce) if the sender’s account lacks sufficient funds.

1.3 Transaction Propagation and the Mempool

  • When a user creates a new transaction, they forward it to a node.
  • This node subsequently broadcasts the transaction to all other nodes in the Peer-to-Peer (P2P) network.
  • The Mempool: A mempool is a collection of unconfirmed Bitcoin transactions that are waiting to be included in a block and permanently added to the blockchain.
  • Each individual node on the Bitcoin network maintains its own independent mempool.
  • The decentralized nature of the system raises fundamental questions regarding how the order of transactions is decided and who determines which transactions are inserted into the ledger.

1.4 Distributed Systems Context

  • Definition: According to Leslie Lamport, a distributed system is one in which the failure of a computer you didn’t even know existed can render your own computer unusable.
  • In a distributed system, no assumptions can be made regarding the following:
    • Timing: Messages can be delayed, reordered, or entirely lost.
    • Network reliability: Communication links can fail or recover unpredictably.
    • Node availability: Any process or machine may crash or restart at any given moment.
    • Global state: No single node ever possesses a perfectly up-to-date view of the whole system.
    • Clocks: Physical clocks inherently drift; one cannot assume perfectly synchronized time across the network.

1.5 Transaction Fees

  • Transactions are not recorded for free; users must pay a fee to have their transaction added to the blockchain.
  • The fee is based strictly on the transaction’s size in bytes, not on the amount of Bitcoin being transferred.
  • The fee rate, typically measured in Satoshis per byte (sat/B), is determined through a competitive auction process.
  • During periods of network congestion, users are required to pay higher fees to get their transactions prioritized by the network.
  • The higher the sat/byte paid, the faster the transaction will be confirmed and added to the blockchain. Conversely, if the fee is too low, the transaction may remain stuck in the mempool indefinitely.

1.6 Blocks and the Blockchain Structure

  • Transactions are batched and packed into data structures called blocks.
  • A block has a fixed size limit.
  • A blockchain is constructed as a chronological sequence of these blocks, linked to each other via cryptographic hashes.

1.7 Bitcoin Node Typology

There are two primary kinds of nodes operating within the Bitcoin network:

  1. Client Nodes: These nodes store a complete copy of the Bitcoin blockchain and validate trans- actions independently. - They verify all transactions and blocks according to Bitcoin’s strict consensus rules. - They help propagate valid transactions and blocks across the network. - They increase the system’s decentralization and security by ensuring there is no single point of failure.
  2. Mining Nodes: These are special client nodes that actively participate in Bitcoin mining by attempting to solve cryptographic puzzles, a mechanism known as Proof-of-Work. - They create new blocks by competing to solve complex mathematical problems. - They receive Bitcoin block rewards and accumulated transaction fees as economic incentives. - Mining requires exceptionally high computational power, typically achieved using Application- Specific Integrated Circuit (ASIC) miners.

1.11 Mining Incentives and Supply

  • The miner who successfully proposes a new block collects both the block reward and the transaction fees.
  • Coinbase Transaction: The block-proposing miner is permitted to forge a special transaction that mints brand new Bitcoins, which is known as the coinbase transaction.
  • The actual current block reward is 3.125 bitcoins.
  • The total supply limit of Bitcoin is strictly capped at 21,000,000 coins.

1.12 Forks and the Longest Chain Rule

  • A fork occurs when two or more miners successfully solve the PoW puzzle at the exact same time.
  • This results in nodes across the system temporarily possessing different versions of the blockchain.
  • Longest Chain Rule: To resolve this, the longest fork is eventually selected as the canonical blockchain, ensuring all nodes eventually converge and agree upon a single state.
  • The blocks that belong to the discarded fork become orphaned, and they are lost forever. Conse- quently, some transactions contained only in the discarded fork can be lost.

2 Hash and Hashpointer

2.1 Introduction to Cryptographic Hash Functions

  • Definition: A hash function is a computationally efficient mathematical function that maps binary strings of arbitrary length to binary strings of a fixed length, yielding what are called hash-values.
  • Hashing Mechanism: Hashing is a method of applying a cryptographic hash function to data, which calculates a relatively unique output (frequently referred to as a message digest, or simply digest) for an input of virtually any size.
  • SHA-256 Example Outputs: Bitcoin primarily uses the SHA-256 algorithm. Examples demon- strating the avalanche effect and deterministic nature: - H(”Bitcoin”) = b4056df6691f8dc72e56302ddad345d65fead3ead9299609a826e2344eb63aa - H(”bitcoin”) = 6b88c087247aa2f07ee1c5956b8e1a9f4c7f892a70e324f1bb3d161e05ca107b - H(”1”) = 6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b - H(”2”) = d4735e3a265e16eee03f59718b9b5d03019c07d8b6c51f90da3a666eec13ab

2.2 General and Cryptographic Properties of Hash Functions

A standard hash function holds the following general properties:

  1. Its input can be any string of any arbitrary size.
  2. It inherently produces a fixed-size output.
  3. It is efficiently computable.

For a hash function to be considered cryptographically secure, it must satisfy three additional properties: Collision-resistance, Hiding, and Puzzle-friendliness.

2.2.1 Collision-Resistance

  • Definition: A hash function H is said to be collision-resistant if it is computationally infeasible to find two distinct values, x and y, such that x ̸= y, yet H(x) = H(y).
  • This property ensures that no adversary can actively compute two different input values that map to the exact same output digest.
  • Note on existence vs. discovery: Because the input space is infinite and the output space is finite, collisions absolutely exist (via the Pigeonhole Principle). ”Collision-resistance” specifically means that nobody can computationally find one.
  • Theoretical Attack (Brute Force):
    1. Consider a hash function with a 256-bit output size.
    2. Pick 2^256 + 1 distinct inputs.
    3. Compute the hash of each.
    4. A collision is mathematically guaranteed to be found.
  • Computational Impracticality: 2256 is an astronomically large 78-digit number (≈ 1. 1579 × 1077 ). - If a computer calculates 10, 000 hashes per second (H/s), it would take more than 10^27 (an octillion) years just to calculate 2^128 hashes. - Even using modern ASIC hardware (e.g., Bitmain Antminer S21 Pro computing at 234 TH/s), it would take approximately 46, 077 , 254 , 411 , 749 years. - The probability of randomly finding a collision is 1/ 2256 , which is vastly smaller than winning major lotteries (e.g., 1 in 622, 614 , 630).
  • Application: Message Digest (Data Integrity):
    • A user uploads a very large file to a cloud service. Before uploading, the user computes and locally stores the file’s digest: H(file) = digest.
    • To verify the service provider hasn’t modified the file, the user downloads it and recomputes the hash. If H(downloaded) = digest, the user has mathematically sound proof the file is untampered.

2.2.2 Hiding Property

  • Definition: A hash function H is hiding if: when a secret value r is chosen from a probability distribution that has high min-entropy, then given H(r ∥ x) (where ∥ denotes concatenation), it is computationally infeasible to find x.
  • Min-entropy: In information theory, min-entropy measures how predictable an outcome is. High min-entropy captures the concept that the distribution is widely ”spread out” (i.e., highly random- ized).
  • Concept: Given the output y = H(r ∥ x), an attacker cannot feasibly figure out the input x.
  • Vulnerability of low entropy: If an input is predictable (e.g., Alice hashing a coin flip: H(”head”) = a, H(”tail”) = b), an attacker (Eve) can precompute the hashes of all possible inputs. If Alice reveals a, Eve instantly knows the input was ”head”.
  • Solution: Hide the low-entropy input by concatenating it with a high min-entropy nonce (random value r). H(r ∥ ”head”) = s. Even if Eve knows the input space is head/tail, she cannot guess r, preventing precomputation attacks.
  • Application: Commitments:
    • Goal: Allow a party to fix a value in a way that is binding (cannot be changed later) and hiding (not revealed until intentionally opened).
    • Protocol: Includes two functions:

2.4 Hash Pointers and the Blockchain Data Structure

  • Hash Pointer: A data structure that not only points to where information is stored but also contains a cryptographic hash of that information.
  • While a regular pointer strictly provides retrieval coordinates, a hash pointer provides retrieval plus verification that the data hasn’t changed.
  • Blockchain Construction: A blockchain is fundamentally a linked list constructed entirely using hash pointers instead of traditional memory pointers.
  • Tamper-Evident Log: It serves as an append-only log data structure.
  • Propagation of Errors: If an adversary tampers with data in an earlier block, the cryptographic hash of that block changes entirely. - Consequently, the hash pointer inside the subsequent block no longer matches the altered block. - To fix this, the adversary must alter the hash pointer in the subsequent block, which alters that block’s hash, cascading the error all the way to the head of the blockchain.
  • By securely remembering the single hash pointer of the head (latest block) of the blockchain, a node essentially remembers a tamper-evident hash of the entire historical list.

2.5 Merkle Trees

  • Structure: A Merkle Tree is a binary tree where the actual data resides exclusively in the leaf nodes. Non-leaf nodes are constructed by concatenating and hashing the hash pointers of their two children.
  • Merkle Root: The single hash at the top of the tree. Verifying the root guarantees the integrity of all underlying data blocks. Example computation:

h 1234 = h(h 12 · h 34 ) (2)

where h 12 = h(h 1 · h 2 ) and h 1 = h(data 1 ).

  • Efficiency: To mathematically prove that a specific piece of data belongs to a Merkle Tree con- taining n nodes, a verifier only needs to check approximately O(log 2 (n)) items (the path from the leaf to the root).
  • Proof of Membership (Light Nodes):
    • If a light node wants to verify transaction t 2 , it queries a full archival node.
    • The full node provides only the necessary sibling hashes to calculate the path up the tree (e.g., h 1 , h 34 , h 5678 ).
    • The light node computes h 2 = h(t 2 ), then h 12 = h(h 1 · h 2 ), then h 1234 = h(h 12 · h 34 ), up to the root to verify inclusion.
  • Proof of Non-Membership:
    • Requires a sorted Merkle tree (the leaves are ordered cryptographically or alphabetically).
    • To prove an item does not exist, the network provides the path for the item immediately preceding and immediately succeeding where the target item would logically be placed. The contiguous absence proves non-membership.
  • Handling Odd Numbers of Leaves: If the dataset does not have 2n^ transactions, the tree remains balanced by duplicating the final element to create a valid pair. For example, if there are 5 transactions, the 5th hash is duplicated to form its own pair:

h 55 = h(h 5 · h 5 ) (3)

3 Signatures and Identities

3.1 Digital Signatures

  • A digital signature is designed to be the digital analog to a traditional handwritten signature on paper.
  • We require two fundamental properties from digital signatures:
    1. Only the owner can generate their signature, but anyone who observes it can computationally verify that it is valid.
    2. The signature must be strictly tied to a particular document, ensuring that the signature cannot be extracted and reused to indicate agreement or endorsement of a completely different document.

3.1.1 Digital Signature Scheme

A formal digital signature scheme consists of three primary algorithms:

  • Key Generation: (sk, pk) := generateKeys(keysize) (4) This function generates a keypair (sk, pk), where pk represents the public verification key, and sk is the secret (private) key that must be securely kept by the owner and used to sign messages.
  • Signing Algorithm: sig := sign(sk, message) (5) The sign function takes a message and a secret key sk as input, and outputs a valid signature for that specific message under sk.
  • Verification Algorithm: isValid := verify(pk, message, sig) (6) This function returns a boolean value, isValid, which evaluates to true if the sig is a mathematically valid signature for the given message under the corresponding public key pk, and false otherwise.

3.1.2 Unforgeability Game

  • The security of a digital signature relies on unforgeability, conceptually modeled as a crypto- graphic game between a challenger and an attacker.
  • The challenger generates a keypair (sk, pk) and shares the public key pk with the attacker.
  • The attacker can repeatedly ask the challenger to sign arbitrary messages (m 0 , m 1 ,... ) and receives the respective signatures (sign(sk, m 0 ), sign(sk, m 1 ),... ).
  • The attacker ultimately produces a new message M and a signature sig, such that M was not among the messages previously signed by the challenger (M /∈ {m 0 , m 1 ,... }).
  • The attacker wins the game (successfully breaking the scheme) if verify(pk, M, sig) evaluates to true.

3.2 Identities on Bitcoin

  • ECDSA: Bitcoin utilizes a specific digital signature scheme known as the Elliptic Curve Digital Signature Algorithm (ECDSA).
  • The specific elliptic curve implemented in Bitcoin is secp256k1.
  • Cryptographic Sizes:
    • Private key: 256 bits.
    • Public key (uncompressed): 512 bits.
    • Public key (compressed): 257 bits.
    • Message to be signed: 256 bits.
    • Signature: 512 bits.

3.3 Practical Application: Vanity Addresses

  • A Vanity Address is a custom Bitcoin address generated to contain specific character patterns.
  • Generating these illustrates the computational difficulty of mining a block, offering hands-on ex- perience with cryptographic complexity.
  • Tools such as Vanitygen++ can be utilized (e.g., using the -v flag to output the corresponding public key: ./vanitygen++ -v 1Massi).

3.4 Conceptual Precursors to Bitcoin

3.4.1 GoofyCoin

  • Creation: Goofy serves as a central authority who can create new coins simply by signing a statement declaring the creation of a new coin with a unique coin ID.
  • Transfer: The owner of a coin can transfer it by signing a cryptographic statement reading: ”Pass on this coin to X”, where X is specified as the recipient’s public key.
  • Verification: Anyone can verify the validity of a coin by following the chronological chain of hash pointers back to its original creation by Goofy, validating all signatures along the path.
  • The Double Spending Problem: GoofyCoin fails to solve the double-spending issue. Alice could pass a coin to Bob with a signed statement, but keep this secret. She could simultaneously create a second signed statement transferring the exact same coin to Chuck. Both Bob and Chuck would possess what appears to be a perfectly valid claim to the coin, breaking the system.

3.4.2 ScroogeCoin

  • To solve the double-spending problem, ScroogeCoin introduces a public append-only ledger (a blockchain).
  • Transaction Rules:
    1. Consumed coins must be valid (meaning they were legitimately created in previous transac- tions, keeping in mind only Scrooge can mint new coins).
    2. Consumed coins must not have been already consumed in a previous transaction, explicitly preventing double-spending.
    3. The total value of the output coins emerging from the transaction must equal the total value of the input coins consumed.
    4. The transaction must be validly signed by the rightful owners of all the consumed coins.
  • Consensus & State: Scrooge acts as the centralized verifier. He refuses to endorse any transaction that attempts to double-spend an already spent coin. A transaction only counts as finalized if it is successfully included in the blockchain explicitly signed by Scrooge.
  • Limitations and Centralization Problems: Because Scrooge controls the ledger, the system introduces fatal centralization flaws: - Can Scrooge forge other people’s signatures? - Can Scrooge create infinite coins for himself? - Can Scrooge censor users by refusing to publish certain transactions? - Can Scrooge shut down the entire blockchain infrastructure unilaterally?

4 Consensus and Network Dynamics

4.1 Distributed Ledger and the Mempool

  • The Ledger: A network of nodes that aim to maintain the exact same copy of data. The system guarantees that everyone can add entries, but no one can modify existing data.
  • Transaction Propagation: A user forwards a new transaction to a node, which then broadcasts it to all other nodes in the Peer-to-Peer (P2P) network.
  • Mempool: A collection of unconfirmed Bitcoin transactions waiting to be included in a block and added to the blockchain. Each node on the Bitcoin network maintains its own independent mempool.
  • Distributed Systems Context: Recalling Leslie Lamport’s definition, a distributed system is one where the failure of an unknown computer can render your own unusable. In such systems, no assumptions can be made regarding: - Timing: Messages can be delayed, reordered, or lost. - Network Reliability: Links can fail or recover unpredictably. - Node Availability: Any process or machine may crash or restart at any moment. - Global State: No single node possesses a perfectly up-to-date view of the system. - Clocks: Physical clocks drift; perfectly synchronized time cannot be assumed.

4.2 Proof-of-Work (PoW) and Target Calculations

  • The Early Idea: PoW originated from research on combating email spam and preventing Denial- of-Service (DoS) attacks, requiring senders to perform a small computational task (expending CPU time) before sending.
  • PoW in Bitcoin: Miners propose a new block by solving a cryptographic puzzle:

H(nonce ∥ prev hash^ ∥^ tx 1 ∥ · · · ∥^ txn)^ <^ target^ (7)

  • A Round is a discrete step where processes communicate and update states. A block serves as the time unit of the blockchain, with a new block produced approximately every 10 minutes.

4.2.1 Target Coefficient

  • Block headers contain the target in a notation called ”target bits”.
  • Example: Target bits = 0x1903a30c
  • The first two hexadecimal digits represent the exponent (0x19), and the next six hex digits act as the coefficient (0x03a30c).
  • The calculation formula is:

target = coefficient × 28 ×(exponent−3)^ (8)

  • Using the example values: target = 0x03a30c × 28 ×(0x19−3)^ (9)
  • This results in an astronomically large number (e.g., 0x0000000000000003A30C...), meaning a valid block must have a block header hash mathematically less than this target. In binary, this requires the hash to have more than 60 leading bits set to zero.

4.4 Mining Incentives: Rewards and Fees

  • Mining Reward: The successful miner collects a block reward (minting new Bitcoins via the coin- base transaction) and transaction fees. The actual block reward is currently 3.125 BTC, working toward a total supply limit of 21,000,000 BTC.
  • Halving: Every 210,000 blocks (approximately every 4 years), the currency issuance rate decreases by 50%. (For the first four years, it was 50 BTC per block). By approximately 2140, no new Bitcoins will be mined.
  • Transaction Fees:
    • A transaction pays a single fee, determined by size/weight (Sat/byte), not the monetary value transferred.
    • The data structure does not contain a dedicated ”fee” field. Fees are implied mathematically: Fee =

P

Inputs −

P

Outputs.

  • Replace-by-fee (RBF): A mechanism allowing the creation of a conflicting version of an unconfirmed transaction that pays a higher fee, incentivizing miners to process it.
  • Child Pays for Parent (CPFP): A mechanism where a recipient of an unconfirmed out- put (parent transaction) spends it in a new transaction (child transaction) with a high fee, incentivizing miners to confirm both transactions together.

4.5 Forks, Confirmations, and Finality

  • Fork: Occurs when two or more miners solve the PoW puzzle simultaneously, creating different versions of the blockchain across nodes.
  • Longest Chain Rule: The fork with the most cumulative work is selected as the canonical blockchain. The alternative blocks become Orphan blocks (or stale blocks) and are discarded, meaning transactions exclusive to them may be lost forever.
  • Confirmations: When a transaction is included in a block, it has one confirmation. Each subse- quent block mined on top adds another. Six or more confirmations are considered sufficient proof of irreversibility.
  • Finality: The wait time for a reasonable guarantee that a transaction will not be reversed. In Bitcoin, 6 confirmations × 10 minutes = 60 minutes for finality.

4.6 Upgrading the Protocol

  • Hard Fork: Occurs when part of the network operates under different consensus rules (due to a bug or deliberate change). The new software recognizes blocks as valid that old software would reject. It permanently splits the network if miners disagree (e.g., Bitcoin vs. Bitcoin Cash).
  • Soft Fork: Adds new features by making validation rules strictly tighter. Old software accepts all blocks; new software rejects some. This avoids permanent splits because blocks considered valid by new miners are also valid to old miners.

4.7 Mining Hardware and Pools

  • Hardware Evolution:
    1. CPU (2009): Regular processors; highly inefficient.
    2. GPU (2010): Graphics cards; more efficient but consumed excessive power and maintenance.
    3. FPGA (2011): Field-Programmable Gate Arrays; configurable, faster, and more energy- efficient than GPUs.
    4. ASIC (2013): Application Specific Integrated Circuits; chips built exclusively for the SHA- 256 mining algorithm. The absolute standard for modern efficiency.
  • Mining Pools: Because the likelihood of solo mining a block is virtually zero, miners pool hash power to share rewards, reducing variance.
  • Pool Manager: Runs the node, collects transactions, distributes block templates, receives the reward, takes a fee, and pays miners based on work done.
  • Mining Shares: Miners prove work by submitting ”shares”—near-valid blocks that meet a lower difficulty threshold than the main network target.
  • Pay per share (PPS): Manager pays a flat fee for every valid share submitted, regardless of whether the pool finds a block.
  • Proportional: Rewards are distributed based on submitted shares only when the pool suc- cessfully finds a valid network block.

4.8 Hash Rate Attacks

If an entity controls a significant portion of the network’s hash power (α), severe attacks become possible:

  • 51% Attack: A miner/group takes control of ≥ 51% of the network to rewrite history and double- spend coins. (Historically, the pool GHash.IO briefly touched ∼ 55% in 2014).
  • Forking Attack (α > 50%): A miner sends a transaction (M → B). They then mine a secret, longer fork from an earlier block, inserting a double-spend (M → M ′). The network adopts the longer malicious chain, erasing the payment to B.
  • Temporary Block-Withholding / Selfish Mining (α > 25% − 33%): Instead of announcing a mined block, the miner keeps it secret to gain a head start on the next block. They aim to find two consecutive blocks and broadcast them suddenly to orphan the honest network’s single block, wasting the honest miners’ power.
  • Blacklisting and Punitive Forking (α > 50%): A majority coalition agrees to automatically orphan any block from minority miners that includes a transaction from a ”blacklisted” address, effectively censoring that address from the network.

5 Wallets and Cryptocurrencies Storage - #

5.1 Fundamentals of Cryptocurrency Storage

  • Core Principle: Storing bitcoins essentially equates to storing and managing cryptographic secret keys. A fundamental maxim in the blockchain space is: ”Not your keys, not your coins.”
  • Wallet Definition: A wallet is a software application or hardware interface that keeps track of a user’s digital assets, manages the cryptographic keys, and provides a convenient user interface.
  • Wallet Operations: When a user wishes to spend cryptocurrencies, the wallet abstracts the underlying complexity by automatically handling which keys to use, generating new addresses, and signing transactions.
  • Clarification: It is a common misconception that public keys are identical to addresses. Public keys are not the same as addresses; an address is derived from a public key through specific hashing algorithms (e.g., SHA-256 and RIPEMD-160).

5.2 Storage Categories: Hot vs. Cold Storage

5.2.1 Hot Storage

  • Definition: Storage methods where the private keys are held on devices connected to the internet.
  • Characteristics:
    • Highly convenient for frequent, day-to-day transactions.
    • Inherently more vulnerable to online threats, including hacks, malware, spyware, and viruses.
  • Types of Hot Wallets: Mobile wallets, Desktop wallets, and Web wallets.

5.4.1 Derivation Path Structure

The standard derivation path format is written as:

m / purpose′^ / coin type′^ / account′^ / change / address index (11)

  • m: Denotes the master node (the root of the tree).
  • purpose’: Typically set to 44′^ to indicate compliance with the BIP44 standard.
  • coin type’: Specifies the cryptocurrency network (e.g., 0′^ represents the Bitcoin mainnet).
  • account’: Allows users to logically separate funds into distinct accounts.
  • change: A boolean value. 0 is used for external (receiving) addresses, and 1 is used for internal (change) addresses.
  • address index: A sequentially incrementing integer representing specific generated addresses (0, 1 , 2 ,... ).

5.5 Hardware Wallets

  • Hardware wallets are dedicated, specialized electronic devices designed solely to secure cryptocur- rencies.
  • They store the user’s private keys in a secure microcontroller environment.
  • Operation Mechanism: The private keys never leave the device. When a transaction needs to be signed, the unsigned transaction data is sent to the hardware wallet. The device signs the transaction internally and transmits only the finalized digital signature back to the computer, ensuring the keys remain isolated from potential malware on the host machine.

5.6 Multi-Signature (Multisig) and Smart Contract Wallets

  • Definition: Multisig involves using a smart contract or advanced scripting setup that acts as a wallet requiring cryptographic signatures from multiple independent parties to authorize a trans- action.
  • M-of-N Threshold: The scheme is defined by a threshold M representing the minimum number of signatures required to approve a transaction, out of a total pool of N possible signers.
  • Example Configuration (2-of-3 Multisig):
    • Alice, Bob, and Charlie establish a multisig wallet with a threshold of 2 (M = 2, N = 3).
    • This means Alice and Bob can execute any transaction, even if Charlie disagrees or loses his key.
    • Likewise, Charlie and Bob can execute a transaction without Alice’s approval.
  • The threshold M is typically strictly smaller than N (to provide redundancy against lost keys) but can also be equal to N (meaning absolute unanimity is required for any funds to move).

6 Bitcoin Script and Transactions - #

6.1 Account-Based Model vs. UTXO Model

  • Account-Based Model: To determine if a transaction is valid in a traditional system, an account- based model is needed to keep track of account balances. This is highly inefficient because verifying a user’s balance requires scanning all past transactions that affected the account or maintaining an additional data structure requiring extensive housekeeping alongside the ledger.
  • UTXO Model (Unspent Transaction Output): Bitcoin uses the UTXO model. Every trans- action creates outputs that can be consumed as inputs in future transactions. UTXOs are simply the transaction outputs that have not yet been consumed and are available for spending.

6.2 Transaction Inputs and Outputs

  • Validation: When a node receives a new transaction, it must strictly validate that all of its inputs reference valid outputs that have not already been spent. If all inputs are valid UTXOs, the transaction is valid. If it attempts to spend an already consumed output, it is an invalid double-spend and is rejected.
  • Inputs: An input is an output that is being spent in the current transaction. It acts as a reference to a previously unspent output, accompanied by an unlocking code to authorize the spend.
  • Balance Calculation: The ”balance” of a Bitcoin address is not a single database entry, but rather the mathematical sum of all UTXOs explicitly locked to that address.
  • Chainstate Database: In Bitcoin Core, all UTXOs are stored in the chainstate database, which is kept in system memory (RAM). This allows for exceptionally fast validation without needing to crawl through raw blockchain files to verify unspent status.
  • Transaction Chains: Transactions form a chronological chain. One transaction creates an output, and a subsequent transaction selects that exact output as an input, unlocking it to create new outputs.

6.3 Consolidation, Change, and Joint Payments

  • Transaction Size and Fees: A transaction can have multiple inputs. However, more inputs increase the transaction’s byte size. Because mining fees are calculated per byte, larger transactions are more expensive. Users must strategically select the fewest inputs required to fulfill the desired payment amount.
  • Consolidating Transactions: A self-transfer that aggregates multiple small UTXOs into a single, larger UTXO. Because each UTXO must be spent in full and adds to the byte size of future inputs, consolidating during periods of low network fees minimizes future transaction costs.
  • Change Address: Since a UTXO must be spent in its entirety, any excess value (total inputs minus required payment) is routed back to the sender. A change address is an output address generated and controlled by the sender’s wallet to receive this remainder.
  • Joint Payment: A cooperative Bitcoin transaction where multiple distinct participants con- tribute inputs and collectively authorize a single transaction, thereby improving space efficiency and privacy.
  • Transaction Fee Calculation: The fee is not explicitly declared as a field; it is the mathematical remainder of the transaction.

Fee =

X

Inputs −

X

Outputs (12)

6.4 Transaction Data Structure and Components

Transactions are serialized as structured data (often represented in JSON). Key components include:

6.4.1 TXID and VOUT

  • TXID (Transaction ID): A unique identifier for a Bitcoin transaction, created by hashing the transaction’s raw data (using SHA-256). TXIDs are used for searching transactions on a block explorer, referencing previous outputs to be used as inputs, and computing the Merkle root for the block header.
  • VOUT (Vector Output): An index number (starting at 0) identifying a specific output within a transaction. Together, a txid and a vout uniquely identify any UTXO in the network.
  • OP CHECKSIG: Evaluates the input signature against the provided public key to ensure it is a mathematically valid signature for the hash of the current transaction.
  • OP CHECKMULTISIG: Verifies that k signatures on the transaction are valid against k of the specified public keys.
  • OP PUSHBYTES XX: Pushes the subsequent XX bytes of data directly onto the stack. (Part of a family from OP PUSHBYTES 1 to OP PUSHBYTES 75).

6.6 Standard Locking Code Patterns

6.6.1 P2PKH (Pay To Public Key Hash)

  • Locks the output to the Hash-160 of a public key.
  • ScriptPubKey: OP DUP OP HASH160 OP EQUALVERIFY OP CHECKSIG
  • ScriptSig:
  • Execution Sequence:
    1. The original public key is duplicated (OP DUP) and hashed (OP HASH160).
    2. This computed hash is compared to the stored public key hash inside the ScriptPubKey (OP EQUALVERIFY).
    3. If they match exactly, execution continues, and OP CHECKSIG validates the cryptographic signature against the public key, placing OP 1 (True) on the stack if valid.

6.6.2 Other Common Patterns

  • P2SH (Pay To Script Hash): Locks the output to the hash of a custom script. Addresses begin with the number ‘3‘. The sender does not need to know the complex spending conditions (e.g., multisig); they only send to the hash. To unlock, the receiver provides the full original script and the data to satisfy it.
  • P2WPKH (Pay To Witness Public Key Hash): Functions identically to P2PKH, but the unlocking data is moved to the SegWit witness field rather than the scriptsig field.
  • P2WSH (Pay To Witness Script Hash): Functions identically to P2SH, but the unlocking code is placed in the witness field.

6.7 Advanced Transaction Types

6.7.1 Escrow Transactions (2-of-3 Multisig)

  • Scenario: Alice wants to buy goods from Bob, but neither fully trusts the other to send the goods/funds first.
  • Solution: They utilize a 2-of-3 multisig transaction involving Alice, Bob, and Judy (an impartial arbitrator).
  • Protocol: The funds are locked on the blockchain. If Bob ships the goods and Alice receives them, they both sign to release the funds to Bob. If a dispute arises, Judy acts as the tie-breaker and signs with either Alice or Bob to distribute the funds appropriately.

6.7.2 Micropayment Channels

  • Scenario: Alice needs to pay Bob tiny amounts continuously (e.g., per minute of wireless service). Standard on-chain transactions are too expensive due to fees.
  • Solution: An off-chain payment channel utilizing multisig and locktime.
  • Protocol:
  1. Setup: Alice and Bob create a refund transaction returning all coins to Alice, locked in the future using the locktime parameter (to prevent coins getting stuck if Bob disappears).
  2. Funding: Alice creates a 2-of-2 multisig transaction locking up the maximum budget on the blockchain.
  3. Off-chain Updates: After each minute, Alice signs a new, updated transaction distributing slightly more Bitcoin to Bob and less change to herself. She sends this to Bob. These are not published to the blockchain.
  4. Settlement: When the service is concluded, Bob counter-signs the final, most lucrative transaction and publishes it to the blockchain.
  5. Result: Only two transactions hit the blockchain (Funding and Settlement), minimizing network fees while guaranteeing trustless micro-increments.

7 Ethereum and the EVM - #

7.1 Origins and Core Concepts

  • History: Ethereum is a blockchain founded by Vitalik Buterin and Gavin Wood. It was conceived in 2013 (when Vitalik was 17 years old), and its inception block was mined on July 20, 2015. Gavin Wood later went on to create the Polkadot blockchain in 2017.
  • The World Computer: The fundamental idea behind Ethereum is to build a blockchain with a globally accessible computer embedded within it. It serves as the foundation for building decen- tralized applications (DApps) and organizations in a decentralized, permissionless, and censorship- resistant manner.
  • State Machine: Every node in the Ethereum network maintains a copy of the state of this global computer. Anyone can broadcast a request to perform arbitrary computation. This execution causes a definitive state change in the Ethereum Virtual Machine (EVM), which is then committed and propagated to the entire network. Therefore, Ethereum is best understood as a distributed state machine rather than a simple distributed ledger.

7.2 Ether (ETH) and Denominations

  • Ether: The native cryptocurrency of the Ethereum network is called Ether (ETH).
  • Wei: Ether can be subdivided down to its smallest possible unit, which is named wei.

1 wei = 1 × 10 −^18 ETH (13)

  • Computational Bounty: Any participant broadcasting a transaction must offer an amount of ETH to the network as a bounty. Unlike Bitcoin (where fees pay for block space), the ETH paid in Ethereum strictly corresponds to the computational resources required to execute the transaction.

7.3 The Ethereum Virtual Machine (EVM)

  • The EVM is a decentralized virtual environment that guarantees code executes consistently and securely across all Ethereum nodes.
  • State Structure: Ethereum’s state is an enormous data structure that holds accounts, balances, and a machine state. This state can change from block to block based on EVM rules and the execution of arbitrary machine code.
  • Merkle Patricia Trie: The state is maintained in a modified Merkle Patricia Trie, which keeps all accounts cryptographically linked by hashes and reducible to a single root hash permanently stored on the blockchain.
  • State Transition: A transaction effectively transitions the system from World state (t) to World state (t+ 1).