Contact us in messengers or by phone.

whatsapp telegram viber phone email
+79214188555

Blockchain from the inside: how Bitcoin works.

DronVR

Private access level
Joined
Jun 1, 2014
Messages
284
Reaction score
262
Points
63
Blockchain from the inside: how Bitcoin works.

001.jpg

Today, when half of my friends play on crypto-exchanges, and the second is preparing for an ICO, even among them only a few understand how everything works from the inside. This post should fix it.

In this sheet of text, I want to tell you why they came up with the blockchain, how cryptocurrencies are arranged and why this is the most beautiful system in recent years in terms of logic.

I am far from hype around the course of bitcoin and exchanges, for me, blockchain is a technology. New, strange, incomprehensible, but it seems to change the world, unlike these your stories. Apparently, she is with us for a long time.
I wrote this post as if I were talking about blockchain to my parents. I can even throw it to my humanities friends and be sure that they will understand.

And Oleg will help me with this. If you do not like Oleg, I will drive him out.

Basics: why do we need blockchain?
Blockchain was described in an article by Satoshi Nakamoto “ Bitcoin: A Peer-to-Peer Electronic Cash System ". There, on just eight pages, the author described the basics of the Bitcoin cryptocurrency, which was based on the Blockchain algorithm.

The blockchain appeared along with bitcoin, but can be used independently of it and even modified. Anyone can make their own blockchain on their laptop.
List that cannot be changed
Blockchain - a chain of blocks or in other words linked list . In such a list, each subsequent record refers to one previous one and so on through the chain to the very first. Like train cars, each drags the next. Regarding the lists there is a good article by Nikita Likhachev on TJ where the same is explained for completely newbies. The analogies are partly taken from there.

Let's take an example.

Oleg’s friends constantly borrow money from him. Oleg is kind, but extremely forgetful. A week later, he no longer remembers who did not repay his debt, but he is embarrassed to ask everyone about it. Therefore, once he decided to put an end to this by making a list of friends on his board at home with whom he borrowed money.

002.jpg

Now Oleg can always go to the board and make sure that Max has returned everything, but Vanya does not give 700 rubles already. Once Oleg invites Vanya to have a drink at his home. While Oleg goes to the toilet, Vanya erases the entry “Vanya took 200 rubles” and writes “Vanya gave 500 rubles” instead.

Trusting his list, Oleg forgets about the debt and loses 700 rubles. He decides to fight it somehow.

Last year, Oleg went to programming courses, where he was told about hashing . He remembers that any string can be turned into an unambiguous set of characters - a hash, and changing any character in a string will completely change it.

003.jpg

Adding a dot at the end changed the final hash beyond recognition - this can be used.

Oleg takes a well-known hash SHA-256 and hashes every record to them, appending the result at the end. Now Oleg can make sure that no one has changed his notes by hashing them again and comparing them with the green one.
004.jpg

But EVIL RUSSIAN IVAN is also capable of SHA-256 and can easily change the record along with its hash. Especially if the hash is written right next to the board.

Therefore, for greater security, Oleg decides not to hash the record itself, but add it along with the hash from the previous record. Now all of the following entries are dependent on previous ones. If you change at least one line, you will have to recalculate the hashes of all the others below the list.
005.jpg


So Oleg has a personal linked list.

But one day, Ivan sneaks into the night, changes the record he needs and updates the hashes for the entire list to the end. It takes him several hours, but Oleg is still sound asleep and cannot hear. In the morning, Oleg discovers an absolutely correct list - all hashes match. But Ivan deceived him anyway, although he spent a sleepless night on it. How else can you protect yourself from Night Ivan?

Oleg decides to complicate his life somehow. Now, to add a new record to the list, Oleg will solve a complex problem connected with it, for example, a mathematical equation. He will add the answer to the final hash.

Oleg is good at mathematics, but even it takes him ten minutes to add a record. Despite this, the time spent is worth it, because if Ivan wants to change something again, he will have to re-solve the equations for each line, and there may be dozens of them. It will take a lot of time, because the equations are each time unique and associated with a particular record.

But checking the list is just as simple: first you need to compare the hashes as before, and then check the solutions of the equations with a simple substitution. If everything converges - the list is not changed.

In reality, things are not so good with equations: computers solve them too well, and where to store so many unique equations. Therefore, the authors of the blockchain came up with a more beautiful task: you need to find such a number (nonce) that the final hash of the entire record starts at 10 zeros. Such a nonce is difficult to find, but the result can always be checked simply with your eyes.

006.jpg


Now Oleg checks all the hashes and additionally makes sure that each starts on the agreed number of zeros. The cunning Ivan, even armed with a powerful laptop, will not have time to count all the hashes overnight so that they satisfy the condition - there will not be enough time.

Such a list is essentially a home blockchain on the knee. Its security is guaranteed by mathematicians who have proven that these hashes cannot be calculated any faster than brute force. Such sorting of hashes for each record is mining, about which today there will be a lot of detail.

Centralization of trust
Our friends liked the idea of maintaining a fake “who occupied whom” list. They also don’t want to remember who paid for whom in the bar and how much more they owed - everything is written on the wall. You discussed the idea and decided that now you need a single list for everyone.
007.jpg


But who to entrust to conduct such an important accounting? Indeed, when it comes to money, trust comes to the fore. We will not trust the unknown to keep our money. For this, our ancestors came up with banks, which over time began to be trusted, because they are backed by a license, laws and insurance of the Central Bank.

In the circle of friends, everyone trusts each other and you can simply choose the most responsible person for this role. But what if the question is about strangers? The whole city, country, or the whole world, as is the case with bitcoin? There, in general, no one can trust anyone.

Decentralization: nobody trusts anyone
So they came up with an alternative approach: to keep a copy of the list for everyone. Thus, the attacker will not only have to rewrite one list, but also sneak into each house and rewrite the lists there. And then it turns out that someone had already kept several lists at home, which no one knew. This is decentralization.

The disadvantage of this approach is that to make new entries you will have to ring up all the other participants and inform each of them of the latest changes. But if these participants are soulless cars, this ceases to be at least some kind of problem.
008.jpg


In such a system, there is no single point of trust, and therefore the possibility of bribery and cheating. All participants in the system act according to a single rule: no one trusts anyone. Everyone believes only the information that he has at his disposal. This is the main law of any decentralized network.



