# Diving into the Bitcoin (BTC) code: Halving

The Halving event, which often signals the start of a bull run, is one of the keys to the success of the Bitcoin model. Halving means the 50% reduction of mining rewards paid to miners, and takes place each 210,000 blocks. Consequently, there is fewer and fewer BTC mined, the supply is reduced, and, provided the demand goes up, the asset goes up in value.

## Let’s do a little recap

This article aims to propose a popularised version of the source code of Bitcoin responsible for halving. Rest assured, because you don’t have to be a programming expert to understand this. If you like this format, we’ll cover other topics like block resolution or how mining pools are assigned transactions to make. Let’s get started!

Before getting a little more technical, let’s do a quick overview. Miners around the world compete to make calculations and be the first to find the results. If so, they can claim the reward: newly generated Bitcoins. As explained in the intro, this reward is halved every 210,000 blocks, hence its name: Halving. Now, let’s go into more detail.

## How does Proof of Work function?

The Proof of Work (PoW) consensus algorithm implies tasking miners with solving complex mathematical problems requiring a lot of computing power. These calculations are the basis of the system on which the Bitcoin blockchain is based. By performing these calculations, miners validate transactions and create blocks that attach to each other to create a blockchain. To roughly explain how this mathematical calculation works: the miner receives some data to which he applies a hash algorithm, which we’ll detail in the next part.

## The Hash

Blockchain technologies stem from a discipline called cryptography, derived from cryptology, aimed at protecting messages, often using cyphers or keys.

To do this, computer scientists around the world have developed something called ‘hash functions’. As part of the Bitcoin blockchain, the algorithm used is called “SHA256” (Secure Hash Algorithm 256 bits). Invented by the National Security Agency (NSA) of the United States, its objective is very simple: to generate a unique ‘hash’ based on an initial message.

A simple example below illustrates this point (the algorithm used, md5, gave rise to SHA256):

For the Bitcoin blockchain, miners try to solve this function:

Miners use the SHA256 algorithm with these parameters: the ‘hash’ of the previous block (previousBlockHash), the characteristics of the transaction of the current block (newTrasnsactionHeadersToBeIncluded) and the ‘magic number’ (it’s with this mechanism that a blockchain is formed: each new block takes the hash from the last one). The ‘magic number’ is also called a nonce (number used once) and is different with each iteration (it can be thought of as a number generated randomly each time the hash function is used).

The miners then apply their hash function over and over again to generate different ‘hashes’ each time. To continue with the example with the fox above, the input data changes each time, so it will be the same for the output of the function.

In short, their goal is to find a ‘magic number’ that gives them the right ‘hash’.

## So when do they stop?

Once they find a ‘hash’ that is smaller or about equal to the difficulty of the network.

Andreas M. Antonopoulos describes this notion of mining difficulty very well in a quote: “A good way to describe mining is like a giant competitive game of sudoku that resets every time someone finds a solution and whose difficulty automatically adjusts so that it takes approximately 10 minutes to find a solution. Imagine a giant sudoku puzzle, several thousand rows and columns in size. If I show you a completed puzzle you can verify it quite quickly. However, […] it takes a lot of work to solve! The difficulty of the sudoku can be adjusted by changing its size (more or fewer rows and columns), but it can still be verified quite easily even if it is very large. The “puzzle” used in bitcoin is based on a cryptographic hash and exhibits similar characteristics: it is asymmetrically hard to solve but easy to verify, and its difficulty can be adjusted.”

## The difficulty

Disclaimer: The following explanations may seem very simple to you, but I assure you that it’s as silly as that!

The difficulty of the network is determined by the result of various hashes. Simply put, the difficulty comes down to the number of zeros in front of the hash. A hash is nothing more than a large number in the hexadecimal system: the digits have the same value as in the decimal system and the letters from A to F are respectively from 10 to 15. A quick comparison of the ‘hashes’ over time clearly shows the increase in the difficulty of the network; the first calculated ‘hash’ contained only 8 zeros, whereas before the 2020 halving, there were no less than 19 zeros in front of the hash.

To recap: the more zeros there are, the lower the value of the ‘hash’, and conversely the greater the difficulty of mining!

Finally, the genius of Satoshi Nakamoto in this algorithm lies in the capacity of the network to adjust its difficulty automatically. You may have heard of it, but the Bitcoin network recently readjusted its difficulty downwards as a result of the Chinese ban. I recommend that you read Luc Jose Adjinacou’s article on the subject for more details.

## The reward

Congratulations if you have made it this far!

