Tendermint and Cosmos SDK working basics

Tendermint and Cosmos SDK working basics

Содержимое

Читать на Русском

13 years have passed since the publication of the Bitcoin whitepaper, which actually opened a new blockchain technology to the world. Over the next years developers have put a lot of effort into making it safer, more reliable and easier to use by creating their own algorithms and applications. One of the most notable developments is the Cosmos blockchain and the Tendermint algorithm working with it in conjunction. We will tell about them in this article.

Genesis Block are the top-class blockchain professionals since 2013. Building dapps (decentralized applications) based on the Cosmos/Tendermint blockchain is also our specialization. Currently, we are fulfilling a large order from the Middle East in the field of building a halal blockchain compatible with the principles of Islamic finance based on the Tendermint blockchain core and Cosmos SDK with the ability of importing into the core of the Ethereum virtual machine (EVM, ethereum virtual machine) which allows to import smart contracts and applications from the popular ETH blockchain network (Ethereum) and run them with a much lower commission. You can get acquainted with the video review of the node and the console wallet of this blockchain project from the video:

Tendermint is a consensus algorithm that has a reliable mechanism of resistance to unauthorized actions, known as «Byzantine falls». It is used in the Cosmos interconnected blockchain system and was introduced in 2014 by programmer Jae Kwon, who aimed to avoid the problems of high energy consumption in blockchain networks and create an «Internet of blockchains» for more reliable decentralized user interaction.

In 2017, the Interchain Foundation, a company engaged in the support and development of new technologies and decentralized applications, signed a contract with developers to create the Cosmos Network. The result of this collaboration was the appearance of the Cosmos Network and the Cosmos SDK, a framework that allows developers to create their own customized blockchains based on the Tendermint consensus algorithm.

Validators

The Tendermint consensus algorithm works on a set of special nodes called validators. They are responsible for adding transaction blocks to the blockchain. At the time of working with each block, there are many validators, from which the algorithm selects the one that will offer the next block. A block is considered valid if more than two-thirds of the validators have signed prevote and precommit and all transactions in the block are valid. Unlike the same Proof-of-Work or Proof-of-Stake, where anyone can become a miner at any time, in BCA only so-called validators can take part in the formation of the blockchain.

How an ordinary network participant becomes a validator depends on the specific implementation. In the simplest case, validators are declared in the genesis block and in the future their list does not change (the main thing is that there should be strictly less than 1/3 in the initial list of Byzantine validators!). In the same Tendermint, you can easily implement rotation of validators. To do this, it is enough to indicate in the protocol a special transaction that will be sent by the participant if he wants to «run». Additionally, you can, as inside the same Lisk, enter a vote for candidates or choose them according to some already existing parameters.

In the Tendermint implementation, it is always possible to get an exact list of validators for any block*. They are identified by their public keys, and during the voting process, they sign messages sent to other validators and ordinary network participants with the corresponding private keys. In this way, you can always identify the author of a particular vote and be sure that no one «from the outside» will be able to take part in building consensus.

* The initial list is set in the genesis file; transactions that change the list of validators are the same transactions as any other, which means they are also stored in the blockchain and are available to all network participants to get the current list of validators.

Simple scheme

Let’s start with an abstract description of what happens in the algorithm at the time of searching for block N.

genesis block, processing, banks

Propose is some kind of proposer** offers its own version of the block at height N.

Prevote is the step on which validators give their «evaluation opinion» to the block. In the simplest case, the validator will send a message to the network like «I received a block , I agree with everything».

Precommit — after some time allocated for the Prevote step, each validator checks how many «accumulated» Prevote messages from other participants. If there are 2/3+ of the total number of validators, then the validator sends a Pre commit transaction.

Three steps in parentheses (Propose -> Prevote -> Precommit) is the so-called round. Its essence is that there are many cases when for some reason it was not possible to find a new block. For example, the selected proposer could be offline or I can offer a deliberately incorrect block (this case is described in detail below).

* * The proposers are selected by the round-robin algorithm from the list of validators in proportion to their weight**. This gives two interesting properties: first of all, the determinism we need (each network participant should be able to know unequivocally which of the validators will be the proposer in this round). But at the same time, we have a pseudo-random choice that will negate the attacks associated with a pre-known sequence of proposers in the selection process.

