
Bitcoin How it works

Search of a habr on Bitcoin gives out two topics . But this is more news. According to the comments, it is noticeable that many people, especially those who are not directly acquainted with Bitcoin, have many questions about the principles of its operation. There are also many guesses, often incorrect. In order to clarify the situation somehow, it was decided to write this article.
Real money?
The first place in the list of the main misconceptions about Bitcoin is occupied by the idea that Bitcoin is another “piece of paper”, albeit electronic ones that only represent “real” money are some kind of debt receipts. Most of the other misconceptions begin from here: since these are pieces of paper, then they are worthless; they can be printed or destroyed as many as you want; they can be faked; they can be copied.
I repeat - all this is nothing more than delusions. The idea of Bitcoin was based on the desire to create not regular “pieces of paper” that represent real money, such as gold, but an analog of gold itself. Take the properties of gold, thanks to which it is perfect money, and make electronic currency based on them.
Mining difficulty
Gold cannot be copied - it can only be mined. But this is a very costly process both in time and in resources. Partly because of this, gold is so highly valued. To make it clearer, consider an example.
Let’s say a man earnestly mined gold all day and eventually gained 1 kg. For him, the value of gold mined is one day of hard work. After a hard day's work, he decided to relax and go to the cinema. By a lucky coincidence, the cashier gave tickets in exchange for gold. Why? Because the cashier likes gold, but doesn't like working with a pickaxe all day. Therefore, he is ready to provide a service - to give a ticket - in exchange for 1 kg of gold. In fact, he exchanges his service for one day of hard work.
Now imagine a different situation. Invented a copier that works with gold. And any person can make 10 kg from one 1 kg of gold per minute. In this situation, the cashier will no longer exchange tickets for gold, since now he himself can easily print it as much as he wants. Gold will cease to have any value and can no longer be used as money.
In Bitcoin, the process of extracting coins also requires resources and time. But in this case, these are not human resources, but computer resources.
Conditionally limited resource
The longer gold is mined, the more difficult (resource-intensive) it is to mine it. This ensures that inflation is in control.
In Bitcoin, a similar behavior is achieved by introducing the function of the speed of the total coins mined over time. This function is inversely proportional, i.e., the velocity decreases over time and tends to zero. If we take the time integral of this function, we get an exponential. Approximately this:

Here you can see that the total number of coins tends to 21 million. Details of the operation of Bitcoin will be discussed later. In the meantime, you need to know two things: coins appear in packs in the system approximately every 10 minutes, the number of coins in one pack is 50, and it halves every 4 years.
Materiality
This property is not so much gold as any non-electronic currency. One bar of gold cannot be exchanged twice for a service or product. That is, at one point in time it can be either the seller or the buyer.
Such behavior is natural for a material currency, but not for an electronic one. To achieve this behavior of virtual money, you need to make a lot of ingenuity. In Bitcoin, this behavior is provided by the transaction mechanism. All transactions are chained together. Each transaction takes coins from one or more existing transactions and indicates to whom they are intended. Therefore, you can always check the entire chain for validity.
The complexity of mining, limited resource, materiality - these properties, plus the use of cryptography for security, allow you to use Bitcoin as money. The core of Bitcoin is based on them. This is not just an arrangement. All of them are embedded in the by design system, and in another way it will not work. It is time to consider this very design.
Block chain
Any electronic payment system must somewhere and somehow store transactions. In Bitcoin, all information is stored in a chain of blocks. Blocks are transmitted in JSON format. Each block contains a header and a list of transactions. The header consists of several properties, among which is the hash of the previous block. Thus, the entire chain of blocks stores all transactions for the entire duration of Bitcoin.
In current versions of the Bitcoin program, a block chain is downloaded entirely by each client, which makes the system completely decentralized. The data is not encrypted in any way and anyone can manually track all transactions. There is even a special site - Bitcoin Block Explorer , where you can easily see all the information about blocks and transactions.
At the time of writing, the number of blocks in the chain was 110 968, and, as I said earlier, this number increases approximately every 10 minutes. This means that one of the participants was able to create a new block.
By the way, all participants are divided into two groups: those who are working on the new block and who are not working. According to statistics, these groups are correlated as 1 to 3. Why create blocks at all, and even every 10 minutes? Blocks record transactions. Each block contains all the transactions that took place during its creation, i.e. in 10 minutes.
It works as follows. One of the clients creates a new transaction and sends it to other customers who are busy generating the block. They add this transaction to their block and continue generating. Sooner or later, someone will be able to generate a block. Such a block is sealed (transactions are no longer added to it) and sent out over the network. Next, clients check the block and transactions within it for validity. If there are no problems, then transactions are considered approved. At this point, a fresh block has already reached each customer and added to the chain. After this, the process repeats - customers begin to generate the next block and collect new transactions into it.
Block
Consider the contents of the block and the process of its generation in more detail. An example of a block can be found on the same Bitcoin Block Explorer . The block consists of a header and a list of transactions. The header consists of the following properties:
hash - SHA-256 hash of the block header. Such a hash is quite random, and its calculation time is predictable. I want to note that only the header is hashed, without transactions. So the number of transactions will not greatly affect the hash calculation time.
ver - Block diagram version. At the moment, all blocks have one version - 1.
prev_block- Hash of the previous block in the chain. Due to this property, a chain cannot be faked by replacing one of the blocks in it, since the hash of a block always depends on the hash of the previous block in the chain. Changing one of the blocks will have to recreate all the subsequent ones.
mrkl_root - Merkle root - list of transaction hashes. The block hash must necessarily depend on transactions so that they cannot be faked. But calculating it directly will be long if the number of transactions is large. Therefore, the transactions themselves are hashed first, and then their hashes are used to calculate the hash of the entire block.
It may seem absurd - why double compute a hash of the same thing. But the fact is that the transaction hash is updated only when a new transaction is added to the block, and the hash of the block header is recounted several thousand times per second. Moreover, the closer the size of the header in the constant, the more accurately you can predict the time to calculate its hash.
time - uint32_t representing the block creation time. The maximum allowable year is 2106.
bits - One of the most important properties. It is an abbreviated form of the target hash value. A block is considered generated (valid) when its hash is less than this target value. The target value determines the complexity of creating the block. The smaller it is, the less likely it is to find a suitable hash in one iteration. This property is updated every two weeks.
It happens as follows. The number of generated blocks over the past two weeks is calculated and compared with the standard (1 block every 10 minutes). If there are too many blocks, then the complexity increases. If there are too few blocks, it decreases. Thus, the system adapts to increase the number of users and, as a result, the total power of their computers.
nonce - A number that, starting from zero, is incremented after each iteration of the calculation of the hash. Actually, this is how the search happens until the hash is less than the target value. In order for each new hash to differ from the previous one, at least one of the properties of the block header must be different.
For example, the version never changes. The hash of the previous block is updated when someone gets ahead of us and generates a new block. Merkle root is updated when a transaction is added. Time - every few seconds. Bits (target value, difficulty) - every two weeks. All this is too long. In order not to wait until one of the properties is updated and nonce exists.
Consider a hypothetical situation. All nonce values have been verified and none of them are suitable. During this time, no other property has changed. Nonce overflow occurs and it starts again from scratch. It turns out that further hashes will be repeated. To avoid such situations, after overflow of nonce, the special property of one of the transactions is changed. After that, Merkle root is updated and the block header hashes will not be repeated.
n_tx - The number of transactions in the list.
size - The size of the block in bytes.
Transactions
Transactions are contained in blocks in the form of a list. They, like blocks, line up in chains. Each transaction should indicate where it takes the money from (from which existing transaction), and where it sends.
To specify the addressee, its public key is used. In order for the addressee to be able to use the money received, he must create a new transaction that will take money from the previous one and redirect it to another address. In order to prove that a person uses his money, not someone else’s, to transfer, he must leave his digital signature in his transaction. Then at any moment in time you can make sure that all transactions in the system are valid.
In practice, all this is implemented using the following properties:
hash- Hash of the entire transaction. It turns out that transactions are hashed twice. First time during transaction hash calculation. The second time during the calculation of the block hash. In addition, each block refers to the hash of the previous block, and each transaction refers to the hash of the previous transaction (or transactions). If you change the transaction and by some miracle its hash does not break, then all other hashes will break and the changed block chain will be rejected by all clients.
ver - Transaction scheme version. So far, it has never changed, so everywhere it is 1.
vin_sz - The number of previous transactions from which money is transferred to new addresses. One or more.
vout_sz - The number of addresses to which money is transferred. One or more.
lock_time- It is not used yet and is equal to 0 everywhere. The idea is to create pending transactions so that they are not added to the current generated block, but, for example, to the next one. It is understood that this property indicates the number of blocks that a transaction must skip before adding. This makes it possible to change the transaction and re-sign it for some time.
size - Transaction size in bytes. The transaction size is in JSON format.
in - Contains a list of transaction inputs (sources). The outputs of previous transactions ( prev_out ) are used as inputs . Each output has the following properties:
hash - Hash of the previous transaction.
n- Since a transaction can have several exits, you need to indicate which of them takes money. For this, this property exists. It contains the exit number of the previous transaction, starting with 0.
scriptSig - In this property, the sender must prove that he is transferring his own money, and not someone else's. To do this, he indicates the public key of the recipient of the previous transaction, i.e. his own key, since it must be the recipient. In addition, he adds an ECDSA signature to the same transaction, which is made his private key. This proves that he manages his money, not strangers.
After the list of transaction inputs ( in ), the list of outputs ( out ) is indicated), i.e., recipients. Each output has the following properties:
value - Contains the amount of money that will be transferred to a new address. They are taken from previous transactions. Therefore, this number should not exceed their amount. For example, we want to take 10 coins from one transaction and 20 from another and send 25 to a new address. So that the remaining 5 coins do not disappear, we send them to ourselves, as a change. Thus, in our transaction there will be two recipients, one of which is ourselves. Value is always indicated in nanocoins to avoid fractional numbers.
scriptPubKey - This property, together with scriptSig, compose a script in a modified Forth-like language . Scriptpubkeycontains language operators and a hash of the public key of the transaction recipient. The script checks the transaction for validity. Using this scenario provides rich opportunities for describing the conditions for receiving money by the addressee. For example, you can force the recipient to specify a password instead of ECDSA.
The total amount of money at the input of the transaction is always equal to the total amount at the output. Otherwise, money either arose from the air or disappeared from circulation. But at the very beginning there was a graph that shows that the number of money is growing exponentially. So where does the new money come from in the system?
For my taste, the issue of money is implemented simply and elegantly. In each block, the first transaction in the list is a special transaction. It always has one input, which instead of the scriptSig propertythere is a coinbase property . This property can contain anything.
The output of a transaction is also always the same. It redirects 50 coins to the one who generated the block in which this transaction is located. This is a kind of reward for the time and resources spent on generating the block. By creating a new block in the chain, the client contributes to the work of Bitcoin.
Every four years, this award is halved, so the total number of coins in circulation is stabilized. After that, even if an attacker creates a block using a modified version of the program and assigns 50 coins to himself, this block will not be added to the chain, as it will be rejected by other honest clients, which should be the majority.
The stability of the system is based on the number of users who have an official client running. While there are most of them, Bitcoin is not in danger.
Conclusion
Proof of work is a result of work that is difficult to achieve, but easy to verify. The operation of the Bitcoin network is based on this principle. You can check the hash (the result of work) in a split second. And in order to pick it up, it takes a lot of work.
Here we can recall the analogy with gold, the extraction of which takes a lot of time and resources. But to understand that before you is gold, you can almost immediately. In this sense, Bitcoin also has its value. But do not understand this as the price in dollars or in electricity bills that the computer used during the selection of the hash.
The price in dollars is a little different. It is not inherent in Bitcoin and is determined solely by the market. After all, gold in itself also does not guarantee you a certain price in dollars. It is guaranteed only by a person who wants to exchange gold for dollars.
The initial value of gold was determined solely by those who mined it. For the mined gold, he requested so much that it was possible to compensate for the efforts to mine it. And after that, the market begins to influence the price of gold.
Once Bitcoin entered the market, its value is determined solely by the level of confidence in the system. The more people trust, the more they will buy Bitcoin, the more dollars they will invest in it and, as a result, the more expensive Bitcoin will be.
Before people can trust Bitcoin, they need to find out if this system has a sufficient degree of security, and whether it can be used as money, that is, whether it has the properties of the money that I listed at the beginning. You can only learn this for sure in the principles of Bitcoin.
I hope that after this article the level of confidence in Bitcoin will grow at least slightly.