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.

670 lines
16 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 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: cmdDeliverTx,
  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 { return servertest.DeliverTx(ctx, client, []byte("abc"), code.CodeTypeBadNonce, nil) },
  257. func() error { return servertest.Commit(ctx, client, nil) },
  258. func() error { return servertest.DeliverTx(ctx, client, []byte{0x00}, code.CodeTypeOK, nil) },
  259. func() error { return servertest.Commit(ctx, client, []byte{0, 0, 0, 0, 0, 0, 0, 1}) },
  260. func() error { return servertest.DeliverTx(ctx, client, []byte{0x00}, code.CodeTypeBadNonce, nil) },
  261. func() error { return servertest.DeliverTx(ctx, client, []byte{0x01}, code.CodeTypeOK, nil) },
  262. func() error { return servertest.DeliverTx(ctx, client, []byte{0x00, 0x02}, code.CodeTypeOK, nil) },
  263. func() error { return servertest.DeliverTx(ctx, client, []byte{0x00, 0x03}, code.CodeTypeOK, nil) },
  264. func() error { return servertest.DeliverTx(ctx, client, []byte{0x00, 0x00, 0x04}, code.CodeTypeOK, nil) },
  265. func() error {
  266. return servertest.DeliverTx(ctx, client, []byte{0x00, 0x00, 0x06}, code.CodeTypeBadNonce, nil)
  267. },
  268. func() error { return servertest.Commit(ctx, client, []byte{0, 0, 0, 0, 0, 0, 0, 5}) },
  269. })
  270. }
  271. func cmdBatch(cmd *cobra.Command, args []string) error {
  272. bufReader := bufio.NewReader(os.Stdin)
  273. LOOP:
  274. for {
  275. line, more, err := bufReader.ReadLine()
  276. switch {
  277. case more:
  278. return errors.New("input line is too long")
  279. case err == io.EOF:
  280. break LOOP
  281. case len(line) == 0:
  282. continue
  283. case err != nil:
  284. return err
  285. }
  286. cmdArgs := persistentArgs(line)
  287. if err := muxOnCommands(cmd, cmdArgs); err != nil {
  288. return err
  289. }
  290. fmt.Println()
  291. }
  292. return nil
  293. }
  294. func cmdConsole(cmd *cobra.Command, args []string) error {
  295. for {
  296. fmt.Printf("> ")
  297. bufReader := bufio.NewReader(os.Stdin)
  298. line, more, err := bufReader.ReadLine()
  299. if more {
  300. return errors.New("input is too long")
  301. } else if err != nil {
  302. return err
  303. }
  304. pArgs := persistentArgs(line)
  305. if err := muxOnCommands(cmd, pArgs); err != nil {
  306. return err
  307. }
  308. }
  309. }
  310. func muxOnCommands(cmd *cobra.Command, pArgs []string) error {
  311. if len(pArgs) < 2 {
  312. return errors.New("expecting persistent args of the form: abci-cli [command] <...>")
  313. }
  314. // TODO: this parsing is fragile
  315. args := []string{}
  316. for i := 0; i < len(pArgs); i++ {
  317. arg := pArgs[i]
  318. // check for flags
  319. if strings.HasPrefix(arg, "-") {
  320. // if it has an equal, we can just skip
  321. if strings.Contains(arg, "=") {
  322. continue
  323. }
  324. // if its a boolean, we can just skip
  325. _, err := cmd.Flags().GetBool(strings.TrimLeft(arg, "-"))
  326. if err == nil {
  327. continue
  328. }
  329. // otherwise, we need to skip the next one too
  330. i++
  331. continue
  332. }
  333. // append the actual arg
  334. args = append(args, arg)
  335. }
  336. var subCommand string
  337. var actualArgs []string
  338. if len(args) > 1 {
  339. subCommand = args[1]
  340. }
  341. if len(args) > 2 {
  342. actualArgs = args[2:]
  343. }
  344. cmd.Use = subCommand // for later print statements ...
  345. switch strings.ToLower(subCommand) {
  346. case "check_tx":
  347. return cmdCheckTx(cmd, actualArgs)
  348. case "commit":
  349. return cmdCommit(cmd, actualArgs)
  350. case "deliver_tx":
  351. return cmdDeliverTx(cmd, actualArgs)
  352. case "echo":
  353. return cmdEcho(cmd, actualArgs)
  354. case "info":
  355. return cmdInfo(cmd, actualArgs)
  356. case "query":
  357. return cmdQuery(cmd, actualArgs)
  358. default:
  359. return cmdUnimplemented(cmd, pArgs)
  360. }
  361. }
  362. func cmdUnimplemented(cmd *cobra.Command, args []string) error {
  363. msg := "unimplemented command"
  364. if len(args) > 0 {
  365. msg += fmt.Sprintf(" args: [%s]", strings.Join(args, " "))
  366. }
  367. printResponse(cmd, args, response{
  368. Code: codeBad,
  369. Log: msg,
  370. })
  371. fmt.Println("Available commands:")
  372. for _, cmd := range cmd.Commands() {
  373. fmt.Printf("%s: %s\n", cmd.Use, cmd.Short)
  374. }
  375. fmt.Println("Use \"[command] --help\" for more information about a command.")
  376. return nil
  377. }
  378. // Have the application echo a message
  379. func cmdEcho(cmd *cobra.Command, args []string) error {
  380. msg := ""
  381. if len(args) > 0 {
  382. msg = args[0]
  383. }
  384. res, err := client.Echo(cmd.Context(), msg)
  385. if err != nil {
  386. return err
  387. }
  388. printResponse(cmd, args, response{
  389. Data: []byte(res.Message),
  390. })
  391. return nil
  392. }
  393. // Get some info from the application
  394. func cmdInfo(cmd *cobra.Command, args []string) error {
  395. var version string
  396. if len(args) == 1 {
  397. version = args[0]
  398. }
  399. res, err := client.Info(cmd.Context(), types.RequestInfo{Version: version})
  400. if err != nil {
  401. return err
  402. }
  403. printResponse(cmd, args, response{
  404. Data: []byte(res.Data),
  405. })
  406. return nil
  407. }
  408. const codeBad uint32 = 10
  409. // Append a new tx to application
  410. func cmdDeliverTx(cmd *cobra.Command, args []string) error {
  411. if len(args) == 0 {
  412. printResponse(cmd, args, response{
  413. Code: codeBad,
  414. Log: "want the tx",
  415. })
  416. return nil
  417. }
  418. txBytes, err := stringOrHexToBytes(args[0])
  419. if err != nil {
  420. return err
  421. }
  422. res, err := client.DeliverTx(cmd.Context(), types.RequestDeliverTx{Tx: txBytes})
  423. if err != nil {
  424. return err
  425. }
  426. printResponse(cmd, args, response{
  427. Code: res.Code,
  428. Data: res.Data,
  429. Info: res.Info,
  430. Log: res.Log,
  431. })
  432. return nil
  433. }
  434. // Validate a tx
  435. func cmdCheckTx(cmd *cobra.Command, args []string) error {
  436. if len(args) == 0 {
  437. printResponse(cmd, args, response{
  438. Code: codeBad,
  439. Info: "want the tx",
  440. })
  441. return nil
  442. }
  443. txBytes, err := stringOrHexToBytes(args[0])
  444. if err != nil {
  445. return err
  446. }
  447. res, err := client.CheckTx(cmd.Context(), types.RequestCheckTx{Tx: txBytes})
  448. if err != nil {
  449. return err
  450. }
  451. printResponse(cmd, args, response{
  452. Code: res.Code,
  453. Data: res.Data,
  454. Info: res.Info,
  455. Log: res.Log,
  456. })
  457. return nil
  458. }
  459. // Get application Merkle root hash
  460. func cmdCommit(cmd *cobra.Command, args []string) error {
  461. res, err := client.Commit(cmd.Context())
  462. if err != nil {
  463. return err
  464. }
  465. printResponse(cmd, args, response{
  466. Data: res.Data,
  467. })
  468. return nil
  469. }
  470. // Query application state
  471. func cmdQuery(cmd *cobra.Command, args []string) error {
  472. if len(args) == 0 {
  473. printResponse(cmd, args, response{
  474. Code: codeBad,
  475. Info: "want the query",
  476. Log: "",
  477. })
  478. return nil
  479. }
  480. queryBytes, err := stringOrHexToBytes(args[0])
  481. if err != nil {
  482. return err
  483. }
  484. resQuery, err := client.Query(cmd.Context(), types.RequestQuery{
  485. Data: queryBytes,
  486. Path: flagPath,
  487. Height: int64(flagHeight),
  488. Prove: flagProve,
  489. })
  490. if err != nil {
  491. return err
  492. }
  493. printResponse(cmd, args, response{
  494. Code: resQuery.Code,
  495. Info: resQuery.Info,
  496. Log: resQuery.Log,
  497. Query: &queryResponse{
  498. Key: resQuery.Key,
  499. Value: resQuery.Value,
  500. Height: resQuery.Height,
  501. ProofOps: resQuery.ProofOps,
  502. },
  503. })
  504. return nil
  505. }
  506. func makeKVStoreCmd(logger log.Logger) func(*cobra.Command, []string) error {
  507. return func(cmd *cobra.Command, args []string) error {
  508. // Create the application - in memory or persisted to disk
  509. var app types.Application
  510. if flagPersist == "" {
  511. app = kvstore.NewApplication()
  512. } else {
  513. app = kvstore.NewPersistentKVStoreApplication(logger, flagPersist)
  514. }
  515. // Start the listener
  516. srv, err := server.NewServer(logger.With("module", "abci-server"), flagAddress, flagAbci, app)
  517. if err != nil {
  518. return err
  519. }
  520. ctx, cancel := signal.NotifyContext(cmd.Context(), syscall.SIGTERM)
  521. defer cancel()
  522. if err := srv.Start(ctx); err != nil {
  523. return err
  524. }
  525. // Run forever.
  526. <-ctx.Done()
  527. return nil
  528. }
  529. }
  530. //--------------------------------------------------------------------------------
  531. func printResponse(cmd *cobra.Command, args []string, rsp response) {
  532. if flagVerbose {
  533. fmt.Println(">", cmd.Use, strings.Join(args, " "))
  534. }
  535. // Always print the status code.
  536. if rsp.Code == types.CodeTypeOK {
  537. fmt.Printf("-> code: OK\n")
  538. } else {
  539. fmt.Printf("-> code: %d\n", rsp.Code)
  540. }
  541. if len(rsp.Data) != 0 {
  542. // Do no print this line when using the commit command
  543. // because the string comes out as gibberish
  544. if cmd.Use != "commit" {
  545. fmt.Printf("-> data: %s\n", rsp.Data)
  546. }
  547. fmt.Printf("-> data.hex: 0x%X\n", rsp.Data)
  548. }
  549. if rsp.Log != "" {
  550. fmt.Printf("-> log: %s\n", rsp.Log)
  551. }
  552. if rsp.Query != nil {
  553. fmt.Printf("-> height: %d\n", rsp.Query.Height)
  554. if rsp.Query.Key != nil {
  555. fmt.Printf("-> key: %s\n", rsp.Query.Key)
  556. fmt.Printf("-> key.hex: %X\n", rsp.Query.Key)
  557. }
  558. if rsp.Query.Value != nil {
  559. fmt.Printf("-> value: %s\n", rsp.Query.Value)
  560. fmt.Printf("-> value.hex: %X\n", rsp.Query.Value)
  561. }
  562. if rsp.Query.ProofOps != nil {
  563. fmt.Printf("-> proof: %#v\n", rsp.Query.ProofOps)
  564. }
  565. }
  566. }
  567. // NOTE: s is interpreted as a string unless prefixed with 0x
  568. func stringOrHexToBytes(s string) ([]byte, error) {
  569. if len(s) > 2 && strings.ToLower(s[:2]) == "0x" {
  570. b, err := hex.DecodeString(s[2:])
  571. if err != nil {
  572. err = fmt.Errorf("error decoding hex argument: %s", err.Error())
  573. return nil, err
  574. }
  575. return b, nil
  576. }
  577. if !strings.HasPrefix(s, "\"") || !strings.HasSuffix(s, "\"") {
  578. err := fmt.Errorf("invalid string arg: \"%s\". Must be quoted or a \"0x\"-prefixed hex string", s)
  579. return nil, err
  580. }
  581. return []byte(s[1 : len(s)-1]), nil
  582. }