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.

420 lines
12 KiB

  1. // nolint: gosec
  2. package main
  3. import (
  4. "bytes"
  5. "encoding/base64"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io/ioutil"
  10. "os"
  11. "path/filepath"
  12. "regexp"
  13. "sort"
  14. "strconv"
  15. "strings"
  16. "text/template"
  17. "time"
  18. "github.com/BurntSushi/toml"
  19. "github.com/tendermint/tendermint/config"
  20. "github.com/tendermint/tendermint/crypto/ed25519"
  21. "github.com/tendermint/tendermint/p2p"
  22. "github.com/tendermint/tendermint/privval"
  23. e2e "github.com/tendermint/tendermint/test/e2e/pkg"
  24. "github.com/tendermint/tendermint/types"
  25. )
  26. const (
  27. AppAddressTCP = "tcp://127.0.0.1:30000"
  28. AppAddressUNIX = "unix:///var/run/app.sock"
  29. PrivvalAddressTCP = "tcp://0.0.0.0:27559"
  30. PrivvalAddressGRPC = "grpc://0.0.0.0:27559"
  31. PrivvalAddressUNIX = "unix:///var/run/privval.sock"
  32. PrivvalKeyFile = "config/priv_validator_key.json"
  33. PrivvalStateFile = "data/priv_validator_state.json"
  34. PrivvalDummyKeyFile = "config/dummy_validator_key.json"
  35. PrivvalDummyStateFile = "data/dummy_validator_state.json"
  36. )
  37. // Setup sets up the testnet configuration.
  38. func Setup(testnet *e2e.Testnet) error {
  39. logger.Info(fmt.Sprintf("Generating testnet files in %q", testnet.Dir))
  40. err := os.MkdirAll(testnet.Dir, os.ModePerm)
  41. if err != nil {
  42. return err
  43. }
  44. compose, err := MakeDockerCompose(testnet)
  45. if err != nil {
  46. return err
  47. }
  48. err = ioutil.WriteFile(filepath.Join(testnet.Dir, "docker-compose.yml"), compose, 0644)
  49. if err != nil {
  50. return err
  51. }
  52. genesis, err := MakeGenesis(testnet)
  53. if err != nil {
  54. return err
  55. }
  56. for _, node := range testnet.Nodes {
  57. nodeDir := filepath.Join(testnet.Dir, node.Name)
  58. dirs := []string{
  59. filepath.Join(nodeDir, "config"),
  60. filepath.Join(nodeDir, "data"),
  61. filepath.Join(nodeDir, "data", "app"),
  62. }
  63. for _, dir := range dirs {
  64. err := os.MkdirAll(dir, 0755)
  65. if err != nil {
  66. return err
  67. }
  68. }
  69. err = genesis.SaveAs(filepath.Join(nodeDir, "config", "genesis.json"))
  70. if err != nil {
  71. return err
  72. }
  73. cfg, err := MakeConfig(node)
  74. if err != nil {
  75. return err
  76. }
  77. config.WriteConfigFile(filepath.Join(nodeDir, "config", "config.toml"), cfg) // panics
  78. appCfg, err := MakeAppConfig(node)
  79. if err != nil {
  80. return err
  81. }
  82. err = ioutil.WriteFile(filepath.Join(nodeDir, "config", "app.toml"), appCfg, 0644)
  83. if err != nil {
  84. return err
  85. }
  86. err = (&p2p.NodeKey{PrivKey: node.NodeKey}).SaveAs(filepath.Join(nodeDir, "config", "node_key.json"))
  87. if err != nil {
  88. return err
  89. }
  90. (privval.NewFilePV(node.PrivvalKey,
  91. filepath.Join(nodeDir, PrivvalKeyFile),
  92. filepath.Join(nodeDir, PrivvalStateFile),
  93. )).Save()
  94. // Set up a dummy validator. Tendermint requires a file PV even when not used, so we
  95. // give it a dummy such that it will fail if it actually tries to use it.
  96. (privval.NewFilePV(ed25519.GenPrivKey(),
  97. filepath.Join(nodeDir, PrivvalDummyKeyFile),
  98. filepath.Join(nodeDir, PrivvalDummyStateFile),
  99. )).Save()
  100. }
  101. return nil
  102. }
  103. // MakeDockerCompose generates a Docker Compose config for a testnet.
  104. func MakeDockerCompose(testnet *e2e.Testnet) ([]byte, error) {
  105. // Must use version 2 Docker Compose format, to support IPv6.
  106. tmpl, err := template.New("docker-compose").Funcs(template.FuncMap{
  107. "startCommands": func(misbehaviors map[int64]string, logLevel string) string {
  108. command := "start"
  109. // FIXME: Temporarily disable behaviors until maverick is redesigned
  110. // misbehaviorString := ""
  111. // for height, misbehavior := range misbehaviors {
  112. // // after the first behavior set, a comma must be prepended
  113. // if misbehaviorString != "" {
  114. // misbehaviorString += ","
  115. // }
  116. // heightString := strconv.Itoa(int(height))
  117. // misbehaviorString += misbehavior + "," + heightString
  118. // }
  119. // if misbehaviorString != "" {
  120. // command += " --misbehaviors " + misbehaviorString
  121. // }
  122. if logLevel != "" && logLevel != config.DefaultLogLevel {
  123. command += " --log-level " + logLevel
  124. }
  125. return command
  126. },
  127. }).Parse(`version: '2.4'
  128. networks:
  129. {{ .Name }}:
  130. labels:
  131. e2e: true
  132. driver: bridge
  133. {{- if .IPv6 }}
  134. enable_ipv6: true
  135. {{- end }}
  136. ipam:
  137. driver: default
  138. config:
  139. - subnet: {{ .IP }}
  140. services:
  141. {{- range .Nodes }}
  142. {{ .Name }}:
  143. labels:
  144. e2e: true
  145. container_name: {{ .Name }}
  146. image: tendermint/e2e-node
  147. {{- if eq .ABCIProtocol "builtin" }}
  148. entrypoint: /usr/bin/entrypoint-builtin
  149. {{- end }}
  150. {{- if ne .ABCIProtocol "builtin"}}
  151. command: {{ startCommands .Misbehaviors .LogLevel }}
  152. {{- end }}
  153. init: true
  154. ports:
  155. - 26656
  156. - {{ if .ProxyPort }}{{ .ProxyPort }}:{{ end }}26657
  157. - 6060
  158. volumes:
  159. - ./{{ .Name }}:/tendermint
  160. networks:
  161. {{ $.Name }}:
  162. ipv{{ if $.IPv6 }}6{{ else }}4{{ end}}_address: {{ .IP }}
  163. {{end}}`)
  164. if err != nil {
  165. return nil, err
  166. }
  167. var buf bytes.Buffer
  168. err = tmpl.Execute(&buf, testnet)
  169. if err != nil {
  170. return nil, err
  171. }
  172. return buf.Bytes(), nil
  173. }
  174. // MakeGenesis generates a genesis document.
  175. func MakeGenesis(testnet *e2e.Testnet) (types.GenesisDoc, error) {
  176. genesis := types.GenesisDoc{
  177. GenesisTime: time.Now(),
  178. ChainID: testnet.Name,
  179. ConsensusParams: types.DefaultConsensusParams(),
  180. InitialHeight: testnet.InitialHeight,
  181. }
  182. switch testnet.KeyType {
  183. case "", types.ABCIPubKeyTypeEd25519, types.ABCIPubKeyTypeSecp256k1:
  184. genesis.ConsensusParams.Validator.PubKeyTypes =
  185. append(genesis.ConsensusParams.Validator.PubKeyTypes, types.ABCIPubKeyTypeSecp256k1)
  186. default:
  187. return genesis, errors.New("unsupported KeyType")
  188. }
  189. for validator, power := range testnet.Validators {
  190. genesis.Validators = append(genesis.Validators, types.GenesisValidator{
  191. Name: validator.Name,
  192. Address: validator.PrivvalKey.PubKey().Address(),
  193. PubKey: validator.PrivvalKey.PubKey(),
  194. Power: power,
  195. })
  196. }
  197. // The validator set will be sorted internally by Tendermint ranked by power,
  198. // but we sort it here as well so that all genesis files are identical.
  199. sort.Slice(genesis.Validators, func(i, j int) bool {
  200. return strings.Compare(genesis.Validators[i].Name, genesis.Validators[j].Name) == -1
  201. })
  202. if len(testnet.InitialState) > 0 {
  203. appState, err := json.Marshal(testnet.InitialState)
  204. if err != nil {
  205. return genesis, err
  206. }
  207. genesis.AppState = appState
  208. }
  209. return genesis, genesis.ValidateAndComplete()
  210. }
  211. // MakeConfig generates a Tendermint config for a node.
  212. func MakeConfig(node *e2e.Node) (*config.Config, error) {
  213. cfg := config.DefaultConfig()
  214. cfg.Moniker = node.Name
  215. cfg.ProxyApp = AppAddressTCP
  216. if node.LogLevel != "" {
  217. cfg.LogLevel = node.LogLevel
  218. }
  219. cfg.RPC.ListenAddress = "tcp://0.0.0.0:26657"
  220. cfg.RPC.PprofListenAddress = ":6060"
  221. cfg.P2P.ExternalAddress = fmt.Sprintf("tcp://%v", node.AddressP2P(false))
  222. cfg.P2P.AddrBookStrict = false
  223. cfg.DBBackend = node.Database
  224. cfg.StateSync.DiscoveryTime = 5 * time.Second
  225. switch node.ABCIProtocol {
  226. case e2e.ProtocolUNIX:
  227. cfg.ProxyApp = AppAddressUNIX
  228. case e2e.ProtocolTCP:
  229. cfg.ProxyApp = AppAddressTCP
  230. case e2e.ProtocolGRPC:
  231. cfg.ProxyApp = AppAddressTCP
  232. cfg.ABCI = "grpc"
  233. case e2e.ProtocolBuiltin:
  234. cfg.ProxyApp = ""
  235. cfg.ABCI = ""
  236. default:
  237. return nil, fmt.Errorf("unexpected ABCI protocol setting %q", node.ABCIProtocol)
  238. }
  239. // Tendermint errors if it does not have a privval key set up, regardless of whether
  240. // it's actually needed (e.g. for remote KMS or non-validators). We set up a dummy
  241. // key here by default, and use the real key for actual validators that should use
  242. // the file privval.
  243. cfg.PrivValidatorListenAddr = ""
  244. cfg.PrivValidatorKey = PrivvalDummyKeyFile
  245. cfg.PrivValidatorState = PrivvalDummyStateFile
  246. switch node.Mode {
  247. case e2e.ModeValidator:
  248. switch node.PrivvalProtocol {
  249. case e2e.ProtocolFile:
  250. cfg.PrivValidatorKey = PrivvalKeyFile
  251. cfg.PrivValidatorState = PrivvalStateFile
  252. case e2e.ProtocolUNIX:
  253. cfg.PrivValidatorListenAddr = PrivvalAddressUNIX
  254. case e2e.ProtocolTCP:
  255. cfg.PrivValidatorListenAddr = PrivvalAddressTCP
  256. case e2e.ProtocolGRPC:
  257. cfg.PrivValidatorListenAddr = PrivvalAddressGRPC
  258. default:
  259. return nil, fmt.Errorf("invalid privval protocol setting %q", node.PrivvalProtocol)
  260. }
  261. case e2e.ModeSeed:
  262. cfg.P2P.SeedMode = true
  263. cfg.P2P.PexReactor = true
  264. case e2e.ModeFull:
  265. // Don't need to do anything, since we're using a dummy privval key by default.
  266. default:
  267. return nil, fmt.Errorf("unexpected mode %q", node.Mode)
  268. }
  269. if node.FastSync == "" {
  270. cfg.FastSyncMode = false
  271. } else {
  272. cfg.FastSync.Version = node.FastSync
  273. }
  274. if node.StateSync {
  275. cfg.StateSync.Enable = true
  276. cfg.StateSync.RPCServers = []string{}
  277. for _, peer := range node.Testnet.ArchiveNodes() {
  278. if peer.Name == node.Name {
  279. continue
  280. }
  281. cfg.StateSync.RPCServers = append(cfg.StateSync.RPCServers, peer.AddressRPC())
  282. }
  283. if len(cfg.StateSync.RPCServers) < 2 {
  284. return nil, errors.New("unable to find 2 suitable state sync RPC servers")
  285. }
  286. }
  287. cfg.P2P.Seeds = ""
  288. for _, seed := range node.Seeds {
  289. if len(cfg.P2P.Seeds) > 0 {
  290. cfg.P2P.Seeds += ","
  291. }
  292. cfg.P2P.Seeds += seed.AddressP2P(true)
  293. }
  294. cfg.P2P.PersistentPeers = ""
  295. for _, peer := range node.PersistentPeers {
  296. if len(cfg.P2P.PersistentPeers) > 0 {
  297. cfg.P2P.PersistentPeers += ","
  298. }
  299. cfg.P2P.PersistentPeers += peer.AddressP2P(true)
  300. }
  301. return cfg, nil
  302. }
  303. // MakeAppConfig generates an ABCI application config for a node.
  304. func MakeAppConfig(node *e2e.Node) ([]byte, error) {
  305. cfg := map[string]interface{}{
  306. "chain_id": node.Testnet.Name,
  307. "dir": "data/app",
  308. "listen": AppAddressUNIX,
  309. "protocol": "socket",
  310. "persist_interval": node.PersistInterval,
  311. "snapshot_interval": node.SnapshotInterval,
  312. "retain_blocks": node.RetainBlocks,
  313. "key_type": node.PrivvalKey.Type(),
  314. }
  315. switch node.ABCIProtocol {
  316. case e2e.ProtocolUNIX:
  317. cfg["listen"] = AppAddressUNIX
  318. case e2e.ProtocolTCP:
  319. cfg["listen"] = AppAddressTCP
  320. case e2e.ProtocolGRPC:
  321. cfg["listen"] = AppAddressTCP
  322. cfg["protocol"] = "grpc"
  323. case e2e.ProtocolBuiltin:
  324. delete(cfg, "listen")
  325. cfg["protocol"] = "builtin"
  326. default:
  327. return nil, fmt.Errorf("unexpected ABCI protocol setting %q", node.ABCIProtocol)
  328. }
  329. if node.Mode == e2e.ModeValidator {
  330. switch node.PrivvalProtocol {
  331. case e2e.ProtocolFile:
  332. case e2e.ProtocolTCP:
  333. cfg["privval_server"] = PrivvalAddressTCP
  334. cfg["privval_key"] = PrivvalKeyFile
  335. cfg["privval_state"] = PrivvalStateFile
  336. case e2e.ProtocolUNIX:
  337. cfg["privval_server"] = PrivvalAddressUNIX
  338. cfg["privval_key"] = PrivvalKeyFile
  339. cfg["privval_state"] = PrivvalStateFile
  340. case e2e.ProtocolGRPC:
  341. cfg["privval_server"] = PrivvalAddressGRPC
  342. cfg["privval_key"] = PrivvalKeyFile
  343. cfg["privval_state"] = PrivvalStateFile
  344. default:
  345. return nil, fmt.Errorf("unexpected privval protocol setting %q", node.PrivvalProtocol)
  346. }
  347. }
  348. misbehaviors := make(map[string]string)
  349. for height, misbehavior := range node.Misbehaviors {
  350. misbehaviors[strconv.Itoa(int(height))] = misbehavior
  351. }
  352. cfg["misbehaviors"] = misbehaviors
  353. if len(node.Testnet.ValidatorUpdates) > 0 {
  354. validatorUpdates := map[string]map[string]int64{}
  355. for height, validators := range node.Testnet.ValidatorUpdates {
  356. updateVals := map[string]int64{}
  357. for node, power := range validators {
  358. updateVals[base64.StdEncoding.EncodeToString(node.PrivvalKey.PubKey().Bytes())] = power
  359. }
  360. validatorUpdates[fmt.Sprintf("%v", height)] = updateVals
  361. }
  362. cfg["validator_update"] = validatorUpdates
  363. }
  364. var buf bytes.Buffer
  365. err := toml.NewEncoder(&buf).Encode(cfg)
  366. if err != nil {
  367. return nil, fmt.Errorf("failed to generate app config: %w", err)
  368. }
  369. return buf.Bytes(), nil
  370. }
  371. // UpdateConfigStateSync updates the state sync config for a node.
  372. func UpdateConfigStateSync(node *e2e.Node, height int64, hash []byte) error {
  373. cfgPath := filepath.Join(node.Testnet.Dir, node.Name, "config", "config.toml")
  374. // FIXME Apparently there's no function to simply load a config file without
  375. // involving the entire Viper apparatus, so we'll just resort to regexps.
  376. bz, err := ioutil.ReadFile(cfgPath)
  377. if err != nil {
  378. return err
  379. }
  380. bz = regexp.MustCompile(`(?m)^trust-height =.*`).ReplaceAll(bz, []byte(fmt.Sprintf(`trust-height = %v`, height)))
  381. bz = regexp.MustCompile(`(?m)^trust-hash =.*`).ReplaceAll(bz, []byte(fmt.Sprintf(`trust-hash = "%X"`, hash)))
  382. return ioutil.WriteFile(cfgPath, bz, 0644)
  383. }