Transactions
When buying a doshirak in a store, you enter a pin code from your card, allowing the store to ask the bank if you have 35 rubles in your account. In other words, you sign your transaction with a PIN code of 35 rubles, which the bank confirms or rejects.

Our records like “I took 500 rubles to Van” are also transactions. But we do not have a bank authorizing the author of the transaction. How can we verify that Ivan quietly did not add the entry “Max owes Oleg 100,500 rubles”?

The blockchain uses the mechanism of public and private keys for this, IT specialists have long used them for authorization in the same SSH.

Briefly about how this complicated but beautiful math works: you generate a pair of long primes on your computer - a public and private key. The private key is considered super-secret, because it can decrypt what is encrypted in public. But the opposite also works. If you tell the public key to all your friends, they will be able to encrypt any message to them so that only you can read it, since you own a private one. But besides this, the public key has a useful effect - with it you can verify that the data has been encrypted with your private key, without decrypting the data itself. All of these properties are well described in the Book of Ciphers at the link above.
009.jpg

Your public key is the number of the crypto wallet. That is, you can get a wallet of any cryptocurrency without going online.



For ordinary users who do not want to figure out how to issue and store private keys, online wallet services will help. To copy long public keys, they make convenient QR codes there. I personally use Blockchain wallet , because it has a convenient mobile application and it supports two main cryptocurrencies - BTC and ETH.

Lack of the concept of "balance"
Like our board, blockchain essentially consists only of transaction history. It does not keep the balance of each wallet, otherwise we would have to invent additional methods of protection.

Owning a wallet confirms only the private key. But how will other network members make sure that I have enough money to buy?

Since we don’t have balance, you must prove it. Therefore, the blockchain transaction includes not only your signature and how much you want to spend, but also links to previous transactions in which you received the right amount of money. That is, if you want to spend 400 rubles, you run through your entire history of income and expenses, and attach to your transaction those incomes where you were given 100 + 250 + 50 rubles, thereby proving that you have these 400 rubles.
010.jpg

Each member of the network will once again verify that you did not attach income twice. What 300 rubles that Max gave last week, you really have not spent.

Such income attached to the transaction in the blockchain is called input (input), and all recipients of money are called output (output). The sum of all the inputs is rarely exactly the amount you want to transfer at a time - because one of the outputs will most often be you yourself. In other words, the transaction on the blockchain looks like "I was given 3 and 2 BTC, I want to transfer 4 BTC from them and return the remaining 1 BTC back."
011.jpg

The beauty of the blockchain is that the inputs do not have to be from one wallet. After all, only the key is checked. If you know the private key of all inputs, then you can easily attach them to your transaction and pay with this money. As if you were paying at the supermarket from several cards at once, from which you know the pin code.

However, if you lose your private key, your drive dies or your laptop is stolen, your bitcoins will be lost forever. No one will be able to use them as inputs for new transactions. This amount will not be available to the whole world forever - as if you are burning a bundle of banknotes. There is no single bank where you can write a statement with a copy of your passport, and it will still print. To do this, we need an additional release of new bitcoins “from the air”.

Double spending problem
I said above that transactions are added to a special “pool of unconfirmed transactions”. Why do we need some kind of intermediate entity, if we already have essentially ready-made signed transactions? Why not write them immediately to the blockchain?

Because the signals from point A to point B always come with a delay. Two transactions can go in completely different ways. And the transaction that was initiated first may reach the recipient later, because it went a longer way. So it turns out double spending when the same money was sent at once to two recipients, which they would not even guess about. This is not a hand-to-hand pass to you.
012.jpg


For a decentralized network in which no one can be trusted, this problem is especially acute. So how do you make sure that one transaction was exactly before the other? Ask the sender to sew in the time of sending, right? But remember, you cannot trust anyone, not even the sender. The time on all computers will necessarily be different and there is no way to synchronize them guaranteed. A copy of the blockchain is stored on each computer on the network and each participant trusts only it.

How to make sure that one transaction was earlier than another?

The answer is simple: it is impossible. There is no way to confirm the transaction time in a decentralized network. And here is the third important idea of the blockchain that Satoshi came up with and, strangely enough, spelled out directly in his name - the blocks is the solution to this problem. +
013.jpg

Blocks are the basis of the blockchain
Each working computer on the network selects from the shared pool any transactions that it likes. Usually just at the highest commission that he can earn on it. So he collects transactions for himself, until their total size reaches the agreed limit. In Bitcoin, this limit on the block size is 1 MB (after SegWit2x there will be 2 MB), and in Bitcoin Cash - 8 MB.

But in networks such as Ethereum, everything is a little more complicated, where the number of transactions per block depends on the computational complexity of the smart contracts included in them. But the essence does not change - there is a certain limit.
The whole blockchain is essentially a list of such blocks, where each refers to the previous one. On it, you can track any transaction in history, unwinding the blockchain even to the very first record. It is this list that now weighs hundreds of gigabytes and must be fully downloaded to all computers that want to participate in the network (but just to create transactions and transfer money is not necessary). It also downloads from all nearby computers on the network, as if you are downloading a series from torrents, only new new episodes are released in it every 10 minutes.
014.jpg



Having collected transactions from the pool, the computer begins to make from them the same forged list as we did at the beginning of the post on the blackboard at home. He only makes it in the form of a tree - hashes the entries in pairs, then the result again in pairs and so on until only one hash remains - the root of the tree, which is added to the block. Why I didn’t find the answer with the tree, but I guess it’s so simple faster. More details are on the wiki: Merkle Tree .

015.jpg

Since the current blockchain has already been downloaded, our computer knows for sure which is the last block in it now. He can only add a link to it in the block header, hash it all and tell all other computers on the network “look, I made a new block, let's add it to our blockchain”.

The rest should check that the block is built according to all the rules and that we have not added unnecessary transactions there, and then add to our chains. Now all the transactions in it are confirmed, the blockchain is increased by one block and everything is going well, right?

But no. Thousands of computers are simultaneously working on the network, and as soon as they assemble a new unit, they almost immediately rush to inform everyone that their unit was created first. And from the previous section, we already know that in a decentralized network it is impossible to prove who really was the first.
016.jpg

Therefore, to include a block in a chain, computers must solve some kind of difficult task that will take them a certain time.

As in school, when everyone decided a difficult control, it seldom happened that even excellent students gave answers at the same time.

