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.

340 lines
9.4 KiB

  1. package p2ptest
  2. import (
  3. "context"
  4. "math/rand"
  5. "testing"
  6. "time"
  7. "github.com/stretchr/testify/require"
  8. dbm "github.com/tendermint/tm-db"
  9. "github.com/tendermint/tendermint/crypto"
  10. "github.com/tendermint/tendermint/crypto/ed25519"
  11. "github.com/tendermint/tendermint/internal/p2p"
  12. "github.com/tendermint/tendermint/libs/log"
  13. "github.com/tendermint/tendermint/types"
  14. )
  15. // Network sets up an in-memory network that can be used for high-level P2P
  16. // testing. It creates an arbitrary number of nodes that are connected to each
  17. // other, and can open channels across all nodes with custom reactors.
  18. type Network struct {
  19. Nodes map[types.NodeID]*Node
  20. logger log.Logger
  21. memoryNetwork *p2p.MemoryNetwork
  22. }
  23. // NetworkOptions is an argument structure to parameterize the
  24. // MakeNetwork function.
  25. type NetworkOptions struct {
  26. NumNodes int
  27. BufferSize int
  28. NodeOpts NodeOptions
  29. }
  30. type NodeOptions struct {
  31. MaxPeers uint16
  32. MaxConnected uint16
  33. }
  34. func (opts *NetworkOptions) setDefaults() {
  35. if opts.BufferSize == 0 {
  36. opts.BufferSize = 1
  37. }
  38. }
  39. // MakeNetwork creates a test network with the given number of nodes and
  40. // connects them to each other.
  41. func MakeNetwork(ctx context.Context, t *testing.T, opts NetworkOptions) *Network {
  42. opts.setDefaults()
  43. logger := log.TestingLogger()
  44. network := &Network{
  45. Nodes: map[types.NodeID]*Node{},
  46. logger: logger,
  47. memoryNetwork: p2p.NewMemoryNetwork(logger, opts.BufferSize),
  48. }
  49. for i := 0; i < opts.NumNodes; i++ {
  50. node := network.MakeNode(ctx, t, opts.NodeOpts)
  51. network.Nodes[node.NodeID] = node
  52. }
  53. return network
  54. }
  55. // Start starts the network by setting up a list of node addresses to dial in
  56. // addition to creating a peer update subscription for each node. Finally, all
  57. // nodes are connected to each other.
  58. func (n *Network) Start(t *testing.T) {
  59. // Set up a list of node addresses to dial, and a peer update subscription
  60. // for each node.
  61. dialQueue := []p2p.NodeAddress{}
  62. subs := map[types.NodeID]*p2p.PeerUpdates{}
  63. for _, node := range n.Nodes {
  64. dialQueue = append(dialQueue, node.NodeAddress)
  65. subs[node.NodeID] = node.PeerManager.Subscribe()
  66. defer subs[node.NodeID].Close()
  67. }
  68. // For each node, dial the nodes that it still doesn't have a connection to
  69. // (either inbound or outbound), and wait for both sides to confirm the
  70. // connection via the subscriptions.
  71. for i, sourceAddress := range dialQueue {
  72. sourceNode := n.Nodes[sourceAddress.NodeID]
  73. sourceSub := subs[sourceAddress.NodeID]
  74. for _, targetAddress := range dialQueue[i+1:] { // nodes <i already connected
  75. targetNode := n.Nodes[targetAddress.NodeID]
  76. targetSub := subs[targetAddress.NodeID]
  77. added, err := sourceNode.PeerManager.Add(targetAddress)
  78. require.NoError(t, err)
  79. require.True(t, added)
  80. select {
  81. case peerUpdate := <-sourceSub.Updates():
  82. require.Equal(t, p2p.PeerUpdate{
  83. NodeID: targetNode.NodeID,
  84. Status: p2p.PeerStatusUp,
  85. }, peerUpdate)
  86. case <-time.After(3 * time.Second):
  87. require.Fail(t, "timed out waiting for peer", "%v dialing %v",
  88. sourceNode.NodeID, targetNode.NodeID)
  89. }
  90. select {
  91. case peerUpdate := <-targetSub.Updates():
  92. require.Equal(t, p2p.PeerUpdate{
  93. NodeID: sourceNode.NodeID,
  94. Status: p2p.PeerStatusUp,
  95. }, peerUpdate)
  96. case <-time.After(3 * time.Second):
  97. require.Fail(t, "timed out waiting for peer", "%v accepting %v",
  98. targetNode.NodeID, sourceNode.NodeID)
  99. }
  100. // Add the address to the target as well, so it's able to dial the
  101. // source back if that's even necessary.
  102. added, err = targetNode.PeerManager.Add(sourceAddress)
  103. require.NoError(t, err)
  104. require.True(t, added)
  105. }
  106. }
  107. }
  108. // NodeIDs returns the network's node IDs.
  109. func (n *Network) NodeIDs() []types.NodeID {
  110. ids := []types.NodeID{}
  111. for id := range n.Nodes {
  112. ids = append(ids, id)
  113. }
  114. return ids
  115. }
  116. // MakeChannels makes a channel on all nodes and returns them, automatically
  117. // doing error checks and cleanups.
  118. func (n *Network) MakeChannels(
  119. t *testing.T,
  120. chDesc *p2p.ChannelDescriptor,
  121. ) map[types.NodeID]*p2p.Channel {
  122. channels := map[types.NodeID]*p2p.Channel{}
  123. for _, node := range n.Nodes {
  124. channels[node.NodeID] = node.MakeChannel(t, chDesc)
  125. }
  126. return channels
  127. }
  128. // MakeChannelsNoCleanup makes a channel on all nodes and returns them,
  129. // automatically doing error checks. The caller must ensure proper cleanup of
  130. // all the channels.
  131. func (n *Network) MakeChannelsNoCleanup(
  132. t *testing.T,
  133. chDesc *p2p.ChannelDescriptor,
  134. ) map[types.NodeID]*p2p.Channel {
  135. channels := map[types.NodeID]*p2p.Channel{}
  136. for _, node := range n.Nodes {
  137. channels[node.NodeID] = node.MakeChannelNoCleanup(t, chDesc)
  138. }
  139. return channels
  140. }
  141. // RandomNode returns a random node.
  142. func (n *Network) RandomNode() *Node {
  143. nodes := make([]*Node, 0, len(n.Nodes))
  144. for _, node := range n.Nodes {
  145. nodes = append(nodes, node)
  146. }
  147. return nodes[rand.Intn(len(nodes))] // nolint:gosec
  148. }
  149. // Peers returns a node's peers (i.e. everyone except itself).
  150. func (n *Network) Peers(id types.NodeID) []*Node {
  151. peers := make([]*Node, 0, len(n.Nodes)-1)
  152. for _, peer := range n.Nodes {
  153. if peer.NodeID != id {
  154. peers = append(peers, peer)
  155. }
  156. }
  157. return peers
  158. }
  159. // Remove removes a node from the network, stopping it and waiting for all other
  160. // nodes to pick up the disconnection.
  161. func (n *Network) Remove(t *testing.T, id types.NodeID) {
  162. require.Contains(t, n.Nodes, id)
  163. node := n.Nodes[id]
  164. delete(n.Nodes, id)
  165. subs := []*p2p.PeerUpdates{}
  166. for _, peer := range n.Nodes {
  167. sub := peer.PeerManager.Subscribe()
  168. defer sub.Close()
  169. subs = append(subs, sub)
  170. }
  171. require.NoError(t, node.Transport.Close())
  172. if node.Router.IsRunning() {
  173. require.NoError(t, node.Router.Stop())
  174. }
  175. node.PeerManager.Close()
  176. for _, sub := range subs {
  177. RequireUpdate(t, sub, p2p.PeerUpdate{
  178. NodeID: node.NodeID,
  179. Status: p2p.PeerStatusDown,
  180. })
  181. }
  182. }
  183. // Node is a node in a Network, with a Router and a PeerManager.
  184. type Node struct {
  185. NodeID types.NodeID
  186. NodeInfo types.NodeInfo
  187. NodeAddress p2p.NodeAddress
  188. PrivKey crypto.PrivKey
  189. Router *p2p.Router
  190. PeerManager *p2p.PeerManager
  191. Transport *p2p.MemoryTransport
  192. }
  193. // MakeNode creates a new Node configured for the network with a
  194. // running peer manager, but does not add it to the existing
  195. // network. Callers are responsible for updating peering relationships.
  196. func (n *Network) MakeNode(ctx context.Context, t *testing.T, opts NodeOptions) *Node {
  197. privKey := ed25519.GenPrivKey()
  198. nodeID := types.NodeIDFromPubKey(privKey.PubKey())
  199. nodeInfo := types.NodeInfo{
  200. NodeID: nodeID,
  201. ListenAddr: "0.0.0.0:0", // FIXME: We have to fake this for now.
  202. Moniker: string(nodeID),
  203. }
  204. transport := n.memoryNetwork.CreateTransport(nodeID)
  205. require.Len(t, transport.Endpoints(), 1, "transport not listening on 1 endpoint")
  206. peerManager, err := p2p.NewPeerManager(nodeID, dbm.NewMemDB(), p2p.PeerManagerOptions{
  207. MinRetryTime: 10 * time.Millisecond,
  208. MaxRetryTime: 100 * time.Millisecond,
  209. RetryTimeJitter: time.Millisecond,
  210. MaxPeers: opts.MaxPeers,
  211. MaxConnected: opts.MaxConnected,
  212. })
  213. require.NoError(t, err)
  214. router, err := p2p.NewRouter(
  215. n.logger,
  216. p2p.NopMetrics(),
  217. nodeInfo,
  218. privKey,
  219. peerManager,
  220. []p2p.Transport{transport},
  221. transport.Endpoints(),
  222. p2p.RouterOptions{DialSleep: func(_ context.Context) {}},
  223. )
  224. require.NoError(t, err)
  225. require.NoError(t, router.Start(ctx))
  226. t.Cleanup(func() {
  227. if router.IsRunning() {
  228. require.NoError(t, router.Stop())
  229. }
  230. peerManager.Close()
  231. require.NoError(t, transport.Close())
  232. })
  233. return &Node{
  234. NodeID: nodeID,
  235. NodeInfo: nodeInfo,
  236. NodeAddress: transport.Endpoints()[0].NodeAddress(nodeID),
  237. PrivKey: privKey,
  238. Router: router,
  239. PeerManager: peerManager,
  240. Transport: transport,
  241. }
  242. }
  243. // MakeChannel opens a channel, with automatic error handling and cleanup. On
  244. // test cleanup, it also checks that the channel is empty, to make sure
  245. // all expected messages have been asserted.
  246. func (n *Node) MakeChannel(
  247. t *testing.T,
  248. chDesc *p2p.ChannelDescriptor,
  249. ) *p2p.Channel {
  250. channel, err := n.Router.OpenChannel(chDesc)
  251. require.NoError(t, err)
  252. require.Contains(t, n.Router.NodeInfo().Channels, byte(chDesc.ID))
  253. t.Cleanup(func() {
  254. RequireEmpty(t, channel)
  255. channel.Close()
  256. })
  257. return channel
  258. }
  259. // MakeChannelNoCleanup opens a channel, with automatic error handling. The
  260. // caller must ensure proper cleanup of the channel.
  261. func (n *Node) MakeChannelNoCleanup(
  262. t *testing.T,
  263. chDesc *p2p.ChannelDescriptor,
  264. ) *p2p.Channel {
  265. channel, err := n.Router.OpenChannel(chDesc)
  266. require.NoError(t, err)
  267. return channel
  268. }
  269. // MakePeerUpdates opens a peer update subscription, with automatic cleanup.
  270. // It checks that all updates have been consumed during cleanup.
  271. func (n *Node) MakePeerUpdates(ctx context.Context, t *testing.T) *p2p.PeerUpdates {
  272. t.Helper()
  273. sub := n.PeerManager.Subscribe()
  274. t.Cleanup(func() {
  275. t.Helper()
  276. RequireNoUpdates(ctx, t, sub)
  277. sub.Close()
  278. })
  279. return sub
  280. }
  281. // MakePeerUpdatesNoRequireEmpty opens a peer update subscription, with automatic cleanup.
  282. // It does *not* check that all updates have been consumed, but will
  283. // close the update channel.
  284. func (n *Node) MakePeerUpdatesNoRequireEmpty(t *testing.T) *p2p.PeerUpdates {
  285. sub := n.PeerManager.Subscribe()
  286. t.Cleanup(func() {
  287. sub.Close()
  288. })
  289. return sub
  290. }
  291. func MakeChannelDesc(chID p2p.ChannelID) *p2p.ChannelDescriptor {
  292. return &p2p.ChannelDescriptor{
  293. ID: chID,
  294. MessageType: &Message{},
  295. Priority: 5,
  296. SendQueueCapacity: 10,
  297. RecvMessageCapacity: 10,
  298. }
  299. }