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.

504 lines
17 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. # Application Development Guide
  2. ## XXX
  3. This page is undergoing deprecation. All content is being moved to the new [home
  4. of the ABCI specification](../spec/abci/README.md).
  5. ## ABCI Design
  6. The purpose of ABCI is to provide a clean interface between state
  7. transition machines on one computer and the mechanics of their
  8. replication across multiple computers. The former we call 'application
  9. logic' and the latter the 'consensus engine'. Application logic
  10. validates transactions and optionally executes transactions against some
  11. persistent state. A consensus engine ensures all transactions are
  12. replicated in the same order on every machine. We call each machine in a
  13. consensus engine a 'validator', and each validator runs the same
  14. transactions through the same application logic. In particular, we are
  15. interested in blockchain-style consensus engines, where transactions are
  16. committed in hash-linked blocks.
  17. The ABCI design has a few distinct components:
  18. - message protocol
  19. - pairs of request and response messages
  20. - consensus makes requests, application responds
  21. - defined using protobuf
  22. - server/client
  23. - consensus engine runs the client
  24. - application runs the server
  25. - two implementations:
  26. - async raw bytes
  27. - grpc
  28. - blockchain protocol
  29. - abci is connection oriented
  30. - Tendermint Core maintains three connections:
  31. - [mempool connection](#mempool-connection): for checking if
  32. transactions should be relayed before they are committed;
  33. only uses `CheckTx`
  34. - [consensus connection](#consensus-connection): for executing
  35. transactions that have been committed. Message sequence is
  36. -for every block -`BeginBlock, [DeliverTx, ...], EndBlock, Commit`
  37. - [query connection](#query-connection): for querying the
  38. application state; only uses Query and Info
  39. The mempool and consensus logic act as clients, and each maintains an
  40. open ABCI connection with the application, which hosts an ABCI server.
  41. Shown are the request and response types sent on each connection.
  42. Most of the examples below are from [kvstore
  43. application](https://github.com/tendermint/tendermint/blob/master/abci/example/kvstore/kvstore.go),
  44. which is a part of the abci repo. [persistent_kvstore
  45. application](https://github.com/tendermint/tendermint/blob/master/abci/example/kvstore/persistent_kvstore.go)
  46. is used to show `BeginBlock`, `EndBlock` and `InitChain` example
  47. implementations.
  48. ## Blockchain Protocol
  49. In ABCI, a transaction is simply an arbitrary length byte-array. It is
  50. the application's responsibility to define the transaction codec as they
  51. please, and to use it for both CheckTx and DeliverTx.
  52. Note that there are two distinct means for running transactions,
  53. corresponding to stages of 'awareness' of the transaction in the
  54. network. The first stage is when a transaction is received by a
  55. validator from a client into the so-called mempool or transaction pool
  56. -this is where we use CheckTx. The second is when the transaction is
  57. successfully committed on more than 2/3 of validators - where we use
  58. DeliverTx. In the former case, it may not be necessary to run all the
  59. state transitions associated with the transaction, as the transaction
  60. may not ultimately be committed until some much later time, when the
  61. result of its execution will be different. For instance, an Ethereum
  62. ABCI app would check signatures and amounts in CheckTx, but would not
  63. actually execute any contract code until the DeliverTx, so as to avoid
  64. executing state transitions that have not been finalized.
  65. To formalize the distinction further, two explicit ABCI connections are
  66. made between Tendermint Core and the application: the mempool connection
  67. and the consensus connection. We also make a third connection, the query
  68. connection, to query the local state of the app.
  69. ### Mempool Connection
  70. The mempool connection is used _only_ for CheckTx requests. Transactions
  71. are run using CheckTx in the same order they were received by the
  72. validator. If the CheckTx returns `OK`, the transaction is kept in
  73. memory and relayed to other peers in the same order it was received.
  74. Otherwise, it is discarded.
  75. CheckTx requests run concurrently with block processing; so they should
  76. run against a copy of the main application state which is reset after
  77. every block. This copy is necessary to track transitions made by a
  78. sequence of CheckTx requests before they are included in a block. When a
  79. block is committed, the application must ensure to reset the mempool
  80. state to the latest committed state. Tendermint Core will then filter
  81. through all transactions in the mempool, removing any that were included
  82. in the block, and re-run the rest using CheckTx against the post-Commit
  83. mempool state (this behaviour can be turned off with
  84. `[mempool] recheck = false`).
  85. In go:
  86. ```
  87. func (app *KVStoreApplication) CheckTx(req types.RequestCheckTx) types.ResponseCheckTx {
  88. return types.ResponseCheckTx{Code: code.CodeTypeOK, GasWanted: 1}
  89. }
  90. ```
  91. In Java:
  92. ```
  93. ResponseCheckTx requestCheckTx(RequestCheckTx req) {
  94. byte[] transaction = req.getTx().toByteArray();
  95. // validate transaction
  96. if (notValid) {
  97. return ResponseCheckTx.newBuilder().setCode(CodeType.BadNonce).setLog("invalid tx").build();
  98. } else {
  99. return ResponseCheckTx.newBuilder().setCode(CodeType.OK).build();
  100. }
  101. }
  102. ```
  103. ### Replay Protection
  104. To prevent old transactions from being replayed, CheckTx must implement
  105. replay protection.
  106. Tendermint provides the first defence layer by keeping a lightweight
  107. in-memory cache of 100k (`[mempool] cache_size`) last transactions in
  108. the mempool. If Tendermint is just started or the clients sent more than
  109. 100k transactions, old transactions may be sent to the application. So
  110. it is important CheckTx implements some logic to handle them.
  111. If there are cases in your application where a transaction may become invalid in some
  112. future state, you probably want to disable Tendermint's
  113. cache. You can do that by setting `[mempool] cache_size = 0` in the
  114. config.
  115. ### Consensus Connection
  116. The consensus connection is used only when a new block is committed, and
  117. communicates all information from the block in a series of requests:
  118. `BeginBlock, [DeliverTx, ...], EndBlock, Commit`. That is, when a block
  119. is committed in the consensus, we send a list of DeliverTx requests (one
  120. for each transaction) sandwiched by BeginBlock and EndBlock requests,
  121. and followed by a Commit.
  122. ### DeliverTx
  123. DeliverTx is the workhorse of the blockchain. Tendermint sends the
  124. DeliverTx requests asynchronously but in order, and relies on the
  125. underlying socket protocol (ie. TCP) to ensure they are received by the
  126. app in order. They have already been ordered in the global consensus by
  127. the Tendermint protocol.
  128. DeliverTx returns a abci.Result, which includes a Code, Data, and Log.
  129. The code may be non-zero (non-OK), meaning the corresponding transaction
  130. should have been rejected by the mempool, but may have been included in
  131. a block by a Byzantine proposer.
  132. The block header will be updated (TODO) to include some commitment to
  133. the results of DeliverTx, be it a bitarray of non-OK transactions, or a
  134. merkle root of the data returned by the DeliverTx requests, or both.
  135. In go:
  136. ```
  137. // tx is either "key=value" or just arbitrary bytes
  138. func (app *KVStoreApplication) DeliverTx(req types.RequestDeliverTx) types.ResponseDeliverTx {
  139. var key, value []byte
  140. parts := bytes.Split(req.Tx, []byte("="))
  141. if len(parts) == 2 {
  142. key, value = parts[0], parts[1]
  143. } else {
  144. key, value = req.Tx, req.Tx
  145. }
  146. app.state.db.Set(prefixKey(key), value)
  147. app.state.Size += 1
  148. events := []types.Event{
  149. {
  150. Type: "app",
  151. Attributes: []cmn.KVPair{
  152. {Key: []byte("creator"), Value: []byte("Cosmoshi Netowoko")},
  153. {Key: []byte("key"), Value: key},
  154. },
  155. },
  156. }
  157. return types.ResponseDeliverTx{Code: code.CodeTypeOK, Events: events}
  158. }
  159. ```
  160. In Java:
  161. ```
  162. /**
  163. * Using Protobuf types from the protoc compiler, we always start with a byte[]
  164. */
  165. ResponseDeliverTx deliverTx(RequestDeliverTx request) {
  166. byte[] transaction = request.getTx().toByteArray();
  167. // validate your transaction
  168. if (notValid) {
  169. return ResponseDeliverTx.newBuilder().setCode(CodeType.BadNonce).setLog("transaction was invalid").build();
  170. } else {
  171. ResponseDeliverTx.newBuilder().setCode(CodeType.OK).build();
  172. }
  173. }
  174. ```
  175. ### Commit
  176. Once all processing of the block is complete, Tendermint sends the
  177. Commit request and blocks waiting for a response. While the mempool may
  178. run concurrently with block processing (the BeginBlock, DeliverTxs, and
  179. EndBlock), it is locked for the Commit request so that its state can be
  180. safely updated during Commit. This means the app _MUST NOT_ do any
  181. blocking communication with the mempool (ie. broadcast_tx) during
  182. Commit, or there will be deadlock. Note also that all remaining
  183. transactions in the mempool are replayed on the mempool connection
  184. (CheckTx) following a commit.
  185. The app should respond to the Commit request with a byte array, which is
  186. the deterministic state root of the application. It is included in the
  187. header of the next block. It can be used to provide easily verified
  188. Merkle-proofs of the state of the application.
  189. It is expected that the app will persist state to disk on Commit. The
  190. option to have all transactions replayed from some previous block is the
  191. job of the [Handshake](#handshake).
  192. In go:
  193. ```
  194. func (app *KVStoreApplication) Commit() types.ResponseCommit {
  195. // Using a memdb - just return the big endian size of the db
  196. appHash := make([]byte, 8)
  197. binary.PutVarint(appHash, app.state.Size)
  198. app.state.AppHash = appHash
  199. app.state.Height += 1
  200. saveState(app.state)
  201. return types.ResponseCommit{Data: appHash}
  202. }
  203. ```
  204. In Java:
  205. ```
  206. ResponseCommit requestCommit(RequestCommit requestCommit) {
  207. // update the internal app-state
  208. byte[] newAppState = calculateAppState();
  209. // and return it to the node
  210. return ResponseCommit.newBuilder().setCode(CodeType.OK).setData(ByteString.copyFrom(newAppState)).build();
  211. }
  212. ```
  213. ### BeginBlock
  214. The BeginBlock request can be used to run some code at the beginning of
  215. every block. It also allows Tendermint to send the current block hash
  216. and header to the application, before it sends any of the transactions.
  217. The app should remember the latest height and header (ie. from which it
  218. has run a successful Commit) so that it can tell Tendermint where to
  219. pick up from when it restarts. See information on the Handshake, below.
  220. In go:
  221. ```
  222. // Track the block hash and header information
  223. func (app *PersistentKVStoreApplication) BeginBlock(req types.RequestBeginBlock) types.ResponseBeginBlock {
  224. // reset valset changes
  225. app.ValUpdates = make([]types.ValidatorUpdate, 0)
  226. return types.ResponseBeginBlock{}
  227. }
  228. ```
  229. In Java:
  230. ```
  231. /*
  232. * all types come from protobuf definition
  233. */
  234. ResponseBeginBlock requestBeginBlock(RequestBeginBlock req) {
  235. Header header = req.getHeader();
  236. byte[] prevAppHash = header.getAppHash().toByteArray();
  237. long prevHeight = header.getHeight();
  238. long numTxs = header.getNumTxs();
  239. // run your pre-block logic. Maybe prepare a state snapshot, message components, etc
  240. return ResponseBeginBlock.newBuilder().build();
  241. }
  242. ```
  243. ### EndBlock
  244. The EndBlock request can be used to run some code at the end of every block.
  245. Additionally, the response may contain a list of validators, which can be used
  246. to update the validator set. To add a new validator or update an existing one,
  247. simply include them in the list returned in the EndBlock response. To remove
  248. one, include it in the list with a `power` equal to `0`. Validator's `address`
  249. field can be left empty. Tendermint core will take care of updating the
  250. validator set. Note the change in voting power must be strictly less than 1/3
  251. per block if you want a light client to be able to prove the transition
  252. externally. See the [light client
  253. docs](https://godoc.org/github.com/tendermint/tendermint/lite#hdr-How_We_Track_Validators)
  254. for details on how it tracks validators.
  255. In go:
  256. ```
  257. // Update the validator set
  258. func (app *PersistentKVStoreApplication) EndBlock(req types.RequestEndBlock) types.ResponseEndBlock {
  259. return types.ResponseEndBlock{ValidatorUpdates: app.ValUpdates}
  260. }
  261. ```
  262. In Java:
  263. ```
  264. /*
  265. * Assume that one validator changes. The new validator has a power of 10
  266. */
  267. ResponseEndBlock requestEndBlock(RequestEndBlock req) {
  268. final long currentHeight = req.getHeight();
  269. final byte[] validatorPubKey = getValPubKey();
  270. ResponseEndBlock.Builder builder = ResponseEndBlock.newBuilder();
  271. builder.addDiffs(1, Types.Validator.newBuilder().setPower(10L).setPubKey(ByteString.copyFrom(validatorPubKey)).build());
  272. return builder.build();
  273. }
  274. ```
  275. ### Query Connection
  276. This connection is used to query the application without engaging
  277. consensus. It's exposed over the tendermint core rpc, so clients can
  278. query the app without exposing a server on the app itself, but they must
  279. serialize each query as a single byte array. Additionally, certain
  280. "standardized" queries may be used to inform local decisions, for
  281. instance about which peers to connect to.
  282. Tendermint Core currently uses the Query connection to filter peers upon
  283. connecting, according to IP address or node ID. For instance,
  284. returning non-OK ABCI response to either of the following queries will
  285. cause Tendermint to not connect to the corresponding peer:
  286. - `p2p/filter/addr/<ip addr>`, where `<ip addr>` is an IP address.
  287. - `p2p/filter/id/<id>`, where `<is>` is the hex-encoded node ID (the hash of
  288. the node's p2p pubkey).
  289. Note: these query formats are subject to change!
  290. In go:
  291. ```
  292. func (app *KVStoreApplication) Query(reqQuery types.RequestQuery) (resQuery types.ResponseQuery) {
  293. if reqQuery.Prove {
  294. value := app.state.db.Get(prefixKey(reqQuery.Data))
  295. resQuery.Index = -1 // TODO make Proof return index
  296. resQuery.Key = reqQuery.Data
  297. resQuery.Value = value
  298. if value != nil {
  299. resQuery.Log = "exists"
  300. } else {
  301. resQuery.Log = "does not exist"
  302. }
  303. return
  304. } else {
  305. resQuery.Key = reqQuery.Data
  306. value := app.state.db.Get(prefixKey(reqQuery.Data))
  307. resQuery.Value = value
  308. if value != nil {
  309. resQuery.Log = "exists"
  310. } else {
  311. resQuery.Log = "does not exist"
  312. }
  313. return
  314. }
  315. }
  316. ```
  317. In Java:
  318. ```
  319. ResponseQuery requestQuery(RequestQuery req) {
  320. final boolean isProveQuery = req.getProve();
  321. final ResponseQuery.Builder responseBuilder = ResponseQuery.newBuilder();
  322. byte[] queryData = req.getData().toByteArray();
  323. if (isProveQuery) {
  324. com.app.example.QueryResultWithProof result = generateQueryResultWithProof(queryData);
  325. responseBuilder.setIndex(result.getLeftIndex());
  326. responseBuilder.setKey(req.getData());
  327. responseBuilder.setValue(result.getValueOrNull(0));
  328. responseBuilder.setHeight(result.getHeight());
  329. responseBuilder.setProof(result.getProof());
  330. responseBuilder.setLog(result.getLogValue());
  331. } else {
  332. com.app.example.QueryResult result = generateQueryResult(queryData);
  333. responseBuilder.setIndex(result.getIndex());
  334. responseBuilder.setValue(result.getValue());
  335. responseBuilder.setLog(result.getLogValue());
  336. }
  337. responseBuilder.setIndex(result.getIndex());
  338. responseBuilder.setValue(ByteString.copyFrom(result.getValue()));
  339. responseBuilder.setLog(result.getLogValue());
  340. }
  341. return responseBuilder.build();
  342. }
  343. ```
  344. ### Handshake
  345. When the app or tendermint restarts, they need to sync to a common
  346. height. When an ABCI connection is first established, Tendermint will
  347. call `Info` on the Query connection. The response should contain the
  348. LastBlockHeight and LastBlockAppHash - the former is the last block for
  349. which the app ran Commit successfully, the latter is the response from
  350. that Commit.
  351. Using this information, Tendermint will determine what needs to be
  352. replayed, if anything, against the app, to ensure both Tendermint and
  353. the app are synced to the latest block height.
  354. If the app returns a LastBlockHeight of 0, Tendermint will just replay
  355. all blocks.
  356. In go:
  357. ```
  358. func (app *KVStoreApplication) Info(req types.RequestInfo) (resInfo types.ResponseInfo) {
  359. return types.ResponseInfo{
  360. Data: fmt.Sprintf("{\"size\":%v}", app.state.Size),
  361. Version: version.ABCIVersion,
  362. AppVersion: ProtocolVersion.Uint64(),
  363. }
  364. }
  365. ```
  366. In Java:
  367. ```
  368. ResponseInfo requestInfo(RequestInfo req) {
  369. final byte[] lastAppHash = getLastAppHash();
  370. final long lastHeight = getLastHeight();
  371. return ResponseInfo.newBuilder().setLastBlockAppHash(ByteString.copyFrom(lastAppHash)).setLastBlockHeight(lastHeight).build();
  372. }
  373. ```
  374. ### Genesis
  375. `InitChain` will be called once upon the genesis. `params` includes the
  376. initial validator set. Later on, it may be extended to take parts of the
  377. consensus params.
  378. In go:
  379. ```
  380. // Save the validators in the merkle tree
  381. func (app *PersistentKVStoreApplication) InitChain(req types.RequestInitChain) types.ResponseInitChain {
  382. for _, v := range req.Validators {
  383. r := app.updateValidator(v)
  384. if r.IsErr() {
  385. app.logger.Error("Error updating validators", "r", r)
  386. }
  387. }
  388. return types.ResponseInitChain{}
  389. }
  390. ```
  391. In Java:
  392. ```
  393. /*
  394. * all types come from protobuf definition
  395. */
  396. ResponseInitChain requestInitChain(RequestInitChain req) {
  397. final int validatorsCount = req.getValidatorsCount();
  398. final List<Types.Validator> validatorsList = req.getValidatorsList();
  399. validatorsList.forEach((validator) -> {
  400. long power = validator.getPower();
  401. byte[] validatorPubKey = validator.getPubKey().toByteArray();
  402. // do somehing for validator setup in app
  403. });
  404. return ResponseInitChain.newBuilder().build();
  405. }
  406. ```