But if it’s a difficult task for a person to plan a vacation so that he gets to the May holidays and tickets to the sea are inexpensive, then for a computer it’s necessary to add a number (nonce) at the end of the block so that as a result the SHA-256 hash for the whole block starts , say, 10 zeros. This is the task that needs to be solved in order to add a block to the Bitcoin network. For other networks, tasks may vary.

So we come to the concept of mining, on which everyone is so obsessed in recent years. 8 comments

017.jpg

Minin
Bitcoin mining is not some sacred sacrament there. Mining is not connected with the search for new bitcoins somewhere in the depths of the Internet. Mining is when thousands of computers around the world are buzzing through the basements, sorting through millions of numbers per second, trying to pick up a hash starting at 10 zeros. They don’t even have to be online for this.

018.jpg

Video cards with their hundreds of parallel cores solve this problem faster than any CPU.

Why exactly 10 zeros? And just like that, this makes no sense. So came up with Satoshi. Because this is one of those tasks for which there is always a solution, but it certainly cannot be found faster than a long monotonous enumeration of options.

The complexity of mining directly depends on the size of the network, that is, its total power. If you create your blockchain and run it yourself at home on two laptops, then the task should be simpler. For example, so that a hash starts only from one zero, or so that the sum of even digits is equal to the sum of odd digits.

To find a hash starting at 10 zeros, a single computer will take several decades. But if you combine thousands of computers into a single network and search in parallel, then according to probability theory this problem is solved on average in 10 minutes. This is the time of the appearance of a new block in the Bitcoin blockchain. Every 8-12 minutes, someone on earth finds such a hash and gets the privilege to announce their find to everyone, thereby avoiding the problem of who was the first.
019.jpg

For finding the answer, the computer (as of 2017) receives 12.5 BTC - this is the amount of the reward that is generated by the Bitcoin system “from the air” and decreases every four years. Technically, this means that each miner always adds another transaction to its block - “create 12.5 BTC and send them to my wallet”. When you hear "the number of bitcoins in the world is limited to 21 million, now they have already mined 16 million" - these are the network-generated rewards.

Go see to a real live block of Bitcoin on one of the special sites. There are transactions with inputs and outputs, and as many as 18 zeros at the beginning and all the hashes described above.

Any blockchain exists only as long as its miners exist.
It is the miners who add the emerging transactions to the blockchain. So if someone tells you that he will “make a blockchain for ***”, the first question that he must answer is who and why will mine on it. Most often, the correct answer is “there will be everything, because for mining we give our coins, which will grow and it’s profitable for miners”. But this is not applicable to all projects. For example, some Ministry of Health tomorrow creates its own closed blockchain for doctors (and they want), who will mine it? Therapists on the weekend?

But what will be the benefit to the miners afterwards when the rewards disappear or become meager?

According to the Creator's idea, by that time people will have to believe in the reality of bitcoin and mining will begin to pay off with the amount of commissions included in each transaction. Everything goes to this: back in 2012, all commissions were zero, miners mined only for block rewards. Today, a transaction with a zero commission can sag in the pool for several hours, because there is competition, and people are willing to pay for speed.

That is the essence of mining in solving meaningless tasks. Is it not possible to put all these powers into something more useful - a search for a cure for cancer, for example?

The essence of mining is to solve any computing problem. This task should be simple enough so that network participants have a stable probability of finding an answer - otherwise the transactions will be confirmed forever. Imagine that at the checkout counter in the store you need to wait half an hour each time until the bank confirms your transaction. No one will use such a bank.

But the task must be at the same time difficult so that all users of the network do not immediately find the answer. Because in this case, they announce a lot of blocks with the same transactions on the network and there will be a likelihood of "double waste", which I spoke about. Or even worse - splitting a single blockchain into several branches, in which no one can figure out which transaction is confirmed and which is not.

If the reward at 12.5 BTC is awarded only once every 10 minutes and only to one who finds the block, do I have to waste video cards for several years in the hope that one day I will get $ 40,000 (at the current rate)?

For bitcoin, that's right. But it was not always so. Previously, the network was smaller, complexity was lower, which means that the probability was more likely to single-handedly find a hash for a new block. But then bitcoin was not so expensive either.

Now no one is mining bitcoins alone. Now the participants are united in special groups - mining pools, where everyone together is trying to find the right hash. If at least one of the group finds, then all the remuneration is divided between the participants depending on their contribution to the overall work. It turns out that you are mining and you get a penny weekly of the total share.

But single mining is quite possible in other networks. More recently, it was easy to mine Ethereum, where the blocks are located every 10 seconds. The reward for the block there is much lower, but the probability of earning a pretty penny is higher.

So we will burn thousands of video cards in vain and there is no way out?

Yes, but there are ideas. That mining that I described is classic and is called Proof-of-Work (proof of work). That is, each machine proves that it worked for the benefit of the network in that it solves meaningless tasks with a given probability.

But some guys are starting to make blockchains with other types of mining. Now the second most popular concept is Proof-of-Stake ( proof of ownership ) In this type of mining, the more “coins” on the account of a network participant, the more likely it is to insert your block into the blockchain. Like the loudest guy in the village.

You can come up with other types of mining. As already suggested, all computers on the network can look for a cure for cancer, only you need to figure out how to fix their contribution to the system in this case. After all, I can say that I also participate, but turn off my video card and do not count anything. How to express the quantitative contribution of each participant to the search for a cure for cancer? Come up with - dare to cut your CancerCoin, hype in the media is provided to you.

Blockchain
Imagine a situation in which, despite all our probability theory, two miners still managed to simultaneously find the right answer. They begin to send two absolutely correct blocks over the network. These blocks are guaranteed to be different, because even if they miraculously chose the same transactions from the pool, made up absolutely identical trees and guessed the same random number (nonce), their hashes will still be different, since everyone will write their wallet number in the block for reward.

Now we have two valid blocks and again the problem arises of who to consider first. How will the network behave in this case?

The blockchain algorithm says that network participants simply accept the first correct answer that reaches them. Then they live on the basis of their own picture of the world. Both miners will receive their remuneration, and all the rest begin to mine, relying on the last block they personally received, discarding all the other re-faithful ones. Two versions of the correct blockchain appear on the network. Such is the paradox.
020.jpg

This is a regular situation in which probability theory helps again. The network operates in such a forked state until one of the miners finds the next block to one of these chains. As soon as such a block is found and inserted into the chain, it becomes longer and one of the conventions of the blockchain network is turned on: under any conditions, the longest chain of blocks is accepted as the only true one for the entire network .

