/
voting.cpp
executable file
·1448 lines (1168 loc) · 61.6 KB
/
voting.cpp
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
/** Fio system contract file
* Description: this file contains actions and data structures pertaining to voting in the fio protocol
* @author Adam Androulidakis, Casey Gardiner, Ed Rotthoff
* @file voting.cpp
* @license FIO Foundation ( https://github.com/fioprotocol/fio/blob/master/LICENSE ) Dapix
*
* Changes:
*/
#include <fio.system/fio.system.hpp>
#include <eosiolib/eosio.hpp>
#include <eosiolib/crypto.h>
#include <eosiolib/datastream.hpp>
#include <eosiolib/serialize.hpp>
#include <eosiolib/multi_index.hpp>
#include <eosiolib/privileged.hpp>
#include <eosiolib/singleton.hpp>
#include <fio.token/fio.token.hpp>
#include <fio.fee/fio.fee.hpp>
#include <fio.common/fio.common.hpp>
#include <eosiolib/asset.hpp>
#include <algorithm>
#include <cmath>
namespace eosiosystem {
using eosio::indexed_by;
using eosio::const_mem_fun;
using eosio::singleton;
using eosio::transaction;
/*******
* this action will do the required work in the system tables that is necessary
* before performing the burning of a fio address, the voters and producers
* table must be cleaned up appropriately for the specified address
* @param fioaddrhash this is the hash of the fio address being considered for burning.
*/
void
system_contract::burnaction(const uint128_t &fioaddrhash) {
require_auth(_self);
//verify that this address is expired.
//this helps to ensure bad actors cant use this action unintentionally.
uint64_t nowtime = now();
auto namesbyname = _fionames.get_index<"byname"_n>();
auto nameiter = namesbyname.find(fioaddrhash);
//check(nameiter != namesbyname.end(),"unexpected error verifying expired address");
uint64_t expire = nameiter->expiration;
if ((expire + ADDRESSWAITFORBURNDAYS) <= nowtime) {
auto prodbyaddress = _producers.get_index<"byaddress"_n>();
auto prod = prodbyaddress.find(fioaddrhash);
if (prod != prodbyaddress.end()) {
prodbyaddress.modify(prod, _self, [&](producer_info &info) {
info.fio_address = "";
info.addresshash = 0;
info.is_active = false;
});
}
auto votersbyaddress = _voters.get_index<"byaddress"_n>();
auto voters = votersbyaddress.find(fioaddrhash);
if (voters != votersbyaddress.end()) {
//be absolutely certain to only delete the record we are interested in.
if (voters->addresshash == fioaddrhash) {
votersbyaddress.erase(voters);
}
}
}
}
void
system_contract::incram(const name &accountnm, const int64_t &amount) {
require_auth(_self);
bool debug=false;
int64_t ram;
int64_t cpu;
int64_t net;
get_resource_limits(accountnm.value,&ram,&net,&cpu);
if (ram > 0 ) {
if (debug) {
print(" incremented the RAM for account ", accountnm, " saw pre-existing RAM value of ", ram,
"\n");
int64_t ramused = get_account_ram_usage(accountnm.value);
print(" RAM used by account ", accountnm, " is ", ramused, "\n");
}
ram += amount;
set_resource_limits(accountnm.value, ram, net, cpu);
if(debug) {
print(" incremented the RAM for account ", accountnm, " new amount is ", ram, "\n");
}
}else{
if(debug) {
print(" saw unlimited ram use for account ", accountnm, "\n");
}
}
}
/**
* This method will create a producer_config and producer_info object for 'producer'
*
* @pre producer is not already registered
* @pre producer to register is an account
* @pre authority of producer to register
*
*/
void
system_contract::regiproducer(const name &producer, const string &producer_key, const std::string &url,
const uint16_t &location, const string &fio_address) {
check(url.size() < 512, "url too long");
check(producer_key != "", "public key should not be the default value");
require_auth(producer);
auto prodbyowner = _producers.get_index<"byowner"_n>();
auto prod = prodbyowner.find(producer.value);
uint128_t addresshash = string_to_uint128_hash(fio_address.c_str());
const auto ct = current_time_point();
if (prod != prodbyowner.end()) {
if (prod->is_active) {
fio_400_assert(false, "fio_address", fio_address,
"Already registered as producer", ErrorFioNameNotReg);
} else {
prodbyowner.modify(prod, producer, [&](producer_info &info) {
info.is_active = true;
info.fio_address = fio_address;
info.addresshash = addresshash;
info.producer_public_key = abieos::string_to_public_key(producer_key);
info.url = url;
info.location = location;
if (info.last_claim_time == time_point())
info.last_claim_time = ct;
});
}
} else {
uint64_t id = _producers.available_primary_key();
_producers.emplace(producer, [&](producer_info &info) {
info.id = id;
info.owner = producer;
info.fio_address = fio_address;
info.addresshash = addresshash;
info.total_votes = 0;
info.producer_public_key = abieos::string_to_public_key(producer_key);
info.is_active = true;
info.url = url;
info.location = location;
info.last_claim_time = ct;
});
}
fio_400_assert(transaction_size() <= MAX_TRX_SIZE, "transaction_size", std::to_string(transaction_size()),
"Transaction is too large", ErrorTransactionTooLarge);
}
/******
* reg producer will register a producer using the specified information
* @param fio_address this is the fio address that will be used to claim rewards.
* @param fio_pub_key this is the pub key that will be used to generate block, this
* can be for a different account than the fio address.
* @param url this is the url of the block producer.
* @param location this is the location number, sorting these determines BP order in the schedule.
* @param actor the account associated with signing.
* @param max_fee the max fee willing to be paid.
*/
void
system_contract::regproducer(
const string &fio_address,
const string &fio_pub_key,
const std::string &url,
const uint16_t &location,
const name &actor,
const int64_t &max_fee) {
require_auth(actor);
fio_400_assert(max_fee >= 0, "max_fee", to_string(max_fee), "Invalid fee value",
ErrorMaxFeeInvalid);
fio_400_assert(validateURLFormat(url), "url", url, "Invalid url",
ErrorMaxFeeInvalid);
fio_400_assert(validateLocationFormat(location), "location", to_string(location), "Invalid location",
ErrorMaxFeeInvalid);
fio_400_assert(isPubKeyValid(fio_pub_key),"fio_pub_key", fio_pub_key,
"Invalid FIO Public Key",
ErrorPubKeyValid);
FioAddress fa;
getFioAddressStruct(fio_address, fa);
uint128_t nameHash = string_to_uint128_hash(fa.fioaddress.c_str());
uint128_t domainHash = string_to_uint128_hash(fa.fiodomain.c_str());
auto namesbyname = _fionames.get_index<"byname"_n>();
auto fioname_iter = namesbyname.find(nameHash);
fio_400_assert(fioname_iter != namesbyname.end(), "fio_address", fio_address,
"FIO Address not registered", ErrorFioNameNotReg);
//check that the name is not expired
uint32_t name_expiration = fioname_iter->expiration;
uint32_t present_time = now();
uint64_t account = fioname_iter->owner_account;
fio_403_assert(account == actor.value, ErrorSignature);
fio_400_assert(present_time <= name_expiration, "fio_address", fio_address,
"FIO Address expired", ErrorFioNameExpired);
auto domainsbyname = _domains.get_index<"byname"_n>();
auto domains_iter = domainsbyname.find(domainHash);
fio_400_assert(domains_iter != domainsbyname.end(), "fio_address", fio_address,
"FIO Address not registered", ErrorFioNameNotReg);
uint32_t expiration = domains_iter->expiration;
//add 30 days to the domain expiration, this call will work until 30 days past expire.
expiration = get_time_plus_seconds(expiration,SECONDS30DAYS);
fio_400_assert(present_time <= expiration, "domain", fa.fiodomain, "FIO Domain expired",
ErrorDomainExpired);
regiproducer(actor, fio_pub_key, url, location, fio_address);
//TODO: REFACTOR FEE ( PROXY / PRODUCER )
//begin new fees, logic for Mandatory fees.
uint128_t endpoint_hash = string_to_uint128_hash(REGISTER_PRODUCER_ENDPOINT);
auto fees_by_endpoint = _fiofees.get_index<"byendpoint"_n>();
auto fee_iter = fees_by_endpoint.find(endpoint_hash);
//if the fee isnt found for the endpoint, then 400 error.
fio_400_assert(fee_iter != fees_by_endpoint.end(), "endpoint_name", REGISTER_PRODUCER_ENDPOINT,
"FIO fee not found for endpoint", ErrorNoEndpoint);
uint64_t reg_amount = fee_iter->suf_amount;
uint64_t fee_type = fee_iter->type;
//if its not a mandatory fee then this is an error.
fio_400_assert(fee_type == 0, "fee_type", to_string(fee_type),
"unexpected fee type for endpoint register_producer, expected 0",
ErrorNoEndpoint);
fio_400_assert(max_fee >= (int64_t)reg_amount, "max_fee", to_string(max_fee), "Fee exceeds supplied maximum.",
ErrorMaxFeeExceeded);
fio_fees(actor, asset(reg_amount, FIOSYMBOL), REGISTER_PRODUCER_ENDPOINT);
processrewardsnotpid(reg_amount, get_self());
//end new fees, logic for Mandatory fees.
const string response_string = string("{\"status\": \"OK\",\"fee_collected\":") +
to_string(reg_amount) + string("}");
if (REGPRODUCERRAM > 0) {
action(
permission_level{SYSTEMACCOUNT, "active"_n},
"eosio"_n,
"incram"_n,
std::make_tuple(actor, REGPRODUCERRAM)
).send();
}
fio_400_assert(transaction_size() <= MAX_TRX_SIZE, "transaction_size", std::to_string(transaction_size()),
"Transaction is too large", ErrorTransactionTooLarge);
send_response(response_string.c_str());
}
void system_contract::unregprod(
const string &fio_address,
const name &actor,
const int64_t &max_fee) {
require_auth(actor);
fio_400_assert(max_fee >= 0, "max_fee", to_string(max_fee), "Invalid fee value",
ErrorMaxFeeInvalid);
FioAddress fa;
getFioAddressStruct(fio_address, fa);
uint128_t nameHash = string_to_uint128_hash(fa.fioaddress.c_str());
uint128_t domainHash = string_to_uint128_hash(fa.fiodomain.c_str());
auto namesbyname = _fionames.get_index<"byname"_n>();
auto fioname_iter = namesbyname.find(nameHash);
fio_400_assert(fioname_iter != namesbyname.end(), "fio_address", fio_address,
"FIO Address not registered", ErrorFioNameNotReg);
//check that the name is not expired
uint32_t name_expiration = fioname_iter->expiration;
uint32_t present_time = now();
uint64_t account = fioname_iter->owner_account;
fio_403_assert(account == actor.value, ErrorSignature);
fio_400_assert(present_time <= name_expiration, "fio_address", fio_address,
"FIO Address expired", ErrorFioNameExpired);
auto domainsbyname = _domains.get_index<"byname"_n>();
auto domains_iter = domainsbyname.find(domainHash);
fio_400_assert(domains_iter != domainsbyname.end(), "fio_address", fio_address,
"FIO Address not registered", ErrorFioNameNotReg);
uint32_t expiration = domains_iter->expiration;
fio_400_assert(present_time <= expiration, "domain", fa.fiodomain, "FIO Domain expired",
ErrorDomainExpired);
auto prodbyowner = _producers.get_index<"byowner"_n>();
const auto &prod = prodbyowner.find(actor.value);
fio_400_assert(prod != prodbyowner.end(), "fio_address", fio_address,
"Not registered as producer", ErrorFioNameNotReg);
prodbyowner.modify(prod, same_payer, [&](producer_info &info) {
info.deactivate();
});
//begin new fees, logic for Mandatory fees.
uint128_t endpoint_hash = string_to_uint128_hash(UNREGISTER_PRODUCER_ENDPOINT);
auto fees_by_endpoint = _fiofees.get_index<"byendpoint"_n>();
auto fee_iter = fees_by_endpoint.find(endpoint_hash);
//if the fee isnt found for the endpoint, then 400 error.
fio_400_assert(fee_iter != fees_by_endpoint.end(), "endpoint_name", UNREGISTER_PRODUCER_ENDPOINT,
"FIO fee not found for endpoint", ErrorNoEndpoint);
uint64_t reg_amount = fee_iter->suf_amount;
uint64_t fee_type = fee_iter->type;
//if its not a mandatory fee then this is an error.
fio_400_assert(fee_type == 0, "fee_type", to_string(fee_type),
"register_producer unexpected fee type for endpoint register_producer, expected 0",
ErrorNoEndpoint);
fio_400_assert(max_fee >= (int64_t)reg_amount, "max_fee", to_string(max_fee), "Fee exceeds supplied maximum.",
ErrorMaxFeeExceeded);
fio_fees(actor, asset(reg_amount, FIOSYMBOL), UNREGISTER_PRODUCER_ENDPOINT);
processrewardsnotpid(reg_amount, get_self());
//end new fees, logic for Mandatory fees.
const string response_string = string("{\"status\": \"OK\",\"fee_collected\":") +
to_string(reg_amount) + string("}");
fio_400_assert(transaction_size() <= MAX_TRX_SIZE, "transaction_size", std::to_string(transaction_size()),
"Transaction is too large", ErrorTransactionTooLarge);
send_response(response_string.c_str());
}
void system_contract::update_elected_producers(const block_timestamp& block_time) {
_gstate.last_producer_schedule_update = block_time;
bool debug=false;
auto idx = _producers.get_index<"prototalvote"_n>();
using value_type = std::pair<eosio::producer_key, uint16_t>;
std::vector< value_type > top_producers;
top_producers.reserve(MAXACTIVEBPS);
vector<name> prevprods;
//clear _topprods table
auto iter = _topprods.begin();
while (iter != _topprods.end()) {
prevprods.push_back(iter->producer);
iter = _topprods.erase(iter);
}
for( auto it = idx.cbegin(); it != idx.cend() && top_producers.size() < MAXACTIVEBPS && 0 < it->total_votes && it->active(); ++it ) {
top_producers.emplace_back(
std::pair<eosio::producer_key, uint16_t>({{it->owner, it->producer_public_key}, it->location}));
_topprods.emplace(get_self(), [&](auto &p) {
p.producer = it->owner;
});
std::vector<name>::iterator pos = std::find(prevprods.begin(), prevprods.end(), it->owner);
if (pos != prevprods.end()) {
//it was in the list before, do not ajust the resource limits, remove from list
prevprods.erase(pos);
}
else {
if(debug) {
print("setting producer to unlimited resources for account ", it->owner, "\n");
}
//it was not in the list before, set it unlimited
set_resource_limits(it->owner.value, -1,-1,-1);
}
}
//this is the producers exiting the schedule, reset their resoource limits.
for(int i=0; i < prevprods.size(); i++){
//get the ram that this account has used.
int64_t ram = get_account_ram_usage(prevprods[i].value);
if(debug) {
print(" de-schedule producer, found ram usage ", ram, " for account ", prevprods[i], "\n");
}
//increment the ram by the set amount.
ram += ADDITIONALRAMBPDESCHEDULING;
//set the new limits going forward.
set_resource_limits(prevprods[i].value, ram, -1, -1);
if(debug) {
print(" de-schedule producer, setting RAM limit ", ram, " for account ", prevprods[i],
"\n");
}
}
if( top_producers.size() == 0 || top_producers.size() < _gstate.last_producer_schedule_size ) {
return;
}
/// sort by producer location, location initialized to zero in fio.system.hpp
/// location will be set upon call to register producer by the block producer.
/// the location should be considered as a scheduled order of producers, they should
/// set the location so that traversing locations gives most proximal producer locations
/// to help address latency.
std::sort( top_producers.begin(), top_producers.end(), []( const value_type& lhs, const value_type& rhs ) {
return lhs.first.producer_name < rhs.first.producer_name; // sort by producer name
// return lhs.second < rhs.second; // sort by location
} );
std::vector<eosio::producer_key> producers;
producers.reserve(top_producers.size());
for( auto& item : top_producers )
producers.push_back( std::move(item.first) );
auto packed_schedule = pack(producers);
if( set_proposed_producers(packed_schedule.data(), packed_schedule.size() ) >= 0 ) {
_gstate.last_producer_schedule_size = static_cast<decltype(_gstate.last_producer_schedule_size)>( top_producers.size() );
}
}
double system_contract::update_total_votepay_share(time_point ct,
double additional_shares_delta,
double shares_rate_delta) {
double delta_total_votepay_share = 0.0;
if (ct > _gstate3.last_vpay_state_update) {
delta_total_votepay_share = _gstate3.total_vpay_share_change_rate
* double((ct - _gstate3.last_vpay_state_update).count() / 1E6);
}
delta_total_votepay_share += additional_shares_delta;
if (delta_total_votepay_share < 0 && _gstate2.total_producer_votepay_share < -delta_total_votepay_share) {
_gstate2.total_producer_votepay_share = 0.0;
} else {
_gstate2.total_producer_votepay_share += delta_total_votepay_share;
}
if (shares_rate_delta < 0 && _gstate3.total_vpay_share_change_rate < -shares_rate_delta) {
_gstate3.total_vpay_share_change_rate = 0.0;
} else {
_gstate3.total_vpay_share_change_rate += shares_rate_delta;
}
_gstate3.last_vpay_state_update = ct;
return _gstate2.total_producer_votepay_share;
}
/**
* @pre producers must be sorted from lowest to highest and must be registered and active
* @pre if proxy is set then no producers can be voted for
* @pre if proxy is set then proxy account must exist and be registered as a proxy
* @pre every listed producer or proxy must have been previously registered
* @pre voter must authorize this action
* @pre voter must have previously staked some amount of CORE_SYMBOL for voting
* @pre voter->staked must be up to date
*
* @post every producer previously voted for will have vote reduced by previous vote weight
* @post every producer newly voted for will have vote increased by new vote amount
* @post prior proxy will proxied_vote_weight decremented by previous vote weight
* @post new proxy will proxied_vote_weight incremented by new vote weight
*
* If voting for a proxy, the producer votes will not change until the proxy updates their own vote.
*/
/*** remove vproducer
void system_contract::vproducer(const name &voter_name, const name &proxy, const std::vector <name> &producers) {
require_auth(voter_name);
update_votes(voter_name, proxy, producers, true);
}
****/
void system_contract::voteproducer(const std::vector<string> &producers, const string &fio_address, const name &actor, const int64_t &max_fee) {
require_auth(actor);
//***** REMOVE POST MIGRATION *****//
auto old_table_iter = _voters_old.begin();
const uint32_t MOVELIMIT = 3;
uint32_t c = 0;
if (old_table_iter != _voters_old.end()) {
auto new_table_iter = _voters.begin();
//copy records
while(old_table_iter !=_voters_old.end()) {
_voters.emplace(get_self(), [&](voter_info &new_table) {
new_table.id = _voters.available_primary_key();
new_table.fioaddress = old_table_iter->fioaddress;
new_table.addresshash = old_table_iter->addresshash;
new_table.owner = old_table_iter->owner;
new_table.proxy = old_table_iter->proxy;
for(uint32_t i = 0; i < old_table_iter->producers.size(); i++) {
new_table.producers.push_back(producername{old_table_iter->producers[i]});
}
new_table.last_vote_weight = old_table_iter->last_vote_weight;
new_table.proxied_vote_weight = old_table_iter->proxied_vote_weight;
new_table.is_proxy = old_table_iter->is_proxy;
new_table.is_auto_proxy = old_table_iter->is_auto_proxy;
new_table.reserved2 = old_table_iter->reserved2;
new_table.reserved3 = old_table_iter->reserved3;
});
old_table_iter = _voters_old.erase(old_table_iter);
c++;
if (c > MOVELIMIT) break;
}
} else {
//***** REMOVE POST MIGRATION *****//
fio_400_assert(max_fee >= 0, "max_fee", to_string(max_fee), "Invalid fee value",
ErrorMaxFeeInvalid);
name proxy;
std::vector<name> producers_accounts;
FioAddress fa;
getFioAddressStruct(fio_address, fa);
fio_400_assert(fio_address == "" || validateFioNameFormat(fa), "fio_address", fio_address, "Invalid FIO Address format",
ErrorDomainAlreadyRegistered);
auto namesbyname = _fionames.get_index<"byname"_n>();
auto domainsbyname = _domains.get_index<"byname"_n>();
uint64_t bundleeligiblecountdown = 0;
if (!fio_address.empty()) {
uint128_t voterHash = string_to_uint128_hash(fio_address.c_str());
uint128_t voterDomainHash = string_to_uint128_hash(fa.fiodomain.c_str());
// compare fio_address owner and compare to actor
auto voter_iter = namesbyname.find(voterHash);
fio_400_assert(voter_iter != namesbyname.end(), "fio_address", fio_address,
"FIO address not registered", ErrorFioNameNotRegistered);
fio_400_assert(now() <= voter_iter->expiration, "fio_address", fio_address, "FIO Address expired",
ErrorDomainExpired);
auto voterdomain_iter = domainsbyname.find(voterDomainHash);
fio_400_assert(voterdomain_iter != domainsbyname.end(), "fio_address", fio_address,
"FIO Address not registered", ErrorFioNameNotReg);
fio_403_assert(voter_iter->owner_account == actor.value, ErrorSignature);
uint32_t voterdomain_expiration = voterdomain_iter->expiration;
fio_400_assert(now() <= voterdomain_expiration, "fio_address", fio_address, "FIO Domain expired",
ErrorDomainExpired);
bundleeligiblecountdown = voter_iter->bundleeligiblecountdown;
}
for (size_t i = 0; i < producers.size(); i++) {
getFioAddressStruct(producers[i], fa);
uint128_t nameHash = string_to_uint128_hash(fa.fioaddress.c_str());
uint128_t domainHash = string_to_uint128_hash(fa.fiodomain.c_str());
auto fioname_iter = namesbyname.find(nameHash);
fio_400_assert(fioname_iter != namesbyname.end(), "fio_address", fio_address,
"FIO Address not registered", ErrorFioNameNotReg);
uint32_t name_expiration = fioname_iter->expiration;
uint64_t account = fioname_iter->owner_account;
fio_400_assert(now() <= name_expiration, "fio_address", producers[i],
"FIO Address expired", ErrorFioNameExpired);
auto domains_iter = domainsbyname.find(domainHash);
fio_400_assert(domains_iter != domainsbyname.end(), "fio_address", fio_address,
"FIO Address not registered", ErrorFioNameNotReg);
fio_400_assert(now() <= domains_iter->expiration, "domain", fa.fiodomain, "FIO Domain expired",
ErrorDomainExpired);
producers_accounts.push_back(name{account});
}
auto votersbyowner = _voters.get_index<"byowner"_n>();
auto voter_prod_iter = votersbyowner.find(actor.value);
if (voter_prod_iter == votersbyowner.end()) {
uint64_t id = _voters.available_primary_key();
_voters.emplace(actor, [&](auto &p) {
p.id = id;
p.owner = actor;
});
}
//note -- we can call these lock token computations like this
//only because token locks are exclusive, meaning an account CANNOT have
//multiple locked token grants.
eosio::token::computeremaininglockedtokens(actor,true);
eosio::token::computegenerallockedtokens(actor,true);
sort(producers_accounts.begin(),producers_accounts.end());
update_votes(actor, proxy, producers_accounts, true);
uint128_t endpoint_hash = string_to_uint128_hash(VOTE_PRODUCER_ENDPOINT);
auto fees_by_endpoint = _fiofees.get_index<"byendpoint"_n>();
auto fee_iter = fees_by_endpoint.find(endpoint_hash);
uint64_t fee_amount = 0;
if (bundleeligiblecountdown > 0) {
action{
permission_level{_self, "active"_n},
AddressContract,
"decrcounter"_n,
make_tuple(fio_address, 1)
}.send();
} else {
fee_amount = fee_iter->suf_amount;
fio_400_assert(max_fee >= (int64_t) fee_amount, "max_fee", to_string(max_fee),
"Fee exceeds supplied maximum.",
ErrorMaxFeeExceeded);
fio_fees(actor, asset(fee_amount, FIOSYMBOL), VOTE_PRODUCER_ENDPOINT);
processrewardsnotpid(fee_amount, get_self());
//end new fees, logic for Mandatory fees.
}
const string response_string = string("{\"status\": \"OK\",\"fee_collected\":") +
to_string(fee_amount) + string("}");
if (VOTEPRODUCERRAM > 0) {
action(
permission_level{SYSTEMACCOUNT, "active"_n},
"eosio"_n,
"incram"_n,
std::make_tuple(actor, VOTEPRODUCERRAM)
).send();
}
fio_400_assert(transaction_size() <= MAX_TRX_SIZE, "transaction_size", std::to_string(transaction_size()),
"Transaction is too large", ErrorTransactionTooLarge);
send_response(response_string.c_str());
} //***** REMOVE POST MIGRATION *****//
}
void system_contract::voteproxy(const string &proxy, const string &fio_address, const name &actor, const int64_t &max_fee) {
require_auth(actor);
fio_400_assert(max_fee >= 0, "max_fee", to_string(max_fee), "Invalid fee value",
ErrorMaxFeeInvalid);
FioAddress proxyAddressObj, fioAddressObj;
getFioAddressStruct(proxy, proxyAddressObj);
getFioAddressStruct(fio_address, fioAddressObj);
fio_400_assert(validateFioNameFormat(proxyAddressObj), "proxy", proxy, "Invalid FIO Address format",
ErrorDomainAlreadyRegistered);
fio_400_assert(fio_address == "" || validateFioNameFormat(fioAddressObj), "fio_address", fio_address, "Invalid FIO Address format",
ErrorDomainAlreadyRegistered);
auto namesbyname = _fionames.get_index<"byname"_n>();
auto domainsbyname = _domains.get_index<"byname"_n>();
uint64_t bundleeligiblecountdown = 0;
uint128_t proxyHash = string_to_uint128_hash(proxyAddressObj.fioaddress.c_str());
uint128_t proxyDomainHash = string_to_uint128_hash(proxyAddressObj.fiodomain.c_str());
auto proxy_iter = namesbyname.find(proxyHash);
fio_400_assert(proxy_iter != namesbyname.end(), "proxy", proxy,
"FIO address not registered", ErrorFioNameNotRegistered);
uint64_t account = proxy_iter->owner_account;
auto votersbyowner = _voters.get_index<"byowner"_n>();
auto voter_proxy_iter = votersbyowner.find(account);
//the first opportunity to throw this error is when the owner account is not present
//in the table.
fio_400_assert(voter_proxy_iter != votersbyowner.end(), "fio_address", proxy,
"This address is not a proxy", AddressNotProxy);
//the second opportunity to throw this error is when the row is present and is not a proxy
fio_400_assert(voter_proxy_iter->is_proxy, "fio_address", proxy,
"This address is not a proxy", AddressNotProxy);
//check that the proxy name is not expired
uint32_t present_time = now();
fio_400_assert(present_time <= proxy_iter->expiration, "proxy", proxy,
"FIO Address expired", ErrorFioNameExpired);
auto domains_iter = domainsbyname.find(proxyDomainHash);
fio_400_assert(domains_iter != domainsbyname.end(), "proxy", proxy,
"FIO Address not registered", ErrorFioNameNotReg);
fio_400_assert(present_time <= get_time_plus_seconds( domains_iter->expiration, SECONDS30DAYS),
"proxy", proxy, "FIO Domain expired", ErrorDomainExpired);
if (!fio_address.empty()) {
uint128_t voterHash = string_to_uint128_hash(fioAddressObj.fioaddress.c_str());
uint128_t voterDomainHash = string_to_uint128_hash(fioAddressObj.fiodomain.c_str());
// compare fio_address owner and compare to actor
auto voter_iter = namesbyname.find(voterHash);
fio_403_assert(voter_iter->owner_account == actor.value, ErrorSignature);
fio_400_assert(voter_iter != namesbyname.end(), "fio_address", fio_address,
"FIO address not registered", ErrorFioNameNotRegistered);
fio_400_assert(present_time <= voter_iter->expiration, "fio_address", fio_address, "FIO Address expired",
ErrorDomainExpired);
auto voterdomain_iter = domainsbyname.find(voterDomainHash);
fio_400_assert(voterdomain_iter != domainsbyname.end(), "fio_address", fio_address,
"FIO Address not registered", ErrorFioNameNotReg);
fio_400_assert(present_time <= voterdomain_iter->expiration, "fio_address", fio_address, "FIO Domain expired",
ErrorDomainExpired);
bundleeligiblecountdown = voter_iter->bundleeligiblecountdown;
}
std::vector<name> producers{}; // Empty
voter_proxy_iter = votersbyowner.find(actor.value);
if (voter_proxy_iter == votersbyowner.end()) {
uint64_t id = _voters.available_primary_key();
_voters.emplace(actor, [&](auto &p) {
p.id = id;
p.owner = actor;
});
}
//note -- we can call these lock token computations like this
//only because token locks are exclusive, meaning an account CANNOT have
//multiple locked token grants.
eosio::token::computeremaininglockedtokens(actor,true);
eosio::token::computegenerallockedtokens(actor,true);
update_votes(actor, name{account}, producers, true);
uint128_t endpoint_hash = string_to_uint128_hash(VOTE_PROXY_ENDPOINT);
auto fees_by_endpoint = _fiofees.get_index<"byendpoint"_n>();
auto fee_iter = fees_by_endpoint.find(endpoint_hash);
uint64_t fee_amount = 0;
if (bundleeligiblecountdown > 0) {
action{
permission_level{_self, "active"_n},
AddressContract,
"decrcounter"_n,
make_tuple(fio_address, 1)
}.send();
} else {
fee_amount = fee_iter->suf_amount;
fio_400_assert(max_fee >= (int64_t) fee_amount, "max_fee", to_string(max_fee),
"Fee exceeds supplied maximum.",
ErrorMaxFeeExceeded);
fio_fees(actor, asset(fee_amount, FIOSYMBOL), VOTE_PROXY_ENDPOINT);
processrewardsnotpid(fee_amount, get_self());
//end new fees, logic for Mandatory fees.
}
const string response_string = string("{\"status\": \"OK\",\"fee_collected\":") +
to_string(fee_amount) + string("}");
if (VOTEPROXYRAM > 0) {
action(
permission_level{SYSTEMACCOUNT, "active"_n},
"eosio"_n,
"incram"_n,
std::make_tuple(actor, VOTEPROXYRAM)
).send();
}
fio_400_assert(transaction_size() <= MAX_TRX_SIZE, "transaction_size", std::to_string(transaction_size()),
"Transaction is too large", ErrorTransactionTooLarge);
send_response(response_string.c_str());
}
//this sets the inhibit_unlocking flag in the lockedtokens table.
// set to 0 is false, non zero is true.
void system_contract::inhibitunlck(const name &owner, const uint32_t &value){
require_auth(FOUNDATIONACCOUNT);
//get the owner, check that the specified grant is type 2, do the
//inhibit, do not do the inhibit otherwise.
auto lockiter = _lockedtokens.find(owner.value);
if(lockiter != _lockedtokens.end()){
if(lockiter->grant_type == 2) {
//update the locked table.
_lockedtokens.modify(lockiter, _self, [&](auto &av) {
av.inhibit_unlocking = value;
});
}
}
}
void system_contract::unlocktokens(const name &actor){
require_auth(TokenContract);
//note -- we can call these lock token computations like this
//only because token locks are exclusive, meaning an account CANNOT have
//multiple locked token grants.
eosio::token::computeremaininglockedtokens(actor,true);
eosio::token::computegenerallockedtokens(actor,true);
}
uint64_t system_contract::get_votable_balance(const name &tokenowner){
//get fio balance for this account,
uint32_t present_time = now();
const auto my_balance = eosio::token::get_balance("fio.token"_n,tokenowner, FIOSYMBOL.code() );
uint64_t amount = my_balance.amount;
//see if the user is in the lockedtokens table, if so recompute the balance
//based on grant type.
auto lockiter = _lockedtokens.find(tokenowner.value);
if(lockiter != _lockedtokens.end()){
check(amount >= lockiter->remaining_locked_amount,"votable balance lock amount is incoherent.");
//if lock type 1 always subtract remaining locked amount from balance
if (lockiter->grant_type == 1) {
double percent = 1.0 - (double)((double)lockiter->remaining_locked_amount / (double)lockiter->total_grant_amount);
if (percent <= .3){
double onethirdgrant = (double)lockiter->total_grant_amount * .3;
//amount is lesser of account amount and 1/3 of the total grant
double damount = (double)amount;
if (onethirdgrant <= damount){
amount = onethirdgrant;
}else{
amount = damount;
}
}else{
//amount is all the available tokens in the account.
return amount;
}
}
//TEST TEST TEST LOCKED TOKENS
//TEST TEST TEST LOCKED TOKENS uint32_t issueplus210 = lockiter->timestamp+(25*60);
//TEST TEST TEST LOCKED TOKENS
uint32_t issueplus210 = lockiter->timestamp+(210*SECONDSPERDAY);
//if lock type 2 only subtract remaining locked amount if 210 days since launch, and inhibit locking true.
if (((lockiter->grant_type == 2)&&((present_time > issueplus210)&&lockiter->inhibit_unlocking)) ||
(lockiter->grant_type == 4)
){
//subtract the lock amount from the balance
if (lockiter->remaining_locked_amount < amount) {
amount -= lockiter->remaining_locked_amount;
} else {
amount = 0;
}
}
}
return amount;
}
glockresult system_contract::get_general_votable_balance(const name &tokenowner){
glockresult res;
bool dbg = true;
//get fio balance for this account,
uint32_t present_time = now();
const auto my_balance = eosio::token::get_balance("fio.token"_n,tokenowner, FIOSYMBOL.code() );
uint64_t amount = my_balance.amount;
auto locks_by_owner = _generallockedtokens.get_index<"byowner"_n>();
auto lockiter = locks_by_owner.find(tokenowner.value);
if(lockiter != locks_by_owner.end()){
if (dbg) {
print("get_general_votable_balance found lock tokens for account ", tokenowner, "\n");
}
res.lockfound = true;
//if can vote --
if (lockiter->can_vote == 1){
if (dbg) {
print("get_general_votable_balance lock tokens can vote returning amount ", amount,"\n");
}
res.amount = amount;
}else{
if (amount > lockiter->remaining_lock_amount) {
if (dbg) {
print("get_general_votable_balance lock tokens cannot vote returning amount ", amount, " minus ",
lockiter->remaining_lock_amount, " \n");
}
res.amount = amount - lockiter->remaining_lock_amount;
}else{
if (dbg) {
print("get_general_votable_balance amount > remaining return 0 ", " \n");
}
res.amount = 0;
}
}
}
if (!res.lockfound){
if(dbg) {
print(" lock tokens not found return amount ", amount, " \n");
}
res.amount = amount;
}
return res;
}
void system_contract::update_votes(
const name &voter_name,
const name &proxy,
const std::vector <name> &producers,
const bool &voting) {
//validate input
if (proxy) {
check(producers.size() == 0, "cannot vote for producers and proxy at same time");
check(voter_name != proxy, "Invalid or duplicated producers0");
} else {
check(producers.size() <= 30, "attempt to vote for too many producers");
for (size_t i = 1; i < producers.size(); ++i) {
check(producers[i - 1] < producers[i], "producer votes must be unique and sorted");
}
}
auto votersbyowner = _voters.get_index<"byowner"_n>();
auto voter = votersbyowner.find(voter_name.value);
check(voter != votersbyowner.end(), "user must vote before votes can be updated");
check(!proxy || !voter->is_proxy, "account registered as a proxy is not allowed to use a proxy");
//change to get_unlocked_balance() Ed 11/25/2019
uint64_t amount = 0;
glockresult res = get_general_votable_balance(voter->owner);
if(res.lockfound){
amount = res.amount;
}else {
amount = get_votable_balance(voter->owner);
}
//on the first vote we update the total voted fio.
auto new_vote_weight = (double)amount;
if (voter->is_proxy) {
new_vote_weight += voter->proxied_vote_weight;
}
if( !(proxy) ) {
if( voter->last_vote_weight > 0.0 ) {
_gstate.total_voted_fio -= voter->last_vote_weight;
}
_gstate.total_voted_fio += new_vote_weight;
if( _gstate.total_voted_fio >= MINVOTEDFIO && _gstate.thresh_voted_fio_time == time_point() ) {
_gstate.thresh_voted_fio_time = current_time_point();
}
}
boost::container::flat_map <name, pair<double, bool /*new*/>> producer_deltas;
if (voter->last_vote_weight > 0) {
if (voter->proxy) {
auto old_proxy = votersbyowner.find(voter->proxy.value);
check(old_proxy != votersbyowner.end(), "old proxy not found"); //data corruption
votersbyowner.modify(old_proxy, same_payer, [&](auto &vp) {
vp.proxied_vote_weight -= voter->last_vote_weight;
});
propagate_weight_change(*old_proxy);
} else {
for (const auto &p : voter->producers) {
auto &d = producer_deltas[p.producer];
d.first -= voter->last_vote_weight;
d.second = false;
}
}