forked from berty/berty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontact_request_manager.go
410 lines (336 loc) · 10.9 KB
/
contact_request_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
package bertyprotocol
import (
"bytes"
"context"
"fmt"
"sync"
ggio "github.com/gogo/protobuf/io"
"github.com/libp2p/go-libp2p-core/crypto"
"github.com/libp2p/go-libp2p-core/network"
"github.com/libp2p/go-libp2p-core/peer"
"go.uber.org/zap"
"moul.io/u"
"berty.tech/berty/v2/go/internal/handshake"
"berty.tech/berty/v2/go/internal/ipfsutil"
"berty.tech/berty/v2/go/pkg/errcode"
"berty.tech/berty/v2/go/pkg/protocoltypes"
)
type pendingRequestDetails struct {
contact *protocoltypes.ShareableContact
ownMetadata []byte
}
type pendingRequest struct {
updateCh chan *pendingRequestDetails
cancelFunc context.CancelFunc
}
type contactRequestsManager struct {
enabled bool
seed []byte
announceCancel context.CancelFunc
metadataStore *metadataStore
lock sync.Mutex
ipfs ipfsutil.ExtendedCoreAPI
accSK crypto.PrivKey
ctx context.Context
logger *zap.Logger
swiper *Swiper
toAdd map[string]*pendingRequest
}
func (c *contactRequestsManager) metadataRequestDisabled(_ *protocoltypes.GroupMetadataEvent) error {
c.enabled = false
if c.announceCancel != nil {
c.announceCancel()
c.ipfs.RemoveStreamHandler(contactRequestV1)
}
c.announceCancel = nil
return nil
}
func (c *contactRequestsManager) metadataRequestEnabled(_ *protocoltypes.GroupMetadataEvent) error {
c.ipfs.SetStreamHandler(contactRequestV1, c.incomingHandler)
c.enabled = true
if c.announceCancel != nil {
return nil
}
return c.enableIncomingRequests()
}
func (c *contactRequestsManager) metadataRequestReset(evt *protocoltypes.GroupMetadataEvent) error {
e := &protocoltypes.AccountContactRequestReferenceReset{}
if err := e.Unmarshal(evt.Event); err != nil {
return errcode.ErrDeserialization.Wrap(err)
}
c.seed = e.PublicRendezvousSeed
if !c.enabled {
return nil
}
return c.enableIncomingRequests()
}
func (c *contactRequestsManager) metadataRequestEnqueued(evt *protocoltypes.GroupMetadataEvent) error {
e := &protocoltypes.AccountContactRequestEnqueued{}
if err := e.Unmarshal(evt.Event); err != nil {
return err
}
return c.enqueueRequest(&protocoltypes.ShareableContact{
PK: e.Contact.PK,
PublicRendezvousSeed: e.Contact.PublicRendezvousSeed,
}, e.OwnMetadata)
}
func (c *contactRequestsManager) metadataRequestSent(evt *protocoltypes.GroupMetadataEvent) error {
e := &protocoltypes.AccountContactRequestSent{}
if err := e.Unmarshal(evt.Event); err != nil {
return err
}
if request, ok := c.toAdd[string(e.ContactPK)]; ok {
request.cancelFunc()
delete(c.toAdd, string(e.ContactPK))
}
return nil
}
func (c *contactRequestsManager) metadataRequestReceived(evt *protocoltypes.GroupMetadataEvent) error {
e := &protocoltypes.AccountContactRequestReceived{}
if err := e.Unmarshal(evt.Event); err != nil {
return err
}
if request, ok := c.toAdd[string(e.ContactPK)]; ok {
request.cancelFunc()
delete(c.toAdd, string(e.ContactPK))
}
return nil
}
func (c *contactRequestsManager) enqueueRequest(contact *protocoltypes.ShareableContact, ownMetadata []byte) error {
pk, err := crypto.UnmarshalEd25519PublicKey(contact.PK)
if err != nil {
return err
}
// contact already queued
if pending, ok := c.toAdd[string(contact.PK)]; ok {
pending.updateCh <- &pendingRequestDetails{
contact: contact,
ownMetadata: ownMetadata,
}
return nil
}
swiperCh := make(chan peer.AddrInfo)
reqCtx, reqCancel := context.WithCancel(c.ctx)
parent := u.NewUniqueChild(context.Background())
var wg sync.WaitGroup
pending := &pendingRequest{
updateCh: make(chan *pendingRequestDetails),
cancelFunc: reqCancel,
}
go func() {
for {
select {
case details := <-pending.updateCh:
wg.Add(1)
parent.SetChild(func(ctx context.Context) {
c.swiper.WatchTopic(
ctx,
details.contact.PK,
details.contact.PublicRendezvousSeed,
swiperCh,
wg.Done,
)
})
case <-reqCtx.Done():
parent.CloseChild()
// drain channel
go func() {
for range swiperCh {
}
}()
wg.Wait()
close(swiperCh)
return
}
}
}()
pending.updateCh <- &pendingRequestDetails{
contact: contact,
ownMetadata: ownMetadata,
}
c.toAdd[string(contact.PK)] = pending
// process addresses from swiper
go func() {
for addr := range swiperCh {
if err := c.ipfs.Swarm().Connect(c.ctx, addr); err != nil {
c.logger.Error("error while connecting with other peer", zap.Error(err))
return
}
stream, err := c.ipfs.NewStream(context.TODO(), addr.ID, contactRequestV1)
if err != nil {
c.logger.Error("error while opening stream with other peer", zap.Error(err))
return
}
if err := c.performSend(pk, stream); err != nil {
c.logger.Error("unable to perform send", zap.Error(err))
}
}
}()
return nil
}
func (c *contactRequestsManager) metadataWatcher(ctx context.Context) {
handlers := map[protocoltypes.EventType]func(*protocoltypes.GroupMetadataEvent) error{
protocoltypes.EventTypeAccountContactRequestDisabled: c.metadataRequestDisabled,
protocoltypes.EventTypeAccountContactRequestEnabled: c.metadataRequestEnabled,
protocoltypes.EventTypeAccountContactRequestReferenceReset: c.metadataRequestReset,
protocoltypes.EventTypeAccountContactRequestOutgoingEnqueued: c.metadataRequestEnqueued,
protocoltypes.EventTypeAccountContactRequestOutgoingSent: c.metadataRequestSent,
protocoltypes.EventTypeAccountContactRequestIncomingReceived: c.metadataRequestReceived,
}
c.lock.Lock()
enabled, contact := c.metadataStore.GetIncomingContactRequestsStatus()
c.enabled = enabled
if contact != nil {
c.seed = contact.PublicRendezvousSeed
}
if c.enabled && len(c.seed) > 0 {
if err := c.metadataRequestEnabled(&protocoltypes.GroupMetadataEvent{}); err != nil {
c.logger.Warn("unable to enable metadata request", zap.Error(err))
}
}
for _, contact := range c.metadataStore.ListContactsByStatus(protocoltypes.ContactStateToRequest) {
ownMeta, err := c.metadataStore.GetRequestOwnMetadataForContact(contact.PK)
if err != nil {
c.logger.Warn("error while retrieving own metadata for contact", zap.Binary("pk", contact.PK), zap.Error(err))
}
if err := c.enqueueRequest(contact, ownMeta); err != nil {
c.logger.Error("unable to enqueue contact request", zap.Error(err))
}
}
c.lock.Unlock()
chSub := c.metadataStore.Subscribe(ctx)
go func() {
for evt := range chSub {
e, ok := evt.(*protocoltypes.GroupMetadataEvent)
if !ok {
continue
}
if _, ok := handlers[e.Metadata.EventType]; !ok {
continue
}
c.logger.Debug("METADATA WATCHER", zap.String("event", e.Metadata.EventType.String()))
c.lock.Lock()
if err := handlers[e.Metadata.EventType](e); err != nil {
c.lock.Unlock()
c.logger.Error("error while handling metadata store event", zap.Error(err))
continue
}
c.lock.Unlock()
}
}()
}
const contactRequestV1 = "/berty/contact_req/1.0.0"
func (c *contactRequestsManager) incomingHandler(stream network.Stream) {
defer func() {
if err := ipfsutil.FullClose(stream); err != nil {
c.logger.Warn("error while closing stream with other peer", zap.Error(err))
}
}()
reader := ggio.NewDelimitedReader(stream, 2048)
writer := ggio.NewDelimitedWriter(stream)
otherPK, err := handshake.ResponseUsingReaderWriter(reader, writer, c.accSK)
if err != nil {
c.logger.Error("an error occurred during handshake", zap.Error(err))
return
}
otherPKBytes, err := otherPK.Raw()
if err != nil {
c.logger.Error("an error occurred during serialization", zap.Error(err))
return
}
contact := &protocoltypes.ShareableContact{}
if err := reader.ReadMsg(contact); err != nil {
c.logger.Error("an error occurred while retrieving contact information", zap.Error(err))
return
}
if err := contact.CheckFormat(protocoltypes.ShareableContactOptionsAllowMissingRDVSeed); err != nil {
c.logger.Error("an error occurred while verifying contact information", zap.Error(err))
return
}
if !bytes.Equal(otherPKBytes, contact.PK) {
c.logger.Error("received contact information does not match handshake data")
return
}
if _, err = c.metadataStore.ContactRequestIncomingReceived(c.ctx, &protocoltypes.ShareableContact{
PK: otherPKBytes,
PublicRendezvousSeed: contact.PublicRendezvousSeed,
Metadata: contact.Metadata,
}); err != nil {
c.logger.Error("an error occurred while adding contact request to received", zap.Error(err))
return
}
}
func (c *contactRequestsManager) performSend(otherPK crypto.PubKey, stream network.Stream) error {
defer func() {
if err := ipfsutil.FullClose(stream); err != nil {
c.logger.Warn("error while closing stream with other peer", zap.Error(err))
}
}()
c.lock.Lock()
if c.metadataStore.checkContactStatus(otherPK, protocoltypes.ContactStateAdded) {
// Nothing to do, contact has already been requested
c.lock.Unlock()
return nil
}
c.lock.Unlock()
_, contact := c.metadataStore.GetIncomingContactRequestsStatus()
if contact == nil {
return fmt.Errorf("unable to retrieve own contact information")
}
pkB, err := otherPK.Raw()
if err != nil {
return fmt.Errorf("unable to get raw pk: %w", err)
}
ownMetadata, err := c.metadataStore.GetRequestOwnMetadataForContact(pkB)
if err != nil {
c.logger.Warn("unable to get own metadata for contact", zap.Error(err))
ownMetadata = nil
}
contact.Metadata = ownMetadata
reader := ggio.NewDelimitedReader(stream, 2048)
writer := ggio.NewDelimitedWriter(stream)
if err := handshake.RequestUsingReaderWriter(reader, writer, c.accSK, otherPK); err != nil {
return fmt.Errorf("an error occurred during handshake: %w", err)
}
if err := writer.WriteMsg(contact); err != nil {
return fmt.Errorf("an error occurred while sending own contact information: %w", err)
}
if _, err := c.metadataStore.ContactRequestOutgoingSent(c.ctx, otherPK); err != nil {
return fmt.Errorf("an error occurred while marking contact request as sent: %w", err)
}
return nil
}
func (c *contactRequestsManager) enableIncomingRequests() error {
c.logger.Debug("enableIncomingRequests start")
if c.announceCancel != nil {
c.announceCancel()
}
c.logger.Debug("enableIncomingRequests get public")
pkBytes, err := c.accSK.GetPublic().Raw()
if err != nil {
return err
}
var ctx context.Context
ctx, c.announceCancel = context.WithCancel(c.ctx)
c.logger.Debug("enableIncomingRequests run announce")
c.swiper.Announce(ctx, pkBytes, c.seed)
c.logger.Debug("enableIncomingRequests end")
return nil
}
func initContactRequestsManager(ctx context.Context, s *Swiper, store *metadataStore, ipfs ipfsutil.ExtendedCoreAPI, logger *zap.Logger) error {
sk, err := store.devKS.AccountPrivKey()
if err != nil {
return err
}
cm := &contactRequestsManager{
metadataStore: store,
ipfs: ipfs,
logger: logger,
accSK: sk,
ctx: ctx,
swiper: s,
toAdd: map[string]*pendingRequest{},
}
go cm.metadataWatcher(ctx)
return nil
}