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.

536 lines
16 KiB

  1. <!---
  2. order: 1
  3. --->
  4. # Creating an application in Go
  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 - written in any programming language - and securely
  11. replicates it on many machines.
  12. Although Tendermint Core is written in the Golang programming language, prior
  13. knowledge of it is not required for this guide. You can learn it as we go due
  14. to it's simplicity. However, you may want to go through [Learn X in Y minutes
  15. Where X=Go](https://learnxinyminutes.com/docs/go/) first to familiarize
  16. yourself with the syntax.
  17. By following along with this guide, you'll create a Tendermint Core project
  18. called kvstore, a (very) simple distributed BFT key-value store.
  19. ## Built-in app vs external app
  20. To get maximum performance it is better to run your application alongside
  21. Tendermint Core. [Cosmos SDK](https://github.com/cosmos/cosmos-sdk) is written
  22. this way. Please refer to [Writing a built-in Tendermint Core application in
  23. Go](./go-built-in.md) guide for details.
  24. Having a separate application might give you better security guarantees as two
  25. processes would be communicating via established binary protocol. Tendermint
  26. Core will not have access to application's state.
  27. ## 1.1 Installing Go
  28. Please refer to [the official guide for installing
  29. Go](https://golang.org/doc/install).
  30. Verify that you have the latest version of Go installed:
  31. ```bash
  32. $ go version
  33. go version go1.14.x darwin/amd64
  34. ```
  35. Make sure you have `$GOPATH` environment variable set:
  36. ```bash
  37. echo $GOPATH
  38. /Users/melekes/go
  39. ```
  40. ## 1.2 Creating a new Go project
  41. We'll start by creating a new Go project.
  42. ```bash
  43. mkdir kvstore
  44. cd kvstore
  45. ```
  46. Inside the example directory create a `main.go` file with the following content:
  47. ```go
  48. package main
  49. import (
  50. "fmt"
  51. )
  52. func main() {
  53. fmt.Println("Hello, Tendermint Core")
  54. }
  55. ```
  56. When run, this should print "Hello, Tendermint Core" to the standard output.
  57. ```bash
  58. go run main.go
  59. Hello, Tendermint Core
  60. ```
  61. ## 1.3 Writing a Tendermint Core application
  62. Tendermint Core communicates with the application through the Application
  63. BlockChain Interface (ABCI). All message types are defined in the [protobuf
  64. file](https://github.com/tendermint/tendermint/blob/master/abci/types/types.proto).
  65. This allows Tendermint Core to run applications written in any programming
  66. language.
  67. Create a file called `app.go` with the following content:
  68. ```go
  69. package main
  70. import (
  71. abcitypes "github.com/tendermint/tendermint/abci/types"
  72. )
  73. type KVStoreApplication struct {}
  74. var _ abcitypes.Application = (*KVStoreApplication)(nil)
  75. func NewKVStoreApplication() *KVStoreApplication {
  76. return &KVStoreApplication{}
  77. }
  78. func (KVStoreApplication) Info(req abcitypes.RequestInfo) abcitypes.ResponseInfo {
  79. return abcitypes.ResponseInfo{}
  80. }
  81. func (KVStoreApplication) SetOption(req abcitypes.RequestSetOption) abcitypes.ResponseSetOption {
  82. return abcitypes.ResponseSetOption{}
  83. }
  84. func (KVStoreApplication) DeliverTx(req abcitypes.RequestDeliverTx) abcitypes.ResponseDeliverTx {
  85. return abcitypes.ResponseDeliverTx{Code: 0}
  86. }
  87. func (KVStoreApplication) CheckTx(req abcitypes.RequestCheckTx) abcitypes.ResponseCheckTx {
  88. return abcitypes.ResponseCheckTx{Code: 0}
  89. }
  90. func (KVStoreApplication) Commit() abcitypes.ResponseCommit {
  91. return abcitypes.ResponseCommit{}
  92. }
  93. func (KVStoreApplication) Query(req abcitypes.RequestQuery) abcitypes.ResponseQuery {
  94. return abcitypes.ResponseQuery{Code: 0}
  95. }
  96. func (KVStoreApplication) InitChain(req abcitypes.RequestInitChain) abcitypes.ResponseInitChain {
  97. return abcitypes.ResponseInitChain{}
  98. }
  99. func (KVStoreApplication) BeginBlock(req abcitypes.RequestBeginBlock) abcitypes.ResponseBeginBlock {
  100. return abcitypes.ResponseBeginBlock{}
  101. }
  102. func (KVStoreApplication) EndBlock(req abcitypes.RequestEndBlock) abcitypes.ResponseEndBlock {
  103. return abcitypes.ResponseEndBlock{}
  104. }
  105. ```
  106. Now I will go through each method explaining when it's called and adding
  107. required business logic.
  108. ### 1.3.1 CheckTx
  109. When a new transaction is added to the Tendermint Core, it will ask the
  110. application to check it (validate the format, signatures, etc.).
  111. ```go
  112. import "bytes"
  113. func (app *KVStoreApplication) isValid(tx []byte) (code uint32) {
  114. // check format
  115. parts := bytes.Split(tx, []byte("="))
  116. if len(parts) != 2 {
  117. return 1
  118. }
  119. key, value := parts[0], parts[1]
  120. // check if the same key=value already exists
  121. err := app.db.View(func(txn *badger.Txn) error {
  122. item, err := txn.Get(key)
  123. if err != nil && err != badger.ErrKeyNotFound {
  124. return err
  125. }
  126. if err == nil {
  127. return item.Value(func(val []byte) error {
  128. if bytes.Equal(val, value) {
  129. code = 2
  130. }
  131. return nil
  132. })
  133. }
  134. return nil
  135. })
  136. if err != nil {
  137. panic(err)
  138. }
  139. return code
  140. }
  141. func (app *KVStoreApplication) CheckTx(req abcitypes.RequestCheckTx) abcitypes.ResponseCheckTx {
  142. code := app.isValid(req.Tx)
  143. return abcitypes.ResponseCheckTx{Code: code, GasWanted: 1}
  144. }
  145. ```
  146. Don't worry if this does not compile yet.
  147. If the transaction does not have a form of `{bytes}={bytes}`, we return `1`
  148. code. When the same key=value already exist (same key and value), we return `2`
  149. code. For others, we return a zero code indicating that they are valid.
  150. Note that anything with non-zero code will be considered invalid (`-1`, `100`,
  151. etc.) by Tendermint Core.
  152. Valid transactions will eventually be committed given they are not too big and
  153. have enough gas. To learn more about gas, check out ["the
  154. specification"](https://docs.tendermint.com/master/spec/abci/apps.html#gas).
  155. For the underlying key-value store we'll use
  156. [badger](https://github.com/dgraph-io/badger), which is an embeddable,
  157. persistent and fast key-value (KV) database.
  158. ```go
  159. import "github.com/dgraph-io/badger"
  160. type KVStoreApplication struct {
  161. db *badger.DB
  162. currentBatch *badger.Txn
  163. }
  164. func NewKVStoreApplication(db *badger.DB) *KVStoreApplication {
  165. return &KVStoreApplication{
  166. db: db,
  167. }
  168. }
  169. ```
  170. ### 1.3.2 BeginBlock -> DeliverTx -> EndBlock -> Commit
  171. When Tendermint Core has decided on the block, it's transferred to the
  172. application in 3 parts: `BeginBlock`, one `DeliverTx` per transaction and
  173. `EndBlock` in the end. DeliverTx are being transferred asynchronously, but the
  174. responses are expected to come in order.
  175. ```go
  176. func (app *KVStoreApplication) BeginBlock(req abcitypes.RequestBeginBlock) abcitypes.ResponseBeginBlock {
  177. app.currentBatch = app.db.NewTransaction(true)
  178. return abcitypes.ResponseBeginBlock{}
  179. }
  180. ```
  181. Here we create a batch, which will store block's transactions.
  182. ```go
  183. func (app *KVStoreApplication) DeliverTx(req abcitypes.RequestDeliverTx) abcitypes.ResponseDeliverTx {
  184. code := app.isValid(req.Tx)
  185. if code != 0 {
  186. return abcitypes.ResponseDeliverTx{Code: code}
  187. }
  188. parts := bytes.Split(req.Tx, []byte("="))
  189. key, value := parts[0], parts[1]
  190. err := app.currentBatch.Set(key, value)
  191. if err != nil {
  192. panic(err)
  193. }
  194. return abcitypes.ResponseDeliverTx{Code: 0}
  195. }
  196. ```
  197. If the transaction is badly formatted or the same key=value already exist, we
  198. again return the non-zero code. Otherwise, we add it to the current batch.
  199. In the current design, a block can include incorrect transactions (those who
  200. passed CheckTx, but failed DeliverTx or transactions included by the proposer
  201. directly). This is done for performance reasons.
  202. Note we can't commit transactions inside the `DeliverTx` because in such case
  203. `Query`, which may be called in parallel, will return inconsistent data (i.e.
  204. it will report that some value already exist even when the actual block was not
  205. yet committed).
  206. `Commit` instructs the application to persist the new state.
  207. ```go
  208. func (app *KVStoreApplication) Commit() abcitypes.ResponseCommit {
  209. app.currentBatch.Commit()
  210. return abcitypes.ResponseCommit{Data: []byte{}}
  211. }
  212. ```
  213. ### 1.3.3 Query
  214. Now, when the client wants to know whenever a particular key/value exist, it
  215. will call Tendermint Core RPC `/abci_query` endpoint, which in turn will call
  216. the application's `Query` method.
  217. Applications are free to provide their own APIs. But by using Tendermint Core
  218. as a proxy, clients (including [light client
  219. package](https://godoc.org/github.com/tendermint/tendermint/lite2)) can leverage
  220. the unified API across different applications. Plus they won't have to call the
  221. otherwise separate Tendermint Core API for additional proofs.
  222. Note we don't include a proof here.
  223. ```go
  224. func (app *KVStoreApplication) Query(reqQuery abcitypes.RequestQuery) (resQuery abcitypes.ResponseQuery) {
  225. resQuery.Key = reqQuery.Data
  226. err := app.db.View(func(txn *badger.Txn) error {
  227. item, err := txn.Get(reqQuery.Data)
  228. if err != nil && err != badger.ErrKeyNotFound {
  229. return err
  230. }
  231. if err == badger.ErrKeyNotFound {
  232. resQuery.Log = "does not exist"
  233. } else {
  234. return item.Value(func(val []byte) error {
  235. resQuery.Log = "exists"
  236. resQuery.Value = val
  237. return nil
  238. })
  239. }
  240. return nil
  241. })
  242. if err != nil {
  243. panic(err)
  244. }
  245. return
  246. }
  247. ```
  248. The complete specification can be found
  249. [here](https://docs.tendermint.com/master/spec/abci/).
  250. ## 1.4 Starting an application and a Tendermint Core instances
  251. Put the following code into the "main.go" file:
  252. ```go
  253. package main
  254. import (
  255. "flag"
  256. "fmt"
  257. "os"
  258. "os/signal"
  259. "syscall"
  260. "github.com/dgraph-io/badger"
  261. abciserver "github.com/tendermint/tendermint/abci/server"
  262. "github.com/tendermint/tendermint/libs/log"
  263. )
  264. var socketAddr string
  265. func init() {
  266. flag.StringVar(&socketAddr, "socket-addr", "unix://example.sock", "Unix domain socket address")
  267. }
  268. func main() {
  269. db, err := badger.Open(badger.DefaultOptions("/tmp/badger"))
  270. if err != nil {
  271. fmt.Fprintf(os.Stderr, "failed to open badger db: %v", err)
  272. os.Exit(1)
  273. }
  274. defer db.Close()
  275. app := NewKVStoreApplication(db)
  276. flag.Parse()
  277. logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout))
  278. server := abciserver.NewSocketServer(socketAddr, app)
  279. server.SetLogger(logger)
  280. if err := server.Start(); err != nil {
  281. fmt.Fprintf(os.Stderr, "error starting socket server: %v", err)
  282. os.Exit(1)
  283. }
  284. defer server.Stop()
  285. c := make(chan os.Signal, 1)
  286. signal.Notify(c, os.Interrupt, syscall.SIGTERM)
  287. <-c
  288. os.Exit(0)
  289. }
  290. ```
  291. This is a huge blob of code, so let's break it down into pieces.
  292. First, we initialize the Badger database and create an app instance:
  293. ```go
  294. db, err := badger.Open(badger.DefaultOptions("/tmp/badger"))
  295. if err != nil {
  296. fmt.Fprintf(os.Stderr, "failed to open badger db: %v", err)
  297. os.Exit(1)
  298. }
  299. defer db.Close()
  300. app := NewKVStoreApplication(db)
  301. ```
  302. For **Windows** users, restarting this app will make badger throw an error as it requires value log to be truncated. For more information on this, visit [here](https://github.com/dgraph-io/badger/issues/744).
  303. This can be avoided by setting the truncate option to true, like this:
  304. ```go
  305. db, err := badger.Open(badger.DefaultOptions("/tmp/badger").WithTruncate(true))
  306. ```
  307. Then we start the ABCI server and add some signal handling to gracefully stop
  308. it upon receiving SIGTERM or Ctrl-C. Tendermint Core will act as a client,
  309. which connects to our server and send us transactions and other messages.
  310. ```go
  311. server := abciserver.NewSocketServer(socketAddr, app)
  312. server.SetLogger(logger)
  313. if err := server.Start(); err != nil {
  314. fmt.Fprintf(os.Stderr, "error starting socket server: %v", err)
  315. os.Exit(1)
  316. }
  317. defer server.Stop()
  318. c := make(chan os.Signal, 1)
  319. signal.Notify(c, os.Interrupt, syscall.SIGTERM)
  320. <-c
  321. os.Exit(0)
  322. ```
  323. ## 1.5 Getting Up and Running
  324. We are going to use [Go modules](https://github.com/golang/go/wiki/Modules) for
  325. dependency management.
  326. ```bash
  327. export GO111MODULE=on
  328. go mod init github.com/me/example
  329. go build
  330. ```
  331. This should build the binary.
  332. To create a default configuration, nodeKey and private validator files, let's
  333. execute `tendermint init`. But before we do that, we will need to install
  334. Tendermint Core. Please refer to [the official
  335. guide](https://docs.tendermint.com/master/introduction/install.html). If you're
  336. installing from source, don't forget to checkout the latest release (`git checkout vX.Y.Z`).
  337. ```bash
  338. rm -rf /tmp/example
  339. TMHOME="/tmp/example" tendermint init
  340. 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
  341. I[2019-07-16|18:20:36.481] Generated node key module=main path=/tmp/example/config/node_key.json
  342. I[2019-07-16|18:20:36.482] Generated genesis file module=main path=/tmp/example/config/genesis.json
  343. ```
  344. Feel free to explore the generated files, which can be found at
  345. `/tmp/example/config` directory. Documentation on the config can be found
  346. [here](https://docs.tendermint.com/master/tendermint-core/configuration.html).
  347. We are ready to start our application:
  348. ```bash
  349. rm example.sock
  350. ./example
  351. badger 2019/07/16 18:25:11 INFO: All 0 tables opened in 0s
  352. badger 2019/07/16 18:25:11 INFO: Replaying file id: 0 at offset: 0
  353. badger 2019/07/16 18:25:11 INFO: Replay took: 300.4s
  354. I[2019-07-16|18:25:11.523] Starting ABCIServer impl=ABCIServ
  355. ```
  356. Then we need to start Tendermint Core and point it to our application. Staying
  357. within the application directory execute:
  358. ```bash
  359. TMHOME="/tmp/example" tendermint node --proxy_app=unix://example.sock
  360. I[2019-07-16|18:26:20.362] Version info module=main software=0.32.1 block=10 p2p=7
  361. I[2019-07-16|18:26:20.383] Starting Node module=main impl=Node
  362. E[2019-07-16|18:26:20.392] Couldn't connect to any seeds module=p2p
  363. I[2019-07-16|18:26:20.394] Started node module=main nodeInfo="{ProtocolVersion:{P2P:7 Block:10 App:0} ID_:8dab80770ae8e295d4ce905d86af78c4ff634b79 ListenAddr:tcp://0.0.0.0:26656 Network:test-chain-nIO96P Version:0.32.1 Channels:4020212223303800 Moniker:app48.fun-box.ru Other:{TxIndex:on RPCAddress:tcp://127.0.0.1:26657}}"
  364. I[2019-07-16|18:26:21.440] Executed block module=state height=1 validTxs=0 invalidTxs=0
  365. I[2019-07-16|18:26:21.446] Committed state module=state height=1 txs=0 appHash=
  366. ```
  367. This should start the full node and connect to our ABCI application.
  368. ```sh
  369. I[2019-07-16|18:25:11.525] Waiting for new connection...
  370. I[2019-07-16|18:26:20.329] Accepted a new connection
  371. I[2019-07-16|18:26:20.329] Waiting for new connection...
  372. I[2019-07-16|18:26:20.330] Accepted a new connection
  373. I[2019-07-16|18:26:20.330] Waiting for new connection...
  374. I[2019-07-16|18:26:20.330] Accepted a new connection
  375. ```
  376. Now open another tab in your terminal and try sending a transaction:
  377. ```json
  378. curl -s 'localhost:26657/broadcast_tx_commit?tx="tendermint=rocks"'
  379. {
  380. "jsonrpc": "2.0",
  381. "id": "",
  382. "result": {
  383. "check_tx": {
  384. "gasWanted": "1"
  385. },
  386. "deliver_tx": {},
  387. "hash": "CDD3C6DFA0A08CAEDF546F9938A2EEC232209C24AA0E4201194E0AFB78A2C2BB",
  388. "height": "33"
  389. }
  390. ```
  391. Response should contain the height where this transaction was committed.
  392. Now let's check if the given key now exists and its value:
  393. ```json
  394. curl -s 'localhost:26657/abci_query?data="tendermint"'
  395. {
  396. "jsonrpc": "2.0",
  397. "id": "",
  398. "result": {
  399. "response": {
  400. "log": "exists",
  401. "key": "dGVuZGVybWludA==",
  402. "value": "cm9ja3My"
  403. }
  404. }
  405. }
  406. ```
  407. "dGVuZGVybWludA==" and "cm9ja3M=" are the base64-encoding of the ASCII of
  408. "tendermint" and "rocks" accordingly.
  409. ## Outro
  410. I hope everything went smoothly and your first, but hopefully not the last,
  411. Tendermint Core application is up and running. If not, please [open an issue on
  412. Github](https://github.com/tendermint/tendermint/issues/new/choose). To dig
  413. deeper, read [the docs](https://docs.tendermint.com/master/).