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.

527 lines
20 KiB

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