-
Notifications
You must be signed in to change notification settings - Fork 38
/
contract.go
877 lines (760 loc) · 28.7 KB
/
contract.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
package main
import (
"encoding/hex"
"errors"
"fmt"
"log"
"math/big"
"strconv"
"strings"
"time"
"unsafe"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/miguelmota/go-solidity-sha3"
)
var ProviderURL = "https://ropsten.infura.io/v3/198fa8670c224bc49a56f4828fcad728"
var GAdminAuth *bind.TransactOpts
var ZkPoDExchangeClient *ZkPoDExchange
//ConnectToProvider connects to contract
func ConnectToProvider(key *keystore.Key, zkPODEXAddr string, Log ILogger) error {
fmt.Println(key.Address.Hex())
/**
* Connecting to provider
*/
var err error
Log.Infof("Dial with provider...url=%v", ProviderURL)
client, err := ethclient.Dial(ProviderURL)
if err != nil {
Log.Warnf("Failed to dial provider, err=%v", err)
return err
}
auth := bind.NewKeyedTransactor(key.PrivateKey)
zkPODEXContractAddr := common.HexToAddress(zkPODEXAddr)
pClient, err := NewZkPoDExchange(zkPODEXContractAddr, client)
if err != nil {
return err
}
GAdminAuth = auth
ZkPoDExchangeClient = pClient
Log.Infof("connect to contract...contract addr=%v", zkPODEXAddr)
return nil
}
func publishPlainDataToContract(b Bulletin, value int64) (string, error) {
size, _ := strconv.ParseUint(b.Size, 10, 64)
s, _ := strconv.ParseUint(b.S, 10, 64)
n, _ := strconv.ParseUint(b.N, 10, 64)
mklrootInt := new(big.Int)
mklroot, rs := mklrootInt.SetString(b.SigmaMKLRoot, 16)
if !rs {
return "", errors.New("failed to convert sessionId")
}
GAdminAuth.Value = big.NewInt(value)
defer func() {
GAdminAuth.Value = big.NewInt(0)
}()
ctx, err := ZkPoDExchangeClient.ZkPoDExchangeTransactor.Publish(GAdminAuth, size, s, n, mklroot, big.NewInt(0), big.NewInt(0))
if err != nil {
return "", fmt.Errorf("failed to Publish: %v", err)
}
return ctx.Hash().Hex(), nil
}
func publishTableDataToContract(b Bulletin, value int64) (string, error) {
s, _ := strconv.ParseUint(b.S, 10, 64)
n, _ := strconv.ParseUint(b.N, 10, 64)
mklrootInt := new(big.Int)
mklroot, rs := mklrootInt.SetString(b.SigmaMKLRoot, 16)
if !rs {
return "", errors.New("failed to convert sessionId")
}
digestInt := new(big.Int)
digest, rs := digestInt.SetString(b.VRFMetaDigest, 16)
if !rs {
return "", errors.New("failed to convert VRFMetaDigest")
}
GAdminAuth.Value = big.NewInt(value)
defer func() {
GAdminAuth.Value = big.NewInt(0)
}()
ctx, err := ZkPoDExchangeClient.ZkPoDExchangeTransactor.Publish(GAdminAuth, 0, s, n, mklroot, digest, big.NewInt(1))
if err != nil {
return "", fmt.Errorf("failed to Publish: %v", err)
}
return ctx.Hash().Hex(), nil
}
func closeDataAtContract(bltByte [32]byte) (string, bool, error) {
ctx, err := ZkPoDExchangeClient.ZkPoDExchangeTransactor.UnPublish(GAdminAuth, bltByte)
if err != nil {
return "", false, fmt.Errorf("failed to close published data. err=%v", err)
}
return ctx.Hash().Hex(), true, nil
}
func readDataStatusAtContract(bltByte [32]byte) (string, error) {
bulletins, err := ZkPoDExchangeClient.ZkPoDExchangeCaller.Bulletins(&bind.CallOpts{}, bltByte)
if err != nil {
return "", fmt.Errorf("failed to read bulletins. err=%v", err)
}
if bulletins.Stat == 0 {
return "OK", nil
} else if bulletins.Stat == 1 {
return "CANCELING", nil
} else if bulletins.Stat == 2 {
return "CANCELED", nil
} else {
return "UNKNOWN", nil
}
}
func withdrawAETHFromContract(bltByte [32]byte, Log ILogger) (string, error) {
t := time.Now()
ctx, err := ZkPoDExchangeClient.ZkPoDExchangeTransactor.WithdrawA(GAdminAuth, bltByte)
if err != nil {
Log.Warnf("failed to withdraw from closed data: %v", err)
return "", errors.New("Failed to withdraw")
}
log.Printf("withdraw from close data...time cost=%v\n", time.Since(t))
return ctx.Hash().Hex(), nil
}
func BobDeposit(value int64, AliceAddr string) (string, error) {
GAdminAuth.Value = big.NewInt(value)
defer func() {
GAdminAuth.Value = big.NewInt(0)
}()
ctx, err := ZkPoDExchangeClient.ZkPoDExchangeTransactor.BobDeposit(GAdminAuth, common.HexToAddress(AliceAddr))
if err != nil {
return "", fmt.Errorf("failed to deposit to %v in contract. err=%v", AliceAddr, err)
}
return ctx.Hash().Hex(), nil
}
func BobUnDeposit(AliceAddr string) (string, error) {
ctx, err := ZkPoDExchangeClient.ZkPoDExchangeTransactor.BobUnDeposit(GAdminAuth, common.HexToAddress(AliceAddr))
if err != nil {
return "", fmt.Errorf("failed to undeposit to %v. err=%v", AliceAddr, err)
}
return ctx.Hash().Hex(), nil
}
func BobWithdrawETHFromContract(AliceAddr string) (string, bool, error) {
ctx, err := ZkPoDExchangeClient.ZkPoDExchangeTransactor.WithdrawB(GAdminAuth, common.HexToAddress(AliceAddr))
if err != nil {
return "", false, fmt.Errorf("failed to withdraw from closed data: %v", err)
}
return ctx.Hash().Hex(), true, nil
}
func submitScrtForComplaint(tx Transaction, receiptSign []byte, Log ILogger) (string, error) {
seed0Path := BConf.AliceDir + "/transaction/" + tx.SessionID + "/secret"
receiptPath := BConf.AliceDir + "/transaction/" + tx.SessionID + "/receipt"
_, receipt, err := readReceiptForComplaint(receiptPath, Log)
if err != nil {
Log.Warnf("failed to read receipt. err=%v", err)
return "", errors.New("failed to read receipt")
}
seed2Byte, err := hex.DecodeString(receipt.S)
if err != nil {
Log.Warnf("failed to decode seed2. seed2string=%v, err=%v", receipt.S, err)
return "", errors.New("failed to decode seed2")
}
mklByte, err := hex.DecodeString(receipt.K)
if err != nil {
Log.Warnf("failed to decode mkl root. mklroot=%v, err=%v", receipt.K, err)
return "", errors.New("failed to decode mkl root")
}
sessionInt := new(big.Int)
sessionInt, rs := sessionInt.SetString(tx.SessionID, 10)
if !rs {
Log.Warnf("failed to convert sessionId.")
return "", errors.New("failed to convert sessionId")
}
bltKey, err := calcuBltKey(tx.Bulletin)
if err != nil {
Log.Warnf("failed to calculate blt key. tx.Bulletin=%v, err=%v", tx.Bulletin, err)
return "", errors.New("failed to calculate blt key")
}
err = verifySigntureForComplaint(tx, sessionInt, bltKey, receiptSign, receipt, Log)
if err != nil {
Log.Warnf("verify signature error! err=%v", err)
return "", errors.New("verify signature error")
}
secret, err := readSeed0ForComplaint(seed0Path, Log)
if err != nil {
Log.Warnf("failed to read seed0. err=%v", err)
return "", errors.New("failed to read seed0")
}
seedByte, err := hex.DecodeString(secret.S)
if err != nil {
Log.Warnf("failed to decode seed. seedstring=%v, err=%v", secret.S, err)
return "", errors.New("failed to parse seed file")
}
t := time.Now()
var _addrs [2]common.Address
_addrs[0] = common.HexToAddress(tx.BobAddr)
_addrs[1] = common.HexToAddress(tx.AliceAddr)
//func (_ZkPoDExchange *ZkPoDExchangeTransactor) SubmitProofComplaint(opts *bind.TransactOpts, _seed0 [32]byte, _sid *big.Int,
// _addrs [2]common.Address, _bltKey [32]byte, _seed2 [32]byte, _k_mkl_root [32]byte, _count uint64, _price *big.Int, _expireAt *big.Int, _sig []byte)
ctx, err := ZkPoDExchangeClient.ZkPoDExchangeTransactor.SubmitProofComplaint(GAdminAuth, *byte32(seedByte), sessionInt,
_addrs, bltKey, *byte32(seed2Byte), *byte32(mklByte), receipt.C, big.NewInt(tx.Price), big.NewInt(tx.ExpireAt), receiptSign)
if err != nil {
Log.Warnf("failed to submit proof. err=%v", err)
return "", errors.New("failed to submit proof")
}
Log.Debugf("POD submit proof successfully, time cost=%v\n",
time.Since(t))
return ctx.Hash().Hex(), nil
}
func verifySigntureForComplaint(tx Transaction, sessionInt *big.Int, bltKey [32]byte, receiptSign []byte, receipt ComplaintReceipt, Log ILogger) error {
if len(receiptSign) != 65 {
Log.Warnf("invalid signature. sig=%v, len(sig)=%v", hexutil.Encode(receiptSign), len(receiptSign))
return errors.New("invalid signature")
}
receiptHash := solsha3.SoliditySHA3( // types
[]string{"uint256", "address", "address", "bytes32", "bytes32", "bytes32", "uint64", "uint256", "uint256"},
// values
[]interface{}{
sessionInt,
common.HexToAddress(tx.BobAddr),
common.HexToAddress(tx.AliceAddr),
bltKey,
"0x" + receipt.S,
"0x" + receipt.K,
receipt.C,
big.NewInt(tx.UnitPrice * tx.Count),
big.NewInt(tx.ExpireAt),
})
Log.Debugf("generate receipt receiptHash=0x%02x\n", receiptHash)
receiptHash = solsha3.SoliditySHA3WithPrefix(receiptHash)
sigPublicKeyECDSA, err := crypto.SigToPub(receiptHash, receiptSign)
if err != nil {
Log.Warnf("failed to generate pub key from signature. err=%v", err)
return errors.New("verify signature error")
}
if crypto.PubkeyToAddress(*sigPublicKeyECDSA) != common.HexToAddress(tx.BobAddr) {
Log.Warnf("failed to verify signature.")
return errors.New("failed to verify signature")
}
return nil
}
func readScrtForComplaint(sessionID string, AliceAddr string, BobAddr string, Log ILogger) (ComplaintSecret, error) {
var secret ComplaintSecret
for i := 0; i < 20; i++ {
Log.Debugf("round %v, read secret from contract. sessionId=%v", i+1, sessionID)
sessionInt := new(big.Int)
sessionInt, rs := sessionInt.SetString(sessionID, 10)
if !rs {
Log.Warnf("Failed to convert sessionId.")
return secret, errors.New("Failed to convert sessionId")
}
t := time.Now()
records, err := ZkPoDExchangeClient.ZkPoDExchangeCaller.GetRecordComplaint(&bind.CallOpts{}, common.HexToAddress(AliceAddr), common.HexToAddress(BobAddr), sessionInt)
if err != nil {
Log.Warnf("Failed to read session record: %v", err)
return secret, errors.New("Failed to read session record")
}
Log.Debugf("POD reads secret from contract...time cost=%v\n",
time.Since(t))
if records.SubmitAt.Int64() == 0 {
time.Sleep(30 * time.Second)
continue
}
secret.S = hex.EncodeToString(records.Seed0[:])
return secret, nil
}
return secret, errors.New("No secret to be read")
}
func claimToContractForComplaint(sessionID string, bulletin Bulletin, claimFile string, AliceAddr string, Log ILogger) (string, error) {
sessionInt := new(big.Int)
sessionInt, rs := sessionInt.SetString(sessionID, 10)
if !rs {
Log.Warnf("Failed to convert sessionId.")
return "", errors.New("Failed to convert sessionId")
}
claim, err := readClaim(claimFile, Log)
if err != nil {
Log.Warnf("Failed to read claim. err=%v", err)
return "", errors.New("Failed to read claim")
}
var mkls = make([][32]byte, len(claim.M))
for i, v := range claim.M {
mklbyte, err := hex.DecodeString(v)
if err != nil {
Log.Warnf("failed to decode merkle root. mkl=%v, err=%v", v, err)
return "", errors.New("failed to decode merkle root")
}
mkls[i] = *byte32(mklbyte)
}
ks := strings.Split(claim.K, " ")
if len(ks) < 3 {
Log.Warnf("Invalid k in claim. err=%v", err)
return "", errors.New("Invalid k in claim")
}
txInt := new(big.Int)
tx, rs := txInt.SetString(ks[1], 10)
if !rs {
Log.Warnf("Failed to convert k[1]. ks[1]=%v", ks[1])
return "", errors.New("Failed to convert k[1]")
}
tyInt := new(big.Int)
ty, rs := tyInt.SetString(ks[2], 10)
if !rs {
Log.Warnf("Failed to convert k[2]. ks[2]=%v", ks[2])
return "", errors.New("Failed to convert k[2]")
}
Log.Debugf("Alice addr=%v, sessionInt=%v, i=%v, j=%v,tx=%v,ty=%v,merkle root length=%v",
AliceAddr, sessionInt, claim.I, claim.J, tx, ty, len(mkls))
_sCnt, err := strconv.ParseUint(bulletin.S, 10, 64)
if err != nil {
Log.Warnf("failed to convert sCnt. sCnt=%v, err=%v", _sCnt, err)
return "", errors.New("failed to convert sCnt")
}
t := time.Now()
ctx, err := ZkPoDExchangeClient.ZkPoDExchangeTransactor.ClaimComplaint(GAdminAuth, common.HexToAddress(AliceAddr), sessionInt,
claim.I, claim.J, tx, ty, mkls, _sCnt)
if err != nil {
Log.Warnf("Failed to submit claim. err=%v", err)
return "", errors.New("Failed to submit claim")
}
Log.Debugf("POD submit claim successfully, time cost=%v\n",
time.Since(t))
return ctx.Hash().Hex(), nil
}
func settleDealForComplaint(sessionID string, AliceAddr string, BobAddr string) (string, error) {
sessionInt := new(big.Int)
sessionInt, rs := sessionInt.SetString(sessionID, 10)
if !rs {
return "", errors.New("failed to convert sessionId")
}
ctx, err := ZkPoDExchangeClient.ZkPoDExchangeTransactor.SettleComplaintDeal(GAdminAuth, common.HexToAddress(AliceAddr), common.HexToAddress(BobAddr), sessionInt)
if err != nil {
return "", fmt.Errorf("failed to settle deal. sessionID=%v, err=%v", sessionID, err)
}
return ctx.Hash().Hex(), nil
}
func submitScrtForAtomicSwap(tx Transaction, receiptSign []byte, Log ILogger) (string, error) {
seed0Path := BConf.AliceDir + "/transaction/" + tx.SessionID + "/secret"
receiptPath := BConf.AliceDir + "/transaction/" + tx.SessionID + "/receipt"
sessionInt := new(big.Int)
sessionInt, rs := sessionInt.SetString(tx.SessionID, 10)
if !rs {
Log.Warnf("failed to convert sessionId.")
return "", errors.New("failed to convert sessionId")
}
_, receipt, err := readReceiptForAtomicSwap(receiptPath, Log)
if err != nil {
Log.Warnf("failed to read receipt. err=%v", err)
return "", errors.New("failed to read receipt")
}
seed2Byte, err := hex.DecodeString(receipt.S)
if err != nil {
Log.Warnf("failed to decode seed2. seed2string=%v, err=%v", receipt.S, err)
return "", errors.New("failed to decode seed2")
}
vwInt := new(big.Int)
vwInt, rs = vwInt.SetString(receipt.VW, 10)
if !rs {
Log.Warnf("failed to convert vw. vw=%v", receipt.VW)
return "", errors.New("failed to convert vw")
}
Log.Debugf(" _sessionId=%v, Bob address=%v, seed2=%v, vwInt=%v, _count=%v,",
sessionInt, tx.BobAddr, seed2Byte, vwInt, receipt.C)
err = verifySigntureForAtomicSwap(tx, sessionInt, vwInt, receiptSign, receipt, Log)
if err != nil {
Log.Warnf("verify signature error! err=%v", err)
return "", errors.New("verify signature error")
}
secret, err := readSeed0ForAtomicSwap(seed0Path, Log)
if err != nil {
Log.Warnf("failed to read seed0. err=%v", err)
return "", errors.New("failed to read seed0")
}
seedByte, err := hex.DecodeString(secret.S)
if err != nil {
Log.Warnf("failed to decode seed s. seedstring=%v, err=%v", secret.S, err)
return "", errors.New("failed to parse seed2 file")
}
_sCnt, err := strconv.ParseUint(tx.Bulletin.S, 10, 64)
if err != nil {
Log.Warnf("failed to convert sCnt. sCnt=%v, err=%v", _sCnt, err)
return "", errors.New("failed to convert sCnt")
}
Log.Debugf("seedByte=%v, _sCnt=%v, sessionInt=%v, BobAddr=%v,seed2Byte=%v, vwInt=%v, receipt.C=%v, tx.Price=%v, tx.ExpireAt=%v, receiptSign=%v",
*byte32(seedByte), _sCnt, sessionInt, tx.BobAddr, *byte32(seed2Byte), vwInt, receipt.C, big.NewInt(tx.Price), big.NewInt(tx.ExpireAt), receiptSign)
t := time.Now()
var _addrs [2]common.Address
_addrs[0] = common.HexToAddress(tx.BobAddr)
_addrs[1] = common.HexToAddress(tx.AliceAddr)
ctx, err := ZkPoDExchangeClient.ZkPoDExchangeTransactor.SubmitProofAtomicSwap(GAdminAuth, *byte32(seedByte), _sCnt, sessionInt,
_addrs, *byte32(seed2Byte), vwInt, receipt.C, big.NewInt(tx.Price), big.NewInt(tx.ExpireAt), receiptSign)
if err != nil {
Log.Warnf("failed to submit proof. err=%v", err)
return "", errors.New("failed to submit proof")
}
Log.Debugf("POD submit proof successfully, time cost=%v\n",
time.Since(t))
return ctx.Hash().Hex(), nil
}
func verifySigntureForAtomicSwap(tx Transaction, sessionInt *big.Int, vwInt *big.Int, receiptSign []byte, receipt AtomicSwapReceipt, Log ILogger) error {
if len(receiptSign) != 65 {
Log.Warnf("invalid signature. sig=%v, len(sig)=%v", hexutil.Encode(receiptSign), len(receiptSign))
return errors.New("invalid signature")
}
receiptHash := solsha3.SoliditySHA3( // types
[]string{"uint256", "address", "address", "bytes32", "uint256", "uint64", "uint256", "uint256"},
// values
[]interface{}{
sessionInt,
common.HexToAddress(tx.BobAddr),
common.HexToAddress(tx.AliceAddr),
"0x" + receipt.S,
vwInt,
receipt.C,
big.NewInt(tx.UnitPrice * tx.Count),
big.NewInt(tx.ExpireAt),
})
Log.Debugf("generate receipt receiptHash=0x%02x\n", receiptHash)
receiptHash = solsha3.SoliditySHA3WithPrefix(receiptHash)
sigPublicKeyECDSA, err := crypto.SigToPub(receiptHash, receiptSign)
if err != nil {
Log.Warnf("failed to generate pub key from signature. err=%v", err)
return errors.New("verify signature error")
}
if crypto.PubkeyToAddress(*sigPublicKeyECDSA) != common.HexToAddress(tx.BobAddr) {
Log.Warnf("failed to verify signature.")
return errors.New("failed to verify signature")
}
return nil
}
func readScrtForAtomicSwap(sessionID string, AliceAddr string, BobAddr string, Log ILogger) (AtomicSwapSecret, error) {
var secret AtomicSwapSecret
for i := 0; i < 20; i++ {
Log.Debugf("round %v, read secret from contract. sessionId=%v", i+1, sessionID)
sessionInt := new(big.Int)
sessionInt, rs := sessionInt.SetString(sessionID, 10)
if !rs {
Log.Warnf("Failed to convert sessionId.")
return secret, errors.New("Failed to convert sessionId")
}
t := time.Now()
records, err := ZkPoDExchangeClient.ZkPoDExchangeCaller.GetRecordAtomicSwap(&bind.CallOpts{}, common.HexToAddress(AliceAddr), common.HexToAddress(BobAddr), sessionInt)
if err != nil {
Log.Warnf("Failed to read session record: %v", err)
return secret, errors.New("Failed to read session record")
}
Log.Debugf("POD reads secret from contract...time cost=%v\n",
time.Since(t))
if records.SubmitAt.Int64() == 0 {
time.Sleep(30 * time.Second)
continue
}
secret.S = hex.EncodeToString(records.Seed0[:])
return secret, nil
}
return secret, errors.New("No secret to be read")
}
func submitScrtForAtomicSwapVc(tx Transaction, receiptSign []byte, Log ILogger) (string, error) {
seed0Path := BConf.AliceDir + "/transaction/" + tx.SessionID + "/secret"
receiptPath := BConf.AliceDir + "/transaction/" + tx.SessionID + "/receipt"
sessionInt := new(big.Int)
sessionInt, rs := sessionInt.SetString(tx.SessionID, 10)
if !rs {
Log.Warnf("failed to convert sessionId.")
return "", errors.New("failed to convert sessionId")
}
_, receipt, err := readReceiptForAtomicSwapVc(receiptPath, Log)
if err != nil {
Log.Warnf("failed to read receipt. err=%v", err)
return "", errors.New("failed to read receipt")
}
digestInt := new(big.Int)
digestInt, rs = digestInt.SetString(receipt.D, 10)
if !rs {
Log.Warnf("failed to convert digestInt. receipt.D=%v", receipt.D)
return "", errors.New("failed to convert digestInt")
}
Log.Debugf(" _sessionId=%v, Bob address=%v, digestInt=%v", sessionInt, tx.BobAddr, digestInt)
err = verifySigntureForAtomicSwapVc(tx, sessionInt, receiptSign, digestInt, Log)
if err != nil {
Log.Warnf("verify signature error! err=%v", err)
return "", errors.New("verify signature error")
}
secret, err := readSeed0ForAtomicSwapVc(seed0Path, Log)
if err != nil {
Log.Warnf("failed to read seed0. err=%v", err)
return "", errors.New("failed to read seed0")
}
seed0Int := new(big.Int)
seed0Int, rs = seed0Int.SetString(secret.S, 10)
if !rs {
Log.Warnf("failed to convert seed0Int. secret.S=%v", secret.S)
return "", errors.New("failed to convert seed0Int")
}
randInt := new(big.Int)
randInt, rs = randInt.SetString(secret.R, 10)
if !rs {
Log.Warnf("failed to convert digestInt. secret.R=%v", secret.R)
return "", errors.New("failed to convert digestInt")
}
Log.Debugf("seedByte=%v, randByte=%v, sessionInt=%v, BobAddr=%v, receipt.D=%v, tx.Price=%v, tx.ExpireAt=%v, receiptSign=%v",
seed0Int, randInt, sessionInt, tx.BobAddr, receipt.D, big.NewInt(tx.Price), big.NewInt(tx.ExpireAt), receiptSign)
t := time.Now()
var _addrs [2]common.Address
_addrs[0] = common.HexToAddress(tx.BobAddr)
_addrs[1] = common.HexToAddress(tx.AliceAddr)
ctx, err := ZkPoDExchangeClient.ZkPoDExchangeTransactor.SubmitProofAtomicSwapVC(GAdminAuth, seed0Int, randInt,
sessionInt, _addrs, digestInt, big.NewInt(tx.Price), big.NewInt(tx.ExpireAt), receiptSign)
if err != nil {
Log.Warnf("failed to submit proof. err=%v", err)
return "", errors.New("failed to submit proof")
}
Log.Debugf("POD submit proof successfully, time cost=%v\n",
time.Since(t))
return ctx.Hash().Hex(), nil
}
func verifySigntureForAtomicSwapVc(tx Transaction, sessionInt *big.Int, receiptSign []byte, digestInt *big.Int, Log ILogger) error {
if len(receiptSign) != 65 {
Log.Warnf("invalid signature. sig=%v, len(sig)=%v", hexutil.Encode(receiptSign), len(receiptSign))
return errors.New("invalid signature")
}
receiptHash := solsha3.SoliditySHA3( // types
[]string{"uint256", "address", "address", "uint256", "uint256", "uint256"},
// values
[]interface{}{
sessionInt,
common.HexToAddress(tx.BobAddr),
common.HexToAddress(tx.AliceAddr),
digestInt,
big.NewInt(tx.UnitPrice * tx.Count),
big.NewInt(tx.ExpireAt),
})
Log.Debugf("generate receipt receiptHash=0x%02x\n", receiptHash)
receiptHash = solsha3.SoliditySHA3WithPrefix(receiptHash)
sigPublicKeyECDSA, err := crypto.SigToPub(receiptHash, receiptSign)
if err != nil {
Log.Warnf("failed to generate pub key from signature. err=%v", err)
return errors.New("verify signature error")
}
if crypto.PubkeyToAddress(*sigPublicKeyECDSA) != common.HexToAddress(tx.BobAddr) {
Log.Warnf("failed to verify signature.")
return errors.New("failed to verify signature")
}
return nil
}
func readScrtForAtomicSwapVc(sessionID string, AliceAddr string, BobAddr string, Log ILogger) (AtomicSwapVcSecret, error) {
var secret AtomicSwapVcSecret
for i := 0; i < 20; i++ {
Log.Debugf("round %v, read secret from contract. sessionId=%v", i+1, sessionID)
sessionInt := new(big.Int)
sessionInt, rs := sessionInt.SetString(sessionID, 10)
if !rs {
Log.Warnf("Failed to convert sessionId.")
return secret, errors.New("Failed to convert sessionId")
}
t := time.Now()
records, err := ZkPoDExchangeClient.ZkPoDExchangeCaller.GetRecordAtomicSwapVC(&bind.CallOpts{}, common.HexToAddress(AliceAddr), common.HexToAddress(BobAddr), sessionInt)
if err != nil {
Log.Warnf("Failed to read session record: %v", err)
return secret, errors.New("Failed to read session record")
}
Log.Debugf("POD reads secret from contract...time cost=%v\n",
time.Since(t))
if records.SubmitAt.Int64() == 0 {
time.Sleep(30 * time.Second)
continue
}
secret.S = records.Seed0.String()
secret.R = records.Seed0Rand.String()
return secret, nil
}
return secret, errors.New("No secret to be read")
}
func submitScrtForVRFQ(tx Transaction, receiptSign []byte, Log ILogger) (string, error) {
seed0Path := BConf.AliceDir + "/transaction/" + tx.SessionID + "/secret"
receiptPath := BConf.AliceDir + "/transaction/" + tx.SessionID + "/receipt"
var rs bool
sessionInt := new(big.Int)
sessionInt, rs = sessionInt.SetString(tx.SessionID, 10)
if !rs {
Log.Warnf("failed to convert sessionId.")
return "", errors.New("failed to convert sessionId")
}
_, receipt, err := readVRFReceipt(receiptPath, Log)
if err != nil {
Log.Warnf("failed to read receipt. err=%v", err)
return "", errors.New("failed to read receipt")
}
gs := strings.Split(receipt.G, " ")
if len(gs) != 3 {
Log.Warnf("invalid g. g=%v", receipt.G)
return "", errors.New("invalid g. ")
}
var _g_exp_r [2]*big.Int
_g_exp_r[0] = new(big.Int)
_g_exp_r[0], rs = _g_exp_r[0].SetString(gs[1], 10)
if !rs {
Log.Warnf("failed to convert g[1]. g[1] = %v", gs[1])
return "", errors.New("failed to convert g[1]")
}
_g_exp_r[1] = new(big.Int)
_g_exp_r[1], rs = _g_exp_r[1].SetString(gs[2], 10)
if !rs {
Log.Warnf("failed to convert g[2]. g[2] = %v", gs[2])
return "", errors.New("failed to convert g[2]")
}
err = verifySigntureForVRFQ(tx, sessionInt, _g_exp_r, receiptSign, receipt, Log)
if err != nil {
Log.Warnf("verify signature error! err=%v", err)
return "", errors.New("verify signature error")
}
secret, err := readSeed0ForVRFQ(seed0Path, Log)
if err != nil {
Log.Warnf("Failed to read seed0. err=%v", err)
return "", errors.New("Failed to read seed0")
}
srInt := new(big.Int)
srInt, rs = srInt.SetString(secret.R, 10)
if !rs {
Log.Warnf("Failed to convert s_r. s_r=%v", secret.R)
return "", errors.New("Failed to convert s_r")
}
t := time.Now()
var _addrs [2]common.Address
_addrs[0] = common.HexToAddress(tx.BobAddr)
_addrs[1] = common.HexToAddress(tx.AliceAddr)
ctx, err := ZkPoDExchangeClient.ZkPoDExchangeTransactor.SubmitProofVRF(GAdminAuth, srInt, sessionInt,
_addrs, _g_exp_r, big.NewInt(tx.Price), big.NewInt(tx.ExpireAt), receiptSign)
if err != nil {
Log.Warnf("Failed to submit proof. err=%v", err)
return "", errors.New("Failed to submit proof")
}
Log.Debugf("POD submit proof successfully, time cost=%v\n",
time.Since(t))
return ctx.Hash().Hex(), nil
}
func verifySigntureForVRFQ(tx Transaction, sessionInt *big.Int, _g_exp_r [2]*big.Int, receiptSign []byte, receipt VRFReceipt, Log ILogger) error {
if len(receiptSign) != 65 {
Log.Warnf("invalid signature. sig=%v, len(sig)=%v", hexutil.Encode(receiptSign), len(receiptSign))
return errors.New("invalid signature")
}
receiptHash := solsha3.SoliditySHA3( // types
[]string{"uint256", "address", "address", "uint256", "uint256", "uint256", "uint256"},
// values
[]interface{}{
sessionInt,
common.HexToAddress(tx.BobAddr),
common.HexToAddress(tx.AliceAddr),
_g_exp_r[0],
_g_exp_r[1],
big.NewInt(tx.UnitPrice * tx.Count),
big.NewInt(tx.ExpireAt),
})
Log.Debugf("generate receipt receiptHash=0x%02x\n", receiptHash)
receiptHash = solsha3.SoliditySHA3WithPrefix(receiptHash)
sigPublicKeyECDSA, err := crypto.SigToPub(receiptHash, receiptSign)
if err != nil {
Log.Warnf("failed to generate pub key from signature. err=%v", err)
return errors.New("verify signature error")
}
if crypto.PubkeyToAddress(*sigPublicKeyECDSA) != common.HexToAddress(tx.BobAddr) {
Log.Warnf("failed to verify signature.")
return errors.New("failed to verify signature")
}
return nil
}
func readScrtForVRFQ(sessionID string, AliceAddr string, BobAddr string, Log ILogger) (VRFSecret, error) {
var secret VRFSecret
for i := 0; i < 20; i++ {
Log.Debugf("round %v, read secret from contract. sessionId=%v", i+1, sessionID)
sessionInt := new(big.Int)
sessionInt, rs := sessionInt.SetString(sessionID, 10)
if !rs {
Log.Warnf("Failed to convert sessionId.")
return secret, errors.New("Failed to convert sessionId")
}
t := time.Now()
records, err := ZkPoDExchangeClient.ZkPoDExchangeCaller.GetRecordVRF(&bind.CallOpts{}, common.HexToAddress(AliceAddr), common.HexToAddress(BobAddr), sessionInt)
if err != nil {
Log.Warnf("Failed to read session record: %v", err)
return secret, errors.New("Failed to read session record")
}
Log.Debugf("POD reads secret from contract...time cost=%v\n",
time.Since(t))
if records.SubmitAt.Int64() == 0 {
time.Sleep(30 * time.Second)
continue
}
secret.R = records.R.String()
return secret, nil
}
return secret, errors.New("No secret to be read")
}
func calcuDeposit(AliceAddr string, BobAddr string, value int64) (bool, error) {
dpst, err := ZkPoDExchangeClient.ZkPoDExchangeCaller.BobDeposits(&bind.CallOpts{}, common.HexToAddress(BobAddr), common.HexToAddress(AliceAddr))
if err != nil {
return false, fmt.Errorf("failed to read deposit. err=%v", err)
}
if value+DepositLockMap[AliceAddr+BobAddr] > dpst.Value.Int64() {
return false, nil
}
if dpst.Stat == 1 {
return false, nil
}
if dpst.Stat == 2 && time.Now().Unix()+600 > dpst.UnDepositAt.Int64()+8*60*60 {
return false, nil
}
DepositLockMap[AliceAddr+BobAddr] += value
return true, nil
}
func checkDeposit(AliceAddr string, BobAddr string, value int64) (bool, error) {
dpst, err := ZkPoDExchangeClient.ZkPoDExchangeCaller.BobDeposits(&bind.CallOpts{}, common.HexToAddress(BobAddr), common.HexToAddress(AliceAddr))
if err != nil {
return false, fmt.Errorf("failed to read deposit. err=%v", err)
}
if dpst.Value.Int64() < value {
return false, nil
}
if dpst.UnDepositAt.Int64() != 0 && dpst.UnDepositAt.Int64()+28800 < time.Now().Unix()+600 && dpst.Stat == 1 {
return false, nil
}
return true, nil
}
func calcuBltKey(b Bulletin) ([32]byte, error) {
if b.Mode == TRANSACTION_MODE_PLAIN_POD {
size, _ := strconv.ParseUint(b.Size, 10, 64)
s, _ := strconv.ParseUint(b.S, 10, 64)
n, _ := strconv.ParseUint(b.N, 10, 64)
bltByte := solsha3.SoliditySHA3(
// types
[]string{"uint64", "uint64", "uint64", "bytes32"},
// values
[]interface{}{
size,
s,
n,
"0x" + b.SigmaMKLRoot,
},
)
return *byte32(bltByte), nil
} else if b.Mode == TRANSACTION_MODE_TABLE_POD {
s, _ := strconv.ParseUint(b.S, 10, 64)
n, _ := strconv.ParseUint(b.N, 10, 64)
bltByte := solsha3.SoliditySHA3(
// types
[]string{"uint64", "uint64", "bytes32", "bytes32"},
// values
[]interface{}{
s,
n,
"0x" + b.SigmaMKLRoot,
"0x" + b.VRFMetaDigest,
},
)
return *byte32(bltByte), nil
}
return *byte32(nil), fmt.Errorf("invalid mode=%v", b.Mode)
}
func byte32(s []byte) (a *[32]byte) {
if len(a) <= len(s) {
a = (*[len(a)]byte)(unsafe.Pointer(&s[0]))
}
return a
}