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.

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