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.

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