Skip to content

Commit 9b4e182

Browse files
authored
Merge pull request ethereum#16210 from gluk256/288-filter-optimization
whisper: message filtering optimization Only run the message through filters who registered their interest.
2 parents 52bb0a1 + d24d10a commit 9b4e182

File tree

4 files changed

+76
-78
lines changed

4 files changed

+76
-78
lines changed

whisper/whisperv6/filter.go

Lines changed: 63 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ type Filter struct {
3535
PoW float64 // Proof of work as described in the Whisper spec
3636
AllowP2P bool // Indicates whether this filter is interested in direct peer-to-peer messages
3737
SymKeyHash common.Hash // The Keccak256Hash of the symmetric key, needed for optimization
38+
id string // unique identifier
3839

3940
Messages map[common.Hash]*ReceivedMessage
4041
mutex sync.RWMutex
@@ -43,15 +44,21 @@ type Filter struct {
4344
// Filters represents a collection of filters
4445
type Filters struct {
4546
watchers map[string]*Filter
46-
whisper *Whisper
47-
mutex sync.RWMutex
47+
48+
topicMatcher map[TopicType]map[*Filter]struct{} // map a topic to the filters that are interested in being notified when a message matches that topic
49+
allTopicsMatcher map[*Filter]struct{} // list all the filters that will be notified of a new message, no matter what its topic is
50+
51+
whisper *Whisper
52+
mutex sync.RWMutex
4853
}
4954

5055
// NewFilters returns a newly created filter collection
5156
func NewFilters(w *Whisper) *Filters {
5257
return &Filters{
53-
watchers: make(map[string]*Filter),
54-
whisper: w,
58+
watchers: make(map[string]*Filter),
59+
topicMatcher: make(map[TopicType]map[*Filter]struct{}),
60+
allTopicsMatcher: make(map[*Filter]struct{}),
61+
whisper: w,
5562
}
5663
}
5764

@@ -81,7 +88,9 @@ func (fs *Filters) Install(watcher *Filter) (string, error) {
8188
watcher.SymKeyHash = crypto.Keccak256Hash(watcher.KeySym)
8289
}
8390

91+
watcher.id = id
8492
fs.watchers[id] = watcher
93+
fs.addTopicMatcher(watcher)
8594
return id, err
8695
}
8796

@@ -91,12 +100,51 @@ func (fs *Filters) Uninstall(id string) bool {
91100
fs.mutex.Lock()
92101
defer fs.mutex.Unlock()
93102
if fs.watchers[id] != nil {
103+
fs.removeFromTopicMatchers(fs.watchers[id])
94104
delete(fs.watchers, id)
95105
return true
96106
}
97107
return false
98108
}
99109

110+
// addTopicMatcher adds a filter to the topic matchers.
111+
// If the filter's Topics array is empty, it will be tried on every topic.
112+
// Otherwise, it will be tried on the topics specified.
113+
func (fs *Filters) addTopicMatcher(watcher *Filter) {
114+
if len(watcher.Topics) == 0 {
115+
fs.allTopicsMatcher[watcher] = struct{}{}
116+
} else {
117+
for _, t := range watcher.Topics {
118+
topic := BytesToTopic(t)
119+
if fs.topicMatcher[topic] == nil {
120+
fs.topicMatcher[topic] = make(map[*Filter]struct{})
121+
}
122+
fs.topicMatcher[topic][watcher] = struct{}{}
123+
}
124+
}
125+
}
126+
127+
// removeFromTopicMatchers removes a filter from the topic matchers
128+
func (fs *Filters) removeFromTopicMatchers(watcher *Filter) {
129+
delete(fs.allTopicsMatcher, watcher)
130+
for _, topic := range watcher.Topics {
131+
delete(fs.topicMatcher[BytesToTopic(topic)], watcher)
132+
}
133+
}
134+
135+
// getWatchersByTopic returns a slice containing the filters that
136+
// match a specific topic
137+
func (fs *Filters) getWatchersByTopic(topic TopicType) []*Filter {
138+
res := make([]*Filter, 0, len(fs.allTopicsMatcher))
139+
for watcher := range fs.allTopicsMatcher {
140+
res = append(res, watcher)
141+
}
142+
for watcher := range fs.topicMatcher[topic] {
143+
res = append(res, watcher)
144+
}
145+
return res
146+
}
147+
100148
// Get returns a filter from the collection with a specific ID
101149
func (fs *Filters) Get(id string) *Filter {
102150
fs.mutex.RLock()
@@ -112,11 +160,10 @@ func (fs *Filters) NotifyWatchers(env *Envelope, p2pMessage bool) {
112160
fs.mutex.RLock()
113161
defer fs.mutex.RUnlock()
114162

115-
i := -1 // only used for logging info
116-
for _, watcher := range fs.watchers {
117-
i++
163+
candidates := fs.getWatchersByTopic(env.Topic)
164+
for _, watcher := range candidates {
118165
if p2pMessage && !watcher.AllowP2P {
119-
log.Trace(fmt.Sprintf("msg [%x], filter [%d]: p2p messages are not allowed", env.Hash(), i))
166+
log.Trace(fmt.Sprintf("msg [%x], filter [%s]: p2p messages are not allowed", env.Hash(), watcher.id))
120167
continue
121168
}
122169

@@ -128,10 +175,10 @@ func (fs *Filters) NotifyWatchers(env *Envelope, p2pMessage bool) {
128175
if match {
129176
msg = env.Open(watcher)
130177
if msg == nil {
131-
log.Trace("processing message: failed to open", "message", env.Hash().Hex(), "filter", i)
178+
log.Trace("processing message: failed to open", "message", env.Hash().Hex(), "filter", watcher.id)
132179
}
133180
} else {
134-
log.Trace("processing message: does not match", "message", env.Hash().Hex(), "filter", i)
181+
log.Trace("processing message: does not match", "message", env.Hash().Hex(), "filter", watcher.id)
135182
}
136183
}
137184

@@ -194,44 +241,27 @@ func (f *Filter) Retrieve() (all []*ReceivedMessage) {
194241

195242
// MatchMessage checks if the filter matches an already decrypted
196243
// message (i.e. a Message that has already been handled by
197-
// MatchEnvelope when checked by a previous filter)
244+
// MatchEnvelope when checked by a previous filter).
245+
// Topics are not checked here, since this is done by topic matchers.
198246
func (f *Filter) MatchMessage(msg *ReceivedMessage) bool {
199247
if f.PoW > 0 && msg.PoW < f.PoW {
200248
return false
201249
}
202250

203251
if f.expectsAsymmetricEncryption() && msg.isAsymmetricEncryption() {
204-
return IsPubKeyEqual(&f.KeyAsym.PublicKey, msg.Dst) && f.MatchTopic(msg.Topic)
252+
return IsPubKeyEqual(&f.KeyAsym.PublicKey, msg.Dst)
205253
} else if f.expectsSymmetricEncryption() && msg.isSymmetricEncryption() {
206-
return f.SymKeyHash == msg.SymKeyHash && f.MatchTopic(msg.Topic)
254+
return f.SymKeyHash == msg.SymKeyHash
207255
}
208256
return false
209257
}
210258

211259
// MatchEnvelope checks if it's worth decrypting the message. If
212260
// it returns `true`, client code is expected to attempt decrypting
213261
// the message and subsequently call MatchMessage.
262+
// Topics are not checked here, since this is done by topic matchers.
214263
func (f *Filter) MatchEnvelope(envelope *Envelope) bool {
215-
if f.PoW > 0 && envelope.pow < f.PoW {
216-
return false
217-
}
218-
219-
return f.MatchTopic(envelope.Topic)
220-
}
221-
222-
// MatchTopic checks that the filter captures a given topic.
223-
func (f *Filter) MatchTopic(topic TopicType) bool {
224-
if len(f.Topics) == 0 {
225-
// any topic matches
226-
return true
227-
}
228-
229-
for _, bt := range f.Topics {
230-
if matchSingleTopic(topic, bt) {
231-
return true
232-
}
233-
}
234-
return false
264+
return f.PoW <= 0 || envelope.pow >= f.PoW
235265
}
236266

237267
func matchSingleTopic(topic TopicType, bt []byte) bool {

whisper/whisperv6/filter_test.go

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -303,9 +303,8 @@ func TestMatchEnvelope(t *testing.T) {
303303
t.Fatalf("failed generateMessageParams with seed %d: %s.", seed, err)
304304
}
305305

306-
params.Topic[0] = 0xFF // ensure mismatch
306+
params.Topic[0] = 0xFF // topic mismatch
307307

308-
// mismatch with pseudo-random data
309308
msg, err := NewSentMessage(params)
310309
if err != nil {
311310
t.Fatalf("failed to create new message with seed %d: %s.", seed, err)
@@ -314,14 +313,6 @@ func TestMatchEnvelope(t *testing.T) {
314313
if err != nil {
315314
t.Fatalf("failed Wrap with seed %d: %s.", seed, err)
316315
}
317-
match := fsym.MatchEnvelope(env)
318-
if match {
319-
t.Fatalf("failed MatchEnvelope symmetric with seed %d.", seed)
320-
}
321-
match = fasym.MatchEnvelope(env)
322-
if match {
323-
t.Fatalf("failed MatchEnvelope asymmetric with seed %d.", seed)
324-
}
325316

326317
// encrypt symmetrically
327318
i := mrand.Int() % 4
@@ -337,7 +328,7 @@ func TestMatchEnvelope(t *testing.T) {
337328
}
338329

339330
// symmetric + matching topic: match
340-
match = fsym.MatchEnvelope(env)
331+
match := fsym.MatchEnvelope(env)
341332
if !match {
342333
t.Fatalf("failed MatchEnvelope() symmetric with seed %d.", seed)
343334
}
@@ -396,7 +387,7 @@ func TestMatchEnvelope(t *testing.T) {
396387
// asymmetric + matching topic: match
397388
fasym.Topics[i] = fasym.Topics[i+1]
398389
match = fasym.MatchEnvelope(env)
399-
if match {
390+
if !match {
400391
t.Fatalf("failed MatchEnvelope(asymmetric + matching topic) with seed %d.", seed)
401392
}
402393

@@ -431,7 +422,8 @@ func TestMatchEnvelope(t *testing.T) {
431422
// filter with topic + envelope without topic: mismatch
432423
fasym.Topics = fsym.Topics
433424
match = fasym.MatchEnvelope(env)
434-
if match {
425+
if !match {
426+
// topic mismatch should have no affect, as topics are handled by topic matchers
435427
t.Fatalf("failed MatchEnvelope(filter without topic + envelope without topic) with seed %d.", seed)
436428
}
437429
}
@@ -487,7 +479,8 @@ func TestMatchMessageSym(t *testing.T) {
487479

488480
// topic mismatch
489481
f.Topics[index][0]++
490-
if f.MatchMessage(msg) {
482+
if !f.MatchMessage(msg) {
483+
// topic mismatch should have no affect, as topics are handled by topic matchers
491484
t.Fatalf("failed MatchEnvelope(topic mismatch) with seed %d.", seed)
492485
}
493486
f.Topics[index][0]--
@@ -580,7 +573,8 @@ func TestMatchMessageAsym(t *testing.T) {
580573

581574
// topic mismatch
582575
f.Topics[index][0]++
583-
if f.MatchMessage(msg) {
576+
if !f.MatchMessage(msg) {
577+
// topic mismatch should have no affect, as topics are handled by topic matchers
584578
t.Fatalf("failed MatchEnvelope(topic mismatch) with seed %d.", seed)
585579
}
586580
f.Topics[index][0]--
@@ -829,8 +823,9 @@ func TestVariableTopics(t *testing.T) {
829823

830824
f.Topics[i][lastTopicByte]++
831825
match = f.MatchEnvelope(env)
832-
if match {
833-
t.Fatalf("MatchEnvelope symmetric with seed %d, step %d: false positive.", seed, i)
826+
if !match {
827+
// topic mismatch should have no affect, as topics are handled by topic matchers
828+
t.Fatalf("MatchEnvelope symmetric with seed %d, step %d.", seed, i)
834829
}
835830
}
836831
}

whisper/whisperv6/whisper.go

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -928,24 +928,6 @@ func (whisper *Whisper) Envelopes() []*Envelope {
928928
return all
929929
}
930930

931-
// Messages iterates through all currently floating envelopes
932-
// and retrieves all the messages, that this filter could decrypt.
933-
func (whisper *Whisper) Messages(id string) []*ReceivedMessage {
934-
result := make([]*ReceivedMessage, 0)
935-
whisper.poolMu.RLock()
936-
defer whisper.poolMu.RUnlock()
937-
938-
if filter := whisper.filters.Get(id); filter != nil {
939-
for _, env := range whisper.envelopes {
940-
msg := filter.processEnvelope(env)
941-
if msg != nil {
942-
result = append(result, msg)
943-
}
944-
}
945-
}
946-
return result
947-
}
948-
949931
// isEnvelopeCached checks if envelope with specific hash has already been received and cached.
950932
func (whisper *Whisper) isEnvelopeCached(hash common.Hash) bool {
951933
whisper.poolMu.Lock()

whisper/whisperv6/whisper_test.go

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -75,10 +75,6 @@ func TestWhisperBasic(t *testing.T) {
7575
if len(mail) != 0 {
7676
t.Fatalf("failed w.Envelopes().")
7777
}
78-
m := w.Messages("non-existent")
79-
if len(m) != 0 {
80-
t.Fatalf("failed w.Messages.")
81-
}
8278

8379
derived := pbkdf2.Key([]byte(peerID), nil, 65356, aesKeyLength, sha256.New)
8480
if !validateDataIntegrity(derived, aesKeyLength) {
@@ -593,7 +589,7 @@ func TestCustomization(t *testing.T) {
593589
}
594590

595591
// check w.messages()
596-
id, err := w.Subscribe(f)
592+
_, err = w.Subscribe(f)
597593
if err != nil {
598594
t.Fatalf("failed subscribe with seed %d: %s.", seed, err)
599595
}
@@ -602,11 +598,6 @@ func TestCustomization(t *testing.T) {
602598
if len(mail) > 0 {
603599
t.Fatalf("received premature mail")
604600
}
605-
606-
mail = w.Messages(id)
607-
if len(mail) != 2 {
608-
t.Fatalf("failed to get whisper messages")
609-
}
610601
}
611602

612603
func TestSymmetricSendCycle(t *testing.T) {

0 commit comments

Comments
 (0)