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.

396 lines
15 KiB

  1. Application Development Guide
  2. =============================
  3. ABCI Design
  4. -----------
  5. The purpose of ABCI is to provide a clean interface between state
  6. transition machines on one computer and the mechanics of their
  7. replication across multiple computers. The former we call 'application
  8. logic' and the latter the 'consensus engine'. Application logic
  9. validates transactions and optionally executes transactions against some
  10. persistent state. A consensus engine ensures all transactions are
  11. replicated in the same order on every machine. We call each machine in a
  12. consensus engine a 'validator', and each validator runs the same
  13. transactions through the same application logic. In particular, we are
  14. interested in blockchain-style consensus engines, where transactions are
  15. committed in hash-linked blocks.
  16. The ABCI design has a few distinct components:
  17. - message protocol
  18. - pairs of request and response messages
  19. - consensus makes requests, application responds
  20. - defined using protobuf
  21. - server/client
  22. - consensus engine runs the client
  23. - application runs the server
  24. - two implementations:
  25. - async raw bytes
  26. - grpc
  27. - blockchain protocol
  28. - abci is connection oriented
  29. - Tendermint Core maintains three connections:
  30. - `mempool connection <#mempool-connection>`__: for checking if
  31. transactions should be relayed before they are committed; only
  32. uses ``CheckTx``
  33. - `consensus connection <#consensus-connection>`__: for executing
  34. transactions that have been committed. Message sequence is -
  35. for every block -
  36. ``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. ----------------
  44. The message protocol consists of pairs of requests and responses. Some
  45. messages have no fields, while others may include byte-arrays, strings,
  46. or integers. See the ``message Request`` and ``message Response``
  47. definitions in `the protobuf definition
  48. file <https://github.com/tendermint/abci/blob/master/types/types.proto>`__,
  49. and the `protobuf
  50. documentation <https://developers.google.com/protocol-buffers/docs/overview>`__
  51. for more details.
  52. For each request, a server should respond with the corresponding
  53. response, where order of requests is preserved in the order of
  54. responses.
  55. Server
  56. ------
  57. To use ABCI in your programming language of choice, there must be a ABCI
  58. server in that language. Tendermint supports two kinds of implementation
  59. of the server:
  60. - Asynchronous, raw socket server (Tendermint Socket Protocol, also
  61. known as TSP or Teaspoon)
  62. - GRPC
  63. Both can be tested using the ``abci-cli`` by setting the ``--abci`` flag
  64. appropriately (ie. to ``socket`` or ``grpc``).
  65. See examples, in various stages of maintenance, in
  66. `Go <https://github.com/tendermint/abci/tree/master/server>`__,
  67. `JavaScript <https://github.com/tendermint/js-abci>`__,
  68. `Python <https://github.com/tendermint/abci/tree/master/example/python3/abci>`__,
  69. `C++ <https://github.com/mdyring/cpp-tmsp>`__, and
  70. `Java <https://github.com/jTendermint/jabci>`__.
  71. GRPC
  72. ~~~~
  73. If GRPC is available in your language, this is the easiest approach,
  74. though it will have significant performance overhead.
  75. To get started with GRPC, copy in the `protobuf
  76. file <https://github.com/tendermint/abci/blob/master/types/types.proto>`__
  77. and compile it using the GRPC plugin for your language. For instance,
  78. for golang, the command is
  79. ``protoc --go_out=plugins=grpc:. types.proto``. See the `grpc
  80. documentation for more details <http://www.grpc.io/docs/>`__. ``protoc``
  81. will autogenerate all the necessary code for ABCI client and server in
  82. your language, including whatever interface your application must
  83. satisfy to be used by the ABCI server for handling requests.
  84. TSP
  85. ~~~
  86. If GRPC is not available in your language, or you require higher
  87. performance, or otherwise enjoy programming, you may implement your own
  88. ABCI server using the Tendermint Socket Protocol, known affectionately
  89. as Teaspoon. The first step is still to auto-generate the relevant data
  90. types and codec in your language using ``protoc``. Messages coming over
  91. the socket are Protobuf3 encoded, but additionally length-prefixed to
  92. facilitate use as a streaming protocol. Protobuf3 doesn't have an
  93. official length-prefix standard, so we use our own. The first byte in
  94. the prefix represents the length of the Big Endian encoded length. The
  95. remaining bytes in the prefix are the Big Endian encoded length.
  96. For example, if the Protobuf3 encoded ABCI message is 0xDEADBEEF (4
  97. bytes), the length-prefixed message is 0x0104DEADBEEF. If the Protobuf3
  98. encoded ABCI message is 65535 bytes long, the length-prefixed message
  99. would be like 0x02FFFF....
  100. Note this prefixing does not apply for grpc.
  101. An ABCI server must also be able to support multiple connections, as
  102. Tendermint uses three connections.
  103. Client
  104. ------
  105. There are currently two use-cases for an ABCI client. One is a testing
  106. tool, as in the ``abci-cli``, which allows ABCI requests to be sent via
  107. command line. The other is a consensus engine, such as Tendermint Core,
  108. which makes requests to the application every time a new transaction is
  109. received or a block is committed.
  110. It is unlikely that you will need to implement a client. For details of
  111. our client, see
  112. `here <https://github.com/tendermint/abci/tree/master/client>`__.
  113. All examples below are from `persistent-dummy application
  114. <https://github.com/tendermint/abci/blob/master/example/dummy/persistent_dummy.go>`__,
  115. which is a part of the abci repo.
  116. Blockchain Protocol
  117. -------------------
  118. In ABCI, a transaction is simply an arbitrary length byte-array. It is
  119. the application's responsibility to define the transaction codec as they
  120. please, and to use it for both CheckTx and DeliverTx.
  121. Note that there are two distinct means for running transactions,
  122. corresponding to stages of 'awareness' of the transaction in the
  123. network. The first stage is when a transaction is received by a
  124. validator from a client into the so-called mempool or transaction pool -
  125. this is where we use CheckTx. The second is when the transaction is
  126. successfully committed on more than 2/3 of validators - where we use
  127. DeliverTx. In the former case, it may not be necessary to run all the
  128. state transitions associated with the transaction, as the transaction
  129. may not ultimately be committed until some much later time, when the
  130. result of its execution will be different. For instance, an Ethereum
  131. ABCI app would check signatures and amounts in CheckTx, but would not
  132. actually execute any contract code until the DeliverTx, so as to avoid
  133. executing state transitions that have not been finalized.
  134. To formalize the distinction further, two explicit ABCI connections are
  135. made between Tendermint Core and the application: the mempool connection
  136. and the consensus connection. We also make a third connection, the query
  137. connection, to query the local state of the app.
  138. Mempool Connection
  139. ~~~~~~~~~~~~~~~~~~
  140. The mempool connection is used *only* for CheckTx requests. Transactions
  141. are run using CheckTx in the same order they were received by the
  142. validator. If the CheckTx returns ``OK``, the transaction is kept in
  143. memory and relayed to other peers in the same order it was received.
  144. Otherwise, it is discarded.
  145. CheckTx requests run concurrently with block processing; so they should
  146. run against a copy of the main application state which is reset after
  147. every block. This copy is necessary to track transitions made by a
  148. sequence of CheckTx requests before they are included in a block. When a
  149. block is committed, the application must ensure to reset the mempool
  150. state to the latest committed state. Tendermint Core will then filter
  151. through all transactions in the mempool, removing any that were included
  152. in the block, and re-run the rest using CheckTx against the post-Commit
  153. mempool state.
  154. ::
  155. func (app *PersistentDummyApplication) CheckTx(tx []byte) types.Result {
  156. return app.app.CheckTx(tx)
  157. }
  158. Consensus Connection
  159. ~~~~~~~~~~~~~~~~~~~~
  160. The consensus connection is used only when a new block is committed, and
  161. communicates all information from the block in a series of requests:
  162. ``BeginBlock, [DeliverTx, ...], EndBlock, Commit``. That is, when a
  163. block is committed in the consensus, we send a list of DeliverTx
  164. requests (one for each transaction) sandwiched by BeginBlock and
  165. EndBlock requests, and followed by a Commit.
  166. DeliverTx
  167. ^^^^^^^^^
  168. DeliverTx is the workhorse of the blockchain. Tendermint sends the
  169. DeliverTx requests asynchronously but in order, and relies on the
  170. underlying socket protocol (ie. TCP) to ensure they are received by the
  171. app in order. They have already been ordered in the global consensus by
  172. the Tendermint protocol.
  173. DeliverTx returns a abci.Result, which includes a Code, Data, and Log.
  174. The code may be non-zero (non-OK), meaning the corresponding transaction
  175. should have been rejected by the mempool, but may have been included in
  176. a block by a Byzantine proposer.
  177. The block header will be updated (TODO) to include some commitment to
  178. the results of DeliverTx, be it a bitarray of non-OK transactions, or a
  179. merkle root of the data returned by the DeliverTx requests, or both.
  180. ::
  181. // tx is either "key=value" or just arbitrary bytes
  182. func (app *PersistentDummyApplication) DeliverTx(tx []byte) types.Result {
  183. // if it starts with "val:", update the validator set
  184. // format is "val:pubkey/power"
  185. if isValidatorTx(tx) {
  186. // update validators in the merkle tree
  187. // and in app.changes
  188. return app.execValidatorTx(tx)
  189. }
  190. // otherwise, update the key-value store
  191. return app.app.DeliverTx(tx)
  192. }
  193. Commit
  194. ^^^^^^
  195. Once all processing of the block is complete, Tendermint sends the
  196. Commit request and blocks waiting for a response. While the mempool may
  197. run concurrently with block processing (the BeginBlock, DeliverTxs, and
  198. EndBlock), it is locked for the Commit request so that its state can be
  199. safely reset during Commit. This means the app *MUST NOT* do any
  200. blocking communication with the mempool (ie. broadcast\_tx) during
  201. Commit, or there will be deadlock. Note also that all remaining
  202. transactions in the mempool are replayed on the mempool connection
  203. (CheckTx) following a commit.
  204. The app should respond with a byte array, which is the deterministic
  205. state root of the application. It is included in the header of the next
  206. block. It can be used to provide easily verified Merkle-proofs of the
  207. state of the application.
  208. It is expected that the app will persist state to disk on Commit. The
  209. option to have all transactions replayed from some previous block is the
  210. job of the `Handshake <#handshake>`__.
  211. ::
  212. func (app *PersistentDummyApplication) Commit() types.Result {
  213. // Save
  214. appHash := app.app.state.Save()
  215. app.logger.Info("Saved state", "root", appHash)
  216. lastBlock := LastBlockInfo{
  217. Height: app.blockHeader.Height,
  218. AppHash: appHash, // this hash will be in the next block header
  219. }
  220. app.logger.Info("Saving block", "height", lastBlock.Height, "root", lastBlock.AppHash)
  221. SaveLastBlock(app.db, lastBlock)
  222. return types.NewResultOK(appHash, "")
  223. }
  224. BeginBlock
  225. ^^^^^^^^^^
  226. The BeginBlock request can be used to run some code at the beginning of
  227. every block. It also allows Tendermint to send the current block hash
  228. and header to the application, before it sends any of the transactions.
  229. The app should remember the latest height and header (ie. from which it
  230. has run a successful Commit) so that it can tell Tendermint where to
  231. pick up from when it restarts. See information on the Handshake, below.
  232. ::
  233. // Track the block hash and header information
  234. func (app *PersistentDummyApplication) BeginBlock(params types.RequestBeginBlock) {
  235. // update latest block info
  236. app.blockHeader = params.Header
  237. // reset valset changes
  238. app.changes = make([]*types.Validator, 0)
  239. }
  240. EndBlock
  241. ^^^^^^^^
  242. The EndBlock request can be used to run some code at the end of every
  243. block. Additionally, the response may contain a list of validators,
  244. which can be used to update the validator set. To add a new validator or
  245. update an existing one, simply include them in the list returned in the
  246. EndBlock response. To remove one, include it in the list with a
  247. ``power`` equal to ``0``. Tendermint core will take care of updating the
  248. validator set. Note validator set changes are only available in v0.8.0
  249. and up.
  250. ::
  251. // Update the validator set
  252. func (app *PersistentDummyApplication) EndBlock(height uint64) (resEndBlock types.ResponseEndBlock) {
  253. return types.ResponseEndBlock{Diffs: app.changes}
  254. }
  255. Query Connection
  256. ~~~~~~~~~~~~~~~~
  257. This connection is used to query the application without engaging
  258. consensus. It's exposed over the tendermint core rpc, so clients can
  259. query the app without exposing a server on the app itself, but they must
  260. serialize each query as a single byte array. Additionally, certain
  261. "standardized" queries may be used to inform local decisions, for
  262. instance about which peers to connect to.
  263. Tendermint Core currently uses the Query connection to filter peers upon
  264. connecting, according to IP address or public key. For instance,
  265. returning non-OK ABCI response to either of the following queries will
  266. cause Tendermint to not connect to the corresponding peer:
  267. - ``p2p/filter/addr/<addr>``, where ``<addr>`` is an IP address.
  268. - ``p2p/filter/pubkey/<pubkey>``, where ``<pubkey>`` is the hex-encoded
  269. ED25519 key of the node (not it's validator key)
  270. Note: these query formats are subject to change!
  271. ::
  272. func (app *PersistentDummyApplication) Query(reqQuery types.RequestQuery) types.ResponseQuery {
  273. return app.app.Query(reqQuery)
  274. }
  275. Handshake
  276. ~~~~~~~~~
  277. When the app or tendermint restarts, they need to sync to a common
  278. height. When an ABCI connection is first established, Tendermint will
  279. call ``Info`` on the Query connection. The response should contain the
  280. LastBlockHeight and LastBlockAppHash - the former is the last block for
  281. the which the app ran Commit successfully, the latter is the response
  282. from that Commit.
  283. Using this information, Tendermint will determine what needs to be
  284. replayed, if anything, against the app, to ensure both Tendermint and
  285. the app are synced to the latest block height.
  286. If the app returns a LastBlockHeight of 0, Tendermint will just replay
  287. all blocks.
  288. ::
  289. func (app *PersistentDummyApplication) Info(req types.RequestInfo) (resInfo types.ResponseInfo) {
  290. resInfo = app.app.Info(req)
  291. lastBlock := LoadLastBlock(app.db)
  292. resInfo.LastBlockHeight = lastBlock.Height
  293. resInfo.LastBlockAppHash = lastBlock.AppHash
  294. return resInfo
  295. }
  296. Genesis
  297. ~~~~~~~
  298. ``InitChain`` will be called once upon the genesis. ``params`` includes the
  299. initial validator set. Later on, it may be extended to take parts of the
  300. consensus params.
  301. ::
  302. // Save the validators in the merkle tree
  303. func (app *PersistentDummyApplication) InitChain(params types.RequestInitChain) {
  304. for _, v := range params.Validators {
  305. r := app.updateValidator(v)
  306. if r.IsErr() {
  307. app.logger.Error("Error updating validators", "r", r)
  308. }
  309. }
  310. }