Unveiling the Mystery of Mining

Beginner7/17/2024, 1:18:16 AM
This article provides a detailed introduction to the "mining" process in blockchain. By drawing an analogy with traditional mining activities, it explains the basic concept of digital mining, which involves using computational resources to solve mathematical problems for transaction validation and new currency issuance.

Forward the Original Title ‘白话区块链三:揭开挖矿神秘的面纱——挖矿是什么?为什么要挖矿?谁是我们买不起显卡的罪魁祸首?’

One of the most familiar concepts related to blockchain for everyone is probably mining. Many people may have heard about mining numerous times but are not quite sure what it actually entails. In this section, we will interrupt our regular programming to first introduce “mining.”

A quick recap of the content from “Plain Blockchain 1: Introduction to Bitcoin (The Pioneer of Blockchain Revolution and the Challenger of Sovereign Currency),” where Satoshi Nakamoto designed the Bitcoin monetary system to link the rewards for bookkeeping with currency issuance. This approach allows the currency issuance to be automated through the bookkeeping process, solving the currency issuance problem while also encouraging bookkeepers to actively participate.

1. What is Mining?

In the real world, mining involves miners using various tools to dig out precious metals hidden in rocks from mines. Miners extract value from these rare metals hidden in nature through physical labor.

For blockchain projects with rewards for bookkeeping (usually digital currency projects), network nodes expend computational resources to solve problems. Once they find the solution, they package the block and receive a reward in the form of newly issued currency. This process is analogous to extracting precious metals like gold from ore, hence it is commonly referred to as “mining.” Here, the bookkeepers are the miners, who compete to package blocks using hardware and electricity, resulting in the creation of new currency.

2. Why is Mining Necessary?

Mining serves two main purposes: validating recent transactions by packaging them into blocks and linking them to the blockchain, and issuing new currency by rewarding bookkeepers. Below are the detailed functions of mining:

  1. Selection of Bookkeepers: A strategy is needed to select the actual bookkeepers from numerous candidates. The mining result is used as the basis for this selection, ensuring that every transaction is recognized by all participants, achieving consensus across the network.
  2. Transaction Verification: Each Bitcoin transaction needs to be verified by miners in the network. This process confirms the validity of the transaction, including:
    • Ensuring the transaction format and size meet the specifications.
    • Verifying the validity of each transaction’s signature to ensure it was initiated by the user possessing the related private key.
    • Checking that the input amount exceeds the output amount (with part of the amount taken as a fee), ensuring that the tokens used for payment have not been double-spent.
    • Confirming that the transaction has not been previously included in a block.
  3. Issuance of New Currency: Mining is also the way new Bitcoins enter circulation. When a miner successfully mines a new block, they receive a certain amount of Bitcoin as a reward. This reward mechanism not only incentivizes people to participate in mining but also serves as a method of Bitcoin issuance. This method of currency issuance ensures a steady and controlled increase in the circulation of currency, helping to manage inflation.
  4. Encouraging Participation: The reward mechanism motivates more people to participate in maintaining the currency system, promoting its continuous and robust development.
  5. Enhancing Network Security and Decentralization: The rewards from mining lead to a large number of miners, resulting in a distributed computational power. This decentralization ensures that no single entity can control 50% of the computational power, thereby enhancing the system’s transparency and security. Adhering to the longest chain principle further improves the system’s security.

3. Why Are Miners Willing to Participate in Mining?

Miners are incentivized to participate in mining because they receive substantial rewards for successfully packaging a block onto the blockchain. These rewards come from two main sources:

  • Block Rewards (Newly Issued Currency): The currency system automatically issues new currency, which goes entirely to the miner. For instance, in the Bitcoin system, currently, miners receive 3.125 Bitcoins for each block they package. Given that each Bitcoin is valued at around $65,000, packaging a single block can yield over $200,000, approximately 1.47 million RMB.
  • Transaction Fees Paid by Users: Due to the limited capacity of a block to hold transaction records, some users pay transaction fees to incentivize miners to prioritize their transactions for faster confirmation. When selecting transactions from the pool to be included in the block, miners tend to choose those with higher fees. A block can contain thousands of transactions, and all the fees from these transactions go to the miner, representing another significant source of income. As more people use Bitcoin for transactions, the competition for inclusion in blocks intensifies, leading to higher fees that users are willing to pay.

Over time, the block rewards will decrease (for example, due to Bitcoin’s halving mechanism, where the reward is halved approximately every four years). Eventually, after all 21 million Bitcoins have been mined, expected around the year 2141, the automatic block reward will cease to exist, and transaction fees will become the primary source of income for miners.

Tips

Bitcoin generates a new block approximately every 10 minutes. Initially, each new block produced 50 Bitcoins. This reward undergoes halving every four years, and to date, there have been four such halving events. Currently, each block generates 3.125 Bitcoins, with the most recent halving occurring in April 2024. The next halving is anticipated around 2028. By around 2141, Bitcoin will reach its issuance limit.

The transaction fee is influenced not only by supply and demand but also by the size of the transaction, as fees are proportional to the space the transaction occupies in the block.

4. How to Participate in Mining

For miners, participating in mining is straightforward. Download a digital currency wallet client, and within the client, click the mining button to start mining.

For blockchain projects with block rewards, the mining algorithm is typically written into a script integrated into the wallet. Miners simply need to click a button to start the script.

The mining algorithm is deterministic, meaning that as long as miners continuously run the algorithm, they will eventually get a result. However, due to varying computational resources, the time required to calculate this result can differ among miners. Once a node calculates the target value, other miners’ efforts during that period are rendered futile, resulting in negative returns due to the expended physical resources.

To avoid wasted effort, miners often pool their computational resources by joining a mining pool node. This node operates like any other node but has significantly more computational power. When the pool successfully mines a block, the rewards are distributed among the participating miners based on their contributed computational resources. It’s important to note that on the blockchain, the miner recorded as packaging the block is the mining pool node, while individual miners receive their share of the rewards allocated by the pool, not directly from the currency system.

Bitmain, a company that manufactures specialized high-efficiency mining chips, has solidified the role of mining pools, contributing to the centralization of bookkeeping power.

5. The Specifics of the Mining Puzzle

Different blockchain projects may have varying mining puzzles and levels of difficulty. Here, we take Bitcoin as an example. The mining algorithm used by Bitcoin is called Proof of Work (PoW). The essence of this algorithm is that to obtain a result, a certain amount of work must be expended to prove it.

The mining puzzle is not a traditional mathematical problem but involves finding a random number, known as a nonce. This nonce, when combined with the data in the block and processed through a hash function, must produce a hash value that meets a specific condition. Typically, this condition requires the hash value to be less than a target value (or, equivalently, that the first n bits of the hash value are zero). The equation is as follows: hash(nonce+block_data)≤target\text{hash}(\text{nonce} + \text{block_data}) \leq \text{target}hash(nonce+block_data)≤target

Bitcoin uses the SHA-256 hash function, which converts any length of input into a fixed-length output of 256 bits (equivalent to 64 hexadecimal digits or 32 bytes). The output is nearly random but guaranteed to be the same for the same input. Mining involves continuously changing the nonce and hashing the block header data using SHA-256 until a hash value that meets the target condition is found.

