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.

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