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.

693 lines
16 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
7 years ago
9 years ago
7 years ago
9 years ago
9 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
7 years ago
7 years ago
7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. package main
  2. import (
  3. "bufio"
  4. "encoding/hex"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "os"
  9. "os/signal"
  10. "strings"
  11. "syscall"
  12. "github.com/spf13/cobra"
  13. "github.com/tendermint/tendermint/libs/log"
  14. "github.com/tendermint/tendermint/version"
  15. abciclient "github.com/tendermint/tendermint/abci/client"
  16. "github.com/tendermint/tendermint/abci/example/code"
  17. "github.com/tendermint/tendermint/abci/example/kvstore"
  18. "github.com/tendermint/tendermint/abci/server"
  19. servertest "github.com/tendermint/tendermint/abci/tests/server"
  20. "github.com/tendermint/tendermint/abci/types"
  21. "github.com/tendermint/tendermint/proto/tendermint/crypto"
  22. )
  23. // client is a global variable so it can be reused by the console
  24. var (
  25. client abciclient.Client
  26. )
  27. // flags
  28. var (
  29. // global
  30. flagAddress string
  31. flagAbci string
  32. flagVerbose bool // for the println output
  33. flagLogLevel string // for the logger
  34. // query
  35. flagPath string
  36. flagHeight int
  37. flagProve bool
  38. // kvstore
  39. flagPersist string
  40. )
  41. func RootCmmand(logger log.Logger) *cobra.Command {
  42. return &cobra.Command{
  43. Use: "abci-cli",
  44. Short: "the ABCI CLI tool wraps an ABCI client",
  45. Long: "the ABCI CLI tool wraps an ABCI client and is used for testing ABCI servers",
  46. PersistentPreRunE: func(cmd *cobra.Command, args []string) (err error) {
  47. switch cmd.Use {
  48. case "kvstore", "version":
  49. return nil
  50. }
  51. if client == nil {
  52. var err error
  53. client, err = abciclient.NewClient(logger.With("module", "abci-client"), flagAddress, flagAbci, false)
  54. if err != nil {
  55. return err
  56. }
  57. if err := client.Start(cmd.Context()); err != nil {
  58. return err
  59. }
  60. }
  61. return nil
  62. },
  63. }
  64. }
  65. // Structure for data passed to print response.
  66. type response struct {
  67. // generic abci response
  68. Data []byte
  69. Code uint32
  70. Info string
  71. Log string
  72. Query *queryResponse
  73. }
  74. type queryResponse struct {
  75. Key []byte
  76. Value []byte
  77. Height int64
  78. ProofOps *crypto.ProofOps
  79. }
  80. func Execute() error {
  81. logger, err := log.NewDefaultLogger(log.LogFormatPlain, log.LogLevelInfo)
  82. if err != nil {
  83. return err
  84. }
  85. cmd := RootCmmand(logger)
  86. addGlobalFlags(cmd)
  87. addCommands(cmd, logger)
  88. return cmd.Execute()
  89. }
  90. func addGlobalFlags(cmd *cobra.Command) {
  91. cmd.PersistentFlags().StringVarP(&flagAddress,
  92. "address",
  93. "",
  94. "tcp://0.0.0.0:26658",
  95. "address of application socket")
  96. cmd.PersistentFlags().StringVarP(&flagAbci, "abci", "", "socket", "either socket or grpc")
  97. cmd.PersistentFlags().BoolVarP(&flagVerbose,
  98. "verbose",
  99. "v",
  100. false,
  101. "print the command and results as if it were a console session")
  102. cmd.PersistentFlags().StringVarP(&flagLogLevel, "log_level", "", "debug", "set the logger level")
  103. }
  104. func addCommands(cmd *cobra.Command, logger log.Logger) {
  105. cmd.AddCommand(batchCmd)
  106. cmd.AddCommand(consoleCmd)
  107. cmd.AddCommand(echoCmd)
  108. cmd.AddCommand(infoCmd)
  109. cmd.AddCommand(deliverTxCmd)
  110. cmd.AddCommand(checkTxCmd)
  111. cmd.AddCommand(commitCmd)
  112. cmd.AddCommand(versionCmd)
  113. cmd.AddCommand(testCmd)
  114. cmd.AddCommand(getQueryCmd())
  115. // examples
  116. cmd.AddCommand(getKVStoreCmd(logger))
  117. }
  118. var batchCmd = &cobra.Command{
  119. Use: "batch",
  120. Short: "run a batch of abci commands against an application",
  121. Long: `run a batch of abci commands against an application
  122. This command is run by piping in a file containing a series of commands
  123. you'd like to run:
  124. abci-cli batch < example.file
  125. where example.file looks something like:
  126. check_tx 0x00
  127. check_tx 0xff
  128. deliver_tx 0x00
  129. check_tx 0x00
  130. deliver_tx 0x01
  131. deliver_tx 0x04
  132. info
  133. `,
  134. Args: cobra.ExactArgs(0),
  135. RunE: cmdBatch,
  136. }
  137. var consoleCmd = &cobra.Command{
  138. Use: "console",
  139. Short: "start an interactive ABCI console for multiple commands",
  140. Long: `start an interactive ABCI console for multiple commands
  141. This command opens an interactive console for running any of the other commands
  142. without opening a new connection each time
  143. `,
  144. Args: cobra.ExactArgs(0),
  145. ValidArgs: []string{"echo", "info", "deliver_tx", "check_tx", "commit", "query"},
  146. RunE: cmdConsole,
  147. }
  148. var echoCmd = &cobra.Command{
  149. Use: "echo",
  150. Short: "have the application echo a message",
  151. Long: "have the application echo a message",
  152. Args: cobra.ExactArgs(1),
  153. RunE: cmdEcho,
  154. }
  155. var infoCmd = &cobra.Command{
  156. Use: "info",
  157. Short: "get some info about the application",
  158. Long: "get some info about the application",
  159. Args: cobra.ExactArgs(0),
  160. RunE: cmdInfo,
  161. }
  162. var deliverTxCmd = &cobra.Command{
  163. Use: "deliver_tx",
  164. Short: "deliver a new transaction to the application",
  165. Long: "deliver a new transaction to the application",
  166. Args: cobra.ExactArgs(1),
  167. RunE: cmdFinalizeBlock,
  168. }
  169. var checkTxCmd = &cobra.Command{
  170. Use: "check_tx",
  171. Short: "validate a transaction",
  172. Long: "validate a transaction",
  173. Args: cobra.ExactArgs(1),
  174. RunE: cmdCheckTx,
  175. }
  176. var commitCmd = &cobra.Command{
  177. Use: "commit",
  178. Short: "commit the application state and return the Merkle root hash",
  179. Long: "commit the application state and return the Merkle root hash",
  180. Args: cobra.ExactArgs(0),
  181. RunE: cmdCommit,
  182. }
  183. var versionCmd = &cobra.Command{
  184. Use: "version",
  185. Short: "print ABCI console version",
  186. Long: "print ABCI console version",
  187. Args: cobra.ExactArgs(0),
  188. RunE: func(cmd *cobra.Command, args []string) error {
  189. fmt.Println(version.ABCIVersion)
  190. return nil
  191. },
  192. }
  193. func getQueryCmd() *cobra.Command {
  194. cmd := &cobra.Command{
  195. Use: "query",
  196. Short: "query the application state",
  197. Long: "query the application state",
  198. Args: cobra.ExactArgs(1),
  199. RunE: cmdQuery,
  200. }
  201. cmd.PersistentFlags().StringVarP(&flagPath, "path", "", "/store", "path to prefix query with")
  202. cmd.PersistentFlags().IntVarP(&flagHeight, "height", "", 0, "height to query the blockchain at")
  203. cmd.PersistentFlags().BoolVarP(&flagProve,
  204. "prove",
  205. "",
  206. false,
  207. "whether or not to return a merkle proof of the query result")
  208. return cmd
  209. }
  210. func getKVStoreCmd(logger log.Logger) *cobra.Command {
  211. cmd := &cobra.Command{
  212. Use: "kvstore",
  213. Short: "ABCI demo example",
  214. Long: "ABCI demo example",
  215. Args: cobra.ExactArgs(0),
  216. RunE: makeKVStoreCmd(logger),
  217. }
  218. cmd.PersistentFlags().StringVarP(&flagPersist, "persist", "", "", "directory to use for a database")
  219. return cmd
  220. }
  221. var testCmd = &cobra.Command{
  222. Use: "test",
  223. Short: "run integration tests",
  224. Long: "run integration tests",
  225. Args: cobra.ExactArgs(0),
  226. RunE: cmdTest,
  227. }
  228. // Generates new Args array based off of previous call args to maintain flag persistence
  229. func persistentArgs(line []byte) []string {
  230. // generate the arguments to run from original os.Args
  231. // to maintain flag arguments
  232. args := os.Args
  233. args = args[:len(args)-1] // remove the previous command argument
  234. if len(line) > 0 { // prevents introduction of extra space leading to argument parse errors
  235. args = append(args, strings.Split(string(line), " ")...)
  236. }
  237. return args
  238. }
  239. //--------------------------------------------------------------------------------
  240. func compose(fs []func() error) error {
  241. if len(fs) == 0 {
  242. return nil
  243. }
  244. err := fs[0]()
  245. if err == nil {
  246. return compose(fs[1:])
  247. }
  248. return err
  249. }
  250. func cmdTest(cmd *cobra.Command, args []string) error {
  251. ctx := cmd.Context()
  252. return compose(
  253. []func() error{
  254. func() error { return servertest.InitChain(ctx, client) },
  255. func() error { return servertest.Commit(ctx, client, nil) },
  256. func() error {
  257. return servertest.FinalizeBlock(ctx, client, [][]byte{
  258. []byte("abc"),
  259. }, []uint32{
  260. code.CodeTypeBadNonce,
  261. }, nil)
  262. },
  263. func() error { return servertest.Commit(ctx, client, nil) },
  264. func() error {
  265. return servertest.FinalizeBlock(ctx, client, [][]byte{
  266. {0x00},
  267. }, []uint32{
  268. code.CodeTypeOK,
  269. }, nil)
  270. },
  271. func() error { return servertest.Commit(ctx, client, []byte{0, 0, 0, 0, 0, 0, 0, 1}) },
  272. func() error {
  273. return servertest.FinalizeBlock(ctx, client, [][]byte{
  274. {0x00},
  275. {0x01},
  276. {0x00, 0x02},
  277. {0x00, 0x03},
  278. {0x00, 0x00, 0x04},
  279. {0x00, 0x00, 0x06},
  280. }, []uint32{
  281. code.CodeTypeBadNonce,
  282. code.CodeTypeOK,
  283. code.CodeTypeOK,
  284. code.CodeTypeOK,
  285. code.CodeTypeOK,
  286. code.CodeTypeBadNonce,
  287. }, nil)
  288. },
  289. func() error { return servertest.Commit(ctx, client, []byte{0, 0, 0, 0, 0, 0, 0, 5}) },
  290. })
  291. }
  292. func cmdBatch(cmd *cobra.Command, args []string) error {
  293. bufReader := bufio.NewReader(os.Stdin)
  294. LOOP:
  295. for {
  296. line, more, err := bufReader.ReadLine()
  297. switch {
  298. case more:
  299. return errors.New("input line is too long")
  300. case err == io.EOF:
  301. break LOOP
  302. case len(line) == 0:
  303. continue
  304. case err != nil:
  305. return err
  306. }
  307. cmdArgs := persistentArgs(line)
  308. if err := muxOnCommands(cmd, cmdArgs); err != nil {
  309. return err
  310. }
  311. fmt.Println()
  312. }
  313. return nil
  314. }
  315. func cmdConsole(cmd *cobra.Command, args []string) error {
  316. for {
  317. fmt.Printf("> ")
  318. bufReader := bufio.NewReader(os.Stdin)
  319. line, more, err := bufReader.ReadLine()
  320. if more {
  321. return errors.New("input is too long")
  322. } else if err != nil {
  323. return err
  324. }
  325. pArgs := persistentArgs(line)
  326. if err := muxOnCommands(cmd, pArgs); err != nil {
  327. return err
  328. }
  329. }
  330. }
  331. func muxOnCommands(cmd *cobra.Command, pArgs []string) error {
  332. if len(pArgs) < 2 {
  333. return errors.New("expecting persistent args of the form: abci-cli [command] <...>")
  334. }
  335. // TODO: this parsing is fragile
  336. args := []string{}
  337. for i := 0; i < len(pArgs); i++ {
  338. arg := pArgs[i]
  339. // check for flags
  340. if strings.HasPrefix(arg, "-") {
  341. // if it has an equal, we can just skip
  342. if strings.Contains(arg, "=") {
  343. continue
  344. }
  345. // if its a boolean, we can just skip
  346. _, err := cmd.Flags().GetBool(strings.TrimLeft(arg, "-"))
  347. if err == nil {
  348. continue
  349. }
  350. // otherwise, we need to skip the next one too
  351. i++
  352. continue
  353. }
  354. // append the actual arg
  355. args = append(args, arg)
  356. }
  357. var subCommand string
  358. var actualArgs []string
  359. if len(args) > 1 {
  360. subCommand = args[1]
  361. }
  362. if len(args) > 2 {
  363. actualArgs = args[2:]
  364. }
  365. cmd.Use = subCommand // for later print statements ...
  366. switch strings.ToLower(subCommand) {
  367. case "check_tx":
  368. return cmdCheckTx(cmd, actualArgs)
  369. case "commit":
  370. return cmdCommit(cmd, actualArgs)
  371. case "deliver_tx":
  372. return cmdFinalizeBlock(cmd, actualArgs)
  373. case "echo":
  374. return cmdEcho(cmd, actualArgs)
  375. case "info":
  376. return cmdInfo(cmd, actualArgs)
  377. case "query":
  378. return cmdQuery(cmd, actualArgs)
  379. default:
  380. return cmdUnimplemented(cmd, pArgs)
  381. }
  382. }
  383. func cmdUnimplemented(cmd *cobra.Command, args []string) error {
  384. msg := "unimplemented command"
  385. if len(args) > 0 {
  386. msg += fmt.Sprintf(" args: [%s]", strings.Join(args, " "))
  387. }
  388. printResponse(cmd, args, response{
  389. Code: codeBad,
  390. Log: msg,
  391. })
  392. fmt.Println("Available commands:")
  393. for _, cmd := range cmd.Commands() {
  394. fmt.Printf("%s: %s\n", cmd.Use, cmd.Short)
  395. }
  396. fmt.Println("Use \"[command] --help\" for more information about a command.")
  397. return nil
  398. }
  399. // Have the application echo a message
  400. func cmdEcho(cmd *cobra.Command, args []string) error {
  401. msg := ""
  402. if len(args) > 0 {
  403. msg = args[0]
  404. }
  405. res, err := client.Echo(cmd.Context(), msg)
  406. if err != nil {
  407. return err
  408. }
  409. printResponse(cmd, args, response{
  410. Data: []byte(res.Message),
  411. })
  412. return nil
  413. }
  414. // Get some info from the application
  415. func cmdInfo(cmd *cobra.Command, args []string) error {
  416. var version string
  417. if len(args) == 1 {
  418. version = args[0]
  419. }
  420. res, err := client.Info(cmd.Context(), types.RequestInfo{Version: version})
  421. if err != nil {
  422. return err
  423. }
  424. printResponse(cmd, args, response{
  425. Data: []byte(res.Data),
  426. })
  427. return nil
  428. }
  429. const codeBad uint32 = 10
  430. // Append a new tx to application
  431. func cmdFinalizeBlock(cmd *cobra.Command, args []string) error {
  432. if len(args) == 0 {
  433. printResponse(cmd, args, response{
  434. Code: codeBad,
  435. Log: "want the tx",
  436. })
  437. return nil
  438. }
  439. txBytes, err := stringOrHexToBytes(args[0])
  440. if err != nil {
  441. return err
  442. }
  443. res, err := client.FinalizeBlock(cmd.Context(), types.RequestFinalizeBlock{Txs: [][]byte{txBytes}})
  444. if err != nil {
  445. return err
  446. }
  447. for _, tx := range res.Txs {
  448. printResponse(cmd, args, response{
  449. Code: tx.Code,
  450. Data: tx.Data,
  451. Info: tx.Info,
  452. Log: tx.Log,
  453. })
  454. }
  455. return nil
  456. }
  457. // Validate a tx
  458. func cmdCheckTx(cmd *cobra.Command, args []string) error {
  459. if len(args) == 0 {
  460. printResponse(cmd, args, response{
  461. Code: codeBad,
  462. Info: "want the tx",
  463. })
  464. return nil
  465. }
  466. txBytes, err := stringOrHexToBytes(args[0])
  467. if err != nil {
  468. return err
  469. }
  470. res, err := client.CheckTx(cmd.Context(), types.RequestCheckTx{Tx: txBytes})
  471. if err != nil {
  472. return err
  473. }
  474. printResponse(cmd, args, response{
  475. Code: res.Code,
  476. Data: res.Data,
  477. Info: res.Info,
  478. Log: res.Log,
  479. })
  480. return nil
  481. }
  482. // Get application Merkle root hash
  483. func cmdCommit(cmd *cobra.Command, args []string) error {
  484. res, err := client.Commit(cmd.Context())
  485. if err != nil {
  486. return err
  487. }
  488. printResponse(cmd, args, response{
  489. Data: res.Data,
  490. })
  491. return nil
  492. }
  493. // Query application state
  494. func cmdQuery(cmd *cobra.Command, args []string) error {
  495. if len(args) == 0 {
  496. printResponse(cmd, args, response{
  497. Code: codeBad,
  498. Info: "want the query",
  499. Log: "",
  500. })
  501. return nil
  502. }
  503. queryBytes, err := stringOrHexToBytes(args[0])
  504. if err != nil {
  505. return err
  506. }
  507. resQuery, err := client.Query(cmd.Context(), types.RequestQuery{
  508. Data: queryBytes,
  509. Path: flagPath,
  510. Height: int64(flagHeight),
  511. Prove: flagProve,
  512. })
  513. if err != nil {
  514. return err
  515. }
  516. printResponse(cmd, args, response{
  517. Code: resQuery.Code,
  518. Info: resQuery.Info,
  519. Log: resQuery.Log,
  520. Query: &queryResponse{
  521. Key: resQuery.Key,
  522. Value: resQuery.Value,
  523. Height: resQuery.Height,
  524. ProofOps: resQuery.ProofOps,
  525. },
  526. })
  527. return nil
  528. }
  529. func makeKVStoreCmd(logger log.Logger) func(*cobra.Command, []string) error {
  530. return func(cmd *cobra.Command, args []string) error {
  531. // Create the application - in memory or persisted to disk
  532. var app types.Application
  533. if flagPersist == "" {
  534. app = kvstore.NewApplication()
  535. } else {
  536. app = kvstore.NewPersistentKVStoreApplication(logger, flagPersist)
  537. }
  538. // Start the listener
  539. srv, err := server.NewServer(logger.With("module", "abci-server"), flagAddress, flagAbci, app)
  540. if err != nil {
  541. return err
  542. }
  543. ctx, cancel := signal.NotifyContext(cmd.Context(), syscall.SIGTERM)
  544. defer cancel()
  545. if err := srv.Start(ctx); err != nil {
  546. return err
  547. }
  548. // Run forever.
  549. <-ctx.Done()
  550. return nil
  551. }
  552. }
  553. //--------------------------------------------------------------------------------
  554. func printResponse(cmd *cobra.Command, args []string, rsp response) {
  555. if flagVerbose {
  556. fmt.Println(">", cmd.Use, strings.Join(args, " "))
  557. }
  558. // Always print the status code.
  559. if rsp.Code == types.CodeTypeOK {
  560. fmt.Printf("-> code: OK\n")
  561. } else {
  562. fmt.Printf("-> code: %d\n", rsp.Code)
  563. }
  564. if len(rsp.Data) != 0 {
  565. // Do no print this line when using the commit command
  566. // because the string comes out as gibberish
  567. if cmd.Use != "commit" {
  568. fmt.Printf("-> data: %s\n", rsp.Data)
  569. }
  570. fmt.Printf("-> data.hex: 0x%X\n", rsp.Data)
  571. }
  572. if rsp.Log != "" {
  573. fmt.Printf("-> log: %s\n", rsp.Log)
  574. }
  575. if rsp.Query != nil {
  576. fmt.Printf("-> height: %d\n", rsp.Query.Height)
  577. if rsp.Query.Key != nil {
  578. fmt.Printf("-> key: %s\n", rsp.Query.Key)
  579. fmt.Printf("-> key.hex: %X\n", rsp.Query.Key)
  580. }
  581. if rsp.Query.Value != nil {
  582. fmt.Printf("-> value: %s\n", rsp.Query.Value)
  583. fmt.Printf("-> value.hex: %X\n", rsp.Query.Value)
  584. }
  585. if rsp.Query.ProofOps != nil {
  586. fmt.Printf("-> proof: %#v\n", rsp.Query.ProofOps)
  587. }
  588. }
  589. }
  590. // NOTE: s is interpreted as a string unless prefixed with 0x
  591. func stringOrHexToBytes(s string) ([]byte, error) {
  592. if len(s) > 2 && strings.ToLower(s[:2]) == "0x" {
  593. b, err := hex.DecodeString(s[2:])
  594. if err != nil {
  595. err = fmt.Errorf("error decoding hex argument: %s", err.Error())
  596. return nil, err
  597. }
  598. return b, nil
  599. }
  600. if !strings.HasPrefix(s, "\"") || !strings.HasSuffix(s, "\"") {
  601. err := fmt.Errorf("invalid string arg: \"%s\". Must be quoted or a \"0x\"-prefixed hex string", s)
  602. return nil, err
  603. }
  604. return []byte(s[1 : len(s)-1]), nil
  605. }