For example, a SHA-256 hash value with the first 30 bits being zeros: 000000000000000000000000000000111111010000011011000100100110111011000110100010011011000110100010110110101010011101011010100100011011010001111101001111110101001101111101011110011100011110011110000111000100110000001011011010001110011100110010111010010010010001101010110010110000000000000000000000000000000111111010000011011000100100110111011000110100010011011000110100010110110101010011101011010100100011011010001111101001111110101001101111101011110011100011110011110000111000100110000001011011010001110011100110010111010010010010001101010110010110000000000000000000000000000000111111010000011011000100100110111011000110100010011011000110100010110110101010011101011010100100011011010001111101001111110101001101111101011110011100011110011110000111000100110000001011011010001110011100110010111010010010010001101010110010110

Converting this to hexadecimal results in a value starting with seven zeros: 00000003f41b126ec689b1a2da9d5d46d13d0fd1bece47983d59c5d32eb4ac9000000003f41b126ec689b1a2da9d5d46d13d0fd1bece47983d59c5d32eb4ac9000000003f41b126ec689b1a2da9d5d46d13d0fd1bece47983d59c5d32eb4ac90

To simplify, the probability of finding a hash with the first n bits being zero is 12n\frac{1}{2^n}2n1​. The larger the n, the more bits are zero, and the lower the probability:

  • n=10n = 10n=10: 1 in 1,024
  • n=20n = 20n=20: 1 in 1,048,576
  • n=30n = 30n=30: 1 in 1,073,741,824
  • n=40n = 40n=40: 1 in 1,099,511,627,776
  • n=50n = 50n=50: 1 in 1,125,899,906,842,624

With n up to 256, finding such a hash value with current human computational power, excluding quantum computers, is virtually impossible before the Earth ceases to exist.

Due to the properties of SHA-256, the only method is brute force, which involves continuously trying different nonces until the condition is met. This necessity for high-performance computing equipment is why mining requires such devices.

Since you cannot predict the hash value generated by adding the nonce to the block data and passing it through SHA-256, the process is entirely random. For instance, if the target hash value is 10,000, you have no way of knowing which nonce combined with the block data will yield a hash value less than 10,000. This unpredictable and random nature means miners must keep enumerating possibilities until the condition is satisfied. If multiple values meet the condition, the smallest hash value is chosen since a smaller hash value indicates higher difficulty and lower probability of occurrence.

Verifying if a generated hash value meets the requirement is easy, requiring just one comparison operation. However, finding a hash value less than or equal to the target value can only be achieved through brute force enumeration. This characteristic, where verifying a result is easy but finding the result is hard, is known as computational asymmetry.

6. Code Simulation of the Mining Algorithm

The following code simulates the mining process. It starts with a block header data string “geekbang” and incrementally searches from a nonce value of 10,000 until it finds a nonce that meets the specified condition.

Here’s a Python script that demonstrates the mining process:


import hashlib

def main():

    base_string = "geekbang"

    nonce = 10000

    count = 0

    while True:

        target_string = base_string + str(nonce)

        pow_hash = hashlib.sha256(target_string.encode()).hexdigest()

        count += 1

        if pow_hash.startswith("0000"):  # First 4 hex digits are 0, equivalent to the first 16 bits being 0

            print("Hash:", pow_hash)

            print("Nonce:", nonce, "Scan times:", count)

            break

        nonce += 1

if __name__ == '__main__':

    main()

When the requirement is that the first 4 hexadecimal digits of the hash result are zero (equivalent to the first 16 bits being zero), the number of calculations is approximately 58,000. If the requirement is increased to the first 5 digits being zero, the number of calculations increases to 1.23 million. When the requirement is the first 7 digits being zero, the number of calculations reaches 160 million. This illustrates that each additional zero in the hash prefix increases the computation by approximately 16 times.

Here are the results for different target conditions:

First 4 hex digits are zero (16 bits):

import hashlib

def main():

base_string = "geekbang"

nonce = 10000

count = 0

while True:

    target_string = base_string + str(nonce)

    pow_hash = hashlib.sha256(target_string).hexdigest()

    count = count + 1

    if pow_hash.startswith("0000"): # 前4个16进制位是0,相当于前16个比特位是0

    print pow_hash

    print "nonce: %s  scan times: %s" % (nonce, count)

    break

    nonce = nonce + 1

if name == ‘main‘:

main()

As seen, increasing the required number of leading zeroes in the hash significantly increases the number of attempts needed, following an exponential growth pattern. This demonstrates the computational difficulty and resources needed for mining, underscoring the need for high-performance computing devices in the mining process.

7. Dynamic Difficulty Adjustment

To ensure that a block is generated approximately every 10 minutes, the Bitcoin system adjusts the mining difficulty by changing the number of leading zeros required in the hash value. This difficulty adjustment mechanism is a crucial part of the Bitcoin system. It evaluates the time taken to generate the last 2016 blocks, which should ideally be about two weeks. If these blocks were mined in less than two weeks, the difficulty increases by adding more leading zeros (lowering the target value). Conversely, if it took longer than two weeks, the difficulty decreases by reducing the number of leading zeros (raising the target value). This mechanism ensures that the time to generate a block remains around 10 minutes, even as the network’s total hash rate fluctuates.

This difficulty adjustment mechanism, designed by Bitcoin’s creator Satoshi Nakamoto, was planned from the beginning to automatically adapt to the total computational power of the network. It maintains a steady mining pace and prevents the currency from being issued too quickly, which could disrupt the market economy.

8. Execution Process of the Mining Algorithm

Different blockchain projects may have varying mining algorithms. Here, we describe the most famous one: the Bitcoin mining algorithm.

The execution process of Bitcoin’s underlying mining algorithm is as follows:

  1. Selecting Transactions: Choose several transactions from the memory pool (generally prioritizing those with higher fees). Automatically generate a special transaction (often called a coinbase transaction) where the recipient is the miner, and the transaction amount is the block reward plus all selected transaction fees. Place this special transaction at the beginning of the selected transactions to form the transaction set for the block to be packaged.
  2. Building the Merkle Tree: Construct a Merkle hash tree from the transaction set. A Merkle tree is a binary tree where each leaf node stores the hash of a transaction, uniquely identifying and indexing it. Each upper node stores the combined hash of its child nodes, culminating in the root node. The root node uniquely identifies the Merkle tree and, by extension, all transactions.
  3. Constructing the Block Header: Assemble the block header from the Merkle root value, a nonce, block version, previous block’s hash, timestamp, difficulty target, and nonce. The block header size is 80 bytes.
  4. Hashing the Block Header: Continuously change the nonce value in the block header and perform a double SHA-256 hash on the block header content (i.e., SHA256(SHA256(Block_Header))). Compare the resulting hash with the network’s current target value. If the result is less than the target value (indicating the first n bits are zero), the puzzle is solved, and the proof of work is complete.
  5. Broadcasting the Block: Send the newly mined block to neighboring nodes, informing them that the block has been successfully mined.
  6. Verification and Propagation: Upon receiving the new block, other nodes perform a double hash on the block header to get the block hash. They verify that the first n bits of the block hash are zero, acknowledge the block, cease calculations for this block, and propagate it to their neighboring nodes.

The size of each field in the block header is as follows:

The Merkle tree structure is as follows:

