forked from vuvuzela/vuvuzela
-
Notifications
You must be signed in to change notification settings - Fork 0
/
convo.go
425 lines (347 loc) · 10.1 KB
/
convo.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
package vuvuzela
import (
"encoding/binary"
"fmt"
"sync"
log "github.com/Sirupsen/logrus"
"golang.org/x/crypto/nacl/box"
. "github.com/davidlazar/vuvuzela/internal"
"github.com/davidlazar/vuvuzela/rand"
"github.com/davidlazar/vuvuzela/vrpc"
)
type ConvoService struct {
roundsMu sync.RWMutex
rounds map[uint32]*ConvoRound
Idle *sync.Mutex
LaplaceMu float64
LaplaceB float64
PKI *PKI
ServerName string
PrivateKey *BoxKey
Client *vrpc.Client
LastServer bool
AccessCounts chan *AccessCount
}
type ConvoRound struct {
srv *ConvoService
status convoStatus
numIncoming int
sharedKeys []*[32]byte
incoming [][]byte
incomingIndex []int
replies [][]byte
numFakeSingles int
numFakeDoubles int
noise [][]byte
noiseWg sync.WaitGroup
}
type convoStatus int
const (
convoRoundNew convoStatus = iota + 1
convoRoundOpen
convoRoundClosed
)
type AccessCount struct {
Singles int64
Doubles int64
}
func InitConvoService(srv *ConvoService) {
srv.rounds = make(map[uint32]*ConvoRound)
srv.AccessCounts = make(chan *AccessCount, 8)
}
func (srv *ConvoService) getRound(round uint32, expectedStatus convoStatus) (*ConvoRound, error) {
srv.roundsMu.RLock()
r, ok := srv.rounds[round]
srv.roundsMu.RUnlock()
if !ok {
return nil, fmt.Errorf("round %d not found", round)
}
if r.status != expectedStatus {
return r, fmt.Errorf("round %d: status %v, expecting %v", round, r.status, expectedStatus)
}
return r, nil
}
func (srv *ConvoService) NewRound(Round uint32, _ *struct{}) error {
log.WithFields(log.Fields{"service": "convo", "rpc": "NewRound", "round": Round}).Info()
// wait for the service to become idle before starting a new round
// TODO temporary hack
srv.Idle.Lock()
srv.roundsMu.Lock()
defer srv.roundsMu.Unlock()
_, exists := srv.rounds[Round]
if exists {
return fmt.Errorf("round %d already exists", Round)
}
round := &ConvoRound{
srv: srv,
}
srv.rounds[Round] = round
if !srv.LastServer {
round.numFakeSingles = cappedFlooredLaplace(srv.LaplaceMu, srv.LaplaceB)
round.numFakeDoubles = cappedFlooredLaplace(srv.LaplaceMu, srv.LaplaceB)
round.numFakeDoubles += round.numFakeDoubles % 2 // ensure numFakeDoubles is even
round.noise = make([][]byte, round.numFakeSingles+round.numFakeDoubles)
nonce := ForwardNonce(Round)
nextKeys := srv.PKI.NextServerKeys(srv.ServerName).Keys()
round.noiseWg.Add(1)
go func() {
FillWithFakeSingles(round.noise[:round.numFakeSingles], nonce, nextKeys)
FillWithFakeDoubles(round.noise[round.numFakeSingles:], nonce, nextKeys)
round.noiseWg.Done()
}()
}
round.status = convoRoundNew
return nil
}
type ConvoOpenArgs struct {
Round uint32
NumIncoming int
}
func (srv *ConvoService) Open(args *ConvoOpenArgs, _ *struct{}) error {
log.WithFields(log.Fields{"service": "convo", "rpc": "Open", "round": args.Round, "incoming": args.NumIncoming}).Info()
round, err := srv.getRound(args.Round, convoRoundNew)
if err != nil {
return err
}
round.numIncoming = args.NumIncoming
round.sharedKeys = make([]*[32]byte, round.numIncoming)
round.incoming = make([][]byte, round.numIncoming)
round.status = convoRoundOpen
return nil
}
type ConvoAddArgs struct {
Round uint32
Offset int
Onions [][]byte
}
func (srv *ConvoService) Add(args *ConvoAddArgs, _ *struct{}) error {
log.WithFields(log.Fields{"service": "convo", "rpc": "Add", "round": args.Round, "onions": len(args.Onions)}).Debug()
round, err := srv.getRound(args.Round, convoRoundOpen)
if err != nil {
return err
}
nonce := ForwardNonce(args.Round)
expectedOnionSize := srv.PKI.IncomingOnionOverhead(srv.ServerName) + SizeConvoExchange
if args.Offset+len(args.Onions) > round.numIncoming {
return fmt.Errorf("overflowing onions (offset=%d, onions=%d, incoming=%d)", args.Offset, len(args.Onions), round.numIncoming)
}
for k, onion := range args.Onions {
i := args.Offset + k
round.sharedKeys[i] = new([32]byte)
if len(onion) == expectedOnionSize {
var theirPublic [32]byte
copy(theirPublic[:], onion[0:32])
box.Precompute(round.sharedKeys[i], &theirPublic, srv.PrivateKey.Key())
message, ok := box.OpenAfterPrecomputation(nil, onion[32:], nonce, round.sharedKeys[i])
if ok {
round.incoming[i] = message
}
} else {
// for debugging
log.WithFields(log.Fields{"round": args.Round, "offset": args.Offset, "onions": len(args.Onions), "onion": k, "onionLen": len(onion)}).Error("bad onion size")
}
}
return nil
}
func (srv *ConvoService) filterIncoming(round *ConvoRound) {
incomingValid := make([][]byte, len(round.incoming))
incomingIndex := make([]int, len(round.incoming))
seen := make(map[uint64]bool)
v := 0
for i, msg := range round.incoming {
if msg == nil {
incomingIndex[i] = -1
continue
}
msgkey := binary.BigEndian.Uint64(msg[len(msg)-8:])
if seen[msgkey] {
incomingIndex[i] = -1
} else {
seen[msgkey] = true
incomingValid[v] = msg
incomingIndex[i] = v
v++
}
}
round.incoming = incomingValid[:v]
round.incomingIndex = incomingIndex
}
func (srv *ConvoService) Close(Round uint32, _ *struct{}) error {
log.WithFields(log.Fields{"service": "convo", "rpc": "Close", "round": Round}).Info()
round, err := srv.getRound(Round, convoRoundOpen)
if err != nil {
return err
}
srv.filterIncoming(round)
if !srv.LastServer {
round.noiseWg.Wait()
outgoing := append(round.incoming, round.noise...)
round.noise = nil
shuffler := NewShuffler(rand.Reader, len(outgoing))
shuffler.Shuffle(outgoing)
if err := NewConvoRound(srv.Client, Round); err != nil {
return fmt.Errorf("NewConvoRound: %s", err)
}
srv.Idle.Unlock()
replies, err := RunConvoRound(srv.Client, Round, outgoing)
if err != nil {
return fmt.Errorf("RunConvoRound: %s", err)
}
shuffler.Unshuffle(replies)
round.replies = replies[:round.numIncoming]
} else {
exchanges := make([]*ConvoExchange, len(round.incoming))
ParallelFor(len(round.incoming), func(p *P) {
for i, ok := p.Next(); ok; i, ok = p.Next() {
exchanges[i] = new(ConvoExchange)
if err := exchanges[i].Unmarshal(round.incoming[i]); err != nil {
log.WithFields(log.Fields{"bug": true, "call": "ConvoExchange.Unmarshal"}).Error(err)
}
}
})
var singles, doubles int64
deadDrops := make(map[DeadDrop][]int)
for i, ex := range exchanges {
drop := deadDrops[ex.DeadDrop]
if len(drop) == 0 {
singles++
deadDrops[ex.DeadDrop] = append(drop, i)
} else if len(drop) == 1 {
singles--
doubles++
deadDrops[ex.DeadDrop] = append(drop, i)
}
}
round.replies = make([][]byte, len(round.incoming))
ParallelFor(len(exchanges), func(p *P) {
for i, ok := p.Next(); ok; i, ok = p.Next() {
ex := exchanges[i]
drop := deadDrops[ex.DeadDrop]
if len(drop) == 1 {
round.replies[i] = ex.EncryptedMessage[:]
}
if len(drop) == 2 {
var k int
if i == drop[0] {
k = drop[1]
} else {
k = drop[0]
}
round.replies[i] = exchanges[k].EncryptedMessage[:]
}
}
})
srv.Idle.Unlock()
ac := &AccessCount{
Singles: singles,
Doubles: doubles,
}
select {
case srv.AccessCounts <- ac:
default:
}
}
round.status = convoRoundClosed
return nil
}
type ConvoGetArgs struct {
Round uint32
Offset int
Count int
}
type ConvoGetResult struct {
Onions [][]byte
}
func (srv *ConvoService) Get(args *ConvoGetArgs, result *ConvoGetResult) error {
log.WithFields(log.Fields{"service": "convo", "rpc": "Get", "round": args.Round, "count": args.Count}).Debug()
round, err := srv.getRound(args.Round, convoRoundClosed)
if err != nil {
return err
}
nonce := BackwardNonce(args.Round)
outgoingOnionSize := srv.PKI.OutgoingOnionOverhead(srv.ServerName) + SizeEncryptedMessage
result.Onions = make([][]byte, args.Count)
for k := range result.Onions {
i := args.Offset + k
if v := round.incomingIndex[i]; v > -1 {
reply := round.replies[v]
onion := box.SealAfterPrecomputation(nil, reply, nonce, round.sharedKeys[i])
result.Onions[k] = onion
}
if len(result.Onions[k]) != outgoingOnionSize {
onion := make([]byte, outgoingOnionSize)
rand.Read(onion)
result.Onions[k] = onion
}
}
return nil
}
func (srv *ConvoService) Delete(Round uint32, _ *struct{}) error {
log.WithFields(log.Fields{"service": "convo", "rpc": "Delete", "round": Round}).Info()
srv.roundsMu.Lock()
delete(srv.rounds, Round)
srv.roundsMu.Unlock()
return nil
}
func NewConvoRound(client *vrpc.Client, round uint32) error {
return client.Call("ConvoService.NewRound", round, nil)
}
func RunConvoRound(client *vrpc.Client, round uint32, onions [][]byte) ([][]byte, error) {
openArgs := &ConvoOpenArgs{
Round: round,
NumIncoming: len(onions),
}
if err := client.Call("ConvoService.Open", openArgs, nil); err != nil {
return nil, fmt.Errorf("Open: %s", err)
}
spans := Spans(len(onions), 4000)
calls := make([]*vrpc.Call, len(spans))
ParallelFor(len(calls), func(p *P) {
for i, ok := p.Next(); ok; i, ok = p.Next() {
span := spans[i]
calls[i] = &vrpc.Call{
Method: "ConvoService.Add",
Args: &ConvoAddArgs{
Round: round,
Offset: span.Start,
Onions: onions[span.Start : span.Start+span.Count],
},
Reply: nil,
}
}
})
if err := client.CallMany(calls); err != nil {
return nil, fmt.Errorf("Add: %s", err)
}
if err := client.Call("ConvoService.Close", round, nil); err != nil {
return nil, fmt.Errorf("Close: %s", err)
}
ParallelFor(len(calls), func(p *P) {
for i, ok := p.Next(); ok; i, ok = p.Next() {
span := spans[i]
calls[i] = &vrpc.Call{
Method: "ConvoService.Get",
Args: &ConvoGetArgs{
Round: round,
Offset: span.Start,
Count: span.Count,
},
Reply: new(ConvoGetResult),
}
}
})
if err := client.CallMany(calls); err != nil {
return nil, fmt.Errorf("Get: %s", err)
}
replies := make([][]byte, len(onions))
ParallelFor(len(calls), func(p *P) {
for i, ok := p.Next(); ok; i, ok = p.Next() {
span := spans[i]
copy(replies[span.Start:span.Start+span.Count], calls[i].Reply.(*ConvoGetResult).Onions)
}
})
if err := client.Call("ConvoService.Delete", round, nil); err != nil {
return nil, fmt.Errorf("Delete: %s", err)
}
return replies, nil
}