Cosmos: сеть распределенных реестров

Cosmos: A Network of Distributed Ledgers

Tác giả Jae Kwon and Ethan Buchman · 2016

Introduction

Introduction

The combined success of the open-source ecosystem, decentralized yle-sharing, and public cryptocurrencies has inspired an understanding that decentralized internet protocols can be used to radically improve socio-economic infrastructure. We have seen specialized blockchain applications like Bitcoin [1] (a cryptocurrency), Zerocash [2] (a cryptocurrency for privacy), and generalized smart contract platforms such as Ethereum [3], with countless distributed applications for the Etherium Virtual Machine (EVM) such as Augur (a prediction market) and TheDAO [4] (an investment club). To date, however, these blockchains have suffered from a number of drawbacks, including their gross energy inefyciency, poor or limited performance, and immature governance mechanisms. Proposals to scale Bitcoin’s transaction throughput, such as Segregated-Witness [5] and BitcoinNG [6], are vertical scaling solutions that remain limited by the capacity of a single physical machine, in order to ensure the property of complete auditability. The Lightning Network [7] can help scale Bitcoin transaction

volume by leaving some transactions off the ledger completely, and is well suited for micropayments and privacy-preserving payment rails, but may not be suitable for more generalized scaling needs. An ideal solution is one that allows multiple parallel blockchains to interoperate while retaining their security properties. This has proven difycult, if not impossible, with proof-of-work. Merged mining, for instance, allows the work done to secure a parent chain to be reused on a child chain, but transactions must still be validated, in order, by each node, and a merge-mined blockchain is vulnerable to attack if a majority of the hashing power on the parent is not actively merge-mining the child. An academic review of alternative blockchain network architectures is provided for additional context, and we provide summaries of other proposals and their drawbacks in Related Work. Here we present Cosmos, a novel blockchain network architecture that addresses all of these problems. Cosmos is a network of many independent blockchains, called zones. The zones are powered by Tendermint Core [8], which provides a high-performance, consistent, secure PBFT-like consensus engine, where strict forkaccountability guarantees hold over the behaviour of malicious actors. Tendermint Core’s BFT consensus algorithm is well suited for scaling public proof-of-stake blockchains. The yrst zone on Cosmos is called the Cosmos Hub. The Cosmos Hub is a multi-asset proof-of-stake cryptocurrency with a simple governance mechanism which enables the network to adapt and upgrade. In addition, the Cosmos Hub can be extended by connecting other zones. The hub and zones of the Cosmos network communicate with each other via an inter-blockchain communication (IBC) protocol, a kind of virtual UDP or TCP for blockchains. Tokens can be transferred from one zone to another securely and quickly

without the need for exchange liquidity between zones. Instead, all inter-zone token transfers go through the Cosmos Hub, which keeps track of the total amount of tokens held by each zone. The hub isolates each zone from the failure of other zones. Because anyone can connect a new zone to the Cosmos Hub, zones allow for future-compatibility with new blockchain innovations. In this section we describe the Tendermint consensus protocol and the interface used to build applications with it. For more details, see the appendix. In classical Byzantine fault-tolerant (BFT) algorithms, each node has the same weight. In Tendermint, nodes have a non-negative amount of voting power, and nodes that have positive voting power are called validators. Validators participate in the consensus protocol by broadcasting cryptographic signatures, or votes, to agree upon the next block. Validators’ voting powers are determined at genesis, or are changed deterministically by the blockchain, depending on the application. For example, in a proof-of-stake application such as the Cosmos Hub, the voting power may be determined by the amount of staking tokens bonded as collateral. NOTE: Fractions like ⅔ and ⅓ refer to fractions of the total voting power, never the total number of validators, unless all the validators have equal weight. \(> 2/3\) means “more than ⅔”, \(\geq 1/3\) means “at least ⅓”. Tendermint is a partially synchronous BFT consensus protocol derived from the DLS consensus algorithm [20]. Tendermint is

notable for its simplicity, performance, and fork-accountability. The protocol requires a yxed known set of validators, where each validator is identiyed by their public key. Validators attempt to come to consensus on one block at a time, where a block is a list of transactions. Voting for consensus on a block proceeds in rounds. Each round has a round-leader, or proposer, who proposes a block. The validators then vote, in stages, on whether to accept the proposed block or move on to the next round. The proposer for a round is chosen deterministically from the ordered list of validators, in proportion to their voting power. The full details of the protocol are described here. Tendermint’s security derives from its use of optimal Byzantine fault-tolerance via super-majority (\(> 2/3\)) voting and a locking mechanism. Together, they ensure that: \(\geq 1/3\) voting power must be Byzantine to cause a violation of safety, where more than two values are committed. if any set of validators ever succeeds in violating safety, or even attempts to do so, they can be identiyed by the protocol. This includes both voting for conzicting blocks and broadcasting unjustiyed votes. Despite its strong guarantees, Tendermint provides exceptional performance. In benchmarks of 64 nodes distributed across 7 datacenters on 5 continents, on commodity cloud instances, Tendermint consensus can process thousands of transactions per second, with commit latencies on the order of one to two seconds. Notably, performance of well over a thousand transactions per second is maintained even in harsh adversarial conditions, with validators crashing or broadcasting maliciously crafted votes. See the ygure below for details.

Tendermint throughput vs block size benchmarked across 64 nodes in 7 datacenters on 5 continents

A major beneyt of Tendermint’s consensus algorithm is simpliyed light client security, making it an ideal candidate for mobile and internet-of-things use cases. While a Bitcoin light client must sync chains of block headers and ynd the one with the most proof of work, Tendermint light clients need only to keep up with changes to the validator set, and then verify the \(> 2/3\) PreCommits in the latest block to determine the latest state. Succinct light client proofs also enable inter-blockchain communication. Tendermint has protective measures for preventing certain notable attacks, like long-range-nothing-at-stake double spends and censorship. These are discussed more fully in the appendix.

The Tendermint consensus algorithm is implemented in a program called Tendermint Core. Tendermint Core is an application-agnostic “consensus engine” that can turn any deterministic blackbox application into a distributedly replicated blockchain. Tendermint Core connects to blockchain applications via the Application Blockchain Interface (ABCI) [17]. Thus, ABCI allows for blockchain applications to be programmed in any language, not just the programming language that the consensus engine is written in. Additionally, ABCI makes it possible to easily swap out the consensus layer of any existing blockchain stack. We draw an analogy with the well-known cryptocurrency Bitcoin. Bitcoin is a cryptocurrency blockchain where each node maintains a fully audited Unspent Transaction Output (UTXO) database. If one wanted to create a Bitcoin-like system on top of ABCI, Tendermint Core would be responsible for Sharing blocks and transactions between nodes Establishing a canonical/immutable order of transactions (the blockchain) Meanwhile, the ABCI application would be responsible for Maintaining the UTXO database Validating cryptographic signatures of transactions Preventing transactions from spending non-existent funds Allowing clients to query the UTXO database Tendermint is able to decompose the blockchain design by offering a very simple API between the application process and consensus process.

Введение

Совокупный успех экосистемы с открытым исходным кодом, децентрализованный обмен данными и публичные криптовалюты вдохновило на понимание того, что децентрализованные интернет-протоколы могут быть использованы для радикального улучшения социально-экономической инфраструктуры. Мы видели специализированные приложения blockchain, такие как Bitcoin PH_0000 ( криптовалюта), Zerocash [2] (криптовалюта для конфиденциальности) и обобщенные платформы smart contract, такие как Ethereum [3], с бесчисленное количество распределенных приложений для Etherium Virtual Машина (PH_0007), такая как Augur (рынок прогнозов) и TheDAO. [4] (инвестиционный клуб). Однако на сегодняшний день эти blockchain пострадали от ряда недостатков, включая их общую энергетическую неэффективность, плохое или ограниченная производительность и незрелые механизмы управления. Предложения по масштабированию пропускной способности транзакций Bitcoin, например: Segregated-Witness [5] и BitcoinNG [6] — вертикальное масштабирование. решения, которые остаются ограниченными емкостью одного физического машина, чтобы обеспечить свойство полной проверяемости. Lightning Network [7] может помочь масштабировать транзакцию Bitcoin.

объем, полностью исключив некоторые транзакции из реестра, и хорошо подходит для микроплатежей и обеспечения конфиденциальности платежные рельсы, но могут не подойти для более универсальных потребности в масштабировании. Идеальным решением является решение, позволяющее нескольким параллельным blockchain взаимодействовать, сохраняя при этом свои свойства безопасности. Это имеет оказалось трудным, если не невозможным, с proof-of-work. Объединено например, майнинг позволяет выполнить работу по защите родительского цепочку для повторного использования в дочерней цепочке, но транзакции все равно должны быть проверяется по порядку каждым узлом и слитным майнингом blockchain уязвим для атаки, если большая часть hashing мощности на родитель не занимается активным слитным майнингом дочернего процесса. Академический обзор альтернативных сетевых архитектур blockchain предусмотрены для дополнительный контекст, и мы предоставляем краткое изложение других предложений и их недостатки в смежных работах. Здесь мы представляем Cosmos, новую сетевую архитектуру blockchain. который решает все эти проблемы. Cosmos — это сеть из многих независимые blockchain, называемые зонами. Зоны питаются от Tendermint Core [8], обеспечивающий высокую производительность, согласованный, безопасный механизм консенсуса, подобный PBFT, в котором строгая ответственность за действия гарантирует сдерживание поведения злоумышленников. актеры. Алгоритм консенсуса BFT Tendermint Core хорошо подходит для масштабирования общедоступных proof-of-stake blockchains. Первая зона на Cosmos называется Cosmos Hub. Cosmos Hub — это мультиактивная криптовалюта proof-of-stake с простой механизм управления, который позволяет сети адаптироваться и обновление. Кроме того, концентратор Cosmos можно расширить за счет подключение других зон. Хаб и зоны сети Cosmos обмениваются данными с друг с другом через протокол связи между blockchain (IBC), своего рода виртуальный UDP или TCP для blockchains. Токены могут быть безопасно и быстро переносить из одной зоны в другуюбез необходимости обмена ликвидности между зонами. Вместо этого, все межзональные передачи token проходят через концентратор Cosmos, который отслеживает общее количество token, находящихся в каждой зоне. концентратор изолирует каждую зону от сбоя других зон. Потому что любой может подключить новую зону к хабу Cosmos, зоны позволяют для будущей совместимости с новыми blockchain инновациями. В этом разделе мы описываем консенсусный протокол Tendermint. и интерфейс, используемый для создания приложений с его помощью. Для более подробности смотрите в приложении. В классических византийских отказоустойчивых алгоритмах (BFT) каждый узел имеет одинаковый вес. В Tendermint узлы имеют неотрицательное значение. количество голосов и узлы, которые имеют положительное голосование мощности называются validators. Валидаторы участвуют в протокол консенсуса путем трансляции криптографических подписей или голосов, чтобы согласовать следующий блок. Право голоса валидаторов определяется на этапе генезиса или детерминировано изменено blockchain, в зависимости от приложение. Например, в приложении proof-of-stake, таком как концентратор Cosmos, право голоса может определяться сумма staking tokens, переданная в качестве залога. ПРИМЕЧАНИЕ. Такие дроби, как ⅔ и ⅓, относятся к долям общего числа голосов. мощность, а не общее количество validator, если только не все validator. иметь равный вес. >⅔ означает «более ⅔», ≥⅓ означает «по крайней мере ⅓». Tendermint — это частично синхронный консенсусный протокол BFT. получено на основе алгоритма консенсуса DLS [20]. Тендерминт - это

отличается своей простотой, производительностью и ответственностью за форк. Протокол требует yxed известного набора validators, где каждый validator идентифицируется по открытому ключу. Валидаторы пытаются прийти к консенсусу по одному блоку за раз, где блок представляет собой список сделок. Голосование за консенсус по блоку продолжается в раунды. В каждом раунде есть лидер раунда или предлагающий, который предлагает блок. Затем validator поэтапно голосуют за то, будет ли принять предложенный блок или перейти к следующему раунду. предлагающий раунд выбирается детерминированно из заказанных список validators, пропорционально их голосу. Полная информация о протоколе описана здесь. Безопасность Tendermint основана на использовании оптимального византийского отказоустойчивость посредством голосования сверхбольшинством (>⅔) и блокировки механизм. Вместе они гарантируют, что: ≥⅓ голосов должно быть византийским, чтобы вызвать нарушение безопасность, где зафиксировано более двух значений. если какой-либо группе validator когда-либо удастся нарушить безопасность или даже попытки сделать это, они могут быть идентифицированы протоколом. Это включает в себя как голосование за составные блоки, так и трансляцию необоснованные голоса. Несмотря на свои серьезные гарантии, Tendermint обеспечивает исключительные производительность. В тестах 64 узла, распределенных по 7 центры обработки данных на 5 континентах, на обычных облачных экземплярах, Консенсус Tendermint может обрабатывать тысячи транзакций за во-вторых, с задержкой фиксации порядка одной-двух секунд. Примечательно, что производительность более тысячи транзакций в второе сохраняется даже в суровых противоборствующих условиях, при validator происходит сбой или трансляция злонамеренно созданных голосов. См. Подробности приведены на рисунке ниже.

Tendermint throughput vs block size benchmarked across 64 nodes in 7 datacenters on 5 continents

Основное преимущество алгоритма консенсуса Tendermint — простота. легкая безопасность клиентов, что делает его идеальным кандидатом для мобильных и Варианты использования Интернета вещей. Хотя легкий клиент Bitcoin должен синхронизироваться цепочки заголовков блоков и найти тот, у которого больше всего доказательств работы, легким клиентам Tendermint нужно только идти в ногу с изменениями в набор validator, а затем проверьте >⅔ PreCommits в последний блок для определения последнего состояния. Краткие легкие доказательства клиента также позволяют использовать inter-blockchain общение. В Tendermint предусмотрены защитные меры для предотвращения определенных заметные атаки, такие как двойные траты на большие расстояния по принципу «ничего не поставлено на карту» и цензура. Более подробно они обсуждаются в приложении.Алгоритм консенсуса Tendermint реализован в программа под названием Tendermint Core. Tendermint Core — это независимый от приложения «механизм консенсуса», который может превратить любую детерминированное приложение «черный ящик» в распределенно реплицируемую blockchain. Tendermint Core подключается к blockchain приложениям через интерфейс блокчейна приложения (ABCI) [17]. Таким образом, ABCI позволяет программировать blockchain приложений в любом язык, а не только язык программирования, на котором существует консенсус engine. Кроме того, ABCI позволяет легко замените уровень консенсуса любого существующего стека blockchain. Проведем аналогию с известной криптовалютой Bitcoin. Bitcoin — это криптовалюта blockchain, в которой каждый узел поддерживает полностью проверенная база данных вывода неизрасходованных транзакций (UTXO). Если хотелось создать систему, подобную Bitcoin, поверх ABCI, Tendermint Core будет отвечать за Совместное использование блоков и транзакций между узлами Установление канонического/неизменяемого порядка транзакций ( blockchain) Между тем, приложение ABCI будет отвечать за Ведение базы данных UTXO Проверка криптографических подписей транзакций Предотвращение траты транзакций на несуществующие средства Разрешение клиентам запрашивать базу данных UTXO Tendermint может разложить дизайн blockchain по предлагая очень простой API между процессом приложения и процесс консенсуса.

Cosmos Architecture

Cosmos Architecture

Cosmos is a network of independent parallel blockchains that are each powered by classical BFT consensus algorithms like Tendermint 1. The yrst blockchain in this network will be the Cosmos Hub. The Cosmos Hub connects to many other blockchains (or zones) via a novel inter-blockchain communication protocol. The Cosmos Hub tracks numerous token types and keeps record of the total number of tokens in each connected zone. Tokens can be transferred from one zone to another securely and quickly without the need for a liquid exchange between zones, because all inter-zone coin transfers go through the Cosmos Hub. This architecture solves many problems that the blockchain space faces today, such as application interoperability, scalability, and seamless upgradability. For example, zones derived from Bitcoind, Go-Ethereum, CryptoNote, ZCash, or any blockchain system can be plugged into the Cosmos Hub. These zones allow Cosmos to scale inynitely to meet global transaction demand. Zones are also a great yt for a distributed exchange, which will be supported as well. Cosmos is not just a single distributed ledger, and the Cosmos Hub isn’t a walled garden or the center of its universe. We are designing a protocol for an open network of distributed ledgers that can serve as a new foundation for future ynancial systems, based on principles of cryptography, sound economics, consensus theory, transparency, and accountability. The Cosmos Hub is the yrst public blockchain in the Cosmos Network, powered by Tendermint’s BFT consensus algorithm. The Tendermint open-source project was born in 2014 to address the speed, scalability, and environmental issues of Bitcoin’s proof-ofwork consensus algorithm. By using and improving upon proven

BFT algorithms developed at MIT in 1988 [20], the Tendermint team was the yrst to conceptually demonstrate a proof-of-stake cryptocurrency that addresses the nothing-at-stake problem suffered by yrst-generation proof-of-stake cryptocurrencies such as NXT and BitShares1.0. Today, practically all Bitcoin mobile wallets use trusted servers to provide them with transaction veriycation. This is because proofof-work requires waiting for many conyrmations before a transaction can be considered irreversibly committed. Doublespend attacks have already been demonstrated on services like CoinBase. Unlike other blockchain consensus systems, Tendermint offers instant and provably secure mobile-client payment veriycation. Since the Tendermint is designed to never fork at all, mobile wallets can receive instant transaction conyrmation, which makes trustless and practical payments a reality on smartphones. This has signiycant ramiycations for Internet of Things applications as well. Validators in Cosmos have a similar role to Bitcoin miners, but instead use cryptographic signatures to vote. Validators are secure, dedicated machines that are responsible for committing blocks. Non-validators can delegate their staking tokens (called “atoms”) to any validator to earn a portion of block fees and atom rewards, but they incur the risk of getting punished (slashed) if the delegate validator gets hacked or violates the protocol. The proven safety guarantees of Tendermint BFT consensus, and the collateral deposit of stakeholders–validators and delegators–provide provable, quantiyable security for nodes and light clients. Distributed public ledgers should have a constitution and a governance system. Bitcoin relies on the Bitcoin Foundation and