9. Controversies in Mining

The main controversy surrounding mining involves the Proof of Work (PoW) algorithms used by Bitcoin and its derivatives. These algorithms require miners to allocate substantial computational resources to solve problems that the network agrees upon. Many people are working on these computations simultaneously, but only the first to solve the problem gets the reward. The other participants’ computational and electrical resources are effectively wasted, producing no additional value.

There are two primary avenues for optimizing this resource waste:

  1. Switching to Less Resource-Intensive Algorithms: Ethereum, for instance, has transitioned from the PoW algorithm to the Proof of Stake (PoS) algorithm, which significantly reduces resource waste.
  2. Using Idle Electrical Resources: Mining nodes are experimenting with using renewable energy sources, like wind power, for mining operations. Another significant development is the utilization of otherwise wasted natural gas. Additionally, some institutions are exploring ways to recycle the excess heat generated by Bitcoin mining.

10. Questions

What is the value of mining? It seems like a waste of resources and meaningless to society.

Revisiting the “Why is Mining Necessary?” section of this article, the direct significance of mining is that it supports the issuance of digital currencies. The mining rewards incentivize more people to participate in maintaining digital currencies, making them more stable. Additionally, mining algorithms uphold transaction consistency within digital currency systems, making them more robust and less susceptible to internal and external attacks.

The indirect significance of mining is derived from digital currencies themselves. Digital currencies create a global, trustless monetary system where secure transactions can occur without the need for centralized institutions, avoiding the drawbacks of centralization. Their global nature also enables efficient and low-cost cross-border transactions.

Will mining returns decrease to the point where they fall below costs, causing miners to stop mining and transactions to cease?

It’s a common concern that mining returns are solely dependent on system rewards, which diminish over time. However, mining also generates significant income from transaction fees. As digital currencies gain wider acceptance, the market for digital currency transactions will expand. This increased transaction volume will intensify competition for block inclusion, leading to higher fees that users are willing to pay to prioritize their transactions. Consequently, miners can continue to earn substantial transaction fees, ensuring the ongoing viability of transaction processing.

If Mining Costs Exceed Blockchain Fees, Can Mining Continue?

Will transaction fees compensate for mining costs?

Yes, transaction fees can help compensate for the costs of mining. As block rewards decrease over time, transaction fees become a crucial source of income for miners. This ensures that even if the electricity costs are high, miners can still sustain their operations through the fees paid by users for transaction processing.

What Happens If Multiple Miners Solve the Puzzle Simultaneously?

Do multiple miners split the mining rewards if they simultaneously broadcast their new blocks?

No, if multiple miners solve the puzzle and broadcast their new blocks at the same time, it creates a temporary fork in the blockchain. Here’s how it works:

  1. Temporary Forks: When some nodes receive two valid blocks of the same height, they temporarily store both blocks, causing a temporary fork in the blockchain.
  2. Resolving Forks: As new blocks are mined, nodes will continue to build on the longest chain. The network eventually converges on a single chain, discarding the shorter one(s).
  3. Choosing the Main Chain: Nodes follow the longest chain (the one with the most accumulated proof of work). The miner whose block ends up on the longest chain receives the reward, while the other block becomes an “orphan” block.

Example:

  • Miner A and Miner B both mine a block at the same height and broadcast it.
  • Some nodes receive Miner A’s block first, while others receive Miner B’s block.
  • Both chains exist temporarily.
  • When the next block is mined, if it is appended to Miner A’s chain, that chain becomes the longest, and nodes will adopt it as the main chain.
  • Miner A receives the reward, and Miner B’s block is discarded.

Why Don’t Nodes with Over 50% Hash Power Cheat?

What is a 51% attack and why don’t super nodes cheat?

A 51% attack occurs when a single entity or group controls more than 50% of the network’s computational power. Here’s why super nodes don’t usually cheat:

  1. Practical Impossibility: Owning 51% of the total network hash power is highly unlikely due to the sheer scale and decentralization of major cryptocurrencies like Bitcoin.
  2. Network Validation: Even if a super node attempts to cheat, all nodes validate each block independently. Invalid transactions or double-spend attempts are rejected by the network, rendering the super node’s efforts futile.
  3. Reputation and Economic Incentives: Super nodes gain more from maintaining the integrity of the blockchain than from attacking it. Successful attacks could devalue the cryptocurrency, harming the attacker’s investment.
  4. Types of Attacks:
    • Double Spend: Attempting to spend the same coins twice.
    • Transaction Blocking: Preventing certain transactions from being included in blocks.
    • Selfish Mining: Trying to gain more mining rewards by selectively revealing blocks.
    • Timestamp Manipulation: Altering block timestamps to gain a mining advantage.
    • Empty Block Attack: Mining blocks without transactions to slow down the network.

Why Blockchain Assumes No Fixed Bookkeepers to Prevent Fraudulent Transactions

How does blockchain prevent intentional disruptions and fraudulent transactions?

  1. Verification by Neighboring Nodes: When a block is distributed to neighboring nodes, these nodes will check the transactions within the block. If they find any invalid transactions, they will reject the block and not propagate it further.
  2. Consensus Mechanism: Bitcoin’s consensus mechanism relies on the principle of the longest chain. All network nodes attempt to extend the longest valid chain. If someone tries to alter historical records (e.g., deleting a transaction), they must modify all subsequent blocks linked to the tampered block and ensure the modified chain is longer than the current main chain. This requires enormous computational resources, making it practically impossible.

Preventing Inconsistent Block Distribution by Miners

  1. Consistency in Block Distribution: A miner cannot find multiple valid nonce values within a short time frame, preventing them from distributing different legitimate blocks to different nodes simultaneously. Any illegal block will be discarded by neighboring nodes.

What is a Transaction Pool (Mempool)?

Definition and Function: In a blockchain network, all broadcast transactions that have not yet been included in a block are temporarily stored in the memory pool (mempool) of network nodes. Miners monitor their mempool to select transactions for constructing new blocks.

Transaction Selection Strategy: Miners can choose transactions from the mempool based on their strategy. Generally, they prioritize transactions with higher fees, but some may also consider other factors, such as the transaction’s age (the time it has spent in the mempool).

Revenue Sources in the Bitcoin System

Who Participates and How They Earn: Apart from users, the three main participants in the Bitcoin system are miners, developers, and node operators.

  1. Miners: Earn rewards and transaction fees through mining.
  2. Developers and Node Operators: Generally do not earn directly from the Bitcoin system. Their contributions are often idealistic, aiming to maintain the system’s integrity. They may receive income through other means, such as donations and sponsorships. Their participation in mining depends on individual preferences.

Why Have GPU Prices Increased? Why Are Mining GPUs Undesirable?

Increase in GPU Prices: The high demand for GPUs by miners for mining purposes has led to a supply shortage, causing prices to increase.

Mining GPUs: Mining GPUs are those previously used for cryptocurrency mining. These GPUs undergo intensive computation, leading to significant wear and tear. Due to their diminished performance, most people prefer not to buy used mining GPUs.

Do Miners Need to Store the Entire Ledger Data?

Full Redundant Storage Requirement: Yes, miners need to store the entire blockchain ledger to verify if a token has been previously spent and to ensure the security and integrity of the ledger. However, for very early blocks, miners only need to store the block headers, not the full block contents. This helps maintain the blockchain’s efficiency while preserving its security.

