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.

650 lines
17 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.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/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. 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 instance in the same process
  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. "path/filepath"
  256. "syscall"
  257. "github.com/dgraph-io/badger"
  258. "github.com/pkg/errors"
  259. "github.com/spf13/viper"
  260. abci "github.com/tendermint/tendermint/abci/types"
  261. cfg "github.com/tendermint/tendermint/config"
  262. tmflags "github.com/tendermint/tendermint/libs/cli/flags"
  263. "github.com/tendermint/tendermint/libs/log"
  264. nm "github.com/tendermint/tendermint/node"
  265. "github.com/tendermint/tendermint/p2p"
  266. "github.com/tendermint/tendermint/privval"
  267. "github.com/tendermint/tendermint/proxy"
  268. )
  269. var configFile string
  270. func init() {
  271. flag.StringVar(&configFile, "config", "$HOME/.tendermint/config/config.toml", "Path to config.toml")
  272. }
  273. func main() {
  274. db, err := badger.Open(badger.DefaultOptions("/tmp/badger"))
  275. if err != nil {
  276. fmt.Fprintf(os.Stderr, "failed to open badger db: %v", err)
  277. os.Exit(1)
  278. }
  279. defer db.Close()
  280. app := NewKVStoreApplication(db)
  281. flag.Parse()
  282. node, err := newTendermint(app, configFile)
  283. if err != nil {
  284. fmt.Fprintf(os.Stderr, "%v", err)
  285. os.Exit(2)
  286. }
  287. node.Start()
  288. defer func() {
  289. node.Stop()
  290. node.Wait()
  291. }()
  292. c := make(chan os.Signal, 1)
  293. signal.Notify(c, os.Interrupt, syscall.SIGTERM)
  294. <-c
  295. os.Exit(0)
  296. }
  297. func newTendermint(app abci.Application, configFile string) (*nm.Node, error) {
  298. // read config
  299. config := cfg.DefaultConfig()
  300. config.RootDir = filepath.Dir(filepath.Dir(configFile))
  301. viper.SetConfigFile(configFile)
  302. if err := viper.ReadInConfig(); err != nil {
  303. return nil, errors.Wrap(err, "viper failed to read config file")
  304. }
  305. if err := viper.Unmarshal(config); err != nil {
  306. return nil, errors.Wrap(err, "viper failed to unmarshal config")
  307. }
  308. if err := config.ValidateBasic(); err != nil {
  309. return nil, errors.Wrap(err, "config is invalid")
  310. }
  311. // create logger
  312. logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout))
  313. var err error
  314. logger, err = tmflags.ParseLogLevel(config.LogLevel, logger, cfg.DefaultLogLevel())
  315. if err != nil {
  316. return nil, errors.Wrap(err, "failed to parse log level")
  317. }
  318. // read private validator
  319. pv := privval.LoadFilePV(
  320. config.PrivValidatorKeyFile(),
  321. config.PrivValidatorStateFile(),
  322. )
  323. // read node key
  324. nodeKey, err := p2p.LoadNodeKey(config.NodeKeyFile())
  325. if err != nil {
  326. return nil, errors.Wrap(err, "failed to load node's key")
  327. }
  328. // create node
  329. node, err := nm.NewNode(
  330. config,
  331. pv,
  332. nodeKey,
  333. proxy.NewLocalClientCreator(app),
  334. nm.DefaultGenesisDocProviderFunc(config),
  335. nm.DefaultDBProvider,
  336. nm.DefaultMetricsProvider(config.Instrumentation),
  337. logger)
  338. if err != nil {
  339. return nil, errors.Wrap(err, "failed to create new Tendermint node")
  340. }
  341. return node, nil
  342. }
  343. ```
  344. This is a huge blob of code, so let's break it down into pieces.
  345. First, we initialize the Badger database and create an app instance:
  346. ```go
  347. db, err := badger.Open(badger.DefaultOptions("/tmp/badger"))
  348. if err != nil {
  349. fmt.Fprintf(os.Stderr, "failed to open badger db: %v", err)
  350. os.Exit(1)
  351. }
  352. defer db.Close()
  353. app := NewKVStoreApplication(db)
  354. ```
  355. 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).
  356. This can be avoided by setting the truncate option to true, like this:
  357. ```go
  358. db, err := badger.Open(badger.DefaultOptions("/tmp/badger").WithTruncate(true))
  359. ```
  360. Then we use it to create a Tendermint Core `Node` instance:
  361. ```go
  362. flag.Parse()
  363. node, err := newTendermint(app, configFile)
  364. if err != nil {
  365. fmt.Fprintf(os.Stderr, "%v", err)
  366. os.Exit(2)
  367. }
  368. ...
  369. // create node
  370. node, err := nm.NewNode(
  371. config,
  372. pv,
  373. nodeKey,
  374. proxy.NewLocalClientCreator(app),
  375. nm.DefaultGenesisDocProviderFunc(config),
  376. nm.DefaultDBProvider,
  377. nm.DefaultMetricsProvider(config.Instrumentation),
  378. logger)
  379. if err != nil {
  380. return nil, errors.Wrap(err, "failed to create new Tendermint node")
  381. }
  382. ```
  383. `NewNode` requires a few things including a configuration file, a private
  384. validator, a node key and a few others in order to construct the full node.
  385. Note we use `proxy.NewLocalClientCreator` here to create a local client instead
  386. of one communicating through a socket or gRPC.
  387. [viper](https://github.com/spf13/viper) is being used for reading the config,
  388. which we will generate later using the `tendermint init` command.
  389. ```go
  390. config := cfg.DefaultConfig()
  391. config.RootDir = filepath.Dir(filepath.Dir(configFile))
  392. viper.SetConfigFile(configFile)
  393. if err := viper.ReadInConfig(); err != nil {
  394. return nil, errors.Wrap(err, "viper failed to read config file")
  395. }
  396. if err := viper.Unmarshal(config); err != nil {
  397. return nil, errors.Wrap(err, "viper failed to unmarshal config")
  398. }
  399. if err := config.ValidateBasic(); err != nil {
  400. return nil, errors.Wrap(err, "config is invalid")
  401. }
  402. ```
  403. We use `FilePV`, which is a private validator (i.e. thing which signs consensus
  404. messages). Normally, you would use `SignerRemote` to connect to an external
  405. [HSM](https://kb.certus.one/hsm.html).
  406. ```go
  407. pv := privval.LoadFilePV(
  408. config.PrivValidatorKeyFile(),
  409. config.PrivValidatorStateFile(),
  410. )
  411. ```
  412. `nodeKey` is needed to identify the node in a p2p network.
  413. ```go
  414. nodeKey, err := p2p.LoadNodeKey(config.NodeKeyFile())
  415. if err != nil {
  416. return nil, errors.Wrap(err, "failed to load node's key")
  417. }
  418. ```
  419. As for the logger, we use the build-in library, which provides a nice
  420. abstraction over [go-kit's
  421. logger](https://github.com/go-kit/kit/tree/master/log).
  422. ```go
  423. logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout))
  424. var err error
  425. logger, err = tmflags.ParseLogLevel(config.LogLevel, logger, cfg.DefaultLogLevel())
  426. if err != nil {
  427. return nil, errors.Wrap(err, "failed to parse log level")
  428. }
  429. ```
  430. Finally, we start the node and add some signal handling to gracefully stop it
  431. upon receiving SIGTERM or Ctrl-C.
  432. ```go
  433. node.Start()
  434. defer func() {
  435. node.Stop()
  436. node.Wait()
  437. }()
  438. c := make(chan os.Signal, 1)
  439. signal.Notify(c, os.Interrupt, syscall.SIGTERM)
  440. <-c
  441. os.Exit(0)
  442. ```
  443. ## 1.5 Getting Up and Running
  444. We are going to use [Go modules](https://github.com/golang/go/wiki/Modules) for
  445. dependency management.
  446. ```sh
  447. $ export GO111MODULE=on
  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.
  455. ```sh
  456. $ rm -rf /tmp/example
  457. $ cd $GOPATH/src/github.com/tendermint/tendermint
  458. $ make install
  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://tendermint.com/docs/).