forked from berty/weshnet
-
Notifications
You must be signed in to change notification settings - Fork 5
/
group_context.go
400 lines (329 loc) · 11 KB
/
group_context.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
package weshnet
import (
"context"
"encoding/base64"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/libp2p/go-libp2p/core/crypto"
"go.uber.org/zap"
"google.golang.org/protobuf/proto"
"berty.tech/go-orbit-db/stores"
"berty.tech/weshnet/v2/pkg/errcode"
"berty.tech/weshnet/v2/pkg/ipfsutil"
"berty.tech/weshnet/v2/pkg/logutil"
"berty.tech/weshnet/v2/pkg/protocoltypes"
"berty.tech/weshnet/v2/pkg/secretstore"
)
type GroupContext struct {
ctx context.Context
cancel context.CancelFunc
group *protocoltypes.Group
metadataStore *MetadataStore
messageStore *MessageStore
secretStore secretstore.SecretStore
ownMemberDevice secretstore.OwnMemberDevice
logger *zap.Logger
closed uint32
tasks sync.WaitGroup
devicesAdded map[string]chan struct{}
muDevicesAdded sync.RWMutex
selfAnnounced chan struct{}
selfAnnouncedOnce sync.Once
}
func (gc *GroupContext) SecretStore() secretstore.SecretStore {
return gc.secretStore
}
func (gc *GroupContext) MessageStore() *MessageStore {
return gc.messageStore
}
func (gc *GroupContext) MetadataStore() *MetadataStore {
return gc.metadataStore
}
func (gc *GroupContext) Group() *protocoltypes.Group {
return gc.group
}
func (gc *GroupContext) MemberPubKey() crypto.PubKey {
return gc.ownMemberDevice.Member()
}
func (gc *GroupContext) DevicePubKey() crypto.PubKey {
return gc.ownMemberDevice.Device()
}
func (gc *GroupContext) Close() error {
gc.cancel()
// @NOTE(gfanton): wait for active tasks to end, doing this we avoid to do
// some operations on a closed store
gc.tasks.Wait()
// mark group context has closed
atomic.StoreUint32(&gc.closed, 1)
// @FIXME(gfanton): should we really handle store closing here ?
gc.metadataStore.Close()
gc.messageStore.Close()
gc.logger.Debug("group context closed", zap.String("groupID", gc.group.GroupIDAsString()))
return nil
}
func (gc *GroupContext) IsClosed() bool {
return atomic.LoadUint32(&gc.closed) != 0
}
func NewContextGroup(group *protocoltypes.Group, metadataStore *MetadataStore, messageStore *MessageStore, secretStore secretstore.SecretStore, memberDevice secretstore.OwnMemberDevice, logger *zap.Logger) *GroupContext {
ctx, cancel := context.WithCancel(context.Background())
if logger == nil {
logger = zap.NewNop()
}
return &GroupContext{
ctx: ctx,
cancel: cancel,
group: group,
metadataStore: metadataStore,
messageStore: messageStore,
secretStore: secretStore,
ownMemberDevice: memberDevice,
logger: logger.With(logutil.PrivateString("group-id", fmt.Sprintf("%.6s", base64.StdEncoding.EncodeToString(group.PublicKey)))),
closed: 0,
devicesAdded: make(map[string]chan struct{}),
selfAnnounced: make(chan struct{}),
}
}
func (gc *GroupContext) ActivateGroupContext(contactPK crypto.PubKey) (err error) {
ctx := gc.ctx
// start watching for GroupMetadataEvent to send secret and register
// chainkey of new members.
{
m := gc.MetadataStore()
sub, err := m.EventBus().Subscribe(new(*protocoltypes.GroupMetadataEvent))
if err != nil {
return fmt.Errorf("unable to subscribe to group metadata event: %w", err)
}
gc.tasks.Add(1)
go func() {
defer gc.tasks.Done() // ultimately, mark bg task has done
defer sub.Close()
for {
var evt interface{}
select {
case <-ctx.Done():
return
case evt = <-sub.Out():
}
// @TODO(gfanton): should we handle this in a sub gorouting ?
e := evt.(*protocoltypes.GroupMetadataEvent)
// start := time.Now()
if err := gc.handleGroupMetadataEvent(e); err != nil {
gc.logger.Error("unable to handle EventTypeGroupDeviceSecretAdded", zap.Error(err))
}
// if t := time.Since(start).Milliseconds(); t > 0 {
// fmt.Printf("elapsed: %dms\n", t)
// }
}
}()
}
// send secret and register key from existing memebers.
// we should wait until all the events have been retreived.
{
var wgExistingMembers sync.WaitGroup
wgExistingMembers.Add(2)
go func() {
start := time.Now()
gc.fillMessageKeysHolderUsingPreviousData()
wgExistingMembers.Done()
gc.logger.Info(fmt.Sprintf("FillMessageKeysHolderUsingPreviousData took %s", time.Since(start)))
}()
go func() {
start := time.Now()
gc.sendSecretsToExistingMembers(contactPK)
wgExistingMembers.Done()
gc.logger.Info(fmt.Sprintf("SendSecretsToExistingMembers took %s", time.Since(start)))
}()
wgExistingMembers.Wait()
}
start := time.Now()
op, err := gc.MetadataStore().AddDeviceToGroup(gc.ctx)
if err != nil {
return fmt.Errorf("unable to add device to groupo: %w", err)
}
gc.logger.Info(fmt.Sprintf("AddDeviceToGroup took %s", time.Since(start)))
if op != nil {
// Waiting for async events to be handled
select {
case <-ctx.Done():
return ctx.Err()
case <-gc.selfAnnounced: // device has been selfAnnounced
}
}
return nil
}
func (gc *GroupContext) handleGroupMetadataEvent(e *protocoltypes.GroupMetadataEvent) (err error) {
switch e.Metadata.EventType {
case protocoltypes.EventType_EventTypeGroupMemberDeviceAdded:
event := &protocoltypes.GroupMemberDeviceAdded{}
if err := proto.Unmarshal(e.Event, event); err != nil {
gc.logger.Error("unable to unmarshal payload", zap.Error(err))
}
memberPK, err := crypto.UnmarshalEd25519PublicKey(event.MemberPk)
if err != nil {
return fmt.Errorf("unable to unmarshal sender member pk: %w", err)
}
if memberPK.Equals(gc.ownMemberDevice.Member()) {
gc.selfAnnouncedOnce.Do(func() { close(gc.selfAnnounced) }) // mark has self announced
}
if _, err := gc.MetadataStore().SendSecret(gc.ctx, memberPK); err != nil {
if !errcode.Is(err, errcode.ErrCode_ErrGroupSecretAlreadySentToMember) {
return fmt.Errorf("unable to send secret to member: %w", err)
}
}
case protocoltypes.EventType_EventTypeGroupDeviceChainKeyAdded:
senderPublicKey, encryptedDeviceChainKey, err := getAndFilterGroupDeviceChainKeyAddedPayload(e.Metadata, gc.ownMemberDevice.Member())
switch err {
case nil: // ok
case errcode.ErrCode_ErrInvalidInput, errcode.ErrCode_ErrGroupSecretOtherDestMember:
// @FIXME(gfanton): should we log this ?
return nil
default:
return fmt.Errorf("an error occurred while opening device secrets: %w", err)
}
if err = gc.SecretStore().RegisterChainKey(gc.ctx, gc.Group(), senderPublicKey, encryptedDeviceChainKey); err != nil {
return fmt.Errorf("unable to register chain key: %w", err)
}
if rawPK, err := senderPublicKey.Raw(); err == nil {
// A new chainKey has been registered, notify watcher
go gc.notifyDeviceAdded(rawPK)
// process queued message and check if cached messages can be opened with it
gc.MessageStore().ProcessMessageQueueForDevicePK(gc.ctx, rawPK)
}
}
return nil
}
func (gc *GroupContext) fillMessageKeysHolderUsingPreviousData() {
publishedSecrets := gc.metadataStoreListSecrets()
for senderPublicKey, encryptedSecret := range publishedSecrets {
if err := gc.SecretStore().RegisterChainKey(gc.ctx, gc.Group(), senderPublicKey, encryptedSecret); err != nil {
gc.logger.Error("unable to register chain key", zap.Error(err))
continue
}
// A new chainKey is registered, check if cached messages can be opened with it
if rawPK, err := senderPublicKey.Raw(); err == nil {
gc.MessageStore().ProcessMessageQueueForDevicePK(gc.ctx, rawPK)
}
}
}
func (gc *GroupContext) metadataStoreListSecrets() map[crypto.PubKey][]byte {
publishedSecrets := map[crypto.PubKey][]byte{}
m := gc.MetadataStore()
metadatas, err := m.ListEvents(gc.ctx, nil, nil, false)
if err != nil {
return nil
}
for metadata := range metadatas {
if metadata == nil {
continue
}
pk, encryptedDeviceChainKey, err := getAndFilterGroupDeviceChainKeyAddedPayload(metadata.Metadata, gc.MemberPubKey())
if errcode.Is(err, errcode.ErrCode_ErrInvalidInput) || errcode.Is(err, errcode.ErrCode_ErrGroupSecretOtherDestMember) {
continue
}
if err != nil {
gc.logger.Error("unable to open chain key", zap.Error(err))
continue
}
publishedSecrets[pk] = encryptedDeviceChainKey
}
return publishedSecrets
}
func (gc *GroupContext) sendSecretsToExistingMembers(contact crypto.PubKey) {
members := gc.MetadataStore().ListMembers()
// Force sending secret to contact member in contact group
if gc.group.GroupType == protocoltypes.GroupType_GroupTypeContact && len(members) < 2 && contact != nil {
// Check if contact member is already listed
found := false
for _, member := range members {
if member.Equals(contact) {
found = true
}
}
// If not listed, add it to the list
if !found {
members = append(members, contact)
}
}
for _, pk := range members {
rawPK, err := pk.Raw()
if err != nil {
gc.logger.Error("failed to serialize pk", zap.Error(err))
continue
}
if _, err := gc.MetadataStore().SendSecret(gc.ctx, pk); err != nil {
if !errcode.Is(err, errcode.ErrCode_ErrGroupSecretAlreadySentToMember) {
gc.logger.Info("secret already sent secret to member", logutil.PrivateString("memberpk", base64.StdEncoding.EncodeToString(rawPK)))
continue
}
} else {
gc.logger.Info("sent secret to existing member", logutil.PrivateString("memberpk", base64.StdEncoding.EncodeToString(rawPK)))
}
}
}
func (gc *GroupContext) TagGroupContextPeers(ipfsCoreAPI ipfsutil.ExtendedCoreAPI, weight int) {
id := gc.Group().GroupIDAsString()
chSub1, err := gc.metadataStore.EventBus().Subscribe(new(stores.EventNewPeer))
if err != nil {
gc.logger.Warn("unable to subscribe to metadata event new peer")
return
}
chSub2, err := gc.messageStore.EventBus().Subscribe(new(stores.EventNewPeer))
if err != nil {
gc.logger.Warn("unable to subscribe to message event new peer")
return
}
go func() {
defer chSub1.Close()
defer chSub2.Close()
for {
var e interface{}
select {
case e = <-chSub1.Out():
case e = <-chSub2.Out():
case <-gc.ctx.Done():
return
}
evt := e.(stores.EventNewPeer)
tag := fmt.Sprintf("grp_%s", id)
gc.logger.Debug("new peer of interest", logutil.PrivateStringer("peer", evt.Peer), zap.String("tag", tag), zap.Int("score", weight))
ipfsCoreAPI.ConnMgr().TagPeer(evt.Peer, tag, weight)
}
}()
}
func (gc *GroupContext) WaitForDeviceAdded(ctx context.Context, devicePK crypto.PubKey) (found chan struct{}) {
gc.muDevicesAdded.Lock()
defer gc.muDevicesAdded.Unlock()
rawpk, err := devicePK.Raw()
if err != nil {
gc.logger.Error("unable to get raw public key", zap.Error(err))
return
}
k := string(rawpk)
var ok bool
if found, ok = gc.devicesAdded[k]; ok {
return
}
groupPublicKey, err := gc.group.GetPubKey()
if err != nil {
gc.logger.Error("unable to get group public key", zap.Error(err))
return
}
found = make(chan struct{})
if gc.secretStore.IsChainKeyKnownForDevice(ctx, groupPublicKey, devicePK) {
close(found)
return
}
gc.devicesAdded[k] = found
return
}
func (gc *GroupContext) notifyDeviceAdded(dPK []byte) {
gc.muDevicesAdded.Lock()
k := string(dPK)
if cc, ok := gc.devicesAdded[k]; ok {
close(cc)
delete(gc.devicesAdded, k)
}
gc.muDevicesAdded.Unlock()
}