What Happens When Bitcoin’s Supply Limit is Reached?

No Automatic Rewards Beyond 21 Million Bitcoins: Once the total supply of Bitcoin reaches its limit of 21 million, the system will no longer issue new bitcoins as rewards to miners. If users are also unwilling to pay transaction fees, theoretically, the transaction system could face operational challenges. However, it is likely that users will be willing to pay transaction fees to have their transactions processed, ensuring the continuation of the system.

Block Height Will Continue to Increase: Even after reaching the maximum supply of 21 million bitcoins, the block height (the total number of blocks) will continue to increase as long as miners are willing to mine and package transactions into new blocks. The block height is not limited by the bitcoin supply cap.

Potential for Consensus Changes: The community could propose changes to the consensus rules, such as increasing the total bitcoin supply, to allow for new coin generation if needed.

How Are Miners Rewarded?

Coinbase Transaction: In the Bitcoin blockchain, miner rewards are distributed through a special transaction known as the “coinbase transaction” or “block reward.” This transaction has unique characteristics:

  1. No Broadcasting Required: The coinbase transaction is the first transaction in each block, created automatically by the mining algorithm and does not need to be broadcasted to other nodes.
  2. No Inputs: Unlike regular Bitcoin transactions, the coinbase transaction has no input (no sender). It generates new bitcoins that are rewarded to the miner.
  3. Outputs: The coinbase transaction outputs the reward to the miner’s wallet address, which includes the newly minted bitcoins and all transaction fees from the transactions included in the block.

How is Miner Revenue Calculated?

Revenue Calculation per Block: Miner revenue is calculated each time a block is successfully mined and confirmed by the network’s consensus mechanism. The miner (or mining pool) that mines the block receives the block reward and the cumulative transaction fees from all transactions included in the block.

Process of Receiving Rewards: Once a miner or mining pool successfully mines a block and it is confirmed by the network, they receive the block reward and transaction fees. This is executed through the coinbase transaction, which converts the fees and rewards into unspent transaction outputs (UTXOs) credited to the miner’s account.

Are Blocks Created Sequentially or in Parallel?

Sequential Creation: Blocks are created sequentially in the blockchain. A new block can only be created after the previous block has been successfully mined and added to the chain.

Packaging Transactions

Multiple Transactions per Block: Blocks typically contain multiple transactions. Miners include as many transactions as possible to maximize their transaction fee earnings, rather than packaging transactions individually.

Utilization of Block Space

Partially Filled Blocks: Most blocks are not fully utilized. Miners start working on the next block as soon as they find a valid hash that meets the difficulty requirement, regardless of whether the block is completely full.

Mining Without Transactions

Empty Blocks: Blocks can be mined even if there are no transactions to include. These blocks, called empty blocks, still provide a system reward to the miner.

Handling Blockchain Forks

Longest Chain Rule: When a fork occurs, the network follows the chain with the most accumulated proof of work, which is usually the longest chain. Nodes switch to the longer chain once it becomes evident which one has more work put into it.

Preventing Double-Spending

Double-Spend Resolution:

  • If a block contains conflicting transactions (double spend), only the first valid transaction to be included in a block is considered valid. The other conflicting transaction is discarded.
  • If two conflicting transactions are included in different blocks, the one in the block that gets confirmed first is considered valid.

Detailed Double-Spending Handling

Validation Process:

  • Between Blocks: If two transactions attempting to spend the same coin are included in separate blocks, the transaction in the block that is confirmed first will be considered valid. The block containing the conflicting transaction will be rejected.
  • Within a Single Block: If two conflicting transactions are included in the same block, the miner will include only one. The miner typically chooses based on the transaction fee (higher fee gets preference) or the transaction’s age (earlier transaction gets preference).

How Do Users Control the Amount of Transaction Fees They Pay?

Transaction Fee Calculation: Users can control the transaction fee to expedite the confirmation of their transactions. The fee is determined by the following formula:

Transaction Fee=Total Input−Total Output−Change

Users set the transaction fee by adjusting the input amount, the output amount, and the change amount.

The Digital Currency Mining Process

  1. Prepare Mining Equipment: Set up mining hardware or high-performance computing devices.
  2. Ensure Internet Access: Connect the mining equipment to the internet.
  3. Download Digital Wallet: Obtain a digital wallet and generate your private and public keys.
  4. Start Mining: Click the mining button in the wallet to begin mining.

Mining in a Pool

Earnings Distribution: When mining in a pool, the pool node receives the block reward. The pool then distributes the earnings to its members based on their contributed computational power. This distribution is executed through transfers to the miners’ wallets.

What is Selfish Mining?

Selfish Mining: Selfish mining is a strategy where a miner (or mining pool) finds a new block but does not immediately broadcast it. Instead, they continue mining privately on their chain (hidden chain). Once they find additional blocks, they broadcast them all at once. This can invalidate other miners’ work and tilt computational power and rewards towards the selfish miner. Bitcoin can mitigate the impact of selfish mining by improving the broadcasting protocol.

Node Validation Upon Receiving Transactions and Blocks

Transaction Validation: When a transaction is broadcast to a node, it undergoes several checks to determine if it should be added to the mempool:

  1. Transaction Format: Verify the correctness of the transaction data structure.
  2. Transaction Signature: Validate the authenticity of the transaction signature.
  3. Double-Spending: Ensure the input has not been previously spent in the mempool or blockchain.
  4. Inputs and Outputs: Confirm that the total input amount is greater than or equal to the total output amount.
  5. Transaction Scripts: Execute and verify scripts (mainly in smart contracts).
  6. Locktime: Check if the locktime condition (block height or time) is satisfied.
  7. Transaction Size and Fees: Ensure the transaction size and fee are adequate.

Block Validation: When a miner node receives a new block, it performs extensive checks on the block and its transactions:

  1. Transaction Validity: Validate each transaction within the block (same checks as transaction validation).
  2. Block-Specific Checks:
    • Block Size: Ensure the block size is within permissible limits.
    • Block Reward: Verify the block reward (newly minted bitcoins and transaction fees) is correct.
    • Merkle Root: Compute and validate the Merkle root of the block.
    • Timestamp: Confirm that the block timestamp is within a reasonable range.
    • Difficulty Target: Check that the block meets the current difficulty target.

11. References

[1] Lecture 12 | In-depth Blockchain Technology (4): PoW Consensus-In-depth explanation of Blockchain-Geek Time:https://time.geekbang.org/column/article/5963

Disclaimer:

  1. This article is reprinted from[大后端私房菜]. Forward the Original Title‘白话区块链三:揭开挖矿神秘的面纱——挖矿是什么?为什么要挖矿?谁是我们买不起显卡的罪魁祸首?’. All copyrights belong to the original author [Lucky小黄人]. If there are objections to this reprint, please contact the Gate Learn team, and they will handle it promptly.
  2. Liability Disclaimer: The views and opinions expressed in this article are solely those of the author and do not constitute any investment advice.
  3. Translations of the article into other languages are done by the Gate Learn team. Unless mentioned, copying, distributing, or plagiarizing the translated articles is prohibited.

Unveiling the Mystery of Mining

