-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathContract.cs
2263 lines (1869 loc) · 102 KB
/
Contract.cs
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
using Neo.SmartContract.Framework;
using Neo.SmartContract.Framework.Services.Neo;
using Neo.SmartContract.Framework.Services.System;
using System;
using System.ComponentModel;
using System.Numerics;
using Helper = Neo.SmartContract.Framework.Helper;
namespace smartBNB
{
public class Contract : SmartContract
{
private static readonly byte CONTRACT_STATUS_NULL = 0xFF;
private static readonly byte CONTRACT_STATUS_PORTREQUEST = 0x01;//WAITING FOR THE USER TO SEND BNB
private static readonly byte CONTRACT_STATUS_WITHDRAWREQUESTED = 0x02;
private static readonly byte CONTRACT_STATUS_CHALLENGEDEPOSIT = 0x03;//CHALLENGE ACTIVATED
private static readonly byte CONTRACT_STATUS_CHALLENGEWITHDRAW = 0x04;//CHALLENGE ACTIVATED
private static readonly byte CONTRACT_STATUS_FINISHED = 0x05;
private static readonly BigInteger CONTRACT_TIMEOUT_PORTREQUEST = 60*60*12;
private static readonly BigInteger CONTRACT_TIMEOUT_UPLOADPROOF = 60*60*12;
private static readonly BigInteger CONTRACT_TIMEOUT_WITHDRAWREQUEST = 60*60*12;
private static readonly BigInteger WINDOW_CHALLENGE = 60*60*12;
private static readonly BigInteger DEPOSIT_CHALLENGE = 130;
private static readonly BigInteger FACTOR_COLLATERAL_NUMERATOR = 3;
private static readonly BigInteger FACTOR_COLLATERAL_DENOMINATOR = 2;
private static readonly BigInteger PRICE_DENOMINATOR = 1000000;
private static readonly BigInteger FACTOR_PORTREQUEST_DIVISOR = 10;
private static readonly byte OPERATION_ADD = 0x01;
private static readonly byte OPERATION_SUB = 0x02;
// See https://docs.tendermint.com/master/spec/blockchain/encoding.html#merkle-trees
private static readonly byte[] leafPrefix = { 0x00 };
private static readonly byte[] innerPrefix = { 0x01 };
private static readonly int SLICESLEN = 16;
private static readonly string STG_TYPE_GENERAL = "GENERAL";
private static readonly string STG_TYPE_PM = "PM";
private static readonly string STG_TYPE_POINTMUL = "a";
private static readonly string STG_TYPE_POINTMUL_SIMPLE = "SIMPLE";
private static readonly string STG_TYPE_POINTMUL_MULTI = "MULTI";
private static readonly string STG_TYPE_SIGNABLEBYTES = "SIGNABLEBYTES";
// Hardcoded, object type prefix in transfer transaction
private static readonly byte[] TX_TRANSFER_PREFIX = {0x2A, 0x2C, 0x87, 0xFA};
// Denomitaion of the token
private static readonly byte[] DENOM = {0x42, 0x4E, 0x42};//"BNB"
private static readonly byte[] byteP = {0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f};
private static readonly byte[] byteD = {0xa3, 0x78, 0x59, 0x13, 0xca, 0x4d, 0xeb, 0x75, 0xab, 0xd8, 0x41, 0x41, 0x4d, 0x0a, 0x70, 0x00, 0x98, 0xe8, 0x79, 0x77, 0x79, 0x40, 0xc7, 0x8c, 0x73, 0xfe, 0x6f, 0x2b, 0xee, 0x6c, 0x03, 0x52};
// Static call docs: https://docs.neo.org/docs/en-us/sc/deploy/invoke.html
// General spec: https://docs.neo.org/tutorial/en-us/9-smartContract/cgas/1_what_is_cgas.html
// Contract addresses: https://medium.com/neo-smart-economy/15-things-you-should-know-about-cneo-and-cgas-1029770d76e0
// Code: https://github.com/neo-ngd/CGAS-Contract
[Appcall("74f2dc36a68fdc4682034178eb2220729231db76")] // ScriptHash of CGAS (address: AScKxyXmNtEnTLTvbVhNQyTJmgytxhwSnM)
public static extern object CGAS(string method, object[] args);
private static readonly byte[] PriceOracle = "ALfnhLg7rUyL6Jr98bzzoxz5J7m64fbR4s".ToScriptHash(); // TODO: Update
[DisplayName("transfer")]
public static event Action<byte[], byte[], BigInteger> Transferred;
[DisplayName("deposited")]
public static event Action<byte[], BigInteger> Deposited;
[DisplayName("priceupdated")]
public static event Action<BigInteger> PriceUpdated;
[DisplayName("collatliquidated")]
public static event Action<byte[], BigInteger> CollatLiquidated;
[DisplayName("portrequestcreated")]
public static event Action<byte[], byte[], byte[], BigInteger> PortRequestCreated;
[DisplayName("withdrawrequestcreated")]
public static event Action<byte[], byte[], byte[], BigInteger> WithdrawRequestCreated;
[DisplayName("challengewithdrawcreated")]
public static event Action<byte[], byte[]> ChallengeWithdrawCreated;
[DisplayName("challengedepositcreated")]
public static event Action<byte[], byte[]> ChallengeDepositCreated;
[DisplayName("portingcompleted")]
public static event Action<byte[], byte[]> PortingCompleted;
[Serializable]
struct Balance
{
public BigInteger amount;
public BigInteger lastTimeTransfered;
}
[Serializable]
struct PortingContract
{
public byte ContractStatus;
public byte[] BCNAddr;
public byte[] CollatAddr;
public byte[] UserAddr;
public BigInteger AmountBNB;
public BigInteger LastTimestamp;
public BigInteger GASDeposit;
}
[Serializable]
struct Collat
{
public byte[] Address;
public byte[] BNCAddress;
public BigInteger CollateralAmount;
public Balance CustodiedBNB;
public BigInteger UnverifiedCustodiedBNB;
}
// This part requires further investigation, as we must make sure that the amount of bytes read or written should never exceed the max amount of state allowed in the vm
[Serializable]
struct GeneralChallengeVariablesPM
{
public byte[][] signature;
public BigInteger[] xs;
public BigInteger[] ys;
public BigInteger[] preHashMod;
}
[Serializable]
struct GeneralChallengeVariables
{
public ulong[][] pre;
public ulong[][] preHash;
public byte[] txproof;
public byte[] blockHeader;
public ulong[] txBytes;
}
[Serializable]
struct PointMulStep
{
public BigInteger[] Q;
public BigInteger s;
public BigInteger[] P;
}
public static object Main(string operation, params object[] args)
{
if (Runtime.Trigger == TriggerType.Application)
{
if(operation=="savestate") return SaveChallengeState(args);
else if (operation=="executeChallenge") return executeChallenge(args);
else if (operation=="registerAsCollateral") return RegisterAsCollateral((byte[])args[0], (byte[])args[1], (BigInteger)args[2], (byte)args[3]);
else if (operation=="newPorting") return RequestNewPorting((byte[])args[0], (byte[])args[1], (BigInteger)args[2]);
else if (operation=="ackDepositByUser") return AckDepositByUser((byte[])args[0]);
else if (operation=="challengedeposit") return ChallengeDeposit((byte[])args[0]);
else if (operation=="challengewithdraw") return ChallengeWithdraw((byte[])args[0]);
else if (operation=="requestwithdraw") return RequestWithdraw((byte[])args[0], (byte[])args[1], (BigInteger)args[2], (byte[])args[3]);
else if (operation=="unlockcollateral") return UnlockCollateral((byte[])args[0]);
else if (operation=="updatepriceoracle")
{
if (!Runtime.CheckWitness(PriceOracle)) return false; // Only updatable by oracle
BigInteger price = (BigInteger)args[0];
Storage.Put("price", price);
PriceUpdated(price);
return true;
}
else if (operation == "getCurrentPrice") return getCurrentPrice();
else if (operation == "balanceOf") return BalanceOf((byte[])args[0]);
else if (operation == "decimals") return Decimals();
else if (operation == "name") return Name();
else if (operation == "symbol") return Symbol();
else if (operation == "supportedStandards") return SupportedStandards();
else if (operation == "totalSupply") return TotalSupply();
else if (operation == "transfer") return Transfer((byte[])args[0], (byte[])args[1], (BigInteger)args[2], ExecutionEngine.CallingScriptHash);
else if (operation == "exchangeLostCollateral") return ExchangeLostCollateral((byte[])args[0], (BigInteger)args[1]);
else if (operation == "undercollateralizationChallenge") return UndercollateralizationChallenge((byte[])args[0]);
else
{
return false;
}
} else {
// Someone is trying to spend NEO or GAS that have been sent to the contract
// This should never happen, must have been user error
return true; // Allow anyone to spend it
}
}
private static Balance deserializeBalance(byte[] balance){
if (balance.Length != 0){
return new Balance() { amount = 0, lastTimeTransfered = Runtime.Time };
} else {
return (Balance)Helper.Deserialize(balance);
}
}
// WHEN USED TO UPDATE COLLATERAL'S BALANCES collateralBalance should be set to true, this is because this function is an approximation of the real function and, as such, will always return a value lower than what the real function would. Although the difference is really small, this could be used by collaterals to reduce their collateral faster than permitted. collateralBalance makes sure that the result is always higher than the theoretical perfect value of that function, so its impossible for collaterals to take advantage of that.
// collateralBalance = true -> approximatedResult >= realResult
// collateralBalance = false -> approximatedResult <= realResult
private static BigInteger updateAmount(BigInteger amount, BigInteger lastTransfer, BigInteger currentTime, bool collateralBalance){
BigInteger deltaTime = currentTime - lastTransfer;
BigInteger collatAccumulator = 0;
// Code generated with NEP5interest.py, it essentially calculates the interest as in percentage^deltaTime in logarithmic time by using pre-computed constants
byte[] rateDenominatorBytes = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
BigInteger rateDenominator = rateDenominatorBytes.AsBigInteger();
byte[] magnitudeBytes = {0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
BigInteger magnitude = magnitudeBytes.AsBigInteger();
byte[][] rateNumeratorBytes = new byte[][] {
new byte[]{0xa0, 0x9b, 0x94, 0x83, 0x2d, 0xbc, 0x75, 0x3c, 0x44, 0xd3, 0xb6, 0xd1, 0x26, 0x7c, 0x40, 0xb0, 0x3f, 0xe0, 0x44, 0xdb, 0x8a, 0xb3, 0x52, 0x90, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
new byte[]{0x1a, 0x59, 0x5e, 0x72, 0xd7, 0xe8, 0xdf, 0xbc, 0xf0, 0xaa, 0xba, 0x6e, 0x7c, 0x0a, 0x4b, 0xaf, 0x06, 0x91, 0xb0, 0x52, 0x79, 0x41, 0x23, 0xc8, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
new byte[]{0x5c, 0xff, 0x37, 0xaa, 0x6b, 0x1e, 0xcb, 0xc0, 0xf4, 0x1e, 0x3c, 0x12, 0xd2, 0xf3, 0x84, 0xf0, 0xdf, 0x74, 0x94, 0x0d, 0x7f, 0x1a, 0x10, 0xe4, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
new byte[]{0x50, 0x62, 0xbb, 0x40, 0x66, 0xb1, 0x00, 0xfb, 0x8f, 0xb5, 0xe7, 0x34, 0x16, 0x58, 0xd2, 0x00, 0xfe, 0x31, 0xb6, 0xcc, 0xaa, 0xab, 0x07, 0xf2, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
new byte[]{0x44, 0xea, 0x2c, 0xca, 0x2c, 0xad, 0xed, 0xe9, 0xc7, 0x37, 0x3c, 0x76, 0x8c, 0x7a, 0xb7, 0x07, 0x46, 0x91, 0x69, 0x8d, 0x6f, 0xbd, 0x03, 0xf9, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
new byte[]{0x39, 0x53, 0xdb, 0x08, 0x3d, 0x63, 0xb7, 0x80, 0xba, 0x98, 0x6b, 0x97, 0x37, 0x68, 0x86, 0x2c, 0xc9, 0x53, 0x2a, 0x3b, 0x9e, 0xd8, 0x81, 0xfc, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
new byte[]{0x2d, 0x9a, 0x32, 0x75, 0xee, 0x14, 0xee, 0x94, 0x3d, 0x69, 0x7e, 0x2a, 0x86, 0x7c, 0x07, 0x02, 0x2d, 0xc2, 0x08, 0xb8, 0xc8, 0xea, 0x40, 0xfe, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
new byte[]{0xc0, 0x21, 0xfa, 0x09, 0x53, 0xf1, 0xd7, 0x73, 0xba, 0x8e, 0x3d, 0x75, 0xac, 0xc6, 0x1e, 0x3c, 0x56, 0x0d, 0x4c, 0xc2, 0x02, 0x75, 0x20, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
new byte[]{0x2a, 0xb1, 0x14, 0x4a, 0x0b, 0xb9, 0x00, 0x25, 0x4e, 0x1d, 0x91, 0x55, 0x03, 0x27, 0x10, 0x9d, 0x78, 0x4a, 0xad, 0xfa, 0x68, 0x3a, 0x90, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
new byte[]{0x79, 0x53, 0xff, 0x83, 0xf4, 0x9d, 0x76, 0x27, 0x85, 0xa4, 0x19, 0x73, 0x80, 0x7b, 0x12, 0xde, 0x46, 0x21, 0xb7, 0x63, 0x2e, 0x1d, 0xc8, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
new byte[]{0xe6, 0xdf, 0x4f, 0xbe, 0x0b, 0xf4, 0x94, 0x37, 0x52, 0xf5, 0xba, 0x11, 0x66, 0x4b, 0xc1, 0xf0, 0x08, 0x85, 0x73, 0xab, 0x95, 0x0e, 0xe4, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
new byte[]{0xfd, 0x87, 0x91, 0xa2, 0xa9, 0x79, 0x73, 0x6d, 0x07, 0x50, 0x1f, 0x2c, 0x48, 0x1a, 0x07, 0x34, 0x4a, 0xba, 0x1f, 0x74, 0x4a, 0x07, 0xf2, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
new byte[]{0x4a, 0x51, 0x22, 0xa9, 0xf1, 0xd6, 0xdc, 0x57, 0xd0, 0xa4, 0x76, 0x98, 0x99, 0x14, 0x4c, 0x14, 0x6c, 0x5a, 0xa9, 0x21, 0xa5, 0x03, 0xf9, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
new byte[]{0xa6, 0xb6, 0xbb, 0x6b, 0x3e, 0xc7, 0x57, 0x77, 0x6e, 0x22, 0xf2, 0xda, 0x36, 0x87, 0x23, 0x7a, 0x72, 0x0c, 0xbb, 0x8a, 0xd2, 0x81, 0xfc, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
new byte[]{0x1b, 0x3c, 0xae, 0x8a, 0x76, 0x5a, 0x5c, 0x2d, 0x70, 0x65, 0x2e, 0xb1, 0x13, 0x86, 0x3e, 0xaf, 0x05, 0x1e, 0xd7, 0x43, 0xe9, 0x40, 0xfe, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
new byte[]{0xbf, 0x93, 0xd4, 0xb8, 0x2b, 0xaf, 0x2b, 0xfe, 0x7f, 0x66, 0x28, 0x64, 0x8d, 0x1f, 0xf0, 0x9e, 0xf5, 0xf4, 0x89, 0xa1, 0x74, 0x20, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
new byte[]{0x09, 0xe8, 0xac, 0x10, 0x67, 0x3d, 0xaf, 0xe1, 0x0a, 0x20, 0x77, 0x20, 0x5c, 0xfc, 0xa4, 0x76, 0xf7, 0x93, 0xac, 0x50, 0x3a, 0x90, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
new byte[]{0xda, 0x42, 0x53, 0xdd, 0xa0, 0x79, 0x05, 0x16, 0x1e, 0xc1, 0x06, 0x7b, 0x01, 0xd0, 0xc8, 0xe3, 0x5a, 0x30, 0x50, 0x28, 0x1d, 0xc8, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
new byte[]{0xe9, 0x72, 0x61, 0x04, 0x61, 0xfc, 0x77, 0xf4, 0xad, 0xa5, 0xf8, 0x51, 0x4b, 0x5f, 0xd7, 0x3b, 0xc5, 0x91, 0x26, 0x94, 0x0e, 0xe4, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
new byte[]{0xbe, 0x5c, 0x22, 0x78, 0x58, 0x23, 0x75, 0x77, 0xdb, 0xb5, 0xcf, 0x04, 0xd3, 0x19, 0x63, 0x90, 0x48, 0xe7, 0x12, 0x4a, 0x07, 0xf2, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
new byte[]{0x4c, 0x0c, 0x4c, 0x24, 0xd6, 0x27, 0x67, 0x8d, 0x10, 0x52, 0x2b, 0x30, 0x00, 0xbd, 0xce, 0xc4, 0x3d, 0x5b, 0x09, 0xa5, 0x03, 0xf9, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
};
while(deltaTime >= magnitude){
BigInteger rateNumerator = rateNumeratorBytes[0].AsBigInteger();
BigInteger amountMult = amount * rateNumerator;
collatAccumulator += amountMult % rateDenominator;
amount = amountMult / rateDenominator;
deltaTime -= magnitude;
}
for(int i = 1; i < rateNumeratorBytes.Length; i += 1){
magnitude /= 2;
if(deltaTime >= magnitude){
BigInteger rateNumerator = rateNumeratorBytes[i].AsBigInteger();
BigInteger amountMult = amount * rateNumerator;
collatAccumulator += amountMult % rateDenominator;
amount = amountMult / rateDenominator;
deltaTime -= magnitude;
}
}
if(collateralBalance == true){
amount += collatAccumulator;
}
return amount;
}
private static Balance updateBalance(Balance bal, bool collatBal){
BigInteger currentTime = Runtime.Time;
bal.amount = updateAmount(bal.amount, bal.lastTimeTransfered, currentTime, collatBal);
bal.lastTimeTransfered = currentTime;
return bal;
}
[DisplayName("balanceOf")]
public static BigInteger BalanceOf(byte[] account)
{
if (account.Length != 20)
throw new Exception("The parameter account SHOULD be 20-byte addresses.");
StorageMap asset = Storage.CurrentContext.CreateMap(nameof(asset));
Balance bal = deserializeBalance(asset.Get(account));
return updateAmount(bal.amount, bal.lastTimeTransfered, Runtime.Time, false);
}
[DisplayName("decimals")]
public static byte Decimals() => 8;
private static bool IsPayable(byte[] to)
{
var c = Blockchain.GetContract(to);
return c == null || c.IsPayable;
}
[DisplayName("name")]
public static string Name() => "smartBNB"; //name of the token
[DisplayName("symbol")]
public static string Symbol() => "SBNB"; //symbol of the token
[DisplayName("supportedStandards")]
public static string[] SupportedStandards() => new string[] { "NEP-5", "NEP-7", "NEP-10" };
// FIXME: This is not getting updated
[DisplayName("totalSupply")]
public static BigInteger TotalSupply()
{
StorageMap contract = Storage.CurrentContext.CreateMap(nameof(contract));
return contract.Get("totalSupply").AsBigInteger();
}
#if DEBUG
[DisplayName("transfer")] //Only for ABI file
public static bool Transfer(byte[] from, byte[] to, BigInteger amount) => true;
#endif
//Methods of actual execution
private static bool Transfer(byte[] from, byte[] to, BigInteger amount, byte[] callscript)
{
//Check parameters
if (from.Length != 20 || to.Length != 20)
throw new Exception("The parameters from and to SHOULD be 20-byte addresses.");
if (amount <= 0)
throw new Exception("The parameter amount MUST be greater than 0.");
if (!IsPayable(to))
return false;
if (!Runtime.CheckWitness(from) && from.AsBigInteger() != callscript.AsBigInteger())
return false;
StorageMap asset = Storage.CurrentContext.CreateMap(nameof(asset));
Balance fromBalance = updateBalance(deserializeBalance(asset.Get(from)), false);
if (fromBalance.amount < amount)
return false;
if (from == to)
return true;
//Reduce payer balances
if (fromBalance.amount == amount){
asset.Delete(from);
} else {
fromBalance.amount = fromBalance.amount - amount;
asset.Put(from, Helper.Serialize(fromBalance));
}
//Increase the payee balance
Balance toBalance = updateBalance(deserializeBalance(asset.Get(to)), false);
toBalance.amount = toBalance.amount + amount;
asset.Put(to, Helper.Serialize(toBalance));
Transferred(from, to, amount);
return true;
}
private static bool ExchangeLostCollateral(byte[] from, BigInteger amountBNB)
{
if (!Runtime.CheckWitness(from)) return false;
if (amountBNB < 1) return false;
BigInteger lostCollateralGAS = Storage.Get("lostCollateralGAS").AsBigInteger();
BigInteger unbackedBNB = Storage.Get("unbackedBNB").AsBigInteger();
if(amountBNB > unbackedBNB) return false;
BigInteger exchangedGAS = (amountBNB*lostCollateralGAS)/unbackedBNB;
Burn(from, amountBNB);
Storage.Put("lostCollateralGAS", lostCollateralGAS - exchangedGAS);
Storage.Put("unbackedBNB", unbackedBNB - amountBNB);
TransferCGAS(ExecutionEngine.ExecutingScriptHash, from, exchangedGAS);
return true;
}
private static void Mint(byte[] to, BigInteger amount)
{
if (amount <= 0) throw new Exception("Burning non-existing sBNB");
StorageMap asset = Storage.CurrentContext.CreateMap(nameof(asset));
Balance toBalance = updateBalance(deserializeBalance(asset.Get(to)), false);
toBalance.amount = toBalance.amount + amount;
asset.Put(to, Helper.Serialize(toBalance));
Transferred(null, to, amount);
}
// amount should never be negative
private static void Burn(byte[] from, BigInteger amount)
{
StorageMap asset = Storage.CurrentContext.CreateMap(nameof(asset));
Balance fromBalance = updateBalance(deserializeBalance(asset.Get(from)), false);
if (amount > fromBalance.amount || amount <= 0) throw new Exception("Burning non-existing sBNB");
fromBalance.amount = fromBalance.amount - amount;
asset.Put(from, Helper.Serialize(fromBalance));
Transferred(from, null, amount);
}
private static Collat getCollatById(byte[] collatID)
{
StorageMap collats = Storage.CurrentContext.CreateMap(nameof(collats));
byte[] collat = collats.Get(collatID);
if (collat.Length == 0) return new Collat{ Address = new byte[0] };
Collat desCollat = (Collat)Helper.Deserialize(collat);
desCollat.CustodiedBNB = updateBalance(desCollat.CustodiedBNB, true);
return desCollat;
}
private static void putCollatById(byte[] collatID, Collat collat)
{
StorageMap collats = Storage.CurrentContext.CreateMap(nameof(collats));
collats.Put(collatID, Helper.Serialize(collat));
}
private static PortingContract getPortingContract(byte[] portingContractID)
{
StorageMap pcs = Storage.CurrentContext.CreateMap(nameof(pcs));
byte[] pc = pcs.Get(portingContractID);
if(pc.Length==0) return new PortingContract(){ ContractStatus = CONTRACT_STATUS_NULL };
return (PortingContract)Helper.Deserialize(pc);
}
private static void putPortingContract(byte[] portingContractID, PortingContract portingContract)
{
StorageMap pcs = Storage.CurrentContext.CreateMap(nameof(pcs));
pcs.Put(portingContractID, Helper.Serialize(portingContract));
}
private static bool executeChallenge(params object[] args)
{
byte[] portingContractID = (byte[])args[0];
byte challengeNum = (byte)args[1];
PortingContract pc = new PortingContract();
pc = getPortingContract(portingContractID);
if(pc.ContractStatus == CONTRACT_STATUS_NULL) return false;
BigInteger t = Runtime.Time-pc.LastTimestamp;
if(t < CONTRACT_TIMEOUT_UPLOADPROOF || t > CONTRACT_TIMEOUT_UPLOADPROOF + WINDOW_CHALLENGE) return false;
bool challengeResult = true;
if(challengeNum==0x1)
{
int sigNum = (int)args[2];
challengeResult = ChallengeInitialChecks(portingContractID, sigNum);
}
else if(challengeNum==0x2)
{
int sigNum = (int)args[2];
challengeResult = ChallengeCheckBytesV2(portingContractID, sigNum);
}
else if(challengeNum==0x3)
{
int sigNum = (int)args[2];
challengeResult = ChallengeSha512(portingContractID, sigNum);
}
else if(challengeNum==0x4)
{
int sigNum = (int)args[2];
challengeResult = ChallengeSha512ModQ(portingContractID, sigNum);
}
else if(challengeNum==0x5)
{
int sigNum = (int)args[2];
challengeResult = ChallengePointEqual(portingContractID, sigNum);
}
else if(challengeNum==0x6){
int sigNum = (int)args[2];
int i = (int)args[3];
string mulid = (string)args[4];
challengeResult = ChallengeEdDSA_PointMul_Setp(portingContractID, sigNum, i, mulid);
}
else if(challengeNum==0x7){
int sigNum = (int)args[2];
challengeResult = ChallengeTxProof(portingContractID, sigNum);
}
else if (challengeNum==0x8){
challengeResult = ChallengeTxData(portingContractID);
}
else if (challengeNum==0x9){
challengeResult = isProofSaved(portingContractID);
}
if (!challengeResult)
{
byte[] collatID = portingContractID.Range(0, 40);
Collat collat = new Collat();
collat = getCollatById(collatID);
if (collat.Address.Length == 0) return false;
if (pc.ContractStatus==CONTRACT_STATUS_CHALLENGEWITHDRAW)
{
// Collateral has not sent BNB to the users that requested it
// Give user an equivalent amount
// TODO: The incentive needs to be bigger here, collat may not bother sendinf bnb for small amounts because he doesn't have much to lose
pc.ContractStatus = CONTRACT_STATUS_FINISHED;
putPortingContract(portingContractID, pc);
BigInteger collateralGASTaken = (pc.AmountBNB * collat.CollateralAmount)/(collat.UnverifiedCustodiedBNB + collat.CustodiedBNB.amount);
collat.CollateralAmount = collat.CollateralAmount - collateralGASTaken;
collat.UnverifiedCustodiedBNB = collat.UnverifiedCustodiedBNB - pc.AmountBNB;
putCollatById(collatID, collat);
TransferCGAS(ExecutionEngine.ExecutingScriptHash, pc.UserAddr, collateralGASTaken + DEPOSIT_CHALLENGE);
PortingCompleted(collatID, portingContractID);
}
else if (pc.ContractStatus==CONTRACT_STATUS_CHALLENGEDEPOSIT)
{
// User did not deposit BNB and faked a challenge
// Collat wins, Deposit gets reverted and collat keeps the user's DEPOSIT_CHALLENGE & initial GASDeposit
pc.ContractStatus = CONTRACT_STATUS_FINISHED;
putPortingContract(portingContractID, pc);
collat.UnverifiedCustodiedBNB = collat.UnverifiedCustodiedBNB - pc.AmountBNB;
collat.CollateralAmount = collat.CollateralAmount + (DEPOSIT_CHALLENGE*2) + pc.GASDeposit;
putCollatById(collatID, collat);
PortingCompleted(collatID, portingContractID);
}
return false;
}
return challengeResult;
}
private static void TransferCGAS(byte[] from, byte[] to, BigInteger amount)
{
// Transfer token
var args = new object[] { from, to, amount };
if (!(bool)CGAS("transfer", args)) throw new Exception("Failed to transfer NEP-5 tokens!");
}
private static bool UndercollateralizationChallenge(byte[] collatID)
{
Collat collat = new Collat();
collat = getCollatById(collatID);
if (collat.Address.Length == 0) return false;
BigInteger currentPrice = getCurrentPrice();
// If collateralization ratio is lower than 1.2, liquidate collat
if ((collat.CollateralAmount * PRICE_DENOMINATOR * 10) < ((collat.CustodiedBNB.amount + collat.UnverifiedCustodiedBNB) * currentPrice * 12))
{
liquidateCollat(collat, collatID);
return true;
}
return false;
}
// Liquidate a collateral's holdings
// Note that the collateral associated with unverified custodied bnb are not removed because if we were to do that the current porting processes would have it's underlying collateral disappear -> attack vector
private static void liquidateCollat(Collat collat, byte[] collatID){
BigInteger lostCollateralGAS = Storage.Get("lostCollateralGAS").AsBigInteger();
BigInteger liquidatedGAS = (collat.CollateralAmount * collat.CustodiedBNB.amount)/(collat.CustodiedBNB.amount + collat.UnverifiedCustodiedBNB); // Calculate the GAS collateral associated with verified BNB in custody
Storage.Put("lostCollateralGAS", lostCollateralGAS + liquidatedGAS);
BigInteger unbackedBNB = Storage.Get("unbackedBNB").AsBigInteger();
Storage.Put("unbackedBNB", unbackedBNB + collat.CustodiedBNB.amount);
collat.CollateralAmount = collat.CollateralAmount - liquidatedGAS;
Balance collatBal = collat.CustodiedBNB;
collatBal.amount = 0;
putCollatById(collatID, collat);
CollatLiquidated(collatID, liquidatedGAS);
}
// Register a new collat or increase/decrease the deposit of an existing one
private static bool RegisterAsCollateral(byte[] address, byte[] BNCAddress, BigInteger newAmount, byte operation)
{
if (!Runtime.CheckWitness(address)) return false;
if (BNCAddress.Length!=20) return false;
if (newAmount<1) return false;
byte[] collatID = address.Concat(BNCAddress);
Collat collat = new Collat();
collat = getCollatById(collatID);
if (collat.Address.Length == 0)
{
collat.Address = address;
collat.BNCAddress = BNCAddress;
collat.CollateralAmount = newAmount;
putCollatById(collatID, collat);
TransferCGAS(address, ExecutionEngine.ExecutingScriptHash, newAmount);
Deposited(address, newAmount);
}
else
{
if(operation==OPERATION_ADD)
{
collat.CollateralAmount = collat.CollateralAmount+newAmount;;
putCollatById(collatID, collat);
TransferCGAS(address, ExecutionEngine.ExecutingScriptHash, newAmount);
Deposited(address, newAmount);
}
else if(operation==OPERATION_SUB)
{
BigInteger currentPrice = getCurrentPrice();
if(newAmount > calculateCollateralAmountLeft(collat, currentPrice)) return false;
collat.CollateralAmount = collat.CollateralAmount - newAmount;
putCollatById(collatID, collat);
TransferCGAS(ExecutionEngine.ExecutingScriptHash, address, newAmount);
}
}
return true;
}
private static BigInteger calculateGASCollateralAmount(BigInteger amountBNB, BigInteger currentPrice)
{
return (amountBNB*currentPrice*FACTOR_COLLATERAL_NUMERATOR)/(FACTOR_COLLATERAL_DENOMINATOR*PRICE_DENOMINATOR);
}
private static BigInteger calculateCollateralAmountLeft(Collat collat, BigInteger currentPrice)
{
return collat.CollateralAmount - calculateGASCollateralAmount(collat.CustodiedBNB.amount + collat.UnverifiedCustodiedBNB, currentPrice);
}
private static BigInteger getCurrentPrice(){
return Storage.Get("price").AsBigInteger();
}
private static byte[] RequestNewPorting(byte[] collatID, byte[] userAddr, BigInteger AmountBNB)
{
if (!Runtime.CheckWitness(userAddr)) return new byte[0];
if (AmountBNB <= 0) throw new Exception("The parameter amount MUST be greater than 0.");
Collat collat = new Collat();
collat = getCollatById(collatID);
if (collat.Address.Length == 0) return new byte[0];
BigInteger currentPrice = getCurrentPrice();
BigInteger collateralAmountNedeed = calculateGASCollateralAmount(AmountBNB, currentPrice) + DEPOSIT_CHALLENGE; // Get the amount needed in GAS
if(calculateCollateralAmountLeft(collat, currentPrice) < collateralAmountNedeed) return new byte[0];
collat.UnverifiedCustodiedBNB = collat.UnverifiedCustodiedBNB + AmountBNB;
collat.CollateralAmount = collat.CollateralAmount - DEPOSIT_CHALLENGE;
putCollatById(collatID, collat);
BigInteger timestamp = Runtime.Time;
byte[] portingContractID = collatID.Concat(userAddr).Concat(timestamp.AsByteArray());
if(getPortingContract(portingContractID).ContractStatus != CONTRACT_STATUS_NULL) return new byte[0];
PortingContract pc = new PortingContract();
pc.ContractStatus = CONTRACT_STATUS_PORTREQUEST;
pc.CollatAddr = collatID.Range(0, 20);
pc.BCNAddr = collat.BNCAddress;
pc.UserAddr = userAddr;
pc.AmountBNB = AmountBNB;
pc.LastTimestamp = timestamp;
pc.GASDeposit = collateralAmountNedeed/FACTOR_PORTREQUEST_DIVISOR;
putPortingContract(portingContractID, pc);
TransferCGAS(userAddr, ExecutionEngine.ExecutingScriptHash, pc.GASDeposit);
PortRequestCreated(collatID, portingContractID, userAddr, AmountBNB);
return portingContractID;
}
private static bool AckDepositByUser(byte[] portingContractID)
{
byte[] collatAddr = portingContractID.Range(0, 20);
if (!Runtime.CheckWitness(collatAddr)) return false;
byte[] collatID = portingContractID.Range(0, 40);
Collat collat = new Collat();
collat = getCollatById(collatID);
if (collat.Address.Length == 0) return false;
PortingContract pc = new PortingContract();
pc = getPortingContract(portingContractID);
if(pc.ContractStatus == CONTRACT_STATUS_NULL) return false;
if(pc.ContractStatus!=CONTRACT_STATUS_PORTREQUEST) return false;
if((Runtime.Time-pc.LastTimestamp) > CONTRACT_TIMEOUT_PORTREQUEST) return false;
SuccessfulDeposit(pc, portingContractID, collat, collatID, false);
TransferCGAS(ExecutionEngine.ExecutingScriptHash, pc.UserAddr, pc.GASDeposit);
return true;
}
private static void SuccessfulDeposit(PortingContract pc, byte[] portingContractID, Collat collat, byte[] collatID, bool collateralPunished)
{
pc.ContractStatus = CONTRACT_STATUS_FINISHED;
pc.LastTimestamp = Runtime.Time;
putPortingContract(portingContractID, pc);
PortingCompleted(collatID, portingContractID);
if (!collateralPunished)
{
collat.CollateralAmount = collat.CollateralAmount + DEPOSIT_CHALLENGE;
}
// Move bnb from unverified to verified
Balance collatBal = collat.CustodiedBNB;
collatBal.amount = collatBal.amount + pc.AmountBNB;
collat.UnverifiedCustodiedBNB = collat.UnverifiedCustodiedBNB - pc.AmountBNB;
putCollatById(collatID, collat);
Mint(pc.UserAddr, pc.AmountBNB);
}
private static bool ChallengeDeposit(byte[] portingContractID)
{
// witness(useraddr)
if (!Runtime.CheckWitness(portingContractID.Range(40,20))) return false; // TODO: Enable fishermen to also create challenges
PortingContract pc = new PortingContract();
pc = getPortingContract(portingContractID);
if(pc.ContractStatus == CONTRACT_STATUS_NULL) return false;
if(pc.ContractStatus!=CONTRACT_STATUS_PORTREQUEST) return false;
BigInteger t = Runtime.Time-pc.LastTimestamp;
if(t < CONTRACT_TIMEOUT_PORTREQUEST || t > (CONTRACT_TIMEOUT_PORTREQUEST + WINDOW_CHALLENGE)) return false;
pc.ContractStatus = CONTRACT_STATUS_CHALLENGEDEPOSIT;
pc.LastTimestamp = Runtime.Time;
putPortingContract(portingContractID, pc);
TransferCGAS(pc.UserAddr, ExecutionEngine.ExecutingScriptHash, DEPOSIT_CHALLENGE);
byte[] collatID = portingContractID.Range(0, 40);
ChallengeDepositCreated(collatID, portingContractID);
return true;
}
private static bool ChallengeWithdraw(byte[] portingContractID)
{
PortingContract pc = new PortingContract();
pc = getPortingContract(portingContractID);
if(pc.ContractStatus == CONTRACT_STATUS_NULL) return false;
if(pc.ContractStatus!=CONTRACT_STATUS_WITHDRAWREQUESTED) return false;
BigInteger t = Runtime.Time-pc.LastTimestamp;
if(t < CONTRACT_TIMEOUT_WITHDRAWREQUEST || t > (CONTRACT_TIMEOUT_WITHDRAWREQUEST + WINDOW_CHALLENGE)) return false;
if (!Runtime.CheckWitness(pc.UserAddr)) return false; // TODO: Enable fishermen to also create challenges
pc.ContractStatus = CONTRACT_STATUS_CHALLENGEWITHDRAW;
pc.LastTimestamp = Runtime.Time;
putPortingContract(portingContractID, pc);
TransferCGAS(pc.UserAddr, ExecutionEngine.ExecutingScriptHash, DEPOSIT_CHALLENGE);
byte[] collatID = portingContractID.Range(0, 40);
ChallengeWithdrawCreated(collatID, portingContractID);
return true;
}
private static bool RequestWithdraw(byte[] collatID, byte[] userAddr, BigInteger AmountBNB, byte[] userBCNAddr)
{
if (!Runtime.CheckWitness(userAddr)) return false;
if (AmountBNB < 1) return false;
Collat collat = new Collat();
collat = getCollatById(collatID);
if (collat.Address.Length == 0) return false;
// Move the equivalent BNB on Collat to the pool of frozen UnverifiedCustodiedBNB
Balance collatBal = collat.CustodiedBNB;
if (collatBal.amount < AmountBNB) return false;
collatBal.amount = collatBal.amount - AmountBNB;
collat.UnverifiedCustodiedBNB = collat.UnverifiedCustodiedBNB + AmountBNB;
putCollatById(collatID, collat);
BigInteger timestamp = Runtime.Time;
byte[] portingContractID = collatID.Concat(userAddr).Concat(timestamp.AsByteArray());
if(getPortingContract(portingContractID).ContractStatus != CONTRACT_STATUS_NULL) return false;
PortingContract pc = new PortingContract();
pc.ContractStatus = CONTRACT_STATUS_WITHDRAWREQUESTED;
pc.CollatAddr = collatID.Range(0, 20);
pc.BCNAddr = userBCNAddr;
pc.UserAddr = userAddr;
pc.AmountBNB = AmountBNB;
pc.LastTimestamp = timestamp;
pc.GASDeposit = 0;
putPortingContract(portingContractID, pc);
Burn(userAddr, AmountBNB);
WithdrawRequestCreated(collatID, portingContractID, userBCNAddr, AmountBNB);
return true;
}
private static bool UnlockCollateral(byte[] portingContractID)
{
PortingContract pc = new PortingContract();
pc = getPortingContract(portingContractID);
if(pc.ContractStatus == CONTRACT_STATUS_NULL) return false;
byte[] collatID = portingContractID.Range(0, 40);
Collat collat = new Collat();
collat = getCollatById(collatID);
if (collat.Address.Length == 0) return false;
BigInteger t = Runtime.Time - pc.LastTimestamp;
if (pc.ContractStatus == CONTRACT_STATUS_WITHDRAWREQUESTED)
{
if (t > (CONTRACT_TIMEOUT_WITHDRAWREQUEST + WINDOW_CHALLENGE))
{
// Withdraw succesful, liberate collateral
pc.ContractStatus = CONTRACT_STATUS_FINISHED;
putPortingContract(portingContractID, pc);
collat.UnverifiedCustodiedBNB = collat.UnverifiedCustodiedBNB - pc.AmountBNB;
PortingCompleted(collatID, portingContractID);
}
}
else if (pc.ContractStatus == CONTRACT_STATUS_PORTREQUEST)
{
if (t > (CONTRACT_TIMEOUT_PORTREQUEST + WINDOW_CHALLENGE))
{
// User has not sent the BNB (no challenge -> we assume no BNB was sent)
collat.CollateralAmount = collat.CollateralAmount + DEPOSIT_CHALLENGE + pc.GASDeposit;
collat.UnverifiedCustodiedBNB = collat.UnverifiedCustodiedBNB - pc.AmountBNB;
pc.ContractStatus = CONTRACT_STATUS_FINISHED;
putPortingContract(portingContractID, pc);
PortingCompleted(collatID, portingContractID);
}
}
else if (pc.ContractStatus == CONTRACT_STATUS_CHALLENGEWITHDRAW)
{
if (t > (CONTRACT_TIMEOUT_UPLOADPROOF + WINDOW_CHALLENGE))
{
// Collat has uploaded proof & user hasn't been able to prove it wrong
// Collat wins, withdraw successful
pc.ContractStatus = CONTRACT_STATUS_FINISHED;
putPortingContract(portingContractID, pc);
collat.UnverifiedCustodiedBNB = collat.UnverifiedCustodiedBNB - pc.AmountBNB;
TransferCGAS(ExecutionEngine.ExecutingScriptHash, pc.CollatAddr, DEPOSIT_CHALLENGE); // Give collat the user's security deposit
PortingCompleted(collatID, portingContractID);
}
}
else if (pc.ContractStatus == CONTRACT_STATUS_CHALLENGEDEPOSIT)
{
if (t > (CONTRACT_TIMEOUT_UPLOADPROOF + WINDOW_CHALLENGE))
{
// User has uploaded proof, collat hasn't been able to prove it wrong -> User wins
// Validate deposit and distribute rewards
SuccessfulDeposit(pc, portingContractID, collat, collatID, true);
TransferCGAS(ExecutionEngine.ExecutingScriptHash, pc.UserAddr, (DEPOSIT_CHALLENGE * 2) + pc.GASDeposit);
PortingCompleted(collatID, portingContractID);
}
}
else
{
return false;
}
putCollatById(collatID, collat);
return true;
}
private static BigInteger min(BigInteger a, BigInteger b)
{
return (a>b)? b : a;
}
private static bool isProofSaved(byte[] portingContractID)
{
string[] labels = {STG_TYPE_GENERAL, STG_TYPE_PM, "Ps_ha", "ss_ha", "Qs_ha", "Ps_sb", "ss_sb", "Qs_sb"};
byte[] key;
for (int i = 0; i<2; i++)
{
key = portingContractID.Concat(labels[i].AsByteArray());
if (Storage.Get(key).Length==0)
return false;
}
portingContractID = portingContractID.Concat(STG_TYPE_POINTMUL.AsByteArray());
byte[] num = new byte[16];
for (byte i=1; i<num.Length; i++) num[i] = i;
for (int i = 2; i<labels.Length; i++)
{
key = portingContractID.Concat(labels[i].AsByteArray());
for (int j = 0; j<SLICESLEN; j++)
{
if (Storage.Get(key.Concat(num.Range(j, 1).Take(1))).Length==0)
return false;
}
}
return true;
}
private static bool SaveChallengeState(params object[] args)
{
byte[] portingContractID = (byte[])args[0];
PortingContract pc = new PortingContract();
pc = getPortingContract(portingContractID);
if(pc.ContractStatus == CONTRACT_STATUS_NULL) return false;
byte[] addrAllowed;
if(Runtime.Time-pc.LastTimestamp > CONTRACT_TIMEOUT_UPLOADPROOF) return false;
if (pc.ContractStatus==CONTRACT_STATUS_CHALLENGEDEPOSIT)
addrAllowed=portingContractID.Range(0, 20);
else if (pc.ContractStatus==CONTRACT_STATUS_CHALLENGEWITHDRAW)
addrAllowed=portingContractID.Range(40, 20);
else
return false;
if (Runtime.CheckWitness(addrAllowed))
return saveStateToStorage(portingContractID, args);
return false;
}
private static bool Validate(byte[] rawProof, byte[] rawHeader)
{
// Verify relationship with the block. Compares if hDataHash and txProofRootHash are equal and merkle path is ok
int accLen = 0;
//getting hDataHash
for (int i = 0; i < 8; i++)
{
if(accLen>=rawHeader.Length) return false;
accLen += rawHeader[accLen]+1;
}
return VerifyTx(rawProof, rawHeader.Range(accLen+2, rawHeader[accLen]-1));
}
private static byte[] HashRawHeader(byte[] rawHeader)
{
if (rawHeader.Length<2) return null;
//Obtaining header slices
byte[][] headerSlices = new byte[16][];
int accLen = 0;
int i = 0;
while (accLen < rawHeader.Length && i < headerSlices.Length)
{
headerSlices[i] = rawHeader.Range(accLen+1, rawHeader[accLen]);
accLen += rawHeader[accLen]+1;
i++;
}
//Hashing header
return SimpleHashFromByteSlices(headerSlices);
}
private static bool VerifyTx(byte[] proof, byte[] merkleRootFromHeader)
{
byte[] txProofLeafHash = proof.Range(0, 32);
int txProofIndex = proof.Range(32, 1)[0];
int txProofTotal = proof.Range(33, 1)[0];
int len = proof.Range(34, proof.Length - 34).Length / 32;
byte[][] txProofAunts = new byte[len][];
for (int i = 0; i < len; i++)
{
txProofAunts[i] = proof.Range(34 + (i * 32), 32);
}
if (txProofIndex < 0)
return false; // Proof index cannot be negative
if (txProofTotal <= 0)
return false; // Proof total must be positive
byte[] computedHash = ComputeHashFromAunts(txProofIndex, txProofTotal, txProofLeafHash, txProofAunts);
if (computedHash == null)
return false;
return (computedHash == merkleRootFromHeader);
}
private static byte[] ComputeHashFromAunts(int index, int total, byte[] leafHash, byte[][] innerHashes)
{
if (index >= total)
return null;
switch (total)
{
case 0:
return null; // Cannot call computeHashFromAunts() with 0 total
case 1:
if (innerHashes.Length != 0)
return null;
return leafHash;
default:
if (innerHashes.Length == 0)
return null;
int numLeft = GetSplitPoint(total);
if(numLeft<1)
return null;
if (index < numLeft)
{
byte[] leftHash = ComputeHashFromAunts(index, numLeft, leafHash, TakeArrays(innerHashes, 0, innerHashes.Length - 2));
if (leftHash == null)
return null;
return InnerHash(leftHash, innerHashes[innerHashes.Length - 1]);
}
byte[] rightHash = ComputeHashFromAunts(index - numLeft, total - numLeft, leafHash, TakeArrays(innerHashes, 0, innerHashes.Length - 2));
if (rightHash == null)
return null;
return InnerHash(innerHashes[innerHashes.Length - 1], rightHash);