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.

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