What is weight is up to the protocol developer to decide. In the simplest case, you can assign the same weight to all validators, that is, the choice of the proposer will be uniform.

In this case, two changes are made to the consensus-building process:

  • A new proposer is selected.
  • • Each step has a certain time duration common to all (conditionally, the Private shakedown lasts 5 seconds, after that all participants switch to Precommit). Since there is a high probability that something went wrong due to a weak connection (for example, the Internet is bad for the proposer, he did not have time to download the block at all and scatter it over the network), the duration of each step increases by some constant.

Below an illustration of the entire process from the official Tendermint documentation is shown.

genesis block, processing, banks

Malicious proposer

To fully understand the essence of the algorithm, we will analyze the principle of its operation on a «real» network. To begin with, let’s define the network itself:

    There are 5 validators:

  • A, B, C, D, E
  • Validator A is the proposer. Moreover, it is proposed to make A a Byzantine validator to look at the work of the network at the moment when it is being compromised.
  • Each step lasts t seconds; the algorithm starts at time T.

So, let’s start creating block #X. The first step is the Propose step, lasting t seconds, during which the proposer must create a block and «scatter» it over the network, and it is extremely important that other validators have time to get this block.

genesis block, processing, banks

Now let’s move on to the Prevent step. Now, the main task of validators is to check the block and decide whether they «agree» with it or not. In this case, B, C, D, E will send a Prevent nil message over the network — it means that none of them agree with the proposed block. For more realism, let’s assume that E has a bad Internet connection and he didn’t get anything at all in t seconds. A (the proposer also participates in the vote!) will send Private, in an attempt to maintain its incorrect block. For more realism, let E, as usual, have a bad Internet connection and he did not receive any new messages from A, B, C, D.

genesis block, processing, banks

Then the messages received at the Prevent step for each validator look like this.

genesis block, processing, banks

E has a bad Internet connection and other participants do not have time to receive messages from him at all.

The final step of the round remains — Precommit. B, C, D, E will send a Pre commit nil message to the network (because the number of Private messages each of them has is less than 2/3+ the number of validators). Let’s look at the collected Precommit messages for each validator.

genesis block, processing, banks

Obviously, there are no validators that would collect 2/3+ Precommit messages, which means, according to the scheme above, this round will be completed without creating a new block of height #X.

Important note: each block should contain these same Precommit messages and, obviously, there should be at least 2/3+ of them. Therefore, even if A wants to spread a «false» block over the network, he will not have the necessary number of signed Precommit messages, which means that any participant will instantly notice the catch.

Optimal scenario

In the round described above, it was not possible to create a new block. This means that before the start of the next round, another validator will be selected by the proposer (let it be B) and the duration of the steps will be slightly increased in order to offset the impact of a slow connection. So, in this round, the validator will no longer stand aside due to poor Internet, but will take a full part.

Again, we start with the Propose step, and this time the block is fully valid and managed to reach all validators. You can immediately switch to the Prevent step and see what the list of Private messages looks like for each validator. For more interest, let’s assume that A is still malicious, so this time it will try to prevent the block from being created.

genesis block, processing, banks

It can be seen that all validators have enough Private messages to send Precommit messages. Suppose A sends a Precommit nil message, even though it’s formal – it’s wrong on his part.

genesis block, processing, banks

In any case, we see that this did not create problems for other participants and they have 2/3+ Precommit messages in order to create a new block.

In computer science, a finite automaton is a mathematical abstraction that has one input, one output and is in one of many states at any given time. The state describes the current state of the machine, and transactions describe changes in the current state. Taking state S and transaction T as input, the automaton will return a new state S’.

genesis block, processing, banks

In practice, transactions are grouped into blocks, which makes the process more efficient. Taking state S and transaction block B as input, the automaton will return a new state S’.

genesis block, processing, banks

The main part of an application written using the Cosmos SDK is a background program (daemon) that runs on each node. If less than one third of the validators in the set of validators are attackers, then each node should receive the same state at a given time when querying.