The short chain, despite all its correctness, is rejected by all network participants. Transactions from it are returned to the pool (if they were not confirmed in another), and their processing starts again. The miner lost his reward because his block no longer exists.

With the growth of the network, such coincidences from "very unlikely" pass into the category of "well, sometimes it happens." Old-timers say that there were times when a chain of four blocks was discarded at once.
021.jpg

Because of this, three rules of security for the tail of the blockchain (end of chain insecurity) were invented:

1. Rewards for mining, you can use it only after another 20 confirmed blocks after receiving. For bitcoin, this is about three hours.

2. If bitcoins were sent to you, you can use them as inputs in new transactions only after 1-5 blocks.

3. Rules 1 and 2 are just spelled out in the settings of each client. No one monitors their compliance. But the law on the longest chain will still destroy all your transactions if you try to trick the system without observing them.

Trying to trick the blockchain
Now that you know everything about mining, the blockchain device and the rule of the longest chain, you might wonder: is it possible to somehow overtake the blockchain by making the longest chain yourself, thereby confirming your fake transactions.

Suppose you have the most powerful computer on Earth. Google and Amazon data centers combined at your disposal and you are trying to figure out a chain that will become the longest in the blockchain network.
022.jpg

You cannot take and immediately calculate several blocks of the chain, because each next block depends on the previous one. Then you decide to read each block on your huge data centers as soon as possible in parallel with how all the other participants continue to increase the main blockchain. Is it possible to overtake them? Probably yes.

If your computing power will be more than 50% of the power of all network participants, then with a 50% probability you can build a longer chain faster than all the others combined. This is a theoretically possible way to trick the blockchain by calculating a longer transaction chain. Then all the transactions of this network will be considered incorrect, and you will collect all the rewards and begin a new milestone in the history of cryptocurrency, which is called "blockchain sharing." Once, because of a bug in the code, this was the case with Ethereum.

But in reality, no data center can be compared in power to all computers in the world. One and a half billion Chinese with icebergs, another one and a half billion hungry Indians with mining farms and cheap electricity - this is a huge computing power. Nobody in the world can compete with them alone, even Google.

It's about how to go out and try to convince every person in the world that the dollar is now worth 1 ruble and catch it before the media exposes you. And if you manage to convince everyone, you can collapse the global economy. In theory, is this possible? But in practice, for some reason, no one succeeded.

Blockchain is also based on this probability. The more participating miners, the greater the security and trust of the network. Therefore, when another major mining farm is being set up in China, the exchange rate collapses. Everyone is afraid that somewhere in the world there was an evil genius who had already collected a pool of miners at ~ 49% of the power.

In fact, this happened several times in the 2014s, when one of the mining pools temporarily became more powerful than the rest of the network. But then no manipulations were noticed.
023.jpg

Conclusion

Blockchain is not just for cryptocurrencies
Blockchain is not a strictly defined set of algorithms. This is a structure for building a fake network between participants, where no one can trust anyone. During the reading, you probably had the thought that “you can redo it this way and it will be even more useful”. This means that you understand the blockchain, congratulations.

Some guys in the world also understood it and wanted to improve or adapt it for some specific tasks. Not the same cryptocurrencies, although they also divorced a lot. Here is a short list of some ideas and projects that have gained some popularity due to a rethinking of the idea of blockchain.

Source
 
Original message
Блокчейн изнутри: как устроен биткоин.

001.jpg

Сегодня, когда половина моих друзей играет на криптобиржах, а вторая готовится к ICO, даже среди них лишь единицы понимают как всё устроено изнутри. Этот пост должен всё исправить.

В этой простыне текста хочу рассказать зачем придумали блокчейн, как устроены криптовалюты и почему это самая красивая система за последние годы с точки зрения логики.

Я далек от хайпа вокруг курса биткоина и бирж, для меня блокчейн — это технология. Новая, странная, непонятная, но похоже меняющая мир, в отличии от этих ваших сторис. Судя по всему, она с нами надолго.
Этот пост я писал так, как будто рассказываю про блокчейн своим родителям. Я даже могу скинуть его друзьям-гуманитариям и буду уверен, что они поймут.

А поможет мне в этом Олег. Если Олег вам не понравится, я его выгоню.

Основы: зачем нам блокчейн?
Блокчейн был описан в статье Сатоши Накамото «Bitcoin: A Peer-to-Peer Electronic Cash System». Там всего на восьми страницах автор описал основы криптовалюты Биткоин, в основе которой лежал как раз алгоритм Блокчейна.

Блокчейн появился вместе с биткоином, но может использоваться независимо от него и даже модифицироваться. Любой может сделать свой блокчейн хоть у себя на ноутбуке.
Список, который нельзя изменить
Блокчейн — цепочка блоков или другими словами связный список. В таком списке каждая следующая запись ссылается на одну предыдущую и так по цепочке до самой первой. Как вагоны поезда, каждый тащит за собой следующий. По поводу списков есть годная статья Никиты Лихачева на TJ, где то же самое объяснено для совсем новичков. Аналогии отчасти взяты оттуда.

Разберем на примере.

Друзья Олега постоянно занимают у него деньги. Олег добр, но крайне забывчив. Через неделю он уже не помнит кто не вернул ему долг, но стесняется всех об этом расспрашивать. Потому однажды он решил положить этому конец, заведя у себя дома на доске список друзей, которым он занимал денег.

002.jpg

Теперь Олег всегда может подойти к доске и убедиться, что Макс всё вернул, а вот Ваня не отдает уже 700 рублей. Однажды Олег приглашает Ваню выпить к себе домой. Пока Олег отходит в туалет, Ваня стирает запись «Занял Ване 200 рублей» и вписывает вместо неё «Ваня отдал 500 рублей».

Доверявший своему списку Олег забывает про долг и теряет 700 рублей. Он решает как-то с этим бороться.

В прошлом году Олег ходил на курсы по программированию, где ему рассказали про хеширование. Он помнит, что любую строку можно превратить в однозначный набор символов — хеш, и изменение любого символа строки полностью изменит его.

003.jpg

Добавление точки в конце изменило итоговый хеш до неузнаваемости — этим можно воспользоваться.

