You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

674 lines
30 KiB

  1. # Applications
  2. Please ensure you've first read the spec for [ABCI Methods and Types](abci.md)
  3. Here we cover the following components of ABCI applications:
  4. - [Connection State](#state) - the interplay between ABCI connections and application state
  5. and the differences between `CheckTx` and `DeliverTx`.
  6. - [Transaction Results](#transaction-results) - rules around transaction
  7. results and validity
  8. - [Validator Set Updates](#validator-updates) - how validator sets are
  9. changed during `InitChain` and `EndBlock`
  10. - [Query](#query) - standards for using the `Query` method and proofs about the
  11. application state
  12. - [Crash Recovery](#crash-recovery) - handshake protocol to synchronize
  13. Tendermint and the application on startup.
  14. - [State Sync](#state-sync) - rapid bootstrapping of new nodes by restoring state machine snapshots
  15. ## State
  16. Since Tendermint maintains four concurrent ABCI connections, it is typical
  17. for an application to maintain a distinct state for each, and for the states to
  18. be synchronized during `Commit`.
  19. ### BeginBlock
  20. The BeginBlock request can be used to run some code at the beginning of
  21. every block. It also allows Tendermint to send the current block hash
  22. and header to the application, before it sends any of the transactions.
  23. The app should remember the latest height and header (ie. from which it
  24. has run a successful Commit) so that it can tell Tendermint where to
  25. pick up from when it restarts. See information on the Handshake, below.
  26. ### Commit
  27. Application state should only be persisted to disk during `Commit`.
  28. Before `Commit` is called, Tendermint locks and flushes the mempool so that no new messages will
  29. be received on the mempool connection. This provides an opportunity to safely update all three
  30. states to the latest committed state at once.
  31. When `Commit` completes, it unlocks the mempool.
  32. WARNING: if the ABCI app logic processing the `Commit` message sends a
  33. `/broadcast_tx_sync` or `/broadcast_tx_commit` and waits for the response
  34. before proceeding, it will deadlock. Executing those `broadcast_tx` calls
  35. involves acquiring a lock that is held during the `Commit` call, so it's not
  36. possible. If you make the call to the `broadcast_tx` endpoints concurrently,
  37. that's no problem, it just can't be part of the sequential logic of the
  38. `Commit` function.
  39. ### Consensus Connection
  40. The Consensus Connection should maintain a `DeliverTxState` -
  41. the working state for block execution. It should be updated by the calls to
  42. `BeginBlock`, `DeliverTx`, and `EndBlock` during block execution and committed to
  43. disk as the "latest committed state" during `Commit`.
  44. Updates made to the DeliverTxState by each method call must be readable by each subsequent method -
  45. ie. the updates are linearizable.
  46. - [BeginBlock](#beginblock)
  47. - [EndBlock](#endblock)
  48. - [Deliver Tx](#delivertx)
  49. - [Commit](#commit)
  50. ### Mempool Connection
  51. The mempool Connection should maintain a `CheckTxState`
  52. to sequentially process pending transactions in the mempool that have
  53. not yet been committed. It should be initialized to the latest committed state
  54. at the end of every `Commit`.
  55. The CheckTxState may be updated concurrently with the DeliverTxState, as
  56. messages may be sent concurrently on the Consensus and Mempool connections. However,
  57. before calling `Commit`, Tendermint will lock and flush the mempool connection,
  58. ensuring that all existing CheckTx are responded to and no new ones can
  59. begin.
  60. After `Commit`, CheckTx is run again on all transactions that remain in the
  61. node's local mempool after filtering those included in the block. To prevent the
  62. mempool from rechecking all transactions every time a block is committed, set
  63. the configuration option `mempool.recheck=false`. As of Tendermint v0.32.1,
  64. an additional `Type` parameter is made available to the CheckTx function that
  65. indicates whether an incoming transaction is new (`CheckTxType_New`), or a
  66. recheck (`CheckTxType_Recheck`).
  67. Finally, the mempool will unlock and new transactions can be processed through CheckTx again.
  68. Note that CheckTx doesn't have to check everything that affects transaction validity; the
  69. expensive things can be skipped. In fact, CheckTx doesn't have to check
  70. anything; it might say that any transaction is a valid transaction.
  71. Unlike DeliverTx, CheckTx is just there as
  72. a sort of weak filter to keep invalid transactions out of the blockchain. It's
  73. weak, because a Byzantine node doesn't care about CheckTx; it can propose a
  74. block full of invalid transactions if it wants.
  75. #### Replay Protection
  76. To prevent old transactions from being replayed, CheckTx must implement
  77. replay protection.
  78. Tendermint provides the first defense layer by keeping a lightweight
  79. in-memory cache of 100k (`[mempool] cache_size`) last transactions in
  80. the mempool. If Tendermint is just started or the clients sent more than
  81. 100k transactions, old transactions may be sent to the application. So
  82. it is important CheckTx implements some logic to handle them.
  83. If there are cases in your application where a transaction may become invalid in some
  84. future state, you probably want to disable Tendermint's
  85. cache. You can do that by setting `[mempool] cache_size = 0` in the
  86. config.
  87. ### Query Connection
  88. The Info Connection should maintain a `QueryState` for answering queries from the user,
  89. and for initialization when Tendermint first starts up (both described further
  90. below).
  91. It should always contain the latest committed state associated with the
  92. latest committed block.
  93. QueryState should be set to the latest `DeliverTxState` at the end of every `Commit`,
  94. ie. after the full block has been processed and the state committed to disk.
  95. Otherwise it should never be modified.
  96. Tendermint Core currently uses the Query connection to filter peers upon
  97. connecting, according to IP address or node ID. For instance,
  98. returning non-OK ABCI response to either of the following queries will
  99. cause Tendermint to not connect to the corresponding peer:
  100. - `p2p/filter/addr/<ip addr>`, where `<ip addr>` is an IP address.
  101. - `p2p/filter/id/<id>`, where `<is>` is the hex-encoded node ID (the hash of
  102. the node's p2p pubkey).
  103. Note: these query formats are subject to change!
  104. ### Snapshot Connection
  105. The Snapshot Connection is optional, and is only used to serve state sync snapshots for other nodes
  106. and/or restore state sync snapshots to a local node being bootstrapped.
  107. ## Transaction Results
  108. `ResponseCheckTx` and `ResponseDeliverTx` contain the same fields.
  109. The `Info` and `Log` fields are non-deterministic values for debugging/convenience purposes
  110. that are otherwise ignored.
  111. The `Data` field must be strictly deterministic, but can be arbitrary data.
  112. ### Gas
  113. Ethereum introduced the notion of `gas` as an abstract representation of the
  114. cost of resources used by nodes when processing transactions. Every operation in the
  115. Ethereum Virtual Machine uses some amount of gas, and gas can be accepted at a market-variable price.
  116. Users propose a maximum amount of gas for their transaction; if the tx uses less, they get
  117. the difference credited back. Tendermint adopts a similar abstraction,
  118. though uses it only optionally and weakly, allowing applications to define
  119. their own sense of the cost of execution.
  120. In Tendermint, the `ConsensusParams.Block.MaxGas` limits the amount of `gas` that can be used in a block.
  121. The default value is `-1`, meaning no limit, or that the concept of gas is
  122. meaningless.
  123. Responses contain a `GasWanted` and `GasUsed` field. The former is the maximum
  124. amount of gas the sender of a tx is willing to use, and the later is how much it actually
  125. used. Applications should enforce that `GasUsed <= GasWanted` - ie. tx execution
  126. should halt before it can use more resources than it requested.
  127. When `MaxGas > -1`, Tendermint enforces the following rules:
  128. - `GasWanted <= MaxGas` for all txs in the mempool
  129. - `(sum of GasWanted in a block) <= MaxGas` when proposing a block
  130. If `MaxGas == -1`, no rules about gas are enforced.
  131. Note that Tendermint does not currently enforce anything about Gas in the consensus, only the mempool.
  132. This means it does not guarantee that committed blocks satisfy these rules!
  133. It is the application's responsibility to return non-zero response codes when gas limits are exceeded.
  134. The `GasUsed` field is ignored completely by Tendermint. That said, applications should enforce:
  135. - `GasUsed <= GasWanted` for any given transaction
  136. - `(sum of GasUsed in a block) <= MaxGas` for every block
  137. In the future, we intend to add a `Priority` field to the responses that can be
  138. used to explicitly prioritize txs in the mempool for inclusion in a block
  139. proposal. See [#1861](https://github.com/tendermint/tendermint/issues/1861).
  140. ### CheckTx
  141. If `Code != 0`, it will be rejected from the mempool and hence
  142. not broadcasted to other peers and not included in a proposal block.
  143. `Data` contains the result of the CheckTx transaction execution, if any. It is
  144. semantically meaningless to Tendermint.
  145. `Events` include any events for the execution, though since the transaction has not
  146. been committed yet, they are effectively ignored by Tendermint.
  147. ### DeliverTx
  148. DeliverTx is the workhorse of the blockchain. Tendermint sends the
  149. DeliverTx requests asynchronously but in order, and relies on the
  150. underlying socket protocol (ie. TCP) to ensure they are received by the
  151. app in order. They have already been ordered in the global consensus by
  152. the Tendermint protocol.
  153. If DeliverTx returns `Code != 0`, the transaction will be considered invalid,
  154. though it is still included in the block.
  155. DeliverTx returns a `abci.Result`, which includes a Code, Data, and Log.
  156. `Data` contains the result of the CheckTx transaction execution, if any. It is
  157. semantically meaningless to Tendermint.
  158. Both the `Code` and `Data` are included in a structure that is hashed into the
  159. `LastResultsHash` of the next block header.
  160. `Events` include any events for the execution, which Tendermint will use to index
  161. the transaction by. This allows transactions to be queried according to what
  162. events took place during their execution.
  163. ## Validator Updates
  164. The application may set the validator set during InitChain, and update it during
  165. EndBlock.
  166. Note that the maximum total power of the validator set is bounded by
  167. `MaxTotalVotingPower = MaxInt64 / 8`. Applications are responsible for ensuring
  168. they do not make changes to the validator set that cause it to exceed this
  169. limit.
  170. Additionally, applications must ensure that a single set of updates does not contain any duplicates -
  171. a given public key can only appear in an update once. If an update includes
  172. duplicates, the block execution will fail irrecoverably.
  173. ### InitChain
  174. ResponseInitChain can return a list of validators.
  175. If the list is empty, Tendermint will use the validators loaded in the genesis
  176. file.
  177. If the list is not empty, Tendermint will use it for the validator set.
  178. This way the application can determine the initial validator set for the
  179. blockchain.
  180. ### EndBlock
  181. Updates to the Tendermint validator set can be made by returning
  182. `ValidatorUpdate` objects in the `ResponseEndBlock`:
  183. ```protobuf
  184. message ValidatorUpdate {
  185. tendermint.crypto.keys.PublicKey pub_key
  186. int64 power
  187. }
  188. message PublicKey {
  189. oneof {
  190. ed25519 bytes = 1;
  191. }
  192. ```
  193. The `pub_key` currently supports only one type:
  194. - `type = "ed25519"`
  195. The `power` is the new voting power for the validator, with the
  196. following rules:
  197. - power must be non-negative
  198. - if power is 0, the validator must already exist, and will be removed from the
  199. validator set
  200. - if power is non-0:
  201. - if the validator does not already exist, it will be added to the validator
  202. set with the given power
  203. - if the validator does already exist, its power will be adjusted to the given power
  204. - the total power of the new validator set must not exceed MaxTotalVotingPower
  205. Note the updates returned in block `H` will only take effect at block `H+2`.
  206. ## Consensus Parameters
  207. ConsensusParams enforce certain limits in the blockchain, like the maximum size
  208. of blocks, amount of gas used in a block, and the maximum acceptable age of
  209. evidence. They can be set in InitChain and updated in EndBlock.
  210. ### BlockParams.MaxBytes
  211. The maximum size of a complete Protobuf encoded block.
  212. This is enforced by Tendermint consensus.
  213. This implies a maximum tx size that is this MaxBytes, less the expected size of
  214. the header, the validator set, and any included evidence in the block.
  215. Must have `0 < MaxBytes < 100 MB`.
  216. ### BlockParams.MaxGas
  217. The maximum of the sum of `GasWanted` in a proposed block.
  218. This is *not* enforced by Tendermint consensus.
  219. It is left to the app to enforce (ie. if txs are included past the
  220. limit, they should return non-zero codes). It is used by Tendermint to limit the
  221. txs included in a proposed block.
  222. Must have `MaxGas >= -1`.
  223. If `MaxGas == -1`, no limit is enforced.
  224. ### BlockParams.TimeIotaMs
  225. The minimum time between consecutive blocks (in milliseconds).
  226. This is enforced by Tendermint consensus.
  227. Must have `TimeIotaMs > 0` to ensure time monotonicity.
  228. > *Note: This is not exposed to the application*
  229. ### EvidenceParams.MaxAgeDuration
  230. This is the maximum age of evidence in time units.
  231. This is enforced by Tendermint consensus.
  232. If a block includes evidence older than this (AND the evidence was created more
  233. than `MaxAgeNumBlocks` ago), the block will be rejected (validators won't vote
  234. for it).
  235. Must have `MaxAgeDuration > 0`.
  236. ### EvidenceParams.MaxAgeNumBlocks
  237. This is the maximum age of evidence in blocks.
  238. This is enforced by Tendermint consensus.
  239. If a block includes evidence older than this (AND the evidence was created more
  240. than `MaxAgeDuration` ago), the block will be rejected (validators won't vote
  241. for it).
  242. Must have `MaxAgeNumBlocks > 0`.
  243. ### EvidenceParams.MaxNum
  244. This is the maximum number of evidence that can be committed to a single block.
  245. The product of this and the `MaxEvidenceBytes` must not exceed the size of
  246. a block minus it's overhead ( ~ `MaxBytes`).
  247. The amount must be a positive number.
  248. ### Updates
  249. The application may set the ConsensusParams during InitChain, and update them during
  250. EndBlock. If the ConsensusParams is empty, it will be ignored. Each field
  251. that is not empty will be applied in full. For instance, if updating the
  252. Block.MaxBytes, applications must also set the other Block fields (like
  253. Block.MaxGas), even if they are unchanged, as they will otherwise cause the
  254. value to be updated to 0.
  255. #### InitChain
  256. ResponseInitChain includes a ConsensusParams.
  257. If its nil, Tendermint will use the params loaded in the genesis
  258. file. If it's not nil, Tendermint will use it.
  259. This way the application can determine the initial consensus params for the
  260. blockchain.
  261. #### EndBlock
  262. ResponseEndBlock includes a ConsensusParams.
  263. If its nil, Tendermint will do nothing.
  264. If it's not nil, Tendermint will use it.
  265. This way the application can update the consensus params over time.
  266. Note the updates returned in block `H` will take effect right away for block
  267. `H+1`.
  268. ## Query
  269. Query is a generic method with lots of flexibility to enable diverse sets
  270. of queries on application state. Tendermint makes use of Query to filter new peers
  271. based on ID and IP, and exposes Query to the user over RPC.
  272. Note that calls to Query are not replicated across nodes, but rather query the
  273. local node's state - hence they may return stale reads. For reads that require
  274. consensus, use a transaction.
  275. The most important use of Query is to return Merkle proofs of the application state at some height
  276. that can be used for efficient application-specific light-clients.
  277. Note Tendermint has technically no requirements from the Query
  278. message for normal operation - that is, the ABCI app developer need not implement
  279. Query functionality if they do not wish too.
  280. ### Query Proofs
  281. The Tendermint block header includes a number of hashes, each providing an
  282. anchor for some type of proof about the blockchain. The `ValidatorsHash` enables
  283. quick verification of the validator set, the `DataHash` gives quick
  284. verification of the transactions included in the block, etc.
  285. The `AppHash` is unique in that it is application specific, and allows for
  286. application-specific Merkle proofs about the state of the application.
  287. While some applications keep all relevant state in the transactions themselves
  288. (like Bitcoin and its UTXOs), others maintain a separated state that is
  289. computed deterministically *from* transactions, but is not contained directly in
  290. the transactions themselves (like Ethereum contracts and accounts).
  291. For such applications, the `AppHash` provides a much more efficient way to verify light-client proofs.
  292. ABCI applications can take advantage of more efficient light-client proofs for
  293. their state as follows:
  294. - return the Merkle root of the deterministic application state in
  295. `ResponseCommit.Data`.
  296. - it will be included as the `AppHash` in the next block.
  297. - return efficient Merkle proofs about that application state in `ResponseQuery.Proof`
  298. that can be verified using the `AppHash` of the corresponding block.
  299. For instance, this allows an application's light-client to verify proofs of
  300. absence in the application state, something which is much less efficient to do using the block hash.
  301. Some applications (eg. Ethereum, Cosmos-SDK) have multiple "levels" of Merkle trees,
  302. where the leaves of one tree are the root hashes of others. To support this, and
  303. the general variability in Merkle proofs, the `ResponseQuery.Proof` has some minimal structure:
  304. ```protobuf
  305. message ProofOps {
  306. repeated ProofOp ops
  307. }
  308. message ProofOp {
  309. string type = 1;
  310. bytes key = 2;
  311. bytes data = 3;
  312. }
  313. ```
  314. Each `ProofOp` contains a proof for a single key in a single Merkle tree, of the specified `type`.
  315. This allows ABCI to support many different kinds of Merkle trees, encoding
  316. formats, and proofs (eg. of presence and absence) just by varying the `type`.
  317. The `data` contains the actual encoded proof, encoded according to the `type`.
  318. When verifying the full proof, the root hash for one ProofOp is the value being
  319. verified for the next ProofOp in the list. The root hash of the final ProofOp in
  320. the list should match the `AppHash` being verified against.
  321. ### Peer Filtering
  322. When Tendermint connects to a peer, it sends two queries to the ABCI application
  323. using the following paths, with no additional data:
  324. - `/p2p/filter/addr/<IP:PORT>`, where `<IP:PORT>` denote the IP address and
  325. the port of the connection
  326. - `p2p/filter/id/<ID>`, where `<ID>` is the peer node ID (ie. the
  327. pubkey.Address() for the peer's PubKey)
  328. If either of these queries return a non-zero ABCI code, Tendermint will refuse
  329. to connect to the peer.
  330. ### Paths
  331. Queries are directed at paths, and may optionally include additional data.
  332. The expectation is for there to be some number of high level paths
  333. differentiating concerns, like `/p2p`, `/store`, and `/app`. Currently,
  334. Tendermint only uses `/p2p`, for filtering peers. For more advanced use, see the
  335. implementation of
  336. [Query in the Cosmos-SDK](https://github.com/cosmos/cosmos-sdk/blob/v0.23.1/baseapp/baseapp.go#L333).
  337. ## Crash Recovery
  338. On startup, Tendermint calls the `Info` method on the Info Connection to get the latest
  339. committed state of the app. The app MUST return information consistent with the
  340. last block it succesfully completed Commit for.
  341. If the app succesfully committed block H but not H+1, then `last_block_height = H` and `last_block_app_hash = <hash returned by Commit for block H>`. If the app
  342. failed during the Commit of block H, then `last_block_height = H-1` and
  343. `last_block_app_hash = <hash returned by Commit for block H-1, which is the hash in the header of block H>`.
  344. We now distinguish three heights, and describe how Tendermint syncs itself with
  345. the app.
  346. ```md
  347. storeBlockHeight = height of the last block Tendermint saw a commit for
  348. stateBlockHeight = height of the last block for which Tendermint completed all
  349. block processing and saved all ABCI results to disk
  350. appBlockHeight = height of the last block for which ABCI app succesfully
  351. completed Commit
  352. ```
  353. Note we always have `storeBlockHeight >= stateBlockHeight` and `storeBlockHeight >= appBlockHeight`
  354. Note also we never call Commit on an ABCI app twice for the same height.
  355. The procedure is as follows.
  356. First, some simple start conditions:
  357. If `appBlockHeight == 0`, then call InitChain.
  358. If `storeBlockHeight == 0`, we're done.
  359. Now, some sanity checks:
  360. If `storeBlockHeight < appBlockHeight`, error
  361. If `storeBlockHeight < stateBlockHeight`, panic
  362. If `storeBlockHeight > stateBlockHeight+1`, panic
  363. Now, the meat:
  364. If `storeBlockHeight == stateBlockHeight && appBlockHeight < storeBlockHeight`,
  365. replay all blocks in full from `appBlockHeight` to `storeBlockHeight`.
  366. This happens if we completed processing the block, but the app forgot its height.
  367. If `storeBlockHeight == stateBlockHeight && appBlockHeight == storeBlockHeight`, we're done.
  368. This happens if we crashed at an opportune spot.
  369. If `storeBlockHeight == stateBlockHeight+1`
  370. This happens if we started processing the block but didn't finish.
  371. If `appBlockHeight < stateBlockHeight`
  372. replay all blocks in full from `appBlockHeight` to `storeBlockHeight-1`,
  373. and replay the block at `storeBlockHeight` using the WAL.
  374. This happens if the app forgot the last block it committed.
  375. If `appBlockHeight == stateBlockHeight`,
  376. replay the last block (storeBlockHeight) in full.
  377. This happens if we crashed before the app finished Commit
  378. If `appBlockHeight == storeBlockHeight`
  379. update the state using the saved ABCI responses but dont run the block against the real app.
  380. This happens if we crashed after the app finished Commit but before Tendermint saved the state.
  381. ## State Sync
  382. A new node joining the network can simply join consensus at the genesis height and replay all
  383. historical blocks until it is caught up. However, for large chains this can take a significant
  384. amount of time, often on the order of days or weeks.
  385. State sync is an alternative mechanism for bootstrapping a new node, where it fetches a snapshot
  386. of the state machine at a given height and restores it. Depending on the application, this can
  387. be several orders of magnitude faster than replaying blocks.
  388. Note that state sync does not currently backfill historical blocks, so the node will have a
  389. truncated block history - users are advised to consider the broader network implications of this in
  390. terms of block availability and auditability. This functionality may be added in the future.
  391. For details on the specific ABCI calls and types, see the [methods and types section](abci.md).
  392. ### Taking Snapshots
  393. Applications that want to support state syncing must take state snapshots at regular intervals. How
  394. this is accomplished is entirely up to the application. A snapshot consists of some metadata and
  395. a set of binary chunks in an arbitrary format:
  396. - `Height (uint64)`: The height at which the snapshot is taken. It must be taken after the given
  397. height has been committed, and must not contain data from any later heights.
  398. - `Format (uint32)`: An arbitrary snapshot format identifier. This can be used to version snapshot
  399. formats, e.g. to switch from Protobuf to MessagePack for serialization. The application can use
  400. this when restoring to choose whether to accept or reject a snapshot.
  401. - `Chunks (uint32)`: The number of chunks in the snapshot. Each chunk contains arbitrary binary
  402. data, and should be less than 16 MB; 10 MB is a good starting point.
  403. - `Hash ([]byte)`: An arbitrary hash of the snapshot. This is used to check whether a snapshot is
  404. the same across nodes when downloading chunks.
  405. - `Metadata ([]byte)`: Arbitrary snapshot metadata, e.g. chunk hashes for verification or any other
  406. necessary info.
  407. For a snapshot to be considered the same across nodes, all of these fields must be identical. When
  408. sent across the network, snapshot metadata messages are limited to 4 MB.
  409. When a new node is running state sync and discovering snapshots, Tendermint will query an existing
  410. application via the ABCI `ListSnapshots` method to discover available snapshots, and load binary
  411. snapshot chunks via `LoadSnapshotChunk`. The application is free to choose how to implement this
  412. and which formats to use, but should provide the following guarantees:
  413. - **Consistent:** A snapshot should be taken at a single isolated height, unaffected by
  414. concurrent writes. This can e.g. be accomplished by using a data store that supports ACID
  415. transactions with snapshot isolation.
  416. - **Asynchronous:** Taking a snapshot can be time-consuming, so it should not halt chain progress,
  417. for example by running in a separate thread.
  418. - **Deterministic:** A snapshot taken at the same height in the same format should be identical
  419. (at the byte level) across nodes, including all metadata. This ensures good availability of
  420. chunks, and that they fit together across nodes.
  421. A very basic approach might be to use a datastore with MVCC transactions (such as RocksDB),
  422. start a transaction immediately after block commit, and spawn a new thread which is passed the
  423. transaction handle. This thread can then export all data items, serialize them using e.g.
  424. Protobuf, hash the byte stream, split it into chunks, and store the chunks in the file system
  425. along with some metadata - all while the blockchain is applying new blocks in parallel.
  426. A more advanced approach might include incremental verification of individual chunks against the
  427. chain app hash, parallel or batched exports, compression, and so on.
  428. Old snapshots should be removed after some time - generally only the last two snapshots are needed
  429. (to prevent the last one from being removed while a node is restoring it).
  430. ### Bootstrapping a Node
  431. An empty node can be state synced by setting the configuration option `statesync.enabled =
  432. true`. The node also needs the chain genesis file for basic chain info, and configuration for
  433. light client verification of the restored snapshot: a set of Tendermint RPC servers, and a
  434. trusted header hash and corresponding height from a trusted source, via the `statesync`
  435. configuration section.
  436. Once started, the node will connect to the P2P network and begin discovering snapshots. These
  437. will be offered to the local application, and once a snapshot is accepted Tendermint will fetch
  438. and apply the snapshot chunks. After all chunks have been successfully applied, Tendermint verifies
  439. the app's `AppHash` against the chain using the light client, then switches the node to normal
  440. consensus operation.
  441. #### Snapshot Discovery
  442. When the empty node join the P2P network, it asks all peers to report snapshots via the
  443. `ListSnapshots` ABCI call (limited to 10 per node). After some time, the node picks the most
  444. suitable snapshot (generally prioritized by height, format, and number of peers), and offers it
  445. to the application via `OfferSnapshot`. The application can choose a number of responses,
  446. including accepting or rejecting it, rejecting the offered format, rejecting the peer who sent
  447. it, and so on. Tendermint will keep discovering and offering snapshots until one is accepted or
  448. the application aborts.
  449. #### Snapshot Restoration
  450. Once a snapshot has been accepted via `OfferSnapshot`, Tendermint begins downloading chunks from
  451. any peers that have the same snapshot (i.e. that have identical metadata fields). Chunks are
  452. spooled in a temporary directory, and then given to the application in sequential order via
  453. `ApplySnapshotChunk` until all chunks have been accepted.
  454. As with taking snapshots, the method for restoring them is entirely up to the application, but will
  455. generally be the inverse of how they are taken.
  456. During restoration, the application can respond to `ApplySnapshotChunk` with instructions for how
  457. to continue. This will typically be to accept the chunk and await the next one, but it can also
  458. ask for chunks to be refetched (either the current one or any number of previous ones), P2P peers
  459. to be banned, snapshots to be rejected or retried, and a number of other responses - see the ABCI
  460. reference for details.
  461. If Tendermint fails to fetch a chunk after some time, it will reject the snapshot and try a
  462. different one via `OfferSnapshot` - the application can choose whether it wants to support
  463. restarting restoration, or simply abort with an error.
  464. #### Snapshot Verification
  465. Once all chunks have been accepted, Tendermint issues an `Info` ABCI call to retrieve the
  466. `LastBlockAppHash`. This is compared with the trusted app hash from the chain, retrieved and
  467. verified using the light client. Tendermint also checks that `LastBlockHeight` corresponds to the
  468. height of the snapshot.
  469. This verification ensures that an application is valid before joining the network. However, the
  470. snapshot restoration may take a long time to complete, so applications may want to employ additional
  471. verification during the restore to detect failures early. This might e.g. include incremental
  472. verification of each chunk against the app hash (using bundled Merkle proofs), checksums to
  473. protect against data corruption by the disk or network, and so on. However, it is important to
  474. note that the only trusted information available is the app hash, and all other snapshot metadata
  475. can be spoofed by adversaries.
  476. Apps may also want to consider state sync denial-of-service vectors, where adversaries provide
  477. invalid or harmful snapshots to prevent nodes from joining the network. The application can
  478. counteract this by asking Tendermint to ban peers. As a last resort, node operators can use
  479. P2P configuration options to whitelist a set of trusted peers that can provide valid snapshots.
  480. #### Transition to Consensus
  481. Once the snapshot has been restored, Tendermint gathers additional information necessary for
  482. bootstrapping the node (e.g. chain ID, consensus parameters, validator sets, and block headers)
  483. from the genesis file and light client RPC servers. It also fetches and records the `AppVersion`
  484. from the ABCI application.
  485. Once the node is bootstrapped with this information and the restored state machine, it transitions
  486. to fast sync (if enabled) to fetch any remaining blocks up the the chain head, and then
  487. transitions to regular consensus operation. At this point the node operates like any other node,
  488. apart from having a truncated block history at the height of the restored snapshot.