-
Notifications
You must be signed in to change notification settings - Fork 1
/
dos_stages.go
537 lines (489 loc) · 13.8 KB
/
dos_stages.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
package dosnode
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"github.com/DOSNetwork/core/configuration"
"github.com/ethereum/go-ethereum/common/hexutil"
"io/ioutil"
"math/big"
"net/http"
"strings"
"sync"
"time"
"github.com/DOSNetwork/core/log"
"github.com/DOSNetwork/core/onchain"
"github.com/DOSNetwork/core/p2p"
"github.com/DOSNetwork/core/share"
"github.com/DOSNetwork/core/share/vss/pedersen"
"github.com/DOSNetwork/core/sign/bls"
"github.com/DOSNetwork/core/sign/tbls"
"github.com/DOSNetwork/core/suites"
"github.com/antchfx/xmlquery"
"github.com/oliveagle/jsonpath"
)
const (
randNumberSize = 32
addrLen = 20
)
func mergeErrors(ctx context.Context, cs ...chan error) chan error {
var wg sync.WaitGroup
// We must ensure that the output channel has the capacity to
// hold as many errors
// as there are error channels.
// This will ensure that it never blocks, even
// if WaitForPipeline returns early.
out := make(chan error, len(cs))
// Start an output goroutine for each input channel in cs. output
// copies values from c to out until c is closed, then calls
// wg.Done.
output := func(c <-chan error) {
for n := range c {
select {
case <-ctx.Done():
return
case out <- n:
}
}
wg.Done()
}
wg.Add(len(cs))
for _, c := range cs {
go output(c)
}
// Start a goroutine to close out once all the output goroutines
// are done. This must start after the wg.Add call.
go func() {
wg.Wait()
close(out)
}()
return out
}
func fanIn(ctx context.Context, channels ...chan *vss.Signature) chan *vss.Signature {
var wg sync.WaitGroup
multiplexedStream := make(chan *vss.Signature)
multiplex := func(c <-chan *vss.Signature) {
defer wg.Done()
for i := range c {
select {
case <-ctx.Done():
return
case multiplexedStream <- i:
}
}
}
// Select from all the channels
wg.Add(len(channels))
for _, c := range channels {
go multiplex(c)
}
// Wait for all the reads to complete
go func() {
wg.Wait()
close(multiplexedStream)
}()
return multiplexedStream
}
//choseSubmitter choses a submitter according to the last random number and check if the submitter is reachable
func choseSubmitter(ctx context.Context, p p2p.P2PInterface, e onchain.ProxyAdapter, lastSysRand *big.Int, ids [][]byte, outCount int, logger log.Logger) ([]chan []byte, chan error) {
errc := make(chan error)
var outs []chan []byte
for i := 0; i < outCount; i++ {
outs = append(outs, make(chan []byte, 1))
}
go func() {
defer close(errc)
start := time.Now()
submitter := lastSysRand.Uint64() % uint64(len(ids))
for _, out := range outs {
select {
case out <- ids[submitter]:
case <-ctx.Done():
}
}
for _, out := range outs {
close(out)
}
logger.TimeTrack(start, "ChoseSubmitter", map[string]interface{}{"GroupID": ctx.Value(ctxKey("GroupID")), "RequestID": ctx.Value(ctxKey("RequestID"))})
return
}()
return outs, errc
}
func genUserRandom(ctx context.Context, submitterc chan []byte, requestId []byte, lastSysRand []byte, userSeed []byte, logger log.Logger) chan []byte {
out := make(chan []byte)
go func() {
defer close(out)
select {
case submitter, ok := <-submitterc:
if !ok {
return
}
defer logger.TimeTrack(time.Now(), "GenUserRandom",
map[string]interface{}{"GroupID": ctx.Value(ctxKey("GroupID")), "RequestID": ctx.Value(ctxKey("RequestID"))})
logger.Info("GenUserRandom ")
// signed message: concat(requestId, lastSystemRandom, userSeed, submitter address)
random := append(requestId, lastSysRand...)
random = append(random, userSeed...)
random = append(random, submitter...)
select {
case out <- random:
case <-ctx.Done():
}
return
case <-ctx.Done():
return
}
}()
return out
}
func genSysRandom(ctx context.Context, submitterc chan []byte, lastSysRand []byte, logger log.Logger) chan []byte {
out := make(chan []byte)
go func() {
defer close(out)
select {
case submitter, ok := <-submitterc:
if !ok {
return
}
defer logger.TimeTrack(time.Now(), "GenSysRandom",
map[string]interface{}{"GroupID": ctx.Value(ctxKey("GroupID")),
"RequestID": ctx.Value(ctxKey("RequestID"))})
logger.Info("genSysRandom ")
// signed message: concat(lastSystemRandom, submitter address)
paddedLastSysRand := padOrTrim(lastSysRand, randNumberSize)
random := append(paddedLastSysRand, submitter...)
select {
case out <- random:
case <-ctx.Done():
}
return
case <-ctx.Done():
return
}
}()
return out
}
func dataFetch(url string) (body []byte, err error) {
client := &http.Client{Timeout: 60 * time.Second}
r, err := client.Get(url)
if err != nil {
return
}
body, err = ioutil.ReadAll(r.Body)
if err != nil {
return
}
err = r.Body.Close()
return
}
func dataParse(rawMsg []byte, pathStr string) (msg []byte, err error) {
if pathStr == "" {
msg = rawMsg
} else if strings.HasPrefix(pathStr, "$") {
var rawMsgJson, msgJson interface{}
if err = json.Unmarshal(rawMsg, &rawMsgJson); err != nil {
return
}
if msgJson, err = jsonpath.JsonPathLookup(rawMsgJson, pathStr); err != nil {
return
}
msg, err = json.Marshal(msgJson)
} else if strings.HasPrefix(pathStr, "/") {
var rawMsgXml *xmlquery.Node
if rawMsgXml, err = xmlquery.Parse(bytes.NewReader(rawMsg)); err != nil {
return
}
xmlNodes := xmlquery.Find(rawMsgXml, pathStr)
for _, xmlNode := range xmlNodes {
msg = append(msg, []byte(xmlNode.OutputXML(false))...)
msg = append(msg, "\n"...)
}
}
return
}
func genUploadPower(ctx context.Context, submitterc chan []byte, logger log.Logger) (chan []byte, chan error) {
out := make(chan []byte)
errc := make(chan error)
go func() {
startTime := time.Now()
defer close(out)
defer close(errc)
configuration.CalSort(configuration.RankInfos)
msgReturn := configuration.SpiltPowerStrToByte(configuration.RankInfos)
logger.Debug(string(msgReturn))
logger.Debug("************************************")
logger.TimeTrack(startTime, "TFetch", map[string]interface{}{"GroupID": ctx.Value(ctxKey("GroupID")), "RequestID": ctx.Value(ctxKey("RequestID"))})
select {
case submitter, ok := <-submitterc:
if !ok {
return
}
defer logger.TimeTrack(time.Now(), "genUploadPower", map[string]interface{}{"GroupID": ctx.Value(ctxKey("GroupID")), "RequestID": ctx.Value(ctxKey("RequestID"))})
// signed message = concat(msgReturn, submitter address)
msgReturn = append(msgReturn, submitter...)
select {
case out <- msgReturn:
case <-ctx.Done():
}
return
case <-ctx.Done():
return
}
}()
return out, errc
}
func genQueryResult(ctx context.Context, submitterc chan []byte, url string, pathStr string, logger log.Logger) (chan []byte, chan error) {
out := make(chan []byte)
errc := make(chan error)
go func() {
startTime := time.Now()
defer close(out)
defer close(errc)
rawMsg, err := dataFetch(url)
if err != nil {
logger.Error(err)
errc <- err
return
}
msgReturn, err := dataParse(rawMsg, pathStr)
if err != nil {
logger.Error(err)
errc <- err
return
}
logger.TimeTrack(startTime, "TFetch", map[string]interface{}{"GroupID": ctx.Value(ctxKey("GroupID")), "RequestID": ctx.Value(ctxKey("RequestID"))})
select {
case submitter, ok := <-submitterc:
if !ok {
return
}
defer logger.TimeTrack(time.Now(), "GenQueryResult", map[string]interface{}{"GroupID": ctx.Value(ctxKey("GroupID")), "RequestID": ctx.Value(ctxKey("RequestID"))})
// signed message = concat(msgReturn, submitter address)
msgReturn = append(msgReturn, submitter...)
select {
case out <- msgReturn:
case <-ctx.Done():
}
return
case <-ctx.Done():
return
}
}()
return out, errc
}
func genSign(ctx context.Context, contentc chan []byte, sec *share.PriShare, suite suites.Suite, sign *vss.Signature, logger log.Logger) (chan *vss.Signature, chan error) {
out := make(chan *vss.Signature)
errc := make(chan error)
go func() {
defer close(out)
defer close(errc)
select {
case content, ok := <-contentc:
if !ok {
return
}
defer logger.TimeTrack(time.Now(), "GenSign", map[string]interface{}{"GroupID": ctx.Value(ctxKey("GroupID")), "RequestID": ctx.Value(ctxKey("RequestID"))})
sign.Content = content
sig, err := tbls.Sign(suite, sec, content)
if err != nil {
logger.Error(err)
select {
case errc <- err:
case <-ctx.Done():
}
return
}
sign.Signature = sig
select {
case <-ctx.Done():
case out <- sign:
}
return
case <-ctx.Done():
return
}
}()
return out, errc
}
func dispatchSign(ctx context.Context, submitterc chan []byte, signc chan *vss.Signature, reqSignc chan request, p p2p.P2PInterface, requestID []byte, threshold int, logger log.Logger) chan *vss.Signature {
out := make(chan *vss.Signature)
go func() {
select {
case submitter, ok := <-submitterc:
fmt.Println("submitter=", hexutil.Encode(submitter))
defer logger.TimeTrack(time.Now(), "dispatchSign", map[string]interface{}{"GroupID": ctx.Value(ctxKey("GroupID")), "RequestID": ctx.Value(ctxKey("RequestID"))})
fmt.Println("ok=", ok)
if !ok {
return
}
if r := bytes.Compare(p.GetID(), submitter); r != 0 {
logger.Event("dispatchSignToSubmitter", map[string]interface{}{"GroupID": ctx.Value(ctxKey("GroupID")), "RequestID": ctx.Value(ctxKey("RequestID"))})
//Send signature to submitter
logger.Info(fmt.Sprintf("dispatchSign to %x", submitter))
select {
case <-ctx.Done():
case sign := <-signc:
logger.Event("dispatchSendToSubmitter", map[string]interface{}{"GroupID": ctx.Value(ctxKey("GroupID")), "RequestID": ctx.Value(ctxKey("RequestID"))})
if _, err := p.Request(ctx, submitter, sign); err != nil {
logger.Error(err)
}
}
fmt.Println("close out_1......")
close(out)
return
} else {
logger.Info(fmt.Sprintf("submitter= %x", submitter))
}
case <-ctx.Done():
fmt.Println("close out_2......")
close(out)
return
}
logger.Event("dispatchSignWaitForSign", map[string]interface{}{"GroupID": ctx.Value(ctxKey("GroupID")), "RequestID": ctx.Value(ctxKey("RequestID"))})
//Bypass signature to next stage
select {
case <-ctx.Done():
fmt.Println("close out_3......")
close(out)
case sign := <-signc:
select {
case <-ctx.Done():
fmt.Println("close out_4......")
close(out)
case out <- sign:
}
}
//Request for peer's signature
req := request{ctx: ctx, requestID: string(requestID), threshold: threshold, reply: out}
select {
case <-ctx.Done():
case reqSignc <- req:
}
}()
return out
}
func recoverSign(ctx context.Context, signc chan *vss.Signature, suite suites.Suite, pubPoly *share.PubPoly, nbThreshold int, nbParticipants int, logger log.Logger) (chan *vss.Signature, chan error) {
out := make(chan *vss.Signature)
errc := make(chan error)
go func() {
var signShares [][]byte
defer close(out)
defer close(errc)
for {
select {
case sign, ok := <-signc:
if !ok {
return
}
logger.Event("recoverSign", map[string]interface{}{"GroupID": ctx.Value(ctxKey("GroupID")), "RequestID": ctx.Value(ctxKey("RequestID"))})
logger.Info(fmt.Sprintf("recoverSign %d", len(signShares)))
if len(signShares) == 0 {
defer logger.TimeTrack(time.Now(), "RecoverSign", map[string]interface{}{"GroupID": ctx.Value(ctxKey("GroupID")), "RequestID": ctx.Value(ctxKey("RequestID"))})
}
signShares = append(signShares, sign.Signature)
if len(signShares) >= nbThreshold {
sig, err := tbls.Recover(suite, pubPoly, sign.Content, signShares, nbThreshold, nbParticipants)
if err != nil {
logger.Error(err)
errc <- err
continue
}
if err = bls.Verify(suite, pubPoly.Commit(), sign.Content, sig); err != nil {
logger.Error(err)
errc <- err
continue
}
x, y := sign.ToBigInt()
logger.Info(fmt.Sprintf("Verify success signature %s %s", x.String(), y.String()))
//Contract will append sender address to content to verify if it is a right submitter
t := len(sign.Content) - addrLen
if t < 0 {
errc <- errors.New("length of content less than 0")
}
queryResult := make([]byte, t)
copy(queryResult, sign.Content)
select {
case out <- &vss.Signature{Index: sign.Index, RequestId: sign.RequestId, Content: queryResult, Signature: sig}:
case <-ctx.Done():
}
return
}
case <-ctx.Done():
return
}
}
}()
return out, errc
}
func registerGroup(ctx context.Context, chain onchain.ProxyAdapter, IdWithPubKeys chan [5]*big.Int) (errc chan error) {
fmt.Println("in registerGroup")
errc = make(chan error)
go func() {
defer close(errc)
var err error
select {
case idPubkey, ok := <-IdWithPubKeys:
if ok {
fmt.Println("registerGroup")
err = chain.RegisterGroupPubKey(idPubkey)
} else {
fmt.Println("RegisterGroupPubKey error")
err = errors.New("no publickey")
}
case <-ctx.Done():
fmt.Println("case <-ctx.Done():")
err = ctx.Err()
return
}
fmt.Println("registerGroup err=", err)
if err != nil {
select {
case errc <- err:
case <-ctx.Done():
}
}
}()
return
}
func reportQueryResult(ctx context.Context, chain onchain.ProxyAdapter, queryType uint32, signC chan *vss.Signature) (errc chan error) {
errc = make(chan error)
go func() {
defer close(errc)
var err error
select {
case signature, ok := <-signC:
if ok {
if queryType == onchain.TrafficSystemRandom {
err = chain.UpdateRandomness(signature)
} else {
err = chain.DataReturn(signature)
}
} else {
err = errors.New("no signature")
}
case <-ctx.Done():
return
}
if err != nil {
select {
case errc <- err:
case <-ctx.Done():
}
}
}()
return
}
func padOrTrim(bb []byte, size int) []byte {
l := len(bb)
if l == size {
return bb
}
if l > size {
return bb[l-size:]
}
tmp := make([]byte, size)
copy(tmp[size-l:], bb)
return tmp
}