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.

539 lines
15 KiB

  1. //nolint: gosec
  2. package e2e
  3. import (
  4. "errors"
  5. "fmt"
  6. "io"
  7. "math/rand"
  8. "net"
  9. "path/filepath"
  10. "sort"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/tendermint/tendermint/crypto"
  15. "github.com/tendermint/tendermint/crypto/ed25519"
  16. "github.com/tendermint/tendermint/crypto/secp256k1"
  17. rpchttp "github.com/tendermint/tendermint/rpc/client/http"
  18. "github.com/tendermint/tendermint/types"
  19. )
  20. const (
  21. randomSeed int64 = 2308084734268
  22. proxyPortFirst uint32 = 5701
  23. networkIPv4 = "10.186.73.0/24"
  24. networkIPv6 = "fd80:b10c::/48"
  25. )
  26. type Mode string
  27. type Protocol string
  28. type Perturbation string
  29. const (
  30. ModeValidator Mode = "validator"
  31. ModeFull Mode = "full"
  32. ModeLight Mode = "light"
  33. ModeSeed Mode = "seed"
  34. ProtocolBuiltin Protocol = "builtin"
  35. ProtocolFile Protocol = "file"
  36. ProtocolGRPC Protocol = "grpc"
  37. ProtocolTCP Protocol = "tcp"
  38. ProtocolUNIX Protocol = "unix"
  39. PerturbationDisconnect Perturbation = "disconnect"
  40. PerturbationKill Perturbation = "kill"
  41. PerturbationPause Perturbation = "pause"
  42. PerturbationRestart Perturbation = "restart"
  43. EvidenceAgeHeight int64 = 5
  44. EvidenceAgeTime time.Duration = 500 * time.Millisecond
  45. )
  46. // Testnet represents a single testnet.
  47. type Testnet struct {
  48. Name string
  49. File string
  50. Dir string
  51. IP *net.IPNet
  52. InitialHeight int64
  53. InitialState map[string]string
  54. Validators map[*Node]int64
  55. ValidatorUpdates map[int64]map[*Node]int64
  56. Nodes []*Node
  57. KeyType string
  58. Evidence int
  59. LogLevel string
  60. }
  61. // Node represents a Tendermint node in a testnet.
  62. type Node struct {
  63. Name string
  64. Testnet *Testnet
  65. Mode Mode
  66. PrivvalKey crypto.PrivKey
  67. NodeKey crypto.PrivKey
  68. IP net.IP
  69. ProxyPort uint32
  70. StartAt int64
  71. FastSync string
  72. StateSync bool
  73. Database string
  74. ABCIProtocol Protocol
  75. PrivvalProtocol Protocol
  76. PersistInterval uint64
  77. SnapshotInterval uint64
  78. RetainBlocks uint64
  79. Seeds []*Node
  80. PersistentPeers []*Node
  81. Perturbations []Perturbation
  82. LogLevel string
  83. DisableLegacyP2P bool
  84. QueueType string
  85. }
  86. // LoadTestnet loads a testnet from a manifest file, using the filename to
  87. // determine the testnet name and directory (from the basename of the file).
  88. // The testnet generation must be deterministic, since it is generated
  89. // separately by the runner and the test cases. For this reason, testnets use a
  90. // random seed to generate e.g. keys.
  91. func LoadTestnet(file string) (*Testnet, error) {
  92. manifest, err := LoadManifest(file)
  93. if err != nil {
  94. return nil, err
  95. }
  96. dir := strings.TrimSuffix(file, filepath.Ext(file))
  97. // Set up resource generators. These must be deterministic.
  98. netAddress := networkIPv4
  99. if manifest.IPv6 {
  100. netAddress = networkIPv6
  101. }
  102. _, ipNet, err := net.ParseCIDR(netAddress)
  103. if err != nil {
  104. return nil, fmt.Errorf("invalid IP network address %q: %w", netAddress, err)
  105. }
  106. ipGen := newIPGenerator(ipNet)
  107. keyGen := newKeyGenerator(randomSeed)
  108. proxyPortGen := newPortGenerator(proxyPortFirst)
  109. testnet := &Testnet{
  110. Name: filepath.Base(dir),
  111. File: file,
  112. Dir: dir,
  113. IP: ipGen.Network(),
  114. InitialHeight: 1,
  115. InitialState: manifest.InitialState,
  116. Validators: map[*Node]int64{},
  117. ValidatorUpdates: map[int64]map[*Node]int64{},
  118. Nodes: []*Node{},
  119. Evidence: manifest.Evidence,
  120. KeyType: "ed25519",
  121. LogLevel: manifest.LogLevel,
  122. }
  123. if len(manifest.KeyType) != 0 {
  124. testnet.KeyType = manifest.KeyType
  125. }
  126. if manifest.InitialHeight > 0 {
  127. testnet.InitialHeight = manifest.InitialHeight
  128. }
  129. // Set up nodes, in alphabetical order (IPs and ports get same order).
  130. nodeNames := []string{}
  131. for name := range manifest.Nodes {
  132. nodeNames = append(nodeNames, name)
  133. }
  134. sort.Strings(nodeNames)
  135. for _, name := range nodeNames {
  136. nodeManifest := manifest.Nodes[name]
  137. node := &Node{
  138. Name: name,
  139. Testnet: testnet,
  140. PrivvalKey: keyGen.Generate(manifest.KeyType),
  141. NodeKey: keyGen.Generate("ed25519"),
  142. IP: ipGen.Next(),
  143. ProxyPort: proxyPortGen.Next(),
  144. Mode: ModeValidator,
  145. Database: "goleveldb",
  146. ABCIProtocol: ProtocolBuiltin,
  147. PrivvalProtocol: ProtocolFile,
  148. StartAt: nodeManifest.StartAt,
  149. FastSync: nodeManifest.FastSync,
  150. StateSync: nodeManifest.StateSync,
  151. PersistInterval: 1,
  152. SnapshotInterval: nodeManifest.SnapshotInterval,
  153. RetainBlocks: nodeManifest.RetainBlocks,
  154. Perturbations: []Perturbation{},
  155. LogLevel: manifest.LogLevel,
  156. DisableLegacyP2P: manifest.DisableLegacyP2P,
  157. QueueType: manifest.QueueType,
  158. }
  159. if node.StartAt == testnet.InitialHeight {
  160. node.StartAt = 0 // normalize to 0 for initial nodes, since code expects this
  161. }
  162. if nodeManifest.Mode != "" {
  163. node.Mode = Mode(nodeManifest.Mode)
  164. }
  165. if nodeManifest.Database != "" {
  166. node.Database = nodeManifest.Database
  167. }
  168. if nodeManifest.ABCIProtocol != "" {
  169. node.ABCIProtocol = Protocol(nodeManifest.ABCIProtocol)
  170. }
  171. if nodeManifest.PrivvalProtocol != "" {
  172. node.PrivvalProtocol = Protocol(nodeManifest.PrivvalProtocol)
  173. }
  174. if nodeManifest.PersistInterval != nil {
  175. node.PersistInterval = *nodeManifest.PersistInterval
  176. }
  177. for _, p := range nodeManifest.Perturb {
  178. node.Perturbations = append(node.Perturbations, Perturbation(p))
  179. }
  180. if nodeManifest.LogLevel != "" {
  181. node.LogLevel = nodeManifest.LogLevel
  182. }
  183. testnet.Nodes = append(testnet.Nodes, node)
  184. }
  185. // We do a second pass to set up seeds and persistent peers, which allows graph cycles.
  186. for _, node := range testnet.Nodes {
  187. nodeManifest, ok := manifest.Nodes[node.Name]
  188. if !ok {
  189. return nil, fmt.Errorf("failed to look up manifest for node %q", node.Name)
  190. }
  191. for _, seedName := range nodeManifest.Seeds {
  192. seed := testnet.LookupNode(seedName)
  193. if seed == nil {
  194. return nil, fmt.Errorf("unknown seed %q for node %q", seedName, node.Name)
  195. }
  196. node.Seeds = append(node.Seeds, seed)
  197. }
  198. for _, peerName := range nodeManifest.PersistentPeers {
  199. peer := testnet.LookupNode(peerName)
  200. if peer == nil {
  201. return nil, fmt.Errorf("unknown persistent peer %q for node %q", peerName, node.Name)
  202. }
  203. node.PersistentPeers = append(node.PersistentPeers, peer)
  204. }
  205. // If there are no seeds or persistent peers specified, default to persistent
  206. // connections to all other nodes.
  207. if len(node.PersistentPeers) == 0 && len(node.Seeds) == 0 {
  208. for _, peer := range testnet.Nodes {
  209. if peer.Name == node.Name {
  210. continue
  211. }
  212. node.PersistentPeers = append(node.PersistentPeers, peer)
  213. }
  214. }
  215. }
  216. // Set up genesis validators. If not specified explicitly, use all validator nodes.
  217. if manifest.Validators != nil {
  218. for validatorName, power := range *manifest.Validators {
  219. validator := testnet.LookupNode(validatorName)
  220. if validator == nil {
  221. return nil, fmt.Errorf("unknown validator %q", validatorName)
  222. }
  223. testnet.Validators[validator] = power
  224. }
  225. } else {
  226. for _, node := range testnet.Nodes {
  227. if node.Mode == ModeValidator {
  228. testnet.Validators[node] = 100
  229. }
  230. }
  231. }
  232. // Set up validator updates.
  233. for heightStr, validators := range manifest.ValidatorUpdates {
  234. height, err := strconv.Atoi(heightStr)
  235. if err != nil {
  236. return nil, fmt.Errorf("invalid validator update height %q: %w", height, err)
  237. }
  238. valUpdate := map[*Node]int64{}
  239. for name, power := range validators {
  240. node := testnet.LookupNode(name)
  241. if node == nil {
  242. return nil, fmt.Errorf("unknown validator %q for update at height %v", name, height)
  243. }
  244. valUpdate[node] = power
  245. }
  246. testnet.ValidatorUpdates[int64(height)] = valUpdate
  247. }
  248. return testnet, testnet.Validate()
  249. }
  250. // Validate validates a testnet.
  251. func (t Testnet) Validate() error {
  252. if t.Name == "" {
  253. return errors.New("network has no name")
  254. }
  255. if t.IP == nil {
  256. return errors.New("network has no IP")
  257. }
  258. if len(t.Nodes) == 0 {
  259. return errors.New("network has no nodes")
  260. }
  261. switch t.KeyType {
  262. case "", types.ABCIPubKeyTypeEd25519, types.ABCIPubKeyTypeSecp256k1:
  263. default:
  264. return errors.New("unsupported KeyType")
  265. }
  266. for _, node := range t.Nodes {
  267. if err := node.Validate(t); err != nil {
  268. return fmt.Errorf("invalid node %q: %w", node.Name, err)
  269. }
  270. }
  271. return nil
  272. }
  273. // Validate validates a node.
  274. func (n Node) Validate(testnet Testnet) error {
  275. if n.Name == "" {
  276. return errors.New("node has no name")
  277. }
  278. if n.IP == nil {
  279. return errors.New("node has no IP address")
  280. }
  281. if !testnet.IP.Contains(n.IP) {
  282. return fmt.Errorf("node IP %v is not in testnet network %v", n.IP, testnet.IP)
  283. }
  284. if n.ProxyPort > 0 {
  285. if n.ProxyPort <= 1024 {
  286. return fmt.Errorf("local port %v must be >1024", n.ProxyPort)
  287. }
  288. for _, peer := range testnet.Nodes {
  289. if peer.Name != n.Name && peer.ProxyPort == n.ProxyPort {
  290. return fmt.Errorf("peer %q also has local port %v", peer.Name, n.ProxyPort)
  291. }
  292. }
  293. }
  294. switch n.FastSync {
  295. case "", "v0", "v2":
  296. default:
  297. return fmt.Errorf("invalid fast sync setting %q", n.FastSync)
  298. }
  299. switch n.Database {
  300. case "goleveldb", "cleveldb", "boltdb", "rocksdb", "badgerdb":
  301. default:
  302. return fmt.Errorf("invalid database setting %q", n.Database)
  303. }
  304. switch n.ABCIProtocol {
  305. case ProtocolBuiltin, ProtocolUNIX, ProtocolTCP, ProtocolGRPC:
  306. default:
  307. return fmt.Errorf("invalid ABCI protocol setting %q", n.ABCIProtocol)
  308. }
  309. if n.Mode == ModeLight && n.ABCIProtocol != ProtocolBuiltin {
  310. return errors.New("light client must use builtin protocol")
  311. }
  312. switch n.PrivvalProtocol {
  313. case ProtocolFile, ProtocolTCP, ProtocolGRPC, ProtocolUNIX:
  314. default:
  315. return fmt.Errorf("invalid privval protocol setting %q", n.PrivvalProtocol)
  316. }
  317. if n.StartAt > 0 && n.StartAt < n.Testnet.InitialHeight {
  318. return fmt.Errorf("cannot start at height %v lower than initial height %v",
  319. n.StartAt, n.Testnet.InitialHeight)
  320. }
  321. if n.StateSync && n.StartAt == 0 {
  322. return errors.New("state synced nodes cannot start at the initial height")
  323. }
  324. if n.RetainBlocks != 0 && n.RetainBlocks < uint64(EvidenceAgeHeight) {
  325. return fmt.Errorf("retain_blocks must be greater or equal to max evidence age (%d)",
  326. EvidenceAgeHeight)
  327. }
  328. if n.PersistInterval == 0 && n.RetainBlocks > 0 {
  329. return errors.New("persist_interval=0 requires retain_blocks=0")
  330. }
  331. if n.PersistInterval > 1 && n.RetainBlocks > 0 && n.RetainBlocks < n.PersistInterval {
  332. return errors.New("persist_interval must be less than or equal to retain_blocks")
  333. }
  334. if n.SnapshotInterval > 0 && n.RetainBlocks > 0 && n.RetainBlocks < n.SnapshotInterval {
  335. return errors.New("snapshot_interval must be less than er equal to retain_blocks")
  336. }
  337. for _, perturbation := range n.Perturbations {
  338. switch perturbation {
  339. case PerturbationDisconnect, PerturbationKill, PerturbationPause, PerturbationRestart:
  340. default:
  341. return fmt.Errorf("invalid perturbation %q", perturbation)
  342. }
  343. }
  344. return nil
  345. }
  346. // LookupNode looks up a node by name. For now, simply do a linear search.
  347. func (t Testnet) LookupNode(name string) *Node {
  348. for _, node := range t.Nodes {
  349. if node.Name == name {
  350. return node
  351. }
  352. }
  353. return nil
  354. }
  355. // ArchiveNodes returns a list of archive nodes that start at the initial height
  356. // and contain the entire blockchain history. They are used e.g. as light client
  357. // RPC servers.
  358. func (t Testnet) ArchiveNodes() []*Node {
  359. nodes := []*Node{}
  360. for _, node := range t.Nodes {
  361. if !node.Stateless() && node.StartAt == 0 && node.RetainBlocks == 0 {
  362. nodes = append(nodes, node)
  363. }
  364. }
  365. return nodes
  366. }
  367. // RandomNode returns a random non-seed node.
  368. func (t Testnet) RandomNode() *Node {
  369. for {
  370. node := t.Nodes[rand.Intn(len(t.Nodes))]
  371. if node.Mode != ModeSeed {
  372. return node
  373. }
  374. }
  375. }
  376. // IPv6 returns true if the testnet is an IPv6 network.
  377. func (t Testnet) IPv6() bool {
  378. return t.IP.IP.To4() == nil
  379. }
  380. // HasPerturbations returns whether the network has any perturbations.
  381. func (t Testnet) HasPerturbations() bool {
  382. for _, node := range t.Nodes {
  383. if len(node.Perturbations) > 0 {
  384. return true
  385. }
  386. }
  387. return false
  388. }
  389. // Address returns a P2P endpoint address for the node.
  390. func (n Node) AddressP2P(withID bool) string {
  391. ip := n.IP.String()
  392. if n.IP.To4() == nil {
  393. // IPv6 addresses must be wrapped in [] to avoid conflict with : port separator
  394. ip = fmt.Sprintf("[%v]", ip)
  395. }
  396. addr := fmt.Sprintf("%v:26656", ip)
  397. if withID {
  398. addr = fmt.Sprintf("%x@%v", n.NodeKey.PubKey().Address().Bytes(), addr)
  399. }
  400. return addr
  401. }
  402. // Address returns an RPC endpoint address for the node.
  403. func (n Node) AddressRPC() string {
  404. ip := n.IP.String()
  405. if n.IP.To4() == nil {
  406. // IPv6 addresses must be wrapped in [] to avoid conflict with : port separator
  407. ip = fmt.Sprintf("[%v]", ip)
  408. }
  409. return fmt.Sprintf("%v:26657", ip)
  410. }
  411. // Client returns an RPC client for a node.
  412. func (n Node) Client() (*rpchttp.HTTP, error) {
  413. return rpchttp.New(fmt.Sprintf("http://127.0.0.1:%v", n.ProxyPort))
  414. }
  415. // Stateless returns true if the node is either a seed node or a light node
  416. func (n Node) Stateless() bool {
  417. return n.Mode == ModeLight || n.Mode == ModeSeed
  418. }
  419. // keyGenerator generates pseudorandom Ed25519 keys based on a seed.
  420. type keyGenerator struct {
  421. random *rand.Rand
  422. }
  423. func newKeyGenerator(seed int64) *keyGenerator {
  424. return &keyGenerator{
  425. random: rand.New(rand.NewSource(seed)),
  426. }
  427. }
  428. func (g *keyGenerator) Generate(keyType string) crypto.PrivKey {
  429. seed := make([]byte, ed25519.SeedSize)
  430. _, err := io.ReadFull(g.random, seed)
  431. if err != nil {
  432. panic(err) // this shouldn't happen
  433. }
  434. switch keyType {
  435. case "secp256k1":
  436. return secp256k1.GenPrivKeySecp256k1(seed)
  437. case "", "ed25519":
  438. return ed25519.GenPrivKeyFromSecret(seed)
  439. default:
  440. panic("KeyType not supported") // should not make it this far
  441. }
  442. }
  443. // portGenerator generates local Docker proxy ports for each node.
  444. type portGenerator struct {
  445. nextPort uint32
  446. }
  447. func newPortGenerator(firstPort uint32) *portGenerator {
  448. return &portGenerator{nextPort: firstPort}
  449. }
  450. func (g *portGenerator) Next() uint32 {
  451. port := g.nextPort
  452. g.nextPort++
  453. if g.nextPort == 0 {
  454. panic("port overflow")
  455. }
  456. return port
  457. }
  458. // ipGenerator generates sequential IP addresses for each node, using a random
  459. // network address.
  460. type ipGenerator struct {
  461. network *net.IPNet
  462. nextIP net.IP
  463. }
  464. func newIPGenerator(network *net.IPNet) *ipGenerator {
  465. nextIP := make([]byte, len(network.IP))
  466. copy(nextIP, network.IP)
  467. gen := &ipGenerator{network: network, nextIP: nextIP}
  468. // Skip network and gateway addresses
  469. gen.Next()
  470. gen.Next()
  471. return gen
  472. }
  473. func (g *ipGenerator) Network() *net.IPNet {
  474. n := &net.IPNet{
  475. IP: make([]byte, len(g.network.IP)),
  476. Mask: make([]byte, len(g.network.Mask)),
  477. }
  478. copy(n.IP, g.network.IP)
  479. copy(n.Mask, g.network.Mask)
  480. return n
  481. }
  482. func (g *ipGenerator) Next() net.IP {
  483. ip := make([]byte, len(g.nextIP))
  484. copy(ip, g.nextIP)
  485. for i := len(g.nextIP) - 1; i >= 0; i-- {
  486. g.nextIP[i]++
  487. if g.nextIP[i] != 0 {
  488. break
  489. }
  490. }
  491. return ip
  492. }