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.

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