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.

251 lines
6.7 KiB

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "github.com/spf13/cobra"
  7. "github.com/spf13/viper"
  8. cmd "github.com/tendermint/tendermint/cmd/tendermint/commands"
  9. "github.com/tendermint/tendermint/cmd/tendermint/commands/debug"
  10. cfg "github.com/tendermint/tendermint/config"
  11. "github.com/tendermint/tendermint/libs/cli"
  12. tmflags "github.com/tendermint/tendermint/libs/cli/flags"
  13. "github.com/tendermint/tendermint/libs/log"
  14. tmos "github.com/tendermint/tendermint/libs/os"
  15. tmrand "github.com/tendermint/tendermint/libs/rand"
  16. "github.com/tendermint/tendermint/p2p"
  17. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  18. cs "github.com/tendermint/tendermint/test/maverick/consensus"
  19. nd "github.com/tendermint/tendermint/test/maverick/node"
  20. "github.com/tendermint/tendermint/types"
  21. tmtime "github.com/tendermint/tendermint/types/time"
  22. )
  23. var (
  24. config = cfg.DefaultConfig()
  25. logger = log.NewTMLogger(log.NewSyncWriter(os.Stdout))
  26. misbehaviorFlag = ""
  27. )
  28. func init() {
  29. registerFlagsRootCmd(RootCmd)
  30. }
  31. func registerFlagsRootCmd(command *cobra.Command) {
  32. command.PersistentFlags().String("log-level", config.LogLevel, "Log level")
  33. }
  34. func ParseConfig() (*cfg.Config, error) {
  35. conf := cfg.DefaultConfig()
  36. err := viper.Unmarshal(conf)
  37. if err != nil {
  38. return nil, err
  39. }
  40. conf.SetRoot(conf.RootDir)
  41. cfg.EnsureRoot(conf.RootDir)
  42. if err = conf.ValidateBasic(); err != nil {
  43. return nil, fmt.Errorf("error in config file: %v", err)
  44. }
  45. return conf, err
  46. }
  47. // RootCmd is the root command for Tendermint core.
  48. var RootCmd = &cobra.Command{
  49. Use: "maverick",
  50. Short: "Tendermint Maverick Node",
  51. Long: "Tendermint Maverick Node for testing with faulty consensus misbehaviors in a testnet. Contains " +
  52. "all the functionality of a normal node but custom misbehaviors can be injected when running the node " +
  53. "through a flag. See maverick node --help for how the misbehavior flag is constructured",
  54. PersistentPreRunE: func(cmd *cobra.Command, args []string) (err error) {
  55. fmt.Printf("use: %v, args: %v", cmd.Use, cmd.Args)
  56. config, err = ParseConfig()
  57. if err != nil {
  58. return err
  59. }
  60. if config.LogFormat == cfg.LogFormatJSON {
  61. logger = log.NewTMJSONLogger(log.NewSyncWriter(os.Stdout))
  62. }
  63. logger, err = tmflags.ParseLogLevel(config.LogLevel, logger, cfg.DefaultLogLevel())
  64. if err != nil {
  65. return err
  66. }
  67. if viper.GetBool(cli.TraceFlag) {
  68. logger = log.NewTracingLogger(logger)
  69. }
  70. logger = logger.With("module", "main")
  71. return nil
  72. },
  73. }
  74. func main() {
  75. rootCmd := RootCmd
  76. rootCmd.AddCommand(
  77. ListMisbehaviorCmd,
  78. cmd.GenValidatorCmd,
  79. InitFilesCmd,
  80. cmd.ProbeUpnpCmd,
  81. cmd.ReplayCmd,
  82. cmd.ReplayConsoleCmd,
  83. cmd.ResetAllCmd,
  84. cmd.ResetPrivValidatorCmd,
  85. cmd.ShowValidatorCmd,
  86. cmd.ShowNodeIDCmd,
  87. cmd.GenNodeKeyCmd,
  88. cmd.VersionCmd,
  89. debug.DebugCmd,
  90. cli.NewCompletionCmd(rootCmd, true),
  91. )
  92. nodeCmd := &cobra.Command{
  93. Use: "start",
  94. Aliases: []string{"node", "run"},
  95. Short: "Run the maverick node",
  96. RunE: func(command *cobra.Command, args []string) error {
  97. return startNode(config, logger, misbehaviorFlag)
  98. },
  99. }
  100. cmd.AddNodeFlags(nodeCmd)
  101. // Create & start node
  102. rootCmd.AddCommand(nodeCmd)
  103. // add special flag for misbehaviors
  104. nodeCmd.Flags().StringVar(
  105. &misbehaviorFlag,
  106. "misbehaviors",
  107. "",
  108. "Select the misbehaviors of the node (comma-separated, no spaces in between): \n"+
  109. "e.g. --misbehaviors double-prevote,3\n"+
  110. "You can also have multiple misbehaviors: e.g. double-prevote,3,no-vote,5")
  111. cmd := cli.PrepareBaseCmd(rootCmd, "TM", os.ExpandEnv(filepath.Join("$HOME", cfg.DefaultTendermintDir)))
  112. if err := cmd.Execute(); err != nil {
  113. panic(err)
  114. }
  115. }
  116. func startNode(config *cfg.Config, logger log.Logger, misbehaviorFlag string) error {
  117. misbehaviors, err := nd.ParseMisbehaviors(misbehaviorFlag)
  118. if err != nil {
  119. return err
  120. }
  121. node, err := nd.DefaultNewNode(config, logger, misbehaviors)
  122. if err != nil {
  123. return fmt.Errorf("failed to create node: %w", err)
  124. }
  125. if err := node.Start(); err != nil {
  126. return fmt.Errorf("failed to start node: %w", err)
  127. }
  128. logger.Info("Started node", "nodeInfo", node.Switch().NodeInfo())
  129. // Stop upon receiving SIGTERM or CTRL-C.
  130. tmos.TrapSignal(logger, func() {
  131. if node.IsRunning() {
  132. if err := node.Stop(); err != nil {
  133. logger.Error("unable to stop the node", "error", err)
  134. }
  135. }
  136. })
  137. // Run forever.
  138. select {}
  139. }
  140. var keyType string
  141. var InitFilesCmd = &cobra.Command{
  142. Use: "init",
  143. Short: "Initialize Tendermint",
  144. RunE: initFiles,
  145. }
  146. func init() {
  147. InitFilesCmd.Flags().StringVar(&keyType, "key", types.ABCIPubKeyTypeEd25519,
  148. "Key type to generate privval file with. Options: ed25519, secp256k1")
  149. }
  150. func initFiles(cmd *cobra.Command, args []string) error {
  151. return initFilesWithConfig(config)
  152. }
  153. func initFilesWithConfig(config *cfg.Config) error {
  154. // private validator
  155. privValKeyFile := config.PrivValidatorKeyFile()
  156. privValStateFile := config.PrivValidatorStateFile()
  157. var pv *nd.FilePV
  158. if tmos.FileExists(privValKeyFile) {
  159. pv = nd.LoadFilePV(privValKeyFile, privValStateFile)
  160. logger.Info("Found private validator", "keyFile", privValKeyFile,
  161. "stateFile", privValStateFile)
  162. } else {
  163. pv = nd.GenFilePV(privValKeyFile, privValStateFile)
  164. pv.Save()
  165. logger.Info("Generated private validator", "keyFile", privValKeyFile,
  166. "stateFile", privValStateFile)
  167. }
  168. nodeKeyFile := config.NodeKeyFile()
  169. if tmos.FileExists(nodeKeyFile) {
  170. logger.Info("Found node key", "path", nodeKeyFile)
  171. } else {
  172. if _, err := p2p.LoadOrGenNodeKey(nodeKeyFile); err != nil {
  173. return err
  174. }
  175. logger.Info("Generated node key", "path", nodeKeyFile)
  176. }
  177. // genesis file
  178. genFile := config.GenesisFile()
  179. if tmos.FileExists(genFile) {
  180. logger.Info("Found genesis file", "path", genFile)
  181. } else {
  182. genDoc := types.GenesisDoc{
  183. ChainID: fmt.Sprintf("test-chain-%v", tmrand.Str(6)),
  184. GenesisTime: tmtime.Now(),
  185. ConsensusParams: types.DefaultConsensusParams(),
  186. }
  187. if keyType == "secp256k1" {
  188. genDoc.ConsensusParams.Validator = tmproto.ValidatorParams{
  189. PubKeyTypes: []string{types.ABCIPubKeyTypeSecp256k1},
  190. }
  191. }
  192. pubKey, err := pv.GetPubKey()
  193. if err != nil {
  194. return fmt.Errorf("can't get pubkey: %w", err)
  195. }
  196. genDoc.Validators = []types.GenesisValidator{{
  197. Address: pubKey.Address(),
  198. PubKey: pubKey,
  199. Power: 10,
  200. }}
  201. if err := genDoc.SaveAs(genFile); err != nil {
  202. return err
  203. }
  204. logger.Info("Generated genesis file", "path", genFile)
  205. }
  206. return nil
  207. }
  208. var ListMisbehaviorCmd = &cobra.Command{
  209. Use: "misbehaviors",
  210. Short: "Lists possible misbehaviors",
  211. RunE: listMisbehaviors,
  212. }
  213. func listMisbehaviors(cmd *cobra.Command, args []string) error {
  214. str := "Currently registered misbehaviors: \n"
  215. for key := range cs.MisbehaviorList {
  216. str += fmt.Sprintf("- %s\n", key)
  217. }
  218. fmt.Println(str)
  219. return nil
  220. }