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.

419 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.DefaultLogLevel {
  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. - 6060
  159. volumes:
  160. - ./{{ .Name }}:/tendermint
  161. networks:
  162. {{ $.Name }}:
  163. ipv{{ if $.IPv6 }}6{{ else }}4{{ end}}_address: {{ .IP }}
  164. {{end}}`)
  165. if err != nil {
  166. return nil, err
  167. }
  168. var buf bytes.Buffer
  169. err = tmpl.Execute(&buf, testnet)
  170. if err != nil {
  171. return nil, err
  172. }
  173. return buf.Bytes(), nil
  174. }
  175. // MakeGenesis generates a genesis document.
  176. func MakeGenesis(testnet *e2e.Testnet) (types.GenesisDoc, error) {
  177. genesis := types.GenesisDoc{
  178. GenesisTime: time.Now(),
  179. ChainID: testnet.Name,
  180. ConsensusParams: types.DefaultConsensusParams(),
  181. InitialHeight: testnet.InitialHeight,
  182. }
  183. switch testnet.KeyType {
  184. case "", types.ABCIPubKeyTypeEd25519, types.ABCIPubKeyTypeSecp256k1:
  185. genesis.ConsensusParams.Validator.PubKeyTypes =
  186. append(genesis.ConsensusParams.Validator.PubKeyTypes, types.ABCIPubKeyTypeSecp256k1)
  187. default:
  188. return genesis, errors.New("unsupported KeyType")
  189. }
  190. for validator, power := range testnet.Validators {
  191. genesis.Validators = append(genesis.Validators, types.GenesisValidator{
  192. Name: validator.Name,
  193. Address: validator.PrivvalKey.PubKey().Address(),
  194. PubKey: validator.PrivvalKey.PubKey(),
  195. Power: power,
  196. })
  197. }
  198. // The validator set will be sorted internally by Tendermint ranked by power,
  199. // but we sort it here as well so that all genesis files are identical.
  200. sort.Slice(genesis.Validators, func(i, j int) bool {
  201. return strings.Compare(genesis.Validators[i].Name, genesis.Validators[j].Name) == -1
  202. })
  203. if len(testnet.InitialState) > 0 {
  204. appState, err := json.Marshal(testnet.InitialState)
  205. if err != nil {
  206. return genesis, err
  207. }
  208. genesis.AppState = appState
  209. }
  210. return genesis, genesis.ValidateAndComplete()
  211. }
  212. // MakeConfig generates a Tendermint config for a node.
  213. func MakeConfig(node *e2e.Node) (*config.Config, error) {
  214. cfg := config.DefaultConfig()
  215. cfg.Moniker = node.Name
  216. cfg.ProxyApp = AppAddressTCP
  217. if node.LogLevel != "" {
  218. cfg.LogLevel = node.LogLevel
  219. }
  220. cfg.RPC.ListenAddress = "tcp://0.0.0.0:26657"
  221. cfg.RPC.PprofListenAddress = ":6060"
  222. cfg.P2P.ExternalAddress = fmt.Sprintf("tcp://%v", node.AddressP2P(false))
  223. cfg.P2P.AddrBookStrict = false
  224. cfg.DBBackend = node.Database
  225. cfg.StateSync.DiscoveryTime = 5 * time.Second
  226. switch node.ABCIProtocol {
  227. case e2e.ProtocolUNIX:
  228. cfg.ProxyApp = AppAddressUNIX
  229. case e2e.ProtocolTCP:
  230. cfg.ProxyApp = AppAddressTCP
  231. case e2e.ProtocolGRPC:
  232. cfg.ProxyApp = AppAddressTCP
  233. cfg.ABCI = "grpc"
  234. case e2e.ProtocolBuiltin:
  235. cfg.ProxyApp = ""
  236. cfg.ABCI = ""
  237. default:
  238. return nil, fmt.Errorf("unexpected ABCI protocol setting %q", node.ABCIProtocol)
  239. }
  240. // Tendermint errors if it does not have a privval key set up, regardless of whether
  241. // it's actually needed (e.g. for remote KMS or non-validators). We set up a dummy
  242. // key here by default, and use the real key for actual validators that should use
  243. // the file privval.
  244. cfg.PrivValidatorListenAddr = ""
  245. cfg.PrivValidatorKey = PrivvalDummyKeyFile
  246. cfg.PrivValidatorState = PrivvalDummyStateFile
  247. switch node.Mode {
  248. case e2e.ModeValidator:
  249. switch node.PrivvalProtocol {
  250. case e2e.ProtocolFile:
  251. cfg.PrivValidatorKey = PrivvalKeyFile
  252. cfg.PrivValidatorState = PrivvalStateFile
  253. case e2e.ProtocolUNIX:
  254. cfg.PrivValidatorListenAddr = PrivvalAddressUNIX
  255. case e2e.ProtocolTCP:
  256. cfg.PrivValidatorListenAddr = PrivvalAddressTCP
  257. case e2e.ProtocolGRPC:
  258. cfg.PrivValidatorListenAddr = PrivvalAddressGRPC
  259. default:
  260. return nil, fmt.Errorf("invalid privval protocol setting %q", node.PrivvalProtocol)
  261. }
  262. case e2e.ModeSeed:
  263. cfg.P2P.SeedMode = true
  264. cfg.P2P.PexReactor = true
  265. case e2e.ModeFull:
  266. // Don't need to do anything, since we're using a dummy privval key by default.
  267. default:
  268. return nil, fmt.Errorf("unexpected mode %q", node.Mode)
  269. }
  270. if node.FastSync == "" {
  271. cfg.FastSyncMode = false
  272. } else {
  273. cfg.FastSync.Version = node.FastSync
  274. }
  275. if node.StateSync {
  276. cfg.StateSync.Enable = true
  277. cfg.StateSync.RPCServers = []string{}
  278. for _, peer := range node.Testnet.ArchiveNodes() {
  279. if peer.Name == node.Name {
  280. continue
  281. }
  282. cfg.StateSync.RPCServers = append(cfg.StateSync.RPCServers, peer.AddressRPC())
  283. }
  284. if len(cfg.StateSync.RPCServers) < 2 {
  285. return nil, errors.New("unable to find 2 suitable state sync RPC servers")
  286. }
  287. }
  288. cfg.P2P.Seeds = ""
  289. for _, seed := range node.Seeds {
  290. if len(cfg.P2P.Seeds) > 0 {
  291. cfg.P2P.Seeds += ","
  292. }
  293. cfg.P2P.Seeds += seed.AddressP2P(true)
  294. }
  295. cfg.P2P.PersistentPeers = ""
  296. for _, peer := range node.PersistentPeers {
  297. if len(cfg.P2P.PersistentPeers) > 0 {
  298. cfg.P2P.PersistentPeers += ","
  299. }
  300. cfg.P2P.PersistentPeers += peer.AddressP2P(true)
  301. }
  302. return cfg, nil
  303. }
  304. // MakeAppConfig generates an ABCI application config for a node.
  305. func MakeAppConfig(node *e2e.Node) ([]byte, error) {
  306. cfg := map[string]interface{}{
  307. "chain_id": node.Testnet.Name,
  308. "dir": "data/app",
  309. "listen": AppAddressUNIX,
  310. "protocol": "socket",
  311. "persist_interval": node.PersistInterval,
  312. "snapshot_interval": node.SnapshotInterval,
  313. "retain_blocks": node.RetainBlocks,
  314. "key_type": node.PrivvalKey.Type(),
  315. }
  316. switch node.ABCIProtocol {
  317. case e2e.ProtocolUNIX:
  318. cfg["listen"] = AppAddressUNIX
  319. case e2e.ProtocolTCP:
  320. cfg["listen"] = AppAddressTCP
  321. case e2e.ProtocolGRPC:
  322. cfg["listen"] = AppAddressTCP
  323. cfg["protocol"] = "grpc"
  324. case e2e.ProtocolBuiltin:
  325. delete(cfg, "listen")
  326. cfg["protocol"] = "builtin"
  327. default:
  328. return nil, fmt.Errorf("unexpected ABCI protocol setting %q", node.ABCIProtocol)
  329. }
  330. if node.Mode == e2e.ModeValidator {
  331. switch node.PrivvalProtocol {
  332. case e2e.ProtocolFile:
  333. case e2e.ProtocolTCP:
  334. cfg["privval_server"] = PrivvalAddressTCP
  335. cfg["privval_key"] = PrivvalKeyFile
  336. cfg["privval_state"] = PrivvalStateFile
  337. case e2e.ProtocolUNIX:
  338. cfg["privval_server"] = PrivvalAddressUNIX
  339. cfg["privval_key"] = PrivvalKeyFile
  340. cfg["privval_state"] = PrivvalStateFile
  341. case e2e.ProtocolGRPC:
  342. cfg["privval_server"] = PrivvalAddressGRPC
  343. cfg["privval_key"] = PrivvalKeyFile
  344. cfg["privval_state"] = PrivvalStateFile
  345. default:
  346. return nil, fmt.Errorf("unexpected privval protocol setting %q", node.PrivvalProtocol)
  347. }
  348. }
  349. misbehaviors := make(map[string]string)
  350. for height, misbehavior := range node.Misbehaviors {
  351. misbehaviors[strconv.Itoa(int(height))] = misbehavior
  352. }
  353. cfg["misbehaviors"] = misbehaviors
  354. if len(node.Testnet.ValidatorUpdates) > 0 {
  355. validatorUpdates := map[string]map[string]int64{}
  356. for height, validators := range node.Testnet.ValidatorUpdates {
  357. updateVals := map[string]int64{}
  358. for node, power := range validators {
  359. updateVals[base64.StdEncoding.EncodeToString(node.PrivvalKey.PubKey().Bytes())] = power
  360. }
  361. validatorUpdates[fmt.Sprintf("%v", height)] = updateVals
  362. }
  363. cfg["validator_update"] = validatorUpdates
  364. }
  365. var buf bytes.Buffer
  366. err := toml.NewEncoder(&buf).Encode(cfg)
  367. if err != nil {
  368. return nil, fmt.Errorf("failed to generate app config: %w", err)
  369. }
  370. return buf.Bytes(), nil
  371. }
  372. // UpdateConfigStateSync updates the state sync config for a node.
  373. func UpdateConfigStateSync(node *e2e.Node, height int64, hash []byte) error {
  374. cfgPath := filepath.Join(node.Testnet.Dir, node.Name, "config", "config.toml")
  375. // FIXME Apparently there's no function to simply load a config file without
  376. // involving the entire Viper apparatus, so we'll just resort to regexps.
  377. bz, err := ioutil.ReadFile(cfgPath)
  378. if err != nil {
  379. return err
  380. }
  381. bz = regexp.MustCompile(`(?m)^trust-height =.*`).ReplaceAll(bz, []byte(fmt.Sprintf(`trust-height = %v`, height)))
  382. bz = regexp.MustCompile(`(?m)^trust-hash =.*`).ReplaceAll(bz, []byte(fmt.Sprintf(`trust-hash = "%X"`, hash)))
  383. return ioutil.WriteFile(cfgPath, bz, 0644)
  384. }