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.

618 lines
19 KiB

  1. ---
  2. order: 3
  3. ---
  4. # Creating an application in Java
  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 Java.
  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 "12.0.2" 2019-07-16
  32. Java(TM) SE Runtime Environment (build 12.0.2+10)
  33. Java HotSpot(TM) 64-Bit Server VM (build 12.0.2+10, mixed mode, sharing)
  34. ```
  35. You can choose any version of Java higher or equal to 8.
  36. This guide is written using Java SE Development Kit 12.
  37. Make sure you have `$JAVA_HOME` environment variable set:
  38. ```sh
  39. $ echo $JAVA_HOME
  40. /Library/Java/JavaVirtualMachines/jdk-12.0.2.jdk/Contents/Home
  41. ```
  42. For Gradle installation, please refer to [their official guide](https://gradle.org/install/).
  43. ## 1.2 Creating a new Java 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 java-application --test-framework junit
  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. | |-- java
  69. | | `-- io
  70. | | `-- example
  71. | | `-- App.java
  72. | `-- resources
  73. `-- test
  74. |-- java
  75. | `-- io
  76. | `-- example
  77. | `-- AppTest.java
  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/common \
  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/common/types.proto \
  141. $KVSTORE_HOME/src/main/proto/github.com/tendermint/tendermint/libs/common/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/java/io/example/KVStoreApp.java` file with the following content:
  183. ```java
  184. package io.example;
  185. import io.grpc.stub.StreamObserver;
  186. import types.ABCIApplicationGrpc;
  187. import types.Types.*;
  188. class KVStoreApp extends 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. ```java
  198. @Override
  199. public void checkTx(RequestCheckTx req, StreamObserver<ResponseCheckTx> responseObserver) {
  200. var tx = req.getTx();
  201. int code = validate(tx);
  202. var resp = ResponseCheckTx.newBuilder()
  203. .setCode(code)
  204. .setGasWanted(1)
  205. .build();
  206. responseObserver.onNext(resp);
  207. responseObserver.onCompleted();
  208. }
  209. private int validate(ByteString tx) {
  210. List<byte[]> parts = split(tx, '=');
  211. if (parts.size() != 2) {
  212. return 1;
  213. }
  214. byte[] key = parts.get(0);
  215. byte[] value = parts.get(1);
  216. // check if the same key=value already exists
  217. var stored = getPersistedValue(key);
  218. if (stored != null && Arrays.equals(stored, value)) {
  219. return 2;
  220. }
  221. return 0;
  222. }
  223. private List<byte[]> split(ByteString tx, char separator) {
  224. var arr = tx.toByteArray();
  225. int i;
  226. for (i = 0; i < tx.size(); i++) {
  227. if (arr[i] == (byte)separator) {
  228. break;
  229. }
  230. }
  231. if (i == tx.size()) {
  232. return Collections.emptyList();
  233. }
  234. return List.of(
  235. tx.substring(0, i).toByteArray(),
  236. tx.substring(i + 1).toByteArray()
  237. );
  238. }
  239. ```
  240. Don't worry if this does not compile yet.
  241. If the transaction does not have a form of `{bytes}={bytes}`, we return `1`
  242. code. When the same key=value already exist (same key and value), we return `2`
  243. code. For others, we return a zero code indicating that they are valid.
  244. Note that anything with non-zero code will be considered invalid (`-1`, `100`,
  245. etc.) by Tendermint Core.
  246. Valid transactions will eventually be committed given they are not too big and
  247. have enough gas. To learn more about gas, check out ["the
  248. specification"](https://docs.tendermint.com/master/spec/abci/apps.html#gas).
  249. For the underlying key-value store we'll use
  250. [JetBrains Xodus](https://github.com/JetBrains/xodus), which is a transactional schema-less embedded high-performance database written in Java.
  251. `build.gradle`:
  252. ```groovy
  253. dependencies {
  254. implementation 'org.jetbrains.xodus:xodus-environment:1.3.91'
  255. }
  256. ```
  257. ```java
  258. ...
  259. import jetbrains.exodus.ArrayByteIterable;
  260. import jetbrains.exodus.ByteIterable;
  261. import jetbrains.exodus.env.Environment;
  262. import jetbrains.exodus.env.Store;
  263. import jetbrains.exodus.env.StoreConfig;
  264. import jetbrains.exodus.env.Transaction;
  265. class KVStoreApp extends ABCIApplicationGrpc.ABCIApplicationImplBase {
  266. private Environment env;
  267. private Transaction txn = null;
  268. private Store store = null;
  269. KVStoreApp(Environment env) {
  270. this.env = env;
  271. }
  272. ...
  273. private byte[] getPersistedValue(byte[] k) {
  274. return env.computeInReadonlyTransaction(txn -> {
  275. var store = env.openStore("store", StoreConfig.WITHOUT_DUPLICATES, txn);
  276. ByteIterable byteIterable = store.get(txn, new ArrayByteIterable(k));
  277. if (byteIterable == null) {
  278. return null;
  279. }
  280. return byteIterable.getBytesUnsafe();
  281. });
  282. }
  283. }
  284. ```
  285. ### 1.3.4 BeginBlock -> DeliverTx -> EndBlock -> Commit
  286. When Tendermint Core has decided on the block, it's transferred to the
  287. application in 3 parts: `BeginBlock`, one `DeliverTx` per transaction and
  288. `EndBlock` in the end. `DeliverTx` are being transferred asynchronously, but the
  289. responses are expected to come in order.
  290. ```java
  291. @Override
  292. public void beginBlock(RequestBeginBlock req, StreamObserver<ResponseBeginBlock> responseObserver) {
  293. txn = env.beginTransaction();
  294. store = env.openStore("store", StoreConfig.WITHOUT_DUPLICATES, txn);
  295. var resp = ResponseBeginBlock.newBuilder().build();
  296. responseObserver.onNext(resp);
  297. responseObserver.onCompleted();
  298. }
  299. ```
  300. Here we begin a new transaction, which will accumulate the block's transactions and open the corresponding store.
  301. ```java
  302. @Override
  303. public void deliverTx(RequestDeliverTx req, StreamObserver<ResponseDeliverTx> responseObserver) {
  304. var tx = req.getTx();
  305. int code = validate(tx);
  306. if (code == 0) {
  307. List<byte[]> parts = split(tx, '=');
  308. var key = new ArrayByteIterable(parts.get(0));
  309. var value = new ArrayByteIterable(parts.get(1));
  310. store.put(txn, key, value);
  311. }
  312. var resp = ResponseDeliverTx.newBuilder()
  313. .setCode(code)
  314. .build();
  315. responseObserver.onNext(resp);
  316. responseObserver.onCompleted();
  317. }
  318. ```
  319. If the transaction is badly formatted or the same key=value already exist, we
  320. again return the non-zero code. Otherwise, we add it to the store.
  321. In the current design, a block can include incorrect transactions (those who
  322. passed `CheckTx`, but failed `DeliverTx` or transactions included by the proposer
  323. directly). This is done for performance reasons.
  324. Note we can't commit transactions inside the `DeliverTx` because in such case
  325. `Query`, which may be called in parallel, will return inconsistent data (i.e.
  326. it will report that some value already exist even when the actual block was not
  327. yet committed).
  328. `Commit` instructs the application to persist the new state.
  329. ```java
  330. @Override
  331. public void commit(RequestCommit req, StreamObserver<ResponseCommit> responseObserver) {
  332. txn.commit();
  333. var resp = ResponseCommit.newBuilder()
  334. .setData(ByteString.copyFrom(new byte[8]))
  335. .build();
  336. responseObserver.onNext(resp);
  337. responseObserver.onCompleted();
  338. }
  339. ```
  340. ### 1.3.5 Query
  341. Now, when the client wants to know whenever a particular key/value exist, it
  342. will call Tendermint Core RPC `/abci_query` endpoint, which in turn will call
  343. the application's `Query` method.
  344. Applications are free to provide their own APIs. But by using Tendermint Core
  345. as a proxy, clients (including [light client
  346. package](https://godoc.org/github.com/tendermint/tendermint/lite)) can leverage
  347. the unified API across different applications. Plus they won't have to call the
  348. otherwise separate Tendermint Core API for additional proofs.
  349. Note we don't include a proof here.
  350. ```java
  351. @Override
  352. public void query(RequestQuery req, StreamObserver<ResponseQuery> responseObserver) {
  353. var k = req.getData().toByteArray();
  354. var v = getPersistedValue(k);
  355. var builder = ResponseQuery.newBuilder();
  356. if (v == null) {
  357. builder.setLog("does not exist");
  358. } else {
  359. builder.setLog("exists");
  360. builder.setKey(ByteString.copyFrom(k));
  361. builder.setValue(ByteString.copyFrom(v));
  362. }
  363. responseObserver.onNext(builder.build());
  364. responseObserver.onCompleted();
  365. }
  366. ```
  367. The complete specification can be found
  368. [here](https://docs.tendermint.com/master/spec/abci/).
  369. ## 1.4 Starting an application and a Tendermint Core instances
  370. Put the following code into the `$KVSTORE_HOME/src/main/java/io/example/App.java` file:
  371. ```java
  372. package io.example;
  373. import jetbrains.exodus.env.Environment;
  374. import jetbrains.exodus.env.Environments;
  375. import java.io.IOException;
  376. public class App {
  377. public static void main(String[] args) throws IOException, InterruptedException {
  378. try (Environment env = Environments.newInstance("tmp/storage")) {
  379. var app = new KVStoreApp(env);
  380. var server = new GrpcServer(app, 26658);
  381. server.start();
  382. server.blockUntilShutdown();
  383. }
  384. }
  385. }
  386. ```
  387. It is the entry point of the application.
  388. Here we create a special object `Environment`, which knows where to store the application state.
  389. Then we create and start the gRPC server to handle Tendermint Core requests.
  390. Create the `$KVSTORE_HOME/src/main/java/io/example/GrpcServer.java` file with the following content:
  391. ```java
  392. package io.example;
  393. import io.grpc.BindableService;
  394. import io.grpc.Server;
  395. import io.grpc.ServerBuilder;
  396. import java.io.IOException;
  397. class GrpcServer {
  398. private Server server;
  399. GrpcServer(BindableService service, int port) {
  400. this.server = ServerBuilder.forPort(port)
  401. .addService(service)
  402. .build();
  403. }
  404. void start() throws IOException {
  405. server.start();
  406. System.out.println("gRPC server started, listening on $port");
  407. Runtime.getRuntime().addShutdownHook(new Thread(() -> {
  408. System.out.println("shutting down gRPC server since JVM is shutting down");
  409. GrpcServer.this.stop();
  410. System.out.println("server shut down");
  411. }));
  412. }
  413. private void stop() {
  414. server.shutdown();
  415. }
  416. /**
  417. * Await termination on the main thread since the grpc library uses daemon threads.
  418. */
  419. void blockUntilShutdown() throws InterruptedException {
  420. server.awaitTermination();
  421. }
  422. }
  423. ```
  424. ## 1.5 Getting Up and Running
  425. To create a default configuration, nodeKey and private validator files, let's
  426. execute `tendermint init`. But before we do that, we will need to install
  427. Tendermint Core.
  428. ```sh
  429. $ rm -rf /tmp/example
  430. $ cd $GOPATH/src/github.com/tendermint/tendermint
  431. $ make install
  432. $ TMHOME="/tmp/example" tendermint init
  433. 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
  434. I[2019-07-16|18:20:36.481] Generated node key module=main path=/tmp/example/config/node_key.json
  435. I[2019-07-16|18:20:36.482] Generated genesis file module=main path=/tmp/example/config/genesis.json
  436. ```
  437. Feel free to explore the generated files, which can be found at
  438. `/tmp/example/config` directory. Documentation on the config can be found
  439. [here](https://docs.tendermint.com/master/tendermint-core/configuration.html).
  440. We are ready to start our application:
  441. ```sh
  442. ./gradlew run
  443. gRPC server started, listening on 26658
  444. ```
  445. Then we need to start Tendermint Core and point it to our application. Staying
  446. within the application directory execute:
  447. ```sh
  448. $ TMHOME="/tmp/example" tendermint node --abci grpc --proxy_app tcp://127.0.0.1:26658
  449. I[2019-07-28|15:44:53.632] Version info module=main software=0.32.1 block=10 p2p=7
  450. I[2019-07-28|15:44:53.677] Starting Node module=main impl=Node
  451. 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}}"
  452. I[2019-07-28|15:44:54.801] Executed block module=state height=8 validTxs=0 invalidTxs=0
  453. I[2019-07-28|15:44:54.814] Committed state module=state height=8 txs=0 appHash=0000000000000000
  454. ```
  455. Now open another tab in your terminal and try sending a transaction:
  456. ```sh
  457. $ curl -s 'localhost:26657/broadcast_tx_commit?tx="tendermint=rocks"'
  458. {
  459. "jsonrpc": "2.0",
  460. "id": "",
  461. "result": {
  462. "check_tx": {
  463. "gasWanted": "1"
  464. },
  465. "deliver_tx": {},
  466. "hash": "CDD3C6DFA0A08CAEDF546F9938A2EEC232209C24AA0E4201194E0AFB78A2C2BB",
  467. "height": "33"
  468. }
  469. ```
  470. Response should contain the height where this transaction was committed.
  471. Now let's check if the given key now exists and its value:
  472. ```sh
  473. $ curl -s 'localhost:26657/abci_query?data="tendermint"'
  474. {
  475. "jsonrpc": "2.0",
  476. "id": "",
  477. "result": {
  478. "response": {
  479. "log": "exists",
  480. "key": "dGVuZGVybWludA==",
  481. "value": "cm9ja3My"
  482. }
  483. }
  484. }
  485. ```
  486. `dGVuZGVybWludA==` and `cm9ja3M=` are the base64-encoding of the ASCII of `tendermint` and `rocks` accordingly.
  487. ## Outro
  488. I hope everything went smoothly and your first, but hopefully not the last,
  489. Tendermint Core application is up and running. If not, please [open an issue on
  490. Github](https://github.com/tendermint/tendermint/issues/new/choose). To dig
  491. deeper, read [the docs](https://docs.tendermint.com/master/).
  492. The full source code of this example project can be found [here](https://github.com/climber73/tendermint-abci-grpc-java).