How Does Halving Work: The Code Behind the Hype
How does Bitcoin’s block halving work on an engineering level? We explain with help from Andreas Antonopoulos.
In a recent video, Antonopoulos explained the Bitcoin Core code that controls the halving of the Bitcoin (BTC) block reward in detail.
Bitcoin halving code. Source: Bitcoin Core Software.
Line by line explanation
Every time a Bitcoin block is evaluated or a new block is mined, the function GetBlockSubsidy gets called. Its purpose is to calculate the appropriate size of the block reward. Line 1240 evaluates the halving cycle and divides the current block height by 210,000; the interval between the halving. At the time of this writing, the block height is 629369, if we divide it by 210,000, we get 2.99. Since the variable that stores this value is an integer type, the decimals get discarded. Using this information, the code “knows” that we have had two halvings. This is why the next halving will happen at block 630000.
Satoshi stands corrected
Lines 1242 and 1243 correct a mistake that Satoshi made in the original code. This error originally kept on halving the block reward past 64 halvings; the total number of halvings embedded in the Bitcoin protocol.
Line 1245 multiplies the original block reward of 50 by a constant COIN, which is equal to 100,000,000 Satoshis. Ironically, there are no Bitcoins in the Bitcoin code, only Satoshis.
Line 1247 calculates the appropriate block reward for the current block height. It uses a bitwise operation which is more efficient than regular math operations. The block reward that was calculated in Line 1245 is then adjusted according to the present block reward. Currently, this would look like this:
50 * 100,000.000 / 22= 1,250,000,000 Satoshis or 12.5 Bitcoins.
Finally, Line 1248 returns the appropriate block reward when called by another function or procedure in the Bitcoin code.
When the halving finally arrives in about 4 days, or 631 blocks, we can all take a sigh of relief and appreciate the beauty of Bitcoin’s code.