Beginner7/17/2024, 1:18:16 AM
This article provides a detailed introduction to the "mining" process in blockchain. By drawing an analogy with traditional mining activities, it explains the basic concept of digital mining, which involves using computational resources to solve mathematical problems for transaction validation and new currency issuance.

Forward the Original Title ‘白话区块链三:揭开挖矿神秘的面纱——挖矿是什么?为什么要挖矿?谁是我们买不起显卡的罪魁祸首?’

One of the most familiar concepts related to blockchain for everyone is probably mining. Many people may have heard about mining numerous times but are not quite sure what it actually entails. In this section, we will interrupt our regular programming to first introduce “mining.”

A quick recap of the content from “Plain Blockchain 1: Introduction to Bitcoin (The Pioneer of Blockchain Revolution and the Challenger of Sovereign Currency),” where Satoshi Nakamoto designed the Bitcoin monetary system to link the rewards for bookkeeping with currency issuance. This approach allows the currency issuance to be automated through the bookkeeping process, solving the currency issuance problem while also encouraging bookkeepers to actively participate.

1. What is Mining?

In the real world, mining involves miners using various tools to dig out precious metals hidden in rocks from mines. Miners extract value from these rare metals hidden in nature through physical labor.

For blockchain projects with rewards for bookkeeping (usually digital currency projects), network nodes expend computational resources to solve problems. Once they find the solution, they package the block and receive a reward in the form of newly issued currency. This process is analogous to extracting precious metals like gold from ore, hence it is commonly referred to as “mining.” Here, the bookkeepers are the miners, who compete to package blocks using hardware and electricity, resulting in the creation of new currency.

2. Why is Mining Necessary?

Mining serves two main purposes: validating recent transactions by packaging them into blocks and linking them to the blockchain, and issuing new currency by rewarding bookkeepers. Below are the detailed functions of mining:

  1. Selection of Bookkeepers: A strategy is needed to select the actual bookkeepers from numerous candidates. The mining result is used as the basis for this selection, ensuring that every transaction is recognized by all participants, achieving consensus across the network.
  2. Transaction Verification: Each Bitcoin transaction needs to be verified by miners in the network. This process confirms the validity of the transaction, including:
    • Ensuring the transaction format and size meet the specifications.
    • Verifying the validity of each transaction’s signature to ensure it was initiated by the user possessing the related private key.
    • Checking that the input amount exceeds the output amount (with part of the amount taken as a fee), ensuring that the tokens used for payment have not been double-spent.
    • Confirming that the transaction has not been previously included in a block.
  3. Issuance of New Currency: Mining is also the way new Bitcoins enter circulation. When a miner successfully mines a new block, they receive a certain amount of Bitcoin as a reward. This reward mechanism not only incentivizes people to participate in mining but also serves as a method of Bitcoin issuance. This method of currency issuance ensures a steady and controlled increase in the circulation of currency, helping to manage inflation.
  4. Encouraging Participation: The reward mechanism motivates more people to participate in maintaining the currency system, promoting its continuous and robust development.
  5. Enhancing Network Security and Decentralization: The rewards from mining lead to a large number of miners, resulting in a distributed computational power. This decentralization ensures that no single entity can control 50% of the computational power, thereby enhancing the system’s transparency and security. Adhering to the longest chain principle further improves the system’s security.

3. Why Are Miners Willing to Participate in Mining?

Miners are incentivized to participate in mining because they receive substantial rewards for successfully packaging a block onto the blockchain. These rewards come from two main sources:

  • Block Rewards (Newly Issued Currency): The currency system automatically issues new currency, which goes entirely to the miner. For instance, in the Bitcoin system, currently, miners receive 3.125 Bitcoins for each block they package. Given that each Bitcoin is valued at around $65,000, packaging a single block can yield over $200,000, approximately 1.47 million RMB.
  • Transaction Fees Paid by Users: Due to the limited capacity of a block to hold transaction records, some users pay transaction fees to incentivize miners to prioritize their transactions for faster confirmation. When selecting transactions from the pool to be included in the block, miners tend to choose those with higher fees. A block can contain thousands of transactions, and all the fees from these transactions go to the miner, representing another significant source of income. As more people use Bitcoin for transactions, the competition for inclusion in blocks intensifies, leading to higher fees that users are willing to pay.

Over time, the block rewards will decrease (for example, due to Bitcoin’s halving mechanism, where the reward is halved approximately every four years). Eventually, after all 21 million Bitcoins have been mined, expected around the year 2141, the automatic block reward will cease to exist, and transaction fees will become the primary source of income for miners.

Tips

Bitcoin generates a new block approximately every 10 minutes. Initially, each new block produced 50 Bitcoins. This reward undergoes halving every four years, and to date, there have been four such halving events. Currently, each block generates 3.125 Bitcoins, with the most recent halving occurring in April 2024. The next halving is anticipated around 2028. By around 2141, Bitcoin will reach its issuance limit.

The transaction fee is influenced not only by supply and demand but also by the size of the transaction, as fees are proportional to the space the transaction occupies in the block.

4. How to Participate in Mining

For miners, participating in mining is straightforward. Download a digital currency wallet client, and within the client, click the mining button to start mining.

For blockchain projects with block rewards, the mining algorithm is typically written into a script integrated into the wallet. Miners simply need to click a button to start the script.

The mining algorithm is deterministic, meaning that as long as miners continuously run the algorithm, they will eventually get a result. However, due to varying computational resources, the time required to calculate this result can differ among miners. Once a node calculates the target value, other miners’ efforts during that period are rendered futile, resulting in negative returns due to the expended physical resources.

To avoid wasted effort, miners often pool their computational resources by joining a mining pool node. This node operates like any other node but has significantly more computational power. When the pool successfully mines a block, the rewards are distributed among the participating miners based on their contributed computational resources. It’s important to note that on the blockchain, the miner recorded as packaging the block is the mining pool node, while individual miners receive their share of the rewards allocated by the pool, not directly from the currency system.

Bitmain, a company that manufactures specialized high-efficiency mining chips, has solidified the role of mining pools, contributing to the centralization of bookkeeping power.

5. The Specifics of the Mining Puzzle

Different blockchain projects may have varying mining puzzles and levels of difficulty. Here, we take Bitcoin as an example. The mining algorithm used by Bitcoin is called Proof of Work (PoW). The essence of this algorithm is that to obtain a result, a certain amount of work must be expended to prove it.

The mining puzzle is not a traditional mathematical problem but involves finding a random number, known as a nonce. This nonce, when combined with the data in the block and processed through a hash function, must produce a hash value that meets a specific condition. Typically, this condition requires the hash value to be less than a target value (or, equivalently, that the first n bits of the hash value are zero). The equation is as follows: hash(nonce+block_data)≤target\text{hash}(\text{nonce} + \text{block_data}) \leq \text{target}hash(nonce+block_data)≤target

Bitcoin uses the SHA-256 hash function, which converts any length of input into a fixed-length output of 256 bits (equivalent to 64 hexadecimal digits or 32 bytes). The output is nearly random but guaranteed to be the same for the same input. Mining involves continuously changing the nonce and hashing the block header data using SHA-256 until a hash value that meets the target condition is found.

