ScalersTalk 成长会 2018 年火热招募中,目前报名人数已经突破 1200 人,参见《持续行动,为三年后的自己,扎心地做点事——ScalersTalk 成长会 2018 年会员资格开放申请》。
这一章讲的比特币的挖矿与共识的细节。关于共识部分的思考,我相信会给你一些启发。这一章太长了,分成部分推送。这是本章的第1篇。
本章原文地址:
https://github.com/bitcoinbook/bitcoinbook/blob/develop/ch10.asciidoc
相关文章:
《精通比特币》英文版批注导读•第5章 比特币钱包技术
《精通比特币》英文版批注导读•第6章(1) 比特币交易记录《精通比特币》英文版批注导读•第7章(1) 比特币高级交易与脚本技术
Chapter 10 Mining and Consensus
Introduction
The word “mining” is somewhat misleading. By evoking the extraction of precious metals, it focuses our attention on the reward for mining, the new bitcoin created in each block. Although mining is incentivized by this reward, the primary purpose of mining is not the reward or the generation of new coins. If you view mining only as the process by which coins are created, you are mistaking the means (incentives) as the goal of the process. Mining is the mechanism that underpins the decentralized clearinghouse, by which transactions are validated and cleared. Mining is the invention that makes bitcoin special, a decentralized security mechanism that is the basis for P2P digital cash.
挖矿一词有误导性。挖矿是分布式精算的底层机制,通过挖矿交易得以验证和清算。挖矿确保比特币安全性,在无中央权威的情况下,涌现出网络级的共识。挖矿是一种激励机制,让矿工的行为与网络安全保持一致,同时发挥供货币应的效果。
Mining secures the bitcoin system and enables the emergence of network-wide consensus without a central authority. The reward of newly minted coins and transaction fees is an incentive scheme that aligns the actions of miners with the security of the network, while simultaneously implementing the monetary supply.
Tip |
The purpose of mining is not the creation of new bitcoin. That’s the incentive system. Mining is the mechanism by which bitcoin’s security is decentralized. |
Miners validate new transactions and record them on the global ledger. A new block, containing transactions that occurred since the last block, is “mined” every 10 minutes on average, thereby adding those transactions to the blockchain. Transactions that become part of a block and added to the blockchain are considered “confirmed,” which allows the new owners of bitcoin to spend the bitcoin they received in those transactions.
Miners receive two types of rewards in return for the security provided by mining: new coins created with each new block, and transaction fees from all the transactions included in the block. To earn this reward, miners compete to solve a difficult mathematical problem based on a cryptographic hash algorithm. The solution to the problem, called the Proof-of-Work, is included in the new block and acts as proof that the miner expended significant computing effort. The competition to solve the Proof-of-Work algorithm to earn the reward and the right to record transactions on the blockchain is the basis for bitcoin’s security model.
工作量证明用于确保矿工花费了相当的计算量,才达到计算的效果。
The process is called mining because the reward (new coin generation) is designed to simulate diminishing returns, just like mining for precious metals. Bitcoin’s money supply is created through mining, similar to how a central bank issues new money by printing bank notes. The maximum amount of newly created bitcoin a miner can add to a block decreases approximately every four years (or precisely every 210,000 blocks). It started at 50 bitcoin per block in January of 2009 and halved to 25 bitcoin per block in November of 2012. It halved again to 12.5 bitcoin in July 2016. Based on this formula, bitcoin mining rewards decrease exponentially until approximately the year 2140, when all bitcoin (20.99999998 million) will have been issued. After 2140, no new bitcoin will be issued.
比特币产生的速度每四年减少一半,最开始是每个区块50个币,到2016年7月,减为12.5个。在2140年以后,区块不再产生新币,矿工由交易费用激励。
Bitcoin miners also earn fees from transactions. Every transaction may include a transaction fee, in the form of a surplus of bitcoin between the transaction’s inputs and outputs. The winning bitcoin miner gets to “keep the change” on the transactions included in the winning block. Today, the fees represent 0.5% or less of a bitcoin miner’s income, the vast majority coming from the newly minted bitcoin. However, as the reward decreases over time and the number of transactions per block increases, a greater proportion of bitcoin mining earnings will come from fees. Gradually, the mining reward will be dominated by transaction fees, which will form the primary incentive for miners. After 2140, the amount of new bitcoin in each block drops to zero and bitcoin mining will be incentivized only by transaction fees.
In this chapter, we will first examine mining as a monetary supply mechanism and then look at the most important function of mining: the decentralized consensus mechanism that underpins bitcoin’s security.
To understand mining and consensus, we will follow Alice’s transaction as it is received and added to a block by Jing’s mining equipment. Then we will follow the block as it is mined, added to the blockchain, and accepted by the bitcoin network through the process of emergent consensus.
Bitcoin Economics and Currency Creation
Bitcoin are “minted” during the creation of each block at a fixed and diminishing rate. Each block, generated on average every 10 minutes, contains entirely new bitcoin, created from nothing. Every 210,000 blocks, or approximately every four years, the currency issuance rate is decreased by 50%. For the first four years of operation of the network, each block contained 50 new bitcoin.
每四年,比特币的供应速度下降一半。
In November 2012, the new bitcoin issuance rate was decreased to 25 bitcoin per block. In July of 2016 it was decreased again to 12.5 bitcoin per block. It will halve again to 6.25 bitcoin at block 630,000, which will be mined sometime in 2020. The rate of new coins decreases like this exponentially over 32 “halvings” until block 6,720,000 (mined approximately in year 2137), when it reaches the minimum currency unit of 1 satoshi. Finally, after 6.93 million blocks, in approximately 2140, almost 2,099,999,997,690,000 satoshis, or almost 21 million bitcoin, will be issued. Thereafter, blocks will contain no new bitcoin, and miners will be rewarded solely through the transaction fees. Supply of bitcoin currency over time based on a geometrically decreasing issuance rate shows the total bitcoin in circulation over time, as the issuance of currency decreases.
Figure 1. Supply of bitcoin currency over time based on a geometrically decreasing issuance rate
Note |
The maximum number of coins mined is the upper limit of possible mining rewards for bitcoin. In practice, a miner may intentionally mine a block taking less than the full reward. Such blocks have already been mined and more may be mined in the future, resulting in a lower total issuance of the currency. |
In the example code in A script for calculating how much total bitcoin will be issued, we calculate the total amount of bitcoin that will be issued.
Example 1. A script for calculating how much total bitcoin will be issued
link:code/max_money.py[]
Running the max_money.py script shows the output produced by running this script.
Example 2. Running the max_money.py script
$ python max_money.py
Total BTC to ever be created: 2099999997690000 Satoshis
The finite and diminishing issuance creates a fixed monetary supply that resists inflation. Unlike a fiat currency, which can be printed in infinite numbers by a central bank, bitcoin can never be inflated by printing.
比特币不像法币,不能无限发行。
Deflationary Money
The most important and debated consequence of fixed and diminishing monetary issuance is that the currency tends to be inherently deflationary. Deflation is the phenomenon of appreciation of value due to a mismatch in supply and demand that drives up the value (and exchange rate) of a currency. The opposite of inflation, price deflation, means that the money has more purchasing power over time.
通货紧缩是由于供需不一致造成的货币价值的腾贵。当人们知道货币价格会上涨,于是会有人囤积货币。
Many economists argue that a deflationary economy is a disaster that should be avoided at all costs. That is because in a period of rapid deflation, people tend to hoard money instead of spending it, hoping that prices will fall. Such a phenomenon unfolded during Japan’s “Lost Decade,” when a complete collapse of demand pushed the currency into a deflationary spiral.
Bitcoin experts argue that deflation is not bad per se. Rather, deflation is associated with a collapse in demand because that is the only example of deflation we have to study. In a fiat currency with the possibility of unlimited printing, it is very difficult to enter a deflationary spiral unless there is a complete collapse in demand and an unwillingness to print money. Deflation in bitcoin is not caused by a collapse in demand, but by a predictably constrained supply.
现有货币在政府的管制下,有这样一个问题:债务过度发放,并且通过增发货币的方式清除,让存钱的人付出代价。
The positive aspect of deflation, of course, is that it is the opposite of inflation. Inflation causes a slow but inevitable debasement of currency, resulting in a form of hidden taxation that punishes savers in order to bail out debtors (including the biggest debtors, governments themselves). Currencies under government control suffer from the moral hazard of easy debt issuance that can later be erased through debasement at the expense of savers.
It remains to be seen whether the deflationary aspect of the currency is a problem when it is not driven by rapid economic retraction, or an advantage because the protection from inflation and debasement far outweighs the risks of deflation.
Decentralized Consensus
In the previous chapter we looked at the blockchain, the global public ledger (list) of all transactions, which everyone in the bitcoin network accepts as the authoritative record of ownership.
所有传统支付系统,依赖于信任模型,信任某个中央机构提供清算,验证每一笔交易。区块链不由中央权威创建,而是由网络中的每个节点独立组成。
But how can everyone in the network agree on a single universal “truth” about who owns what, without having to trust anyone? All traditional payment systems depend on a trust model that has a central authority providing a clearinghouse service, basically verifying and clearing all transactions. Bitcoin has no central authority, yet somehow every full node has a complete copy of a public ledger that it can trust as the authoritative record. The blockchain is not created by a central authority, but is assembled independently by every node in the network. Somehow, every node in the network, acting on information transmitted across insecure network connections, can arrive at the same conclusion and assemble a copy of the same public ledger as everyone else. This chapter examines the process by which the bitcoin network achieves global consensus without central authority.
Satoshi Nakamoto’s main invention is the decentralized mechanism for emergent consensus. Emergent, because consensus is not achieved explicitly—there is no election or fixed moment when consensus occurs. Instead, consensus is an emergent artifact of the asynchronous interaction of thousands of independent nodes, all following simple rules. All the properties of bitcoin, including currency, transactions, payments, and the security model that does not depend on central authority or trust, derive from this invention.
中本聪发明去中心化的机制目的是为了涌现的共识。共识来自成千上万个节点的异步互动,遵循简单的规则。比特币的去中心化共识来自网络中节点相互互动的四个流程:
Bitcoin’s decentralized consensus emerges from the interplay of four processes that occur independently on nodes across the network:
-
Independent verification of each transaction, by every full node, based on a comprehensive list of criteria每个节点独立验证交易
-
Independent aggregation of those transactions into new blocks by mining nodes, coupled with demonstrated computation through a Proof-of-Work algorithm每个节点独立打包交易计算PoW
-
Independent verification of the new blocks by every node and assembly into a chain每个节点独立验证新区块组成区块链
-
Independent selection, by every node, of the chain with the most cumulative computation demonstrated through Proof-of-Work每个节点独立选择算力最长的链
In the next few sections we will examine these processes and how they interact to create the emergent property of network-wide consensus that allows any bitcoin node to assemble its own copy of the authoritative, trusted, public, global ledger.
Independent Verification of Transactions
In [transactions], we saw how wallet software creates transactions by collecting UTXO, providing the appropriate unlocking scripts, and then constructing new outputs assigned to a new owner. The resulting transaction is then sent to the neighboring nodes in the bitcoin network so that it can be propagated across the entire bitcoin network.
比特币网络中,每个节点在验证收到的交易后,再转发出去。
However, before forwarding transactions to its neighbors, every bitcoin node that receives a transaction will first verify the transaction. This ensures that only valid transactions are propagated across the network, while invalid transactions are discarded at the first node that encounters them.
Each node verifies every transaction against a long checklist of criteria:
-
The transaction’s syntax and data structure must be correct.
-
Neither lists of inputs or outputs are empty.
-
The transaction size in bytes is less than MAX_BLOCK_SIZE.
-
Each output value, as well as the total, must be within the allowed range of values (less than 21m coins, more than the dust threshold).
-
None of the inputs have hash=0, N=–1 (coinbase transactions should not be relayed).
-
nLocktime is equal to INT_MAX, or nLocktime and nSequence values are satisfied according to MedianTimePast.
-
The transaction size in bytes is greater than or equal to 100.
-
The number of signature operations (SIGOPS) contained in the transaction is less than the signature operation limit.
-
The unlocking script (scriptSig) can only push numbers on the stack, and the locking script (scriptPubkey) must match IsStandard forms (this rejects “nonstandard” transactions).
-
A matching transaction in the pool, or in a block in the main branch, must exist.
-
For each input, if the referenced output exists in any other transaction in the pool, the transaction must be rejected.
-
For each input, look in the main branch and the transaction pool to find the referenced output transaction. If the output transaction is missing for any input, this will be an orphan transaction. Add to the orphan transactions pool, if a matching transaction is not already in the pool.
-
For each input, if the referenced output transaction is a coinbase output, it must have at least COINBASE_MATURITY (100) confirmations.
-
For each input, the referenced output must exist and cannot already be spent.
-
Using the referenced output transactions to get input values, check that each input value, as well as the sum, are in the allowed range of values (less than 21m coins, more than 0).
-
Reject if the sum of input values is less than sum of output values.
-
Reject if transaction fee would be too low (minRelayTxFee) to get into an empty block.
-
The unlocking scripts for each input must validate against the corresponding output locking scripts.
These conditions can be seen in detail in the functions AcceptToMemoryPool, CheckTransaction, and CheckInputs in Bitcoin Core. Note that the conditions change over time, to address new types of denial-of-service attacks or sometimes to relax the rules so as to include more types of transactions.
独立验证每一笔交易然后再转发,每个节点都有一个有效交易的交易池。
By independently verifying each transaction as it is received and before propagating it, every node builds a pool of valid (but unconfirmed) transactions known as the transaction pool, memory pool, or mempool.
Mining Nodes
Some of the nodes on the bitcoin network are specialized nodes called miners. In [ch01_intro_what_is_bitcoin] we introduced Jing, a computer engineering student in Shanghai, China, who is a bitcoin miner. Jing earns bitcoin by running a “mining rig,” which is a specialized computer-hardware system designed to mine bitcoin. Jing’s specialized mining hardware is connected to a server running a full bitcoin node. Unlike Jing, some miners mine without a full node, as we will see in Mining Pools. Like every other full node, Jing’s node receives and propagates unconfirmed transactions on the bitcoin network. Jing’s node, however, also aggregates these transactions into new blocks.
矿工的矿机与一个全节点的服务器连接,当收到一个新区块的时候,不是一场竞赛的终止,而一下一轮竞赛的开始。
Jing’s node is listening for new blocks, propagated on the bitcoin network, as do all nodes. However, the arrival of a new block has special significance for a mining node. The competition among miners effectively ends with the propagation of a new block that acts as an announcement of a winner. To miners, receiving a valid new block means someone else won the competition and they lost. However, the end of one round of a competition is also the beginning of the next round. The new block is not just a checkered flag, marking the end of the race; it is also the starting pistol in the race for the next block.
Aggregating Transactions into Blocks
After validating transactions, a bitcoin node will add them to the memory pool, or transaction pool, where transactions await until they can be included (mined) into a block. Jing’s node collects, validates, and relays new transactions just like any other node. Unlike other nodes, however, Jing’s node will then aggregate these transactions into a candidate block.
Let’s follow the blocks that were created during the time Alice bought a cup of coffee from Bob’s Cafe (see [cup_of_coffee]). Alice’s transaction was included in block 277,316. For the purpose of demonstrating the concepts in this chapter, let’s assume that block was mined by Jing’s mining system and follows Alice’s transaction as it becomes part of this new block.
Jing’s mining node maintains a local copy of the blockchain. By the time Alice buys the cup of coffee, Jing’s node has assembled a chain up to block 277,314. Jing’s node is listening for transactions, trying to mine a new block and also listening for blocks discovered by other nodes. As Jing’s node is mining, it receives block 277,315 through the bitcoin network. The arrival of this block signifies the end of the competition for block 277,315 and the beginning of the competition to create block 277,316.
矿工节点会把所有的交易打包成一个候选的区块,并且从交易池中移除收到的新区块中的交易。
During the previous 10 minutes, while Jing’s node was searching for a solution to block 277,315, it was also collecting transactions in preparation for the next block. By now it has collected a few hundred transactions in the memory pool. Upon receiving block 277,315 and validating it, Jing’s node will also compare it against all the transactions in the memory pool and remove any that were included in block 277,315. Whatever transactions remain in the memory pool are unconfirmed and are waiting to be recorded in a new block.
Jing’s node immediately constructs a new empty block, a candidate for block 277,316. This block is called a candidate block because it is not yet a valid block, as it does not contain a valid Proof-of-Work. The block becomes valid only if the miner succeeds in finding a solution to the Proof-of-Work algorithm.
When Jing’s node aggregates all the transactions from the memory pool, the new candidate block has 418 transactions with total transaction fees of 0.09094928 bitcoin. You can see this block in the blockchain using the Bitcoin Core client command-line interface, as shown in Using the command line to retrieve block 277,316.
Example 3. Using the command line to retrieve block 277,316
$ bitcoin-cli getblockhash 277316
0000000000000001b6b9a13b095e96db41c4a928b97ef2d944a9b31b2cc7bdc4
$ bitcoin-cli getblock 0000000000000001b6b9a13b095e96db41c4a928b97ef2d9\
44a9b31b2cc7bdc4
{
“hash” : “0000000000000001b6b9a13b095e96db41c4a928b97ef2d944a9b31b2cc7bdc4″,
“confirmations” : 35561,
“size” : 218629,
“height” : 277316,
“version” : 2,
“merkleroot” : “c91c008c26e50763e9f548bb8b2fc323735f73577effbc55502c51eb4cc7cf2e”,
“tx” : [
“d5ada064c6417ca25c4308bd158c34b77e1c0eca2a73cda16c737e7424afba2f”,
“b268b45c59b39d759614757718b9918caf0ba9d97c56f3b91956ff877c503fbe”,
… 417 more transactions …
],
“time” : 1388185914,
“nonce” : 924591752,
“bits” : “1903a30c”,
“difficulty” : 1180923195.25802612,
“chainwork” : “000000000000000000000000000000000000000000000934695e92aaf53afa1a”,
“previousblockhash” : “0000000000000002a7bbd25a417c0374cc55261021e8a9ca74442b01284f0569″
}
The Coinbase Transaction
The first transaction in any block is a special transaction, called a coinbase transaction. This transaction is constructed by Jing’s node and contains his reward for the mining effort.
区块的第一笔交易相对特别,叫币基(coinbase)交易。
Note |
When block 277,316 was mined, the reward was 25 bitcoin per block. Since then, one “halving” period has elapsed. The block reward changed to 12.5 bitcoin in July 2016. It will be halved again in 210,000 blocks, in the year 2020. |
Jing’s node creates the coinbase transaction as a payment to his own wallet: “Pay Jing’s address 25.09094928 bitcoin.” The total amount of reward that Jing collects for mining a block is the sum of the coinbase reward (25 new bitcoin) and the transaction fees (0.09094928) from all the transactions included in the block as shown in Coinbase transaction.
Example 4. Coinbase transaction
$ bitcoin-cli getrawtransaction d5ada064c6417ca25c4308bd158c34b77e1c0eca2a73cda16c737e7424afba2f 1
{
“hex” : “01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0f03443b0403858402062f503253482fffffffff0110c08d9500000000232102aa970c592640d19de03ff6f329d6fd2eecb023263b9ba5d1b81c29b523da8b21ac00000000″,
“txid” : “d5ada064c6417ca25c4308bd158c34b77e1c0eca2a73cda16c737e7424afba2f”,
“version” : 1,
“locktime” : 0,
“vin” : [
{
“coinbase” : “03443b0403858402062f503253482f”,
“sequence” : 4294967295
}
],
“vout” : [
{
“value” : 25.09094928,
“n” : 0,
“scriptPubKey” : {
“asm” : “02aa970c592640d19de03ff6f329d6fd2eecb023263b9ba5d1b81c29b523da8b21OP_CHECKSIG”,
“hex” : “2102aa970c592640d19de03ff6f329d6fd2eecb023263b9ba5d1b81c29b523da8b21ac”,
“reqSigs” : 1,
“type” : “pubkey”,
“addresses” : [
“1MxTkeEP2PmHSMze5tUZ1hAV3YTKu2Gh1N”
]
}
}
]
}
Unlike regular transactions, the coinbase transaction does not consume (spend) UTXO as inputs. Instead, it has only one input, called the coinbase, which creates bitcoin from nothing. The coinbase transaction has one output, payable to the miner’s own bitcoin address. The output of the coinbase transaction sends the value of 25.09094928 bitcoin to the miner’s bitcoin address; in this case it is 1MxTkeEP2PmHSMze5tUZ1hAV3YTKu2Gh1N.
这笔币基(coinbase)交易不消耗UTXO,只有一个输入就是coinbase,凭空创造比特币,而且只有一个输出,付给矿工的地址。
Coinbase Reward and Fees
To construct the coinbase transaction, Jing’s node first calculates the total amount of transaction fees by adding all the inputs and outputs of the 418 transactions that were added to the block. The fees are calculated as:
Total Fees = Sum(Inputs) – Sum(Outputs)
In block 277,316, the total transaction fees are 0.09094928 bitcoin.
要计算交易费,矿工先把打包的区块的交易里的输入输出相加再求差,差值即为交易费。之后再根据当前块高度计算新区块的奖励。
Next, Jing’s node calculates the correct reward for the new block. The reward is calculated based on the block height, starting at 50 bitcoin per block and reduced by half every 210,000 blocks. Because this block is at height 277,316, the correct reward is 25 bitcoin.
The calculation can be seen in function GetBlockSubsidy in the Bitcoin Core client, as shown in Calculating the block reward—Function GetBlockSubsidy, Bitcoin Core Client, main.cpp.
Example 5. Calculating the block reward—Function GetBlockSubsidy, Bitcoin Core Client, main.cpp
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams)
{
int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
// Force block reward to zero when right shift is undefined.
if (halvings >= 64)
return 0;
CAmount nSubsidy = 50 * COIN;
// Subsidy is cut in half every 210,000 blocks which will occur approximately every 4 years.
nSubsidy >>= halvings;
return nSubsidy;
}
The initial subsidy is calculated in satoshis by multiplying 50 with the COIN constant (100,000,000 satoshis). This sets the initial reward (nSubsidy) at 5 billion satoshis.
Next, the function calculates the number of halvings that have occurred by dividing the current block height by the halving interval (SubsidyHalvingInterval). In the case of block 277,316, with a halving interval every 210,000 blocks, the result is 1 halving.
The maximum number of halvings allowed is 64, so the code imposes a zero reward (returns only the fees) if the 64 halvings is exceeded.
Next, the function uses the binary-right-shift operator to divide the reward (nSubsidy) by two for each round of halving. In the case of block 277,316, this would binary-right-shift the reward of 5 billion satoshis once (one halving) and result in 2.5 billion satoshis, or 25 bitcoins. The binary-right-shift operator is used because it is more efficient than multiple repeated divisions. To avoid a potential bug, the shift operation is skipped after 63 halvings, and the subsidy is set to 0.
在代码中采用右移操作,比多次重复相除,更有效。
Finally, the coinbase reward (nSubsidy) is added to the transaction fees (nFees), and the sum is returned.
Tip |
If Jing’s mining node writes the coinbase transaction, what stops Jing from “rewarding” himself 100 or 1000 bitcoin? The answer is that an incorrect reward would result in the block being deemed invalid by everyone else, wasting Jing’s electricity used for Proof-of-Work. Jing only gets to spend the reward if the block is accepted by everyone. |
Structure of the Coinbase Transaction
With these calculations, Jing’s node then constructs the coinbase transaction to pay himself 25.09094928 bitcoin.
As you can see in Coinbase transaction, the coinbase transaction has a special format. Instead of a transaction input specifying a previous UTXO to spend, it has a “coinbase” input. We examined transaction inputs in [tx_in_structure]. Let’s compare a regular transaction input with a coinbase transaction input. The structure of a “normal” transaction input shows the structure of a regular transaction, while The structure of a coinbase transaction input shows the structure of the coinbase transaction’s input.
Table 1. The structure of a “normal” transaction input
Size |
Field |
Description |
32 bytes |
Transaction Hash |
Pointer to the transaction containing the UTXO to be spent |
4 bytes |
Output Index |
The index number of the UTXO to be spent, first one is 0 |
1–9 bytes (VarInt) |
Unlocking-Script Size |
Unlocking-Script length in bytes, to follow |
Variable |
Unlocking-Script |
A script that fulfills the conditions of the UTXO locking script |
4 bytes |
Sequence Number |
Currently disabled Tx-replacement feature, set to 0xFFFFFFFF |
Table 2. The structure of a coinbase transaction input
Size |
Field |
Description |
32 bytes |
Transaction Hash |
All bits are zero: Not a transaction hash reference |
4 bytes |
Output Index |
All bits are ones: 0xFFFFFFFF |
1–9 bytes (VarInt) |
Coinbase Data Size |
Length of the coinbase data, from 2 to 100 bytes |
Variable |
Coinbase Data |
Arbitrary data used for extra nonce and mining tags. In v2 blocks; must begin with block height |
4 bytes |
Sequence Number |
Set to 0xFFFFFFFF |
In a coinbase transaction, the first two fields are set to values that do not represent a UTXO reference. Instead of a “transaction hash,” the first field is filled with 32 bytes all set to zero. The “output index” is filled with 4 bytes all set to 0xFF (255 decimal). The “Unlocking Script” (scriptSig) is replaced by coinbase data, a data field used by the miners, as we will see next.
在区块链第一笔币的交易中,只有一个coinbase的输入,参见如下表2。在这笔交易中,前两个字段不指向UTXO的引用。
Coinbase Data
Coinbase transactions do not have an unlocking script (aka, scriptSig) field. Instead, this field is replaced by coinbase data, which must be between 2 and 100 bytes. Except for the first few bytes, the rest of the coinbase data can be used by miners in any way they want; it is arbitrary data.
Coinbase的交易,不包含解锁脚本,而是包括2字节-200字节的数据,可以填写任意矿工想填的信息。
In the genesis block, for example, Satoshi Nakamoto added the text “The Times 03/Jan/2009 Chancellor on brink of second bailout for banks” in the coinbase data, using it as a proof of the date and to convey a message. Currently, miners use the coinbase data to include extra nonce values and strings identifying the mining pool.
The first few bytes of the coinbase used to be arbitrary, but that is no longer the case. As per BIP-34, version-2 blocks (blocks with the version field set to 2) must contain the block height index as a script “push” operation in the beginning of the coinbase field.
In block 277,316 we see that the coinbase (see Coinbase transaction), which is in the unlocking script or scriptSig field of the transaction input, contains the hexadecimal value 03443b0403858402062f503253482f. Let’s decode this value.
The first byte, 03, instructs the script execution engine to push the next three bytes onto the script stack (see [tx_script_ops_table_pushdata]). The next three bytes, 0x443b04, are the block height encoded in little-endian format (backward, least-significant byte first). Reverse the order of the bytes and the result is 0x043b44, which is 277,316 in decimal.
The next few hexadecimal digits (0385840206) are used to encode an extra nonce (see The Extra Nonce Solution), or random value, used to find a suitable Proof-of-Work solution.
The final part of the coinbase data (2f503253482f) is the ASCII-encoded string /P2SH/, which indicates that the mining node that mined this block supports the P2SH improvement defined in BIP-16. The introduction of the P2SH capability required signaling by miners to endorse either BIP-16 or BIP-17. Those endorsing the BIP-16 implementation were to include /P2SH/ in their coinbase data. Those endorsing the BIP-17 implementation of P2SH were to include the string p2sh/CHV in their coinbase data. The BIP-16 was elected as the winner, and many miners continued including the string /P2SH/ in their coinbase to indicate support for this feature.
有许多矿工会在最后一部分加入/P2SH/用于支持此项特征。
Extract the coinbase data from the genesis block uses the libbitcoin library introduced in [alt_libraries] to extract the coinbase data from the genesis block, displaying Satoshi’s message. Note that the libbitcoin library contains a static copy of the genesis block, so the example code can retrieve the genesis block directly from the library.
Example 6. Extract the coinbase data from the genesis block
link:code/satoshi-words.cpp[]
We compile the code with the GNU C++ compiler and run the resulting executable, as shown in Compiling and running the satoshi-words example code.
Example 7. Compiling and running the satoshi-words example code
$ # Compile the code
$ g++ -o satoshi-words satoshi-words.cpp $(pkg-config –cflags –libs libbitcoin)
$ # Run the executable
$ ./satoshi-words
^D��<GS>^A^DEThe Times 03/Jan/2009 Chancellor on brink of second bailout for banks
Constructing the Block Header
To construct the block header, the mining node needs to fill in six fields, as listed in The structure of the block header.
Table 3. The structure of the block header
Size |
Field |
Description |
4 bytes |
Version |
A version number to track software/protocol upgrades |
32 bytes |
Previous Block Hash |
A reference to the hash of the previous (parent) block in the chain |
32 bytes |
Merkle Root |
A hash of the root of the merkle tree of this block’s transactions |
4 bytes |
Timestamp |
The approximate creation time of this block (seconds from Unix Epoch) |
4 bytes |
Target |
The Proof-of-Work algorithm target for this block |
4 bytes |
Nonce |
A counter used for the Proof-of-Work algorithm |
At the time that block 277,316 was mined, the version number describing the block structure is version 2, which is encoded in little-endian format in 4 bytes as 0x02000000.
Next, the mining node needs to add the “Previous Block Hash” (also known as prevhash). That is the hash of the block header of block 277,315, the previous block received from the network, which Jing’s node has accepted and selected as the parent of the candidate block 277,316. The block header hash for block 277,315 is:
0000000000000002a7bbd25a417c0374cc55261021e8a9ca74442b01284f0569
Tip |
By selecting the specific parent block, indicated by the Previous Block Hash field in the candidate block header, Jing is committing his mining power to extending the chain that ends in that specific block. In essence, this is how Jing “votes” with his mining power for the longest-difficulty valid chain. |
The next step is to summarize all the transactions with a merkle tree, in order to add the merkle root to the block header. The coinbase transaction is listed as the first transaction in the block. Then, 418 more transactions are added after it, for a total of 419 transactions in the block.
在币基(coinbase)交易以后,还有418笔交易,区块中一共打包419项交易。
As we saw in the [merkle_trees], there must be an even number of “leaf” nodes in the tree, so the last transaction is duplicated, creating 420 nodes, each containing the hash of one transaction. The transaction hashes are then combined, in pairs, creating each level of the tree, until all the transactions are summarized into one node at the “root” of the tree. The root of the merkle tree summarizes all the transactions into a single 32-byte value, which you can see listed as “merkle root” in Using the command line to retrieve block 277,316, and here:
c91c008c26e50763e9f548bb8b2fc323735f73577effbc55502c51eb4cc7cf2e
Jing’s mining node will then add a 4-byte timestamp, encoded as a Unix “epoch” timestamp, which is based on the number of seconds elapsed from January 1, 1970, midnight UTC/GMT. The time 1388185914 is equal to Friday, 27 Dec 2013, 23:11:54 UTC/GMT.
Jing’s node then fills in the target, which defines the required Proof-of-Work to make this a valid block. The target is stored in the block as a “target bits” metric, which is a mantissa-exponent encoding of the target. The encoding has a 1-byte exponent, followed by a 3-byte mantissa (coefficient). In block 277,316, for example, the target bits value is 0x1903a30c. The first part 0x19 is a hexadecimal exponent, while the next part, 0x03a30c, is the coefficient. The concept of a target is explained in Retargeting to Adjust Difficulty and the “target bits” representation is explained in Target Representation.
The final field is the nonce, which is initialized to zero.
With all the other fields filled, the block header is now complete and the process of mining can begin. The goal is now to find a value for the nonce that results in a block header hash that is less than the target. The mining node will need to test billions or trillions of nonce values before a nonce is found that satisfies the requirement.
欢迎大家关注我的新微信公众号,“刻意学习区块链”,我会把我所有关于区块链和比特币学习解析的文章,汇总在上面便于检索,这是ScalersTalk成长持续论的一个分叉。 搜索“刻意学习区块链”或者长按扫二维码关注。
ScalersTalk成长持续论
★★★★★
ScalersTalk成长会是由Scalers发起的社群生态体系,专注1000天以上的“N阶持续行动理论体系与能力构建”,以“从英语初阶到同声传译全栈解决方案”为特色,以“持续输入输出训练实践拓宽认知边界”为导向。
微信公众号 l ScalersTalk成长持续论
新 浪 微 博 l @Scalers
网 站 l ScalersTalk.com
开 放 社 群 l 100小时训练QQ群 456036104
畅 销 书 籍 l 《刻意学习》火热销售中
★★★★★
2018年成长会申请说明
《持续行动,为三年后的自己,扎心地做点事——ScalersTalk成长会2018年会员资格开放申请(2017.12)》(请点击)
▼
本文原文: http://www.scalerstalk.com/1351-MasterBTC10