Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test(gossipsub): Topic Membership Tests #1201

Open
wants to merge 35 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 28 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
871efab
added test wrt subscribe and unsubscribe
shashankshampi Sep 26, 2024
dc7f8d4
added tests/pubsub/testgossipinternal2 file
shashankshampi Sep 26, 2024
5790b6f
linters
shashankshampi Sep 26, 2024
eced002
Merge branch 'master' into block6Test
shashankshampi Sep 26, 2024
1c2e221
refactor and suite name refactor
shashankshampi Sep 27, 2024
2923a2d
test(gossipsub): added test for membership for join and leave topic
shashankshampi Sep 30, 2024
fda0d2b
test(gossipsub): import optimization
shashankshampi Oct 1, 2024
eb2f6bf
test(gossipsub): Test cases covering subscribe and unsubscribe Events
shashankshampi Sep 26, 2024
9c0966e
Merge branch 'master' into block6Test
shashankshampi Oct 2, 2024
27c2850
Merge branch 'master' into block6Test2
shashankshampi Oct 2, 2024
25df50d
updtaed as per review comment
shashankshampi Oct 3, 2024
f0c8c5b
review comments to remove unwanted comments
shashankshampi Oct 3, 2024
46b7125
removed internal subscribe and unsubscribe test
shashankshampi Oct 3, 2024
19d3ead
removed unwanted check
shashankshampi Oct 3, 2024
f42a763
added assertion for handle SUBSCRIBE to the topic
shashankshampi Oct 3, 2024
e10e4d0
rebase with block6Test
shashankshampi Oct 5, 2024
89473da
TC fix
shashankshampi Oct 5, 2024
806592d
PR update
shashankshampi Oct 7, 2024
2d38e8a
fix in test logic for multiple peers join and leave topic simultaneously
shashankshampi Oct 8, 2024
d594c04
addressed wornderful review comments
shashankshampi Oct 10, 2024
a12b56c
Merge branch 'block6Test' into block6Test2
shashankshampi Oct 10, 2024
cb7ccae
updated as per review comment
shashankshampi Oct 10, 2024
ff6b274
review comment fix
shashankshampi Oct 10, 2024
567a456
Merge branch 'block6Test' into block6Test2
shashankshampi Oct 10, 2024
cc8e976
removed PubSub in sunscribe
shashankshampi Oct 10, 2024
e68685c
added part 2 PR in same
shashankshampi Oct 16, 2024
44dd7d1
added updated logic to use common handler and create peers nodes as r…
shashankshampi Oct 21, 2024
d80abe0
review comment fix
shashankshampi Oct 22, 2024
a7e80de
rebase
shashankshampi Oct 24, 2024
be818b9
Remove tests/pubsub/testgossipmembership from the PR
shashankshampi Oct 24, 2024
a3c29ae
rebase
shashankshampi Oct 24, 2024
aa34c7f
fix in last test
shashankshampi Oct 24, 2024
df674d5
another set of review comment fix
shashankshampi Oct 24, 2024
1bfdded
added documentation as per request
shashankshampi Oct 25, 2024
49ce782
added alex changes
shashankshampi Oct 26, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ build/
*.exe
*.dll
.vscode/
.idea/
.DS_Store
tests/pubsub/testgossipsub
examples/*.md
Expand Down
40 changes: 0 additions & 40 deletions tests/pubsub/testgossipinternal.nim
Original file line number Diff line number Diff line change
Expand Up @@ -33,46 +33,6 @@ suite "GossipSub internal":
teardown:
checkTrackers()

asyncTest "subscribe/unsubscribeAll":
let gossipSub = TestGossipSub.init(newStandardSwitch())

proc handler(topic: string, data: seq[byte]): Future[void] {.gcsafe.} =
discard

let topic = "foobar"
gossipSub.mesh[topic] = initHashSet[PubSubPeer]()
gossipSub.topicParams[topic] = TopicParams.init()

var conns = newSeq[Connection]()
gossipSub.gossipsub[topic] = initHashSet[PubSubPeer]()
for i in 0 ..< 15:
let conn = TestBufferStream.new(noop)
conns &= conn
let peerId = randomPeerId()
conn.peerId = peerId
let peer = gossipSub.getPubSubPeer(peerId)
peer.sendConn = conn
gossipSub.gossipsub[topic].incl(peer)

# test via dynamic dispatch
gossipSub.PubSub.subscribe(topic, handler)

check:
gossipSub.topics.contains(topic)
gossipSub.gossipsub[topic].len() > 0
gossipSub.mesh[topic].len() > 0

# test via dynamic dispatch
gossipSub.PubSub.unsubscribeAll(topic)

check:
topic notin gossipSub.topics # not in local topics
topic notin gossipSub.mesh # not in mesh
topic in gossipSub.gossipsub # but still in gossipsub table (for fanning out)

await allFuturesThrowing(conns.mapIt(it.close()))
await gossipSub.switch.stop()

asyncTest "topic params":
let params = TopicParams.init()
params.validateParameters().tryGet()
Expand Down
Binary file added tests/pubsub/testgossipmembership
AlejandroCabeza marked this conversation as resolved.
Show resolved Hide resolved
Binary file not shown.
284 changes: 284 additions & 0 deletions tests/pubsub/testgossipmembership.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,284 @@
# Nim-LibP2P
# Copyright (c) 2023-2024 Status Research & Development GmbH
# Licensed under either of
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
# * MIT license ([LICENSE-MIT](LICENSE-MIT))
# at your option.
# This file may not be copied, modified, or distributed except according to
# those terms.

{.used.}

import std/[options, deques, sequtils, enumerate, algorithm, sets]
import stew/byteutils
import ../../libp2p/builders
import ../../libp2p/errors
import ../../libp2p/crypto/crypto
import ../../libp2p/stream/bufferstream
import ../../libp2p/protocols/pubsub/[pubsub, gossipsub, mcache, mcache, peertable]
import ../../libp2p/protocols/pubsub/rpc/[message, messages]
import ../../libp2p/switch
import ../../libp2p/muxers/muxer
import ../../libp2p/protocols/pubsub/rpc/protobuf
import utils
import chronos
import chronicles
import ../helpers

proc noop(data: seq[byte]) {.async: (raises: [CancelledError, LPStreamError]).} =
discard

proc voidTopicHandler(topic: string, data: seq[byte]) {.async.} =
discard

const MsgIdSuccess = "msg id gen success"
let DURATION_TIMEOUT = 500.milliseconds

suite "GossipSub Topic Membership Tests":
teardown:
checkTrackers()

# Addition of Designed Test cases for 6. Topic Membership Tests: https://www.notion.so/Gossipsub-651e02d4d7894bb2ac1e4edb55f3192d

# Generalized setup function to initialize one or more topics
proc setupGossipSub(
AlejandroCabeza marked this conversation as resolved.
Show resolved Hide resolved
topics: seq[string], numPeers: int
): (TestGossipSub, seq[Connection]) =
let gossipSub = TestGossipSub.init(newStandardSwitch())
var conns = newSeq[Connection]()

for topic in topics:
gossipSub.mesh[topic] = initHashSet[PubSubPeer]()
gossipSub.topicParams[topic] = TopicParams.init()
gossipSub.gossipsub[topic] = initHashSet[PubSubPeer]()

for i in 0 ..< numPeers:
let conn = TestBufferStream.new(noop)
conns &= conn
let peerId = randomPeerId()
conn.peerId = peerId
let peer = gossipSub.getPubSubPeer(peerId)
peer.sendConn = conn
gossipSub.gossipsub[topic].incl(peer)

return (gossipSub, conns)

# Wrapper function to initialize a single topic by converting it into a seq
proc setupGossipSub(topic: string, numPeers: int): (TestGossipSub, seq[Connection]) =
setupGossipSub(@[topic], numPeers)

# Helper function to subscribe to topics
proc subscribeToTopics(gossipSub: TestGossipSub, topics: seq[string]) =
for topic in topics:
gossipSub.subscribe(
topic,
proc(topic: string, data: seq[byte]): Future[void] {.async.} =
discard
,
)

# Helper function to unsubscribe to topics
proc unsubscribeFromTopics(gossipSub: TestGossipSub, topics: seq[string]) =
for topic in topics:
gossipSub.unsubscribeAll(topic)

proc commonSubscribe(
nodes: seq[TestGossipSub],
topic: string,
handler: proc(topic: string, data: seq[byte]) {.async.},
) =
# Subscribe all nodes to the topic
for node in nodes:
node.subscribe(topic, handler)
echo "Subscribed all nodes to the topic: ", topic

proc commonUnsubscribe(
nodes: seq[TestGossipSub],
topic: string,
handler: proc(topic: string, data: seq[byte]) {.async.},
) =
# Unsubscribe all nodes from the topic
for node in nodes:
node.unsubscribe(topic, handler)
echo "Unsubscribed all nodes from the topic: ", topic

# Simulate the `SUBSCRIBE` to the topic and check proper handling in the mesh and gossipsub structures
asyncTest "handle SUBSCRIBE to the topic":
AlejandroCabeza marked this conversation as resolved.
Show resolved Hide resolved
AlejandroCabeza marked this conversation as resolved.
Show resolved Hide resolved
let topic = "test-topic"
let (gossipSub, conns) = setupGossipSub(topic, 5)

# Subscribe to the topic
subscribeToTopics(gossipSub, @[topic])

# Check if the topic is present in the list of subscribed topics
check gossipSub.topics.contains(topic)

# Check if the topic is added to gossipsub and the peers list is not empty
check gossipSub.gossipsub[topic].len() == 5

AlejandroCabeza marked this conversation as resolved.
Show resolved Hide resolved
# Close all peer connections and verify that they are properly cleaned up
await allFuturesThrowing(conns.mapIt(it.close()))
diegomrsantos marked this conversation as resolved.
Show resolved Hide resolved

# Stop the gossipSub switch and wait for it to stop completely
await gossipSub.switch.stop()

# Simulate an UNSUBSCRIBE to the topic and check if the topic is removed from the relevant data structures but remains in gossipsub
asyncTest "handle UNSUBSCRIBE to the topic":
let topic = "test-topic"
let (gossipSub, conns) = setupGossipSub(topic, 5)

# Subscribe to the topic first
subscribeToTopics(gossipSub, @[topic])

# Now unsubscribe from the topic
unsubscribeFromTopics(gossipSub, @[topic])

# Verify the topic is removed from relevant structures
check topic notin gossipSub.topics
AlejandroCabeza marked this conversation as resolved.
Show resolved Hide resolved
check topic notin gossipSub.mesh
check topic in gossipSub.gossipsub

# The topic should remain in gossipsub
await allFuturesThrowing(conns.mapIt(it.close()))
await gossipSub.switch.stop()

# Test subscribing and unsubscribing multiple topics
asyncTest "handle SUBSCRIBE and UNSUBSCRIBE multiple topics":
let topics = ["topic1", "topic2", "topic3"].toSeq()
let (gossipSub, conns) = setupGossipSub(topics, 5)

# Subscribe to multiple topics
subscribeToTopics(gossipSub, topics)

# Verify that all topics are added to the topics and gossipsub
check gossipSub.topics.len == 3
for topic in topics:
check gossipSub.gossipsub[topic].len() == 5
AlejandroCabeza marked this conversation as resolved.
Show resolved Hide resolved

# Unsubscribe from all topics
unsubscribeFromTopics(gossipSub, topics)

# Ensure topics are removed from topics and mesh, but still present in gossipsub
for topic in topics:
check topic notin gossipSub.topics
check topic notin gossipSub.mesh
check topic in gossipSub.gossipsub

await allFuturesThrowing(conns.mapIt(it.close()))
await gossipSub.switch.stop()

# Test ensuring that the number of subscriptions does not exceed the limit set in the GossipSub parameters
asyncTest "subscription limit test":
let topicCount = 15 # Total number of topics to be tested
let gossipSubParams = 10 # Subscription limit for the topics
let topicNames = toSeq(mapIt(0 .. topicCount - 1, "topic" & $it))

# Use setupGossipSub to initialize the GossipSub system with connections
let (gossipSub, conns) = setupGossipSub(topicNames, 0) # No peers for now

gossipSub.topicsHigh = gossipSubParams # Set the subscription limit

for topic in topicNames:
if gossipSub.topics.len < gossipSub.topicsHigh:
AlejandroCabeza marked this conversation as resolved.
Show resolved Hide resolved
AlejandroCabeza marked this conversation as resolved.
Show resolved Hide resolved
AlejandroCabeza marked this conversation as resolved.
Show resolved Hide resolved
gossipSub.subscribe(
topic,
proc(topic: string, data: seq[byte]): Future[void] {.async.} =
discard
,
)
else:
# Assert that no subscription happens beyond the limit with custom message
doAssert gossipSub.topics.len == gossipSub.topicsHigh,
"Subscription limit exceeded for topic: " & topic

# Ensure that the number of subscribed topics does not exceed the limit
doAssert gossipSub.topics.len <= gossipSub.topicsHigh
doAssert gossipSub.topics.len == gossipSub.topicsHigh

await allFuturesThrowing(conns.mapIt(it.close()))
await gossipSub.switch.stop()

# Test for verifying peers joining a topic using `JOIN(topic)`
asyncTest "handle JOIN topic and mesh is updated":
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the difference between this case and the handle SUBSCRIBE to the topic one?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The first test is primarily about verifying mesh behavior after joining.
The second test is broader and checks both mesh and gossipsub structures to ensure proper subscription handling.

In short, the second test provides a more thorough validation by checking both the mesh and gossipsub structures, while the first test is specifically focused on the mesh when peers join a topic.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you might be able to condense the two cases into one.

Are they two different cases in the test plans?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There were 6 TC on documentation, and I followed the same.
Let me know if this is not required now will remove it

let topic = "test-join-topic"

# Initialize the GossipSub system and simulate peer connections
let (gossipSub, conns) = setupGossipSub(topic, 5)

# Simulate peer joining the topic using commonSubscribe
commonSubscribe(@[gossipSub], topic, voidTopicHandler)

# Check that peers are added to the mesh and the topic is tracked
check gossipSub.mesh[topic].len == 5
check gossipSub.topics.contains(topic)

await allFuturesThrowing(conns.mapIt(it.close()))
await gossipSub.switch.stop()

# Test for verifying peers leaving a topic using `LEAVE(topic)`
asyncTest "multiple peers join and leave topic simultaneously":
let
numberOfNodes = 6
topic = "foobar"
var nodes = newSeq[TestGossipSub]()

# Initialize each node and start the switch
for i in 0 ..< numberOfNodes:
let (gossipSub, _) = setupGossipSub(topic, 5)
nodes.add(gossipSub) # Add the gossipSub instance to the sequence
await gossipSub.switch.start()
AlejandroCabeza marked this conversation as resolved.
Show resolved Hide resolved

# Subscribe all nodes to the topic using the commonSubscribe method
AlejandroCabeza marked this conversation as resolved.
Show resolved Hide resolved
commonSubscribe(nodes, topic, voidTopicHandler)

# Allow time for subscription propagation
await sleepAsync(2 * DURATION_TIMEOUT)

# Ensure that all nodes are subscribed to the topic
for i in 0 ..< numberOfNodes:
let currentGossip = nodes[i]
doAssert currentGossip.gossipsub.hasKey(topic), "Node is not subscribed to the topic"
AlejandroCabeza marked this conversation as resolved.
Show resolved Hide resolved

# Allow time for mesh stabilization
await sleepAsync(2 * DURATION_TIMEOUT)

# Print the mesh size for all nodes before unsubscription
for i in 0 ..< numberOfNodes:
let currentGossip = nodes[i]
echo "Node ", i, " mesh size: ", currentGossip.mesh.getOrDefault(topic).len
AlejandroCabeza marked this conversation as resolved.
Show resolved Hide resolved

# Expected number of peers in the mesh
let expectedNumberOfPeers = numberOfNodes - 1
for i in 0 ..< numberOfNodes:
let currentGossip = nodes[i]
check:
currentGossip.gossipsub[topic].len == expectedNumberOfPeers
currentGossip.mesh[topic].len == expectedNumberOfPeers
currentGossip.fanout.len == 0

# Simulate unsubscription of 3 peers
let peersToUnsubscribe = nodes[0].mesh[topic].toSeq()[0 .. 2]

# Unsubscribe these peers from all the nodes
for node in nodes:
for peer in peersToUnsubscribe:
node.unsubscribe(topic, voidTopicHandler)
echo "Unsubscribing peer: ", peer.peerId
AlejandroCabeza marked this conversation as resolved.
Show resolved Hide resolved

# Allow time for heartbeat to adjust the mesh
await sleepAsync(3 * DURATION_TIMEOUT)

# Check the mesh size for the first node after unsubscription
let firstNodeGossip = nodes[0]
echo "Mesh size after unsubscription: ",
firstNodeGossip.mesh.getOrDefault(topic).len
doAssert firstNodeGossip.mesh.getOrDefault(topic).len == 3,
"Expected 3 peers to remain in the mesh"
AlejandroCabeza marked this conversation as resolved.
Show resolved Hide resolved

# Assert that unsubscribed peers are no longer in the mesh
for peer in peersToUnsubscribe:
for node in nodes:
doAssert not node.mesh[topic].contains(peer),
"Unsubscribed peer should not be in the mesh"

await allFuturesThrowing(nodes.mapIt(allFutures(it.switch.stop())))
Loading