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