mining to coordinate upgrades, but this is a slow process. Ethereum split into ETH and ETC after hard-forking to address TheDAO hack, largely because there was no prior social contract nor mechanism for making such decisions. Validators and delegators on the Cosmos Hub can vote on proposals that can change preset parameters of the system automatically (such as the block gas limit), coordinate upgrades, as well as vote on amendments to the human-readable constitution that govern the policies of the Cosmos Hub. The constitution allows for cohesion among the stakeholders on issues such as theft and bugs (such as TheDAO incident), allowing for quicker and cleaner resolution. Each zone can also have their own constitution and governance mechanism as well. For example, the Cosmos Hub could have a constitution that enforces immutability at the Hub (no roll-backs, save for bugs of the Cosmos Hub node implementation), while each zone can set their own policies regarding roll-backs. By enabling interoperability among differing policy zones, the Cosmos network gives its users ultimate freedom and potential for permissionless experimentation. Here we describe a novel model of decentralization and scalability. Cosmos is a network of many blockchains powered by Tendermint. While existing proposals aim to create a “single blockchain” with total global transaction ordering, Cosmos permits many blockchains to run concurrently with one another while retaining interoperability. At the basis, the Cosmos Hub manages many independent blockchains called “zones” (sometimes referred to as “shards”, in reference to the database scaling technique known as “sharding”).

A constant stream of recent block commits from zones posted on the Hub allows the Hub to keep up with the state of each zone. Likewise, each zone keeps up with the state of the Hub (but zones do not keep up with each other except indirectly through the Hub). Packets of information are then communicated from one zone to another by posting Merkle-proofs as evidence that the information was sent and received. This mechanism is called inter-blockchain communication, or IBC for short. Any of the zones can themselves be hubs to form an acyclic graph, but for the sake of clarity we will only describe the simple conyguration where there is only one hub, and many non-hub zones. The Cosmos Hub is a blockchain that hosts a multi-asset distributed ledger, where tokens can be held by individual users or by zones themselves. These tokens can be moved from one zone to another in a special IBC packet called a "coin packet". The hub is responsible for preserving the global invariance of the total amount of each token across the zones. IBC coin packet transactions must be committed by the sender, hub, and receiver blockchains.

Cosmos hub and zones architecture showing the Cosmos Hub connecting multiple independent zones via IBC

Since the Cosmos Hub acts as the central ledger for the whole system, the security of the Hub is of paramount importance. While each zone may be a Tendermint blockchain that is secured by as few as 4 (or even less if BFT consensus is not needed), the Hub must be secured by a globally decentralized set of validators that can withstand the most severe attack scenarios, such as a continental network partition or a nation-state sponsored attack. A Cosmos zone is an independent blockchain that exchanges IBC messages with the Hub. From the Hub’s perspective, a zone is a multi-asset dynamic-membership multi-signature account that can send and receive tokens using IBC packets. Like a cryptocurrency account, a zone cannot transfer more tokens than it has, but can receive tokens from others who have them. A zone may be designated as an "source" of one or more token types, granting it the power to inzate that token supply. Atoms of the Cosmos Hub may be staked by validators of a zone connected to the Hub. While double-spend attacks on these zones would result in the slashing of atoms with Tendermint’s forkaccountability, a zone where \(> 2/3\) of the voting power are Byzantine can commit invalid state. The Cosmos Hub does not verify or execute transactions committed on other zones, so it is the responsibility of users to send tokens to zones that they trust. In the future, the Cosmos Hub’s governance system may pass Hub improvement proposals that account for zone failures. For example, outbound token transfers from some (or all) zones may be throttled to allow for the emergency circuit-breaking of zones (a temporary halt of token transfers) when an attack is detected. Now we look at how the Hub and zones communicate with each other. For example, if there are three blockchains, “Zone1”, “Zone2”,

and “Hub”, and we wish for "Zone1" to produce a packet destined for “Zone2” going through “Hub”. To move a packet from one blockchain to another, a proof is posted on the receiving chain. The proof states that the sending chain published a packet for the alleged destination. For the receiving chain to check this proof, it must be able keep up with the sender’s block headers. This mechanism is similar to that used by sidechains, which requires two interacting chains to be aware of one another via a bidirectional stream of proof-of-existence datagrams (transactions). The IBC protocol can naturally be deyned using two types of transactions: an  IBCBlockCommitTx  transaction, which allows a blockchain to prove to any observer of its most recent block-hash, and an  IBCPacketTx  transaction, which allows a blockchain to prove to any observer that the given packet was indeed published by the sender’s application, via a Merkle-proof to the recent block-hash. By splitting the IBC mechanics into two separate transactions, we allow the native fee market-mechanism of the receiving chain to determine which packets get committed (i.e. acknowledged), while allowing for complete freedom on the sending chain as to how many outbound packets are allowed. In the example above, in order to update the block-hash of "Zone1" on “Hub” (or of “Hub” on “Zone2”), an  IBCBlockCommitTx

transaction must be posted on “Hub” with the block-hash of “Zone1” (or on "Zone2" with the block-hash of “Hub”). See IBCBlockCommitTx and IBCPacketTx for for more information on the two IBC transaction types. In the same way that Bitcoin is more secure by being a distributed, mass-replicated ledger, we can make exchanges less vulnerable to external and internal hacks by running it on the blockchain. We call this a distributed exchange. What the cryptocurrency community calls a decentralized exchange today are based on something called “atomic crosschain” (AXC) transactions. With an AXC transaction, two users on two different chains can make two transfer transactions that are committed together on both ledgers, or none at all (i.e. atomically). For example, two users can trade bitcoins for ether (or any two tokens on two different ledgers) using AXC transactions, even though Bitcoin and Ethereum are not connected to each other. The beneyt of running an exchange on AXC transactions is that neither users need to trust each other or the trade-matching service. The downside is that both parties need to be online for the trade to occur. Another type of decentralized exchange is a mass-replicated distributed exchange that runs on its own blockchain. Users on this kind of exchange can submit a limit order and turn their computer off, and the trade can execute without the user being online. The blockchain matches and completes the trade on behalf of the trader.

Cosmos Архитектура

Cosmos — это сеть независимых параллельных blockchain, которые каждый из них основан на классических алгоритмах консенсуса BFT, таких как Тендерминт 1. Первым blockchain в этой сети будет концентратор Cosmos. Cosmos Хаб подключается ко многим другим blockchain (или зонам) через новый протокол связи между blockchain. Концентратор Cosmos отслеживает многочисленные типы token и ведет учет общего количества количество tokens в каждой подключенной зоне. Токены могут быть безопасно и быстро переносить из одной зоны в другую без необходимости обмена жидкостью между зонами, поскольку все межзональные переводы монет проходят через концентратор Cosmos. Эта архитектура решает многие проблемы, с которыми сталкивается пространство blockchain. сегодняшние проблемы, такие как совместимость приложений, масштабируемость и возможность бесшовной модернизации. Например, зоны, производные от Bitcoind, Go-Ethereum, CryptoNote, ZCash или любая другая система blockchain может быть подключен к концентратору Cosmos. Эти зоны позволяют Cosmos бесконечно масштабироваться для удовлетворения глобального спроса на транзакции. Зоны также отличный вариант для распределенного обмена, который будет поддерживаться как ну. Cosmos — это не просто один распределенный реестр, а Cosmos Хаб — это не огороженный сад и не центр вселенной. Мы разработка протокола для открытой сети распределенных реестров которые могут послужить новой основой для будущих финансовых систем, основанный на принципах криптографии, разумной экономики, консенсуса теория, прозрачность и подотчетность. Хаб Cosmos является первым общедоступным blockchain в PH_0005. Сеть, основанная на алгоритме консенсуса BFT Tendermint. Проект с открытым исходным кодом Tendermint родился в 2014 году для решения скорость, масштабируемость и экологические проблемы алгоритма консенсуса доказательства работы Bitcoin. Используя и совершенствуя проверенные

BFT алгоритмы, разработанные в Массачусетском технологическом институте в 1988 году [20], Tendermint команда была первой, кто концептуально продемонстрировал proof-of-stake криптовалюта, которая решает проблему «ничего на кону» пострадали от криптовалют proof-of-stake первого поколения, таких как как NXT и BitShares1.0. Сегодня практически все мобильные кошельки Bitcoin используют доверенные серверы для предоставить им проверку транзакции. Это связано с тем, что доказательство работы требует ожидания множества подтверждений, прежде чем транзакция может считаться необратимо совершенной. Атаки двойной траты уже были продемонстрированы на таких сервисах, как CoinBase. В отличие от других консенсусных систем blockchain, Tendermint предлагает Мгновенная и доказуемо безопасная проверка платежей мобильного клиента. Поскольку Tendermint вообще никогда не разветвляется, мобильные кошельки могут получать мгновенное подтверждение транзакции, что делает надежные и практичные платежи – реальность на смартфонах. Это имеет значительные последствия для приложений Интернета вещей, поскольку ну. Валидаторы в Cosmos выполняют аналогичную роль майнерам Bitcoin, но вместо этого используйте криптографические подписи для голосования. Валидаторы безопасные, выделенные машины, которые отвечают за совершение блоки. Лица, не validator, могут делегировать свои staking token (называемые «атомы») любому validator, чтобы заработать часть комиссий за блок и атом награды, но они подвергаются риску быть наказанными (урезанными), если делегат validator взломан или нарушает протокол. Проверенный гарантии безопасности консенсуса Tendermint BFT и сопутствующие депозит заинтересованных сторон – validator и делегаторов – обеспечивают доказуемая, количественная безопасность для узлов и легких клиентов. Распределенные публичные реестры должны иметь конституцию и система управления. Bitcoin опирается на Фонд Bitcoin имайнинг для координации обновлений, но это медленный процесс. Ethereum разделился на ETH и ETC после хард-форка по адресу Взлом DAO, в основном потому, что не было предварительного общественного договора. ни механизма принятия таких решений. Валидаторы и делегаты в хабе Cosmos могут голосовать за предложения, позволяющие изменить заданные параметры системы автоматически (например, лимит газа блока), координировать обновления, как а также голосовать по поправкам в удобочитаемую конституцию которые регулируют политику Cosmos Hub. Конституция позволяет обеспечить сплоченность заинтересованных сторон по таким вопросам, как кражи и ошибки (например, инцидент TheDAO), что позволяет быстрее и более чистое разрешение. Каждая зона также может иметь свою собственную конституцию и управление. механизм тоже. Например, концентратор Cosmos может иметь конституция, которая обеспечивает неизменность в Хабе (без откатов, за исключением ошибок реализации узла концентратора Cosmos), в то время как каждая зона может устанавливать свою собственную политику в отношении откатов. Обеспечивая совместимость между различными зонами политики, Сеть Cosmos предоставляет своим пользователям максимальную свободу и возможности для несанкционированные эксперименты. Здесь мы описываем новую модель децентрализации и масштабируемости. Cosmos — это сеть из множества blockchain, работающих на Мята. Хотя существующие предложения направлены на создание «единой blockchain» с общим заказом глобальных транзакций, Cosmos позволяет многим blockchain работать одновременно друг с другом сохраняя при этом совместимость. По сути, хаб Cosmos управляет множеством независимых blockchains, называемые «зонами» (иногда называемые «осколками», в ссылка на метод масштабирования базы данных, известный как «шардинг»).

Постоянный поток последних коммитов блоков из зон, опубликованных на Hub позволяет Hub отслеживать состояние каждой зоны. Аналогично, каждая зона следит за состоянием Хаба (но зоны не идти в ногу друг с другом, кроме как косвенно через Хаб). Пакеты информации затем передаются от одного зону другому, разместив доказательства Меркла в качестве доказательства того, что информация была отправлена и получена. Этот механизм называется связь между blockchain или сокращенно IBC. Любая из зон сама может быть хабом для формирования ациклического графа. но для ясности мы опишем только простое конфигурация, в которой есть только один концентратор и множество неконцентраторов зоны. Хаб Cosmos — это blockchain, на котором размещено несколько активов. распределенный реестр, в котором token могут храниться отдельными пользователями или по самим зонам. Эти token можно переместить из одной зоны. другому в специальном пакете IBC, называемом «пакет монет». Концентратор ответственный за сохранение глобальной инвариантности полной количество каждого token в зонах. IBC пачка монет транзакции должны быть зафиксированы отправителем, концентратором и получателем blockchainс.Поскольку Cosmos Hub действует как центральный реестр для всего системы, безопасность Хаба имеет первостепенное значение. Пока каждая зона может представлять собой Tendermint blockchain, защищенный всего 4 (или даже меньше, если консенсус BFT не требуется), Hub должен быть защищен глобально децентрализованным набором validator, который может противостоять самым серьезным сценариям атак, таким как раздел континентальной сети или атака, спонсируемая национальным государством. Зона Cosmos — это независимая зона blockchain, которая обменивается IBC. сообщения с помощью Hub. С точки зрения Хаба, зона — это учетная запись с несколькими подписями и динамическим членством, которая может отправлять и получать token, используя пакеты IBC. Как криптовалютный счет, зона не может перевести более tokens, чем он имеет, но может получать token от других, у которых они есть. Зона может быть обозначен как «источник» одного или нескольких типов token, предоставив ему возможность инзацировать этот источник token. Атомы Cosmos Hub могут быть застейканы validators зоны подключен к хабу. В то время как атаки двойного расходования на эти зоны приведет к разделению атомов с помощью системы подотчетности Tendermint, зоны, в которой > ⅔ голосов Византийский может совершить недействительное состояние. Концентратор Cosmos не поддерживает проверять или выполнять транзакции, совершенные в других зонах, поэтому ответственность пользователей отправлять token в зоны, которым они доверяют. В будущем система управления Cosmos Hub может пройти мимо Hub. предложения по улучшению, учитывающие сбои зон. Для например, исходящие переводы token из некоторых (или всех) зон могут регулироваться для обеспечения аварийного отключения зон (временная остановка передачи token) при обнаружении атаки. Теперь посмотрим, как Хаб и зоны общаются друг с другом. другое. Например, если есть три blockchain: «Зона1», «Зона2»,

Cosmos hub and zones architecture showing the Cosmos Hub connecting multiple independent zones via IBC

и «Хаб», и мы хотим, чтобы «Зона 1» создавала пакет, предназначенный для «Зоны 2» через «Хаб». Чтобы переместить пакет из одного blockchain другому, доказательство отправляется в принимающую цепочку. Доказательство гласит, что передающая цепочка опубликовала пакет для предполагаемое место назначения. Чтобы принимающая цепочка могла проверить это доказательство, она должен быть в состоянии успевать за заголовками блоков отправителя. Это механизм аналогичен тому, который используется в сайдчейнах, что требует две взаимодействующие цепи, чтобы знать друг о друге через двунаправленный поток датаграмм подтверждения существования (транзакции). Протокол IBC естественным образом может быть разработан с использованием двух типов транзакции: транзакция  IBCBlockCommitTx , которая позволяет blockchain, чтобы доказать любому наблюдателю свой последний блок - hash, и транзакция  IBCPacketTx , которая позволяет blockchain доказать любому наблюдателю, что данный пакет действительно был опубликован приложением отправителя, через доказательство Меркла к недавнему блок-hash. Разделив механику IBC на две отдельные транзакции, мы позволить внутреннему рыночному механизму комиссий принимающей цепочки определить, какие пакеты будут зафиксированы (т.е. подтверждены), в то время как предоставляя полную свободу в цепочке отправки относительно того, как разрешено много исходящих пакетов. В приведенном выше примере для обновления блока hash «Zone1» на «Hub» (или «Hub» на «Zone2»), IBCBlockCommitTxтранзакция должна быть размещена на «Хабе» с блоком hash «Зона1» (или «Зона2» с блоком hash «Хаба»). Дополнительную информацию см. в IBCBlockCommitTx и IBCPacketTx. для двух типов транзакций IBC. Точно так же, как Bitcoin более безопасен, поскольку является распределенным, массово тиражируемый реестр, мы можем сделать биржи менее уязвимыми для внешние и внутренние хаки, запустив его на blockchain. Мы назовите это распределенным обменом. То, что криптовалютное сообщество называет децентрализованным сегодняшние обмены основаны на так называемых транзакциях «атомной кроссчейн» (AXC). При транзакции AXC два пользователя на две разные цепочки могут совершать две транзакции перевода, которые зафиксировано одновременно в обоих реестрах или не зафиксировано вообще (т. е. атомарно). Например, два пользователя могут обменять биткойны на эфир (или любые два token в двух разных реестрах) с использованием транзакций AXC, хотя Bitcoin и Ethereum не подключены друг к другу другое. Преимущество обмена транзакциями AXC заключается в что ни пользователям не нужно доверять друг другу, ни системе сопоставления сделок. сервис. Обратной стороной является то, что обе стороны должны быть онлайн для торговля произойдет. Другой тип децентрализованной биржи — это массово тиражируемая биржа. распределенный обмен, работающий самостоятельно blockchain. Пользователи на этот вид биржи может подать лимитный ордер и развернуть свои компьютер выключен, и сделка может выполняться без участия пользователя. онлайн. blockchain соответствует и завершает сделку от имени трейдера.

Applications

Applications

