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.

428 lines
12 KiB

  1. package main
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "sort"
  6. "strings"
  7. e2e "github.com/tendermint/tendermint/test/e2e/pkg"
  8. "github.com/tendermint/tendermint/types"
  9. )
  10. var (
  11. // testnetCombinations defines global testnet options, where we generate a
  12. // separate testnet for each combination (Cartesian product) of options.
  13. testnetCombinations = map[string][]interface{}{
  14. "topology": {"single", "quad", "large"},
  15. "p2p": {NewP2PMode, LegacyP2PMode, HybridP2PMode},
  16. "queueType": {"priority"}, // "fifo", "wdrr"
  17. "initialHeight": {0, 1000},
  18. "initialState": {
  19. map[string]string{},
  20. map[string]string{"initial01": "a", "initial02": "b", "initial03": "c"},
  21. },
  22. "validators": {"genesis", "initchain"},
  23. }
  24. // The following specify randomly chosen values for testnet nodes.
  25. nodeDatabases = weightedChoice{
  26. "goleveldb": 35,
  27. "badgerdb": 35,
  28. "boltdb": 15,
  29. "rocksdb": 10,
  30. "cleveldb": 5,
  31. }
  32. nodeABCIProtocols = weightedChoice{
  33. "builtin": 50,
  34. "tcp": 20,
  35. "grpc": 20,
  36. "unix": 10,
  37. }
  38. nodePrivvalProtocols = weightedChoice{
  39. "file": 50,
  40. "grpc": 20,
  41. "tcp": 20,
  42. "unix": 10,
  43. }
  44. // FIXME: v2 disabled due to flake
  45. nodeBlockSyncs = uniformChoice{"v0"} // "v2"
  46. nodeMempools = uniformChoice{"v0", "v1"}
  47. nodeStateSyncs = weightedChoice{
  48. e2e.StateSyncDisabled: 10,
  49. e2e.StateSyncP2P: 45,
  50. e2e.StateSyncRPC: 45,
  51. }
  52. nodePersistIntervals = uniformChoice{0, 1, 5}
  53. nodeSnapshotIntervals = uniformChoice{0, 3}
  54. nodeRetainBlocks = uniformChoice{0, 2 * int(e2e.EvidenceAgeHeight), 4 * int(e2e.EvidenceAgeHeight)}
  55. nodePerturbations = probSetChoice{
  56. "disconnect": 0.1,
  57. "pause": 0.1,
  58. "kill": 0.1,
  59. "restart": 0.1,
  60. }
  61. evidence = uniformChoice{0, 1, 10}
  62. txSize = uniformChoice{1024, 4096} // either 1kb or 4kb
  63. ipv6 = uniformChoice{false, true}
  64. keyType = uniformChoice{types.ABCIPubKeyTypeEd25519, types.ABCIPubKeyTypeSecp256k1}
  65. )
  66. // Generate generates random testnets using the given RNG.
  67. func Generate(r *rand.Rand, opts Options) ([]e2e.Manifest, error) {
  68. manifests := []e2e.Manifest{}
  69. switch opts.P2P {
  70. case NewP2PMode, LegacyP2PMode, HybridP2PMode:
  71. defer func() {
  72. // avoid modifying the global state.
  73. original := make([]interface{}, len(testnetCombinations["p2p"]))
  74. copy(original, testnetCombinations["p2p"])
  75. testnetCombinations["p2p"] = original
  76. }()
  77. testnetCombinations["p2p"] = []interface{}{opts.P2P}
  78. default:
  79. testnetCombinations["p2p"] = []interface{}{NewP2PMode, LegacyP2PMode, HybridP2PMode}
  80. }
  81. for _, opt := range combinations(testnetCombinations) {
  82. manifest, err := generateTestnet(r, opt)
  83. if err != nil {
  84. return nil, err
  85. }
  86. if len(manifest.Nodes) < opts.MinNetworkSize {
  87. continue
  88. }
  89. if len(manifest.Nodes) == 1 {
  90. if opt["p2p"] == HybridP2PMode {
  91. continue
  92. }
  93. }
  94. if opts.MaxNetworkSize > 0 && len(manifest.Nodes) >= opts.MaxNetworkSize {
  95. continue
  96. }
  97. manifests = append(manifests, manifest)
  98. }
  99. return manifests, nil
  100. }
  101. type Options struct {
  102. MinNetworkSize int
  103. MaxNetworkSize int
  104. NumGroups int
  105. Directory string
  106. P2P P2PMode
  107. Reverse bool
  108. }
  109. type P2PMode string
  110. const (
  111. NewP2PMode P2PMode = "new"
  112. LegacyP2PMode P2PMode = "legacy"
  113. HybridP2PMode P2PMode = "hybrid"
  114. // mixed means that all combination are generated
  115. MixedP2PMode P2PMode = "mixed"
  116. )
  117. // generateTestnet generates a single testnet with the given options.
  118. func generateTestnet(r *rand.Rand, opt map[string]interface{}) (e2e.Manifest, error) {
  119. manifest := e2e.Manifest{
  120. IPv6: ipv6.Choose(r).(bool),
  121. InitialHeight: int64(opt["initialHeight"].(int)),
  122. InitialState: opt["initialState"].(map[string]string),
  123. Validators: &map[string]int64{},
  124. ValidatorUpdates: map[string]map[string]int64{},
  125. Nodes: map[string]*e2e.ManifestNode{},
  126. KeyType: keyType.Choose(r).(string),
  127. Evidence: evidence.Choose(r).(int),
  128. QueueType: opt["queueType"].(string),
  129. TxSize: int64(txSize.Choose(r).(int)),
  130. }
  131. p2pMode := opt["p2p"].(P2PMode)
  132. switch p2pMode {
  133. case NewP2PMode, LegacyP2PMode, HybridP2PMode:
  134. default:
  135. return manifest, fmt.Errorf("unknown p2p mode %s", p2pMode)
  136. }
  137. var numSeeds, numValidators, numFulls, numLightClients int
  138. switch opt["topology"].(string) {
  139. case "single":
  140. numValidators = 1
  141. case "quad":
  142. numValidators = 4
  143. case "large":
  144. // FIXME Networks are kept small since large ones use too much CPU.
  145. numSeeds = r.Intn(1)
  146. numLightClients = r.Intn(2)
  147. numValidators = 4 + r.Intn(4)
  148. numFulls = r.Intn(4)
  149. default:
  150. return manifest, fmt.Errorf("unknown topology %q", opt["topology"])
  151. }
  152. const legacyP2PFactor float64 = 0.5
  153. // First we generate seed nodes, starting at the initial height.
  154. for i := 1; i <= numSeeds; i++ {
  155. node := generateNode(r, manifest, e2e.ModeSeed, 0, false)
  156. switch p2pMode {
  157. case LegacyP2PMode:
  158. node.UseLegacyP2P = true
  159. case HybridP2PMode:
  160. node.UseLegacyP2P = r.Float64() < legacyP2PFactor
  161. }
  162. manifest.Nodes[fmt.Sprintf("seed%02d", i)] = node
  163. }
  164. var (
  165. numSyncingNodes = 0
  166. hybridNumNew = 0
  167. hybridNumLegacy = 0
  168. )
  169. // Next, we generate validators. We make sure a BFT quorum of validators start
  170. // at the initial height, and that we have two archive nodes. We also set up
  171. // the initial validator set, and validator set updates for delayed nodes.
  172. nextStartAt := manifest.InitialHeight + 5
  173. quorum := numValidators*2/3 + 1
  174. for i := 1; i <= numValidators; i++ {
  175. startAt := int64(0)
  176. if i > quorum && numSyncingNodes < 2 && r.Float64() >= 0.25 {
  177. numSyncingNodes++
  178. startAt = nextStartAt
  179. nextStartAt += 5
  180. }
  181. name := fmt.Sprintf("validator%02d", i)
  182. node := generateNode(r, manifest, e2e.ModeValidator, startAt, i <= 2)
  183. switch p2pMode {
  184. case LegacyP2PMode:
  185. node.UseLegacyP2P = true
  186. case HybridP2PMode:
  187. node.UseLegacyP2P = r.Float64() < legacyP2PFactor
  188. if node.UseLegacyP2P {
  189. hybridNumLegacy++
  190. if hybridNumNew == 0 {
  191. hybridNumNew++
  192. hybridNumLegacy--
  193. node.UseLegacyP2P = false
  194. }
  195. } else {
  196. hybridNumNew++
  197. if hybridNumLegacy == 0 {
  198. hybridNumNew--
  199. hybridNumLegacy++
  200. node.UseLegacyP2P = true
  201. }
  202. }
  203. }
  204. manifest.Nodes[name] = node
  205. if startAt == 0 {
  206. (*manifest.Validators)[name] = int64(30 + r.Intn(71))
  207. } else {
  208. manifest.ValidatorUpdates[fmt.Sprint(startAt+5)] = map[string]int64{
  209. name: int64(30 + r.Intn(71)),
  210. }
  211. }
  212. }
  213. // Move validators to InitChain if specified.
  214. switch opt["validators"].(string) {
  215. case "genesis":
  216. case "initchain":
  217. manifest.ValidatorUpdates["0"] = *manifest.Validators
  218. manifest.Validators = &map[string]int64{}
  219. default:
  220. return manifest, fmt.Errorf("invalid validators option %q", opt["validators"])
  221. }
  222. // Finally, we generate random full nodes.
  223. for i := 1; i <= numFulls; i++ {
  224. startAt := int64(0)
  225. if numSyncingNodes < 2 && r.Float64() >= 0.5 {
  226. numSyncingNodes++
  227. startAt = nextStartAt
  228. nextStartAt += 5
  229. }
  230. node := generateNode(r, manifest, e2e.ModeFull, startAt, false)
  231. switch p2pMode {
  232. case LegacyP2PMode:
  233. node.UseLegacyP2P = true
  234. case HybridP2PMode:
  235. node.UseLegacyP2P = r.Float64() > legacyP2PFactor
  236. }
  237. manifest.Nodes[fmt.Sprintf("full%02d", i)] = node
  238. }
  239. // We now set up peer discovery for nodes. Seed nodes are fully meshed with
  240. // each other, while non-seed nodes either use a set of random seeds or a
  241. // set of random peers that start before themselves.
  242. var seedNames, peerNames, lightProviders []string
  243. for name, node := range manifest.Nodes {
  244. if node.Mode == string(e2e.ModeSeed) {
  245. seedNames = append(seedNames, name)
  246. } else {
  247. // if the full node or validator is an ideal candidate, it is added as a light provider.
  248. // There are at least two archive nodes so there should be at least two ideal candidates
  249. if (node.StartAt == 0 || node.StartAt == manifest.InitialHeight) && node.RetainBlocks == 0 {
  250. lightProviders = append(lightProviders, name)
  251. }
  252. peerNames = append(peerNames, name)
  253. }
  254. }
  255. for _, name := range seedNames {
  256. for _, otherName := range seedNames {
  257. if name != otherName {
  258. manifest.Nodes[name].Seeds = append(manifest.Nodes[name].Seeds, otherName)
  259. }
  260. }
  261. }
  262. sort.Slice(peerNames, func(i, j int) bool {
  263. iName, jName := peerNames[i], peerNames[j]
  264. switch {
  265. case manifest.Nodes[iName].StartAt < manifest.Nodes[jName].StartAt:
  266. return true
  267. case manifest.Nodes[iName].StartAt > manifest.Nodes[jName].StartAt:
  268. return false
  269. default:
  270. return strings.Compare(iName, jName) == -1
  271. }
  272. })
  273. for i, name := range peerNames {
  274. // there are seeds, statesync is disabled, and it's
  275. // either the first peer by the sort order, and
  276. // (randomly half of the remaining peers use a seed
  277. // node; otherwise, choose some remaining set of the
  278. // peers.
  279. if len(seedNames) > 0 &&
  280. manifest.Nodes[name].StateSync == e2e.StateSyncDisabled &&
  281. (i == 0 || r.Float64() >= 0.5) {
  282. // choose one of the seeds
  283. manifest.Nodes[name].Seeds = uniformSetChoice(seedNames).Choose(r)
  284. } else if i > 0 {
  285. peers := uniformSetChoice(peerNames[:i])
  286. if manifest.Nodes[name].StateSync == e2e.StateSyncP2P {
  287. manifest.Nodes[name].PersistentPeers = peers.ChooseAtLeast(r, 2)
  288. } else {
  289. manifest.Nodes[name].PersistentPeers = peers.Choose(r)
  290. }
  291. }
  292. }
  293. // lastly, set up the light clients
  294. for i := 1; i <= numLightClients; i++ {
  295. startAt := manifest.InitialHeight + 5
  296. manifest.Nodes[fmt.Sprintf("light%02d", i)] = generateLightNode(
  297. r, startAt+(5*int64(i)), lightProviders,
  298. )
  299. }
  300. return manifest, nil
  301. }
  302. // generateNode randomly generates a node, with some constraints to avoid
  303. // generating invalid configurations. We do not set Seeds or PersistentPeers
  304. // here, since we need to know the overall network topology and startup
  305. // sequencing.
  306. func generateNode(
  307. r *rand.Rand,
  308. manifest e2e.Manifest,
  309. mode e2e.Mode,
  310. startAt int64,
  311. forceArchive bool,
  312. ) *e2e.ManifestNode {
  313. node := e2e.ManifestNode{
  314. Mode: string(mode),
  315. StartAt: startAt,
  316. Database: nodeDatabases.Choose(r),
  317. ABCIProtocol: nodeABCIProtocols.Choose(r),
  318. PrivvalProtocol: nodePrivvalProtocols.Choose(r),
  319. BlockSync: nodeBlockSyncs.Choose(r).(string),
  320. Mempool: nodeMempools.Choose(r).(string),
  321. StateSync: e2e.StateSyncDisabled,
  322. PersistInterval: ptrUint64(uint64(nodePersistIntervals.Choose(r).(int))),
  323. SnapshotInterval: uint64(nodeSnapshotIntervals.Choose(r).(int)),
  324. RetainBlocks: uint64(nodeRetainBlocks.Choose(r).(int)),
  325. Perturb: nodePerturbations.Choose(r),
  326. }
  327. if startAt > 0 {
  328. node.StateSync = nodeStateSyncs.Choose(r)
  329. if manifest.InitialHeight-startAt <= 5 && node.StateSync == e2e.StateSyncDisabled {
  330. // avoid needing to blocsync more than five total blocks.
  331. node.StateSync = uniformSetChoice([]string{
  332. e2e.StateSyncP2P,
  333. e2e.StateSyncRPC,
  334. }).Choose(r)[0]
  335. }
  336. }
  337. // If this node is forced to be an archive node, retain all blocks and
  338. // enable state sync snapshotting.
  339. if forceArchive {
  340. node.RetainBlocks = 0
  341. node.SnapshotInterval = 3
  342. }
  343. // If a node which does not persist state also does not retain blocks, randomly
  344. // choose to either persist state or retain all blocks.
  345. if node.PersistInterval != nil && *node.PersistInterval == 0 && node.RetainBlocks > 0 {
  346. if r.Float64() > 0.5 {
  347. node.RetainBlocks = 0
  348. } else {
  349. node.PersistInterval = ptrUint64(node.RetainBlocks)
  350. }
  351. }
  352. // If either PersistInterval or SnapshotInterval are greater than RetainBlocks,
  353. // expand the block retention time.
  354. if node.RetainBlocks > 0 {
  355. if node.PersistInterval != nil && node.RetainBlocks < *node.PersistInterval {
  356. node.RetainBlocks = *node.PersistInterval
  357. }
  358. if node.RetainBlocks < node.SnapshotInterval {
  359. node.RetainBlocks = node.SnapshotInterval
  360. }
  361. }
  362. if node.StateSync != e2e.StateSyncDisabled {
  363. node.BlockSync = "v0"
  364. }
  365. return &node
  366. }
  367. func generateLightNode(r *rand.Rand, startAt int64, providers []string) *e2e.ManifestNode {
  368. return &e2e.ManifestNode{
  369. Mode: string(e2e.ModeLight),
  370. StartAt: startAt,
  371. Database: nodeDatabases.Choose(r),
  372. ABCIProtocol: "builtin",
  373. PersistInterval: ptrUint64(0),
  374. PersistentPeers: providers,
  375. }
  376. }
  377. func ptrUint64(i uint64) *uint64 {
  378. return &i
  379. }