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.

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