A centralized exchange can create a deep orderbook of limit orders and thereby attract more traders. Liquidity begets more liquidity in the exchange world, and so there is a strong network effect (or at least a winner-take-most effect) in the exchange business. The current leader for cryptocurrency exchanges today is Poloniex with a 24-hour volume of $20M, and in second place is Bitynex with a 24-hour volume of $5M. Given such strong network effects, it is unlikely for AXC-based decentralized exchanges to win volume over the centralized exchanges. For a decentralized exchange to compete with a centralized exchange, it would need to support deep orderbooks with limit orders. Only a distributed exchange on a blockchain can provide that. Tendermint provides additional beneyts of faster transaction commits. By prioritizing fast ynality without sacriycing consistency, zones in Cosmos can ynalize transactions fast – for both exchange order transactions as well as IBC token transfers to and from other zones. Given the state of cryptocurrency exchanges today, a great application for Cosmos is the distributed exchange (aka the Cosmos DEX). The transaction throughput capacity as well as commit latency can be comparable to those of centralized exchanges. Traders can submit limit orders that can be executed without both parties having to be online. And with Tendermint, the Cosmos hub, and IBC, traders can move funds in and out of the exchange to and from other zones with speed. A privileged zone can act as the source of a bridged token of another cryptocurrency. A bridge is similar to the relationship between a Cosmos hub and zone; both must keep up with the latest blocks of the other in order to verify proofs that tokens have moved from one to the other. A "bridge-zone" on the Cosmos network keeps up with the Hub as well as the other

cryptocurrency. The indirection through the bridge-zone allows the logic of the Hub to remain simple and agnostic to other blockchain consensus strategies such as Bitcoin’s proof-of-work mining. Each bridge-zone validator would run a Tendermint-powered blockchain with a special ABCI bridge-app, but also a full-node of the “origin” blockchain. When new blocks are mined on the origin, the bridge-zone validators will come to agreement on committed blocks by signing and sharing their respective local view of the origin’s blockchain tip. When a bridge-zone receives payment on the origin (and sufycient conyrmations were agreed to have been seen in the case of a PoW chain such as Ethereum or Bitcoin), a corresponding account is created on the bridge-zone with that balance. In the case of Ethereum, the bridge-zone can share the same validator-set as the Cosmos Hub. On the Ethereum side (the origin), a bridge-contract would allow ether holders to send ether to the bridge-zone by sending it to the bridge-contract on Ethereum. Once ether is received by the bridge-contract, the ether cannot be withdrawn unless an appropriate IBC packet is received by the bridge-contract from the bridge-zone. The bridge-contract tracks the validator-set of the bridge-zone, which may be identical to the Cosmos Hub’s validator-set. In the case of Bitcoin, the concept is similar except that instead of a single bridge-contract, each UTXO would be controlled by a threshold multisignature P2SH pubscript. Due to the limitations of the P2SH system, the signers cannot be identical to the Cosmos Hub validator-set.

Ether on the bridge-zone (“bridged-ether”) can be transferred to and from the Hub, and later be destroyed with a transaction that sends it to a particular withdrawal address on Ethereum. An IBC packet proving that the transaction occurred on the bridge-zone can be posted to the Ethereum bridge-contract to allow the ether to be withdrawn. In the case of Bitcoin, the restricted scripting system makes it difycult to mirror the IBC coin-transfer mechanism. Each UTXO has its own independent pubscript, so every UTXO must be migrated to a new UTXO when there is a change in the set of Bitcoin escrow signers. One solution is to compress and decompress the UTXO-set as necessary to keep the total number of UTXOs down. The risk of such a bridgeging contract is a rogue validator set. \(\geq 1/3\) Byzantine voting power could cause a fork, withdrawing ether from the bridge-contract on Ethereum while keeping the bridgedether on the bridge-zone. Worse, \(> 2/3\) Byzantine voting power can steal ether outright from those who sent it to the bridge-contract by deviating from the original bridgeging logic of the bridge-zone. It is possible to address these issues by designing the bridge to be totally accountable. For example, all IBC packets, from the hub and the origin, might require acknowledgement by the bridge-zone in such a way that all state transitions of the bridge-zone can be efyciently challenged and veriyed by either the hub or the origin’s bridge-contract. The Hub and the origin should allow the bridgezone validators to post collateral, and token transfers out of the bridge-contract should be delayed (and collateral unbonding period sufyciently long) to allow for any challenges to be made by independent auditors. We leave the design of the speciycation and implementation of this system open as a future Cosmos

improvement proposal, to be passed by the Cosmos Hub’s governance system. Solving the scaling problem is an open issue for Ethereum. Currently, Ethereum nodes process every single transaction and also store all the states. link. Since Tendermint can commit blocks much faster than Ethereum’s proof-of-work, EVM zones powered by Tendermint consensus and operating on bridged-ether can provide higher performance to Ethereum blockchains. Additionally, though the Cosmos Hub and IBC packet mechanics does not allow for arbitrary contract logic execution per se, it can be used to coordinate token movements between Ethereum contracts running on different zones, providing a foundation for token-centric Ethereum scaling via sharding. Cosmos zones run arbitrary application logic, which is deyned at the beginning of the zone’s life and can potentially be updated over time by governance. Such zexibility allows Cosmos zones to act as bridges to other cryptocurrencies such as Ethereum or Bitcoin, and it also permits derivatives of those blockchains, utilizing the same codebase but with a different validator set and initial distribution. This allows many existing cryptocurrency frameworks, such as those of Ethereum, Zerocash, Bitcoin, CryptoNote and so on, to be used with Tendermint Core, which is a higher performance consensus engine, on a common network, opening tremendous opportunity for interoperability across platforms. Furthermore, as a multi-asset blockchain, a single transaction may contain multiple inputs and outputs, where each input can be any token type, enabling Cosmos to serve directly as a platform for decentralized exchange, though orders are assumed

to be matched via other platforms. Alternatively, a zone can serve as a distributed fault-tolerant exchange (with orderbooks), which can be a strict improvement over existing centralized cryptocurrency exchanges which tend to get hacked over time. Zones can also serve as blockchain-backed versions of enterprise and government systems, where pieces of a particular service that are traditionally run by an organization or group of organizations are instead run as a ABCI application on a certain zone, which allows it to inherit the security and interoperability of the public Cosmos network without sacriycing control over the underlying service. Thus, Cosmos may offer the best of both worlds for organizations looking to utilize blockchain technology but who are wary of relinquishing control completely to a distributed third party. Some claim that a major problem with consistency-favouring consensus algorithms like Tendermint is that any network partition which causes there to be no single partition with \(> 2/3\) voting power (e.g. \(\geq 1/3\) going ofzine) will halt consensus altogether. The Cosmos architecture can help mitigate this problem by using a global hub with regional autonomous zones, where voting power for each zone are distributed based on a common geographic region. For instance, a common paradigm may be for individual cities, or regions, to operate their own zones while sharing a common hub (e.g. the Cosmos Hub), enabling municipal activity to persist in the event that the hub halts due to a temporary network partition. Note that this allows real geological, political, and network-topological features to be considered in designing robust federated fault-tolerant systems.

NameCoin was one of the yrst blockchains to attempt to solve the name-resolution problem by adapting the Bitcoin blockchain. Unfortunately there have been several issues with this approach. With Namecoin, we can verify that, for example, @satoshi was registered with a particular public key at some point in the past, but we wouldn’t know whether the public key had since been updated recently unless we download all the blocks since the last update of that name. This is due to the limitation of Bitcoin’s UTXO transaction Merkle-ization model, where only the transactions (but not mutable application state) are Merkle-ized into the block-hash. This lets us prove existence, but not the nonexistence of later updates to a name. Thus, we can’t know for certain the most recent value of a name without trusting a full node, or incurring signiycant costs in bandwidth by downloading the whole blockchain. Even if a Merkle-ized search tree were implemented in NameCoin, its dependency on proof-of-work makes light client veriycation problematic. Light clients must download a complete copy of the headers for all blocks in the entire blockchain (or at least all the headers since the last update to a name). This means that the bandwidth requirements scale linearly with the amount of time [21]. In addition, name-changes on a proof-of-work blockchain requires waiting for additional proof-of-work conyrmation blocks, which can take up to an hour on Bitcoin. With Tendermint, all we need is the most recent block-hash signed by a quorum of validators (by voting power), and a Merkle proof to the current value associated with the name. This makes it possible to have a succinct, quick, and secure light-client veriycation of name values. In Cosmos, we can take this concept and extend it further. Each name-registration zone in Cosmos can have an associated toplevel-domain (TLD) name such as “.com” or “.org”, and each name-

registration zone can have its own governance and registration rules.

Приложения

Централизованная биржа может создать глубокую книгу заказов с лимитами. заказов и тем самым привлечь больше трейдеров. Ликвидность порождает больше ликвидность в биржевом мире, поэтому существует сильная сеть эффект (или, по крайней мере, эффект «победитель получает большую часть») при обмене бизнес. Текущий лидер криптовалютных бирж сегодня находится Poloniex с 24-часовым объемом $20 млн, а на втором месте находится Bitynex с 24-часовым объемом в 5 миллионов долларов. Учитывая такую сильную сеть эффектов, маловероятно, что децентрализованные биржи на базе AXC выиграть объем над централизованными биржами. Для децентрализованного биржа, чтобы конкурировать с централизованной биржей, ей потребуется для поддержки глубоких книг заказов с лимитными ордерами. Только распределенный обмен на blockchain может это обеспечить. Tendermint обеспечивает дополнительные преимущества более быстрой транзакции. совершает. Отдавая приоритет быстрой динамичности, не жертвуя при этом согласованность, зоны в Cosmos могут быстро анализировать транзакции – для как транзакции обменных заказов, так и переводы IBC token на и из других зон. Учитывая сегодняшнее состояние криптовалютных бирж, отличный приложение для Cosmos — это распределенный обмен (он же Cosmos DEX). Пропускная способность транзакций, а также задержка фиксации может быть сравнима с задержкой централизованного обмены. Трейдеры могут отправлять лимитные ордера, которые могут быть исполнены. без необходимости присутствия обеих сторон в сети. И с Тендерминтом, хаб Cosmos и IBC, трейдеры могут вводить и выводить средства быстрый обмен данными с другими зонами. Привилегированная зона может выступать в качестве источника мостового token еще одна криптовалюта. Мост похож на отношения между концентратором Cosmos и зоной; оба должны идти в ногу с последние блоки друг друга, чтобы проверить доказательства того, что tokens имеют перешел из одного в другой. «Мост-зона» на Cosmos. сеть не отстает от концентратора, а также от других

криптовалюта. Косвенное направление через зону моста позволяет логика Хаба должна оставаться простой и независимой от других blockchain консенсусные стратегии, такие как proof-of-work Bitcoin добыча полезных ископаемых. В каждой зоне моста validator будет работать сервер на базе Tendermint. blockchain со специальным мостовым приложением ABCI, а также с полным узлом «происхождение» blockchain. Когда в источнике добываются новые блоки, зона моста validators придут к соглашению о зафиксированных блоках, подписав и делятся своим местным мнением об источнике blockchain. совет. Когда мостовая зона получает платеж от источника (и было решено, что по делу были рассмотрены достаточные подтверждения цепочки PoW, например Ethereum или Bitcoin), соответствующий аккаунт создается в бридж-зоне с этим балансом. В случае Ethereum зона моста может использовать один и тот же validator — установлен как концентратор Cosmos. На стороне Ethereum ( origin), мостовой контракт позволит держателям эфира отправлять эфир в бридж-зону, отправив его в бридж-контракт на Ethereum. Как только эфир будет получен бридж-контрактом, эфир нельзя вывести, пока не будет получен соответствующий пакет IBC. полученные по бридж-контракту от бридж-зоны. Bridge-contract отслеживает набор validator зоны моста, который может быть идентичен набору validator концентратора Cosmos. В случае Bitcoin концепция аналогична, за исключением того, что вместо один мостовой контракт, каждый UTXO будет контролироваться пороговая мультиподпись P2SH. Из-за ограничений системе P2SH подписывающие стороны не могут быть идентичными Cosmos Ступица validator-комплект.Эфир в бридж-зоне («мостовой эфир») можно перевести на и из Хаба, а затем быть уничтожены с помощью транзакции, которая отправляет его на определенный адрес вывода средств Ethereum. IBC пакет, подтверждающий, что транзакция произошла в зоне моста может быть опубликован в мостовом контракте Ethereum, чтобы разрешить эфир быть отозванным. В случае Bitcoin система ограниченных сценариев делает это сложно отразить механизм перевода монет IBC. Каждый UTXO имеет свою собственную независимую публикацию, поэтому каждый UTXO должен быть перенесен на новый UTXO при изменении набора Bitcoin лица, подписавшие условное депонирование. Одним из решений является сжатие и распакуйте набор UTXO по мере необходимости, чтобы сохранить общее число из UTXOс не работает. Риск такого промежуточного контракта представляет собой мошеннический набор validator. ≥⅓ Византийское право голоса может вызвать форк, выводящий эфир из контракта о мосте на Ethereum, сохраняя при этом мост в зоне моста. Хуже того, более ⅔ византийского права голоса может украсть эфир начисто у тех, кто отправил его на бридж-контракт отклоняясь от исходной логики мостовой зоны. Решить эти проблемы можно, спроектировав мост так, чтобы он был полностью подотчетен. Например, все пакеты IBC от концентратора и происхождения, может потребоваться подтверждение со стороны мостовой зоны в таким образом, чтобы все переходы состояний мостовой зоны могли быть эффективно оспаривается и проверяется либо хабом, либо источником мост-контракт. Хаб и источник должны разрешить мостовой зоне validators размещать обеспечение, а token переводить из бридж-контракт должен быть отложен (и расторжение залога достаточно длительный период), чтобы можно было решать любые проблемы, независимые аудиторы. Мы оставляем дизайн спецификации и реализация этой системы открыта в будущем Cosmos

предложение по улучшению, которое должно быть принято Cosmos Hub система управления. Решение проблемы масштабирования является открытой проблемой для Ethereum. В настоящее время узлы Ethereum обрабатывают каждую транзакцию и также сохраните все состояния. связь. Поскольку Tendermint может фиксировать блоки намного быстрее, чем Ethereum Зоны proof-of-work, EVM, основанные на консенсусе Tendermint и работа на мостовом эфире может обеспечить более высокую производительность Ethereum blockchainс. Кроме того, хотя концентратор Cosmos и Механика пакетов IBC не допускает произвольной логики контракта исполнение как таковое, его можно использовать для координации token движений между Ethereum контрактами, работающими в разных зонах, обеспечивая основу для token-центричного Ethereum масштабирования с помощью шардинг. Зоны Cosmos выполняют произвольную логику приложения, которая определяется начало жизни зоны и потенциально может обновляться со временем правительством. Такая гибкость позволяет Cosmos зонам действовать как мосты к другим криптовалютам, таким как Ethereum или Bitcoin, а также допускает производные от этих blockchain, используя ту же кодовую базу, но с другим набором validator и первоначальное распространение. Это позволяет многим существующим криптовалютам фреймворки, такие как Ethereum, Zerocash, Bitcoin, CryptoNote и т. д. для использования с Tendermint Core, который механизм консенсуса с более высокой производительностью в общей сети, открывая огромные возможности для взаимодействия между платформы. Кроме того, в качестве мультиактива blockchain один транзакция может содержать несколько входов и выходов, где каждый ввод может быть любого типа token, что позволяет Cosmos служить непосредственно в качестве платформа для децентрализованного обмена, хотя заказы предполагаютсядля сопоставления через другие платформы. В качестве альтернативы зона может служить как распределенная отказоустойчивая биржа (с книгами заказов), которая может быть строгим улучшением по сравнению с существующими централизованными криптовалютные биржи, которые со временем часто подвергаются взлому. Зоны также могут служить blockchain версиями корпоративных и правительственные системы, где части конкретной услуги, которые традиционно управляются организацией или группой организаций вместо этого запускаются как приложение ABCI в определенной зоне, что позволяет ему унаследовать безопасность и совместимость общедоступных Cosmos сети, не жертвуя контролем над базовой сервис. Таким образом, Cosmos может предложить лучшее из обоих миров для организации, желающие использовать технологию blockchain, но которые опасаясь полностью передать контроль распределенной третьей стороне вечеринка. Некоторые утверждают, что основная проблема с обеспечением согласованности консенсусных алгоритмов, таких как Tendermint, заключается в том, что любая сеть раздел, из-за которого не существует ни одного раздела с размером >⅔ Количество голосов (например, выход из журнала ≥⅓) полностью остановит консенсус. Архитектура Cosmos может помочь смягчить эту проблему, используя глобальный центр с региональными автономными зонами, где право голоса для каждой зоны распределяются на основе общего географического регион. Например, общая парадигма может быть для отдельных города или регионы, чтобы управлять своими собственными зонами, разделяя при этом общий центр (например, Cosmos Hub), позволяющий муниципальной деятельности сохраняться в случае остановки хаба из-за временной неисправности сети перегородка. Обратите внимание, что это позволяет реальным геологическим, политическим и топологические особенности сети, которые следует учитывать при проектировании надежного федеративные отказоустойчивые системы.

