-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmasternode.cpp
More file actions
838 lines (673 loc) · 27 KB
/
Copy pathmasternode.cpp
File metadata and controls
838 lines (673 loc) · 27 KB
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
#include "masternode.h"
#include "activemasternode.h"
#include "darksend.h"
//#include "primitives/transaction.h"
#include "main.h"
#include "util.h"
#include "addrman.h"
#include <boost/lexical_cast.hpp>
int CMasterNode::minProtoVersion = MIN_MN_PROTO_VERSION;
CCriticalSection cs_masternodes;
/** The list of active masternodes */
std::vector<CMasterNode> vecMasternodes;
/** Object for who's going to get paid on which blocks */
CMasternodePayments masternodePayments;
// keep track of masternode votes I've seen
map<uint256, CMasternodePaymentWinner> mapSeenMasternodeVotes;
// keep track of the scanning errors I've seen
map<uint256, int> mapSeenMasternodeScanningErrors;
// who's asked for the masternode list and the last time
std::map<CNetAddr, int64_t> askedForMasternodeList;
// which masternodes we've asked for
std::map<COutPoint, int64_t> askedForMasternodeListEntry;
// cache block hashes as we calculate them
std::map<int64_t, uint256> mapCacheBlockHashes;
// manage the masternode connections
void ProcessMasternodeConnections(){
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
//if it's our masternode, let it be
if(darkSendPool.submittedToMasternode == pnode->addr) continue;
if(pnode->fDarkSendMaster){
LogPrintf("Closing masternode connection %s \n", pnode->addr.ToString().c_str());
pnode->CloseSocketDisconnect();
}
}
}
void ProcessMessageMasternode(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
if (strCommand == "dsee") { //DarkSend Election Entry
if(fLiteMode) return; //disable all darksend/masternode related functionality
bool fIsInitialDownload = IsInitialBlockDownload();
if(fIsInitialDownload) return;
CTxIn vin;
CService addr;
CPubKey pubkey;
CPubKey pubkey2;
vector<unsigned char> vchSig;
int64_t sigTime;
int count;
int current;
int64_t lastUpdated;
int protocolVersion;
std::string strMessage;
// 70047 and greater
vRecv >> vin >> addr >> vchSig >> sigTime >> pubkey >> pubkey2 >> count >> current >> lastUpdated >> protocolVersion;
// make sure signature isn't in the future (past is OK)
if (sigTime > GetAdjustedTime() + 60 * 60) {
LogPrintf("dsee - Signature rejected, too far into the future %s\n", vin.ToString().c_str());
return;
}
bool isLocal = addr.IsRFC1918() || addr.IsLocal();
//if(Params().MineBlocksOnDemand()) isLocal = false;
std::string vchPubKey(pubkey.begin(), pubkey.end());
std::string vchPubKey2(pubkey2.begin(), pubkey2.end());
strMessage = addr.ToString() + boost::lexical_cast<std::string>(sigTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(protocolVersion);
if(protocolVersion < MIN_MN_PROTO_VERSION) {
LogPrintf("dsee - ignoring outdated masternode %s protocol version %d\n", vin.ToString().c_str(), protocolVersion);
return;
}
CScript pubkeyScript;
pubkeyScript =GetScriptForDestination(pubkey.GetID());
if(pubkeyScript.size() != 25) {
LogPrintf("dsee - pubkey the wrong size\n");
Misbehaving(pfrom->GetId(), 100);
return;
}
CScript pubkeyScript2;
pubkeyScript2 =GetScriptForDestination(pubkey2.GetID());
if(pubkeyScript2.size() != 25) {
LogPrintf("dsee - pubkey2 the wrong size\n");
Misbehaving(pfrom->GetId(), 100);
return;
}
std::string errorMessage = "";
if(!darkSendSigner.VerifyMessage(pubkey, vchSig, strMessage, errorMessage)){
LogPrintf("dsee - Got bad masternode address signature\n");
Misbehaving(pfrom->GetId(), 100);
return;
}
//search existing masternode list, this is where we update existing masternodes with new dsee broadcasts
LOCK(cs_masternodes);
BOOST_FOREACH(CMasterNode& mn, vecMasternodes) {
if(mn.vin.prevout == vin.prevout) {
// count == -1 when it's a new entry
// e.g. We don't want the entry relayed/time updated when we're syncing the list
// mn.pubkey = pubkey, IsVinAssociatedWithPubkey is validated once below,
// after that they just need to match
if(count == -1 && mn.pubkey == pubkey && !mn.UpdatedWithin(MASTERNODE_MIN_DSEE_SECONDS)){
mn.UpdateLastSeen();
if(mn.now < sigTime){ //take the newest entry
LogPrintf("dsee - Got updated entry for %s\n", addr.ToString().c_str());
mn.pubkey2 = pubkey2;
mn.now = sigTime;
mn.sig = vchSig;
mn.protocolVersion = protocolVersion;
mn.addr = addr;
RelayDarkSendElectionEntry(vin, addr, vchSig, sigTime, pubkey, pubkey2, count, current, lastUpdated, protocolVersion);
}
}
return;
}
}
// make sure the vout that was signed is related to the transaction that spawned the masternode
// - this is expensive, so it's only done once per masternode
if(!darkSendSigner.IsVinAssociatedWithPubkey(vin, pubkey)) {
LogPrintf("dsee - Got mismatched pubkey and vin\n");
Misbehaving(pfrom->GetId(), 100);
return;
}
if(fDebug) LogPrintf("dsee - Got NEW masternode entry %s\n", addr.ToString().c_str());
// make sure it's still unspent
// - this is checked later by .check() in many places and by ThreadCheckDarkSendPool()
CValidationState state;
CTransaction tx = CTransaction();
CTxOut vout = CTxOut(99999*COIN, darkSendPool.collateralPubKey);
tx.vin.push_back(vin);
tx.vout.push_back(vout);
//if(AcceptableInputs(mempool, state, tx)){
bool* pfMissingInputs = false;
if(AcceptableInputs(mempool, tx, false, pfMissingInputs)){
if(fDebug) LogPrintf("dsee - Accepted masternode entry %i %i\n", count, current);
if(GetInputAge(vin) < MASTERNODE_MIN_CONFIRMATIONS){
LogPrintf("dsee - Input must have least %d confirmations\n", MASTERNODE_MIN_CONFIRMATIONS);
Misbehaving(pfrom->GetId(), 20);
return;
}
// use this as a peer
addrman.Add(CAddress(addr), pfrom->addr, 2*60*60);
// add our masternode
CMasterNode mn(addr, vin, pubkey, vchSig, sigTime, pubkey2, protocolVersion);
mn.UpdateLastSeen(lastUpdated);
vecMasternodes.push_back(mn);
// if it matches our masternodeprivkey, then we've been remotely activated
if(pubkey2 == activeMasternode.pubKeyMasternode && protocolVersion == PROTOCOL_VERSION){
activeMasternode.EnableHotColdMasterNode(vin, addr);
}
if(count == -1 && !isLocal)
RelayDarkSendElectionEntry(vin, addr, vchSig, sigTime, pubkey, pubkey2, count, current, lastUpdated, protocolVersion);
} else {
LogPrintf("dsee - Rejected masternode entry %s\n", addr.ToString().c_str());
int nDoS = 0;
if (state.IsInvalid(nDoS))
{
LogPrintf("dsee - %s from %s %s was not accepted into the memory pool\n", tx.GetHash().ToString().c_str(),
pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str());
if (nDoS > 0)
Misbehaving(pfrom->GetId(), nDoS);
}
}
}
else if (strCommand == "dseep") { //DarkSend Election Entry Ping
if(fLiteMode) return; //disable all darksend/masternode related functionality
bool fIsInitialDownload = IsInitialBlockDownload();
if(fIsInitialDownload) return;
CTxIn vin;
vector<unsigned char> vchSig;
int64_t sigTime;
bool stop;
vRecv >> vin >> vchSig >> sigTime >> stop;
//LogPrintf("dseep - Received: vin: %s sigTime: %lld stop: %s\n", vin.ToString().c_str(), sigTime, stop ? "true" : "false");
if (sigTime > GetAdjustedTime() + 60 * 60) {
LogPrintf("dseep - Signature rejected, too far into the future %s\n", vin.ToString().c_str());
return;
}
if (sigTime <= GetAdjustedTime() - 60 * 60) {
LogPrintf("dseep - Signature rejected, too far into the past %s - %d %d \n", vin.ToString().c_str(), sigTime, GetAdjustedTime());
return;
}
// see if we have this masternode
LOCK(cs_masternodes);
BOOST_FOREACH(CMasterNode& mn, vecMasternodes) {
if(mn.vin.prevout == vin.prevout) {
// LogPrintf("dseep - Found corresponding mn for vin: %s\n", vin.ToString().c_str());
// take this only if it's newer
if(mn.lastDseep < sigTime){
std::string strMessage = mn.addr.ToString() + boost::lexical_cast<std::string>(sigTime) + boost::lexical_cast<std::string>(stop);
std::string errorMessage = "";
if(!darkSendSigner.VerifyMessage(mn.pubkey2, vchSig, strMessage, errorMessage)){
LogPrintf("dseep - Got bad masternode address signature %s \n", vin.ToString().c_str());
//Misbehaving(pfrom->GetId(), 100);
return;
}
mn.lastDseep = sigTime;
if(!mn.UpdatedWithin(MASTERNODE_MIN_DSEEP_SECONDS)){
mn.UpdateLastSeen();
if(stop) {
mn.Disable();
mn.Check();
}
RelayDarkSendElectionEntryPing(vin, vchSig, sigTime, stop);
}
}
return;
}
}
if(fDebug) LogPrintf("dseep - Couldn't find masternode entry %s\n", vin.ToString().c_str());
std::map<COutPoint, int64_t>::iterator i = askedForMasternodeListEntry.find(vin.prevout);
if (i != askedForMasternodeListEntry.end()){
int64_t t = (*i).second;
if (GetTime() < t) {
// we've asked recently
return;
}
}
// ask for the dsee info once from the node that sent dseep
LogPrintf("dseep - Asking source node for missing entry %s\n", vin.ToString().c_str());
pfrom->PushMessage("dseg", vin);
int64_t askAgain = GetTime()+(60*60*24);
askedForMasternodeListEntry[vin.prevout] = askAgain;
} else if (strCommand == "dseg") { //Get masternode list or specific entry
if(fLiteMode) return; //disable all darksend/masternode related functionality
CTxIn vin;
vRecv >> vin;
if(vin == CTxIn()) { //only should ask for this once
//local network
//Note tor peers show up as local proxied addrs //if(!pfrom->addr.IsRFC1918())//&& !Params().MineBlocksOnDemand())
//{
std::map<CNetAddr, int64_t>::iterator i = askedForMasternodeList.find(pfrom->addr);
if (i != askedForMasternodeList.end())
{
int64_t t = (*i).second;
if (GetTime() < t) {
//Misbehaving(pfrom->GetId(), 34);
//LogPrintf("dseg - peer already asked me for the list\n");
//return;
}
}
int64_t askAgain = GetTime()+(60*60*3);
askedForMasternodeList[pfrom->addr] = askAgain;
//}
} //else, asking for a specific node which is ok
LOCK(cs_masternodes);
int count = vecMasternodes.size();
int i = 0;
BOOST_FOREACH(CMasterNode mn, vecMasternodes) {
if(mn.addr.IsRFC1918()) continue; //local network
if(vin == CTxIn()){
mn.Check();
if(mn.IsEnabled()) {
if(fDebug) LogPrintf("dseg - Sending masternode entry - %s \n", mn.addr.ToString().c_str());
pfrom->PushMessage("dsee", mn.vin, mn.addr, mn.sig, mn.now, mn.pubkey, mn.pubkey2, count, i, mn.lastTimeSeen, mn.protocolVersion);
}
} else if (vin == mn.vin) {
if(fDebug) LogPrintf("dseg - Sending masternode entry - %s \n", mn.addr.ToString().c_str());
pfrom->PushMessage("dsee", mn.vin, mn.addr, mn.sig, mn.now, mn.pubkey, mn.pubkey2, count, i, mn.lastTimeSeen, mn.protocolVersion);
LogPrintf("dseg - Sent 1 masternode entries to %s\n", pfrom->addr.ToString().c_str());
return;
}
i++;
}
LogPrintf("dseg - Sent %d masternode entries to %s\n", count, pfrom->addr.ToString().c_str());
}
else if (strCommand == "mnget") { //Masternode Payments Request Sync
if(fLiteMode) return; //disable all darksend/masternode related functionality
/*if(pfrom->HasFulfilledRequest("mnget")) {
LogPrintf("mnget - peer already asked me for the list\n");
Misbehaving(pfrom->GetId(), 20);
return;
}*/
pfrom->FulfilledRequest("mnget");
masternodePayments.Sync(pfrom);
LogPrintf("mnget - Sent masternode winners to %s\n", pfrom->addr.ToString().c_str());
}
else if (strCommand == "mnw") { //Masternode Payments Declare Winner
//this is required in litemode
CMasternodePaymentWinner winner;
int a = 0;
vRecv >> winner >> a;
if(pindexBest == NULL) return;
uint256 hash = winner.GetHash();
if(mapSeenMasternodeVotes.count(hash)) {
if(fDebug) LogPrintf("mnw - seen vote %s Height %d bestHeight %d\n", hash.ToString().c_str(), winner.nBlockHeight, pindexBest->nHeight);
return;
}
if(winner.nBlockHeight < pindexBest->nHeight - 10 || winner.nBlockHeight > pindexBest->nHeight+20){
LogPrintf("mnw - winner out of range %s Height %d bestHeight %d\n", winner.vin.ToString().c_str(), winner.nBlockHeight, pindexBest->nHeight);
return;
}
if(winner.vin.nSequence != std::numeric_limits<unsigned int>::max()){
LogPrintf("mnw - invalid nSequence\n");
Misbehaving(pfrom->GetId(), 100);
return;
}
LogPrintf("mnw - winning vote %s Height %d bestHeight %d\n", winner.vin.ToString().c_str(), winner.nBlockHeight, pindexBest->nHeight);
if(!masternodePayments.CheckSignature(winner)){
LogPrintf("mnw - invalid signature\n");
Misbehaving(pfrom->GetId(), 100);
return;
}
mapSeenMasternodeVotes.insert(make_pair(hash, winner));
if(masternodePayments.AddWinningMasternode(winner)){
masternodePayments.Relay(winner);
}
}
}
struct CompareValueOnly
{
bool operator()(const pair<int64_t, CTxIn>& t1,
const pair<int64_t, CTxIn>& t2) const
{
return t1.first < t2.first;
}
};
struct CompareValueOnly2
{
bool operator()(const pair<int64_t, int>& t1,
const pair<int64_t, int>& t2) const
{
return t1.first < t2.first;
}
};
int CountMasternodesAboveProtocol(int protocolVersion)
{
int i = 0;
LOCK(cs_masternodes);
BOOST_FOREACH(CMasterNode& mn, vecMasternodes) {
if(mn.protocolVersion < protocolVersion) continue;
i++;
}
return i;
}
int GetMasternodeByVin(CTxIn& vin)
{
int i = 0;
LOCK(cs_masternodes);
BOOST_FOREACH(CMasterNode& mn, vecMasternodes) {
if (mn.vin == vin) return i;
i++;
}
return -1;
}
int GetCurrentMasterNode(int mod, int64_t nBlockHeight, int minProtocol)
{
int i = 0;
unsigned int score = 0;
int winner = -1;
LOCK(cs_masternodes);
// scan for winner
BOOST_FOREACH(CMasterNode mn, vecMasternodes) {
mn.Check();
if(mn.protocolVersion < minProtocol) continue;
if(!mn.IsEnabled()) {
i++;
continue;
}
// calculate the score for each masternode
uint256 n = mn.CalculateScore(mod, nBlockHeight);
unsigned int n2 = 0;
memcpy(&n2, &n, sizeof(n2));
// determine the winner
if(n2 > score){
score = n2;
winner = i;
}
i++;
}
return winner;
}
int GetMasternodeByRank(int findRank, int64_t nBlockHeight, int minProtocol)
{
LOCK(cs_masternodes);
int i = 0;
std::vector<pair<unsigned int, int> > vecMasternodeScores;
i = 0;
BOOST_FOREACH(CMasterNode mn, vecMasternodes) {
mn.Check();
if(mn.protocolVersion < minProtocol) continue;
if(!mn.IsEnabled()) {
i++;
continue;
}
uint256 n = mn.CalculateScore(1, nBlockHeight);
unsigned int n2 = 0;
memcpy(&n2, &n, sizeof(n2));
vecMasternodeScores.push_back(make_pair(n2, i));
i++;
}
sort(vecMasternodeScores.rbegin(), vecMasternodeScores.rend(), CompareValueOnly2());
int rank = 0;
BOOST_FOREACH (PAIRTYPE(unsigned int, int)& s, vecMasternodeScores){
rank++;
if(rank == findRank) return s.second;
}
return -1;
}
int GetMasternodeRank(CTxIn& vin, int64_t nBlockHeight, int minProtocol)
{
LOCK(cs_masternodes);
std::vector<pair<unsigned int, CTxIn> > vecMasternodeScores;
BOOST_FOREACH(CMasterNode& mn, vecMasternodes) {
mn.Check();
if(mn.protocolVersion < minProtocol) continue;
if(!mn.IsEnabled()) {
continue;
}
uint256 n = mn.CalculateScore(1, nBlockHeight);
unsigned int n2 = 0;
memcpy(&n2, &n, sizeof(n2));
vecMasternodeScores.push_back(make_pair(n2, mn.vin));
}
sort(vecMasternodeScores.rbegin(), vecMasternodeScores.rend(), CompareValueOnly());
unsigned int rank = 0;
BOOST_FOREACH (PAIRTYPE(unsigned int, CTxIn)& s, vecMasternodeScores){
rank++;
if(s.second == vin) {
return rank;
}
}
return -1;
}
//Get the last hash that matches the modulus given. Processed in reverse order
bool GetBlockHash(uint256& hash, int nBlockHeight)
{
if (pindexBest == NULL) return false;
if(nBlockHeight == 0)
nBlockHeight = pindexBest->nHeight;
if(mapCacheBlockHashes.count(nBlockHeight)){
hash = mapCacheBlockHashes[nBlockHeight];
return true;
}
const CBlockIndex *BlockLastSolved = pindexBest;
const CBlockIndex *BlockReading = pindexBest;
if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || pindexBest->nHeight+1 < nBlockHeight) return false;
int nBlocksAgo = 0;
if(nBlockHeight > 0) nBlocksAgo = (pindexBest->nHeight+1)-nBlockHeight;
assert(nBlocksAgo >= 0);
int n = 0;
for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
if(n >= nBlocksAgo){
hash = BlockReading->GetBlockHash();
mapCacheBlockHashes[nBlockHeight] = hash;
return true;
}
n++;
if (BlockReading->pprev == NULL) { assert(BlockReading); break; }
BlockReading = BlockReading->pprev;
}
return false;
}
//
// Deterministically calculate a given "score" for a masternode depending on how close it's hash is to
// the proof of work for that block. The further away they are the better, the furthest will win the election
// and get paid this block
//
uint256 CMasterNode::CalculateScore(int mod, int64_t nBlockHeight)
{
if(pindexBest == NULL) return 0;
uint256 hash = 0;
uint256 aux = vin.prevout.hash + vin.prevout.n;
if(!GetBlockHash(hash, nBlockHeight)) return 0;
uint256 hash2 = Hash(BEGIN(hash), END(hash));
uint256 hash3 = Hash(BEGIN(hash), END(aux));
uint256 r = (hash3 > hash2 ? hash3 - hash2 : hash2 - hash3);
return r;
}
void CMasterNode::Check()
{
//once spent, stop doing the checks
if(enabled==3) return;
if(!UpdatedWithin(MASTERNODE_REMOVAL_SECONDS)){
enabled = 4;
return;
}
if(!UpdatedWithin(MASTERNODE_EXPIRATION_SECONDS)){
enabled = 2;
return;
}
if(!unitTest){
CValidationState state;
CTransaction tx = CTransaction();
CTxOut vout = CTxOut(99999*COIN, darkSendPool.collateralPubKey);
tx.vin.push_back(vin);
tx.vout.push_back(vout);
//if(!AcceptableInputs(mempool, state, tx)){
bool* pfMissingInputs = false;
if(!AcceptableInputs(mempool, tx, false, pfMissingInputs)){
enabled = 3;
return;
}
}
enabled = 1; // OK
}
bool CMasternodePayments::CheckSignature(CMasternodePaymentWinner& winner)
{
//note: need to investigate why this is failing
std::string strMessage = winner.vin.ToString().c_str() + boost::lexical_cast<std::string>(winner.nBlockHeight) + winner.payee.ToString();
std::string strPubKey = strMainPubKey ;
CPubKey pubkey(ParseHex(strPubKey));
std::string errorMessage = "";
if(!darkSendSigner.VerifyMessage(pubkey, winner.vchSig, strMessage, errorMessage)){
return false;
}
return true;
}
bool CMasternodePayments::Sign(CMasternodePaymentWinner& winner)
{
std::string strMessage = winner.vin.ToString().c_str() + boost::lexical_cast<std::string>(winner.nBlockHeight) + winner.payee.ToString();
CKey key2;
CPubKey pubkey2;
std::string errorMessage = "";
if(!darkSendSigner.SetKey(strMasterPrivKey, errorMessage, key2, pubkey2))
{
LogPrintf("CMasternodePayments::Sign - ERROR: Invalid masternodeprivkey: '%s'\n", errorMessage.c_str());
return false;
}
if(!darkSendSigner.SignMessage(strMessage, errorMessage, winner.vchSig, key2)) {
LogPrintf("CMasternodePayments::Sign - Sign message failed");
return false;
}
if(!darkSendSigner.VerifyMessage(pubkey2, winner.vchSig, strMessage, errorMessage)) {
LogPrintf("CMasternodePayments::Sign - Verify message failed");
return false;
}
return true;
}
uint64_t CMasternodePayments::CalculateScore(uint256 blockHash, CTxIn& vin)
{
uint256 n1 = blockHash;
uint256 n2 = Hash(BEGIN(n1), END(n1));
uint256 n3 = Hash(BEGIN(vin.prevout.hash), END(vin.prevout.hash));
uint256 n4 = n3 > n2 ? (n3 - n2) : (n2 - n3);
//printf(" -- CMasternodePayments CalculateScore() n2 = %d \n", n2.Get64());
//printf(" -- CMasternodePayments CalculateScore() n3 = %d \n", n3.Get64());
//printf(" -- CMasternodePayments CalculateScore() n4 = %d \n", n4.Get64());
return n4.Get64();
}
bool CMasternodePayments::GetBlockPayee(int nBlockHeight, CScript& payee)
{
BOOST_FOREACH(CMasternodePaymentWinner& winner, vWinning){
if(winner.nBlockHeight == nBlockHeight) {
payee = winner.payee;
return true;
}
}
return false;
}
bool CMasternodePayments::GetWinningMasternode(int nBlockHeight, CTxIn& vinOut)
{
BOOST_FOREACH(CMasternodePaymentWinner& winner, vWinning){
if(winner.nBlockHeight == nBlockHeight) {
vinOut = winner.vin;
return true;
}
}
return false;
}
bool CMasternodePayments::AddWinningMasternode(CMasternodePaymentWinner& winnerIn)
{
uint256 blockHash = 0;
if(!GetBlockHash(blockHash, winnerIn.nBlockHeight-576)) {
return false;
}
winnerIn.score = CalculateScore(blockHash, winnerIn.vin);
bool foundBlock = false;
BOOST_FOREACH(CMasternodePaymentWinner& winner, vWinning){
if(winner.nBlockHeight == winnerIn.nBlockHeight) {
foundBlock = true;
if(winner.score < winnerIn.score){
winner.score = winnerIn.score;
winner.vin = winnerIn.vin;
winner.payee = winnerIn.payee;
winner.vchSig = winnerIn.vchSig;
return true;
}
}
}
// if it's not in the vector
if(!foundBlock){
vWinning.push_back(winnerIn);
mapSeenMasternodeVotes.insert(make_pair(winnerIn.GetHash(), winnerIn));
return true;
}
return false;
}
void CMasternodePayments::CleanPaymentList()
{
LOCK(cs_masternodes);
if(pindexBest == NULL) return;
int nLimit = std::max(((int)vecMasternodes.size())*2, 1000);
vector<CMasternodePaymentWinner>::iterator it;
for(it=vWinning.begin();it<vWinning.end();it++){
if(pindexBest->nHeight - (*it).nBlockHeight > nLimit){
if(fDebug) LogPrintf("CMasternodePayments::CleanPaymentList - Removing old masternode payment - block %d\n", (*it).nBlockHeight);
vWinning.erase(it);
break;
}
}
}
bool CMasternodePayments::ProcessBlock(int nBlockHeight)
{
LOCK(cs_masternodes);
if(!enabled) return false;
CMasternodePaymentWinner winner;
std::vector<CTxIn> vecLastPayments;
int c = 0;
BOOST_REVERSE_FOREACH(CMasternodePaymentWinner& winner, vWinning){
vecLastPayments.push_back(winner.vin);
//if we have one full payment cycle, break
if(++c > (int)vecMasternodes.size()) break;
}
std::random_shuffle ( vecMasternodes.begin(), vecMasternodes.end() );
BOOST_FOREACH(CMasterNode& mn, vecMasternodes) {
bool found = false;
BOOST_FOREACH(CTxIn& vin, vecLastPayments)
if(mn.vin == vin) found = true;
if(found) continue;
mn.Check();
if(!mn.IsEnabled()) {
continue;
}
winner.score = 0;
winner.nBlockHeight = nBlockHeight;
winner.vin = mn.vin;
winner.payee =GetScriptForDestination(mn.pubkey.GetID());
break;
}
//if we can't find someone to get paid, pick randomly
if(winner.nBlockHeight == 0 && vecMasternodes.size() > 0) {
winner.score = 0;
winner.nBlockHeight = nBlockHeight;
winner.vin = vecMasternodes[0].vin;
winner.payee =GetScriptForDestination(vecMasternodes[0].pubkey.GetID());
}
if(Sign(winner)){
if(AddWinningMasternode(winner)){
Relay(winner);
return true;
}
}
return false;
}
void CMasternodePayments::Relay(CMasternodePaymentWinner& winner)
{
CInv inv(MSG_MASTERNODE_WINNER, winner.GetHash());
vector<CInv> vInv;
vInv.push_back(inv);
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes){
pnode->PushMessage("inv", vInv);
}
}
void CMasternodePayments::Sync(CNode* node)
{
int a = 0;
BOOST_FOREACH(CMasternodePaymentWinner& winner, vWinning)
if(winner.nBlockHeight >= pindexBest->nHeight-10 && winner.nBlockHeight <= pindexBest->nHeight + 20)
node->PushMessage("mnw", winner, a);
}
bool CMasternodePayments::SetPrivKey(std::string strPrivKey)
{
CMasternodePaymentWinner winner;
// Test signing successful, proceed
strMasterPrivKey = strPrivKey;
Sign(winner);
if(CheckSignature(winner)){
LogPrintf("CMasternodePayments::SetPrivKey - Successfully initialized as masternode payments master\n");
enabled = true;
return true;
} else {
return false;
}
}