Skip to content

Commit 5f0a441

Browse files
committed
whisper: fixed broadcast race
Whisper's expire and broadcast loops happen in two separate go routines. Whenever an envelope is being expired it's removed from the set of envelopes and it looses all information about the envelope, including the "known hash". After the envelope has been removed it can be re-accepted by a broadcasting peer putting back the envelope in the set of envelopes. Since the envelope broadcast loop is separate of the expire loop expired messages may be broadcast to other peer, resulting in messages **never** being dropped. This PR includes an expire check before adding new messages to the set of envelopes.
1 parent 4c2933a commit 5f0a441

3 files changed

Lines changed: 19 additions & 2 deletions

File tree

‎whisper/peer_test.go‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -239,14 +239,17 @@ func TestPeerMessageExpiration(t *testing.T) {
239239
}
240240
payload := []interface{}{envelope}
241241
if err := p2p.ExpectMsg(tester.stream, messagesCode, payload); err != nil {
242-
t.Fatalf("message mismatch: %v", err)
242+
// A premature empty message may have been broadcast, check the next too
243+
if err := p2p.ExpectMsg(tester.stream, messagesCode, payload); err != nil {
244+
t.Fatalf("message mismatch: %v", err)
245+
}
243246
}
244247
// Check that the message is inside the cache
245248
if !peer.known.Has(envelope.Hash()) {
246249
t.Fatalf("message not found in cache")
247250
}
248251
// Discard messages until expiration and check cache again
249-
exp := time.Now().Add(time.Second + expirationCycle)
252+
exp := time.Now().Add(time.Second + 2*expirationCycle + 100*time.Millisecond)
250253
for time.Now().Before(exp) {
251254
if err := p2p.ExpectMsg(tester.stream, messagesCode, []interface{}{}); err != nil {
252255
t.Fatalf("message mismatch: %v", err)

‎whisper/whisper.go‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,11 @@ func (self *Whisper) add(envelope *Envelope) error {
234234
self.poolMu.Lock()
235235
defer self.poolMu.Unlock()
236236

237+
// short circuit when a received envelope has already expired
238+
if envelope.Expiry <= uint32(time.Now().Unix()) {
239+
return nil
240+
}
241+
237242
// Insert the message into the tracked pool
238243
hash := envelope.Hash()
239244
if _, ok := self.messages[hash]; ok {

‎whisper/whisper_test.go‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,4 +207,13 @@ func TestMessageExpiration(t *testing.T) {
207207
if found {
208208
t.Fatalf("message not expired from cache")
209209
}
210+
211+
node.add(envelope)
212+
node.poolMu.RLock()
213+
_, found = node.messages[envelope.Hash()]
214+
node.poolMu.RUnlock()
215+
if found {
216+
t.Fatalf("message was added to cache")
217+
}
218+
210219
}

0 commit comments

Comments
 (0)