NameCoin был одним из первых blockchain, попытавшихся решить проблема разрешения имен путем адаптации Bitcoin blockchain. К сожалению, при таком подходе возникло несколько проблем. С помощью Namecoin мы можем убедиться, что, например, @satoshi был зарегистрированный с определенным открытым ключом в какой-то момент в прошлом, но мы не будем знать, был ли с тех пор открытый ключ обновлено недавно, если мы не загрузим все блоки с момента последнего обновление этого имени. Это связано с ограничением Bitcoin UTXO транзакция Модель Мерклеизации, где только транзакции (но не изменяемое состояние приложения) являются меркловскими в блок-hash. Это позволяет нам доказать существование, а не несуществование более поздних обновлений имени. Таким образом, мы не можем знать, определить самое последнее значение имени, не доверяя полной узла или понести значительные затраты на пропускную способность из-за загрузки весь blockchain. Даже если бы в NameCoin было реализовано дерево поиска в стиле Меркла, его зависимость от proof-of-work упрощает проверку клиента проблематично. Легкие клиенты должны загрузить полную копию заголовки для всех блоков всего blockchain (или, по крайней мере, всех заголовки с момента последнего обновления имени). Это означает, что Требования к пропускной способности линейно масштабируются с течением времени [21]. Кроме того, имя меняется на proof-of-work blockchain. требует ожидания дополнительных блоков подтверждения proof-of-work, это может занять до часа на Bitcoin. В случае с Tendermint все, что нам нужно, это самый последний блок — hash. подписано кворумом в validators (по числу голосов) и членом Меркла подтверждение текущего значения, связанного с именем. Это делает это возможно иметь краткий, быстрый и безопасный легкий клиент проверка значений имени. В Cosmos мы можем взять эту концепцию и расширить ее. Каждый Зона регистрации имен в Cosmos может иметь связанное имя домена верхнего уровня (TLD), например «.com» или «.org», и каждое имя-

зона регистрации может иметь собственное управление и регистрацию правила.

Governance and Economics

Governance and Economics

While the Cosmos Hub is a multi-asset distributed ledger, there is a special native token called the atom. Atoms are the only staking token of the Cosmos Hub. Atoms are a license for the holder to vote, validate, or delegate to other validators. Like Ethereum’s ether, atoms can also be used to pay for transaction fees to mitigate spam. Additional inzationary atoms and block transaction fees are rewarded to validators and delegators who delegate to validators. The  BurnAtomTx  transaction can be used to recover any proportionate amount of tokens from the reserve pool. The initial distribution of atom tokens and validators on Genesis will go to the donors of the Cosmos Fundraiser (75%), lead donors (5%), Cosmos Network Foundation (10%), and ALL IN BITS, Inc (10%). From genesis onward, 1/3 of the total amount of atoms will be rewarded to bonded validators and delegators every year. See the Cosmos Plan for additional details. Unlike Bitcoin or other proof-of-work blockchains, a Tendermint blockchain gets slower with more validators due to the increased communication complexity. Fortunately, we can support enough validators to make for a robust globally distributed blockchain with very fast transaction conyrmation times, and, as bandwidth,

storage, and parallel compute capacity increases, we will be able to support more validators in the future. On genesis day, the maximum number of validators will be set to 100, and this number will increase at a rate of 13% for 10 years, and settle at 300 validators. Atom holders who are not already can become validators by signing and submitting a  BondTx  transaction. The amount of atoms provided as collateral must be nonzero. Anyone can become a validator at any time, except when the size of the current validator set is greater than the maximum number of validators allowed. In that case, the transaction is only valid if the amount of atoms is greater than the amount of effective atoms held by the smallest validator, where effective atoms include delegated atoms. When a new validator replaces an existing validator in such a way, the existing validator becomes inactive and all the atoms and delegated atoms enter the unbonding state. There must be some penalty imposed on the validators for any intentional or unintentional deviation from the sanctioned protocol. Some evidence is immediately admissible, such as a double-sign at the same height and round, or a violation of Year 0: 100  Year 1: 113  Year 2: 127  Year 3: 144  Year 4: 163  Year 5: 184  Year 6: 208  Year 7: 235  Year 8: 265  Year 9: 300  Year 10: 300  ...

“prevote-the-lock” (a rule of the Tendermint consensus protocol). Such evidence will result in the validator losing its good standing and its bonded atoms as well its proportionate share of tokens in the reserve pool – collectively called its “stake” – will get slashed. Sometimes, validators will not be available, either due to regional network disruptions, power failure, or other reasons. If, at any point in the past  ValidatorTimeoutWindow  blocks, a validator’s commit vote is not included in the blockchain more than  ValidatorTimeoutMaxAbsent  times, that validator will become inactive, and lose  ValidatorTimeoutPenalty  (DEFAULT 1%) of its stake. Some “malicious” behavior does not produce obviously discernable evidence on the blockchain. In these cases, the validators can coordinate out of band to force the timeout of these malicious validators, if there is a supermajority consensus. In situations where the Cosmos Hub halts due to a \(\geq 1/3\) coalition of voting power going ofzine, or in situations where a \(\geq 1/3\) coalition of voting power censor evidence of malicious behavior from entering the blockchain, the hub must recover with a hard-fork reorg-proposal. (Link to “Forks and Censorship Attacks”). Cosmos Hub validators can accept any token type or combination of types as fees for processing a transaction. Each validator can subjectively set whatever exchange rate it wants, and choose whatever transactions it wants, as long as the  BlockGasLimit  is not exceeded. The collected fees, minus any taxes speciyed below, are redistributed to the bonded stakeholders in proportion to their bonded atoms, every  ValidatorPayoutPeriod  (DEFAULT 1 hour).

Of the collected transaction fees,  ReserveTax  (DEFAULT 2%) will go toward the reserve pool to increase the reserve pool and increase the security and value of the Cosmos network. These funds can also be distributed in accordance with the decisions made by the governance system. Atom holders who delegate their voting power to other validators pay a commission to the delegated validator. The commission can be set by each validator. The security of the Cosmos Hub is a function of the security of the underlying validators and the choice of delegation by delegators. In order to encourage the discovery and early reporting of found vulnerabilities, the Cosmos Hub encourages hackers to publish successful exploits via a  ReportHackTx  transaction that says, “This validator got hacked. Please send bounty to this address”. Upon such an exploit, the validator and delegators will become inactive,  HackPunishmentRatio  (default 5%) of everyone’s atoms will get slashed, and  HackRewardRatio  (default 5%) of everyone’s atoms will get rewarded to the hacker’s bounty address. The validator must recover the remaining atoms by using their backup key. In order to prevent this feature from being abused to transfer unvested atoms, the portion of vested vs unvested atoms of validators and delegators before and after the  ReportHackTx  will remain the same, and the hacker bounty will include some unvested atoms, if any. The Cosmos Hub is operated by a distributed organization that requires a well-deyned governance mechanism in order to coordinate various changes to the blockchain, such as the variable

parameters of the system, as well as software upgrades and constitutional amendments. All validators are responsible for voting on all proposals. Failing to vote on a proposal in a timely manner will result in the validator being deactivated automatically for a period of time called the  AbsenteeismPenaltyPeriod  (DEFAULT 1 week). Delegators automatically inherit the vote of the delegated validator. This vote may be overridden manually. Unbonded atoms get no vote. Each proposal requires a deposit of  MinimumProposalDeposit  tokens, which may be a combination of one or more tokens including atoms. For each proposal, the voters may vote to take the deposit. If more than half of the voters choose to take the deposit (e.g. because the proposal was spam), the deposit goes to the reserve pool, except any atoms which are burned. For each proposal, voters may vote with the following options: Yea YeaWithForce Nay NayWithForce Abstain A strict majority of Yea or YeaWithForce votes (or Nay or NayWithForce votes) is required for the proposal to be decided as passed (or decided as failed), but 1/3+ can veto the majority decision by voting “with force”. When a strict majority is vetoed, everyone gets punished by losing  VetoPenaltyFeeBlocks  (DEFAULT 1 day’s worth of blocks) worth of fees (except taxes which will not be affected), and the party that vetoed the majority

decision will be additionally punished by losing  VetoPenaltyAtoms  (DEFAULT 0.1%) of its atoms. Any of the parameters deyned here can be changed with the passing of a  ParameterChangeProposal . Atoms can be inzated and reserve pool funds spent with the passing of a  BountyProposal . All other proposals, such as a proposal to upgrade the protocol, will be coordinated via the generic  TextProposal . See the Plan. There have been many innovations in blockchain consensus and scalability in the past couple of years. This section provides a brief survey of a select number of important ones. Consensus in the presence of malicious participants is a problem dating back to the early 1980s, when Leslie Lamport coined the phrase “Byzantine fault” to refer to arbitrary process behavior that deviates from the intended behavior, in contrast to a “crash fault”, wherein a process simply crashes. Early solutions were discovered for synchronous networks where there is an upper bound on

message latency, though practical use was limited to highly controlled environments such as airplane controllers and datacenters synchronized via atomic clocks. It was not until the late 90s that Practical Byzantine Fault Tolerance (PBFT) [11] was introduced as an efycient partially synchronous consensus algorithm able to tolerate up to ⅓ of processes behaving arbitrarily. PBFT became the standard algorithm, spawning many variations, including most recently one created by IBM as part of their contribution to Hyperledger. The main beneyt of Tendermint consensus over PBFT is that Tendermint has an improved and simpliyed underlying structure, some of which is a result of embracing the blockchain paradigm. Tendermint blocks must commit in order, which obviates the complexity and communication overhead associated with PBFT’s view-changes. In Cosmos and many cryptocurrencies, there is no need to allow for block N+i where i >= 1 to commit, when block N itself hasn’t yet committed. If bandwidth is the reason why block N hasn’t committed in a Cosmos zone, then it doesn’t help to use bandwidth sharing votes for blocks N+i. If a network partition or ofzine nodes is the reason why block N hasn’t committed, then N+i won’t commit anyway. In addition, the batching of transactions into blocks allows for regular Merkle-hashing of the application state, rather than periodic digests as with PBFT’s checkpointing scheme. This allows for faster provable transaction commits for light-clients and faster inter-blockchain communication. Tendermint Core also includes many optimizations and features that go above and beyond what is speciyed in PBFT. For example, the blocks proposed by validators are split into parts, Merkle-ized, and gossipped in such a way that improves broadcasting performance (see LibSwift [19] for inspiration). Also, Tendermint Core doesn’t make any assumption about point-to-point

connectivity, and functions for as long as the P2P network is weakly connected. While not the yrst to deploy proof-of-stake (PoS), BitShares1.0 [12] contributed considerably to research and adoption of PoS blockchains, particularly those known as “delegated” PoS. In BitShares, stake holders elect "witnesses", responsible for ordering and committing transactions, and "delegates", responsible for coordinating software updates and parameter changes. BitShares2.0 aims to achieve high performance (100k tx/s, 1s latency) in ideal conditions, with each block signed by a single signer, and transaction ynality taking quite a bit longer than the block interval. A canonical speciycation is still in development. Stakeholders can remove or replace misbehaving witnesses on a daily basis, but there is no signiycant collateral of witnesses or delegators in the likeness of Tendermint PoS that get slashed in the case of a successful double-spend attack. Building on an approach pioneered by Ripple, Stellar [13] reyned a model of Federated Byzantine Agreement wherein the processes participating in consensus do not constitute a yxed and globally known set. Rather, each process node curates one or more “quorum slices”, each constituting a set of trusted processes. A “quorum” in Stellar is deyned to be a set of nodes that contain at least one quorum slice for each node in the set, such that agreement can be reached. The security of the Stellar mechanism relies on the assumption that the intersection of any two quorums is non-empty, while the availability of a node requires at least one of its quorum slices to consist entirely of correct nodes, creating a trade-off between using large or small quorum-slices that may be difycult to balance without imposing signiycant assumptions about trust. Ultimately,

nodes must somehow choose adequate quorum slices for there to be sufycient fault-tolerance (or any “intact nodes” at all, of which much of the results of the paper depend on), and the only provided strategy for ensuring such a conyguration is hierarchical and similar to the Border Gateway Protocol (BGP), used by toptier ISPs on the internet to establish global routing tables, and by that used by browsers to manage TLS certiycates; both notorious for their insecurity. The criticism in the Stellar paper of the Tendermint-based proofof-stake systems is mitigated by the token strategy described here, wherein a new type of token called the atom is issued that represent claims to future portions of fees and rewards. The advantage of Tendermint-based proof-of-stake, then, is its relative simplicity, while still providing sufycient and provable security guarantees. BitcoinNG is a proposed improvement to Bitcoin that would allow for forms of vertical scalability, such as increasing the block size, without the negative economic consequences typically associated with such a change, such as the disproportionately large impact on small miners. This improvement is achieved by separating leader election from transaction broadcast: leaders are yrst elected by proof-of-work in “micro-blocks”, and then able to broadcast transactions to be committed until a new micro-block is found. This reduces the bandwidth requirements necessary to win the PoW race, allowing small miners to more fairly compete, and allowing transactions to be committed more regularly by the last miner to ynd a micro-block. Casper [16] is a proposed proof-of-stake consensus algorithm for Ethereum. Its prime mode of operation is “consensus-by-bet”. By letting validators iteratively bet on which block they believe will

become committed into the blockchain based on the other bets that they have seen so far, ynality can be achieved eventually. link. This is an active area of research by the Casper team. The challenge is in constructing a betting mechanism that can be proven to be an evolutionarily stable strategy. The main beneyt of Casper as compared to Tendermint may be in offering “availability over consistency” – consensus does not require a \(> 2/3\) quorum of voting power – perhaps at the cost of commit speed or implementation complexity. The Interledger Protocol [14] is not strictly a scalability solution. It provides an ad hoc interoperation between different ledger systems through a loosely coupled bilateral relationship network. Like the Lightning Network, the purpose of ILP is to facilitate payments, but it speciycally focuses on payments across disparate ledger types, and extends the atomic transaction mechanism to include not only hash-locks, but also a quorum of notaries (called the Atomic Transport Protocol). The latter mechanism for enforcing atomicity in inter-ledger transactions is similar to Tendermint’s light-client SPV mechanism, so an illustration of the distinction between ILP and Cosmos/IBC is warranted, and provided below. 1. The notaries of a connector in ILP do not support membership changes, and do not allow for zexible weighting between notaries. On the other hand, IBC is designed speciycally for blockchains, where validators can have different weights, and where membership can change over the course of the blockchain. 2. As in the Lightning Network, the receiver of payment in ILP must be online to send a conyrmation back to the sender. In a

token transfer over IBC, the validator-set of the receiver’s blockchain is responsible for providing conyrmation, not the receiving user. 3. The most striking difference is that ILP’s connectors are not responsible or keeping authoritative state about payments, whereas in Cosmos, the validators of a hub are the authority of the state of IBC token transfers as well as the authority of the amount of tokens held by each zone (but not the amount of tokens held by each account within a zone). This is the fundamental innovation that allows for secure asymmetric transfer of tokens from zone to zone; the analog to ILP’s connector in Cosmos is a persistent and maximally secure blockchain ledger, the Cosmos Hub. 4. The inter-ledger payments in ILP need to be backed by an exchange orderbook, as there is no asymmetric transfer of coins from one ledger to another, only the transfer of value or market equivalents. Sidechains [15] are a proposed mechanism for scaling the Bitcoin network via alternative blockchains that are “two-way pegged” to the Bitcoin blockchain. (Two-way pegging is equivalent to bridging. In Cosmos we say "bridging" to distinguish from marketpegging). Sidechains allow bitcoins to effectively move from the Bitcoin blockchain to the sidechain and back, and allow for experimentation in new features on the sidechain. As in the Cosmos Hub, the sidechain and Bitcoin serve as light-clients of each other, using SPV proofs to determine when coins should be transferred to the sidechain and back. Of course, since Bitcoin uses proof-of-work, sidechains centered around Bitcoin suffer from the many problems and risks of proof-of-work as a consensus mechanism. Furthermore, this is a Bitcoin-maximalist solution that doesn’t natively support a variety of tokens and

inter-zone network topology as Cosmos does. That said, the core mechanism of the two-way peg is in principle the same as that employed by the Cosmos network. Ethereum is currently researching a number of different strategies to shard the state of the Ethereum blockchain to address scalability needs. These efforts have the goal of maintaining the abstraction layer offered by the current Ethereum Virtual Machine across the shared state space. Multiple research efforts are underway at this time. [18][22] Cosmos and Ethereum 2.0 Mauve [22] have different design goals. Cosmos is speciycally about tokens. Mauve is about scaling general computation. Cosmos is not bound to the EVM, so even different VMs can interoperate. Cosmos lets the zone creator determine who validates the zone. Anyone can start a new zone in Cosmos (unless governance decides otherwise). The hub isolates zone failures so global token invariants are preserved. The Lightning Network is a proposed token transfer network operating at a layer above the Bitcoin blockchain (and other public blockchains), enabling improvement of many orders of magnitude in transaction throughput by moving the majority of transactions outside of the consensus ledger into so-called “payment channels”.

This is made possible by on-chain cryptocurrency scripts, which enable parties to enter into bilateral stateful contracts where the state can be updated by sharing digital signatures, and contracts can be closed by ynally publishing evidence onto the blockchain, a mechanism yrst popularized by cross-chain atomic swaps. By opening payment channels with many parties, participants in the Lightning Network can become focal points for routing the payments of others, leading to a fully connected payment channel network, at the cost of capital being tied up on payment channels. While the Lightning Network can also easily extend across multiple independent blockchains to allow for the transfer of value via an exchange market, it cannot be used to asymmetrically transfer tokens from one blockchain to another. The main beneyt of the Cosmos network described here is to enable such direct token transfers. That said, we expect payment channels and the Lightning Network to become widely adopted along with our token transfer mechanism, for cost-saving and privacy reasons. Segregated Witness is a Bitcoin improvement proposal link that aims to increase the per-block transaction throughput 2X or 3X, while simultaneously making block syncing faster for new nodes. The brilliance of this solution is in how it works within the limitations of Bitcoin’s current protocol and allows for a soft-fork upgrade (i.e. clients with older versions of the software will continue to function after the upgrade). Tendermint, being a new protocol, has no design restrictions, so it has a different scaling priorities. Primarily, Tendermint uses a BFT round-robin algorithm based on cryptographic signatures instead of mining, which trivially allows horizontal scaling through multiple parallel blockchains, while regular, more frequent block commits allow for vertical scaling as well.

