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.

604 lines
20 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. ```bash
  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. ```bash
  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. ```bash
  46. $ export KVSTORE_HOME=~/kvstore
  47. $ mkdir $KVSTORE_HOME
  48. $ cd $KVSTORE_HOME
  49. ```
  50. Inside the example directory run:
  51. ```bash
  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. ```bash
  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. ```bash
  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. ```bash
  131. mkdir -p \
  132. $KVSTORE_HOME/src/main/proto/github.com/tendermint/tendermint/proto/tendermint/abci \
  133. $KVSTORE_HOME/src/main/proto/github.com/tendermint/tendermint/proto/tendermint/version \
  134. $KVSTORE_HOME/src/main/proto/github.com/tendermint/tendermint/proto/tendermint/types \
  135. $KVSTORE_HOME/src/main/proto/github.com/tendermint/tendermint/proto/tendermint/crypto \
  136. $KVSTORE_HOME/src/main/proto/github.com/tendermint/tendermint/proto/tendermint/libs \
  137. $KVSTORE_HOME/src/main/proto/github.com/gogo/protobuf/gogoproto
  138. cp $GOPATH/src/github.com/tendermint/tendermint/proto/tendermint/abci/types.proto \
  139. $KVSTORE_HOME/src/main/proto/github.com/tendermint/tendermint/proto/tendermint/abci/types.proto
  140. cp $GOPATH/src/github.com/tendermint/tendermint/proto/tendermint/version/version.proto \
  141. $KVSTORE_HOME/src/main/proto/github.com/tendermint/tendermint/proto/tendermint/version/version.proto
  142. cp $GOPATH/src/github.com/tendermint/tendermint/proto/tendermint/types/types.proto \
  143. $KVSTORE_HOME/src/main/proto/github.com/tendermint/tendermint/proto/tendermint/types/types.proto
  144. cp $GOPATH/src/github.com/tendermint/tendermint/proto/tendermint/types/evidence.proto \
  145. $KVSTORE_HOME/src/main/proto/github.com/tendermint/tendermint/proto/tendermint/types/evidence.proto
  146. cp $GOPATH/src/github.com/tendermint/tendermint/proto/tendermint/types/params.proto \
  147. $KVSTORE_HOME/src/main/proto/github.com/tendermint/tendermint/proto/tendermint/types/params.proto
  148. cp $GOPATH/src/github.com/tendermint/tendermint/proto/tendermint/crypto/merkle.proto \
  149. $KVSTORE_HOME/src/main/proto/github.com/tendermint/tendermint/proto/tendermint/crypto/merkle.proto
  150. cp $GOPATH/src/github.com/tendermint/tendermint/proto/tendermint/crypto/keys.proto \
  151. $KVSTORE_HOME/src/main/proto/github.com/tendermint/tendermint/proto/tendermint/crypto/keys.proto
  152. cp $GOPATH/src/github.com/tendermint/tendermint/proto/tendermint/libs/types.proto \
  153. $KVSTORE_HOME/src/main/proto/github.com/tendermint/tendermint/proto/tendermint/libs/types.proto
  154. cp $GOPATH/src/github.com/gogo/protobuf/gogoproto/gogo.proto \
  155. $KVSTORE_HOME/src/main/proto/github.com/gogo/protobuf/gogoproto/gogo.proto
  156. ```
  157. Add these dependencies to `build.gradle`:
  158. ```groovy
  159. dependencies {
  160. implementation 'io.grpc:grpc-protobuf:1.22.1'
  161. implementation 'io.grpc:grpc-netty-shaded:1.22.1'
  162. implementation 'io.grpc:grpc-stub:1.22.1'
  163. }
  164. ```
  165. To generate all protobuf-type classes run:
  166. ```bash
  167. ./gradlew generateProto
  168. ```
  169. To verify that everything went smoothly, you can inspect the `build/generated/` directory:
  170. ```bash
  171. $ tree build/generated/
  172. build/generated/
  173. `-- source
  174. `-- proto
  175. `-- main
  176. |-- grpc
  177. | `-- types
  178. | `-- ABCIApplicationGrpc.java
  179. `-- java
  180. |-- com
  181. | `-- google
  182. | `-- protobuf
  183. | `-- GoGoProtos.java
  184. |-- common
  185. | `-- Types.java
  186. |-- merkle
  187. | `-- Merkle.java
  188. `-- types
  189. `-- Types.java
  190. ```
  191. ### 1.3.2 Implementing ABCI
  192. The resulting `$KVSTORE_HOME/build/generated/source/proto/main/grpc/types/ABCIApplicationGrpc.java` file
  193. contains the abstract class `ABCIApplicationImplBase`, which is an interface we'll need to implement.
  194. Create `$KVSTORE_HOME/src/main/kotlin/io/example/KVStoreApp.kt` file with the following content:
  195. ```kotlin
  196. package io.example
  197. import io.grpc.stub.StreamObserver
  198. import types.ABCIApplicationGrpc
  199. import types.Types.*
  200. class KVStoreApp : ABCIApplicationGrpc.ABCIApplicationImplBase() {
  201. // methods implementation
  202. }
  203. ```
  204. Now I will go through each method of `ABCIApplicationImplBase` explaining when it's called and adding
  205. required business logic.
  206. ### 1.3.3 CheckTx
  207. When a new transaction is added to the Tendermint Core, it will ask the
  208. application to check it (validate the format, signatures, etc.).
  209. ```kotlin
  210. override fun checkTx(req: RequestCheckTx, responseObserver: StreamObserver<ResponseCheckTx>) {
  211. val code = req.tx.validate()
  212. val resp = ResponseCheckTx.newBuilder()
  213. .setCode(code)
  214. .setGasWanted(1)
  215. .build()
  216. responseObserver.onNext(resp)
  217. responseObserver.onCompleted()
  218. }
  219. private fun ByteString.validate(): Int {
  220. val parts = this.split('=')
  221. if (parts.size != 2) {
  222. return 1
  223. }
  224. val key = parts[0]
  225. val value = parts[1]
  226. // check if the same key=value already exists
  227. val stored = getPersistedValue(key)
  228. if (stored != null && stored.contentEquals(value)) {
  229. return 2
  230. }
  231. return 0
  232. }
  233. private fun ByteString.split(separator: Char): List<ByteArray> {
  234. val arr = this.toByteArray()
  235. val i = (0 until this.size()).firstOrNull { arr[it] == separator.toByte() }
  236. ?: return emptyList()
  237. return listOf(
  238. this.substring(0, i).toByteArray(),
  239. this.substring(i + 1).toByteArray()
  240. )
  241. }
  242. ```
  243. Don't worry if this does not compile yet.
  244. If the transaction does not have a form of `{bytes}={bytes}`, we return `1`
  245. code. When the same key=value already exist (same key and value), we return `2`
  246. code. For others, we return a zero code indicating that they are valid.
  247. Note that anything with non-zero code will be considered invalid (`-1`, `100`,
  248. etc.) by Tendermint Core.
  249. Valid transactions will eventually be committed given they are not too big and
  250. have enough gas. To learn more about gas, check out ["the
  251. specification"](https://docs.tendermint.com/master/spec/abci/apps.html#gas).
  252. For the underlying key-value store we'll use
  253. [JetBrains Xodus](https://github.com/JetBrains/xodus), which is a transactional schema-less embedded high-performance database written in Java.
  254. `build.gradle`:
  255. ```groovy
  256. dependencies {
  257. implementation 'org.jetbrains.xodus:xodus-environment:1.3.91'
  258. }
  259. ```
  260. ```kotlin
  261. ...
  262. import jetbrains.exodus.ArrayByteIterable
  263. import jetbrains.exodus.env.Environment
  264. import jetbrains.exodus.env.Store
  265. import jetbrains.exodus.env.StoreConfig
  266. import jetbrains.exodus.env.Transaction
  267. class KVStoreApp(
  268. private val env: Environment
  269. ) : ABCIApplicationGrpc.ABCIApplicationImplBase() {
  270. private var txn: Transaction? = null
  271. private var store: Store? = null
  272. ...
  273. private fun getPersistedValue(k: ByteArray): ByteArray? {
  274. return env.computeInReadonlyTransaction { txn ->
  275. val store = env.openStore("store", StoreConfig.WITHOUT_DUPLICATES, txn)
  276. store.get(txn, ArrayByteIterable(k))?.bytesUnsafe
  277. }
  278. }
  279. }
  280. ```
  281. ### 1.3.4 BeginBlock -> DeliverTx -> EndBlock -> Commit
  282. When Tendermint Core has decided on the block, it's transferred to the
  283. application in 3 parts: `BeginBlock`, one `DeliverTx` per transaction and
  284. `EndBlock` in the end. `DeliverTx` are being transferred asynchronously, but the
  285. responses are expected to come in order.
  286. ```kotlin
  287. override fun beginBlock(req: RequestBeginBlock, responseObserver: StreamObserver<ResponseBeginBlock>) {
  288. txn = env.beginTransaction()
  289. store = env.openStore("store", StoreConfig.WITHOUT_DUPLICATES, txn!!)
  290. val resp = ResponseBeginBlock.newBuilder().build()
  291. responseObserver.onNext(resp)
  292. responseObserver.onCompleted()
  293. }
  294. ```
  295. Here we begin a new transaction, which will accumulate the block's transactions and open the corresponding store.
  296. ```kotlin
  297. override fun deliverTx(req: RequestDeliverTx, responseObserver: StreamObserver<ResponseDeliverTx>) {
  298. val code = req.tx.validate()
  299. if (code == 0) {
  300. val parts = req.tx.split('=')
  301. val key = ArrayByteIterable(parts[0])
  302. val value = ArrayByteIterable(parts[1])
  303. store!!.put(txn!!, key, value)
  304. }
  305. val resp = ResponseDeliverTx.newBuilder()
  306. .setCode(code)
  307. .build()
  308. responseObserver.onNext(resp)
  309. responseObserver.onCompleted()
  310. }
  311. ```
  312. If the transaction is badly formatted or the same key=value already exist, we
  313. again return the non-zero code. Otherwise, we add it to the store.
  314. In the current design, a block can include incorrect transactions (those who
  315. passed `CheckTx`, but failed `DeliverTx` or transactions included by the proposer
  316. directly). This is done for performance reasons.
  317. Note we can't commit transactions inside the `DeliverTx` because in such case
  318. `Query`, which may be called in parallel, will return inconsistent data (i.e.
  319. it will report that some value already exist even when the actual block was not
  320. yet committed).
  321. `Commit` instructs the application to persist the new state.
  322. ```kotlin
  323. override fun commit(req: RequestCommit, responseObserver: StreamObserver<ResponseCommit>) {
  324. txn!!.commit()
  325. val resp = ResponseCommit.newBuilder()
  326. .setData(ByteString.copyFrom(ByteArray(8)))
  327. .build()
  328. responseObserver.onNext(resp)
  329. responseObserver.onCompleted()
  330. }
  331. ```
  332. ### 1.3.5 Query
  333. Now, when the client wants to know whenever a particular key/value exist, it
  334. will call Tendermint Core RPC `/abci_query` endpoint, which in turn will call
  335. the application's `Query` method.
  336. Applications are free to provide their own APIs. But by using Tendermint Core
  337. as a proxy, clients (including [light client
  338. package](https://godoc.org/github.com/tendermint/tendermint/light)) can leverage
  339. the unified API across different applications. Plus they won't have to call the
  340. otherwise separate Tendermint Core API for additional proofs.
  341. Note we don't include a proof here.
  342. ```kotlin
  343. override fun query(req: RequestQuery, responseObserver: StreamObserver<ResponseQuery>) {
  344. val k = req.data.toByteArray()
  345. val v = getPersistedValue(k)
  346. val builder = ResponseQuery.newBuilder()
  347. if (v == null) {
  348. builder.log = "does not exist"
  349. } else {
  350. builder.log = "exists"
  351. builder.key = ByteString.copyFrom(k)
  352. builder.value = ByteString.copyFrom(v)
  353. }
  354. responseObserver.onNext(builder.build())
  355. responseObserver.onCompleted()
  356. }
  357. ```
  358. The complete specification can be found
  359. [here](https://docs.tendermint.com/master/spec/abci/).
  360. ## 1.4 Starting an application and a Tendermint Core instances
  361. Put the following code into the `$KVSTORE_HOME/src/main/kotlin/io/example/App.kt` file:
  362. ```kotlin
  363. package io.example
  364. import jetbrains.exodus.env.Environments
  365. fun main() {
  366. Environments.newInstance("tmp/storage").use { env ->
  367. val app = KVStoreApp(env)
  368. val server = GrpcServer(app, 26658)
  369. server.start()
  370. server.blockUntilShutdown()
  371. }
  372. }
  373. ```
  374. It is the entry point of the application.
  375. Here we create a special object `Environment`, which knows where to store the application state.
  376. Then we create and start the gRPC server to handle Tendermint Core requests.
  377. Create `$KVSTORE_HOME/src/main/kotlin/io/example/GrpcServer.kt` file with the following content:
  378. ```kotlin
  379. package io.example
  380. import io.grpc.BindableService
  381. import io.grpc.ServerBuilder
  382. class GrpcServer(
  383. private val service: BindableService,
  384. private val port: Int
  385. ) {
  386. private val server = ServerBuilder
  387. .forPort(port)
  388. .addService(service)
  389. .build()
  390. fun start() {
  391. server.start()
  392. println("gRPC server started, listening on $port")
  393. Runtime.getRuntime().addShutdownHook(object : Thread() {
  394. override fun run() {
  395. println("shutting down gRPC server since JVM is shutting down")
  396. this@GrpcServer.stop()
  397. println("server shut down")
  398. }
  399. })
  400. }
  401. fun stop() {
  402. server.shutdown()
  403. }
  404. /**
  405. * Await termination on the main thread since the grpc library uses daemon threads.
  406. */
  407. fun blockUntilShutdown() {
  408. server.awaitTermination()
  409. }
  410. }
  411. ```
  412. ## 1.5 Getting Up and Running
  413. To create a default configuration, nodeKey and private validator files, let's
  414. execute `tendermint init`. But before we do that, we will need to install
  415. Tendermint Core.
  416. ```bash
  417. $ rm -rf /tmp/example
  418. $ cd $GOPATH/src/github.com/tendermint/tendermint
  419. $ make install
  420. $ TMHOME="/tmp/example" tendermint init
  421. 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
  422. I[2019-07-16|18:20:36.481] Generated node key module=main path=/tmp/example/config/node_key.json
  423. I[2019-07-16|18:20:36.482] Generated genesis file module=main path=/tmp/example/config/genesis.json
  424. ```
  425. Feel free to explore the generated files, which can be found at
  426. `/tmp/example/config` directory. Documentation on the config can be found
  427. [here](https://docs.tendermint.com/master/tendermint-core/configuration.html).
  428. We are ready to start our application:
  429. ```bash
  430. ./gradlew run
  431. gRPC server started, listening on 26658
  432. ```
  433. Then we need to start Tendermint Core and point it to our application. Staying
  434. within the application directory execute:
  435. ```bash
  436. $ TMHOME="/tmp/example" tendermint node --abci grpc --proxy_app tcp://127.0.0.1:26658
  437. I[2019-07-28|15:44:53.632] Version info module=main software=0.32.1 block=10 p2p=7
  438. I[2019-07-28|15:44:53.677] Starting Node module=main impl=Node
  439. 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}}"
  440. I[2019-07-28|15:44:54.801] Executed block module=state height=8 validTxs=0 invalidTxs=0
  441. I[2019-07-28|15:44:54.814] Committed state module=state height=8 txs=0 appHash=0000000000000000
  442. ```
  443. Now open another tab in your terminal and try sending a transaction:
  444. ```bash
  445. $ curl -s 'localhost:26657/broadcast_tx_commit?tx="tendermint=rocks"'
  446. {
  447. "jsonrpc": "2.0",
  448. "id": "",
  449. "result": {
  450. "check_tx": {
  451. "gasWanted": "1"
  452. },
  453. "deliver_tx": {},
  454. "hash": "CDD3C6DFA0A08CAEDF546F9938A2EEC232209C24AA0E4201194E0AFB78A2C2BB",
  455. "height": "33"
  456. }
  457. ```
  458. Response should contain the height where this transaction was committed.
  459. Now let's check if the given key now exists and its value:
  460. ```bash
  461. $ curl -s 'localhost:26657/abci_query?data="tendermint"'
  462. {
  463. "jsonrpc": "2.0",
  464. "id": "",
  465. "result": {
  466. "response": {
  467. "log": "exists",
  468. "key": "dGVuZGVybWludA==",
  469. "value": "cm9ja3My"
  470. }
  471. }
  472. }
  473. ```
  474. `dGVuZGVybWludA==` and `cm9ja3M=` are the base64-encoding of the ASCII of `tendermint` and `rocks` accordingly.
  475. ## Outro
  476. I hope everything went smoothly and your first, but hopefully not the last,
  477. Tendermint Core application is up and running. If not, please [open an issue on
  478. Github](https://github.com/tendermint/tendermint/issues/new/choose). To dig
  479. deeper, read [the docs](https://docs.tendermint.com/master/).
  480. The full source code of this example project can be found [here](https://github.com/climber73/tendermint-abci-grpc-kotlin).