-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathelector-code.fc
1602 lines (1529 loc) · 64.7 KB
/
elector-code.fc
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
;; Elector smartcontract
#include "constants.fc";
{-
participant#_ stake:Grams ;; submitted stake
time:32 ;; time of stake submition
max_factor:32
src_addr:256
adnl_addr:256
= Participant;
elect#_ elect_at:uint32 ;; planned time of new set activation
elect_close:uint32 ;; planned time of closing election for new application
min_stake:Grams ;; minimal stake accepted
total_stake:Grams ;; sum of all stakes accepted
members:(HashmapE 256 Participant) ;; index - validator_pubkey
failed:Bool
finished:Bool
= CurrentElection;
validator#_ addr:uint256 ;; wallet address of validator
weight:64
stake:Grams ;; accepted stake, can be lower than proposed
banned:Bool ;; currently unused flag
= Validator;
validator_complaint#bc validator_pubkey:uint256
description:^ComplaintDescr
created_at:uint32
severity:uint8
reward_addr:uint256
paid:Grams
suggested_fine:Grams
suggested_fine_part:uint32
= ValidatorComplaint;
complaint_status#2d complaint:^ValidatorComplaint voters:(HashmapE 16 True)
vset_id:uint256 weight_remaining:int64 = ComplaintStatus;
elect#_ unfreeze_at:uint32 ;; time validator stakes unfrozen and can be withdrawn
stake_held:uint32 ;; period for holding stakes frozen, defined by ConfigParam 15
vset_hash:uint32 ;; validator set cell hash
frozen_dict:(HashmapE 256 Validator) ;; index validator_pubkey
total_stake:Grams ;; sum of accepted stakes of validators
bonuses:Grams ;; accumulated bonuses, distributed pro-rata
complaints:(HashmapE 256 ComplaintStatus) ;; index complaint hash
= PastElection;
storage#_ elect:CurrentElection
credits:(Hashmap 256 Grams) ;; index address
past_elections:(HashmapE 32 PastElection) ;; index elect_at
grams:Grams ;; nobody balance
active_id:uint32 ;; active election id
active_hash:uint256 ;; hash of current cur_validators cell
= Storage;
-}
(cell, cell, cell, int, int, int) load_data() inline_ref {
slice cs = get_data().begin_parse();
(cell, cell, cell, int, int, int) res = (cs~load_dict(),
cs~load_dict(),
cs~load_dict(),
cs~load_grams(),
cs~load_uint(32),
cs~load_uint(256));
cs.end_parse();
return res;
}
;; cur_elect credits past_elections grams active_id active_hash
() store_data(cell elect,
cell credits,
cell past_elections,
int grams,
int active_id,
int active_hash) impure inline_ref {
set_data(begin_cell()
.store_dict(elect)
.store_dict(credits)
.store_dict(past_elections)
.store_grams(grams)
.store_uint(active_id, 32)
.store_uint(active_hash, 256)
.end_cell());
}
;; elect -> elect_at elect_close min_stake total_stake members failed finished
(int, int, int, int, cell, int, int) unpack_elect(cell elect) inline_ref {
slice es = elect.begin_parse();
(int, int, int, int, cell, int, int) res = (es~load_uint(32),
es~load_uint(32),
es~load_grams(),
es~load_grams(),
es~load_dict(),
es~load_int(1),
es~load_int(1));
es.end_parse();
return res;
}
cell pack_elect(int elect_at,
int elect_close,
int min_stake,
int total_stake,
cell members,
int failed,
int finished) inline_ref {
return begin_cell()
.store_uint(elect_at, 32)
.store_uint(elect_close, 32)
.store_grams(min_stake)
.store_grams(total_stake)
.store_dict(members)
.store_int(failed, 1)
.store_int(finished, 1)
.end_cell();
}
;; slice -> unfreeze_at stake_held vset_hash frozen_dict total_stake bonuses complaints
(int, int, int, cell, int, int, cell) unpack_past_election(slice fs) inline_ref {
(int, int, int, cell, int, int, cell) res = (fs~load_uint(32),
fs~load_uint(32),
fs~load_uint(256),
fs~load_dict(),
fs~load_grams(),
fs~load_grams(),
fs~load_dict());
fs.end_parse();
return res;
}
builder pack_past_election(int unfreeze_at,
int stake_held,
int vset_hash,
cell frozen_dict,
int total_stake,
int bonuses,
cell complaints) inline_ref {
return begin_cell()
.store_uint(unfreeze_at, 32)
.store_uint(stake_held, 32)
.store_uint(vset_hash, 256)
.store_dict(frozen_dict)
.store_grams(total_stake)
.store_grams(bonuses)
.store_dict(complaints);
}
;; complaint_status#2d complaint:^ValidatorComplaint voters:(HashmapE 16 True)
;; vset_id:uint256 weight_remaining:int64 = ValidatorComplaintStatus;
(cell, cell, int, int) unpack_complaint_status(slice cs) inline_ref {
throw_unless(9, cs~load_uint(8) == 0x2d);
(cell, cell, int, int) res = (cs~load_ref(), cs~load_dict(), cs~load_uint(256), cs~load_int(64));
cs.end_parse();
return res;
}
builder pack_complaint_status(cell complaint,
cell voters,
int vset_id,
int weight_remaining) inline_ref {
return begin_cell()
.store_uint(0x2d, 8)
.store_ref(complaint)
.store_dict(voters)
.store_uint(vset_id, 256)
.store_int(weight_remaining, 64);
}
;; validator_complaint#bc validator_pubkey:uint256 description:^ComplaintDescr
;; created_at:uint32 severity:uint8 reward_addr:uint256 paid:Grams suggested_fine:Grams
;; suggested_fine_part:uint32 = ValidatorComplaint;
(int, cell, int, int, int, int, int, int) unpack_complaint(slice cs) inline_ref {
throw_unless(9, cs~load_uint(8) == 0xbc);
(int, cell, int, int, int, int, int, int) res = (cs~load_uint(256),
cs~load_ref(),
cs~load_uint(32),
cs~load_uint(8),
cs~load_uint(256),
cs~load_grams(),
cs~load_grams(),
cs~load_uint(32));
cs.end_parse();
return res;
}
builder pack_complaint(int validator_pubkey,
cell description,
int created_at,
int severity,
int reward_addr,
int paid,
int suggested_fine,
int suggested_fine_part) inline_ref {
return begin_cell()
.store_int(0xbc - 0x100, 8)
.store_uint(validator_pubkey, 256)
.store_ref(description)
.store_uint(created_at, 32)
.store_uint(severity, 8)
.store_uint(reward_addr, 256)
.store_grams(paid)
.store_grams(suggested_fine)
.store_uint(suggested_fine_part, 32);
}
;; complaint_prices#1a deposit:Grams bit_price:Grams cell_price:Grams = ComplaintPricing;
(int, int, int) parse_complaint_prices(cell info) inline {
slice cs = info.begin_parse();
throw_unless(9, cs~load_uint(8) == 0x1a);
(int, int, int) res = (cs~load_grams(), cs~load_grams(), cs~load_grams());
cs.end_parse();
return res;
}
;; deposit bit_price cell_price
(int, int, int) get_complaint_prices() inline_ref {
cell info = config_param(config_params::complaint_prices);
return info.null?() ? (1 << 36, 1, 512) : info.parse_complaint_prices();
}
;; elected_for elections_begin_before elections_end_before stake_held_for
(int, int, int, int) get_validator_conf() inline_ref {
;; _ validators_elected_for:uint32 elections_start_before:uint32
;; elections_end_before:uint32 stake_held_for:uint32
;; = ConfigParam 15;
slice cs = config_param(config_params::validation_times).begin_parse();
(int, int, int, int) res = (cs~load_uint(32), cs~load_uint(32), cs~load_uint(32), cs~load_uint(32));
cs.end_parse();
return res;
}
;; next three functions return information about current validator set (config param #34)
;; they are borrowed from config-code.fc
(cell, int, cell) get_current_vset() inline_ref {
cell vset = config_param(config_params::current_validators_set);
slice cs = begin_parse(vset);
;; validators_ext#12 utime_since:uint32 utime_until:uint32
;; total:(## 16) main:(## 16) { main <= total } { main >= 1 }
;; total_weight:uint64
throw_unless(40, cs~load_uint(8) == 0x12);
cs~skip_bits(32 + 32 + 16 + 16);
(int total_weight, cell dict) = (cs~load_uint(64), cs~load_dict());
cs.end_parse();
return (vset, total_weight, dict);
}
(slice, int) get_validator_descr(int idx) inline {
(cell vset, int total_weight, cell dict) = get_current_vset();
(slice value, _) = dict.udict_get?(16, idx);
return (value, total_weight);
}
(int, int) unpack_validator_descr(slice cs) inline {
;; ed25519_pubkey#8e81278a pubkey:bits256 = SigPubKey;
;; validator#53 public_key:SigPubKey weight:uint64 = ValidatorDescr;
;; validator_addr#73 public_key:SigPubKey weight:uint64 adnl_addr:bits256 = ValidatorDescr;
throw_unless(41, (cs~load_uint(8) & ~ 0x20) == 0x53);
throw_unless(41, cs~load_uint(32) == tag::ed25519_pubkey);
return (cs~load_uint(256), cs~load_uint(64));
}
() send_message_back(slice addr,
int ans_tag,
int query_id,
int body, ;; optional, if 0 - neglected
int grams,
int mode) impure inline_ref {
;; int_msg_info$0 ihr_disabled:Bool bounce:Bool bounced:Bool src:MsgAddress -> 011000
builder msg = begin_cell() ;; see "Message X" description in crypto/block/block.tlb
;; or https://ton.org/docs/#/smart-contracts/messages?id=sending-messages
.store_uint(0x18, 6) ;; 0x18 = 0b011000 = {0, 1, 1 , 0, 00}
;; First 0 means int_msg_info$0 tag
;; 1 1 0 are flags (ihr_disabled, bounce, bounced)
;; 00 is a source address addr_none$00 tag,
;; correct value added automatically
.store_slice(addr) ;; destination address
.store_grams(grams) ;; stake value
.store_uint(0, 1 + 4 + 4 + 64 + 32 + 1 + 1) ;; 1 zero bit means there is no other:ExtraCurrencyCollection
;; 4 + 4 zero bits for empty ihr_fee:Grams and fwd_fee:Grams,
;; correct values added automatically
;; 64 + 32 zero bits for created_lt:uint64 and created_at:uint32,
;; correct values added automatically, see "CommonMsgInfo" description
;; 1 zero bit means there is no StateInit structure
;; 1 zero bit means the message body is represented
;; in this cell, not in reference
;; The following bits are the message body
.store_uint(ans_tag, 32)
.store_uint(query_id, 64);
if (body >= 0) {
msg~store_uint(body, 32);
}
send_raw_message(msg.end_cell(), mode);
}
() return_stake(slice addr,
int query_id,
int reason) impure inline_ref {
return send_message_back(addr, op::response::stake_rejected, query_id, reason, 0, 64);
}
() send_confirmation(slice addr,
int query_id,
int comment) impure inline {
return send_message_back(addr, op::response::stake_accepted, query_id, comment, ONECOIN, 2);
}
() send_validator_set_to_config(int config_addr,
cell vset,
int query_id) impure inline {
builder msg = begin_cell() ;; see "Message X" description in crypto/block/block.tlb
;; or https://ton.org/docs/#/smart-contracts/messages?id=sending-messages
.store_uint(0xc4ff, 17) ;; 0xc4ff = 0b01100010011111111 = {0, 1, 1, 0, 00, 10, 0, 11111111}
;; First 0 means int_msg_info$0 tag
;; 110 are flags (ihr_disabled, bounce, bounced)
;; 00 is a source address addr_none$00 tag,
;; correct value added automatically
;; 10 means addr_std$10 tag, 0 means no anycast
;; 0xFF means workchain_id (masterchain) dest_addr
.store_uint(config_addr, 256)
;;destination address hash_part, see "MsgAddressInt" description
.store_grams(ONECOIN) ;; 1 TONCOIN of value to process and obtain answer
.store_uint(0, 1 + 4 + 4 + 64 + 32 + 1 + 1)
;; 1 zero bit means there is no other:ExtraCurrencyCollection
;; 4 + 4 zero bits for empty ihr_fee:Grams and fwd_fee:Grams,
;; correct values added automatically
;; 64 + 32 zero bits for created_lt:uint64 and created_at:uint32,
;; correct values added automatically, see "CommonMsgInfo" description
;; 1 zero bit means there is no StateInit structure
;; 1 zero bit means the message body is represented
;; in this cell, not in reference
;; The following bits are the message body
.store_uint(op::set_next_validator_set, 32)
.store_uint(query_id, 64)
.store_ref(vset);
send_raw_message(msg.end_cell(), 1);
}
() send_validator_vote_to_config(int config_addr,
int query_id,
cell vote) impure inline {
builder msg = begin_cell() ;; see "Message X" description in crypto/block/block.tlb
;; or https://ton.org/docs/#/smart-contracts/messages?id=sending-messages
.store_uint(0xc4ff, 17) ;; 0xc4ff = 0b01100010011111111 = {0, 1, 1, 0, 00, 10, 0, 11111111}
;; First 0 means int_msg_info$0 tag
;; 110 are flags (ihr_disabled, bounce, bounced)
;; 00 is a source address addr_none$00 tag,
;; correct value added automatically
;; 10 means addr_std$10 tag, 0 means no anycast
;; 0xFF means workchain_id (masterchain) dest_addr
.store_uint(config_addr, 256)
;;destination address hash_part, see "MsgAddressInt" description
.store_grams(ONECOIN) ;; 1 TONCOIN of value to process and obtain answer
.store_uint(0, 1 + 4 + 4 + 64 + 32 + 1 + 1)
;; 1 zero bit means there is no other:ExtraCurrencyCollection
;; 4 + 4 zero bits for empty ihr_fee:Grams and fwd_fee:Grams,
;; correct values added automatically
;; 64 + 32 zero bits for created_lt:uint64 and created_at:uint32,
;; correct values added automatically, see "CommonMsgInfo" description
;; 1 zero bit means there is no StateInit structure
;; 1 zero bit means the message body is represented
;; in this cell, not in reference
;; The following bits are the message body
.store_uint(op::vote_for_config_proposal_from_elector, 32)
.store_uint(query_id, 64)
.store_ref(vote);
send_raw_message(msg.end_cell(), 1);
}
;; credits 'amount' to 'addr' inside credit dictionary 'credits'
(cell, ()) ~credit_to(cell credits,
int addr,
int amount) inline_ref {
(slice val, int f) = credits.udict_get?(256, addr);
if (f) {
amount += val~load_grams();
}
credits~udict_set_builder(256, addr, begin_cell().store_grams(amount));
return (credits, ());
}
() process_new_stake(slice s_addr,
int msg_value,
slice payload,
int query_id) impure inline {
(int src_wc, int src_addr) = parse_std_addr(s_addr);
slice ds = get_data().begin_parse();
cell elect = ds~load_dict();
if (elect.null?() | (src_wc != - 1)) {
;; no elections active, or source is not in masterchain
;; bounce message
return return_stake(s_addr, query_id, 0);
}
;; parse the remainder of new stake message
int validator_pubkey = payload~load_uint(256);
int stake_at = payload~load_uint(32);
int max_factor = payload~load_uint(32);
int adnl_addr = payload~load_uint(256);
slice signature = payload~load_ref().begin_parse().preload_bits(512);
payload.end_parse();
ifnot (check_data_signature(begin_cell()
.store_uint(tag::stake_application, 32)
.store_uint(stake_at, 32)
.store_uint(max_factor, 32)
.store_uint(src_addr, 256)
.store_uint(adnl_addr, 256)
.end_cell().begin_parse(), signature, validator_pubkey)) {
;; incorrect signature, return stake
return return_stake(s_addr, query_id, 1);
}
if (max_factor < 0x10000) {
;; factor must be >= 1. = 65536/65536
return return_stake(s_addr, query_id, 6);
}
;; parse current election data
(int elect_at,
int elect_close,
int min_stake,
int total_stake,
cell members,
int failed,
int finished) = elect.unpack_elect();
int confirmation_requested = query_id > 0;
msg_value -= confirmation_requested ? ONECOIN : 0; ;; deduct GR$1 for sending confirmation
if ((msg_value * 4096) < total_stake) {
;; stake smaller than 1/4096 of the total accumulated stakes, return
return return_stake(s_addr, query_id, 2);
}
total_stake += msg_value; ;; (provisionally) increase total stake
if (stake_at != elect_at) {
;; stake for some other elections, return
return return_stake(s_addr, query_id, 3);
}
if (finished) {
;; elections already finished, return stake
return return_stake(s_addr, query_id, 0);
}
(slice mem, int found) = members.udict_get?(256, validator_pubkey);
if (found) {
;; entry found, merge stakes
msg_value += mem~load_grams();
mem~load_uint(64); ;; skip timestamp and max_factor
if(src_addr != mem~load_uint(256)) {
;; can make stakes for a public key from one address only
return return_stake(s_addr, query_id, 4);
}
}
if (msg_value < min_stake) {
;; stake too small, return it
return return_stake(s_addr, query_id, 5);
}
throw_unless(44, msg_value);
accept_message();
;; store stake in the dictionary
members~udict_set_builder(256, validator_pubkey, begin_cell()
.store_grams(msg_value)
.store_uint(now(), 32)
.store_uint(max_factor, 32)
.store_uint(src_addr, 256)
.store_uint(adnl_addr, 256));
;; gather and save election data
elect = pack_elect(elect_at, elect_close, min_stake, total_stake, members, false, false);
set_data(begin_cell().store_dict(elect).store_slice(ds).end_cell());
;; return confirmation message
if (confirmation_requested) {
return send_confirmation(s_addr, query_id, 0);
}
return ();
}
(cell, int) unfreeze_without_bonuses(cell credits,
cell frozen_dict,
int total_stake) inline {
int total = int recovered = 0;
int pubkey = -1;
do {
(pubkey, slice cs, int f) = frozen_dict.udict_get_next?(256, pubkey);
if (f) {
(int addr, int weight, int stake, int banned) = (cs~load_uint(256), cs~load_uint(64), cs~load_grams(), cs~load_int(1));
cs.end_parse();
if (banned) {
recovered += stake;
} else {
credits~credit_to(addr, stake);
}
total += stake;
}
} until (~ f);
throw_unless(59, total == total_stake);
return (credits, recovered);
}
(cell, int) unfreeze_with_bonuses(cell credits,
cell frozen_dict,
int total_stake,
int total_bonuses) inline {
int total = int recovered = int returned_bonuses = 0;
int pubkey = -1;
do {
(pubkey, slice cs, int f) = frozen_dict.udict_get_next?(256, pubkey);
if (f) {
(int addr, int weight, int stake, int banned) = (cs~load_uint(256), cs~load_uint(64), cs~load_grams(), cs~load_int(1));
cs.end_parse();
if (banned) {
recovered += stake;
} else {
int bonus = muldiv(total_bonuses, stake, total_stake);
returned_bonuses += bonus;
credits~credit_to(addr, stake + bonus);
}
total += stake;
}
} until (~ f);
throw_unless(59, (total == total_stake) & (returned_bonuses <= total_bonuses));
return (credits, recovered + total_bonuses - returned_bonuses);
}
(cell, cell, int) unfreeze_all(cell credits,
cell past_elections,
int elect_id) inline_ref {
(slice fs, int f) = past_elections~udict_delete_get?(32, elect_id);
ifnot (f) {
;; no elections with this id
return (credits, past_elections, 0);
}
(int unfreeze_at,
int stake_held,
int vset_hash,
cell frozen_dict,
int total_stake,
int bonuses,
cell complaints) = fs.unpack_past_election();
int unused_prizes = (bonuses > 0) ?
credits~unfreeze_with_bonuses(frozen_dict, total_stake, bonuses) :
credits~unfreeze_without_bonuses(frozen_dict, total_stake);
return (credits, past_elections, unused_prizes);
}
() config_set_confirmed(slice s_addr,
int query_id,
int ok) impure inline {
(int src_wc, int src_addr) = parse_std_addr(s_addr);
int config_addr = config_param(config_params::config_address).begin_parse().preload_uint(256);
slice ds = get_data().begin_parse();
cell elect = ds~load_dict();
if ((src_wc != - 1) | (src_addr != config_addr) | elect.null?()) {
;; not from config smc, somebody's joke?
;; or no elections active (or just completed)
return ();
}
(int elect_at,
int elect_close,
int min_stake,
int total_stake,
cell members,
int failed,
int finished) = elect.unpack_elect();
if ((elect_at != query_id) | ~ finished) {
;; not these elections, or elections not finished yet
return ();
}
accept_message();
ifnot (ok) {
;; cancel elections, return stakes
(cell credits, cell past_elections, int grams) = (ds~load_dict(), ds~load_dict(), ds~load_grams());
(credits, past_elections, int unused_prizes) = unfreeze_all(credits, past_elections, elect_at);
set_data(begin_cell()
.store_int(false, 1)
.store_dict(credits)
.store_dict(past_elections)
.store_grams(grams + unused_prizes)
.store_slice(ds)
.end_cell());
}
;; ... do not remove elect until we see this set as the next elected validator set
}
() process_simple_transfer(slice s_addr,
int msg_value) impure inline_ref {
(cell elect, cell credits, cell past_elections, int grams, int active_id, int active_hash) = load_data();
(int src_wc, int src_addr) = parse_std_addr(s_addr);
if (src_addr | (src_wc != - 1) | (active_id == 0)) {
;; simple transfer to us (credit "nobody's" account)
;; (or no known active validator set)
grams += msg_value;
return store_data(elect, credits, past_elections, grams, active_id, active_hash);
}
;; zero source address -1:00..00 (collecting validator fees)
(slice fs, int f) = past_elections.udict_get?(32, active_id);
ifnot (f) {
;; active validator set not found (?)
grams += msg_value;
} else {
;; credit active validator set bonuses
(int unfreeze_at,
int stake_held,
int hash,
cell frozen_dict,
int total_stake,
int bonuses,
cell complaints) = fs.unpack_past_election();
bonuses += msg_value;
past_elections~udict_set_builder(32, active_id,
pack_past_election(unfreeze_at, stake_held, hash, frozen_dict, total_stake, bonuses, complaints));
}
return store_data(elect, credits, past_elections, grams, active_id, active_hash);
}
() recover_stake(int op,
slice s_addr,
int query_id) impure inline_ref {
(int src_wc, int src_addr) = parse_std_addr(s_addr);
if (src_wc != - 1) {
;; not from masterchain, return error
return send_message_back(s_addr, op::not_allowed, query_id, op, 0, 64);
}
slice ds = get_data().begin_parse();
(cell elect, cell credits) = (ds~load_dict(), ds~load_dict());
(slice cs, int f) = credits~udict_delete_get?(256, src_addr);
ifnot (f) {
;; no credit for sender, return error
return send_message_back(s_addr, op::not_allowed, query_id, op, 0, 64);
}
int amount = cs~load_grams();
cs.end_parse();
;; save data
set_data(begin_cell().store_dict(elect).store_dict(credits).store_slice(ds).end_cell());
;; send amount to sender in a new message
send_raw_message(begin_cell() ;; see "Message X" description in crypto/block/block.tlb
;; or https://ton.org/docs/#/smart-contracts/messages?id=sending-messages
.store_uint(0x18, 6) ;; 0x18 = 0b011000 = {0, 1, 1 , 0, 00}
;; First 0 means int_msg_info$0 tag
;; 1 1 0 are flags (ihr_disabled, bounce, bounced)
;; 00 is a source address addr_none$00 tag,
;; correct value added automatically
.store_slice(s_addr) ;; destination address
.store_grams(amount) ;; stake value
.store_uint(0, 1 + 4 + 4 + 64 + 32 + 1 + 1) ;; 1 zero bit means there is no other:ExtraCurrencyCollection
;; 1 zero bit means there is no other:ExtraCurrencyCollection
;; 4 + 4 zero bits for empty ihr_fee:Grams and fwd_fee:Grams,
;; correct values added automatically
;; 64 + 32 zero bits for created_lt:uint64 and created_at:uint32,
;; correct values added automatically, see "CommonMsgInfo" description
;; 1 zero bit means there is no StateInit structure
;; 1 zero bit means the message body is represented
;; in this cell, not in reference
;; The following bits are the message body
.store_uint(op::response::stake_recover, 32)
.store_uint(query_id, 64)
.end_cell(), 64);
}
() after_code_upgrade(slice s_addr,
slice payload,
int query_id) impure method_id(1666) {
int op = op::set_new_code;
return send_message_back(s_addr, op::response::new_code_set, query_id, op, 0, 64);
}
int upgrade_code(slice s_addr,
slice payload,
int query_id) inline {
cell c_addr = config_param(config_params::config_address);
if (c_addr.null?()) {
;; no configuration smart contract known
return false;
}
int config_addr = c_addr.begin_parse().preload_uint(256);
(int src_wc, int src_addr) = parse_std_addr(s_addr);
if ((src_wc != - 1) | (src_addr != config_addr)) {
;; not from configuration smart contract, return error
return false;
}
accept_message();
cell code = payload~load_ref();
set_code(code);
ifnot(payload.slice_empty?()) {
set_c3(code.begin_parse().bless());
after_code_upgrade(s_addr, payload, query_id);
throw(0);
}
return true;
}
int compute_storage_price(int bits,
int refs,
int expire_in,
int deposit,
int bit_price,
int cell_price) inline_ref {
int pps = (bits + 1024) * bit_price + (refs + 2) * cell_price;
return pps * expire_in + deposit;
}
;; paid_price, error
(int, int) register_complaint(slice s_addr,
slice complaint,
int msg_value) inline {
(int src_wc, int src_addr) = parse_std_addr(s_addr);
if (src_wc != - 1) { ;; not from masterchain, return error
return (0, 1);
}
if (complaint.slice_depth() >= 128) {
return (0, 3); ;; invalid complaint
}
(cell elect, cell credits, cell past_elections, int grams, int active_id, int active_hash) = load_data();
int election_id = complaint~load_uint(32);
(slice fs, int f) = past_elections.udict_get?(32, election_id);
ifnot (f) { ;; election not found
return (0, 2);
}
int expire_in = fs.preload_uint(32) - now();
if (expire_in <= 0) { ;; already expired
return (0, 4);
}
(int validator_pubkey,
cell description,
int created_at,
int severity,
int reward_addr,
int paid,
int suggested_fine,
int suggested_fine_part) = unpack_complaint(complaint);
reward_addr = src_addr;
created_at = now();
;; compute complaint storage/creation price
(int deposit, int bit_price, int cell_price) = get_complaint_prices();
var (_, bits, refs) = slice_compute_data_size(complaint, 4096); ;; 4096 is max_cells
int paid = compute_storage_price(bits, refs, expire_in, deposit, bit_price, cell_price);
if (msg_value < paid + ONECOIN) { ;; not enough money
return (0, 5);
}
;; re-pack modified complaint
cell complaint = pack_complaint(validator_pubkey, description, created_at, severity, reward_addr, paid, suggested_fine, suggested_fine_part).end_cell();
(int unfreeze_at,
int stake_held,
int vset_hash,
cell frozen_dict,
int total_stake,
int bonuses,
cell complaints) = unpack_past_election(fs);
(slice fs, int f) = frozen_dict.udict_get?(256, validator_pubkey);
ifnot (f) { ;; no such validator, cannot complain
return (0, 6);
}
fs~skip_bits(256 + 64); ;; addr weight
int validator_stake = fs~load_grams();
int fine = suggested_fine + muldiv(validator_stake, suggested_fine_part, 1 << 32);
if (fine > validator_stake) { ;; validator's stake is less than suggested fine
return (0, 7);
}
if (fine <= paid) { ;; fine is less than the money paid for creating complaint
return (0, 8);
}
;; create complaint status
builder cstatus = pack_complaint_status(complaint, null(), 0, 0);
;; save complaint status into complaints
int cpl_id = complaint.cell_hash();
ifnot (complaints~udict_add_builder?(256, cpl_id, cstatus)) {
return (0, 9); ;; complaint already exists
}
;; pack past election info
past_elections~udict_set_builder(32, election_id, pack_past_election(unfreeze_at, stake_held, vset_hash, frozen_dict, total_stake, bonuses, complaints));
;; pack persistent data
;; next line can be commented, but it saves a lot of stack manipulations
(cell elect, cell credits, cell past_elections, int grams, int active_id, int active_hash) = load_data();
store_data(elect, credits, past_elections, grams, active_id, active_hash);
return (paid, 0);
}
(cell, cell, int, int) punish(cell credits,
cell frozen_dict,
cell complaint) inline_ref {
(int validator_pubkey,
cell description,
int created_at,
int severity,
int reward_addr,
int paid,
int suggested_fine,
int suggested_fine_part) = complaint.begin_parse().unpack_complaint();
(slice cs, int f) = frozen_dict.udict_get?(256, validator_pubkey);
ifnot (f) {
;; no validator to punish
return (credits, frozen_dict, 0, 0);
}
(int addr, int weight, int stake, int banned) = (cs~load_uint(256),
cs~load_uint(64),
cs~load_grams(),
cs~load_int(1));
cs.end_parse();
int fine = min(stake, suggested_fine + muldiv(stake, suggested_fine_part, 1 << 32));
stake -= fine;
frozen_dict~udict_set_builder(256, validator_pubkey,
begin_cell()
.store_uint(addr, 256)
.store_uint(weight, 64)
.store_grams(stake)
.store_int(banned, 1)
);
int reward = min(fine >> 3, paid * 8);
credits~credit_to(reward_addr, reward);
return (credits, frozen_dict, fine - reward, fine);
}
(cell, cell, int) register_vote(cell complaints,
int chash,
int idx,
int weight) inline {
(slice cstatus, int found?) = complaints.udict_get?(256, chash);
ifnot (found?) {
;; complaint not found
return (complaints, null(), -1);
}
(cell cur_vset, int total_weight, _) = get_current_vset();
int cur_vset_id = cur_vset.cell_hash();
(cell complaint, cell voters, int vset_id, int weight_remaining) = unpack_complaint_status(cstatus);
int vset_old? = (vset_id != cur_vset_id);
if ((weight_remaining < 0) & vset_old?) {
;; previous validator set already collected 2/3 votes, skip new votes
return (complaints, null(), -3);
}
if (vset_old?) {
;; complaint votes belong to a previous validator set, reset voting
vset_id = cur_vset_id;
voters = null();
weight_remaining = muldiv(total_weight, 2, 3);
}
(_, int found?) = voters.udict_get?(16, idx);
if (found?) {
;; already voted for this proposal, ignore vote
return (complaints, null(), 0);
}
;; register vote
voters~udict_set_builder(16, idx, begin_cell().store_uint(now(), 32));
int old_wr = weight_remaining;
weight_remaining -= weight;
;; save voters and weight_remaining
complaints~udict_set_builder(256, chash, pack_complaint_status(complaint, voters, vset_id, weight_remaining));
if( (old_wr >= 0) & (weight_remaining < 0)) {
;; complaint wins, prepare punishment
return (complaints, complaint, 2);
}
return (complaints, null(), 1);
}
int proceed_register_vote(int election_id,
int chash,
int idx,
int weight,
int val_pubkey,
int src_addr) impure inline {
(cell elect, cell credits, cell past_elections, int grams, int active_id, int active_hash) = load_data();
(slice fs, int f) = past_elections.udict_get?(32, election_id);
ifnot (f) { ;; election not found
return -2;
}
(int unfreeze_at,
int stake_held,
int vset_hash,
cell frozen_dict,
int total_stake,
int bonuses,
cell complaints) = unpack_past_election(fs);
(slice cs, int pubkey_found) = frozen_dict.udict_get?(256, val_pubkey);
throw_unless(error::validator_params_mismatch, pubkey_found);
throw_unless(error::validator_params_mismatch, (cs~load_uint(256) == src_addr));
(complaints, cell accepted_complaint, int status) = register_vote(complaints, chash, idx, weight);
if (status <= 0) {
return status;
}
ifnot (accepted_complaint.null?()) {
(credits, frozen_dict, int fine_unalloc, int fine_collected) = punish(credits, frozen_dict, accepted_complaint);
grams += fine_unalloc;
total_stake -= fine_collected;
}
past_elections~udict_set_builder(32, election_id, pack_past_election(unfreeze_at, stake_held, vset_hash, frozen_dict, total_stake, bonuses, complaints));
store_data(elect, credits, past_elections, grams, active_id, active_hash);
return status;
}
() recv_internal(int msg_value, cell in_msg_cell, slice in_msg) impure {
;; do nothing for internal messages
slice cs = in_msg_cell.begin_parse();
int flags = cs~load_uint(4); ;; int_msg_info$0 ihr_disabled:Bool bounce:Bool bounced:Bool
int is_bounced = flags & 1;
if (is_bounced) {
;; ignore all bounced messages
return ();
}
slice s_addr = cs~load_msg_addr();
if (in_msg.slice_empty?()) {
;; inbound message has empty body
return process_simple_transfer(s_addr, msg_value);
}
int op = in_msg~load_uint(32);
if (op == 0) {
;; simple transfer with comment, return
return process_simple_transfer(s_addr, msg_value);
}
int query_id = in_msg~load_uint(64);
if (op == op::new_stake) {
;; new stake message
return process_new_stake(s_addr, msg_value, in_msg, query_id);
}
if (op == op::recover_stake) {
;; recover stake request
return recover_stake(op, s_addr, query_id);
}
if (op == op::set_new_code) {
;; upgrade code (accepted only from configuration smart contract)
int ok = upgrade_code(s_addr, in_msg, query_id);
return send_message_back(s_addr, ok ? op::response::new_code_set : op::not_supported, query_id, op, 0, 64);
}
int cfg_ok = (op == op::response::update_vset_confirm);
if (cfg_ok | (op == op::response::update_vset_reject)) {
;; confirmation from configuration smart contract
return config_set_confirmed(s_addr, query_id, cfg_ok);
}
if (op == op::new_complaint) {
;; new complaint
(int paid, int error) = register_complaint(s_addr, in_msg, msg_value);
int mode = 64;
int ans_tag = error;
ifnot (error) {
;; ok, debit price
raw_reserve(paid, 4);
mode = 128;
}
return send_message_back(s_addr, ans_tag + op::response::new_complaint, query_id, op, 0, mode);
}
if (op == op::vote_for_complaint) {
;; vote for a complaint
slice signature = in_msg~load_bits(512);
slice msg_body = in_msg;
(int sign_tag, int idx, int elect_id, int chash) = (in_msg~load_uint(32),
in_msg~load_uint(16),
in_msg~load_uint(32),
in_msg~load_uint(256));
in_msg.end_parse();
throw_unless(37, sign_tag == tag::complaint);
(slice vdescr, int total_weight) = get_validator_descr(idx);
(int val_pubkey, int weight) = unpack_validator_descr(vdescr);
throw_unless(34, check_data_signature(msg_body, signature, val_pubkey));
(int src_wc, int src_addr) = parse_std_addr(s_addr);
throw_unless(error::validator_params_mismatch, src_wc == -1);
int res = proceed_register_vote(elect_id, chash, idx, weight, val_pubkey, src_addr);
return send_message_back(s_addr, res + op::response::vote_result, query_id, op, 0, 64);
}
if (op == op::vote_for_config_proposal) {
(int idx, int pubkey, int phash) = (in_msg~load_uint(16), in_msg~load_uint(256), in_msg~load_uint(256));
(_, _, cell past_elections, _, int active_id, int active_hash) = load_data();
(slice fs, int election_found) = past_elections.udict_get?(32, active_id);
throw_unless(error::no_elected_set, election_found);
(_, _, _, cell frozen_dict, _, _, _) = fs.unpack_past_election();
(slice cs, int pubkey_found) = frozen_dict.udict_get?(256, pubkey);
throw_unless(error::validator_params_mismatch, pubkey_found);
(int src_wc, int src_addr) = parse_std_addr(s_addr);
throw_unless(error::validator_params_mismatch, (cs~load_uint(256) == src_addr) & (src_wc == -1));
(slice vdescr, int total_weight) = get_validator_descr(idx);
(int val_pubkey, int weight) = unpack_validator_descr(vdescr);
throw_unless(error::validator_params_mismatch, val_pubkey == pubkey);
int config_addr = config_param(config_params::config_address).begin_parse().preload_uint(256);
send_validator_vote_to_config(config_addr, query_id,
begin_cell()
.store_uint(idx, 16)
.store_uint(phash, 256)
.store_uint(active_hash, 256)
.end_cell()
);
;; Note, since elector and config are special contracts they do not pay fees
;; thus we only enforce voter to pay for processing on Elector
return send_message_back(s_addr, op::response::vote_for_config_proposal, query_id, 0, 0, 64);
}
ifnot (op & (1 << 31)) {
;; unknown query, return error
return send_message_back(s_addr, op::not_supported, query_id, op, 0, 64);
}
;; unknown answer, ignore
return ();
}
int postpone_elections() inline {
;; in the case postpone_elections will implement some additional logic
;; don't forget to add impure modificator
return false;
}
;; computes the total stake out of the first n entries of list l
int compute_total_stake(tuple applications_list, int cutoff, int m_stake) inline_ref {
int tot_stake = 0;
repeat (cutoff) {
(tuple h, tuple applications_list) = uncons(applications_list);
int stake = h.at(0);
int max_f = h.at(1);