Управление и экономика

Хотя Cosmos Hub представляет собой распределенный реестр с несколькими активами, существует особый природный объект token, называемый атомом. Атомы — единственные staking token узла Cosmos. Атомы — это лицензия для владельца на голосуйте, подтверждайте или делегируйте полномочия другим validator. Нравится Ethereum эфира, атомы также можно использовать для оплаты комиссий за транзакции уменьшить спам. Дополнительные инзационные атомы и блочная транзакция гонорары вознаграждаются validator и делегаторов, делегирующих полномочия validatorс. Транзакция  BurnAtomTx  может использоваться для восстановления любого пропорциональная сумма tokens из резервного пула. Первоначальное распределение атомов tokens и validators в книге Бытия. пойдут донорам Cosmos Сбора средств (75%), ведущие доноры (5%), Cosmos Network Foundation (10%) и ALL IN BITS, Inc. (10%). Начиная с зарождения, 1/3 общего количества атомов будет будут вознаграждены связанным validator и делегатам каждый год. Дополнительные сведения см. в плане Cosmos. В отличие от Bitcoin или других proof-of-work blockchain, Tendermint blockchain становится медленнее при увеличении количества validator из-за увеличения сложность общения. К счастью, мы можем поддержать достаточно validators для создания надежного глобально распределенного blockchain с очень быстрым временем подтверждения транзакций и, что касается пропускной способности,

хранилища и увеличится мощность параллельных вычислений, мы сможем для поддержки большего количества validator в будущем. В день создания максимальное количество validator будет установлено равным 100, и это число будет увеличиваться со скоростью 13% в течение 10 лет, и расчет на уровне 300 validators. Владельцы атомов, которые еще этого не сделали, могут стать validators путем подписание и отправка транзакции  BondTx . Сумма атомы, предоставленные в качестве залога, должны быть ненулевыми. Любой может стать validator в любое время, за исключением случаев, когда размер текущего Набор validator превышает максимальное количество validator. разрешено. В этом случае сделка действительна только в том случае, если сумма атомов больше, чем количество эффективных атомов, удерживаемых наименьший validator, где эффективные атомы включают делегированные атомы. Когда новый validator заменяет существующий validator таким образом, существующий validator становится неактивным, и все атомы и делегированные атомы переходят в состояние разъединения. На validators должен быть наложен какой-то штраф за любое умышленное или неумышленное отклонение от санкционированного протокол. Некоторые доказательства являются допустимыми сразу, например, двойной знак на одной и той же высоте и витке, либо нарушение Год 0: 100  Год 1: 113  Год 2: 127  Год 3: 144  Год 4: 163  Год 5: 184  Год 6: 208  Год 7: 235  Год 8: 265  Год 9: 300  10 год: 300  ...

«prevote-the-lock» (правило консенсусного протокола Tendermint). Подобные доказательства приведут к потере validator своей хорошей репутации. и его связанные атомы, а также его пропорциональную долю tokens в резервный пул, который в совокупности называется «долей», будет сокращен. Иногда validator будут недоступны либо из-за региональных сбои в сети, сбой питания или другие причины. Если в любой момент точка в прошлых блоках  ValidatorTimeoutWindow , validator голосование за принятие не включено в blockchain более чем  ValidatorTimeoutMaxAbsent  раз, то validator станет неактивен и теряет  ValidatorTimeoutPenalty  (ПО УМОЛЧАНИЮ 1 %) ставка. Некоторые «злонамеренные» действия не приводят к явно различимым последствиям. доказательства по делу blockchain. В этих случаях validator могут координировать внеполосные действия, чтобы принудительно отключить эти вредоносные validators, если существует консенсус сверхбольшинства. В ситуациях, когда хаб Cosmos останавливается из-за коалиции ≥⅓ количество голосов теряется в журнале или в ситуациях, когда коалиция ≥⅓ Цензура голосов, свидетельствующая о злонамеренном поведении со стороны входя в blockchain, хаб должен восстановиться с помощью хард-форка реорг-предложение. (Ссылка на «Форки и цензурные атаки»). Cosmos Концентратор validators может принимать любой тип token или комбинацию типов в качестве комиссий за обработку транзакции. Каждый validator может субъективно установить любой обменный курс, который он хочет, и выбрать любые транзакции, которые он хочет, при условии, что  BlockGasLimit  не превышен. Собранные сборы за вычетом любых налогов, указанных ниже, перераспределяются среди связанных стейкхолдеров пропорционально их связанные атомы, каждый  ValidatorPayoutPeriod  (ПО УМОЛЧАНИЮ 1 час).Из собранной комиссии за транзакцию  ReserveTax  (ПО УМОЛЧАНИЮ 2%) будет идите к резервному пулу, чтобы увеличить резервный пул и повысить безопасность и ценность сети Cosmos. Эти средства также могут распределяться в соответствии с решениями производится системой управления. Владельцы атомов, которые делегируют свое право голоса другим validator. выплатить комиссию делегированному validator. Комиссия может устанавливается каждым validator. Безопасность хаба Cosmos является функцией безопасности лежащие в основе validators и выбор делегирования делегирующими лицами. Чтобы стимулировать обнаружение и раннее сообщение о найденных уязвимостей, хаб Cosmos призывает хакеров публиковать успешные эксплойты через транзакцию  ReportHackTx , в которой говорится: «Этот validator был взломан. Пожалуйста, пришлите награду на этот адрес». После такой эксплойт, validator и делегаторы станут неактивными,  HackPunishmentRatio  (по умолчанию 5%) всех атомов получит сокращено, а  HackRewardRatio  (по умолчанию 5%) всех атомов получит вознаграждение на баунти-адрес хакера. validator должен восстановить оставшиеся атомы, используя их резервный ключ. Чтобы предотвратить злоупотребление этой функцией для передачи неинвестированные атомы, доля наделенных и неинвестированных атомов validators и делегаторы до и после  ReportHackTx  будут останется прежним, а награда за хакера будет включать в себя некоторые нераспределенные атомы, если таковые имеются. Хаб Cosmos управляется распределенной организацией, которая требует хорошо продуманного механизма управления, чтобы координировать различные изменения в blockchain, например переменную

параметры системы, а также обновления программного обеспечения и конституционные поправки. Все validator несут ответственность за голосование по всем предложениям. Не удалось Своевременное голосование по предложению приведет к validator автоматически деактивируется на период времени, называемый  Прогул на штрафной период (ПО УМОЛЧАНИЮ 1 неделя). Делегаторы автоматически наследуют голоса делегированных validator. Это голосование может быть отменено вручную. Несвязанные атомы не получить голоса. Для каждого предложения требуется внести депозит в размере MinimumProposalDeposit.  token, которые могут представлять собой комбинацию одного или нескольких token. включая атомы. По каждому предложению избиратели могут проголосовать за принятие депозит. Если более половины избирателей выберут депозит (например, потому что предложение было спамом), депозит переходит на резервный пул, за исключением сгоревших атомов. По каждому предложению избиратели могут голосовать следующими вариантами: Да ДаСфорс Нет NayWithForce Воздерживаться Строгое большинство голосов за или YeaWithForce (или против, или голосов NayWithForce) требуется для того, чтобы предложение было принято как принято (или решено как проваленное), но 1/3+ могут наложить вето на большинство решение путем голосования «принудительным». Когда строгое большинство накладывает вето, все будут наказаны потерей  VetoPenaltyFeeBlocks  (ПО УМОЛЧАНИЮ блоков за 1 день) стоимость сборов (кроме налогов которая не будет затронута), и партия, наложившая вето на большинство

решение будет дополнительно наказано потерей  VetoPenaltyAtoms  (ПО УМОЛЧАНИЮ 0,1%) его атомов. Любой из определенных здесь параметров можно изменить с помощью передача  ParameterChangeProposal. Атомы можно интегрировать и резервировать средства пула, потраченные с помощью принятие  BountyProposal. Все остальные предложения, такие как предложение по обновлению протокола, будет координироваться с помощью общего  TextProposal . См. План. В консенсусе blockchain было много нововведений и масштабируемость за последние пару лет. В этом разделе представлено краткое обзор избранного числа важных из них. Консенсус в присутствии злонамеренных участников является проблемой восходит к началу 1980-х годов, когда Лесли Лэмпорт придумал фраза «Византийская ошибка» относится к произвольному поведению процесса, которое отклоняется от запланированного поведения, в отличие от «аварии», при этом процесс просто аварийно завершает работу. Были обнаружены ранние решения для синхронных сетей, где существует верхняя границазадержка сообщения, хотя практическое использование было ограничено высокой контролируемые среды, такие как диспетчеры самолетов и центры обработки данных синхронизируются с помощью атомных часов. Так было до тех пор, пока В конце 90-х годов «Практическая византийская отказоустойчивость» (PBFT) PH_0000 была представлен как эффективный частично синхронный консенсус алгоритм, способный выдерживать поведение до ⅓ процессов произвольно. PBFT стал стандартным алгоритмом, породив множество вариации, включая самый последний, созданный IBM в рамках их вклад в Hyperledger. Основное преимущество консенсуса Tendermint по сравнению с PBFT заключается в том, что Tendermint имеет улучшенную и упрощенную базовую структуру. некоторые из них являются результатом принятия парадигмы blockchain. Блоки Tendermint должны фиксироваться по порядку, что позволяет избежать сложность и накладные расходы на связь, связанные с PBFT просмотр-изменения. В Cosmos и многих криптовалютах нет необходимо разрешить блок N+i, где i >= 1, для фиксации, когда блок N сама еще не взяла на себя обязательства. Если пропускная способность является причиной блокировки N не совершил коммит в зоне Cosmos, то использование не поможет голосование за разделение полосы пропускания для блоков N+i. Если сетевой раздел или узлы журнала являются причиной того, что блок N не зафиксировался, тогда Н+я в любом случае не буду брать на себя обязательства. Кроме того, группировка транзакций в блоки позволяет регулярное Merkle-hash состояние приложения, а не периодические дайджесты, как в схеме контрольных точек PBFT. Это позволяет для более быстрого и доказуемого подтверждения транзакций для легких клиентов и более быстрого меж-blockchain связь. Tendermint Core также включает в себя множество оптимизаций и функций. которые выходят за рамки того, что указано в PBFT. Например, блоки, предложенные validators, разделены на части, Меркле-изированы, и сплетничали таким образом, чтобы улучшить вещание производительность (для вдохновения см. LibSwift [19]). А еще Тендерминт Core не делает никаких предположений о двухточечном соединении.

возможность подключения и работает до тех пор, пока работает P2P-сеть. слабо связан. Хотя BitShares1.0 [12] не является первым развертыванием proof-of-stake (PoS), внес значительный вклад в исследование и внедрение PoS blockchain, особенно те, которые известны как «делегированные» PoS. В BitShares, заинтересованные стороны выбирают «свидетелей», ответственных за оформление заказа и совершение транзакций, а также «делегаты», ответственные за координация обновлений программного обеспечения и изменений параметров. BitShares2.0 нацелен на достижение высокой производительности (100 тыс. транзакций в секунду, 1 с). задержка) в идеальных условиях, когда каждый блок подписан одним подписывающему лицу, а качество транзакции занимает немного больше времени, чем интервал блока. Каноническая спецификация все еще находится в разработке. Заинтересованные стороны могут удалить или заменить свидетелей, плохо себя ведущих ежедневно, но нет существенного залога в виде свидетелей или делегаты по подобию Tendermint PoS, которые врезаются в случае успешной атаки двойной траты. Опираясь на подход, впервые предложенный Ripple, Stellar [13] Рейнед модель Федеративного Византийского соглашения, в которой процессы участие в консенсусе не представляют собой фиксированного и глобального известный набор. Скорее, каждый узел процесса курирует один или несколько «куски кворума», каждый из которых представляет собой набор доверенных процессов. А «Кворум» в Stellar определяется как набор узлов, содержащих хотя бы один срез кворума для каждого узла в наборе, такой, что соглашение может быть достигнуто. Безопасность механизма Stellar основана на предположении что пересечение любых двух кворумов непусто, а доступность узла требует, чтобы хотя бы один из его срезов кворума был полностью состоять из правильных узлов, создавая компромисс между использование больших или малых фрагментов кворума, которые может быть сложно сбалансировать без навязывания существенных предположений о доверии. В конечном счете,узлы должны каким-то образом выбрать адекватные фрагменты кворума, чтобы иметь достаточную отказоустойчивость (или вообще любые «неповреждённые узлы», из которых от этого зависит большая часть результатов статьи), и единственное предоставленная стратегия обеспечения иерархичности такой конфигурации и похож на протокол пограничного шлюза (BGP), используемый интернет-провайдерами высшего уровня для создания глобальных таблиц маршрутизации, а также который используется браузерами для управления сертификатами TLS; оба печально известные из-за их неуверенности. Критика в статье Stellar систем доказательства доли на основе Tendermint смягчается описанной стратегией token. здесь выдается новый тип token, называемый атомом, который представляют собой претензии на будущие части гонораров и вознаграждений. Таким образом, преимущество proof-of-stake на основе Tendermint является его относительным простота, но при этом обеспечивает достаточную и доказуемую безопасность гарантии. BitcoinNG — это предлагаемое улучшение Bitcoin, которое позволит для форм вертикальной масштабируемости, таких как увеличение размера блока, без негативных экономических последствий, обычно связанных с с таким изменением, таким как непропорционально большое влияние на мелких майнерах. Это улучшение достигается за счет разделения выборы лидера из трансляции транзакций: лидеры впервые избранный proof-of-work в «микроблоках», а затем имеющий возможность широковещательные транзакции, которые будут зафиксированы до появления нового микроблока найден. Это снижает требования к полосе пропускания, необходимые для выиграть гонку PoW, что позволит мелким майнерам более честно конкурировать, и разрешить более регулярное совершение транзакций со стороны последний майнер, нашедший микроблок. Casper [16] — это предложенный алгоритм консенсуса proof-of-stake для Ethereum. Его основной режим работы – «консенсус за ставкой». Автор позволяя validators итеративно делать ставки на то, какой блок, по их мнению, будет

стать приверженцем blockchain на основании других ставок что они видели до сих пор, инальность может быть достигнута в конечном итоге. связь. Это активная область исследований команды Casper. Задача состоит в создании механизма ставок, который можно было бы оказалась эволюционно стабильной стратегией. Основная польза от Casper по сравнению с Tendermint может предлагать «доступность» чрезмерная последовательность» – для достижения консенсуса не требуется кворум >⅔ количество голосов – возможно, за счет скорости принятия решений или сложность реализации. Протокол Interledger [14] не является строго решением масштабируемости. Это обеспечивает специальное взаимодействие между различными реестрами системы через слабосвязанную сеть двусторонних отношений. Как и в случае с Lightning Network, цель ILP – облегчить платежи, но он специально фокусируется на платежах по разным типы реестров и расширяет механизм атомарных транзакций для включать не только hash-замки, но и кворум нотариусов (так называемый «Атомный транспортный протокол»). Последний механизм для обеспечение атомарности в транзакциях между реестрами аналогично Механизм SPV легкого клиента Tendermint, поэтому иллюстрация различие между ILP и Cosmos/IBC гарантировано, и представлено ниже. 1. Нотариусы коннектора в ILP не поддерживают членство изменения и не допускают гибкого взвешивания между нотариусы. С другой стороны, IBC разработан специально для blockchains, где validators могут иметь разные веса, и где членство может меняться в течение blockchain. 2. Как и в Lightning Network, получатель платежа в ILP должен быть онлайн, чтобы отправить подтверждение отправителю. Вtoken передача через IBC, набор validator получателя За предоставление подтверждения отвечает blockchain, а не принимающий пользователь. 3. Самое поразительное отличие заключается в том, что разъемы ILP не ответственное или авторитетное государство в отношении платежей, тогда как в Cosmos validator концентратора являются полномочиями состояние IBC token передается, а также полномочия количество tokens, удерживаемое каждой зоной (но не количество tokens принадлежат каждой учетной записи в зоне). Это фундаментальная инновация, позволяющая обеспечить безопасную асимметричную перенос tokens из зоны в зону; аналог ILP соединитель в Cosmos — это постоянный и максимально безопасный blockchain реестр, концентратор Cosmos. 4. Платежи между реестрами в рамках ILP должны быть подкреплены биржевой стакан заявок, так как нет асимметричной передачи монеты из одного реестра в другой, только передача стоимости или рыночные эквиваленты. Сайдчейны [15] — это предлагаемый механизм масштабирования Bitcoin. сеть через альтернативные blockchain, которые «двусторонне привязаны» к Bitcoin blockchain. (Двусторонняя привязка эквивалентна мост. В Cosmos мы говорим «мост», чтобы отличить его от рыночной привязки). Сайдчейны позволяют биткойнам эффективно перемещаться из Bitcoin blockchain в сайдчейн и обратно, а также разрешить экспериментирование с новыми функциями сайдчейна. Как и в Cosmos Хаб, сайдчейн и Bitcoin служат лёгкими клиентами друг друга, используя доказательства SPV, чтобы определить, когда монеты должны быть переносится в сайдчейн и обратно. Конечно, поскольку Bitcoin использует proof-of-work, страдают сайдчейны, сосредоточенные вокруг Bitcoin. от многих проблем и рисков proof-of-work как механизм консенсуса. Кроме того, это Bitcoin-максималист решение, которое изначально не поддерживает различные token и

