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.

342 lines
9.4 KiB

  1. package p2ptest
  2. import (
  3. "context"
  4. "math/rand"
  5. "testing"
  6. "time"
  7. "github.com/gogo/protobuf/proto"
  8. "github.com/stretchr/testify/require"
  9. dbm "github.com/tendermint/tm-db"
  10. "github.com/tendermint/tendermint/crypto"
  11. "github.com/tendermint/tendermint/crypto/ed25519"
  12. "github.com/tendermint/tendermint/libs/log"
  13. "github.com/tendermint/tendermint/p2p"
  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[p2p.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(t *testing.T, opts NetworkOptions) *Network {
  42. opts.setDefaults()
  43. logger := log.TestingLogger()
  44. network := &Network{
  45. Nodes: map[p2p.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(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[p2p.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() []p2p.NodeID {
  110. ids := []p2p.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. messageType proto.Message,
  122. size int,
  123. ) map[p2p.NodeID]*p2p.Channel {
  124. channels := map[p2p.NodeID]*p2p.Channel{}
  125. for _, node := range n.Nodes {
  126. channels[node.NodeID] = node.MakeChannel(t, chDesc, messageType, size)
  127. }
  128. return channels
  129. }
  130. // MakeChannelsNoCleanup makes a channel on all nodes and returns them,
  131. // automatically doing error checks. The caller must ensure proper cleanup of
  132. // all the channels.
  133. func (n *Network) MakeChannelsNoCleanup(
  134. t *testing.T,
  135. chDesc p2p.ChannelDescriptor,
  136. messageType proto.Message,
  137. size int,
  138. ) map[p2p.NodeID]*p2p.Channel {
  139. channels := map[p2p.NodeID]*p2p.Channel{}
  140. for _, node := range n.Nodes {
  141. channels[node.NodeID] = node.MakeChannelNoCleanup(t, chDesc, messageType, size)
  142. }
  143. return channels
  144. }
  145. // RandomNode returns a random node.
  146. func (n *Network) RandomNode() *Node {
  147. nodes := make([]*Node, 0, len(n.Nodes))
  148. for _, node := range n.Nodes {
  149. nodes = append(nodes, node)
  150. }
  151. return nodes[rand.Intn(len(nodes))] // nolint:gosec
  152. }
  153. // Peers returns a node's peers (i.e. everyone except itself).
  154. func (n *Network) Peers(id p2p.NodeID) []*Node {
  155. peers := make([]*Node, 0, len(n.Nodes)-1)
  156. for _, peer := range n.Nodes {
  157. if peer.NodeID != id {
  158. peers = append(peers, peer)
  159. }
  160. }
  161. return peers
  162. }
  163. // Remove removes a node from the network, stopping it and waiting for all other
  164. // nodes to pick up the disconnection.
  165. func (n *Network) Remove(t *testing.T, id p2p.NodeID) {
  166. require.Contains(t, n.Nodes, id)
  167. node := n.Nodes[id]
  168. delete(n.Nodes, id)
  169. subs := []*p2p.PeerUpdates{}
  170. for _, peer := range n.Nodes {
  171. sub := peer.PeerManager.Subscribe()
  172. defer sub.Close()
  173. subs = append(subs, sub)
  174. }
  175. require.NoError(t, node.Transport.Close())
  176. if node.Router.IsRunning() {
  177. require.NoError(t, node.Router.Stop())
  178. }
  179. node.PeerManager.Close()
  180. for _, sub := range subs {
  181. RequireUpdate(t, sub, p2p.PeerUpdate{
  182. NodeID: node.NodeID,
  183. Status: p2p.PeerStatusDown,
  184. })
  185. }
  186. }
  187. // Node is a node in a Network, with a Router and a PeerManager.
  188. type Node struct {
  189. NodeID p2p.NodeID
  190. NodeInfo p2p.NodeInfo
  191. NodeAddress p2p.NodeAddress
  192. PrivKey crypto.PrivKey
  193. Router *p2p.Router
  194. PeerManager *p2p.PeerManager
  195. Transport *p2p.MemoryTransport
  196. }
  197. // MakeNode creates a new Node configured for the network with a
  198. // running peer manager, but does not add it to the existing
  199. // network. Callers are responsible for updating peering relationships.
  200. func (n *Network) MakeNode(t *testing.T, opts NodeOptions) *Node {
  201. privKey := ed25519.GenPrivKey()
  202. nodeID := p2p.NodeIDFromPubKey(privKey.PubKey())
  203. nodeInfo := p2p.NodeInfo{
  204. NodeID: nodeID,
  205. ListenAddr: "0.0.0.0:0", // FIXME: We have to fake this for now.
  206. Moniker: string(nodeID),
  207. }
  208. transport := n.memoryNetwork.CreateTransport(nodeID)
  209. require.Len(t, transport.Endpoints(), 1, "transport not listening on 1 endpoint")
  210. peerManager, err := p2p.NewPeerManager(nodeID, dbm.NewMemDB(), p2p.PeerManagerOptions{
  211. MinRetryTime: 10 * time.Millisecond,
  212. MaxRetryTime: 100 * time.Millisecond,
  213. RetryTimeJitter: time.Millisecond,
  214. MaxPeers: opts.MaxPeers,
  215. MaxConnected: opts.MaxConnected,
  216. })
  217. require.NoError(t, err)
  218. router, err := p2p.NewRouter(
  219. n.logger,
  220. p2p.NopMetrics(),
  221. nodeInfo,
  222. privKey,
  223. peerManager,
  224. []p2p.Transport{transport},
  225. p2p.RouterOptions{DialSleep: func(_ context.Context) {}},
  226. )
  227. require.NoError(t, err)
  228. require.NoError(t, router.Start())
  229. t.Cleanup(func() {
  230. if router.IsRunning() {
  231. require.NoError(t, router.Stop())
  232. }
  233. peerManager.Close()
  234. require.NoError(t, transport.Close())
  235. })
  236. return &Node{
  237. NodeID: nodeID,
  238. NodeInfo: nodeInfo,
  239. NodeAddress: transport.Endpoints()[0].NodeAddress(nodeID),
  240. PrivKey: privKey,
  241. Router: router,
  242. PeerManager: peerManager,
  243. Transport: transport,
  244. }
  245. }
  246. // MakeChannel opens a channel, with automatic error handling and cleanup. On
  247. // test cleanup, it also checks that the channel is empty, to make sure
  248. // all expected messages have been asserted.
  249. func (n *Node) MakeChannel(t *testing.T, chDesc p2p.ChannelDescriptor,
  250. messageType proto.Message, size int) *p2p.Channel {
  251. channel, err := n.Router.OpenChannel(chDesc, messageType, size)
  252. require.NoError(t, err)
  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. messageType proto.Message,
  265. size int,
  266. ) *p2p.Channel {
  267. channel, err := n.Router.OpenChannel(chDesc, messageType, size)
  268. require.NoError(t, err)
  269. return channel
  270. }
  271. // MakePeerUpdates opens a peer update subscription, with automatic cleanup.
  272. // It checks that all updates have been consumed during cleanup.
  273. func (n *Node) MakePeerUpdates(t *testing.T) *p2p.PeerUpdates {
  274. t.Helper()
  275. sub := n.PeerManager.Subscribe()
  276. t.Cleanup(func() {
  277. t.Helper()
  278. RequireNoUpdates(t, sub)
  279. sub.Close()
  280. })
  281. return sub
  282. }
  283. // MakePeerUpdatesNoRequireEmpty opens a peer update subscription, with automatic cleanup.
  284. // It does *not* check that all updates have been consumed, but will
  285. // close the update channel.
  286. func (n *Node) MakePeerUpdatesNoRequireEmpty(t *testing.T) *p2p.PeerUpdates {
  287. sub := n.PeerManager.Subscribe()
  288. t.Cleanup(func() {
  289. sub.Close()
  290. })
  291. return sub
  292. }
  293. func MakeChannelDesc(chID p2p.ChannelID) p2p.ChannelDescriptor {
  294. return p2p.ChannelDescriptor{
  295. ID: byte(chID),
  296. Priority: 5,
  297. SendQueueCapacity: 10,
  298. RecvMessageCapacity: 10,
  299. MaxSendBytes: 1000,
  300. }
  301. }