Skip to content

Commit

Permalink
fix: message cache removal crash (#2682)
Browse files Browse the repository at this point in the history
  • Loading branch information
SionoiS authored and Ivansete-status committed May 14, 2024
1 parent bff7564 commit e290a52
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
40 changes: 39 additions & 1 deletion tests/test_message_cache.nim
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
{.used.}

import std/sets, stew/[results, byteutils], testutils/unittests
import std/[sets, random], stew/[results, byteutils], testutils/unittests
import ../../waku/waku_core, ../../waku/waku_api/message_cache, ./testlib/wakucore

randomize()

suite "MessageCache":
setup:
## Given
Expand Down Expand Up @@ -209,3 +211,39 @@ suite "MessageCache":

check:
cache.messagesCount() == 2

test "fuzzing":
let testContentTopic1 = "contentTopic1"
let testContentTopic2 = "contentTopic2"

let cache = MessageCache.init(50)

cache.contentSubscribe(testContentTopic1)
cache.contentSubscribe(testContentTopic2)

for _ in 0 .. 10000:
let numb = rand(1.0)

if numb > 0.4:
let topic = if rand(1.0) > 0.5: testContentTopic1 else: testContentTopic2

let testMessage = fakeWakuMessage(contentTopic = topic)

cache.addMessage(DefaultPubsubTopic, testMessage)
elif numb > 0.1:
let topic = if rand(1.0) > 0.5: testContentTopic1 else: testContentTopic2

let clear = rand(1.0) > 0.5
discard cache.getAutoMessages(topic, clear)
elif numb > 0.05:
if rand(1.0) > 0.5:
cache.pubsubUnsubscribe(DefaultPubsubTopic)
else:
cache.pubsubSubscribe(DefaultPubsubTopic)
else:
let topic = if rand(1.0) > 0.5: testContentTopic1 else: testContentTopic2

if rand(1.0) > 0.5:
cache.contentUnsubscribe(topic)
else:
cache.contentSubscribe(topic)
6 changes: 3 additions & 3 deletions waku/waku_api/message_cache.nim
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ proc pubsubUnsubscribe*(self: MessageCache, pubsubTopic: PubsubTopic) =
dec(j)

# check if messages on this pubsub topic are indexed by any content topic, if not remove them.
for mId in msgIndices:
for mId in msgIndices.sorted(SortOrder.Descending):
if not self.contentIndex.anyIt(it.msgIdx == mId):
self.removeMessage(mId)

Expand Down Expand Up @@ -167,7 +167,7 @@ proc contentUnsubscribe*(self: MessageCache, contentTopic: ContentTopic) =
dec(j)

# check if messages on this content topic are indexed by any pubsub topic, if not remove them.
for mId in msgIndices:
for mId in msgIndices.sorted(SortOrder.Descending):
if not self.pubsubIndex.anyIt(it.msgIdx == mId):
self.removeMessage(mId)

Expand Down Expand Up @@ -275,7 +275,7 @@ proc getAutoMessages*(
let messages = msgIndices.mapIt(self.messages[it])

if clear:
for idx in msgIndices.reversed:
for idx in msgIndices.sorted(SortOrder.Descending):
self.removeMessage(idx)

return ok(messages)

0 comments on commit e290a52

Please sign in to comment.