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.

523 lines
15 KiB

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