Олег берет общеизвестный хеш SHA-256 и хеширует им каждую запись, дописывая результат в конце. Теперь Олег может удостовериться, что его записи никто не изменял, захешировав их заново и сравнив с зелёненьким.
004.jpg

Но ЗЛОЙ РЮСЬКИЙ ИВАН тоже умеет в SHA-256 и легко может изменить запись вместе с её хешем. Особенно, если хеш написан прямо рядом на доске.

Потому для большей безопасности Олег решает хешировать не саму только запись, а складывать её вместе с хешем от прошлой записи. Теперь все следующие записи зависят от предыдущих. Если изменить хотя бы одну строчку, то придется пересчитать хеши всех остальных ниже по списку.
005.jpg


Так у Олега появляется личный связный список.

Но однажды Иван прокрадывается ночью, изменяет нужную ему запись и обновляет хеши для всего списка до конца. У него это занимает несколько часов, но Олег всё равно крепко спит и не слышит. На утро Олег обнаруживает абсолютно верный список — все хеши совпадают. Но Иван всё равно его обманул, хоть и потратил на это бессонную ночь. Как еще можно защититься от Ночного Ивана?

Олег решает как-то усложнить ему жизнь. Теперь для добавления новой записи в список, Олег будет решать связанную с ней сложную задачку, например математическое уравнение. Ответ он будет добавлять в итоговый хеш.

Олег силен в математике, но даже у него на добавление записи уходит по десять минут. Несмотря на это, потраченное время того стоит, ведь если Иван опять захочет что-то изменить, ему придется заново решать уравнения для каждой строки, а их могут быть десятки. На это уйдет куча времени, ведь уравнения каждый раз уникальны и связаны с конкретной записью.

Зато проверить список всё так же просто: сначала нужно как раньше сравнить хеши, а потом проверить решения уравнений простой подстановкой. Если всё сходится — список не изменен.

В реальности же с уравнениями не всё так хорошо: компьютеры слишком хорошо их решают, да и где хранить столько уникальных уравнений. Потому авторы блокчейна придумали более красивую задачу: нужно найти такое число (nonce), чтобы итоговый хеш всей записи начинался на 10 нулей. Такой nonce сложно найти, зато результат всегда можно проверить просто глазами.

006.jpg


Теперь Олег сверяет все хеши и дополнительно убеждаются, чтобы каждый начинался на оговоренное количество нулей. Хитрый Иван, даже вооружившись мощным ноутбуком, не успеет за ночь пересчитать все хеши так, чтобы они удовлетворяли условию — не хватит времени.

Такой список по сути и есть домашний блокчейн на коленке. Его безопасность гарантирована математиками, которые доказали, что эти хеши нельзя вычислить как-то быстрее, кроме как перебором. Такой перебор хешей к каждой записи и есть майнинг, о котором сегодня будет много и подробно.

Централизация доверия
Идея вести неподделываемый список «кто кому занимал» понравилась нашим друзьям. Они тоже не хотят запоминать кто за кого заплатил в баре и сколько еще остался должен — всё записано на стене. Вы обсудили идею и решили, что теперь вам нужен единый список на всех.
007.jpg


Но кому доверить вести столь важную бухгалтерию? Ведь когда дело касается денег — доверие выходит на первый план. Мы не доверим хранить свои деньги неизвестному. Наши предки для этого придумали банки, которым со временем стали доверять, потому что они подкреплёны лицензией, законами и страховкой Центрального Банка.

В кругу друзей все доверяют друг другу и можно просто выбрать на эту роль самого ответственного. Но что если вопрос касается незнакомых людей? Целого города, страны, или всего мира, как в случае с биткоином? Там вообще никто никому не может доверять.

Децентрализация: никто не доверяет никому
Так придумали альтернативный подход: хранить копию списка у каждого. Таким образом злоумышленнику придется не просто переписать один список, но и прокрасться в каждый дом и переписать списки там. А потом выяснится, что кто-то хранил у себя дома аж несколько списков, о чем никто не догадывался. Это и есть децентрализация.

Минусом такого подхода является то, что для внесения новых записей придется обзванивать всех остальных участников и сообщать каждому из них свежие изменения. Но если эти участники — бездушные машины, это перестаёт быть хоть какой-то проблемой.
008.jpg


В такой системе не существует единой точки доверия, а значит и возможности подкупа и жульничества. Все участники системы действуют согласно единому правилу: никто не доверяет никому. Каждый верит только той информации, которой располагает сам. Это главный закон любой децентрализованной сети.



Транзакции
Покупая доширак в магазине, вы вводите пин-код от своей карты, разрешая магазину спросить у банка есть ли у вас на счету 35 рублей. Другими словами, вы подписываете своим пин-кодом транзакцию на 35 рублей, которую банк подтверждает или отклоняет.

Наши записи типа «Занял Ване 500 рублей» — тоже транзакции. Но у нас нет банка, авторизующего автора транзакций. Как нам проверить, что Иван втихую не добавил запись «Макс должен Олегу 100500 рублей»?

В блокчейне для этого используется механизм публичных и приватных ключей, айтишники давно используют их для авторизации в том же SSH.

Коротко о том, как работает эта сложная, но красивая математика: вы у себя на компьютере генерируете пару длинных простых чисел — публичный и приватный ключ. Приватный ключ считается супер-секретным, потому что может расшифровать то, что зашифровано публичным. Но наоборот тоже работает. Если вы расскажете публичный ключ всем друзьям, они смогут зашифровать им любое сообщение так, что прочитать его сможете только вы, так как владеете приватным. Но кроме этого у публичного ключа есть полезный эффект — с помощью него можно проверить, что данные были зашифрованы именно вашим приватным ключом, не расшифровывая при этом сами данные. Обо всех этих свойствах хорошо рассказано в «Книге Шифров» по ссылке выше.
009.jpg

Ваш публичный ключ и является номером крипто-кошелька. То есть вы можете завести кошелек любой криптовалюты вообще не выходя в сеть.



Простым пользователям, не желающим разбираться как выпускать и хранить приватные ключи, помогут сервисы онлайн-кошельков. Чтобы копировать длинные публичные ключи, там делают удобные QR-коды. Лично я пользуюсь Blockchain Wallet, потому что у него есть удобное мобильное приложение и он поддерживает две главные криптовалюты — BTC и ETH.

Отсутствие понятия «баланса»
Как и наша доска, блокчейн по сути состоит только из истории транзакций. Он не хранит баланс каждого кошелька, иначе бы нам пришлось изобретать дополнительные способы защиты.