For example, a SHA-256 hash value with the first 30 bits being zeros: 000000000000000000000000000000111111010000011011000100100110111011000110100010011011000110100010110110101010011101011010100100011011010001111101001111110101001101111101011110011100011110011110000111000100110000001011011010001110011100110010111010010010010001101010110010110000000000000000000000000000000111111010000011011000100100110111011000110100010011011000110100010110110101010011101011010100100011011010001111101001111110101001101111101011110011100011110011110000111000100110000001011011010001110011100110010111010010010010001101010110010110000000000000000000000000000000111111010000011011000100100110111011000110100010011011000110100010110110101010011101011010100100011011010001111101001111110101001101111101011110011100011110011110000111000100110000001011011010001110011100110010111010010010010001101010110010110

Converting this to hexadecimal results in a value starting with seven zeros: 00000003f41b126ec689b1a2da9d5d46d13d0fd1bece47983d59c5d32eb4ac9000000003f41b126ec689b1a2da9d5d46d13d0fd1bece47983d59c5d32eb4ac9000000003f41b126ec689b1a2da9d5d46d13d0fd1bece47983d59c5d32eb4ac90

To simplify, the probability of finding a hash with the first n bits being zero is 12n\frac{1}{2^n}2n1​. The larger the n, the more bits are zero, and the lower the probability:

  • n=10n = 10n=10: 1 in 1,024
  • n=20n = 20n=20: 1 in 1,048,576
  • n=30n = 30n=30: 1 in 1,073,741,824
  • n=40n = 40n=40: 1 in 1,099,511,627,776
  • n=50n = 50n=50: 1 in 1,125,899,906,842,624

With n up to 256, finding such a hash value with current human computational power, excluding quantum computers, is virtually impossible before the Earth ceases to exist.

Due to the properties of SHA-256, the only method is brute force, which involves continuously trying different nonces until the condition is met. This necessity for high-performance computing equipment is why mining requires such devices.

Since you cannot predict the hash value generated by adding the nonce to the block data and passing it through SHA-256, the process is entirely random. For instance, if the target hash value is 10,000, you have no way of knowing which nonce combined with the block data will yield a hash value less than 10,000. This unpredictable and random nature means miners must keep enumerating possibilities until the condition is satisfied. If multiple values meet the condition, the smallest hash value is chosen since a smaller hash value indicates higher difficulty and lower probability of occurrence.

Verifying if a generated hash value meets the requirement is easy, requiring just one comparison operation. However, finding a hash value less than or equal to the target value can only be achieved through brute force enumeration. This characteristic, where verifying a result is easy but finding the result is hard, is known as computational asymmetry.

6. Code Simulation of the Mining Algorithm

The following code simulates the mining process. It starts with a block header data string “geekbang” and incrementally searches from a nonce value of 10,000 until it finds a nonce that meets the specified condition.

Here’s a Python script that demonstrates the mining process:


import hashlib

def main():

    base_string = "geekbang"

    nonce = 10000

    count = 0

    while True:

        target_string = base_string + str(nonce)

        pow_hash = hashlib.sha256(target_string.encode()).hexdigest()

        count += 1

        if pow_hash.startswith("0000"):  # First 4 hex digits are 0, equivalent to the first 16 bits being 0

            print("Hash:", pow_hash)

            print("Nonce:", nonce, "Scan times:", count)

            break

        nonce += 1

if __name__ == '__main__':

    main()

When the requirement is that the first 4 hexadecimal digits of the hash result are zero (equivalent to the first 16 bits being zero), the number of calculations is approximately 58,000. If the requirement is increased to the first 5 digits being zero, the number of calculations increases to 1.23 million. When the requirement is the first 7 digits being zero, the number of calculations reaches 160 million. This illustrates that each additional zero in the hash prefix increases the computation by approximately 16 times.

Here are the results for different target conditions:

First 4 hex digits are zero (16 bits):

import hashlib

def main():

base_string = "geekbang"

nonce = 10000

count = 0

while True:

    target_string = base_string + str(nonce)

    pow_hash = hashlib.sha256(target_string).hexdigest()

    count = count + 1

    if pow_hash.startswith("0000"): # 前4个16进制位是0,相当于前16个比特位是0

    print pow_hash

    print "nonce: %s  scan times: %s" % (nonce, count)

    break

    nonce = nonce + 1

if name == ‘main‘:

main()

As seen, increasing the required number of leading zeroes in the hash significantly increases the number of attempts needed, following an exponential growth pattern. This demonstrates the computational difficulty and resources needed for mining, underscoring the need for high-performance computing devices in the mining process.

7. Dynamic Difficulty Adjustment

To ensure that a block is generated approximately every 10 minutes, the Bitcoin system adjusts the mining difficulty by changing the number of leading zeros required in the hash value. This difficulty adjustment mechanism is a crucial part of the Bitcoin system. It evaluates the time taken to generate the last 2016 blocks, which should ideally be about two weeks. If these blocks were mined in less than two weeks, the difficulty increases by adding more leading zeros (lowering the target value). Conversely, if it took longer than two weeks, the difficulty decreases by reducing the number of leading zeros (raising the target value). This mechanism ensures that the time to generate a block remains around 10 minutes, even as the network’s total hash rate fluctuates.

This difficulty adjustment mechanism, designed by Bitcoin’s creator Satoshi Nakamoto, was planned from the beginning to automatically adapt to the total computational power of the network. It maintains a steady mining pace and prevents the currency from being issued too quickly, which could disrupt the market economy.

8. Execution Process of the Mining Algorithm

Different blockchain projects may have varying mining algorithms. Here, we describe the most famous one: the Bitcoin mining algorithm.

The execution process of Bitcoin’s underlying mining algorithm is as follows:

  1. Selecting Transactions: Choose several transactions from the memory pool (generally prioritizing those with higher fees). Automatically generate a special transaction (often called a coinbase transaction) where the recipient is the miner, and the transaction amount is the block reward plus all selected transaction fees. Place this special transaction at the beginning of the selected transactions to form the transaction set for the block to be packaged.
  2. Building the Merkle Tree: Construct a Merkle hash tree from the transaction set. A Merkle tree is a binary tree where each leaf node stores the hash of a transaction, uniquely identifying and indexing it. Each upper node stores the combined hash of its child nodes, culminating in the root node. The root node uniquely identifies the Merkle tree and, by extension, all transactions.
  3. Constructing the Block Header: Assemble the block header from the Merkle root value, a nonce, block version, previous block’s hash, timestamp, difficulty target, and nonce. The block header size is 80 bytes.
  4. Hashing the Block Header: Continuously change the nonce value in the block header and perform a double SHA-256 hash on the block header content (i.e., SHA256(SHA256(Block_Header))). Compare the resulting hash with the network’s current target value. If the result is less than the target value (indicating the first n bits are zero), the puzzle is solved, and the proof of work is complete.
  5. Broadcasting the Block: Send the newly mined block to neighboring nodes, informing them that the block has been successfully mined.
  6. Verification and Propagation: Upon receiving the new block, other nodes perform a double hash on the block header to get the block hash. They verify that the first n bits of the block hash are zero, acknowledge the block, cease calculations for this block, and propagate it to their neighboring nodes.

The size of each field in the block header is as follows:

The Merkle tree structure is as follows:

9. Controversies in Mining

