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.

684 lines
19 KiB

  1. <!---
  2. order: 2
  3. --->
  4. # Creating a built-in 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. > Note: please use a released version of Tendermint with this guide. The guides will work with the latest version. Please, do not use master.
  20. ## Built-in app vs external app
  21. Running your application inside the same process as Tendermint Core will give
  22. you the best possible performance.
  23. For other languages, your application have to communicate with Tendermint Core
  24. through a TCP, Unix domain socket or gRPC.
  25. ## 1.1 Installing Go
  26. Please refer to [the official guide for installing
  27. Go](https://golang.org/doc/install).
  28. Verify that you have the latest version of Go installed:
  29. ```bash
  30. $ go version
  31. go version go1.16.x darwin/amd64
  32. ```
  33. ## 1.2 Creating a new Go project
  34. We'll start by creating a new Go project.
  35. ```bash
  36. mkdir kvstore
  37. cd kvstore
  38. go mod init github.com/<github_username>/<repo_name>
  39. ```
  40. Inside the example directory create a `main.go` file with the following content:
  41. > Note: there is no need to clone or fork Tendermint in this tutorial.
  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) DeliverTx(req abcitypes.RequestDeliverTx) abcitypes.ResponseDeliverTx {
  77. return abcitypes.ResponseDeliverTx{Code: 0}
  78. }
  79. func (KVStoreApplication) CheckTx(req abcitypes.RequestCheckTx) abcitypes.ResponseCheckTx {
  80. return abcitypes.ResponseCheckTx{Code: 0}
  81. }
  82. func (KVStoreApplication) Commit() abcitypes.ResponseCommit {
  83. return abcitypes.ResponseCommit{}
  84. }
  85. func (KVStoreApplication) Query(req abcitypes.RequestQuery) abcitypes.ResponseQuery {
  86. return abcitypes.ResponseQuery{Code: 0}
  87. }
  88. func (KVStoreApplication) InitChain(req abcitypes.RequestInitChain) abcitypes.ResponseInitChain {
  89. return abcitypes.ResponseInitChain{}
  90. }
  91. func (KVStoreApplication) BeginBlock(req abcitypes.RequestBeginBlock) abcitypes.ResponseBeginBlock {
  92. return abcitypes.ResponseBeginBlock{}
  93. }
  94. func (KVStoreApplication) EndBlock(req abcitypes.RequestEndBlock) abcitypes.ResponseEndBlock {
  95. return abcitypes.ResponseEndBlock{}
  96. }
  97. func (KVStoreApplication) ListSnapshots(abcitypes.RequestListSnapshots) abcitypes.ResponseListSnapshots {
  98. return abcitypes.ResponseListSnapshots{}
  99. }
  100. func (KVStoreApplication) OfferSnapshot(abcitypes.RequestOfferSnapshot) abcitypes.ResponseOfferSnapshot {
  101. return abcitypes.ResponseOfferSnapshot{}
  102. }
  103. func (KVStoreApplication) LoadSnapshotChunk(abcitypes.RequestLoadSnapshotChunk) abcitypes.ResponseLoadSnapshotChunk {
  104. return abcitypes.ResponseLoadSnapshotChunk{}
  105. }
  106. func (KVStoreApplication) ApplySnapshotChunk(abcitypes.RequestApplySnapshotChunk) abcitypes.ResponseApplySnapshotChunk {
  107. return abcitypes.ResponseApplySnapshotChunk{}
  108. }
  109. ```
  110. Now I will go through each method explaining when it's called and adding
  111. required business logic.
  112. ### 1.3.1 CheckTx
  113. When a new transaction is added to the Tendermint Core, it will ask the
  114. application to check it (validate the format, signatures, etc.).
  115. ```go
  116. import "bytes"
  117. func (app *KVStoreApplication) isValid(tx []byte) (code uint32) {
  118. // check format
  119. parts := bytes.Split(tx, []byte("="))
  120. if len(parts) != 2 {
  121. return 1
  122. }
  123. key, value := parts[0], parts[1]
  124. // check if the same key=value already exists
  125. err := app.db.View(func(txn *badger.Txn) error {
  126. item, err := txn.Get(key)
  127. if err != nil && err != badger.ErrKeyNotFound {
  128. return err
  129. }
  130. if err == nil {
  131. return item.Value(func(val []byte) error {
  132. if bytes.Equal(val, value) {
  133. code = 2
  134. }
  135. return nil
  136. })
  137. }
  138. return nil
  139. })
  140. if err != nil {
  141. panic(err)
  142. }
  143. return code
  144. }
  145. func (app *KVStoreApplication) CheckTx(req abcitypes.RequestCheckTx) abcitypes.ResponseCheckTx {
  146. code := app.isValid(req.Tx)
  147. return abcitypes.ResponseCheckTx{Code: code, GasWanted: 1}
  148. }
  149. ```
  150. Don't worry if this does not compile yet.
  151. If the transaction does not have a form of `{bytes}={bytes}`, we return `1`
  152. code. When the same key=value already exist (same key and value), we return `2`
  153. code. For others, we return a zero code indicating that they are valid.
  154. Note that anything with non-zero code will be considered invalid (`-1`, `100`,
  155. etc.) by Tendermint Core.
  156. Valid transactions will eventually be committed given they are not too big and
  157. have enough gas. To learn more about gas, check out ["the
  158. specification"](https://github.com/tendermint/tendermint/blob/master/spec/abci/apps.md#gas).
  159. For the underlying key-value store we'll use
  160. [badger](https://github.com/dgraph-io/badger), which is an embeddable,
  161. persistent and fast key-value (KV) database.
  162. ```go
  163. import "github.com/dgraph-io/badger"
  164. type KVStoreApplication struct {
  165. db *badger.DB
  166. currentBatch *badger.Txn
  167. }
  168. func NewKVStoreApplication(db *badger.DB) *KVStoreApplication {
  169. return &KVStoreApplication{
  170. db: db,
  171. }
  172. }
  173. ```
  174. ### 1.3.2 BeginBlock -> DeliverTx -> EndBlock -> Commit
  175. When Tendermint Core has decided on the block, it's transfered to the
  176. application in 3 parts: `BeginBlock`, one `DeliverTx` per transaction and
  177. `EndBlock` in the end. DeliverTx are being transfered asynchronously, but the
  178. responses are expected to come in order.
  179. ```go
  180. func (app *KVStoreApplication) BeginBlock(req abcitypes.RequestBeginBlock) abcitypes.ResponseBeginBlock {
  181. app.currentBatch = app.db.NewTransaction(true)
  182. return abcitypes.ResponseBeginBlock{}
  183. }
  184. ```
  185. Here we create a batch, which will store block's transactions.
  186. ```go
  187. func (app *KVStoreApplication) DeliverTx(req abcitypes.RequestDeliverTx) abcitypes.ResponseDeliverTx {
  188. code := app.isValid(req.Tx)
  189. if code != 0 {
  190. return abcitypes.ResponseDeliverTx{Code: code}
  191. }
  192. parts := bytes.Split(req.Tx, []byte("="))
  193. key, value := parts[0], parts[1]
  194. err := app.currentBatch.Set(key, value)
  195. if err != nil {
  196. panic(err)
  197. }
  198. return abcitypes.ResponseDeliverTx{Code: 0}
  199. }
  200. ```
  201. If the transaction is badly formatted or the same key=value already exist, we
  202. again return the non-zero code. Otherwise, we add it to the current batch.
  203. In the current design, a block can include incorrect transactions (those who
  204. passed CheckTx, but failed DeliverTx or transactions included by the proposer
  205. directly). This is done for performance reasons.
  206. Note we can't commit transactions inside the `DeliverTx` because in such case
  207. `Query`, which may be called in parallel, will return inconsistent data (i.e.
  208. it will report that some value already exist even when the actual block was not
  209. yet committed).
  210. `Commit` instructs the application to persist the new state.
  211. ```go
  212. func (app *KVStoreApplication) Commit() abcitypes.ResponseCommit {
  213. app.currentBatch.Commit()
  214. return abcitypes.ResponseCommit{Data: []byte{}}
  215. }
  216. ```
  217. ### 1.3.3 Query
  218. Now, when the client wants to know whenever a particular key/value exist, it
  219. will call Tendermint Core RPC `/abci_query` endpoint, which in turn will call
  220. the application's `Query` method.
  221. Applications are free to provide their own APIs. But by using Tendermint Core
  222. as a proxy, clients (including [light client
  223. package](https://godoc.org/github.com/tendermint/tendermint/light)) can leverage
  224. the unified API across different applications. Plus they won't have to call the
  225. otherwise separate Tendermint Core API for additional proofs.
  226. Note we don't include a proof here.
  227. ```go
  228. func (app *KVStoreApplication) Query(reqQuery abcitypes.RequestQuery) (resQuery abcitypes.ResponseQuery) {
  229. resQuery.Key = reqQuery.Data
  230. err := app.db.View(func(txn *badger.Txn) error {
  231. item, err := txn.Get(reqQuery.Data)
  232. if err != nil && err != badger.ErrKeyNotFound {
  233. return err
  234. }
  235. if err == badger.ErrKeyNotFound {
  236. resQuery.Log = "does not exist"
  237. } else {
  238. return item.Value(func(val []byte) error {
  239. resQuery.Log = "exists"
  240. resQuery.Value = val
  241. return nil
  242. })
  243. }
  244. return nil
  245. })
  246. if err != nil {
  247. panic(err)
  248. }
  249. return
  250. }
  251. ```
  252. The complete specification can be found
  253. [here](https://github.com/tendermint/tendermint/tree/master/spec/abci/).
  254. ## 1.4 Starting an application and a Tendermint Core instance in the same process
  255. Put the following code into the "main.go" file:
  256. ```go
  257. package main
  258. import (
  259. "flag"
  260. "fmt"
  261. "os"
  262. "os/signal"
  263. "path/filepath"
  264. "syscall"
  265. "github.com/dgraph-io/badger"
  266. "github.com/spf13/viper"
  267. abci "github.com/tendermint/tendermint/abci/types"
  268. cfg "github.com/tendermint/tendermint/config"
  269. tmflags "github.com/tendermint/tendermint/libs/cli/flags"
  270. "github.com/tendermint/tendermint/libs/log"
  271. nm "github.com/tendermint/tendermint/node"
  272. "github.com/tendermint/tendermint/internal/p2p"
  273. "github.com/tendermint/tendermint/privval"
  274. "github.com/tendermint/tendermint/proxy"
  275. )
  276. var configFile string
  277. func init() {
  278. flag.StringVar(&configFile, "config", "$HOME/.tendermint/config/config.toml", "Path to config.toml")
  279. }
  280. func main() {
  281. db, err := badger.Open(badger.DefaultOptions("/tmp/badger"))
  282. if err != nil {
  283. fmt.Fprintf(os.Stderr, "failed to open badger db: %v", err)
  284. os.Exit(1)
  285. }
  286. defer db.Close()
  287. app := NewKVStoreApplication(db)
  288. flag.Parse()
  289. node, err := newTendermint(app, configFile)
  290. if err != nil {
  291. fmt.Fprintf(os.Stderr, "%v", err)
  292. os.Exit(2)
  293. }
  294. node.Start()
  295. defer func() {
  296. node.Stop()
  297. node.Wait()
  298. }()
  299. c := make(chan os.Signal, 1)
  300. signal.Notify(c, os.Interrupt, syscall.SIGTERM)
  301. <-c
  302. }
  303. func newTendermint(app abci.Application, configFile string) (*nm.Node, error) {
  304. // read config
  305. config := cfg.DefaultValidatorConfig()
  306. config.RootDir = filepath.Dir(filepath.Dir(configFile))
  307. viper.SetConfigFile(configFile)
  308. if err := viper.ReadInConfig(); err != nil {
  309. return nil, fmt.Errorf("viper failed to read config file: %w", err)
  310. }
  311. if err := viper.Unmarshal(config); err != nil {
  312. return nil, fmt.Errorf("viper failed to unmarshal config: %w", err)
  313. }
  314. if err := config.ValidateBasic(); err != nil {
  315. return nil, fmt.Errorf("config is invalid: %w", err)
  316. }
  317. // create logger
  318. logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout))
  319. var err error
  320. logger, err = tmflags.ParseLogLevel(config.LogLevel, logger, cfg.DefaultLogLevel)
  321. if err != nil {
  322. return nil, fmt.Errorf("failed to parse log level: %w", err)
  323. }
  324. // read private validator
  325. pv := privval.LoadFilePV(
  326. config.PrivValidatorKeyFile(),
  327. config.PrivValidatorStateFile(),
  328. )
  329. // read node key
  330. nodeKey, err := p2p.LoadNodeKey(config.NodeKeyFile())
  331. if err != nil {
  332. return nil, fmt.Errorf("failed to load node's key: %w", err)
  333. }
  334. // create node
  335. node, err := nm.NewNode(
  336. config,
  337. pv,
  338. nodeKey,
  339. abcicli.NewLocalClientCreator(app),
  340. nm.DefaultGenesisDocProviderFunc(config),
  341. nm.DefaultDBProvider,
  342. nm.DefaultMetricsProvider(config.Instrumentation),
  343. logger)
  344. if err != nil {
  345. return nil, fmt.Errorf("failed to create new Tendermint node: %w", err)
  346. }
  347. return node, nil
  348. }
  349. ```
  350. This is a huge blob of code, so let's break it down into pieces.
  351. First, we initialize the Badger database and create an app instance:
  352. ```go
  353. db, err := badger.Open(badger.DefaultOptions("/tmp/badger"))
  354. if err != nil {
  355. fmt.Fprintf(os.Stderr, "failed to open badger db: %v", err)
  356. os.Exit(1)
  357. }
  358. defer db.Close()
  359. app := NewKVStoreApplication(db)
  360. ```
  361. 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).
  362. This can be avoided by setting the truncate option to true, like this:
  363. ```go
  364. db, err := badger.Open(badger.DefaultOptions("/tmp/badger").WithTruncate(true))
  365. ```
  366. Then we use it to create a Tendermint Core `Node` instance:
  367. ```go
  368. flag.Parse()
  369. node, err := newTendermint(app, configFile)
  370. if err != nil {
  371. fmt.Fprintf(os.Stderr, "%v", err)
  372. os.Exit(2)
  373. }
  374. ...
  375. // create node
  376. node, err := nm.NewNode(
  377. config,
  378. pv,
  379. nodeKey,
  380. abcicli.NewLocalClientCreator(app),
  381. nm.DefaultGenesisDocProviderFunc(config),
  382. nm.DefaultDBProvider,
  383. nm.DefaultMetricsProvider(config.Instrumentation),
  384. logger)
  385. if err != nil {
  386. return nil, fmt.Errorf("failed to create new Tendermint node: %w", err)
  387. }
  388. ```
  389. `NewNode` requires a few things including a configuration file, a private
  390. validator, a node key and a few others in order to construct the full node.
  391. Note we use `abcicli.NewLocalClientCreator` here to create a local client instead
  392. of one communicating through a socket or gRPC.
  393. [viper](https://github.com/spf13/viper) is being used for reading the config,
  394. which we will generate later using the `tendermint init` command.
  395. ```go
  396. config := cfg.DefaultValidatorConfig()
  397. config.RootDir = filepath.Dir(filepath.Dir(configFile))
  398. viper.SetConfigFile(configFile)
  399. if err := viper.ReadInConfig(); err != nil {
  400. return nil, fmt.Errorf("viper failed to read config file: %w", err)
  401. }
  402. if err := viper.Unmarshal(config); err != nil {
  403. return nil, fmt.Errorf("viper failed to unmarshal config: %w", err)
  404. }
  405. if err := config.ValidateBasic(); err != nil {
  406. return nil, fmt.Errorf("config is invalid: %w", err)
  407. }
  408. ```
  409. We use `FilePV`, which is a private validator (i.e. thing which signs consensus
  410. messages). Normally, you would use `SignerRemote` to connect to an external
  411. [HSM](https://kb.certus.one/hsm.html).
  412. ```go
  413. pv := privval.LoadFilePV(
  414. config.PrivValidatorKeyFile(),
  415. config.PrivValidatorStateFile(),
  416. )
  417. ```
  418. `nodeKey` is needed to identify the node in a p2p network.
  419. ```go
  420. nodeKey, err := p2p.LoadNodeKey(config.NodeKeyFile())
  421. if err != nil {
  422. return nil, fmt.Errorf("failed to load node's key: %w", err)
  423. }
  424. ```
  425. As for the logger, we use the build-in library, which provides a nice
  426. abstraction over [go-kit's
  427. logger](https://github.com/go-kit/kit/tree/master/log).
  428. ```go
  429. logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout))
  430. var err error
  431. logger, err = tmflags.ParseLogLevel(config.LogLevel, logger, cfg.DefaultLogLevel())
  432. if err != nil {
  433. return nil, fmt.Errorf("failed to parse log level: %w", err)
  434. }
  435. ```
  436. Finally, we start the node and add some signal handling to gracefully stop it
  437. upon receiving SIGTERM or Ctrl-C.
  438. ```go
  439. node.Start()
  440. defer func() {
  441. node.Stop()
  442. node.Wait()
  443. }()
  444. c := make(chan os.Signal, 1)
  445. signal.Notify(c, os.Interrupt, syscall.SIGTERM)
  446. <-c
  447. ```
  448. ## 1.5 Getting Up and Running
  449. We are going to use [Go modules](https://github.com/golang/go/wiki/Modules) for
  450. dependency management.
  451. ```bash
  452. export GO111MODULE=on
  453. go mod init github.com/me/example
  454. ```
  455. This should create a `go.mod` file. The current tutorial only works with
  456. the master branch of Tendermint. so let's make sure we're using the latest version:
  457. ```sh
  458. go get github.com/tendermint/tendermint@master
  459. ```
  460. This will populate the `go.mod` with a release number followed by a hash for Tendermint.
  461. ```go
  462. module github.com/me/example
  463. go 1.15
  464. require (
  465. github.com/dgraph-io/badger v1.6.2
  466. github.com/tendermint/tendermint <vX>
  467. )
  468. ```
  469. Now we can build the binary:
  470. ```bash
  471. go build
  472. ```
  473. To create a default configuration, nodeKey and private validator files, let's
  474. execute `tendermint init validator`. But before we do that, we will need to install
  475. Tendermint Core. Please refer to [the official
  476. guide](https://docs.tendermint.com/master/introduction/install.html). If you're
  477. installing from source, don't forget to checkout the latest release (`git
  478. checkout vX.Y.Z`). Don't forget to check that the application uses the same
  479. major version.
  480. ```bash
  481. $ rm -rf /tmp/example
  482. $ TMHOME="/tmp/example" tendermint init validator
  483. I[2019-07-16|18:40:36.480] Generated private validator module=main keyFile=/tmp/example/config/priv_validator_key.json stateFile=/tmp/example2/data/priv_validator_state.json
  484. I[2019-07-16|18:40:36.481] Generated node key module=main path=/tmp/example/config/node_key.json
  485. I[2019-07-16|18:40:36.482] Generated genesis file module=main path=/tmp/example/config/genesis.json
  486. I[2019-07-16|18:40:36.483] Generated config module=main mode=validator
  487. ```
  488. We are ready to start our application:
  489. ```bash
  490. $ ./example -config "/tmp/example/config/config.toml"
  491. badger 2019/07/16 18:42:25 INFO: All 0 tables opened in 0s
  492. badger 2019/07/16 18:42:25 INFO: Replaying file id: 0 at offset: 0
  493. badger 2019/07/16 18:42:25 INFO: Replay took: 695.227s
  494. E[2019-07-16|18:42:25.818] Couldn't connect to any seeds module=p2p
  495. I[2019-07-16|18:42:26.853] Executed block module=state height=1 validTxs=0 invalidTxs=0
  496. I[2019-07-16|18:42:26.865] Committed state module=state height=1 txs=0 appHash=
  497. ```
  498. Now open another tab in your terminal and try sending a transaction:
  499. ```bash
  500. $ curl -s 'localhost:26657/broadcast_tx_commit?tx="tendermint=rocks"'
  501. {
  502. "check_tx": {
  503. "gasWanted": "1",
  504. ...
  505. },
  506. "deliver_tx": { ... },
  507. "hash": "1B3C5A1093DB952C331B1749A21DCCBB0F6C7F4E0055CD04D16346472FC60EC6",
  508. "height": "128"
  509. }
  510. ```
  511. Response should contain the height where this transaction was committed.
  512. Now let's check if the given key now exists and its value:
  513. ```json
  514. $ curl -s 'localhost:26657/abci_query?data="tendermint"'
  515. {
  516. "response": {
  517. "code": 0,
  518. "log": "exists",
  519. "info": "",
  520. "index": "0",
  521. "key": "dGVuZGVybWludA==",
  522. "value": "cm9ja3M=",
  523. "proofOps": null,
  524. "height": "6",
  525. "codespace": ""
  526. }
  527. }
  528. ```
  529. "dGVuZGVybWludA==" and "cm9ja3M=" are the base64-encoding of the ASCII of
  530. "tendermint" and "rocks" accordingly.
  531. ## Outro
  532. I hope everything went smoothly and your first, but hopefully not the last,
  533. Tendermint Core application is up and running. If not, please [open an issue on
  534. Github](https://github.com/tendermint/tendermint/issues/new/choose). To dig
  535. deeper, read [the docs](https://docs.tendermint.com/master/).