топология межзоновой сети, как это делает Cosmos. Тем не менее, ядро механизм двусторонней привязки в принципе такой же, как и у работает в сети Cosmos. Ethereum в настоящее время исследует ряд различных стратегий. сегментировать состояние Ethereum blockchain по адресу потребности в масштабируемости. Эти усилия имеют целью поддержание уровень абстракции, предлагаемый текущей виртуальной машиной Ethereum через общее пространство состояний. Многочисленные исследовательские усилия в настоящее время ведется. [18][22] Cosmos и Ethereum 2.0 Сиреневый [22] преследуют разные цели дизайна. Cosmos конкретно относится к token. Mauve — это масштабирование общий расчет. Cosmos не привязан к EVM, поэтому даже разные виртуальные машины могут взаимодействовать. Cosmos позволяет создателю зоны определить, кто проверяет зона. Любой может создать новую зону в Cosmos (кроме случаев, когда управление решит иначе). Концентратор изолирует сбои зон, поэтому глобальные инварианты token сохранился. Lightning Network — это предлагаемая сеть передачи данных token. работающий на уровне выше Bitcoin blockchain (и других общедоступных blockchains), позволяющие улучшить ситуацию на многие порядки. в пропускной способности транзакций за счет перемещения большинства транзакций за пределы консенсусного реестра в так называемые «платёжные каналы».Это стало возможным благодаря внутрисетевым скриптам криптовалюты, которые позволяют сторонам заключать двусторонние договоры, предусматривающие статус государства, в которых состояние можно обновлять путем обмена цифровыми подписями и контрактами. можно закрыть, опубликовав доказательства на blockchain, Механизм впервые популяризировался посредством атомных свопов между цепочками. Автор открытие каналов оплаты со многими сторонами, участниками Lightning Network может стать центром маршрутизации платежи других, что приводит к полностью подключенному платежному каналу сети, за счет капитала, привязанного к платежным каналам. Хотя сеть Lightning также может легко распространяться на несколько независимых blockchain для обеспечения передачи стоимости через валютный рынок, его нельзя использовать для асимметричного перенести token с одного blockchain на другой. Основная польза описанной здесь сети Cosmos заключается в том, чтобы обеспечить такую прямую token переводы. Тем не менее, мы ожидаем, что каналы оплаты и Lightning Network получит широкое распространение вместе с нашей token механизм передачи, предназначенный для экономии средств и обеспечения конфиденциальности. Segregated Witness — это Bitcoin ссылка на предложение по улучшению, которая направлен на увеличение пропускной способности транзакций на блок в 2 или 3 раза, одновременно ускоряя синхронизацию блоков для новых узлов. Гениальность этого решения в том, как оно работает внутри ограничения текущего протокола Bitcoin и допускает софт-форк обновление (т. е. клиенты с более старыми версиями программного обеспечения будут продолжать работать после обновления). Tendermint — новый продукт протокол, не имеет конструктивных ограничений, поэтому имеет другое масштабирование приоритеты. В первую очередь, Tendermint использует алгоритм циклического перебора BFT. на основе криптографических подписей вместо майнинга, что тривиально позволяет горизонтальное масштабирование посредством нескольких параллельных blockchains, в то время как регулярные, более частые фиксации блоков позволяют вертикальное масштабирование.

Consensus and Technical Details

Consensus and Technical Details

A well designed consensus protocol should provide some guarantees in the event that the tolerance capacity is exceeded and the consensus fails. This is especially necessary in economic systems, where Byzantine behaviour can have substantial ynancial reward. The most important such guarantee is a form of forkaccountability, where the processes that caused the consensus to fail (ie. caused clients of the protocol to accept different values - a fork) can be identiyed and punished according to the rules of the protocol, or, possibly, the legal system. When the legal system is unreliable or excessively expensive to invoke, validators can be forced to make security deposits in order to participate, and those deposits can be revoked, or slashed, when malicious behaviour is detected [10]. Note this is unlike Bitcoin, where forking is a regular occurence due to network asynchrony and the probabilistic nature of ynding partial hash collisions. Since in many cases a malicious fork is indistinguishable from a fork due to asynchrony, Bitcoin cannot reliably implement fork-accountability, other than the implicit opportunity cost paid by miners for mining an orphaned block. We call the voting stages PreVote and PreCommit. A vote can be for a particular block or for Nil. We call a collection of \(> 2/3\) PreVotes for a single block in the same round a Polka, and a collection of \(> 2/3\) PreCommits for a single block in the same round a Commit. If \(> 2/3\) PreCommit for Nil in the same round, they move to the next round. Note that strict determinism in the protocol incurs a weak synchrony assumption as faulty leaders must be detected and

skipped. Thus, validators wait some amount of time, TimeoutPropose, before they Prevote Nil, and the value of TimeoutPropose increases with each round. Progression through the rest of a round is fully asynchronous, in that progress is only made once a validator hears from \(> 2/3\) of the network. In practice, it would take an extremely strong adversary to indeynitely thwart the weak synchrony assumption (causing the consensus to fail to ever commit a block), and doing so can be made even more difycult by using randomized values of TimeoutPropose on each validator. An additional set of constraints, or Locking Rules, ensure that the network will eventually commit just one block at each height. Any malicious attempt to cause more than one block to be committed at a given height can be identiyed. First, a PreCommit for a block must come with justiycation, in the form of a Polka for that block. If the validator has already PreCommit a block at round R_1, we say they are locked on that block, and the Polka used to justify the new PreCommit at round R_2 must come in a round R_polka where R_1 < R_polka <= R_2. Second, validators must Propose and/or PreVote the block they are locked on. Together, these conditions ensure that a validator does not PreCommit without sufycient evidence as justiycation, and that validators which have already PreCommit cannot contribute to evidence to PreCommit something else. This ensures both safety and liveness of the consensus algorithm. The full details of the protocol are described here. The need to sync all block headers is eliminated in TendermintPoS as the existence of an alternative chain (a fork) means \(\geq 1/3\) of bonded stake can be slashed. Of course, since slashing requires that someone share evidence of a fork, light clients should store any block-hash commits that it sees. Additionally, light clients

could periodically stay synced with changes to the validator set, in order to avoid long range attacks (but other solutions are possible). In spirit similar to Ethereum, Tendermint enables applications to embed a global Merkle root hash in each block, allowing easily veriyable state queries for things like account balances, the value stored in a contract, or the existence of an unspent transaction output, depending on the nature of the application. Assuming a sufyciently resilient collection of broadcast networks and a static validator set, any fork in the blockchain can be detected and the deposits of the offending validators slashed. This innovation, yrst suggested by Vitalik Buterin in early 2014, solves the nothing-at-stake problem of other proof-of-stake cryptocurrencies (see Related Work). However, since validator sets must be able to change, over a long range of time the original validators may all become unbonded, and hence would be free to create a new chain from the genesis block, incurring no cost as they no longer have deposits locked up. This attack came to be known as the Long Range Attack (LRA), in contrast to a Short Range Attack, where validators who are currently bonded cause a fork and are hence punishable (assuming a fork-accountable BFT algorithm like Tendermint consensus). Long Range Attacks are often thought to be a critical blow to proof-of-stake. Fortunately, the LRA can be mitigated as follows. First, for a validator to unbond (thereby recovering their collateral deposit and no longer earning fees to participate in the consensus), the deposit must be made untransferable for an amount of time known as the “unbonding period”, which may be on the order of weeks or months. Second, for a light client to be secure, the yrst time it connects to the network it must verify a recent block-hash against a trusted source, or preferably multiple sources. This

condition is sometimes referred to as “weak subjectivity”. Finally, to remain secure, it must sync up with the latest validator set at least as frequently as the length of the unbonding period. This ensures that the light client knows about changes to the validator set before a validator has its capital unbonded and thus no longer at stake, which would allow it to deceive the client by carrying out a long range attack by creating new blocks beginning back at a height where it was bonded (assuming it has control of sufyciently many of the early private keys). Note that overcoming the LRA in this way requires an overhaul of the original security model of proof-of-work. In PoW, it is assumed that a light client can sync to the current height from the trusted genesis block at any time simply by processing the proofof-work in every block header. To overcome the LRA, however, we require that a light client come online with some regularity to track changes in the validator set, and that the yrst time they come online they must be particularly careful to authenticate what they hear from the network against trusted sources. Of course, this latter requirement is similar to that of Bitcoin, where the protocol and software must also be obtained from a trusted source. The above method for preventing LRA is well suited for validators and full nodes of a Tendermint-powered blockchain because these nodes are meant to remain connected to the network. The method is also suitable for light clients that can be expected to sync with the network frequently. However, for light clients that are not expected to have frequent access to the internet or the blockchain network, yet another solution can be used to overcome the LRA. Non-validator token holders can post their tokens as collateral with a very long unbonding period (e.g. much longer than the unbonding period for validators) and serve light clients with a secondary method of attesting to the validity of current and past block-hashes. While these tokens do not count toward the security of the blockchain’s consensus, they nevertheless can

provide strong guarantees for light clients. If historical block-hash querying were supported in Ethereum, anyone could bond their tokens in a specially designed smart contract and provide attestation services for pay, effectively creating a market for lightclient LRA security. Due to the deynition of a block commit, any \(\geq 1/3\) coalition of voting power can halt the blockchain by going ofzine or not broadcasting their votes. Such a coalition can also censor particular transactions by rejecting blocks that include these transactions, though this would result in a signiycant proportion of block proposals to be rejected, which would slow down the rate of block commits of the blockchain, reducing its utility and value. The malicious coalition might also broadcast votes in a trickle so as to grind blockchain block commits to a near halt, or engage in any combination of these attacks. Finally, it can cause the blockchain to fork, by double-signing or violating the locking rules. If a globally active adversary were also involved, it could partition the network in such a way that it may appear that the wrong subset of validators were responsible for the slowdown. This is not just a limitation of Tendermint, but rather a limitation of all consensus protocols whose network is potentially controlled by an active adversary. For these types of attacks, a subset of the validators should coordinate through external means to sign a reorg-proposal that chooses a fork (and any evidence thereof) and the initial subset of validators with their signatures. Validators who sign such a reorgproposal forego their collateral on all other forks. Clients should verify the signatures on the reorg-proposal, verify any evidence, and make a judgement or prompt the end-user for a decision. For example, a phone wallet app may prompt the user with a security

warning, while a refrigerator may accept any reorg-proposal signed by +½ of the original validators by voting power. No non-synchronous Byzantine fault-tolerant algorithm can come to consensus when \(\geq 1/3\) of voting power are dishonest, yet a fork assumes that \(\geq 1/3\) of voting power have already been dishonest by double-signing or lock-changing without justiycation. So, signing the reorg-proposal is a coordination problem that cannot be solved by any non-synchronous protocol (i.e. automatically, and without making assumptions about the reliability of the underlying network). For now, we leave the problem of reorgproposal coordination to human coordination via social consensus on internet media. Validators must take care to ensure that there are no remaining network partitions prior to signing a reorgproposal, to avoid situations where two conzicting reorgproposals are signed. Assuming that the external coordination medium and protocol is robust, it follows that forks are less of a concern than censorship attacks. In addition to forks and censorship, which require \(\geq 1/3\) Byzantine voting power, a coalition of \(> 2/3\) voting power may commit arbitrary, invalid state. This is characteristic of any (BFT) consensus system. Unlike double-signing, which creates forks with easily veriyable evidence, detecting committment of an invalid state requires non-validating peers to verify whole blocks, which implies that they keep a local copy of the state and execute each transaction, computing the state root independently for themselves. Once detected, the only way to handle such a failure is via social consensus. For instance, in situations where Bitcoin has failed, whether forking due to software bugs (as in March 2013), or committing invalid state due to Byzantine behavior of miners (as in July 2015), the well connected community of businesses, developers, miners, and other organizations established a social consensus as to what manual actions were

required by participants to heal the network. Furthermore, since validators of a Tendermint blockchain may be expected to be identiyable, commitment of an invalid state may even be punishable by law or some external jurisprudence, if desired. ABCI consists of 3 primary message types that get delivered from the core to the application. The application replies with corresponding response messages. The  AppendTx  message is the work horse of the application. Each transaction in the blockchain is delivered with this message. The application needs to validate each transactions received with the AppendTx message against the current state, application protocol, and the cryptographic credentials of the transaction. A validated transaction then needs to update the application state — by binding a value into a key values store, or by updating the UTXO database. The  CheckTx  message is similar to AppendTx, but it’s only for validating transactions. Tendermint Core’s mempool yrst checks the validity of a transaction with CheckTx, and only relays valid transactions to its peers. Applications may check an incrementing nonce in the transaction and return an error upon CheckTx if the nonce is old. The  Commit  message is used to compute a cryptographic commitment to the current application state, to be placed into the next block header. This has some handy properties. Inconsistencies in updating that state will now appear as blockchain forks which catches a whole class of programming errors. This also simpliyes the development of secure lightweight clients, as Merkle-hash proofs can be veriyed by checking against the block-hash, and the block-hash is signed by a quorum of validators (by voting power).

Additional ABCI messages allow the application to keep track of and change the validator set, and for the application to receive the block information, such as the height and the commit votes. ABCI requests/responses are simple Protobuf messages. Check out the schema yle. Arguments: Data ([]byte) : The request transaction bytes Returns: Code (uint32) : Response code Data ([]byte) : Result bytes, if any Log (string) : Debug or error message Usage:

Append and run a transaction. If the transaction is valid, returns CodeType.OK Arguments: Data ([]byte) : The request transaction bytes Returns: Code (uint32) : Response code Data ([]byte) : Result bytes, if any Log (string) : Debug or error message Usage:

Validate a transaction. This message should not mutate the state. Transactions are yrst run through CheckTx before broadcast to peers in the mempool layer. You can make CheckTx semi-stateful and clear the state upon Commit or BeginBlock , to allow for dependent sequences of transactions in the same block.

Returns: Data ([]byte) : The Merkle root hash Log (string) : Debug or error message Usage:

Return a Merkle root hash of the application state. Arguments: Data ([]byte) : The query request bytes Returns: Code (uint32) : Response code Data ([]byte) : The query response bytes Log (string) : Debug or error message Usage:

Flush the response queue. Applications that implement types.Application need not implement this message – it’s handled by the project. Returns: Data ([]byte) : The info bytes Usage:

Return information about the application state. Application speciyc. Arguments: Key (string) : Key to set

Value (string) : Value to set for key Returns: Log (string) : Debug or error message Usage:

Set application options. E.g. Key=“mode”, Value=“mempool” for a mempool connection, or Key=“mode”, Value=“consensus” for a consensus connection. Other options are application speciyc. Arguments: Validators ([]Validator) : Initial genesis-validators Usage:

Called once upon genesis Arguments: Height (uint64) : The block height that is starting Usage:

Signals the beginning of a new block. Called prior to any AppendTxs. Arguments: Height (uint64) : The block height that ended Returns: Validators ([]Validator) : Changed validators with new voting powers (0 to remove) Usage:

Signals the end of a block. Called prior to each Commit after all transactions See the ABCI repository for more details.

There are several reasons why a sender may want the acknowledgement of delivery of a packet by the receiving chain. For example, the sender may not know the status of the destination chain, if it is expected to be faulty. Or, the sender may want to impose a timeout on the packet (with the  MaxHeight  packet yeld), while any destination chain may suffer from a denialof-service attack with a sudden spike in the number of incoming packets. In these cases, the sender can require delivery acknowledgement by setting the initial packet status to  AckPending . Then, it is the receiving chain’s responsibility to conyrm delivery by including an abbreviated  IBCPacket  in the app Merkle hash. First, an  IBCBlockCommit  and  IBCPacketTx  are posted on “Hub” that proves the existence of an  IBCPacket  on “Zone1”. Say that  IBCPacketTx  has the following value: FromChainID : “Zone1” FromBlockHeight : 100 (say) Packet : an IBCPacket :

Header : an IBCPacketHeader : SrcChainID : “Zone1” DstChainID : “Zone2” Number : 200 (say) Status : AckPending Type : “coin” MaxHeight : 350 (say “Hub” is currently at height 300) Payload : Next, an  IBCBlockCommit  and  IBCPacketTx  are posted on “Zone2” that proves the existence of an  IBCPacket  on “Hub”. Say that  IBCPacketTx  has the following value: FromChainID : “Hub” FromBlockHeight : 300 Packet : an IBCPacket : Header : an IBCPacketHeader : SrcChainID : “Zone1” DstChainID : “Zone2” Number : 200 Status : AckPending Type : “coin” MaxHeight : 350 Payload : Next, “Zone2” must include in its app-hash an abbreviated packet that shows the new status of  AckSent . An  IBCBlockCommit  and  IBCPacketTx  are posted back on “Hub” that proves the existence of an abbreviated  IBCPacket  on "Zone2". Say that  IBCPacketTx  has the following value: FromChainID : “Zone2”

FromBlockHeight : 400 (say) Packet : an IBCPacket : Header : an IBCPacketHeader : SrcChainID : “Zone1” DstChainID : “Zone2” Number : 200 Status : AckSent Type : “coin” MaxHeight : 350 PayloadHash : Finally, “Hub” must update the status of the packet from  AckPending  to  AckReceived . Evidence of this new ynalized status should go back to "Zone2". Say that  IBCPacketTx  has the following value: FromChainID : “Hub” FromBlockHeight : 301 Packet : an IBCPacket : Header : an IBCPacketHeader : SrcChainID : “Zone1” DstChainID : “Zone2” Number : 200 Status : AckReceived Type : “coin” MaxHeight : 350 PayloadHash : Meanwhile, “Zone1” may optimistically assume successful delivery of a "coin" packet unless evidence to the contrary is proven on “Hub”. In the example above, if “Hub” had not received an  AckSent

