forked from bitcoin/bitcoin
/
masternode-budget.cpp
2045 lines (1637 loc) · 68.6 KB
/
masternode-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 The Dash developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "init.h"
#include "masternode-budget.h"
#include "masternode.h"
#include "darksend.h"
#include "masternodeman.h"
#include "masternode-sync.h"
#include "util.h"
#include "addrman.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 GetBudgetPaymentCycleBlocks(){
// Amount of blocks in a months period of time (using 2.6 minutes per) = (60*24*30)/2.6
if(Params().NetworkID() == CBaseChainParams::MAIN) return 16616;
//for testing purposes
return 50; //ten times per day
}
bool IsBudgetCollateralValid(uint256 nTxCollateralHash, uint256 nExpectedHash, std::string& strError, int64_t& nTime, int& nConf)
{
CTransaction txCollateral;
uint256 nBlockHash;
if(!GetTransaction(nTxCollateralHash, txCollateral, nBlockHash, true)){
strError = strprintf("Can't find collateral tx %s", txCollateral.ToString());
LogPrintf ("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());
LogPrintf ("CBudgetProposalBroadcast::IsBudgetCollateralValid - %s\n", strError);
return false;
}
if(o.scriptPubKey == findScript && o.nValue >= BUDGET_FEE_TX) foundOpReturn = true;
}
if(!foundOpReturn){
strError = strprintf("Couldn't find opReturn %s in %s", nExpectedHash.ToString(), txCollateral.ToString());
LogPrintf ("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 instantX information, so accept 1 confirmation
if(conf >= BUDGET_FEE_CONFIRMATIONS){
return true;
} else {
strError = strprintf("Collateral requires at least %d confirmations - %d confirmations", BUDGET_FEE_CONFIRMATIONS, conf);
LogPrintf ("CBudgetProposalBroadcast::IsBudgetCollateralValid - %s - %d confirmations\n", strError, conf);
return false;
}
}
void CBudgetManager::CheckOrphanVotes()
{
LOCK(cs);
std::string strError = "";
std::map<uint256, CBudgetVote>::iterator it1 = mapOrphanMasternodeBudgetVotes.begin();
while(it1 != mapOrphanMasternodeBudgetVotes.end()){
if(budget.UpdateProposal(((*it1).second), NULL, strError)){
LogPrintf("CBudgetManager::CheckOrphanVotes - Proposal/Budget is known, activating and removing orphan vote\n");
mapOrphanMasternodeBudgetVotes.erase(it1++);
} else {
++it1;
}
}
std::map<uint256, CFinalizedBudgetVote>::iterator it2 = mapOrphanFinalizedBudgetVotes.begin();
while(it2 != mapOrphanFinalizedBudgetVotes.end()){
if(budget.UpdateFinalizedBudget(((*it2).second),NULL, strError)){
LogPrintf("CBudgetManager::CheckOrphanVotes - Proposal/Budget is known, activating and removing orphan vote\n");
mapOrphanFinalizedBudgetVotes.erase(it2++);
} else {
++it2;
}
}
}
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) return;
if(nBlockStart - nCurrentHeight > 576*2) return; // allow submitting final budget only when 2 days left before payments
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) {
LogPrintf("CBudgetManager::SubmitFinalBudget - Found No Proposals For Period\n");
return;
}
CFinalizedBudgetBroadcast tempBudget(strBudgetName, nBlockStart, vecTxBudgetPayments, 0);
if(mapSeenFinalizedBudgets.count(tempBudget.GetHash())) {
LogPrintf("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)){
LogPrintf("CBudgetManager::SubmitFinalBudget - Can't make collateral transaction\n");
return;
}
// make our change address
CReserveKey reservekey(pwalletMain);
//send the tx to the network
pwalletMain->CommitTransaction(wtx, reservekey, "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)) {
LogPrintf ("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 < BUDGET_FEE_CONFIRMATIONS+1){
LogPrintf ("CBudgetManager::SubmitFinalBudget - Collateral requires at least %d confirmations - %s - %d confirmations\n", 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)){
LogPrintf("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;
LogPrintf("CBudgetManager::SubmitFinalBudget - Done! %s\n", finalizedBudgetBroadcast.GetHash().ToString());
}
//
// CBudgetDB
//
CBudgetDB::CBudgetDB()
{
pathDB = GetDataDir() / "budget.dat";
strMagicMessage = "MasternodeBudget";
}
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; // masternode 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();
LogPrintf("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 (masternode cache file specific magic message) and ..
ssObj >> strMagicMessageTmp;
// ... verify the message matches predefined one
if (strMagicMessage != strMagicMessageTmp)
{
error("%s : Invalid masternode 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;
}
LogPrintf("Loaded info from budget.dat %dms\n", GetTimeMillis() - nStart);
LogPrintf(" %s\n", objToLoad.ToString());
if(!fDryRun) {
LogPrintf("Budget manager - cleaning....\n");
objToLoad.CheckAndRemove();
LogPrintf("Budget manager - result:\n");
LogPrintf(" %s\n", objToLoad.ToString());
}
return Ok;
}
void DumpBudgets()
{
int64_t nStart = GetTimeMillis();
CBudgetDB budgetdb;
CBudgetManager tempBudget;
LogPrintf("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)
LogPrintf("Missing budgets file - budget.dat, will try to recreate\n");
else if (readResult != CBudgetDB::Ok)
{
LogPrintf("Error reading budget.dat: ");
if(readResult == CBudgetDB::IncorrectFormat)
LogPrintf("magic is ok but data has invalid format, will try to recreate\n");
else
{
LogPrintf("file format is unknown or invalid, please fix it manually\n");
return;
}
}
LogPrintf("Writting info to budget.dat...\n");
budgetdb.Write(budget);
LogPrintf("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)) {
LogPrintf("CBudgetManager::AddProposal - invalid budget proposal - %s\n", strError);
return false;
}
if(mapProposals.count(budgetProposal.GetHash())) {
return false;
}
mapProposals.insert(make_pair(budgetProposal.GetHash(), budgetProposal));
return true;
}
void CBudgetManager::CheckAndRemove()
{
LogPrintf("CBudgetManager::CheckAndRemove\n");
std::string strError = "";
LogPrintf("CBudgetManager::CheckAndRemove - mapFinalizedBudgets cleanup - size: %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);
LogPrintf("CBudgetManager::CheckAndRemove - pfinalizedBudget->IsValid - strError: %s\n", strError);
if(pfinalizedBudget->fValid) {
pfinalizedBudget->AutoCheck();
}
++it;
}
LogPrintf("CBudgetManager::CheckAndRemove - mapProposals cleanup - size: %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);
++it2;
}
LogPrintf("CBudgetManager::CheckAndRemove - PASSED\n");
}
void CBudgetManager::FillBlockPayee(CMutableTransaction& txNew, CAmount nFees)
{
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->nBits, pindexPrev->nHeight, nFees);
//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);
LogPrintf("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;
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;
}
/*
If budget doesn't have 5% of the network votes, then we should pay a masternode instead
*/
if(nHighestCount > mnodeman.CountEnabled(MIN_BUDGET_PEER_PROTO_VERSION)/20) return true;
return false;
}
bool CBudgetManager::HasNextFinalizedBudget()
{
CBlockIndex* pindexPrev = chainActive.Tip();
if(!pindexPrev) return false;
if(masternodeSync.IsBudgetFinEmpty()) return true;
int nBlockStart = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks();
if(nBlockStart - pindexPrev->nHeight > 576*2) return true; //we wouldn't have the budget yet
if(budget.IsBudgetPaymentBlock(nBlockStart)) return true;
LogPrintf("CBudgetManager::HasNextFinalizedBudget() - Client is missing budget - %lli\n", nBlockStart);
return false;
}
bool CBudgetManager::IsTransactionValid(const CTransaction& txNew, int nBlockHeight)
{
LOCK(cs);
int nHighestCount = 0;
std::vector<CFinalizedBudget*> ret;
// ------- 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;
}
/*
If budget doesn't have 5% of the network votes, then we should pay a masternode instead
*/
if(nHighestCount < mnodeman.CountEnabled(MIN_BUDGET_PEER_PROTO_VERSION)/20) return false;
// check the highest finalized budgets (+/- 10% to assist in consensus)
it = mapFinalizedBudgets.begin();
while(it != mapFinalizedBudgets.end())
{
CFinalizedBudget* pfinalizedBudget = &((*it).second);
if(pfinalizedBudget->GetVoteCount() > nHighestCount - mnodeman.CountEnabled(MIN_BUDGET_PEER_PROTO_VERSION)/10){
if(nBlockHeight >= pfinalizedBudget->GetBlockStart() && nBlockHeight <= pfinalizedBudget->GetBlockEnd()){
if(pfinalizedBudget->IsTransactionValid(txNew, nBlockHeight)){
return true;
}
}
}
++it;
}
//we looked through all of the known budgets
return false;
}
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());
// ------- Grab The Budgets In Order
std::vector<CBudgetProposal*> vBudgetProposalsRet;
CAmount nBudgetAllocated = 0;
CBlockIndex* pindexPrev = chainActive.Tip();
if(pindexPrev == NULL) return vBudgetProposalsRet;
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;
//prop start/end should be inside this period
if(pbudgetProposal->fValid && pbudgetProposal->nBlockStart <= nBlockStart &&
pbudgetProposal->nBlockEnd >= nBlockEnd &&
pbudgetProposal->GetYeas() - pbudgetProposal->GetNays() > mnodeman.CountEnabled(MIN_BUDGET_PEER_PROTO_VERSION)/10 &&
pbudgetProposal->IsEstablished())
{
if(pbudgetProposal->GetAmount() + nBudgetAllocated <= nTotalBudget) {
pbudgetProposal->SetAllotted(pbudgetProposal->GetAmount());
nBudgetAllocated += pbudgetProposal->GetAmount();
vBudgetProposalsRet.push_back(pbudgetProposal);
} else {
pbudgetProposal->SetAllotted(0);
}
}
++it2;
}
return vBudgetProposalsRet;
}
struct sortFinalizedBudgetsByVotes {
bool operator()(const std::pair<CFinalizedBudget*, int> &left, const std::pair<CFinalizedBudget*, int> &right) {
return left.second > right.second;
}
};
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 {
LogPrintf("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;
//get min block value and calculate from that
CAmount nSubsidy = 5 * COIN;
if(Params().NetworkID() == CBaseChainParams::TESTNET){
for(int i = 46200; i <= nHeight; i += 210240) nSubsidy -= nSubsidy/14;
} else {
// yearly decline of production by 7.1% per year, projected 21.3M coins max by year 2050.
for(int i = 210240; i <= nHeight; i += 210240) nSubsidy -= nSubsidy/14;
}
// Amount of blocks in a months period of time (using 2.6 minutes per) = (60*24*30)/2.6
if(Params().NetworkID() == CBaseChainParams::MAIN) return ((nSubsidy/100)*10)*576*30;
//for testing purposes
return ((nSubsidy/100)*10)*50;
}
void CBudgetManager::NewBlock()
{
TRY_LOCK(cs, fBudgetNewBlock);
if(!fBudgetNewBlock) return;
if (masternodeSync.RequestedMasternodeAssets <= MASTERNODE_SYNC_BUDGET) return;
if (strBudgetMode == "suggest") { //suggest the budget we see
SubmitFinalBudget();
}
//this function should be called 1/6 blocks, allowing up to 100 votes per day on all proposals
if(chainActive.Height() % 6 != 0) return;
// incremental sync with our peers
if(masternodeSync.IsSynced()){
LogPrintf("CBudgetManager::NewBlock - incremental sync started\n");
if(chainActive.Height() % 600 == rand() % 600) {
ClearSeen();
ResetSync();
}
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if(pnode->nVersion >= MIN_BUDGET_PEER_PROTO_VERSION)
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)
LogPrintf("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++);
}
}
LogPrintf("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;
}
LogPrintf("CBudgetManager::NewBlock - mapFinalizedBudgets cleanup - size: %d\n", mapFinalizedBudgets.size());
std::map<uint256, CFinalizedBudget>::iterator it3 = mapFinalizedBudgets.begin();
while(it3 != mapFinalizedBudgets.end()){
(*it3).second.CleanAndRemove(false);
++it3;
}
LogPrintf("CBudgetManager::NewBlock - vecImmatureBudgetProposals cleanup - size: %d\n", vecImmatureBudgetProposals.size());
std::vector<CBudgetProposalBroadcast>::iterator it4 = vecImmatureBudgetProposals.begin();
while(it4 != vecImmatureBudgetProposals.end())
{
std::string strError = "";
int nConf = 0;
if(!IsBudgetCollateralValid((*it4).nFeeTXHash, (*it4).GetHash(), strError, (*it4).nTime, nConf)){
++it4;
continue;
}
if(!(*it4).IsValid(strError)) {
LogPrintf("mprop (immature) - invalid budget proposal - %s\n", strError);
it4 = vecImmatureBudgetProposals.erase(it4);
continue;
}
CBudgetProposal budgetProposal((*it4));
if(AddProposal(budgetProposal)) {(*it4).Relay();}
LogPrintf("mprop (immature) - new budget - %s\n", (*it4).GetHash().ToString());
it4 = vecImmatureBudgetProposals.erase(it4);
}
LogPrintf("CBudgetManager::NewBlock - vecImmatureFinalizedBudgets cleanup - size: %d\n", vecImmatureFinalizedBudgets.size());
std::vector<CFinalizedBudgetBroadcast>::iterator it5 = vecImmatureFinalizedBudgets.begin();
while(it5 != vecImmatureFinalizedBudgets.end())
{
std::string strError = "";
int nConf = 0;
if(!IsBudgetCollateralValid((*it5).nFeeTXHash, (*it5).GetHash(), strError, (*it5).nTime, nConf)){
++it5;
continue;
}
if(!(*it5).IsValid(strError)) {
LogPrintf("fbs (immature) - invalid finalized budget - %s\n", strError);
it5 = vecImmatureFinalizedBudgets.erase(it5);
continue;
}
LogPrintf("fbs (immature) - new finalized budget - %s\n", (*it5).GetHash().ToString());
CFinalizedBudget finalizedBudget((*it5));
if(AddFinalizedBudget(finalizedBudget)) {(*it5).Relay();}
it5 = vecImmatureFinalizedBudgets.erase(it5);
}
LogPrintf("CBudgetManager::NewBlock - PASSED\n");
}
void CBudgetManager::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
// lite mode is not supported
if(fLiteMode) return;
if(!masternodeSync.IsBlockchainSynced()) return;
LOCK(cs_budget);
if (strCommand == "mnvs") { //Masternode vote sync
uint256 nProp;
vRecv >> nProp;
if(Params().NetworkID() == CBaseChainParams::MAIN){
if(nProp == 0) {
if(pfrom->HasFulfilledRequest("mnvs")) {
LogPrintf("mnvs - peer already asked me for the list\n");
Misbehaving(pfrom->GetId(), 20);
return;
}
pfrom->FulfilledRequest("mnvs");
}
}
Sync(pfrom, nProp);
LogPrintf("mnvs - Sent Masternode votes to %s\n", pfrom->addr.ToString());
}
if (strCommand == "mprop") { //Masternode Proposal
CBudgetProposalBroadcast budgetProposalBroadcast;
vRecv >> budgetProposalBroadcast;
if(mapSeenMasternodeBudgetProposals.count(budgetProposalBroadcast.GetHash())){
masternodeSync.AddedBudgetItem(budgetProposalBroadcast.GetHash());
return;
}
std::string strError = "";
int nConf = 0;
if(!IsBudgetCollateralValid(budgetProposalBroadcast.nFeeTXHash, budgetProposalBroadcast.GetHash(), strError, budgetProposalBroadcast.nTime, nConf)){
LogPrintf("Proposal FeeTX is not valid - %s - %s\n", budgetProposalBroadcast.nFeeTXHash.ToString(), strError);
if(nConf >= 1) vecImmatureBudgetProposals.push_back(budgetProposalBroadcast);
return;
}
mapSeenMasternodeBudgetProposals.insert(make_pair(budgetProposalBroadcast.GetHash(), budgetProposalBroadcast));
if(!budgetProposalBroadcast.IsValid(strError)) {
LogPrintf("mprop - invalid budget proposal - %s\n", strError);
return;
}
CBudgetProposal budgetProposal(budgetProposalBroadcast);
if(AddProposal(budgetProposal)) {budgetProposalBroadcast.Relay();}
masternodeSync.AddedBudgetItem(budgetProposalBroadcast.GetHash());
LogPrintf("mprop - new budget - %s\n", budgetProposalBroadcast.GetHash().ToString());
//We might have active votes for this proposal that are valid now
CheckOrphanVotes();
}
if (strCommand == "mvote") { //Masternode Vote
CBudgetVote vote;
vRecv >> vote;
vote.fValid = true;
if(mapSeenMasternodeBudgetVotes.count(vote.GetHash())){
masternodeSync.AddedBudgetItem(vote.GetHash());
return;
}
CMasternode* pmn = mnodeman.Find(vote.vin);
if(pmn == NULL) {
LogPrint("mnbudget", "mvote - unknown masternode - vin: %s\n", vote.vin.ToString());
mnodeman.AskForMN(pfrom, vote.vin);
return;
}
mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote));
if(!vote.SignatureValid(true)){
LogPrintf("mvote - signature invalid\n");
if(masternodeSync.IsSynced()) Misbehaving(pfrom->GetId(), 20);
// it could just be a non-synced masternode