forked from dashpay/dash
-
Notifications
You must be signed in to change notification settings - Fork 15
/
masternode-payments.cpp
1154 lines (932 loc) · 43.2 KB
/
masternode-payments.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-2017 The Däsh Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "activemasternode.h"
#include "darksend.h"
#include "governance-classes.h"
#include "masternode-payments.h"
#include "masternode-sync.h"
#include "masternodeman.h"
#include "netfulfilledman.h"
#include "spork.h"
#include "util.h"
#include <boost/lexical_cast.hpp>
/** Object for who's going to get paid on which blocks */
CMasternodePayments mnpayments;
CCriticalSection cs_vecPayees;
CCriticalSection cs_mapMasternodeBlocks;
CCriticalSection cs_mapMasternodePaymentVotes;
/**
* IsBlockValueValid
*
* Determine if coinbase outgoing created money is the correct value
*
* Why is this needed?
* - In Biblepay some blocks are superblocks, which output much higher amounts of coins
* - Otherblocks are 10% lower in outgoing value, so in total, no extra coins are created
* - When non-superblocks are detected, the normal schedule should be maintained
*/
std::string RoundToString(double d, int place);
CAmount GetRetirementAccountContributionAmount(int nPrevHeight);
extern CAmount GetTxSanctuaryCollateral(const CTransaction& txNew);
extern CAmount GetSanctuaryCollateral(CTxIn vin);
std::string GetTxOutScript(const CTransaction& tx1)
{
std::string sXML = "";
BOOST_REVERSE_FOREACH(CTxOut txout, tx1.vout)
{
sXML += txout.sTxOutMessage;
}
return sXML;
}
bool IsBlockValueValid(const CBlock& block, int nBlockHeight, CAmount blockReward, std::string &strErrorRet)
{
strErrorRet = "";
bool isBlockRewardValueMet = (block.vtx[0].GetValueOut() <= blockReward);
if(!isBlockRewardValueMet && fDebugMaster)
{
LogPrintf("block.vtx[0].GetValueOut() %f <= blockReward %f \n", (double)block.vtx[0].GetValueOut()/COIN, (double)blockReward/COIN);
}
// we are still using budgets, but we have no data about them anymore,
// all we know is predefined budget cycle and window
const Consensus::Params& consensusParams = Params().GetConsensus();
if(nBlockHeight < consensusParams.nSuperblockStartBlock)
{
/* This is for Budgeting, not used by BiblePay
int nOffset = nBlockHeight % consensusParams.nBudgetPaymentsCycleBlocks;
if(nBlockHeight >= consensusParams.nBudgetPaymentsStartBlock &&
nOffset < consensusParams.nBudgetPaymentsWindowBlocks) {
// NOTE: make sure SPORK_13_OLD_SUPERBLOCK_FLAG is disabled when 12.1 starts to go live
if(masternodeSync.IsSynced() && !sporkManager.IsSporkActive(SPORK_13_OLD_SUPERBLOCK_FLAG))
{
// no budget blocks should be accepted here, if SPORK_13_OLD_SUPERBLOCK_FLAG is disabled
LogPrint("gobject", "IsBlockValueValid -- Client synced but budget spork is disabled, checking block value against block reward\n");
if(!isBlockRewardValueMet)
{
std::string sNarr = "coinbase pays too much at height " + RoundToString(nBlockHeight,0)
+ " (actual=" + RoundToString(block.vtx[0].GetValueOut(),0) + " vs limit="
+ RoundToString(blockReward,0) + ", exceeded block reward, budgets are disabled";
LogPrintf(sNarr.c_str());
strErrorRet = sNarr;
}
return isBlockRewardValueMet;
}
LogPrint("gobject", "IsBlockValueValid -- WARNING: Skipping budget block value checks, accepting block\n");
return true;
}
// LogPrint("gobject", "IsBlockValueValid -- Block is not in budget cycle window, checking block value against block reward\n");
*/
// This section is before superblocks went live between Sep 2017 and Christmas 2017 - ensure each block is between 5000-20000:
if(!isBlockRewardValueMet)
{
LogPrintf("Block Reward Exceeded.\n");
strErrorRet = strprintf("Coinbase pays too much at height %f (actual=%f vs limit=%f), exceeded block reward, block is not in budget cycle window",
(double)nBlockHeight, (double)block.vtx[0].GetValueOut(), (double)blockReward);
}
return isBlockRewardValueMet;
}
// superblocks started
CAmount nSuperblockMaxValue = blockReward + CSuperblock::GetPaymentsLimit(nBlockHeight);
bool isSuperblockMaxValueMet = (block.vtx[0].GetValueOut() <= nSuperblockMaxValue);
LogPrint("gobject", "block.vtx[0].GetValueOut() %f <= nSuperblockMaxValue %f \n", (double)block.vtx[0].GetValueOut()/COIN, (double)nSuperblockMaxValue);
if(!masternodeSync.IsSynced())
{
// not enough data but at least it must NOT exceed superblock max value
if(CSuperblock::IsValidBlockHeight(nBlockHeight))
{
if(fDebugMaster) LogPrintf("IsBlockPayeeValid -- WARNING: Client not synced, checking superblock max bounds only \n");
if(!isSuperblockMaxValueMet)
{
strErrorRet = strprintf("coinbase pays too much at height %f (actual=%f vs limit=%f), exceeded superblock max value",
(double)nBlockHeight, (double)block.vtx[0].GetValueOut()/COIN, (double)nSuperblockMaxValue/COIN);
LogPrintf(strErrorRet.c_str());
}
return isSuperblockMaxValueMet;
}
if(!isBlockRewardValueMet)
{
strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, only regular blocks are allowed at this height",
nBlockHeight, block.vtx[0].GetValueOut()/COIN, blockReward/COIN);
}
// it MUST be a regular block otherwise
return isBlockRewardValueMet;
}
// we are synced, let's try to check as much data as we can
bool fSuperblocksEnabled = (nBlockHeight >= consensusParams.nSuperblockStartBlock) && fMasternodesEnabled;
if(fSuperblocksEnabled)
{
if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight))
{
if(CSuperblockManager::IsValid(block.vtx[0], nBlockHeight, blockReward))
{
LogPrint("gobject", "IsBlockValueValid -- Valid superblock at height %d: %s", nBlockHeight, block.vtx[0].ToString());
// all checks are done in CSuperblock::IsValid, nothing to do here
return true;
}
// triggered but invalid? that's weird
LogPrintf("IsBlockValueValid -- ERROR: Invalid superblock detected at height %d: %s", nBlockHeight, block.vtx[0].ToString());
// should NOT allow invalid superblocks, when superblocks are enabled
strErrorRet = strprintf("invalid superblock detected at height %d", nBlockHeight);
return false;
}
// Superblocks are enabled, this is not a superblock
LogPrint("gobject", "IsBlockValueValid -- No triggered superblock detected at height %d\n", nBlockHeight);
if(!isBlockRewardValueMet)
{
strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, no triggered superblock detected",
nBlockHeight, block.vtx[0].GetValueOut()/COIN, blockReward/COIN);
return false;
}
}
else
{
// should NOT allow superblocks at all, when superblocks are disabled
LogPrint("gobject", "IsBlockValueValid -- Superblocks are disabled, no superblocks allowed\n");
if(!isBlockRewardValueMet)
{
strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, superblocks are disabled",
nBlockHeight, block.vtx[0].GetValueOut()/COIN, blockReward/COIN);
}
}
// it MUST be a regular block
return isBlockRewardValueMet;
}
bool IsBlockPayeeValid(const CTransaction& txNew, int nBlockHeight, CAmount blockReward)
{
const Consensus::Params& consensusParams = Params().GetConsensus();
if (nBlockHeight < consensusParams.nMasternodePaymentsStartBlock) return true;
if(!masternodeSync.IsSynced())
{
//there is no budget data to use to check anything, let's just accept the longest chain
if(fDebugMaster) LogPrintf("IsBlockPayeeValid -- WARNING: Client not synced, skipping block payee checks\n");
return true;
}
// we are still using budgets, but we have no data about them anymore,
// we can only check masternode payments
if(nBlockHeight < consensusParams.nSuperblockStartBlock)
{
if(mnpayments.IsTransactionValid(txNew, nBlockHeight))
{
if (fDebugMaster) LogPrint("mnpayments", "IsBlockPayeeValid -- Valid masternode payment at height %d: %s", nBlockHeight, txNew.ToString());
return true;
}
/* This is for Budgeting - Not used by BiblePay
int nOffset = nBlockHeight % consensusParams.nBudgetPaymentsCycleBlocks;
if(nBlockHeight >= consensusParams.nBudgetPaymentsStartBlock &&
nOffset < consensusParams.nBudgetPaymentsWindowBlocks)
{
if(!sporkManager.IsSporkActive(SPORK_13_OLD_SUPERBLOCK_FLAG)) {
// no budget blocks should be accepted here, if SPORK_13_OLD_SUPERBLOCK_FLAG is disabled
if (fDebugMaster) LogPrint("gobject", "IsBlockPayeeValid -- ERROR: Client synced but budget spork is disabled and masternode payment is invalid\n");
return false;
}
// NOTE: this should never happen in real, SPORK_13_OLD_SUPERBLOCK_FLAG MUST be disabled when 12.1 starts to go live
LogPrint("gobject", "IsBlockPayeeValid -- WARNING: Probably valid budget block, have no data, accepting\n");
return true;
}
*/
bool bSpork8 = nBlockHeight > consensusParams.nMasternodePaymentsStartBlock + (7 * BLOCKS_PER_DAY);
if(fMasternodesEnabled && bSpork8)
{
LogPrintf("IsBlockPayeeValid -- ERROR: Invalid masternode payment detected at height %d: %s", nBlockHeight, txNew.ToString());
return false;
}
if (fDebugMaster) LogPrintf("IsBlockPayeeValid -- WARNING: Masternode payment enforcement is disabled, accepting any payee\n");
return true;
}
// superblocks started
// SEE IF THIS IS A VALID SUPERBLOCK
bool fSuperblocksEnabled = (nBlockHeight >= consensusParams.nSuperblockStartBlock) && fMasternodesEnabled;
if(fSuperblocksEnabled)
{
if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) {
if(CSuperblockManager::IsValid(txNew, nBlockHeight, blockReward)) {
LogPrint("gobject", "IsBlockPayeeValid -- Valid superblock at height %d: %s", nBlockHeight, txNew.ToString());
return true;
}
LogPrintf("IsBlockPayeeValid -- ERROR: Invalid superblock detected at height %d: %s", nBlockHeight, txNew.ToString());
// should NOT allow such superblocks, when superblocks are enabled
return false;
}
// continue validation, should pay MN
LogPrint("gobject", "IsBlockPayeeValid -- No triggered superblock detected at height %d\n", nBlockHeight);
} else {
// should NOT allow superblocks at all, when superblocks are disabled
LogPrint("gobject", "IsBlockPayeeValid -- Superblocks are disabled, no superblocks allowed\n");
}
// IF THIS ISN'T A SUPERBLOCK OR SUPERBLOCK IS INVALID, IT SHOULD PAY A MASTERNODE DIRECTLY
int nSpork8Height = fProd ? SPORK8_HEIGHT : SPORK8_HEIGHT_TESTNET;
bool bSpork8 = nBlockHeight > nSpork8Height;
if(mnpayments.IsTransactionValid(txNew, nBlockHeight))
{
LogPrint("mnpayments", "IsBlockPayeeValid -- Valid masternode payment at height %d: %s", nBlockHeight, txNew.ToString());
return true;
}
else if(bSpork8 && fMasternodesEnabled)
{
LogPrintf("IsBlockPayeeValid -- ERROR: Invalid masternode payment detected at height %d: %s", nBlockHeight, txNew.ToString());
return false;
}
LogPrintf("IsBlockPayeeValid -- WARNING: Masternode payment enforcement is disabled, accepting any payee\n");
return true;
}
void FillBlockPayments(CMutableTransaction& txNew, int nBlockHeight, CAmount blockReward, CTxOut& txoutMasternodeRet, std::vector<CTxOut>& voutSuperblockRet)
{
// only create superblocks if spork is enabled AND if superblock is actually triggered
// (height should be validated inside)
const Consensus::Params& consensusParams = Params().GetConsensus();
bool fSuperblocksEnabled = nBlockHeight >= consensusParams.nSuperblockStartBlock && fMasternodesEnabled;
if(fSuperblocksEnabled &&
CSuperblockManager::IsSuperblockTriggered(nBlockHeight))
{
if (fDebugMaster) LogPrint("gobject", "FillBlockPayments -- triggered superblock creation at height %d\n", nBlockHeight);
CSuperblockManager::CreateSuperblock(txNew, nBlockHeight, voutSuperblockRet);
return;
}
if (fSuperblocksEnabled)
{
// FILL BLOCK PAYEE WITH MASTERNODE PAYMENT OTHERWISE
mnpayments.FillBlockPayee(txNew, nBlockHeight, blockReward, txoutMasternodeRet);
if (fDebug10) LogPrintf("FillBlockPayments -- nBlockHeight %d blockReward %f txoutMasternodeRet %s txNew %s",
nBlockHeight, (double)blockReward, txoutMasternodeRet.ToString(), txNew.ToString());
}
}
std::string GetRequiredPaymentsString(int nBlockHeight)
{
// IF WE HAVE A ACTIVATED TRIGGER FOR THIS HEIGHT - IT IS A SUPERBLOCK, GET THE REQUIRED PAYEES
if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) {
return CSuperblockManager::GetRequiredPaymentsString(nBlockHeight);
}
// OTHERWISE, PAY MASTERNODE
return mnpayments.GetRequiredPaymentsString(nBlockHeight);
}
void CMasternodePayments::Clear()
{
LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes);
mapMasternodeBlocks.clear();
mapMasternodePaymentVotes.clear();
}
bool CMasternodePayments::CanVote(COutPoint outMasternode, int nBlockHeight)
{
LOCK(cs_mapMasternodePaymentVotes);
if (mapMasternodesLastVote.count(outMasternode) && mapMasternodesLastVote[outMasternode] == nBlockHeight) {
return false;
}
//record this masternode voted
mapMasternodesLastVote[outMasternode] = nBlockHeight;
return true;
}
/**
* FillBlockPayee
*
* Fill Masternode ONLY payment block
*/
void CMasternodePayments::FillBlockPayee(CMutableTransaction& txNew, int nBlockHeight, CAmount blockReward, CTxOut& txoutMasternodeRet)
{
if (fRetirementAccountsEnabled)
{
// Award colored coins for retirement
CAmount retirementAmount = GetRetirementAccountContributionAmount(nBlockHeight);
// Ensure retirement emission per block is capped at a max of 10% of miner block subsidy
if (retirementAmount > (txNew.vout[0].nValue * .10)) retirementAmount = txNew.vout[0].nValue * .10;
txNew.vout.resize(txNew.vout.size()+1);
txNew.vout[0].nValue -= retirementAmount;
txNew.vout[txNew.vout.size()-1].scriptPubKey = txNew.vout[0].scriptPubKey;
txNew.vout[txNew.vout.size()-1].nValue = retirementAmount;
CComplexTransaction cct(txNew);
std::string sAssetColorScript = cct.GetScriptForAssetColor("401"); // Get the script for 401k coins
txNew.vout[txNew.vout.size()-1].sTxOutMessage += sAssetColorScript;
}
txoutMasternodeRet = CTxOut();
CScript payee;
CAmount nCollateral = 0;
std::string sCollateralScript = "";
if(!mnpayments.GetBlockPayeeAndCollateral(nBlockHeight, payee, nCollateral, sCollateralScript))
{
// no masternode detected...
int nCount = 0;
CMasternode *winningNode = mnodeman.GetNextMasternodeInQueueForPayment(nBlockHeight, true, nCount);
if(!winningNode) {
// ...and we can't calculate it on our own
if (fDebugMaster) LogPrintf("CMasternodePayments::FillBlockPayee -- Failed to detect masternode to pay\n");
return;
}
// fill payee with locally calculated winner and hope for the best
payee = GetScriptForDestination(winningNode->pubKeyCollateralAddress.GetID());
}
if (false && fDebugMaster) LogPrintf(" Collateral amount %f, Coll Script %s ",(double)nCollateral/COIN,sCollateralScript.c_str());
// GET MASTERNODE PAYMENT VARIABLES SETUP
CAmount masternodePayment = GetMasternodePayment(nBlockHeight, blockReward, nCollateral);
// split reward between miner ...
txNew.vout[0].nValue -= masternodePayment;
// ... and masternode
txoutMasternodeRet = CTxOut(masternodePayment, payee);
txNew.vout.push_back(txoutMasternodeRet);
CTxDestination address1;
ExtractDestination(payee, address1);
CBitcoinAddress address2(address1);
LogPrintf("CMasternodePayments::FillBlockPayee -- Masternode payment %f to %s\n", (double)masternodePayment, address2.ToString().c_str());
}
int CMasternodePayments::GetMinMasternodePaymentsProto() {
return sporkManager.IsSporkActive(SPORK_10_MASTERNODE_PAY_UPDATED_NODES)
? MIN_MASTERNODE_PAYMENT_PROTO_VERSION_2
: MIN_MASTERNODE_PAYMENT_PROTO_VERSION_1;
}
void CMasternodePayments::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
// Ignore any payments messages until masternode list is synced
if(!masternodeSync.IsMasternodeListSynced()) return;
if(fLiteMode) return; // disable all Biblepay specific functionality
if (strCommand == NetMsgType::MASTERNODEPAYMENTSYNC) { //Masternode Payments Request Sync
// Ignore such requests until we are fully synced.
// We could start processing this after masternode list is synced
// but this is a heavy one so it's better to finish sync first.
if (!masternodeSync.IsSynced()) return;
int nCountNeeded;
vRecv >> nCountNeeded;
if (fMasternodesEnabled)
{
if(netfulfilledman.HasFulfilledRequest(pfrom->addr, NetMsgType::MASTERNODEPAYMENTSYNC))
{
// Asking for the payments list multiple times in a short period of time is no good
LogPrintf("MASTERNODEPAYMENTSYNC -- peer already asked me for the list, peer=%d\n", pfrom->id);
Misbehaving(pfrom->GetId(), 15);
return;
}
}
netfulfilledman.AddFulfilledRequest(pfrom->addr, NetMsgType::MASTERNODEPAYMENTSYNC);
Sync(pfrom);
LogPrintf("MASTERNODEPAYMENTSYNC -- Sent Masternode payment votes to peer %d\n", pfrom->id);
} else if (strCommand == NetMsgType::MASTERNODEPAYMENTVOTE) { // Masternode Payments Vote for the Winner
CMasternodePaymentVote vote;
vRecv >> vote;
if(pfrom->nVersion < GetMinMasternodePaymentsProto()) return;
if(!pCurrentBlockIndex) return;
uint256 nHash = vote.GetHash();
pfrom->setAskFor.erase(nHash);
{
LOCK(cs_mapMasternodePaymentVotes);
if(mapMasternodePaymentVotes.count(nHash)) {
LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- hash=%s, nHeight=%d seen\n", nHash.ToString(), pCurrentBlockIndex->nHeight);
return;
}
// Avoid processing same vote multiple times
mapMasternodePaymentVotes[nHash] = vote;
// but first mark vote as non-verified,
// AddPaymentVote() below should take care of it if vote is actually ok
mapMasternodePaymentVotes[nHash].MarkAsNotVerified();
}
int nFirstBlock = pCurrentBlockIndex->nHeight - GetStorageLimit();
if(vote.nBlockHeight < nFirstBlock || vote.nBlockHeight > pCurrentBlockIndex->nHeight+20) {
LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- vote out of range: nFirstBlock=%d, nBlockHeight=%d, nHeight=%d\n", nFirstBlock, vote.nBlockHeight, pCurrentBlockIndex->nHeight);
return;
}
std::string strError = "";
if(!vote.IsValid(pfrom, pCurrentBlockIndex->nHeight, strError)) {
LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- invalid message, error: %s\n", strError);
return;
}
if(!CanVote(vote.vinMasternode.prevout, vote.nBlockHeight)) {
LogPrintf("MASTERNODEPAYMENTVOTE -- masternode already voted, masternode=%s\n", vote.vinMasternode.prevout.ToStringShort());
return;
}
masternode_info_t mnInfo = mnodeman.GetMasternodeInfo(vote.vinMasternode);
if(!mnInfo.fInfoValid) {
// mn was not found, so we can't check vote, some info is probably missing
LogPrintf("MASTERNODEPAYMENTVOTE -- masternode is missing %s\n", vote.vinMasternode.prevout.ToStringShort());
mnodeman.AskForMN(pfrom, vote.vinMasternode);
return;
}
int nDos = 0;
if(!vote.CheckSignature(mnInfo.pubKeyMasternode, pCurrentBlockIndex->nHeight, nDos)) {
if(nDos) {
LogPrintf("MASTERNODEPAYMENTVOTE -- ERROR: invalid signature\n");
Misbehaving(pfrom->GetId(), nDos);
} else {
// only warn about anything non-critical (i.e. nDos == 0) in debug mode
LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- WARNING: invalid signature\n");
}
// Either our info or vote info could be outdated.
// In case our info is outdated, ask for an update,
mnodeman.AskForMN(pfrom, vote.vinMasternode);
// but there is nothing we can do if vote info itself is outdated
// (i.e. it was signed by a mn which changed its key),
// so just quit here.
return;
}
CTxDestination address1;
ExtractDestination(vote.payee, address1);
CBitcoinAddress address2(address1);
LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- vote: address=%s, nBlockHeight=%d, nHeight=%d, prevout=%s\n", address2.ToString(), vote.nBlockHeight, pCurrentBlockIndex->nHeight,
vote.vinMasternode.prevout.ToStringShort());
if(AddPaymentVote(vote)){
vote.Relay();
masternodeSync.AddedPaymentVote();
}
}
}
bool CMasternodePaymentVote::Sign()
{
std::string strError;
std::string strMessage = vinMasternode.prevout.ToStringShort() +
boost::lexical_cast<std::string>(nBlockHeight) +
ScriptToAsmStr(payee);
if(!darkSendSigner.SignMessage(strMessage, vchSig, activeMasternode.keyMasternode)) {
LogPrintf("CMasternodePaymentVote::Sign -- SignMessage() failed\n");
return false;
}
if(!darkSendSigner.VerifyMessage(activeMasternode.pubKeyMasternode, vchSig, strMessage, strError)) {
LogPrintf("CMasternodePaymentVote::Sign -- VerifyMessage() failed, error: %s\n", strError);
return false;
}
return true;
}
bool CMasternodePayments::GetBlockPayeeAndCollateral(int nBlockHeight, CScript& payee, CAmount& nCollateral, std::string& sScript)
{
if(mapMasternodeBlocks.count(nBlockHeight))
{
mapMasternodeBlocks[nBlockHeight].GetBestPayee(payee, nCollateral, sScript);
return true;
}
return false;
}
// Is this masternode scheduled to get paid soon?
// -- Only look ahead up to 8 blocks to allow for propagation of the latest 2 blocks of votes
bool CMasternodePayments::IsScheduled(CMasternode& mn, int nNotBlockHeight)
{
LOCK(cs_mapMasternodeBlocks);
if(!pCurrentBlockIndex) return false;
CScript mnpayee;
mnpayee = GetScriptForDestination(mn.pubKeyCollateralAddress.GetID());
CScript payee;
for(int64_t h = pCurrentBlockIndex->nHeight; h <= pCurrentBlockIndex->nHeight + 8; h++)
{
if(h == nNotBlockHeight) continue;
CAmount Collateral = 0;
std::string sScript = "";
if(mapMasternodeBlocks.count(h) && mapMasternodeBlocks[h].GetBestPayee(payee,Collateral,sScript) && mnpayee == payee)
{
return true;
}
}
return false;
}
bool CMasternodePayments::AddPaymentVote(const CMasternodePaymentVote& vote)
{
uint256 blockHash = uint256();
if(!GetBlockHash(blockHash, vote.nBlockHeight - 101)) return false;
if(HasVerifiedPaymentVote(vote.GetHash())) return false;
LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes);
mapMasternodePaymentVotes[vote.GetHash()] = vote;
if(!mapMasternodeBlocks.count(vote.nBlockHeight)) {
CMasternodeBlockPayees blockPayees(vote.nBlockHeight);
mapMasternodeBlocks[vote.nBlockHeight] = blockPayees;
}
mapMasternodeBlocks[vote.nBlockHeight].AddPayee(vote);
return true;
}
bool CMasternodePayments::HasVerifiedPaymentVote(uint256 hashIn)
{
LOCK(cs_mapMasternodePaymentVotes);
std::map<uint256, CMasternodePaymentVote>::iterator it = mapMasternodePaymentVotes.find(hashIn);
return it != mapMasternodePaymentVotes.end() && it->second.IsVerified();
}
CAmount GetSanctuaryCollateral(CTxIn vin)
{
CCoins coins;
if(!pcoinsTip->GetCoins(vin.prevout.hash, coins)
|| (unsigned int)vin.prevout.n>=coins.vout.size()
|| coins.vout[vin.prevout.n].IsNull())
{
LogPrintf("GetSanctuaryCollateral::Unable to retrieve Masternode UTXO, masternode=%s\n", vin.prevout.ToStringShort());
return 0;
}
return coins.vout[vin.prevout.n].nValue;
}
void CMasternodeBlockPayees::AddPayee(const CMasternodePaymentVote& vote)
{
LOCK(cs_vecPayees);
BOOST_FOREACH(CMasternodePayee& payee, vecPayees)
{
if (payee.GetPayee() == vote.payee)
{
payee.AddVoteHash(vote.GetHash());
return;
}
}
CMasternodePayee payeeNew(vote.payee, vote.GetHash(), vote.vinMasternode);
// BiblePay 10-26-2017 - Track Sanctuary VIN on voted payees
// Verify collateral
CAmount nCollateral = GetSanctuaryCollateral(vote.vinMasternode);
if (fDebugMaster && false) LogPrintf(" Sanctuary AddPayee VIN %s collateral %f txid %s %f\n", vote.vinMasternode.prevout.ToStringShort(),
nCollateral, vote.vinMasternode.prevout.hash.GetHex().c_str(), vote.vinMasternode.prevout.n);
vecPayees.push_back(payeeNew);
}
/*
std::string GetTempleCollateralScript(CMasternodePayee& payee)
{
CAmount caCollateral = GetSanctuaryCollateral(payee.GetVin());
if (caCollateral == (TEMPLE_COLLATERAL * COIN))
{
std::string sCollateral = "<COLLATERAL><HASH>" + payee.GetVin().prevout.hash.GetHex() + "</HASH><N>"
+ RoundToString((int)payee.GetVin().prevout.n,0) + "</N><AMOUNT>"
+ RoundToString(caCollateral/COIN,4) + "</AMOUNT></COLLATERAL>";
return sCollateral;
}
return "<COLLATERAL></COLLATERAL>";
}
*/
bool CMasternodeBlockPayees::GetBestPayee(CScript& payeeRet, CAmount& nCollateral, std::string& sScript)
{
LOCK(cs_vecPayees);
if(!vecPayees.size())
{
LogPrint("mnpayments", "CMasternodeBlockPayees::GetBestPayee -- ERROR: couldn't find any payee\n");
return false;
}
int nVotes = -1;
BOOST_FOREACH(CMasternodePayee& payee, vecPayees)
{
if (payee.GetVoteCount() > nVotes)
{
payeeRet = payee.GetPayee();
nVotes = payee.GetVoteCount();
nCollateral = GetSanctuaryCollateral(payee.GetVin());
sScript = "";
}
}
return (nVotes > -1);
}
bool CMasternodeBlockPayees::HasPayeeWithVotes(CScript payeeIn, int nVotesReq)
{
LOCK(cs_vecPayees);
BOOST_FOREACH(CMasternodePayee& payee, vecPayees) {
if (payee.GetVoteCount() >= nVotesReq && payee.GetPayee() == payeeIn) {
return true;
}
}
LogPrint("mnpayments", "CMasternodeBlockPayees::HasPayeeWithVotes -- ERROR: couldn't find any payee with %d+ votes\n", nVotesReq);
return false;
}
bool CMasternodeBlockPayees::IsTransactionValid(const CTransaction& txNew)
{
LOCK(cs_vecPayees);
int nMaxSignatures = 0;
std::string strPayeesPossible = "";
CAmount nCollateral = GetTxSanctuaryCollateral(txNew);
CAmount nMasternodePayment = GetMasternodePayment(nBlockHeight, txNew.GetValueOut(), nCollateral);
//require at least MNPAYMENTS_SIGNATURES_REQUIRED signatures
BOOST_FOREACH(CMasternodePayee& payee, vecPayees)
{
if (payee.GetVoteCount() >= nMaxSignatures)
{
nMaxSignatures = payee.GetVoteCount();
}
}
// if we don't have at least MNPAYMENTS_SIGNATURES_REQUIRED signatures on a payee, approve whichever is the longest chain
if(nMaxSignatures < MNPAYMENTS_SIGNATURES_REQUIRED) return true;
BOOST_FOREACH(CMasternodePayee& payee, vecPayees)
{
if (payee.GetVoteCount() >= MNPAYMENTS_SIGNATURES_REQUIRED)
{
BOOST_FOREACH(CTxOut txout, txNew.vout)
{
if (payee.GetPayee() == txout.scriptPubKey && nMasternodePayment == txout.nValue)
{
LogPrint("mnpayments", "CMasternodeBlockPayees::IsTransactionValid -- Found required payment\n");
return true;
}
}
CTxDestination address1;
ExtractDestination(payee.GetPayee(), address1);
CBitcoinAddress address2(address1);
if(strPayeesPossible == "")
{
strPayeesPossible = address2.ToString();
} else {
strPayeesPossible += "," + address2.ToString();
}
}
}
LogPrintf("CMasternodeBlockPayees::IsTransactionValid -- ERROR: Missing required payment, possible payees: '%s', amount: %f biblepay\n", strPayeesPossible, (double)nMasternodePayment/COIN);
return false;
}
std::string CMasternodeBlockPayees::GetRequiredPaymentsString()
{
LOCK(cs_vecPayees);
std::string strRequiredPayments = "Unknown";
BOOST_FOREACH(CMasternodePayee& payee, vecPayees)
{
CTxDestination address1;
ExtractDestination(payee.GetPayee(), address1);
CBitcoinAddress address2(address1);
if (strRequiredPayments != "Unknown") {
strRequiredPayments += ", " + address2.ToString() + ":" + boost::lexical_cast<std::string>(payee.GetVoteCount());
} else {
strRequiredPayments = address2.ToString() + ":" + boost::lexical_cast<std::string>(payee.GetVoteCount());
}
}
return strRequiredPayments;
}
CAmount CMasternodeBlockPayees::GetTxSanctuaryCollateral(const CTransaction& txNew)
{
BOOST_REVERSE_FOREACH(CMasternodePayee& payee, vecPayees)
{
BOOST_REVERSE_FOREACH(CTxOut txout, txNew.vout)
{
if (payee.GetPayee() == txout.scriptPubKey)
{
CAmount caCollateral = GetSanctuaryCollateral(payee.GetVin());
return caCollateral;
}
}
}
return 0;
}
std::string CMasternodePayments::GetRequiredPaymentsString(int nBlockHeight)
{
LOCK(cs_mapMasternodeBlocks);
if(mapMasternodeBlocks.count(nBlockHeight)){
return mapMasternodeBlocks[nBlockHeight].GetRequiredPaymentsString();
}
return "Unknown";
}
bool CMasternodePayments::IsTransactionValid(const CTransaction& txNew, int nBlockHeight)
{
LOCK(cs_mapMasternodeBlocks);
if(mapMasternodeBlocks.count(nBlockHeight))
{
return mapMasternodeBlocks[nBlockHeight].IsTransactionValid(txNew);
}
return true;
}
void CMasternodePayments::CheckAndRemove()
{
if(!pCurrentBlockIndex) return;
LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes);
int nLimit = GetStorageLimit();
std::map<uint256, CMasternodePaymentVote>::iterator it = mapMasternodePaymentVotes.begin();
while(it != mapMasternodePaymentVotes.end()) {
CMasternodePaymentVote vote = (*it).second;
if(pCurrentBlockIndex->nHeight - vote.nBlockHeight > nLimit)
{
if (fDebugMaster) LogPrint("mnpayments", "CMasternodePayments::CheckAndRemove -- Removing old Masternode payment: nBlockHeight=%d\n", vote.nBlockHeight);
mapMasternodePaymentVotes.erase(it++);
mapMasternodeBlocks.erase(vote.nBlockHeight);
} else {
++it;
}
}
if (fDebugMaster) LogPrintf("CMasternodePayments::CheckAndRemove -- %s\n", ToString());
}
bool CMasternodePaymentVote::IsValid(CNode* pnode, int nValidationHeight, std::string& strError)
{
CMasternode* pmn = mnodeman.Find(vinMasternode);
if(!pmn) {
strError = strprintf("Unknown Masternode: prevout=%s", vinMasternode.prevout.ToStringShort());
// Only ask if we are already synced and still have no idea about that Masternode
if(masternodeSync.IsMasternodeListSynced()) {
mnodeman.AskForMN(pnode, vinMasternode);
}
return false;
}
int nMinRequiredProtocol;
if(nBlockHeight >= nValidationHeight) {
// new votes must comply SPORK_10_MASTERNODE_PAY_UPDATED_NODES rules
nMinRequiredProtocol = mnpayments.GetMinMasternodePaymentsProto();
} else {
// allow non-updated masternodes for old blocks
nMinRequiredProtocol = MIN_MASTERNODE_PAYMENT_PROTO_VERSION_1;
}
if(pmn->nProtocolVersion < nMinRequiredProtocol) {
strError = strprintf("Masternode protocol is too old: nProtocolVersion=%d, nMinRequiredProtocol=%d", pmn->nProtocolVersion, nMinRequiredProtocol);
return false;
}
// Only masternodes should try to check masternode rank for old votes - they need to pick the right winner for future blocks.
// Regular clients (miners included) need to verify masternode rank for future block votes only.
if(!fMasterNode && nBlockHeight < nValidationHeight) return true;
int nRank = mnodeman.GetMasternodeRank(vinMasternode, nBlockHeight - 101, nMinRequiredProtocol, false);
if(nRank == -1) {
LogPrint("mnpayments", "CMasternodePaymentVote::IsValid -- Can't calculate rank for masternode %s\n",
vinMasternode.prevout.ToStringShort());
return false;
}
if(nRank > MNPAYMENTS_SIGNATURES_TOTAL)
{
// It's common to have masternodes mistakenly think they are in the top 10
// We don't want to print all of these messages in normal mode, debug mode should print though
strError = strprintf("Masternode is not in the top %d (%d)", MNPAYMENTS_SIGNATURES_TOTAL, nRank);
// Only ban for new mnw which is out of bounds, for old mnw MN list itself might be way too much off
if(nRank > MNPAYMENTS_SIGNATURES_TOTAL*2 && nBlockHeight > nValidationHeight) {
strError = strprintf("Masternode is not in the top %d (%d)", MNPAYMENTS_SIGNATURES_TOTAL*2, nRank);
LogPrintf("CMasternodePaymentVote::IsValid -- Error: %s\n", strError);
Misbehaving(pnode->GetId(), 25);
}
// Still invalid however
return false;
}
return true;
}
bool CMasternodePayments::ProcessBlock(int nBlockHeight)
{
// DETERMINE IF WE SHOULD BE VOTING FOR THE NEXT PAYEE
if(fLiteMode || !fMasterNode) return false;
const Consensus::Params& consensusParams = Params().GetConsensus();
if (nBlockHeight < consensusParams.nMasternodePaymentsStartBlock) return false;
// We have little chances to pick the right winner if winners list is out of sync
// but we have no choice, so we'll try. However it doesn't make sense to even try to do so
// if we have not enough data about masternodes.
if(!masternodeSync.IsMasternodeListSynced()) return false;
int nRank = mnodeman.GetMasternodeRank(activeMasternode.vin, nBlockHeight - 101, GetMinMasternodePaymentsProto(), false);
if (nRank == -1) {
if (fDebugMaster) LogPrint("mnpayments", "CMasternodePayments::ProcessBlock -- Unknown Masternode\n");
return false;
}
if (nRank > MNPAYMENTS_SIGNATURES_TOTAL)
{
if (fDebugMaster) LogPrint("mnpayments", "CMasternodePayments::ProcessBlock -- Masternode not in the top %d (%d)\n", MNPAYMENTS_SIGNATURES_TOTAL, nRank);
return false;
}
// LOCATE THE NEXT MASTERNODE WHICH SHOULD BE PAID
if (fDebugMaster) LogPrintf("CMasternodePayments::ProcessBlock -- Start: nBlockHeight=%d, masternode=%s\n", nBlockHeight, activeMasternode.vin.prevout.ToStringShort());
// pay to the oldest MN that still had no payment but its input is old enough and it was active long enough
int nCount = 0;
CMasternode *pmn = mnodeman.GetNextMasternodeInQueueForPayment(nBlockHeight, true, nCount);
if (pmn == NULL)
{
if (fDebugMaster) LogPrintf("CMasternodePayments::ProcessBlock -- ERROR: Failed to find masternode to pay\n");
return false;
}
if (fDebugMaster) LogPrintf("CMasternodePayments::ProcessBlock -- Masternode found by GetNextMasternodeInQueueForPayment(): %s\n", pmn->vin.prevout.ToStringShort());
CScript payee = GetScriptForDestination(pmn->pubKeyCollateralAddress.GetID());
CMasternodePaymentVote voteNew(activeMasternode.vin, nBlockHeight, payee);
CTxDestination address1;
ExtractDestination(payee, address1);
CBitcoinAddress address2(address1);
if (fDebugMaster) LogPrintf("CMasternodePayments::ProcessBlock -- vote: payee=%s, nBlockHeight=%d\n", address2.ToString(), nBlockHeight);
// SIGN MESSAGE TO NETWORK WITH OUR MASTERNODE KEYS
if (fDebugMaster) LogPrintf("CMasternodePayments::ProcessBlock -- Signing vote\n");
if (voteNew.Sign())
{
if (fDebugMaster) LogPrintf("CMasternodePayments::ProcessBlock -- AddPaymentVote()\n");
if (AddPaymentVote(voteNew))
{
voteNew.Relay();
return true;
}
}
return false;
}
void CMasternodePaymentVote::Relay()
{
// do not relay until synced
if (!masternodeSync.IsWinnersListSynced()) return;
CInv inv(MSG_MASTERNODE_PAYMENT_VOTE, GetHash());
RelayInv(inv);
}
bool CMasternodePaymentVote::CheckSignature(const CPubKey& pubKeyMasternode, int nValidationHeight, int &nDos)
{
// do not ban by default
nDos = 0;
std::string strMessage = vinMasternode.prevout.ToStringShort() +
boost::lexical_cast<std::string>(nBlockHeight) +
ScriptToAsmStr(payee);
std::string strError = "";
if (!darkSendSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) {
// Only ban for future block vote when we are already synced.
// Otherwise it could be the case when MN which signed this vote is using another key now
// and we have no idea about the old one.
if(masternodeSync.IsMasternodeListSynced() && nBlockHeight > nValidationHeight) {
nDos = 20;
}