In the context of blockchain, a finite automaton is deterministic. Determinism means that applying the same sequence of transactions to the same state always leads to the same final state. The Cosmos SDK provides maximum flexibility in determining the state of the application being developed, transaction types, and state change functions. The process of developing a finite state machine using the SDK will be described in the following chapters. First, let’s look at the replication process using Tendermint.

Tendermint

Tendermint is a program independent of the application being developed, responsible for networking and consensus. In practice, this means that Tendermint is responsible for transmitting and ordering transaction bytes. It is based on the Byzantine-Fault-Tolerant (BFT) algorithm to achieve consensus on the order of transactions. The only thing the developer needs to do is to describe the state machine using the Cosmos SDK. The replication process through the network takes over.

genesis block, processing, banks

ABCI

Tendermint transmits transactions to the application over the network via an API that the application must implement.

genesis block, processing, banks

Tendermint works with transaction bytes, but has no information about what these bytes mean. All Tendermint does is deterministically order these bytes. Tendermint passes bytes to the application via ABCI and expects to receive a return code that contains a message indicating whether transactions have been processed successfully.

The most important types of ABCI messages:

  • CheckTx: After accepting the Tendermint Core transaction, the transaction is passed to the application to verify the basic requirements. The cache is used to protect the mempool (mempool) spam protection node. A pre-handler (Ante Handler) is used to perform a sequence of validation steps, such as verifying fees and validators’ signatures. If the transaction is valid, it is added to the Mempool and broadcast to other nodes. It should be noted that CheckTx does not process transactions, that is, there is no state change, because transactions at this stage have not yet been included in the block.
  • DeliverTx: When Tendermint Core accepts a valid block, each transaction in this block is passed to the application via DeliverTx for processing. It is at this stage that the state changes. The handler (Ante Handler) is executed repeatedly along with the rest of the handlers for each message in the transaction.
  • BeginBlock/EndBlock: These messages are executed at the beginning and end of the block, regardless of whether the block contains transactions or not. This is convenient if you need to execute the code automatically. It should be noted that processes that require large computing resources can slow down the work of the blockchain or even lead to a stop in the case of an infinite loop.

What is the result

Among the distinctive features and advantages of working with Cosmos and Tendermint for developers are:

  1. The network has high scalability and, importantly, has self-healing procedures by blocking validators suspected of double-signing blocks or insufficient performance, which eliminates the possibility of network death due to the shutdown of data centers.
  2. The network supports the Solidity smart contract language and has a huge number of examples and documentation.
  3. The network is lightweight and does not require mining devices. The system requirements of the device are 2-3 GB of RAM and 1 CPU. 40 GB HDD.
  4. The algorithm for selecting a validator and awarding the most honest, because the one who works best gets the one with the least number of passes. The algorithm for selecting a validator is based on the round-robin algorithm.
  5. The minimum number of validators for stable network operation is 30. These validators should not belong to one person, and should not be located in the same data center. In this case, validators will be able to replace each other and balance.
  6. This blockchain protocol is designed for a «honeycomb» system, where each blockchain is independent, but is a child process of tendermint. Which in the future has the possibility of working between blockchains.

>>> О КОМПАНИИ GENESIS BLOCK:

Компания Genesis Block – международный системный интегратор и разработчик финтех-решений, систем платежей и процессинга, систем биллинга и программных решений для ЖКХ, блокчейн-решений, веб-сайтов, порталов и мобильных приложений. Под брендом Genesis Block объединены компании, разработчики и сервисы, работающие на рынке с 2010 г. Качество наших сервисов подтверждается международной сертификацией по ISO. Входим в российскую ассоциацию программного обеспечения НП РУССОФТ. Genesis Block является постоянным главным спонсором и спикером на международных банковских и финансовых конференциях IFIN и ВБА (Вся Банковская Автоматизация). Аккредитованная IT-компания Минкомсвязи. Является членом РАКИБ (Российская Ассоциация Криптовалют и Блокчейна). С 2020 компания Genesis Block ведет собственную авторскую передачу на деловом телевидении ПРОБИЗНЕС. Являемся авторизованным официальным интегратором крупнейшей BPM / CRM системы Terrasoft.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *