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.

562 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. "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. LogLevel string
  56. }
  57. // Node represents a Tendermint node in a testnet.
  58. type Node struct {
  59. Name string
  60. Testnet *Testnet
  61. Mode Mode
  62. PrivvalKey crypto.PrivKey
  63. NodeKey crypto.PrivKey
  64. IP net.IP
  65. ProxyPort uint32
  66. StartAt int64
  67. FastSync string
  68. StateSync bool
  69. Database string
  70. ABCIProtocol Protocol
  71. PrivvalProtocol Protocol
  72. PersistInterval uint64
  73. SnapshotInterval uint64
  74. RetainBlocks uint64
  75. Seeds []*Node
  76. PersistentPeers []*Node
  77. Perturbations []Perturbation
  78. Misbehaviors map[int64]string
  79. LogLevel string
  80. }
  81. // LoadTestnet loads a testnet from a manifest file, using the filename to
  82. // determine the testnet name and directory (from the basename of the file).
  83. // The testnet generation must be deterministic, since it is generated
  84. // separately by the runner and the test cases. For this reason, testnets use a
  85. // random seed to generate e.g. keys.
  86. func LoadTestnet(file string) (*Testnet, error) {
  87. manifest, err := LoadManifest(file)
  88. if err != nil {
  89. return nil, err
  90. }
  91. dir := strings.TrimSuffix(file, filepath.Ext(file))
  92. // Set up resource generators. These must be deterministic.
  93. netAddress := networkIPv4
  94. if manifest.IPv6 {
  95. netAddress = networkIPv6
  96. }
  97. _, ipNet, err := net.ParseCIDR(netAddress)
  98. if err != nil {
  99. return nil, fmt.Errorf("invalid IP network address %q: %w", netAddress, err)
  100. }
  101. ipGen := newIPGenerator(ipNet)
  102. keyGen := newKeyGenerator(randomSeed)
  103. proxyPortGen := newPortGenerator(proxyPortFirst)
  104. testnet := &Testnet{
  105. Name: filepath.Base(dir),
  106. File: file,
  107. Dir: dir,
  108. IP: ipGen.Network(),
  109. InitialHeight: 1,
  110. InitialState: manifest.InitialState,
  111. Validators: map[*Node]int64{},
  112. ValidatorUpdates: map[int64]map[*Node]int64{},
  113. Nodes: []*Node{},
  114. KeyType: "ed25519",
  115. LogLevel: manifest.LogLevel,
  116. }
  117. if len(manifest.KeyType) != 0 {
  118. testnet.KeyType = manifest.KeyType
  119. }
  120. if manifest.InitialHeight > 0 {
  121. testnet.InitialHeight = manifest.InitialHeight
  122. }
  123. // Set up nodes, in alphabetical order (IPs and ports get same order).
  124. nodeNames := []string{}
  125. for name := range manifest.Nodes {
  126. nodeNames = append(nodeNames, name)
  127. }
  128. sort.Strings(nodeNames)
  129. for _, name := range nodeNames {
  130. nodeManifest := manifest.Nodes[name]
  131. node := &Node{
  132. Name: name,
  133. Testnet: testnet,
  134. PrivvalKey: keyGen.Generate(manifest.KeyType),
  135. NodeKey: keyGen.Generate("ed25519"),
  136. IP: ipGen.Next(),
  137. ProxyPort: proxyPortGen.Next(),
  138. Mode: ModeValidator,
  139. Database: "goleveldb",
  140. ABCIProtocol: ProtocolUNIX,
  141. PrivvalProtocol: ProtocolFile,
  142. StartAt: nodeManifest.StartAt,
  143. FastSync: nodeManifest.FastSync,
  144. StateSync: nodeManifest.StateSync,
  145. PersistInterval: 1,
  146. SnapshotInterval: nodeManifest.SnapshotInterval,
  147. RetainBlocks: nodeManifest.RetainBlocks,
  148. Perturbations: []Perturbation{},
  149. Misbehaviors: make(map[int64]string),
  150. LogLevel: manifest.LogLevel,
  151. }
  152. if node.StartAt == testnet.InitialHeight {
  153. node.StartAt = 0 // normalize to 0 for initial nodes, since code expects this
  154. }
  155. if nodeManifest.Mode != "" {
  156. node.Mode = Mode(nodeManifest.Mode)
  157. }
  158. if nodeManifest.Database != "" {
  159. node.Database = nodeManifest.Database
  160. }
  161. if nodeManifest.ABCIProtocol != "" {
  162. node.ABCIProtocol = Protocol(nodeManifest.ABCIProtocol)
  163. }
  164. if nodeManifest.PrivvalProtocol != "" {
  165. node.PrivvalProtocol = Protocol(nodeManifest.PrivvalProtocol)
  166. }
  167. if nodeManifest.PersistInterval != nil {
  168. node.PersistInterval = *nodeManifest.PersistInterval
  169. }
  170. for _, p := range nodeManifest.Perturb {
  171. node.Perturbations = append(node.Perturbations, Perturbation(p))
  172. }
  173. for heightString, misbehavior := range nodeManifest.Misbehaviors {
  174. height, err := strconv.ParseInt(heightString, 10, 64)
  175. if err != nil {
  176. return nil, fmt.Errorf("unable to parse height %s to int64: %w", heightString, err)
  177. }
  178. node.Misbehaviors[height] = misbehavior
  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. switch n.PrivvalProtocol {
  310. case ProtocolFile, ProtocolTCP, ProtocolGRPC, ProtocolUNIX:
  311. default:
  312. return fmt.Errorf("invalid privval protocol setting %q", n.PrivvalProtocol)
  313. }
  314. if n.StartAt > 0 && n.StartAt < n.Testnet.InitialHeight {
  315. return fmt.Errorf("cannot start at height %v lower than initial height %v",
  316. n.StartAt, n.Testnet.InitialHeight)
  317. }
  318. if n.StateSync && n.StartAt == 0 {
  319. return errors.New("state synced nodes cannot start at the initial height")
  320. }
  321. if n.PersistInterval == 0 && n.RetainBlocks > 0 {
  322. return errors.New("persist_interval=0 requires retain_blocks=0")
  323. }
  324. if n.PersistInterval > 1 && n.RetainBlocks > 0 && n.RetainBlocks < n.PersistInterval {
  325. return errors.New("persist_interval must be less than or equal to retain_blocks")
  326. }
  327. if n.SnapshotInterval > 0 && n.RetainBlocks > 0 && n.RetainBlocks < n.SnapshotInterval {
  328. return errors.New("snapshot_interval must be less than er equal to retain_blocks")
  329. }
  330. for _, perturbation := range n.Perturbations {
  331. switch perturbation {
  332. case PerturbationDisconnect, PerturbationKill, PerturbationPause, PerturbationRestart:
  333. default:
  334. return fmt.Errorf("invalid perturbation %q", perturbation)
  335. }
  336. }
  337. if (n.PrivvalProtocol != "file" || n.Mode != "validator") && len(n.Misbehaviors) != 0 {
  338. return errors.New("must be using \"file\" privval protocol to implement misbehaviors")
  339. }
  340. for height, misbehavior := range n.Misbehaviors {
  341. if height < n.StartAt {
  342. return fmt.Errorf("misbehavior height %d is below node start height %d",
  343. height, n.StartAt)
  344. }
  345. if height < testnet.InitialHeight {
  346. return fmt.Errorf("misbehavior height %d is below network initial height %d",
  347. height, testnet.InitialHeight)
  348. }
  349. exists := false
  350. for possibleBehaviors := range mcs.MisbehaviorList {
  351. if possibleBehaviors == misbehavior {
  352. exists = true
  353. }
  354. }
  355. if !exists {
  356. return fmt.Errorf("misbehavior %s does not exist", misbehavior)
  357. }
  358. }
  359. return nil
  360. }
  361. // LookupNode looks up a node by name. For now, simply do a linear search.
  362. func (t Testnet) LookupNode(name string) *Node {
  363. for _, node := range t.Nodes {
  364. if node.Name == name {
  365. return node
  366. }
  367. }
  368. return nil
  369. }
  370. // ArchiveNodes returns a list of archive nodes that start at the initial height
  371. // and contain the entire blockchain history. They are used e.g. as light client
  372. // RPC servers.
  373. func (t Testnet) ArchiveNodes() []*Node {
  374. nodes := []*Node{}
  375. for _, node := range t.Nodes {
  376. if node.Mode != ModeSeed && node.StartAt == 0 && node.RetainBlocks == 0 {
  377. nodes = append(nodes, node)
  378. }
  379. }
  380. return nodes
  381. }
  382. // RandomNode returns a random non-seed node.
  383. func (t Testnet) RandomNode() *Node {
  384. for {
  385. node := t.Nodes[rand.Intn(len(t.Nodes))]
  386. if node.Mode != ModeSeed {
  387. return node
  388. }
  389. }
  390. }
  391. // IPv6 returns true if the testnet is an IPv6 network.
  392. func (t Testnet) IPv6() bool {
  393. return t.IP.IP.To4() == nil
  394. }
  395. // HasPerturbations returns whether the network has any perturbations.
  396. func (t Testnet) HasPerturbations() bool {
  397. for _, node := range t.Nodes {
  398. if len(node.Perturbations) > 0 {
  399. return true
  400. }
  401. }
  402. return false
  403. }
  404. // LastMisbehaviorHeight returns the height of the last misbehavior.
  405. func (t Testnet) LastMisbehaviorHeight() int64 {
  406. lastHeight := int64(0)
  407. for _, node := range t.Nodes {
  408. for height := range node.Misbehaviors {
  409. if height > lastHeight {
  410. lastHeight = height
  411. }
  412. }
  413. }
  414. return lastHeight
  415. }
  416. // Address returns a P2P endpoint address for the node.
  417. func (n Node) AddressP2P(withID bool) string {
  418. ip := n.IP.String()
  419. if n.IP.To4() == nil {
  420. // IPv6 addresses must be wrapped in [] to avoid conflict with : port separator
  421. ip = fmt.Sprintf("[%v]", ip)
  422. }
  423. addr := fmt.Sprintf("%v:26656", ip)
  424. if withID {
  425. addr = fmt.Sprintf("%x@%v", n.NodeKey.PubKey().Address().Bytes(), addr)
  426. }
  427. return addr
  428. }
  429. // Address returns an RPC endpoint address for the node.
  430. func (n Node) AddressRPC() string {
  431. ip := n.IP.String()
  432. if n.IP.To4() == nil {
  433. // IPv6 addresses must be wrapped in [] to avoid conflict with : port separator
  434. ip = fmt.Sprintf("[%v]", ip)
  435. }
  436. return fmt.Sprintf("%v:26657", ip)
  437. }
  438. // Client returns an RPC client for a node.
  439. func (n Node) Client() (*rpchttp.HTTP, error) {
  440. return rpchttp.New(fmt.Sprintf("http://127.0.0.1:%v", n.ProxyPort), "/websocket")
  441. }
  442. // keyGenerator generates pseudorandom Ed25519 keys based on a seed.
  443. type keyGenerator struct {
  444. random *rand.Rand
  445. }
  446. func newKeyGenerator(seed int64) *keyGenerator {
  447. return &keyGenerator{
  448. random: rand.New(rand.NewSource(seed)),
  449. }
  450. }
  451. func (g *keyGenerator) Generate(keyType string) crypto.PrivKey {
  452. seed := make([]byte, ed25519.SeedSize)
  453. _, err := io.ReadFull(g.random, seed)
  454. if err != nil {
  455. panic(err) // this shouldn't happen
  456. }
  457. switch keyType {
  458. case "secp256k1":
  459. return secp256k1.GenPrivKeySecp256k1(seed)
  460. case "", "ed25519":
  461. return ed25519.GenPrivKeyFromSecret(seed)
  462. default:
  463. panic("KeyType not supported") // should not make it this far
  464. }
  465. }
  466. // portGenerator generates local Docker proxy ports for each node.
  467. type portGenerator struct {
  468. nextPort uint32
  469. }
  470. func newPortGenerator(firstPort uint32) *portGenerator {
  471. return &portGenerator{nextPort: firstPort}
  472. }
  473. func (g *portGenerator) Next() uint32 {
  474. port := g.nextPort
  475. g.nextPort++
  476. if g.nextPort == 0 {
  477. panic("port overflow")
  478. }
  479. return port
  480. }
  481. // ipGenerator generates sequential IP addresses for each node, using a random
  482. // network address.
  483. type ipGenerator struct {
  484. network *net.IPNet
  485. nextIP net.IP
  486. }
  487. func newIPGenerator(network *net.IPNet) *ipGenerator {
  488. nextIP := make([]byte, len(network.IP))
  489. copy(nextIP, network.IP)
  490. gen := &ipGenerator{network: network, nextIP: nextIP}
  491. // Skip network and gateway addresses
  492. gen.Next()
  493. gen.Next()
  494. return gen
  495. }
  496. func (g *ipGenerator) Network() *net.IPNet {
  497. n := &net.IPNet{
  498. IP: make([]byte, len(g.network.IP)),
  499. Mask: make([]byte, len(g.network.Mask)),
  500. }
  501. copy(n.IP, g.network.IP)
  502. copy(n.Mask, g.network.Mask)
  503. return n
  504. }
  505. func (g *ipGenerator) Next() net.IP {
  506. ip := make([]byte, len(g.nextIP))
  507. copy(ip, g.nextIP)
  508. for i := len(g.nextIP) - 1; i >= 0; i-- {
  509. g.nextIP[i]++
  510. if g.nextIP[i] != 0 {
  511. break
  512. }
  513. }
  514. return ip
  515. }