Владение кошельком подтверждает только приватный ключ. Но как другие участники сети убедятся, что у меня есть достаточно денег для покупки?

Раз у нас нет баланса — это должны доказывать вы. Потому в транзакцию блокчейна входит не только ваша подпись и сколько вы хотите потратить, но и ссылки на предыдущие транзакции, в которых вы получили нужное количество денег. То есть если вы хотите потратить 400 рублей вы пробегаете по всей своей истории доходов и расходов, и прикрепляете к своей транзакции те доходы, где вам дали 100 + 250 + 50 рублей, тем самым доказывая, что у вас есть эти 400 рублей.
010.jpg

Каждый участник сети еще раз обязательно проверит, что вы не прикрепляли доходы дважды. Что те 300 рублей, что дал Макс на прошлой неделе, вы действительно еще не потратили.

Такие прикрепленные к транзакции доходы в блокчейне называются инпутами (input), а все получатели денег — аутпутами (output). Сумма всех инпутов редко бывает ровно такой, сколько вы хотите перевести за раз — потому один из аутпутов чаще всего будете вы сами. Другими словами транзакция в блокчейне выглядит как «мне дали 3 и 2 BTC, я хочу из них перевести 4 BTC и оставшийся 1 BTC вернуть себе обратно».
011.jpg

Красота блокчейна еще и в том, что инпуты не обязательно должны быть с одного кошелька. Проверяется ведь только ключ. Если вы знаете приватный ключ всех инпутов, то вы без проблем сможете прикрепить их к своей транзакции и расплатиться этими деньгами. Как если бы вы в супермаркете платили сразу с нескольких карт, от которых знаете пин-код.

Однако если вы потеряете свой приватный ключ, ваш диск умрет или украдут ноутбук, ваши биткоины будут потеряны навсегда. Никто не сможет использовать их в качестве инпутов для новых транзакций. Эта сумма будет недоступна для всего мира навсегда — как если бы вы сожги пачку банкнот. Здесь нет единого банка, куда можно написать заявление с копией паспорта, и он еще напечатает. Для этого нужен еще дополнительный выпуск новых биткоинов «из воздуха».

Проблема двойной траты
Выше я сказал, что транзакции добавляются в специальный «пул неподтвержденных транзакций». Зачем нам какая-то промежуточная сущность, если у нас уже есть по сути готовые подписанные транзакции? Почему не писать их сразу в блокчейн?

Потому что сигналы из пункта А в пункт Б всегда идут с задержкой. Две транзакции могут пойти абсолютно разными путями. И транзакция, которая была инициирована первой, может дойти до получателя позже, потому что шла более длинным путём. Так получается двойное расходование, когда одни и те же деньги были отправлены сразу двум адресатам, о чем они даже не догадаются. Это вам не купюры из рук в руки передавать.
012.jpg


Для децентрализованной сети, в которой никому нельзя доверять, эта проблема стоит особенно остро. Вот как вы убедитесь, что одна транзакция точно была раньше другой? Попросите отправителя вшивать в неё время отправки, не так ли? Но вспомните — никому нельзя доверять, даже отправителю. Время на всех компьютерах обязательно будет отличаться и нет способа их гарантировано синхронизировать. Копия блокчейна хранится на каждом компьютере сети и каждый участник доверяет только ей.

Как же убедиться, что одна транзакция была раньше другой?

Ответ прост: это невозможно. Нет способа подтвердить время транзакции в децентрализованной сети. И вот в решении этой проблемы и заключается третья важная идея блокчейна, которую придумал Сатоши и которая, как ни странно, прописана прям в его названии — блоки. +
013.jpg

Блоки — основа блокчейна
Каждый работающий компьютер в сети выбирает из общего пула любые транзакции, которые ему нравятся. Обычно просто по самой высокой комиссии, которую он может на ней заработать. Так он набирает себе транзакции, пока их суммарный размер не достигнет обговорённого лимита. В Биткоине этот лимит на размер блока равен 1 Мб (после SegWit2x будет 2 Мб), а в Биткоин Кеше — 8 Мб.

А вот в сетях типа Ethereum всё немного сложнее, там количество транзакций на блок зависит от вычислительной сложности включенных в них смарт-контрактов. Но суть не меняется — есть определенный лимит.
Весь блокчейн по сути и есть список таких блоков, где каждый ссылается на предыдущий. По нему можно отследить любую транзакцию за всю историю, разматывая блокчейн хоть до самой первой записи. Именно этот список и весит сейчас сотни гигабайт и должен быть полностью скачан на все компьютеры, которые хотят принимать участие в работе сети (но чтобы просто создавать транзакции и переводить деньги, это не обязательно). Скачивается он так же со всех ближайших компьютеров сети, как будто вы качаете сериал с торрентов, только новые новые серии в нём выходят каждые 10 минут.
014.jpg



Набрав себе транзакций из пула компьютер начинает составлять из них такой же неподделываемый список, как мы в начале поста на доске у себя дома. Только делает он его в виде дерева — хеширует записи попарно, потом результат еще раз попарно и так пока не останется лишь один хеш — корень дерева, который и добавляется в блок. Почему именно деревом — ответа я не нашел, но предполагаю, что так просто быстрее. Подробнее есть на вики: Дерево Меркла.

015.jpg

Так как актуальный блокчейн уже скачан, наш компьютер точно знает какой в нём сейчас последний блок. Ему остается только добавить ссылку на него в заголовок блока, захешировать всё это и сообщить всем остальным компьютерам сети «смотрите, я сделал новый блок, давайте добавим его в наш блокчейн».

Остальные должны проверить, что блок построен по всем правилам и что мы не добавили туда лишних транзакций, а затем добавить к себе в цепочки. Теперь все транзакции в нём подтверждены, блокчейн увеличен на один блок и всё идет хорошо, не так ли?

А вот и нет. В сети одновременно работают тысячи компьютеров, и как только они соберут новый блок, они почти одновременно ринутся сообщать всем, что их блок был создан первым. А из предыдущего раздела мы уже знаем, что в децентрализованной сети невозможно доказать кто действительно был первым.
016.jpg

Поэтому для включения блока в цепочку компьютеры должны решить какую-то сложную задачку, которая займет у них определенное время.

