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.

433 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. if node.Mode != e2e.ModeLight {
  233. cfg.Mode = string(node.Mode)
  234. }
  235. switch node.ABCIProtocol {
  236. case e2e.ProtocolUNIX:
  237. cfg.ProxyApp = AppAddressUNIX
  238. case e2e.ProtocolTCP:
  239. cfg.ProxyApp = AppAddressTCP
  240. case e2e.ProtocolGRPC:
  241. cfg.ProxyApp = AppAddressTCP
  242. cfg.ABCI = "grpc"
  243. case e2e.ProtocolBuiltin:
  244. cfg.ProxyApp = ""
  245. cfg.ABCI = ""
  246. default:
  247. return nil, fmt.Errorf("unexpected ABCI protocol setting %q", node.ABCIProtocol)
  248. }
  249. // Tendermint errors if it does not have a privval key set up, regardless of whether
  250. // it's actually needed (e.g. for remote KMS or non-validators). We set up a dummy
  251. // key here by default, and use the real key for actual validators that should use
  252. // the file privval.
  253. cfg.PrivValidatorListenAddr = ""
  254. cfg.PrivValidatorKey = PrivvalDummyKeyFile
  255. cfg.PrivValidatorState = PrivvalDummyStateFile
  256. switch node.Mode {
  257. case e2e.ModeValidator:
  258. switch node.PrivvalProtocol {
  259. case e2e.ProtocolFile:
  260. cfg.PrivValidatorKey = PrivvalKeyFile
  261. cfg.PrivValidatorState = PrivvalStateFile
  262. case e2e.ProtocolUNIX:
  263. cfg.PrivValidatorListenAddr = PrivvalAddressUNIX
  264. case e2e.ProtocolTCP:
  265. cfg.PrivValidatorListenAddr = PrivvalAddressTCP
  266. case e2e.ProtocolGRPC:
  267. cfg.PrivValidatorListenAddr = PrivvalAddressGRPC
  268. default:
  269. return nil, fmt.Errorf("invalid privval protocol setting %q", node.PrivvalProtocol)
  270. }
  271. case e2e.ModeSeed:
  272. cfg.P2P.PexReactor = true
  273. case e2e.ModeFull, e2e.ModeLight:
  274. // Don't need to do anything, since we're using a dummy privval key by default.
  275. default:
  276. return nil, fmt.Errorf("unexpected mode %q", node.Mode)
  277. }
  278. if node.FastSync == "" {
  279. cfg.FastSyncMode = false
  280. } else {
  281. cfg.FastSync.Version = node.FastSync
  282. }
  283. if node.StateSync {
  284. cfg.StateSync.Enable = true
  285. cfg.StateSync.RPCServers = []string{}
  286. for _, peer := range node.Testnet.ArchiveNodes() {
  287. if peer.Name == node.Name {
  288. continue
  289. }
  290. cfg.StateSync.RPCServers = append(cfg.StateSync.RPCServers, peer.AddressRPC())
  291. }
  292. if len(cfg.StateSync.RPCServers) < 2 {
  293. return nil, errors.New("unable to find 2 suitable state sync RPC servers")
  294. }
  295. }
  296. cfg.P2P.Seeds = ""
  297. for _, seed := range node.Seeds {
  298. if len(cfg.P2P.Seeds) > 0 {
  299. cfg.P2P.Seeds += ","
  300. }
  301. cfg.P2P.Seeds += seed.AddressP2P(true)
  302. }
  303. cfg.P2P.PersistentPeers = ""
  304. for _, peer := range node.PersistentPeers {
  305. if len(cfg.P2P.PersistentPeers) > 0 {
  306. cfg.P2P.PersistentPeers += ","
  307. }
  308. cfg.P2P.PersistentPeers += peer.AddressP2P(true)
  309. }
  310. return cfg, nil
  311. }
  312. // MakeAppConfig generates an ABCI application config for a node.
  313. func MakeAppConfig(node *e2e.Node) ([]byte, error) {
  314. cfg := map[string]interface{}{
  315. "chain_id": node.Testnet.Name,
  316. "dir": "data/app",
  317. "listen": AppAddressUNIX,
  318. "mode": node.Mode,
  319. "proxy_port": node.ProxyPort,
  320. "protocol": "socket",
  321. "persist_interval": node.PersistInterval,
  322. "snapshot_interval": node.SnapshotInterval,
  323. "retain_blocks": node.RetainBlocks,
  324. "key_type": node.PrivvalKey.Type(),
  325. }
  326. switch node.ABCIProtocol {
  327. case e2e.ProtocolUNIX:
  328. cfg["listen"] = AppAddressUNIX
  329. case e2e.ProtocolTCP:
  330. cfg["listen"] = AppAddressTCP
  331. case e2e.ProtocolGRPC:
  332. cfg["listen"] = AppAddressTCP
  333. cfg["protocol"] = "grpc"
  334. case e2e.ProtocolBuiltin:
  335. delete(cfg, "listen")
  336. cfg["protocol"] = "builtin"
  337. default:
  338. return nil, fmt.Errorf("unexpected ABCI protocol setting %q", node.ABCIProtocol)
  339. }
  340. if node.Mode == e2e.ModeValidator {
  341. switch node.PrivvalProtocol {
  342. case e2e.ProtocolFile:
  343. case e2e.ProtocolTCP:
  344. cfg["privval_server"] = PrivvalAddressTCP
  345. cfg["privval_key"] = PrivvalKeyFile
  346. cfg["privval_state"] = PrivvalStateFile
  347. case e2e.ProtocolUNIX:
  348. cfg["privval_server"] = PrivvalAddressUNIX
  349. cfg["privval_key"] = PrivvalKeyFile
  350. cfg["privval_state"] = PrivvalStateFile
  351. case e2e.ProtocolGRPC:
  352. cfg["privval_server"] = PrivvalAddressGRPC
  353. cfg["privval_key"] = PrivvalKeyFile
  354. cfg["privval_state"] = PrivvalStateFile
  355. default:
  356. return nil, fmt.Errorf("unexpected privval protocol setting %q", node.PrivvalProtocol)
  357. }
  358. }
  359. misbehaviors := make(map[string]string)
  360. for height, misbehavior := range node.Misbehaviors {
  361. misbehaviors[strconv.Itoa(int(height))] = misbehavior
  362. }
  363. cfg["misbehaviors"] = misbehaviors
  364. if len(node.Testnet.ValidatorUpdates) > 0 {
  365. validatorUpdates := map[string]map[string]int64{}
  366. for height, validators := range node.Testnet.ValidatorUpdates {
  367. updateVals := map[string]int64{}
  368. for node, power := range validators {
  369. updateVals[base64.StdEncoding.EncodeToString(node.PrivvalKey.PubKey().Bytes())] = power
  370. }
  371. validatorUpdates[fmt.Sprintf("%v", height)] = updateVals
  372. }
  373. cfg["validator_update"] = validatorUpdates
  374. }
  375. var buf bytes.Buffer
  376. err := toml.NewEncoder(&buf).Encode(cfg)
  377. if err != nil {
  378. return nil, fmt.Errorf("failed to generate app config: %w", err)
  379. }
  380. return buf.Bytes(), nil
  381. }
  382. // UpdateConfigStateSync updates the state sync config for a node.
  383. func UpdateConfigStateSync(node *e2e.Node, height int64, hash []byte) error {
  384. cfgPath := filepath.Join(node.Testnet.Dir, node.Name, "config", "config.toml")
  385. // FIXME Apparently there's no function to simply load a config file without
  386. // involving the entire Viper apparatus, so we'll just resort to regexps.
  387. bz, err := ioutil.ReadFile(cfgPath)
  388. if err != nil {
  389. return err
  390. }
  391. bz = regexp.MustCompile(`(?m)^trust-height =.*`).ReplaceAll(bz, []byte(fmt.Sprintf(`trust-height = %v`, height)))
  392. bz = regexp.MustCompile(`(?m)^trust-hash =.*`).ReplaceAll(bz, []byte(fmt.Sprintf(`trust-hash = "%X"`, hash)))
  393. return ioutil.WriteFile(cfgPath, bz, 0644)
  394. }