status from “Zone2” by block 350, it would have set the status automatically to  Timeout . This evidence of a timeout can get posted back on “Zone1”, and any tokens can be returned. There are two types of Merkle trees supported in the Tendermint/Cosmos ecosystem: The Simple Tree, and the IAVL+ Tree. The Simple Tree is a Merkle tree for a static list of elements. If the number of items is not a power of two, some leaves will be at different levels. Simple Tree tries to keep both sides of the tree the same height, but the left may be one greater. This Merkle tree is used to Merkle-ize the transactions of a block, and the top level elements of the application state root.

The purpose of the IAVL+ data structure is to provide persistent storage for key-value pairs in the application state such that a deterministic Merkle root hash can be computed efyciently. The tree is balanced using a variant of the AVL algorithm, and all operations are \(O(\log n)\). In an AVL tree, the heights of the two child subtrees of any node differ by at most one. Whenever this condition is violated upon an update, the tree is rebalanced by creating \(O(\log n)\) new nodes that point to unmodiyed nodes of the old tree. In the original AVL algorithm, inner nodes can also hold key-value pairs. The AVL+ algorithm (note the plus) modiyes the AVL algorithm to keep all values on leaf nodes, while only using branch-nodes to store keys. This simpliyes the algorithm while keeping the merkle hash trail short. The AVL+ Tree is analogous to Ethereum’s Patricia tries. There are tradeoffs. Keys do not need to be hashed prior to insertion in IAVL+ trees, so this provides faster ordered iteration in the key space which may beneyt some applications. The logic is simpler to implement, requiring only two types of nodes – inner nodes and leaf nodes. The Merkle proof is on average shorter, being a                 *                 / \               /     \             /         \           /             \          *               *         / \             / \        /   \           /   \       /     \         /     \      *       *       *       h6     / \     / \     / \    h0  h1  h2  h3  h4  h5    A SimpleTree with 7 elements

balanced binary tree. On the other hand, the Merkle root of an IAVL+ tree depends on the order of updates. We will support additional efycient Merkle trees, such as Ethereum’s Patricia Trie when the binary variant becomes available. In the canonical implementation, transactions are streamed to the Cosmos hub application via the ABCI interface. The Cosmos Hub will accept a number of primary transaction types, including  SendTx ,  BondTx ,  UnbondTx ,  ReportHackTx ,  SlashTx ,  BurnAtomTx ,  ProposalCreateTx , and  ProposalVoteTx , which are fairly self-explanatory and will be documented in a future revision of this paper. Here we document the two primary transaction types for IBC:  IBCBlockCommitTx  and  IBCPacketTx . An  IBCBlockCommitTx  transaction is composed of: ChainID (string) : The ID of the blockchain BlockHash ([]byte) : The block-hash bytes, the Merkle root which includes the app-hash BlockPartsHeader (PartSetHeader) : The block part-set header bytes, only needed to verify vote signatures BlockHeight (int) : The height of the commit BlockRound (int) : The round of the commit Commit ([]Vote) : The \(> 2/3\) Tendermint Precommit votes that comprise a block commit ValidatorsHash ([]byte) : A Merkle-tree root hash of the new validator set

ValidatorsHashProof (SimpleProof) : A SimpleTree Merkleproof for proving the ValidatorsHash against the BlockHash AppHash ([]byte) : A IAVLTree Merkle-tree root hash of the application state AppHashProof (SimpleProof) : A SimpleTree Merkle-proof for proving the AppHash against the BlockHash An  IBCPacket  is composed of: Header (IBCPacketHeader) : The packet header Payload ([]byte) : The bytes of the packet payload. Optional PayloadHash ([]byte) : The hash for the bytes of the packet. Optional Either one of  Payload  or  PayloadHash  must be present. The hash of an  IBCPacket  is a simple Merkle root of the two items,  Header  and  Payload . An  IBCPacket  without the full payload is called an abbreviated packet. An  IBCPacketHeader  is composed of: SrcChainID (string) : The source blockchain ID DstChainID (string) : The destination blockchain ID Number (int) : A unique number for all packets Status (enum) : Can be one of AckPending , AckSent , AckReceived , NoAck , or Timeout Type (string) : The types are application-dependent. Cosmos reserves the "coin" packet type MaxHeight (int) : If status is not NoAckWanted or AckReceived by this height, status becomes Timeout . Optional An  IBCPacketTx  transaction is composed of:

FromChainID (string) : The ID of the blockchain which is providing this packet; not necessarily the source FromBlockHeight (int) : The blockchain height in which the following packet is included (Merkle-ized) in the block-hash of the source chain Packet (IBCPacket) : A packet of data, whose status may be one of AckPending , AckSent , AckReceived , NoAck , or Timeout PacketProof (IAVLProof) : A IAVLTree Merkle-proof for proving the packet’s hash against the AppHash of the source chain at given height The sequence for sending a packet from “Zone1” to “Zone2” through the "Hub" is depicted in {Figure X}. First, an  IBCPacketTx  proves to "Hub" that the packet is included in the app-state of “Zone1”. Then, another  IBCPacketTx  proves to “Zone2” that the packet is included in the app-state of “Hub”. During this procedure, the  IBCPacket  yelds are identical: the  SrcChainID  is always “Zone1”, and the  DstChainID  is always "Zone2". The  PacketProof  must have the correct Merkle-proof path, as follows: When “Zone1” wants to send a packet to “Zone2” through “Hub”, the  IBCPacket  data are identical whether the packet is Merkleized on “Zone1”, the “Hub”, or “Zone2”. The only mutable yeld is  Status  for tracking delivery. We thank our friends and peers for assistance in conceptualizing, reviewing, and providing support for our work with Tendermint and Cosmos. IBC///

Zaki Manian of SkuChain provided much help in formatting and wording, especially under the ABCI section Jehan Tremback of Althea and Dustin Byington for helping with initial iterations Andrew Miller of Honey Badger for feedback on consensus Greg Slepak for feedback on consensus and wording Also thanks to Bill Gleim and Seunghwan Han for various contributions. Your name and organization here for your contribution 1 Bitcoin: https://bitcoin.org/bitcoin.pdf 2 ZeroCash: http://zerocash-project.org/paper 3 Ethereum: https://github.com/ethereum/wiki/wiki/WhitePaper 4 TheDAO: https://download.slock.it/public/DAO/WhitePaper.pdf 5 Segregated Witness: https://github.com/bitcoin/bips/blob/master/bip0141.mediawiki 6 BitcoinNG: https://arxiv.org/pdf/1510.02037v2.pdf 7 Lightning Network: https://lightning.network/lightningnetwork-paper-DRAFT-0.5.pdf 8 Tendermint: https://github.com/tendermint/tendermint/wiki 9 FLP Impossibility: https://groups.csail.mit.edu/tds/papers/Lynch/jacm85.pdf 10 Slasher: https://blog.ethereum.org/2014/01/15/slasher-apunitive-proof-of-stake-algorithm/ 11 PBFT: http://pmg.csail.mit.edu/papers/osdi99.pdf 12 BitShares: https://bitshares.org/technology/delegatedproof-of-stake-consensus/

13 Stellar: https://www.stellar.org/papers/stellar-consensusprotocol.pdf 14 Interledger: https://interledger.org/rfcs/0001-interledgerarchitecture/ 15 Sidechains: https://blockstream.com/sidechains.pdf 16 Casper: https://blog.ethereum.org/2015/08/01/introducing-casperfriendly-ghost/ 17 ABCI: https://github.com/tendermint/abci 18 Ethereum Sharding: https://github.com/ethereum/EIPs/issues/53 19 LibSwift: http://www.ds.ewi.tudelft.nl/yleadmin/pds/papers/Performa nceAnalysisOfLibswift.pdf 20 DLS: http://groups.csail.mit.edu/tds/papers/Lynch/jacm88.pdf 21 Thin Client Security: https://en.bitcoin.it/wiki/Thin_Client_Security 22 Ethereum 2.0 Mauve Paper: http://vitalik.ca/yles/mauve_paper.html https://www.docdroid.net/ec7xGzs/314477721-ethereumplatform-review-opportunities-and-challenges-for-privateand-consortium-blockchains.pdf.html

“ è 

Консенсус и технические детали

Хорошо разработанный протокол консенсуса должен обеспечить некоторые гарантии в случае превышения допускаемой мощности и консенсус терпит неудачу. Это особенно необходимо в экономической сфере. системы, в которых византийское поведение может иметь существенные финансовые последствия. награда. Самой важной такой гарантией является форма форкаподотчетности, при которой процессы, вызвавшие консенсус, сбой (т. е. заставил клиентов протокола принимать разные значения - вилка) могут быть выявлены и наказаны в соответствии с правилами протокол или, возможно, правовая система. Когда правовая система ненадежны или слишком дороги в вызове, validator могут быть были вынуждены внести залог для участия, и те депозиты могут быть отозваны или сокращены в случае выявления злонамеренного поведения. обнаружен [10]. Обратите внимание, что это не похоже на Bitcoin, где разветвление происходит регулярно. из-за сетевой асинхронности и вероятностного характера поиска частичные hash коллизии. Поскольку во многих случаях вредоносный форк неотличим от форка из-за асинхронности, Bitcoin не может надежно реализовать форк-подотчетность, кроме неявной Альтернативная стоимость, которую платят майнеры за добычу потерянного блока. Мы называем этапы голосования PreVote и PreCommit. Голосование может быть за конкретный блок или для Nil. Мы называем коллекцию из >⅔ PreVotes за один блок в одном раунде Полька и коллекция >⅔ PreCommits для одного блока в одном раунде фиксации. Если >⅔ PreCommit for Nil в том же раунде, они переходят к следующему круглый. Обратите внимание, что строгий детерминизм в протоколе влечет за собой слабую предположение синхронности, поскольку дефектные лидеры должны быть обнаружены и

пропущен. Таким образом, validator ждут некоторое время, TimeoutPropose, прежде чем они проголосуют за ноль, и значение TimeoutPropose увеличивается с каждым раундом. Прогресс через оставшаяся часть раунда полностью асинхронна, то есть прогресс только сделано, как только validator получит сообщение от >⅔ сети. На практике потребуется чрезвычайно сильный противник, чтобы навсегда помешать предположение о слабой синхронности (из-за которого консенсус не может быть достигнут) когда-либо фиксировать блок), и это можно сделать еще более сложно использовать случайные значения TimeoutPropose для каждого validator. Дополнительный набор ограничений или правил блокировки гарантирует, что сеть в конечном итоге зафиксирует только один блок на каждой высоте. Любой злонамеренная попытка вызвать фиксацию более одного блока на заданной высоте можно идентифицировать. Во-первых, PreCommit для блока должно прийти с обоснованием, в виде польки для этого блока. Если validator уже имеет PreCommit блок на этапе R_1, мы говорят, что они заперты в этом квартале, и полька раньше оправдывала новый PreCommit в раунде R_2 должен прийти в раунде R_polka где Р_1 < Р_полька <= Р_2. Во-вторых, validator должны сделать предложение. и/или предварительно проголосовать за блок, на котором они заблокированы. Вместе эти условия гарантируют, что validator не выполняет PreCommit без достаточные доказательства в качестве оправдания, и что validators, которые имеют PreCommit уже не может предоставлять доказательства PreCommit что-то еще. Это обеспечивает безопасность и жизнеспособность алгоритм консенсуса. Полная информация о протоколе описана здесь. Необходимость синхронизации всех заголовков блоков в TendermintPoS устранена, поскольку существование альтернативной цепочки (форка) означает ≥⅓ облигационную ставку можно сократить. Конечно, поскольку слэшинг требует что кто-то поделится доказательствами форка, легкие клиенты должны хранить любой блок-hash фиксирует то, что видит. Кроме того, легкие клиентыможет периодически синхронизироваться с изменениями в наборе validator, в чтобы избежать атак на большие расстояния (но есть и другие решения). возможно). По духу схожий с Ethereum, Tendermint позволяет приложениям встроить глобальный корень Меркла hash в каждый блок, что позволяет легко проверяемые запросы состояния для таких вещей, как баланс счетов, значение хранится в контракте или наличие неизрасходованной транзакции выход в зависимости от характера приложения. Предполагая, что набор широковещательных сетей достаточно устойчив. и статический набор validator, любая вилка в blockchain может быть обнаружены, а депозиты нарушителей validator удалены. Это инновация, впервые предложенная Виталиком Бутериным в начале 2014 года, решает проблема «ничего на кону» другого proof-of-stake криптовалюты (см. раздел «Связанные работы»). Однако, поскольку validator устанавливает должен иметь возможность изменять в течение длительного периода времени исходный Все validator могут потерять связь и, следовательно, смогут свободно создать новую цепочку из генезис-блока, не неся никаких затрат, поскольку у них больше нет заблокированных депозитов. Эта атака произошла известная как Атака на дальнюю дистанцию (LRA), в отличие от Короткой атаки. Атака на расстоянии, при которой validator, которые в данный момент связаны, вызывают форк и, следовательно, наказуемы (при условии, что форк несет ответственность BFT алгоритм, такой как консенсус Tendermint). Атаки на дальние дистанции часто считается критическим ударом по proof-of-stake. К счастью, влияние LRA можно смягчить следующим образом. Во-первых, для validator разорвать связь (тем самым вернув залоговый депозит и больше не получаю комиссию за участие в консенсусе), депозит должен быть непереводимым в течение определенного периода времени известный как «период разъединения», который может быть порядка недели или месяцы. Во-вторых, чтобы легкий клиент был безопасным, в первую очередь при подключении к сети он должен проверить недавний блок — hash против надежного источника или, предпочтительно, нескольких источников. Это

Это состояние иногда называют «слабой субъективностью». Наконец, чтобы оставаться в безопасности, он должен синхронизироваться с последней версией validator, установленной по адресу по крайней мере так часто, как продолжительность периода отсоединения. Это гарантирует, что легкий клиент узнает об изменениях в validator устанавливается до того, как капитал validator будет освобожден от обязательств и, следовательно, больше не будет на кону, что позволило бы обмануть клиента, выполняя атака на дальнюю дистанцию путем создания новых блоков, начиная с высота, на которой он был прикреплен (при условии, что он контролирует достаточно многие из ранних закрытых ключей). Отметим, что преодоление ЛРА таким путем требует пересмотра исходная модель безопасности proof-of-work. В PoW это предположил, что легкий клиент может синхронизироваться с текущей высотой из доверенный блок генезиса в любое время, просто обрабатывая подтверждение работы в каждом заголовке блока. Однако, чтобы победить ЛРА, мы требуют, чтобы легкий клиент подключался к сети с некоторой регулярностью для отслеживать изменения в наборе validator и что в первый раз они выходят в Интернет, они должны быть особенно осторожны при аутентификации что они слышат из сети в отношении проверенных источников. Из конечно, последнее требование аналогично требованию Bitcoin, где протокол и программное обеспечение также должны быть получены от доверенного лица. источник. Вышеописанный метод предотвращения LRA хорошо подходит для validators. и полные узлы blockchain на базе Tendermint, потому что эти узлы предназначены для того, чтобы оставаться подключенными к сети. метод также подходит для легких клиентов, от которых можно ожидать часто синхронизируйтесь с сетью. Однако для легких клиентов, которые не предполагается, что они будут иметь частый доступ к Интернету или blockchain, можно использовать еще одно решение для преодоления ЛРА. Владельцы validator token могут публиковать свои token как залог с очень длительным периодом отсоединения (например, гораздо более длительный чем период отсоединения для validators) и обслуживать легких клиентов с вторичным методом подтверждения действительности текущих и прошлый блок-hashes. Хотя эти token не засчитываются в счет безопасности консенсуса blockchain, они, тем не менее, могутпредоставить надежные гарантии для легких клиентов. Если исторический блок-hash запросы поддерживались в Ethereum, любой мог связать свои tokens в специально разработанном smart contract и обеспечивают платные услуги по аттестации, что эффективно создает рынок безопасности LRA для легких клиентов. В связи с определением фиксации блока любая коалиция ≥⅓ блоков Право голоса может остановить blockchain, выйдя из журнала или нет транслируя свои голоса. Такая коалиция может также подвергать цензуре определенные транзакции, отклоняя блоки, которые включают в себя эти транзакций, хотя это привело бы к значительной доле блоков предложений, которые будут отклонены, что замедлит скорость блоковых коммитов blockchain, что снижает его полезность и ценность. Злонамеренная коалиция также может транслировать голоса небольшими порциями, поэтому при измельчении blockchain блок почти останавливается или вступает в любая комбинация этих атак. Наконец, это может привести к blockchain для разветвления путем двойной подписи или нарушения блокировки правила. Если бы в дело вмешался и глобально активный противник, он мог бы разделить сети таким образом, что может показаться, что это неправильный за замедление ответственно подмножество validators. Это не просто ограничение Tendermint, а скорее ограничение всех консенсусные протоколы, сеть которых потенциально контролируется активный противник. Для этих типов атак следует использовать подмножество validator. координировать действия с помощью внешних средств для подписания предложения о реорганизации, которое выбирает ответвление (и любые его доказательства) и начальное подмножество validators со своими подписями. Валидаторы, подписавшие такое предложение о реорганизации, отказываются от обеспечения на всех других форках. Клиенты должны проверить подписи на предложении о реорганизации, проверить любые доказательства, и вынести суждение или предложить конечному пользователю принять решение. Для Например, приложение телефонного кошелька может предложить пользователю ввести пароль безопасности.