Как в школе, когда все решали сложную контрольную, очень редко бывало так, что даже отличники сдавали ответы абсолютно одновременно.

Но если для человека сложная задача — это спланировать отпуск, чтобы и на майские праздники попал, и билеты на море недорого, то для компьютера — это добавить в конец блока такое число (nonce), чтобы в результате хеш SHA-256 для всего блока начинался, скажем, на 10 нулей. Это и есть та задача, которую надо решить, чтобы добавить блок в сеть Bitcoin. Для других сетей задачи могут отличаться.

Так мы приходим к понятию майнинга, на котором все так помешаны в последние годы. 8 комментариев

017.jpg

Майнин
Майнинг биткоина — не какое-то там священное таинство. Майнинг не связан с поиском новых биткоинов где-то в глубинах интернета. Майнинг — это когда тысячи компьютеров по всему миру гудят по подвалам, перебирая миллионы чисел в секунду, пытаясь подобрать хеш, начинающийся на 10 нулей. Им даже не обязательно для этого находиться в сети.

018.jpg

Видеокарты с их сотнями параллельных ядер, решают эту задачу быстрее любого CPU.

Почему именно на 10 нулей? А просто так, в этом нет никакого смысла. Так придумал Сатоши. Потому что это одна из тех задач, на которую точно всегда есть решение, но оно точно не может быть найдено быстрее, чем долгим монотонным перебором вариантов.

Сложность майнинга напрямую зависит от размера сети, то есть её суммарной мощности. Если вы создадите свой блокчейн и запустите его себя дома на двух ноутбуках, то задача должна быть попроще. Например чтобы хеш начинался только с одного нуля, или чтобы сумма четных разрядов была равна сумме нечетных.

Чтобы найти начинающийся на 10 нулей хеш, у одного компьютера уйдет несколько десятков лет. Но если объединить тысячи компьютеров в единую сеть и искать параллельно, то по теории вероятностей эта задача решается в среднем за 10 минут. Это и есть время появления нового блока в блокчейне биткоина. Каждые 8-12 минут кто-то на земле находит такой хеш и получает привилегию анонсировать свою находку на всех, избежав тем самым проблемы кто был первым.
019.jpg

За нахождение ответа компьютер (по данным на 2017 год) получает 12.5 BTC — это сумма вознаграждения, которая генерируется системой биткоин «из воздуха» и уменьшается каждые четыре года. Технически это означает, что каждый майнер всегда добавляет в свой блок еще одну транзакцию — «создать 12.5 BTC и отправить их на мой кошелек». Когда вы слышите «количество биткоинов в мире ограничено 21 млн, сейчас наймайнили уже 16 млн» — это и есть такие генерируемые сетью вознаграждения.

Сходите посмотрите на настоящий живой блок Биткоина на одном из специальных сайтов. Там есть и транзакции с инпутами и аутпутами, и аж 18 нулей в начале и все описанные выше хеши.

Любой блокчейн существует только пока существуют его майнеры.
Именно майнеры добавляют появляющиеся транзакции в блокчейн. Так что если кто-то рассказывает вам, что он «сделает блокчейн для ***», первый вопрос, на который он должен ответить — кто и зачем будет майнить на нём. Чаще всего правильный ответ — «будут все, потому что за майнинг мы даём наши коины, которые будут расти и майнерам это выгодно». Но это применимо не для всех проектов. Например какой-нибудь Минздрав завтра создает свой закрытый блокчейн для докторов (а они хотят), кто его будет майнить? Терапевты по выходным?

Но какая выгода майнерам будет потом, когда вознаграждения исчезнут или станут мизерными?

По задумке Создателя, к тому времени люди должны будут поверить в реальность биткоина и майнинг начнет окупаться суммой комиссий, включенных в каждую транзакцию. К этому всё и идет: еще в 2012 году все комиссии были нулевые, майнеры майнили только за вознаграждения от блоков. Сегодня же транзакция с нулевой комиссией может провисеть в пуле несколько часов, потому что появилась и конкуренция, и люди готовы платить за скорость.

То есть суть майнинга в решешии бессмысленных задачек. Разве нельзя пустить все эти мощности на что-то более полезное — поиск лекарства от рака, например?

Суть майнинга — решить любую вычислительную задачу. Эта задача должна быть достаточно простой, чтобы у участников сети была стабильная вероятность найти ответ — иначе транзакции будут подтверждаться вечность. Представьте, что на кассе в магазине вам надо каждый раз ждать по пол часа, пока банк подтвердит вашу транзакцию. Никто не будет пользоваться таким банком.

Но задача должна быть одновременно и сложной, чтобы ответ не нашли сразу все пользователи сети. Потому что в таком случае они анонсируют в сеть много блоков с одинаковыми транзакциями и будет вероятность «двойной растраты», о которой я говорил. Или еще хуже — разделения единого блокчейна на несколько веток, в которых уже никто не сможет разобраться какая транзакция подтверждена, а какая нет.

Если награда в 12.5 BTC вручается лишь раз в 10 минут и только одному нашедшему блок, получается мне надо впустую жечь видеокарты несколько лет в надежде, что однажды мне упадет $40000 (по текущему курсу)?

Для биткоина именно так. Но так было не всегда. Раньше сеть была меньше, сложность ниже, а значит и выше вероятность единолично найти хеш для нового блока. Но и биткоин тогда стоил не так дорого.

Сейчас биткоины в одиночку уже никто не майнит. Теперь участники объединяются в специальные группы — майнинг пулы, где все вместе пытаются найти правильный хеш. Если хоть один из группы находит, то всё вознаграждение делится между участниками в зависимости от их вклада в общую работу. Получается, что ты майнишь и тебе еженедельно падает копеечка от общей доли.

Но одиночный майнинг вполне возможен в других сетях. Вот еще недавно было легко майнить Ethereum, где блоки находятся каждые 10 секунд. Вознаграждение за блок там намного ниже, но вероятность заработать копеечку получается выше.

Значит мы так и будем сжигать тысячи видеокарт впустую и никакого выхода нет?

Да, но есть идеи. Тот майнинг, что я описал, является классическим и называется Proof-of-Work (доказательство работы). То есть каждая машина доказывает, что она работала на благо сети тем, что решает бессмысленные задачки с заданной вероятностью.

