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.

630 lines
17 KiB

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