предупреждение, а холодильник может принять любое предложение по реорганизации подписано +½ исходного числа validator по числу голосов. Никакой асинхронный византийский отказоустойчивый алгоритм не может прийти к консенсусу, когда ≥⅓ голосов нечестны, но это форк предполагает, что ≥⅓ голосов уже были нечестны двойное подписание или смена блокировки без обоснования. Итак, подписываем предложение о реорганизации представляет собой проблему координации, которую невозможно решить. решается любым несинхронным протоколом (т.е. автоматически, и не делая предположений о надежности базовая сеть). На данный момент мы оставляем проблему координации предложений по реорганизации на усмотрение человека посредством социального консенсуса. в интернет-СМИ. Валидаторы должны позаботиться о том, чтобы до подписания предложения о реорганизации не осталось никаких сетевых разделов, чтобы избежать ситуаций, когда подписываются два противоречивых предложения о реорганизации. Предполагая, что внешняя среда и протокол координации надежный, из этого следует, что форки вызывают меньшую озабоченность, чем цензура. атаки. Помимо форков и цензуры, требующей ≥⅓ византийского голосов, коалиция с числом голосов >⅔ может взять на себя обязательство произвольное, недействительное состояние. Это свойственно любому (BFT) система консенсуса. В отличие от двойной подписи, которая создает форки с помощью легко проверяемых доказательств, выявляющих совершение недействительное состояние требует, чтобы непроверяющие узлы проверяли целые блоки, что означает, что они сохраняют локальную копию состояния и выполняют каждой транзакции, вычисляя корень состояния независимо для себя. После обнаружения единственный способ справиться с таким сбоем происходит через социальный консенсус. Например, в ситуациях, когда Bitcoin не удалось, то ли форк из-за ошибок в программном обеспечении (как в марте 2013), или совершение недопустимого состояния из-за византийского поведения майнеры (как и в июле 2015 г.), сообщество с хорошими связями предприятия, разработчики, майнеры и другие организации установил социальный консенсус относительно того, какие ручные действия былинеобходимые участникам для исцеления сети. Кроме того, поскольку Можно ожидать, что validators Tendermint blockchain будут идентифицироваться, принятие недействительного состояния может даже быть наказуемо по закону или какой-либо внешней судебной практике, если это необходимо. ABCI состоит из трех основных типов сообщений, которые доставляются ядро приложения. Приложение отвечает соответствующие ответные сообщения. Сообщение  AppendTx  — это рабочая лошадка приложения. Каждый транзакция в blockchain доставляется с этим сообщением. приложению необходимо проверять каждую транзакцию, полученную с помощью Сообщение AppendTx о текущем состоянии, протоколе приложения, и криптографические учетные данные транзакции. проверенный затем транзакция должна обновить состояние приложения — путем привязка значения к хранилищу значений ключей или обновление UTXO база данных. Сообщение  CheckTx  похоже на AppendTx, но предназначено только для проверка транзакций. Ежегодные проверки мемпула Tendermint Core достоверность транзакции с CheckTx, действительны только реле транзакции со своими коллегами. Приложения могут проверять возрастающее nonce в транзакции и возвращает ошибку при CheckTx, если nonce старый. Сообщение  Commit  используется для вычисления криптографического обязательство по текущему состоянию приложения, которое будет помещено в заголовок следующего блока. У этого есть несколько полезных свойств. Несоответствия в обновлении этого состояния теперь будут отображаться как blockchain разветвляется, охватывая целый класс программирования ошибки. Это также упрощает разработку безопасных и легких клиентов, поскольку доказательства Merkle-hash можно проверить, проверив блок-hash и блок-hash подписаны кворумом из validators (по количеству голосов).

Дополнительные сообщения ABCI позволяют приложению отслеживать и измените набор validator, чтобы приложение получало информация о блоке, такая как высота и голоса за фиксацию. ABCI запросы/ответы — это простые сообщения Protobuf. Проверить из схемы yle. Аргументы: Данные ([]byte): байты транзакции запроса. Возврат: Код (uint32): код ответа. Данные ([]byte): байты результата, если таковые имеются. Журнал (строка): сообщение об отладке или ошибке. Использование:

Добавьте и запустите транзакцию. Если сделка действительна, возвращает КодТип.ОК Аргументы: Данные ([]byte): байты транзакции запроса. Возврат: Код (uint32): код ответа. Данные ([]byte): байты результата, если таковые имеются. Журнал (строка): сообщение об отладке или ошибке. Использование:

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

Возврат: Данные ([]байт): корень Меркла hash Журнал (строка): сообщение об отладке или ошибке. Использование:

Возвращает корень Merkle hash состояния приложения. Аргументы: Данные ([]byte): байты запроса запроса. Возврат: Код (uint32): код ответа. Данные ([]byte): байты ответа на запрос. Журнал (строка): сообщение об отладке или ошибке. Использование:

Очистить очередь ответов. Приложения, реализующие типы. Приложению не обязательно реализовывать это сообщение – оно обрабатывается проектом. Возврат: Данные ([]byte): информационные байты. Использование:

Возвращает информацию о состоянии приложения. Приложение специфический. Аргументы: Ключ (строка): ключ для установки.

Значение (строка): значение, которое нужно установить для ключа. Возврат: Журнал (строка): сообщение об отладке или ошибке. Использование:

Установите параметры приложения. Например. Key="mode", Value="mempool" для соединение с мемпулом или Key="mode", Value="consensus" для консенсусная связь. Другие параметры зависят от приложения. Аргументы: Валидаторы ([]Валидатор): Начальное происхождение — validators. Использование:

Вызванный однажды при зарождении Аргументы: Высота (uint64): высота блока, начиная с Использование:

Сигнализирует о начале нового блока. Вызывается перед любым AppendTxs. Аргументы: Высота (uint64): высота блока, который закончился. Возврат: Валидаторы ([]Validator): изменены validator на новые. право голоса (0 для удаления) Использование:

Сигнализирует об окончании блока. Вызывается перед каждым коммитом в конце концов транзакции Дополнительную информацию см. в репозитории ABCI.Существует несколько причин, по которым отправитель может захотеть подтверждение доставки пакета принимающей цепочкой. Например, отправитель может не знать статус сообщения. цепочка назначения, если ожидается, что она неисправна. Или отправитель может хотите установить для пакета тайм-аут (с помощью параметра MaxHeight  пакетный ответ), в то время как любая цепочка назначения может пострадать от атаки типа «отказ в обслуживании» с внезапным всплеском количества входящих пакетов. пакеты. В этих случаях отправитель может потребовать подтверждение доставки. установив первоначальный статус пакета на  AckPending . Тогда это ответственность принимающей сети за подтверждение доставки путем включения сокращенно IBCPacket  в приложении Merkle hash. Сначала IBCBlockCommit  и  IBCPacketTx  публикуются в «Hub». это доказывает существование IBCПакета  в «Зоне1». Скажи это  IBCPacketTx  имеет следующее значение: FromChainID: «Зона1» FromBlockHeight: 100 (скажем) Пакет: IBCПакет:

Заголовок: IBCPacketHeader: SrcChainID: «Зона1» DstChainID: «Зона2» Число: 200 (скажем) Статус: Подтверждено Тип: «монета» MaxHeight: 350 (скажем, «Hub» сейчас находится на высоте 300) Полезная нагрузка: <Байты полезной нагрузки «монеты»> Затем IBCBlockCommit и IBCPacketTx  публикуются в «Zone2». это доказывает существование IBCПакета  на «Хабе». Скажи это  IBCPacketTx  имеет следующее значение: FromChainID: «Хаб» ФромБлокХигхт: 300 Пакет: IBCПакет: Заголовок: IBCPacketHeader: SrcChainID: «Зона1» DstChainID: «Зона2» Количество : 200 Статус: Подтверждено Тип: «монета» Макс.Высота: 350 Полезная нагрузка: <Те же байты полезной нагрузки «монеты»> Далее «Зона2» должна включить в свое приложение-hash сокращенный пакет. который показывает новый статус  AckSent . IBCBlockCommit  и  IBCPacketTx  отправляются обратно на «Хаб», что доказывает существование сокращенного  IBCПакета  в "Zone2". Скажите, что IBCPacketTx  имеет следующее значение: FromChainID: «Зона2»

FromBlockHeight: 400 (скажем) Пакет: IBCПакет: Заголовок: IBCPacketHeader: SrcChainID: «Зона1» DstChainID: «Зона2» Количество : 200 Статус: Подтверждено Тип: «монета» Макс.Высота: 350 PayloadHash: Наконец, «Хаб» должен обновить статус пакета с  От AckPending до AckReceived. Доказательства этого нового статуса должен вернуться в «Зону2». Предположим, что IBCPacketTx  имеет следующее значение: FromChainID: «Хаб» ФромБлокХигхт: 301 Пакет: IBCПакет: Заголовок: IBCPacketHeader: SrcChainID: «Зона1» DstChainID: «Зона2» Количество : 200 Статус: Подтверждено Тип: «монета» Макс.Высота: 350 PayloadHash: Между тем, «Зона 1» может с оптимизмом предполагать успешную доставку. пакета «монет», если только не доказано обратное «Хаб». В приведенном выше примере, если «Хаб» не получил сообщение AckSent

статус из «Зоны2» в блоке 350, он бы установил статус автоматически на  Тайм-аут . Это свидетельство тайм-аута можно получить отправлено обратно в «Зону1», и любые token могут быть возвращены. В файле поддерживается два типа Merkle tree. Экосистема Tendermint/Cosmos: Простое дерево и IAVL+ Дерево. Простое дерево — это Merkle tree для статического списка элементов. Если количество предметов не является степенью двойки, некоторые листья будут находиться в разные уровни. Simple Tree пытается сохранить обе стороны дерева одинаковой высоты, но левая может быть на единицу больше. Это Merkle tree используется для Мерклеизации транзакций блока, а верхний уровень элементы корня состояния приложения.Целью структуры данных IAVL+ является обеспечение постоянного хранилище для пар ключ-значение в состоянии приложения, так что детерминированный корень Меркла hash может быть эффективно вычислен. дерево сбалансировано с использованием варианта алгоритма AVL, и все операции - O(log(n)). В дереве AVL высоты двух дочерних поддеревьев любого узла отличаются не более чем на единицу. Всякий раз, когда это условие нарушается обновлении, дерево перебалансируется путем создания новых узлов O(log(n)) указать на неизмененные узлы старого дерева. В оригинальном АВЛ алгоритме внутренние узлы также могут содержать пары ключ-значение. АВЛ+ алгоритм (обратите внимание на плюс) модифицирует алгоритм AVL, чтобы сохранить все значения на конечных узлах, используя только узлы ветвей для хранения ключей. Это упрощает алгоритм, сохраняя при этом след Меркла hash. короткий. Дерево AVL+ аналогично попыткам Патрисии Ethereum. Есть компромиссы. Ключи не требуется hash перед вставкой в Деревья IAVL+, что обеспечивает более быструю упорядоченную итерацию ключа. пространство, которое может принести пользу некоторым приложениям. Логика проще реализовать, требуя только два типа узлов – внутренние узлы и листовые узлы. Доказательство Меркла в среднем короче, поскольку                 *                 / \               /     \             /         \           /             \          *               *         / \             / \        /   \           /   \       /     \         /     \      *        *       *       h6     / \     / \     / \    h0  h1  h2  h3  h4  h5    Простое дерево с 7 элементами.

сбалансированное двоичное дерево. С другой стороны, корень Меркла Дерево IAVL+ зависит от порядка обновлений. Мы будем поддерживать дополнительные эффективные Merkle tree, такие как Патриция Три из Ethereum, когда бинарный вариант становится доступен. В канонической реализации транзакции передаются в Приложение-концентратор Cosmos через интерфейс ABCI. Хаб Cosmos примет ряд первичных транзакций. типы, включая  SendTx ,  BondTx ,  UnbondTx ,  ReportHackTx ,  SlashTx, BurnAtomTx, ProposalCreateTx и ProposalVoteTx, которые достаточно очевидны и будут задокументированы в будущая редакция этой статьи. Здесь мы документируем два основных типы транзакций для IBC:  IBCBlockCommitTx  и  IBCPacketTx . Транзакция  IBCBlockCommitTx  состоит из: ChainID (строка): идентификатор blockchain. BlockHash ([]byte): блок — hash байт, корень Меркла. который включает приложение-hash BlockPartsHeader (PartSetHeader): заголовок набора частей блока. байты, необходимы только для проверки подписей голосований BlockHeight (int): высота фиксации. BlockRound (int) : раунд фиксации. Commit ([]Vote): Предварительное принятие Tendermint >⅔ голосует за то, включать фиксацию блока ValidatorsHash ([]byte): корень дерева Меркла hash нового validator набор

ValidatorsHashProof (SimpleProof): SimpleTree Merkleproof для проверки ValidatorsHash на соответствие BlockHash. AppHash ([]byte): корень дерева Меркла IAVLTree hash состояние приложения AppHashProof (SimpleProof): SimpleTree, защищенный Мерклем для сравнение AppHash с BlockHash  IBCПакет  состоит из: Заголовок (IBCPacketHeader): заголовок пакета. Полезная нагрузка ([]byte): байты полезной нагрузки пакета. Необязательно PayloadHash ([]byte): hash для байтов пакета. Необязательно Должен присутствовать любой из  Payload  или  PayloadHash . hash пакета  IBCPacket       является простым корнем Меркла двух элементов:  Header  и  Полезная нагрузка . Пакет IBC без полной полезной нагрузки называется пакетом. сокращенный пакет. IBCPacketHeader  состоит из: SrcChainID (строка): идентификатор источника blockchain. DstChainID (строка): идентификатор пункта назначения blockchain. Номер (int): уникальный номер для всех пакетов. Статус (перечисление): может быть одним из AckPending, AckSent, AckReceived, NoAck или Timeout Тип (строка): типы зависят от приложения. Cosmos резервирует тип пакета «монета» MaxHeight (int): если статус не NoAckWanted или AckReceived. на этой высоте статус становится Timeout . Необязательно Транзакция  IBCPacketTx  состоит из:FromChainID (строка): идентификатор blockchain, который предоставление этого пакета; не обязательно источник FromBlockHeight (int) : высота blockchain, на которой следующий пакет включен (в формате Меркла) в блок - hash из исходная цепочка Пакет (IBCPacket): пакет данных, статус которого может быть одним из AckPending, AckSent, AckReceived, NoAck или Timeout PacketProof (IAVLProof): IAVLTree-доказательство Меркла для доказательства hash пакета по AppHash исходной цепочки по адресу заданная высота Последовательность отправки пакета из «Зоны1» в «Зону2» через «Хаб» изображен на {Рис. X}. Сначала IBCPacketTx  доказывает «Хабу», что пакет включен в app-состояние «Зона1». Затем другой IBCPacketTx  доказывает «Зоне2», что пакет включен в состояние приложения «Хаб». Во время этого процедуры, поля IBCPacket идентичны:  SrcChainID  всегда «Зона1», а  DstChainID — всегда «Зона2».  PacketProof  должен иметь правильный путь, защищенный Меркле, так как следует: Когда «Зона 1» хочет отправить пакет в «Зону 2» через «Хаб», Данные  IBCPacket  идентичны независимо от того, зарегистрирован ли пакет в «Зоне 1», «Хабе» или «Зоне 2». Единственный изменяемый Yeld - это  Статус для отслеживания доставки. Мы благодарим наших друзей и коллег за помощь в концептуализации, проверка и поддержка нашей работы с Tendermint и Cosmos. IBC///<Номер>

Заки Маниан из SkuChain оказал большую помощь в форматировании и формулировка, особенно в разделе ABCI Джехану Трембаку из Althea и Дастину Байингтону за помощь с начальные итерации Эндрю Миллер из Honey Badger за отзыв о консенсусе Грег Слепак за отзыв о консенсусе и формулировках Также спасибо Биллу Глейму и Сынхван Хану за различные взносы. Ваше имя и организация здесь за ваш вклад 1 Bitcoin: https://bitcoin.org/bitcoin.pdf 2 ZeroCash: http://zerocash-project.org/paper 3 Ethereum: https://github.com/ethereum/wiki/wiki/WhitePaper 4 DAO: https://download.slock.it/public/DAO/WhitePaper.pdf 5 отдельных свидетелей: https://github.com/bitcoin/bips/blob/master/bip0141.mediawiki 6 BitcoinNG: https://arxiv.org/pdf/1510.02037v2.pdf 7 Сеть Lightning: https://lightning.network/lightningnetwork-paper-DRAFT-0.5.pdf 8 Тендерминт: https://github.com/tendermint/tendermint/wiki 9 Невозможность ФЛП: https://groups.csail.mit.edu/tds/papers/Lynch/jacm85.pdf 10 Слэшер: https://blog.ethereum.org/2014/01/15/slasher-apunitive-proof-of-stake-algorithm/ 11 PBFT: http://pmg.csail.mit.edu/papers/osdi99.pdf 12 BitShares: https://bitshares.org/technology/delegatedproof-of-stake-consensus/

13 Stellar: https://www.stellar.org/papers/stellar-consensusprotocol.pdf 14 Интерледжер: https://interledger.org/rfcs/0001-interledgerarchitecture/ 15 сайдчейнов: https://blockstream.com/sidechains.pdf 16 Каспер: https://blog.ethereum.org/2015/08/01/introducing-casperfriendly-ghost/ 17 ABCI: https://github.com/tendermint/abci 18 Ethereum Шардинг: https://github.com/ethereum/EIPs/issues/53 19 ЛибСвифт: http://www.ds.ewi.tudelft.nl/yleadmin/pds/papers/Performa nceAnaлизOfLibswift.pdf 20 ДЛС: http://groups.csail.mit.edu/tds/papers/Lynch/jacm88.pdf 21 Безопасность тонкого клиента: https://en.bitcoin.it/wiki/Thin_Client_Security 22 Ethereum 2.0 Сиреневая бумага: http://vitalik.ca/yles/mauve_paper.html https://www.docdroid.net/ec7xGzs/314477721-ethereumplatform-review-opportunities-and-challenges-for-privateand-consortium-blockchains.pdf.html

гл è