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.

579 lines
20 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
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. ## Message Protocol
  43. The message protocol consists of pairs of requests and responses. Some
  44. messages have no fields, while others may include byte-arrays, strings,
  45. or integers. See the `message Request` and `message Response`
  46. definitions in [the protobuf definition
  47. file](https://github.com/tendermint/tendermint/blob/develop/abci/types/types.proto),
  48. and the [protobuf
  49. documentation](https://developers.google.com/protocol-buffers/docs/overview)
  50. for more details.
  51. For each request, a server should respond with the corresponding
  52. response, where order of requests is preserved in the order of
  53. responses.
  54. ## Server
  55. To use ABCI in your programming language of choice, there must be a ABCI
  56. server in that language. Tendermint supports two kinds of implementation
  57. of the server:
  58. - Asynchronous, raw socket server (Tendermint Socket Protocol, also
  59. known as TSP or Teaspoon)
  60. - GRPC
  61. Both can be tested using the `abci-cli` by setting the `--abci` flag
  62. appropriately (ie. to `socket` or `grpc`).
  63. See examples, in various stages of maintenance, in
  64. [Go](https://github.com/tendermint/tendermint/tree/develop/abci/server),
  65. [JavaScript](https://github.com/tendermint/js-abci),
  66. [Python](https://github.com/tendermint/tendermint/tree/develop/abci/example/python3/abci),
  67. [C++](https://github.com/mdyring/cpp-tmsp), and
  68. [Java](https://github.com/jTendermint/jabci).
  69. ### GRPC
  70. If GRPC is available in your language, this is the easiest approach,
  71. though it will have significant performance overhead.
  72. To get started with GRPC, copy in the [protobuf
  73. file](https://github.com/tendermint/tendermint/blob/develop/abci/types/types.proto)
  74. and compile it using the GRPC plugin for your language. For instance,
  75. for golang, the command is `protoc --go_out=plugins=grpc:. types.proto`.
  76. See the [grpc documentation for more details](http://www.grpc.io/docs/).
  77. `protoc` will autogenerate all the necessary code for ABCI client and
  78. server in your language, including whatever interface your application
  79. must satisfy to be used by the ABCI server for handling requests.
  80. ### TSP
  81. If GRPC is not available in your language, or you require higher
  82. performance, or otherwise enjoy programming, you may implement your own
  83. ABCI server using the Tendermint Socket Protocol, known affectionately
  84. as Teaspoon. The first step is still to auto-generate the relevant data
  85. types and codec in your language using `protoc`. Messages coming over
  86. the socket are proto3 encoded, but additionally length-prefixed to
  87. facilitate use as a streaming protocol. proto3 doesn't have an
  88. official length-prefix standard, so we use our own. The first byte in
  89. the prefix represents the length of the Big Endian encoded length. The
  90. remaining bytes in the prefix are the Big Endian encoded length.
  91. For example, if the proto3 encoded ABCI message is 0xDEADBEEF (4
  92. bytes), the length-prefixed message is 0x0104DEADBEEF. If the proto3
  93. encoded ABCI message is 65535 bytes long, the length-prefixed message
  94. would be like 0x02FFFF....
  95. Note this prefixing does not apply for grpc.
  96. An ABCI server must also be able to support multiple connections, as
  97. Tendermint uses three connections.
  98. ## Client
  99. There are currently two use-cases for an ABCI client. One is a testing
  100. tool, as in the `abci-cli`, which allows ABCI requests to be sent via
  101. command line. The other is a consensus engine, such as Tendermint Core,
  102. which makes requests to the application every time a new transaction is
  103. received or a block is committed.
  104. It is unlikely that you will need to implement a client. For details of
  105. our client, see
  106. [here](https://github.com/tendermint/tendermint/tree/develop/abci/client).
  107. Most of the examples below are from [kvstore
  108. application](https://github.com/tendermint/tendermint/blob/develop/abci/example/kvstore/kvstore.go),
  109. which is a part of the abci repo. [persistent_kvstore
  110. application](https://github.com/tendermint/tendermint/blob/develop/abci/example/kvstore/persistent_kvstore.go)
  111. is used to show `BeginBlock`, `EndBlock` and `InitChain` example
  112. implementations.
  113. ## Blockchain Protocol
  114. In ABCI, a transaction is simply an arbitrary length byte-array. It is
  115. the application's responsibility to define the transaction codec as they
  116. please, and to use it for both CheckTx and DeliverTx.
  117. Note that there are two distinct means for running transactions,
  118. corresponding to stages of 'awareness' of the transaction in the
  119. network. The first stage is when a transaction is received by a
  120. validator from a client into the so-called mempool or transaction pool
  121. -this is where we use CheckTx. The second is when the transaction is
  122. successfully committed on more than 2/3 of validators - where we use
  123. DeliverTx. In the former case, it may not be necessary to run all the
  124. state transitions associated with the transaction, as the transaction
  125. may not ultimately be committed until some much later time, when the
  126. result of its execution will be different. For instance, an Ethereum
  127. ABCI app would check signatures and amounts in CheckTx, but would not
  128. actually execute any contract code until the DeliverTx, so as to avoid
  129. executing state transitions that have not been finalized.
  130. To formalize the distinction further, two explicit ABCI connections are
  131. made between Tendermint Core and the application: the mempool connection
  132. and the consensus connection. We also make a third connection, the query
  133. connection, to query the local state of the app.
  134. ### Mempool Connection
  135. The mempool connection is used _only_ for CheckTx requests. Transactions
  136. are run using CheckTx in the same order they were received by the
  137. validator. If the CheckTx returns `OK`, the transaction is kept in
  138. memory and relayed to other peers in the same order it was received.
  139. Otherwise, it is discarded.
  140. CheckTx requests run concurrently with block processing; so they should
  141. run against a copy of the main application state which is reset after
  142. every block. This copy is necessary to track transitions made by a
  143. sequence of CheckTx requests before they are included in a block. When a
  144. block is committed, the application must ensure to reset the mempool
  145. state to the latest committed state. Tendermint Core will then filter
  146. through all transactions in the mempool, removing any that were included
  147. in the block, and re-run the rest using CheckTx against the post-Commit
  148. mempool state (this behaviour can be turned off with
  149. `[mempool] recheck = false`).
  150. In go:
  151. ```
  152. func (app *KVStoreApplication) CheckTx(tx []byte) types.Result {
  153. return types.OK
  154. }
  155. ```
  156. In Java:
  157. ```
  158. ResponseCheckTx requestCheckTx(RequestCheckTx req) {
  159. byte[] transaction = req.getTx().toByteArray();
  160. // validate transaction
  161. if (notValid) {
  162. return ResponseCheckTx.newBuilder().setCode(CodeType.BadNonce).setLog("invalid tx").build();
  163. } else {
  164. return ResponseCheckTx.newBuilder().setCode(CodeType.OK).build();
  165. }
  166. }
  167. ```
  168. ### Replay Protection
  169. To prevent old transactions from being replayed, CheckTx must implement
  170. replay protection.
  171. Tendermint provides the first defence layer by keeping a lightweight
  172. in-memory cache of 100k (`[mempool] cache_size`) last transactions in
  173. the mempool. If Tendermint is just started or the clients sent more than
  174. 100k transactions, old transactions may be sent to the application. So
  175. it is important CheckTx implements some logic to handle them.
  176. There are cases where a transaction will (or may) become valid in some
  177. future state, in which case you probably want to disable Tendermint's
  178. cache. You can do that by setting `[mempool] cache_size = 0` in the
  179. config.
  180. ### Consensus Connection
  181. The consensus connection is used only when a new block is committed, and
  182. communicates all information from the block in a series of requests:
  183. `BeginBlock, [DeliverTx, ...], EndBlock, Commit`. That is, when a block
  184. is committed in the consensus, we send a list of DeliverTx requests (one
  185. for each transaction) sandwiched by BeginBlock and EndBlock requests,
  186. and followed by a Commit.
  187. ### DeliverTx
  188. DeliverTx is the workhorse of the blockchain. Tendermint sends the
  189. DeliverTx requests asynchronously but in order, and relies on the
  190. underlying socket protocol (ie. TCP) to ensure they are received by the
  191. app in order. They have already been ordered in the global consensus by
  192. the Tendermint protocol.
  193. DeliverTx returns a abci.Result, which includes a Code, Data, and Log.
  194. The code may be non-zero (non-OK), meaning the corresponding transaction
  195. should have been rejected by the mempool, but may have been included in
  196. a block by a Byzantine proposer.
  197. The block header will be updated (TODO) to include some commitment to
  198. the results of DeliverTx, be it a bitarray of non-OK transactions, or a
  199. merkle root of the data returned by the DeliverTx requests, or both.
  200. In go:
  201. ```
  202. // tx is either "key=value" or just arbitrary bytes
  203. func (app *KVStoreApplication) DeliverTx(tx []byte) types.Result {
  204. parts := strings.Split(string(tx), "=")
  205. if len(parts) == 2 {
  206. app.state.Set([]byte(parts[0]), []byte(parts[1]))
  207. } else {
  208. app.state.Set(tx, tx)
  209. }
  210. return types.OK
  211. }
  212. ```
  213. In Java:
  214. ```
  215. /**
  216. * Using Protobuf types from the protoc compiler, we always start with a byte[]
  217. */
  218. ResponseDeliverTx deliverTx(RequestDeliverTx request) {
  219. byte[] transaction = request.getTx().toByteArray();
  220. // validate your transaction
  221. if (notValid) {
  222. return ResponseDeliverTx.newBuilder().setCode(CodeType.BadNonce).setLog("transaction was invalid").build();
  223. } else {
  224. ResponseDeliverTx.newBuilder().setCode(CodeType.OK).build();
  225. }
  226. }
  227. ```
  228. ### Commit
  229. Once all processing of the block is complete, Tendermint sends the
  230. Commit request and blocks waiting for a response. While the mempool may
  231. run concurrently with block processing (the BeginBlock, DeliverTxs, and
  232. EndBlock), it is locked for the Commit request so that its state can be
  233. safely reset during Commit. This means the app _MUST NOT_ do any
  234. blocking communication with the mempool (ie. broadcast_tx) during
  235. Commit, or there will be deadlock. Note also that all remaining
  236. transactions in the mempool are replayed on the mempool connection
  237. (CheckTx) following a commit.
  238. The app should respond to the Commit request with a byte array, which is
  239. the deterministic state root of the application. It is included in the
  240. header of the next block. It can be used to provide easily verified
  241. Merkle-proofs of the state of the application.
  242. It is expected that the app will persist state to disk on Commit. The
  243. option to have all transactions replayed from some previous block is the
  244. job of the [Handshake](#handshake).
  245. In go:
  246. ```
  247. func (app *KVStoreApplication) Commit() types.Result {
  248. hash := app.state.Hash()
  249. return types.NewResultOK(hash, "")
  250. }
  251. ```
  252. In Java:
  253. ```
  254. ResponseCommit requestCommit(RequestCommit requestCommit) {
  255. // update the internal app-state
  256. byte[] newAppState = calculateAppState();
  257. // and return it to the node
  258. return ResponseCommit.newBuilder().setCode(CodeType.OK).setData(ByteString.copyFrom(newAppState)).build();
  259. }
  260. ```
  261. ### BeginBlock
  262. The BeginBlock request can be used to run some code at the beginning of
  263. every block. It also allows Tendermint to send the current block hash
  264. and header to the application, before it sends any of the transactions.
  265. The app should remember the latest height and header (ie. from which it
  266. has run a successful Commit) so that it can tell Tendermint where to
  267. pick up from when it restarts. See information on the Handshake, below.
  268. In go:
  269. ```
  270. // Track the block hash and header information
  271. func (app *PersistentKVStoreApplication) BeginBlock(params types.RequestBeginBlock) {
  272. // update latest block info
  273. app.blockHeader = params.Header
  274. // reset valset changes
  275. app.changes = make([]*types.Validator, 0)
  276. }
  277. ```
  278. In Java:
  279. ```
  280. /*
  281. * all types come from protobuf definition
  282. */
  283. ResponseBeginBlock requestBeginBlock(RequestBeginBlock req) {
  284. Header header = req.getHeader();
  285. byte[] prevAppHash = header.getAppHash().toByteArray();
  286. long prevHeight = header.getHeight();
  287. long numTxs = header.getNumTxs();
  288. // run your pre-block logic. Maybe prepare a state snapshot, message components, etc
  289. return ResponseBeginBlock.newBuilder().build();
  290. }
  291. ```
  292. ### EndBlock
  293. The EndBlock request can be used to run some code at the end of every block.
  294. Additionally, the response may contain a list of validators, which can be used
  295. to update the validator set. To add a new validator or update an existing one,
  296. simply include them in the list returned in the EndBlock response. To remove
  297. one, include it in the list with a `power` equal to `0`. Validator's `address`
  298. field can be left empty. Tendermint core will take care of updating the
  299. validator set. Note the change in voting power must be strictly less than 1/3
  300. per block if you want a light client to be able to prove the transition
  301. externally. See the [light client
  302. docs](https://godoc.org/github.com/tendermint/tendermint/lite#hdr-How_We_Track_Validators)
  303. for details on how it tracks validators.
  304. In go:
  305. ```
  306. // Update the validator set
  307. func (app *PersistentKVStoreApplication) EndBlock(req types.RequestEndBlock) types.ResponseEndBlock {
  308. return types.ResponseEndBlock{ValidatorUpdates: app.ValUpdates}
  309. }
  310. ```
  311. In Java:
  312. ```
  313. /*
  314. * Assume that one validator changes. The new validator has a power of 10
  315. */
  316. ResponseEndBlock requestEndBlock(RequestEndBlock req) {
  317. final long currentHeight = req.getHeight();
  318. final byte[] validatorPubKey = getValPubKey();
  319. ResponseEndBlock.Builder builder = ResponseEndBlock.newBuilder();
  320. builder.addDiffs(1, Types.Validator.newBuilder().setPower(10L).setPubKey(ByteString.copyFrom(validatorPubKey)).build());
  321. return builder.build();
  322. }
  323. ```
  324. ### Query Connection
  325. This connection is used to query the application without engaging
  326. consensus. It's exposed over the tendermint core rpc, so clients can
  327. query the app without exposing a server on the app itself, but they must
  328. serialize each query as a single byte array. Additionally, certain
  329. "standardized" queries may be used to inform local decisions, for
  330. instance about which peers to connect to.
  331. Tendermint Core currently uses the Query connection to filter peers upon
  332. connecting, according to IP address or node ID. For instance,
  333. returning non-OK ABCI response to either of the following queries will
  334. cause Tendermint to not connect to the corresponding peer:
  335. - `p2p/filter/addr/<ip addr>`, where `<ip addr>` is an IP address.
  336. - `p2p/filter/id/<id>`, where `<is>` is the hex-encoded node ID (the hash of
  337. the node's p2p pubkey).
  338. Note: these query formats are subject to change!
  339. In go:
  340. ```
  341. func (app *KVStoreApplication) Query(reqQuery types.RequestQuery) (resQuery types.ResponseQuery) {
  342. if reqQuery.Prove {
  343. value, proof, exists := app.state.GetWithProof(reqQuery.Data)
  344. resQuery.Index = -1 // TODO make Proof return index
  345. resQuery.Key = reqQuery.Data
  346. resQuery.Value = value
  347. resQuery.Proof = proof
  348. if exists {
  349. resQuery.Log = "exists"
  350. } else {
  351. resQuery.Log = "does not exist"
  352. }
  353. return
  354. } else {
  355. index, value, exists := app.state.Get(reqQuery.Data)
  356. resQuery.Index = int64(index)
  357. resQuery.Value = value
  358. if exists {
  359. resQuery.Log = "exists"
  360. } else {
  361. resQuery.Log = "does not exist"
  362. }
  363. return
  364. }
  365. }
  366. return
  367. } else {
  368. index, value, exists := app.state.Get(reqQuery.Data)
  369. resQuery.Index = int64(index)
  370. resQuery.Value = value
  371. if exists {
  372. resQuery.Log = "exists"
  373. } else {
  374. resQuery.Log = "does not exist"
  375. }
  376. return
  377. }
  378. }
  379. ```
  380. In Java:
  381. ```
  382. ResponseQuery requestQuery(RequestQuery req) {
  383. final boolean isProveQuery = req.getProve();
  384. final ResponseQuery.Builder responseBuilder = ResponseQuery.newBuilder();
  385. byte[] queryData = req.getData().toByteArray();
  386. if (isProveQuery) {
  387. com.app.example.QueryResultWithProof result = generateQueryResultWithProof(queryData);
  388. responseBuilder.setIndex(result.getLeftIndex());
  389. responseBuilder.setKey(req.getData());
  390. responseBuilder.setValue(result.getValueOrNull(0));
  391. responseBuilder.setHeight(result.getHeight());
  392. responseBuilder.setProof(result.getProof());
  393. responseBuilder.setLog(result.getLogValue());
  394. } else {
  395. com.app.example.QueryResult result = generateQueryResult(queryData);
  396. responseBuilder.setIndex(result.getIndex());
  397. responseBuilder.setValue(result.getValue());
  398. responseBuilder.setLog(result.getLogValue());
  399. }
  400. responseBuilder.setIndex(result.getIndex());
  401. responseBuilder.setValue(ByteString.copyFrom(result.getValue()));
  402. responseBuilder.setLog(result.getLogValue());
  403. }
  404. return responseBuilder.build();
  405. }
  406. ```
  407. ### Handshake
  408. When the app or tendermint restarts, they need to sync to a common
  409. height. When an ABCI connection is first established, Tendermint will
  410. call `Info` on the Query connection. The response should contain the
  411. LastBlockHeight and LastBlockAppHash - the former is the last block for
  412. which the app ran Commit successfully, the latter is the response from
  413. that Commit.
  414. Using this information, Tendermint will determine what needs to be
  415. replayed, if anything, against the app, to ensure both Tendermint and
  416. the app are synced to the latest block height.
  417. If the app returns a LastBlockHeight of 0, Tendermint will just replay
  418. all blocks.
  419. In go:
  420. ```
  421. func (app *KVStoreApplication) Info(req types.RequestInfo) (resInfo types.ResponseInfo) {
  422. return types.ResponseInfo{Data: fmt.Sprintf("{\"size\":%v}", app.state.Size())}
  423. }
  424. ```
  425. In Java:
  426. ```
  427. ResponseInfo requestInfo(RequestInfo req) {
  428. final byte[] lastAppHash = getLastAppHash();
  429. final long lastHeight = getLastHeight();
  430. return ResponseInfo.newBuilder().setLastBlockAppHash(ByteString.copyFrom(lastAppHash)).setLastBlockHeight(lastHeight).build();
  431. }
  432. ```
  433. ### Genesis
  434. `InitChain` will be called once upon the genesis. `params` includes the
  435. initial validator set. Later on, it may be extended to take parts of the
  436. consensus params.
  437. In go:
  438. ```
  439. // Save the validators in the merkle tree
  440. func (app *PersistentKVStoreApplication) InitChain(params types.RequestInitChain) {
  441. for _, v := range params.Validators {
  442. r := app.updateValidator(v)
  443. if r.IsErr() {
  444. app.logger.Error("Error updating validators", "r", r)
  445. }
  446. }
  447. }
  448. ```
  449. In Java:
  450. ```
  451. /*
  452. * all types come from protobuf definition
  453. */
  454. ResponseInitChain requestInitChain(RequestInitChain req) {
  455. final int validatorsCount = req.getValidatorsCount();
  456. final List<Types.Validator> validatorsList = req.getValidatorsList();
  457. validatorsList.forEach((validator) -> {
  458. long power = validator.getPower();
  459. byte[] validatorPubKey = validator.getPubKey().toByteArray();
  460. // do somehing for validator setup in app
  461. });
  462. return ResponseInitChain.newBuilder().build();
  463. }
  464. ```