-
Notifications
You must be signed in to change notification settings - Fork 244
/
filters_manager.go
622 lines (503 loc) · 13.8 KB
/
filters_manager.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
package transport
import (
"crypto/ecdsa"
"encoding/hex"
"sync"
"github.com/pkg/errors"
"go.uber.org/zap"
"github.com/status-im/status-go/eth-node/types"
)
const (
minPow = 0.0
)
type RawFilter struct {
FilterID string
Topic types.TopicType
SymKeyID string
}
type KeysPersistence interface {
All() (map[string][]byte, error)
Add(chatID string, key []byte) error
}
type FiltersService interface {
AddKeyPair(key *ecdsa.PrivateKey) (string, error)
DeleteKeyPair(keyID string) bool
AddSymKeyDirect(key []byte) (string, error)
AddSymKeyFromPassword(password string) (string, error)
GetSymKey(id string) ([]byte, error)
DeleteSymKey(id string) bool
Subscribe(opts *types.SubscriptionOptions) (string, error)
Unsubscribe(id string) error
UnsubscribeMany(ids []string) error
}
type FiltersManager struct {
service FiltersService
persistence KeysPersistence
privateKey *ecdsa.PrivateKey
keys map[string][]byte // a cache of symmetric manager derived from passwords
logger *zap.Logger
mutex sync.Mutex
filters map[string]*Filter
}
// NewFiltersManager returns a new filtersManager.
func NewFiltersManager(persistence KeysPersistence, service FiltersService, privateKey *ecdsa.PrivateKey, logger *zap.Logger) (*FiltersManager, error) {
if logger == nil {
logger = zap.NewNop()
}
keys, err := persistence.All()
if err != nil {
return nil, err
}
return &FiltersManager{
privateKey: privateKey,
service: service,
persistence: persistence,
keys: keys,
filters: make(map[string]*Filter),
logger: logger.With(zap.Namespace("filtersManager")),
}, nil
}
func (f *FiltersManager) Init(
chatIDs []string,
publicKeys []*ecdsa.PublicKey,
) ([]*Filter, error) {
// Load our contact code.
_, err := f.LoadContactCode(&f.privateKey.PublicKey)
if err != nil {
return nil, errors.Wrap(err, "failed to load contact code")
}
// Load partitioned topic.
_, err = f.loadMyPartitioned()
if err != nil {
return nil, err
}
// Add discovery topic.
_, err = f.LoadDiscovery()
if err != nil {
return nil, err
}
// Add public, one-to-one and negotiated filters.
for _, chatID := range chatIDs {
_, err := f.LoadPublic(chatID)
if err != nil {
return nil, err
}
}
for _, publicKey := range publicKeys {
_, err := f.LoadContactCode(publicKey)
if err != nil {
return nil, err
}
}
f.mutex.Lock()
defer f.mutex.Unlock()
var allFilters []*Filter
for _, f := range f.filters {
allFilters = append(allFilters, f)
}
return allFilters, nil
}
func (f *FiltersManager) InitPublicFilters(chatIDs []string) ([]*Filter, error) {
var filters []*Filter
// Add public, one-to-one and negotiated filters.
for _, chatID := range chatIDs {
f, err := f.LoadPublic(chatID)
if err != nil {
return nil, err
}
filters = append(filters, f)
}
return filters, nil
}
func (f *FiltersManager) InitCommunityFilters(pks []*ecdsa.PrivateKey) ([]*Filter, error) {
var filters []*Filter
f.mutex.Lock()
defer f.mutex.Unlock()
for _, pk := range pks {
identityStr := PublicKeyToStr(&pk.PublicKey)
rawFilter, err := f.addAsymmetric(identityStr, pk, true)
if err != nil {
return nil, err
}
filterID := identityStr + "-admin"
filter := &Filter{
ChatID: filterID,
FilterID: rawFilter.FilterID,
Topic: rawFilter.Topic,
Identity: identityStr,
Listen: true,
OneToOne: true,
}
f.filters[filterID] = filter
filters = append(filters, filter)
}
return filters, nil
}
// DEPRECATED
func (f *FiltersManager) InitWithFilters(filters []*Filter) ([]*Filter, error) {
var (
chatIDs []string
publicKeys []*ecdsa.PublicKey
)
for _, filter := range filters {
if filter.Identity != "" && filter.OneToOne {
publicKey, err := StrToPublicKey(filter.Identity)
if err != nil {
return nil, err
}
publicKeys = append(publicKeys, publicKey)
} else if filter.ChatID != "" {
chatIDs = append(chatIDs, filter.ChatID)
}
}
return f.Init(chatIDs, publicKeys)
}
func (f *FiltersManager) Reset() error {
var filters []*Filter
f.mutex.Lock()
for _, f := range f.filters {
filters = append(filters, f)
}
f.mutex.Unlock()
return f.Remove(filters...)
}
func (f *FiltersManager) Filters() (result []*Filter) {
f.mutex.Lock()
defer f.mutex.Unlock()
for _, f := range f.filters {
result = append(result, f)
}
return
}
func (f *FiltersManager) Filter(chatID string) *Filter {
f.mutex.Lock()
defer f.mutex.Unlock()
return f.filters[chatID]
}
// FilterByFilterID returns a Filter with a given Whisper filter ID.
func (f *FiltersManager) FilterByFilterID(filterID string) *Filter {
f.mutex.Lock()
defer f.mutex.Unlock()
for _, f := range f.filters {
if f.FilterID == filterID {
return f
}
}
return nil
}
// FiltersByIdentities returns an array of filters for given list of public keys
func (f *FiltersManager) FiltersByIdentities(identities []string) []*Filter {
f.mutex.Lock()
defer f.mutex.Unlock()
identitiesMap := make(map[string]bool)
for _, identity := range identities {
identitiesMap[identity] = true
}
var filters []*Filter
for _, filter := range f.filters {
// Pre-pend 0x before comparing
if identitiesMap["0x"+filter.Identity] {
filters = append(filters, filter)
}
}
return filters
}
// FilterByChatID returns a Filter for given chat id
func (f *FiltersManager) FilterByChatID(chatID string) *Filter {
f.mutex.Lock()
defer f.mutex.Unlock()
return f.filters[chatID]
}
// Remove remove all the filters associated with a chat/identity
func (f *FiltersManager) Remove(filters ...*Filter) error {
f.mutex.Lock()
defer f.mutex.Unlock()
for _, filter := range filters {
if err := f.service.Unsubscribe(filter.FilterID); err != nil {
return err
}
if filter.SymKeyID != "" {
f.service.DeleteSymKey(filter.SymKeyID)
}
delete(f.filters, filter.ChatID)
}
return nil
}
// Remove remove all the filters associated with a chat/identity
func (f *FiltersManager) RemoveNoListenFilters() error {
f.mutex.Lock()
defer f.mutex.Unlock()
var filterIDs []string
var filters []*Filter
for _, f := range filters {
if !f.Listen {
filterIDs = append(filterIDs, f.FilterID)
filters = append(filters, f)
}
}
if err := f.service.UnsubscribeMany(filterIDs); err != nil {
return err
}
for _, filter := range filters {
if filter.SymKeyID != "" {
f.service.DeleteSymKey(filter.SymKeyID)
}
delete(f.filters, filter.ChatID)
}
return nil
}
// Remove remove all the filters associated with a chat/identity
func (f *FiltersManager) RemoveFilterByChatID(chatID string) (*Filter, error) {
f.mutex.Lock()
filter, ok := f.filters[chatID]
f.mutex.Unlock()
if !ok {
return nil, nil
}
err := f.Remove(filter)
if err != nil {
return nil, err
}
return filter, nil
}
// LoadPartitioned creates a filter for a partitioned topic.
func (f *FiltersManager) LoadPartitioned(publicKey *ecdsa.PublicKey, identity *ecdsa.PrivateKey, listen bool) (*Filter, error) {
return f.loadPartitioned(publicKey, identity, listen, false)
}
// LoadEphemeral creates a filter for a partitioned/personal topic.
func (f *FiltersManager) LoadEphemeral(publicKey *ecdsa.PublicKey, identity *ecdsa.PrivateKey, listen bool) (*Filter, error) {
return f.loadPartitioned(publicKey, identity, listen, true)
}
// LoadPersonal creates a filter for a personal topic.
func (f *FiltersManager) LoadPersonal(publicKey *ecdsa.PublicKey, identity *ecdsa.PrivateKey, listen bool) (*Filter, error) {
f.mutex.Lock()
defer f.mutex.Unlock()
chatID := PersonalDiscoveryTopic(publicKey)
if _, ok := f.filters[chatID]; ok {
return f.filters[chatID], nil
}
// We set up a filter so we can publish,
// but we discard envelopes if listen is false.
filter, err := f.addAsymmetric(chatID, identity, listen)
if err != nil {
return nil, err
}
chat := &Filter{
ChatID: chatID,
FilterID: filter.FilterID,
Topic: filter.Topic,
Identity: PublicKeyToStr(publicKey),
Listen: listen,
OneToOne: true,
}
f.filters[chatID] = chat
return chat, nil
}
func (f *FiltersManager) loadMyPartitioned() (*Filter, error) {
return f.loadPartitioned(&f.privateKey.PublicKey, f.privateKey, true, false)
}
func (f *FiltersManager) loadPartitioned(publicKey *ecdsa.PublicKey, identity *ecdsa.PrivateKey, listen, ephemeral bool) (*Filter, error) {
f.mutex.Lock()
defer f.mutex.Unlock()
chatID := PartitionedTopic(publicKey)
if _, ok := f.filters[chatID]; ok {
return f.filters[chatID], nil
}
// We set up a filter so we can publish,
// but we discard envelopes if listen is false.
filter, err := f.addAsymmetric(chatID, identity, listen)
if err != nil {
return nil, err
}
chat := &Filter{
ChatID: chatID,
FilterID: filter.FilterID,
Topic: filter.Topic,
Identity: PublicKeyToStr(publicKey),
Listen: listen,
Ephemeral: ephemeral,
OneToOne: true,
}
f.filters[chatID] = chat
return chat, nil
}
// LoadNegotiated loads a negotiated secret as a filter.
func (f *FiltersManager) LoadNegotiated(secret types.NegotiatedSecret) (*Filter, error) {
f.mutex.Lock()
defer f.mutex.Unlock()
chatID := NegotiatedTopic(secret.PublicKey)
if _, ok := f.filters[chatID]; ok {
return f.filters[chatID], nil
}
keyString := hex.EncodeToString(secret.Key)
filter, err := f.addSymmetric(keyString)
if err != nil {
return nil, err
}
chat := &Filter{
ChatID: chatID,
Topic: filter.Topic,
SymKeyID: filter.SymKeyID,
FilterID: filter.FilterID,
Identity: PublicKeyToStr(secret.PublicKey),
Negotiated: true,
Listen: true,
OneToOne: true,
}
f.filters[chat.ChatID] = chat
return chat, nil
}
// LoadDiscovery adds 1 discovery filter
// for the personal discovery topic.
func (f *FiltersManager) LoadDiscovery() ([]*Filter, error) {
f.mutex.Lock()
defer f.mutex.Unlock()
personalDiscoveryTopic := PersonalDiscoveryTopic(&f.privateKey.PublicKey)
// Check if filters are already loaded.
var result []*Filter
expectedTopicCount := 1
if chat, ok := f.filters[personalDiscoveryTopic]; ok {
result = append(result, chat)
}
if len(result) == expectedTopicCount {
return result, nil
}
identityStr := PublicKeyToStr(&f.privateKey.PublicKey)
// Load personal discovery
personalDiscoveryChat := &Filter{
ChatID: personalDiscoveryTopic,
Identity: identityStr,
Discovery: true,
Listen: true,
OneToOne: true,
}
discoveryResponse, err := f.addAsymmetric(personalDiscoveryChat.ChatID, f.privateKey, true)
if err != nil {
return nil, err
}
personalDiscoveryChat.Topic = discoveryResponse.Topic
personalDiscoveryChat.FilterID = discoveryResponse.FilterID
f.filters[personalDiscoveryChat.ChatID] = personalDiscoveryChat
return []*Filter{personalDiscoveryChat}, nil
}
func (f *FiltersManager) PersonalTopicFilter() *Filter {
personalDiscoveryTopic := PersonalDiscoveryTopic(&f.privateKey.PublicKey)
return f.filters[personalDiscoveryTopic]
}
// LoadPublic adds a filter for a public chat.
func (f *FiltersManager) LoadPublic(chatID string) (*Filter, error) {
f.mutex.Lock()
defer f.mutex.Unlock()
if chat, ok := f.filters[chatID]; ok {
return chat, nil
}
filterAndTopic, err := f.addSymmetric(chatID)
if err != nil {
return nil, err
}
chat := &Filter{
ChatID: chatID,
FilterID: filterAndTopic.FilterID,
SymKeyID: filterAndTopic.SymKeyID,
Topic: filterAndTopic.Topic,
Listen: true,
OneToOne: false,
}
f.filters[chatID] = chat
return chat, nil
}
// LoadContactCode creates a filter for the advertise topic for a given public key.
func (f *FiltersManager) LoadContactCode(pubKey *ecdsa.PublicKey) (*Filter, error) {
f.mutex.Lock()
defer f.mutex.Unlock()
chatID := ContactCodeTopic(pubKey)
if _, ok := f.filters[chatID]; ok {
return f.filters[chatID], nil
}
contactCodeFilter, err := f.addSymmetric(chatID)
if err != nil {
return nil, err
}
chat := &Filter{
ChatID: chatID,
FilterID: contactCodeFilter.FilterID,
Topic: contactCodeFilter.Topic,
SymKeyID: contactCodeFilter.SymKeyID,
Identity: PublicKeyToStr(pubKey),
Listen: true,
}
f.filters[chatID] = chat
return chat, nil
}
// addSymmetric adds a symmetric key filter
func (f *FiltersManager) addSymmetric(chatID string) (*RawFilter, error) {
var symKeyID string
var err error
topic := ToTopic(chatID)
topics := [][]byte{topic}
symKey, ok := f.keys[chatID]
if ok {
symKeyID, err = f.service.AddSymKeyDirect(symKey)
if err != nil {
return nil, err
}
} else {
symKeyID, err = f.service.AddSymKeyFromPassword(chatID)
if err != nil {
return nil, err
}
if symKey, err = f.service.GetSymKey(symKeyID); err != nil {
return nil, err
}
f.keys[chatID] = symKey
err = f.persistence.Add(chatID, symKey)
if err != nil {
return nil, err
}
}
id, err := f.service.Subscribe(&types.SubscriptionOptions{
SymKeyID: symKeyID,
PoW: minPow,
Topics: topics,
})
if err != nil {
return nil, err
}
return &RawFilter{
FilterID: id,
SymKeyID: symKeyID,
Topic: types.BytesToTopic(topic),
}, nil
}
// addAsymmetricFilter adds a filter with our private key
// and set minPow according to the listen parameter.
func (f *FiltersManager) addAsymmetric(chatID string, identity *ecdsa.PrivateKey, listen bool) (*RawFilter, error) {
var (
err error
pow = 1.0 // use PoW high enough to discard all messages for the filter
)
if listen {
pow = minPow
}
topic := ToTopic(chatID)
topics := [][]byte{topic}
privateKeyID, err := f.service.AddKeyPair(identity)
if err != nil {
return nil, err
}
id, err := f.service.Subscribe(&types.SubscriptionOptions{
PrivateKeyID: privateKeyID,
PoW: pow,
Topics: topics,
})
if err != nil {
return nil, err
}
return &RawFilter{FilterID: id, Topic: types.BytesToTopic(topic)}, nil
}
// GetNegotiated returns a negotiated chat given an identity
func (f *FiltersManager) GetNegotiated(identity *ecdsa.PublicKey) *Filter {
f.mutex.Lock()
defer f.mutex.Unlock()
return f.filters[NegotiatedTopic(identity)]
}