/
swiftnode-budget.cpp
2300 lines (1868 loc) · 85.2 KB
/
swiftnode-budget.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
// Copyright (c) 2014-2015 Dash developers
// Copyright (c) 2015-2018 PIVX developers
// Copyright (c) 2018-2020 SwiftCash developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h"
#include "main.h"
#include "activeswiftnode.h"
#include "addrman.h"
#include "swiftnode-budget.h"
#include "swiftnode-sync.h"
#include "swiftnode-helpers.h"
#include "swiftnodeconfig.h"
#include "swiftnode.h"
#include "swiftnodeman.h"
#include "util.h"
#include "wallet.h"
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
CBudgetManager budget;
CCriticalSection cs_budget;
std::map<uint256, int64_t> askedForSourceProposalOrBudget;
std::vector<CBudgetProposalBroadcast> vecImmatureBudgetProposals;
std::vector<CFinalizedBudgetBroadcast> vecImmatureFinalizedBudgets;
int nSubmittedFinalBudget;
int GetBudgetPaymentCycleBlocks()
{
// Amount of blocks in a month period of time (using 10 minutes per) = (6*24*30)
if (Params().NetworkID() == CBaseChainParams::MAIN) return 4320;
//for testing purposes - once a day
return 144;
}
bool IsBudgetCollateralValid(uint256 nTxCollateralHash, uint256 nExpectedHash, std::string& strError, int64_t& nTime, int& nConf, bool fBudgetFinalization)
{
CTransaction txCollateral;
uint256 nBlockHash;
if (!GetTransaction(nTxCollateralHash, txCollateral, nBlockHash, true)) {
strError = strprintf("Can't find collateral tx %s", txCollateral.ToString());
LogPrint("mnbudget","CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError);
return false;
}
if (txCollateral.vout.size() < 1) return false;
if (txCollateral.nLockTime != 0) return false;
CScript findScript;
findScript << OP_RETURN << ToByteVector(nExpectedHash);
bool foundOpReturn = false;
BOOST_FOREACH (const CTxOut o, txCollateral.vout) {
if (!o.scriptPubKey.IsNormalPaymentScript() && !o.scriptPubKey.IsUnspendable()) {
strError = strprintf("Invalid Script %s", txCollateral.ToString());
LogPrint("mnbudget","CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError);
return false;
}
CAmount trxRequiredFee = fBudgetFinalization ? BUDGET_FEE_TX : PROPOSAL_FEE_TX;
if (o.scriptPubKey == findScript && o.nValue >= trxRequiredFee) foundOpReturn = true;
}
if (!foundOpReturn) {
strError = strprintf("Couldn't find opReturn %s in %s", nExpectedHash.ToString(), txCollateral.ToString());
LogPrint("mnbudget","CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError);
return false;
}
// RETRIEVE CONFIRMATIONS AND NTIME
/*
- nTime starts as zero and is passed-by-reference out of this function and stored in the external proposal
- nTime is never validated via the hashing mechanism and comes from a full-validated source (the blockchain)
*/
int conf = GetIXConfirmations(nTxCollateralHash);
if (nBlockHash != uint256(0)) {
BlockMap::iterator mi = mapBlockIndex.find(nBlockHash);
if (mi != mapBlockIndex.end() && (*mi).second) {
CBlockIndex* pindex = (*mi).second;
if (chainActive.Contains(pindex)) {
conf += chainActive.Height() - pindex->nHeight + 1;
nTime = pindex->nTime;
}
}
}
nConf = conf;
//if we're syncing we won't have swiftTX information, so accept 1 confirmation
if (conf >= Params().Budget_Fee_Confirmations()) {
return true;
} else {
strError = strprintf("Collateral requires at least %d confirmations - %d confirmations", Params().Budget_Fee_Confirmations(), conf);
LogPrint("mnbudget","CBudgetProposalBroadcast::IsBudgetCollateralValid - %s - %d confirmations\n", strError, conf);
return false;
}
}
void CBudgetManager::CheckOrphanVotes()
{
LOCK(cs);
std::string strError = "";
std::map<uint256, CBudgetVote>::iterator it1 = mapOrphanSwiftnodeBudgetVotes.begin();
while (it1 != mapOrphanSwiftnodeBudgetVotes.end()) {
if (budget.UpdateProposal(((*it1).second), NULL, strError)) {
LogPrint("mnbudget","CBudgetManager::CheckOrphanVotes - Proposal/Budget is known, activating and removing orphan vote\n");
mapOrphanSwiftnodeBudgetVotes.erase(it1++);
} else {
++it1;
}
}
std::map<uint256, CFinalizedBudgetVote>::iterator it2 = mapOrphanFinalizedBudgetVotes.begin();
while (it2 != mapOrphanFinalizedBudgetVotes.end()) {
if (budget.UpdateFinalizedBudget(((*it2).second), NULL, strError)) {
LogPrint("mnbudget","CBudgetManager::CheckOrphanVotes - Proposal/Budget is known, activating and removing orphan vote\n");
mapOrphanFinalizedBudgetVotes.erase(it2++);
} else {
++it2;
}
}
LogPrint("mnbudget","CBudgetManager::CheckOrphanVotes - Done\n");
}
void CBudgetManager::SubmitFinalBudget()
{
static int nSubmittedHeight = 0; // height at which final budget was submitted last time
int nCurrentHeight;
{
TRY_LOCK(cs_main, locked);
if (!locked) return;
if (!chainActive.Tip()) return;
nCurrentHeight = chainActive.Height();
}
int nBlockStart = nCurrentHeight - nCurrentHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks();
if (nSubmittedHeight >= nBlockStart){
LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - nSubmittedHeight(=%ld) < nBlockStart(=%ld) condition not fulfilled.\n", nSubmittedHeight, nBlockStart);
return;
}
// Submit final budget during the last 2 days (288 blocks) before payment for Mainnet
int finalizationWindow = ((GetBudgetPaymentCycleBlocks() / 30) * 2);
if (Params().NetworkID() == CBaseChainParams::TESTNET) {
finalizationWindow = 64; // 56 + 4 finalization confirmations + 40 minutes buffer for propagation
}
int nFinalizationStart = nBlockStart - finalizationWindow;
int nOffsetToStart = nFinalizationStart - nCurrentHeight;
if (nBlockStart - nCurrentHeight > finalizationWindow) {
LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Too early for finalization. Current block is %ld, next Superblock is %ld.\n", nCurrentHeight, nBlockStart);
LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - First possible block for finalization: %ld. Last possible block for finalization: %ld. You have to wait for %ld block(s) until Budget finalization will be possible\n", nFinalizationStart, nBlockStart, nOffsetToStart);
return;
}
std::vector<CBudgetProposal*> vBudgetProposals = budget.GetBudget();
std::string strBudgetName = "main";
std::vector<CTxBudgetPayment> vecTxBudgetPayments;
for (unsigned int i = 0; i < vBudgetProposals.size(); i++) {
CTxBudgetPayment txBudgetPayment;
txBudgetPayment.nProposalHash = vBudgetProposals[i]->GetHash();
txBudgetPayment.payee = vBudgetProposals[i]->GetPayee();
txBudgetPayment.nAmount = vBudgetProposals[i]->GetAllotted();
vecTxBudgetPayments.push_back(txBudgetPayment);
}
if (vecTxBudgetPayments.size() < 1) {
LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Found No Proposals For Period\n");
return;
}
CFinalizedBudgetBroadcast tempBudget(strBudgetName, nBlockStart, vecTxBudgetPayments, 0);
if (mapSeenFinalizedBudgets.count(tempBudget.GetHash())) {
LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Budget already exists - %s\n", tempBudget.GetHash().ToString());
nSubmittedHeight = nCurrentHeight;
return; //already exists
}
//create fee tx
CTransaction tx;
uint256 txidCollateral;
if (!mapCollateralTxids.count(tempBudget.GetHash())) {
CWalletTx wtx;
if (!pwalletMain->GetBudgetSystemCollateralTX(wtx, tempBudget.GetHash(), false, false)) {
LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Can't make collateral transaction\n");
return;
}
// Get our change address
CReserveKey reservekey(pwalletMain);
// Send the tx to the network. Do NOT use SwiftTx, locking might need too much time to propagate, especially for testnet
pwalletMain->CommitTransaction(wtx, reservekey, "NO-ix");
tx = (CTransaction)wtx;
txidCollateral = tx.GetHash();
mapCollateralTxids.insert(make_pair(tempBudget.GetHash(), txidCollateral));
} else {
txidCollateral = mapCollateralTxids[tempBudget.GetHash()];
}
int conf = GetIXConfirmations(txidCollateral);
CTransaction txCollateral;
uint256 nBlockHash;
if (!GetTransaction(txidCollateral, txCollateral, nBlockHash, true)) {
LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Can't find collateral tx %s", txidCollateral.ToString());
return;
}
if (nBlockHash != uint256(0)) {
BlockMap::iterator mi = mapBlockIndex.find(nBlockHash);
if (mi != mapBlockIndex.end() && (*mi).second) {
CBlockIndex* pindex = (*mi).second;
if (chainActive.Contains(pindex)) {
conf += chainActive.Height() - pindex->nHeight + 1;
}
}
}
/*
Wait will we have 1 extra confirmation, otherwise some clients might reject this feeTX
-- This function is tied to NewBlock, so we will propagate this budget while the block is also propagating
*/
if (conf < Params().Budget_Fee_Confirmations() + 1) {
LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Collateral requires at least %d confirmations - %s - %d confirmations\n", Params().Budget_Fee_Confirmations() + 1, txidCollateral.ToString(), conf);
return;
}
//create the proposal incase we're the first to make it
CFinalizedBudgetBroadcast finalizedBudgetBroadcast(strBudgetName, nBlockStart, vecTxBudgetPayments, txidCollateral);
std::string strError = "";
if (!finalizedBudgetBroadcast.IsValid(strError)) {
LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Invalid finalized budget - %s \n", strError);
return;
}
LOCK(cs);
mapSeenFinalizedBudgets.insert(make_pair(finalizedBudgetBroadcast.GetHash(), finalizedBudgetBroadcast));
finalizedBudgetBroadcast.Relay();
budget.AddFinalizedBudget(finalizedBudgetBroadcast);
nSubmittedHeight = nCurrentHeight;
LogPrint("mnbudget","CBudgetManager::SubmitFinalBudget - Done! %s\n", finalizedBudgetBroadcast.GetHash().ToString());
}
//
// CBudgetDB
//
CBudgetDB::CBudgetDB()
{
pathDB = GetDataDir() / "budget.dat";
strMagicMessage = "SwiftnodeBudget";
}
bool CBudgetDB::Write(const CBudgetManager& objToSave)
{
LOCK(objToSave.cs);
int64_t nStart = GetTimeMillis();
// serialize, checksum data up to that point, then append checksum
CDataStream ssObj(SER_DISK, CLIENT_VERSION);
ssObj << strMagicMessage; // swiftnode cache file specific magic message
ssObj << FLATDATA(Params().MessageStart()); // network specific magic number
ssObj << objToSave;
uint256 hash = Hash(ssObj.begin(), ssObj.end());
ssObj << hash;
// open output file, and associate with CAutoFile
FILE* file = fopen(pathDB.string().c_str(), "wb");
CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("%s : Failed to open file %s", __func__, pathDB.string());
// Write and commit header, data
try {
fileout << ssObj;
} catch (std::exception& e) {
return error("%s : Serialize or I/O error - %s", __func__, e.what());
}
fileout.fclose();
LogPrint("mnbudget","Written info to budget.dat %dms\n", GetTimeMillis() - nStart);
return true;
}
CBudgetDB::ReadResult CBudgetDB::Read(CBudgetManager& objToLoad, bool fDryRun)
{
LOCK(objToLoad.cs);
int64_t nStart = GetTimeMillis();
// open input file, and associate with CAutoFile
FILE* file = fopen(pathDB.string().c_str(), "rb");
CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
if (filein.IsNull()) {
error("%s : Failed to open file %s", __func__, pathDB.string());
return FileError;
}
// use file size to size memory buffer
int fileSize = boost::filesystem::file_size(pathDB);
int dataSize = fileSize - sizeof(uint256);
// Don't try to resize to a negative number if file is small
if (dataSize < 0)
dataSize = 0;
vector<unsigned char> vchData;
vchData.resize(dataSize);
uint256 hashIn;
// read data and checksum from file
try {
filein.read((char*)&vchData[0], dataSize);
filein >> hashIn;
} catch (std::exception& e) {
error("%s : Deserialize or I/O error - %s", __func__, e.what());
return HashReadError;
}
filein.fclose();
CDataStream ssObj(vchData, SER_DISK, CLIENT_VERSION);
// verify stored checksum matches input data
uint256 hashTmp = Hash(ssObj.begin(), ssObj.end());
if (hashIn != hashTmp) {
error("%s : Checksum mismatch, data corrupted", __func__);
return IncorrectHash;
}
unsigned char pchMsgTmp[4];
std::string strMagicMessageTmp;
try {
// de-serialize file header (swiftnode cache file specific magic message) and ..
ssObj >> strMagicMessageTmp;
// ... verify the message matches predefined one
if (strMagicMessage != strMagicMessageTmp) {
error("%s : Invalid swiftnode cache magic message", __func__);
return IncorrectMagicMessage;
}
// de-serialize file header (network specific magic number) and ..
ssObj >> FLATDATA(pchMsgTmp);
// ... verify the network matches ours
if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) {
error("%s : Invalid network magic number", __func__);
return IncorrectMagicNumber;
}
// de-serialize data into CBudgetManager object
ssObj >> objToLoad;
} catch (std::exception& e) {
objToLoad.Clear();
error("%s : Deserialize or I/O error - %s", __func__, e.what());
return IncorrectFormat;
}
LogPrint("mnbudget","Loaded info from budget.dat %dms\n", GetTimeMillis() - nStart);
LogPrint("mnbudget"," %s\n", objToLoad.ToString());
if (!fDryRun) {
LogPrint("mnbudget","Budget manager - cleaning....\n");
objToLoad.CheckAndRemove();
LogPrint("mnbudget","Budget manager - result:\n");
LogPrint("mnbudget"," %s\n", objToLoad.ToString());
}
return Ok;
}
void DumpBudgets()
{
int64_t nStart = GetTimeMillis();
CBudgetDB budgetdb;
CBudgetManager tempBudget;
LogPrint("mnbudget","Verifying budget.dat format...\n");
CBudgetDB::ReadResult readResult = budgetdb.Read(tempBudget, true);
// there was an error and it was not an error on file opening => do not proceed
if (readResult == CBudgetDB::FileError)
LogPrint("mnbudget","Missing budgets file - budget.dat, will try to recreate\n");
else if (readResult != CBudgetDB::Ok) {
LogPrint("mnbudget","Error reading budget.dat: ");
if (readResult == CBudgetDB::IncorrectFormat)
LogPrint("mnbudget","magic is ok but data has invalid format, will try to recreate\n");
else {
LogPrint("mnbudget","file format is unknown or invalid, please fix it manually\n");
return;
}
}
LogPrint("mnbudget","Writting info to budget.dat...\n");
budgetdb.Write(budget);
LogPrint("mnbudget","Budget dump finished %dms\n", GetTimeMillis() - nStart);
}
bool CBudgetManager::AddFinalizedBudget(CFinalizedBudget& finalizedBudget)
{
std::string strError = "";
if (!finalizedBudget.IsValid(strError)) return false;
if (mapFinalizedBudgets.count(finalizedBudget.GetHash())) {
return false;
}
mapFinalizedBudgets.insert(make_pair(finalizedBudget.GetHash(), finalizedBudget));
return true;
}
bool CBudgetManager::AddProposal(CBudgetProposal& budgetProposal)
{
LOCK(cs);
std::string strError = "";
if (!budgetProposal.IsValid(strError)) {
LogPrint("mnbudget","CBudgetManager::AddProposal - invalid budget proposal - %s\n", strError);
return false;
}
if (mapProposals.count(budgetProposal.GetHash())) {
return false;
}
mapProposals.insert(make_pair(budgetProposal.GetHash(), budgetProposal));
LogPrint("mnbudget","CBudgetManager::AddProposal - proposal %s added\n", budgetProposal.GetName ().c_str ());
return true;
}
void CBudgetManager::CheckAndRemove()
{
int nHeight = 0;
// Add some verbosity once loading blocks from files has finished
{
TRY_LOCK(cs_main, locked);
if ((locked) && (chainActive.Tip() != NULL)) {
CBlockIndex* pindexPrev = chainActive.Tip();
if (pindexPrev) {
nHeight = pindexPrev->nHeight;
}
}
}
LogPrint("mnbudget", "CBudgetManager::CheckAndRemove at Height=%d\n", nHeight);
map<uint256, CFinalizedBudget> tmpMapFinalizedBudgets;
map<uint256, CBudgetProposal> tmpMapProposals;
std::string strError = "";
LogPrint("mnbudget", "CBudgetManager::CheckAndRemove - mapFinalizedBudgets cleanup - size before: %d\n", mapFinalizedBudgets.size());
std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin();
while (it != mapFinalizedBudgets.end()) {
CFinalizedBudget* pfinalizedBudget = &((*it).second);
pfinalizedBudget->fValid = pfinalizedBudget->IsValid(strError);
if (!strError.empty ()) {
LogPrint("mnbudget","CBudgetManager::CheckAndRemove - Invalid finalized budget: %s\n", strError);
}
else {
LogPrint("mnbudget","CBudgetManager::CheckAndRemove - Found valid finalized budget: %s %s\n",
pfinalizedBudget->strBudgetName.c_str(), pfinalizedBudget->nFeeTXHash.ToString().c_str());
}
if (pfinalizedBudget->fValid) {
pfinalizedBudget->AutoCheck();
tmpMapFinalizedBudgets.insert(make_pair(pfinalizedBudget->GetHash(), *pfinalizedBudget));
}
++it;
}
LogPrint("mnbudget", "CBudgetManager::CheckAndRemove - mapProposals cleanup - size before: %d\n", mapProposals.size());
std::map<uint256, CBudgetProposal>::iterator it2 = mapProposals.begin();
while (it2 != mapProposals.end()) {
CBudgetProposal* pbudgetProposal = &((*it2).second);
pbudgetProposal->fValid = pbudgetProposal->IsValid(strError);
if (!strError.empty ()) {
LogPrint("mnbudget","CBudgetManager::CheckAndRemove - Invalid budget proposal - %s\n", strError);
strError = "";
}
else {
LogPrint("mnbudget","CBudgetManager::CheckAndRemove - Found valid budget proposal: %s %s\n",
pbudgetProposal->strProposalName.c_str(), pbudgetProposal->nFeeTXHash.ToString().c_str());
}
if (pbudgetProposal->fValid) {
tmpMapProposals.insert(make_pair(pbudgetProposal->GetHash(), *pbudgetProposal));
}
++it2;
}
// Remove invalid entries by overwriting complete map
mapFinalizedBudgets.swap(tmpMapFinalizedBudgets);
mapProposals.swap(tmpMapProposals);
// clang doesn't accept copy assignemnts :-/
// mapFinalizedBudgets = tmpMapFinalizedBudgets;
// mapProposals = tmpMapProposals;
LogPrint("mnbudget", "CBudgetManager::CheckAndRemove - mapFinalizedBudgets cleanup - size after: %d\n", mapFinalizedBudgets.size());
LogPrint("mnbudget", "CBudgetManager::CheckAndRemove - mapProposals cleanup - size after: %d\n", mapProposals.size());
LogPrint("mnbudget","CBudgetManager::CheckAndRemove - PASSED\n");
}
void CBudgetManager::FillBlockPayee(CMutableTransaction& txNew, CAmount nFees, bool fProofOfStake)
{
LOCK(cs);
CBlockIndex* pindexPrev = chainActive.Tip();
if (!pindexPrev) return;
int nHighestCount = 0;
CScript payee;
CAmount nAmount = 0;
// ------- Grab The Highest Count
std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin();
while (it != mapFinalizedBudgets.end()) {
CFinalizedBudget* pfinalizedBudget = &((*it).second);
if (pfinalizedBudget->GetVoteCount() > nHighestCount &&
pindexPrev->nHeight + 1 >= pfinalizedBudget->GetBlockStart() &&
pindexPrev->nHeight + 1 <= pfinalizedBudget->GetBlockEnd() &&
pfinalizedBudget->GetPayeeAndAmount(pindexPrev->nHeight + 1, payee, nAmount)) {
nHighestCount = pfinalizedBudget->GetVoteCount();
}
++it;
}
CAmount blockValue = GetBlockValue(pindexPrev->nHeight);
if (fProofOfStake) {
if (nHighestCount > 0) {
unsigned int i = txNew.vout.size();
txNew.vout.resize(i + 1);
txNew.vout[i].scriptPubKey = payee;
txNew.vout[i].nValue = nAmount;
CTxDestination address1;
ExtractDestination(payee, address1);
CBitcoinAddress address2(address1);
LogPrint("mnbudget","CBudgetManager::FillBlockPayee - Budget payment to %s for %lld, nHighestCount = %d\n", address2.ToString(), nAmount, nHighestCount);
}
else {
LogPrint("mnbudget","CBudgetManager::FillBlockPayee - No Budget payment, nHighestCount = %d\n", nHighestCount);
}
} else {
//miners get the full amount on these blocks
txNew.vout[0].nValue = blockValue;
if (nHighestCount > 0) {
txNew.vout.resize(2);
//these are super blocks, so their value can be much larger than normal
txNew.vout[1].scriptPubKey = payee;
txNew.vout[1].nValue = nAmount;
CTxDestination address1;
ExtractDestination(payee, address1);
CBitcoinAddress address2(address1);
LogPrint("mnbudget","CBudgetManager::FillBlockPayee - Budget payment to %s for %lld\n", address2.ToString(), nAmount);
}
}
}
CFinalizedBudget* CBudgetManager::FindFinalizedBudget(uint256 nHash)
{
if (mapFinalizedBudgets.count(nHash))
return &mapFinalizedBudgets[nHash];
return NULL;
}
CBudgetProposal* CBudgetManager::FindProposal(const std::string& strProposalName)
{
//find the prop with the highest yes count
int nYesCount = -99999;
CBudgetProposal* pbudgetProposal = NULL;
std::map<uint256, CBudgetProposal>::iterator it = mapProposals.begin();
while (it != mapProposals.end()) {
if ((*it).second.strProposalName == strProposalName && (*it).second.GetYeas() > nYesCount) {
pbudgetProposal = &((*it).second);
nYesCount = pbudgetProposal->GetYeas();
}
++it;
}
if (nYesCount == -99999) return NULL;
return pbudgetProposal;
}
CBudgetProposal* CBudgetManager::FindProposal(uint256 nHash)
{
LOCK(cs);
if (mapProposals.count(nHash))
return &mapProposals[nHash];
return NULL;
}
bool CBudgetManager::IsBudgetPaymentBlock(int nBlockHeight)
{
int nHighestCount = -1;
int nFivePercent = mnodeman.CountEnabled(ActiveProtocol()) / 20;
std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin();
while (it != mapFinalizedBudgets.end()) {
CFinalizedBudget* pfinalizedBudget = &((*it).second);
if (pfinalizedBudget->GetVoteCount() > nHighestCount &&
nBlockHeight >= pfinalizedBudget->GetBlockStart() &&
nBlockHeight <= pfinalizedBudget->GetBlockEnd()) {
nHighestCount = pfinalizedBudget->GetVoteCount();
}
++it;
}
LogPrint("mnbudget","CBudgetManager::IsBudgetPaymentBlock() - nHighestCount: %lli, 5%% of Swiftnodes: %lli. Number of finalized budgets: %lli\n",
nHighestCount, nFivePercent, mapFinalizedBudgets.size());
// If budget doesn't have 5% of the network votes, then we should pay a swiftnode instead
if (nHighestCount > nFivePercent) return true;
return false;
}
TrxValidationStatus CBudgetManager::IsTransactionValid(const CTransaction& txNew, int nBlockHeight, CAmount& nBudgetPaid)
{
LOCK(cs);
TrxValidationStatus transactionStatus = TrxValidationStatus::InValid;
int nHighestCount = 0;
int nFivePercent = mnodeman.CountEnabled(ActiveProtocol()) / 20;
std::vector<CFinalizedBudget*> ret;
LogPrint("mnbudget","CBudgetManager::IsTransactionValid - checking %lli finalized budgets\n", mapFinalizedBudgets.size());
// ------- Grab The Highest Count
std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin();
while (it != mapFinalizedBudgets.end()) {
CFinalizedBudget* pfinalizedBudget = &((*it).second);
if (pfinalizedBudget->GetVoteCount() > nHighestCount &&
nBlockHeight >= pfinalizedBudget->GetBlockStart() &&
nBlockHeight <= pfinalizedBudget->GetBlockEnd()) {
nHighestCount = pfinalizedBudget->GetVoteCount();
}
++it;
}
LogPrint("mnbudget","CBudgetManager::IsTransactionValid() - nHighestCount: %lli, 5%% of Swiftnodes: %lli mapFinalizedBudgets.size(): %ld\n",
nHighestCount, nFivePercent, mapFinalizedBudgets.size());
/*
If budget doesn't have 5% of the network votes, then we should pay a swiftnode instead
*/
if (nHighestCount < nFivePercent) return TrxValidationStatus::InValid;
// check the highest finalized budgets (+/- 10% to assist in consensus)
std::string strProposals = "";
int nCountThreshold = nHighestCount - mnodeman.CountEnabled(ActiveProtocol()) / 10;
bool fThreshold = false;
it = mapFinalizedBudgets.begin();
while (it != mapFinalizedBudgets.end()) {
CFinalizedBudget* pfinalizedBudget = &((*it).second);
strProposals = pfinalizedBudget->GetProposals();
LogPrint("mnbudget","CBudgetManager::IsTransactionValid - checking budget (%s) with blockstart %lli, blockend %lli, nBlockHeight %lli, votes %lli, nCountThreshold %lli\n",
strProposals.c_str(), pfinalizedBudget->GetBlockStart(), pfinalizedBudget->GetBlockEnd(),
nBlockHeight, pfinalizedBudget->GetVoteCount(), nCountThreshold);
if (pfinalizedBudget->GetVoteCount() >= nCountThreshold) {
fThreshold = true;
LogPrint("mnbudget","CBudgetManager::IsTransactionValid - GetVoteCount() > nCountThreshold passed\n");
if (nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()) {
LogPrint("mnbudget","CBudgetManager::IsTransactionValid - GetBlockStart() passed\n");
transactionStatus = pfinalizedBudget->IsTransactionValid(txNew, nBlockHeight, nBudgetPaid);
if (transactionStatus == TrxValidationStatus::Valid) {
LogPrint("mnbudget","CBudgetManager::IsTransactionValid - pfinalizedBudget->IsTransactionValid() passed\n");
return TrxValidationStatus::Valid;
} else {
LogPrint("mnbudget","CBudgetManager::IsTransactionValid - pfinalizedBudget->IsTransactionValid() error\n");
}
} else {
LogPrint("mnbudget","CBudgetManager::IsTransactionValid - GetBlockStart() failed, budget is outside current payment cycle and will be ignored.\n");
}
}
++it;
}
// If not enough swiftnodes autovoted for any of the finalized budgets pay a swiftnode instead
if(!fThreshold) {
transactionStatus = TrxValidationStatus::VoteThreshold;
}
// We looked through all of the known budgets
return transactionStatus;
}
std::vector<CBudgetProposal*> CBudgetManager::GetAllProposals()
{
LOCK(cs);
std::vector<CBudgetProposal*> vBudgetProposalRet;
std::map<uint256, CBudgetProposal>::iterator it = mapProposals.begin();
while (it != mapProposals.end()) {
(*it).second.CleanAndRemove(false);
CBudgetProposal* pbudgetProposal = &((*it).second);
vBudgetProposalRet.push_back(pbudgetProposal);
++it;
}
return vBudgetProposalRet;
}
//
// Sort by votes, if there's a tie sort by their feeHash TX
//
struct sortProposalsByVotes {
bool operator()(const std::pair<CBudgetProposal*, int>& left, const std::pair<CBudgetProposal*, int>& right)
{
if (left.second != right.second)
return (left.second > right.second);
return (left.first->nFeeTXHash > right.first->nFeeTXHash);
}
};
//Need to review this function
std::vector<CBudgetProposal*> CBudgetManager::GetBudget()
{
LOCK(cs);
// ------- Sort budgets by Yes Count
std::vector<std::pair<CBudgetProposal*, int> > vBudgetPorposalsSort;
std::map<uint256, CBudgetProposal>::iterator it = mapProposals.begin();
while (it != mapProposals.end()) {
(*it).second.CleanAndRemove(false);
vBudgetPorposalsSort.push_back(make_pair(&((*it).second), (*it).second.GetYeas() - (*it).second.GetNays()));
++it;
}
std::sort(vBudgetPorposalsSort.begin(), vBudgetPorposalsSort.end(), sortProposalsByVotes());
std::vector<CBudgetProposal*> vBudgetProposalsRet;
CAmount nBudgetAllocated = 0;
CBlockIndex* pindexPrev = chainActive.Tip();
if (pindexPrev == NULL) return vBudgetProposalsRet;
// Grab The Highest Count
int nHighestCount = 0;
int nBlockHeight = pindexPrev->nHeight + 1;
std::map<uint256, CBudgetProposal>::iterator it1 = mapProposals.begin();
while (it1 != mapProposals.end()) {
CBudgetProposal* pBudgetProposal = &((*it1).second);
if (nHighestCount < pBudgetProposal->GetVoteCount() &&
nBlockHeight >= pBudgetProposal->GetBlockStart() &&
nBlockHeight <= pBudgetProposal->GetBlockEnd()) {
nHighestCount = pBudgetProposal->GetVoteCount();
}
++it1;
}
// ------- Grab The Budgets In Order
int nBlockStart = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks();
int nBlockEnd = nBlockStart + GetBudgetPaymentCycleBlocks() - 1;
CAmount nTotalBudget = GetTotalBudget(nBlockStart);
std::vector<std::pair<CBudgetProposal*, int> >::iterator it2 = vBudgetPorposalsSort.begin();
while (it2 != vBudgetPorposalsSort.end()) {
CBudgetProposal* pbudgetProposal = (*it2).first;
LogPrint("mnbudget","CBudgetManager::GetBudget() - Processing Budget %s\n", pbudgetProposal->strProposalName.c_str());
//prop start/end should be inside this period
if (pbudgetProposal->fValid && pbudgetProposal->nBlockStart <= nBlockStart &&
pbudgetProposal->nBlockEnd >= nBlockEnd &&
pbudgetProposal->GetYeas() - pbudgetProposal->GetNays() >= mnodeman.CountEnabled(ActiveProtocol()) / 10 &&
pbudgetProposal->IsEstablished()) {
LogPrint("mnbudget","CBudgetManager::GetBudget() - Check 1 passed: valid=%d | %ld <= %ld | %ld >= %ld | Yeas=%d Nays=%d Count=%d | established=%d\n",
pbudgetProposal->fValid, pbudgetProposal->nBlockStart, nBlockStart, pbudgetProposal->nBlockEnd,
nBlockEnd, pbudgetProposal->GetYeas(), pbudgetProposal->GetNays(), mnodeman.CountEnabled(ActiveProtocol()) / 10,
pbudgetProposal->IsEstablished());
if (pbudgetProposal->GetAmount() + nBudgetAllocated <= nTotalBudget) {
pbudgetProposal->SetAllotted(pbudgetProposal->GetAmount());
nBudgetAllocated += pbudgetProposal->GetAmount();
vBudgetProposalsRet.push_back(pbudgetProposal);
LogPrint("mnbudget","CBudgetManager::GetBudget() - Check 2 passed: Budget added\n");
} else {
pbudgetProposal->SetAllotted(0);
LogPrint("mnbudget","CBudgetManager::GetBudget() - Check 2 failed: no amount allotted\n");
}
}
else {
LogPrint("mnbudget","CBudgetManager::GetBudget() - Check 1 failed: valid=%d | %ld <= %ld | %ld >= %ld | Yeas=%d Nays=%d Count=%d | established=%d\n",
pbudgetProposal->fValid, pbudgetProposal->nBlockStart, nBlockStart, pbudgetProposal->nBlockEnd,
nBlockEnd, pbudgetProposal->GetYeas(), pbudgetProposal->GetNays(), mnodeman.CountEnabled(ActiveProtocol()) / 10,
pbudgetProposal->IsEstablished());
}
++it2;
}
return vBudgetProposalsRet;
}
// Sort by votes, if there's a tie sort by their feeHash TX
struct sortFinalizedBudgetsByVotes {
bool operator()(const std::pair<CFinalizedBudget*, int>& left, const std::pair<CFinalizedBudget*, int>& right)
{
if (left.second != right.second)
return left.second > right.second;
return (left.first->nFeeTXHash > right.first->nFeeTXHash);
}
};
std::vector<CFinalizedBudget*> CBudgetManager::GetFinalizedBudgets()
{
LOCK(cs);
std::vector<CFinalizedBudget*> vFinalizedBudgetsRet;
std::vector<std::pair<CFinalizedBudget*, int> > vFinalizedBudgetsSort;
// ------- Grab The Budgets In Order
std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin();
while (it != mapFinalizedBudgets.end()) {
CFinalizedBudget* pfinalizedBudget = &((*it).second);
vFinalizedBudgetsSort.push_back(make_pair(pfinalizedBudget, pfinalizedBudget->GetVoteCount()));
++it;
}
std::sort(vFinalizedBudgetsSort.begin(), vFinalizedBudgetsSort.end(), sortFinalizedBudgetsByVotes());
std::vector<std::pair<CFinalizedBudget*, int> >::iterator it2 = vFinalizedBudgetsSort.begin();
while (it2 != vFinalizedBudgetsSort.end()) {
vFinalizedBudgetsRet.push_back((*it2).first);
++it2;
}
return vFinalizedBudgetsRet;
}
std::string CBudgetManager::GetRequiredPaymentsString(int nBlockHeight)
{
LOCK(cs);
std::string ret = "unknown-budget";
std::map<uint256, CFinalizedBudget>::iterator it = mapFinalizedBudgets.begin();
while (it != mapFinalizedBudgets.end()) {
CFinalizedBudget* pfinalizedBudget = &((*it).second);
if (nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()) {
CTxBudgetPayment payment;
if (pfinalizedBudget->GetBudgetPaymentByBlock(nBlockHeight, payment)) {
if (ret == "unknown-budget") {
ret = payment.nProposalHash.ToString();
} else {
ret += ",";
ret += payment.nProposalHash.ToString();
}
} else {
LogPrint("mnbudget","CBudgetManager::GetRequiredPaymentsString - Couldn't find budget payment for block %d\n", nBlockHeight);
}
}
++it;
}
return ret;
}
CAmount CBudgetManager::GetTotalBudget(int nHeight)
{
if (chainActive.Tip() == NULL) return 0;
if (Params().NetworkID() == CBaseChainParams::TESTNET) {
if(nHeight < Params().LAST_POW_BLOCK()) return 144 * 35000 * COIN; // constant rewards
else if (nHeight < 800) return 144 * ((double)nHeight/100) * 1000 * COIN; // increasing rewards
else return 144 * ( (double)(4*200 * 52560)/(4*52560 + nHeight + 58300 - 800) ) * COIN; // decreasing rewards
}
//No budget during the pow phase
if (nHeight <= Params().LAST_POW_BLOCK())
return 0;
//Get block value and calculate from that
CAmount nSubsidy = 0;
if (nHeight < 2000) {
nSubsidy = 5 * COIN; // fair launch - give appx 1 week to users to set up their wallets and nodes
} else {
// Add 53.8K to nHeight for v3.0 HF/RESET
nSubsidy = ( (double)(4*200 * 52560)/(4*52560 + nHeight + 58300 - 2000) ) * COIN; // 10% 0f actual subsidy planned
}
// This part is planning ahead for 150+ years
if (nSubsidy < 3 * COIN)
nSubsidy = 5; // At one point we should burn enough fees to leave about 5 SWIFT per block for proposals
// Check if we reached the coin max supply.
int64_t nMoneySupply = chainActive.Tip()->nMoneySupply;
if (nMoneySupply + nSubsidy >= Params().MaxMoneyOut())
nSubsidy = Params().MaxMoneyOut() - nMoneySupply;
if (nMoneySupply >= Params().MaxMoneyOut())
nSubsidy = 0;
// Amount of blocks in a month period of time (using 10 minutes block time) = (6*24*30)
return nSubsidy * 144 * 30;
}
void CBudgetManager::NewBlock()
{
TRY_LOCK(cs, fBudgetNewBlock);
if (!fBudgetNewBlock) return;
if (swiftnodeSync.RequestedSwiftnodeAssets <= SWIFTNODE_SYNC_BUDGET) return;
if (strBudgetMode == "suggest") { //suggest the budget we see
SubmitFinalBudget();
}
//this function should be called 1/14 blocks, allowing up to 100 votes per day on all proposals
if (chainActive.Height() % 14 != 0) return;
// incremental sync with our peers
if (swiftnodeSync.IsSynced()) {
LogPrint("mnbudget","CBudgetManager::NewBlock - incremental sync started\n");
if (chainActive.Height() % 144 == rand() % 144) {
ClearSeen();
ResetSync();
}
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes)
if (pnode->nVersion >= ActiveProtocol())
Sync(pnode, 0, true);
MarkSynced();
}
CheckAndRemove();
//remove invalid votes once in a while (we have to check the signatures and validity of every vote, somewhat CPU intensive)
LogPrint("mnbudget","CBudgetManager::NewBlock - askedForSourceProposalOrBudget cleanup - size: %d\n", askedForSourceProposalOrBudget.size());
std::map<uint256, int64_t>::iterator it = askedForSourceProposalOrBudget.begin();
while (it != askedForSourceProposalOrBudget.end()) {
if ((*it).second > GetTime() - (60 * 60 * 24)) {
++it;
} else {
askedForSourceProposalOrBudget.erase(it++);
}
}
LogPrint("mnbudget","CBudgetManager::NewBlock - mapProposals cleanup - size: %d\n", mapProposals.size());
std::map<uint256, CBudgetProposal>::iterator it2 = mapProposals.begin();
while (it2 != mapProposals.end()) {
(*it2).second.CleanAndRemove(false);
++it2;
}
LogPrint("mnbudget","CBudgetManager::NewBlock - mapFinalizedBudgets cleanup - size: %d\n", mapFinalizedBudgets.size());
std::map<uint256, CFinalizedBudget>::iterator it3 = mapFinalizedBudgets.begin();