The main controversy surrounding mining involves the Proof of Work (PoW) algorithms used by Bitcoin and its derivatives. These algorithms require miners to allocate substantial computational resources to solve problems that the network agrees upon. Many people are working on these computations simultaneously, but only the first to solve the problem gets the reward. The other participants’ computational and electrical resources are effectively wasted, producing no additional value.

There are two primary avenues for optimizing this resource waste:

  1. Switching to Less Resource-Intensive Algorithms: Ethereum, for instance, has transitioned from the PoW algorithm to the Proof of Stake (PoS) algorithm, which significantly reduces resource waste.
  2. Using Idle Electrical Resources: Mining nodes are experimenting with using renewable energy sources, like wind power, for mining operations. Another significant development is the utilization of otherwise wasted natural gas. Additionally, some institutions are exploring ways to recycle the excess heat generated by Bitcoin mining.

10. Questions

What is the value of mining? It seems like a waste of resources and meaningless to society.

Revisiting the “Why is Mining Necessary?” section of this article, the direct significance of mining is that it supports the issuance of digital currencies. The mining rewards incentivize more people to participate in maintaining digital currencies, making them more stable. Additionally, mining algorithms uphold transaction consistency within digital currency systems, making them more robust and less susceptible to internal and external attacks.

The indirect significance of mining is derived from digital currencies themselves. Digital currencies create a global, trustless monetary system where secure transactions can occur without the need for centralized institutions, avoiding the drawbacks of centralization. Their global nature also enables efficient and low-cost cross-border transactions.

Will mining returns decrease to the point where they fall below costs, causing miners to stop mining and transactions to cease?

It’s a common concern that mining returns are solely dependent on system rewards, which diminish over time. However, mining also generates significant income from transaction fees. As digital currencies gain wider acceptance, the market for digital currency transactions will expand. This increased transaction volume will intensify competition for block inclusion, leading to higher fees that users are willing to pay to prioritize their transactions. Consequently, miners can continue to earn substantial transaction fees, ensuring the ongoing viability of transaction processing.

If Mining Costs Exceed Blockchain Fees, Can Mining Continue?

Will transaction fees compensate for mining costs?

Yes, transaction fees can help compensate for the costs of mining. As block rewards decrease over time, transaction fees become a crucial source of income for miners. This ensures that even if the electricity costs are high, miners can still sustain their operations through the fees paid by users for transaction processing.

What Happens If Multiple Miners Solve the Puzzle Simultaneously?

Do multiple miners split the mining rewards if they simultaneously broadcast their new blocks?

No, if multiple miners solve the puzzle and broadcast their new blocks at the same time, it creates a temporary fork in the blockchain. Here’s how it works:

  1. Temporary Forks: When some nodes receive two valid blocks of the same height, they temporarily store both blocks, causing a temporary fork in the blockchain.
  2. Resolving Forks: As new blocks are mined, nodes will continue to build on the longest chain. The network eventually converges on a single chain, discarding the shorter one(s).
  3. Choosing the Main Chain: Nodes follow the longest chain (the one with the most accumulated proof of work). The miner whose block ends up on the longest chain receives the reward, while the other block becomes an “orphan” block.

Example:

  • Miner A and Miner B both mine a block at the same height and broadcast it.
  • Some nodes receive Miner A’s block first, while others receive Miner B’s block.
  • Both chains exist temporarily.
  • When the next block is mined, if it is appended to Miner A’s chain, that chain becomes the longest, and nodes will adopt it as the main chain.
  • Miner A receives the reward, and Miner B’s block is discarded.

Why Don’t Nodes with Over 50% Hash Power Cheat?

What is a 51% attack and why don’t super nodes cheat?

A 51% attack occurs when a single entity or group controls more than 50% of the network’s computational power. Here’s why super nodes don’t usually cheat:

  1. Practical Impossibility: Owning 51% of the total network hash power is highly unlikely due to the sheer scale and decentralization of major cryptocurrencies like Bitcoin.
  2. Network Validation: Even if a super node attempts to cheat, all nodes validate each block independently. Invalid transactions or double-spend attempts are rejected by the network, rendering the super node’s efforts futile.
  3. Reputation and Economic Incentives: Super nodes gain more from maintaining the integrity of the blockchain than from attacking it. Successful attacks could devalue the cryptocurrency, harming the attacker’s investment.
  4. Types of Attacks:
    • Double Spend: Attempting to spend the same coins twice.
    • Transaction Blocking: Preventing certain transactions from being included in blocks.
    • Selfish Mining: Trying to gain more mining rewards by selectively revealing blocks.
    • Timestamp Manipulation: Altering block timestamps to gain a mining advantage.
    • Empty Block Attack: Mining blocks without transactions to slow down the network.

Why Blockchain Assumes No Fixed Bookkeepers to Prevent Fraudulent Transactions

How does blockchain prevent intentional disruptions and fraudulent transactions?

  1. Verification by Neighboring Nodes: When a block is distributed to neighboring nodes, these nodes will check the transactions within the block. If they find any invalid transactions, they will reject the block and not propagate it further.
  2. Consensus Mechanism: Bitcoin’s consensus mechanism relies on the principle of the longest chain. All network nodes attempt to extend the longest valid chain. If someone tries to alter historical records (e.g., deleting a transaction), they must modify all subsequent blocks linked to the tampered block and ensure the modified chain is longer than the current main chain. This requires enormous computational resources, making it practically impossible.

Preventing Inconsistent Block Distribution by Miners

  1. Consistency in Block Distribution: A miner cannot find multiple valid nonce values within a short time frame, preventing them from distributing different legitimate blocks to different nodes simultaneously. Any illegal block will be discarded by neighboring nodes.

What is a Transaction Pool (Mempool)?

Definition and Function: In a blockchain network, all broadcast transactions that have not yet been included in a block are temporarily stored in the memory pool (mempool) of network nodes. Miners monitor their mempool to select transactions for constructing new blocks.

Transaction Selection Strategy: Miners can choose transactions from the mempool based on their strategy. Generally, they prioritize transactions with higher fees, but some may also consider other factors, such as the transaction’s age (the time it has spent in the mempool).

Revenue Sources in the Bitcoin System

Who Participates and How They Earn: Apart from users, the three main participants in the Bitcoin system are miners, developers, and node operators.

  1. Miners: Earn rewards and transaction fees through mining.
  2. Developers and Node Operators: Generally do not earn directly from the Bitcoin system. Their contributions are often idealistic, aiming to maintain the system’s integrity. They may receive income through other means, such as donations and sponsorships. Their participation in mining depends on individual preferences.

Why Have GPU Prices Increased? Why Are Mining GPUs Undesirable?

Increase in GPU Prices: The high demand for GPUs by miners for mining purposes has led to a supply shortage, causing prices to increase.

Mining GPUs: Mining GPUs are those previously used for cryptocurrency mining. These GPUs undergo intensive computation, leading to significant wear and tear. Due to their diminished performance, most people prefer not to buy used mining GPUs.

Do Miners Need to Store the Entire Ledger Data?

Full Redundant Storage Requirement: Yes, miners need to store the entire blockchain ledger to verify if a token has been previously spent and to ensure the security and integrity of the ledger. However, for very early blocks, miners only need to store the block headers, not the full block contents. This helps maintain the blockchain’s efficiency while preserving its security.

