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.

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