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.

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