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.

421 lines
12 KiB

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