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.

574 lines
18 KiB

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