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.

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