forked from bitcoin/bitcoin
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathprivatesend-client.cpp
1448 lines (1199 loc) · 59.5 KB
/
privatesend-client.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 Dash Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "privatesend-client.h"
#include "wallet/coincontrol.h"
#include "consensus/validation.h"
#include "core_io.h"
#include "init.h"
#include "masternode-sync.h"
#include "masternodeman.h"
#include "netmessagemaker.h"
#include "script/sign.h"
#include "txmempool.h"
#include "util.h"
#include "utilmoneystr.h"
#include <memory>
CPrivateSendClient privateSendClient;
void CPrivateSendClient::ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman)
{
if(fMasternodeMode) return;
if(fLiteMode) return; // ignore all Dash related functionality
if(!masternodeSync.IsBlockchainSynced()) return;
if(strCommand == NetMsgType::DSQUEUE) {
TRY_LOCK(cs_darksend, lockRecv);
if(!lockRecv) return;
if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) {
LogPrint("privatesend", "DSQUEUE -- incompatible version! nVersion: %d\n", pfrom->nVersion);
return;
}
CDarksendQueue dsq;
vRecv >> dsq;
// process every dsq only once
BOOST_FOREACH(CDarksendQueue q, vecDarksendQueue) {
if(q == dsq) {
// LogPrint("privatesend", "DSQUEUE -- %s seen\n", dsq.ToString());
return;
}
}
LogPrint("privatesend", "DSQUEUE -- %s new\n", dsq.ToString());
if(dsq.IsExpired()) return;
masternode_info_t infoMn;
if(!mnodeman.GetMasternodeInfo(dsq.vin.prevout, infoMn)) return;
if(!dsq.CheckSignature(infoMn.pubKeyMasternode)) {
// we probably have outdated info
mnodeman.AskForMN(pfrom, dsq.vin.prevout, connman);
return;
}
// if the queue is ready, submit if we can
if(dsq.fReady) {
if(!infoMixingMasternode.fInfoValid) return;
if(infoMixingMasternode.addr != infoMn.addr) {
LogPrintf("DSQUEUE -- message doesn't match current Masternode: infoMixingMasternode=%s, addr=%s\n", infoMixingMasternode.addr.ToString(), infoMn.addr.ToString());
return;
}
if(nState == POOL_STATE_QUEUE) {
LogPrint("privatesend", "DSQUEUE -- PrivateSend queue (%s) is ready on masternode %s\n", dsq.ToString(), infoMn.addr.ToString());
SubmitDenominate(connman);
}
} else {
BOOST_FOREACH(CDarksendQueue q, vecDarksendQueue) {
if(q.vin == dsq.vin) {
// no way same mn can send another "not yet ready" dsq this soon
LogPrint("privatesend", "DSQUEUE -- Masternode %s is sending WAY too many dsq messages\n", infoMn.addr.ToString());
return;
}
}
int nThreshold = infoMn.nLastDsq + mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION)/5;
LogPrint("privatesend", "DSQUEUE -- nLastDsq: %d threshold: %d nDsqCount: %d\n", infoMn.nLastDsq, nThreshold, mnodeman.nDsqCount);
//don't allow a few nodes to dominate the queuing process
if(infoMn.nLastDsq != 0 && nThreshold > mnodeman.nDsqCount) {
LogPrint("privatesend", "DSQUEUE -- Masternode %s is sending too many dsq messages\n", infoMn.addr.ToString());
return;
}
if(!mnodeman.AllowMixing(dsq.vin.prevout)) return;
LogPrint("privatesend", "DSQUEUE -- new PrivateSend queue (%s) from masternode %s\n", dsq.ToString(), infoMn.addr.ToString());
if(infoMixingMasternode.fInfoValid && infoMixingMasternode.vin.prevout == dsq.vin.prevout) {
dsq.fTried = true;
}
vecDarksendQueue.push_back(dsq);
dsq.Relay(connman);
}
} else if(strCommand == NetMsgType::DSSTATUSUPDATE) {
if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) {
LogPrintf("DSSTATUSUPDATE -- incompatible version! nVersion: %d\n", pfrom->nVersion);
return;
}
if(!infoMixingMasternode.fInfoValid) return;
if(infoMixingMasternode.addr != pfrom->addr) {
//LogPrintf("DSSTATUSUPDATE -- message doesn't match current Masternode: infoMixingMasternode %s addr %s\n", infoMixingMasternode.addr.ToString(), pfrom->addr.ToString());
return;
}
int nMsgSessionID;
int nMsgState;
int nMsgEntriesCount;
int nMsgStatusUpdate;
int nMsgMessageID;
vRecv >> nMsgSessionID >> nMsgState >> nMsgEntriesCount >> nMsgStatusUpdate >> nMsgMessageID;
LogPrint("privatesend", "DSSTATUSUPDATE -- nMsgSessionID %d nMsgState: %d nEntriesCount: %d nMsgStatusUpdate: %d nMsgMessageID %d\n",
nMsgSessionID, nMsgState, nEntriesCount, nMsgStatusUpdate, nMsgMessageID);
if(nMsgState < POOL_STATE_MIN || nMsgState > POOL_STATE_MAX) {
LogPrint("privatesend", "DSSTATUSUPDATE -- nMsgState is out of bounds: %d\n", nMsgState);
return;
}
if(nMsgStatusUpdate < STATUS_REJECTED || nMsgStatusUpdate > STATUS_ACCEPTED) {
LogPrint("privatesend", "DSSTATUSUPDATE -- nMsgStatusUpdate is out of bounds: %d\n", nMsgStatusUpdate);
return;
}
if(nMsgMessageID < MSG_POOL_MIN || nMsgMessageID > MSG_POOL_MAX) {
LogPrint("privatesend", "DSSTATUSUPDATE -- nMsgMessageID is out of bounds: %d\n", nMsgMessageID);
return;
}
LogPrint("privatesend", "DSSTATUSUPDATE -- GetMessageByID: %s\n", CPrivateSend::GetMessageByID(PoolMessage(nMsgMessageID)));
if(!CheckPoolStateUpdate(PoolState(nMsgState), nMsgEntriesCount, PoolStatusUpdate(nMsgStatusUpdate), PoolMessage(nMsgMessageID), nMsgSessionID)) {
LogPrint("privatesend", "DSSTATUSUPDATE -- CheckPoolStateUpdate failed\n");
}
} else if(strCommand == NetMsgType::DSFINALTX) {
if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) {
LogPrintf("DSFINALTX -- incompatible version! nVersion: %d\n", pfrom->nVersion);
return;
}
if(!infoMixingMasternode.fInfoValid) return;
if(infoMixingMasternode.addr != pfrom->addr) {
//LogPrintf("DSFINALTX -- message doesn't match current Masternode: infoMixingMasternode %s addr %s\n", infoMixingMasternode.addr.ToString(), pfrom->addr.ToString());
return;
}
int nMsgSessionID;
vRecv >> nMsgSessionID;
CTransaction txNew(deserialize, vRecv);
if(nSessionID != nMsgSessionID) {
LogPrint("privatesend", "DSFINALTX -- message doesn't match current PrivateSend session: nSessionID: %d nMsgSessionID: %d\n", nSessionID, nMsgSessionID);
return;
}
LogPrint("privatesend", "DSFINALTX -- txNew %s", txNew.ToString());
//check to see if input is spent already? (and probably not confirmed)
SignFinalTransaction(txNew, pfrom, connman);
} else if(strCommand == NetMsgType::DSCOMPLETE) {
if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) {
LogPrintf("DSCOMPLETE -- incompatible version! nVersion: %d\n", pfrom->nVersion);
return;
}
if(!infoMixingMasternode.fInfoValid) return;
if(infoMixingMasternode.addr != pfrom->addr) {
LogPrint("privatesend", "DSCOMPLETE -- message doesn't match current Masternode: infoMixingMasternode=%s addr=%s\n", infoMixingMasternode.addr.ToString(), pfrom->addr.ToString());
return;
}
int nMsgSessionID;
int nMsgMessageID;
vRecv >> nMsgSessionID >> nMsgMessageID;
if(nMsgMessageID < MSG_POOL_MIN || nMsgMessageID > MSG_POOL_MAX) {
LogPrint("privatesend", "DSCOMPLETE -- nMsgMessageID is out of bounds: %d\n", nMsgMessageID);
return;
}
if(nSessionID != nMsgSessionID) {
LogPrint("privatesend", "DSCOMPLETE -- message doesn't match current PrivateSend session: nSessionID: %d nMsgSessionID: %d\n", nSessionID, nMsgSessionID);
return;
}
LogPrint("privatesend", "DSCOMPLETE -- nMsgSessionID %d nMsgMessageID %d (%s)\n", nMsgSessionID, nMsgMessageID, CPrivateSend::GetMessageByID(PoolMessage(nMsgMessageID)));
CompletedTransaction(PoolMessage(nMsgMessageID));
}
}
void CPrivateSendClient::ResetPool()
{
nCachedLastSuccessBlock = 0;
txMyCollateral = CMutableTransaction();
vecMasternodesUsed.clear();
UnlockCoins();
keyHolderStorage.ReturnAll();
SetNull();
}
void CPrivateSendClient::SetNull()
{
// Client side
nEntriesCount = 0;
fLastEntryAccepted = false;
infoMixingMasternode = masternode_info_t();
{
LOCK(cs_dsaQueue);
dsaQueue.clear();
}
CPrivateSendBase::SetNull();
}
//
// Unlock coins after mixing fails or succeeds
//
void CPrivateSendClient::UnlockCoins()
{
while(true) {
TRY_LOCK(pwalletMain->cs_wallet, lockWallet);
if(!lockWallet) {MilliSleep(50); continue;}
BOOST_FOREACH(COutPoint outpoint, vecOutPointLocked)
pwalletMain->UnlockCoin(outpoint);
break;
}
vecOutPointLocked.clear();
}
std::string CPrivateSendClient::GetStatus()
{
static int nStatusMessageProgress = 0;
nStatusMessageProgress += 10;
std::string strSuffix = "";
if(WaitForAnotherBlock() || !masternodeSync.IsBlockchainSynced())
return strAutoDenomResult;
switch(nState) {
case POOL_STATE_IDLE:
return _("PrivateSend is idle.");
case POOL_STATE_QUEUE:
if( nStatusMessageProgress % 70 <= 30) strSuffix = ".";
else if(nStatusMessageProgress % 70 <= 50) strSuffix = "..";
else if(nStatusMessageProgress % 70 <= 70) strSuffix = "...";
return strprintf(_("Submitted to masternode, waiting in queue %s"), strSuffix);;
case POOL_STATE_ACCEPTING_ENTRIES:
if(nEntriesCount == 0) {
nStatusMessageProgress = 0;
return strAutoDenomResult;
} else if(fLastEntryAccepted) {
if(nStatusMessageProgress % 10 > 8) {
fLastEntryAccepted = false;
nStatusMessageProgress = 0;
}
return _("PrivateSend request complete:") + " " + _("Your transaction was accepted into the pool!");
} else {
if( nStatusMessageProgress % 70 <= 40) return strprintf(_("Submitted following entries to masternode: %u / %d"), nEntriesCount, CPrivateSend::GetMaxPoolTransactions());
else if(nStatusMessageProgress % 70 <= 50) strSuffix = ".";
else if(nStatusMessageProgress % 70 <= 60) strSuffix = "..";
else if(nStatusMessageProgress % 70 <= 70) strSuffix = "...";
return strprintf(_("Submitted to masternode, waiting for more entries ( %u / %d ) %s"), nEntriesCount, CPrivateSend::GetMaxPoolTransactions(), strSuffix);
}
case POOL_STATE_SIGNING:
if( nStatusMessageProgress % 70 <= 40) return _("Found enough users, signing ...");
else if(nStatusMessageProgress % 70 <= 50) strSuffix = ".";
else if(nStatusMessageProgress % 70 <= 60) strSuffix = "..";
else if(nStatusMessageProgress % 70 <= 70) strSuffix = "...";
return strprintf(_("Found enough users, signing ( waiting %s )"), strSuffix);
case POOL_STATE_ERROR:
return _("PrivateSend request incomplete:") + " " + strLastMessage + " " + _("Will retry...");
case POOL_STATE_SUCCESS:
return _("PrivateSend request complete:") + " " + strLastMessage;
default:
return strprintf(_("Unknown state: id = %u"), nState);
}
}
bool CPrivateSendClient::GetMixingMasternodeInfo(masternode_info_t& mnInfoRet)
{
mnInfoRet = infoMixingMasternode.fInfoValid ? infoMixingMasternode : masternode_info_t();
return infoMixingMasternode.fInfoValid;
}
bool CPrivateSendClient::IsMixingMasternode(const CNode* pnode)
{
return infoMixingMasternode.fInfoValid && pnode->addr == infoMixingMasternode.addr;
}
//
// Check the mixing progress and send client updates if a Masternode
//
void CPrivateSendClient::CheckPool()
{
// reset if we're here for 10 seconds
if((nState == POOL_STATE_ERROR || nState == POOL_STATE_SUCCESS) && GetTimeMillis() - nTimeLastSuccessfulStep >= 10000) {
LogPrint("privatesend", "CPrivateSendClient::CheckPool -- timeout, RESETTING\n");
UnlockCoins();
if (nState == POOL_STATE_ERROR) {
keyHolderStorage.ReturnAll();
} else {
keyHolderStorage.KeepAll();
}
SetNull();
}
}
//
// Check for various timeouts (queue objects, mixing, etc)
//
void CPrivateSendClient::CheckTimeout()
{
CheckQueue();
if(!fEnablePrivateSend && !fMasternodeMode) return;
// catching hanging sessions
if(!fMasternodeMode) {
switch(nState) {
case POOL_STATE_ERROR:
LogPrint("privatesend", "CPrivateSendClient::CheckTimeout -- Pool error -- Running CheckPool\n");
CheckPool();
break;
case POOL_STATE_SUCCESS:
LogPrint("privatesend", "CPrivateSendClient::CheckTimeout -- Pool success -- Running CheckPool\n");
CheckPool();
break;
default:
break;
}
}
int nLagTime = fMasternodeMode ? 0 : 10000; // if we're the client, give the server a few extra seconds before resetting.
int nTimeout = (nState == POOL_STATE_SIGNING) ? PRIVATESEND_SIGNING_TIMEOUT : PRIVATESEND_QUEUE_TIMEOUT;
bool fTimeout = GetTimeMillis() - nTimeLastSuccessfulStep >= nTimeout*1000 + nLagTime;
if(nState != POOL_STATE_IDLE && fTimeout) {
LogPrint("privatesend", "CPrivateSendClient::CheckTimeout -- %s timed out (%ds) -- restting\n",
(nState == POOL_STATE_SIGNING) ? "Signing" : "Session", nTimeout);
UnlockCoins();
keyHolderStorage.ReturnAll();
SetNull();
SetState(POOL_STATE_ERROR);
strLastMessage = _("Session timed out.");
}
}
//
// Execute a mixing denomination via a Masternode.
// This is only ran from clients
//
bool CPrivateSendClient::SendDenominate(const std::vector<CTxDSIn>& vecTxDSIn, const std::vector<CTxOut>& vecTxOut, CConnman& connman)
{
if(fMasternodeMode) {
LogPrintf("CPrivateSendClient::SendDenominate -- PrivateSend from a Masternode is not supported currently.\n");
return false;
}
if(txMyCollateral == CMutableTransaction()) {
LogPrintf("CPrivateSendClient:SendDenominate -- PrivateSend collateral not set\n");
return false;
}
// lock the funds we're going to use
BOOST_FOREACH(CTxIn txin, txMyCollateral.vin)
vecOutPointLocked.push_back(txin.prevout);
for (const auto& txdsin : vecTxDSIn)
vecOutPointLocked.push_back(txdsin.prevout);
// we should already be connected to a Masternode
if(!nSessionID) {
LogPrintf("CPrivateSendClient::SendDenominate -- No Masternode has been selected yet.\n");
UnlockCoins();
keyHolderStorage.ReturnAll();
SetNull();
return false;
}
if(!CheckDiskSpace()) {
UnlockCoins();
keyHolderStorage.ReturnAll();
SetNull();
fEnablePrivateSend = false;
LogPrintf("CPrivateSendClient::SendDenominate -- Not enough disk space, disabling PrivateSend.\n");
return false;
}
SetState(POOL_STATE_ACCEPTING_ENTRIES);
strLastMessage = "";
LogPrintf("CPrivateSendClient::SendDenominate -- Added transaction to pool.\n");
//check it against the memory pool to make sure it's valid
{
CValidationState validationState;
CMutableTransaction tx;
for (const auto& txdsin : vecTxDSIn) {
LogPrint("privatesend", "CPrivateSendClient::SendDenominate -- txdsin=%s\n", txdsin.ToString());
tx.vin.push_back(txdsin);
}
BOOST_FOREACH(const CTxOut& txout, vecTxOut) {
LogPrint("privatesend", "CPrivateSendClient::SendDenominate -- txout=%s\n", txout.ToString());
tx.vout.push_back(txout);
}
LogPrintf("CPrivateSendClient::SendDenominate -- Submitting partial tx %s", tx.ToString());
mempool.PrioritiseTransaction(tx.GetHash(), tx.GetHash().ToString(), 1000, 0.1*COIN);
TRY_LOCK(cs_main, lockMain);
if(!lockMain || !AcceptToMemoryPool(mempool, validationState, MakeTransactionRef(tx), false, NULL, false, maxTxFee, true)) {
LogPrintf("CPrivateSendClient::SendDenominate -- AcceptToMemoryPool() failed! tx=%s", tx.ToString());
UnlockCoins();
keyHolderStorage.ReturnAll();
SetNull();
return false;
}
}
// store our entry for later use
CDarkSendEntry entry(vecTxDSIn, vecTxOut, txMyCollateral);
vecEntries.push_back(entry);
RelayIn(entry, connman);
nTimeLastSuccessfulStep = GetTimeMillis();
return true;
}
// Incoming message from Masternode updating the progress of mixing
bool CPrivateSendClient::CheckPoolStateUpdate(PoolState nStateNew, int nEntriesCountNew, PoolStatusUpdate nStatusUpdate, PoolMessage nMessageID, int nSessionIDNew)
{
if(fMasternodeMode) return false;
// do not update state when mixing client state is one of these
if(nState == POOL_STATE_IDLE || nState == POOL_STATE_ERROR || nState == POOL_STATE_SUCCESS) return false;
strAutoDenomResult = _("Masternode:") + " " + CPrivateSend::GetMessageByID(nMessageID);
// if rejected at any state
if(nStatusUpdate == STATUS_REJECTED) {
LogPrintf("CPrivateSendClient::CheckPoolStateUpdate -- entry is rejected by Masternode\n");
UnlockCoins();
keyHolderStorage.ReturnAll();
SetNull();
SetState(POOL_STATE_ERROR);
strLastMessage = CPrivateSend::GetMessageByID(nMessageID);
return true;
}
if(nStatusUpdate == STATUS_ACCEPTED && nState == nStateNew) {
if(nStateNew == POOL_STATE_QUEUE && nSessionID == 0 && nSessionIDNew != 0) {
// new session id should be set only in POOL_STATE_QUEUE state
nSessionID = nSessionIDNew;
nTimeLastSuccessfulStep = GetTimeMillis();
LogPrintf("CPrivateSendClient::CheckPoolStateUpdate -- set nSessionID to %d\n", nSessionID);
return true;
}
else if(nStateNew == POOL_STATE_ACCEPTING_ENTRIES && nEntriesCount != nEntriesCountNew) {
nEntriesCount = nEntriesCountNew;
nTimeLastSuccessfulStep = GetTimeMillis();
fLastEntryAccepted = true;
LogPrintf("CPrivateSendClient::CheckPoolStateUpdate -- new entry accepted!\n");
return true;
}
}
// only situations above are allowed, fail in any other case
return false;
}
//
// After we receive the finalized transaction from the Masternode, we must
// check it to make sure it's what we want, then sign it if we agree.
// If we refuse to sign, it's possible we'll be charged collateral
//
bool CPrivateSendClient::SignFinalTransaction(const CTransaction& finalTransactionNew, CNode* pnode, CConnman& connman)
{
if(fMasternodeMode || pnode == NULL) return false;
finalMutableTransaction = finalTransactionNew;
LogPrintf("CPrivateSendClient::SignFinalTransaction -- finalMutableTransaction=%s", finalMutableTransaction.ToString());
// Make sure it's BIP69 compliant
sort(finalMutableTransaction.vin.begin(), finalMutableTransaction.vin.end(), CompareInputBIP69());
sort(finalMutableTransaction.vout.begin(), finalMutableTransaction.vout.end(), CompareOutputBIP69());
if(finalMutableTransaction.GetHash() != finalTransactionNew.GetHash()) {
LogPrintf("CPrivateSendClient::SignFinalTransaction -- WARNING! Masternode %s is not BIP69 compliant!\n", infoMixingMasternode.vin.prevout.ToStringShort());
UnlockCoins();
keyHolderStorage.ReturnAll();
SetNull();
return false;
}
std::vector<CTxIn> sigs;
//make sure my inputs/outputs are present, otherwise refuse to sign
BOOST_FOREACH(const CDarkSendEntry entry, vecEntries) {
BOOST_FOREACH(const CTxDSIn txdsin, entry.vecTxDSIn) {
/* Sign my transaction and all outputs */
int nMyInputIndex = -1;
CScript prevPubKey = CScript();
CTxIn txin = CTxIn();
for(unsigned int i = 0; i < finalMutableTransaction.vin.size(); i++) {
if(finalMutableTransaction.vin[i] == txdsin) {
nMyInputIndex = i;
prevPubKey = txdsin.prevPubKey;
txin = txdsin;
}
}
if(nMyInputIndex >= 0) { //might have to do this one input at a time?
int nFoundOutputsCount = 0;
CAmount nValue1 = 0;
CAmount nValue2 = 0;
for (const auto& txoutFinal : finalMutableTransaction.vout) {
for (const auto& txout: entry.vecTxOut) {
if(txoutFinal == txout) {
nFoundOutputsCount++;
nValue1 += txoutFinal.nValue;
}
}
}
for (const auto& txout : entry.vecTxOut)
nValue2 += txout.nValue;
int nTargetOuputsCount = entry.vecTxOut.size();
if(nFoundOutputsCount < nTargetOuputsCount || nValue1 != nValue2) {
// in this case, something went wrong and we'll refuse to sign. It's possible we'll be charged collateral. But that's
// better then signing if the transaction doesn't look like what we wanted.
LogPrintf("CPrivateSendClient::SignFinalTransaction -- My entries are not correct! Refusing to sign: nFoundOutputsCount: %d, nTargetOuputsCount: %d\n", nFoundOutputsCount, nTargetOuputsCount);
UnlockCoins();
keyHolderStorage.ReturnAll();
SetNull();
return false;
}
const CKeyStore& keystore = *pwalletMain;
LogPrint("privatesend", "CPrivateSendClient::SignFinalTransaction -- Signing my input %i\n", nMyInputIndex);
if(!SignSignature(keystore, prevPubKey, finalMutableTransaction, nMyInputIndex, int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))) { // changes scriptSig
LogPrint("privatesend", "CPrivateSendClient::SignFinalTransaction -- Unable to sign my own transaction!\n");
// not sure what to do here, it will timeout...?
}
sigs.push_back(finalMutableTransaction.vin[nMyInputIndex]);
LogPrint("privatesend", "CPrivateSendClient::SignFinalTransaction -- nMyInputIndex: %d, sigs.size(): %d, scriptSig=%s\n", nMyInputIndex, (int)sigs.size(), ScriptToAsmStr(finalMutableTransaction.vin[nMyInputIndex].scriptSig));
}
}
}
if(sigs.empty()) {
LogPrintf("CPrivateSendClient::SignFinalTransaction -- can't sign anything!\n");
UnlockCoins();
keyHolderStorage.ReturnAll();
SetNull();
return false;
}
// push all of our signatures to the Masternode
LogPrintf("CPrivateSendClient::SignFinalTransaction -- pushing sigs to the masternode, finalMutableTransaction=%s", finalMutableTransaction.ToString());
CNetMsgMaker msgMaker(pnode->GetSendVersion());
connman.PushMessage(pnode, msgMaker.Make(NetMsgType::DSSIGNFINALTX, sigs));
SetState(POOL_STATE_SIGNING);
nTimeLastSuccessfulStep = GetTimeMillis();
return true;
}
// mixing transaction was completed (failed or successful)
void CPrivateSendClient::CompletedTransaction(PoolMessage nMessageID)
{
if(fMasternodeMode) return;
if(nMessageID == MSG_SUCCESS) {
LogPrintf("CompletedTransaction -- success\n");
nCachedLastSuccessBlock = nCachedBlockHeight;
keyHolderStorage.KeepAll();
} else {
LogPrintf("CompletedTransaction -- error\n");
keyHolderStorage.ReturnAll();
}
UnlockCoins();
SetNull();
strLastMessage = CPrivateSend::GetMessageByID(nMessageID);
}
bool CPrivateSendClient::WaitForAnotherBlock()
{
if(!masternodeSync.IsMasternodeListSynced())
return true;
if(fPrivateSendMultiSession)
return false;
return nCachedBlockHeight - nCachedLastSuccessBlock < nMinBlocksToWait;
}
bool CPrivateSendClient::CheckAutomaticBackup()
{
switch(nWalletBackups) {
case 0:
LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- Automatic backups disabled, no mixing available.\n");
strAutoDenomResult = _("Automatic backups disabled") + ", " + _("no mixing available.");
fEnablePrivateSend = false; // stop mixing
pwalletMain->nKeysLeftSinceAutoBackup = 0; // no backup, no "keys since last backup"
return false;
case -1:
// Automatic backup failed, nothing else we can do until user fixes the issue manually.
// There is no way to bring user attention in daemon mode so we just update status and
// keep spaming if debug is on.
LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- ERROR! Failed to create automatic backup.\n");
strAutoDenomResult = _("ERROR! Failed to create automatic backup") + ", " + _("see debug.log for details.");
return false;
case -2:
// We were able to create automatic backup but keypool was not replenished because wallet is locked.
// There is no way to bring user attention in daemon mode so we just update status and
// keep spaming if debug is on.
LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- WARNING! Failed to create replenish keypool, please unlock your wallet to do so.\n");
strAutoDenomResult = _("WARNING! Failed to replenish keypool, please unlock your wallet to do so.") + ", " + _("see debug.log for details.");
return false;
}
if(pwalletMain->nKeysLeftSinceAutoBackup < PRIVATESEND_KEYS_THRESHOLD_STOP) {
// We should never get here via mixing itself but probably smth else is still actively using keypool
LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- Very low number of keys left: %d, no mixing available.\n", pwalletMain->nKeysLeftSinceAutoBackup);
strAutoDenomResult = strprintf(_("Very low number of keys left: %d") + ", " + _("no mixing available."), pwalletMain->nKeysLeftSinceAutoBackup);
// It's getting really dangerous, stop mixing
fEnablePrivateSend = false;
return false;
} else if(pwalletMain->nKeysLeftSinceAutoBackup < PRIVATESEND_KEYS_THRESHOLD_WARNING) {
// Low number of keys left but it's still more or less safe to continue
LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- Very low number of keys left: %d\n", pwalletMain->nKeysLeftSinceAutoBackup);
strAutoDenomResult = strprintf(_("Very low number of keys left: %d"), pwalletMain->nKeysLeftSinceAutoBackup);
if(fCreateAutoBackups) {
LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- Trying to create new backup.\n");
std::string warningString;
std::string errorString;
if(!AutoBackupWallet(pwalletMain, "", warningString, errorString)) {
if(!warningString.empty()) {
// There were some issues saving backup but yet more or less safe to continue
LogPrintf("CPrivateSendClient::CheckAutomaticBackup -- WARNING! Something went wrong on automatic backup: %s\n", warningString);
}
if(!errorString.empty()) {
// Things are really broken
LogPrintf("CPrivateSendClient::CheckAutomaticBackup -- ERROR! Failed to create automatic backup: %s\n", errorString);
strAutoDenomResult = strprintf(_("ERROR! Failed to create automatic backup") + ": %s", errorString);
return false;
}
}
} else {
// Wait for smth else (e.g. GUI action) to create automatic backup for us
return false;
}
}
LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- Keys left since latest backup: %d\n", pwalletMain->nKeysLeftSinceAutoBackup);
return true;
}
//
// Passively run mixing in the background to anonymize funds based on the given configuration.
//
bool CPrivateSendClient::DoAutomaticDenominating(CConnman& connman, bool fDryRun)
{
if(fMasternodeMode) return false; // no client-side mixing on masternodes
if(!fEnablePrivateSend) return false;
if(!pwalletMain || pwalletMain->IsLocked(true)) return false;
if(nState != POOL_STATE_IDLE) return false;
if(!masternodeSync.IsMasternodeListSynced()) {
strAutoDenomResult = _("Can't mix while sync in progress.");
return false;
}
if(!CheckAutomaticBackup())
return false;
if(GetEntriesCount() > 0) {
strAutoDenomResult = _("Mixing in progress...");
return false;
}
TRY_LOCK(cs_darksend, lockDS);
if(!lockDS) {
strAutoDenomResult = _("Lock is already in place.");
return false;
}
if(!fDryRun && pwalletMain->IsLocked(true)) {
strAutoDenomResult = _("Wallet is locked.");
return false;
}
if(WaitForAnotherBlock()) {
LogPrintf("CPrivateSendClient::DoAutomaticDenominating -- Last successful PrivateSend action was too recent\n");
strAutoDenomResult = _("Last successful PrivateSend action was too recent.");
return false;
}
if(mnodeman.size() == 0) {
LogPrint("privatesend", "CPrivateSendClient::DoAutomaticDenominating -- No Masternodes detected\n");
strAutoDenomResult = _("No Masternodes detected.");
return false;
}
CAmount nValueMin = CPrivateSend::GetSmallestDenomination();
// if there are no confirmed DS collateral inputs yet
if(!pwalletMain->HasCollateralInputs()) {
// should have some additional amount for them
nValueMin += CPrivateSend::GetMaxCollateralAmount();
}
// including denoms but applying some restrictions
CAmount nBalanceNeedsAnonymized = pwalletMain->GetNeedsToBeAnonymizedBalance(nValueMin);
// anonymizable balance is way too small
if(nBalanceNeedsAnonymized < nValueMin) {
LogPrintf("CPrivateSendClient::DoAutomaticDenominating -- Not enough funds to anonymize\n");
strAutoDenomResult = _("Not enough funds to anonymize.");
return false;
}
// excluding denoms
CAmount nBalanceAnonimizableNonDenom = pwalletMain->GetAnonymizableBalance(true);
// denoms
CAmount nBalanceDenominatedConf = pwalletMain->GetDenominatedBalance();
CAmount nBalanceDenominatedUnconf = pwalletMain->GetDenominatedBalance(true);
CAmount nBalanceDenominated = nBalanceDenominatedConf + nBalanceDenominatedUnconf;
LogPrint("privatesend", "CPrivateSendClient::DoAutomaticDenominating -- nValueMin: %f, nBalanceNeedsAnonymized: %f, nBalanceAnonimizableNonDenom: %f, nBalanceDenominatedConf: %f, nBalanceDenominatedUnconf: %f, nBalanceDenominated: %f\n",
(float)nValueMin/COIN,
(float)nBalanceNeedsAnonymized/COIN,
(float)nBalanceAnonimizableNonDenom/COIN,
(float)nBalanceDenominatedConf/COIN,
(float)nBalanceDenominatedUnconf/COIN,
(float)nBalanceDenominated/COIN);
if(fDryRun) return true;
// Check if we have should create more denominated inputs i.e.
// there are funds to denominate and denominated balance does not exceed
// max amount to mix yet.
if(nBalanceAnonimizableNonDenom >= nValueMin + CPrivateSend::GetCollateralAmount() && nBalanceDenominated < nPrivateSendAmount*COIN)
return CreateDenominated(connman);
//check if we have the collateral sized inputs
if(!pwalletMain->HasCollateralInputs())
return !pwalletMain->HasCollateralInputs(false) && MakeCollateralAmounts(connman);
if(nSessionID) {
strAutoDenomResult = _("Mixing in progress...");
return false;
}
// Initial phase, find a Masternode
// Clean if there is anything left from previous session
UnlockCoins();
keyHolderStorage.ReturnAll();
SetNull();
// should be no unconfirmed denoms in non-multi-session mode
if(!fPrivateSendMultiSession && nBalanceDenominatedUnconf > 0) {
LogPrintf("CPrivateSendClient::DoAutomaticDenominating -- Found unconfirmed denominated outputs, will wait till they confirm to continue.\n");
strAutoDenomResult = _("Found unconfirmed denominated outputs, will wait till they confirm to continue.");
return false;
}
//check our collateral and create new if needed
std::string strReason;
if(txMyCollateral == CMutableTransaction()) {
if(!pwalletMain->CreateCollateralTransaction(txMyCollateral, strReason)) {
LogPrintf("CPrivateSendClient::DoAutomaticDenominating -- create collateral error:%s\n", strReason);
return false;
}
} else {
if(!CPrivateSend::IsCollateralValid(txMyCollateral)) {
LogPrintf("CPrivateSendClient::DoAutomaticDenominating -- invalid collateral, recreating...\n");
if(!pwalletMain->CreateCollateralTransaction(txMyCollateral, strReason)) {
LogPrintf("CPrivateSendClient::DoAutomaticDenominating -- create collateral error: %s\n", strReason);
return false;
}
}
}
int nMnCountEnabled = mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION);
// If we've used 90% of the Masternode list then drop the oldest first ~30%
int nThreshold_high = nMnCountEnabled * 0.9;
int nThreshold_low = nThreshold_high * 0.7;
LogPrint("privatesend", "Checking vecMasternodesUsed: size: %d, threshold: %d\n", (int)vecMasternodesUsed.size(), nThreshold_high);
if((int)vecMasternodesUsed.size() > nThreshold_high) {
vecMasternodesUsed.erase(vecMasternodesUsed.begin(), vecMasternodesUsed.begin() + vecMasternodesUsed.size() - nThreshold_low);
LogPrint("privatesend", " vecMasternodesUsed: new size: %d, threshold: %d\n", (int)vecMasternodesUsed.size(), nThreshold_high);
}
bool fUseQueue = GetRandInt(100) > 33;
// don't use the queues all of the time for mixing unless we are a liquidity provider
if((nLiquidityProvider || fUseQueue) && JoinExistingQueue(nBalanceNeedsAnonymized, connman))
return true;
// do not initiate queue if we are a liquidity provider to avoid useless inter-mixing
if(nLiquidityProvider) return false;
if(StartNewQueue(nValueMin, nBalanceNeedsAnonymized, connman))
return true;
strAutoDenomResult = _("No compatible Masternode found.");
return false;
}
bool CPrivateSendClient::JoinExistingQueue(CAmount nBalanceNeedsAnonymized, CConnman& connman)
{
std::vector<CAmount> vecStandardDenoms = CPrivateSend::GetStandardDenominations();
// Look through the queues and see if anything matches
BOOST_FOREACH(CDarksendQueue& dsq, vecDarksendQueue) {
// only try each queue once
if(dsq.fTried) continue;
dsq.fTried = true;
if(dsq.IsExpired()) continue;
masternode_info_t infoMn;
if(!mnodeman.GetMasternodeInfo(dsq.vin.prevout, infoMn)) {
LogPrintf("CPrivateSendClient::JoinExistingQueue -- dsq masternode is not in masternode list, masternode=%s\n", dsq.vin.prevout.ToStringShort());
continue;
}
if(infoMn.nProtocolVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) continue;
std::vector<int> vecBits;
if(!CPrivateSend::GetDenominationsBits(dsq.nDenom, vecBits)) {
// incompatible denom
continue;
}
// mixing rate limit i.e. nLastDsq check should already pass in DSQUEUE ProcessMessage
// in order for dsq to get into vecDarksendQueue, so we should be safe to mix already,
// no need for additional verification here
LogPrint("privatesend", "CPrivateSendClient::JoinExistingQueue -- found valid queue: %s\n", dsq.ToString());
CAmount nValueInTmp = 0;
std::vector<CTxDSIn> vecTxDSInTmp;
std::vector<COutput> vCoinsTmp;
// Try to match their denominations if possible, select at least 1 denominations
if(!pwalletMain->SelectCoinsByDenominations(dsq.nDenom, vecStandardDenoms[vecBits.front()], nBalanceNeedsAnonymized, vecTxDSInTmp, vCoinsTmp, nValueInTmp, 0, nPrivateSendRounds)) {
LogPrintf("CPrivateSendClient::JoinExistingQueue -- Couldn't match denominations %d %d (%s)\n", vecBits.front(), dsq.nDenom, CPrivateSend::GetDenominationsToString(dsq.nDenom));
continue;
}
vecMasternodesUsed.push_back(dsq.vin.prevout);
if (connman.IsMasternodeOrDisconnectRequested(infoMn.addr)) {
LogPrintf("CPrivateSendClient::JoinExistingQueue -- skipping masternode connection, addr=%s\n", infoMn.addr.ToString());
continue;
}
nSessionDenom = dsq.nDenom;
infoMixingMasternode = infoMn;
{
LOCK(cs_dsaQueue);
dsaQueue.push_back(std::make_pair(GetTime(), std::make_pair(infoMn.addr, CDarksendAccept(nSessionDenom, txMyCollateral))));
}
connman.AddPendingMasternode(infoMn.addr);
SetState(POOL_STATE_QUEUE);
nTimeLastSuccessfulStep = GetTimeMillis();
LogPrintf("CPrivateSendClient::JoinExistingQueue -- connecting (from queue): nSessionDenom: %d (%s), addr=%s\n",
nSessionDenom, CPrivateSend::GetDenominationsToString(nSessionDenom), infoMn.addr.ToString());
strAutoDenomResult = _("Mixing in progress...");
return true;
}
strAutoDenomResult = _("Failed to join existing mixing queues");
return false;
}
bool CPrivateSendClient::StartNewQueue(CAmount nValueMin, CAmount nBalanceNeedsAnonymized, CConnman& connman)
{
int nTries = 0;
int nMnCountEnabled = mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION);
// ** find the coins we'll use
std::vector<CTxIn> vecTxIn;
CAmount nValueInTmp = 0;
if(!pwalletMain->SelectCoinsDark(nValueMin, nBalanceNeedsAnonymized, vecTxIn, nValueInTmp, 0, nPrivateSendRounds)) {
// this should never happen
LogPrintf("CPrivateSendClient::StartNewQueue -- Can't mix: no compatible inputs found!\n");
strAutoDenomResult = _("Can't mix: no compatible inputs found!");
return false;
}
// otherwise, try one randomly
while(nTries < 10) {
masternode_info_t infoMn = mnodeman.FindRandomNotInVec(vecMasternodesUsed, MIN_PRIVATESEND_PEER_PROTO_VERSION);
if(!infoMn.fInfoValid) {
LogPrintf("CPrivateSendClient::StartNewQueue -- Can't find random masternode!\n");
strAutoDenomResult = _("Can't find random Masternode.");
return false;
}
vecMasternodesUsed.push_back(infoMn.vin.prevout);
if(infoMn.nLastDsq != 0 && infoMn.nLastDsq + nMnCountEnabled/5 > mnodeman.nDsqCount) {
LogPrintf("CPrivateSendClient::StartNewQueue -- Too early to mix on this masternode!"
" masternode=%s addr=%s nLastDsq=%d CountEnabled/5=%d nDsqCount=%d\n",
infoMn.vin.prevout.ToStringShort(), infoMn.addr.ToString(), infoMn.nLastDsq,
nMnCountEnabled/5, mnodeman.nDsqCount);
nTries++;
continue;
}
if (connman.IsMasternodeOrDisconnectRequested(infoMn.addr)) {
LogPrintf("CPrivateSendClient::StartNewQueue -- skipping masternode connection, addr=%s\n", infoMn.addr.ToString());
nTries++;
continue;
}
LogPrintf("CPrivateSendClient::StartNewQueue -- attempt %d connection to Masternode %s\n", nTries, infoMn.addr.ToString());
std::vector<CAmount> vecAmounts;
pwalletMain->ConvertList(vecTxIn, vecAmounts);
// try to get a single random denom out of vecAmounts
while(nSessionDenom == 0) {
nSessionDenom = CPrivateSend::GetDenominationsByAmounts(vecAmounts);
}
infoMixingMasternode = infoMn;
connman.AddPendingMasternode(infoMn.addr);
{
LOCK(cs_dsaQueue);
dsaQueue.push_back(std::make_pair(GetTime(), std::make_pair(infoMn.addr, CDarksendAccept(nSessionDenom, txMyCollateral))));
}
SetState(POOL_STATE_QUEUE);
nTimeLastSuccessfulStep = GetTimeMillis();
LogPrintf("CPrivateSendClient::StartNewQueue -- pending connection, nSessionDenom: %d (%s), addr=%s\n",
nSessionDenom, CPrivateSend::GetDenominationsToString(nSessionDenom), infoMn.addr.ToString());
strAutoDenomResult = _("Mixing in progress...");
return true;
}
strAutoDenomResult = _("Failed to start a new mixing queue");
return false;
}
void CPrivateSendClient::ProcessQueuedDsa(CConnman& connman)
{
LOCK(cs_dsaQueue);
if (!dsaQueue.empty()) {
// wait at least 5 seconds since we tried to open corresponding connection
if (GetTime() - dsaQueue.front().first < 5) {
return;
}
auto request = dsaQueue.front().second;
LogPrint("privatesend", "CPrivateSendClient::%s -- processing dsa queue for addr=%s\n", __func__, request.first.ToString());
bool fFound = connman.ForNode(request.first, [&](CNode* pnode) {
LogPrint("privatesend", "-- processing dsa queue for addr=%s\n", request.first.ToString());
nTimeLastSuccessfulStep = GetTimeMillis();
CNetMsgMaker msgMaker(pnode->GetSendVersion());
connman.PushMessage(pnode, msgMaker.Make(NetMsgType::DSACCEPT, request.second));
return true;
});
dsaQueue.pop_front();
LogPrint("privatesend", "CPrivateSendClient::%s -- dsa queue size: %d\n", __func__, dsaQueue.size());
if (!fFound) {
LogPrint("privatesend", "CPrivateSendClient::%s -- failed to connect to %s\n", __func__, request.first.ToString());