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.

391 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.NodeKey}).SaveAs(filepath.Join(nodeDir, "config", "node_key.json"))
  86. if err != nil {
  87. return err
  88. }
  89. (privval.NewFilePV(node.PrivvalKey,
  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.PrivvalKey.PubKey().Address(),
  176. PubKey: validator.PrivvalKey.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. "key_type": node.PrivvalKey.Type(),
  291. }
  292. switch node.ABCIProtocol {
  293. case e2e.ProtocolUNIX:
  294. cfg["listen"] = AppAddressUNIX
  295. case e2e.ProtocolTCP:
  296. cfg["listen"] = AppAddressTCP
  297. case e2e.ProtocolGRPC:
  298. cfg["listen"] = AppAddressTCP
  299. cfg["protocol"] = "grpc"
  300. case e2e.ProtocolBuiltin:
  301. delete(cfg, "listen")
  302. cfg["protocol"] = "builtin"
  303. default:
  304. return nil, fmt.Errorf("unexpected ABCI protocol setting %q", node.ABCIProtocol)
  305. }
  306. if node.Mode == e2e.ModeValidator {
  307. switch node.PrivvalProtocol {
  308. case e2e.ProtocolFile:
  309. case e2e.ProtocolTCP:
  310. cfg["privval_server"] = PrivvalAddressTCP
  311. cfg["privval_key"] = PrivvalKeyFile
  312. cfg["privval_state"] = PrivvalStateFile
  313. case e2e.ProtocolUNIX:
  314. cfg["privval_server"] = PrivvalAddressUNIX
  315. cfg["privval_key"] = PrivvalKeyFile
  316. cfg["privval_state"] = PrivvalStateFile
  317. default:
  318. return nil, fmt.Errorf("unexpected privval protocol setting %q", node.PrivvalProtocol)
  319. }
  320. }
  321. misbehaviors := make(map[string]string)
  322. for height, misbehavior := range node.Misbehaviors {
  323. misbehaviors[strconv.Itoa(int(height))] = misbehavior
  324. }
  325. cfg["misbehaviors"] = misbehaviors
  326. if len(node.Testnet.ValidatorUpdates) > 0 {
  327. validatorUpdates := map[string]map[string]int64{}
  328. for height, validators := range node.Testnet.ValidatorUpdates {
  329. updateVals := map[string]int64{}
  330. for node, power := range validators {
  331. updateVals[base64.StdEncoding.EncodeToString(node.PrivvalKey.PubKey().Bytes())] = power
  332. }
  333. validatorUpdates[fmt.Sprintf("%v", height)] = updateVals
  334. }
  335. cfg["validator_update"] = validatorUpdates
  336. }
  337. var buf bytes.Buffer
  338. err := toml.NewEncoder(&buf).Encode(cfg)
  339. if err != nil {
  340. return nil, fmt.Errorf("failed to generate app config: %w", err)
  341. }
  342. return buf.Bytes(), nil
  343. }
  344. // UpdateConfigStateSync updates the state sync config for a node.
  345. func UpdateConfigStateSync(node *e2e.Node, height int64, hash []byte) error {
  346. cfgPath := filepath.Join(node.Testnet.Dir, node.Name, "config", "config.toml")
  347. // FIXME Apparently there's no function to simply load a config file without
  348. // involving the entire Viper apparatus, so we'll just resort to regexps.
  349. bz, err := ioutil.ReadFile(cfgPath)
  350. if err != nil {
  351. return err
  352. }
  353. bz = regexp.MustCompile(`(?m)^trust_height =.*`).ReplaceAll(bz, []byte(fmt.Sprintf(`trust_height = %v`, height)))
  354. bz = regexp.MustCompile(`(?m)^trust_hash =.*`).ReplaceAll(bz, []byte(fmt.Sprintf(`trust_hash = "%X"`, hash)))
  355. return ioutil.WriteFile(cfgPath, bz, 0644)
  356. }