-
Notifications
You must be signed in to change notification settings - Fork 244
/
filters_manager.go
477 lines (385 loc) · 10.4 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
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
}
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 (s *FiltersManager) Init(
chatIDs []string,
publicKeys []*ecdsa.PublicKey,
) ([]*Filter, error) {
logger := s.logger.With(zap.String("site", "Init"))
logger.Info("initializing")
// Load our contact code.
_, err := s.LoadContactCode(&s.privateKey.PublicKey)
if err != nil {
return nil, errors.Wrap(err, "failed to load contact code")
}
// Load partitioned topic.
_, err = s.loadMyPartitioned()
if err != nil {
return nil, err
}
// Add discovery topic.
_, err = s.LoadDiscovery()
if err != nil {
return nil, err
}
// Add public, one-to-one and negotiated filters.
for _, chatID := range chatIDs {
_, err := s.LoadPublic(chatID)
if err != nil {
return nil, err
}
}
for _, publicKey := range publicKeys {
_, err := s.LoadContactCode(publicKey)
if err != nil {
return nil, err
}
}
s.mutex.Lock()
defer s.mutex.Unlock()
var allFilters []*Filter
for _, f := range s.filters {
allFilters = append(allFilters, f)
}
return allFilters, nil
}
// DEPRECATED
func (s *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 s.Init(chatIDs, publicKeys)
}
func (s *FiltersManager) Reset() error {
var filters []*Filter
s.mutex.Lock()
for _, f := range s.filters {
filters = append(filters, f)
}
s.mutex.Unlock()
return s.Remove(filters...)
}
func (s *FiltersManager) Filters() (result []*Filter) {
s.mutex.Lock()
defer s.mutex.Unlock()
for _, f := range s.filters {
result = append(result, f)
}
return
}
func (s *FiltersManager) Filter(chatID string) *Filter {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.filters[chatID]
}
// FilterByFilterID returns a Filter with a given Whisper filter ID.
func (s *FiltersManager) FilterByFilterID(filterID string) *Filter {
s.mutex.Lock()
defer s.mutex.Unlock()
for _, f := range s.filters {
if f.FilterID == filterID {
return f
}
}
return nil
}
func (s *FiltersManager) FiltersByPublicKey(publicKey *ecdsa.PublicKey) (result []*Filter) {
s.mutex.Lock()
defer s.mutex.Unlock()
identityStr := PublicKeyToStr(publicKey)
for _, f := range s.filters {
if f.Identity == identityStr {
result = append(result, f)
}
}
return
}
// Remove remove all the filters associated with a chat/identity
func (s *FiltersManager) Remove(filters ...*Filter) error {
s.mutex.Lock()
defer s.mutex.Unlock()
for _, f := range filters {
if err := s.service.Unsubscribe(f.FilterID); err != nil {
return err
}
if f.SymKeyID != "" {
s.service.DeleteSymKey(f.SymKeyID)
}
delete(s.filters, f.ChatID)
}
return nil
}
// LoadPartitioned creates a filter for a partitioned topic.
func (s *FiltersManager) LoadPartitioned(publicKey *ecdsa.PublicKey, identity *ecdsa.PrivateKey, listen bool) (*Filter, error) {
return s.loadPartitioned(publicKey, identity, listen)
}
func (s *FiltersManager) loadMyPartitioned() (*Filter, error) {
return s.loadPartitioned(&s.privateKey.PublicKey, s.privateKey, true)
}
func (s *FiltersManager) loadPartitioned(publicKey *ecdsa.PublicKey, identity *ecdsa.PrivateKey, listen bool) (*Filter, error) {
s.mutex.Lock()
defer s.mutex.Unlock()
chatID := PartitionedTopic(publicKey)
if _, ok := s.filters[chatID]; ok {
return s.filters[chatID], nil
}
// We set up a filter so we can publish,
// but we discard envelopes if listen is false.
filter, err := s.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,
}
s.filters[chatID] = chat
return chat, nil
}
// LoadNegotiated loads a negotiated secret as a filter.
func (s *FiltersManager) LoadNegotiated(secret types.NegotiatedSecret) (*Filter, error) {
s.mutex.Lock()
defer s.mutex.Unlock()
chatID := NegotiatedTopic(secret.PublicKey)
if _, ok := s.filters[chatID]; ok {
return s.filters[chatID], nil
}
keyString := hex.EncodeToString(secret.Key)
filter, err := s.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,
}
s.filters[chat.ChatID] = chat
return chat, nil
}
// LoadDiscovery adds 1 discovery filter
// for the personal discovery topic.
func (s *FiltersManager) LoadDiscovery() ([]*Filter, error) {
s.mutex.Lock()
defer s.mutex.Unlock()
personalDiscoveryTopic := PersonalDiscoveryTopic(&s.privateKey.PublicKey)
// Check if filters are already loaded.
var result []*Filter
expectedTopicCount := 1
if chat, ok := s.filters[personalDiscoveryTopic]; ok {
result = append(result, chat)
}
if len(result) == expectedTopicCount {
return result, nil
}
identityStr := PublicKeyToStr(&s.privateKey.PublicKey)
// Load personal discovery
personalDiscoveryChat := &Filter{
ChatID: personalDiscoveryTopic,
Identity: identityStr,
Discovery: true,
Listen: true,
OneToOne: true,
}
discoveryResponse, err := s.addAsymmetric(personalDiscoveryChat.ChatID, s.privateKey, true)
if err != nil {
return nil, err
}
personalDiscoveryChat.Topic = discoveryResponse.Topic
personalDiscoveryChat.FilterID = discoveryResponse.FilterID
s.filters[personalDiscoveryChat.ChatID] = personalDiscoveryChat
return []*Filter{personalDiscoveryChat}, nil
}
// LoadPublic adds a filter for a public chat.
func (s *FiltersManager) LoadPublic(chatID string) (*Filter, error) {
s.mutex.Lock()
defer s.mutex.Unlock()
if chat, ok := s.filters[chatID]; ok {
return chat, nil
}
filterAndTopic, err := s.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,
}
s.filters[chatID] = chat
return chat, nil
}
// LoadContactCode creates a filter for the advertise topic for a given public key.
func (s *FiltersManager) LoadContactCode(pubKey *ecdsa.PublicKey) (*Filter, error) {
s.mutex.Lock()
defer s.mutex.Unlock()
chatID := ContactCodeTopic(pubKey)
if _, ok := s.filters[chatID]; ok {
return s.filters[chatID], nil
}
contactCodeFilter, err := s.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,
}
s.filters[chatID] = chat
return chat, nil
}
// addSymmetric adds a symmetric key filter
func (s *FiltersManager) addSymmetric(chatID string) (*RawFilter, error) {
var symKeyID string
var err error
topic := ToTopic(chatID)
topics := [][]byte{topic}
symKey, ok := s.keys[chatID]
if ok {
symKeyID, err = s.service.AddSymKeyDirect(symKey)
if err != nil {
return nil, err
}
} else {
symKeyID, err = s.service.AddSymKeyFromPassword(chatID)
if err != nil {
return nil, err
}
if symKey, err = s.service.GetSymKey(symKeyID); err != nil {
return nil, err
}
s.keys[chatID] = symKey
err = s.persistence.Add(chatID, symKey)
if err != nil {
return nil, err
}
}
id, err := s.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 (s *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 := s.service.AddKeyPair(identity)
if err != nil {
return nil, err
}
id, err := s.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 (s *FiltersManager) GetNegotiated(identity *ecdsa.PublicKey) *Filter {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.filters[NegotiatedTopic(identity)]
}