Но некоторые ребята начинают делать блокчейны с другими видами майнинга. Сейчас вторая по популярности концепция — это Proof-of-Stake (доказательство доли владения). В таком виде майнинга, чем больше «коинов» на счету у участника сети, тем больше его вероятность вставить в блокчейн свой блок. Как самый громкий парень на деревне.

Можно придумать и другие виды майнинга. Как уже предлагали, все компьютеры в сети могут искать лекарство от рака, только нужно придумать как в таком случае зафиксировать их вклад в систему. Ведь я могу заявить, что я тоже участвую, но отключить свою видеокарту и ничего не считать. Как выразить количественный вклад каждого участника в поиск лекарства от рака? Придумаете — дерзайте пилить свой CancerCoin, хайп в СМИ вам обеспечен.

Блокчейн
Представим ситуацию, в которой несмотря на всю нашу теорию вероятностей, два майнера всё равно умудрились одновременно найти правильный ответ. Они начинают рассылать два абсолютно верных блока по сети. Эти блоки гарантировано отличаются, ведь даже если они чудом выбрали одинаковые транзакции из пула, составили абсолютно идентичные деревья и угадали одинаковое рандомное число (nonce), их хеши всё равно будут разными, так как каждый пропишет в блок свой номер кошелька для вознаграждения.

Теперь у нас есть два валидных блока и снова возникает проблема кого считать первым. Как поведет себя сеть в таком случае?

В алгоритме блокчейна прописано, что участники сети просто принимают первый правильный ответ, который до них дошел. Дальше они живут исходя из собственной картины мира. Оба майнера получат своё вознаграждение, а все остальные начинают майнить, опираясь на последний ими лично полученный блок, отбрасывая все остальные повторно-верные. В сети появляется две версии правильного блокчейна. Такой вот парадокс.
020.jpg

Это штатная ситуация, в которой снова помогает теория вероятностей. Сеть функционирует в таком вот раздвоенном состоянии, пока кто-то из майнеров не находит следующий блок к одной из этих цепочек. Как только такой блок находится и вставляется в цепочку, она становится длиннее и включается одно из соглашений сети блокчейн: при любых условиях, самая длинная цепочка блоков принимается как единственно верная для всей сети.

Короткая цепочка, несмотря на всю свою правильность, отвергается всеми участникам сети. Транзакции из неё возвращаются в пул (если они не были подтверждены в другой), а их обработка начинается заново. У майнера пропадает его вознаграждение, потому что его блока больше не существует.

С ростом сети такие совпадения из «очень маловероятных» переходят в разряд «ну иногда бывает». Старожилы рассказывают, что бывали случаи, когда отбрасывалась цепочка сразу из четырех блоков.
021.jpg

Из-за этого были придуманы три правила безопасности хвоста блокчейна (end of chain insecurity):

1. Вознаграждениями за майнинг, можно пользоваться только спустя еще 20 подтвержденных блоков после получения. Для биткоина это около трёх часов.

2. Если вам переслали биткоины, использовать их в качестве инпутов в новых транзакциях можно только спустя 1-5 блоков.

3. Правила 1 и 2 всего лишь прописаны в настройках каждого клиента. Никто не следит за их соблюдением. Но закон о самой длинной цепочке всё равно уничтожит все ваши транзакции, если вы попытаетесь обмануть систему, не соблюдая их.

Пытаемся обмануть блокчейн
Теперь, когда вы знаете всё о майнинге, устройстве блокчейна и правиле самой длинной цепочки, у вас мог возникнуть вопрос: а можно ли как-то специально обогнать блокчейн, составив самую длинную цепочку самому, тем самым подтвердив свои фейковые транзакции.

Предположим у вас есть самый мощный компьютер на Земле. Датацентры Google и Amazon вместе взятые в вашем распоряжении и вы пытаетесь просчитать такую цепочку, которая станет самой длинной в сети блокчейн.
022.jpg

Вы не можете взять и сразу просчитать несколько блоков цепочки, ведь каждый следующий блок зависит от предыдущего. Тогда вы решаете как можно быстрее считать каждый блок на своих огромных датацентрах параллельно с тем, как все остальные участники продолжают увеличивать основной блокчейн. Возможно ли их обогнать? Вероятно, да.

Если ваша вычислительная мощность будет составлять больше 50% от мощности всех участников сети, то с вероятностью 50% вы сможете построить более длинную цепочку быстрее всех остальных вместе взятых. Это теоретически возможный способ обмануть блокчейн, просчитав более длинную цепочку транзакций. Тогда все транзакции настоящей сети будут считаться неверными, а вы соберете все вознаграждения и начнете новую веху в истории криптовалюты, которая называется «разделение блокчейна». Однажды из-за бага в коде так было с Ethereum.

Но в реальности ни один датацентр не сравнится по мощности со всеми компьютерами в мире. Полтора миллиарда китайцев с айсиками, еще полтора миллиарда голодных индусов с фермами для майнинга и дешевым электричеством — это огромная вычислительная мощность. Никто в мире пока не может составить им конкуренцию в одиночку, даже Google.

Это примерно как выйти на улицу и пытаться убедить каждого человека в мире, что доллар теперь стоит 1 рубль и успеть до того, как в СМИ вас разоблачат. И вот если вы умудритесь убедить всех, то сможете обвалить мировую экономику. В теории ведь это возможно? Но на практике почему-то ни у кого не получалось.

На этой вероятности держится и блокчейн. Чем больше участников-майнеров — тем больше безопасность и доверие сети. Потому когда в Китае накрывают очередную крупную майнинг-ферму, курс и обваливается. Все боятся, что где-то в мире сидел злой гений, который уже собрал пул майнеров на ~49% мощности.

По факту такое было несколько раз годах в 2014-х, когда один из пулов для майнинга временно стал мощнее остальной сети. Но манипуляций тогда замечено не было.
023.jpg

Заключение

Блокчейн не только для криптовалют
Блокчейн — не строго определенный набор алгоритмов. Это структура построения неподделываемой сети между участниками, где никто никому не может доверять. Во время прочтения наверняка у вас ни раз проскакивала мысль, что «можно же вот так переделать и будет еще полезнее». Это значит, что вы поняли блокчейн, поздравляю.

Некоторые ребята в мире тоже его поняли и захотели улучшить или адаптировать под какие-то специфические задачи. Не криптовалютами же едиными, хотя их тоже развелось немало. Вот краткий список некоторых идей и проектов, которые набрали определенную популярность благодаря переосмыслению идеи блокчейна.

Источник