Understanding Bitcoin Basics
Cryptographic Foundations
Hash Functions
Hash functions are mathematical functions in cryptography that convert input of arbitrary length (usually called "messages" or "data") into output of fixed length, typically referred to as "hash values" or "hash codes". The main characteristics of hash functions include:
- Determinism: The same input always produces the same output, meaning that whenever the hash function is applied to the same data, it will yield the same hash value.
- One-way: It's practically impossible to derive the original input from the hash value, making hash functions very useful for data security protection.
- Avalanche effect: Even a tiny change in the input data leads to a significant change in the hash value, which helps prevent hash collisions.
- Collision resistance: It's difficult to find two different inputs that produce the same hash value. Ideally, hash functions should be able to resist premeditated collision attacks.
- Puzzle friendly: It's impossible to predict in advance what input will yield a specific hash value; one can only try one by one.
Applications in the Cryptographic World
Application 1:
Let's look at an example: The MD5 hash of hello
is: 5d41402abc4b2a76b9719d911017c592
While the slightly modified hollo
results in 181d1f65fc3edfc75945b24f22cd7e22
As we can see, the hash results of these two are completely different.
In the cryptographic world, we only need to take a hash of a piece of information and then save this hash result to the blockchain. Because once someone tampers with this information, the corresponding hash will change dramatically.
Application 2:
We all know that Bitcoin is obtained through mining, and the mining process is actually a constant hashing process.
Bitcoin will set a target space
, let's say it's 000000
here, although the actual situation is much more complex.
The Bitcoin mechanism requires miners to find an input that, when hashed, produces a hash value starting with 000000
.
If miners find such an input, it proves that they have been working for a long time, and then a certain amount of Bitcoin is issued as a reward.
Signatures
Bitcoin uses public keys and private keys to build an asymmetric encryption system.
Public Keys and Private Keys
- Public Key: Public and can be viewed and used by anyone. It's similar to a bank account number; others can transfer money to you through your public key.
- Private Key: Private and only known by the owner. It's similar to your bank account password, able to prove your control over a certain public key and allow you to sign transactions.
Signature Process
-
Generate the hash of the message
First, the message to be signed (msg) is hashed to generate a fixed-length hash value. Bitcoin uses the SHA-256 algorithm for hashing.
- A hash function is a one-way function that converts input into a fixed-length string, and the probability of different inputs generating the same output is extremely low.
-
Sign the hash value
Use the private key to sign the generated hash value. The signing process generates a digital signature that is specific to that message and private key.
- The digital signature is generated through the Elliptic Curve Digital Signature Algorithm (ECDSA). This signature ensures that only the person holding that private key can generate this signature.
-
Append the signature to the message: Append the generated digital signature to the original message to form a complete signed message.
Verification Process
-
Obtain the public key and signature: The receiver extracts the public key, signature, and original message from the signed message.
-
Hash the message: Similar to the signing process, the receiver also hashes the received message to generate a hash value.
-
Verify the signature
: Use the sender's public key and the generated hash value to verify the validity of the digital signature.
- If the verification is successful, it indicates that the signature was generated by someone possessing the private key corresponding to that public key, and the message was not tampered with during transmission.
Example
Suppose you want to send a Bitcoin transaction to someone:
- You use your private key to sign the hash value generated from the transaction information (including recipient address, transfer amount, etc.), generating a digital signature.
- Append this digital signature to the transaction information and broadcast the signed transaction information to the Bitcoin network.
- Nodes in the Bitcoin network use your public key to verify the signature, ensuring that the transaction was indeed initiated by you and the information was not tampered with.
Data Structures
Hash Pointers
In blockchain, hash pointers replace ordinary pointers used in traditional data structures, providing a more secure and efficient way of data storage and verification.
Hash pointers not only point to the previous block but also contain the hash value of the previous block. Specifically, when creating a new block, the content of that block (only the block header is calculated, not the block body, which is the specific transaction information) is hashed to generate a unique hash value. This hash value both represents the content of that block and points to the previous block.
Tamper-Evident Log
A major advantage of hash pointers is that they provide a tamper-evident log. The specific mechanism is as follows:
- Integrity verification: Since each block contains the hash value of the previous block, any tampering with a block will change its hash value, thus causing the hash values of all subsequent blocks to change. In this way, tampering can be easily detected.
- Tamper-resistant chain: Because each block depends on the hash value of the previous block, if someone tries to modify a block, they not only need to modify that block but also all subsequent blocks, which is almost impossible to accomplish.
Data Storage Optimization
Due to this chain structure of hash pointers, we don't need to save the data of the entire blockchain; we only need to save the last few blocks. The specific process is as follows:
- Last few blocks: Only the last few blocks need to be saved because each block contains the hash value of the previous block, allowing the integrity of the entire blockchain to be verified through these hash values.
- On-demand lookup: If earlier data needs to be accessed, it can be found and verified for integrity through these hash pointers.
Blockchain simulation process
https://andersbrownworth.com/blockchain/blockchain
Merkle Tree
In the Bitcoin system, the Merkle Tree is an important structure used to organize and verify transaction data. Its basic units are the underlying data blocks, which are actually individual transactions.
Each block has a Merkle tree, where each leaf node is a hash value of a transaction (Bitcoin uses double SHA256 hashing). The number of leaf nodes must be even, but not every block has exactly an even number of transactions. When a block has an odd number of transactions, the last transaction is duplicated (the duplication only occurs in the Merkle tree, not in the block itself!).
The Merkle tree is organized from bottom to top. Leaf nodes are paired, their two hash values are combined to generate a new hash value, forming the tree nodes at the upper level. This process is repeated until there is only one tree node left, which is called the root node. The hash value of the root node is the unique identifier of the entire transaction set, saved in the block header information, and used for the PoW process. The root node (Root Hash) represents the hash value of the entire tree. By remembering this root hash value, any modification to the entire tree can be detected.
Merkle Proof
An important benefit of the Merkle Tree is that it allows for Merkle Proof. Merkle Proof is a method used to prove that a certain data block (transaction) exists in a given Merkle Tree.
Full Nodes and Light Nodes
- Full Node: Saves all data of the entire blockchain, including all transactions and blocks.
- Light Node: Only saves block headers, not all transaction data.
Transaction Verification for Light Nodes
Suppose you're running a light node on your phone. If I make a transfer to you, you need to verify that this transaction exists in the blockchain. This is where Merkle Proof comes in handy.
Verification Process
- Receive Path (Merkle Proof): The light node receives a path from a full node or other source. This path includes all hash values from the target transaction to the root hash.
- Verify Path: The light node uses this path to verify whether the hash value of this branch path is consistent with the final block header. If consistent, it proves that the transaction exists in the blockchain.
This process proves Proof of Membership, with a complexity of O(log n).
Proof of Non-Membership
To prove that a certain transaction is not in the blockchain (Proof of Non-Membership), there is currently no relatively efficient method. One can only check one by one, with a complexity of O(n).
Sorted Merkle Tree
If the transaction data is ordered, sorted by hash value, this structure is called a Sorted Merkle Tree. This structure allows for quick checking of whether a transaction exists. However, Bitcoin doesn't use this structure as it doesn't need this functionality, and sorting also requires additional cost.
BTC Protocol
The Bitcoin protocol includes mechanisms for coin minting, transaction process, and prevention of double-spending attacks.
Coin Minting and Transaction Process
Each transaction includes input and output parts:
- Input Part: Specifies the source of the coins (i.e., previous transactions) and the public key of the transferor. The transferor's public key needs to match the public key of the coin source to ensure legitimacy.
- Output Part: Specifies the public key of the recipient. This transaction needs to have the sender's signature to ensure that the transaction is initiated by the legitimate coin holder.
Hash pointers are used to point to a previous transaction, proving the source of this part of the money and preventing the fabrication of coins out of thin air. This mechanism also prevents double-spending attacks.
Double-Spending Attack
A double-spending attack refers to a situation where the same Bitcoin is spent twice. Bitcoin prevents double-spending attacks through the following mechanisms:
- Blockchain Consensus: Each transaction needs to be packaged into a block by miners and confirmed through the consensus mechanism.
- Transaction Verification: When a new block is broadcasted, all nodes in the network will verify whether each transaction in it is legal, checking for double-spending behavior.
- Longest Chain Rule: The Bitcoin network will choose the longest legal chain. If double-spending transactions occur in different blocks, only the transaction included in the longest chain will be recognized.
Double-Spending Attack Detection Example
Suppose Alice tries to transfer the same Bitcoin to both Bob and Charlie:
- Broadcast Two Transactions: Alice initiates two transactions with the same input to Bob and Charlie respectively and broadcasts them to the network almost simultaneously.
- Miner Packaging: Miners receive these two transactions and package them into different blocks, forming two forks.
- Fork Propagation: Nodes in the network will receive these two forked blockchains, temporarily splitting into two branches.
- Longest Chain Selection: As time goes on, miners continue to mine and generate new blocks. When one branch is extended to form a new longest chain, the blocks on the other branch will be discarded, becoming orphan blocks.
- Transaction Confirmation: Eventually, only the transaction included in the longest chain will be confirmed and accepted. At this point, Alice's double-spending attack will fail because only one transaction will be accepted by the blockchain network, and the other transaction will be rolled back.
Bitcoin mining produces one block every ten minutes, which is actually to prevent fork attacks. If the time were too short and there were too many forks, it would be easy to be attacked.
Distributed Consensus
When talking about consensus, we might think of voting, but any consensus protocol based on voting has a voting rights issue and may be subject to Sybil attacks. In the Bitcoin system, it's not feasible to simply use voting to determine consensus. The Bitcoin network uses Proof of Work (PoW) to achieve distributed consensus, ensuring that all nodes reach agreement on the state of the blockchain. Its core idea is to prevent Sybil attacks and other malicious behaviors by consuming computational resources. The specific process is as follows:
- Mining Process: Miners competitively perform a large number of hash calculations, trying to find a hash value that meets specific conditions (i.e., a hash below the target value).
- Hash Value Calculation: Miners perform hash calculations on the block header, which includes the hash value of the previous block, the Merkle root of transactions in the current block, timestamp, difficulty target (nbits), and nonce.
- Target Value: The difficulty target (nbits) determines the target value that the hash value must be smaller than. As the network's computing power changes, difficulty adjustments occur every 2016 blocks (about two weeks). This ensures that new blocks are generated approximately every 10 minutes. If blocks are generated too quickly, the difficulty increases; if too slowly, the difficulty decreases.
Block Structure
Each block consists of a block header and a block body.
The block header includes the following fields:
- Version Number (version): Indicates the version of the block.
- Previous Block Hash (previous block hash): Points to the previous block, ensuring the continuity of the chain.
- Merkle Root (Merkle root): The root hash obtained by calculating all transaction hash values in the current block through the Merkle tree.
- Timestamp (timestamp): Records the time when the block was created.
- Difficulty Target (nbits): The mining difficulty of the current block.
- Nonce (nonce): A counter used for mining.
The block body contains a transaction list, recording all transactions included in that block.
Block Verification
After receiving a new block, other nodes will perform a series of verifications to ensure the legitimacy of the block:
- Hash Value Verification: Check if the hash value of the block header is less than the difficulty target.
- Previous Block Hash: Verify if the hash value of the previous block matches the last block in the local chain.
- Transaction Verification: Verify if each transaction in the block is legal, including:
- Signature Validity: Check if the signature of the transaction is generated by a legitimate private key. - Double-Spending Detection: Ensure that each input has not been spent in previous blocks.
- Merkle Root Verification: Check if the Merkle root of the transaction list is consistent with the Merkle root in the block header.
If the block passes all verifications, it will be added to the local blockchain; otherwise, it will be rejected.
Block Reward
After successfully finding a hash value that meets the conditions, miners gain the right to record and broadcast the new block to the entire network. The new block contains a special transaction (coinbase transaction) to reward the miner:
- Block Reward: The initial block reward was 50 BTC, halving every 210,000 blocks (about 4 years). The current (2024) reward is 6.25 BTC.
- Transaction Fees: In addition to the block reward, miners can also receive transaction fees for transactions included in the block. These fees are paid by transaction initiators as an incentive for miners to package transactions.
Consensus Protocol and Fork Handling
Longest Chain Rule
The Bitcoin network adopts the longest chain rule to decide which chain is legitimate. That is, all nodes choose the legal chain that contains the most work (i.e., the longest). This ensures the consistency of the network and prevents fork attacks.
Fork Handling
If two miners find valid blocks almost simultaneously, a chain fork will occur. At this time:
- Temporary Fork: Nodes in the network will temporarily split into two branches, each receiving one of the blocks.
- Final Selection: When one branch is extended by subsequent blocks and surpasses the other branch, the blocks on the shorter branch will be discarded, becoming orphan blocks.
- Transaction Rollback: Transactions on orphan blocks will be rolled back to an unconfirmed state and may be included in subsequent blocks.
BTC Implementation
Bitcoin adopts a transaction-based ledger to record each transaction, rather than directly maintaining the balance of each wallet. In other words, querying the balance of a wallet requires traversing all transaction records to calculate.
UTXO
UTXO (Unspent Transaction Output) represents unspent transaction outputs and is a core concept in the Bitcoin transaction system.
- Definition: Each UTXO contains the hash value (transaction ID) of the transaction that produced it and which output it is in the transaction.
- Function: Used to prevent double-spending attacks. A Bitcoin can only be spent once, and only coins in the UTXO set are legal. Full nodes need to maintain this set in memory.
- Transaction process:
- Consume UTXO: Each transaction consumes some UTXOs as input.
- Generate new UTXO: Each transaction also produces new UTXOs as output.
Confirmation Mechanism
Confirming transactions is to prevent fork attacks and ensure the immutability of transactions. Generally, waiting for 6 confirmations (i.e., 6 subsequent blocks) is considered sufficiently secure.
- Confirmation Time: The average time for each block to be produced is 10 minutes, so 6 confirmations take about 1 hour.
- Zero-confirmation Transaction: Some transactions are accepted before being packaged into a block, but this carries a higher risk as the transaction has not yet been confirmed.
Block Size
The size limit for each block is 1MB, which limits the number of transactions that can be included in each block.
- Package Transactions: If some transactions fail to be packaged into the current block, they need to wait for the next block.
- Congestion Situation: When the transaction volume is large, unconfirmed transactions will accumulate, requiring higher transaction fees to increase the priority of being packaged.
BTC Network
The Bitcoin network is a decentralized peer-to-peer (P2P) network, where each node in the network is equal.
- Peer Nodes: The Bitcoin network consists of multiple peer nodes, each node has the same status, with no central server or control node.
- Node Communication: Nodes communicate with each other through the TCP protocol, exchanging transaction information and block data.
Joining the Network
For a new node to join the Bitcoin network, it needs to connect to a known seed node. These seed nodes help new nodes discover and connect to other nodes. New nodes obtain a list of other nodes through seed nodes and then attempt to establish connections with these nodes.
Node Connection and Maintenance
- Neighbor Nodes: Nodes randomly select other nodes as their neighbor nodes for connection. This selection has no proximity principle; a node in the United States might choose a node in Argentina as a neighbor node, so the time for cross-regional transfers is about the same as for offline face-to-face transfers.
- Node Maintenance: Nodes periodically send "ping" messages to check the alive status of neighbor nodes. If no message is received from a certain node for a long time, that node is considered to have exited the network and will be removed from the connection list.
Transaction Propagation and Block Broadcasting
- Transaction Pool: Each node maintains a transaction pool (Mempool), storing all pending transactions. These transactions wait to be packaged into blocks by miners.
- Transaction Propagation: When a node receives a new transaction, it first verifies the legitimacy of the transaction, then broadcasts the transaction to its neighbor nodes. Neighbor nodes perform the same operation, ensuring the transaction spreads throughout the network.
- Block Broadcasting: When a miner finds a new block, they broadcast the block to the network. Nodes receiving the block verify its legitimacy and add it to their local blockchain.
Network Topology and Message Passing
- Simple and Robust Design: The design of the Bitcoin network emphasizes simplicity and robustness rather than efficiency. This design ensures the stability and security of the network.
- Message Passing: Nodes communicate with each other through a series of predefined message types, such as
inv
(announcing new transactions or blocks),getdata
(requesting data),block
(transmitting blocks),tx
(transmitting transactions), etc. - Exit Mechanism: If a node hasn't sent a message for a long time, it will be considered to have exited the network, and other nodes will remove its connection.
BTC Mining
Mining Difficulty
Bitcoin mining difficulty is a measure used to represent the difficulty of finding a valid block. The difficulty is closely related to the target value, which is a 256-bit number representing the value that the hash value must be smaller than to be accepted. The calculation of the target value is based on the difficulty; the higher the difficulty, the smaller the target value, and the harder the mining.
The dynamic adjustment of Bitcoin mining difficulty is to keep the average block time at around 10 minutes. If the mining difficulty is not adjusted, as the miners' computing power continues to increase, the block time would become shorter and shorter. This would make temporary forks the norm, dispersing the system's computing power, which is not conducive to the overall security of the Bitcoin system.
Necessity of Dynamic Adjustment
- Fork Problem: If the block time is too short, miners frequently find new blocks, increasing the phenomenon of temporary forks. Frequent forks lead to the dispersion of system computing power, reducing the overall security of the network.
- Security Risks: The dispersion of computing power makes it easier for malicious nodes to successfully mine on a malicious fork chain, threatening network security. Therefore, maintaining a stable block time helps reduce forks and improve network security.
Nonce and Extra Nonce
- nonce: The block header contains a 4-byte (32-bit) nonce field. Miners constantly change the nonce value to try to find a hash value that meets the difficulty requirements.
- extra nonce: As the difficulty increases, a single nonce may not be enough. Miners can add an additional field (extra nonce) in the coinbase transaction to expand the search space. The position of this field in the coinbase transaction allows miners to change more values, thereby increasing the adjustable range.
Mining Difficulty Adjustment Mechanism
The Bitcoin network uses a difficulty adjustment algorithm to ensure the stability of block time. The specific mechanism is as follows:
- Difficulty Adjustment Cycle: The Bitcoin network adjusts the mining difficulty every 2016 blocks (about two weeks).
- Ideal Time: Ideally, 2016 blocks should take 20160 minutes (2016 blocks × 10 minutes/block).
- Adjustment Formula: The formula for difficulty adjustment is:
Adjustment Range: The range of difficulty change for each adjustment is limited to between one-quarter and four times the original difficulty, avoiding large difficulty changes due to short-term computing power fluctuations.
Mining Equipment
Evolution of Mining Equipment
- CPU (Central Processing Unit)
- Initial Stage: When Bitcoin first started, users could mine using the CPU of ordinary computers.
- Characteristics: Slow processing speed, low computing power, but sufficient for early low-difficulty mining. - Disadvantages: Low energy efficiency, difficult to cope with mining demands after difficulty increases.
- GPU (Graphics Processing Unit)
- Middle Stage: As mining difficulty increased, miners turned to using GPUs for mining.
- Characteristics: GPUs have a large number of parallel processing units, capable of performing multiple hash calculations simultaneously, much more efficient than CPUs.
- Advantages: Significantly increased computing power, suitable for mining work that requires high computational capabilities. - Disadvantages: Higher power consumption, increased equipment costs.
- FPGA (Field-Programmable Gate Array)
- Transition Stage: After GPUs, some miners began using FPGAs.
- Characteristics: Programmable hardware that can be optimized for specific algorithms.
- Advantages: Higher energy efficiency than GPUs, relatively flexible.
- Disadvantages: High development difficulty, requires professional knowledge.
- ASIC (Application-Specific Integrated Circuit)
- Current Stage: Currently, Bitcoin mining mainly uses ASIC miners.
- Characteristics: Hardware specifically designed for Bitcoin mining, capable of maximizing hash calculation efficiency.
- Advantages: Highest energy efficiency, extremely high computing power, optimized specifically for the SHA-256 algorithm.
- Disadvantages: High cost, lack of flexibility, can only be used for mining specific algorithms.
Main Parameters of Mining Equipment
- Hash Rate
- Represents the number of hash calculations the device can perform per second, typically measured in TH/s (Tera Hashes per second) or GH/s (Giga Hashes per second). - The higher the hash rate, the greater the probability of the device finding a hash value that meets the difficulty target.
- Efficiency
- Represents the hash calculation capability produced per watt of energy consumed, typically measured in J/TH (Joules per Tera Hash).
- The higher the efficiency, the lower the device's power consumption, and the lower the mining cost.
- Power Consumption
- Represents the power consumption of the device during operation, typically measured in Watts (W). - The lower the power consumption, the lower the device's operating cost.
Mining Pools
Working Principle of Mining Pools
Bitcoin mining is a highly competitive process, and the probability of an individual miner successfully finding a new block is very low. To increase the stability of earnings, miners can join mining pools, sharing computing power to mine together and distribute rewards proportionally. In Bitcoin mining pools, submitting shares is a mechanism for miners to prove their workload and contribution to the pool. The process of submitting and verifying shares is at the core of mining pool operations.
Share: This is a hash value that meets the low difficulty target set by the mining pool. Although these shares themselves are not enough to find a new block (because they don't meet the network-wide difficulty target), they prove the miner's workload and computing power contribution.
- Working Mechanism - Task Assignment:
- The mining pool server assigns mining tasks to miners, including a specific block header template and a lower target difficulty.
- After accepting the task, miners use their own devices to try to find a hash value that meets the low difficulty target. - Calculation and Submission:
- Miners perform hash calculations, trying to find a hash value that is smaller than the low difficulty target set by the mining pool.
- Once a miner finds a hash value that meets the low difficulty target, generating a share, the miner submits this share to the mining pool server.
- Miners continuously repeat this process, submitting multiple shares until the task ends or is replaced by a new task.
- Share Verification
- After receiving the share submitted by the miner, the mining pool server verifies its validity.
- The verification process includes checking whether the hash value meets the low difficulty target and ensuring the share is generated based on the task assigned by the mining pool.
- Reward Distribution
- The mining pool distributes mining rewards based on the number of shares submitted by miners. Common reward distribution methods include:
- PPS (Pay Per Share): Pay a fixed amount for each valid share. The miner's earnings are directly related to the number of shares submitted, with the mining pool bearing the risk of finding blocks.
- PPLNS (Pay Per Last N Shares): Reward distribution is based on the proportion of the last N shares, emphasizing long-term contribution.
- The mining pool distributes mining rewards based on the number of shares submitted by miners. Common reward distribution methods include:
How Pool Owners Prevent Miners from Hoarding Blocks
- Real-time Submission Verification: The mining pool requires miners to submit all low difficulty hash values (shares) found and verifies their validity in real-time, ensuring miners are not hoarding.
- Monitoring Computing Power Fluctuations: The mining pool monitors the computing power fluctuations of each miner. If a miner's computing power suddenly drops significantly, the pool will suspect they might be hoarding blocks.
- Reputation Scoring: The mining pool establishes a reputation scoring system for each miner. Miners with long-term good performance will receive higher rewards, while miners with poor records will be warned or kicked out of the pool.
Impact of Mining Pools on Decentralization
Mining pools, by concentrating the computing power of a large number of miners, have made Bitcoin mining more centralized, which poses a certain threat to Bitcoin's decentralized nature:
- Concentration of Computing Power: Large mining pools control a large amount of computing power in the network, reducing the degree of decentralization of the Bitcoin network.
- Influence on Consensus: The concentration of computing power in the hands of a few mining pools gives these pools greater influence in the consensus process, potentially even swaying decisions in the Bitcoin network.
Risk of 51% Attack
If a mining pool or combined mining pools control over 51% of the computing power of the Bitcoin network, they could launch the following attacks:
- Double Spending Attack: The attacker can create two transactions using the same UTXO and choose to confirm one transaction on a private chain while the other transaction is confirmed on the public chain. Through the 51% computing power advantage, the attacker can make the private chain surpass the public chain, invalidating the transaction on the public chain.
- Fork Attack: The attacker can create forks on the network, invalidating transactions on shorter chains by controlling the longer chain, causing transaction rollbacks.
- Denial of Service Attack: The attacker can choose not to broadcast certain transactions or blocks to the network, causing these transactions or blocks to be unable to be confirmed, or even prevent certain users from making transactions.
BTC Script
Working Principle
Bitcoin uses a stack-based script language to handle transaction inputs and outputs, specifically designed to verify the legitimacy of Bitcoin transactions. Bitcoin script is non-Turing complete, designed to ensure the security and simplicity of transactions.
Bitcoin scripts are mainly used to create verification logic between transaction inputs and outputs, ensuring that only legitimate owners can spend Bitcoins. The output script from the previous transaction and the input script of the current transaction are concatenated and executed; if there are no issues, it's considered legal.
- Output Script (ScriptPubKey): Defined in the transaction output, specifying how to spend that output.
- Input Script (ScriptSig): Defined in the transaction input, providing data that meets the conditions of the output script.
- Script Execution: The input script and output script are concatenated and executed, verifying whether the input script can unlock the output script.
Script Execution Process
When a Bitcoin transaction is broadcast to the network, Bitcoin nodes verify the input and output scripts of that transaction.
- Concatenate Scripts: Concatenate the output script (locking script) from the previous transaction with the input script (unlocking script) of the current transaction to form a complete script.
- Execute Script: Execute script instructions sequentially in a stack-based virtual machine.
- Stack Operations: The script language uses a stack for operations, including pushing data onto the stack, popping data from the stack, performing hash calculations, signature verification, etc.
- Verify Result: If the script executes completely and the top element of the stack is true (True), the transaction input is considered legal, and the transaction is accepted. If the top element of the stack is false (False) or an error occurs during script execution, the transaction input is rejected, and the transaction is invalid.
Pay-to-PubKey-Hash(P2PKH)
P2PKH is the most common payment method in Bitcoin transactions. It uses a public key hash (PubKey Hash) to lock Bitcoins, and only users with the corresponding private key can unlock and spend these Bitcoins.
Working Method
-
Output Script(ScriptPubKey):
OP_DUP OP_HASH160 <PubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
OP_DUP
:Duplicate the top element of the stack (public key).OP_HASH160
: Perform Hash160 (SHA-256 followed by RIPEMD-160) on the public key.<PubKeyHash>
:Hash of the public key.OP_EQUALVERIFY
:Compare if two elements are equal.OP_CHECKSIG
:Verify if the signature corresponds to the public key.
-
Input Script(ScriptSig):
<Signature> <PubKey>
<Signature>
:Signature of the transaction.<PubKey>
:Public key.
Example
-
Alice Generates Transaction: Alice sends Bitcoin to Bob, creating a P2PKH output that locks Bob's public key hash.
-
Bob Spends Bitcoin: Bob creates a new transaction, referencing Alice's transaction as input, and provides an unlocking script (including signature and public key).
-
Verification Process
-
Concatenated script:
<Signature> <PubKey> OP_DUP OP_HASH160 <PubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
-
Execute script: Verify if the hash of
<PubKey>
equals<PubKeyHash>
, and verify if<Signature>
is valid.
-
Pay-to-Script-Hash (P2SH)
P2SH allows Bitcoin addresses to represent arbitrary script conditions, rather than simple public key hashes.
- Simplifies the use of complex scripts: P2SH allows users to use complex conditions to spend Bitcoin, such as multi-signature, multi-step verification, etc., without the sender needing to understand these complex script conditions.
- Improves flexibility and security: Through P2SH, complex scripts are hidden in hash values and only revealed when spending, effectively protecting the privacy and security of the script.
- Supports complex conditions: Through P2SH, complex payment conditions such as multi-signature, time-locking, conditional payment can be easily implemented without the sender needing to understand the specific implementation details.
- Compatibility and extensibility: P2SH allows new script types and conditions to be seamlessly integrated into the existing Bitcoin network without requiring major changes to the Bitcoin protocol.
P2SH transactions involve two stages: creating a P2SH output and spending a P2SH output. Here's the detailed working principle:
Creating P2SH Output
- Generate Redeem Script: The receiver defines a complex conditional script that contains the conditions required to spend the Bitcoin.
- Calculate Script Hash: Perform Hash160 (SHA-256 followed by RIPEMD-160) operation on the redeem script to obtain a script hash value.
- Create P2SH output script: The output script contains this script hash value, in the following format:
OP_HASH160 <ScriptHash> OP_EQUAL
OP_HASH160
: Perform Hash160 operation on the subsequently provided redeem script.<ScriptHash>
: Hash value of the redeem script.OP_EQUAL
: Verify if the calculated hash value equals the provided hash value.
Spending P2SH Output
- Create Input Script (ScriptSig): The spender creates an input script containing unlock conditions, including data that satisfies the redeem script conditions and the redeem script itself.
- Input Script Format:
<Signature> <PubKey> <RedeemScript>
<Signature>
: Signature that satisfies the redeem script conditions.<PubKey>
: Public key that satisfies the redeem script conditions (if needed).<RedeemScript>
: The actual redeem script, containing spending conditions.
- Verification Process:
- Concatenate the input script and output script to form a complete verification script.
- When executing the script, first verify if the hash value of the redeem script matches the hash value in the output script.
- If it matches, execute the redeem script to verify if the provided data (such as signatures and public keys) satisfies the conditions of the redeem script.
Example
Creating P2SH Transaction
-
Alice generates complex script: Alice wants to create a multi-signature address requiring at least two signatures from Bob and Charlie to spend the Bitcoin. The redeem script is as follows:
2 <BobPubKey> <CharliePubKey> 2 OP_CHECKMULTISIG
-
Calculate redeem script hash:
- The redeem script undergoes Hash160 operation to obtain the script hash
<ScriptHash>
.
- The redeem script undergoes Hash160 operation to obtain the script hash
-
Create P2SH output: Alice creates a P2SH output, sending Bitcoin to the
<ScriptHash>
address, with the output script being:OP_HASH160 <ScriptHash> OP_EQUAL
Spending P2SH Output
-
Bob and Charlie cooperate to spend Bitcoin: Bob and Charlie create a new transaction, referencing Alice's P2SH output, and provide the following input script:
<SignatureBob> <SignatureCharlie> 2 <BobPubKey> <CharliePubKey> 2 OP_CHECKMULTISIG
-
<SignatureBob>
and<SignatureCharlie>
: Signatures from Bob and Charlie. -
<BobPubKey>
and<CharliePubKey>
: Public keys of Bob and Charlie. -
Redeem script
2 <BobPubKey> <CharliePubKey> 2 OP_CHECKMULTISIG
.
-
-
Verification Process:
-
Concatenated script:
<SignatureBob> <SignatureCharlie> 2 <BobPubKey> <CharliePubKey> 2 OP_CHECKMULTISIG OP_HASH160 <ScriptHash> OP_EQUAL
-
Verification: First verify if the hash value of the redeem script matches the
<ScriptHash>
in the output script, then execute the redeem script to verify if the signatures and public keys satisfy the conditions.
-
Proof of Burn
Proof of Burn is a consensus mechanism where users prove they have performed a specific operation by "burning" Bitcoin. The way to burn Bitcoin is to send it to an unusable address (i.e., an address without a private key), making these Bitcoins permanently unspendable.
Working Method
- Create Transaction: Users create a transaction, sending Bitcoin to a special address, for example, an address starting with
1Burn
. - Verify Burning: Other nodes verify the transaction and confirm that the Bitcoin has been sent to the burn address.
- Consensus Proof: Users can use the burn transaction as proof to participate in specific operations or receive rewards.
Example Applications
- Issuing New Coins: Some blockchain projects use the Proof of Burn mechanism to issue new coins, where users gain the right to issue new coins by burning Bitcoin.
- Consensus Mechanism: Proof of Burn can be used to prove users' long-term investment commitment, as burned Bitcoin cannot be recovered.
BTC Forks
Hard Fork
A hard fork is a major change to the blockchain protocol that is incompatible with previous versions. All participants must update to the new version to continue participating in transactions and block verification on the new chain. If some nodes do not update the protocol, this fork will permanently exist, forming two different chains.
An Example:
Suppose in the Bitcoin network, the size limit for each block is 1MB, and each transaction takes about 250 bytes, so each block can contain about 4000 transactions. If we expand the block size to 4MB, this will cause a hard fork.
- Impact: Old nodes (nodes that haven't updated the protocol) will not be able to recognize and accept 4MB blocks created by new nodes.
- Potential Issues: Transaction replay, where if a user makes a transaction on chain A, that transaction might be rebroadcast to chain B.
- Solution: Introduce a chainID (chain identifier) to distinguish different chains.
Soft Fork
A soft fork is a backward-compatible modification to the blockchain protocol. Even if some nodes haven't updated to the new protocol, they can still accept and verify blocks generated by new nodes (as long as blocks published by new nodes are considered legal by old nodes, it's a soft fork). Soft forks do not cause permanent chain splits, only temporary forks until all nodes upgrade to the new protocol.
Using the same example, if we adjust the block size from 1MB to 0.5MB, it would result in a soft fork because old nodes also recognize the new protocol. There would only be temporary forks, not permanent ones.
Author: LeapWhale
Copyright: This article is copyrighted by LeapWhale. If reproduced, please cite the source!