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.

639 lines
17 KiB

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