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.

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