What Happens When Bitcoin’s Supply Limit is Reached?

No Automatic Rewards Beyond 21 Million Bitcoins: Once the total supply of Bitcoin reaches its limit of 21 million, the system will no longer issue new bitcoins as rewards to miners. If users are also unwilling to pay transaction fees, theoretically, the transaction system could face operational challenges. However, it is likely that users will be willing to pay transaction fees to have their transactions processed, ensuring the continuation of the system.

Block Height Will Continue to Increase: Even after reaching the maximum supply of 21 million bitcoins, the block height (the total number of blocks) will continue to increase as long as miners are willing to mine and package transactions into new blocks. The block height is not limited by the bitcoin supply cap.

Potential for Consensus Changes: The community could propose changes to the consensus rules, such as increasing the total bitcoin supply, to allow for new coin generation if needed.

How Are Miners Rewarded?

Coinbase Transaction: In the Bitcoin blockchain, miner rewards are distributed through a special transaction known as the “coinbase transaction” or “block reward.” This transaction has unique characteristics:

  1. No Broadcasting Required: The coinbase transaction is the first transaction in each block, created automatically by the mining algorithm and does not need to be broadcasted to other nodes.
  2. No Inputs: Unlike regular Bitcoin transactions, the coinbase transaction has no input (no sender). It generates new bitcoins that are rewarded to the miner.
  3. Outputs: The coinbase transaction outputs the reward to the miner’s wallet address, which includes the newly minted bitcoins and all transaction fees from the transactions included in the block.

How is Miner Revenue Calculated?

Revenue Calculation per Block: Miner revenue is calculated each time a block is successfully mined and confirmed by the network’s consensus mechanism. The miner (or mining pool) that mines the block receives the block reward and the cumulative transaction fees from all transactions included in the block.

Process of Receiving Rewards: Once a miner or mining pool successfully mines a block and it is confirmed by the network, they receive the block reward and transaction fees. This is executed through the coinbase transaction, which converts the fees and rewards into unspent transaction outputs (UTXOs) credited to the miner’s account.

Are Blocks Created Sequentially or in Parallel?

Sequential Creation: Blocks are created sequentially in the blockchain. A new block can only be created after the previous block has been successfully mined and added to the chain.

Packaging Transactions

Multiple Transactions per Block: Blocks typically contain multiple transactions. Miners include as many transactions as possible to maximize their transaction fee earnings, rather than packaging transactions individually.

Utilization of Block Space

Partially Filled Blocks: Most blocks are not fully utilized. Miners start working on the next block as soon as they find a valid hash that meets the difficulty requirement, regardless of whether the block is completely full.

Mining Without Transactions

Empty Blocks: Blocks can be mined even if there are no transactions to include. These blocks, called empty blocks, still provide a system reward to the miner.

Handling Blockchain Forks

Longest Chain Rule: When a fork occurs, the network follows the chain with the most accumulated proof of work, which is usually the longest chain. Nodes switch to the longer chain once it becomes evident which one has more work put into it.

Preventing Double-Spending

Double-Spend Resolution:

  • If a block contains conflicting transactions (double spend), only the first valid transaction to be included in a block is considered valid. The other conflicting transaction is discarded.
  • If two conflicting transactions are included in different blocks, the one in the block that gets confirmed first is considered valid.

Detailed Double-Spending Handling

Validation Process:

  • Between Blocks: If two transactions attempting to spend the same coin are included in separate blocks, the transaction in the block that is confirmed first will be considered valid. The block containing the conflicting transaction will be rejected.
  • Within a Single Block: If two conflicting transactions are included in the same block, the miner will include only one. The miner typically chooses based on the transaction fee (higher fee gets preference) or the transaction’s age (earlier transaction gets preference).

How Do Users Control the Amount of Transaction Fees They Pay?

Transaction Fee Calculation: Users can control the transaction fee to expedite the confirmation of their transactions. The fee is determined by the following formula:

Transaction Fee=Total Input−Total Output−Change

Users set the transaction fee by adjusting the input amount, the output amount, and the change amount.

The Digital Currency Mining Process

  1. Prepare Mining Equipment: Set up mining hardware or high-performance computing devices.
  2. Ensure Internet Access: Connect the mining equipment to the internet.
  3. Download Digital Wallet: Obtain a digital wallet and generate your private and public keys.
  4. Start Mining: Click the mining button in the wallet to begin mining.

Mining in a Pool

Earnings Distribution: When mining in a pool, the pool node receives the block reward. The pool then distributes the earnings to its members based on their contributed computational power. This distribution is executed through transfers to the miners’ wallets.

What is Selfish Mining?

Selfish Mining: Selfish mining is a strategy where a miner (or mining pool) finds a new block but does not immediately broadcast it. Instead, they continue mining privately on their chain (hidden chain). Once they find additional blocks, they broadcast them all at once. This can invalidate other miners’ work and tilt computational power and rewards towards the selfish miner. Bitcoin can mitigate the impact of selfish mining by improving the broadcasting protocol.

Node Validation Upon Receiving Transactions and Blocks

Transaction Validation: When a transaction is broadcast to a node, it undergoes several checks to determine if it should be added to the mempool:

  1. Transaction Format: Verify the correctness of the transaction data structure.
  2. Transaction Signature: Validate the authenticity of the transaction signature.
  3. Double-Spending: Ensure the input has not been previously spent in the mempool or blockchain.
  4. Inputs and Outputs: Confirm that the total input amount is greater than or equal to the total output amount.
  5. Transaction Scripts: Execute and verify scripts (mainly in smart contracts).
  6. Locktime: Check if the locktime condition (block height or time) is satisfied.
  7. Transaction Size and Fees: Ensure the transaction size and fee are adequate.

Block Validation: When a miner node receives a new block, it performs extensive checks on the block and its transactions:

  1. Transaction Validity: Validate each transaction within the block (same checks as transaction validation).
  2. Block-Specific Checks:
    • Block Size: Ensure the block size is within permissible limits.
    • Block Reward: Verify the block reward (newly minted bitcoins and transaction fees) is correct.
    • Merkle Root: Compute and validate the Merkle root of the block.
    • Timestamp: Confirm that the block timestamp is within a reasonable range.
    • Difficulty Target: Check that the block meets the current difficulty target.

11. References

[1] Lecture 12 | In-depth Blockchain Technology (4): PoW Consensus-In-depth explanation of Blockchain-Geek Time:https://time.geekbang.org/column/article/5963

Disclaimer:

  1. This article is reprinted from[大后端私房菜]. Forward the Original Title‘白话区块链三:揭开挖矿神秘的面纱——挖矿是什么?为什么要挖矿?谁是我们买不起显卡的罪魁祸首?’. All copyrights belong to the original author [Lucky小黄人]. If there are objections to this reprint, please contact the Gate Learn team, and they will handle it promptly.
  2. Liability Disclaimer: The views and opinions expressed in this article are solely those of the author and do not constitute any investment advice.
  3. Translations of the article into other languages are done by the Gate Learn team. Unless mentioned, copying, distributing, or plagiarizing the translated articles is prohibited.
Nu Starten
Meld Je Aan En Ontvang
$100
Voucher!