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.

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