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.

592 lines
18 KiB

  1. <!---
  2. order: 4
  3. --->
  4. # Creating an application in Kotlin
  5. ## Guide Assumptions
  6. This guide is designed for beginners who want to get started with a Tendermint
  7. Core application from scratch. It does not assume that you have any prior
  8. experience with Tendermint Core.
  9. Tendermint Core is Byzantine Fault Tolerant (BFT) middleware that takes a state
  10. transition machine (your application) - written in any programming language - and securely
  11. replicates it on many machines.
  12. By following along with this guide, you'll create a Tendermint Core project
  13. called kvstore, a (very) simple distributed BFT key-value store. The application (which should
  14. implementing the blockchain interface (ABCI)) will be written in Kotlin.
  15. This guide assumes that you are not new to JVM world. If you are new please see [JVM Minimal Survival Guide](https://hadihariri.com/2013/12/29/jvm-minimal-survival-guide-for-the-dotnet-developer/#java-the-language-java-the-ecosystem-java-the-jvm) and [Gradle Docs](https://docs.gradle.org/current/userguide/userguide.html).
  16. ## Built-in app vs external app
  17. If you use Golang, you can run your app and Tendermint Core in the same process to get maximum performance.
  18. [Cosmos SDK](https://github.com/cosmos/cosmos-sdk) is written this way.
  19. Please refer to [Writing a built-in Tendermint Core application in Go](./go-built-in.md) guide for details.
  20. If you choose another language, like we did in this guide, you have to write a separate app,
  21. which will communicate with Tendermint Core via a socket (UNIX or TCP) or gRPC.
  22. This guide will show you how to build external application using RPC server.
  23. Having a separate application might give you better security guarantees as two
  24. processes would be communicating via established binary protocol. Tendermint
  25. Core will not have access to application's state.
  26. ## 1.1 Installing Java and Gradle
  27. Please refer to [the Oracle's guide for installing JDK](https://www.oracle.com/technetwork/java/javase/downloads/index.html).
  28. Verify that you have installed Java successfully:
  29. ```sh
  30. $ java -version
  31. java version "1.8.0_162"
  32. Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
  33. Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)
  34. ```
  35. You can choose any version of Java higher or equal to 8.
  36. In my case it is Java SE Development Kit 8.
  37. Make sure you have `$JAVA_HOME` environment variable set:
  38. ```sh
  39. $ echo $JAVA_HOME
  40. /Library/Java/JavaVirtualMachines/jdk1.8.0_162.jdk/Contents/Home
  41. ```
  42. For Gradle installation, please refer to [their official guide](https://gradle.org/install/).
  43. ## 1.2 Creating a new Kotlin project
  44. We'll start by creating a new Gradle project.
  45. ```sh
  46. $ export KVSTORE_HOME=~/kvstore
  47. $ mkdir $KVSTORE_HOME
  48. $ cd $KVSTORE_HOME
  49. ```
  50. Inside the example directory run:
  51. ```sh
  52. gradle init --dsl groovy --package io.example --project-name example --type kotlin-application
  53. ```
  54. This will create a new project for you. The tree of files should look like:
  55. ```sh
  56. $ tree
  57. .
  58. |-- build.gradle
  59. |-- gradle
  60. | `-- wrapper
  61. | |-- gradle-wrapper.jar
  62. | `-- gradle-wrapper.properties
  63. |-- gradlew
  64. |-- gradlew.bat
  65. |-- settings.gradle
  66. `-- src
  67. |-- main
  68. | |-- kotlin
  69. | | `-- io
  70. | | `-- example
  71. | | `-- App.kt
  72. | `-- resources
  73. `-- test
  74. |-- kotlin
  75. | `-- io
  76. | `-- example
  77. | `-- AppTest.kt
  78. `-- resources
  79. ```
  80. When run, this should print "Hello world." to the standard output.
  81. ```sh
  82. $ ./gradlew run
  83. > Task :run
  84. Hello world.
  85. ```
  86. ## 1.3 Writing a Tendermint Core application
  87. Tendermint Core communicates with the application through the Application
  88. BlockChain Interface (ABCI). All message types are defined in the [protobuf
  89. file](https://github.com/tendermint/tendermint/blob/master/abci/types/types.proto).
  90. This allows Tendermint Core to run applications written in any programming
  91. language.
  92. ### 1.3.1 Compile .proto files
  93. Add the following piece to the top of the `build.gradle`:
  94. ```groovy
  95. buildscript {
  96. repositories {
  97. mavenCentral()
  98. }
  99. dependencies {
  100. classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.8'
  101. }
  102. }
  103. ```
  104. Enable the protobuf plugin in the `plugins` section of the `build.gradle`:
  105. ```groovy
  106. plugins {
  107. id 'com.google.protobuf' version '0.8.8'
  108. }
  109. ```
  110. Add the following code to `build.gradle`:
  111. ```groovy
  112. protobuf {
  113. protoc {
  114. artifact = "com.google.protobuf:protoc:3.7.1"
  115. }
  116. plugins {
  117. grpc {
  118. artifact = 'io.grpc:protoc-gen-grpc-java:1.22.1'
  119. }
  120. }
  121. generateProtoTasks {
  122. all()*.plugins {
  123. grpc {}
  124. }
  125. }
  126. }
  127. ```
  128. Now we should be ready to compile the `*.proto` files.
  129. Copy the necessary `.proto` files to your project:
  130. ```sh
  131. mkdir -p \
  132. $KVSTORE_HOME/src/main/proto/github.com/tendermint/tendermint/abci/types \
  133. $KVSTORE_HOME/src/main/proto/github.com/tendermint/tendermint/crypto/merkle \
  134. $KVSTORE_HOME/src/main/proto/github.com/tendermint/tendermint/libs/kv \
  135. $KVSTORE_HOME/src/main/proto/github.com/gogo/protobuf/gogoproto
  136. cp $GOPATH/src/github.com/tendermint/tendermint/abci/types/types.proto \
  137. $KVSTORE_HOME/src/main/proto/github.com/tendermint/tendermint/abci/types/types.proto
  138. cp $GOPATH/src/github.com/tendermint/tendermint/crypto/merkle/merkle.proto \
  139. $KVSTORE_HOME/src/main/proto/github.com/tendermint/tendermint/crypto/merkle/merkle.proto
  140. cp $GOPATH/src/github.com/tendermint/tendermint/libs/kv/types.proto \
  141. $KVSTORE_HOME/src/main/proto/github.com/tendermint/tendermint/libs/kv/types.proto
  142. cp $GOPATH/src/github.com/gogo/protobuf/gogoproto/gogo.proto \
  143. $KVSTORE_HOME/src/main/proto/github.com/gogo/protobuf/gogoproto/gogo.proto
  144. ```
  145. Add these dependencies to `build.gradle`:
  146. ```groovy
  147. dependencies {
  148. implementation 'io.grpc:grpc-protobuf:1.22.1'
  149. implementation 'io.grpc:grpc-netty-shaded:1.22.1'
  150. implementation 'io.grpc:grpc-stub:1.22.1'
  151. }
  152. ```
  153. To generate all protobuf-type classes run:
  154. ```sh
  155. ./gradlew generateProto
  156. ```
  157. To verify that everything went smoothly, you can inspect the `build/generated/` directory:
  158. ```sh
  159. $ tree build/generated/
  160. build/generated/
  161. `-- source
  162. `-- proto
  163. `-- main
  164. |-- grpc
  165. | `-- types
  166. | `-- ABCIApplicationGrpc.java
  167. `-- java
  168. |-- com
  169. | `-- google
  170. | `-- protobuf
  171. | `-- GoGoProtos.java
  172. |-- common
  173. | `-- Types.java
  174. |-- merkle
  175. | `-- Merkle.java
  176. `-- types
  177. `-- Types.java
  178. ```
  179. ### 1.3.2 Implementing ABCI
  180. The resulting `$KVSTORE_HOME/build/generated/source/proto/main/grpc/types/ABCIApplicationGrpc.java` file
  181. contains the abstract class `ABCIApplicationImplBase`, which is an interface we'll need to implement.
  182. Create `$KVSTORE_HOME/src/main/kotlin/io/example/KVStoreApp.kt` file with the following content:
  183. ```kotlin
  184. package io.example
  185. import io.grpc.stub.StreamObserver
  186. import types.ABCIApplicationGrpc
  187. import types.Types.*
  188. class KVStoreApp : ABCIApplicationGrpc.ABCIApplicationImplBase() {
  189. // methods implementation
  190. }
  191. ```
  192. Now I will go through each method of `ABCIApplicationImplBase` explaining when it's called and adding
  193. required business logic.
  194. ### 1.3.3 CheckTx
  195. When a new transaction is added to the Tendermint Core, it will ask the
  196. application to check it (validate the format, signatures, etc.).
  197. ```kotlin
  198. override fun checkTx(req: RequestCheckTx, responseObserver: StreamObserver<ResponseCheckTx>) {
  199. val code = req.tx.validate()
  200. val resp = ResponseCheckTx.newBuilder()
  201. .setCode(code)
  202. .setGasWanted(1)
  203. .build()
  204. responseObserver.onNext(resp)
  205. responseObserver.onCompleted()
  206. }
  207. private fun ByteString.validate(): Int {
  208. val parts = this.split('=')
  209. if (parts.size != 2) {
  210. return 1
  211. }
  212. val key = parts[0]
  213. val value = parts[1]
  214. // check if the same key=value already exists
  215. val stored = getPersistedValue(key)
  216. if (stored != null && stored.contentEquals(value)) {
  217. return 2
  218. }
  219. return 0
  220. }
  221. private fun ByteString.split(separator: Char): List<ByteArray> {
  222. val arr = this.toByteArray()
  223. val i = (0 until this.size()).firstOrNull { arr[it] == separator.toByte() }
  224. ?: return emptyList()
  225. return listOf(
  226. this.substring(0, i).toByteArray(),
  227. this.substring(i + 1).toByteArray()
  228. )
  229. }
  230. ```
  231. Don't worry if this does not compile yet.
  232. If the transaction does not have a form of `{bytes}={bytes}`, we return `1`
  233. code. When the same key=value already exist (same key and value), we return `2`
  234. code. For others, we return a zero code indicating that they are valid.
  235. Note that anything with non-zero code will be considered invalid (`-1`, `100`,
  236. etc.) by Tendermint Core.
  237. Valid transactions will eventually be committed given they are not too big and
  238. have enough gas. To learn more about gas, check out ["the
  239. specification"](https://docs.tendermint.com/master/spec/abci/apps.html#gas).
  240. For the underlying key-value store we'll use
  241. [JetBrains Xodus](https://github.com/JetBrains/xodus), which is a transactional schema-less embedded high-performance database written in Java.
  242. `build.gradle`:
  243. ```groovy
  244. dependencies {
  245. implementation 'org.jetbrains.xodus:xodus-environment:1.3.91'
  246. }
  247. ```
  248. ```kotlin
  249. ...
  250. import jetbrains.exodus.ArrayByteIterable
  251. import jetbrains.exodus.env.Environment
  252. import jetbrains.exodus.env.Store
  253. import jetbrains.exodus.env.StoreConfig
  254. import jetbrains.exodus.env.Transaction
  255. class KVStoreApp(
  256. private val env: Environment
  257. ) : ABCIApplicationGrpc.ABCIApplicationImplBase() {
  258. private var txn: Transaction? = null
  259. private var store: Store? = null
  260. ...
  261. private fun getPersistedValue(k: ByteArray): ByteArray? {
  262. return env.computeInReadonlyTransaction { txn ->
  263. val store = env.openStore("store", StoreConfig.WITHOUT_DUPLICATES, txn)
  264. store.get(txn, ArrayByteIterable(k))?.bytesUnsafe
  265. }
  266. }
  267. }
  268. ```
  269. ### 1.3.4 BeginBlock -> DeliverTx -> EndBlock -> Commit
  270. When Tendermint Core has decided on the block, it's transferred to the
  271. application in 3 parts: `BeginBlock`, one `DeliverTx` per transaction and
  272. `EndBlock` in the end. `DeliverTx` are being transferred asynchronously, but the
  273. responses are expected to come in order.
  274. ```kotlin
  275. override fun beginBlock(req: RequestBeginBlock, responseObserver: StreamObserver<ResponseBeginBlock>) {
  276. txn = env.beginTransaction()
  277. store = env.openStore("store", StoreConfig.WITHOUT_DUPLICATES, txn!!)
  278. val resp = ResponseBeginBlock.newBuilder().build()
  279. responseObserver.onNext(resp)
  280. responseObserver.onCompleted()
  281. }
  282. ```
  283. Here we begin a new transaction, which will accumulate the block's transactions and open the corresponding store.
  284. ```kotlin
  285. override fun deliverTx(req: RequestDeliverTx, responseObserver: StreamObserver<ResponseDeliverTx>) {
  286. val code = req.tx.validate()
  287. if (code == 0) {
  288. val parts = req.tx.split('=')
  289. val key = ArrayByteIterable(parts[0])
  290. val value = ArrayByteIterable(parts[1])
  291. store!!.put(txn!!, key, value)
  292. }
  293. val resp = ResponseDeliverTx.newBuilder()
  294. .setCode(code)
  295. .build()
  296. responseObserver.onNext(resp)
  297. responseObserver.onCompleted()
  298. }
  299. ```
  300. If the transaction is badly formatted or the same key=value already exist, we
  301. again return the non-zero code. Otherwise, we add it to the store.
  302. In the current design, a block can include incorrect transactions (those who
  303. passed `CheckTx`, but failed `DeliverTx` or transactions included by the proposer
  304. directly). This is done for performance reasons.
  305. Note we can't commit transactions inside the `DeliverTx` because in such case
  306. `Query`, which may be called in parallel, will return inconsistent data (i.e.
  307. it will report that some value already exist even when the actual block was not
  308. yet committed).
  309. `Commit` instructs the application to persist the new state.
  310. ```kotlin
  311. override fun commit(req: RequestCommit, responseObserver: StreamObserver<ResponseCommit>) {
  312. txn!!.commit()
  313. val resp = ResponseCommit.newBuilder()
  314. .setData(ByteString.copyFrom(ByteArray(8)))
  315. .build()
  316. responseObserver.onNext(resp)
  317. responseObserver.onCompleted()
  318. }
  319. ```
  320. ### 1.3.5 Query
  321. Now, when the client wants to know whenever a particular key/value exist, it
  322. will call Tendermint Core RPC `/abci_query` endpoint, which in turn will call
  323. the application's `Query` method.
  324. Applications are free to provide their own APIs. But by using Tendermint Core
  325. as a proxy, clients (including [light client
  326. package](https://godoc.org/github.com/tendermint/tendermint/light)) can leverage
  327. the unified API across different applications. Plus they won't have to call the
  328. otherwise separate Tendermint Core API for additional proofs.
  329. Note we don't include a proof here.
  330. ```kotlin
  331. override fun query(req: RequestQuery, responseObserver: StreamObserver<ResponseQuery>) {
  332. val k = req.data.toByteArray()
  333. val v = getPersistedValue(k)
  334. val builder = ResponseQuery.newBuilder()
  335. if (v == null) {
  336. builder.log = "does not exist"
  337. } else {
  338. builder.log = "exists"
  339. builder.key = ByteString.copyFrom(k)
  340. builder.value = ByteString.copyFrom(v)
  341. }
  342. responseObserver.onNext(builder.build())
  343. responseObserver.onCompleted()
  344. }
  345. ```
  346. The complete specification can be found
  347. [here](https://docs.tendermint.com/master/spec/abci/).
  348. ## 1.4 Starting an application and a Tendermint Core instances
  349. Put the following code into the `$KVSTORE_HOME/src/main/kotlin/io/example/App.kt` file:
  350. ```kotlin
  351. package io.example
  352. import jetbrains.exodus.env.Environments
  353. fun main() {
  354. Environments.newInstance("tmp/storage").use { env ->
  355. val app = KVStoreApp(env)
  356. val server = GrpcServer(app, 26658)
  357. server.start()
  358. server.blockUntilShutdown()
  359. }
  360. }
  361. ```
  362. It is the entry point of the application.
  363. Here we create a special object `Environment`, which knows where to store the application state.
  364. Then we create and start the gRPC server to handle Tendermint Core requests.
  365. Create `$KVSTORE_HOME/src/main/kotlin/io/example/GrpcServer.kt` file with the following content:
  366. ```kotlin
  367. package io.example
  368. import io.grpc.BindableService
  369. import io.grpc.ServerBuilder
  370. class GrpcServer(
  371. private val service: BindableService,
  372. private val port: Int
  373. ) {
  374. private val server = ServerBuilder
  375. .forPort(port)
  376. .addService(service)
  377. .build()
  378. fun start() {
  379. server.start()
  380. println("gRPC server started, listening on $port")
  381. Runtime.getRuntime().addShutdownHook(object : Thread() {
  382. override fun run() {
  383. println("shutting down gRPC server since JVM is shutting down")
  384. this@GrpcServer.stop()
  385. println("server shut down")
  386. }
  387. })
  388. }
  389. fun stop() {
  390. server.shutdown()
  391. }
  392. /**
  393. * Await termination on the main thread since the grpc library uses daemon threads.
  394. */
  395. fun blockUntilShutdown() {
  396. server.awaitTermination()
  397. }
  398. }
  399. ```
  400. ## 1.5 Getting Up and Running
  401. To create a default configuration, nodeKey and private validator files, let's
  402. execute `tendermint init`. But before we do that, we will need to install
  403. Tendermint Core.
  404. ```sh
  405. $ rm -rf /tmp/example
  406. $ cd $GOPATH/src/github.com/tendermint/tendermint
  407. $ make install
  408. $ TMHOME="/tmp/example" tendermint init
  409. I[2019-07-16|18:20:36.480] Generated private validator module=main keyFile=/tmp/example/config/priv_validator_key.json stateFile=/tmp/example2/data/priv_validator_state.json
  410. I[2019-07-16|18:20:36.481] Generated node key module=main path=/tmp/example/config/node_key.json
  411. I[2019-07-16|18:20:36.482] Generated genesis file module=main path=/tmp/example/config/genesis.json
  412. ```
  413. Feel free to explore the generated files, which can be found at
  414. `/tmp/example/config` directory. Documentation on the config can be found
  415. [here](https://docs.tendermint.com/master/tendermint-core/configuration.html).
  416. We are ready to start our application:
  417. ```sh
  418. ./gradlew run
  419. gRPC server started, listening on 26658
  420. ```
  421. Then we need to start Tendermint Core and point it to our application. Staying
  422. within the application directory execute:
  423. ```sh
  424. $ TMHOME="/tmp/example" tendermint node --abci grpc --proxy_app tcp://127.0.0.1:26658
  425. I[2019-07-28|15:44:53.632] Version info module=main software=0.32.1 block=10 p2p=7
  426. I[2019-07-28|15:44:53.677] Starting Node module=main impl=Node
  427. I[2019-07-28|15:44:53.681] Started node module=main nodeInfo="{ProtocolVersion:{P2P:7 Block:10 App:0} ID_:7639e2841ccd47d5ae0f5aad3011b14049d3f452 ListenAddr:tcp://0.0.0.0:26656 Network:test-chain-Nhl3zk Version:0.32.1 Channels:4020212223303800 Moniker:Ivans-MacBook-Pro.local Other:{TxIndex:on RPCAddress:tcp://127.0.0.1:26657}}"
  428. I[2019-07-28|15:44:54.801] Executed block module=state height=8 validTxs=0 invalidTxs=0
  429. I[2019-07-28|15:44:54.814] Committed state module=state height=8 txs=0 appHash=0000000000000000
  430. ```
  431. Now open another tab in your terminal and try sending a transaction:
  432. ```sh
  433. $ curl -s 'localhost:26657/broadcast_tx_commit?tx="tendermint=rocks"'
  434. {
  435. "jsonrpc": "2.0",
  436. "id": "",
  437. "result": {
  438. "check_tx": {
  439. "gasWanted": "1"
  440. },
  441. "deliver_tx": {},
  442. "hash": "CDD3C6DFA0A08CAEDF546F9938A2EEC232209C24AA0E4201194E0AFB78A2C2BB",
  443. "height": "33"
  444. }
  445. ```
  446. Response should contain the height where this transaction was committed.
  447. Now let's check if the given key now exists and its value:
  448. ```sh
  449. $ curl -s 'localhost:26657/abci_query?data="tendermint"'
  450. {
  451. "jsonrpc": "2.0",
  452. "id": "",
  453. "result": {
  454. "response": {
  455. "log": "exists",
  456. "key": "dGVuZGVybWludA==",
  457. "value": "cm9ja3My"
  458. }
  459. }
  460. }
  461. ```
  462. `dGVuZGVybWludA==` and `cm9ja3M=` are the base64-encoding of the ASCII of `tendermint` and `rocks` accordingly.
  463. ## Outro
  464. I hope everything went smoothly and your first, but hopefully not the last,
  465. Tendermint Core application is up and running. If not, please [open an issue on
  466. Github](https://github.com/tendermint/tendermint/issues/new/choose). To dig
  467. deeper, read [the docs](https://docs.tendermint.com/master/).
  468. The full source code of this example project can be found [here](https://github.com/climber73/tendermint-abci-grpc-kotlin).