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.

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