/
reqsign.go
3099 lines (2635 loc) · 99.2 KB
/
reqsign.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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2020-2021 AnySwap Ltd. All rights reserved.
* Copyright (C) 2020-2021 haijun.cai@anyswap.exchange
*
* This library is free software; you can redistribute it and/or
* modify it under the Apache License, Version 2.0.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package smpc
import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math/big"
"sort"
"strconv"
"strings"
"time"
"github.com/RWAValueRouter/FastMulThreshold-DSA/crypto/secp256k1"
"github.com/RWAValueRouter/FastMulThreshold-DSA/internal/common"
"github.com/RWAValueRouter/FastMulThreshold-DSA/p2p/discover"
"github.com/RWAValueRouter/FastMulThreshold-DSA/smpc-lib/crypto/ec2"
"github.com/RWAValueRouter/FastMulThreshold-DSA/smpc-lib/ecdsa/keygen"
"github.com/RWAValueRouter/FastMulThreshold-DSA/smpc-lib/ecdsa/signing"
edkeygen "github.com/RWAValueRouter/FastMulThreshold-DSA/smpc-lib/eddsa/keygen"
edsigning "github.com/RWAValueRouter/FastMulThreshold-DSA/smpc-lib/eddsa/signing"
smpclib "github.com/RWAValueRouter/FastMulThreshold-DSA/smpc-lib/smpc"
"github.com/astaxie/beego/logs"
"runtime/debug"
"sync"
"github.com/RWAValueRouter/FastMulThreshold-DSA/log"
)
var (
// SignChan the channel of RPCSignData
SignChan = make(chan *RPCSignData, 10000)
mutex sync.Mutex
)
//--------------------------------------------------------------------------------------
// GetSignNonce get sign special tx nonce
func GetSignNonce(account string) (string, string, error) {
mutex.Lock()
defer mutex.Unlock()
if account == "" {
log.Error("================GetSignNonce,invalid account==================")
return "", "", fmt.Errorf("invalid account")
}
key := Keccak256Hash([]byte(strings.ToLower(account + ":" + "Sign"))).Hex()
exsit, da := GetPubKeyData([]byte(key))
if !exsit {
nonce := "0"
err := PutPubKeyData([]byte(key), []byte(nonce))
if err != nil {
log.Error("================GetSignNonce,nonce = 0,save nonce fail==================","err",err,"account",account,"accountkey",key)
return "", "", err
}
log.Info("================GetSignNonce,return 0==================","account",account,"accountkey",key)
return "0", "", nil
}
nonce, _ := new(big.Int).SetString(string(da.([]byte)), 10)
one, _ := new(big.Int).SetString("1", 10)
nonce = new(big.Int).Add(nonce, one)
err := PutPubKeyData([]byte(key), []byte(fmt.Sprintf("%v", nonce)))
if err != nil {
log.Error("================GetSignNonce,put pubkey data error==================","err",err,"account",account,"accountkey",key,"nonce",nonce)
return "", "", err
}
log.Debug("================GetSignNonce,put pubkey data success==================","account",account,"accountkey",key,"nonce",nonce)
return fmt.Sprintf("%v", nonce), "", nil
}
// SetSignNonce set sign special tx nonce
func SetSignNonce(account string, nonce string) (string, error) {
if account == "" || nonce == "" {
return "",errors.New("param error")
}
key := Keccak256Hash([]byte(strings.ToLower(account + ":" + "Sign"))).Hex()
err := PutPubKeyData([]byte(key), []byte(nonce))
if err != nil {
return err.Error(), err
}
return "", nil
}
//------------------------------------------------------------------------------------------
// DoSign execute sign
// sbd : sign command data + key of picked pre-sign data
// workid : current worker id
// sender : send node's enodeID
// ch : the channel to save the sign result or error info.
func DoSign(sbd *SignPickData, workid int, sender string, ch chan interface{}) error {
if sbd == nil || workid < 0 || sender == "" || sbd.Raw == "" || sbd.PickData == nil {
common.Error("=====================DoSign,param error ================", "workid", workid, "sender", sender, "raw", sbd.Raw)
res := RPCSmpcRes{Ret: "", Tip: "do sign fail.", Err: fmt.Errorf("do sign fail")}
ch <- res
return fmt.Errorf("do sign fail")
}
key, from, nonce, txdata, err := CheckRaw(sbd.Raw)
common.Info("=====================DoSign,check raw data finish ================", "key", key, "from", from, "err", err, "raw", sbd.Raw, "tx data", txdata)
if err != nil {
common.Error("===============DoSign,check raw data error===================", "err ", err, "key", key, "from", from, "raw", sbd.Raw)
res := RPCSmpcRes{Ret: "", Tip: err.Error(), Err: err}
ch <- res
return err
}
sig, ok := txdata.(*TxDataSign)
if !ok {
common.Error("===============DoSign,sign data error===================","key", key, "from", from, "raw", sbd.Raw)
res := RPCSmpcRes{Ret: "", Tip:"sign data error", Err: fmt.Errorf("sign data error")}
ch <- res
return fmt.Errorf("sign data error")
}
exsit, _ := GetSignInfoData([]byte(key))
if exsit {
common.Error("===============DoSign,the sign cmd has handled before===================","key", key, "from", from, "raw", sbd.Raw)
res := RPCSmpcRes{Ret: "", Tip:"the sign cmd has handled before", Err: fmt.Errorf("the sign cmd has handled before")}
ch <- res
return fmt.Errorf("the sign cmd has handled before")
}
ars := GetAllReplyFromGroup(workid,sig.GroupID,RPCSIGN,sender)
ac := &AcceptSignData{Raw:sbd.Raw,Initiator: sender, Account: from, GroupID: sig.GroupID, Nonce: nonce, PubKey: sig.PubKey, MsgHash: sig.MsgHash, MsgContext: sig.MsgContext, Keytype: sig.Keytype, LimitNum: sig.ThresHold, Mode: sig.Mode, TimeStamp: sig.TimeStamp, Deal: "false", Accept: "false", Status: "Pending", Rsv: "", Tip: "", Error: "", AllReply: ars, WorkID: workid}
err = SaveAcceptSignData(ac)
if err != nil {
common.Error("===============DoSign,save sign accept data fail===================","err",err,"key", key, "from", from, "raw", sbd.Raw)
res := RPCSmpcRes{Ret: "", Tip:"save sign accept data fail", Err: fmt.Errorf("save sign accept data fail")}
ch <- res
return fmt.Errorf("save sign accept data fail")
}
common.Info("===============DoSign,save sign accept data finish===================", "ars ", ars, "key ", key, "tx data", sig)
w := workers[workid]
w.sid = key
w.groupid = sig.GroupID
w.limitnum = sig.ThresHold
gcnt, _ := GetGroup(w.groupid)
w.NodeCnt = gcnt
w.ThresHold = w.NodeCnt
nums := strings.Split(w.limitnum, "/")
if len(nums) == 2 {
nodecnt, err := strconv.Atoi(nums[1])
if err == nil {
w.NodeCnt = nodecnt
}
w.ThresHold = gcnt
}
w.SmpcFrom = sig.PubKey // pubkey replace smpcfrom in sign
//
index := -1
for j,rh := range w.ApprovReplys {
if rh == nil {
continue
}
if strings.EqualFold(rh.From,from) {
index = j
break
}
}
reqaddrkey := GetReqAddrKeyByOtherKey(key, RPCSIGN)
exsit, da := GetPubKeyData([]byte(reqaddrkey))
if !exsit {
log.Error("================DoSign,get keygen data by key from db fail===============","sign key",key,"keygen key",reqaddrkey)
res := RPCSmpcRes{Ret: "", Tip:"", Err: fmt.Errorf("get keygen data by key from db fail")}
ch <- res
return fmt.Errorf("get keygen data by key from db fail")
}
acceptreqdata, ok := da.(*AcceptReqAddrData)
if !ok || acceptreqdata == nil {
log.Error("================DoSign,get keygen data fail===============","sign key",key,"keygen key",reqaddrkey)
res := RPCSmpcRes{Ret: "", Tip:"", Err: fmt.Errorf("get keygen data fail")}
ch <- res
return fmt.Errorf("get keygen data fail")
}
enode := curEnode
if acceptreqdata.Mode == "0" || acceptreqdata.Mode == "2" {
enode = GetENodeByFrom(from,acceptreqdata)
if enode == "" {
log.Error("================DoSign,get enode fail===============","sign key",key,"keygen key",reqaddrkey)
res := RPCSmpcRes{Ret: "", Tip: "", Err: errors.New("get enode fail")}
ch <- res
return errors.New("get enode fail")
}
}
reply := &ApprovReply{ENode:enode,From: from, Accept: "AGREE", TimeStamp: acceptreqdata.TimeStamp}
if index != -1 {
w.ApprovReplys[index] = reply
} else {
w.ApprovReplys = append(w.ApprovReplys,reply)
}
//arstmp := GetAllReplyFromGroup2(w.id,sender)
//AcceptSign(sbd.Raw, sender, from, sig.PubKey, sig.MsgHash, sig.Keytype, sig.GroupID, nonce, sig.ThresHold, sig.Mode, "false", "false", "Pending", "", "", "", arstmp, workid)
//
if sig.Mode == "0" || sig.Mode == "2" { // self-group
var reply bool
var tip string
var signtimeout bool
timeout := make(chan bool, 1)
go func(wid int) {
curEnode = discover.GetLocalID().String() //GetSelfEnode()
ato,err := strconv.Atoi(sig.AcceptTimeOut)
if err != nil || sig.AcceptTimeOut == "" {
ato = 600
}
agreeWaitTime := time.Duration(ato) * time.Second
agreeWaitTimeOut := time.NewTicker(agreeWaitTime)
wtmp2 := workers[wid]
for {
select {
case account := <-wtmp2.acceptSignChan:
common.Debug("InitAcceptData,", "account= ", account, "key = ", key)
ars := GetAllReplyFromGroup2(w.id,sender)
common.Info("==================get all signing approve results===============", "result ", ars, "key ", key)
reply = true
for _, nr := range ars {
if !strings.EqualFold(nr.Status, "Agree") {
reply = false
break
}
}
if !reply {
_, err = AcceptSign(sbd.Raw, sender, from, sig.PubKey, sig.MsgHash, sig.Keytype, sig.GroupID, nonce, sig.ThresHold, sig.Mode, "true", "false", "Failure", "", "Someone refused to sign", "Someone refused to sign", ars, wid)
} else {
_, err = AcceptSign(sbd.Raw, sender, from, sig.PubKey, sig.MsgHash, sig.Keytype, sig.GroupID, nonce, sig.ThresHold, sig.Mode, "false", "true", "Pending", "", "", "", ars, wid)
}
timeout <- true
return
case <-agreeWaitTimeOut.C:
ars := GetAllReplyFromGroup2(w.id,sender)
common.Info("================== DoSign, agree wait timeout=============", "ars", ars, "key ", key)
_, err = AcceptSign(sbd.Raw, sender, from, sig.PubKey, sig.MsgHash, sig.Keytype, sig.GroupID, nonce, sig.ThresHold, sig.Mode, "true", "false", "Timeout", "", "Approval timeout", "Approval timeout", ars, wid)
reply = false
signtimeout = true
timeout <- true
return
}
}
}(workid)
if len(workers[workid].acceptWaitSignChan) == 0 {
workers[workid].acceptWaitSignChan <- "go on"
}
DisAcceptMsg(sbd.Raw, workid)
reqaddrkey := GetReqAddrKeyByOtherKey(key, RPCSIGN)
if reqaddrkey == "" {
res := RPCSmpcRes{Ret: "", Tip: "", Err: fmt.Errorf("get reqaddr key fail")}
ch <- res
return fmt.Errorf("get reqaddr key fail")
}
exsit, da := GetPubKeyData([]byte(reqaddrkey))
if !exsit {
res := RPCSmpcRes{Ret: "", Tip: "", Err: fmt.Errorf("get reqaddr sigs data fail")}
ch <- res
return fmt.Errorf("get reqaddr sigs data fail")
}
acceptreqdata, ok := da.(*AcceptReqAddrData)
if !ok || acceptreqdata == nil {
common.Debug("===============DoSign, get req addr key by other key error ===================", "key ", key)
res := RPCSmpcRes{Ret: "", Tip: "", Err: fmt.Errorf("get reqaddr sigs data fail")}
ch <- res
return fmt.Errorf("get reqaddr sigs data fail")
}
HandleC1Data(acceptreqdata, key)
<-timeout
if !reply {
arstmp := GetAllReplyFromGroup2(w.id,sender)
if signtimeout {
AcceptSign(sbd.Raw, sender, from, sig.PubKey, sig.MsgHash, sig.Keytype, sig.GroupID, nonce, sig.ThresHold, sig.Mode, "true", "false", "Timeout", "", "Approval timeout", "Approval timeout", arstmp, workid)
} else {
AcceptSign(sbd.Raw, sender, from, sig.PubKey, sig.MsgHash, sig.Keytype, sig.GroupID, nonce, sig.ThresHold, sig.Mode, "true", "false", "Failure", "", "Someone refused to sign", "Someone refused to sign", arstmp, workid)
}
res := RPCSmpcRes{Ret: "", Tip: tip, Err: fmt.Errorf("approval fail")}
ch <- res
return fmt.Errorf("approval fail")
}
} else {
if len(workers[workid].acceptWaitSignChan) == 0 {
workers[workid].acceptWaitSignChan <- "go on"
}
ars := GetAllReplyFromGroup2(w.id,sender)
_, err = AcceptSign(sbd.Raw, sender, from, sig.PubKey, sig.MsgHash, sig.Keytype, sig.GroupID, nonce, sig.ThresHold, sig.Mode, "false", "true", "Pending", "", "", "", ars, workid)
if err != nil {
res := RPCSmpcRes{Ret: "", Tip: err.Error(), Err: err}
ch <- res
return err
}
}
rch := make(chan interface{}, 1)
sign(w.sid, from, sig.PubKey, sig.InputCode, sig.MsgHash, sig.Keytype, nonce, sig.Mode, sbd.PickData, rch)
chret, tip, cherr := GetChannelValue(waitallgg20+20, rch)
if chret != "" {
_, reply := AcceptSign(sbd.Raw, "", from, sig.PubKey, sig.MsgHash, sig.Keytype, sig.GroupID, nonce, w.limitnum, sig.Mode, "true", "true", "Success", chret, "", "", nil, w.id)
if reply != nil {
common.Error("=====================DoSign,accept sign fail ================", "key", key, "from", from, "gid",sig.GroupID)
ars := GetAllReplyFromGroup2(w.id,sender)
errinfo := "Abnormal value in MPC calculation,please try again."
if cherr.Error() == "signing timeout" {
errinfo = "Data network transmission failure in MPC calculation,please try again."
}
AcceptSign(sbd.Raw, sender, from, sig.PubKey, sig.MsgHash, sig.Keytype, sig.GroupID, nonce, sig.ThresHold, sig.Mode, "true", "true", "Failure", "", "", errinfo, ars, workid)
res := RPCSmpcRes{Ret: "", Tip: tip, Err: errors.New(errinfo)}
ch <- res
return errors.New(errinfo)
}
res := RPCSmpcRes{Ret: chret, Tip: "", Err: nil}
ch <- res
return nil
}
if cherr != nil {
common.Error("=====================DoSign,sign fail ================", "key", key, "from", from, "gid", sig.GroupID)
ars := GetAllReplyFromGroup2(w.id,sender)
errinfo := "Abnormal value in MPC calculation,please try again."
if cherr.Error() == "signing timeout" {
errinfo = "Data network transmission failure in MPC calculation,please try again."
}
AcceptSign(sbd.Raw, sender, from, sig.PubKey, sig.MsgHash, sig.Keytype, sig.GroupID, nonce, sig.ThresHold, sig.Mode, "true", "true", "Failure", "", "", errinfo, ars, workid)
res := RPCSmpcRes{Ret: "", Tip: tip, Err: cherr}
ch <- res
return cherr
}
common.Error("=====================DoSign,sign fail,Abnormal value ================", "key", key, "from", from, "gid", sig.GroupID)
ars = GetAllReplyFromGroup2(w.id,sender)
errinfo := "Abnormal value in MPC calculation,please try again."
AcceptSign(sbd.Raw, sender, from, sig.PubKey, sig.MsgHash, sig.Keytype, sig.GroupID, nonce, sig.ThresHold, sig.Mode, "true", "true", "Failure", "", "", errinfo, ars, workid)
res := RPCSmpcRes{Ret: "", Tip: tip, Err: fmt.Errorf(errinfo)}
ch <- res
return fmt.Errorf(errinfo)
}
//------------------------------------------------------------------------------------------------------
// RPCAcceptSign Agree to the sign request
// raw : accept data, including the key of the sign request
func RPCAcceptSign(raw string) (string, string, error) {
if raw == "" {
return "","",errors.New("param error")
}
key, from, _, txdata, err := CheckRaw(raw)
if err != nil {
common.Error("=====================RPCAcceptSign,check raw data error================", "raw", raw, "err", err)
return "Failure", err.Error(), err
}
if key == "" || from == "" || txdata == nil {
return "Failure", "check accept raw data fail", fmt.Errorf("check accept raw data fail")
}
acceptsig, ok := txdata.(*TxDataAcceptSign)
if !ok {
return "Failure", "check raw fail,it is not *TxDataAcceptSign", fmt.Errorf("check raw fail,it is not *TxDataAcceptSign")
}
if acceptsig.Key == "" || acceptsig.Accept == "" {
return "Failure", "check accept raw data fail", fmt.Errorf("check accept raw data fail")
}
exsit, da := GetSignInfoData([]byte(acceptsig.Key))
if exsit {
ac, ok := da.(*AcceptSignData)
if ok && ac != nil {
SendMsgToSmpcGroup(raw, ac.GroupID)
//SetUpMsgList(raw, curEnode)
go ExecApproveSigning(raw,from,acceptsig,ac,true)
return "Success", "", nil
}
}
return "Failure", "accept fail", fmt.Errorf("accept fail")
}
func ExecApproveSigning(raw string,from string,sig *TxDataAcceptSign,ac *AcceptSignData,check bool) {
w, err := FindWorker(sig.Key)
if err != nil || w == nil {
common.Info("===============ExecApproveSigning, worker was not found.=====================", "accept sign key ", sig.Key, "from ", from)
c1data := strings.ToLower(sig.Key + "-" + from)
C1Data.WriteMap(c1data, raw) // save the lastest accept msg??
return
}
if w.approved {
return
}
if ac.Deal == "true" || ac.Status == "Success" || ac.Status == "Failure" || ac.Status == "Timeout" {
common.Info("===============ExecApproveSigning,sign has handled before=====================", "key ", sig.Key, "from ", from)
return
}
reqaddrkey := GetReqAddrKeyByOtherKey(sig.Key, RPCSIGN)
exsit, da := GetPubKeyData([]byte(reqaddrkey))
if !exsit {
common.Error("===============ExecApproveSigning, get reqaddr sigs data fail=====================", "key ",sig.Key, "from ", from)
return
}
acceptreqdata, ok := da.(*AcceptReqAddrData)
if !ok || acceptreqdata == nil {
common.Error("===============ExecApproveSigning, get reqaddr sigs data fail =====================", "key ",sig.Key, "from ", from)
return
}
/////fix bug: miss accept msg for 7-11 test
if Find(w.msgacceptsignres, raw) {
return
}
////
if !IsValidAccept(ac.GroupID,from,acceptreqdata) {
return
}
if !CheckSignDulpRawReply(raw, w.msgacceptsignres) {
return
}
w.msgacceptsignres.PushBack(raw)
if check {
HandleC1Data(acceptreqdata, sig.Key)
}
//status := "Pending"
accept := sig.Accept
if accept == "" {
accept = "DISAGREE"
}
//if sig.Accept != "AGREE" {
// status = "Failure"
//}
//AcceptSign(ac.Initiator, ac.Account, ac.PubKey, ac.MsgHash, ac.Keytype, ac.GroupID, ac.Nonce, ac.LimitNum, ac.Mode, "false", accept, status, "", "", "", nil, ac.WorkID)
/////fix bug: miss accept msg for 7-11 test
if RelayInPeers {
SendMsgToSmpcGroup(raw, ac.GroupID)
}
/////
index := -1
for k,vv := range w.ApprovReplys {
if vv == nil {
continue
}
if strings.EqualFold(vv.From,from) {
index = k
break
}
}
enode := curEnode
if acceptreqdata.Mode == "0" || acceptreqdata.Mode == "2" {
enode = GetENodeByFrom(from,acceptreqdata)
if enode == "" {
return
}
}
reply := &ApprovReply{ENode:enode,From: from, Accept: accept, TimeStamp: sig.TimeStamp}
if index != -1 {
w.ApprovReplys[index] = reply
} else {
w.ApprovReplys = append(w.ApprovReplys,reply)
}
///////
if ac.Mode == "2" {
res := GetReply(w.id)
if res == 0 || res == 1 {
w.approved = true
w.bacceptsignres <- true
workers[ac.WorkID].acceptSignChan <- "go on"
}
return
}
///////
if w.msgacceptsignres.Len() >= w.ThresHold && len(w.ApprovReplys) >= w.ThresHold {
//if !CheckReply(w.msgacceptsignres, RPCSIGN, sig.Key) {
// common.Debug("=====================ExecApproveSigning,receive one msg, but Not all accept data has been received ===================", "raw", raw, "key", sig.Key)
// return
//}
w.approved = true
w.bacceptsignres <- true
workers[ac.WorkID].acceptSignChan <- "go on"
}
}
//------------------------------------------------------------------------------------------
// RPCSignData the sign data of put into the channel to handle
type RPCSignData struct {
Raw string
PubKey string
InputCode string
GroupID string
MsgHash []string
Key string
KeyType string
}
// TxDataSign the data of the special tx of sign
type TxDataSign struct {
TxType string
Account string
Nonce string
PubKey string
InputCode string
MsgHash []string
MsgContext []string
Keytype string
GroupID string
ThresHold string
Mode string
AcceptTimeOut string
TimeStamp string
FixedApprover []string
Comment string
}
// Sign execute the sign command
// raw : sign command data
func Sign(raw string) (string, string, error) {
if raw == "" {
return "","",errors.New("param error")
}
key, from, _, txdata, err := CheckRaw(raw)
if err != nil {
common.Error("=====================Sign,check raw data error================", "raw", raw, "err", err)
return "", err.Error(), err
}
sig, ok := txdata.(*TxDataSign)
if !ok {
return "", "check raw fail,it is not *TxDataSign", fmt.Errorf("check raw fail,it is not *TxDataSign")
}
common.Debug("=====================Sign================", "key", key, "from", from, "raw", raw)
/////
exsit, _ := GetSignInfoData([]byte(key))
if !exsit {
exsit, _ = GetPubKeyData([]byte(key))
}
if exsit {
common.Debug("=====================Sign,The sign command already exist================", "key", key, "from", from, "raw", raw)
return "","",fmt.Errorf("The sign command already exist")
}
if sig.Mode == "2" {
pickdata := make([]*PickHashData, 0)
pickhash := make([]*PickHashKey, 0)
m := make(map[string]string)
send, err := CompressSignBrocastData(raw, pickhash)
if err != nil || send == "" {
return "","",err
}
m["ComSignBrocastData"] = send
m["Type"] = "ComSignBrocastData"
val, err := json.Marshal(m)
if err != nil {
return "", "",err
}
SendMsgToSmpcGroup(string(val), sig.GroupID)
m2 := make(map[string]string)
selfsend, err := CompressSignData(raw, pickdata)
if err != nil || selfsend == "" {
return "","",err
}
m2["ComSignData"] = selfsend
m2["Type"] = "ComSignData"
val2, err := json.Marshal(m2)
if err != nil {
return "", "",err
}
msghash := Keccak256Hash([]byte(strings.ToLower(string(val)))).Hex()
MsgReceiv.WriteMap(msghash,NowMilliStr())
SetUpMsgList(string(val2), curEnode)
return key,"",nil
}
/////
if sig.Keytype == smpclib.ED25519 || sig.Keytype == smpclib.SR25519 {
pickdata := make([]*PickHashData, 0)
pickhash := make([]*PickHashKey, 0)
m := make(map[string]string)
send, err := CompressSignBrocastData(raw, pickhash)
if err != nil || send == "" {
return "","",err
}
m["ComSignBrocastData"] = send
m["Type"] = "ComSignBrocastData"
val, err := json.Marshal(m)
if err != nil {
return "", "",err
}
SendMsgToSmpcGroup(string(val), sig.GroupID)
m2 := make(map[string]string)
selfsend, err := CompressSignData(raw, pickdata)
if err != nil || selfsend == "" {
return "","",err
}
m2["ComSignData"] = selfsend
m2["Type"] = "ComSignData"
val2, err := json.Marshal(m2)
if err != nil {
return "", "",err
}
msghash := Keccak256Hash([]byte(strings.ToLower(string(val)))).Hex()
MsgReceiv.WriteMap(msghash,NowMilliStr())
SetUpMsgList(string(val2), curEnode)
} else {
rsd := &RPCSignData{Raw: raw, PubKey: sig.PubKey, InputCode: sig.InputCode, GroupID: sig.GroupID, MsgHash: sig.MsgHash, Key: key,KeyType:sig.Keytype}
SignChan <- rsd
//go HandleRPCSign2(rsd)
}
return key, "", nil
}
func DoPreSign(pubkey string,gid string,hash string,mode string,keytype string) string {
if pubkey == "" || gid == "" || hash == "" || mode == "" {
return ""
}
pub := Keccak256Hash([]byte(strings.ToLower(pubkey + ":" + gid))).Hex()
if mode != "2" {
PutPreSigal(pub, true)
err := SavePrekeyToDb(pubkey, "", gid,keytype)
if err != nil {
common.Error("=========================DoPreSign,save (pubkey,gid) to db fail=======================", "pubkey", pubkey, "gid", gid,"hash",hash, "err", err)
return ""
}
}
tt := fmt.Sprintf("%v", time.Now().UnixNano()/1e6)
nonce := Keccak256Hash([]byte(strings.ToLower(pub + tt + hash))).Hex()
ps := &PreSign{Pub: pubkey, Gid: gid, Nonce: nonce,Index:-1,KeyType:keytype}
m := make(map[string]string)
psjson, err := ps.MarshalJSON()
if err == nil {
m["PreSign"] = string(psjson)
}
m["Type"] = "PreSign"
val, err := json.Marshal(m)
if err != nil {
return ""
}
SendMsgToSmpcGroup(string(val), gid)
//check msg
msghash := Keccak256Hash([]byte(strings.ToLower(string(val)))).Hex()
_,exist := MsgReceiv.ReadMap(msghash)
if exist {
return ""
}
MsgReceiv.WriteMap(msghash,NowMilliStr())
rch := make(chan interface{}, 1)
SetUpMsgList3(string(val), curEnode, rch)
reply := false
timeout := make(chan bool, 1)
go func() {
syncWaitTime := 600 * time.Second
syncWaitTimeOut := time.NewTicker(syncWaitTime)
for {
select {
case v := <-rch:
ret, ok := v.(RPCSmpcRes)
if ok {
if ret.Err != nil {
reply = false
timeout <- false
} else {
reply = true
timeout <- false
}
} else {
reply = false
timeout <- false
}
return
case <-syncWaitTimeOut.C:
reply = false
timeout <- true
return
}
}
}()
<-timeout
if !reply {
DelPrekeyFromDb(pubkey, "", gid,keytype)
DeletePreSignData(pubkey,"",gid,nonce)
common.Error("=====================DoPreSign, failed to pre-generate sign data.========================", "pubkey", pubkey, "sub-groupid", gid, "hash", hash,"index",ps.Index)
return ""
}
common.Info("================================DoPreSign,success to pre-generation of sign data==================================", "pubkey", pubkey, "sub-groupid", gid, "hash", hash,"index",ps.Index,"data key",nonce)
return nonce
}
func HandleRPCSign2(rsd *RPCSignData) {
if rsd == nil {
return
}
smpcpks, err := hex.DecodeString(rsd.PubKey)
if err != nil {
common.Error("[SIGN] decode pubkey string error", "pubkey", rsd.PubKey, "key", rsd.Key,"err",err)
return
}
exsit, da := GetPubKeyData(smpcpks[:])
common.Debug("=========================HandleRpcSign2======================", "rsd.Pubkey", rsd.PubKey, "key", rsd.Key, "exsit", exsit)
if !exsit {
return
}
_, ok := da.(*PubKeyData)
common.Debug("=========================HandleRpcSign2======================", "rsd.Pubkey", rsd.PubKey, "key", rsd.Key, "exsit", exsit, "ok", ok)
if !ok {
return
}
var datakey string
var pick *PreSignData
bret := false
pickdata := make([]*PickHashData, 0)
pickhash := make([]*PickHashKey, 0)
for _, vv := range rsd.MsgHash {
go func(hashtmp string) {
for {
if bret {
common.Debug("=========================HandleRpcSign2,pick pre-sign data fail======================", "rsd.Pubkey", rsd.PubKey, "key", rsd.Key, "gid", rsd.GroupID)
return
}
datakey = DoPreSign(rsd.PubKey,rsd.GroupID,hashtmp,"0",rsd.KeyType)
if datakey == "" {
time.Sleep(time.Duration(1) * time.Second)
continue
}
common.Debug("=========================HandleRpcSign2,pick pre-sign data succes======================", "rsd.Pubkey", rsd.PubKey, "key", rsd.Key, "gid", rsd.GroupID,"data key",datakey)
return
}
}(vv)
timeout := make(chan bool, 1)
rch := make(chan bool, 1)
go func() {
for {
if bret {
common.Debug("=========================HandleRpcSign2,pick pre-sign data fail======================", "rsd.Pubkey", rsd.PubKey, "key", rsd.Key, "gid", rsd.GroupID)
return
}
pick = GetPreSignData(rsd.PubKey,rsd.InputCode,rsd.GroupID,datakey)
if pick != nil {
common.Debug("=========================HandleRpcSign2,pick pre-sign data successfully======================", "rsd.Pubkey", rsd.PubKey, "key", rsd.Key, "gid", rsd.GroupID,"pick key",pick.Key,"data key",datakey)
rch <-true
bret = false
return
}
time.Sleep(time.Duration(3) * time.Second)
}
}()
go func() {
syncWaitTime := 600 * time.Second
syncWaitTimeOut := time.NewTicker(syncWaitTime)
for {
select {
case <-rch:
//common.Debug("=========================HandleRpcSign,pick pre-sign data finish======================", "rsd.Pubkey", rsd.PubKey, "key", rsd.Key, "gid", rsd.GroupID,"pick key",pick.Key)
bret = false
timeout <-false
return
case <-syncWaitTimeOut.C:
common.Debug("=========================HandleRpcSign2,pick pre-sign data timeout======================", "rsd.Pubkey", rsd.PubKey, "key", rsd.Key, "gid", rsd.GroupID)
bret = true
time.Sleep(time.Duration(2) * time.Second) //wait bret to exit
timeout <- true
return
}
}
}()
<-timeout
if bret {
return
}
err = DeletePreSignData(rsd.PubKey,rsd.InputCode,rsd.GroupID,pick.Key)
if err != nil {
log.Error("============================HandleRpcSign2,delete pre-sign data fail============================","err",err,"pubkey",rsd.PubKey,"gid",rsd.GroupID,"data key",pick.Key)
return
}
common.Info("========================HandleRpcSign2,choose pickkey==================", "txhash", vv, "pickkey", pick.Key, "key", rsd.Key)
ph := &PickHashKey{Hash: vv, PickKey: pick.Key}
pickhash = append(pickhash, ph)
phd := &PickHashData{Hash: vv, Pre: pick}
pickdata = append(pickdata, phd)
datakey = ""
pick = nil
}
if bret {
return
}
m := make(map[string]string)
send, err := CompressSignBrocastData(rsd.Raw, pickhash)
if err == nil {
m["ComSignBrocastData"] = send
}
m["Type"] = "ComSignBrocastData"
val, err := json.Marshal(m)
if err != nil {
common.Error("=========================HandleRpcSign2======================", "rsd.Pubkey", rsd.PubKey, "key", rsd.Key, "exsit", exsit, "ok", ok, "bret", bret, "err", err)
return
}
SendMsgToSmpcGroup(string(val), rsd.GroupID)
m2 := make(map[string]string)
selfsend, err := CompressSignData(rsd.Raw, pickdata)
if err == nil {
m2["ComSignData"] = selfsend
}
m2["Type"] = "ComSignData"
val2, err := json.Marshal(m2)
if err != nil {
common.Error("=========================HandleRpcSign2,compress hash data.======================", "rsd.Pubkey", rsd.PubKey, "key", rsd.Key, "exsit", exsit, "ok", ok, "bret", bret, "err", err)
return
}
msghash := Keccak256Hash([]byte(strings.ToLower(string(val)))).Hex()
MsgReceiv.WriteMap(msghash,NowMilliStr())
SetUpMsgList(string(val2), curEnode)
}
// HandleRPCSign handle sign request,read sign command from the channel and do it!
func HandleRPCSign() {
for {
rsd := <-SignChan
smpcpks, err := hex.DecodeString(rsd.PubKey)
if err != nil {
common.Error("[SIGN] decode pubkey string error", "pubkey", rsd.PubKey, "key", rsd.Key,"err",err)
continue
}
exsit, da := GetPubKeyData(smpcpks[:])
if !exsit {
common.Debug("=====================HandleRPCSign,sign cmd not in pubkeydata================", "key",rsd.Key, "pubkey", rsd.PubKey)
continue
}
_, ok := da.(*PubKeyData)
if !ok {
common.Debug("=====================HandleRPCSign,sign cmd data error================", "key",rsd.Key, "pubkey", rsd.PubKey)
continue
}
var pub string
if rsd.InputCode != "" {
pub = Keccak256Hash([]byte(strings.ToLower(rsd.PubKey + ":" + rsd.InputCode + ":" + rsd.GroupID))).Hex()
} else {
pub = Keccak256Hash([]byte(strings.ToLower(rsd.PubKey + ":" + rsd.GroupID))).Hex()
}
bret := false
pickdata := make([]*PickHashData, 0)
pickhash := make([]*PickHashKey, 0)
for _, vv := range rsd.MsgHash {
pick := PickPreSignData(rsd.PubKey, rsd.InputCode, rsd.GroupID)
if pick == nil {
common.Debug("=========================HandleRpcSign,pick pre-sign fail and auto generate the pre-sign data by self======================", "rsd.Pubkey", rsd.PubKey, "key", rsd.Key)
go HandleRPCSign2(rsd)
bret = true
break
}
common.Info("========================HandleRpcSign,pick pre-sign data success,no need to generate pre-sign data by self==================", "txhash", vv, "pickkey", pick.Key, "key", rsd.Key)
ph := &PickHashKey{Hash: vv, PickKey: pick.Key}
pickhash = append(pickhash, ph)
phd := &PickHashData{Hash: vv, Pre: pick}
pickdata = append(pickdata, phd)
//check pre sigal
if rsd.InputCode != "" {
if GetTotalCount(rsd.PubKey, rsd.InputCode, rsd.GroupID) >= (PreBip32DataCount/2) && GetTotalCount(rsd.PubKey, rsd.InputCode, rsd.GroupID) <= PreBip32DataCount {
PutPreSigal(pub, false)
} else {
PutPreSigal(pub, true)
}
} else {
if GetTotalCount(rsd.PubKey, "", rsd.GroupID) >= (PrePubDataCount*3/4) && GetTotalCount(rsd.PubKey, "", rsd.GroupID) <= PrePubDataCount {
PutPreSigal(pub, false)
} else {
PutPreSigal(pub, true)
}
}
}
if bret {
common.Debug("=====================HandleRPCSign,return is true================", "key",rsd.Key, "pubkey", rsd.PubKey)
continue
}
m := make(map[string]string)
send, err := CompressSignBrocastData(rsd.Raw, pickhash)