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.

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