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.

399 lines
16 KiB

6 years ago
6 years ago
6 years ago
6 years ago
  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
  15. Since Tendermint maintains three concurrent ABCI connections, it is typical
  16. for an application to maintain a distinct state for each, and for the states to
  17. be synchronized during `Commit`.
  18. ### Commit
  19. Application state should only be persisted to disk during `Commit`.
  20. Before `Commit` is called, Tendermint locks and flushes the mempool so that no new messages will
  21. be received on the mempool connection. This provides an opportunity to safely update all three
  22. states to the latest committed state at once.
  23. When `Commit` completes, it unlocks the mempool.
  24. Note that it is not possible to send transactions to Tendermint during `Commit` - if your app
  25. tries to send a `/broadcast_tx` to Tendermint during Commit, it will deadlock.
  26. ### Consensus Connection
  27. The Consensus Connection should maintain a `DeliverTxState` -
  28. the working state for block execution. It should be updated by the calls to
  29. `BeginBlock`, `DeliverTx`, and `EndBlock` during block execution and committed to
  30. disk as the "latest committed state" during `Commit`.
  31. Updates made to the DeliverTxState by each method call must be readable by each subsequent method -
  32. ie. the updates are linearizable.
  33. ### Mempool Connection
  34. The Mempool Connection should maintain a `CheckTxState`
  35. to sequentially process pending transactions in the mempool that have
  36. not yet been committed. It should be initialized to the latest committed state
  37. at the end of every `Commit`.
  38. The CheckTxState may be updated concurrently with the DeliverTxState, as
  39. messages may be sent concurrently on the Consensus and Mempool connections. However,
  40. before calling `Commit`, Tendermint will lock and flush the mempool connection,
  41. ensuring that all existing CheckTx are responded to and no new ones can
  42. begin.
  43. After `Commit`, CheckTx is run again on all transactions that remain in the
  44. node's local mempool after filtering those included in the block. To prevent the
  45. mempool from rechecking all transactions every time a block is committed, set
  46. the configuration option `mempool.recheck=false`.
  47. Finally, the mempool will unlock and new transactions can be processed through CheckTx again.
  48. Note that CheckTx doesn't have to check everything that affects transaction validity; the
  49. expensive things can be skipped. In fact, CheckTx doesn't have to check
  50. anything; it might say that any transaction is a valid transaction.
  51. Unlike DeliverTx, CheckTx is just there as
  52. a sort of weak filter to keep invalid transactions out of the blockchain. It's
  53. weak, because a Byzantine node doesn't care about CheckTx; it can propose a
  54. block full of invalid transactions if it wants.
  55. ### Info Connection
  56. The Info Connection should maintain a `QueryState` for answering queries from the user,
  57. and for initialization when Tendermint first starts up (both described further
  58. below).
  59. It should always contain the latest committed state associated with the
  60. latest committed block.
  61. QueryState should be set to the latest `DeliverTxState` at the end of every `Commit`,
  62. ie. after the full block has been processed and the state committed to disk.
  63. Otherwise it should never be modified.
  64. ## Transaction Results
  65. `ResponseCheckTx` and `ResponseDeliverTx` contain the same fields.
  66. The `Info` and `Log` fields are non-deterministic values for debugging/convenience purposes
  67. that are otherwise ignored.
  68. The `Data` field must be strictly deterministic, but can be arbitrary data.
  69. ### Gas
  70. Ethereum introduced the notion of `gas` as an abstract representation of the
  71. cost of resources used by nodes when processing transactions. Every operation in the
  72. Ethereum Virtual Machine uses some amount of gas, and gas can be accepted at a market-variable price.
  73. Users propose a maximum amount of gas for their transaction; if the tx uses less, they get
  74. the difference credited back. Tendermint adopts a similar abstraction,
  75. though uses it only optionally and weakly, allowing applications to define
  76. their own sense of the cost of execution.
  77. In Tendermint, the `ConsensusParams.BlockSize.MaxGas` limits the amount of `gas` that can be used in a block.
  78. The default value is `-1`, meaning no limit, or that the concept of gas is
  79. meaningless.
  80. Responses contain a `GasWanted` and `GasUsed` field. The former is the maximum
  81. amount of gas the sender of a tx is willing to use, and the later is how much it actually
  82. used. Applications should enforce that `GasUsed <= GasWanted` - ie. tx execution
  83. should halt before it can use more resources than it requested.
  84. When `MaxGas > -1`, Tendermint enforces the following rules:
  85. - `GasWanted <= MaxGas` for all txs in the mempool
  86. - `(sum of GasWanted in a block) <= MaxGas` when proposing a block
  87. If `MaxGas == -1`, no rules about gas are enforced.
  88. Note that Tendermint does not currently enforce anything about Gas in the consensus, only the mempool.
  89. This means it does not guarantee that committed blocks satisfy these rules!
  90. It is the application's responsibility to return non-zero response codes when gas limits are exceeded.
  91. The `GasUsed` field is ignored completely by Tendermint. That said, applications should enforce:
  92. - `GasUsed <= GasWanted` for any given transaction
  93. - `(sum of GasUsed in a block) <= MaxGas` for every block
  94. In the future, we intend to add a `Priority` field to the responses that can be
  95. used to explicitly prioritize txs in the mempool for inclusion in a block
  96. proposal. See [#1861](https://github.com/tendermint/tendermint/issues/1861).
  97. ### CheckTx
  98. If `Code != 0`, it will be rejected from the mempool and hence
  99. not broadcasted to other peers and not included in a proposal block.
  100. `Data` contains the result of the CheckTx transaction execution, if any. It is
  101. semantically meaningless to Tendermint.
  102. `Tags` include any tags for the execution, though since the transaction has not
  103. been committed yet, they are effectively ignored by Tendermint.
  104. ### DeliverTx
  105. If DeliverTx returns `Code != 0`, the transaction will be considered invalid,
  106. though it is still included in the block.
  107. `Data` contains the result of the CheckTx transaction execution, if any. It is
  108. semantically meaningless to Tendermint.
  109. Both the `Code` and `Data` are included in a structure that is hashed into the
  110. `LastResultsHash` of the next block header.
  111. `Tags` include any tags for the execution, which Tendermint will use to index
  112. the transaction by. This allows transactions to be queried according to what
  113. events took place during their execution.
  114. See issue [#1007](https://github.com/tendermint/tendermint/issues/1007) for how
  115. the tags will be hashed into the next block header.
  116. ## Validator Updates
  117. The application may set the validator set during InitChain, and update it during
  118. EndBlock.
  119. ### InitChain
  120. ResponseInitChain can return a list of validators.
  121. If the list is empty, Tendermint will use the validators loaded in the genesis
  122. file.
  123. If the list is not empty, Tendermint will use it for the validator set.
  124. This way the application can determine the initial validator set for the
  125. blockchain.
  126. ### EndBlock
  127. Updates to the Tendermint validator set can be made by returning
  128. `ValidatorUpdate` objects in the `ResponseEndBlock`:
  129. ```
  130. message ValidatorUpdate {
  131. PubKey pub_key
  132. int64 power
  133. }
  134. message PubKey {
  135. string type
  136. bytes data
  137. }
  138. ```
  139. The `pub_key` currently supports only one type:
  140. - `type = "ed25519" and`data = <raw 32-byte public key>`
  141. The `power` is the new voting power for the validator, with the
  142. following rules:
  143. - power must be non-negative
  144. - if power is 0, the validator must already exist, and will be removed from the
  145. validator set
  146. - if power is non-0:
  147. - if the validator does not already exist, it will be added to the validator
  148. set with the given power
  149. - if the validator does already exist, its power will be adjusted to the given power
  150. Note the updates returned in block `H` will only take effect at block `H+2`.
  151. ## Consensus Parameters
  152. ConsensusParams enforce certain limits in the blockchain, like the maximum size
  153. of blocks, amount of gas used in a block, and the maximum acceptable age of
  154. evidence. They can be set in InitChain and updated in EndBlock.
  155. ### BlockSize.MaxBytes
  156. The maximum size of a complete Amino encoded block.
  157. This is enforced by Tendermint consensus.
  158. This implies a maximum tx size that is this MaxBytes, less the expected size of
  159. the header, the validator set, and any included evidence in the block.
  160. Must have `0 < MaxBytes < 100 MB`.
  161. ### BlockSize.MaxGas
  162. The maximum of the sum of `GasWanted` in a proposed block.
  163. This is *not* enforced by Tendermint consensus.
  164. It is left to the app to enforce (ie. if txs are included past the
  165. limit, they should return non-zero codes). It is used by Tendermint to limit the
  166. txs included in a proposed block.
  167. Must have `MaxGas >= -1`.
  168. If `MaxGas == -1`, no limit is enforced.
  169. ### EvidenceParams.MaxAge
  170. This is the maximum age of evidence.
  171. This is enforced by Tendermint consensus.
  172. If a block includes evidence older than this, the block will be rejected
  173. (validators won't vote for it).
  174. Must have `0 < MaxAge`.
  175. ### Updates
  176. The application may set the consensus params during InitChain, and update them during
  177. EndBlock.
  178. #### InitChain
  179. ResponseInitChain includes a ConsensusParams.
  180. If its nil, Tendermint will use the params loaded in the genesis
  181. file. If it's not nil, Tendermint will use it.
  182. This way the application can determine the initial consensus params for the
  183. blockchain.
  184. #### EndBlock
  185. ResponseEndBlock includes a ConsensusParams.
  186. If its nil, Tendermint will do nothing.
  187. If it's not nil, Tendermint will use it.
  188. This way the application can update the consensus params over time.
  189. Note the updates returned in block `H` will take effect right away for block
  190. `H+1`.
  191. ## Query
  192. Query is a generic method with lots of flexibility to enable diverse sets
  193. of queries on application state. Tendermint makes use of Query to filter new peers
  194. based on ID and IP, and exposes Query to the user over RPC.
  195. Note that calls to Query are not replicated across nodes, but rather query the
  196. local node's state - hence they may return stale reads. For reads that require
  197. consensus, use a transaction.
  198. The most important use of Query is to return Merkle proofs of the application state at some height
  199. that can be used for efficient application-specific lite-clients.
  200. Note Tendermint has technically no requirements from the Query
  201. message for normal operation - that is, the ABCI app developer need not implement
  202. Query functionality if they do not wish too.
  203. ### Query Proofs
  204. The Tendermint block header includes a number of hashes, each providing an
  205. anchor for some type of proof about the blockchain. The `ValidatorsHash` enables
  206. quick verification of the validator set, the `DataHash` gives quick
  207. verification of the transactions included in the block, etc.
  208. The `AppHash` is unique in that it is application specific, and allows for
  209. application-specific Merkle proofs about the state of the application.
  210. While some applications keep all relevant state in the transactions themselves
  211. (like Bitcoin and its UTXOs), others maintain a separated state that is
  212. computed deterministically *from* transactions, but is not contained directly in
  213. the transactions themselves (like Ethereum contracts and accounts).
  214. For such applications, the `AppHash` provides a much more efficient way to verify lite-client proofs.
  215. ABCI applications can take advantage of more efficient lite-client proofs for
  216. their state as follows:
  217. - return the Merkle root of the deterministic application state in
  218. `ResponseCommit.Data`.
  219. - it will be included as the `AppHash` in the next block.
  220. - return efficient Merkle proofs about that application state in `ResponseQuery.Proof`
  221. that can be verified using the `AppHash` of the corresponding block.
  222. For instance, this allows an application's lite-client to verify proofs of
  223. absence in the application state, something which is much less efficient to do using the block hash.
  224. ### Peer Filtering
  225. When Tendermint connects to a peer, it sends two queries to the ABCI application
  226. using the following paths, with no additional data:
  227. - `/p2p/filter/addr/<IP:PORT>`, where `<IP:PORT>` denote the IP address and
  228. the port of the connection
  229. - `p2p/filter/id/<ID>`, where `<ID>` is the peer node ID (ie. the
  230. pubkey.Address() for the peer's PubKey)
  231. If either of these queries return a non-zero ABCI code, Tendermint will refuse
  232. to connect to the peer.
  233. ### Paths
  234. Queries are directed at paths, and may optionally include additional data.
  235. The expectation is for there to be some number of high level paths
  236. differentiating concerns, like `/p2p`, `/store`, and `/app`. Currently,
  237. Tendermint only uses `/p2p`, for filtering peers. For more advanced use, see the
  238. implementation of
  239. [Query in the Cosmos-SDK](https://github.com/cosmos/cosmos-sdk/blob/v0.23.1/baseapp/baseapp.go#L333).
  240. ## Crash Recovery
  241. On startup, Tendermint calls the `Info` method on the Info Connection to get the latest
  242. committed state of the app. The app MUST return information consistent with the
  243. last block it succesfully completed Commit for.
  244. 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
  245. failed during the Commit of block H, then `last_block_height = H-1` and
  246. `last_block_app_hash = <hash returned by Commit for block H-1, which is the hash in the header of block H>`.
  247. We now distinguish three heights, and describe how Tendermint syncs itself with
  248. the app.
  249. ```
  250. storeBlockHeight = height of the last block Tendermint saw a commit for
  251. stateBlockHeight = height of the last block for which Tendermint completed all
  252. block processing and saved all ABCI results to disk
  253. appBlockHeight = height of the last block for which ABCI app succesfully
  254. completed Commit
  255. ```
  256. Note we always have `storeBlockHeight >= stateBlockHeight` and `storeBlockHeight >= appBlockHeight`
  257. Note also we never call Commit on an ABCI app twice for the same height.
  258. The procedure is as follows.
  259. First, some simple start conditions:
  260. If `appBlockHeight == 0`, then call InitChain.
  261. If `storeBlockHeight == 0`, we're done.
  262. Now, some sanity checks:
  263. If `storeBlockHeight < appBlockHeight`, error
  264. If `storeBlockHeight < stateBlockHeight`, panic
  265. If `storeBlockHeight > stateBlockHeight+1`, panic
  266. Now, the meat:
  267. If `storeBlockHeight == stateBlockHeight && appBlockHeight < storeBlockHeight`,
  268. replay all blocks in full from `appBlockHeight` to `storeBlockHeight`.
  269. This happens if we completed processing the block, but the app forgot its height.
  270. If `storeBlockHeight == stateBlockHeight && appBlockHeight == storeBlockHeight`, we're done
  271. This happens if we crashed at an opportune spot.
  272. If `storeBlockHeight == stateBlockHeight+1`
  273. This happens if we started processing the block but didn't finish.
  274. If `appBlockHeight < stateBlockHeight`
  275. replay all blocks in full from `appBlockHeight` to `storeBlockHeight-1`,
  276. and replay the block at `storeBlockHeight` using the WAL.
  277. This happens if the app forgot the last block it committed.
  278. If `appBlockHeight == stateBlockHeight`,
  279. replay the last block (storeBlockHeight) in full.
  280. This happens if we crashed before the app finished Commit
  281. If appBlockHeight == storeBlockHeight {
  282. update the state using the saved ABCI responses but dont run the block against the real app.
  283. This happens if we crashed after the app finished Commit but before Tendermint saved the state.