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.

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