2019-01-29 15:53:14 +01:00
// Copyright (c) 2014-2019 The Dash Core developers
2017-05-05 13:26:27 +02:00
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
2018-11-05 10:29:33 +01:00
2017-05-05 13:26:27 +02:00
# include "privatesend-client.h"
# include "consensus/validation.h"
# include "core_io.h"
# include "init.h"
2018-02-12 13:47:20 +01:00
# include "masternode-payments.h"
2017-05-05 13:26:27 +02:00
# include "masternode-sync.h"
2019-01-03 21:08:34 +01:00
# include "masternode-meta.h"
2016-11-25 20:01:56 +01:00
# include "netmessagemaker.h"
2017-05-05 13:26:27 +02:00
# include "script/sign.h"
# include "txmempool.h"
# include "util.h"
# include "utilmoneystr.h"
2019-01-03 21:08:34 +01:00
# include "validation.h"
2018-11-05 10:29:07 +01:00
# include "wallet/coincontrol.h"
2017-07-03 15:14:07 +02:00
2017-05-28 15:50:07 +02:00
# include <memory>
2017-05-05 13:26:27 +02:00
2018-09-04 12:54:59 +02:00
CPrivateSendClientManager privateSendClient ;
2017-05-05 13:26:27 +02:00
2018-09-04 12:54:59 +02:00
void CPrivateSendClientManager : : ProcessMessage ( CNode * pfrom , const std : : string & strCommand , CDataStream & vRecv , CConnman & connman )
2017-05-05 13:26:27 +02:00
{
2018-11-05 10:29:07 +01:00
if ( fMasternodeMode ) return ;
if ( fLiteMode ) return ; // ignore all Dash related functionality
if ( ! masternodeSync . IsBlockchainSynced ( ) ) return ;
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
if ( ! CheckDiskSpace ( ) ) {
2018-09-04 12:54:59 +02:00
ResetPool ( ) ;
fEnablePrivateSend = false ;
LogPrintf ( " CPrivateSendClientManager::ProcessMessage -- Not enough disk space, disabling PrivateSend. \n " ) ;
return ;
}
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
if ( strCommand = = NetMsgType : : DSQUEUE ) {
if ( pfrom - > nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION ) {
2018-03-15 10:21:43 +01:00
LogPrint ( " privatesend " , " DSQUEUE -- peer=%d using obsolete version %i \n " , pfrom - > id , pfrom - > nVersion ) ;
2018-11-05 10:29:07 +01:00
connman . PushMessage ( pfrom , CNetMsgMaker ( pfrom - > GetSendVersion ( ) ) . Make ( NetMsgType : : REJECT , strCommand , REJECT_OBSOLETE , strprintf ( " Version must be %d or greater " , MIN_PRIVATESEND_PEER_PROTO_VERSION ) ) ) ;
2017-05-05 13:26:27 +02:00
return ;
}
2018-10-25 16:31:32 +02:00
CPrivateSendQueue dsq ;
2017-05-05 13:26:27 +02:00
vRecv > > dsq ;
2018-09-04 12:54:59 +02:00
{
TRY_LOCK ( cs_vecqueue , lockRecv ) ;
2018-11-05 10:29:07 +01:00
if ( ! lockRecv ) return ;
2018-09-04 12:54:59 +02:00
// process every dsq only once
2018-10-25 16:31:32 +02:00
for ( const auto & q : vecPrivateSendQueue ) {
2018-11-05 10:29:07 +01:00
if ( q = = dsq ) {
2018-09-04 12:54:59 +02:00
// LogPrint("privatesend", "DSQUEUE -- %s seen\n", dsq.ToString());
return ;
}
2017-05-05 13:26:27 +02:00
}
2018-09-04 12:54:59 +02:00
} // cs_vecqueue
2017-05-05 13:26:27 +02:00
LogPrint ( " privatesend " , " DSQUEUE -- %s new \n " , dsq . ToString ( ) ) ;
2018-11-05 10:29:07 +01:00
if ( dsq . IsExpired ( ) ) return ;
2017-05-05 13:26:27 +02:00
2018-12-17 15:45:36 +01:00
auto mnList = deterministicMNManager - > GetListAtChainTip ( ) ;
auto dmn = mnList . GetValidMNByCollateral ( dsq . masternodeOutpoint ) ;
if ( ! dmn ) return ;
2017-05-05 13:26:27 +02:00
2018-12-17 15:45:36 +01:00
if ( ! dsq . CheckSignature ( dmn - > pdmnState - > pubKeyOperator ) ) {
2018-12-31 14:01:04 +01:00
LOCK ( cs_main ) ;
Misbehaving ( pfrom - > id , 10 ) ;
2017-05-05 13:26:27 +02:00
return ;
}
// if the queue is ready, submit if we can
2018-11-05 10:29:07 +01:00
if ( dsq . fReady ) {
2018-09-20 14:40:43 +02:00
LOCK ( cs_deqsessions ) ;
for ( auto & session : deqSessions ) {
2018-12-17 15:45:36 +01:00
CDeterministicMNCPtr mnMixing ;
if ( session . GetMixingMasternodeInfo ( mnMixing ) & & mnMixing - > pdmnState - > addr = = dmn - > pdmnState - > addr & & session . GetState ( ) = = POOL_STATE_QUEUE ) {
LogPrint ( " privatesend " , " DSQUEUE -- PrivateSend queue (%s) is ready on masternode %s \n " , dsq . ToString ( ) , dmn - > pdmnState - > addr . ToString ( ) ) ;
2018-09-04 12:54:59 +02:00
session . SubmitDenominate ( connman ) ;
return ;
}
2017-05-05 13:26:27 +02:00
}
} else {
2018-09-20 14:40:43 +02:00
LOCK ( cs_deqsessions ) ; // have to lock this first to avoid deadlocks with cs_vecqueue
2018-09-04 12:54:59 +02:00
TRY_LOCK ( cs_vecqueue , lockRecv ) ;
2018-11-05 10:29:07 +01:00
if ( ! lockRecv ) return ;
2018-09-04 12:54:59 +02:00
2018-10-25 16:31:32 +02:00
for ( const auto & q : vecPrivateSendQueue ) {
2018-11-05 10:29:07 +01:00
if ( q . masternodeOutpoint = = dsq . masternodeOutpoint ) {
2017-05-05 13:26:27 +02:00
// no way same mn can send another "not yet ready" dsq this soon
2018-12-17 15:45:36 +01:00
LogPrint ( " privatesend " , " DSQUEUE -- Masternode %s is sending WAY too many dsq messages \n " , dmn - > pdmnState - > ToString ( ) ) ;
2017-05-05 13:26:27 +02:00
return ;
}
}
2019-01-03 21:08:34 +01:00
int64_t nLastDsq = mmetaman . GetMetaInfo ( dmn - > proTxHash ) - > GetLastDsq ( ) ;
2018-12-17 15:45:36 +01:00
int nThreshold = nLastDsq + mnList . GetValidMNsCount ( ) / 5 ;
2019-01-03 21:08:34 +01:00
LogPrint ( " privatesend " , " DSQUEUE -- nLastDsq: %d threshold: %d nDsqCount: %d \n " , nLastDsq , nThreshold , mmetaman . GetDsqCount ( ) ) ;
2017-05-05 13:26:27 +02:00
//don't allow a few nodes to dominate the queuing process
2019-01-03 21:08:34 +01:00
if ( nLastDsq ! = 0 & & nThreshold > mmetaman . GetDsqCount ( ) ) {
2018-12-17 15:45:36 +01:00
LogPrint ( " privatesend " , " DSQUEUE -- Masternode %s is sending too many dsq messages \n " , dmn - > proTxHash . ToString ( ) ) ;
2017-05-05 13:26:27 +02:00
return ;
}
2019-01-03 21:08:34 +01:00
mmetaman . AllowMixing ( dmn - > proTxHash ) ;
2017-05-05 13:26:27 +02:00
2018-12-17 15:45:36 +01:00
LogPrint ( " privatesend " , " DSQUEUE -- new PrivateSend queue (%s) from masternode %s \n " , dsq . ToString ( ) , dmn - > pdmnState - > addr . ToString ( ) ) ;
2018-09-20 14:40:43 +02:00
for ( auto & session : deqSessions ) {
2018-12-17 15:45:36 +01:00
CDeterministicMNCPtr mnMixing ;
if ( session . GetMixingMasternodeInfo ( mnMixing ) & & mnMixing - > collateralOutpoint = = dsq . masternodeOutpoint ) {
2018-09-04 12:54:59 +02:00
dsq . fTried = true ;
}
2017-05-05 13:26:27 +02:00
}
2018-10-25 16:31:32 +02:00
vecPrivateSendQueue . push_back ( dsq ) ;
2017-09-19 16:51:38 +02:00
dsq . Relay ( connman ) ;
2017-05-05 13:26:27 +02:00
}
2018-09-04 12:54:59 +02:00
} else if (
strCommand = = NetMsgType : : DSSTATUSUPDATE | |
strCommand = = NetMsgType : : DSFINALTX | |
2018-11-05 10:29:07 +01:00
strCommand = = NetMsgType : : DSCOMPLETE ) {
2018-09-20 14:40:43 +02:00
LOCK ( cs_deqsessions ) ;
for ( auto & session : deqSessions ) {
2018-09-04 12:54:59 +02:00
session . ProcessMessage ( pfrom , strCommand , vRecv , connman ) ;
}
}
}
void CPrivateSendClientSession : : ProcessMessage ( CNode * pfrom , const std : : string & strCommand , CDataStream & vRecv , CConnman & connman )
{
2018-11-05 10:29:07 +01:00
if ( fMasternodeMode ) return ;
if ( fLiteMode ) return ; // ignore all Dash related functionality
if ( ! masternodeSync . IsBlockchainSynced ( ) ) return ;
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
if ( strCommand = = NetMsgType : : DSSTATUSUPDATE ) {
if ( pfrom - > nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION ) {
2018-03-15 10:21:43 +01:00
LogPrint ( " privatesend " , " DSSTATUSUPDATE -- peer=%d using obsolete version %i \n " , pfrom - > id , pfrom - > nVersion ) ;
2018-11-05 10:29:07 +01:00
connman . PushMessage ( pfrom , CNetMsgMaker ( pfrom - > GetSendVersion ( ) ) . Make ( NetMsgType : : REJECT , strCommand , REJECT_OBSOLETE , strprintf ( " Version must be %d or greater " , MIN_PRIVATESEND_PEER_PROTO_VERSION ) ) ) ;
2017-05-05 13:26:27 +02:00
return ;
}
2018-12-17 15:45:36 +01:00
if ( ! mixingMasternode ) return ;
if ( mixingMasternode - > pdmnState - > addr ! = pfrom - > addr ) {
2017-05-05 13:26:27 +02:00
//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 ;
2018-11-05 10:29:07 +01:00
if ( nMsgState < POOL_STATE_MIN | | nMsgState > POOL_STATE_MAX ) {
2017-05-05 13:26:27 +02:00
LogPrint ( " privatesend " , " DSSTATUSUPDATE -- nMsgState is out of bounds: %d \n " , nMsgState ) ;
return ;
}
2018-11-05 10:29:07 +01:00
if ( nMsgStatusUpdate < STATUS_REJECTED | | nMsgStatusUpdate > STATUS_ACCEPTED ) {
2017-05-05 13:26:27 +02:00
LogPrint ( " privatesend " , " DSSTATUSUPDATE -- nMsgStatusUpdate is out of bounds: %d \n " , nMsgStatusUpdate ) ;
return ;
}
2018-11-05 10:29:07 +01:00
if ( nMsgMessageID < MSG_POOL_MIN | | nMsgMessageID > MSG_POOL_MAX ) {
2017-05-05 13:26:27 +02:00
LogPrint ( " privatesend " , " DSSTATUSUPDATE -- nMsgMessageID is out of bounds: %d \n " , nMsgMessageID ) ;
return ;
}
2018-02-26 12:10:20 +01:00
LogPrint ( " privatesend " , " DSSTATUSUPDATE -- nMsgSessionID %d nMsgState: %d nEntriesCount: %d nMsgStatusUpdate: %d nMsgMessageID %d (%s) \n " ,
2018-11-05 10:29:07 +01:00
nMsgSessionID , nMsgState , nEntriesCount , nMsgStatusUpdate , nMsgMessageID , CPrivateSend : : GetMessageByID ( PoolMessage ( nMsgMessageID ) ) ) ;
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
if ( ! CheckPoolStateUpdate ( PoolState ( nMsgState ) , nMsgEntriesCount , PoolStatusUpdate ( nMsgStatusUpdate ) , PoolMessage ( nMsgMessageID ) , nMsgSessionID ) ) {
2017-05-05 13:26:27 +02:00
LogPrint ( " privatesend " , " DSSTATUSUPDATE -- CheckPoolStateUpdate failed \n " ) ;
}
2018-11-05 10:29:07 +01:00
} else if ( strCommand = = NetMsgType : : DSFINALTX ) {
if ( pfrom - > nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION ) {
2018-03-15 10:21:43 +01:00
LogPrint ( " privatesend " , " DSFINALTX -- peer=%d using obsolete version %i \n " , pfrom - > id , pfrom - > nVersion ) ;
2018-11-05 10:29:07 +01:00
connman . PushMessage ( pfrom , CNetMsgMaker ( pfrom - > GetSendVersion ( ) ) . Make ( NetMsgType : : REJECT , strCommand , REJECT_OBSOLETE , strprintf ( " Version must be %d or greater " , MIN_PRIVATESEND_PEER_PROTO_VERSION ) ) ) ;
2017-05-05 13:26:27 +02:00
return ;
}
2018-12-17 15:45:36 +01:00
if ( ! mixingMasternode ) return ;
if ( mixingMasternode - > pdmnState - > addr ! = pfrom - > addr ) {
2017-05-05 13:26:27 +02:00
//LogPrintf("DSFINALTX -- message doesn't match current Masternode: infoMixingMasternode %s addr %s\n", infoMixingMasternode.addr.ToString(), pfrom->addr.ToString());
return ;
}
int nMsgSessionID ;
2016-12-05 08:01:20 +01:00
vRecv > > nMsgSessionID ;
CTransaction txNew ( deserialize , vRecv ) ;
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
if ( nSessionID ! = nMsgSessionID ) {
2017-05-05 13:26:27 +02:00
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)
2017-09-19 16:51:38 +02:00
SignFinalTransaction ( txNew , pfrom , connman ) ;
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
} else if ( strCommand = = NetMsgType : : DSCOMPLETE ) {
if ( pfrom - > nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION ) {
2018-03-15 10:21:43 +01:00
LogPrint ( " privatesend " , " DSCOMPLETE -- peer=%d using obsolete version %i \n " , pfrom - > id , pfrom - > nVersion ) ;
2018-11-05 10:29:07 +01:00
connman . PushMessage ( pfrom , CNetMsgMaker ( pfrom - > GetSendVersion ( ) ) . Make ( NetMsgType : : REJECT , strCommand , REJECT_OBSOLETE , strprintf ( " Version must be %d or greater " , MIN_PRIVATESEND_PEER_PROTO_VERSION ) ) ) ;
2017-05-05 13:26:27 +02:00
return ;
}
2018-12-17 15:45:36 +01:00
if ( ! mixingMasternode ) return ;
if ( mixingMasternode - > pdmnState - > addr ! = pfrom - > addr ) {
LogPrint ( " privatesend " , " DSCOMPLETE -- message doesn't match current Masternode: infoMixingMasternode=%s addr=%s \n " , mixingMasternode - > pdmnState - > addr . ToString ( ) , pfrom - > addr . ToString ( ) ) ;
2017-05-05 13:26:27 +02:00
return ;
}
int nMsgSessionID ;
int nMsgMessageID ;
vRecv > > nMsgSessionID > > nMsgMessageID ;
2018-11-05 10:29:07 +01:00
if ( nMsgMessageID < MSG_POOL_MIN | | nMsgMessageID > MSG_POOL_MAX ) {
2017-05-05 13:26:27 +02:00
LogPrint ( " privatesend " , " DSCOMPLETE -- nMsgMessageID is out of bounds: %d \n " , nMsgMessageID ) ;
return ;
}
2018-11-05 10:29:07 +01:00
if ( nSessionID ! = nMsgSessionID ) {
2017-05-05 13:26:27 +02:00
LogPrint ( " privatesend " , " DSCOMPLETE -- message doesn't match current PrivateSend session: nSessionID: %d nMsgSessionID: %d \n " , nSessionID , nMsgSessionID ) ;
return ;
}
2017-06-30 20:30:16 +02:00
LogPrint ( " privatesend " , " DSCOMPLETE -- nMsgSessionID %d nMsgMessageID %d (%s) \n " , nMsgSessionID , nMsgMessageID , CPrivateSend : : GetMessageByID ( PoolMessage ( nMsgMessageID ) ) ) ;
2017-05-05 13:26:27 +02:00
CompletedTransaction ( PoolMessage ( nMsgMessageID ) ) ;
}
}
2018-09-04 12:54:59 +02:00
void CPrivateSendClientSession : : ResetPool ( )
2017-05-05 13:26:27 +02:00
{
txMyCollateral = CMutableTransaction ( ) ;
UnlockCoins ( ) ;
2017-09-11 16:14:55 +02:00
keyHolderStorage . ReturnAll ( ) ;
2017-05-05 13:26:27 +02:00
SetNull ( ) ;
}
2018-09-04 12:54:59 +02:00
void CPrivateSendClientManager : : ResetPool ( )
{
2018-09-20 14:40:43 +02:00
LOCK ( cs_deqsessions ) ;
2018-09-04 12:54:59 +02:00
nCachedLastSuccessBlock = 0 ;
vecMasternodesUsed . clear ( ) ;
2018-09-20 14:40:43 +02:00
for ( auto & session : deqSessions ) {
2018-09-04 12:54:59 +02:00
session . ResetPool ( ) ;
}
2018-09-20 14:40:43 +02:00
deqSessions . clear ( ) ;
2018-09-04 12:54:59 +02:00
}
void CPrivateSendClientSession : : SetNull ( )
2017-05-05 13:26:27 +02:00
{
// Client side
nEntriesCount = 0 ;
fLastEntryAccepted = false ;
2018-12-17 15:45:36 +01:00
mixingMasternode = nullptr ;
2018-02-01 02:10:52 +01:00
pendingDsaRequest = CPendingDsaRequest ( ) ;
2017-05-05 13:26:27 +02:00
2018-09-04 12:54:59 +02:00
CPrivateSendBaseSession : : SetNull ( ) ;
2017-05-05 13:26:27 +02:00
}
//
// Unlock coins after mixing fails or succeeds
//
2018-09-04 12:54:59 +02:00
void CPrivateSendClientSession : : UnlockCoins ( )
2017-05-05 13:26:27 +02:00
{
2018-07-28 15:50:41 +02:00
if ( ! pwalletMain ) return ;
2018-11-05 10:29:07 +01:00
while ( true ) {
2017-05-05 13:26:27 +02:00
TRY_LOCK ( pwalletMain - > cs_wallet , lockWallet ) ;
2018-11-05 10:29:07 +01:00
if ( ! lockWallet ) {
MilliSleep ( 50 ) ;
continue ;
}
2018-02-06 12:09:33 +01:00
for ( const auto & outpoint : vecOutPointLocked )
2017-05-05 13:26:27 +02:00
pwalletMain - > UnlockCoin ( outpoint ) ;
break ;
}
vecOutPointLocked . clear ( ) ;
}
2018-09-04 12:54:59 +02:00
std : : string CPrivateSendClientSession : : GetStatus ( bool fWaitForBlock )
2017-05-05 13:26:27 +02:00
{
static int nStatusMessageProgress = 0 ;
nStatusMessageProgress + = 10 ;
std : : string strSuffix = " " ;
2018-11-05 10:29:07 +01:00
if ( fWaitForBlock | | ! masternodeSync . IsBlockchainSynced ( ) )
2017-05-05 13:26:27 +02:00
return strAutoDenomResult ;
2018-11-05 10:29:07 +01:00
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 ;
2017-05-05 13:26:27 +02:00
nStatusMessageProgress = 0 ;
}
2018-11-05 10:29:07 +01:00
return _ ( " PrivateSend request complete: " ) + " " + _ ( " Your transaction was accepted into the pool! " ) ;
} else {
if ( nStatusMessageProgress % 70 < = 40 )
2019-01-07 11:21:10 +01:00
return strprintf ( _ ( " Submitted following entries to masternode: %u " ) , nEntriesCount ) ;
2018-11-05 10:29:07 +01:00
else if ( nStatusMessageProgress % 70 < = 50 )
strSuffix = " . " ;
else if ( nStatusMessageProgress % 70 < = 60 )
strSuffix = " .. " ;
else if ( nStatusMessageProgress % 70 < = 70 )
strSuffix = " ... " ;
2019-01-07 11:21:10 +01:00
return strprintf ( _ ( " Submitted to masternode, waiting for more entries ( %u ) % s " ), nEntriesCount, strSuffix) ;
2018-11-05 10:29:07 +01:00
}
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 ) ;
2017-05-05 13:26:27 +02:00
}
}
2018-09-04 12:54:59 +02:00
std : : string CPrivateSendClientManager : : GetStatuses ( )
{
2018-09-20 14:40:43 +02:00
LOCK ( cs_deqsessions ) ;
2018-09-04 12:54:59 +02:00
std : : string strStatus ;
bool fWaitForBlock = WaitForAnotherBlock ( ) ;
2018-09-20 14:40:43 +02:00
for ( auto & session : deqSessions ) {
2018-09-04 12:54:59 +02:00
strStatus + = session . GetStatus ( fWaitForBlock ) + " ; " ;
}
return strStatus ;
}
std : : string CPrivateSendClientManager : : GetSessionDenoms ( )
{
2018-09-20 14:40:43 +02:00
LOCK ( cs_deqsessions ) ;
2018-09-04 12:54:59 +02:00
std : : string strSessionDenoms ;
2018-09-20 14:40:43 +02:00
for ( auto & session : deqSessions ) {
2018-09-04 12:54:59 +02:00
strSessionDenoms + = ( session . nSessionDenom ? CPrivateSend : : GetDenominationsToString ( session . nSessionDenom ) : " N/A " ) + " ; " ;
}
return strSessionDenoms . empty ( ) ? " N/A " : strSessionDenoms ;
}
2018-12-17 15:45:36 +01:00
bool CPrivateSendClientSession : : GetMixingMasternodeInfo ( CDeterministicMNCPtr & ret ) const
2017-12-04 07:06:07 +01:00
{
2018-12-17 15:45:36 +01:00
ret = mixingMasternode ;
return ret ! = nullptr ;
2017-12-04 07:06:07 +01:00
}
2018-12-17 15:45:36 +01:00
bool CPrivateSendClientManager : : GetMixingMasternodesInfo ( std : : vector < CDeterministicMNCPtr > & vecDmnsRet ) const
2017-12-04 07:06:07 +01:00
{
2018-09-20 14:40:43 +02:00
LOCK ( cs_deqsessions ) ;
for ( const auto & session : deqSessions ) {
2018-12-17 15:45:36 +01:00
CDeterministicMNCPtr dmn ;
if ( session . GetMixingMasternodeInfo ( dmn ) ) {
vecDmnsRet . push_back ( dmn ) ;
2018-09-04 12:54:59 +02:00
}
}
2018-12-17 15:45:36 +01:00
return ! vecDmnsRet . empty ( ) ;
2017-12-04 07:06:07 +01:00
}
2017-05-05 13:26:27 +02:00
//
// Check the mixing progress and send client updates if a Masternode
//
2018-09-04 12:54:59 +02:00
void CPrivateSendClientSession : : CheckPool ( )
2017-05-05 13:26:27 +02:00
{
// reset if we're here for 10 seconds
2018-11-05 10:29:07 +01:00
if ( ( nState = = POOL_STATE_ERROR | | nState = = POOL_STATE_SUCCESS ) & & GetTime ( ) - nTimeLastSuccessfulStep > = 10 ) {
2018-09-04 12:54:59 +02:00
LogPrint ( " privatesend " , " CPrivateSendClientSession::CheckPool -- timeout, RESETTING \n " ) ;
2017-05-05 13:26:27 +02:00
UnlockCoins ( ) ;
2017-09-11 16:14:55 +02:00
if ( nState = = POOL_STATE_ERROR ) {
keyHolderStorage . ReturnAll ( ) ;
} else {
keyHolderStorage . KeepAll ( ) ;
}
2017-05-05 13:26:27 +02:00
SetNull ( ) ;
}
}
//
2018-09-04 12:54:59 +02:00
// Check session timeouts
2017-05-05 13:26:27 +02:00
//
2018-09-04 12:54:59 +02:00
bool CPrivateSendClientSession : : CheckTimeout ( )
2017-05-05 13:26:27 +02:00
{
2018-11-05 10:29:07 +01:00
if ( fMasternodeMode ) return false ;
2017-05-05 13:26:27 +02:00
// catching hanging sessions
2018-11-05 10:29:07 +01:00
switch ( nState ) {
case POOL_STATE_ERROR :
LogPrint ( " privatesend " , " CPrivateSendClientSession::CheckTimeout -- Pool error -- Running CheckPool \n " ) ;
CheckPool ( ) ;
break ;
case POOL_STATE_SUCCESS :
LogPrint ( " privatesend " , " CPrivateSendClientSession::CheckTimeout -- Pool success -- Running CheckPool \n " ) ;
CheckPool ( ) ;
break ;
default :
break ;
2017-05-05 13:26:27 +02:00
}
2018-02-12 13:47:53 +01:00
int nLagTime = 10 ; // give the server a few extra seconds before resetting.
2017-05-05 13:26:27 +02:00
int nTimeout = ( nState = = POOL_STATE_SIGNING ) ? PRIVATESEND_SIGNING_TIMEOUT : PRIVATESEND_QUEUE_TIMEOUT ;
2018-02-12 13:47:53 +01:00
bool fTimeout = GetTime ( ) - nTimeLastSuccessfulStep > = nTimeout + nLagTime ;
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
if ( nState = = POOL_STATE_IDLE | | ! fTimeout )
2018-09-04 12:54:59 +02:00
return false ;
LogPrint ( " privatesend " , " CPrivateSendClientSession::CheckTimeout -- %s timed out (%ds) -- resetting \n " ,
2018-11-05 10:29:07 +01:00
( nState = = POOL_STATE_SIGNING ) ? " Signing " : " Session " , nTimeout ) ;
2018-09-04 12:54:59 +02:00
UnlockCoins ( ) ;
keyHolderStorage . ReturnAll ( ) ;
SetNull ( ) ;
SetState ( POOL_STATE_ERROR ) ;
return true ;
}
//
// Check all queues and sessions for timeouts
//
void CPrivateSendClientManager : : CheckTimeout ( )
{
2018-11-05 10:29:07 +01:00
if ( fMasternodeMode ) return ;
2018-09-04 12:54:59 +02:00
CheckQueue ( ) ;
2018-11-25 14:35:52 +01:00
if ( ! fEnablePrivateSend ) return ;
2018-09-20 14:40:43 +02:00
LOCK ( cs_deqsessions ) ;
for ( auto & session : deqSessions ) {
2018-09-04 12:54:59 +02:00
if ( session . CheckTimeout ( ) ) {
strAutoDenomResult = _ ( " Session timed out. " ) ;
}
2017-05-05 13:26:27 +02:00
}
}
//
// Execute a mixing denomination via a Masternode.
// This is only ran from clients
//
2018-11-05 10:29:07 +01:00
bool CPrivateSendClientSession : : SendDenominate ( const std : : vector < std : : pair < CTxDSIn , CTxOut > > & vecPSInOutPairsIn , CConnman & connman )
2017-05-05 13:26:27 +02:00
{
2018-11-05 10:29:07 +01:00
if ( fMasternodeMode ) {
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::SendDenominate -- PrivateSend from a Masternode is not supported currently. \n " ) ;
2017-05-05 13:26:27 +02:00
return false ;
}
2018-11-05 10:29:07 +01:00
if ( txMyCollateral = = CMutableTransaction ( ) ) {
2017-05-05 13:26:27 +02:00
LogPrintf ( " CPrivateSendClient:SendDenominate -- PrivateSend collateral not set \n " ) ;
return false ;
}
// lock the funds we're going to use
2018-02-06 12:09:33 +01:00
for ( const auto & txin : txMyCollateral . vin )
2017-05-05 13:26:27 +02:00
vecOutPointLocked . push_back ( txin . prevout ) ;
2018-09-15 12:18:32 +02:00
for ( const auto & pair : vecPSInOutPairsIn )
vecOutPointLocked . push_back ( pair . first . prevout ) ;
2017-05-05 13:26:27 +02:00
// we should already be connected to a Masternode
2018-11-05 10:29:07 +01:00
if ( ! nSessionID ) {
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::SendDenominate -- No Masternode has been selected yet. \n " ) ;
2017-05-05 13:26:27 +02:00
UnlockCoins ( ) ;
2017-09-11 16:14:55 +02:00
keyHolderStorage . ReturnAll ( ) ;
2017-05-05 13:26:27 +02:00
SetNull ( ) ;
return false ;
}
2018-11-05 10:29:07 +01:00
if ( ! CheckDiskSpace ( ) ) {
2017-05-05 13:26:27 +02:00
UnlockCoins ( ) ;
2017-09-11 16:14:55 +02:00
keyHolderStorage . ReturnAll ( ) ;
2017-05-05 13:26:27 +02:00
SetNull ( ) ;
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::SendDenominate -- Not enough disk space. \n " ) ;
2017-05-05 13:26:27 +02:00
return false ;
}
SetState ( POOL_STATE_ACCEPTING_ENTRIES ) ;
strLastMessage = " " ;
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::SendDenominate -- Added transaction to pool. \n " ) ;
2017-05-05 13:26:27 +02:00
2018-09-15 12:18:32 +02:00
CMutableTransaction tx ; // for debug purposes only
std : : vector < CTxDSIn > vecTxDSInTmp ;
std : : vector < CTxOut > vecTxOutTmp ;
2017-05-05 13:26:27 +02:00
2018-09-15 12:18:32 +02:00
for ( const auto & pair : vecPSInOutPairsIn ) {
vecTxDSInTmp . emplace_back ( pair . first ) ;
vecTxOutTmp . emplace_back ( pair . second ) ;
tx . vin . emplace_back ( pair . first ) ;
tx . vout . emplace_back ( pair . second ) ;
2017-05-05 13:26:27 +02:00
}
2018-09-15 12:18:32 +02:00
LogPrintf ( " CPrivateSendClientSession::SendDenominate -- Submitting partial tx %s " , tx . ToString ( ) ) ;
2017-05-05 13:26:27 +02:00
// store our entry for later use
2018-09-15 12:18:32 +02:00
vecEntries . emplace_back ( vecTxDSInTmp , vecTxOutTmp , txMyCollateral ) ;
RelayIn ( vecEntries . back ( ) , connman ) ;
2018-02-12 13:47:53 +01:00
nTimeLastSuccessfulStep = GetTime ( ) ;
2017-05-05 13:26:27 +02:00
return true ;
}
// Incoming message from Masternode updating the progress of mixing
2018-09-04 12:54:59 +02:00
bool CPrivateSendClientSession : : CheckPoolStateUpdate ( PoolState nStateNew , int nEntriesCountNew , PoolStatusUpdate nStatusUpdate , PoolMessage nMessageID , int nSessionIDNew )
2017-05-05 13:26:27 +02:00
{
2018-11-05 10:29:07 +01:00
if ( fMasternodeMode ) return false ;
2017-05-05 13:26:27 +02:00
// do not update state when mixing client state is one of these
2018-11-05 10:29:07 +01:00
if ( nState = = POOL_STATE_IDLE | | nState = = POOL_STATE_ERROR | | nState = = POOL_STATE_SUCCESS ) return false ;
2017-05-05 13:26:27 +02:00
2017-06-30 20:30:16 +02:00
strAutoDenomResult = _ ( " Masternode: " ) + " " + CPrivateSend : : GetMessageByID ( nMessageID ) ;
2017-05-05 13:26:27 +02:00
// if rejected at any state
2018-11-05 10:29:07 +01:00
if ( nStatusUpdate = = STATUS_REJECTED ) {
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::CheckPoolStateUpdate -- entry is rejected by Masternode \n " ) ;
2017-05-05 13:26:27 +02:00
UnlockCoins ( ) ;
2017-09-11 16:14:55 +02:00
keyHolderStorage . ReturnAll ( ) ;
2017-05-05 13:26:27 +02:00
SetNull ( ) ;
SetState ( POOL_STATE_ERROR ) ;
2017-06-30 20:30:16 +02:00
strLastMessage = CPrivateSend : : GetMessageByID ( nMessageID ) ;
2017-05-05 13:26:27 +02:00
return true ;
}
2018-11-05 10:29:07 +01:00
if ( nStatusUpdate = = STATUS_ACCEPTED & & nState = = nStateNew ) {
if ( nStateNew = = POOL_STATE_QUEUE & & nSessionID = = 0 & & nSessionIDNew ! = 0 ) {
2017-05-05 13:26:27 +02:00
// new session id should be set only in POOL_STATE_QUEUE state
nSessionID = nSessionIDNew ;
2018-02-12 13:47:53 +01:00
nTimeLastSuccessfulStep = GetTime ( ) ;
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::CheckPoolStateUpdate -- set nSessionID to %d \n " , nSessionID ) ;
2017-05-05 13:26:27 +02:00
return true ;
2018-11-05 10:29:07 +01:00
} else if ( nStateNew = = POOL_STATE_ACCEPTING_ENTRIES & & nEntriesCount ! = nEntriesCountNew ) {
2017-05-05 13:26:27 +02:00
nEntriesCount = nEntriesCountNew ;
2018-02-12 13:47:53 +01:00
nTimeLastSuccessfulStep = GetTime ( ) ;
2017-05-05 13:26:27 +02:00
fLastEntryAccepted = true ;
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::CheckPoolStateUpdate -- new entry accepted! \n " ) ;
2017-05-05 13:26:27 +02:00
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
//
2018-09-04 12:54:59 +02:00
bool CPrivateSendClientSession : : SignFinalTransaction ( const CTransaction & finalTransactionNew , CNode * pnode , CConnman & connman )
2017-05-05 13:26:27 +02:00
{
2018-07-28 15:50:41 +02:00
if ( ! pwalletMain ) return false ;
2018-11-05 10:29:07 +01:00
if ( fMasternodeMode | | pnode = = nullptr ) return false ;
2018-12-17 15:45:36 +01:00
if ( ! mixingMasternode ) return false ;
2017-05-05 13:26:27 +02:00
finalMutableTransaction = finalTransactionNew ;
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::SignFinalTransaction -- finalMutableTransaction=%s " , finalMutableTransaction . ToString ( ) ) ;
2017-05-05 13:26:27 +02:00
2017-09-22 03:53:15 +02:00
// Make sure it's BIP69 compliant
sort ( finalMutableTransaction . vin . begin ( ) , finalMutableTransaction . vin . end ( ) , CompareInputBIP69 ( ) ) ;
sort ( finalMutableTransaction . vout . begin ( ) , finalMutableTransaction . vout . end ( ) , CompareOutputBIP69 ( ) ) ;
2018-11-05 10:29:07 +01:00
if ( finalMutableTransaction . GetHash ( ) ! = finalTransactionNew . GetHash ( ) ) {
2018-12-17 15:45:36 +01:00
LogPrintf ( " CPrivateSendClientSession::SignFinalTransaction -- WARNING! Masternode %s is not BIP69 compliant! \n " , mixingMasternode - > proTxHash . ToString ( ) ) ;
2017-09-22 03:53:15 +02:00
UnlockCoins ( ) ;
keyHolderStorage . ReturnAll ( ) ;
SetNull ( ) ;
return false ;
}
2017-05-05 13:26:27 +02:00
std : : vector < CTxIn > sigs ;
//make sure my inputs/outputs are present, otherwise refuse to sign
2018-02-06 12:09:33 +01:00
for ( const auto & entry : vecEntries ) {
for ( const auto & txdsin : entry . vecTxDSIn ) {
2017-05-05 13:26:27 +02:00
/* Sign my transaction and all outputs */
int nMyInputIndex = - 1 ;
CScript prevPubKey = CScript ( ) ;
CTxIn txin = CTxIn ( ) ;
2018-11-05 10:29:07 +01:00
for ( unsigned int i = 0 ; i < finalMutableTransaction . vin . size ( ) ; i + + ) {
if ( finalMutableTransaction . vin [ i ] = = txdsin ) {
2017-05-05 13:26:27 +02:00
nMyInputIndex = i ;
prevPubKey = txdsin . prevPubKey ;
txin = txdsin ;
}
}
2018-11-05 10:29:07 +01:00
if ( nMyInputIndex > = 0 ) { //might have to do this one input at a time?
2017-05-05 13:26:27 +02:00
int nFoundOutputsCount = 0 ;
CAmount nValue1 = 0 ;
CAmount nValue2 = 0 ;
2017-12-04 07:06:07 +01:00
for ( const auto & txoutFinal : finalMutableTransaction . vout ) {
2018-11-05 10:29:07 +01:00
for ( const auto & txout : entry . vecTxOut ) {
if ( txoutFinal = = txout ) {
2017-05-05 13:26:27 +02:00
nFoundOutputsCount + + ;
2017-12-04 07:06:07 +01:00
nValue1 + = txoutFinal . nValue ;
2017-05-05 13:26:27 +02:00
}
}
}
2017-12-04 07:06:07 +01:00
for ( const auto & txout : entry . vecTxOut )
2017-05-05 13:26:27 +02:00
nValue2 + = txout . nValue ;
2017-12-04 07:06:07 +01:00
int nTargetOuputsCount = entry . vecTxOut . size ( ) ;
2018-11-05 10:29:07 +01:00
if ( nFoundOutputsCount < nTargetOuputsCount | | nValue1 ! = nValue2 ) {
2017-05-05 13:26:27 +02:00
// 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.
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::SignFinalTransaction -- My entries are not correct! Refusing to sign: nFoundOutputsCount: %d, nTargetOuputsCount: %d \n " , nFoundOutputsCount , nTargetOuputsCount ) ;
2017-05-05 13:26:27 +02:00
UnlockCoins ( ) ;
2017-09-11 16:14:55 +02:00
keyHolderStorage . ReturnAll ( ) ;
2017-05-05 13:26:27 +02:00
SetNull ( ) ;
return false ;
}
const CKeyStore & keystore = * pwalletMain ;
2018-09-04 12:54:59 +02:00
LogPrint ( " privatesend " , " CPrivateSendClientSession::SignFinalTransaction -- Signing my input %i \n " , nMyInputIndex ) ;
2018-11-05 10:29:07 +01:00
if ( ! SignSignature ( keystore , prevPubKey , finalMutableTransaction , nMyInputIndex , int ( SIGHASH_ALL | SIGHASH_ANYONECANPAY ) ) ) { // changes scriptSig
2018-09-04 12:54:59 +02:00
LogPrint ( " privatesend " , " CPrivateSendClientSession::SignFinalTransaction -- Unable to sign my own transaction! \n " ) ;
2017-05-05 13:26:27 +02:00
// not sure what to do here, it will timeout...?
}
sigs . push_back ( finalMutableTransaction . vin [ nMyInputIndex ] ) ;
2018-09-04 12:54:59 +02:00
LogPrint ( " privatesend " , " CPrivateSendClientSession::SignFinalTransaction -- nMyInputIndex: %d, sigs.size(): %d, scriptSig=%s \n " , nMyInputIndex , ( int ) sigs . size ( ) , ScriptToAsmStr ( finalMutableTransaction . vin [ nMyInputIndex ] . scriptSig ) ) ;
2017-05-05 13:26:27 +02:00
}
}
}
2018-11-05 10:29:07 +01:00
if ( sigs . empty ( ) ) {
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::SignFinalTransaction -- can't sign anything! \n " ) ;
2017-05-05 13:26:27 +02:00
UnlockCoins ( ) ;
2017-09-11 16:14:55 +02:00
keyHolderStorage . ReturnAll ( ) ;
2017-05-05 13:26:27 +02:00
SetNull ( ) ;
return false ;
}
// push all of our signatures to the Masternode
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::SignFinalTransaction -- pushing sigs to the masternode, finalMutableTransaction=%s " , finalMutableTransaction . ToString ( ) ) ;
2016-11-25 20:01:56 +01:00
CNetMsgMaker msgMaker ( pnode - > GetSendVersion ( ) ) ;
connman . PushMessage ( pnode , msgMaker . Make ( NetMsgType : : DSSIGNFINALTX , sigs ) ) ;
2017-05-05 13:26:27 +02:00
SetState ( POOL_STATE_SIGNING ) ;
2018-02-12 13:47:53 +01:00
nTimeLastSuccessfulStep = GetTime ( ) ;
2017-05-05 13:26:27 +02:00
return true ;
}
// mixing transaction was completed (failed or successful)
2018-09-04 12:54:59 +02:00
void CPrivateSendClientSession : : CompletedTransaction ( PoolMessage nMessageID )
2017-05-05 13:26:27 +02:00
{
2018-11-05 10:29:07 +01:00
if ( fMasternodeMode ) return ;
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
if ( nMessageID = = MSG_SUCCESS ) {
2017-05-05 13:26:27 +02:00
LogPrintf ( " CompletedTransaction -- success \n " ) ;
2018-09-04 12:54:59 +02:00
privateSendClient . UpdatedSuccessBlock ( ) ;
2017-09-11 16:14:55 +02:00
keyHolderStorage . KeepAll ( ) ;
2017-05-05 13:26:27 +02:00
} else {
LogPrintf ( " CompletedTransaction -- error \n " ) ;
2017-09-11 16:14:55 +02:00
keyHolderStorage . ReturnAll ( ) ;
2017-05-05 13:26:27 +02:00
}
UnlockCoins ( ) ;
SetNull ( ) ;
2017-06-30 20:30:16 +02:00
strLastMessage = CPrivateSend : : GetMessageByID ( nMessageID ) ;
2017-05-05 13:26:27 +02:00
}
2018-09-04 12:54:59 +02:00
void CPrivateSendClientManager : : UpdatedSuccessBlock ( )
{
2018-11-05 10:29:07 +01:00
if ( fMasternodeMode ) return ;
2018-09-04 12:54:59 +02:00
nCachedLastSuccessBlock = nCachedBlockHeight ;
}
bool CPrivateSendClientManager : : IsDenomSkipped ( const CAmount & nDenomValue )
2018-04-20 12:53:23 +02:00
{
return std : : find ( vecDenominationsSkipped . begin ( ) , vecDenominationsSkipped . end ( ) , nDenomValue ) ! = vecDenominationsSkipped . end ( ) ;
}
2018-09-04 12:54:59 +02:00
void CPrivateSendClientManager : : AddSkippedDenom ( const CAmount & nDenomValue )
{
vecDenominationsSkipped . push_back ( nDenomValue ) ;
}
bool CPrivateSendClientManager : : WaitForAnotherBlock ( )
2017-09-03 15:30:58 +02:00
{
2019-01-03 10:17:43 +01:00
if ( ! masternodeSync . IsBlockchainSynced ( ) )
2017-09-03 15:30:58 +02:00
return true ;
2018-11-05 10:29:07 +01:00
if ( fPrivateSendMultiSession )
2017-09-03 15:30:58 +02:00
return false ;
return nCachedBlockHeight - nCachedLastSuccessBlock < nMinBlocksToWait ;
}
2017-05-05 13:26:27 +02:00
2018-09-04 12:54:59 +02:00
bool CPrivateSendClientManager : : CheckAutomaticBackup ( )
2017-05-05 13:26:27 +02:00
{
2018-07-28 15:50:41 +02:00
if ( ! pwalletMain ) {
2018-09-04 12:54:59 +02:00
LogPrint ( " privatesend " , " CPrivateSendClientManager::CheckAutomaticBackup -- Wallet is not initialized, no mixing available. \n " ) ;
2018-07-28 15:50:41 +02:00
strAutoDenomResult = _ ( " Wallet is not initialized " ) + " , " + _ ( " no mixing available. " ) ;
fEnablePrivateSend = false ; // no mixing
return false ;
}
2018-11-05 10:29:07 +01:00
switch ( nWalletBackups ) {
case 0 :
LogPrint ( " privatesend " , " CPrivateSendClientManager::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 spamming if debug is on.
LogPrint ( " privatesend " , " CPrivateSendClientManager::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 spamming if debug is on.
LogPrint ( " privatesend " , " CPrivateSendClientManager::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 ;
2017-05-05 13:26:27 +02:00
}
2018-11-05 10:29:07 +01:00
if ( pwalletMain - > nKeysLeftSinceAutoBackup < PRIVATESEND_KEYS_THRESHOLD_STOP ) {
2017-05-05 13:26:27 +02:00
// We should never get here via mixing itself but probably smth else is still actively using keypool
2018-09-04 12:54:59 +02:00
LogPrint ( " privatesend " , " CPrivateSendClientManager::CheckAutomaticBackup -- Very low number of keys left: %d, no mixing available. \n " , pwalletMain - > nKeysLeftSinceAutoBackup ) ;
2017-05-05 13:26:27 +02:00
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 ;
2018-11-05 10:29:07 +01:00
} else if ( pwalletMain - > nKeysLeftSinceAutoBackup < PRIVATESEND_KEYS_THRESHOLD_WARNING ) {
2017-05-05 13:26:27 +02:00
// Low number of keys left but it's still more or less safe to continue
2018-09-04 12:54:59 +02:00
LogPrint ( " privatesend " , " CPrivateSendClientManager::CheckAutomaticBackup -- Very low number of keys left: %d \n " , pwalletMain - > nKeysLeftSinceAutoBackup ) ;
2017-05-05 13:26:27 +02:00
strAutoDenomResult = strprintf ( _ ( " Very low number of keys left: %d " ) , pwalletMain - > nKeysLeftSinceAutoBackup ) ;
2018-11-05 10:29:07 +01:00
if ( fCreateAutoBackups ) {
2018-09-04 12:54:59 +02:00
LogPrint ( " privatesend " , " CPrivateSendClientManager::CheckAutomaticBackup -- Trying to create new backup. \n " ) ;
2017-05-05 13:26:27 +02:00
std : : string warningString ;
std : : string errorString ;
2018-11-05 10:29:07 +01:00
if ( ! AutoBackupWallet ( pwalletMain , " " , warningString , errorString ) ) {
if ( ! warningString . empty ( ) ) {
2017-05-05 13:26:27 +02:00
// There were some issues saving backup but yet more or less safe to continue
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientManager::CheckAutomaticBackup -- WARNING! Something went wrong on automatic backup: %s \n " , warningString ) ;
2017-05-05 13:26:27 +02:00
}
2018-11-05 10:29:07 +01:00
if ( ! errorString . empty ( ) ) {
2017-05-05 13:26:27 +02:00
// Things are really broken
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientManager::CheckAutomaticBackup -- ERROR! Failed to create automatic backup: %s \n " , errorString ) ;
2017-05-05 13:26:27 +02:00
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 ;
}
}
2018-09-04 12:54:59 +02:00
LogPrint ( " privatesend " , " CPrivateSendClientManager::CheckAutomaticBackup -- Keys left since latest backup: %d \n " , pwalletMain - > nKeysLeftSinceAutoBackup ) ;
2017-05-05 13:26:27 +02:00
return true ;
}
//
// Passively run mixing in the background to anonymize funds based on the given configuration.
//
2018-09-04 12:54:59 +02:00
bool CPrivateSendClientSession : : DoAutomaticDenominating ( CConnman & connman , bool fDryRun )
2017-05-05 13:26:27 +02:00
{
2018-11-05 10:29:07 +01:00
if ( fMasternodeMode ) return false ; // no client-side mixing on masternodes
if ( nState ! = POOL_STATE_IDLE ) return false ;
2017-05-05 13:26:27 +02:00
2019-01-03 10:17:43 +01:00
if ( ! masternodeSync . IsBlockchainSynced ( ) ) {
2017-05-05 13:26:27 +02:00
strAutoDenomResult = _ ( " Can't mix while sync in progress. " ) ;
return false ;
}
2018-07-28 15:51:45 +02:00
if ( ! pwalletMain ) {
strAutoDenomResult = _ ( " Wallet is not initialized " ) ;
return false ;
}
2018-09-04 12:54:59 +02:00
CAmount nBalanceNeedsAnonymized ;
CAmount nValueMin = CPrivateSend : : GetSmallestDenomination ( ) ;
{
2018-11-05 10:29:07 +01:00
LOCK2 ( cs_main , pwalletMain - > cs_wallet ) ;
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
if ( ! fDryRun & & pwalletMain - > IsLocked ( true ) ) {
strAutoDenomResult = _ ( " Wallet is locked. " ) ;
return false ;
}
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
if ( GetEntriesCount ( ) > 0 ) {
strAutoDenomResult = _ ( " Mixing in progress... " ) ;
return false ;
}
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
TRY_LOCK ( cs_privatesend , lockDS ) ;
if ( ! lockDS ) {
strAutoDenomResult = _ ( " Lock is already in place. " ) ;
return false ;
}
2017-05-05 13:26:27 +02:00
2018-12-17 15:45:36 +01:00
if ( deterministicMNManager - > GetListAtChainTip ( ) . GetValidMNsCount ( ) = = 0 ) {
2018-11-05 10:29:07 +01:00
LogPrint ( " privatesend " , " CPrivateSendClientSession::DoAutomaticDenominating -- No Masternodes detected \n " ) ;
strAutoDenomResult = _ ( " No Masternodes detected. " ) ;
return false ;
}
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
// if there are no confirmed DS collateral inputs yet
if ( ! pwalletMain - > HasCollateralInputs ( ) ) {
// should have some additional amount for them
nValueMin + = CPrivateSend : : GetMaxCollateralAmount ( ) ;
}
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
// including denoms but applying some restrictions
nBalanceNeedsAnonymized = pwalletMain - > GetNeedsToBeAnonymizedBalance ( nValueMin ) ;
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
// anonymizable balance is way too small
if ( nBalanceNeedsAnonymized < nValueMin ) {
LogPrintf ( " CPrivateSendClientSession::DoAutomaticDenominating -- Not enough funds to anonymize \n " ) ;
strAutoDenomResult = _ ( " Not enough funds to anonymize. " ) ;
return false ;
}
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
// excluding denoms
CAmount nBalanceAnonimizableNonDenom = pwalletMain - > GetAnonymizableBalance ( true ) ;
// denoms
CAmount nBalanceDenominatedConf = pwalletMain - > GetDenominatedBalance ( ) ;
CAmount nBalanceDenominatedUnconf = pwalletMain - > GetDenominatedBalance ( true ) ;
CAmount nBalanceDenominated = nBalanceDenominatedConf + nBalanceDenominatedUnconf ;
LogPrint ( " privatesend " , " CPrivateSendClientSession::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 < privateSendClient . 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 ;
}
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
// Initial phase, find a Masternode
// Clean if there is anything left from previous session
UnlockCoins ( ) ;
keyHolderStorage . ReturnAll ( ) ;
SetNull ( ) ;
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
// should be no unconfirmed denoms in non-multi-session mode
if ( ! privateSendClient . fPrivateSendMultiSession & & nBalanceDenominatedUnconf > 0 ) {
LogPrintf ( " CPrivateSendClientSession::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. " ) ;
2017-05-05 13:26:27 +02:00
return false ;
}
2018-11-05 10:29:07 +01:00
//check our collateral and create new if needed
std : : string strReason ;
if ( txMyCollateral = = CMutableTransaction ( ) ) {
if ( ! pwalletMain - > CreateCollateralTransaction ( txMyCollateral , strReason ) ) {
LogPrintf ( " CPrivateSendClientSession::DoAutomaticDenominating -- create collateral error:%s \n " , strReason ) ;
2017-05-05 13:26:27 +02:00
return false ;
}
2018-11-05 10:29:07 +01:00
} else {
if ( ! CPrivateSend : : IsCollateralValid ( txMyCollateral ) ) {
LogPrintf ( " CPrivateSendClientSession::DoAutomaticDenominating -- invalid collateral, recreating... \n " ) ;
if ( ! pwalletMain - > CreateCollateralTransaction ( txMyCollateral , strReason ) ) {
LogPrintf ( " CPrivateSendClientSession::DoAutomaticDenominating -- create collateral error: %s \n " , strReason ) ;
return false ;
}
}
2017-05-05 13:26:27 +02:00
}
2018-09-04 12:54:59 +02:00
} // LOCK2(cs_main, pwalletMain->cs_wallet);
bool fUseQueue = GetRandInt ( 100 ) > 33 ;
// don't use the queues all of the time for mixing unless we are a liquidity provider
2018-11-05 10:29:07 +01:00
if ( ( privateSendClient . nLiquidityProvider | | fUseQueue ) & & JoinExistingQueue ( nBalanceNeedsAnonymized , connman ) )
2018-09-04 12:54:59 +02:00
return true ;
// do not initiate queue if we are a liquidity provider to avoid useless inter-mixing
2018-11-05 10:29:07 +01:00
if ( privateSendClient . nLiquidityProvider ) return false ;
2018-09-04 12:54:59 +02:00
2018-11-05 10:29:07 +01:00
if ( StartNewQueue ( nValueMin , nBalanceNeedsAnonymized , connman ) )
2018-09-04 12:54:59 +02:00
return true ;
strAutoDenomResult = _ ( " No compatible Masternode found. " ) ;
return false ;
}
bool CPrivateSendClientManager : : DoAutomaticDenominating ( CConnman & connman , bool fDryRun )
{
if ( fMasternodeMode ) return false ; // no client-side mixing on masternodes
if ( ! fEnablePrivateSend ) return false ;
2019-01-03 10:17:43 +01:00
if ( ! masternodeSync . IsBlockchainSynced ( ) ) {
2018-09-04 12:54:59 +02:00
strAutoDenomResult = _ ( " Can't mix while sync in progress. " ) ;
return false ;
}
if ( ! pwalletMain ) {
strAutoDenomResult = _ ( " Wallet is not initialized " ) ;
return false ;
}
if ( ! fDryRun & & pwalletMain - > IsLocked ( true ) ) {
strAutoDenomResult = _ ( " Wallet is locked. " ) ;
return false ;
}
2017-05-05 13:26:27 +02:00
2018-12-17 15:45:36 +01:00
int nMnCountEnabled = deterministicMNManager - > GetListAtChainTip ( ) . GetValidMNsCount ( ) ;
2017-05-05 13:26:27 +02:00
// If we've used 90% of the Masternode list then drop the oldest first ~30%
2018-11-27 08:03:41 +01:00
int nThreshold_high = nMnCountEnabled * 0.9 ;
2017-05-05 13:26:27 +02:00
int nThreshold_low = nThreshold_high * 0.7 ;
LogPrint ( " privatesend " , " Checking vecMasternodesUsed: size: %d, threshold: %d \n " , ( int ) vecMasternodesUsed . size ( ) , nThreshold_high ) ;
2018-11-05 10:29:07 +01:00
if ( ( int ) vecMasternodesUsed . size ( ) > nThreshold_high ) {
2017-05-05 13:26:27 +02:00
vecMasternodesUsed . erase ( vecMasternodesUsed . begin ( ) , vecMasternodesUsed . begin ( ) + vecMasternodesUsed . size ( ) - nThreshold_low ) ;
LogPrint ( " privatesend " , " vecMasternodesUsed: new size: %d, threshold: %d \n " , ( int ) vecMasternodesUsed . size ( ) , nThreshold_high ) ;
}
2018-09-20 14:40:43 +02:00
LOCK ( cs_deqsessions ) ;
2018-09-04 12:54:59 +02:00
bool fResult = true ;
2018-09-20 14:40:43 +02:00
if ( ( int ) deqSessions . size ( ) < nPrivateSendSessions ) {
deqSessions . emplace_back ( ) ;
2018-09-04 12:54:59 +02:00
}
2018-09-20 14:40:43 +02:00
for ( auto & session : deqSessions ) {
2018-09-04 12:54:59 +02:00
if ( ! CheckAutomaticBackup ( ) )
return false ;
2017-05-05 13:26:27 +02:00
2018-09-04 12:54:59 +02:00
if ( WaitForAnotherBlock ( ) ) {
LogPrintf ( " CPrivateSendClientManager::DoAutomaticDenominating -- Last successful PrivateSend action was too recent \n " ) ;
strAutoDenomResult = _ ( " Last successful PrivateSend action was too recent. " ) ;
return false ;
}
2017-05-05 13:26:27 +02:00
2018-09-04 12:54:59 +02:00
fResult & = session . DoAutomaticDenominating ( connman , fDryRun ) ;
}
2017-05-05 13:26:27 +02:00
2018-09-04 12:54:59 +02:00
return fResult ;
}
void CPrivateSendClientManager : : AddUsedMasternode ( const COutPoint & outpointMn )
{
vecMasternodesUsed . push_back ( outpointMn ) ;
}
2018-12-17 15:47:57 +01:00
CDeterministicMNCPtr CPrivateSendClientManager : : GetRandomNotUsedMasternode ( )
2018-09-04 12:54:59 +02:00
{
2018-12-17 15:47:57 +01:00
auto mnList = deterministicMNManager - > GetListAtChainTip ( ) ;
int nCountEnabled = mnList . GetValidMNsCount ( ) ;
int nCountNotExcluded = nCountEnabled - vecMasternodesUsed . size ( ) ;
LogPrintf ( " CPrivateSendClientManager::%s -- %d enabled masternodes, %d masternodes to choose from \n " , __func__ , nCountEnabled , nCountNotExcluded ) ;
if ( nCountNotExcluded < 1 ) {
return nullptr ;
}
// fill a vector
std : : vector < CDeterministicMNCPtr > vpMasternodesShuffled ;
vpMasternodesShuffled . reserve ( ( size_t ) nCountEnabled ) ;
mnList . ForEachMN ( true , [ & ] ( const CDeterministicMNCPtr & dmn ) {
vpMasternodesShuffled . emplace_back ( dmn ) ;
} ) ;
FastRandomContext insecure_rand ;
// shuffle pointers
std : : random_shuffle ( vpMasternodesShuffled . begin ( ) , vpMasternodesShuffled . end ( ) , insecure_rand ) ;
std : : set < COutPoint > excludeSet ( vecMasternodesUsed . begin ( ) , vecMasternodesUsed . end ( ) ) ;
// loop through
for ( const auto & dmn : vpMasternodesShuffled ) {
if ( excludeSet . count ( dmn - > collateralOutpoint ) ) {
continue ;
}
LogPrint ( " masternode " , " CPrivateSendClientManager::%s -- found, masternode=%s \n " , __func__ , dmn - > collateralOutpoint . ToStringShort ( ) ) ;
return dmn ;
}
LogPrint ( " masternode " , " CPrivateSendClientManager::%s -- failed \n " , __func__ ) ;
return nullptr ;
2017-05-05 13:26:27 +02:00
}
2018-09-04 12:54:59 +02:00
bool CPrivateSendClientSession : : JoinExistingQueue ( CAmount nBalanceNeedsAnonymized , CConnman & connman )
2017-05-05 13:26:27 +02:00
{
2018-11-05 10:29:07 +01:00
if ( ! pwalletMain ) return false ;
2018-07-28 15:50:41 +02:00
2018-12-17 15:45:36 +01:00
auto mnList = deterministicMNManager - > GetListAtChainTip ( ) ;
2017-06-30 20:30:16 +02:00
std : : vector < CAmount > vecStandardDenoms = CPrivateSend : : GetStandardDenominations ( ) ;
2017-05-05 13:26:27 +02:00
// Look through the queues and see if anything matches
2018-10-25 16:31:32 +02:00
CPrivateSendQueue dsq ;
2018-09-04 12:54:59 +02:00
while ( privateSendClient . GetQueueItemAndTry ( dsq ) ) {
2018-12-17 15:45:36 +01:00
auto dmn = mnList . GetValidMNByCollateral ( dsq . masternodeOutpoint ) ;
2017-05-05 13:26:27 +02:00
2018-12-17 15:45:36 +01:00
if ( ! dmn ) {
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::JoinExistingQueue -- dsq masternode is not in masternode list, masternode=%s \n " , dsq . masternodeOutpoint . ToStringShort ( ) ) ;
2017-05-05 13:26:27 +02:00
continue ;
}
2018-02-12 13:47:20 +01:00
// skip next mn payments winners
2018-12-17 15:45:36 +01:00
if ( mnpayments . IsScheduled ( dmn , 0 ) ) {
LogPrintf ( " CPrivateSendClientSession::JoinExistingQueue -- skipping winner, masternode=%s \n " , dmn - > proTxHash . ToString ( ) ) ;
2018-02-12 13:47:20 +01:00
continue ;
}
2017-05-05 13:26:27 +02:00
std : : vector < int > vecBits ;
2018-11-05 10:29:07 +01:00
if ( ! CPrivateSend : : GetDenominationsBits ( dsq . nDenom , vecBits ) ) {
2017-05-05 13:26:27 +02:00
// incompatible denom
continue ;
}
// mixing rate limit i.e. nLastDsq check should already pass in DSQUEUE ProcessMessage
2018-10-25 16:31:32 +02:00
// in order for dsq to get into vecPrivateSendQueue, so we should be safe to mix already,
2017-05-05 13:26:27 +02:00
// no need for additional verification here
2018-09-04 12:54:59 +02:00
LogPrint ( " privatesend " , " CPrivateSendClientSession::JoinExistingQueue -- found valid queue: %s \n " , dsq . ToString ( ) ) ;
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
std : : vector < std : : pair < CTxDSIn , CTxOut > > vecPSInOutPairsTmp ;
2018-06-06 09:59:09 +02:00
CAmount nMinAmount = vecStandardDenoms [ vecBits . front ( ) ] ;
CAmount nMaxAmount = nBalanceNeedsAnonymized ;
2018-05-26 20:03:23 +02:00
// Try to match their denominations if possible, select exact number of denominations
2018-09-15 12:18:32 +02:00
if ( ! pwalletMain - > SelectPSInOutPairsByDenominations ( dsq . nDenom , nMinAmount , nMaxAmount , vecPSInOutPairsTmp ) ) {
2018-09-05 13:19:03 +02:00
LogPrintf ( " CPrivateSendClientSession::JoinExistingQueue -- Couldn't match %d denominations %d (%s) \n " , vecBits . front ( ) , dsq . nDenom , CPrivateSend : : GetDenominationsToString ( dsq . nDenom ) ) ;
2017-05-05 13:26:27 +02:00
continue ;
}
2018-09-04 12:54:59 +02:00
privateSendClient . AddUsedMasternode ( dsq . masternodeOutpoint ) ;
2017-05-05 13:26:27 +02:00
2018-12-17 15:45:36 +01:00
if ( connman . IsMasternodeOrDisconnectRequested ( dmn - > pdmnState - > addr ) ) {
LogPrintf ( " CPrivateSendClientSession::JoinExistingQueue -- skipping masternode connection, addr=%s \n " , dmn - > pdmnState - > addr . ToString ( ) ) ;
Backport Bitcoin PR#8085: p2p: Begin encapsulation (#1537)
* net: move CBanDB and CAddrDB out of net.h/cpp
This will eventually solve a circular dependency
* net: Create CConnman to encapsulate p2p connections
* net: Move socket binding into CConnman
* net: move OpenNetworkConnection into CConnman
* net: move ban and addrman functions into CConnman
* net: Add oneshot functions to CConnman
* net: move added node functions to CConnman
* net: Add most functions needed for vNodes to CConnman
* net: handle nodesignals in CConnman
* net: Pass CConnection to wallet rather than using the global
* net: Add rpc error for missing/disabled p2p functionality
* net: Pass CConnman around as needed
* gui: add NodeID to the peer table
* net: create generic functor accessors and move vNodes to CConnman
* net: move whitelist functions into CConnman
* net: move nLastNodeId to CConnman
* net: move nLocalHostNonce to CConnman
This behavior seems to have been quite racy and broken.
Move nLocalHostNonce into CNode, and check received nonces against all
non-fully-connected nodes. If there's a match, assume we've connected
to ourself.
* net: move messageHandlerCondition to CConnman
* net: move send/recv statistics to CConnman
* net: move SendBufferSize/ReceiveFloodSize to CConnman
* net: move nLocalServices/nRelevantServices to CConnman
These are in-turn passed to CNode at connection time. This allows us to offer
different services to different peers (or test the effects of doing so).
* net: move semOutbound and semMasternodeOutbound to CConnman
* net: SocketSendData returns written size
* net: move max/max-outbound to CConnman
* net: Pass best block known height into CConnman
CConnman then passes the current best height into CNode at creation time.
This way CConnman/CNode have no dependency on main for height, and the signals
only move in one direction.
This also helps to prevent identity leakage a tiny bit. Before this change, an
attacker could theoretically make 2 connections on different interfaces. They
would connect fully on one, and only establish the initial connection on the
other. Once they receive a new block, they would relay it to your first
connection, and immediately commence the version handshake on the second. Since
the new block height is reflected immediately, they could attempt to learn
whether the two connections were correlated.
This is, of course, incredibly unlikely to work due to the small timings
involved and receipt from other senders. But it doesn't hurt to lock-in
nBestHeight at the time of connection, rather than letting the remote choose
the time.
* net: pass CClientUIInterface into CConnman
* net: Drop StartNode/StopNode and use CConnman directly
* net: Introduce CConnection::Options to avoid passing so many params
* net: add nSendBufferMaxSize/nReceiveFloodSize to CConnection::Options
* net: move vNodesDisconnected into CConnman
* Made the ForEachNode* functions in src/net.cpp more pragmatic and self documenting
* Convert ForEachNode* functions to take a templated function argument rather than a std::function to eliminate std::function overhead
* net: move MAX_FEELER_CONNECTIONS into connman
2017-07-21 11:35:19 +02:00
continue ;
2018-01-09 10:17:54 +01:00
}
2017-05-05 13:26:27 +02:00
2018-02-01 02:10:52 +01:00
nSessionDenom = dsq . nDenom ;
2018-12-17 15:45:36 +01:00
mixingMasternode = dmn ;
pendingDsaRequest = CPendingDsaRequest ( dmn - > pdmnState - > addr , CPrivateSendAccept ( nSessionDenom , txMyCollateral ) ) ;
connman . AddPendingMasternode ( dmn - > pdmnState - > addr ) ;
2018-02-01 02:10:52 +01:00
// TODO: add new state POOL_STATE_CONNECTING and bump MIN_PRIVATESEND_PEER_PROTO_VERSION
SetState ( POOL_STATE_QUEUE ) ;
2018-02-12 13:47:53 +01:00
nTimeLastSuccessfulStep = GetTime ( ) ;
2018-09-05 13:19:03 +02:00
LogPrintf ( " CPrivateSendClientSession::JoinExistingQueue -- pending connection (from queue): nSessionDenom: %d (%s), addr=%s \n " ,
2018-12-17 15:45:36 +01:00
nSessionDenom , CPrivateSend : : GetDenominationsToString ( nSessionDenom ) , dmn - > pdmnState - > addr . ToString ( ) ) ;
2018-02-01 02:10:52 +01:00
strAutoDenomResult = _ ( " Trying to connect... " ) ;
2018-01-17 16:09:08 +01:00
return true ;
2017-05-05 13:26:27 +02:00
}
2018-02-01 02:10:52 +01:00
strAutoDenomResult = _ ( " Failed to find mixing queue to join " ) ;
2017-05-05 13:26:27 +02:00
return false ;
}
2018-09-04 12:54:59 +02:00
bool CPrivateSendClientSession : : StartNewQueue ( CAmount nValueMin , CAmount nBalanceNeedsAnonymized , CConnman & connman )
2017-05-05 13:26:27 +02:00
{
2018-07-28 15:50:41 +02:00
if ( ! pwalletMain ) return false ;
2017-05-05 13:26:27 +02:00
int nTries = 0 ;
2018-12-17 15:45:36 +01:00
int nMnCount = deterministicMNManager - > GetListAtChainTip ( ) . GetValidMNsCount ( ) ;
2017-05-05 13:26:27 +02:00
// ** find the coins we'll use
std : : vector < CTxIn > vecTxIn ;
CAmount nValueInTmp = 0 ;
2018-11-05 10:29:07 +01:00
if ( ! pwalletMain - > SelectPrivateCoins ( nValueMin , nBalanceNeedsAnonymized , vecTxIn , nValueInTmp , 0 , privateSendClient . nPrivateSendRounds - 1 ) ) {
2017-05-05 13:26:27 +02:00
// this should never happen
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::StartNewQueue -- Can't mix: no compatible inputs found! \n " ) ;
2017-05-05 13:26:27 +02:00
strAutoDenomResult = _ ( " Can't mix: no compatible inputs found! " ) ;
return false ;
}
// otherwise, try one randomly
2018-11-05 10:29:07 +01:00
while ( nTries < 10 ) {
2018-12-17 15:45:36 +01:00
auto dmn = privateSendClient . GetRandomNotUsedMasternode ( ) ;
2018-02-12 13:47:20 +01:00
2018-12-17 15:45:36 +01:00
if ( ! dmn ) {
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::StartNewQueue -- Can't find random masternode! \n " ) ;
2017-05-05 13:26:27 +02:00
strAutoDenomResult = _ ( " Can't find random Masternode. " ) ;
return false ;
}
2018-02-12 13:47:20 +01:00
2018-12-17 15:45:36 +01:00
privateSendClient . AddUsedMasternode ( dmn - > collateralOutpoint ) ;
2018-10-11 16:32:51 +02:00
2018-02-12 13:47:20 +01:00
// skip next mn payments winners
2018-12-17 15:45:36 +01:00
if ( mnpayments . IsScheduled ( dmn , 0 ) ) {
LogPrintf ( " CPrivateSendClientSession::StartNewQueue -- skipping winner, masternode=%s \n " , dmn - > proTxHash . ToString ( ) ) ;
2018-02-12 13:47:20 +01:00
nTries + + ;
continue ;
}
2019-01-03 21:08:34 +01:00
int64_t nLastDsq = mmetaman . GetMetaInfo ( dmn - > proTxHash ) - > GetLastDsq ( ) ;
if ( nLastDsq ! = 0 & & nLastDsq + nMnCount / 5 > mmetaman . GetDsqCount ( ) ) {
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::StartNewQueue -- Too early to mix on this masternode! "
2018-11-05 10:29:07 +01:00
" masternode=%s addr=%s nLastDsq=%d CountEnabled/5=%d nDsqCount=%d \n " ,
2018-12-17 15:45:36 +01:00
dmn - > proTxHash . ToString ( ) , dmn - > pdmnState - > addr . ToString ( ) , nLastDsq ,
2019-01-03 21:08:34 +01:00
nMnCount / 5 , mmetaman . GetDsqCount ( ) ) ;
2017-05-05 13:26:27 +02:00
nTries + + ;
continue ;
}
2018-12-17 15:45:36 +01:00
if ( connman . IsMasternodeOrDisconnectRequested ( dmn - > pdmnState - > addr ) ) {
LogPrintf ( " CPrivateSendClientSession::StartNewQueue -- skipping masternode connection, addr=%s \n " , dmn - > pdmnState - > addr . ToString ( ) ) ;
Backport Bitcoin PR#8085: p2p: Begin encapsulation (#1537)
* net: move CBanDB and CAddrDB out of net.h/cpp
This will eventually solve a circular dependency
* net: Create CConnman to encapsulate p2p connections
* net: Move socket binding into CConnman
* net: move OpenNetworkConnection into CConnman
* net: move ban and addrman functions into CConnman
* net: Add oneshot functions to CConnman
* net: move added node functions to CConnman
* net: Add most functions needed for vNodes to CConnman
* net: handle nodesignals in CConnman
* net: Pass CConnection to wallet rather than using the global
* net: Add rpc error for missing/disabled p2p functionality
* net: Pass CConnman around as needed
* gui: add NodeID to the peer table
* net: create generic functor accessors and move vNodes to CConnman
* net: move whitelist functions into CConnman
* net: move nLastNodeId to CConnman
* net: move nLocalHostNonce to CConnman
This behavior seems to have been quite racy and broken.
Move nLocalHostNonce into CNode, and check received nonces against all
non-fully-connected nodes. If there's a match, assume we've connected
to ourself.
* net: move messageHandlerCondition to CConnman
* net: move send/recv statistics to CConnman
* net: move SendBufferSize/ReceiveFloodSize to CConnman
* net: move nLocalServices/nRelevantServices to CConnman
These are in-turn passed to CNode at connection time. This allows us to offer
different services to different peers (or test the effects of doing so).
* net: move semOutbound and semMasternodeOutbound to CConnman
* net: SocketSendData returns written size
* net: move max/max-outbound to CConnman
* net: Pass best block known height into CConnman
CConnman then passes the current best height into CNode at creation time.
This way CConnman/CNode have no dependency on main for height, and the signals
only move in one direction.
This also helps to prevent identity leakage a tiny bit. Before this change, an
attacker could theoretically make 2 connections on different interfaces. They
would connect fully on one, and only establish the initial connection on the
other. Once they receive a new block, they would relay it to your first
connection, and immediately commence the version handshake on the second. Since
the new block height is reflected immediately, they could attempt to learn
whether the two connections were correlated.
This is, of course, incredibly unlikely to work due to the small timings
involved and receipt from other senders. But it doesn't hurt to lock-in
nBestHeight at the time of connection, rather than letting the remote choose
the time.
* net: pass CClientUIInterface into CConnman
* net: Drop StartNode/StopNode and use CConnman directly
* net: Introduce CConnection::Options to avoid passing so many params
* net: add nSendBufferMaxSize/nReceiveFloodSize to CConnection::Options
* net: move vNodesDisconnected into CConnman
* Made the ForEachNode* functions in src/net.cpp more pragmatic and self documenting
* Convert ForEachNode* functions to take a templated function argument rather than a std::function to eliminate std::function overhead
* net: move MAX_FEELER_CONNECTIONS into connman
2017-07-21 11:35:19 +02:00
nTries + + ;
continue ;
2017-05-05 13:26:27 +02:00
}
2018-12-17 15:45:36 +01:00
LogPrintf ( " CPrivateSendClientSession::StartNewQueue -- attempt %d connection to Masternode %s \n " , nTries , dmn - > pdmnState - > addr . ToString ( ) ) ;
2018-02-01 02:10:52 +01:00
std : : vector < CAmount > vecAmounts ;
pwalletMain - > ConvertList ( vecTxIn , vecAmounts ) ;
// try to get a single random denom out of vecAmounts
2018-11-05 10:29:07 +01:00
while ( nSessionDenom = = 0 ) {
2018-02-01 02:10:52 +01:00
nSessionDenom = CPrivateSend : : GetDenominationsByAmounts ( vecAmounts ) ;
2017-05-05 13:26:27 +02:00
}
2018-02-01 02:10:52 +01:00
2018-12-17 15:45:36 +01:00
mixingMasternode = dmn ;
connman . AddPendingMasternode ( dmn - > pdmnState - > addr ) ;
pendingDsaRequest = CPendingDsaRequest ( dmn - > pdmnState - > addr , CPrivateSendAccept ( nSessionDenom , txMyCollateral ) ) ;
2018-02-01 02:10:52 +01:00
// TODO: add new state POOL_STATE_CONNECTING and bump MIN_PRIVATESEND_PEER_PROTO_VERSION
SetState ( POOL_STATE_QUEUE ) ;
2018-02-12 13:47:53 +01:00
nTimeLastSuccessfulStep = GetTime ( ) ;
2018-09-05 13:19:03 +02:00
LogPrintf ( " CPrivateSendClientSession::StartNewQueue -- pending connection, nSessionDenom: %d (%s), addr=%s \n " ,
2018-12-17 15:45:36 +01:00
nSessionDenom , CPrivateSend : : GetDenominationsToString ( nSessionDenom ) , dmn - > pdmnState - > addr . ToString ( ) ) ;
2018-02-01 02:10:52 +01:00
strAutoDenomResult = _ ( " Trying to connect... " ) ;
2018-01-17 16:09:08 +01:00
return true ;
2017-05-05 13:26:27 +02:00
}
2018-02-01 02:10:52 +01:00
strAutoDenomResult = _ ( " Failed to start a new mixing queue " ) ;
2017-05-05 13:26:27 +02:00
return false ;
}
2018-09-04 12:54:59 +02:00
bool CPrivateSendClientSession : : ProcessPendingDsaRequest ( CConnman & connman )
2018-02-01 02:10:52 +01:00
{
2018-09-04 12:54:59 +02:00
if ( ! pendingDsaRequest ) return false ;
2018-02-01 02:10:52 +01:00
bool fDone = connman . ForNode ( pendingDsaRequest . GetAddr ( ) , [ & ] ( CNode * pnode ) {
LogPrint ( " privatesend " , " -- processing dsa queue for addr=%s \n " , pnode - > addr . ToString ( ) ) ;
2018-02-12 13:47:53 +01:00
nTimeLastSuccessfulStep = GetTime ( ) ;
2018-02-01 02:10:52 +01:00
// TODO: this vvvv should be here after new state POOL_STATE_CONNECTING is added and MIN_PRIVATESEND_PEER_PROTO_VERSION is bumped
// SetState(POOL_STATE_QUEUE);
CNetMsgMaker msgMaker ( pnode - > GetSendVersion ( ) ) ;
connman . PushMessage ( pnode , msgMaker . Make ( NetMsgType : : DSACCEPT , pendingDsaRequest . GetDSA ( ) ) ) ;
return true ;
} ) ;
if ( fDone ) {
pendingDsaRequest = CPendingDsaRequest ( ) ;
} else if ( pendingDsaRequest . IsExpired ( ) ) {
2018-09-04 12:54:59 +02:00
LogPrint ( " privatesend " , " CPrivateSendClientSession::%s -- failed to connect to %s \n " , __func__ , pendingDsaRequest . GetAddr ( ) . ToString ( ) ) ;
2018-02-01 02:10:52 +01:00
SetNull ( ) ;
}
2018-09-04 12:54:59 +02:00
return fDone ;
}
void CPrivateSendClientManager : : ProcessPendingDsaRequest ( CConnman & connman )
{
2018-09-20 14:40:43 +02:00
LOCK ( cs_deqsessions ) ;
for ( auto & session : deqSessions ) {
2018-09-04 12:54:59 +02:00
if ( session . ProcessPendingDsaRequest ( connman ) ) {
strAutoDenomResult = _ ( " Mixing in progress... " ) ;
}
}
2018-02-01 02:10:52 +01:00
}
2018-09-04 12:54:59 +02:00
bool CPrivateSendClientSession : : SubmitDenominate ( CConnman & connman )
2017-05-05 13:26:27 +02:00
{
2018-09-04 12:54:59 +02:00
LOCK2 ( cs_main , pwalletMain - > cs_wallet ) ;
2017-05-05 13:26:27 +02:00
std : : string strError ;
2018-11-05 10:29:07 +01:00
std : : vector < std : : pair < CTxDSIn , CTxOut > > vecPSInOutPairs , vecPSInOutPairsTmp ;
2018-09-15 12:18:32 +02:00
if ( ! SelectDenominate ( strError , vecPSInOutPairs ) ) {
LogPrintf ( " CPrivateSendClientSession::SubmitDenominate -- SelectDenominate failed, error: %s \n " , strError ) ;
return false ;
}
2018-11-05 10:29:07 +01:00
std : : vector < std : : pair < int , size_t > > vecInputsByRounds ;
2018-10-15 13:58:47 +02:00
// Note: liquidity providers are fine with whatever number of inputs they've got
bool fDryRun = privateSendClient . nLiquidityProvider = = 0 ;
2017-05-05 13:26:27 +02:00
2018-10-15 13:58:47 +02:00
for ( int i = 0 ; i < privateSendClient . nPrivateSendRounds ; i + + ) {
if ( PrepareDenominate ( i , i , strError , vecPSInOutPairs , vecPSInOutPairsTmp , fDryRun ) ) {
LogPrintf ( " CPrivateSendClientSession::SubmitDenominate -- Running PrivateSend denominate for %d rounds, success \n " , i ) ;
if ( ! fDryRun ) {
2018-09-15 12:18:32 +02:00
return SendDenominate ( vecPSInOutPairsTmp , connman ) ;
2018-01-06 11:06:22 +01:00
}
2018-10-15 13:58:47 +02:00
vecInputsByRounds . emplace_back ( i , vecPSInOutPairsTmp . size ( ) ) ;
} else {
2018-09-11 20:33:06 +02:00
LogPrint ( " privatesend " , " CPrivateSendClientSession::SubmitDenominate -- Running PrivateSend denominate for %d rounds, error: %s \n " , i , strError ) ;
2017-05-05 13:26:27 +02:00
}
2018-10-15 13:58:47 +02:00
}
// more inputs first, for equal input count prefer the one with less rounds
std : : sort ( vecInputsByRounds . begin ( ) , vecInputsByRounds . end ( ) , [ ] ( const auto & a , const auto & b ) {
return a . second > b . second | | ( a . second = = b . second & & a . first < b . first ) ;
} ) ;
LogPrint ( " privatesend " , " vecInputsByRounds for denom %d \n " , nSessionDenom ) ;
for ( const auto & pair : vecInputsByRounds ) {
LogPrint ( " privatesend " , " vecInputsByRounds: rounds: %d, inputs: %d \n " , pair . first , pair . second ) ;
}
int nRounds = vecInputsByRounds . begin ( ) - > first ;
if ( PrepareDenominate ( nRounds , nRounds , strError , vecPSInOutPairs , vecPSInOutPairsTmp ) ) {
LogPrintf ( " CPrivateSendClientSession::SubmitDenominate -- Running PrivateSend denominate for %d rounds, success \n " , nRounds ) ;
return SendDenominate ( vecPSInOutPairsTmp , connman ) ;
2017-05-05 13:26:27 +02:00
}
// We failed? That's strange but let's just make final attempt and try to mix everything
2018-09-15 12:18:32 +02:00
if ( PrepareDenominate ( 0 , privateSendClient . nPrivateSendRounds - 1 , strError , vecPSInOutPairs , vecPSInOutPairsTmp ) ) {
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::SubmitDenominate -- Running PrivateSend denominate for all rounds, success \n " ) ;
2018-09-15 12:18:32 +02:00
return SendDenominate ( vecPSInOutPairsTmp , connman ) ;
2017-05-05 13:26:27 +02:00
}
// Should never actually get here but just in case
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::SubmitDenominate -- Running PrivateSend denominate for all rounds, error: %s \n " , strError ) ;
2017-05-05 13:26:27 +02:00
strAutoDenomResult = strError ;
return false ;
}
2018-11-05 10:29:07 +01:00
bool CPrivateSendClientSession : : SelectDenominate ( std : : string & strErrorRet , std : : vector < std : : pair < CTxDSIn , CTxOut > > & vecPSInOutPairsRet )
2017-05-05 13:26:27 +02:00
{
2018-09-15 12:18:32 +02:00
if ( ! pwalletMain ) {
2017-05-05 13:26:27 +02:00
strErrorRet = " Wallet is not initialized " ;
return false ;
}
if ( pwalletMain - > IsLocked ( true ) ) {
strErrorRet = " Wallet locked, unable to create transaction! " ;
return false ;
}
if ( GetEntriesCount ( ) > 0 ) {
strErrorRet = " Already have pending entries in the PrivateSend pool " ;
return false ;
}
2018-09-15 12:18:32 +02:00
vecPSInOutPairsRet . clear ( ) ;
2017-05-05 13:26:27 +02:00
std : : vector < int > vecBits ;
2017-06-30 20:30:16 +02:00
if ( ! CPrivateSend : : GetDenominationsBits ( nSessionDenom , vecBits ) ) {
2017-05-05 13:26:27 +02:00
strErrorRet = " Incorrect session denom " ;
return false ;
}
2017-06-30 20:30:16 +02:00
std : : vector < CAmount > vecStandardDenoms = CPrivateSend : : GetStandardDenominations ( ) ;
2018-09-15 12:18:32 +02:00
bool fSelected = pwalletMain - > SelectPSInOutPairsByDenominations ( nSessionDenom , vecStandardDenoms [ vecBits . front ( ) ] , CPrivateSend : : GetMaxPoolAmount ( ) , vecPSInOutPairsRet ) ;
if ( ! fSelected ) {
2017-05-05 13:26:27 +02:00
strErrorRet = " Can't select current denominated inputs " ;
return false ;
}
2018-09-15 12:18:32 +02:00
return true ;
}
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
bool CPrivateSendClientSession : : PrepareDenominate ( int nMinRounds , int nMaxRounds , std : : string & strErrorRet , const std : : vector < std : : pair < CTxDSIn , CTxOut > > & vecPSInOutPairsIn , std : : vector < std : : pair < CTxDSIn , CTxOut > > & vecPSInOutPairsRet , bool fDryRun )
2018-09-15 12:18:32 +02:00
{
std : : vector < int > vecBits ;
if ( ! CPrivateSend : : GetDenominationsBits ( nSessionDenom , vecBits ) ) {
strErrorRet = " Incorrect session denom " ;
return false ;
2017-05-05 13:26:27 +02:00
}
2018-09-15 12:18:32 +02:00
for ( const auto & pair : vecPSInOutPairsIn ) {
pwalletMain - > LockCoin ( pair . first . prevout ) ;
}
2017-05-05 13:26:27 +02:00
// NOTE: No need to randomize order of inputs because they were
2018-09-15 12:18:32 +02:00
// initially shuffled in CWallet::SelectPSInOutPairsByDenominations already.
int nDenomResult { 0 } ;
std : : vector < CAmount > vecStandardDenoms = CPrivateSend : : GetStandardDenominations ( ) ;
std : : vector < int > vecSteps ( vecStandardDenoms . size ( ) , 0 ) ;
vecPSInOutPairsRet . clear ( ) ;
2017-05-05 13:26:27 +02:00
2018-10-15 13:58:47 +02:00
// Try to add up to PRIVATESEND_ENTRY_MAX_SIZE of every needed denomination
2018-11-05 10:29:07 +01:00
for ( const auto & pair : vecPSInOutPairsIn ) {
2018-09-15 12:18:32 +02:00
if ( pair . second . nRounds < nMinRounds | | pair . second . nRounds > nMaxRounds ) {
// unlock unused coins
pwalletMain - > UnlockCoin ( pair . first . prevout ) ;
continue ;
}
bool fFound = false ;
2018-02-06 12:09:33 +01:00
for ( const auto & nBit : vecBits ) {
2018-10-15 13:58:47 +02:00
if ( vecSteps [ nBit ] > = PRIVATESEND_ENTRY_MAX_SIZE ) break ;
2017-06-30 20:30:16 +02:00
CAmount nValueDenom = vecStandardDenoms [ nBit ] ;
2018-09-15 12:18:32 +02:00
if ( pair . second . nValue = = nValueDenom ) {
2018-10-15 13:58:47 +02:00
CScript scriptDenom ;
if ( fDryRun ) {
scriptDenom = CScript ( ) ;
} else {
// randomly skip some inputs when we have at least one of the same denom already
// TODO: make it adjustable via options/cmd-line params
if ( vecSteps [ nBit ] > = 1 & & GetRandInt ( 5 ) = = 0 ) {
// still count it as a step to randomize number of inputs
// if we have more than (or exactly) PRIVATESEND_ENTRY_MAX_SIZE of them
+ + vecSteps [ nBit ] ;
break ;
}
scriptDenom = keyHolderStorage . AddKey ( pwalletMain ) ;
}
2018-09-15 12:18:32 +02:00
vecPSInOutPairsRet . emplace_back ( pair . first , CTxOut ( nValueDenom , scriptDenom ) ) ;
fFound = true ;
nDenomResult | = 1 < < nBit ;
// step is complete
+ + vecSteps [ nBit ] ;
break ;
2017-05-05 13:26:27 +02:00
}
}
2018-10-15 13:58:47 +02:00
if ( ! fFound | | fDryRun ) {
// unlock unused coins and if we are not going to mix right away
2018-09-15 12:18:32 +02:00
pwalletMain - > UnlockCoin ( pair . first . prevout ) ;
2017-05-05 13:26:27 +02:00
}
}
2018-09-15 12:18:32 +02:00
if ( nDenomResult ! = nSessionDenom ) {
// unlock used coins on failure
for ( const auto & pair : vecPSInOutPairsRet ) {
pwalletMain - > UnlockCoin ( pair . first . prevout ) ;
2017-05-05 13:26:27 +02:00
}
2017-09-11 16:14:55 +02:00
keyHolderStorage . ReturnAll ( ) ;
2018-09-04 12:54:59 +02:00
strErrorRet = " Can't prepare current denominated outputs " ;
2017-05-05 13:26:27 +02:00
return false ;
}
return true ;
}
// Create collaterals by looping through inputs grouped by addresses
2018-09-04 12:54:59 +02:00
bool CPrivateSendClientSession : : MakeCollateralAmounts ( CConnman & connman )
2017-05-05 13:26:27 +02:00
{
2018-07-28 15:50:41 +02:00
if ( ! pwalletMain ) return false ;
2017-05-05 13:26:27 +02:00
std : : vector < CompactTallyItem > vecTally ;
2018-11-05 10:29:07 +01:00
if ( ! pwalletMain - > SelectCoinsGroupedByAddresses ( vecTally , false , false ) ) {
2018-10-25 16:32:08 +02:00
LogPrint ( " privatesend " , " CPrivateSendClientSession::MakeCollateralAmounts -- SelectCoinsGroupedByAddresses can't find any inputs! \n " ) ;
2017-05-05 13:26:27 +02:00
return false ;
}
2018-11-26 14:22:39 +01:00
// Start from smallest balances first to consume tiny amounts and cleanup UTXO a bit
std : : sort ( vecTally . begin ( ) , vecTally . end ( ) , [ ] ( const CompactTallyItem & a , const CompactTallyItem & b ) {
return a . nAmount < b . nAmount ;
} ) ;
2017-07-10 16:42:32 +02:00
// First try to use only non-denominated funds
2018-02-06 12:09:33 +01:00
for ( const auto & item : vecTally ) {
2018-11-05 10:29:07 +01:00
if ( ! MakeCollateralAmounts ( item , false , connman ) ) continue ;
2017-05-05 13:26:27 +02:00
return true ;
}
2017-07-10 16:42:32 +02:00
// There should be at least some denominated funds we should be able to break in pieces to continue mixing
2018-02-06 12:09:33 +01:00
for ( const auto & item : vecTally ) {
2018-11-05 10:29:07 +01:00
if ( ! MakeCollateralAmounts ( item , true , connman ) ) continue ;
2017-07-10 16:42:32 +02:00
return true ;
}
// If we got here then smth is terribly broken actually
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::MakeCollateralAmounts -- ERROR: Can't make collaterals! \n " ) ;
2017-05-05 13:26:27 +02:00
return false ;
}
// Split up large inputs or create fee sized inputs
2018-09-04 12:54:59 +02:00
bool CPrivateSendClientSession : : MakeCollateralAmounts ( const CompactTallyItem & tallyItem , bool fTryDenominated , CConnman & connman )
2017-05-05 13:26:27 +02:00
{
2018-07-28 15:50:41 +02:00
if ( ! pwalletMain ) return false ;
2017-07-10 16:42:32 +02:00
LOCK2 ( cs_main , pwalletMain - > cs_wallet ) ;
2017-09-27 19:42:53 +02:00
// denominated input is always a single one, so we can check its amount directly and return early
2018-11-05 10:29:07 +01:00
if ( ! fTryDenominated & & tallyItem . vecOutPoints . size ( ) = = 1 & & CPrivateSend : : IsDenominatedAmount ( tallyItem . nAmount ) )
2017-09-27 19:42:53 +02:00
return false ;
2017-05-05 13:26:27 +02:00
CWalletTx wtx ;
CAmount nFeeRet = 0 ;
int nChangePosRet = - 1 ;
std : : string strFail = " " ;
std : : vector < CRecipient > vecSend ;
// make our collateral address
CReserveKey reservekeyCollateral ( pwalletMain ) ;
// make our change address
CReserveKey reservekeyChange ( pwalletMain ) ;
CScript scriptCollateral ;
CPubKey vchPubKey ;
2017-05-29 13:51:40 +02:00
assert ( reservekeyCollateral . GetReservedKey ( vchPubKey , false ) ) ; // should never fail, as we just unlocked
2017-05-05 13:26:27 +02:00
scriptCollateral = GetScriptForDestination ( vchPubKey . GetID ( ) ) ;
2017-06-30 20:30:16 +02:00
vecSend . push_back ( ( CRecipient ) { scriptCollateral , CPrivateSend : : GetMaxCollateralAmount ( ) , false } ) ;
2017-05-05 13:26:27 +02:00
// try to use non-denominated and not mn-like funds first, select them explicitly
CCoinControl coinControl ;
coinControl . fAllowOtherInputs = false ;
coinControl . fAllowWatchOnly = false ;
// send change to the same address so that we were able create more denoms out of it later
2017-09-27 19:43:16 +02:00
coinControl . destChange = tallyItem . txdest ;
2018-02-15 08:29:31 +01:00
for ( const auto & outpoint : tallyItem . vecOutPoints )
coinControl . Select ( outpoint ) ;
2017-05-05 13:26:27 +02:00
bool fSuccess = pwalletMain - > CreateTransaction ( vecSend , wtx , reservekeyChange ,
2018-11-05 10:29:07 +01:00
nFeeRet , nChangePosRet , strFail , & coinControl , true , ONLY_NONDENOMINATED ) ;
if ( ! fSuccess ) {
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::MakeCollateralAmounts -- ONLY_NONDENOMINATED: %s \n " , strFail ) ;
2018-02-08 06:46:44 +01:00
// If we failed then most likely there are not enough funds on this address.
2018-11-05 10:29:07 +01:00
if ( fTryDenominated ) {
2017-07-10 16:42:32 +02:00
// Try to also use denominated coins (we can't mix denominated without collaterals anyway).
2018-11-05 10:29:07 +01:00
if ( ! pwalletMain - > CreateTransaction ( vecSend , wtx , reservekeyChange ,
nFeeRet , nChangePosRet , strFail , & coinControl , true , ALL_COINS ) ) {
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::MakeCollateralAmounts -- ALL_COINS Error: %s \n " , strFail ) ;
2017-07-10 16:42:32 +02:00
reservekeyCollateral . ReturnKey ( ) ;
return false ;
}
} else {
// Nothing else we can do.
2017-05-05 13:26:27 +02:00
reservekeyCollateral . ReturnKey ( ) ;
return false ;
}
}
reservekeyCollateral . KeepKey ( ) ;
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::MakeCollateralAmounts -- txid=%s \n " , wtx . GetHash ( ) . GetHex ( ) ) ;
2017-05-05 13:26:27 +02:00
2018-02-08 06:46:44 +01:00
// use the same nCachedLastSuccessBlock as for DS mixing to prevent race
2016-10-28 13:49:04 +02:00
CValidationState state ;
2018-11-05 10:29:07 +01:00
if ( ! pwalletMain - > CommitTransaction ( wtx , reservekeyChange , & connman , state ) ) {
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::MakeCollateralAmounts -- CommitTransaction failed! Reason given: %s \n " , state . GetRejectReason ( ) ) ;
2017-05-05 13:26:27 +02:00
return false ;
}
2018-09-04 12:54:59 +02:00
privateSendClient . UpdatedSuccessBlock ( ) ;
2017-05-05 13:26:27 +02:00
return true ;
}
// Create denominations by looping through inputs grouped by addresses
2018-09-04 12:54:59 +02:00
bool CPrivateSendClientSession : : CreateDenominated ( CConnman & connman )
2017-05-05 13:26:27 +02:00
{
2018-07-28 15:50:41 +02:00
if ( ! pwalletMain ) return false ;
2017-05-28 15:50:07 +02:00
LOCK2 ( cs_main , pwalletMain - > cs_wallet ) ;
2018-11-25 14:27:31 +01:00
// NOTE: We do not allow txes larger than 100kB, so we have to limit number of inputs here.
// We still want to consume a lot of inputs to avoid creating only smaller denoms though.
// Knowing that each CTxIn is at least 148b big, 400 inputs should take 400 x ~148b = ~60kB.
// This still leaves more than enough room for another data of typical CreateDenominated tx.
2017-05-05 13:26:27 +02:00
std : : vector < CompactTallyItem > vecTally ;
2018-11-25 14:27:31 +01:00
if ( ! pwalletMain - > SelectCoinsGroupedByAddresses ( vecTally , true , true , true , 400 ) ) {
2018-10-25 16:32:08 +02:00
LogPrint ( " privatesend " , " CPrivateSendClientSession::CreateDenominated -- SelectCoinsGroupedByAddresses can't find any inputs! \n " ) ;
2017-05-05 13:26:27 +02:00
return false ;
}
2018-11-26 14:22:39 +01:00
// Start from largest balances first to speed things up by creating txes with larger/largest denoms included
std : : sort ( vecTally . begin ( ) , vecTally . end ( ) , [ ] ( const CompactTallyItem & a , const CompactTallyItem & b ) {
return a . nAmount > b . nAmount ;
} ) ;
2017-05-05 13:26:27 +02:00
bool fCreateMixingCollaterals = ! pwalletMain - > HasCollateralInputs ( ) ;
2018-02-06 12:09:33 +01:00
for ( const auto & item : vecTally ) {
2018-11-05 10:29:07 +01:00
if ( ! CreateDenominated ( item , fCreateMixingCollaterals , connman ) ) continue ;
2017-05-05 13:26:27 +02:00
return true ;
}
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::CreateDenominated -- failed! \n " ) ;
2017-05-05 13:26:27 +02:00
return false ;
}
// Create denominations
2018-09-04 12:54:59 +02:00
bool CPrivateSendClientSession : : CreateDenominated ( const CompactTallyItem & tallyItem , bool fCreateMixingCollaterals , CConnman & connman )
2017-05-05 13:26:27 +02:00
{
2018-07-28 15:50:41 +02:00
if ( ! pwalletMain ) return false ;
2017-05-05 13:26:27 +02:00
std : : vector < CRecipient > vecSend ;
2017-09-11 16:14:55 +02:00
CKeyHolderStorage keyHolderStorageDenom ;
2017-05-05 13:26:27 +02:00
CAmount nValueLeft = tallyItem . nAmount ;
2017-06-30 20:30:16 +02:00
nValueLeft - = CPrivateSend : : GetCollateralAmount ( ) ; // leave some room for fees
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
LogPrintf ( " CPrivateSendClientSession::CreateDenominated -- 0 - %s nValueLeft: %f \n " , CBitcoinAddress ( tallyItem . txdest ) . ToString ( ) , ( float ) nValueLeft / COIN ) ;
2017-05-05 13:26:27 +02:00
2017-09-11 16:14:55 +02:00
// ****** Add an output for mixing collaterals ************ /
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
if ( fCreateMixingCollaterals ) {
2018-01-09 12:11:43 +01:00
CScript scriptCollateral = keyHolderStorageDenom . AddKey ( pwalletMain ) ;
2018-11-05 10:29:07 +01:00
vecSend . push_back ( ( CRecipient ) { scriptCollateral , CPrivateSend : : GetMaxCollateralAmount ( ) , false } ) ;
2017-06-30 20:30:16 +02:00
nValueLeft - = CPrivateSend : : GetMaxCollateralAmount ( ) ;
2017-05-05 13:26:27 +02:00
}
2017-09-11 16:14:55 +02:00
// ****** Add outputs for denoms ************ /
2017-05-05 13:26:27 +02:00
2017-09-11 16:14:55 +02:00
// try few times - skipping smallest denoms first if there are too many of them already, if failed - use them too
2017-05-05 13:26:27 +02:00
int nOutputsTotal = 0 ;
bool fSkip = true ;
do {
2017-06-30 20:30:16 +02:00
std : : vector < CAmount > vecStandardDenoms = CPrivateSend : : GetStandardDenominations ( ) ;
2017-05-05 13:26:27 +02:00
2018-07-12 11:07:51 +02:00
for ( auto it = vecStandardDenoms . rbegin ( ) ; it ! = vecStandardDenoms . rend ( ) ; + + it ) {
CAmount nDenomValue = * it ;
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
if ( fSkip ) {
2017-05-05 13:26:27 +02:00
// Note: denoms are skipped if there are already DENOMS_COUNT_MAX of them
// and there are still larger denoms which can be used for mixing
// check skipped denoms
2018-11-05 10:29:07 +01:00
if ( privateSendClient . IsDenomSkipped ( nDenomValue ) ) {
strAutoDenomResult = strprintf ( _ ( " Too many %f denominations, skipping. " ) , ( float ) nDenomValue / COIN ) ;
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::CreateDenominated -- %s \n " , strAutoDenomResult ) ;
continue ;
}
2017-05-05 13:26:27 +02:00
// find new denoms to skip if any (ignore the largest one)
2018-11-05 10:29:07 +01:00
if ( nDenomValue ! = vecStandardDenoms . front ( ) & & pwalletMain - > CountInputsWithAmount ( nDenomValue ) > DENOMS_COUNT_MAX ) {
strAutoDenomResult = strprintf ( _ ( " Too many %f denominations, removing. " ) , ( float ) nDenomValue / COIN ) ;
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::CreateDenominated -- %s \n " , strAutoDenomResult ) ;
privateSendClient . AddSkippedDenom ( nDenomValue ) ;
2017-05-05 13:26:27 +02:00
continue ;
}
}
int nOutputs = 0 ;
2017-05-28 15:50:07 +02:00
// add each output up to 11 times until it can't be added again
2018-11-05 10:29:07 +01:00
while ( nValueLeft - nDenomValue > = 0 & & nOutputs < = 10 ) {
2018-01-09 12:11:43 +01:00
CScript scriptDenom = keyHolderStorageDenom . AddKey ( pwalletMain ) ;
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
vecSend . push_back ( ( CRecipient ) { scriptDenom , nDenomValue , false } ) ;
2017-05-05 13:26:27 +02:00
//increment outputs and subtract denomination amount
nOutputs + + ;
nValueLeft - = nDenomValue ;
2018-11-05 10:29:07 +01:00
LogPrintf ( " CPrivateSendClientSession::CreateDenominated -- 1 - totalOutputs: %d, nOutputsTotal: %d, nOutputs: %d, nValueLeft: %f \n " , nOutputsTotal + nOutputs , nOutputsTotal , nOutputs , ( float ) nValueLeft / COIN ) ;
2017-05-05 13:26:27 +02:00
}
nOutputsTotal + = nOutputs ;
2018-11-05 10:29:07 +01:00
if ( nValueLeft = = 0 ) break ;
2017-05-05 13:26:27 +02:00
}
2018-11-05 10:29:07 +01:00
LogPrintf ( " CPrivateSendClientSession::CreateDenominated -- 2 - nOutputsTotal: %d, nValueLeft: %f \n " , nOutputsTotal , ( float ) nValueLeft / COIN ) ;
2017-05-05 13:26:27 +02:00
// if there were no outputs added, start over without skipping
fSkip = ! fSkip ;
} while ( nOutputsTotal = = 0 & & ! fSkip ) ;
2018-11-05 10:29:07 +01:00
LogPrintf ( " CPrivateSendClientSession::CreateDenominated -- 3 - nOutputsTotal: %d, nValueLeft: %f \n " , nOutputsTotal , ( float ) nValueLeft / COIN ) ;
2017-05-05 13:26:27 +02:00
2018-09-15 12:19:00 +02:00
// No reasons to create mixing collaterals if we can't create denoms to mix
if ( nOutputsTotal = = 0 ) return false ;
2017-05-05 13:26:27 +02:00
// if we have anything left over, it will be automatically send back as change - there is no need to send it manually
CCoinControl coinControl ;
coinControl . fAllowOtherInputs = false ;
coinControl . fAllowWatchOnly = false ;
// send change to the same address so that we were able create more denoms out of it later
2017-09-27 19:43:16 +02:00
coinControl . destChange = tallyItem . txdest ;
2018-02-15 08:29:31 +01:00
for ( const auto & outpoint : tallyItem . vecOutPoints )
coinControl . Select ( outpoint ) ;
2017-05-05 13:26:27 +02:00
CWalletTx wtx ;
CAmount nFeeRet = 0 ;
int nChangePosRet = - 1 ;
std : : string strFail = " " ;
// make our change address
CReserveKey reservekeyChange ( pwalletMain ) ;
bool fSuccess = pwalletMain - > CreateTransaction ( vecSend , wtx , reservekeyChange ,
2018-11-05 10:29:07 +01:00
nFeeRet , nChangePosRet , strFail , & coinControl , true , ONLY_NONDENOMINATED ) ;
if ( ! fSuccess ) {
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::CreateDenominated -- Error: %s \n " , strFail ) ;
2017-09-11 16:14:55 +02:00
keyHolderStorageDenom . ReturnAll ( ) ;
2017-05-05 13:26:27 +02:00
return false ;
}
2017-09-11 16:14:55 +02:00
keyHolderStorageDenom . KeepAll ( ) ;
2017-05-05 13:26:27 +02:00
2016-10-28 13:49:04 +02:00
CValidationState state ;
2018-11-05 10:29:07 +01:00
if ( ! pwalletMain - > CommitTransaction ( wtx , reservekeyChange , & connman , state ) ) {
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::CreateDenominated -- CommitTransaction failed! Reason given: %s \n " , state . GetRejectReason ( ) ) ;
2017-05-05 13:26:27 +02:00
return false ;
}
// use the same nCachedLastSuccessBlock as for DS mixing to prevent race
2018-09-04 12:54:59 +02:00
privateSendClient . UpdatedSuccessBlock ( ) ;
LogPrintf ( " CPrivateSendClientSession::CreateDenominated -- txid=%s \n " , wtx . GetHash ( ) . GetHex ( ) ) ;
2017-05-05 13:26:27 +02:00
return true ;
}
2018-10-25 16:31:32 +02:00
void CPrivateSendClientSession : : RelayIn ( const CPrivateSendEntry & entry , CConnman & connman )
2017-05-05 13:26:27 +02:00
{
2018-12-17 15:45:36 +01:00
if ( ! mixingMasternode ) return ;
2017-05-05 13:26:27 +02:00
2018-12-17 15:45:36 +01:00
connman . ForNode ( mixingMasternode - > pdmnState - > addr , [ & entry , & connman ] ( CNode * pnode ) {
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::RelayIn -- found master, relaying message to %s \n " , pnode - > addr . ToString ( ) ) ;
2016-11-25 20:01:56 +01:00
CNetMsgMaker msgMaker ( pnode - > GetSendVersion ( ) ) ;
connman . PushMessage ( pnode , msgMaker . Make ( NetMsgType : : DSVIN , entry ) ) ;
Backport Bitcoin PR#8085: p2p: Begin encapsulation (#1537)
* net: move CBanDB and CAddrDB out of net.h/cpp
This will eventually solve a circular dependency
* net: Create CConnman to encapsulate p2p connections
* net: Move socket binding into CConnman
* net: move OpenNetworkConnection into CConnman
* net: move ban and addrman functions into CConnman
* net: Add oneshot functions to CConnman
* net: move added node functions to CConnman
* net: Add most functions needed for vNodes to CConnman
* net: handle nodesignals in CConnman
* net: Pass CConnection to wallet rather than using the global
* net: Add rpc error for missing/disabled p2p functionality
* net: Pass CConnman around as needed
* gui: add NodeID to the peer table
* net: create generic functor accessors and move vNodes to CConnman
* net: move whitelist functions into CConnman
* net: move nLastNodeId to CConnman
* net: move nLocalHostNonce to CConnman
This behavior seems to have been quite racy and broken.
Move nLocalHostNonce into CNode, and check received nonces against all
non-fully-connected nodes. If there's a match, assume we've connected
to ourself.
* net: move messageHandlerCondition to CConnman
* net: move send/recv statistics to CConnman
* net: move SendBufferSize/ReceiveFloodSize to CConnman
* net: move nLocalServices/nRelevantServices to CConnman
These are in-turn passed to CNode at connection time. This allows us to offer
different services to different peers (or test the effects of doing so).
* net: move semOutbound and semMasternodeOutbound to CConnman
* net: SocketSendData returns written size
* net: move max/max-outbound to CConnman
* net: Pass best block known height into CConnman
CConnman then passes the current best height into CNode at creation time.
This way CConnman/CNode have no dependency on main for height, and the signals
only move in one direction.
This also helps to prevent identity leakage a tiny bit. Before this change, an
attacker could theoretically make 2 connections on different interfaces. They
would connect fully on one, and only establish the initial connection on the
other. Once they receive a new block, they would relay it to your first
connection, and immediately commence the version handshake on the second. Since
the new block height is reflected immediately, they could attempt to learn
whether the two connections were correlated.
This is, of course, incredibly unlikely to work due to the small timings
involved and receipt from other senders. But it doesn't hurt to lock-in
nBestHeight at the time of connection, rather than letting the remote choose
the time.
* net: pass CClientUIInterface into CConnman
* net: Drop StartNode/StopNode and use CConnman directly
* net: Introduce CConnection::Options to avoid passing so many params
* net: add nSendBufferMaxSize/nReceiveFloodSize to CConnection::Options
* net: move vNodesDisconnected into CConnman
* Made the ForEachNode* functions in src/net.cpp more pragmatic and self documenting
* Convert ForEachNode* functions to take a templated function argument rather than a std::function to eliminate std::function overhead
* net: move MAX_FEELER_CONNECTIONS into connman
2017-07-21 11:35:19 +02:00
return true ;
} ) ;
2017-05-05 13:26:27 +02:00
}
2018-09-04 12:54:59 +02:00
void CPrivateSendClientSession : : SetState ( PoolState nStateNew )
2017-05-05 13:26:27 +02:00
{
2018-09-04 12:54:59 +02:00
LogPrintf ( " CPrivateSendClientSession::SetState -- nState: %d, nStateNew: %d \n " , nState , nStateNew ) ;
2017-05-05 13:26:27 +02:00
nState = nStateNew ;
}
2018-11-05 10:29:07 +01:00
void CPrivateSendClientManager : : UpdatedBlockTip ( const CBlockIndex * pindex )
2017-05-05 13:26:27 +02:00
{
2017-08-25 14:57:05 +02:00
nCachedBlockHeight = pindex - > nHeight ;
2018-09-04 12:54:59 +02:00
LogPrint ( " privatesend " , " CPrivateSendClientManager::UpdatedBlockTip -- nCachedBlockHeight: %d \n " , nCachedBlockHeight ) ;
2017-05-05 13:26:27 +02:00
}
2018-09-04 12:54:59 +02:00
void CPrivateSendClientManager : : DoMaintenance ( CConnman & connman )
2017-05-05 13:26:27 +02:00
{
2018-11-05 10:29:07 +01:00
if ( fLiteMode ) return ; // disable all Dash specific functionality
if ( fMasternodeMode ) return ; // no client-side mixing on masternodes
2017-05-05 13:26:27 +02:00
2018-11-05 10:29:07 +01:00
if ( ! masternodeSync . IsBlockchainSynced ( ) | | ShutdownRequested ( ) )
2018-07-16 14:47:37 +02:00
return ;
2017-05-05 13:26:27 +02:00
2018-07-16 14:47:37 +02:00
static unsigned int nTick = 0 ;
static unsigned int nDoAutoNextRun = nTick + PRIVATESEND_AUTO_TIMEOUT_MIN ;
2017-05-05 13:26:27 +02:00
2018-07-16 14:47:37 +02:00
nTick + + ;
2018-09-04 12:54:59 +02:00
CheckTimeout ( ) ;
ProcessPendingDsaRequest ( connman ) ;
2018-11-05 10:29:07 +01:00
if ( nDoAutoNextRun = = nTick ) {
2018-09-04 12:54:59 +02:00
DoAutomaticDenominating ( connman ) ;
2018-07-16 14:47:37 +02:00
nDoAutoNextRun = nTick + PRIVATESEND_AUTO_TIMEOUT_MIN + GetRandInt ( PRIVATESEND_AUTO_TIMEOUT_MAX - PRIVATESEND_AUTO_TIMEOUT_MIN ) ;
2017-05-05 13:26:27 +02:00
}
}