We now know that miners race to find the right hash and validate blocks. When a miner (or a group of miners) succeeds, they receive a reward in the form of newly created Bitcoins. These rewards come as a thank you from the network for upholding its security.

New Bitcoins are created through a Coinbase Transaction, written in each block, which pays miners for finding the right ‘hash’ (you guessed it, this is probably where the famous exchange that has recently gone public takes its name).

No more time to waste, let’s get our hands dirty! After all, that’s why you’ve made it this far… right?

## Onwards!

The Bitcoin code is, like almost all blockchain projects, is open source. The project has hundreds of collaborators who keep it up-to-date and work to strengthen the security of the network.

The src/validation.cpp file contains all the secrets of halving. It is in this source file that we can find the “GetBlockSubsidy” function, which is in charge of this mechanism.

The function, which you can see below, is written in the C language and only represents ten lines in a 5065 line file (and believe me, there’s a bunch of files). This is to tell you about the work behind it all!

## So, what does this all tell us?

Let’s start from the beginning, the first line of the function (after the brackets):

The last parameter in this line, consensusParams.nSubsidyHalvingInterval is defined in the src/chainparams.cpp file and is a consensus rule. These rules must be observed by all members of the Bitcoin network. Changing any of these rules would change the blockchain consensus and lead to a hard fork.

In this file, we find the following line, which clearly defines that every 210,000 blocks, a halving occurs:

In this same line, we find the parameter “nHeight”, which refers to the number of already mined blocks. At the time of writing this article, just over 690,000 blocks have been mined, so the calculation of this first line becomes:

int halvings = 690,000/210,000;

The result of dividing 690,000 by 210,000 is about 3.29. However, the three letters “int” before the word “halvings” indicate that the result must be an integer, in this case, “3”. So there have been 3 halvings since the start of the project, and the next one will take place at the 840,000th block.

We then come across this:

One could misunderstand this part of the function as “there will be 64 Bitcoin halvings”. You will see that there will be only 33 halvings. Additionally, this piece of code appeared in 2014 to fix a bug, so let’s not dwell on it.

## Money!

What really interests miners is their reward, which is halved every 210,000 blocks. The following piece of code calculates the reward to be awarded to miners:

Originally, each mined block brought 50 BTC to its miner. In 2021, after dividing this reward three times (three ‘halvings’), we reached 6.25 BTC per block mined. A quick calculation allows us to understand that 10,500,000 BTC were generated before the first ‘halving’ (around £229 billion at the current market price, not too bad!).

In the piece of code above, the variable “nSubsidy” contains the number of Bitcoins that the miner will receive (this value is returned to the rest of the programme in the third line thanks to the keyword ‘return’). To be more precise, it should instead be said that each coin is divided into 100,000,000 units, defined in the src/amount.h file. Each miner therefore receives 50*100,000,000 fractions of Bitcoin.

Let’s replace the variables with everything we have calculated so far:

Here we have replaced the value of “COIN” by 100000000 (see the previous paragraph) and ‘halvings’ by 3 (see calculation a little above ‘int halvings’).

## Let’s analyse!

The variable nSubsidy was originally equal to 50*100,000,000 = 5,000,000,000 fractions of Bitcoin = 50 BTC. We’re good!

To understand the next line, you’ll have to convert everything to binary, which is:

100101010000001011111001000000000

The line nSubsidy >>= 3 means: move the bits three digits to the right, which gives us the following binary value:

100101010000001011111001000000

When we transform this binary value into decimal, we get 625,000,000. This value is always in Bitcoin fractions, which when dividing by 100,000,000 (value of COIN) brings us back to 6.25 BTC, the current reward. We therefore shift the binary value to the right to divide its value. We will shift a digit to the next halving, etc.

I told you above that there would only be 33 halvings. The reason now seems a little more obvious: the initial binary value of nSubsidy is 33 bits! There will come a time when we will no longer be able to shift its value to the right, after the 33rd halving, estimated for the year 2140.

## Conclusion

Still here? I don’t know about you, but I’m quite amazed by the fact that such a small and simple function throws the entire blockchain community into upheaval every 4 years! The Bitcoin code is full of fascinating mechanics like halving and I hope we get a chance to browse the leading crypto’s source code together again.

Plus d’actions
Partagez

Passionné d’innovation et de projets disruptifs, les technologies Blockchain ont rapidement attiré mon attention ! Je prends plaisir à évoluer dans cet écosystème bouillonnant et à en découvrir toutes ses facettes ! Pourquoi ne pas partager cela avec vous ?

DISCLAIMER
The views, thoughts, and opinions expressed in this article belong solely to the author, and should not be taken as investment advice. Do your own research before taking any investment decisions.