From 571798f44092c2ade72c45344dfd18aa9c70debf Mon Sep 17 00:00:00 2001 From: Duality-CDOO Date: Sun, 14 Oct 2018 00:01:22 +0200 Subject: [PATCH 1/2] clang-format all dash specific files --- src/activemasternode.cpp | 132 +++-- src/activemasternode.h | 29 +- src/dsnotificationinterface.cpp | 16 +- src/dsnotificationinterface.h | 11 +- src/governance-classes.cpp | 8 +- src/governance-vote.cpp | 25 +- src/governance-vote.h | 18 +- src/governance.cpp | 4 +- src/masternode-payments.cpp | 264 +++++----- src/masternode-payments.h | 40 +- src/masternode-sync.cpp | 222 ++++---- src/masternode-sync.h | 30 +- src/masternode.cpp | 253 ++++----- src/masternode.h | 93 ++-- src/masternodeconfig.cpp | 45 +- src/masternodeconfig.h | 37 +- src/masternodeman.cpp | 470 +++++++++-------- src/masternodeman.h | 54 +- src/privatesend-client.cpp | 631 ++++++++++++----------- src/privatesend-client.h | 64 +-- src/privatesend-server.cpp | 246 +++++---- src/privatesend-server.h | 9 +- src/privatesend-util.cpp | 8 +- src/privatesend-util.h | 3 +- src/privatesend.cpp | 193 ++++--- src/privatesend.h | 76 +-- src/qt/masternodelist.cpp | 159 +++--- src/qt/masternodelist.h | 33 +- src/rpc/governance.cpp | 409 +++++++-------- src/rpc/masternode.cpp | 361 ++++++------- src/test/governance_validators_tests.cpp | 10 +- 31 files changed, 1993 insertions(+), 1960 deletions(-) diff --git a/src/activemasternode.cpp b/src/activemasternode.cpp index 844622f36df9..b3631f51ee1b 100644 --- a/src/activemasternode.cpp +++ b/src/activemasternode.cpp @@ -3,15 +3,14 @@ // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "activemasternode.h" -#include "masternode.h" +#include "evo/deterministicmns.h" +#include "init.h" #include "masternode-sync.h" +#include "masternode.h" #include "masternodeman.h" #include "netbase.h" #include "protocol.h" -#include "netbase.h" #include "warnings.h" -#include "init.h" -#include "evo/deterministicmns.h" // Keep track of the active Masternode CActiveMasternodeInfo activeMasternodeInfo; @@ -21,24 +20,36 @@ CActiveDeterministicMasternodeManager* activeMasternodeManager; std::string CActiveDeterministicMasternodeManager::GetStateString() const { switch (state) { - case MASTERNODE_WAITING_FOR_PROTX: return "WAITING_FOR_PROTX"; - case MASTERNODE_POSE_BANNED: return "POSE_BANNED"; - case MASTERNODE_REMOVED: return "REMOVED"; - case MASTERNODE_READY: return "READY"; - case MASTERNODE_ERROR: return "ERROR"; - default: return "UNKNOWN"; + case MASTERNODE_WAITING_FOR_PROTX: + return "WAITING_FOR_PROTX"; + case MASTERNODE_POSE_BANNED: + return "POSE_BANNED"; + case MASTERNODE_REMOVED: + return "REMOVED"; + case MASTERNODE_READY: + return "READY"; + case MASTERNODE_ERROR: + return "ERROR"; + default: + return "UNKNOWN"; } } std::string CActiveDeterministicMasternodeManager::GetStatus() const { switch (state) { - case MASTERNODE_WAITING_FOR_PROTX: return "Waiting for ProTx to appear on-chain"; - case MASTERNODE_POSE_BANNED: return "Masternode was PoSe banned"; - case MASTERNODE_REMOVED: return "Masternode removed from list"; - case MASTERNODE_READY: return "Ready"; - case MASTERNODE_ERROR: return "Error. " + strError; - default: return "Unknown"; + case MASTERNODE_WAITING_FOR_PROTX: + return "Waiting for ProTx to appear on-chain"; + case MASTERNODE_POSE_BANNED: + return "Masternode was PoSe banned"; + case MASTERNODE_REMOVED: + return "Masternode removed from list"; + case MASTERNODE_READY: + return "Ready"; + case MASTERNODE_ERROR: + return "Error. " + strError; + default: + return "Unknown"; } } @@ -123,7 +134,7 @@ void CActiveDeterministicMasternodeManager::UpdatedBlockTip(const CBlockIndex* p } } -bool CActiveDeterministicMasternodeManager::GetLocalAddress(CService &addrRet) +bool CActiveDeterministicMasternodeManager::GetLocalAddress(CService& addrRet) { // First try to find whatever local address is specified by externalip option bool fFoundLocal = GetLocal(addrRet) && CMasternode::IsValidNetAddr(addrRet); @@ -132,7 +143,7 @@ bool CActiveDeterministicMasternodeManager::GetLocalAddress(CService &addrRet) fFoundLocal = true; } } - if(!fFoundLocal) { + if (!fFoundLocal) { strError = "Can't detect valid external address. Please consider using the externalip configuration option if problem persists. Make sure to use IPv4 address only."; LogPrintf("CActiveDeterministicMasternodeManager::GetLocalAddress -- ERROR: %s\n", strError); return false; @@ -148,27 +159,27 @@ void CActiveLegacyMasternodeManager::ManageState(CConnman& connman) return; LogPrint("masternode", "CActiveLegacyMasternodeManager::ManageState -- Start\n"); - if(!fMasternodeMode) { + if (!fMasternodeMode) { LogPrint("masternode", "CActiveLegacyMasternodeManager::ManageState -- Not a masternode, returning\n"); return; } - if(Params().NetworkIDString() != CBaseChainParams::REGTEST && !masternodeSync.IsBlockchainSynced()) { + if (Params().NetworkIDString() != CBaseChainParams::REGTEST && !masternodeSync.IsBlockchainSynced()) { nState = ACTIVE_MASTERNODE_SYNC_IN_PROCESS; LogPrintf("CActiveLegacyMasternodeManager::ManageState -- %s: %s\n", GetStateString(), GetStatus()); return; } - if(nState == ACTIVE_MASTERNODE_SYNC_IN_PROCESS) { + if (nState == ACTIVE_MASTERNODE_SYNC_IN_PROCESS) { nState = ACTIVE_MASTERNODE_INITIAL; } LogPrint("masternode", "CActiveLegacyMasternodeManager::ManageState -- status = %s, type = %s, pinger enabled = %d\n", GetStatus(), GetTypeString(), fPingerEnabled); - if(eType == MASTERNODE_UNKNOWN) { + if (eType == MASTERNODE_UNKNOWN) { ManageStateInitial(connman); } - if(eType == MASTERNODE_REMOTE) { + if (eType == MASTERNODE_REMOTE) { ManageStateRemote(); } @@ -178,31 +189,43 @@ void CActiveLegacyMasternodeManager::ManageState(CConnman& connman) std::string CActiveLegacyMasternodeManager::GetStateString() const { switch (nState) { - case ACTIVE_MASTERNODE_INITIAL: return "INITIAL"; - case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return "SYNC_IN_PROCESS"; - case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return "INPUT_TOO_NEW"; - case ACTIVE_MASTERNODE_NOT_CAPABLE: return "NOT_CAPABLE"; - case ACTIVE_MASTERNODE_STARTED: return "STARTED"; - default: return "UNKNOWN"; + case ACTIVE_MASTERNODE_INITIAL: + return "INITIAL"; + case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: + return "SYNC_IN_PROCESS"; + case ACTIVE_MASTERNODE_INPUT_TOO_NEW: + return "INPUT_TOO_NEW"; + case ACTIVE_MASTERNODE_NOT_CAPABLE: + return "NOT_CAPABLE"; + case ACTIVE_MASTERNODE_STARTED: + return "STARTED"; + default: + return "UNKNOWN"; } } std::string CActiveLegacyMasternodeManager::GetStatus() const { switch (nState) { - case ACTIVE_MASTERNODE_INITIAL: return "Node just started, not yet activated"; - case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: return "Sync in progress. Must wait until sync is complete to start Masternode"; - case ACTIVE_MASTERNODE_INPUT_TOO_NEW: return strprintf("Masternode input must have at least %d confirmations", Params().GetConsensus().nMasternodeMinimumConfirmations); - case ACTIVE_MASTERNODE_NOT_CAPABLE: return "Not capable masternode: " + strNotCapableReason; - case ACTIVE_MASTERNODE_STARTED: return "Masternode successfully started"; - default: return "Unknown"; + case ACTIVE_MASTERNODE_INITIAL: + return "Node just started, not yet activated"; + case ACTIVE_MASTERNODE_SYNC_IN_PROCESS: + return "Sync in progress. Must wait until sync is complete to start Masternode"; + case ACTIVE_MASTERNODE_INPUT_TOO_NEW: + return strprintf("Masternode input must have at least %d confirmations", Params().GetConsensus().nMasternodeMinimumConfirmations); + case ACTIVE_MASTERNODE_NOT_CAPABLE: + return "Not capable masternode: " + strNotCapableReason; + case ACTIVE_MASTERNODE_STARTED: + return "Masternode successfully started"; + default: + return "Unknown"; } } std::string CActiveLegacyMasternodeManager::GetTypeString() const { std::string strType; - switch(eType) { + switch (eType) { case MASTERNODE_REMOTE: strType = "REMOTE"; break; @@ -218,12 +241,12 @@ bool CActiveLegacyMasternodeManager::SendMasternodePing(CConnman& connman) if (deterministicMNManager->IsDeterministicMNsSporkActive()) return false; - if(!fPingerEnabled) { + if (!fPingerEnabled) { LogPrint("masternode", "CActiveLegacyMasternodeManager::SendMasternodePing -- %s: masternode ping service is disabled, skipping...\n", GetStateString()); return false; } - if(!mnodeman.Has(activeMasternodeInfo.outpoint)) { + if (!mnodeman.Has(activeMasternodeInfo.outpoint)) { strNotCapableReason = "Masternode not in masternode list"; nState = ACTIVE_MASTERNODE_NOT_CAPABLE; LogPrintf("CActiveLegacyMasternodeManager::SendMasternodePing -- %s: %s\n", GetStateString(), strNotCapableReason); @@ -233,14 +256,14 @@ bool CActiveLegacyMasternodeManager::SendMasternodePing(CConnman& connman) CMasternodePing mnp(activeMasternodeInfo.outpoint); mnp.nSentinelVersion = nSentinelVersion; mnp.fSentinelIsCurrent = - (abs(GetAdjustedTime() - nSentinelPingTime) < MASTERNODE_SENTINEL_PING_MAX_SECONDS); - if(!mnp.Sign(activeMasternodeInfo.keyOperator, activeMasternodeInfo.keyIDOperator)) { + (abs(GetAdjustedTime() - nSentinelPingTime) < MASTERNODE_SENTINEL_PING_MAX_SECONDS); + if (!mnp.Sign(activeMasternodeInfo.keyOperator, activeMasternodeInfo.keyIDOperator)) { LogPrintf("CActiveLegacyMasternodeManager::SendMasternodePing -- ERROR: Couldn't sign Masternode Ping\n"); return false; } // Update lastPing for our masternode in Masternode list - if(mnodeman.IsMasternodePingedWithin(activeMasternodeInfo.outpoint, MASTERNODE_MIN_MNP_SECONDS, mnp.sigTime)) { + if (mnodeman.IsMasternodePingedWithin(activeMasternodeInfo.outpoint, MASTERNODE_MIN_MNP_SECONDS, mnp.sigTime)) { LogPrintf("CActiveLegacyMasternodeManager::SendMasternodePing -- Too early to send Masternode Ping\n"); return false; } @@ -279,7 +302,7 @@ void CActiveLegacyMasternodeManager::ManageStateInitial(CConnman& connman) // First try to find whatever local address is specified by externalip option bool fFoundLocal = GetLocal(activeMasternodeInfo.service) && CMasternode::IsValidNetAddr(activeMasternodeInfo.service); - if(!fFoundLocal) { + if (!fFoundLocal) { bool empty = true; // If we have some peers, let's try to find our local address from one of them connman.ForEachNodeContinueIf(CConnman::AllNodes, [&fFoundLocal, &empty](CNode* pnode) { @@ -303,7 +326,7 @@ void CActiveLegacyMasternodeManager::ManageStateInitial(CConnman& connman) } } - if(!fFoundLocal) { + if (!fFoundLocal) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Can't detect valid external address. Please consider using the externalip configuration option if problem persists. Make sure to use IPv4 address only."; LogPrintf("CActiveLegacyMasternodeManager::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); @@ -311,21 +334,21 @@ void CActiveLegacyMasternodeManager::ManageStateInitial(CConnman& connman) } int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort(); - if(Params().NetworkIDString() == CBaseChainParams::MAIN) { - if(activeMasternodeInfo.service.GetPort() != mainnetDefaultPort) { + if (Params().NetworkIDString() == CBaseChainParams::MAIN) { + if (activeMasternodeInfo.service.GetPort() != mainnetDefaultPort) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = strprintf("Invalid port: %u - only %d is supported on mainnet.", activeMasternodeInfo.service.GetPort(), mainnetDefaultPort); LogPrintf("CActiveLegacyMasternodeManager::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } - } else if(activeMasternodeInfo.service.GetPort() == mainnetDefaultPort) { + } else if (activeMasternodeInfo.service.GetPort() == mainnetDefaultPort) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = strprintf("Invalid port: %u - %d is only supported on mainnet.", activeMasternodeInfo.service.GetPort(), mainnetDefaultPort); LogPrintf("CActiveLegacyMasternodeManager::ManageStateInitial -- %s: %s\n", GetStateString(), strNotCapableReason); return; } - if(Params().NetworkIDString() != CBaseChainParams::REGTEST) { + if (Params().NetworkIDString() != CBaseChainParams::REGTEST) { // Check socket connectivity LogPrintf("CActiveLegacyMasternodeManager::ManageStateInitial -- Checking inbound connection to '%s'\n", activeMasternodeInfo.service.ToString()); SOCKET hSocket; @@ -351,24 +374,24 @@ void CActiveLegacyMasternodeManager::ManageStateRemote() return; LogPrint("masternode", "CActiveLegacyMasternodeManager::ManageStateRemote -- Start status = %s, type = %s, pinger enabled = %d, keyIDOperator = %s\n", - GetStatus(), GetTypeString(), fPingerEnabled, activeMasternodeInfo.keyIDOperator.ToString()); + GetStatus(), GetTypeString(), fPingerEnabled, activeMasternodeInfo.keyIDOperator.ToString()); mnodeman.CheckMasternode(activeMasternodeInfo.keyIDOperator, true); masternode_info_t infoMn; - if(mnodeman.GetMasternodeInfo(activeMasternodeInfo.keyIDOperator, infoMn)) { - if(infoMn.nProtocolVersion != PROTOCOL_VERSION) { + if (mnodeman.GetMasternodeInfo(activeMasternodeInfo.keyIDOperator, infoMn)) { + if (infoMn.nProtocolVersion != PROTOCOL_VERSION) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Invalid protocol version"; LogPrintf("CActiveLegacyMasternodeManager::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); return; } - if(activeMasternodeInfo.service != infoMn.addr) { + if (activeMasternodeInfo.service != infoMn.addr) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Broadcasted IP doesn't match our external address. Make sure you issued a new broadcast if IP of this masternode changed recently."; LogPrintf("CActiveLegacyMasternodeManager::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); return; } - if(!CMasternode::IsValidStateForAutoStart(infoMn.nActiveState)) { + if (!CMasternode::IsValidStateForAutoStart(infoMn.nActiveState)) { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = strprintf("Masternode in %s state", CMasternode::StateToString(infoMn.nActiveState)); LogPrintf("CActiveLegacyMasternodeManager::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); @@ -390,15 +413,14 @@ void CActiveLegacyMasternodeManager::ManageStateRemote() } LogPrintf("CActiveLegacyMasternodeManager::ManageStateRemote -- Collateral is a ProTx\n"); } - if(nState != ACTIVE_MASTERNODE_STARTED) { + if (nState != ACTIVE_MASTERNODE_STARTED) { LogPrintf("CActiveLegacyMasternodeManager::ManageStateRemote -- STARTED!\n"); activeMasternodeInfo.outpoint = infoMn.outpoint; activeMasternodeInfo.service = infoMn.addr; fPingerEnabled = true; nState = ACTIVE_MASTERNODE_STARTED; } - } - else { + } else { nState = ACTIVE_MASTERNODE_NOT_CAPABLE; strNotCapableReason = "Masternode not in masternode list"; LogPrintf("CActiveLegacyMasternodeManager::ManageStateRemote -- %s: %s\n", GetStateString(), strNotCapableReason); diff --git a/src/activemasternode.h b/src/activemasternode.h index 22f761caba5a..6f102973c7e7 100644 --- a/src/activemasternode.h +++ b/src/activemasternode.h @@ -11,18 +11,18 @@ #include "primitives/transaction.h" #include "validationinterface.h" -#include "evo/providertx.h" #include "evo/deterministicmns.h" +#include "evo/providertx.h" struct CActiveMasternodeInfo; class CActiveLegacyMasternodeManager; class CActiveDeterministicMasternodeManager; -static const int ACTIVE_MASTERNODE_INITIAL = 0; // initial state -static const int ACTIVE_MASTERNODE_SYNC_IN_PROCESS = 1; -static const int ACTIVE_MASTERNODE_INPUT_TOO_NEW = 2; -static const int ACTIVE_MASTERNODE_NOT_CAPABLE = 3; -static const int ACTIVE_MASTERNODE_STARTED = 4; +static const int ACTIVE_MASTERNODE_INITIAL = 0; // initial state +static const int ACTIVE_MASTERNODE_SYNC_IN_PROCESS = 1; +static const int ACTIVE_MASTERNODE_INPUT_TOO_NEW = 2; +static const int ACTIVE_MASTERNODE_NOT_CAPABLE = 3; +static const int ACTIVE_MASTERNODE_STARTED = 4; extern CActiveMasternodeInfo activeMasternodeInfo; extern CActiveLegacyMasternodeManager legacyActiveMasternodeManager; @@ -66,7 +66,7 @@ class CActiveDeterministicMasternodeManager : public CValidationInterface std::string GetStatus() const; private: - bool GetLocalAddress(CService &addrRet); + bool GetLocalAddress(CService& addrRet); }; // Responsible for activating the Masternode and pinging the network (legacy MN list) @@ -75,7 +75,7 @@ class CActiveLegacyMasternodeManager public: enum masternode_type_enum_t { MASTERNODE_UNKNOWN = 0, - MASTERNODE_REMOTE = 1 + MASTERNODE_REMOTE = 1 }; private: @@ -98,11 +98,12 @@ class CActiveLegacyMasternodeManager std::string strNotCapableReason; - CActiveLegacyMasternodeManager() - : eType(MASTERNODE_UNKNOWN), - fPingerEnabled(false), - nState(ACTIVE_MASTERNODE_INITIAL) - {} + CActiveLegacyMasternodeManager() : + eType(MASTERNODE_UNKNOWN), + fPingerEnabled(false), + nState(ACTIVE_MASTERNODE_INITIAL) + { + } /// Manage state of active Masternode void ManageState(CConnman& connman); @@ -113,7 +114,7 @@ class CActiveLegacyMasternodeManager bool UpdateSentinelPing(int version); - void DoMaintenance(CConnman &connman) { ManageState(connman); } + void DoMaintenance(CConnman& connman) { ManageState(connman); } private: void ManageStateInitial(CConnman& connman); diff --git a/src/dsnotificationinterface.cpp b/src/dsnotificationinterface.cpp index 5e7fbcef5acc..bf02803690c7 100644 --- a/src/dsnotificationinterface.cpp +++ b/src/dsnotificationinterface.cpp @@ -2,13 +2,13 @@ // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include "chainparams.h" #include "dsnotificationinterface.h" -#include "instantx.h" +#include "chainparams.h" #include "governance.h" -#include "masternodeman.h" +#include "instantx.h" #include "masternode-payments.h" #include "masternode-sync.h" +#include "masternodeman.h" #include "privatesend.h" #ifdef ENABLE_WALLET #include "privatesend-client.h" @@ -22,17 +22,17 @@ void CDSNotificationInterface::InitializeCurrentBlockTip() UpdatedBlockTip(chainActive.Tip(), NULL, IsInitialBlockDownload()); } -void CDSNotificationInterface::AcceptedBlockHeader(const CBlockIndex *pindexNew) +void CDSNotificationInterface::AcceptedBlockHeader(const CBlockIndex* pindexNew) { masternodeSync.AcceptedBlockHeader(pindexNew); } -void CDSNotificationInterface::NotifyHeaderTip(const CBlockIndex *pindexNew, bool fInitialDownload) +void CDSNotificationInterface::NotifyHeaderTip(const CBlockIndex* pindexNew, bool fInitialDownload) { masternodeSync.NotifyHeaderTip(pindexNew, fInitialDownload, connman); } -void CDSNotificationInterface::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) +void CDSNotificationInterface::UpdatedBlockTip(const CBlockIndex* pindexNew, const CBlockIndex* pindexFork, bool fInitialDownload) { if (pindexNew == pindexFork) // blocks were disconnected without any new ones return; @@ -46,7 +46,7 @@ void CDSNotificationInterface::UpdatedBlockTip(const CBlockIndex *pindexNew, con fDIP0003ActiveAtTip = (VersionBitsState(pindexNew->pprev, Params().GetConsensus(), Consensus::DEPLOYMENT_DIP0003, versionbitscache) == THRESHOLD_ACTIVE); // update instantsend autolock activation flag instantsend.isAutoLockBip9Active = - (VersionBitsTipState(Params().GetConsensus(), Consensus::DEPLOYMENT_ISAUTOLOCKS) == THRESHOLD_ACTIVE); + (VersionBitsTipState(Params().GetConsensus(), Consensus::DEPLOYMENT_ISAUTOLOCKS) == THRESHOLD_ACTIVE); if (fInitialDownload) return; @@ -64,7 +64,7 @@ void CDSNotificationInterface::UpdatedBlockTip(const CBlockIndex *pindexNew, con governance.UpdatedBlockTip(pindexNew, connman); } -void CDSNotificationInterface::SyncTransaction(const CTransaction &tx, const CBlockIndex *pindex, int posInBlock) +void CDSNotificationInterface::SyncTransaction(const CTransaction& tx, const CBlockIndex* pindex, int posInBlock) { instantsend.SyncTransaction(tx, pindex, posInBlock); CPrivateSend::SyncTransaction(tx, pindex, posInBlock); diff --git a/src/dsnotificationinterface.h b/src/dsnotificationinterface.h index 8e7df34a3309..b86824e50f40 100644 --- a/src/dsnotificationinterface.h +++ b/src/dsnotificationinterface.h @@ -10,7 +10,8 @@ class CDSNotificationInterface : public CValidationInterface { public: - CDSNotificationInterface(CConnman& connmanIn): connman(connmanIn) {} + CDSNotificationInterface(CConnman& connmanIn) : + connman(connmanIn) {} virtual ~CDSNotificationInterface() = default; // a small helper to initialize current block height in sub-modules on startup @@ -18,10 +19,10 @@ class CDSNotificationInterface : public CValidationInterface protected: // CValidationInterface - void AcceptedBlockHeader(const CBlockIndex *pindexNew) override; - void NotifyHeaderTip(const CBlockIndex *pindexNew, bool fInitialDownload) override; - void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override; - void SyncTransaction(const CTransaction &tx, const CBlockIndex *pindex, int posInBlock) override; + void AcceptedBlockHeader(const CBlockIndex* pindexNew) override; + void NotifyHeaderTip(const CBlockIndex* pindexNew, bool fInitialDownload) override; + void UpdatedBlockTip(const CBlockIndex* pindexNew, const CBlockIndex* pindexFork, bool fInitialDownload) override; + void SyncTransaction(const CTransaction& tx, const CBlockIndex* pindex, int posInBlock) override; private: CConnman& connman; diff --git a/src/governance-classes.cpp b/src/governance-classes.cpp index 89a8b75056df..8af9fe0c9695 100644 --- a/src/governance-classes.cpp +++ b/src/governance-classes.cpp @@ -198,10 +198,10 @@ void CGovernanceTriggerManager::CleanAndRemove() std::string strDataAsPlainString = "NULL"; if (pObj) { strDataAsPlainString = pObj->GetDataAsPlainString(); - } - std::cout << "CGovernanceTriggerManager::CleanAndRemove: Removing object: " - << strDataAsPlainString - << std::endl;); + } std::cout + << "CGovernanceTriggerManager::CleanAndRemove: Removing object: " + << strDataAsPlainString + << std::endl;); LogPrint("gobject", "CGovernanceTriggerManager::CleanAndRemove -- Removing trigger object\n"); // mark corresponding object for deletion if (pObj) { diff --git a/src/governance-vote.cpp b/src/governance-vote.cpp index 7e68675ce753..bac7efaf3b87 100644 --- a/src/governance-vote.cpp +++ b/src/governance-vote.cpp @@ -12,10 +12,10 @@ std::string CGovernanceVoting::ConvertOutcomeToString(vote_outcome_enum_t nOutcome) { static const std::map mapOutcomeString = { - { VOTE_OUTCOME_NONE, "none" }, - { VOTE_OUTCOME_YES, "yes" }, - { VOTE_OUTCOME_NO, "no" }, - { VOTE_OUTCOME_ABSTAIN, "abstain" } }; + {VOTE_OUTCOME_NONE, "none"}, + {VOTE_OUTCOME_YES, "yes"}, + {VOTE_OUTCOME_NO, "no"}, + {VOTE_OUTCOME_ABSTAIN, "abstain"}}; const auto& it = mapOutcomeString.find(nOutcome); if (it == mapOutcomeString.end()) { @@ -28,10 +28,10 @@ std::string CGovernanceVoting::ConvertOutcomeToString(vote_outcome_enum_t nOutco std::string CGovernanceVoting::ConvertSignalToString(vote_signal_enum_t nSignal) { static const std::map mapSignalsString = { - { VOTE_SIGNAL_FUNDING, "funding" }, - { VOTE_SIGNAL_VALID, "valid" }, - { VOTE_SIGNAL_DELETE, "delete" }, - { VOTE_SIGNAL_ENDORSED, "endorsed" } }; + {VOTE_SIGNAL_FUNDING, "funding"}, + {VOTE_SIGNAL_VALID, "valid"}, + {VOTE_SIGNAL_DELETE, "delete"}, + {VOTE_SIGNAL_ENDORSED, "endorsed"}}; const auto& it = mapSignalsString.find(nSignal); if (it == mapSignalsString.end()) { @@ -45,10 +45,10 @@ std::string CGovernanceVoting::ConvertSignalToString(vote_signal_enum_t nSignal) vote_outcome_enum_t CGovernanceVoting::ConvertVoteOutcome(const std::string& strVoteOutcome) { static const std::map mapStringOutcome = { - { "none", VOTE_OUTCOME_NONE }, - { "yes", VOTE_OUTCOME_YES }, - { "no", VOTE_OUTCOME_NO }, - { "abstain", VOTE_OUTCOME_ABSTAIN } }; + {"none", VOTE_OUTCOME_NONE}, + {"yes", VOTE_OUTCOME_YES}, + {"no", VOTE_OUTCOME_NO}, + {"abstain", VOTE_OUTCOME_ABSTAIN}}; const auto& it = mapStringOutcome.find(strVoteOutcome); if (it == mapStringOutcome.end()) { @@ -56,7 +56,6 @@ vote_outcome_enum_t CGovernanceVoting::ConvertVoteOutcome(const std::string& str return VOTE_OUTCOME_NONE; } return it->second; - } vote_signal_enum_t CGovernanceVoting::ConvertVoteSignal(const std::string& strVoteSignal) diff --git a/src/governance-vote.h b/src/governance-vote.h index 0a2ac0489f48..70db4cdfd78c 100644 --- a/src/governance-vote.h +++ b/src/governance-vote.h @@ -13,20 +13,20 @@ class CConnman; // INTENTION OF MASTERNODES REGARDING ITEM enum vote_outcome_enum_t { - VOTE_OUTCOME_NONE = 0, - VOTE_OUTCOME_YES = 1, - VOTE_OUTCOME_NO = 2, - VOTE_OUTCOME_ABSTAIN = 3 + VOTE_OUTCOME_NONE = 0, + VOTE_OUTCOME_YES = 1, + VOTE_OUTCOME_NO = 2, + VOTE_OUTCOME_ABSTAIN = 3 }; // SIGNAL VARIOUS THINGS TO HAPPEN: enum vote_signal_enum_t { - VOTE_SIGNAL_NONE = 0, - VOTE_SIGNAL_FUNDING = 1, // -- fund this object for it's stated amount - VOTE_SIGNAL_VALID = 2, // -- this object checks out in sentinel engine - VOTE_SIGNAL_DELETE = 3, // -- this object should be deleted from memory entirely - VOTE_SIGNAL_ENDORSED = 4, // -- officially endorsed by the network somehow (delegation) + VOTE_SIGNAL_NONE = 0, + VOTE_SIGNAL_FUNDING = 1, // -- fund this object for it's stated amount + VOTE_SIGNAL_VALID = 2, // -- this object checks out in sentinel engine + VOTE_SIGNAL_DELETE = 3, // -- this object should be deleted from memory entirely + VOTE_SIGNAL_ENDORSED = 4, // -- officially endorsed by the network somehow (delegation) }; static const int MAX_SUPPORTED_VOTE_SIGNAL = VOTE_SIGNAL_ENDORSED; diff --git a/src/governance.cpp b/src/governance.cpp index e0586362bdef..4e7f6a564760 100644 --- a/src/governance.cpp +++ b/src/governance.cpp @@ -594,14 +594,14 @@ bool CGovernanceManager::ConfirmInventoryRequest(const CInv& inv) return false; } break; - } + } case MSG_GOVERNANCE_OBJECT_VOTE: { if (cmapVoteToObject.HasKey(inv.hash)) { LogPrint("gobject", "CGovernanceManager::ConfirmInventoryRequest already have governance vote, returning false\n"); return false; } break; - } + } default: LogPrint("gobject", "CGovernanceManager::ConfirmInventoryRequest unknown type, returning false\n"); return false; diff --git a/src/masternode-payments.cpp b/src/masternode-payments.cpp index 97ea640e5fa6..0619b4b788ef 100644 --- a/src/masternode-payments.cpp +++ b/src/masternode-payments.cpp @@ -2,10 +2,10 @@ // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. +#include "masternode-payments.h" #include "activemasternode.h" #include "consensus/validation.h" #include "governance-classes.h" -#include "masternode-payments.h" #include "masternode-sync.h" #include "masternodeman.h" #include "messagesigner.h" @@ -25,7 +25,8 @@ CCriticalSection cs_vecPayees; CCriticalSection cs_mapMasternodeBlocks; CCriticalSection cs_mapMasternodePaymentVotes; -bool IsOldBudgetBlockValueValid(const CBlock& block, int nBlockHeight, CAmount blockReward, std::string& strErrorRet) { +bool IsOldBudgetBlockValueValid(const CBlock& block, int nBlockHeight, CAmount blockReward, std::string& strErrorRet) +{ const Consensus::Params& consensusParams = Params().GetConsensus(); bool isBlockRewardValueMet = (block.vtx[0]->GetValueOut() <= blockReward); @@ -43,16 +44,16 @@ bool IsOldBudgetBlockValueValid(const CBlock& block, int nBlockHeight, CAmount b // all we know is predefined budget cycle and window int nOffset = nBlockHeight % consensusParams.nBudgetPaymentsCycleBlocks; - if(nBlockHeight >= consensusParams.nBudgetPaymentsStartBlock && - nOffset < consensusParams.nBudgetPaymentsWindowBlocks) { + if (nBlockHeight >= consensusParams.nBudgetPaymentsStartBlock && + nOffset < consensusParams.nBudgetPaymentsWindowBlocks) { // NOTE: old budget system is disabled since 12.1 - if(masternodeSync.IsSynced()) { + if (masternodeSync.IsSynced()) { // no old budget blocks should be accepted here on mainnet, // testnet/devnet/regtest should produce regular blocks only LogPrint("gobject", "%s -- WARNING: Client synced but old budget system is disabled, checking block value against block reward\n", __func__); - if(!isBlockRewardValueMet) { + if (!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, old budgets are disabled", - nBlockHeight, block.vtx[0]->GetValueOut(), blockReward); + nBlockHeight, block.vtx[0]->GetValueOut(), blockReward); } return isBlockRewardValueMet; } @@ -61,9 +62,9 @@ bool IsOldBudgetBlockValueValid(const CBlock& block, int nBlockHeight, CAmount b return true; } // LogPrint("gobject", "%s -- Block is not in budget cycle window, checking block value against block reward\n", __func__); - if(!isBlockRewardValueMet) { + if (!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, block is not in old budget cycle window", - nBlockHeight, block.vtx[0]->GetValueOut(), blockReward); + nBlockHeight, block.vtx[0]->GetValueOut(), blockReward); } return isBlockRewardValueMet; } @@ -88,9 +89,9 @@ bool IsBlockValueValid(const CBlock& block, int nBlockHeight, CAmount blockRewar if (nBlockHeight < consensusParams.nBudgetPaymentsStartBlock) { // old budget system is not activated yet, just make sure we do not exceed the regular block reward - if(!isBlockRewardValueMet) { + if (!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, old budgets are not activated yet", - nBlockHeight, block.vtx[0]->GetValueOut(), blockReward); + nBlockHeight, block.vtx[0]->GetValueOut(), blockReward); } return isBlockRewardValueMet; } else if (nBlockHeight < consensusParams.nSuperblockStartBlock) { @@ -98,9 +99,9 @@ bool IsBlockValueValid(const CBlock& block, int nBlockHeight, CAmount blockRewar return IsOldBudgetBlockValueValid(block, nBlockHeight, blockReward, strErrorRet); } - if(fDebug) LogPrintf("block.vtx[0]->GetValueOut() %lld <= blockReward %lld\n", block.vtx[0]->GetValueOut(), blockReward); + if (fDebug) LogPrintf("block.vtx[0]->GetValueOut() %lld <= blockReward %lld\n", block.vtx[0]->GetValueOut(), blockReward); - CAmount nSuperblockMaxValue = blockReward + CSuperblock::GetPaymentsLimit(nBlockHeight); + CAmount nSuperblockMaxValue = blockReward + CSuperblock::GetPaymentsLimit(nBlockHeight); bool isSuperblockMaxValueMet = (block.vtx[0]->GetValueOut() <= nSuperblockMaxValue); LogPrint("gobject", "block.vtx[0]->GetValueOut() %lld <= nSuperblockMaxValue %lld\n", block.vtx[0]->GetValueOut(), nSuperblockMaxValue); @@ -109,7 +110,7 @@ bool IsBlockValueValid(const CBlock& block, int nBlockHeight, CAmount blockRewar // can't possibly be a superblock, so lets just check for block reward limits if (!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, only regular blocks are allowed at this height", - nBlockHeight, block.vtx[0]->GetValueOut(), blockReward); + nBlockHeight, block.vtx[0]->GetValueOut(), blockReward); } return isBlockRewardValueMet; } @@ -117,12 +118,12 @@ bool IsBlockValueValid(const CBlock& block, int nBlockHeight, CAmount blockRewar // bail out in case superblock limits were exceeded if (!isSuperblockMaxValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded superblock max value", - nBlockHeight, block.vtx[0]->GetValueOut(), nSuperblockMaxValue); + nBlockHeight, block.vtx[0]->GetValueOut(), nSuperblockMaxValue); return false; } - if(!masternodeSync.IsSynced() || fLiteMode) { - if(fDebug) LogPrintf("%s -- WARNING: Not enough data, checked superblock max bounds only\n", __func__); + if (!masternodeSync.IsSynced() || fLiteMode) { + if (fDebug) LogPrintf("%s -- WARNING: Not enough data, checked superblock max bounds only\n", __func__); // not enough data for full checks but at least we know that the superblock limits were honored. // We rely on the network to have followed the correct chain in this case return true; @@ -134,9 +135,9 @@ bool IsBlockValueValid(const CBlock& block, int nBlockHeight, CAmount blockRewar // should NOT allow superblocks at all, when superblocks are disabled // revert to block reward limits in this case LogPrint("gobject", "%s -- Superblocks are disabled, no superblocks allowed\n", __func__); - if(!isBlockRewardValueMet) { + if (!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, superblocks are disabled", - nBlockHeight, block.vtx[0]->GetValueOut(), blockReward); + nBlockHeight, block.vtx[0]->GetValueOut(), blockReward); } return isBlockRewardValueMet; } @@ -144,9 +145,9 @@ bool IsBlockValueValid(const CBlock& block, int nBlockHeight, CAmount blockRewar if (!CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { // we are on a valid superblock height but a superblock was not triggered // revert to block reward limits in this case - if(!isBlockRewardValueMet) { + if (!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, no triggered superblock detected", - nBlockHeight, block.vtx[0]->GetValueOut(), blockReward); + nBlockHeight, block.vtx[0]->GetValueOut(), blockReward); } return isBlockRewardValueMet; } @@ -166,9 +167,9 @@ bool IsBlockValueValid(const CBlock& block, int nBlockHeight, CAmount blockRewar bool IsBlockPayeeValid(const CTransaction& txNew, int nBlockHeight, CAmount blockReward) { - if((!masternodeSync.IsSynced() && !deterministicMNManager->IsDeterministicMNsSporkActive(nBlockHeight)) || fLiteMode) { + if ((!masternodeSync.IsSynced() && !deterministicMNManager->IsDeterministicMNsSporkActive(nBlockHeight)) || fLiteMode) { //there is no budget data to use to check anything, let's just accept the longest chain - if(fDebug) LogPrintf("%s -- WARNING: Not enough data, skipping block payee checks\n", __func__); + if (fDebug) LogPrintf("%s -- WARNING: Not enough data, skipping block payee checks\n", __func__); return true; } @@ -177,7 +178,7 @@ bool IsBlockPayeeValid(const CTransaction& txNew, int nBlockHeight, CAmount bloc const Consensus::Params& consensusParams = Params().GetConsensus(); - if(nBlockHeight < consensusParams.nSuperblockStartBlock) { + if (nBlockHeight < consensusParams.nSuperblockStartBlock) { // NOTE: old budget system is disabled since 12.1 and we should never enter this branch // anymore when sync is finished (on mainnet). We have no old budget data but these blocks // have tons of confirmations and can be safely accepted without payee verification @@ -188,9 +189,9 @@ bool IsBlockPayeeValid(const CTransaction& txNew, int nBlockHeight, CAmount bloc // superblocks started // SEE IF THIS IS A VALID SUPERBLOCK - if(sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED)) { - if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { - if(CSuperblockManager::IsValid(txNew, nBlockHeight, blockReward)) { + if (sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED)) { + if (CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { + if (CSuperblockManager::IsValid(txNew, nBlockHeight, blockReward)) { LogPrint("gobject", "%s -- Valid superblock at height %d: %s", __func__, nBlockHeight, txNew.ToString()); // only allow superblock and masternode payments in the same block after spork15 activation if (!deterministicMNManager->IsDeterministicMNsSporkActive(nBlockHeight)) @@ -210,7 +211,7 @@ bool IsBlockPayeeValid(const CTransaction& txNew, int nBlockHeight, CAmount bloc } // If this isn't a superblock or spork15 is activated, check for correct masternode payment - if(mnpayments.IsTransactionValid(txNew, nBlockHeight, blockReward)) { + if (mnpayments.IsTransactionValid(txNew, nBlockHeight, blockReward)) { LogPrint("mnpayments", "%s -- Valid masternode payment at height %d: %s", __func__, nBlockHeight, txNew.ToString()); return true; } @@ -219,7 +220,7 @@ bool IsBlockPayeeValid(const CTransaction& txNew, int nBlockHeight, CAmount bloc // always enforce masternode payments when spork15 is active return false; } else { - if(sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) { + if (sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) { LogPrintf("%s -- ERROR: Invalid masternode payment detected at height %d: %s", __func__, nBlockHeight, txNew.ToString()); return false; } @@ -233,10 +234,10 @@ void FillBlockPayments(CMutableTransaction& txNew, int nBlockHeight, CAmount blo { // only create superblocks if spork is enabled AND if superblock is actually triggered // (height should be validated inside) - if(sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED) && + if (sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED) && CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { - LogPrint("gobject", "%s -- triggered superblock creation at height %d\n", __func__, nBlockHeight); - CSuperblockManager::GetSuperblockPayments(nBlockHeight, voutSuperblockPaymentsRet); + LogPrint("gobject", "%s -- triggered superblock creation at height %d\n", __func__, nBlockHeight); + CSuperblockManager::GetSuperblockPayments(nBlockHeight, voutSuperblockPaymentsRet); } bool allowSuperblockAndMNReward = deterministicMNManager->IsDeterministicMNsSporkActive(nBlockHeight); @@ -265,13 +266,13 @@ void FillBlockPayments(CMutableTransaction& txNew, int nBlockHeight, CAmount blo } LogPrint("mnpayments", "%s -- nBlockHeight %d blockReward %lld voutMasternodePaymentsRet \"%s\" txNew %s", __func__, - nBlockHeight, blockReward, voutMasternodeStr, txNew.ToString()); + nBlockHeight, blockReward, voutMasternodeStr, txNew.ToString()); } std::string GetLegacyRequiredPaymentsString(int nBlockHeight) { // IF WE HAVE A ACTIVATED TRIGGER FOR THIS HEIGHT - IT IS A SUPERBLOCK, GET THE REQUIRED PAYEES - if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { + if (CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { return CSuperblockManager::GetRequiredPaymentsString(nBlockHeight); } @@ -279,7 +280,7 @@ std::string GetLegacyRequiredPaymentsString(int nBlockHeight) return mnpayments.GetRequiredPaymentsString(nBlockHeight); } -std::string GetRequiredPaymentsString(int nBlockHeight, const CDeterministicMNCPtr &payee) +std::string GetRequiredPaymentsString(int nBlockHeight, const CDeterministicMNCPtr& payee) { std::string strPayee = "Unknown"; if (payee) { @@ -302,7 +303,7 @@ std::map GetRequiredPaymentsStrings(int nStartHeight, int nEnd int nChainTipHeight = chainActive.Height(); bool doProjection = false; - for(int h = nStartHeight; h < nEndHeight; h++) { + for (int h = nStartHeight; h < nEndHeight; h++) { if (deterministicMNManager->IsDeterministicMNsSporkActive(h)) { if (h <= nChainTipHeight) { auto payee = deterministicMNManager->GetListForBlock(chainActive[h - 1]->GetBlockHash()).GetMNPayee(); @@ -365,13 +366,13 @@ bool CMasternodePayments::GetMasternodeTxOuts(int nBlockHeight, CAmount blockRew // make sure it's not filled yet voutMasternodePaymentsRet.clear(); - if(!GetBlockTxOuts(nBlockHeight, blockReward, voutMasternodePaymentsRet)) { + if (!GetBlockTxOuts(nBlockHeight, blockReward, voutMasternodePaymentsRet)) { assert(!deterministicMNManager->IsDeterministicMNsSporkActive(nBlockHeight)); // no masternode detected... int nCount = 0; masternode_info_t mnInfo; - if(!mnodeman.GetNextMasternodeInQueueForPayment(nBlockHeight, true, nCount, mnInfo)) { + if (!mnodeman.GetNextMasternodeInQueueForPayment(nBlockHeight, true, nCount, mnInfo)) { // ...and we can't calculate it on our own LogPrintf("CMasternodePayments::%s -- Failed to detect masternode to pay\n", __func__); return false; @@ -393,10 +394,11 @@ bool CMasternodePayments::GetMasternodeTxOuts(int nBlockHeight, CAmount blockRew return true; } -int CMasternodePayments::GetMinMasternodePaymentsProto() const { +int CMasternodePayments::GetMinMasternodePaymentsProto() const +{ return sporkManager.IsSporkActive(SPORK_10_MASTERNODE_PAY_UPDATED_NODES) - ? MIN_MASTERNODE_PAYMENT_PROTO_VERSION_2 - : MIN_MASTERNODE_PAYMENT_PROTO_VERSION_1; + ? MIN_MASTERNODE_PAYMENT_PROTO_VERSION_2 + : MIN_MASTERNODE_PAYMENT_PROTO_VERSION_1; } void CMasternodePayments::ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman) @@ -404,14 +406,13 @@ void CMasternodePayments::ProcessMessage(CNode* pfrom, const std::string& strCom if (deterministicMNManager->IsDeterministicMNsSporkActive()) return; - if(fLiteMode) return; // disable all Dash specific functionality + if (fLiteMode) return; // disable all Dash specific functionality if (strCommand == NetMsgType::MASTERNODEPAYMENTSYNC) { //Masternode Payments Request Sync - if(pfrom->nVersion < GetMinMasternodePaymentsProto()) { + if (pfrom->nVersion < GetMinMasternodePaymentsProto()) { LogPrint("mnpayments", "MASTERNODEPAYMENTSYNC -- peer=%d using obsolete version %i\n", pfrom->id, pfrom->nVersion); - connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, - strprintf("Version must be %d or greater", GetMinMasternodePaymentsProto()))); + connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", GetMinMasternodePaymentsProto()))); return; } @@ -420,7 +421,7 @@ void CMasternodePayments::ProcessMessage(CNode* pfrom, const std::string& strCom // but this is a heavy one so it's better to finish sync first. if (!masternodeSync.IsSynced()) return; - if(netfulfilledman.HasFulfilledRequest(pfrom->addr, NetMsgType::MASTERNODEPAYMENTSYNC)) { + if (netfulfilledman.HasFulfilledRequest(pfrom->addr, NetMsgType::MASTERNODEPAYMENTSYNC)) { LOCK(cs_main); // Asking for the payments list multiple times in a short period of time is no good LogPrintf("MASTERNODEPAYMENTSYNC -- peer already asked me for the list, peer=%d\n", pfrom->id); @@ -437,10 +438,9 @@ void CMasternodePayments::ProcessMessage(CNode* pfrom, const std::string& strCom CMasternodePaymentVote vote; vRecv >> vote; - if(pfrom->nVersion < GetMinMasternodePaymentsProto()) { + if (pfrom->nVersion < GetMinMasternodePaymentsProto()) { LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- peer=%d using obsolete version %i\n", pfrom->id, pfrom->nVersion); - connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, - strprintf("Version must be %d or greater", GetMinMasternodePaymentsProto()))); + connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", GetMinMasternodePaymentsProto()))); return; } @@ -451,7 +451,7 @@ void CMasternodePayments::ProcessMessage(CNode* pfrom, const std::string& strCom // TODO: clear setAskFor for MSG_MASTERNODE_PAYMENT_BLOCK too // Ignore any payments messages until masternode list is synced - if(!masternodeSync.IsMasternodeListSynced()) return; + if (!masternodeSync.IsMasternodeListSynced()) return; { LOCK(cs_mapMasternodePaymentVotes); @@ -459,9 +459,9 @@ void CMasternodePayments::ProcessMessage(CNode* pfrom, const std::string& strCom auto res = mapMasternodePaymentVotes.emplace(nHash, vote); // Avoid processing same vote multiple times if it was already verified earlier - if(!res.second && res.first->second.IsVerified()) { + if (!res.second && res.first->second.IsVerified()) { LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- hash=%s, nBlockHeight=%d/%d seen\n", - nHash.ToString(), vote.nBlockHeight, nCachedBlockHeight); + nHash.ToString(), vote.nBlockHeight, nCachedBlockHeight); return; } @@ -471,19 +471,19 @@ void CMasternodePayments::ProcessMessage(CNode* pfrom, const std::string& strCom } int nFirstBlock = nCachedBlockHeight - GetStorageLimit(); - if(vote.nBlockHeight < nFirstBlock || vote.nBlockHeight > nCachedBlockHeight+20) { + if (vote.nBlockHeight < nFirstBlock || vote.nBlockHeight > nCachedBlockHeight + 20) { LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- vote out of range: nFirstBlock=%d, nBlockHeight=%d, nHeight=%d\n", nFirstBlock, vote.nBlockHeight, nCachedBlockHeight); return; } std::string strError = ""; - if(!vote.IsValid(pfrom, nCachedBlockHeight, strError, connman)) { + if (!vote.IsValid(pfrom, nCachedBlockHeight, strError, connman)) { LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- invalid message, error: %s\n", strError); return; } masternode_info_t mnInfo; - if(!mnodeman.GetMasternodeInfo(vote.masternodeOutpoint, mnInfo)) { + if (!mnodeman.GetMasternodeInfo(vote.masternodeOutpoint, mnInfo)) { // mn was not found, so we can't check vote, some info is probably missing LogPrintf("MASTERNODEPAYMENTVOTE -- masternode is missing %s\n", vote.masternodeOutpoint.ToStringShort()); mnodeman.AskForMN(pfrom, vote.masternodeOutpoint, connman); @@ -491,8 +491,8 @@ void CMasternodePayments::ProcessMessage(CNode* pfrom, const std::string& strCom } int nDos = 0; - if(!vote.CheckSignature(mnInfo.keyIDOperator, nCachedBlockHeight, nDos)) { - if(nDos) { + if (!vote.CheckSignature(mnInfo.keyIDOperator, nCachedBlockHeight, nDos)) { + if (nDos) { LOCK(cs_main); LogPrintf("MASTERNODEPAYMENTVOTE -- ERROR: invalid signature\n"); Misbehaving(pfrom->GetId(), nDos); @@ -509,7 +509,7 @@ void CMasternodePayments::ProcessMessage(CNode* pfrom, const std::string& strCom return; } - if(!UpdateLastVote(vote)) { + if (!UpdateLastVote(vote)) { LogPrintf("MASTERNODEPAYMENTVOTE -- masternode already voted, masternode=%s\n", vote.masternodeOutpoint.ToStringShort()); return; } @@ -519,9 +519,9 @@ void CMasternodePayments::ProcessMessage(CNode* pfrom, const std::string& strCom CBitcoinAddress address2(address1); LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- vote: address=%s, nBlockHeight=%d, nHeight=%d, prevout=%s, hash=%s new\n", - address2.ToString(), vote.nBlockHeight, nCachedBlockHeight, vote.masternodeOutpoint.ToStringShort(), nHash.ToString()); + address2.ToString(), vote.nBlockHeight, nCachedBlockHeight, vote.masternodeOutpoint.ToStringShort(), nHash.ToString()); - if(AddOrUpdatePaymentVote(vote)){ + if (AddOrUpdatePaymentVote(vote)) { vote.Relay(connman); masternodeSync.BumpAssetLastTime("MASTERNODEPAYMENTVOTE"); } @@ -551,7 +551,7 @@ bool CMasternodePaymentVote::Sign() if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { uint256 hash = GetSignatureHash(); - if(!CHashSigner::SignHash(hash, activeMasternodeInfo.keyOperator, vchSig)) { + if (!CHashSigner::SignHash(hash, activeMasternodeInfo.keyOperator, vchSig)) { LogPrintf("CMasternodePaymentVote::%s -- SignHash() failed\n", __func__); return false; } @@ -562,15 +562,15 @@ bool CMasternodePaymentVote::Sign() } } else { std::string strMessage = masternodeOutpoint.ToStringShort() + - std::to_string(nBlockHeight) + - ScriptToAsmStr(payee); + std::to_string(nBlockHeight) + + ScriptToAsmStr(payee); - if(!CMessageSigner::SignMessage(strMessage, vchSig, activeMasternodeInfo.keyOperator)) { + if (!CMessageSigner::SignMessage(strMessage, vchSig, activeMasternodeInfo.keyOperator)) { LogPrintf("CMasternodePaymentVote::%s -- SignMessage() failed\n", __func__); return false; } - if(!CMessageSigner::VerifyMessage(activeMasternodeInfo.keyIDOperator, vchSig, strMessage, strError)) { + if (!CMessageSigner::VerifyMessage(activeMasternodeInfo.keyIDOperator, vchSig, strMessage, strError)) { LogPrintf("CMasternodePaymentVote::%s -- VerifyMessage() failed, error: %s\n", __func__, strError); return false; } @@ -626,7 +626,7 @@ bool CMasternodePayments::IsScheduled(const masternode_info_t& mnInfo, int nNotB if (deterministicMNManager->IsDeterministicMNsSporkActive()) { auto projectedPayees = deterministicMNManager->GetListAtChainTip().GetProjectedMNPayees(8); - for (const auto &dmn : projectedPayees) { + for (const auto& dmn : projectedPayees) { if (dmn->proTxHash == mnInfo.outpoint.hash) { return true; } @@ -634,15 +634,15 @@ bool CMasternodePayments::IsScheduled(const masternode_info_t& mnInfo, int nNotB return false; } - if(!masternodeSync.IsMasternodeListSynced()) return false; + if (!masternodeSync.IsMasternodeListSynced()) return false; CScript mnpayee; mnpayee = GetScriptForDestination(mnInfo.keyIDCollateralAddress); - for(int64_t h = nCachedBlockHeight; h <= nCachedBlockHeight + 8; h++){ - if(h == nNotBlockHeight) continue; + for (int64_t h = nCachedBlockHeight; h <= nCachedBlockHeight + 8; h++) { + if (h == nNotBlockHeight) continue; std::vector voutMasternodePayments; - if(GetBlockTxOuts(h, 0, voutMasternodePayments)) { + if (GetBlockTxOuts(h, 0, voutMasternodePayments)) { for (const auto& txout : voutMasternodePayments) { if (txout.scriptPubKey == mnpayee) return true; @@ -656,11 +656,11 @@ bool CMasternodePayments::IsScheduled(const masternode_info_t& mnInfo, int nNotB bool CMasternodePayments::AddOrUpdatePaymentVote(const CMasternodePaymentVote& vote) { uint256 blockHash = uint256(); - if(!GetBlockHash(blockHash, vote.nBlockHeight - 101)) return false; + if (!GetBlockHash(blockHash, vote.nBlockHeight - 101)) return false; uint256 nVoteHash = vote.GetHash(); - if(HasVerifiedPaymentVote(nVoteHash)) return false; + if (HasVerifiedPaymentVote(nVoteHash)) return false; LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes); @@ -701,7 +701,7 @@ bool CMasternodeBlockPayees::GetBestPayee(CScript& payeeRet) const { LOCK(cs_vecPayees); - if(vecPayees.empty()) { + if (vecPayees.empty()) { LogPrint("mnpayments", "CMasternodeBlockPayees::%s -- ERROR: couldn't find any payee\n", __func__); return false; } @@ -749,7 +749,7 @@ bool CMasternodeBlockPayees::IsTransactionValid(const CTransaction& txNew) const } // if we don't have at least MNPAYMENTS_SIGNATURES_REQUIRED signatures on a payee, approve whichever is the longest chain - if(nMaxSignatures < MNPAYMENTS_SIGNATURES_REQUIRED) return true; + if (nMaxSignatures < MNPAYMENTS_SIGNATURES_REQUIRED) return true; for (const auto& payee : vecPayees) { if (payee.GetVoteCount() >= MNPAYMENTS_SIGNATURES_REQUIRED) { @@ -764,7 +764,7 @@ bool CMasternodeBlockPayees::IsTransactionValid(const CTransaction& txNew) const ExtractDestination(payee.GetPayee(), address1); CBitcoinAddress address2(address1); - if(strPayeesPossible == "") { + if (strPayeesPossible == "") { strPayeesPossible = address2.ToString(); } else { strPayeesPossible += "," + address2.ToString(); @@ -772,7 +772,7 @@ bool CMasternodeBlockPayees::IsTransactionValid(const CTransaction& txNew) const } } - LogPrintf("CMasternodeBlockPayees::%s -- ERROR: Missing required payment, possible payees: '%s', amount: %f DASH\n", __func__, strPayeesPossible, (float)nMasternodePayment/COIN); + LogPrintf("CMasternodeBlockPayees::%s -- ERROR: Missing required payment, possible payees: '%s', amount: %f DASH\n", __func__, strPayeesPossible, (float)nMasternodePayment / COIN); return false; } @@ -782,8 +782,7 @@ std::string CMasternodeBlockPayees::GetRequiredPaymentsString() const std::string strRequiredPayments = ""; - for (const auto& payee : vecPayees) - { + for (const auto& payee : vecPayees) { CTxDestination address1; ExtractDestination(payee.GetPayee(), address1); CBitcoinAddress address2(address1); @@ -846,17 +845,17 @@ void CMasternodePayments::CheckAndRemove() return; } - if(!masternodeSync.IsBlockchainSynced()) return; + if (!masternodeSync.IsBlockchainSynced()) return; LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes); int nLimit = GetStorageLimit(); std::map::iterator it = mapMasternodePaymentVotes.begin(); - while(it != mapMasternodePaymentVotes.end()) { + while (it != mapMasternodePaymentVotes.end()) { CMasternodePaymentVote vote = (*it).second; - if(nCachedBlockHeight - vote.nBlockHeight > nLimit) { + if (nCachedBlockHeight - vote.nBlockHeight > nLimit) { LogPrint("mnpayments", "CMasternodePayments::%s -- Removing old Masternode payment: nBlockHeight=%d\n", __func__, vote.nBlockHeight); mapMasternodePaymentVotes.erase(it++); mapMasternodeBlocks.erase(vote.nBlockHeight); @@ -871,10 +870,10 @@ bool CMasternodePaymentVote::IsValid(CNode* pnode, int nValidationHeight, std::s { masternode_info_t mnInfo; - if(!mnodeman.GetMasternodeInfo(masternodeOutpoint, mnInfo)) { + if (!mnodeman.GetMasternodeInfo(masternodeOutpoint, mnInfo)) { strError = strprintf("Unknown masternode=%s", masternodeOutpoint.ToStringShort()); // Only ask if we are already synced and still have no idea about that Masternode - if(masternodeSync.IsMasternodeListSynced()) { + if (masternodeSync.IsMasternodeListSynced()) { mnodeman.AskForMN(pnode, masternodeOutpoint, connman); } @@ -882,7 +881,7 @@ bool CMasternodePaymentVote::IsValid(CNode* pnode, int nValidationHeight, std::s } int nMinRequiredProtocol; - if(nBlockHeight >= nValidationHeight) { + if (nBlockHeight >= nValidationHeight) { // new votes must comply SPORK_10_MASTERNODE_PAY_UPDATED_NODES rules nMinRequiredProtocol = mnpayments.GetMinMasternodePaymentsProto(); } else { @@ -890,31 +889,31 @@ bool CMasternodePaymentVote::IsValid(CNode* pnode, int nValidationHeight, std::s nMinRequiredProtocol = MIN_MASTERNODE_PAYMENT_PROTO_VERSION_1; } - if(mnInfo.nProtocolVersion < nMinRequiredProtocol) { + if (mnInfo.nProtocolVersion < nMinRequiredProtocol) { strError = strprintf("Masternode protocol is too old: nProtocolVersion=%d, nMinRequiredProtocol=%d", mnInfo.nProtocolVersion, nMinRequiredProtocol); return false; } // Only masternodes should try to check masternode rank for old votes - they need to pick the right winner for future blocks. // Regular clients (miners included) need to verify masternode rank for future block votes only. - if(!fMasternodeMode && nBlockHeight < nValidationHeight) return true; + if (!fMasternodeMode && nBlockHeight < nValidationHeight) return true; int nRank; - if(!mnodeman.GetMasternodeRank(masternodeOutpoint, nRank, nBlockHeight - 101, nMinRequiredProtocol)) { + if (!mnodeman.GetMasternodeRank(masternodeOutpoint, nRank, nBlockHeight - 101, nMinRequiredProtocol)) { LogPrint("mnpayments", "CMasternodePaymentVote::%s -- Can't calculate rank for masternode %s\n", __func__, - masternodeOutpoint.ToStringShort()); + masternodeOutpoint.ToStringShort()); return false; } - if(nRank > MNPAYMENTS_SIGNATURES_TOTAL) { + if (nRank > MNPAYMENTS_SIGNATURES_TOTAL) { // It's common to have masternodes mistakenly think they are in the top 10 // We don't want to print all of these messages in normal mode, debug mode should print though strError = strprintf("Masternode %s is not in the top %d (%d)", masternodeOutpoint.ToStringShort(), MNPAYMENTS_SIGNATURES_TOTAL, nRank); // Only ban for new mnw which is out of bounds, for old mnw MN list itself might be way too much off - if(nRank > MNPAYMENTS_SIGNATURES_TOTAL*2 && nBlockHeight > nValidationHeight) { + if (nRank > MNPAYMENTS_SIGNATURES_TOTAL * 2 && nBlockHeight > nValidationHeight) { LOCK(cs_main); - strError = strprintf("Masternode %s is not in the top %d (%d)", masternodeOutpoint.ToStringShort(), MNPAYMENTS_SIGNATURES_TOTAL*2, nRank); + strError = strprintf("Masternode %s is not in the top %d (%d)", masternodeOutpoint.ToStringShort(), MNPAYMENTS_SIGNATURES_TOTAL * 2, nRank); LogPrintf("CMasternodePaymentVote::%s -- Error: %s\n", __func__, strError); Misbehaving(pnode->GetId(), 20); } @@ -933,12 +932,12 @@ bool CMasternodePayments::ProcessBlock(int nBlockHeight, CConnman& connman) // DETERMINE IF WE SHOULD BE VOTING FOR THE NEXT PAYEE - if(fLiteMode || !fMasternodeMode) return false; + if (fLiteMode || !fMasternodeMode) return false; // We have little chances to pick the right winner if winners list is out of sync // but we have no choice, so we'll try. However it doesn't make sense to even try to do so // if we have not enough data about masternodes. - if(!masternodeSync.IsMasternodeListSynced()) return false; + if (!masternodeSync.IsMasternodeListSynced()) return false; int nRank; @@ -1022,7 +1021,7 @@ void CMasternodePayments::CheckBlockVotes(int nBlockHeight) const auto itVote = mapMasternodePaymentVotes.find(voteHash); if (itVote == mapMasternodePaymentVotes.end()) { debugStr += strprintf(" - could not find vote %s\n", - voteHash.ToString()); + voteHash.ToString()); continue; } if (itVote->second.masternodeOutpoint == mn.second.outpoint) { @@ -1040,12 +1039,12 @@ void CMasternodePayments::CheckBlockVotes(int nBlockHeight) CBitcoinAddress address2(address1); debugStr += strprintf(" - %s - voted for %s\n", - mn.second.outpoint.ToStringShort(), address2.ToString()); + mn.second.outpoint.ToStringShort(), address2.ToString()); } else { mapMasternodesDidNotVote.emplace(mn.second.outpoint, 0).first->second++; debugStr += strprintf(" - %s - no vote received\n", - mn.second.outpoint.ToStringShort()); + mn.second.outpoint.ToStringShort()); } if (++i >= MNPAYMENTS_SIGNATURES_TOTAL) break; @@ -1071,7 +1070,7 @@ void CMasternodePaymentVote::Relay(CConnman& connman) const } // Do not relay until fully synced - if(!masternodeSync.IsSynced()) { + if (!masternodeSync.IsSynced()) { LogPrint("mnpayments", "CMasternodePayments::%s -- won't relay until fully synced\n", __func__); return; } @@ -1080,7 +1079,7 @@ void CMasternodePaymentVote::Relay(CConnman& connman) const connman.RelayInv(inv); } -bool CMasternodePaymentVote::CheckSignature(const CKeyID& keyIDOperator, int nValidationHeight, int &nDos) const +bool CMasternodePaymentVote::CheckSignature(const CKeyID& keyIDOperator, int nValidationHeight, int& nDos) const { // do not ban by default nDos = 0; @@ -1092,34 +1091,34 @@ bool CMasternodePaymentVote::CheckSignature(const CKeyID& keyIDOperator, int nVa if (!CHashSigner::VerifyHash(hash, keyIDOperator, vchSig, strError)) { // could be a signature in old format std::string strMessage = masternodeOutpoint.ToStringShort() + - std::to_string(nBlockHeight) + - ScriptToAsmStr(payee); - if(!CMessageSigner::VerifyMessage(keyIDOperator, vchSig, strMessage, strError)) { + std::to_string(nBlockHeight) + + ScriptToAsmStr(payee); + if (!CMessageSigner::VerifyMessage(keyIDOperator, vchSig, strMessage, strError)) { // nope, not in old format either // Only ban for future block vote when we are already synced. // Otherwise it could be the case when MN which signed this vote is using another key now // and we have no idea about the old one. - if(masternodeSync.IsMasternodeListSynced() && nBlockHeight > nValidationHeight) { + if (masternodeSync.IsMasternodeListSynced() && nBlockHeight > nValidationHeight) { nDos = 20; } return error("CMasternodePaymentVote::CheckSignature -- Got bad Masternode payment signature, masternode=%s, error: %s", - masternodeOutpoint.ToStringShort(), strError); + masternodeOutpoint.ToStringShort(), strError); } } } else { std::string strMessage = masternodeOutpoint.ToStringShort() + - std::to_string(nBlockHeight) + - ScriptToAsmStr(payee); + std::to_string(nBlockHeight) + + ScriptToAsmStr(payee); if (!CMessageSigner::VerifyMessage(keyIDOperator, vchSig, strMessage, strError)) { // Only ban for future block vote when we are already synced. // Otherwise it could be the case when MN which signed this vote is using another key now // and we have no idea about the old one. - if(masternodeSync.IsMasternodeListSynced() && nBlockHeight > nValidationHeight) { + if (masternodeSync.IsMasternodeListSynced() && nBlockHeight > nValidationHeight) { nDos = 20; } return error("CMasternodePaymentVote::CheckSignature -- Got bad Masternode payment signature, masternode=%s, error: %s", - masternodeOutpoint.ToStringShort(), strError); + masternodeOutpoint.ToStringShort(), strError); } } @@ -1130,10 +1129,7 @@ std::string CMasternodePaymentVote::ToString() const { std::ostringstream info; - info << masternodeOutpoint.ToStringShort() << - ", " << nBlockHeight << - ", " << ScriptToAsmStr(payee) << - ", " << (int)vchSig.size(); + info << masternodeOutpoint.ToStringShort() << ", " << nBlockHeight << ", " << ScriptToAsmStr(payee) << ", " << (int)vchSig.size(); return info.str(); } @@ -1143,17 +1139,17 @@ void CMasternodePayments::Sync(CNode* pnode, CConnman& connman) const { LOCK(cs_mapMasternodeBlocks); - if(!masternodeSync.IsWinnersListSynced()) return; + if (!masternodeSync.IsWinnersListSynced()) return; int nInvCount = 0; - for(int h = nCachedBlockHeight; h < nCachedBlockHeight + 20; h++) { + for (int h = nCachedBlockHeight; h < nCachedBlockHeight + 20; h++) { const auto it = mapMasternodeBlocks.find(h); - if(it != mapMasternodeBlocks.end()) { + if (it != mapMasternodeBlocks.end()) { for (const auto& payee : it->second.vecPayees) { std::vector vecVoteHashes = payee.GetVoteHashes(); for (const auto& hash : vecVoteHashes) { - if(!HasVerifiedPaymentVote(hash)) continue; + if (!HasVerifiedPaymentVote(hash)) continue; pnode->PushInventory(CInv(MSG_MASTERNODE_PAYMENT_VOTE, hash)); nInvCount++; } @@ -1169,7 +1165,7 @@ void CMasternodePayments::Sync(CNode* pnode, CConnman& connman) const // Request low data/unknown payment blocks in batches directly from some node instead of/after preliminary Sync. void CMasternodePayments::RequestLowDataPaymentBlocks(CNode* pnode, CConnman& connman) const { - if(!masternodeSync.IsMasternodeListSynced()) return; + if (!masternodeSync.IsMasternodeListSynced()) return; CNetMsgMaker msgMaker(pnode->GetSendVersion()); LOCK2(cs_main, cs_mapMasternodeBlocks); @@ -1177,22 +1173,22 @@ void CMasternodePayments::RequestLowDataPaymentBlocks(CNode* pnode, CConnman& co std::vector vToFetch; int nLimit = GetStorageLimit(); - const CBlockIndex *pindex = chainActive.Tip(); + const CBlockIndex* pindex = chainActive.Tip(); - while(nCachedBlockHeight - pindex->nHeight < nLimit) { + while (nCachedBlockHeight - pindex->nHeight < nLimit) { const auto it = mapMasternodeBlocks.find(pindex->nHeight); - if(it == mapMasternodeBlocks.end()) { + if (it == mapMasternodeBlocks.end()) { // We have no idea about this block height, let's ask vToFetch.push_back(CInv(MSG_MASTERNODE_PAYMENT_BLOCK, pindex->GetBlockHash())); // We should not violate GETDATA rules - if(vToFetch.size() == MAX_INV_SZ) { + if (vToFetch.size() == MAX_INV_SZ) { LogPrintf("CMasternodePayments::%s -- asking peer=%d for %d blocks\n", __func__, pnode->id, MAX_INV_SZ); connman.PushMessage(pnode, msgMaker.Make(NetMsgType::GETDATA, vToFetch)); // Start filling new batch vToFetch.clear(); } } - if(!pindex->pprev) break; + if (!pindex->pprev) break; pindex = pindex->pprev; } @@ -1201,7 +1197,7 @@ void CMasternodePayments::RequestLowDataPaymentBlocks(CNode* pnode, CConnman& co int nTotalVotes = 0; bool fFound = false; for (const auto& payee : mnBlockPayees.second.vecPayees) { - if(payee.GetVoteCount() >= MNPAYMENTS_SIGNATURES_REQUIRED) { + if (payee.GetVoteCount() >= MNPAYMENTS_SIGNATURES_REQUIRED) { fFound = true; break; } @@ -1209,29 +1205,28 @@ void CMasternodePayments::RequestLowDataPaymentBlocks(CNode* pnode, CConnman& co } // A clear winner (MNPAYMENTS_SIGNATURES_REQUIRED+ votes) was found // or no clear winner was found but there are at least avg number of votes - if(fFound || nTotalVotes >= (MNPAYMENTS_SIGNATURES_TOTAL + MNPAYMENTS_SIGNATURES_REQUIRED)/2) { + if (fFound || nTotalVotes >= (MNPAYMENTS_SIGNATURES_TOTAL + MNPAYMENTS_SIGNATURES_REQUIRED) / 2) { // so just move to the next block continue; } // DEBUG - DBG ( + DBG( // Let's see why this failed - for (const auto& payee : mnBlockPayees.second.vecPayees) { + for (const auto& payee + : mnBlockPayees.second.vecPayees) { CTxDestination address1; ExtractDestination(payee.GetPayee(), address1); CBitcoinAddress address2(address1); printf("payee %s votes %d\n", address2.ToString().c_str(), payee.GetVoteCount()); - } - printf("block %d votes total %d\n", nBlockHeight, nTotalVotes); - ) + } printf("block %d votes total %d\n", nBlockHeight, nTotalVotes);) // END DEBUG // Low data block found, let's try to sync it uint256 hash; - if(GetBlockHash(hash, nBlockHeight)) { + if (GetBlockHash(hash, nBlockHeight)) { vToFetch.push_back(CInv(MSG_MASTERNODE_PAYMENT_BLOCK, hash)); } // We should not violate GETDATA rules - if(vToFetch.size() == MAX_INV_SZ) { + if (vToFetch.size() == MAX_INV_SZ) { LogPrintf("CMasternodePayments::%s -- asking peer=%d for %d payment blocks\n", __func__, pnode->id, MAX_INV_SZ); connman.PushMessage(pnode, msgMaker.Make(NetMsgType::GETDATA, vToFetch)); // Start filling new batch @@ -1239,7 +1234,7 @@ void CMasternodePayments::RequestLowDataPaymentBlocks(CNode* pnode, CConnman& co } } // Ask for the rest of it - if(!vToFetch.empty()) { + if (!vToFetch.empty()) { LogPrintf("CMasternodePayments::%s -- asking peer=%d for %d payment blocks\n", __func__, pnode->id, vToFetch.size()); connman.PushMessage(pnode, msgMaker.Make(NetMsgType::GETDATA, vToFetch)); } @@ -1249,8 +1244,7 @@ std::string CMasternodePayments::ToString() const { std::ostringstream info; - info << "Votes: " << (int)mapMasternodePaymentVotes.size() << - ", Blocks: " << (int)mapMasternodeBlocks.size(); + info << "Votes: " << (int)mapMasternodePaymentVotes.size() << ", Blocks: " << (int)mapMasternodeBlocks.size(); return info.str(); } @@ -1267,9 +1261,9 @@ int CMasternodePayments::GetStorageLimit() const return std::max(int(mnodeman.size() * nStorageCoeff), nMinBlocksToStore); } -void CMasternodePayments::UpdatedBlockTip(const CBlockIndex *pindex, CConnman& connman) +void CMasternodePayments::UpdatedBlockTip(const CBlockIndex* pindex, CConnman& connman) { - if(!pindex) return; + if (!pindex) return; if (deterministicMNManager->IsDeterministicMNsSporkActive(pindex->nHeight)) { return; diff --git a/src/masternode-payments.h b/src/masternode-payments.h index e1e2eb9eecad..a3dc83c57143 100644 --- a/src/masternode-payments.h +++ b/src/masternode-payments.h @@ -5,19 +5,19 @@ #ifndef MASTERNODE_PAYMENTS_H #define MASTERNODE_PAYMENTS_H -#include "util.h" #include "core_io.h" #include "key.h" #include "masternode.h" #include "net_processing.h" +#include "util.h" #include "utilstrencodings.h" class CMasternodePayments; class CMasternodePaymentVote; class CMasternodeBlockPayees; -static const int MNPAYMENTS_SIGNATURES_REQUIRED = 6; -static const int MNPAYMENTS_SIGNATURES_TOTAL = 10; +static const int MNPAYMENTS_SIGNATURES_REQUIRED = 6; +static const int MNPAYMENTS_SIGNATURES_TOTAL = 10; //! minimum peer version that can receive and send masternode payment messages, // vote for masternode and be elected as a payment winner @@ -47,7 +47,8 @@ class CMasternodePayee CMasternodePayee() : scriptPubKey(), vecVoteHashes() - {} + { + } CMasternodePayee(CScript payee, uint256 hashIn) : scriptPubKey(payee), @@ -59,7 +60,8 @@ class CMasternodePayee ADD_SERIALIZE_METHODS; template - inline void SerializationOp(Stream& s, Operation ser_action) { + inline void SerializationOp(Stream& s, Operation ser_action) + { READWRITE(*(CScriptBase*)(&scriptPubKey)); READWRITE(vecVoteHashes); } @@ -81,16 +83,19 @@ class CMasternodeBlockPayees CMasternodeBlockPayees() : nBlockHeight(0), vecPayees() - {} + { + } CMasternodeBlockPayees(int nBlockHeightIn) : nBlockHeight(nBlockHeightIn), vecPayees() - {} + { + } ADD_SERIALIZE_METHODS; template - inline void SerializationOp(Stream& s, Operation ser_action) { + inline void SerializationOp(Stream& s, Operation ser_action) + { READWRITE(nBlockHeight); READWRITE(vecPayees); } @@ -119,19 +124,22 @@ class CMasternodePaymentVote nBlockHeight(0), payee(), vchSig() - {} + { + } CMasternodePaymentVote(COutPoint outpoint, int nBlockHeight, CScript payee) : masternodeOutpoint(outpoint), nBlockHeight(nBlockHeight), payee(payee), vchSig() - {} + { + } ADD_SERIALIZE_METHODS; template - inline void SerializationOp(Stream& s, Operation ser_action) { + inline void SerializationOp(Stream& s, Operation ser_action) + { READWRITE(masternodeOutpoint); READWRITE(nBlockHeight); READWRITE(*(CScriptBase*)(&payee)); @@ -144,7 +152,7 @@ class CMasternodePaymentVote uint256 GetSignatureHash() const; bool Sign(); - bool CheckSignature(const CKeyID& keyIDOperator, int nValidationHeight, int &nDos) const; + bool CheckSignature(const CKeyID& keyIDOperator, int nValidationHeight, int& nDos) const; bool IsValid(CNode* pnode, int nValidationHeight, std::string& strError, CConnman& connman) const; void Relay(CConnman& connman) const; @@ -177,12 +185,14 @@ class CMasternodePayments std::map mapMasternodesLastVote; std::map mapMasternodesDidNotVote; - CMasternodePayments() : nStorageCoeff(1.25), nMinBlocksToStore(6000) {} + CMasternodePayments() : + nStorageCoeff(1.25), nMinBlocksToStore(6000) {} ADD_SERIALIZE_METHODS; template - inline void SerializationOp(Stream& s, Operation ser_action) { + inline void SerializationOp(Stream& s, Operation ser_action) + { READWRITE(mapMasternodePaymentVotes); READWRITE(mapMasternodeBlocks); } @@ -216,7 +226,7 @@ class CMasternodePayments bool IsEnoughData() const; int GetStorageLimit() const; - void UpdatedBlockTip(const CBlockIndex *pindex, CConnman& connman); + void UpdatedBlockTip(const CBlockIndex* pindex, CConnman& connman); void DoMaintenance() { CheckAndRemove(); } }; diff --git a/src/masternode-sync.cpp b/src/masternode-sync.cpp index 2581de6ebe90..8c969c65d91a 100644 --- a/src/masternode-sync.cpp +++ b/src/masternode-sync.cpp @@ -2,16 +2,16 @@ // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. +#include "masternode-sync.h" #include "activemasternode.h" +#include "evo/deterministicmns.h" #include "governance.h" -#include "validation.h" #include "masternode-payments.h" -#include "masternode-sync.h" #include "masternodeman.h" #include "netfulfilledman.h" #include "netmessagemaker.h" #include "ui_interface.h" -#include "evo/deterministicmns.h" +#include "validation.h" class CMasternodeSync; CMasternodeSync masternodeSync; @@ -33,73 +33,79 @@ void CMasternodeSync::Reset() void CMasternodeSync::BumpAssetLastTime(const std::string& strFuncName) { - if(IsSynced() || IsFailed()) return; + if (IsSynced() || IsFailed()) return; nTimeLastBumped = GetTime(); LogPrint("mnsync", "CMasternodeSync::BumpAssetLastTime -- %s\n", strFuncName); } std::string CMasternodeSync::GetAssetName() { - switch(nCurrentAsset) - { - case(MASTERNODE_SYNC_INITIAL): return "MASTERNODE_SYNC_INITIAL"; - case(MASTERNODE_SYNC_WAITING): return "MASTERNODE_SYNC_WAITING"; - case(MASTERNODE_SYNC_LIST): return "MASTERNODE_SYNC_LIST"; - case(MASTERNODE_SYNC_MNW): return "MASTERNODE_SYNC_MNW"; - case(MASTERNODE_SYNC_GOVERNANCE): return "MASTERNODE_SYNC_GOVERNANCE"; - case(MASTERNODE_SYNC_FAILED): return "MASTERNODE_SYNC_FAILED"; - case MASTERNODE_SYNC_FINISHED: return "MASTERNODE_SYNC_FINISHED"; - default: return "UNKNOWN"; + switch (nCurrentAsset) { + case (MASTERNODE_SYNC_INITIAL): + return "MASTERNODE_SYNC_INITIAL"; + case (MASTERNODE_SYNC_WAITING): + return "MASTERNODE_SYNC_WAITING"; + case (MASTERNODE_SYNC_LIST): + return "MASTERNODE_SYNC_LIST"; + case (MASTERNODE_SYNC_MNW): + return "MASTERNODE_SYNC_MNW"; + case (MASTERNODE_SYNC_GOVERNANCE): + return "MASTERNODE_SYNC_GOVERNANCE"; + case (MASTERNODE_SYNC_FAILED): + return "MASTERNODE_SYNC_FAILED"; + case MASTERNODE_SYNC_FINISHED: + return "MASTERNODE_SYNC_FINISHED"; + default: + return "UNKNOWN"; } } void CMasternodeSync::SwitchToNextAsset(CConnman& connman) { - switch(nCurrentAsset) - { - case(MASTERNODE_SYNC_FAILED): - throw std::runtime_error("Can't switch to next asset from failed, should use Reset() first!"); - break; - case(MASTERNODE_SYNC_INITIAL): - nCurrentAsset = MASTERNODE_SYNC_WAITING; - LogPrintf("CMasternodeSync::SwitchToNextAsset -- Starting %s\n", GetAssetName()); - break; - case(MASTERNODE_SYNC_WAITING): - LogPrintf("CMasternodeSync::SwitchToNextAsset -- Completed %s in %llds\n", GetAssetName(), GetTime() - nTimeAssetSyncStarted); - if (deterministicMNManager->IsDeterministicMNsSporkActive()) { - nCurrentAsset = MASTERNODE_SYNC_GOVERNANCE; - } else { - nCurrentAsset = MASTERNODE_SYNC_LIST; - } - LogPrintf("CMasternodeSync::SwitchToNextAsset -- Starting %s\n", GetAssetName()); - break; - case(MASTERNODE_SYNC_LIST): - LogPrintf("CMasternodeSync::SwitchToNextAsset -- Completed %s in %llds\n", GetAssetName(), GetTime() - nTimeAssetSyncStarted); - if (deterministicMNManager->IsDeterministicMNsSporkActive()) { - nCurrentAsset = MASTERNODE_SYNC_GOVERNANCE; - } else { - nCurrentAsset = MASTERNODE_SYNC_MNW; - } - LogPrintf("CMasternodeSync::SwitchToNextAsset -- Starting %s\n", GetAssetName()); - break; - case(MASTERNODE_SYNC_MNW): - LogPrintf("CMasternodeSync::SwitchToNextAsset -- Completed %s in %llds\n", GetAssetName(), GetTime() - nTimeAssetSyncStarted); + switch (nCurrentAsset) { + case (MASTERNODE_SYNC_FAILED): + throw std::runtime_error("Can't switch to next asset from failed, should use Reset() first!"); + break; + case (MASTERNODE_SYNC_INITIAL): + nCurrentAsset = MASTERNODE_SYNC_WAITING; + LogPrintf("CMasternodeSync::SwitchToNextAsset -- Starting %s\n", GetAssetName()); + break; + case (MASTERNODE_SYNC_WAITING): + LogPrintf("CMasternodeSync::SwitchToNextAsset -- Completed %s in %llds\n", GetAssetName(), GetTime() - nTimeAssetSyncStarted); + if (deterministicMNManager->IsDeterministicMNsSporkActive()) { nCurrentAsset = MASTERNODE_SYNC_GOVERNANCE; - LogPrintf("CMasternodeSync::SwitchToNextAsset -- Starting %s\n", GetAssetName()); - break; - case(MASTERNODE_SYNC_GOVERNANCE): - LogPrintf("CMasternodeSync::SwitchToNextAsset -- Completed %s in %llds\n", GetAssetName(), GetTime() - nTimeAssetSyncStarted); - nCurrentAsset = MASTERNODE_SYNC_FINISHED; - uiInterface.NotifyAdditionalDataSyncProgressChanged(1); - //try to activate our masternode if possible - legacyActiveMasternodeManager.ManageState(connman); - - connman.ForEachNode(CConnman::AllNodes, [](CNode* pnode) { - netfulfilledman.AddFulfilledRequest(pnode->addr, "full-sync"); - }); - LogPrintf("CMasternodeSync::SwitchToNextAsset -- Sync has finished\n"); - - break; + } else { + nCurrentAsset = MASTERNODE_SYNC_LIST; + } + LogPrintf("CMasternodeSync::SwitchToNextAsset -- Starting %s\n", GetAssetName()); + break; + case (MASTERNODE_SYNC_LIST): + LogPrintf("CMasternodeSync::SwitchToNextAsset -- Completed %s in %llds\n", GetAssetName(), GetTime() - nTimeAssetSyncStarted); + if (deterministicMNManager->IsDeterministicMNsSporkActive()) { + nCurrentAsset = MASTERNODE_SYNC_GOVERNANCE; + } else { + nCurrentAsset = MASTERNODE_SYNC_MNW; + } + LogPrintf("CMasternodeSync::SwitchToNextAsset -- Starting %s\n", GetAssetName()); + break; + case (MASTERNODE_SYNC_MNW): + LogPrintf("CMasternodeSync::SwitchToNextAsset -- Completed %s in %llds\n", GetAssetName(), GetTime() - nTimeAssetSyncStarted); + nCurrentAsset = MASTERNODE_SYNC_GOVERNANCE; + LogPrintf("CMasternodeSync::SwitchToNextAsset -- Starting %s\n", GetAssetName()); + break; + case (MASTERNODE_SYNC_GOVERNANCE): + LogPrintf("CMasternodeSync::SwitchToNextAsset -- Completed %s in %llds\n", GetAssetName(), GetTime() - nTimeAssetSyncStarted); + nCurrentAsset = MASTERNODE_SYNC_FINISHED; + uiInterface.NotifyAdditionalDataSyncProgressChanged(1); + //try to activate our masternode if possible + legacyActiveMasternodeManager.ManageState(connman); + + connman.ForEachNode(CConnman::AllNodes, [](CNode* pnode) { + netfulfilledman.AddFulfilledRequest(pnode->addr, "full-sync"); + }); + LogPrintf("CMasternodeSync::SwitchToNextAsset -- Sync has finished\n"); + + break; } nTriedPeerCount = 0; nTimeAssetSyncStarted = GetTime(); @@ -109,14 +115,22 @@ void CMasternodeSync::SwitchToNextAsset(CConnman& connman) std::string CMasternodeSync::GetSyncStatus() { switch (masternodeSync.nCurrentAsset) { - case MASTERNODE_SYNC_INITIAL: return _("Synchroning blockchain..."); - case MASTERNODE_SYNC_WAITING: return _("Synchronization pending..."); - case MASTERNODE_SYNC_LIST: return _("Synchronizing masternodes..."); - case MASTERNODE_SYNC_MNW: return _("Synchronizing masternode payments..."); - case MASTERNODE_SYNC_GOVERNANCE: return _("Synchronizing governance objects..."); - case MASTERNODE_SYNC_FAILED: return _("Synchronization failed"); - case MASTERNODE_SYNC_FINISHED: return _("Synchronization finished"); - default: return ""; + case MASTERNODE_SYNC_INITIAL: + return _("Synchroning blockchain..."); + case MASTERNODE_SYNC_WAITING: + return _("Synchronization pending..."); + case MASTERNODE_SYNC_LIST: + return _("Synchronizing masternodes..."); + case MASTERNODE_SYNC_MNW: + return _("Synchronizing masternode payments..."); + case MASTERNODE_SYNC_GOVERNANCE: + return _("Synchronizing governance objects..."); + case MASTERNODE_SYNC_FAILED: + return _("Synchronization failed"); + case MASTERNODE_SYNC_FINISHED: + return _("Synchronization finished"); + default: + return ""; } } @@ -125,7 +139,7 @@ void CMasternodeSync::ProcessMessage(CNode* pfrom, const std::string& strCommand if (strCommand == NetMsgType::SYNCSTATUSCOUNT) { //Sync status count //do not care about stats if sync process finished or failed - if(IsSynced() || IsFailed()) return; + if (IsSynced() || IsFailed()) return; int nItemID; int nCount; @@ -142,7 +156,7 @@ void CMasternodeSync::ProcessTick(CConnman& connman) // reset the sync process if the last call to this function was more than 60 minutes ago (client was in sleep mode) static int64_t nTimeLastProcess = GetTime(); - if(GetTime() - nTimeLastProcess > 60*60) { + if (GetTime() - nTimeLastProcess > 60 * 60) { LogPrintf("CMasternodeSync::ProcessTick -- WARNING: no actions for too long, restarting sync...\n"); Reset(); SwitchToNextAsset(connman); @@ -152,8 +166,8 @@ void CMasternodeSync::ProcessTick(CConnman& connman) nTimeLastProcess = GetTime(); // reset sync status in case of any other sync failure - if(IsFailed()) { - if(nTimeLastFailure + (1*60) < GetTime()) { // 1 minute cooldown after failed sync + if (IsFailed()) { + if (nTimeLastFailure + (1 * 60) < GetTime()) { // 1 minute cooldown after failed sync LogPrintf("CMasternodeSync::ProcessTick -- WARNING: failed to sync, trying again...\n"); Reset(); SwitchToNextAsset(connman); @@ -162,7 +176,7 @@ void CMasternodeSync::ProcessTick(CConnman& connman) } // gradually request the rest of the votes after sync finished - if(IsSynced()) { + if (IsSynced()) { std::vector vNodesCopy = connman.CopyNodeVector(CConnman::FullyConnectedOnly); governance.RequestGovernanceObjectVotes(vNodesCopy, connman); connman.ReleaseNodeVector(vNodesCopy); @@ -170,25 +184,23 @@ void CMasternodeSync::ProcessTick(CConnman& connman) } // Calculate "progress" for LOG reporting / GUI notification - double nSyncProgress = double(nTriedPeerCount + (nCurrentAsset - 1) * 8) / (8*4); + double nSyncProgress = double(nTriedPeerCount + (nCurrentAsset - 1) * 8) / (8 * 4); LogPrintf("CMasternodeSync::ProcessTick -- nTick %d nCurrentAsset %d nTriedPeerCount %d nSyncProgress %f\n", nTick, nCurrentAsset, nTriedPeerCount, nSyncProgress); uiInterface.NotifyAdditionalDataSyncProgressChanged(nSyncProgress); std::vector vNodesCopy = connman.CopyNodeVector(CConnman::FullyConnectedOnly); - for (auto& pnode : vNodesCopy) - { + for (auto& pnode : vNodesCopy) { CNetMsgMaker msgMaker(pnode->GetSendVersion()); // Don't try to sync any data from outbound "masternode" connections - // they are temporary and should be considered unreliable for a sync process. // Inbound connection this early is most likely a "masternode" connection // initiated from another node, so skip it too. - if(pnode->fMasternode || (fMasternodeMode && pnode->fInbound)) continue; + if (pnode->fMasternode || (fMasternodeMode && pnode->fInbound)) continue; // QUICK MODE (REGTEST ONLY!) - if(Params().NetworkIDString() == CBaseChainParams::REGTEST) - { + if (Params().NetworkIDString() == CBaseChainParams::REGTEST) { if (nCurrentAsset == MASTERNODE_SYNC_WAITING) { connman.PushMessage(pnode, msgMaker.Make(NetMsgType::GETSPORKS)); //get current network sporks SwitchToNextAsset(connman); @@ -212,7 +224,7 @@ void CMasternodeSync::ProcessTick(CConnman& connman) // NORMAL NETWORK MODE - TESTNET/MAINNET { - if(netfulfilledman.HasFulfilledRequest(pnode->addr, "full-sync")) { + if (netfulfilledman.HasFulfilledRequest(pnode->addr, "full-sync")) { // We already fully synced from this node recently, // disconnect to free this connection slot for another peer. pnode->fDisconnect = true; @@ -222,7 +234,7 @@ void CMasternodeSync::ProcessTick(CConnman& connman) // SPORK : ALWAYS ASK FOR SPORKS AS WE SYNC - if(!netfulfilledman.HasFulfilledRequest(pnode->addr, "spork-sync")) { + if (!netfulfilledman.HasFulfilledRequest(pnode->addr, "spork-sync")) { // always get sporks first, only request once from each peer netfulfilledman.AddFulfilledRequest(pnode->addr, "spork-sync"); // get current network sporks @@ -232,8 +244,8 @@ void CMasternodeSync::ProcessTick(CConnman& connman) // INITIAL TIMEOUT - if(nCurrentAsset == MASTERNODE_SYNC_WAITING) { - if(GetTime() - nTimeLastBumped > MASTERNODE_SYNC_TIMEOUT_SECONDS) { + if (nCurrentAsset == MASTERNODE_SYNC_WAITING) { + if (GetTime() - nTimeLastBumped > MASTERNODE_SYNC_TIMEOUT_SECONDS) { // At this point we know that: // a) there are peers (because we are looping on at least one of them); // b) we waited for at least MASTERNODE_SYNC_TIMEOUT_SECONDS since we reached @@ -248,7 +260,7 @@ void CMasternodeSync::ProcessTick(CConnman& connman) // MNLIST : SYNC MASTERNODE LIST FROM OTHER CONNECTED CLIENTS - if(nCurrentAsset == MASTERNODE_SYNC_LIST) { + if (nCurrentAsset == MASTERNODE_SYNC_LIST) { if (deterministicMNManager->IsDeterministicMNsSporkActive()) { SwitchToNextAsset(connman); connman.ReleaseNodeVector(vNodesCopy); @@ -257,7 +269,7 @@ void CMasternodeSync::ProcessTick(CConnman& connman) LogPrint("masternode", "CMasternodeSync::ProcessTick -- nTick %d nCurrentAsset %d nTimeLastBumped %lld GetTime() %lld diff %lld\n", nTick, nCurrentAsset, nTimeLastBumped, GetTime(), GetTime() - nTimeLastBumped); // check for timeout first - if(GetTime() - nTimeLastBumped > MASTERNODE_SYNC_TIMEOUT_SECONDS) { + if (GetTime() - nTimeLastBumped > MASTERNODE_SYNC_TIMEOUT_SECONDS) { LogPrintf("CMasternodeSync::ProcessTick -- nTick %d nCurrentAsset %d -- timeout\n", nTick, nCurrentAsset); if (nTriedPeerCount == 0) { LogPrintf("CMasternodeSync::ProcessTick -- ERROR: failed to sync %s\n", GetAssetName()); @@ -278,7 +290,7 @@ void CMasternodeSync::ProcessTick(CConnman& connman) } // only request once from each peer - if(netfulfilledman.HasFulfilledRequest(pnode->addr, "masternode-list-sync")) continue; + if (netfulfilledman.HasFulfilledRequest(pnode->addr, "masternode-list-sync")) continue; netfulfilledman.AddFulfilledRequest(pnode->addr, "masternode-list-sync"); if (pnode->nVersion < mnpayments.GetMinMasternodePaymentsProto()) continue; @@ -292,7 +304,7 @@ void CMasternodeSync::ProcessTick(CConnman& connman) // MNW : SYNC MASTERNODE PAYMENT VOTES FROM OTHER CONNECTED CLIENTS - if(nCurrentAsset == MASTERNODE_SYNC_MNW) { + if (nCurrentAsset == MASTERNODE_SYNC_MNW) { if (deterministicMNManager->IsDeterministicMNsSporkActive()) { SwitchToNextAsset(connman); connman.ReleaseNodeVector(vNodesCopy); @@ -303,7 +315,7 @@ void CMasternodeSync::ProcessTick(CConnman& connman) // check for timeout first // This might take a lot longer than MASTERNODE_SYNC_TIMEOUT_SECONDS due to new blocks, // but that should be OK and it should timeout eventually. - if(GetTime() - nTimeLastBumped > MASTERNODE_SYNC_TIMEOUT_SECONDS) { + if (GetTime() - nTimeLastBumped > MASTERNODE_SYNC_TIMEOUT_SECONDS) { LogPrintf("CMasternodeSync::ProcessTick -- nTick %d nCurrentAsset %d -- timeout\n", nTick, nCurrentAsset); if (nTriedPeerCount == 0) { LogPrintf("CMasternodeSync::ProcessTick -- ERROR: failed to sync %s\n", GetAssetName()); @@ -320,7 +332,7 @@ void CMasternodeSync::ProcessTick(CConnman& connman) // check for data // if mnpayments already has enough blocks and votes, switch to the next asset // try to fetch data from at least two peers though - if(nTriedPeerCount > 1 && mnpayments.IsEnoughData()) { + if (nTriedPeerCount > 1 && mnpayments.IsEnoughData()) { LogPrintf("CMasternodeSync::ProcessTick -- nTick %d nCurrentAsset %d -- found enough data\n", nTick, nCurrentAsset); SwitchToNextAsset(connman); connman.ReleaseNodeVector(vNodesCopy); @@ -334,10 +346,10 @@ void CMasternodeSync::ProcessTick(CConnman& connman) } // only request once from each peer - if(netfulfilledman.HasFulfilledRequest(pnode->addr, "masternode-payment-sync")) continue; + if (netfulfilledman.HasFulfilledRequest(pnode->addr, "masternode-payment-sync")) continue; netfulfilledman.AddFulfilledRequest(pnode->addr, "masternode-payment-sync"); - if(pnode->nVersion < mnpayments.GetMinMasternodePaymentsProto()) continue; + if (pnode->nVersion < mnpayments.GetMinMasternodePaymentsProto()) continue; nTriedPeerCount++; // ask node for all payment votes it has (new nodes will only return votes for future payments) @@ -351,13 +363,13 @@ void CMasternodeSync::ProcessTick(CConnman& connman) // GOVOBJ : SYNC GOVERNANCE ITEMS FROM OUR PEERS - if(nCurrentAsset == MASTERNODE_SYNC_GOVERNANCE) { + if (nCurrentAsset == MASTERNODE_SYNC_GOVERNANCE) { LogPrint("gobject", "CMasternodeSync::ProcessTick -- nTick %d nCurrentAsset %d nTimeLastBumped %lld GetTime() %lld diff %lld\n", nTick, nCurrentAsset, nTimeLastBumped, GetTime(), GetTime() - nTimeLastBumped); // check for timeout first - if(GetTime() - nTimeLastBumped > MASTERNODE_SYNC_TIMEOUT_SECONDS) { + if (GetTime() - nTimeLastBumped > MASTERNODE_SYNC_TIMEOUT_SECONDS) { LogPrintf("CMasternodeSync::ProcessTick -- nTick %d nCurrentAsset %d -- timeout\n", nTick, nCurrentAsset); - if(nTriedPeerCount == 0) { + if (nTriedPeerCount == 0) { LogPrintf("CMasternodeSync::ProcessTick -- WARNING: failed to sync %s\n", GetAssetName()); // it's kind of ok to skip this for now, hopefully we'll catch up later? } @@ -367,22 +379,21 @@ void CMasternodeSync::ProcessTick(CConnman& connman) } // only request obj sync once from each peer, then request votes on per-obj basis - if(netfulfilledman.HasFulfilledRequest(pnode->addr, "governance-sync")) { + if (netfulfilledman.HasFulfilledRequest(pnode->addr, "governance-sync")) { int nObjsLeftToAsk = governance.RequestGovernanceObjectVotes(pnode, connman); static int64_t nTimeNoObjectsLeft = 0; // check for data - if(nObjsLeftToAsk == 0) { + if (nObjsLeftToAsk == 0) { static int nLastTick = 0; static int nLastVotes = 0; - if(nTimeNoObjectsLeft == 0) { + if (nTimeNoObjectsLeft == 0) { // asked all objects for votes for the first time nTimeNoObjectsLeft = GetTime(); } // make sure the condition below is checked only once per tick - if(nLastTick == nTick) continue; - if(GetTime() - nTimeNoObjectsLeft > MASTERNODE_SYNC_TIMEOUT_SECONDS && - governance.GetVoteCount() - nLastVotes < std::max(int(0.0001 * nLastVotes), MASTERNODE_SYNC_TICK_SECONDS) - ) { + if (nLastTick == nTick) continue; + if (GetTime() - nTimeNoObjectsLeft > MASTERNODE_SYNC_TIMEOUT_SECONDS && + governance.GetVoteCount() - nLastVotes < std::max(int(0.0001 * nLastVotes), MASTERNODE_SYNC_TICK_SECONDS)) { // We already asked for all objects, waited for MASTERNODE_SYNC_TIMEOUT_SECONDS // after that and less then 0.01% or MASTERNODE_SYNC_TICK_SECONDS // (i.e. 1 per second) votes were recieved during the last tick. @@ -419,18 +430,17 @@ void CMasternodeSync::SendGovernanceSyncRequest(CNode* pnode, CConnman& connman) { CNetMsgMaker msgMaker(pnode->GetSendVersion()); - if(pnode->nVersion >= GOVERNANCE_FILTER_PROTO_VERSION) { + if (pnode->nVersion >= GOVERNANCE_FILTER_PROTO_VERSION) { CBloomFilter filter; filter.clear(); connman.PushMessage(pnode, msgMaker.Make(NetMsgType::MNGOVERNANCESYNC, uint256(), filter)); - } - else { + } else { connman.PushMessage(pnode, msgMaker.Make(NetMsgType::MNGOVERNANCESYNC, uint256())); } } -void CMasternodeSync::AcceptedBlockHeader(const CBlockIndex *pindexNew) +void CMasternodeSync::AcceptedBlockHeader(const CBlockIndex* pindexNew) { LogPrint("mnsync", "CMasternodeSync::AcceptedBlockHeader -- pindexNew->nHeight: %d\n", pindexNew->nHeight); @@ -440,7 +450,7 @@ void CMasternodeSync::AcceptedBlockHeader(const CBlockIndex *pindexNew) } } -void CMasternodeSync::NotifyHeaderTip(const CBlockIndex *pindexNew, bool fInitialDownload, CConnman& connman) +void CMasternodeSync::NotifyHeaderTip(const CBlockIndex* pindexNew, bool fInitialDownload, CConnman& connman) { LogPrint("mnsync", "CMasternodeSync::NotifyHeaderTip -- pindexNew->nHeight: %d fInitialDownload=%d\n", pindexNew->nHeight, fInitialDownload); @@ -453,7 +463,7 @@ void CMasternodeSync::NotifyHeaderTip(const CBlockIndex *pindexNew, bool fInitia } } -void CMasternodeSync::UpdatedBlockTip(const CBlockIndex *pindexNew, bool fInitialDownload, CConnman& connman) +void CMasternodeSync::UpdatedBlockTip(const CBlockIndex* pindexNew, bool fInitialDownload, CConnman& connman) { LogPrint("mnsync", "CMasternodeSync::UpdatedBlockTip -- pindexNew->nHeight: %d fInitialDownload=%d\n", pindexNew->nHeight, fInitialDownload); @@ -491,7 +501,7 @@ void CMasternodeSync::UpdatedBlockTip(const CBlockIndex *pindexNew, bool fInitia fReachedBestHeader = fReachedBestHeaderNew; LogPrint("mnsync", "CMasternodeSync::UpdatedBlockTip -- pindexNew->nHeight: %d pindexBestHeader->nHeight: %d fInitialDownload=%d fReachedBestHeader=%d\n", - pindexNew->nHeight, pindexBestHeader->nHeight, fInitialDownload, fReachedBestHeader); + pindexNew->nHeight, pindexBestHeader->nHeight, fInitialDownload, fReachedBestHeader); if (!IsBlockchainSynced() && fReachedBestHeader) { if (fLiteMode) { diff --git a/src/masternode-sync.h b/src/masternode-sync.h index e0632c267238..5b97598a3c22 100644 --- a/src/masternode-sync.h +++ b/src/masternode-sync.h @@ -9,17 +9,17 @@ class CMasternodeSync; -static const int MASTERNODE_SYNC_FAILED = -1; -static const int MASTERNODE_SYNC_INITIAL = 0; // sync just started, was reset recently or still in IDB -static const int MASTERNODE_SYNC_WAITING = 1; // waiting after initial to see if we can get more headers/blocks -static const int MASTERNODE_SYNC_LIST = 2; -static const int MASTERNODE_SYNC_MNW = 3; -static const int MASTERNODE_SYNC_GOVERNANCE = 4; -static const int MASTERNODE_SYNC_GOVOBJ = 10; -static const int MASTERNODE_SYNC_GOVOBJ_VOTE = 11; -static const int MASTERNODE_SYNC_FINISHED = 999; - -static const int MASTERNODE_SYNC_TICK_SECONDS = 6; +static const int MASTERNODE_SYNC_FAILED = -1; +static const int MASTERNODE_SYNC_INITIAL = 0; // sync just started, was reset recently or still in IDB +static const int MASTERNODE_SYNC_WAITING = 1; // waiting after initial to see if we can get more headers/blocks +static const int MASTERNODE_SYNC_LIST = 2; +static const int MASTERNODE_SYNC_MNW = 3; +static const int MASTERNODE_SYNC_GOVERNANCE = 4; +static const int MASTERNODE_SYNC_GOVOBJ = 10; +static const int MASTERNODE_SYNC_GOVOBJ_VOTE = 11; +static const int MASTERNODE_SYNC_FINISHED = 999; + +static const int MASTERNODE_SYNC_TICK_SECONDS = 6; static const int MASTERNODE_SYNC_TIMEOUT_SECONDS = 30; // our blocks are 2.5 minutes so 30 seconds should be fine extern CMasternodeSync masternodeSync; @@ -70,11 +70,11 @@ class CMasternodeSync void ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv); void ProcessTick(CConnman& connman); - void AcceptedBlockHeader(const CBlockIndex *pindexNew); - void NotifyHeaderTip(const CBlockIndex *pindexNew, bool fInitialDownload, CConnman& connman); - void UpdatedBlockTip(const CBlockIndex *pindexNew, bool fInitialDownload, CConnman& connman); + void AcceptedBlockHeader(const CBlockIndex* pindexNew); + void NotifyHeaderTip(const CBlockIndex* pindexNew, bool fInitialDownload, CConnman& connman); + void UpdatedBlockTip(const CBlockIndex* pindexNew, bool fInitialDownload, CConnman& connman); - void DoMaintenance(CConnman &connman) { ProcessTick(connman); } + void DoMaintenance(CConnman& connman) { ProcessTick(connman); } }; #endif diff --git a/src/masternode.cpp b/src/masternode.cpp index 6dad0e224d31..baa313bdf983 100644 --- a/src/masternode.cpp +++ b/src/masternode.cpp @@ -2,16 +2,16 @@ // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. +#include "masternode.h" #include "activemasternode.h" #include "base58.h" #include "clientversion.h" #include "init.h" -#include "netbase.h" -#include "masternode.h" #include "masternode-payments.h" #include "masternode-sync.h" #include "masternodeman.h" #include "messagesigner.h" +#include "netbase.h" #include "script/standard.h" #include "util.h" #ifdef ENABLE_WALLET @@ -24,15 +24,17 @@ CMasternode::CMasternode() : - masternode_info_t{ MASTERNODE_ENABLED, PROTOCOL_VERSION, GetAdjustedTime()}, + masternode_info_t{MASTERNODE_ENABLED, PROTOCOL_VERSION, GetAdjustedTime()}, fAllowMixingTx(true) -{} +{ +} CMasternode::CMasternode(CService addr, COutPoint outpoint, CPubKey pubKeyCollateralAddressNew, CPubKey pubKeyMasternodeNew, int nProtocolVersionIn) : - masternode_info_t{ MASTERNODE_ENABLED, nProtocolVersionIn, GetAdjustedTime(), - outpoint, addr, pubKeyCollateralAddressNew, pubKeyMasternodeNew}, + masternode_info_t{MASTERNODE_ENABLED, nProtocolVersionIn, GetAdjustedTime(), + outpoint, addr, pubKeyCollateralAddressNew, pubKeyMasternodeNew}, fAllowMixingTx(true) -{} +{ +} CMasternode::CMasternode(const CMasternode& other) : masternode_info_t{other}, @@ -44,19 +46,21 @@ CMasternode::CMasternode(const CMasternode& other) : nPoSeBanHeight(other.nPoSeBanHeight), fAllowMixingTx(other.fAllowMixingTx), fUnitTest(other.fUnitTest) -{} +{ +} CMasternode::CMasternode(const CMasternodeBroadcast& mnb) : - masternode_info_t{ mnb.nActiveState, mnb.nProtocolVersion, mnb.sigTime, - mnb.outpoint, mnb.addr, mnb.pubKeyCollateralAddress, mnb.pubKeyMasternode}, + masternode_info_t{mnb.nActiveState, mnb.nProtocolVersion, mnb.sigTime, + mnb.outpoint, mnb.addr, mnb.pubKeyCollateralAddress, mnb.pubKeyMasternode}, lastPing(mnb.lastPing), vchSig(mnb.vchSig), fAllowMixingTx(true) -{} +{ +} -CMasternode::CMasternode(const uint256 &proTxHash, const CDeterministicMNCPtr& dmn) : - masternode_info_t{ MASTERNODE_ENABLED, dmn->pdmnState->nProtocolVersion, GetAdjustedTime(), - COutPoint(proTxHash, dmn->nCollateralIndex), dmn->pdmnState->addr, CKeyID(), dmn->pdmnState->keyIDOwner, dmn->pdmnState->keyIDOperator, dmn->pdmnState->keyIDVoting}, +CMasternode::CMasternode(const uint256& proTxHash, const CDeterministicMNCPtr& dmn) : + masternode_info_t{MASTERNODE_ENABLED, dmn->pdmnState->nProtocolVersion, GetAdjustedTime(), + COutPoint(proTxHash, dmn->nCollateralIndex), dmn->pdmnState->addr, CKeyID(), dmn->pdmnState->keyIDOwner, dmn->pdmnState->keyIDOperator, dmn->pdmnState->keyIDVoting}, fAllowMixingTx(true) { CTxDestination dest; @@ -70,7 +74,7 @@ CMasternode::CMasternode(const uint256 &proTxHash, const CDeterministicMNCPtr& d // bool CMasternode::UpdateFromNewBroadcast(CMasternodeBroadcast& mnb, CConnman& connman) { - if(mnb.sigTime <= sigTime && !mnb.fRecovery) return false; + if (mnb.sigTime <= sigTime && !mnb.fRecovery) return false; pubKeyMasternode = mnb.pubKeyMasternode; keyIDOwner = mnb.pubKeyMasternode.GetID(); @@ -84,14 +88,14 @@ bool CMasternode::UpdateFromNewBroadcast(CMasternodeBroadcast& mnb, CConnman& co nPoSeBanHeight = 0; nTimeLastChecked = 0; int nDos = 0; - if(!mnb.lastPing || (mnb.lastPing && mnb.lastPing.CheckAndUpdate(this, true, nDos, connman))) { + if (!mnb.lastPing || (mnb.lastPing && mnb.lastPing.CheckAndUpdate(this, true, nDos, connman))) { lastPing = mnb.lastPing; mnodeman.mapSeenMasternodePing.insert(std::make_pair(lastPing.GetHash(), lastPing)); } // if it matches our Masternode privkey... - if(fMasternodeMode && keyIDOperator == activeMasternodeInfo.keyIDOperator) { + if (fMasternodeMode && keyIDOperator == activeMasternodeInfo.keyIDOperator) { nPoSeBanScore = -MASTERNODE_POSE_BAN_MAX_SCORE; - if(nProtocolVersion == PROTOCOL_VERSION) { + if (nProtocolVersion == PROTOCOL_VERSION) { // ... and PROTOCOL_VERSION, then we've been remotely activated ... legacyActiveMasternodeManager.ManageState(connman); } else { @@ -128,15 +132,15 @@ CMasternode::CollateralStatus CMasternode::CheckCollateral(const COutPoint& outp AssertLockHeld(cs_main); Coin coin; - if(!GetUTXOCoin(outpoint, coin)) { + if (!GetUTXOCoin(outpoint, coin)) { return COLLATERAL_UTXO_NOT_FOUND; } - if(coin.out.nValue != 1000 * COIN) { + if (coin.out.nValue != 1000 * COIN) { return COLLATERAL_INVALID_AMOUNT; } - if(keyID.IsNull() || coin.out.scriptPubKey != GetScriptForDestination(keyID)) { + if (keyID.IsNull() || coin.out.scriptPubKey != GetScriptForDestination(keyID)) { return COLLATERAL_INVALID_PUBKEY; } @@ -149,7 +153,7 @@ CMasternode::CollateralStatus CMasternode::CheckCollateral(const COutPoint& outp if (tx->nType != TRANSACTION_PROVIDER_REGISTER) { assert(mapBlockIndex.count(hashBlock)); - CBlockIndex *pindex = mapBlockIndex[hashBlock]; + CBlockIndex* pindex = mapBlockIndex[hashBlock]; if (VersionBitsState(pindex->pprev, Params().GetConsensus(), Consensus::DEPLOYMENT_DIP0003, versionbitscache) == THRESHOLD_ACTIVE) { LogPrintf("CMasternode::CheckCollateral -- ERROR: Collateral of masternode %s was created after DIP3 activation and is not a ProTx\n", outpoint.ToStringShort()); return COLLATERAL_UTXO_NOT_PROTX; @@ -165,20 +169,20 @@ void CMasternode::Check(bool fForce) AssertLockHeld(cs_main); LOCK(cs); - if(ShutdownRequested()) return; + if (ShutdownRequested()) return; - if(!fForce && (GetTime() - nTimeLastChecked < MASTERNODE_CHECK_SECONDS)) return; + if (!fForce && (GetTime() - nTimeLastChecked < MASTERNODE_CHECK_SECONDS)) return; nTimeLastChecked = GetTime(); LogPrint("masternode", "CMasternode::Check -- Masternode %s is in %s state\n", outpoint.ToStringShort(), GetStateString()); //once spent, stop doing the checks - if(IsOutpointSpent()) return; + if (IsOutpointSpent()) return; int nHeight = 0; - if(!fUnitTest) { + if (!fUnitTest) { Coin coin; - if(!GetUTXOCoin(outpoint, coin)) { + if (!GetUTXOCoin(outpoint, coin)) { nActiveState = MASTERNODE_OUTPOINT_SPENT; LogPrint("masternode", "CMasternode::Check -- Failed to find Masternode UTXO, masternode=%s\n", outpoint.ToStringShort()); return; @@ -187,14 +191,14 @@ void CMasternode::Check(bool fForce) nHeight = chainActive.Height(); } - if(IsPoSeBanned()) { - if(nHeight < nPoSeBanHeight) return; // too early? + if (IsPoSeBanned()) { + if (nHeight < nPoSeBanHeight) return; // too early? // Otherwise give it a chance to proceed further to do all the usual checks and to change its state. // Masternode still will be on the edge and can be banned back easily if it keeps ignoring mnverify // or connect attempts. Will require few mnverify messages to strengthen its position in mn list. LogPrintf("CMasternode::Check -- Masternode %s is unbanned and back in list now\n", outpoint.ToStringShort()); DecreasePoSeBanScore(); - } else if(nPoSeBanScore >= MASTERNODE_POSE_BAN_MAX_SCORE) { + } else if (nPoSeBanScore >= MASTERNODE_POSE_BAN_MAX_SCORE) { nActiveState = MASTERNODE_POSE_BAN; // ban for the whole payment cycle nPoSeBanHeight = nHeight + mnodeman.size(); @@ -205,14 +209,14 @@ void CMasternode::Check(bool fForce) int nActiveStatePrev = nActiveState; bool fOurMasternode = fMasternodeMode && activeMasternodeInfo.keyIDOperator == keyIDOperator; - // masternode doesn't meet payment protocol requirements ... + // masternode doesn't meet payment protocol requirements ... bool fRequireUpdate = nProtocolVersion < mnpayments.GetMinMasternodePaymentsProto() || - // or it's our own node and we just updated it to the new protocol but we are still waiting for activation ... - (fOurMasternode && nProtocolVersion < PROTOCOL_VERSION); + // or it's our own node and we just updated it to the new protocol but we are still waiting for activation ... + (fOurMasternode && nProtocolVersion < PROTOCOL_VERSION); - if(fRequireUpdate) { + if (fRequireUpdate) { nActiveState = MASTERNODE_UPDATE_REQUIRED; - if(nActiveStatePrev != nActiveState) { + if (nActiveStatePrev != nActiveState) { LogPrint("masternode", "CMasternode::Check -- Masternode %s is in %s state now\n", outpoint.ToStringShort(), GetStateString()); } return; @@ -221,28 +225,27 @@ void CMasternode::Check(bool fForce) // keep old masternodes on start, give them a chance to receive updates... bool fWaitForPing = !masternodeSync.IsMasternodeListSynced() && !IsPingedWithin(MASTERNODE_MIN_MNP_SECONDS); - if(fWaitForPing && !fOurMasternode) { + if (fWaitForPing && !fOurMasternode) { // ...but if it was already expired before the initial check - return right away - if(IsExpired() || IsSentinelPingExpired() || IsNewStartRequired()) { + if (IsExpired() || IsSentinelPingExpired() || IsNewStartRequired()) { LogPrint("masternode", "CMasternode::Check -- Masternode %s is in %s state, waiting for ping\n", outpoint.ToStringShort(), GetStateString()); return; } } // don't expire if we are still in "waiting for ping" mode unless it's our own masternode - if(!fWaitForPing || fOurMasternode) { - - if(!IsPingedWithin(MASTERNODE_NEW_START_REQUIRED_SECONDS)) { + if (!fWaitForPing || fOurMasternode) { + if (!IsPingedWithin(MASTERNODE_NEW_START_REQUIRED_SECONDS)) { nActiveState = MASTERNODE_NEW_START_REQUIRED; - if(nActiveStatePrev != nActiveState) { + if (nActiveStatePrev != nActiveState) { LogPrint("masternode", "CMasternode::Check -- Masternode %s is in %s state now\n", outpoint.ToStringShort(), GetStateString()); } return; } - if(!IsPingedWithin(MASTERNODE_EXPIRATION_SECONDS)) { + if (!IsPingedWithin(MASTERNODE_EXPIRATION_SECONDS)) { nActiveState = MASTERNODE_EXPIRED; - if(nActiveStatePrev != nActiveState) { + if (nActiveStatePrev != nActiveState) { LogPrint("masternode", "CMasternode::Check -- Masternode %s is in %s state now\n", outpoint.ToStringShort(), GetStateString()); } return; @@ -252,11 +255,11 @@ void CMasternode::Check(bool fForce) bool fSentinelPingActive = masternodeSync.IsSynced() && mnodeman.IsSentinelPingActive(); bool fSentinelPingExpired = fSentinelPingActive && !IsPingedWithin(MASTERNODE_SENTINEL_PING_MAX_SECONDS); LogPrint("masternode", "CMasternode::Check -- outpoint=%s, GetAdjustedTime()=%d, fSentinelPingExpired=%d\n", - outpoint.ToStringShort(), GetAdjustedTime(), fSentinelPingExpired); + outpoint.ToStringShort(), GetAdjustedTime(), fSentinelPingExpired); - if(fSentinelPingExpired) { + if (fSentinelPingExpired) { nActiveState = MASTERNODE_SENTINEL_PING_EXPIRED; - if(nActiveStatePrev != nActiveState) { + if (nActiveStatePrev != nActiveState) { LogPrint("masternode", "CMasternode::Check -- Masternode %s is in %s state now\n", outpoint.ToStringShort(), GetStateString()); } return; @@ -275,17 +278,17 @@ void CMasternode::Check(bool fForce) } } - if(!fWaitForPing || fOurMasternode) { + if (!fWaitForPing || fOurMasternode) { // part 2: expire based on sentinel info bool fSentinelPingActive = masternodeSync.IsSynced() && mnodeman.IsSentinelPingActive(); bool fSentinelPingExpired = fSentinelPingActive && !lastPing.fSentinelIsCurrent; LogPrint("masternode", "CMasternode::Check -- outpoint=%s, GetAdjustedTime()=%d, fSentinelPingExpired=%d\n", - outpoint.ToStringShort(), GetAdjustedTime(), fSentinelPingExpired); + outpoint.ToStringShort(), GetAdjustedTime(), fSentinelPingExpired); - if(fSentinelPingExpired) { + if (fSentinelPingExpired) { nActiveState = MASTERNODE_SENTINEL_PING_EXPIRED; - if(nActiveStatePrev != nActiveState) { + if (nActiveStatePrev != nActiveState) { LogPrint("masternode", "CMasternode::Check -- Masternode %s is in %s state now\n", outpoint.ToStringShort(), GetStateString()); } return; @@ -293,7 +296,7 @@ void CMasternode::Check(bool fForce) } nActiveState = MASTERNODE_ENABLED; // OK - if(nActiveStatePrev != nActiveState) { + if (nActiveStatePrev != nActiveState) { LogPrint("masternode", "CMasternode::Check -- Masternode %s is in %s state now\n", outpoint.ToStringShort(), GetStateString()); } } @@ -308,7 +311,7 @@ bool CMasternode::IsValidNetAddr(CService addrIn) // TODO: regtest is fine with any addresses for now, // should probably be a bit smarter if one day we start to implement tests for this return Params().NetworkIDString() == CBaseChainParams::REGTEST || - (addrIn.IsIPv4() && IsReachable(addrIn) && addrIn.IsRoutable()); + (addrIn.IsIPv4() && IsReachable(addrIn) && addrIn.IsRoutable()); } masternode_info_t CMasternode::GetInfo() const @@ -321,16 +324,25 @@ masternode_info_t CMasternode::GetInfo() const std::string CMasternode::StateToString(int nStateIn) { - switch(nStateIn) { - case MASTERNODE_PRE_ENABLED: return "PRE_ENABLED"; - case MASTERNODE_ENABLED: return "ENABLED"; - case MASTERNODE_EXPIRED: return "EXPIRED"; - case MASTERNODE_OUTPOINT_SPENT: return "OUTPOINT_SPENT"; - case MASTERNODE_UPDATE_REQUIRED: return "UPDATE_REQUIRED"; - case MASTERNODE_SENTINEL_PING_EXPIRED: return "SENTINEL_PING_EXPIRED"; - case MASTERNODE_NEW_START_REQUIRED: return "NEW_START_REQUIRED"; - case MASTERNODE_POSE_BAN: return "POSE_BAN"; - default: return "UNKNOWN"; + switch (nStateIn) { + case MASTERNODE_PRE_ENABLED: + return "PRE_ENABLED"; + case MASTERNODE_ENABLED: + return "ENABLED"; + case MASTERNODE_EXPIRED: + return "EXPIRED"; + case MASTERNODE_OUTPOINT_SPENT: + return "OUTPOINT_SPENT"; + case MASTERNODE_UPDATE_REQUIRED: + return "UPDATE_REQUIRED"; + case MASTERNODE_SENTINEL_PING_EXPIRED: + return "SENTINEL_PING_EXPIRED"; + case MASTERNODE_NEW_START_REQUIRED: + return "NEW_START_REQUIRED"; + case MASTERNODE_POSE_BAN: + return "POSE_BAN"; + default: + return "UNKNOWN"; } } @@ -345,11 +357,11 @@ std::string CMasternode::GetStatus() const return GetStateString(); } -void CMasternode::UpdateLastPaid(const CBlockIndex *pindex, int nMaxBlocksToScanBack) +void CMasternode::UpdateLastPaid(const CBlockIndex* pindex, int nMaxBlocksToScanBack) { AssertLockHeld(cs_main); - if(!pindex) return; + if (!pindex) return; if (deterministicMNManager->IsDeterministicMNsSporkActive(pindex->nHeight)) { auto dmn = deterministicMNManager->GetListForBlock(pindex->GetBlockHash()).GetMN(outpoint.hash); @@ -363,7 +375,7 @@ void CMasternode::UpdateLastPaid(const CBlockIndex *pindex, int nMaxBlocksToScan return; } - const CBlockIndex *BlockReading = pindex; + const CBlockIndex* BlockReading = pindex; CScript mnpayee = GetScriptForDestination(keyIDCollateralAddress); // LogPrint("mnpayments", "CMasternode::UpdateLastPaidBlock -- searching for block with payment to %s\n", outpoint.ToStringShort()); @@ -371,17 +383,16 @@ void CMasternode::UpdateLastPaid(const CBlockIndex *pindex, int nMaxBlocksToScan LOCK(cs_mapMasternodeBlocks); for (int i = 0; BlockReading && BlockReading->nHeight > nBlockLastPaid && i < nMaxBlocksToScanBack; i++) { - if(mnpayments.mapMasternodeBlocks.count(BlockReading->nHeight) && - mnpayments.mapMasternodeBlocks[BlockReading->nHeight].HasPayeeWithVotes(mnpayee, 2)) - { + if (mnpayments.mapMasternodeBlocks.count(BlockReading->nHeight) && + mnpayments.mapMasternodeBlocks[BlockReading->nHeight].HasPayeeWithVotes(mnpayee, 2)) { CBlock block; - if(!ReadBlockFromDisk(block, BlockReading, Params().GetConsensus())) + if (!ReadBlockFromDisk(block, BlockReading, Params().GetConsensus())) continue; // shouldn't really happen CAmount nMasternodePayment = GetMasternodePayment(BlockReading->nHeight, block.vtx[0]->GetValueOut()); for (const auto& txout : block.vtx[0]->vout) - if(mnpayee == txout.scriptPubKey && nMasternodePayment == txout.nValue) { + if (mnpayee == txout.scriptPubKey && nMasternodePayment == txout.nValue) { nBlockLastPaid = BlockReading->nHeight; nTimeLastPaid = BlockReading->nTime; LogPrint("mnpayments", "CMasternode::UpdateLastPaidBlock -- searching for block with payment to %s -- found new %d\n", outpoint.ToStringShort(), nBlockLastPaid); @@ -389,7 +400,10 @@ void CMasternode::UpdateLastPaid(const CBlockIndex *pindex, int nMaxBlocksToScan } } - if (BlockReading->pprev == nullptr) { assert(BlockReading); break; } + if (BlockReading->pprev == nullptr) { + assert(BlockReading); + break; + } BlockReading = BlockReading->pprev; } @@ -399,7 +413,7 @@ void CMasternode::UpdateLastPaid(const CBlockIndex *pindex, int nMaxBlocksToScan } #ifdef ENABLE_WALLET -bool CMasternodeBroadcast::Create(const std::string& strService, const std::string& strKeyMasternode, const std::string& strTxHash, const std::string& strOutputIndex, std::string& strErrorRet, CMasternodeBroadcast &mnbRet, bool fOffline) +bool CMasternodeBroadcast::Create(const std::string& strService, const std::string& strKeyMasternode, const std::string& strTxHash, const std::string& strOutputIndex, std::string& strErrorRet, CMasternodeBroadcast& mnbRet, bool fOffline) { COutPoint outpoint; CPubKey pubKeyCollateralAddressNew; @@ -407,8 +421,7 @@ bool CMasternodeBroadcast::Create(const std::string& strService, const std::stri CPubKey pubKeyMasternodeNew; CKey keyMasternodeNew; - auto Log = [&strErrorRet](std::string sErr)->bool - { + auto Log = [&strErrorRet](std::string sErr) -> bool { strErrorRet = sErr; LogPrintf("CMasternodeBroadcast::Create -- %s\n", strErrorRet); return false; @@ -437,17 +450,16 @@ bool CMasternodeBroadcast::Create(const std::string& strService, const std::stri return Create(outpoint, service, keyCollateralAddressNew, pubKeyCollateralAddressNew, keyMasternodeNew, pubKeyMasternodeNew, strErrorRet, mnbRet); } -bool CMasternodeBroadcast::Create(const COutPoint& outpoint, const CService& service, const CKey& keyCollateralAddressNew, const CPubKey& pubKeyCollateralAddressNew, const CKey& keyMasternodeNew, const CPubKey& pubKeyMasternodeNew, std::string &strErrorRet, CMasternodeBroadcast &mnbRet) +bool CMasternodeBroadcast::Create(const COutPoint& outpoint, const CService& service, const CKey& keyCollateralAddressNew, const CPubKey& pubKeyCollateralAddressNew, const CKey& keyMasternodeNew, const CPubKey& pubKeyMasternodeNew, std::string& strErrorRet, CMasternodeBroadcast& mnbRet) { // wait for reindex and/or import to finish if (fImporting || fReindex) return false; LogPrint("masternode", "CMasternodeBroadcast::Create -- pubKeyCollateralAddressNew = %s, keyIDOperator = %s\n", - CBitcoinAddress(pubKeyCollateralAddressNew.GetID()).ToString(), - pubKeyMasternodeNew.GetID().ToString()); + CBitcoinAddress(pubKeyCollateralAddressNew.GetID()).ToString(), + pubKeyMasternodeNew.GetID().ToString()); - auto Log = [&strErrorRet,&mnbRet](std::string sErr)->bool - { + auto Log = [&strErrorRet, &mnbRet](std::string sErr) -> bool { strErrorRet = sErr; LogPrintf("CMasternodeBroadcast::Create -- %s\n", strErrorRet); mnbRet = CMasternodeBroadcast(); @@ -478,9 +490,9 @@ bool CMasternodeBroadcast::SimpleCheck(int& nDos) AssertLockHeld(cs_main); // make sure addr is valid - if(!IsValidNetAddr()) { + if (!IsValidNetAddr()) { LogPrintf("CMasternodeBroadcast::SimpleCheck -- Invalid addr, rejected: masternode=%s addr=%s\n", - outpoint.ToStringShort(), addr.ToString()); + outpoint.ToStringShort(), addr.ToString()); return false; } @@ -492,12 +504,12 @@ bool CMasternodeBroadcast::SimpleCheck(int& nDos) } // empty ping or incorrect sigTime/unknown blockhash - if(!lastPing || !lastPing.SimpleCheck(nDos)) { + if (!lastPing || !lastPing.SimpleCheck(nDos)) { // one of us is probably forked or smth, just mark it as expired and check the rest of the rules nActiveState = MASTERNODE_EXPIRED; } - if(nProtocolVersion < mnpayments.GetMinMasternodePaymentsProto()) { + if (nProtocolVersion < mnpayments.GetMinMasternodePaymentsProto()) { LogPrintf("CMasternodeBroadcast::SimpleCheck -- outdated Masternode: masternode=%s nProtocolVersion=%d\n", outpoint.ToStringShort(), nProtocolVersion); nActiveState = MASTERNODE_UPDATE_REQUIRED; } @@ -505,7 +517,7 @@ bool CMasternodeBroadcast::SimpleCheck(int& nDos) CScript pubkeyScript; pubkeyScript = GetScriptForDestination(keyIDCollateralAddress); - if(pubkeyScript.size() != 25) { + if (pubkeyScript.size() != 25) { LogPrintf("CMasternodeBroadcast::SimpleCheck -- keyIDCollateralAddress has the wrong size\n"); nDos = 100; return false; @@ -514,16 +526,17 @@ bool CMasternodeBroadcast::SimpleCheck(int& nDos) CScript pubkeyScript2; pubkeyScript2 = GetScriptForDestination(keyIDOperator); - if(pubkeyScript2.size() != 25) { + if (pubkeyScript2.size() != 25) { LogPrintf("CMasternodeBroadcast::SimpleCheck -- keyIDOperator has the wrong size\n"); nDos = 100; return false; } int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort(); - if(Params().NetworkIDString() == CBaseChainParams::MAIN) { - if(addr.GetPort() != mainnetDefaultPort) return false; - } else if(addr.GetPort() == mainnetDefaultPort) return false; + if (Params().NetworkIDString() == CBaseChainParams::MAIN) { + if (addr.GetPort() != mainnetDefaultPort) return false; + } else if (addr.GetPort() == mainnetDefaultPort) + return false; return true; } @@ -534,7 +547,7 @@ bool CMasternodeBroadcast::Update(CMasternode* pmn, int& nDos, CConnman& connman AssertLockHeld(cs_main); - if(pmn->sigTime == sigTime && !fRecovery) { + if (pmn->sigTime == sigTime && !fRecovery) { // mapSeenMasternodeBroadcast in CMasternodeMan::CheckMnbAndUpdateMasternodeList should filter legit duplicates // but this still can happen if we just started, which is ok, just do nothing here. return false; @@ -542,22 +555,22 @@ bool CMasternodeBroadcast::Update(CMasternode* pmn, int& nDos, CConnman& connman // this broadcast is older than the one that we already have - it's bad and should never happen // unless someone is doing something fishy - if(pmn->sigTime > sigTime) { + if (pmn->sigTime > sigTime) { LogPrintf("CMasternodeBroadcast::Update -- Bad sigTime %d (existing broadcast is at %d) for Masternode %s %s\n", - sigTime, pmn->sigTime, outpoint.ToStringShort(), addr.ToString()); + sigTime, pmn->sigTime, outpoint.ToStringShort(), addr.ToString()); return false; } pmn->Check(); // masternode is banned by PoSe - if(pmn->IsPoSeBanned()) { + if (pmn->IsPoSeBanned()) { LogPrintf("CMasternodeBroadcast::Update -- Banned by PoSe, masternode=%s\n", outpoint.ToStringShort()); return false; } // IsVnAssociatedWithPubkey is validated once in CheckOutpoint, after that they just need to match - if(pmn->keyIDCollateralAddress != keyIDCollateralAddress) { + if (pmn->keyIDCollateralAddress != keyIDCollateralAddress) { LogPrintf("CMasternodeBroadcast::Update -- Got mismatched keyIDCollateralAddress and outpoint\n"); nDos = 33; return false; @@ -569,10 +582,10 @@ bool CMasternodeBroadcast::Update(CMasternode* pmn, int& nDos, CConnman& connman } // if ther was no masternode broadcast recently or if it matches our Masternode privkey... - if(!pmn->IsBroadcastedWithin(MASTERNODE_MIN_MNB_SECONDS) || (fMasternodeMode && keyIDOperator == activeMasternodeInfo.keyIDOperator)) { + if (!pmn->IsBroadcastedWithin(MASTERNODE_MIN_MNB_SECONDS) || (fMasternodeMode && keyIDOperator == activeMasternodeInfo.keyIDOperator)) { // take the newest entry LogPrintf("CMasternodeBroadcast::Update -- Got UPDATED Masternode entry: addr=%s\n", addr.ToString()); - if(pmn->UpdateFromNewBroadcast(*this, connman)) { + if (pmn->UpdateFromNewBroadcast(*this, connman)) { pmn->Check(); Relay(connman); } @@ -586,7 +599,7 @@ bool CMasternodeBroadcast::CheckOutpoint(int& nDos) { // we are a masternode with the same outpoint (i.e. already activated) and this mnb is ours (matches our Masternode privkey) // so nothing to do here for us - if(fMasternodeMode && outpoint == activeMasternodeInfo.outpoint && keyIDOperator == activeMasternodeInfo.keyIDOperator) { + if (fMasternodeMode && outpoint == activeMasternodeInfo.outpoint && keyIDOperator == activeMasternodeInfo.keyIDOperator) { return false; } @@ -610,15 +623,15 @@ bool CMasternodeBroadcast::CheckOutpoint(int& nDos) return false; } - if(err == COLLATERAL_INVALID_PUBKEY) { + if (err == COLLATERAL_INVALID_PUBKEY) { LogPrint("masternode", "CMasternodeBroadcast::CheckOutpoint -- Masternode UTXO should match keyIDCollateralAddress, masternode=%s\n", outpoint.ToStringShort()); nDos = 33; return false; } - if(chainActive.Height() - nHeight + 1 < Params().GetConsensus().nMasternodeMinimumConfirmations) { + if (chainActive.Height() - nHeight + 1 < Params().GetConsensus().nMasternodeMinimumConfirmations) { LogPrintf("CMasternodeBroadcast::CheckOutpoint -- Masternode UTXO must have at least %d confirmations, masternode=%s\n", - Params().GetConsensus().nMasternodeMinimumConfirmations, outpoint.ToStringShort()); + Params().GetConsensus().nMasternodeMinimumConfirmations, outpoint.ToStringShort()); // UTXO is legit but has not enough confirmations. // Maybe we miss few blocks, let this mnb be checked again later. mnodeman.mapSeenMasternodeBroadcast.erase(GetHash()); @@ -631,9 +644,9 @@ bool CMasternodeBroadcast::CheckOutpoint(int& nDos) // at which collateral became nMasternodeMinimumConfirmations blocks deep. // NOTE: this is not accurate because block timestamp is NOT guaranteed to be 100% correct one. CBlockIndex* pRequiredConfIndex = chainActive[nHeight + Params().GetConsensus().nMasternodeMinimumConfirmations - 1]; // block where tx got nMasternodeMinimumConfirmations - if(pRequiredConfIndex->GetBlockTime() > sigTime) { + if (pRequiredConfIndex->GetBlockTime() > sigTime) { LogPrintf("CMasternodeBroadcast::CheckOutpoint -- Bad sigTime %d (%d conf block is at %d) for Masternode %s %s\n", - sigTime, Params().GetConsensus().nMasternodeMinimumConfirmations, pRequiredConfIndex->GetBlockTime(), outpoint.ToStringShort(), addr.ToString()); + sigTime, Params().GetConsensus().nMasternodeMinimumConfirmations, pRequiredConfIndex->GetBlockTime(), outpoint.ToStringShort(), addr.ToString()); return false; } @@ -692,15 +705,15 @@ bool CMasternodeBroadcast::Sign(const CKey& keyCollateralAddress) } } else { std::string strMessage = addr.ToString(false) + std::to_string(sigTime) + - keyIDCollateralAddress.ToString() + keyIDOperator.ToString() + - std::to_string(nProtocolVersion); + keyIDCollateralAddress.ToString() + keyIDOperator.ToString() + + std::to_string(nProtocolVersion); if (!CMessageSigner::SignMessage(strMessage, vchSig, keyCollateralAddress)) { LogPrintf("CMasternodeBroadcast::Sign -- SignMessage() failed\n"); return false; } - if(!CMessageSigner::VerifyMessage(keyIDCollateralAddress, vchSig, strMessage, strError)) { + if (!CMessageSigner::VerifyMessage(keyIDCollateralAddress, vchSig, strMessage, strError)) { LogPrintf("CMasternodeBroadcast::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } @@ -720,10 +733,10 @@ bool CMasternodeBroadcast::CheckSignature(int& nDos) const if (!CHashSigner::VerifyHash(hash, keyIDCollateralAddress, vchSig, strError)) { // maybe it's in old format std::string strMessage = addr.ToString(false) + std::to_string(sigTime) + - keyIDCollateralAddress.ToString() + keyIDOperator.ToString() + - std::to_string(nProtocolVersion); + keyIDCollateralAddress.ToString() + keyIDOperator.ToString() + + std::to_string(nProtocolVersion); - if (!CMessageSigner::VerifyMessage(keyIDCollateralAddress, vchSig, strMessage, strError)){ + if (!CMessageSigner::VerifyMessage(keyIDCollateralAddress, vchSig, strMessage, strError)) { // nope, not in old format either LogPrintf("CMasternodeBroadcast::CheckSignature -- Got bad Masternode announce signature, error: %s\n", strError); nDos = 100; @@ -732,10 +745,10 @@ bool CMasternodeBroadcast::CheckSignature(int& nDos) const } } else { std::string strMessage = addr.ToString(false) + std::to_string(sigTime) + - keyIDCollateralAddress.ToString() + keyIDOperator.ToString() + - std::to_string(nProtocolVersion); + keyIDCollateralAddress.ToString() + keyIDOperator.ToString() + + std::to_string(nProtocolVersion); - if(!CMessageSigner::VerifyMessage(keyIDCollateralAddress, vchSig, strMessage, strError)){ + if (!CMessageSigner::VerifyMessage(keyIDCollateralAddress, vchSig, strMessage, strError)) { LogPrintf("CMasternodeBroadcast::CheckSignature -- Got bad Masternode announce signature, error: %s\n", strError); nDos = 100; return false; @@ -748,7 +761,7 @@ bool CMasternodeBroadcast::CheckSignature(int& nDos) const void CMasternodeBroadcast::Relay(CConnman& connman) const { // Do not relay until fully synced - if(!masternodeSync.IsSynced()) { + if (!masternodeSync.IsSynced()) { LogPrint("masternode", "CMasternodeBroadcast::Relay -- won't relay until fully synced\n"); return; } @@ -813,14 +826,14 @@ bool CMasternodePing::Sign(const CKey& keyMasternode, const CKeyID& keyIDOperato } } else { std::string strMessage = CTxIn(masternodeOutpoint).ToString() + blockHash.ToString() + - std::to_string(sigTime); + std::to_string(sigTime); if (!CMessageSigner::SignMessage(strMessage, vchSig, keyMasternode)) { LogPrintf("CMasternodePing::Sign -- SignMessage() failed\n"); return false; } - if(!CMessageSigner::VerifyMessage(keyIDOperator, vchSig, strMessage, strError)) { + if (!CMessageSigner::VerifyMessage(keyIDOperator, vchSig, strMessage, strError)) { LogPrintf("CMasternodePing::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } @@ -829,7 +842,7 @@ bool CMasternodePing::Sign(const CKey& keyMasternode, const CKeyID& keyIDOperato return true; } -bool CMasternodePing::CheckSignature(CKeyID& keyIDOperator, int &nDos) const +bool CMasternodePing::CheckSignature(CKeyID& keyIDOperator, int& nDos) const { std::string strError = ""; nDos = 0; @@ -839,9 +852,9 @@ bool CMasternodePing::CheckSignature(CKeyID& keyIDOperator, int &nDos) const if (!CHashSigner::VerifyHash(hash, keyIDOperator, vchSig, strError)) { std::string strMessage = CTxIn(masternodeOutpoint).ToString() + blockHash.ToString() + - std::to_string(sigTime); + std::to_string(sigTime); - if(!CMessageSigner::VerifyMessage(keyIDOperator, vchSig, strMessage, strError)) { + if (!CMessageSigner::VerifyMessage(keyIDOperator, vchSig, strMessage, strError)) { LogPrintf("CMasternodePing::CheckSignature -- Got bad Masternode ping signature, masternode=%s, error: %s\n", masternodeOutpoint.ToStringShort(), strError); nDos = 33; return false; @@ -849,7 +862,7 @@ bool CMasternodePing::CheckSignature(CKeyID& keyIDOperator, int &nDos) const } } else { std::string strMessage = CTxIn(masternodeOutpoint).ToString() + blockHash.ToString() + - std::to_string(sigTime); + std::to_string(sigTime); if (!CMessageSigner::VerifyMessage(keyIDOperator, vchSig, strMessage, strError)) { LogPrintf("CMasternodePing::CheckSignature -- Got bad Masternode ping signature, masternode=%s, error: %s\n", masternodeOutpoint.ToStringShort(), strError); @@ -903,7 +916,7 @@ bool CMasternodePing::CheckAndUpdate(CMasternode* pmn, bool fFromNewBroadcast, i return false; } - if(!fFromNewBroadcast) { + if (!fFromNewBroadcast) { if (pmn->IsUpdateRequired()) { LogPrint("masternode", "CMasternodePing::CheckAndUpdate -- masternode protocol is outdated, masternode=%s\n", masternodeOutpoint.ToStringShort()); return false; @@ -941,7 +954,7 @@ bool CMasternodePing::CheckAndUpdate(CMasternode* pmn, bool fFromNewBroadcast, i // if we are still syncing and there was no known ping for this mn for quite a while // (NOTE: assuming that MASTERNODE_EXPIRATION_SECONDS/2 should be enough to finish mn list sync) - if(!masternodeSync.IsMasternodeListSynced() && !pmn->IsPingedWithin(MASTERNODE_EXPIRATION_SECONDS/2)) { + if (!masternodeSync.IsMasternodeListSynced() && !pmn->IsPingedWithin(MASTERNODE_EXPIRATION_SECONDS / 2)) { // let's bump sync timeout LogPrint("masternode", "CMasternodePing::CheckAndUpdate -- bumping sync timeout, masternode=%s\n", masternodeOutpoint.ToStringShort()); masternodeSync.BumpAssetLastTime("CMasternodePing::CheckAndUpdate"); @@ -972,7 +985,7 @@ bool CMasternodePing::CheckAndUpdate(CMasternode* pmn, bool fFromNewBroadcast, i void CMasternodePing::Relay(CConnman& connman) { // Do not relay until fully synced - if(!masternodeSync.IsSynced()) { + if (!masternodeSync.IsSynced()) { LogPrint("masternode", "CMasternodePing::Relay -- won't relay until fully synced\n"); return; } diff --git a/src/masternode.h b/src/masternode.h index 6b9be5df6c1e..df5b3490e513 100644 --- a/src/masternode.h +++ b/src/masternode.h @@ -6,8 +6,8 @@ #define MASTERNODE_H #include "key.h" -#include "validation.h" #include "spork.h" +#include "validation.h" #include "evo/deterministicmns.h" @@ -15,14 +15,14 @@ class CMasternode; class CMasternodeBroadcast; class CConnman; -static const int MASTERNODE_CHECK_SECONDS = 5; -static const int MASTERNODE_MIN_MNB_SECONDS = 5 * 60; -static const int MASTERNODE_MIN_MNP_SECONDS = 10 * 60; -static const int MASTERNODE_SENTINEL_PING_MAX_SECONDS = 60 * 60; -static const int MASTERNODE_EXPIRATION_SECONDS = 120 * 60; -static const int MASTERNODE_NEW_START_REQUIRED_SECONDS = 180 * 60; +static const int MASTERNODE_CHECK_SECONDS = 5; +static const int MASTERNODE_MIN_MNB_SECONDS = 5 * 60; +static const int MASTERNODE_MIN_MNP_SECONDS = 10 * 60; +static const int MASTERNODE_SENTINEL_PING_MAX_SECONDS = 60 * 60; +static const int MASTERNODE_EXPIRATION_SECONDS = 120 * 60; +static const int MASTERNODE_NEW_START_REQUIRED_SECONDS = 180 * 60; -static const int MASTERNODE_POSE_BAN_MAX_SCORE = 5; +static const int MASTERNODE_POSE_BAN_MAX_SCORE = 5; // // The Masternode Ping Class : Contains a different serialize method for sending pings from masternodes throughout the network @@ -52,7 +52,8 @@ class CMasternodePing ADD_SERIALIZE_METHODS; template - inline void SerializationOp(Stream& s, Operation ser_action) { + inline void SerializationOp(Stream& s, Operation ser_action) + { READWRITE(masternodeOutpoint); READWRITE(blockHash); READWRITE(sigTime); @@ -70,7 +71,7 @@ class CMasternodePing bool IsExpired() const { return GetAdjustedTime() - sigTime > MASTERNODE_NEW_START_REQUIRED_SECONDS; } bool Sign(const CKey& keyMasternode, const CKeyID& keyIDOperator); - bool CheckSignature(CKeyID& keyIDOperator, int &nDos) const; + bool CheckSignature(CKeyID& keyIDOperator, int& nDos) const; bool SimpleCheck(int& nDos); bool CheckAndUpdate(CMasternode* pmn, bool fFromNewBroadcast, int& nDos, CConnman& connman); void Relay(CConnman& connman); @@ -94,8 +95,7 @@ inline CMasternodePing::operator bool() const return *this != CMasternodePing(); } -struct masternode_info_t -{ +struct masternode_info_t { // Note: all these constructors can be removed once C++14 is enabled. // (in C++11 the member initializers wrongly disqualify this as an aggregate) masternode_info_t() = default; @@ -105,17 +105,13 @@ struct masternode_info_t nActiveState{activeState}, nProtocolVersion{protoVer}, sigTime{sTime} {} // only called when the network is in legacy MN list mode - masternode_info_t(int activeState, int protoVer, int64_t sTime, - COutPoint const& outpnt, CService const& addr, - CPubKey const& pkCollAddr, CPubKey const& pkMN) : + masternode_info_t(int activeState, int protoVer, int64_t sTime, COutPoint const& outpnt, CService const& addr, CPubKey const& pkCollAddr, CPubKey const& pkMN) : nActiveState{activeState}, nProtocolVersion{protoVer}, sigTime{sTime}, outpoint{outpnt}, addr{addr}, pubKeyCollateralAddress{pkCollAddr}, pubKeyMasternode{pkMN}, keyIDCollateralAddress{pkCollAddr.GetID()}, keyIDOwner{pkMN.GetID()}, keyIDOperator{pkMN.GetID()}, keyIDVoting{pkMN.GetID()} {} // only called when the network is in deterministic MN list mode - masternode_info_t(int activeState, int protoVer, int64_t sTime, - COutPoint const& outpnt, CService const& addr, - CKeyID const& pkCollAddr, CKeyID const& pkOwner, CKeyID const& pkOperator, CKeyID const& pkVoting) : + masternode_info_t(int activeState, int protoVer, int64_t sTime, COutPoint const& outpnt, CService const& addr, CKeyID const& pkCollAddr, CKeyID const& pkOwner, CKeyID const& pkOperator, CKeyID const& pkVoting) : nActiveState{activeState}, nProtocolVersion{protoVer}, sigTime{sTime}, outpoint{outpnt}, addr{addr}, pubKeyCollateralAddress{}, pubKeyMasternode{}, keyIDCollateralAddress{pkCollAddr}, keyIDOwner{pkOwner}, keyIDOperator{pkOperator}, keyIDVoting{pkVoting} {} @@ -127,7 +123,7 @@ struct masternode_info_t COutPoint outpoint{}; CService addr{}; CPubKey pubKeyCollateralAddress{}; // this will be invalid/unset when the network switches to deterministic MNs (luckely it's only important for the broadcast hash) - CPubKey pubKeyMasternode{}; // this will be invalid/unset when the network switches to deterministic MNs (luckely it's only important for the broadcast hash) + CPubKey pubKeyMasternode{}; // this will be invalid/unset when the network switches to deterministic MNs (luckely it's only important for the broadcast hash) CKeyID keyIDCollateralAddress{}; CKeyID keyIDOwner{}; CKeyID keyIDOperator{}; @@ -137,7 +133,7 @@ struct masternode_info_t int64_t nTimeLastChecked = 0; int64_t nTimeLastPaid = 0; int64_t nTimeLastPing = 0; //* not in CMN - bool fInfoValid = false; //* not in CMN + bool fInfoValid = false; //* not in CMN }; // @@ -188,12 +184,13 @@ class CMasternode : public masternode_info_t CMasternode(const CMasternode& other); CMasternode(const CMasternodeBroadcast& mnb); CMasternode(CService addrNew, COutPoint outpointNew, CPubKey pubKeyCollateralAddressNew, CPubKey pubKeyMasternodeNew, int nProtocolVersionIn); - CMasternode(const uint256 &proTxHash, const CDeterministicMNCPtr& dmn); + CMasternode(const uint256& proTxHash, const CDeterministicMNCPtr& dmn); ADD_SERIALIZE_METHODS; template - inline void SerializationOp(Stream& s, Operation ser_action) { + inline void SerializationOp(Stream& s, Operation ser_action) + { LOCK(cs); READWRITE(outpoint); READWRITE(addr); @@ -233,9 +230,9 @@ class CMasternode : public masternode_info_t bool IsPingedWithin(int nSeconds, int64_t nTimeToCheckAt = -1) { - if(!lastPing) return false; + if (!lastPing) return false; - if(nTimeToCheckAt == -1) { + if (nTimeToCheckAt == -1) { nTimeToCheckAt = GetAdjustedTime(); } return nTimeToCheckAt - lastPing.sigTime < nSeconds; @@ -254,19 +251,19 @@ class CMasternode : public masternode_info_t static bool IsValidStateForAutoStart(int nActiveStateIn) { - return nActiveStateIn == MASTERNODE_ENABLED || - nActiveStateIn == MASTERNODE_PRE_ENABLED || - nActiveStateIn == MASTERNODE_EXPIRED || - nActiveStateIn == MASTERNODE_SENTINEL_PING_EXPIRED; + return nActiveStateIn == MASTERNODE_ENABLED || + nActiveStateIn == MASTERNODE_PRE_ENABLED || + nActiveStateIn == MASTERNODE_EXPIRED || + nActiveStateIn == MASTERNODE_SENTINEL_PING_EXPIRED; } bool IsValidForPayment() const { - if(nActiveState == MASTERNODE_ENABLED) { + if (nActiveState == MASTERNODE_ENABLED) { return true; } - if(!sporkManager.IsSporkActive(SPORK_14_REQUIRE_SENTINEL_FLAG) && - (nActiveState == MASTERNODE_SENTINEL_PING_EXPIRED)) { + if (!sporkManager.IsSporkActive(SPORK_14_REQUIRE_SENTINEL_FLAG) && + (nActiveState == MASTERNODE_SENTINEL_PING_EXPIRED)) { return true; } @@ -276,8 +273,14 @@ class CMasternode : public masternode_info_t bool IsValidNetAddr(); static bool IsValidNetAddr(CService addrIn); - void IncreasePoSeBanScore() { if(nPoSeBanScore < MASTERNODE_POSE_BAN_MAX_SCORE) nPoSeBanScore++; } - void DecreasePoSeBanScore() { if(nPoSeBanScore > -MASTERNODE_POSE_BAN_MAX_SCORE) nPoSeBanScore--; } + void IncreasePoSeBanScore() + { + if (nPoSeBanScore < MASTERNODE_POSE_BAN_MAX_SCORE) nPoSeBanScore++; + } + void DecreasePoSeBanScore() + { + if (nPoSeBanScore > -MASTERNODE_POSE_BAN_MAX_SCORE) nPoSeBanScore--; + } void PoSeBan() { nPoSeBanScore = MASTERNODE_POSE_BAN_MAX_SCORE; } masternode_info_t GetInfo() const; @@ -288,7 +291,7 @@ class CMasternode : public masternode_info_t int GetLastPaidTime() const { return nTimeLastPaid; } int GetLastPaidBlock() const { return nBlockLastPaid; } - void UpdateLastPaid(const CBlockIndex *pindex, int nMaxBlocksToScanBack); + void UpdateLastPaid(const CBlockIndex* pindex, int nMaxBlocksToScanBack); // KEEP TRACK OF EACH GOVERNANCE ITEM INCASE THIS NODE GOES OFFLINE, SO WE CAN RECALC THEIR STATUS void AddGovernanceVote(uint256 nGovernanceObjectHash); @@ -299,7 +302,7 @@ class CMasternode : public masternode_info_t CMasternode& operator=(CMasternode const& from) { - static_cast(*this)=from; + static_cast(*this) = from; lastPing = from.lastPing; vchSig = from.vchSig; nCollateralMinConfBlockHash = from.nCollateralMinConfBlockHash; @@ -330,18 +333,20 @@ inline bool operator!=(const CMasternode& a, const CMasternode& b) class CMasternodeBroadcast : public CMasternode { public: - bool fRecovery; - CMasternodeBroadcast() : CMasternode(), fRecovery(false) {} - CMasternodeBroadcast(const CMasternode& mn) : CMasternode(mn), fRecovery(false) {} + CMasternodeBroadcast() : + CMasternode(), fRecovery(false) {} + CMasternodeBroadcast(const CMasternode& mn) : + CMasternode(mn), fRecovery(false) {} CMasternodeBroadcast(CService addrNew, COutPoint outpointNew, CPubKey pubKeyCollateralAddressNew, CPubKey pubKeyMasternodeNew, int nProtocolVersionIn) : CMasternode(addrNew, outpointNew, pubKeyCollateralAddressNew, pubKeyMasternodeNew, nProtocolVersionIn), fRecovery(false) {} ADD_SERIALIZE_METHODS; template - inline void SerializationOp(Stream& s, Operation ser_action) { + inline void SerializationOp(Stream& s, Operation ser_action) + { READWRITE(outpoint); READWRITE(addr); READWRITE(pubKeyCollateralAddress); @@ -367,8 +372,8 @@ class CMasternodeBroadcast : public CMasternode uint256 GetSignatureHash() const; /// Create Masternode broadcast, needs to be relayed manually after that - static bool Create(const COutPoint& outpoint, const CService& service, const CKey& keyCollateralAddressNew, const CPubKey& pubKeyCollateralAddressNew, const CKey& keyMasternodeNew, const CPubKey& pubKeyMasternodeNew, std::string &strErrorRet, CMasternodeBroadcast &mnbRet); - static bool Create(const std::string& strService, const std::string& strKey, const std::string& strTxHash, const std::string& strOutputIndex, std::string& strErrorRet, CMasternodeBroadcast &mnbRet, bool fOffline = false); + static bool Create(const COutPoint& outpoint, const CService& service, const CKey& keyCollateralAddressNew, const CPubKey& pubKeyCollateralAddressNew, const CKey& keyMasternodeNew, const CPubKey& pubKeyMasternodeNew, std::string& strErrorRet, CMasternodeBroadcast& mnbRet); + static bool Create(const std::string& strService, const std::string& strKey, const std::string& strTxHash, const std::string& strOutputIndex, std::string& strErrorRet, CMasternodeBroadcast& mnbRet, bool fOffline = false); bool SimpleCheck(int& nDos); bool Update(CMasternode* pmn, int& nDos, CConnman& connman); @@ -396,12 +401,14 @@ class CMasternodeVerification addr(addr), nonce(nonce), nBlockHeight(nBlockHeight) - {} + { + } ADD_SERIALIZE_METHODS; template - inline void SerializationOp(Stream& s, Operation ser_action) { + inline void SerializationOp(Stream& s, Operation ser_action) + { READWRITE(masternodeOutpoint1); READWRITE(masternodeOutpoint2); READWRITE(addr); diff --git a/src/masternodeconfig.cpp b/src/masternodeconfig.cpp index 0e2e67be796a..9e04fa3b3e34 100644 --- a/src/masternodeconfig.cpp +++ b/src/masternodeconfig.cpp @@ -1,20 +1,22 @@ -#include "netbase.h" #include "masternodeconfig.h" -#include "util.h" #include "chainparams.h" +#include "netbase.h" +#include "util.h" #include #include CMasternodeConfig masternodeConfig; -void CMasternodeConfig::add(const std::string& alias, const std::string& ip, const std::string& privKey, const std::string& txHash, const std::string& outputIndex) { +void CMasternodeConfig::add(const std::string& alias, const std::string& ip, const std::string& privKey, const std::string& txHash, const std::string& outputIndex) +{ CMasternodeEntry cme(alias, ip, privKey, txHash, outputIndex); entries.push_back(cme); } -bool CMasternodeConfig::read(std::string& strErrRet) { +bool CMasternodeConfig::read(std::string& strErrRet) +{ int linenumber = 1; boost::filesystem::path pathMasternodeConfigFile = GetMasternodeConfigFile(); boost::filesystem::ifstream streamConfig(pathMasternodeConfigFile); @@ -23,23 +25,22 @@ bool CMasternodeConfig::read(std::string& strErrRet) { FILE* configFile = fopen(pathMasternodeConfigFile.string().c_str(), "a"); if (configFile != nullptr) { std::string strHeader = "# Masternode config file\n" - "# Format: alias IP:port masternodeprivkey collateral_output_txid collateral_output_index\n" - "# Example: mn1 127.0.0.2:19999 93HaYBVUCYjEMeeH1Y4sBGLALQZE1Yc1K64xiqgX37tGBDQL8Xg 2bcd3c84c84f87eaa86e4e56834c92927a07f9e18718810b92e0d0324456a67c 0\n"; + "# Format: alias IP:port masternodeprivkey collateral_output_txid collateral_output_index\n" + "# Example: mn1 127.0.0.2:19999 93HaYBVUCYjEMeeH1Y4sBGLALQZE1Yc1K64xiqgX37tGBDQL8Xg 2bcd3c84c84f87eaa86e4e56834c92927a07f9e18718810b92e0d0324456a67c 0\n"; fwrite(strHeader.c_str(), std::strlen(strHeader.c_str()), 1, configFile); fclose(configFile); } return true; // Nothing to read, so just return } - for(std::string line; std::getline(streamConfig, line); linenumber++) - { - if(line.empty()) continue; + for (std::string line; std::getline(streamConfig, line); linenumber++) { + if (line.empty()) continue; std::istringstream iss(line); std::string comment, alias, ip, privKey, txHash, outputIndex; if (iss >> comment) { - if(comment.at(0) == '#') continue; + if (comment.at(0) == '#') continue; iss.str(line); iss.clear(); } @@ -49,7 +50,7 @@ bool CMasternodeConfig::read(std::string& strErrRet) { iss.clear(); if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) { strErrRet = _("Could not parse masternode.conf") + "\n" + - strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\""; + strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\""; streamConfig.close(); return false; } @@ -58,26 +59,26 @@ bool CMasternodeConfig::read(std::string& strErrRet) { int port = 0; std::string hostname = ""; SplitHostPort(ip, port, hostname); - if(port == 0 || hostname == "") { - strErrRet = _("Failed to parse host:port string") + "\n"+ - strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\""; + if (port == 0 || hostname == "") { + strErrRet = _("Failed to parse host:port string") + "\n" + + strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\""; streamConfig.close(); return false; } int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort(); - if(Params().NetworkIDString() == CBaseChainParams::MAIN) { - if(port != mainnetDefaultPort) { + if (Params().NetworkIDString() == CBaseChainParams::MAIN) { + if (port != mainnetDefaultPort) { strErrRet = _("Invalid port detected in masternode.conf") + "\n" + - strprintf(_("Port: %d"), port) + "\n" + - strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" + - strprintf(_("(must be %d for mainnet)"), mainnetDefaultPort); + strprintf(_("Port: %d"), port) + "\n" + + strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" + + strprintf(_("(must be %d for mainnet)"), mainnetDefaultPort); streamConfig.close(); return false; } - } else if(port == mainnetDefaultPort) { + } else if (port == mainnetDefaultPort) { strErrRet = _("Invalid port detected in masternode.conf") + "\n" + - strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" + - strprintf(_("(%d could be used only on mainnet)"), mainnetDefaultPort); + strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" + + strprintf(_("(%d could be used only on mainnet)"), mainnetDefaultPort); streamConfig.close(); return false; } diff --git a/src/masternodeconfig.h b/src/masternodeconfig.h index 7d978d9dc7d4..6f308b494924 100644 --- a/src/masternodeconfig.h +++ b/src/masternodeconfig.h @@ -11,20 +11,19 @@ extern CMasternodeConfig masternodeConfig; class CMasternodeConfig { - public: - - class CMasternodeEntry { - + class CMasternodeEntry + { private: std::string alias; std::string ip; std::string privKey; std::string txHash; std::string outputIndex; - public: - CMasternodeEntry(const std::string& alias, const std::string& ip, const std::string& privKey, const std::string& txHash, const std::string& outputIndex) { + public: + CMasternodeEntry(const std::string& alias, const std::string& ip, const std::string& privKey, const std::string& txHash, const std::string& outputIndex) + { this->alias = alias; this->ip = ip; this->privKey = privKey; @@ -32,28 +31,34 @@ class CMasternodeConfig this->outputIndex = outputIndex; } - const std::string& getAlias() const { + const std::string& getAlias() const + { return alias; } - const std::string& getOutputIndex() const { + const std::string& getOutputIndex() const + { return outputIndex; } - const std::string& getPrivKey() const { + const std::string& getPrivKey() const + { return privKey; } - const std::string& getTxHash() const { + const std::string& getTxHash() const + { return txHash; } - const std::string& getIp() const { + const std::string& getIp() const + { return ip; } }; - CMasternodeConfig() { + CMasternodeConfig() + { entries = std::vector(); } @@ -61,18 +66,18 @@ class CMasternodeConfig bool read(std::string& strErrRet); void add(const std::string& alias, const std::string& ip, const std::string& privKey, const std::string& txHash, const std::string& outputIndex); - std::vector& getEntries() { + std::vector& getEntries() + { return entries; } - int getCount() { + int getCount() + { return (int)entries.size(); } private: std::vector entries; - - }; diff --git a/src/masternodeman.cpp b/src/masternodeman.cpp index 1dbda34f9453..96e96199e40e 100644 --- a/src/masternodeman.cpp +++ b/src/masternodeman.cpp @@ -2,15 +2,15 @@ // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. +#include "masternodeman.h" #include "activemasternode.h" #include "addrman.h" #include "alert.h" #include "clientversion.h" -#include "init.h" #include "governance.h" +#include "init.h" #include "masternode-payments.h" #include "masternode-sync.h" -#include "masternodeman.h" #include "messagesigner.h" #include "netfulfilledman.h" #include "netmessagemaker.h" @@ -31,19 +31,17 @@ CMasternodeMan mnodeman; const std::string CMasternodeMan::SERIALIZATION_VERSION_STRING = "CMasternodeMan-Version-10"; const int CMasternodeMan::LAST_PAID_SCAN_BLOCKS = 100; -struct CompareLastPaidBlock -{ +struct CompareLastPaidBlock { bool operator()(const std::pair& t1, - const std::pair& t2) const + const std::pair& t2) const { return (t1.first != t2.first) ? (t1.first < t2.first) : (t1.second->outpoint < t2.second->outpoint); } }; -struct CompareScoreMN -{ +struct CompareScoreMN { bool operator()(const std::pair& t1, - const std::pair& t2) const + const std::pair& t2) const { return (t1.first != t2.first) ? (t1.first < t2.first) : (t1.second->outpoint < t2.second->outpoint); } @@ -53,13 +51,13 @@ struct CompareByAddr { bool operator()(const CMasternode* t1, - const CMasternode* t2) const + const CMasternode* t2) const { return t1->addr < t2->addr; } }; -CMasternodeMan::CMasternodeMan(): +CMasternodeMan::CMasternodeMan() : cs(), mapMasternodes(), mAskedUsForMasternodeList(), @@ -76,9 +74,10 @@ CMasternodeMan::CMasternodeMan(): mapSeenMasternodeBroadcast(), mapSeenMasternodePing(), nDsqCount(0) -{} +{ +} -bool CMasternodeMan::Add(CMasternode &mn) +bool CMasternodeMan::Add(CMasternode& mn) { LOCK(cs); @@ -95,7 +94,7 @@ bool CMasternodeMan::Add(CMasternode &mn) void CMasternodeMan::AskForMN(CNode* pnode, const COutPoint& outpoint, CConnman& connman) { - if(!pnode) return; + if (!pnode) return; CNetMsgMaker msgMaker(pnode->GetSendVersion()); LOCK(cs); @@ -127,7 +126,7 @@ void CMasternodeMan::AskForMN(CNode* pnode, const COutPoint& outpoint, CConnman& connman.PushMessage(pnode, msgMaker.Make(NetMsgType::DSEG, outpoint)); } -bool CMasternodeMan::AllowMixing(const COutPoint &outpoint) +bool CMasternodeMan::AllowMixing(const COutPoint& outpoint) { LOCK(cs); CMasternode* pmn = Find(outpoint); @@ -141,7 +140,7 @@ bool CMasternodeMan::AllowMixing(const COutPoint &outpoint) return true; } -bool CMasternodeMan::DisallowMixing(const COutPoint &outpoint) +bool CMasternodeMan::DisallowMixing(const COutPoint& outpoint) { LOCK(cs); CMasternode* pmn = Find(outpoint); @@ -153,7 +152,7 @@ bool CMasternodeMan::DisallowMixing(const COutPoint &outpoint) return true; } -bool CMasternodeMan::PoSeBan(const COutPoint &outpoint) +bool CMasternodeMan::PoSeBan(const COutPoint& outpoint) { LOCK(cs); @@ -188,7 +187,7 @@ void CMasternodeMan::CheckAndRemove(CConnman& connman) if (deterministicMNManager->IsDeterministicMNsSporkActive()) return; - if(!masternodeSync.IsMasternodeListSynced()) return; + if (!masternodeSync.IsMasternodeListSynced()) return; LogPrintf("CMasternodeMan::CheckAndRemove\n"); @@ -225,26 +224,26 @@ void CMasternodeMan::CheckAndRemove(CConnman& connman) it->second.IsNewStartRequired() && !IsMnbRecoveryRequested(hash) && !IsArgSet("-connect"); - if(fAsk) { + if (fAsk) { // this mn is in a non-recoverable state and we haven't asked other nodes yet std::set setRequested; // calulate only once and only when it's needed - if(vecMasternodeRanks.empty()) { + if (vecMasternodeRanks.empty()) { int nRandomBlockHeight = GetRandInt(nCachedBlockHeight); GetMasternodeRanks(vecMasternodeRanks, nRandomBlockHeight); } bool fAskedForMnbRecovery = false; // ask first MNB_RECOVERY_QUORUM_TOTAL masternodes we can connect to and we haven't asked recently - for(int i = 0; setRequested.size() < MNB_RECOVERY_QUORUM_TOTAL && i < (int)vecMasternodeRanks.size(); i++) { + for (int i = 0; setRequested.size() < MNB_RECOVERY_QUORUM_TOTAL && i < (int)vecMasternodeRanks.size(); i++) { // avoid banning - if(mWeAskedForMasternodeListEntry.count(it->first) && mWeAskedForMasternodeListEntry[it->first].count(vecMasternodeRanks[i].second.addr)) continue; + if (mWeAskedForMasternodeListEntry.count(it->first) && mWeAskedForMasternodeListEntry[it->first].count(vecMasternodeRanks[i].second.addr)) continue; // didn't ask recently, ok to ask now CService addr = vecMasternodeRanks[i].second.addr; setRequested.insert(addr); listScheduledMnbRequestConnections.push_back(std::make_pair(addr, hash)); fAskedForMnbRecovery = true; } - if(fAskedForMnbRecovery) { + if (fAskedForMnbRecovery) { LogPrint("masternode", "CMasternodeMan::CheckAndRemove -- Recovery initiated, masternode=%s\n", it->first.ToStringShort()); nAskForMnbRecovery--; } @@ -258,10 +257,10 @@ void CMasternodeMan::CheckAndRemove(CConnman& connman) // proces replies for MASTERNODE_NEW_START_REQUIRED masternodes LogPrint("masternode", "CMasternodeMan::CheckAndRemove -- mMnbRecoveryGoodReplies size=%d\n", (int)mMnbRecoveryGoodReplies.size()); std::map >::iterator itMnbReplies = mMnbRecoveryGoodReplies.begin(); - while(itMnbReplies != mMnbRecoveryGoodReplies.end()){ - if(mMnbRecoveryRequests[itMnbReplies->first].first < GetTime()) { + while (itMnbReplies != mMnbRecoveryGoodReplies.end()) { + if (mMnbRecoveryRequests[itMnbReplies->first].first < GetTime()) { // all nodes we asked should have replied now - if(itMnbReplies->second.size() >= MNB_RECOVERY_QUORUM_REQUIRED) { + if (itMnbReplies->second.size() >= MNB_RECOVERY_QUORUM_REQUIRED) { // majority of nodes we asked agrees that this mn doesn't require new mnb, reprocess one of new mnbs LogPrint("masternode", "CMasternodeMan::CheckAndRemove -- reprocessing mnb, masternode=%s\n", itMnbReplies->second[0].outpoint.ToStringShort()); // mapSeenMasternodeBroadcast.erase(itMnbReplies->first); @@ -281,10 +280,10 @@ void CMasternodeMan::CheckAndRemove(CConnman& connman) LOCK(cs); auto itMnbRequest = mMnbRecoveryRequests.begin(); - while(itMnbRequest != mMnbRecoveryRequests.end()){ + while (itMnbRequest != mMnbRecoveryRequests.end()) { // Allow this mnb to be re-verified again after MNB_RECOVERY_RETRY_SECONDS seconds // if mn is still in MASTERNODE_NEW_START_REQUIRED state. - if(GetTime() - itMnbRequest->second.first > MNB_RECOVERY_RETRY_SECONDS) { + if (GetTime() - itMnbRequest->second.first > MNB_RECOVERY_RETRY_SECONDS) { mMnbRecoveryRequests.erase(itMnbRequest++); } else { ++itMnbRequest; @@ -293,8 +292,8 @@ void CMasternodeMan::CheckAndRemove(CConnman& connman) // check who's asked for the Masternode list auto it1 = mAskedUsForMasternodeList.begin(); - while(it1 != mAskedUsForMasternodeList.end()){ - if((*it1).second < GetTime()) { + while (it1 != mAskedUsForMasternodeList.end()) { + if ((*it1).second < GetTime()) { mAskedUsForMasternodeList.erase(it1++); } else { ++it1; @@ -303,8 +302,8 @@ void CMasternodeMan::CheckAndRemove(CConnman& connman) // check who we asked for the Masternode list it1 = mWeAskedForMasternodeList.begin(); - while(it1 != mWeAskedForMasternodeList.end()){ - if((*it1).second < GetTime()){ + while (it1 != mWeAskedForMasternodeList.end()) { + if ((*it1).second < GetTime()) { mWeAskedForMasternodeList.erase(it1++); } else { ++it1; @@ -313,16 +312,16 @@ void CMasternodeMan::CheckAndRemove(CConnman& connman) // check which Masternodes we've asked for auto it2 = mWeAskedForMasternodeListEntry.begin(); - while(it2 != mWeAskedForMasternodeListEntry.end()){ + while (it2 != mWeAskedForMasternodeListEntry.end()) { auto it3 = it2->second.begin(); - while(it3 != it2->second.end()){ - if(it3->second < GetTime()){ + while (it3 != it2->second.end()) { + if (it3->second < GetTime()) { it2->second.erase(it3++); } else { ++it3; } } - if(it2->second.empty()) { + if (it2->second.empty()) { mWeAskedForMasternodeListEntry.erase(it2++); } else { ++it2; @@ -330,8 +329,8 @@ void CMasternodeMan::CheckAndRemove(CConnman& connman) } auto it3 = mWeAskedForVerification.begin(); - while(it3 != mWeAskedForVerification.end()){ - if(it3->second.nBlockHeight < nCachedBlockHeight - MAX_POSE_BLOCKS) { + while (it3 != mWeAskedForVerification.end()) { + if (it3->second.nBlockHeight < nCachedBlockHeight - MAX_POSE_BLOCKS) { mWeAskedForVerification.erase(it3++); } else { ++it3; @@ -342,8 +341,8 @@ void CMasternodeMan::CheckAndRemove(CConnman& connman) // remove expired mapSeenMasternodePing std::map::iterator it4 = mapSeenMasternodePing.begin(); - while(it4 != mapSeenMasternodePing.end()){ - if((*it4).second.IsExpired()) { + while (it4 != mapSeenMasternodePing.end()) { + if ((*it4).second.IsExpired()) { LogPrint("masternode", "CMasternodeMan::CheckAndRemove -- Removing expired Masternode ping: hash=%s\n", (*it4).second.GetHash().ToString()); mapSeenMasternodePing.erase(it4++); } else { @@ -353,8 +352,8 @@ void CMasternodeMan::CheckAndRemove(CConnman& connman) // remove expired mapSeenMasternodeVerification std::map::iterator itv2 = mapSeenMasternodeVerification.begin(); - while(itv2 != mapSeenMasternodeVerification.end()){ - if((*itv2).second.nBlockHeight < nCachedBlockHeight - MAX_POSE_BLOCKS){ + while (itv2 != mapSeenMasternodeVerification.end()) { + if ((*itv2).second.nBlockHeight < nCachedBlockHeight - MAX_POSE_BLOCKS) { LogPrint("masternode", "CMasternodeMan::CheckAndRemove -- Removing expired Masternode verification: hash=%s\n", (*itv2).first.ToString()); mapSeenMasternodeVerification.erase(itv2++); } else { @@ -365,7 +364,7 @@ void CMasternodeMan::CheckAndRemove(CConnman& connman) LogPrintf("CMasternodeMan::CheckAndRemove -- %s\n", ToString()); } - if(fMasternodesRemoved) { + if (fMasternodesRemoved) { NotifyMasternodeUpdates(connman); } } @@ -462,7 +461,7 @@ int CMasternodeMan::CountMasternodes(int nProtocolVersion) }); } else { for (const auto& mnpair : mapMasternodes) { - if(mnpair.second.nProtocolVersion < nProtocolVersion) continue; + if (mnpair.second.nProtocolVersion < nProtocolVersion) continue; nCount++; } } @@ -480,7 +479,7 @@ int CMasternodeMan::CountEnabled(int nProtocolVersion) nProtocolVersion = nProtocolVersion == -1 ? mnpayments.GetMinMasternodePaymentsProto() : nProtocolVersion; for (const auto& mnpair : mapMasternodes) { - if(mnpair.second.nProtocolVersion < nProtocolVersion || !mnpair.second.IsEnabled()) continue; + if (mnpair.second.nProtocolVersion < nProtocolVersion || !mnpair.second.IsEnabled()) continue; nCount++; } @@ -513,10 +512,10 @@ void CMasternodeMan::DsegUpdate(CNode* pnode, CConnman& connman) return; CService addrSquashed = Params().AllowMultiplePorts() ? (CService)pnode->addr : CService(pnode->addr, 0); - if(Params().NetworkIDString() == CBaseChainParams::MAIN) { - if(!(pnode->addr.IsRFC1918() || pnode->addr.IsLocal())) { + if (Params().NetworkIDString() == CBaseChainParams::MAIN) { + if (!(pnode->addr.IsRFC1918() || pnode->addr.IsLocal())) { auto it = mWeAskedForMasternodeList.find(addrSquashed); - if(it != mWeAskedForMasternodeList.end() && GetTime() < (*it).second) { + if (it != mWeAskedForMasternodeList.end() && GetTime() < (*it).second) { LogPrintf("CMasternodeMan::DsegUpdate -- we already asked %s for the list; skipping...\n", addrSquashed.ToString()); return; } @@ -531,7 +530,7 @@ void CMasternodeMan::DsegUpdate(CNode* pnode, CConnman& connman) LogPrint("masternode", "CMasternodeMan::DsegUpdate -- asked %s for the list\n", pnode->addr.ToString()); } -CMasternode* CMasternodeMan::Find(const COutPoint &outpoint) +CMasternode* CMasternodeMan::Find(const COutPoint& outpoint) { LOCK(cs); @@ -595,7 +594,8 @@ bool CMasternodeMan::GetMasternodeInfo(const COutPoint& outpoint, masternode_inf return true; } -bool CMasternodeMan::GetMasternodeInfo(const CKeyID& keyIDOperator, masternode_info_t& mnInfoRet) { +bool CMasternodeMan::GetMasternodeInfo(const CKeyID& keyIDOperator, masternode_info_t& mnInfoRet) +{ LOCK(cs); if (deterministicMNManager->IsDeterministicMNsSporkActive()) { auto mnList = deterministicMNManager->GetListAtChainTip(); @@ -669,7 +669,7 @@ bool CMasternodeMan::GetNextMasternodeInQueueForPayment(int nBlockHeight, bool f } // Need LOCK2 here to ensure consistent locking order because the GetBlockHash call below locks cs_main - LOCK2(cs_main,cs); + LOCK2(cs_main, cs); std::vector > vecMasternodeLastPaid; @@ -680,19 +680,19 @@ bool CMasternodeMan::GetNextMasternodeInQueueForPayment(int nBlockHeight, bool f int nMnCount = CountMasternodes(); for (const auto& mnpair : mapMasternodes) { - if(!mnpair.second.IsValidForPayment()) continue; + if (!mnpair.second.IsValidForPayment()) continue; //check protocol version - if(mnpair.second.nProtocolVersion < mnpayments.GetMinMasternodePaymentsProto()) continue; + if (mnpair.second.nProtocolVersion < mnpayments.GetMinMasternodePaymentsProto()) continue; //it's in the list (up to 8 entries ahead of current block to allow propagation) -- so let's skip it - if(mnpayments.IsScheduled(mnpair.second, nBlockHeight)) continue; + if (mnpayments.IsScheduled(mnpair.second, nBlockHeight)) continue; //it's too new, wait for a cycle - if(fFilterSigTime && mnpair.second.sigTime + (nMnCount*2.6*60) > GetAdjustedTime()) continue; + if (fFilterSigTime && mnpair.second.sigTime + (nMnCount * 2.6 * 60) > GetAdjustedTime()) continue; //make sure it has at least as many confirmations as there are masternodes - if(GetUTXOConfirmations(mnpair.first) < nMnCount) continue; + if (GetUTXOConfirmations(mnpair.first) < nMnCount) continue; vecMasternodeLastPaid.push_back(std::make_pair(mnpair.second.GetLastPaidBlock(), &mnpair.second)); } @@ -700,14 +700,14 @@ bool CMasternodeMan::GetNextMasternodeInQueueForPayment(int nBlockHeight, bool f nCountRet = (int)vecMasternodeLastPaid.size(); //when the network is in the process of upgrading, don't penalize nodes that recently restarted - if(fFilterSigTime && nCountRet < nMnCount/3) + if (fFilterSigTime && nCountRet < nMnCount / 3) return GetNextMasternodeInQueueForPayment(nBlockHeight, false, nCountRet, mnInfoRet); // Sort them low to high sort(vecMasternodeLastPaid.begin(), vecMasternodeLastPaid.end(), CompareLastPaidBlock()); uint256 blockHash; - if(!GetBlockHash(blockHash, nBlockHeight - 101)) { + if (!GetBlockHash(blockHash, nBlockHeight - 101)) { LogPrintf("CMasternode::GetNextMasternodeInQueueForPayment -- ERROR: GetBlockHash() failed at nBlockHeight %d\n", nBlockHeight - 101); return false; } @@ -715,18 +715,18 @@ bool CMasternodeMan::GetNextMasternodeInQueueForPayment(int nBlockHeight, bool f // -- This doesn't look at who is being paid in the +8-10 blocks, allowing for double payments very rarely // -- 1/100 payments should be a double payment on mainnet - (1/(3000/10))*2 // -- (chance per block * chances before IsScheduled will fire) - int nTenthNetwork = nMnCount/10; + int nTenthNetwork = nMnCount / 10; int nCountTenth = 0; arith_uint256 nHighest = 0; - const CMasternode *pBestMasternode = nullptr; + const CMasternode* pBestMasternode = nullptr; for (const auto& s : vecMasternodeLastPaid) { arith_uint256 nScore = s.second->CalculateScore(blockHash); - if(nScore > nHighest){ + if (nScore > nHighest) { nHighest = nScore; pBestMasternode = s.second; } nCountTenth++; - if(nCountTenth >= nTenthNetwork) break; + if (nCountTenth >= nTenthNetwork) break; } if (pBestMasternode) { mnInfoRet = pBestMasternode->GetInfo(); @@ -734,7 +734,7 @@ bool CMasternodeMan::GetNextMasternodeInQueueForPayment(int nBlockHeight, bool f return mnInfoRet.fInfoValid; } -masternode_info_t CMasternodeMan::FindRandomNotInVec(const std::vector &vecToExclude, int nProtocolVersion) +masternode_info_t CMasternodeMan::FindRandomNotInVec(const std::vector& vecToExclude, int nProtocolVersion) { LOCK(cs); @@ -744,7 +744,7 @@ masternode_info_t CMasternodeMan::FindRandomNotInVec(const std::vector vpMasternodesShuffled; @@ -759,15 +759,15 @@ masternode_info_t CMasternodeMan::FindRandomNotInVec(const std::vectornProtocolVersion < nProtocolVersion || !pmn->IsEnabled()) continue; + if (pmn->nProtocolVersion < nProtocolVersion || !pmn->IsEnabled()) continue; fExclude = false; for (const auto& outpointToExclude : vecToExclude) { - if(pmn->outpoint == outpointToExclude) { + if (pmn->outpoint == outpointToExclude) { fExclude = true; break; } } - if(fExclude) continue; + if (fExclude) continue; if (deterministicMNManager->IsDeterministicMNsSporkActive() && !deterministicMNManager->HasValidMNAtChainTip(pmn->outpoint.hash)) continue; // found the one not in vecToExclude @@ -785,7 +785,7 @@ std::map CMasternodeMan::GetFullMasternodeMap() if (deterministicMNManager->IsDeterministicMNsSporkActive()) { std::map result; - for (const auto &p : mapMasternodes) { + for (const auto& p : mapMasternodes) { if (deterministicMNManager->HasValidMNAtChainTip(p.first.hash)) { result.emplace(p.first, p.second); } @@ -845,7 +845,7 @@ bool CMasternodeMan::GetMasternodeRank(const COutPoint& outpoint, int& nRankRet, int nRank = 0; for (const auto& scorePair : vecMasternodeScores) { nRank++; - if(scorePair.second->outpoint == outpoint) { + if (scorePair.second->outpoint == outpoint) { nRankRet = nRank; return true; } @@ -886,7 +886,7 @@ bool CMasternodeMan::GetMasternodeRanks(CMasternodeMan::rank_pair_vec_t& vecMast void CMasternodeMan::ProcessMasternodeConnections(CConnman& connman) { //we don't care about this for regtest - if(Params().NetworkIDString() == CBaseChainParams::REGTEST) return; + if (Params().NetworkIDString() == CBaseChainParams::REGTEST) return; std::vector vecMnInfo; // will be empty when no wallet #ifdef ENABLE_WALLET @@ -904,7 +904,7 @@ void CMasternodeMan::ProcessMasternodeConnections(CConnman& connman) } } if (fFound) return; // do NOT disconnect mixing masternodes -#endif // ENABLE_WALLET +#endif // ENABLE_WALLET LogPrintf("Closing Masternode connection: peer=%d, addr=%s\n", pnode->id, pnode->addr.ToString()); pnode->fDisconnect = true; } @@ -917,7 +917,7 @@ std::pair > CMasternodeMan::PopScheduledMnbRequestCo if (deterministicMNManager->IsDeterministicMNsSporkActive()) { return std::make_pair(CService(), std::set()); } - if(listScheduledMnbRequestConnections.empty()) { + if (listScheduledMnbRequestConnections.empty()) { return std::make_pair(CService(), std::set()); } @@ -927,9 +927,9 @@ std::pair > CMasternodeMan::PopScheduledMnbRequestCo std::pair pairFront = listScheduledMnbRequestConnections.front(); // squash hashes from requests with the same CService as the first one into setResult - std::list< std::pair >::iterator it = listScheduledMnbRequestConnections.begin(); - while(it != listScheduledMnbRequestConnections.end()) { - if(pairFront.first == it->first) { + std::list >::iterator it = listScheduledMnbRequestConnections.begin(); + while (it != listScheduledMnbRequestConnections.end()) { + if (pairFront.first == it->first) { setResult.insert(it->second); it = listScheduledMnbRequestConnections.erase(it); } else { @@ -959,7 +959,7 @@ void CMasternodeMan::ProcessPendingMnbRequests(CConnman& connman) // compile request vector std::vector vToFetch; for (auto& nHash : itPendingMNB->second.second) { - if(nHash != uint256()) { + if (nHash != uint256()) { vToFetch.push_back(CInv(MSG_MASTERNODE_ANNOUNCE, nHash)); LogPrint("masternode", "-- asking for mnb %s from addr=%s\n", nHash.ToString(), pnode->addr.ToString()); } @@ -988,7 +988,7 @@ void CMasternodeMan::ProcessMessage(CNode* pfrom, const std::string& strCommand, if (deterministicMNManager->IsDeterministicMNsSporkActive()) return; - if(fLiteMode) return; // disable all Dash specific functionality + if (fLiteMode) return; // disable all Dash specific functionality if (strCommand == NetMsgType::MNANNOUNCE) { //Masternode Broadcast @@ -997,7 +997,7 @@ void CMasternodeMan::ProcessMessage(CNode* pfrom, const std::string& strCommand, pfrom->setAskFor.erase(mnb.GetHash()); - if(!masternodeSync.IsBlockchainSynced()) return; + if (!masternodeSync.IsBlockchainSynced()) return; LogPrint("masternode", "MNANNOUNCE -- Masternode announce, masternode=%s\n", mnb.outpoint.ToStringShort()); @@ -1005,13 +1005,13 @@ void CMasternodeMan::ProcessMessage(CNode* pfrom, const std::string& strCommand, if (CheckMnbAndUpdateMasternodeList(pfrom, mnb, nDos, connman)) { // use announced Masternode as a peer - connman.AddNewAddress(CAddress(mnb.addr, NODE_NETWORK), pfrom->addr, 2*60*60); - } else if(nDos > 0) { + connman.AddNewAddress(CAddress(mnb.addr, NODE_NETWORK), pfrom->addr, 2 * 60 * 60); + } else if (nDos > 0) { LOCK(cs_main); Misbehaving(pfrom->GetId(), nDos); } - if(fMasternodesAdded) { + if (fMasternodesAdded) { NotifyMasternodeUpdates(connman); } } else if (strCommand == NetMsgType::MNPING) { //Masternode Ping @@ -1023,14 +1023,14 @@ void CMasternodeMan::ProcessMessage(CNode* pfrom, const std::string& strCommand, pfrom->setAskFor.erase(nHash); - if(!masternodeSync.IsBlockchainSynced()) return; + if (!masternodeSync.IsBlockchainSynced()) return; LogPrint("masternode", "MNPING -- Masternode ping, masternode=%s\n", mnp.masternodeOutpoint.ToStringShort()); // Need LOCK2 here to ensure consistent locking order because the CheckAndUpdate call below locks cs_main LOCK2(cs_main, cs); - if(mapSeenMasternodePing.count(nHash)) return; //seen + if (mapSeenMasternodePing.count(nHash)) return; //seen mapSeenMasternodePing.insert(std::make_pair(nHash, mnp)); LogPrint("masternode", "MNPING -- Masternode ping, masternode=%s new\n", mnp.masternodeOutpoint.ToStringShort()); @@ -1038,19 +1038,19 @@ void CMasternodeMan::ProcessMessage(CNode* pfrom, const std::string& strCommand, // see if we have this Masternode CMasternode* pmn = Find(mnp.masternodeOutpoint); - if(pmn && mnp.fSentinelIsCurrent) + if (pmn && mnp.fSentinelIsCurrent) UpdateLastSentinelPingTime(); // too late, new MNANNOUNCE is required - if(pmn && pmn->IsNewStartRequired()) return; + if (pmn && pmn->IsNewStartRequired()) return; int nDos = 0; - if(mnp.CheckAndUpdate(pmn, false, nDos, connman)) return; + if (mnp.CheckAndUpdate(pmn, false, nDos, connman)) return; - if(nDos > 0) { + if (nDos > 0) { // if anything significant failed, mark that node Misbehaving(pfrom->GetId(), nDos); - } else if(pmn != nullptr) { + } else if (pmn != nullptr) { // nothing significant failed, mn is a known one too return; } @@ -1070,7 +1070,7 @@ void CMasternodeMan::ProcessMessage(CNode* pfrom, const std::string& strCommand, LogPrint("masternode", "DSEG -- Masternode list, masternode=%s\n", masternodeOutpoint.ToStringShort()); - if(masternodeOutpoint.IsNull()) { + if (masternodeOutpoint.IsNull()) { SyncAll(pfrom, connman); } else { SyncSingle(pfrom, masternodeOutpoint, connman); @@ -1086,9 +1086,9 @@ void CMasternodeMan::ProcessMessage(CNode* pfrom, const std::string& strCommand, pfrom->setAskFor.erase(mnv.GetHash()); - if(!masternodeSync.IsMasternodeListSynced()) return; + if (!masternodeSync.IsMasternodeListSynced()) return; - if(mnv.vchSig1.empty()) { + if (mnv.vchSig1.empty()) { // CASE 1: someone asked me to verify myself /IP we are using/ SendVerifyReply(pfrom, mnv, connman); } else if (mnv.vchSig2.empty()) { @@ -1110,7 +1110,7 @@ void CMasternodeMan::SyncSingle(CNode* pnode, const COutPoint& outpoint, CConnma auto it = mapMasternodes.find(outpoint); - if(it != mapMasternodes.end()) { + if (it != mapMasternodes.end()) { if (it->second.addr.IsRFC1918() || it->second.addr.IsLocal()) return; // do not send local network masternode // NOTE: send masternode regardless of its current state, the other node will need it to verify old votes. LogPrint("masternode", "CMasternodeMan::%s -- Sending Masternode entry: masternode=%s addr=%s\n", __func__, outpoint.ToStringShort(), it->second.addr.ToString()); @@ -1129,7 +1129,7 @@ void CMasternodeMan::SyncAll(CNode* pnode, CConnman& connman) CService addrSquashed = Params().AllowMultiplePorts() ? (CService)pnode->addr : CService(pnode->addr, 0); // should only ask for this once - if(!isLocal && Params().NetworkIDString() == CBaseChainParams::MAIN) { + if (!isLocal && Params().NetworkIDString() == CBaseChainParams::MAIN) { LOCK2(cs_main, cs); auto it = mAskedUsForMasternodeList.find(addrSquashed); if (it != mAskedUsForMasternodeList.end() && it->second > GetTime()) { @@ -1180,8 +1180,8 @@ void CMasternodeMan::DoFullVerificationStep(CConnman& connman) if (deterministicMNManager->IsDeterministicMNsSporkActive()) return; - if(activeMasternodeInfo.outpoint.IsNull()) return; - if(!masternodeSync.IsSynced()) return; + if (activeMasternodeInfo.outpoint.IsNull()) return; + if (!masternodeSync.IsSynced()) return; rank_pair_vec_t vecMasternodeRanks; GetMasternodeRanks(vecMasternodeRanks, nCachedBlockHeight - 1, MIN_POSE_PROTO_VERSION); @@ -1189,58 +1189,58 @@ void CMasternodeMan::DoFullVerificationStep(CConnman& connman) std::vector vAddr; { - LOCK(cs); + LOCK(cs); - int nMyRank = -1; - int nRanksTotal = (int)vecMasternodeRanks.size(); + int nMyRank = -1; + int nRanksTotal = (int)vecMasternodeRanks.size(); - // send verify requests only if we are in top MAX_POSE_RANK - for (auto& rankPair : vecMasternodeRanks) { - if(rankPair.first > MAX_POSE_RANK) { - LogPrint("masternode", "CMasternodeMan::DoFullVerificationStep -- Must be in top %d to send verify request\n", - (int)MAX_POSE_RANK); - return; - } - if(rankPair.second.outpoint == activeMasternodeInfo.outpoint) { - nMyRank = rankPair.first; - LogPrint("masternode", "CMasternodeMan::DoFullVerificationStep -- Found self at rank %d/%d, verifying up to %d masternodes\n", - nMyRank, nRanksTotal, (int)MAX_POSE_CONNECTIONS); - break; + // send verify requests only if we are in top MAX_POSE_RANK + for (auto& rankPair : vecMasternodeRanks) { + if (rankPair.first > MAX_POSE_RANK) { + LogPrint("masternode", "CMasternodeMan::DoFullVerificationStep -- Must be in top %d to send verify request\n", + (int)MAX_POSE_RANK); + return; + } + if (rankPair.second.outpoint == activeMasternodeInfo.outpoint) { + nMyRank = rankPair.first; + LogPrint("masternode", "CMasternodeMan::DoFullVerificationStep -- Found self at rank %d/%d, verifying up to %d masternodes\n", + nMyRank, nRanksTotal, (int)MAX_POSE_CONNECTIONS); + break; + } } - } - - // edge case: list is too short and this masternode is not enabled - if(nMyRank == -1) return; - // send verify requests to up to MAX_POSE_CONNECTIONS masternodes - // starting from MAX_POSE_RANK + nMyRank and using MAX_POSE_CONNECTIONS as a step - int nOffset = MAX_POSE_RANK + nMyRank - 1; - if(nOffset >= (int)vecMasternodeRanks.size()) return; - - auto it = vecMasternodeRanks.begin() + nOffset; - while(it != vecMasternodeRanks.end()) { - if(it->second.IsPoSeVerified() || it->second.IsPoSeBanned()) { - LogPrint("masternode", "CMasternodeMan::DoFullVerificationStep -- Already %s%s%s masternode %s address %s, skipping...\n", - it->second.IsPoSeVerified() ? "verified" : "", - it->second.IsPoSeVerified() && it->second.IsPoSeBanned() ? " and " : "", - it->second.IsPoSeBanned() ? "banned" : "", - it->second.outpoint.ToStringShort(), it->second.addr.ToString()); + // edge case: list is too short and this masternode is not enabled + if (nMyRank == -1) return; + + // send verify requests to up to MAX_POSE_CONNECTIONS masternodes + // starting from MAX_POSE_RANK + nMyRank and using MAX_POSE_CONNECTIONS as a step + int nOffset = MAX_POSE_RANK + nMyRank - 1; + if (nOffset >= (int)vecMasternodeRanks.size()) return; + + auto it = vecMasternodeRanks.begin() + nOffset; + while (it != vecMasternodeRanks.end()) { + if (it->second.IsPoSeVerified() || it->second.IsPoSeBanned()) { + LogPrint("masternode", "CMasternodeMan::DoFullVerificationStep -- Already %s%s%s masternode %s address %s, skipping...\n", + it->second.IsPoSeVerified() ? "verified" : "", + it->second.IsPoSeVerified() && it->second.IsPoSeBanned() ? " and " : "", + it->second.IsPoSeBanned() ? "banned" : "", + it->second.outpoint.ToStringShort(), it->second.addr.ToString()); + nOffset += MAX_POSE_CONNECTIONS; + if (nOffset >= (int)vecMasternodeRanks.size()) break; + it += MAX_POSE_CONNECTIONS; + continue; + } + LogPrint("masternode", "CMasternodeMan::DoFullVerificationStep -- Verifying masternode %s rank %d/%d address %s\n", + it->second.outpoint.ToStringShort(), it->first, nRanksTotal, it->second.addr.ToString()); + CAddress addr = CAddress(it->second.addr, NODE_NETWORK); + if (CheckVerifyRequestAddr(addr, connman)) { + vAddr.push_back(addr); + if ((int)vAddr.size() >= MAX_POSE_CONNECTIONS) break; + } nOffset += MAX_POSE_CONNECTIONS; - if(nOffset >= (int)vecMasternodeRanks.size()) break; + if (nOffset >= (int)vecMasternodeRanks.size()) break; it += MAX_POSE_CONNECTIONS; - continue; - } - LogPrint("masternode", "CMasternodeMan::DoFullVerificationStep -- Verifying masternode %s rank %d/%d address %s\n", - it->second.outpoint.ToStringShort(), it->first, nRanksTotal, it->second.addr.ToString()); - CAddress addr = CAddress(it->second.addr, NODE_NETWORK); - if(CheckVerifyRequestAddr(addr, connman)) { - vAddr.push_back(addr); - if((int)vAddr.size() >= MAX_POSE_CONNECTIONS) break; } - nOffset += MAX_POSE_CONNECTIONS; - if(nOffset >= (int)vecMasternodeRanks.size()) break; - it += MAX_POSE_CONNECTIONS; - } } // cs for (const auto& addr : vAddr) { @@ -1260,7 +1260,7 @@ void CMasternodeMan::CheckSameAddr() if (deterministicMNManager->IsDeterministicMNsSporkActive()) return; - if(!masternodeSync.IsSynced() || mapMasternodes.empty()) return; + if (!masternodeSync.IsSynced() || mapMasternodes.empty()) return; std::vector vBan; std::vector vSortedByAddr; @@ -1279,19 +1279,19 @@ void CMasternodeMan::CheckSameAddr() for (const auto& pmn : vSortedByAddr) { // check only (pre)enabled masternodes - if(!pmn->IsEnabled() && !pmn->IsPreEnabled()) continue; + if (!pmn->IsEnabled() && !pmn->IsPreEnabled()) continue; // initial step - if(!pprevMasternode) { + if (!pprevMasternode) { pprevMasternode = pmn; pverifiedMasternode = pmn->IsPoSeVerified() ? pmn : nullptr; continue; } // second+ step - if(pmn->addr == pprevMasternode->addr) { - if(pverifiedMasternode) { + if (pmn->addr == pprevMasternode->addr) { + if (pverifiedMasternode) { // another masternode with the same ip is verified, ban this one vBan.push_back(pmn); - } else if(pmn->IsPoSeVerified()) { + } else if (pmn->IsPoSeVerified()) { // this masternode with the same ip is verified, ban previous one vBan.push_back(pprevMasternode); // and keep a reference to be able to ban following masternodes with the same ip @@ -1316,7 +1316,7 @@ bool CMasternodeMan::CheckVerifyRequestAddr(const CAddress& addr, CConnman& conn if (deterministicMNManager->IsDeterministicMNsSporkActive()) return false; - if(netfulfilledman.HasFulfilledRequest(addr, strprintf("%s", NetMsgType::MNVERIFY)+"-request")) { + if (netfulfilledman.HasFulfilledRequest(addr, strprintf("%s", NetMsgType::MNVERIFY) + "-request")) { // we already asked for verification, not a good idea to do this too often, skip it LogPrint("masternode", "CMasternodeMan::%s -- too many requests, skipping... addr=%s\n", __func__, addr.ToString()); return false; @@ -1346,7 +1346,7 @@ void CMasternodeMan::ProcessPendingMnvRequests(CConnman& connman) while (itPendingMNV != mapPendingMNV.end()) { bool fDone = connman.ForNode(itPendingMNV->first, [&](CNode* pnode) { - netfulfilledman.AddFulfilledRequest(pnode->addr, strprintf("%s", NetMsgType::MNVERIFY)+"-request"); + netfulfilledman.AddFulfilledRequest(pnode->addr, strprintf("%s", NetMsgType::MNVERIFY) + "-request"); // use random nonce, store it and require node to reply with correct one later mWeAskedForVerification[pnode->addr] = itPendingMNV->second.second; LogPrint("masternode", "-- verifying node using nonce %d addr=%s\n", itPendingMNV->second.second.nonce, pnode->addr.ToString()); @@ -1375,13 +1375,13 @@ void CMasternodeMan::SendVerifyReply(CNode* pnode, CMasternodeVerification& mnv, return; // only masternodes can sign this, why would someone ask regular node? - if(!fMasternodeMode) { + if (!fMasternodeMode) { // do not ban, malicious node might be using my IP // and trying to confuse the node which tries to verify it return; } - if(netfulfilledman.HasFulfilledRequest(pnode->addr, strprintf("%s", NetMsgType::MNVERIFY)+"-reply")) { + if (netfulfilledman.HasFulfilledRequest(pnode->addr, strprintf("%s", NetMsgType::MNVERIFY) + "-reply")) { // peer should not ask us that often LogPrintf("MasternodeMan::SendVerifyReply -- ERROR: peer already asked me recently, peer=%d\n", pnode->id); Misbehaving(pnode->id, 20); @@ -1389,7 +1389,7 @@ void CMasternodeMan::SendVerifyReply(CNode* pnode, CMasternodeVerification& mnv, } uint256 blockHash; - if(!GetBlockHash(blockHash, mnv.nBlockHeight)) { + if (!GetBlockHash(blockHash, mnv.nBlockHeight)) { LogPrintf("MasternodeMan::SendVerifyReply -- can't get block hash for unknown block height %d, peer=%d\n", mnv.nBlockHeight, pnode->id); return; } @@ -1399,7 +1399,7 @@ void CMasternodeMan::SendVerifyReply(CNode* pnode, CMasternodeVerification& mnv, if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { uint256 hash = mnv.GetSignatureHash1(blockHash); - if(!CHashSigner::SignHash(hash, activeMasternodeInfo.keyOperator, mnv.vchSig1)) { + if (!CHashSigner::SignHash(hash, activeMasternodeInfo.keyOperator, mnv.vchSig1)) { LogPrintf("CMasternodeMan::SendVerifyReply -- SignHash() failed\n"); return; } @@ -1411,12 +1411,12 @@ void CMasternodeMan::SendVerifyReply(CNode* pnode, CMasternodeVerification& mnv, } else { std::string strMessage = strprintf("%s%d%s", activeMasternodeInfo.service.ToString(false), mnv.nonce, blockHash.ToString()); - if(!CMessageSigner::SignMessage(strMessage, mnv.vchSig1, activeMasternodeInfo.keyOperator)) { + if (!CMessageSigner::SignMessage(strMessage, mnv.vchSig1, activeMasternodeInfo.keyOperator)) { LogPrintf("MasternodeMan::SendVerifyReply -- SignMessage() failed\n"); return; } - if(!CMessageSigner::VerifyMessage(activeMasternodeInfo.keyIDOperator, mnv.vchSig1, strMessage, strError)) { + if (!CMessageSigner::VerifyMessage(activeMasternodeInfo.keyIDOperator, mnv.vchSig1, strMessage, strError)) { LogPrintf("MasternodeMan::SendVerifyReply -- VerifyMessage() failed, error: %s\n", strError); return; } @@ -1424,7 +1424,7 @@ void CMasternodeMan::SendVerifyReply(CNode* pnode, CMasternodeVerification& mnv, CNetMsgMaker msgMaker(pnode->GetSendVersion()); connman.PushMessage(pnode, msgMaker.Make(NetMsgType::MNVERIFY, mnv)); - netfulfilledman.AddFulfilledRequest(pnode->addr, strprintf("%s", NetMsgType::MNVERIFY)+"-reply"); + netfulfilledman.AddFulfilledRequest(pnode->addr, strprintf("%s", NetMsgType::MNVERIFY) + "-reply"); } void CMasternodeMan::ProcessVerifyReply(CNode* pnode, CMasternodeVerification& mnv) @@ -1437,37 +1437,37 @@ void CMasternodeMan::ProcessVerifyReply(CNode* pnode, CMasternodeVerification& m std::string strError; // did we even ask for it? if that's the case we should have matching fulfilled request - if(!netfulfilledman.HasFulfilledRequest(pnode->addr, strprintf("%s", NetMsgType::MNVERIFY)+"-request")) { + if (!netfulfilledman.HasFulfilledRequest(pnode->addr, strprintf("%s", NetMsgType::MNVERIFY) + "-request")) { LogPrintf("CMasternodeMan::ProcessVerifyReply -- ERROR: we didn't ask for verification of %s, peer=%d\n", pnode->addr.ToString(), pnode->id); Misbehaving(pnode->id, 20); return; } // Received nonce for a known address must match the one we sent - if(mWeAskedForVerification[pnode->addr].nonce != mnv.nonce) { + if (mWeAskedForVerification[pnode->addr].nonce != mnv.nonce) { LogPrintf("CMasternodeMan::ProcessVerifyReply -- ERROR: wrong nounce: requested=%d, received=%d, peer=%d\n", - mWeAskedForVerification[pnode->addr].nonce, mnv.nonce, pnode->id); + mWeAskedForVerification[pnode->addr].nonce, mnv.nonce, pnode->id); Misbehaving(pnode->id, 20); return; } // Received nBlockHeight for a known address must match the one we sent - if(mWeAskedForVerification[pnode->addr].nBlockHeight != mnv.nBlockHeight) { + if (mWeAskedForVerification[pnode->addr].nBlockHeight != mnv.nBlockHeight) { LogPrintf("CMasternodeMan::ProcessVerifyReply -- ERROR: wrong nBlockHeight: requested=%d, received=%d, peer=%d\n", - mWeAskedForVerification[pnode->addr].nBlockHeight, mnv.nBlockHeight, pnode->id); + mWeAskedForVerification[pnode->addr].nBlockHeight, mnv.nBlockHeight, pnode->id); Misbehaving(pnode->id, 20); return; } uint256 blockHash; - if(!GetBlockHash(blockHash, mnv.nBlockHeight)) { + if (!GetBlockHash(blockHash, mnv.nBlockHeight)) { // this shouldn't happen... LogPrintf("MasternodeMan::ProcessVerifyReply -- can't get block hash for unknown block height %d, peer=%d\n", mnv.nBlockHeight, pnode->id); return; } // we already verified this address, why node is spamming? - if(netfulfilledman.HasFulfilledRequest(pnode->addr, strprintf("%s", NetMsgType::MNVERIFY)+"-done")) { + if (netfulfilledman.HasFulfilledRequest(pnode->addr, strprintf("%s", NetMsgType::MNVERIFY) + "-done")) { LogPrintf("CMasternodeMan::ProcessVerifyReply -- ERROR: already verified %s recently\n", pnode->addr.ToString()); Misbehaving(pnode->id, 20); return; @@ -1483,7 +1483,7 @@ void CMasternodeMan::ProcessVerifyReply(CNode* pnode, CMasternodeVerification& m std::string strMessage1 = strprintf("%s%d%s", pnode->addr.ToString(false), mnv.nonce, blockHash.ToString()); for (auto& mnpair : mapMasternodes) { - if(CAddress(mnpair.second.addr, NODE_NETWORK) == pnode->addr) { + if (CAddress(mnpair.second.addr, NODE_NETWORK) == pnode->addr) { bool fFound = false; if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { fFound = CHashSigner::VerifyHash(hash1, mnpair.second.keyIDOperator, mnv.vchSig1, strError); @@ -1494,13 +1494,13 @@ void CMasternodeMan::ProcessVerifyReply(CNode* pnode, CMasternodeVerification& m if (fFound) { // found it! prealMasternode = &mnpair.second; - if(!mnpair.second.IsPoSeVerified()) { + if (!mnpair.second.IsPoSeVerified()) { mnpair.second.DecreasePoSeBanScore(); } - netfulfilledman.AddFulfilledRequest(pnode->addr, strprintf("%s", NetMsgType::MNVERIFY)+"-done"); + netfulfilledman.AddFulfilledRequest(pnode->addr, strprintf("%s", NetMsgType::MNVERIFY) + "-done"); // we can only broadcast it if we are an activated masternode - if(activeMasternodeInfo.outpoint.IsNull()) continue; + if (activeMasternodeInfo.outpoint.IsNull()) continue; // update ... mnv.addr = mnpair.second.addr; mnv.masternodeOutpoint1 = mnpair.second.outpoint; @@ -1511,25 +1511,25 @@ void CMasternodeMan::ProcessVerifyReply(CNode* pnode, CMasternodeVerification& m if (sporkManager.IsSporkActive(SPORK_6_NEW_SIGS)) { uint256 hash2 = mnv.GetSignatureHash2(blockHash); - if(!CHashSigner::SignHash(hash2, activeMasternodeInfo.keyOperator, mnv.vchSig2)) { + if (!CHashSigner::SignHash(hash2, activeMasternodeInfo.keyOperator, mnv.vchSig2)) { LogPrintf("MasternodeMan::ProcessVerifyReply -- SignHash() failed\n"); return; } - if(!CHashSigner::VerifyHash(hash2, activeMasternodeInfo.keyIDOperator, mnv.vchSig2, strError)) { + if (!CHashSigner::VerifyHash(hash2, activeMasternodeInfo.keyIDOperator, mnv.vchSig2, strError)) { LogPrintf("MasternodeMan::ProcessVerifyReply -- VerifyHash() failed, error: %s\n", strError); return; } } else { std::string strMessage2 = strprintf("%s%d%s%s%s", mnv.addr.ToString(false), mnv.nonce, blockHash.ToString(), - mnv.masternodeOutpoint1.ToStringShort(), mnv.masternodeOutpoint2.ToStringShort()); + mnv.masternodeOutpoint1.ToStringShort(), mnv.masternodeOutpoint2.ToStringShort()); - if(!CMessageSigner::SignMessage(strMessage2, mnv.vchSig2, activeMasternodeInfo.keyOperator)) { + if (!CMessageSigner::SignMessage(strMessage2, mnv.vchSig2, activeMasternodeInfo.keyOperator)) { LogPrintf("MasternodeMan::ProcessVerifyReply -- SignMessage() failed\n"); return; } - if(!CMessageSigner::VerifyMessage(activeMasternodeInfo.keyIDOperator, mnv.vchSig2, strMessage2, strError)) { + if (!CMessageSigner::VerifyMessage(activeMasternodeInfo.keyIDOperator, mnv.vchSig2, strMessage2, strError)) { LogPrintf("MasternodeMan::ProcessVerifyReply -- VerifyMessage() failed, error: %s\n", strError); return; } @@ -1545,7 +1545,7 @@ void CMasternodeMan::ProcessVerifyReply(CNode* pnode, CMasternodeVerification& m } } // no real masternode found?... - if(!prealMasternode) { + if (!prealMasternode) { // this should never be the case normally, // only if someone is trying to game the system in some way or smth like that LogPrintf("CMasternodeMan::ProcessVerifyReply -- ERROR: no real masternode found for addr %s\n", pnode->addr.ToString()); @@ -1553,16 +1553,16 @@ void CMasternodeMan::ProcessVerifyReply(CNode* pnode, CMasternodeVerification& m return; } LogPrintf("CMasternodeMan::ProcessVerifyReply -- verified real masternode %s for addr %s\n", - prealMasternode->outpoint.ToStringShort(), pnode->addr.ToString()); + prealMasternode->outpoint.ToStringShort(), pnode->addr.ToString()); // increase ban score for everyone else for (const auto& pmn : vpMasternodesToBan) { pmn->IncreasePoSeBanScore(); LogPrint("masternode", "CMasternodeMan::ProcessVerifyReply -- increased PoSe ban score for %s addr %s, new score %d\n", - prealMasternode->outpoint.ToStringShort(), pnode->addr.ToString(), pmn->nPoSeBanScore); + prealMasternode->outpoint.ToStringShort(), pnode->addr.ToString(), pmn->nPoSeBanScore); } - if(!vpMasternodesToBan.empty()) + if (!vpMasternodesToBan.empty()) LogPrintf("CMasternodeMan::ProcessVerifyReply -- PoSe score increased for %d fake masternodes, addr %s\n", - (int)vpMasternodesToBan.size(), pnode->addr.ToString()); + (int)vpMasternodesToBan.size(), pnode->addr.ToString()); } } @@ -1575,22 +1575,22 @@ void CMasternodeMan::ProcessVerifyBroadcast(CNode* pnode, const CMasternodeVerif std::string strError; - if(mapSeenMasternodeVerification.find(mnv.GetHash()) != mapSeenMasternodeVerification.end()) { + if (mapSeenMasternodeVerification.find(mnv.GetHash()) != mapSeenMasternodeVerification.end()) { // we already have one return; } mapSeenMasternodeVerification[mnv.GetHash()] = mnv; // we don't care about history - if(mnv.nBlockHeight < nCachedBlockHeight - MAX_POSE_BLOCKS) { + if (mnv.nBlockHeight < nCachedBlockHeight - MAX_POSE_BLOCKS) { LogPrint("masternode", "CMasternodeMan::ProcessVerifyBroadcast -- Outdated: current block %d, verification block %d, peer=%d\n", - nCachedBlockHeight, mnv.nBlockHeight, pnode->id); + nCachedBlockHeight, mnv.nBlockHeight, pnode->id); return; } - if(mnv.masternodeOutpoint1 == mnv.masternodeOutpoint2) { + if (mnv.masternodeOutpoint1 == mnv.masternodeOutpoint2) { LogPrint("masternode", "CMasternodeMan::ProcessVerifyBroadcast -- ERROR: same outpoints %s, peer=%d\n", - mnv.masternodeOutpoint1.ToStringShort(), pnode->id); + mnv.masternodeOutpoint1.ToStringShort(), pnode->id); // that was NOT a good idea to cheat and verify itself, // ban the node we received such message from Misbehaving(pnode->id, 100); @@ -1598,7 +1598,7 @@ void CMasternodeMan::ProcessVerifyBroadcast(CNode* pnode, const CMasternodeVerif } uint256 blockHash; - if(!GetBlockHash(blockHash, mnv.nBlockHeight)) { + if (!GetBlockHash(blockHash, mnv.nBlockHeight)) { // this shouldn't happen... LogPrintf("CMasternodeMan::ProcessVerifyBroadcast -- Can't get block hash for unknown block height %d, peer=%d\n", mnv.nBlockHeight, pnode->id); return; @@ -1608,13 +1608,13 @@ void CMasternodeMan::ProcessVerifyBroadcast(CNode* pnode, const CMasternodeVerif if (!GetMasternodeRank(mnv.masternodeOutpoint2, nRank, mnv.nBlockHeight, MIN_POSE_PROTO_VERSION)) { LogPrint("masternode", "CMasternodeMan::ProcessVerifyBroadcast -- Can't calculate rank for masternode %s\n", - mnv.masternodeOutpoint2.ToStringShort()); + mnv.masternodeOutpoint2.ToStringShort()); return; } - if(nRank > MAX_POSE_RANK) { + if (nRank > MAX_POSE_RANK) { LogPrint("masternode", "CMasternodeMan::ProcessVerifyBroadcast -- Masternode %s is not in top %d, current rank %d, peer=%d\n", - mnv.masternodeOutpoint2.ToStringShort(), (int)MAX_POSE_RANK, nRank, pnode->id); + mnv.masternodeOutpoint2.ToStringShort(), (int)MAX_POSE_RANK, nRank, pnode->id); return; } @@ -1622,18 +1622,18 @@ void CMasternodeMan::ProcessVerifyBroadcast(CNode* pnode, const CMasternodeVerif LOCK(cs); CMasternode* pmn1 = Find(mnv.masternodeOutpoint1); - if(!pmn1) { + if (!pmn1) { LogPrintf("CMasternodeMan::ProcessVerifyBroadcast -- can't find masternode1 %s\n", mnv.masternodeOutpoint1.ToStringShort()); return; } CMasternode* pmn2 = Find(mnv.masternodeOutpoint2); - if(!pmn2) { + if (!pmn2) { LogPrintf("CMasternodeMan::ProcessVerifyBroadcast -- can't find masternode2 %s\n", mnv.masternodeOutpoint2.ToStringShort()); return; } - if(pmn1->addr != mnv.addr) { + if (pmn1->addr != mnv.addr) { LogPrintf("CMasternodeMan::ProcessVerifyBroadcast -- addr %s does not match %s\n", mnv.addr.ToString(), pmn1->addr.ToString()); return; } @@ -1642,51 +1642,51 @@ void CMasternodeMan::ProcessVerifyBroadcast(CNode* pnode, const CMasternodeVerif uint256 hash1 = mnv.GetSignatureHash1(blockHash); uint256 hash2 = mnv.GetSignatureHash2(blockHash); - if(!CHashSigner::VerifyHash(hash1, pmn1->keyIDOperator, mnv.vchSig1, strError)) { + if (!CHashSigner::VerifyHash(hash1, pmn1->keyIDOperator, mnv.vchSig1, strError)) { LogPrintf("MasternodeMan::ProcessVerifyBroadcast -- VerifyHash() failed, error: %s\n", strError); return; } - if(!CHashSigner::VerifyHash(hash2, pmn2->keyIDOperator, mnv.vchSig2, strError)) { + if (!CHashSigner::VerifyHash(hash2, pmn2->keyIDOperator, mnv.vchSig2, strError)) { LogPrintf("MasternodeMan::ProcessVerifyBroadcast -- VerifyHash() failed, error: %s\n", strError); return; } } else { std::string strMessage1 = strprintf("%s%d%s", mnv.addr.ToString(false), mnv.nonce, blockHash.ToString()); std::string strMessage2 = strprintf("%s%d%s%s%s", mnv.addr.ToString(false), mnv.nonce, blockHash.ToString(), - mnv.masternodeOutpoint1.ToStringShort(), mnv.masternodeOutpoint2.ToStringShort()); + mnv.masternodeOutpoint1.ToStringShort(), mnv.masternodeOutpoint2.ToStringShort()); - if(!CMessageSigner::VerifyMessage(pmn1->keyIDOperator, mnv.vchSig1, strMessage1, strError)) { + if (!CMessageSigner::VerifyMessage(pmn1->keyIDOperator, mnv.vchSig1, strMessage1, strError)) { LogPrintf("CMasternodeMan::ProcessVerifyBroadcast -- VerifyMessage() for masternode1 failed, error: %s\n", strError); return; } - if(!CMessageSigner::VerifyMessage(pmn2->keyIDOperator, mnv.vchSig2, strMessage2, strError)) { + if (!CMessageSigner::VerifyMessage(pmn2->keyIDOperator, mnv.vchSig2, strMessage2, strError)) { LogPrintf("CMasternodeMan::ProcessVerifyBroadcast -- VerifyMessage() for masternode2 failed, error: %s\n", strError); return; } } - if(!pmn1->IsPoSeVerified()) { + if (!pmn1->IsPoSeVerified()) { pmn1->DecreasePoSeBanScore(); } mnv.Relay(); LogPrintf("CMasternodeMan::ProcessVerifyBroadcast -- verified masternode %s for addr %s\n", - pmn1->outpoint.ToStringShort(), pmn1->addr.ToString()); + pmn1->outpoint.ToStringShort(), pmn1->addr.ToString()); // increase ban score for everyone else with the same addr int nCount = 0; for (auto& mnpair : mapMasternodes) { - if(mnpair.second.addr != mnv.addr || mnpair.first == mnv.masternodeOutpoint1) continue; + if (mnpair.second.addr != mnv.addr || mnpair.first == mnv.masternodeOutpoint1) continue; mnpair.second.IncreasePoSeBanScore(); nCount++; LogPrint("masternode", "CMasternodeMan::ProcessVerifyBroadcast -- increased PoSe ban score for %s addr %s, new score %d\n", - mnpair.first.ToStringShort(), mnpair.second.addr.ToString(), mnpair.second.nPoSeBanScore); + mnpair.first.ToStringShort(), mnpair.second.addr.ToString(), mnpair.second.nPoSeBanScore); } - if(nCount) + if (nCount) LogPrintf("CMasternodeMan::ProcessVerifyBroadcast -- PoSe score increased for %d fake masternodes, addr %s\n", - nCount, pmn1->addr.ToString()); + nCount, pmn1->addr.ToString()); } } @@ -1695,15 +1695,9 @@ std::string CMasternodeMan::ToString() const std::ostringstream info; if (deterministicMNManager->IsDeterministicMNsSporkActive()) { - info << "Masternodes: masternode object count: " << (int)mapMasternodes.size() << - ", deterministic masternode count: " << deterministicMNManager->GetListAtChainTip().GetAllMNsCount() << - ", nDsqCount: " << (int)nDsqCount; + info << "Masternodes: masternode object count: " << (int)mapMasternodes.size() << ", deterministic masternode count: " << deterministicMNManager->GetListAtChainTip().GetAllMNsCount() << ", nDsqCount: " << (int)nDsqCount; } else { - info << "Masternodes: " << (int)mapMasternodes.size() << - ", peers who asked us for Masternode list: " << (int)mAskedUsForMasternodeList.size() << - ", peers we asked for Masternode list: " << (int)mWeAskedForMasternodeList.size() << - ", entries in Masternode list we asked for: " << (int)mWeAskedForMasternodeListEntry.size() << - ", nDsqCount: " << (int)nDsqCount; + info << "Masternodes: " << (int)mapMasternodes.size() << ", peers who asked us for Masternode list: " << (int)mAskedUsForMasternodeList.size() << ", peers we asked for Masternode list: " << (int)mWeAskedForMasternodeList.size() << ", entries in Masternode list we asked for: " << (int)mWeAskedForMasternodeListEntry.size() << ", nDsqCount: " << (int)nDsqCount; } return info.str(); } @@ -1722,28 +1716,28 @@ bool CMasternodeMan::CheckMnbAndUpdateMasternodeList(CNode* pfrom, CMasternodeBr LogPrint("masternode", "CMasternodeMan::CheckMnbAndUpdateMasternodeList -- masternode=%s\n", mnb.outpoint.ToStringShort()); uint256 hash = mnb.GetHash(); - if(mapSeenMasternodeBroadcast.count(hash) && !mnb.fRecovery) { //seen + if (mapSeenMasternodeBroadcast.count(hash) && !mnb.fRecovery) { //seen LogPrint("masternode", "CMasternodeMan::CheckMnbAndUpdateMasternodeList -- masternode=%s seen\n", mnb.outpoint.ToStringShort()); // less then 2 pings left before this MN goes into non-recoverable state, bump sync timeout - if(GetTime() - mapSeenMasternodeBroadcast[hash].first > MASTERNODE_NEW_START_REQUIRED_SECONDS - MASTERNODE_MIN_MNP_SECONDS * 2) { + if (GetTime() - mapSeenMasternodeBroadcast[hash].first > MASTERNODE_NEW_START_REQUIRED_SECONDS - MASTERNODE_MIN_MNP_SECONDS * 2) { LogPrint("masternode", "CMasternodeMan::CheckMnbAndUpdateMasternodeList -- masternode=%s seen update\n", mnb.outpoint.ToStringShort()); mapSeenMasternodeBroadcast[hash].first = GetTime(); masternodeSync.BumpAssetLastTime("CMasternodeMan::CheckMnbAndUpdateMasternodeList - seen"); } // did we ask this node for it? - if(pfrom && IsMnbRecoveryRequested(hash) && GetTime() < mMnbRecoveryRequests[hash].first) { + if (pfrom && IsMnbRecoveryRequested(hash) && GetTime() < mMnbRecoveryRequests[hash].first) { LogPrint("masternode", "CMasternodeMan::CheckMnbAndUpdateMasternodeList -- mnb=%s seen request\n", hash.ToString()); - if(mMnbRecoveryRequests[hash].second.count(pfrom->addr)) { + if (mMnbRecoveryRequests[hash].second.count(pfrom->addr)) { LogPrint("masternode", "CMasternodeMan::CheckMnbAndUpdateMasternodeList -- mnb=%s seen request, addr=%s\n", hash.ToString(), pfrom->addr.ToString()); // do not allow node to send same mnb multiple times in recovery mode mMnbRecoveryRequests[hash].second.erase(pfrom->addr); // does it have newer lastPing? - if(mnb.lastPing.sigTime > mapSeenMasternodeBroadcast[hash].second.lastPing.sigTime) { + if (mnb.lastPing.sigTime > mapSeenMasternodeBroadcast[hash].second.lastPing.sigTime) { // simulate Check CMasternode mnTemp = CMasternode(mnb); mnTemp.Check(); - LogPrint("masternode", "CMasternodeMan::CheckMnbAndUpdateMasternodeList -- mnb=%s seen request, addr=%s, better lastPing: %d min ago, projected mn state: %s\n", hash.ToString(), pfrom->addr.ToString(), (GetAdjustedTime() - mnb.lastPing.sigTime)/60, mnTemp.GetStateString()); - if(mnTemp.IsValidStateForAutoStart(mnTemp.nActiveState)) { + LogPrint("masternode", "CMasternodeMan::CheckMnbAndUpdateMasternodeList -- mnb=%s seen request, addr=%s, better lastPing: %d min ago, projected mn state: %s\n", hash.ToString(), pfrom->addr.ToString(), (GetAdjustedTime() - mnb.lastPing.sigTime) / 60, mnTemp.GetStateString()); + if (mnTemp.IsValidStateForAutoStart(mnTemp.nActiveState)) { // this node thinks it's a good one LogPrint("masternode", "CMasternodeMan::CheckMnbAndUpdateMasternodeList -- masternode=%s seen good\n", mnb.outpoint.ToStringShort()); mMnbRecoveryGoodReplies[hash].push_back(mnb); @@ -1757,36 +1751,36 @@ bool CMasternodeMan::CheckMnbAndUpdateMasternodeList(CNode* pfrom, CMasternodeBr LogPrint("masternode", "CMasternodeMan::CheckMnbAndUpdateMasternodeList -- masternode=%s new\n", mnb.outpoint.ToStringShort()); - if(!mnb.SimpleCheck(nDos)) { + if (!mnb.SimpleCheck(nDos)) { LogPrint("masternode", "CMasternodeMan::CheckMnbAndUpdateMasternodeList -- SimpleCheck() failed, masternode=%s\n", mnb.outpoint.ToStringShort()); return false; } // search Masternode list CMasternode* pmn = Find(mnb.outpoint); - if(pmn) { + if (pmn) { CMasternodeBroadcast mnbOld = mapSeenMasternodeBroadcast[CMasternodeBroadcast(*pmn).GetHash()].second; - if(!mnb.Update(pmn, nDos, connman)) { + if (!mnb.Update(pmn, nDos, connman)) { LogPrint("masternode", "CMasternodeMan::CheckMnbAndUpdateMasternodeList -- Update() failed, masternode=%s\n", mnb.outpoint.ToStringShort()); return false; } - if(hash != mnbOld.GetHash()) { + if (hash != mnbOld.GetHash()) { mapSeenMasternodeBroadcast.erase(mnbOld.GetHash()); } return true; } } - if(mnb.CheckOutpoint(nDos)) { + if (mnb.CheckOutpoint(nDos)) { Add(mnb); masternodeSync.BumpAssetLastTime("CMasternodeMan::CheckMnbAndUpdateMasternodeList - new"); // if it matches our Masternode privkey... - if(fMasternodeMode && mnb.keyIDOperator == activeMasternodeInfo.keyIDOperator) { + if (fMasternodeMode && mnb.keyIDOperator == activeMasternodeInfo.keyIDOperator) { mnb.nPoSeBanScore = -MASTERNODE_POSE_BAN_MAX_SCORE; - if(mnb.nProtocolVersion == PROTOCOL_VERSION) { + if (mnb.nProtocolVersion == PROTOCOL_VERSION) { // ... and PROTOCOL_VERSION, then we've been remotely activated ... LogPrintf("CMasternodeMan::CheckMnbAndUpdateMasternodeList -- Got NEW Masternode entry: masternode=%s sigTime=%lld addr=%s\n", - mnb.outpoint.ToStringShort(), mnb.sigTime, mnb.addr.ToString()); + mnb.outpoint.ToStringShort(), mnb.sigTime, mnb.addr.ToString()); legacyActiveMasternodeManager.ManageState(connman); } else { // ... otherwise we need to reactivate our node, do not add it to the list and do not relay @@ -1808,7 +1802,7 @@ void CMasternodeMan::UpdateLastPaid(const CBlockIndex* pindex) { LOCK2(cs_main, cs); - if(fLiteMode || !masternodeSync.IsWinnersListSynced() || mapMasternodes.empty()) return; + if (fLiteMode || !masternodeSync.IsWinnersListSynced() || mapMasternodes.empty()) return; static int nLastRunBlockHeight = 0; // Scan at least LAST_PAID_SCAN_BLOCKS but no more than mnpayments.GetStorageLimit() @@ -1816,7 +1810,7 @@ void CMasternodeMan::UpdateLastPaid(const CBlockIndex* pindex) nMaxBlocksToScanBack = std::min(nMaxBlocksToScanBack, mnpayments.GetStorageLimit()); LogPrint("masternode", "CMasternodeMan::UpdateLastPaid -- nCachedBlockHeight=%d, nLastRunBlockHeight=%d, nMaxBlocksToScanBack=%d\n", - nCachedBlockHeight, nLastRunBlockHeight, nMaxBlocksToScanBack); + nCachedBlockHeight, nLastRunBlockHeight, nMaxBlocksToScanBack); for (auto& mnpair : mapMasternodes) { mnpair.second.UpdateLastPaid(pindex, nMaxBlocksToScanBack); @@ -1844,7 +1838,7 @@ bool CMasternodeMan::AddGovernanceVote(const COutPoint& outpoint, uint256 nGover { LOCK(cs); CMasternode* pmn = Find(outpoint); - if(!pmn) { + if (!pmn) { return false; } pmn->AddGovernanceVote(nGovernanceObjectHash); @@ -1854,7 +1848,7 @@ bool CMasternodeMan::AddGovernanceVote(const COutPoint& outpoint, uint256 nGover void CMasternodeMan::RemoveGovernanceObject(uint256 nGovernanceObjectHash) { LOCK(cs); - for(auto& mnpair : mapMasternodes) { + for (auto& mnpair : mapMasternodes) { mnpair.second.RemoveGovernanceObject(nGovernanceObjectHash); } } @@ -1885,23 +1879,23 @@ void CMasternodeMan::SetMasternodeLastPing(const COutPoint& outpoint, const CMas if (deterministicMNManager->IsDeterministicMNsSporkActive()) return; CMasternode* pmn = Find(outpoint); - if(!pmn) { + if (!pmn) { return; } pmn->lastPing = mnp; - if(mnp.fSentinelIsCurrent) { + if (mnp.fSentinelIsCurrent) { UpdateLastSentinelPingTime(); } mapSeenMasternodePing.insert(std::make_pair(mnp.GetHash(), mnp)); CMasternodeBroadcast mnb(*pmn); uint256 hash = mnb.GetHash(); - if(mapSeenMasternodeBroadcast.count(hash)) { + if (mapSeenMasternodeBroadcast.count(hash)) { mapSeenMasternodeBroadcast[hash].second.lastPing = mnp; } } -void CMasternodeMan::UpdatedBlockTip(const CBlockIndex *pindex) +void CMasternodeMan::UpdatedBlockTip(const CBlockIndex* pindex) { nCachedBlockHeight = pindex->nHeight; LogPrint("masternode", "CMasternodeMan::UpdatedBlockTip -- nCachedBlockHeight=%d\n", nCachedBlockHeight); @@ -1911,7 +1905,7 @@ void CMasternodeMan::UpdatedBlockTip(const CBlockIndex *pindex) CheckSameAddr(); - if(fMasternodeMode) { + if (fMasternodeMode) { // normal wallet does not need to update this every block, doing update on rpc call should be enough UpdateLastPaid(pindex); } @@ -1941,11 +1935,11 @@ void CMasternodeMan::WarnMasternodeDaemonUpdates() std::string strWarning; if (nUpdatedMasternodes != size()) { strWarning = strprintf(_("Warning: At least %d of %d masternodes are running on a newer software version. Please check latest releases, you might need to update too."), - nUpdatedMasternodes, size()); + nUpdatedMasternodes, size()); } else { // someone was postponing this update for way too long probably strWarning = strprintf(_("Warning: Every masternode (out of %d known ones) is running on a newer software version. Please check latest releases, it's very likely that you missed a major/critical update."), - size()); + size()); } // notify GetWarnings(), called by Qt and the JSON-RPC code to warn the user @@ -1969,11 +1963,11 @@ void CMasternodeMan::NotifyMasternodeUpdates(CConnman& connman, bool forceAddedC fMasternodesRemovedLocal = fMasternodesRemoved; } - if(fMasternodesAddedLocal || forceAddedChecks) { + if (fMasternodesAddedLocal || forceAddedChecks) { governance.CheckMasternodeOrphanObjects(connman); governance.CheckMasternodeOrphanVotes(connman); } - if(fMasternodesRemovedLocal || forceRemovedChecks) { + if (fMasternodesRemovedLocal || forceRemovedChecks) { governance.UpdateCachesAndClean(); } @@ -1984,9 +1978,9 @@ void CMasternodeMan::NotifyMasternodeUpdates(CConnman& connman, bool forceAddedC void CMasternodeMan::DoMaintenance(CConnman& connman) { - if(fLiteMode) return; // disable all Dash specific functionality + if (fLiteMode) return; // disable all Dash specific functionality - if(!masternodeSync.IsBlockchainSynced() || ShutdownRequested()) + if (!masternodeSync.IsBlockchainSynced() || ShutdownRequested()) return; static unsigned int nTick = 0; @@ -1999,13 +1993,13 @@ void CMasternodeMan::DoMaintenance(CConnman& connman) mnodeman.ProcessPendingMnbRequests(connman); mnodeman.ProcessPendingMnvRequests(connman); - if(nTick % 60 == 0) { + if (nTick % 60 == 0) { mnodeman.ProcessMasternodeConnections(connman); mnodeman.CheckAndRemove(connman); mnodeman.WarnMasternodeDaemonUpdates(); } - if(fMasternodeMode && (nTick % (60 * 5) == 0)) { + if (fMasternodeMode && (nTick % (60 * 5) == 0)) { mnodeman.DoFullVerificationStep(connman); } } diff --git a/src/masternodeman.h b/src/masternodeman.h index 750ba90978a0..cdd470fc8b4b 100644 --- a/src/masternodeman.h +++ b/src/masternodeman.h @@ -24,20 +24,20 @@ class CMasternodeMan private: static const std::string SERIALIZATION_VERSION_STRING; - static const int DSEG_UPDATE_SECONDS = 3 * 60 * 60; + static const int DSEG_UPDATE_SECONDS = 3 * 60 * 60; static const int LAST_PAID_SCAN_BLOCKS; - static const int MIN_POSE_PROTO_VERSION = 70203; - static const int MAX_POSE_CONNECTIONS = 10; - static const int MAX_POSE_RANK = 10; - static const int MAX_POSE_BLOCKS = 10; + static const int MIN_POSE_PROTO_VERSION = 70203; + static const int MAX_POSE_CONNECTIONS = 10; + static const int MAX_POSE_RANK = 10; + static const int MAX_POSE_BLOCKS = 10; - static const int MNB_RECOVERY_QUORUM_TOTAL = 10; - static const int MNB_RECOVERY_QUORUM_REQUIRED = 6; - static const int MNB_RECOVERY_MAX_ASK_ENTRIES = 10; - static const int MNB_RECOVERY_WAIT_SECONDS = 60; - static const int MNB_RECOVERY_RETRY_SECONDS = 3 * 60 * 60; + static const int MNB_RECOVERY_QUORUM_TOTAL = 10; + static const int MNB_RECOVERY_QUORUM_REQUIRED = 6; + static const int MNB_RECOVERY_MAX_ASK_ENTRIES = 10; + static const int MNB_RECOVERY_WAIT_SECONDS = 60; + static const int MNB_RECOVERY_RETRY_SECONDS = 3 * 60 * 60; // critical section to protect the inner data structures @@ -59,9 +59,9 @@ class CMasternodeMan std::map mWeAskedForVerification; // these maps are used for masternode recovery from MASTERNODE_NEW_START_REQUIRED state - std::map > > mMnbRecoveryRequests; + std::map > > mMnbRecoveryRequests; std::map > mMnbRecoveryGoodReplies; - std::list< std::pair > listScheduledMnbRequestConnections; + std::list > listScheduledMnbRequestConnections; std::map > > mapPendingMNB; std::map > mapPendingMNV; CCriticalSection cs_mapPendingMNV; @@ -101,14 +101,14 @@ class CMasternodeMan ADD_SERIALIZE_METHODS; template - inline void SerializationOp(Stream& s, Operation ser_action) { + inline void SerializationOp(Stream& s, Operation ser_action) + { LOCK(cs); std::string strVersion; - if(ser_action.ForRead()) { + if (ser_action.ForRead()) { READWRITE(strVersion); - } - else { - strVersion = SERIALIZATION_VERSION_STRING; + } else { + strVersion = SERIALIZATION_VERSION_STRING; READWRITE(strVersion); } @@ -123,7 +123,7 @@ class CMasternodeMan READWRITE(mapSeenMasternodeBroadcast); READWRITE(mapSeenMasternodePing); - if(ser_action.ForRead() && (strVersion != SERIALIZATION_VERSION_STRING)) { + if (ser_action.ForRead() && (strVersion != SERIALIZATION_VERSION_STRING)) { Clear(); } } @@ -131,14 +131,14 @@ class CMasternodeMan CMasternodeMan(); /// Add an entry - bool Add(CMasternode &mn); + bool Add(CMasternode& mn); /// Ask (source) node for mnb - void AskForMN(CNode *pnode, const COutPoint& outpoint, CConnman& connman); + void AskForMN(CNode* pnode, const COutPoint& outpoint, CConnman& connman); - bool PoSeBan(const COutPoint &outpoint); - bool AllowMixing(const COutPoint &outpoint); - bool DisallowMixing(const COutPoint &outpoint); + bool PoSeBan(const COutPoint& outpoint); + bool AllowMixing(const COutPoint& outpoint); + bool DisallowMixing(const COutPoint& outpoint); /// Check all Masternodes void Check(); @@ -182,12 +182,12 @@ class CMasternodeMan bool GetNextMasternodeInQueueForPayment(bool fFilterSigTime, int& nCountRet, masternode_info_t& mnInfoRet); /// Find a random entry - masternode_info_t FindRandomNotInVec(const std::vector &vecToExclude, int nProtocolVersion = -1); + masternode_info_t FindRandomNotInVec(const std::vector& vecToExclude, int nProtocolVersion = -1); std::map GetFullMasternodeMap(); bool GetMasternodeRanks(rank_pair_vec_t& vecMasternodeRanksRet, int nBlockHeight = -1, int nMinProtocol = 0); - bool GetMasternodeRank(const COutPoint &outpoint, int& nRankRet, int nBlockHeight = -1, int nMinProtocol = 0); + bool GetMasternodeRank(const COutPoint& outpoint, int& nRankRet, int nBlockHeight = -1, int nMinProtocol = 0); void ProcessMasternodeConnections(CConnman& connman); std::pair > PopScheduledMnbRequestConnection(); @@ -239,7 +239,7 @@ class CMasternodeMan bool IsMasternodePingedWithin(const COutPoint& outpoint, int nSeconds, int64_t nTimeToCheckAt = -1); void SetMasternodeLastPing(const COutPoint& outpoint, const CMasternodePing& mnp); - void UpdatedBlockTip(const CBlockIndex *pindex); + void UpdatedBlockTip(const CBlockIndex* pindex); void WarnMasternodeDaemonUpdates(); @@ -249,7 +249,7 @@ class CMasternodeMan */ void NotifyMasternodeUpdates(CConnman& connman, bool forceAddedChecks = false, bool forceRemovedChecks = false); - void DoMaintenance(CConnman &connman); + void DoMaintenance(CConnman& connman); }; #endif diff --git a/src/privatesend-client.cpp b/src/privatesend-client.cpp index b3668b302e73..653c3a8777a5 100644 --- a/src/privatesend-client.cpp +++ b/src/privatesend-client.cpp @@ -3,7 +3,6 @@ // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "privatesend-client.h" -#include "wallet/coincontrol.h" #include "consensus/validation.h" #include "core_io.h" #include "init.h" @@ -15,6 +14,7 @@ #include "txmempool.h" #include "util.h" #include "utilmoneystr.h" +#include "wallet/coincontrol.h" #include @@ -22,22 +22,21 @@ CPrivateSendClientManager privateSendClient; void CPrivateSendClientManager::ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman) { - if(fMasternodeMode) return; - if(fLiteMode) return; // ignore all Dash related functionality - if(!masternodeSync.IsBlockchainSynced()) return; + if (fMasternodeMode) return; + if (fLiteMode) return; // ignore all Dash related functionality + if (!masternodeSync.IsBlockchainSynced()) return; - if(!CheckDiskSpace()) { + if (!CheckDiskSpace()) { ResetPool(); fEnablePrivateSend = false; LogPrintf("CPrivateSendClientManager::ProcessMessage -- Not enough disk space, disabling PrivateSend.\n"); return; } - if(strCommand == NetMsgType::DSQUEUE) { - if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { + if (strCommand == NetMsgType::DSQUEUE) { + if (pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrint("privatesend", "DSQUEUE -- peer=%d using obsolete version %i\n", pfrom->id, pfrom->nVersion); - connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, - strprintf("Version must be %d or greater", MIN_PRIVATESEND_PEER_PROTO_VERSION))); + connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", MIN_PRIVATESEND_PEER_PROTO_VERSION))); return; } @@ -46,11 +45,11 @@ void CPrivateSendClientManager::ProcessMessage(CNode* pfrom, const std::string& { TRY_LOCK(cs_vecqueue, lockRecv); - if(!lockRecv) return; + if (!lockRecv) return; // process every dsq only once for (const auto& q : vecDarksendQueue) { - if(q == dsq) { + if (q == dsq) { // LogPrint("privatesend", "DSQUEUE -- %s seen\n", dsq.ToString()); return; } @@ -59,19 +58,19 @@ void CPrivateSendClientManager::ProcessMessage(CNode* pfrom, const std::string& LogPrint("privatesend", "DSQUEUE -- %s new\n", dsq.ToString()); - if(dsq.IsExpired()) return; + if (dsq.IsExpired()) return; masternode_info_t infoMn; - if(!mnodeman.GetMasternodeInfo(dsq.masternodeOutpoint, infoMn)) return; + if (!mnodeman.GetMasternodeInfo(dsq.masternodeOutpoint, infoMn)) return; - if(!dsq.CheckSignature(infoMn.keyIDOperator)) { + if (!dsq.CheckSignature(infoMn.keyIDOperator)) { // we probably have outdated info mnodeman.AskForMN(pfrom, dsq.masternodeOutpoint, connman); return; } // if the queue is ready, submit if we can - if(dsq.fReady) { + if (dsq.fReady) { LOCK(cs_deqsessions); for (auto& session : deqSessions) { masternode_info_t mnMixing; @@ -84,25 +83,25 @@ void CPrivateSendClientManager::ProcessMessage(CNode* pfrom, const std::string& } else { LOCK(cs_deqsessions); // have to lock this first to avoid deadlocks with cs_vecqueue TRY_LOCK(cs_vecqueue, lockRecv); - if(!lockRecv) return; + if (!lockRecv) return; for (const auto& q : vecDarksendQueue) { - if(q.masternodeOutpoint == dsq.masternodeOutpoint) { + if (q.masternodeOutpoint == dsq.masternodeOutpoint) { // no way same mn can send another "not yet ready" dsq this soon LogPrint("privatesend", "DSQUEUE -- Masternode %s is sending WAY too many dsq messages\n", infoMn.addr.ToString()); return; } } - int nThreshold = infoMn.nLastDsq + mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION)/5; + int nThreshold = infoMn.nLastDsq + mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION) / 5; LogPrint("privatesend", "DSQUEUE -- nLastDsq: %d threshold: %d nDsqCount: %d\n", infoMn.nLastDsq, nThreshold, mnodeman.nDsqCount); //don't allow a few nodes to dominate the queuing process - if(infoMn.nLastDsq != 0 && nThreshold > mnodeman.nDsqCount) { + if (infoMn.nLastDsq != 0 && nThreshold > mnodeman.nDsqCount) { LogPrint("privatesend", "DSQUEUE -- Masternode %s is sending too many dsq messages\n", infoMn.addr.ToString()); return; } - if(!mnodeman.AllowMixing(dsq.masternodeOutpoint)) return; + if (!mnodeman.AllowMixing(dsq.masternodeOutpoint)) return; LogPrint("privatesend", "DSQUEUE -- new PrivateSend queue (%s) from masternode %s\n", dsq.ToString(), infoMn.addr.ToString()); for (auto& session : deqSessions) { @@ -118,8 +117,7 @@ void CPrivateSendClientManager::ProcessMessage(CNode* pfrom, const std::string& } else if ( strCommand == NetMsgType::DSSTATUSUPDATE || strCommand == NetMsgType::DSFINALTX || - strCommand == NetMsgType::DSCOMPLETE - ) { + strCommand == NetMsgType::DSCOMPLETE) { LOCK(cs_deqsessions); for (auto& session : deqSessions) { session.ProcessMessage(pfrom, strCommand, vRecv, connman); @@ -129,21 +127,19 @@ void CPrivateSendClientManager::ProcessMessage(CNode* pfrom, const std::string& void CPrivateSendClientSession::ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman) { - if(fMasternodeMode) return; - if(fLiteMode) return; // ignore all Dash related functionality - if(!masternodeSync.IsBlockchainSynced()) return; - - if(strCommand == NetMsgType::DSSTATUSUPDATE) { + if (fMasternodeMode) return; + if (fLiteMode) return; // ignore all Dash related functionality + if (!masternodeSync.IsBlockchainSynced()) return; - if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { + if (strCommand == NetMsgType::DSSTATUSUPDATE) { + if (pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrint("privatesend", "DSSTATUSUPDATE -- peer=%d using obsolete version %i\n", pfrom->id, pfrom->nVersion); - connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, - strprintf("Version must be %d or greater", MIN_PRIVATESEND_PEER_PROTO_VERSION))); + connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", MIN_PRIVATESEND_PEER_PROTO_VERSION))); return; } - if(!infoMixingMasternode.fInfoValid) return; - if(infoMixingMasternode.addr != pfrom->addr) { + if (!infoMixingMasternode.fInfoValid) return; + if (infoMixingMasternode.addr != pfrom->addr) { //LogPrintf("DSSTATUSUPDATE -- message doesn't match current Masternode: infoMixingMasternode %s addr %s\n", infoMixingMasternode.addr.ToString(), pfrom->addr.ToString()); return; } @@ -155,39 +151,37 @@ void CPrivateSendClientSession::ProcessMessage(CNode* pfrom, const std::string& int nMsgMessageID; vRecv >> nMsgSessionID >> nMsgState >> nMsgEntriesCount >> nMsgStatusUpdate >> nMsgMessageID; - if(nMsgState < POOL_STATE_MIN || nMsgState > POOL_STATE_MAX) { + if (nMsgState < POOL_STATE_MIN || nMsgState > POOL_STATE_MAX) { LogPrint("privatesend", "DSSTATUSUPDATE -- nMsgState is out of bounds: %d\n", nMsgState); return; } - if(nMsgStatusUpdate < STATUS_REJECTED || nMsgStatusUpdate > STATUS_ACCEPTED) { + if (nMsgStatusUpdate < STATUS_REJECTED || nMsgStatusUpdate > STATUS_ACCEPTED) { LogPrint("privatesend", "DSSTATUSUPDATE -- nMsgStatusUpdate is out of bounds: %d\n", nMsgStatusUpdate); return; } - if(nMsgMessageID < MSG_POOL_MIN || nMsgMessageID > MSG_POOL_MAX) { + if (nMsgMessageID < MSG_POOL_MIN || nMsgMessageID > MSG_POOL_MAX) { LogPrint("privatesend", "DSSTATUSUPDATE -- nMsgMessageID is out of bounds: %d\n", nMsgMessageID); return; } LogPrint("privatesend", "DSSTATUSUPDATE -- nMsgSessionID %d nMsgState: %d nEntriesCount: %d nMsgStatusUpdate: %d nMsgMessageID %d (%s)\n", - nMsgSessionID, nMsgState, nEntriesCount, nMsgStatusUpdate, nMsgMessageID, CPrivateSend::GetMessageByID(PoolMessage(nMsgMessageID))); + nMsgSessionID, nMsgState, nEntriesCount, nMsgStatusUpdate, nMsgMessageID, CPrivateSend::GetMessageByID(PoolMessage(nMsgMessageID))); - if(!CheckPoolStateUpdate(PoolState(nMsgState), nMsgEntriesCount, PoolStatusUpdate(nMsgStatusUpdate), PoolMessage(nMsgMessageID), nMsgSessionID)) { + if (!CheckPoolStateUpdate(PoolState(nMsgState), nMsgEntriesCount, PoolStatusUpdate(nMsgStatusUpdate), PoolMessage(nMsgMessageID), nMsgSessionID)) { LogPrint("privatesend", "DSSTATUSUPDATE -- CheckPoolStateUpdate failed\n"); } - } else if(strCommand == NetMsgType::DSFINALTX) { - - if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { + } else if (strCommand == NetMsgType::DSFINALTX) { + if (pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrint("privatesend", "DSFINALTX -- peer=%d using obsolete version %i\n", pfrom->id, pfrom->nVersion); - connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, - strprintf("Version must be %d or greater", MIN_PRIVATESEND_PEER_PROTO_VERSION))); + connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", MIN_PRIVATESEND_PEER_PROTO_VERSION))); return; } - if(!infoMixingMasternode.fInfoValid) return; - if(infoMixingMasternode.addr != pfrom->addr) { + if (!infoMixingMasternode.fInfoValid) return; + if (infoMixingMasternode.addr != pfrom->addr) { //LogPrintf("DSFINALTX -- message doesn't match current Masternode: infoMixingMasternode %s addr %s\n", infoMixingMasternode.addr.ToString(), pfrom->addr.ToString()); return; } @@ -196,7 +190,7 @@ void CPrivateSendClientSession::ProcessMessage(CNode* pfrom, const std::string& vRecv >> nMsgSessionID; CTransaction txNew(deserialize, vRecv); - if(nSessionID != nMsgSessionID) { + if (nSessionID != nMsgSessionID) { LogPrint("privatesend", "DSFINALTX -- message doesn't match current PrivateSend session: nSessionID: %d nMsgSessionID: %d\n", nSessionID, nMsgSessionID); return; } @@ -206,17 +200,15 @@ void CPrivateSendClientSession::ProcessMessage(CNode* pfrom, const std::string& //check to see if input is spent already? (and probably not confirmed) SignFinalTransaction(txNew, pfrom, connman); - } else if(strCommand == NetMsgType::DSCOMPLETE) { - - if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { + } else if (strCommand == NetMsgType::DSCOMPLETE) { + if (pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrint("privatesend", "DSCOMPLETE -- peer=%d using obsolete version %i\n", pfrom->id, pfrom->nVersion); - connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, - strprintf("Version must be %d or greater", MIN_PRIVATESEND_PEER_PROTO_VERSION))); + connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", MIN_PRIVATESEND_PEER_PROTO_VERSION))); return; } - if(!infoMixingMasternode.fInfoValid) return; - if(infoMixingMasternode.addr != pfrom->addr) { + if (!infoMixingMasternode.fInfoValid) return; + if (infoMixingMasternode.addr != pfrom->addr) { LogPrint("privatesend", "DSCOMPLETE -- message doesn't match current Masternode: infoMixingMasternode=%s addr=%s\n", infoMixingMasternode.addr.ToString(), pfrom->addr.ToString()); return; } @@ -225,12 +217,12 @@ void CPrivateSendClientSession::ProcessMessage(CNode* pfrom, const std::string& int nMsgMessageID; vRecv >> nMsgSessionID >> nMsgMessageID; - if(nMsgMessageID < MSG_POOL_MIN || nMsgMessageID > MSG_POOL_MAX) { + if (nMsgMessageID < MSG_POOL_MIN || nMsgMessageID > MSG_POOL_MAX) { LogPrint("privatesend", "DSCOMPLETE -- nMsgMessageID is out of bounds: %d\n", nMsgMessageID); return; } - if(nSessionID != nMsgSessionID) { + if (nSessionID != nMsgSessionID) { LogPrint("privatesend", "DSCOMPLETE -- message doesn't match current PrivateSend session: nSessionID: %d nMsgSessionID: %d\n", nSessionID, nMsgSessionID); return; } @@ -278,9 +270,12 @@ void CPrivateSendClientSession::UnlockCoins() { if (!pwalletMain) return; - while(true) { + while (true) { TRY_LOCK(pwalletMain->cs_wallet, lockWallet); - if(!lockWallet) {MilliSleep(50); continue;} + if (!lockWallet) { + MilliSleep(50); + continue; + } for (const auto& outpoint : vecOutPointLocked) pwalletMain->UnlockCoin(outpoint); break; @@ -295,46 +290,57 @@ std::string CPrivateSendClientSession::GetStatus(bool fWaitForBlock) nStatusMessageProgress += 10; std::string strSuffix = ""; - if(fWaitForBlock || !masternodeSync.IsBlockchainSynced()) + if (fWaitForBlock || !masternodeSync.IsBlockchainSynced()) return strAutoDenomResult; - switch(nState) { - case POOL_STATE_IDLE: - return _("PrivateSend is idle."); - case POOL_STATE_QUEUE: - if( nStatusMessageProgress % 70 <= 30) strSuffix = "."; - else if(nStatusMessageProgress % 70 <= 50) strSuffix = ".."; - else if(nStatusMessageProgress % 70 <= 70) strSuffix = "..."; - return strprintf(_("Submitted to masternode, waiting in queue %s"), strSuffix); - case POOL_STATE_ACCEPTING_ENTRIES: - if(nEntriesCount == 0) { + switch (nState) { + case POOL_STATE_IDLE: + return _("PrivateSend is idle."); + case POOL_STATE_QUEUE: + if (nStatusMessageProgress % 70 <= 30) + strSuffix = "."; + else if (nStatusMessageProgress % 70 <= 50) + strSuffix = ".."; + else if (nStatusMessageProgress % 70 <= 70) + strSuffix = "..."; + return strprintf(_("Submitted to masternode, waiting in queue %s"), strSuffix); + case POOL_STATE_ACCEPTING_ENTRIES: + if (nEntriesCount == 0) { + nStatusMessageProgress = 0; + return strAutoDenomResult; + } else if (fLastEntryAccepted) { + if (nStatusMessageProgress % 10 > 8) { + fLastEntryAccepted = false; nStatusMessageProgress = 0; - return strAutoDenomResult; - } else if(fLastEntryAccepted) { - if(nStatusMessageProgress % 10 > 8) { - fLastEntryAccepted = false; - nStatusMessageProgress = 0; - } - return _("PrivateSend request complete:") + " " + _("Your transaction was accepted into the pool!"); - } else { - if( nStatusMessageProgress % 70 <= 40) return strprintf(_("Submitted following entries to masternode: %u / %d"), nEntriesCount, CPrivateSend::GetMaxPoolTransactions()); - else if(nStatusMessageProgress % 70 <= 50) strSuffix = "."; - else if(nStatusMessageProgress % 70 <= 60) strSuffix = ".."; - else if(nStatusMessageProgress % 70 <= 70) strSuffix = "..."; - return strprintf(_("Submitted to masternode, waiting for more entries ( %u / %d ) %s"), nEntriesCount, CPrivateSend::GetMaxPoolTransactions(), strSuffix); } - case POOL_STATE_SIGNING: - if( nStatusMessageProgress % 70 <= 40) return _("Found enough users, signing ..."); - else if(nStatusMessageProgress % 70 <= 50) strSuffix = "."; - else if(nStatusMessageProgress % 70 <= 60) strSuffix = ".."; - else if(nStatusMessageProgress % 70 <= 70) strSuffix = "..."; - return strprintf(_("Found enough users, signing ( waiting %s )"), strSuffix); - case POOL_STATE_ERROR: - return _("PrivateSend request incomplete:") + " " + strLastMessage + " " + _("Will retry..."); - case POOL_STATE_SUCCESS: - return _("PrivateSend request complete:") + " " + strLastMessage; - default: - return strprintf(_("Unknown state: id = %u"), nState); + return _("PrivateSend request complete:") + " " + _("Your transaction was accepted into the pool!"); + } else { + if (nStatusMessageProgress % 70 <= 40) + return strprintf(_("Submitted following entries to masternode: %u / %d"), nEntriesCount, CPrivateSend::GetMaxPoolTransactions()); + else if (nStatusMessageProgress % 70 <= 50) + strSuffix = "."; + else if (nStatusMessageProgress % 70 <= 60) + strSuffix = ".."; + else if (nStatusMessageProgress % 70 <= 70) + strSuffix = "..."; + return strprintf(_("Submitted to masternode, waiting for more entries ( %u / %d ) %s"), nEntriesCount, CPrivateSend::GetMaxPoolTransactions(), strSuffix); + } + case POOL_STATE_SIGNING: + if (nStatusMessageProgress % 70 <= 40) + return _("Found enough users, signing ..."); + else if (nStatusMessageProgress % 70 <= 50) + strSuffix = "."; + else if (nStatusMessageProgress % 70 <= 60) + strSuffix = ".."; + else if (nStatusMessageProgress % 70 <= 70) + strSuffix = "..."; + return strprintf(_("Found enough users, signing ( waiting %s )"), strSuffix); + case POOL_STATE_ERROR: + return _("PrivateSend request incomplete:") + " " + strLastMessage + " " + _("Will retry..."); + case POOL_STATE_SUCCESS: + return _("PrivateSend request complete:") + " " + strLastMessage; + default: + return strprintf(_("Unknown state: id = %u"), nState); } } @@ -385,7 +391,7 @@ bool CPrivateSendClientManager::GetMixingMasternodesInfo(std::vector= 10) { + if ((nState == POOL_STATE_ERROR || nState == POOL_STATE_SUCCESS) && GetTime() - nTimeLastSuccessfulStep >= 10) { LogPrint("privatesend", "CPrivateSendClientSession::CheckPool -- timeout, RESETTING\n"); UnlockCoins(); if (nState == POOL_STATE_ERROR) { @@ -402,31 +408,31 @@ void CPrivateSendClientSession::CheckPool() // bool CPrivateSendClientSession::CheckTimeout() { - if(fMasternodeMode) return false; + if (fMasternodeMode) return false; // catching hanging sessions - 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; + 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; } int nLagTime = 10; // give the server a few extra seconds before resetting. int nTimeout = (nState == POOL_STATE_SIGNING) ? PRIVATESEND_SIGNING_TIMEOUT : PRIVATESEND_QUEUE_TIMEOUT; bool fTimeout = GetTime() - nTimeLastSuccessfulStep >= nTimeout + nLagTime; - if(nState == POOL_STATE_IDLE || !fTimeout) + if (nState == POOL_STATE_IDLE || !fTimeout) return false; LogPrint("privatesend", "CPrivateSendClientSession::CheckTimeout -- %s timed out (%ds) -- resetting\n", - (nState == POOL_STATE_SIGNING) ? "Signing" : "Session", nTimeout); + (nState == POOL_STATE_SIGNING) ? "Signing" : "Session", nTimeout); UnlockCoins(); keyHolderStorage.ReturnAll(); SetNull(); @@ -440,8 +446,8 @@ bool CPrivateSendClientSession::CheckTimeout() // void CPrivateSendClientManager::CheckTimeout() { - if(fMasternodeMode) return; - if(!fEnablePrivateSend) return; + if (fMasternodeMode) return; + if (!fEnablePrivateSend) return; CheckQueue(); @@ -457,14 +463,14 @@ void CPrivateSendClientManager::CheckTimeout() // Execute a mixing denomination via a Masternode. // This is only ran from clients // -bool CPrivateSendClientSession::SendDenominate(const std::vector< std::pair >& vecPSInOutPairsIn, CConnman& connman) +bool CPrivateSendClientSession::SendDenominate(const std::vector >& vecPSInOutPairsIn, CConnman& connman) { - if(fMasternodeMode) { + if (fMasternodeMode) { LogPrintf("CPrivateSendClientSession::SendDenominate -- PrivateSend from a Masternode is not supported currently.\n"); return false; } - if(txMyCollateral == CMutableTransaction()) { + if (txMyCollateral == CMutableTransaction()) { LogPrintf("CPrivateSendClient:SendDenominate -- PrivateSend collateral not set\n"); return false; } @@ -477,7 +483,7 @@ bool CPrivateSendClientSession::SendDenominate(const std::vector< std::pair= 0) { //might have to do this one input at a time? + if (nMyInputIndex >= 0) { //might have to do this one input at a time? int nFoundOutputsCount = 0; CAmount nValue1 = 0; CAmount nValue2 = 0; for (const auto& txoutFinal : finalMutableTransaction.vout) { - for (const auto& txout: entry.vecTxOut) { - if(txoutFinal == txout) { + for (const auto& txout : entry.vecTxOut) { + if (txoutFinal == txout) { nFoundOutputsCount++; nValue1 += txoutFinal.nValue; } @@ -624,7 +629,7 @@ bool CPrivateSendClientSession::SignFinalTransaction(const CTransaction& finalTr nValue2 += txout.nValue; int nTargetOuputsCount = entry.vecTxOut.size(); - if(nFoundOutputsCount < nTargetOuputsCount || nValue1 != nValue2) { + if (nFoundOutputsCount < nTargetOuputsCount || nValue1 != nValue2) { // in this case, something went wrong and we'll refuse to sign. It's possible we'll be charged collateral. But that's // better then signing if the transaction doesn't look like what we wanted. LogPrintf("CPrivateSendClientSession::SignFinalTransaction -- My entries are not correct! Refusing to sign: nFoundOutputsCount: %d, nTargetOuputsCount: %d\n", nFoundOutputsCount, nTargetOuputsCount); @@ -638,7 +643,7 @@ bool CPrivateSendClientSession::SignFinalTransaction(const CTransaction& finalTr const CKeyStore& keystore = *pwalletMain; LogPrint("privatesend", "CPrivateSendClientSession::SignFinalTransaction -- Signing my input %i\n", nMyInputIndex); - if(!SignSignature(keystore, prevPubKey, finalMutableTransaction, nMyInputIndex, int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))) { // changes scriptSig + if (!SignSignature(keystore, prevPubKey, finalMutableTransaction, nMyInputIndex, int(SIGHASH_ALL | SIGHASH_ANYONECANPAY))) { // changes scriptSig LogPrint("privatesend", "CPrivateSendClientSession::SignFinalTransaction -- Unable to sign my own transaction!\n"); // not sure what to do here, it will timeout...? } @@ -649,7 +654,7 @@ bool CPrivateSendClientSession::SignFinalTransaction(const CTransaction& finalTr } } - if(sigs.empty()) { + if (sigs.empty()) { LogPrintf("CPrivateSendClientSession::SignFinalTransaction -- can't sign anything!\n"); UnlockCoins(); keyHolderStorage.ReturnAll(); @@ -671,9 +676,9 @@ bool CPrivateSendClientSession::SignFinalTransaction(const CTransaction& finalTr // mixing transaction was completed (failed or successful) void CPrivateSendClientSession::CompletedTransaction(PoolMessage nMessageID) { - if(fMasternodeMode) return; + if (fMasternodeMode) return; - if(nMessageID == MSG_SUCCESS) { + if (nMessageID == MSG_SUCCESS) { LogPrintf("CompletedTransaction -- success\n"); privateSendClient.UpdatedSuccessBlock(); keyHolderStorage.KeepAll(); @@ -688,7 +693,7 @@ void CPrivateSendClientSession::CompletedTransaction(PoolMessage nMessageID) void CPrivateSendClientManager::UpdatedSuccessBlock() { - if(fMasternodeMode) return; + if (fMasternodeMode) return; nCachedLastSuccessBlock = nCachedBlockHeight; } @@ -704,10 +709,10 @@ void CPrivateSendClientManager::AddSkippedDenom(const CAmount& nDenomValue) bool CPrivateSendClientManager::WaitForAnotherBlock() { - if(!masternodeSync.IsMasternodeListSynced()) + if (!masternodeSync.IsMasternodeListSynced()) return true; - if(fPrivateSendMultiSession) + if (fPrivateSendMultiSession) return false; return nCachedBlockHeight - nCachedLastSuccessBlock < nMinBlocksToWait; @@ -722,52 +727,52 @@ bool CPrivateSendClientManager::CheckAutomaticBackup() return false; } - 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; + 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; } - if(pwalletMain->nKeysLeftSinceAutoBackup < PRIVATESEND_KEYS_THRESHOLD_STOP) { + if (pwalletMain->nKeysLeftSinceAutoBackup < PRIVATESEND_KEYS_THRESHOLD_STOP) { // We should never get here via mixing itself but probably smth else is still actively using keypool LogPrint("privatesend", "CPrivateSendClientManager::CheckAutomaticBackup -- Very low number of keys left: %d, no mixing available.\n", pwalletMain->nKeysLeftSinceAutoBackup); strAutoDenomResult = strprintf(_("Very low number of keys left: %d") + ", " + _("no mixing available."), pwalletMain->nKeysLeftSinceAutoBackup); // It's getting really dangerous, stop mixing fEnablePrivateSend = false; return false; - } else if(pwalletMain->nKeysLeftSinceAutoBackup < PRIVATESEND_KEYS_THRESHOLD_WARNING) { + } else if (pwalletMain->nKeysLeftSinceAutoBackup < PRIVATESEND_KEYS_THRESHOLD_WARNING) { // Low number of keys left but it's still more or less safe to continue LogPrint("privatesend", "CPrivateSendClientManager::CheckAutomaticBackup -- Very low number of keys left: %d\n", pwalletMain->nKeysLeftSinceAutoBackup); strAutoDenomResult = strprintf(_("Very low number of keys left: %d"), pwalletMain->nKeysLeftSinceAutoBackup); - if(fCreateAutoBackups) { + if (fCreateAutoBackups) { LogPrint("privatesend", "CPrivateSendClientManager::CheckAutomaticBackup -- Trying to create new backup.\n"); std::string warningString; std::string errorString; - if(!AutoBackupWallet(pwalletMain, "", warningString, errorString)) { - if(!warningString.empty()) { + if (!AutoBackupWallet(pwalletMain, "", warningString, errorString)) { + if (!warningString.empty()) { // There were some issues saving backup but yet more or less safe to continue LogPrintf("CPrivateSendClientManager::CheckAutomaticBackup -- WARNING! Something went wrong on automatic backup: %s\n", warningString); } - if(!errorString.empty()) { + if (!errorString.empty()) { // Things are really broken LogPrintf("CPrivateSendClientManager::CheckAutomaticBackup -- ERROR! Failed to create automatic backup: %s\n", errorString); strAutoDenomResult = strprintf(_("ERROR! Failed to create automatic backup") + ": %s", errorString); @@ -790,10 +795,10 @@ bool CPrivateSendClientManager::CheckAutomaticBackup() // bool CPrivateSendClientSession::DoAutomaticDenominating(CConnman& connman, bool fDryRun) { - if(fMasternodeMode) return false; // no client-side mixing on masternodes - if(nState != POOL_STATE_IDLE) return false; + if (fMasternodeMode) return false; // no client-side mixing on masternodes + if (nState != POOL_STATE_IDLE) return false; - if(!masternodeSync.IsMasternodeListSynced()) { + if (!masternodeSync.IsMasternodeListSynced()) { strAutoDenomResult = _("Can't mix while sync in progress."); return false; } @@ -807,118 +812,118 @@ bool CPrivateSendClientSession::DoAutomaticDenominating(CConnman& connman, bool CAmount nValueMin = CPrivateSend::GetSmallestDenomination(); { - LOCK2(cs_main, pwalletMain->cs_wallet); - - if(!fDryRun && pwalletMain->IsLocked(true)) { - strAutoDenomResult = _("Wallet is locked."); - return false; - } + LOCK2(cs_main, pwalletMain->cs_wallet); - if(GetEntriesCount() > 0) { - strAutoDenomResult = _("Mixing in progress..."); - return false; - } + if (!fDryRun && pwalletMain->IsLocked(true)) { + strAutoDenomResult = _("Wallet is locked."); + return false; + } - TRY_LOCK(cs_darksend, lockDS); - if(!lockDS) { - strAutoDenomResult = _("Lock is already in place."); - return false; - } + if (GetEntriesCount() > 0) { + strAutoDenomResult = _("Mixing in progress..."); + return false; + } - if(mnodeman.size() == 0) { - LogPrint("privatesend", "CPrivateSendClientSession::DoAutomaticDenominating -- No Masternodes detected\n"); - strAutoDenomResult = _("No Masternodes detected."); - return false; - } + TRY_LOCK(cs_darksend, lockDS); + if (!lockDS) { + strAutoDenomResult = _("Lock is already in place."); + return false; + } - // if there are no confirmed DS collateral inputs yet - if(!pwalletMain->HasCollateralInputs()) { - // should have some additional amount for them - nValueMin += CPrivateSend::GetMaxCollateralAmount(); - } + if (mnodeman.size() == 0) { + LogPrint("privatesend", "CPrivateSendClientSession::DoAutomaticDenominating -- No Masternodes detected\n"); + strAutoDenomResult = _("No Masternodes detected."); + return false; + } - // including denoms but applying some restrictions - nBalanceNeedsAnonymized = pwalletMain->GetNeedsToBeAnonymizedBalance(nValueMin); + // if there are no confirmed DS collateral inputs yet + if (!pwalletMain->HasCollateralInputs()) { + // should have some additional amount for them + nValueMin += CPrivateSend::GetMaxCollateralAmount(); + } - // 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; - } + // including denoms but applying some restrictions + nBalanceNeedsAnonymized = pwalletMain->GetNeedsToBeAnonymizedBalance(nValueMin); - // 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; - } + // 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; + } - // Initial phase, find a Masternode - // Clean if there is anything left from previous session - UnlockCoins(); - keyHolderStorage.ReturnAll(); - SetNull(); + // 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; + } - // 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."); - return false; - } + // Initial phase, find a Masternode + // Clean if there is anything left from previous session + UnlockCoins(); + keyHolderStorage.ReturnAll(); + SetNull(); - //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); + // 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."); return false; } - } 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); + + //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); return false; } + } 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; + } + } } - } } // 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 - if((privateSendClient.nLiquidityProvider || fUseQueue) && JoinExistingQueue(nBalanceNeedsAnonymized, connman)) + if ((privateSendClient.nLiquidityProvider || fUseQueue) && JoinExistingQueue(nBalanceNeedsAnonymized, connman)) return true; // do not initiate queue if we are a liquidity provider to avoid useless inter-mixing - if(privateSendClient.nLiquidityProvider) return false; + if (privateSendClient.nLiquidityProvider) return false; - if(StartNewQueue(nValueMin, nBalanceNeedsAnonymized, connman)) + if (StartNewQueue(nValueMin, nBalanceNeedsAnonymized, connman)) return true; strAutoDenomResult = _("No compatible Masternode found."); @@ -952,7 +957,7 @@ bool CPrivateSendClientManager::DoAutomaticDenominating(CConnman& connman, bool int nThreshold_low = nThreshold_high * 0.7; LogPrint("privatesend", "Checking vecMasternodesUsed: size: %d, threshold: %d\n", (int)vecMasternodesUsed.size(), nThreshold_high); - if((int)vecMasternodesUsed.size() > nThreshold_high) { + if ((int)vecMasternodesUsed.size() > nThreshold_high) { vecMasternodesUsed.erase(vecMasternodesUsed.begin(), vecMasternodesUsed.begin() + vecMasternodesUsed.size() - nThreshold_low); LogPrint("privatesend", " vecMasternodesUsed: new size: %d, threshold: %d\n", (int)vecMasternodesUsed.size(), nThreshold_high); } @@ -990,7 +995,7 @@ masternode_info_t CPrivateSendClientManager::GetNotUsedMasternode() bool CPrivateSendClientSession::JoinExistingQueue(CAmount nBalanceNeedsAnonymized, CConnman& connman) { - if (!pwalletMain) return false; + if (!pwalletMain) return false; std::vector vecStandardDenoms = CPrivateSend::GetStandardDenominations(); // Look through the queues and see if anything matches @@ -998,12 +1003,12 @@ bool CPrivateSendClientSession::JoinExistingQueue(CAmount nBalanceNeedsAnonymize while (privateSendClient.GetQueueItemAndTry(dsq)) { masternode_info_t infoMn; - if(!mnodeman.GetMasternodeInfo(dsq.masternodeOutpoint, infoMn)) { + if (!mnodeman.GetMasternodeInfo(dsq.masternodeOutpoint, infoMn)) { LogPrintf("CPrivateSendClientSession::JoinExistingQueue -- dsq masternode is not in masternode list, masternode=%s\n", dsq.masternodeOutpoint.ToStringShort()); continue; } - if(infoMn.nProtocolVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) continue; + if (infoMn.nProtocolVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) continue; // skip next mn payments winners if (mnpayments.IsScheduled(infoMn, 0)) { @@ -1012,7 +1017,7 @@ bool CPrivateSendClientSession::JoinExistingQueue(CAmount nBalanceNeedsAnonymize } std::vector vecBits; - if(!CPrivateSend::GetDenominationsBits(dsq.nDenom, vecBits)) { + if (!CPrivateSend::GetDenominationsBits(dsq.nDenom, vecBits)) { // incompatible denom continue; } @@ -1023,7 +1028,7 @@ bool CPrivateSendClientSession::JoinExistingQueue(CAmount nBalanceNeedsAnonymize LogPrint("privatesend", "CPrivateSendClientSession::JoinExistingQueue -- found valid queue: %s\n", dsq.ToString()); - std::vector< std::pair > vecPSInOutPairsTmp; + std::vector > vecPSInOutPairsTmp; CAmount nMinAmount = vecStandardDenoms[vecBits.front()]; CAmount nMaxAmount = nBalanceNeedsAnonymized; @@ -1048,7 +1053,7 @@ bool CPrivateSendClientSession::JoinExistingQueue(CAmount nBalanceNeedsAnonymize SetState(POOL_STATE_QUEUE); nTimeLastSuccessfulStep = GetTime(); LogPrintf("CPrivateSendClientSession::JoinExistingQueue -- pending connection (from queue): nSessionDenom: %d (%s), addr=%s\n", - nSessionDenom, CPrivateSend::GetDenominationsToString(nSessionDenom), infoMn.addr.ToString()); + nSessionDenom, CPrivateSend::GetDenominationsToString(nSessionDenom), infoMn.addr.ToString()); strAutoDenomResult = _("Trying to connect..."); return true; } @@ -1066,7 +1071,7 @@ bool CPrivateSendClientSession::StartNewQueue(CAmount nValueMin, CAmount nBalanc // ** find the coins we'll use std::vector vecTxIn; CAmount nValueInTmp = 0; - if(!pwalletMain->SelectCoinsDark(nValueMin, nBalanceNeedsAnonymized, vecTxIn, nValueInTmp, 0, privateSendClient.nPrivateSendRounds - 1)) { + if (!pwalletMain->SelectCoinsDark(nValueMin, nBalanceNeedsAnonymized, vecTxIn, nValueInTmp, 0, privateSendClient.nPrivateSendRounds - 1)) { // this should never happen LogPrintf("CPrivateSendClientSession::StartNewQueue -- Can't mix: no compatible inputs found!\n"); strAutoDenomResult = _("Can't mix: no compatible inputs found!"); @@ -1074,10 +1079,10 @@ bool CPrivateSendClientSession::StartNewQueue(CAmount nValueMin, CAmount nBalanc } // otherwise, try one randomly - while(nTries < 10) { + while (nTries < 10) { masternode_info_t infoMn = privateSendClient.GetNotUsedMasternode(); - if(!infoMn.fInfoValid) { + if (!infoMn.fInfoValid) { LogPrintf("CPrivateSendClientSession::StartNewQueue -- Can't find random masternode!\n"); strAutoDenomResult = _("Can't find random Masternode."); return false; @@ -1092,11 +1097,11 @@ bool CPrivateSendClientSession::StartNewQueue(CAmount nValueMin, CAmount nBalanc continue; } - if(infoMn.nLastDsq != 0 && infoMn.nLastDsq + nMnCountEnabled/5 > mnodeman.nDsqCount) { + if (infoMn.nLastDsq != 0 && infoMn.nLastDsq + nMnCountEnabled / 5 > mnodeman.nDsqCount) { LogPrintf("CPrivateSendClientSession::StartNewQueue -- Too early to mix on this masternode!" - " masternode=%s addr=%s nLastDsq=%d CountEnabled/5=%d nDsqCount=%d\n", - infoMn.outpoint.ToStringShort(), infoMn.addr.ToString(), infoMn.nLastDsq, - nMnCountEnabled/5, mnodeman.nDsqCount); + " masternode=%s addr=%s nLastDsq=%d CountEnabled/5=%d nDsqCount=%d\n", + infoMn.outpoint.ToStringShort(), infoMn.addr.ToString(), infoMn.nLastDsq, + nMnCountEnabled / 5, mnodeman.nDsqCount); nTries++; continue; } @@ -1112,7 +1117,7 @@ bool CPrivateSendClientSession::StartNewQueue(CAmount nValueMin, CAmount nBalanc std::vector vecAmounts; pwalletMain->ConvertList(vecTxIn, vecAmounts); // try to get a single random denom out of vecAmounts - while(nSessionDenom == 0) { + while (nSessionDenom == 0) { nSessionDenom = CPrivateSend::GetDenominationsByAmounts(vecAmounts); } @@ -1123,7 +1128,7 @@ bool CPrivateSendClientSession::StartNewQueue(CAmount nValueMin, CAmount nBalanc SetState(POOL_STATE_QUEUE); nTimeLastSuccessfulStep = GetTime(); LogPrintf("CPrivateSendClientSession::StartNewQueue -- pending connection, nSessionDenom: %d (%s), addr=%s\n", - nSessionDenom, CPrivateSend::GetDenominationsToString(nSessionDenom), infoMn.addr.ToString()); + nSessionDenom, CPrivateSend::GetDenominationsToString(nSessionDenom), infoMn.addr.ToString()); strAutoDenomResult = _("Trying to connect..."); return true; } @@ -1168,8 +1173,7 @@ void CPrivateSendClientManager::ProcessPendingDsaRequest(CConnman& connman) bool CPrivateSendClientSession::SubmitDenominate(CConnman& connman) { // This is just a local helper - auto GetStartRound = [](bool fMixLowest, bool fScanFromTheMiddle) -> int - { + auto GetStartRound = [](bool fMixLowest, bool fScanFromTheMiddle) -> int { if (fScanFromTheMiddle) { return privateSendClient.nPrivateSendRounds / 2; } else if (!fMixLowest) { @@ -1181,7 +1185,7 @@ bool CPrivateSendClientSession::SubmitDenominate(CConnman& connman) LOCK2(cs_main, pwalletMain->cs_wallet); std::string strError; - std::vector< std::pair > vecPSInOutPairs, vecPSInOutPairsTmp; + std::vector > vecPSInOutPairs, vecPSInOutPairsTmp; if (!SelectDenominate(strError, vecPSInOutPairs)) { LogPrintf("CPrivateSendClientSession::SubmitDenominate -- SelectDenominate failed, error: %s\n", strError); @@ -1224,7 +1228,7 @@ bool CPrivateSendClientSession::SubmitDenominate(CConnman& connman) return false; } -bool CPrivateSendClientSession::SelectDenominate(std::string& strErrorRet, std::vector< std::pair >& vecPSInOutPairsRet) +bool CPrivateSendClientSession::SelectDenominate(std::string& strErrorRet, std::vector >& vecPSInOutPairsRet) { if (!pwalletMain) { strErrorRet = "Wallet is not initialized"; @@ -1259,7 +1263,7 @@ bool CPrivateSendClientSession::SelectDenominate(std::string& strErrorRet, std:: return true; } -bool CPrivateSendClientSession::PrepareDenominate(int nMinRounds, int nMaxRounds, std::string& strErrorRet, const std::vector< std::pair >& vecPSInOutPairsIn, std::vector< std::pair >& vecPSInOutPairsRet) +bool CPrivateSendClientSession::PrepareDenominate(int nMinRounds, int nMaxRounds, std::string& strErrorRet, const std::vector >& vecPSInOutPairsIn, std::vector >& vecPSInOutPairsRet) { std::vector vecBits; if (!CPrivateSend::GetDenominationsBits(nSessionDenom, vecBits)) { @@ -1281,7 +1285,7 @@ bool CPrivateSendClientSession::PrepareDenominate(int nMinRounds, int nMaxRounds std::vector vecSteps(vecStandardDenoms.size(), 0); vecPSInOutPairsRet.clear(); - for (const auto& pair: vecPSInOutPairsIn) { + for (const auto& pair : vecPSInOutPairsIn) { if (pair.second.nRounds < nMinRounds || pair.second.nRounds > nMaxRounds) { // unlock unused coins pwalletMain->UnlockCoin(pair.first.prevout); @@ -1327,20 +1331,20 @@ bool CPrivateSendClientSession::MakeCollateralAmounts(CConnman& connman) if (!pwalletMain) return false; std::vector vecTally; - if(!pwalletMain->SelectCoinsGrouppedByAddresses(vecTally, false, false)) { + if (!pwalletMain->SelectCoinsGrouppedByAddresses(vecTally, false, false)) { LogPrint("privatesend", "CPrivateSendClientSession::MakeCollateralAmounts -- SelectCoinsGrouppedByAddresses can't find any inputs!\n"); return false; } // First try to use only non-denominated funds for (const auto& item : vecTally) { - if(!MakeCollateralAmounts(item, false, connman)) continue; + if (!MakeCollateralAmounts(item, false, connman)) continue; return true; } // There should be at least some denominated funds we should be able to break in pieces to continue mixing for (const auto& item : vecTally) { - if(!MakeCollateralAmounts(item, true, connman)) continue; + if (!MakeCollateralAmounts(item, true, connman)) continue; return true; } @@ -1357,7 +1361,7 @@ bool CPrivateSendClientSession::MakeCollateralAmounts(const CompactTallyItem& ta LOCK2(cs_main, pwalletMain->cs_wallet); // denominated input is always a single one, so we can check its amount directly and return early - if(!fTryDenominated && tallyItem.vecOutPoints.size() == 1 && CPrivateSend::IsDenominatedAmount(tallyItem.nAmount)) + if (!fTryDenominated && tallyItem.vecOutPoints.size() == 1 && CPrivateSend::IsDenominatedAmount(tallyItem.nAmount)) return false; CWalletTx wtx; @@ -1388,14 +1392,14 @@ bool CPrivateSendClientSession::MakeCollateralAmounts(const CompactTallyItem& ta coinControl.Select(outpoint); bool fSuccess = pwalletMain->CreateTransaction(vecSend, wtx, reservekeyChange, - nFeeRet, nChangePosRet, strFail, &coinControl, true, ONLY_NONDENOMINATED); - if(!fSuccess) { + nFeeRet, nChangePosRet, strFail, &coinControl, true, ONLY_NONDENOMINATED); + if (!fSuccess) { LogPrintf("CPrivateSendClientSession::MakeCollateralAmounts -- ONLY_NONDENOMINATED: %s\n", strFail); // If we failed then most likely there are not enough funds on this address. - if(fTryDenominated) { + if (fTryDenominated) { // Try to also use denominated coins (we can't mix denominated without collaterals anyway). - if(!pwalletMain->CreateTransaction(vecSend, wtx, reservekeyChange, - nFeeRet, nChangePosRet, strFail, &coinControl, true, ALL_COINS)) { + if (!pwalletMain->CreateTransaction(vecSend, wtx, reservekeyChange, + nFeeRet, nChangePosRet, strFail, &coinControl, true, ALL_COINS)) { LogPrintf("CPrivateSendClientSession::MakeCollateralAmounts -- ALL_COINS Error: %s\n", strFail); reservekeyCollateral.ReturnKey(); return false; @@ -1413,7 +1417,7 @@ bool CPrivateSendClientSession::MakeCollateralAmounts(const CompactTallyItem& ta // use the same nCachedLastSuccessBlock as for DS mixing to prevent race CValidationState state; - if(!pwalletMain->CommitTransaction(wtx, reservekeyChange, &connman, state)) { + if (!pwalletMain->CommitTransaction(wtx, reservekeyChange, &connman, state)) { LogPrintf("CPrivateSendClientSession::MakeCollateralAmounts -- CommitTransaction failed! Reason given: %s\n", state.GetRejectReason()); return false; } @@ -1431,7 +1435,7 @@ bool CPrivateSendClientSession::CreateDenominated(CConnman& connman) LOCK2(cs_main, pwalletMain->cs_wallet); std::vector vecTally; - if(!pwalletMain->SelectCoinsGrouppedByAddresses(vecTally)) { + if (!pwalletMain->SelectCoinsGrouppedByAddresses(vecTally)) { LogPrint("privatesend", "CPrivateSendClientSession::CreateDenominated -- SelectCoinsGrouppedByAddresses can't find any inputs!\n"); return false; } @@ -1439,7 +1443,7 @@ bool CPrivateSendClientSession::CreateDenominated(CConnman& connman) bool fCreateMixingCollaterals = !pwalletMain->HasCollateralInputs(); for (const auto& item : vecTally) { - if(!CreateDenominated(item, fCreateMixingCollaterals, connman)) continue; + if (!CreateDenominated(item, fCreateMixingCollaterals, connman)) continue; return true; } @@ -1458,13 +1462,13 @@ bool CPrivateSendClientSession::CreateDenominated(const CompactTallyItem& tallyI CAmount nValueLeft = tallyItem.nAmount; nValueLeft -= CPrivateSend::GetCollateralAmount(); // leave some room for fees - LogPrintf("CPrivateSendClientSession::CreateDenominated -- 0 - %s nValueLeft: %f\n", CBitcoinAddress(tallyItem.txdest).ToString(), (float)nValueLeft/COIN); + LogPrintf("CPrivateSendClientSession::CreateDenominated -- 0 - %s nValueLeft: %f\n", CBitcoinAddress(tallyItem.txdest).ToString(), (float)nValueLeft / COIN); // ****** Add an output for mixing collaterals ************ / - if(fCreateMixingCollaterals) { + if (fCreateMixingCollaterals) { CScript scriptCollateral = keyHolderStorageDenom.AddKey(pwalletMain); - vecSend.push_back((CRecipient){ scriptCollateral, CPrivateSend::GetMaxCollateralAmount(), false }); + vecSend.push_back((CRecipient){scriptCollateral, CPrivateSend::GetMaxCollateralAmount(), false}); nValueLeft -= CPrivateSend::GetMaxCollateralAmount(); } @@ -1479,20 +1483,20 @@ bool CPrivateSendClientSession::CreateDenominated(const CompactTallyItem& tallyI for (auto it = vecStandardDenoms.rbegin(); it != vecStandardDenoms.rend(); ++it) { CAmount nDenomValue = *it; - if(fSkip) { + if (fSkip) { // 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 - if(privateSendClient.IsDenomSkipped(nDenomValue)) { - strAutoDenomResult = strprintf(_("Too many %f denominations, skipping."), (float)nDenomValue/COIN); + if (privateSendClient.IsDenomSkipped(nDenomValue)) { + strAutoDenomResult = strprintf(_("Too many %f denominations, skipping."), (float)nDenomValue / COIN); LogPrintf("CPrivateSendClientSession::CreateDenominated -- %s\n", strAutoDenomResult); continue; } // find new denoms to skip if any (ignore the largest one) - if(nDenomValue != vecStandardDenoms.front() && pwalletMain->CountInputsWithAmount(nDenomValue) > DENOMS_COUNT_MAX) { - strAutoDenomResult = strprintf(_("Too many %f denominations, removing."), (float)nDenomValue/COIN); + if (nDenomValue != vecStandardDenoms.front() && pwalletMain->CountInputsWithAmount(nDenomValue) > DENOMS_COUNT_MAX) { + strAutoDenomResult = strprintf(_("Too many %f denominations, removing."), (float)nDenomValue / COIN); LogPrintf("CPrivateSendClientSession::CreateDenominated -- %s\n", strAutoDenomResult); privateSendClient.AddSkippedDenom(nDenomValue); continue; @@ -1502,25 +1506,25 @@ bool CPrivateSendClientSession::CreateDenominated(const CompactTallyItem& tallyI int nOutputs = 0; // add each output up to 11 times until it can't be added again - while(nValueLeft - nDenomValue >= 0 && nOutputs <= 10) { + while (nValueLeft - nDenomValue >= 0 && nOutputs <= 10) { CScript scriptDenom = keyHolderStorageDenom.AddKey(pwalletMain); - vecSend.push_back((CRecipient){ scriptDenom, nDenomValue, false }); + vecSend.push_back((CRecipient){scriptDenom, nDenomValue, false}); //increment outputs and subtract denomination amount nOutputs++; nValueLeft -= nDenomValue; - LogPrintf("CPrivateSendClientSession::CreateDenominated -- 1 - totalOutputs: %d, nOutputsTotal: %d, nOutputs: %d, nValueLeft: %f\n", nOutputsTotal + nOutputs, nOutputsTotal, nOutputs, (float)nValueLeft/COIN); + LogPrintf("CPrivateSendClientSession::CreateDenominated -- 1 - totalOutputs: %d, nOutputsTotal: %d, nOutputs: %d, nValueLeft: %f\n", nOutputsTotal + nOutputs, nOutputsTotal, nOutputs, (float)nValueLeft / COIN); } nOutputsTotal += nOutputs; - if(nValueLeft == 0) break; + if (nValueLeft == 0) break; } - LogPrintf("CPrivateSendClientSession::CreateDenominated -- 2 - nOutputsTotal: %d, nValueLeft: %f\n", nOutputsTotal, (float)nValueLeft/COIN); + LogPrintf("CPrivateSendClientSession::CreateDenominated -- 2 - nOutputsTotal: %d, nValueLeft: %f\n", nOutputsTotal, (float)nValueLeft / COIN); // if there were no outputs added, start over without skipping fSkip = !fSkip; } while (nOutputsTotal == 0 && !fSkip); - LogPrintf("CPrivateSendClientSession::CreateDenominated -- 3 - nOutputsTotal: %d, nValueLeft: %f\n", nOutputsTotal, (float)nValueLeft/COIN); + LogPrintf("CPrivateSendClientSession::CreateDenominated -- 3 - nOutputsTotal: %d, nValueLeft: %f\n", nOutputsTotal, (float)nValueLeft / COIN); // No reasons to create mixing collaterals if we can't create denoms to mix if (nOutputsTotal == 0) return false; @@ -1543,8 +1547,8 @@ bool CPrivateSendClientSession::CreateDenominated(const CompactTallyItem& tallyI CReserveKey reservekeyChange(pwalletMain); bool fSuccess = pwalletMain->CreateTransaction(vecSend, wtx, reservekeyChange, - nFeeRet, nChangePosRet, strFail, &coinControl, true, ONLY_NONDENOMINATED); - if(!fSuccess) { + nFeeRet, nChangePosRet, strFail, &coinControl, true, ONLY_NONDENOMINATED); + if (!fSuccess) { LogPrintf("CPrivateSendClientSession::CreateDenominated -- Error: %s\n", strFail); keyHolderStorageDenom.ReturnAll(); return false; @@ -1553,7 +1557,7 @@ bool CPrivateSendClientSession::CreateDenominated(const CompactTallyItem& tallyI keyHolderStorageDenom.KeepAll(); CValidationState state; - if(!pwalletMain->CommitTransaction(wtx, reservekeyChange, &connman, state)) { + if (!pwalletMain->CommitTransaction(wtx, reservekeyChange, &connman, state)) { LogPrintf("CPrivateSendClientSession::CreateDenominated -- CommitTransaction failed! Reason given: %s\n", state.GetRejectReason()); return false; } @@ -1567,7 +1571,7 @@ bool CPrivateSendClientSession::CreateDenominated(const CompactTallyItem& tallyI void CPrivateSendClientSession::RelayIn(const CDarkSendEntry& entry, CConnman& connman) { - if(!infoMixingMasternode.fInfoValid) return; + if (!infoMixingMasternode.fInfoValid) return; connman.ForNode(infoMixingMasternode.addr, [&entry, &connman](CNode* pnode) { LogPrintf("CPrivateSendClientSession::RelayIn -- found master, relaying message to %s\n", pnode->addr.ToString()); @@ -1583,19 +1587,18 @@ void CPrivateSendClientSession::SetState(PoolState nStateNew) nState = nStateNew; } -void CPrivateSendClientManager::UpdatedBlockTip(const CBlockIndex *pindex) +void CPrivateSendClientManager::UpdatedBlockTip(const CBlockIndex* pindex) { nCachedBlockHeight = pindex->nHeight; LogPrint("privatesend", "CPrivateSendClientManager::UpdatedBlockTip -- nCachedBlockHeight: %d\n", nCachedBlockHeight); - } void CPrivateSendClientManager::DoMaintenance(CConnman& connman) { - if(fLiteMode) return; // disable all Dash specific functionality - if(fMasternodeMode) return; // no client-side mixing on masternodes + if (fLiteMode) return; // disable all Dash specific functionality + if (fMasternodeMode) return; // no client-side mixing on masternodes - if(!masternodeSync.IsBlockchainSynced() || ShutdownRequested()) + if (!masternodeSync.IsBlockchainSynced() || ShutdownRequested()) return; static unsigned int nTick = 0; @@ -1604,7 +1607,7 @@ void CPrivateSendClientManager::DoMaintenance(CConnman& connman) nTick++; CheckTimeout(); ProcessPendingDsaRequest(connman); - if(nDoAutoNextRun == nTick) { + if (nDoAutoNextRun == nTick) { DoAutomaticDenominating(connman); nDoAutoNextRun = nTick + PRIVATESEND_AUTO_TIMEOUT_MIN + GetRandInt(PRIVATESEND_AUTO_TIMEOUT_MAX - PRIVATESEND_AUTO_TIMEOUT_MIN); } diff --git a/src/privatesend-client.h b/src/privatesend-client.h index c63f39754096..e0e7a4c50cba 100644 --- a/src/privatesend-client.h +++ b/src/privatesend-client.h @@ -6,35 +6,35 @@ #define PRIVATESENDCLIENT_H #include "masternode.h" +#include "privatesend-util.h" #include "privatesend.h" #include "wallet/wallet.h" -#include "privatesend-util.h" class CPrivateSendClientManager; class CConnman; -static const int DENOMS_COUNT_MAX = 100; +static const int DENOMS_COUNT_MAX = 100; -static const int MIN_PRIVATESEND_SESSIONS = 1; -static const int MIN_PRIVATESEND_ROUNDS = 2; -static const int MIN_PRIVATESEND_AMOUNT = 2; -static const int MIN_PRIVATESEND_LIQUIDITY = 0; -static const int MAX_PRIVATESEND_SESSIONS = 10; -static const int MAX_PRIVATESEND_ROUNDS = 16; -static const int MAX_PRIVATESEND_AMOUNT = MAX_MONEY / COIN; -static const int MAX_PRIVATESEND_LIQUIDITY = 100; -static const int DEFAULT_PRIVATESEND_SESSIONS = 4; -static const int DEFAULT_PRIVATESEND_ROUNDS = 4; -static const int DEFAULT_PRIVATESEND_AMOUNT = 1000; -static const int DEFAULT_PRIVATESEND_LIQUIDITY = 0; +static const int MIN_PRIVATESEND_SESSIONS = 1; +static const int MIN_PRIVATESEND_ROUNDS = 2; +static const int MIN_PRIVATESEND_AMOUNT = 2; +static const int MIN_PRIVATESEND_LIQUIDITY = 0; +static const int MAX_PRIVATESEND_SESSIONS = 10; +static const int MAX_PRIVATESEND_ROUNDS = 16; +static const int MAX_PRIVATESEND_AMOUNT = MAX_MONEY / COIN; +static const int MAX_PRIVATESEND_LIQUIDITY = 100; +static const int DEFAULT_PRIVATESEND_SESSIONS = 4; +static const int DEFAULT_PRIVATESEND_ROUNDS = 4; +static const int DEFAULT_PRIVATESEND_AMOUNT = 1000; +static const int DEFAULT_PRIVATESEND_LIQUIDITY = 0; -static const bool DEFAULT_PRIVATESEND_MULTISESSION = false; +static const bool DEFAULT_PRIVATESEND_MULTISESSION = false; // Warn user if mixing in gui or try to create backup if mixing in daemon mode // when we have only this many keys left static const int PRIVATESEND_KEYS_THRESHOLD_WARNING = 100; // Stop mixing completely, it's too dangerous to continue when we have only this many keys left -static const int PRIVATESEND_KEYS_THRESHOLD_STOP = 50; +static const int PRIVATESEND_KEYS_THRESHOLD_STOP = 50; // The main object for accessing mixing extern CPrivateSendClientManager privateSendClient; @@ -49,17 +49,19 @@ class CPendingDsaRequest int64_t nTimeCreated; public: - CPendingDsaRequest(): + CPendingDsaRequest() : addr(CService()), dsa(CDarksendAccept()), nTimeCreated(0) - {} + { + } - CPendingDsaRequest(const CService& addr_, const CDarksendAccept& dsa_): + CPendingDsaRequest(const CService& addr_, const CDarksendAccept& dsa_) : addr(addr_), dsa(dsa_), nTimeCreated(GetTime()) - {} + { + } CService GetAddr() { return addr; } CDarksendAccept GetDSA() { return dsa; } @@ -108,14 +110,14 @@ class CPrivateSendClientSession : public CPrivateSendBaseSession bool StartNewQueue(CAmount nValueMin, CAmount nBalanceNeedsAnonymized, CConnman& connman); /// step 0: select denominated inputs and txouts - bool SelectDenominate(std::string& strErrorRet, std::vector< std::pair >& vecPSInOutPairsRet); + bool SelectDenominate(std::string& strErrorRet, std::vector >& vecPSInOutPairsRet); /// step 1: prepare denominated inputs and outputs - bool PrepareDenominate(int nMinRounds, int nMaxRounds, std::string& strErrorRet, const std::vector< std::pair >& vecPSInOutPairsIn, std::vector< std::pair >& vecPSInOutPairsRet); + bool PrepareDenominate(int nMinRounds, int nMaxRounds, std::string& strErrorRet, const std::vector >& vecPSInOutPairsIn, std::vector >& vecPSInOutPairsRet); /// step 2: send denominated inputs and outputs prepared in step 1 - bool SendDenominate(const std::vector< std::pair >& vecPSInOutPairsIn, CConnman& connman); + bool SendDenominate(const std::vector >& vecPSInOutPairsIn, CConnman& connman); /// Get Masternode updates about the progress of mixing - bool CheckPoolStateUpdate(PoolState nStateNew, int nEntriesCountNew, PoolStatusUpdate nStatusUpdate, PoolMessage nMessageID, int nSessionIDNew=0); + bool CheckPoolStateUpdate(PoolState nStateNew, int nEntriesCountNew, PoolStatusUpdate nStatusUpdate, PoolMessage nMessageID, int nSessionIDNew = 0); // Set the 'state' value, with some logging and capturing when the state changed void SetState(PoolState nStateNew); @@ -141,7 +143,8 @@ class CPrivateSendClientSession : public CPrivateSendBaseSession txMyCollateral(), pendingDsaRequest(), keyHolderStorage() - {} + { + } void ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman); @@ -154,7 +157,7 @@ class CPrivateSendClientSession : public CPrivateSendBaseSession bool GetMixingMasternodeInfo(masternode_info_t& mnInfoRet) const; /// Passively run mixing in the background according to the configuration in settings - bool DoAutomaticDenominating(CConnman& connman, bool fDryRun=false); + bool DoAutomaticDenominating(CConnman& connman, bool fDryRun = false); /// As a client, submit part of a future mixing transaction to a Masternode to start the process bool SubmitDenominate(CConnman& connman); @@ -198,7 +201,7 @@ class CPrivateSendClientManager : public CPrivateSendBaseManager bool fEnablePrivateSend; bool fPrivateSendMultiSession; - int nCachedNumBlocks; //used for the overview screen + int nCachedNumBlocks; //used for the overview screen bool fCreateAutoBackups; //builtin support for automatic backups CPrivateSendClientManager() : @@ -216,7 +219,8 @@ class CPrivateSendClientManager : public CPrivateSendBaseManager fPrivateSendMultiSession(DEFAULT_PRIVATESEND_MULTISESSION), nCachedNumBlocks(std::numeric_limits::max()), fCreateAutoBackups(true) - {} + { + } void ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman); @@ -234,7 +238,7 @@ class CPrivateSendClientManager : public CPrivateSendBaseManager bool GetMixingMasternodesInfo(std::vector& vecMnInfoRet) const; /// Passively run mixing in the background according to the configuration in settings - bool DoAutomaticDenominating(CConnman& connman, bool fDryRun=false); + bool DoAutomaticDenominating(CConnman& connman, bool fDryRun = false); void CheckTimeout(); @@ -245,7 +249,7 @@ class CPrivateSendClientManager : public CPrivateSendBaseManager void UpdatedSuccessBlock(); - void UpdatedBlockTip(const CBlockIndex *pindex); + void UpdatedBlockTip(const CBlockIndex* pindex); void DoMaintenance(CConnman& connman); }; diff --git a/src/privatesend-server.cpp b/src/privatesend-server.cpp index 4f7b76a38fdc..23d5ca2da91f 100644 --- a/src/privatesend-server.cpp +++ b/src/privatesend-server.cpp @@ -19,21 +19,19 @@ CPrivateSendServer privateSendServer; void CPrivateSendServer::ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman) { - if(!fMasternodeMode) return; - if(fLiteMode) return; // ignore all Dash related functionality - if(!masternodeSync.IsBlockchainSynced()) return; - - if(strCommand == NetMsgType::DSACCEPT) { + if (!fMasternodeMode) return; + if (fLiteMode) return; // ignore all Dash related functionality + if (!masternodeSync.IsBlockchainSynced()) return; - if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { + if (strCommand == NetMsgType::DSACCEPT) { + if (pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrint("privatesend", "DSACCEPT -- peer=%d using obsolete version %i\n", pfrom->id, pfrom->nVersion); - connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, - strprintf("Version must be %d or greater", MIN_PRIVATESEND_PEER_PROTO_VERSION))); + connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", MIN_PRIVATESEND_PEER_PROTO_VERSION))); PushStatus(pfrom, STATUS_REJECTED, ERR_VERSION, connman); return; } - if(IsSessionReady()) { + if (IsSessionReady()) { // too many users in this session already, reject new ones LogPrintf("DSACCEPT -- queue is already full!\n"); PushStatus(pfrom, STATUS_ACCEPTED, ERR_QUEUE_FULL, connman); @@ -46,14 +44,13 @@ void CPrivateSendServer::ProcessMessage(CNode* pfrom, const std::string& strComm LogPrint("privatesend", "DSACCEPT -- nDenom %d (%s) txCollateral %s", dsa.nDenom, CPrivateSend::GetDenominationsToString(dsa.nDenom), dsa.txCollateral.ToString()); masternode_info_t mnInfo; - if(!mnodeman.GetMasternodeInfo(activeMasternodeInfo.outpoint, mnInfo)) { + if (!mnodeman.GetMasternodeInfo(activeMasternodeInfo.outpoint, mnInfo)) { PushStatus(pfrom, STATUS_REJECTED, ERR_MN_LIST, connman); return; } - if(vecSessionCollaterals.size() == 0 && mnInfo.nLastDsq != 0 && - mnInfo.nLastDsq + mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION)/5 > mnodeman.nDsqCount) - { + if (vecSessionCollaterals.size() == 0 && mnInfo.nLastDsq != 0 && + mnInfo.nLastDsq + mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION) / 5 > mnodeman.nDsqCount) { LogPrintf("DSACCEPT -- last dsq too recent, must wait: addr=%s\n", pfrom->addr.ToString()); PushStatus(pfrom, STATUS_REJECTED, ERR_RECENT, connman); return; @@ -61,9 +58,9 @@ void CPrivateSendServer::ProcessMessage(CNode* pfrom, const std::string& strComm PoolMessage nMessageID = MSG_NOERR; - bool fResult = nSessionID == 0 ? CreateNewSession(dsa, nMessageID, connman) - : AddUserToExistingSession(dsa, nMessageID); - if(fResult) { + bool fResult = nSessionID == 0 ? CreateNewSession(dsa, nMessageID, connman) + : AddUserToExistingSession(dsa, nMessageID); + if (fResult) { LogPrintf("DSACCEPT -- is compatible, please submit!\n"); PushStatus(pfrom, STATUS_ACCEPTED, nMessageID, connman); return; @@ -73,14 +70,13 @@ void CPrivateSendServer::ProcessMessage(CNode* pfrom, const std::string& strComm return; } - } else if(strCommand == NetMsgType::DSQUEUE) { + } else if (strCommand == NetMsgType::DSQUEUE) { TRY_LOCK(cs_vecqueue, lockRecv); - if(!lockRecv) return; + if (!lockRecv) return; - if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { + if (pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrint("privatesend", "DSQUEUE -- peer=%d using obsolete version %i\n", pfrom->id, pfrom->nVersion); - connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, - strprintf("Version must be %d or greater", MIN_PRIVATESEND_PEER_PROTO_VERSION))); + connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", MIN_PRIVATESEND_PEER_PROTO_VERSION))); return; } @@ -89,7 +85,7 @@ void CPrivateSendServer::ProcessMessage(CNode* pfrom, const std::string& strComm // process every dsq only once for (const auto& q : vecDarksendQueue) { - if(q == dsq) { + if (q == dsq) { // LogPrint("privatesend", "DSQUEUE -- %s seen\n", dsq.ToString()); return; } @@ -97,30 +93,30 @@ void CPrivateSendServer::ProcessMessage(CNode* pfrom, const std::string& strComm LogPrint("privatesend", "DSQUEUE -- %s new\n", dsq.ToString()); - if(dsq.IsExpired()) return; + if (dsq.IsExpired()) return; masternode_info_t mnInfo; - if(!mnodeman.GetMasternodeInfo(dsq.masternodeOutpoint, mnInfo)) return; + if (!mnodeman.GetMasternodeInfo(dsq.masternodeOutpoint, mnInfo)) return; - if(!dsq.CheckSignature(mnInfo.keyIDOperator)) { + if (!dsq.CheckSignature(mnInfo.keyIDOperator)) { // we probably have outdated info mnodeman.AskForMN(pfrom, dsq.masternodeOutpoint, connman); return; } - if(!dsq.fReady) { + if (!dsq.fReady) { for (const auto& q : vecDarksendQueue) { - if(q.masternodeOutpoint == dsq.masternodeOutpoint) { + if (q.masternodeOutpoint == dsq.masternodeOutpoint) { // no way same mn can send another "not yet ready" dsq this soon LogPrint("privatesend", "DSQUEUE -- Masternode %s is sending WAY too many dsq messages\n", mnInfo.addr.ToString()); return; } } - int nThreshold = mnInfo.nLastDsq + mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION)/5; + int nThreshold = mnInfo.nLastDsq + mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION) / 5; LogPrint("privatesend", "DSQUEUE -- nLastDsq: %d threshold: %d nDsqCount: %d\n", mnInfo.nLastDsq, nThreshold, mnodeman.nDsqCount); //don't allow a few nodes to dominate the queuing process - if(mnInfo.nLastDsq != 0 && nThreshold > mnodeman.nDsqCount) { + if (mnInfo.nLastDsq != 0 && nThreshold > mnodeman.nDsqCount) { LogPrint("privatesend", "DSQUEUE -- Masternode %s is sending too many dsq messages\n", mnInfo.addr.ToString()); return; } @@ -131,18 +127,16 @@ void CPrivateSendServer::ProcessMessage(CNode* pfrom, const std::string& strComm dsq.Relay(connman); } - } else if(strCommand == NetMsgType::DSVIN) { - - if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { + } else if (strCommand == NetMsgType::DSVIN) { + if (pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrint("privatesend", "DSVIN -- peer=%d using obsolete version %i\n", pfrom->id, pfrom->nVersion); - connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, - strprintf("Version must be %d or greater", MIN_PRIVATESEND_PEER_PROTO_VERSION))); + connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", MIN_PRIVATESEND_PEER_PROTO_VERSION))); PushStatus(pfrom, STATUS_REJECTED, ERR_VERSION, connman); return; } //do we have enough users in the current session? - if(!IsSessionReady()) { + if (!IsSessionReady()) { LogPrintf("DSVIN -- session not complete!\n"); PushStatus(pfrom, STATUS_REJECTED, ERR_SESSION, connman); return; @@ -153,20 +147,20 @@ void CPrivateSendServer::ProcessMessage(CNode* pfrom, const std::string& strComm LogPrint("privatesend", "DSVIN -- txCollateral %s", entry.txCollateral->ToString()); - if(entry.vecTxDSIn.size() > PRIVATESEND_ENTRY_MAX_SIZE) { + if (entry.vecTxDSIn.size() > PRIVATESEND_ENTRY_MAX_SIZE) { LogPrintf("DSVIN -- ERROR: too many inputs! %d/%d\n", entry.vecTxDSIn.size(), PRIVATESEND_ENTRY_MAX_SIZE); PushStatus(pfrom, STATUS_REJECTED, ERR_MAXIMUM, connman); return; } - if(entry.vecTxOut.size() > PRIVATESEND_ENTRY_MAX_SIZE) { + if (entry.vecTxOut.size() > PRIVATESEND_ENTRY_MAX_SIZE) { LogPrintf("DSVIN -- ERROR: too many outputs! %d/%d\n", entry.vecTxOut.size(), PRIVATESEND_ENTRY_MAX_SIZE); PushStatus(pfrom, STATUS_REJECTED, ERR_MAXIMUM, connman); return; } //do we have the same denominations as the current session? - if(!IsOutputsCompatibleWithSessionDenom(entry.vecTxOut)) { + if (!IsOutputsCompatibleWithSessionDenom(entry.vecTxOut)) { LogPrintf("DSVIN -- not compatible with existing transactions!\n"); PushStatus(pfrom, STATUS_REJECTED, ERR_EXISTING_TX, connman); return; @@ -183,12 +177,12 @@ void CPrivateSendServer::ProcessMessage(CNode* pfrom, const std::string& strComm nValueOut += txout.nValue; tx.vout.push_back(txout); - if(txout.scriptPubKey.size() != 25) { + if (txout.scriptPubKey.size() != 25) { LogPrintf("DSVIN -- non-standard pubkey detected! scriptPubKey=%s\n", ScriptToAsmStr(txout.scriptPubKey)); PushStatus(pfrom, STATUS_REJECTED, ERR_NON_STANDARD_PUBKEY, connman); return; } - if(!txout.scriptPubKey.IsPayToPublicKeyHash()) { + if (!txout.scriptPubKey.IsPayToPublicKeyHash()) { LogPrintf("DSVIN -- invalid script! scriptPubKey=%s\n", ScriptToAsmStr(txout.scriptPubKey)); PushStatus(pfrom, STATUS_REJECTED, ERR_INVALID_SCRIPT, connman); return; @@ -201,7 +195,7 @@ void CPrivateSendServer::ProcessMessage(CNode* pfrom, const std::string& strComm LogPrint("privatesend", "DSVIN -- txin=%s\n", txin.ToString()); Coin coin; - if(GetUTXOCoin(txin.prevout, coin)) { + if (GetUTXOCoin(txin.prevout, coin)) { nValueIn += coin.out.nValue; } else { LogPrintf("DSVIN -- missing input! txin=%s\n", txin.ToString()); @@ -212,7 +206,7 @@ void CPrivateSendServer::ProcessMessage(CNode* pfrom, const std::string& strComm // There should be no fee in mixing tx CAmount nFee = nValueIn - nValueOut; - if(nFee != 0) { + if (nFee != 0) { LogPrintf("DSVIN -- there should be no fee in mixing tx! fees: %lld, tx=%s", nFee, tx.ToString()); PushStatus(pfrom, STATUS_REJECTED, ERR_FEES, connman); return; @@ -222,7 +216,7 @@ void CPrivateSendServer::ProcessMessage(CNode* pfrom, const std::string& strComm PoolMessage nMessageID = MSG_NOERR; entry.addr = pfrom->addr; - if(AddEntry(entry, nMessageID)) { + if (AddEntry(entry, nMessageID)) { PushStatus(pfrom, STATUS_ACCEPTED, nMessageID, connman); CheckPool(connman); RelayStatus(STATUS_ACCEPTED, connman); @@ -231,12 +225,10 @@ void CPrivateSendServer::ProcessMessage(CNode* pfrom, const std::string& strComm SetNull(); } - } else if(strCommand == NetMsgType::DSSIGNFINALTX) { - - if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { + } else if (strCommand == NetMsgType::DSSIGNFINALTX) { + if (pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrint("privatesend", "DSSIGNFINALTX -- peer=%d using obsolete version %i\n", pfrom->id, pfrom->nVersion); - connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, - strprintf("Version must be %d or greater", MIN_PRIVATESEND_PEER_PROTO_VERSION))); + connman.PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", MIN_PRIVATESEND_PEER_PROTO_VERSION))); return; } @@ -250,7 +242,7 @@ void CPrivateSendServer::ProcessMessage(CNode* pfrom, const std::string& strComm for (const auto& txin : vecTxIn) { nTxInIndex++; - if(!AddScriptSig(txin)) { + if (!AddScriptSig(txin)) { LogPrint("privatesend", "DSSIGNFINALTX -- AddScriptSig() failed at %d/%d, session: %d\n", nTxInIndex, nTxInsCount, nSessionID); RelayStatus(STATUS_REJECTED, connman); return; @@ -302,7 +294,7 @@ void CPrivateSendServer::CreateFinalTransaction(CConnman& connman) CMutableTransaction txNew; // make our new transaction - for(int i = 0; i < GetEntriesCount(); i++) { + for (int i = 0; i < GetEntriesCount(); i++) { for (const auto& txout : vecEntries[i].vecTxOut) txNew.vout.push_back(txout); @@ -323,7 +315,7 @@ void CPrivateSendServer::CreateFinalTransaction(CConnman& connman) void CPrivateSendServer::CommitFinalTransaction(CConnman& connman) { - if(!fMasternodeMode) return; // check and relay final tx only on masternode + if (!fMasternodeMode) return; // check and relay final tx only on masternode CTransactionRef finalTransaction = MakeTransactionRef(finalMutableTransaction); uint256 hashTx = finalTransaction->GetHash(); @@ -334,9 +326,8 @@ void CPrivateSendServer::CommitFinalTransaction(CConnman& connman) // See if the transaction is valid TRY_LOCK(cs_main, lockMain); CValidationState validationState; - mempool.PrioritiseTransaction(hashTx, hashTx.ToString(), 1000, 0.1*COIN); - if(!lockMain || !AcceptToMemoryPool(mempool, validationState, finalTransaction, false, NULL, false, maxTxFee, true)) - { + mempool.PrioritiseTransaction(hashTx, hashTx.ToString(), 1000, 0.1 * COIN); + if (!lockMain || !AcceptToMemoryPool(mempool, validationState, finalTransaction, false, NULL, false, maxTxFee, true)) { LogPrintf("CPrivateSendServer::CommitFinalTransaction -- AcceptToMemoryPool() error: Transaction not valid\n"); SetNull(); // not much we can do in this case, just notify clients @@ -348,7 +339,7 @@ void CPrivateSendServer::CommitFinalTransaction(CConnman& connman) LogPrintf("CPrivateSendServer::CommitFinalTransaction -- CREATING DSTX\n"); // create and sign masternode dstx transaction - if(!CPrivateSend::GetDSTX(hashTx)) { + if (!CPrivateSend::GetDSTX(hashTx)) { CDarksendBroadcastTx dstxNew(finalTransaction, activeMasternodeInfo.outpoint, GetAdjustedTime()); dstxNew.Sign(); CPrivateSend::AddDSTX(dstxNew); @@ -384,33 +375,33 @@ void CPrivateSendServer::CommitFinalTransaction(CConnman& connman) // void CPrivateSendServer::ChargeFees(CConnman& connman) { - if(!fMasternodeMode) return; + if (!fMasternodeMode) return; //we don't need to charge collateral for every offence. - if(GetRandInt(100) > 33) return; + if (GetRandInt(100) > 33) return; std::vector vecOffendersCollaterals; - if(nState == POOL_STATE_ACCEPTING_ENTRIES) { + if (nState == POOL_STATE_ACCEPTING_ENTRIES) { for (const auto& txCollateral : vecSessionCollaterals) { bool fFound = false; for (const auto& entry : vecEntries) - if(*entry.txCollateral == *txCollateral) + if (*entry.txCollateral == *txCollateral) fFound = true; // This queue entry didn't send us the promised transaction - if(!fFound) { + if (!fFound) { LogPrintf("CPrivateSendServer::ChargeFees -- found uncooperative node (didn't send transaction), found offence\n"); vecOffendersCollaterals.push_back(txCollateral); } } } - if(nState == POOL_STATE_SIGNING) { + if (nState == POOL_STATE_SIGNING) { // who didn't sign? for (const auto& entry : vecEntries) { for (const auto& txdsin : entry.vecTxDSIn) { - if(!txdsin.fHasSig) { + if (!txdsin.fHasSig) { LogPrintf("CPrivateSendServer::ChargeFees -- found uncooperative node (didn't sign), found offence\n"); vecOffendersCollaterals.push_back(entry.txCollateral); } @@ -419,25 +410,25 @@ void CPrivateSendServer::ChargeFees(CConnman& connman) } // no offences found - if(vecOffendersCollaterals.empty()) return; + if (vecOffendersCollaterals.empty()) return; //mostly offending? Charge sometimes - if((int)vecOffendersCollaterals.size() >= Params().PoolMaxTransactions() - 1 && GetRandInt(100) > 33) return; + if ((int)vecOffendersCollaterals.size() >= Params().PoolMaxTransactions() - 1 && GetRandInt(100) > 33) return; //everyone is an offender? That's not right - if((int)vecOffendersCollaterals.size() >= Params().PoolMaxTransactions()) return; + if ((int)vecOffendersCollaterals.size() >= Params().PoolMaxTransactions()) return; //charge one of the offenders randomly std::random_shuffle(vecOffendersCollaterals.begin(), vecOffendersCollaterals.end()); - if(nState == POOL_STATE_ACCEPTING_ENTRIES || nState == POOL_STATE_SIGNING) { + if (nState == POOL_STATE_ACCEPTING_ENTRIES || nState == POOL_STATE_SIGNING) { LogPrintf("CPrivateSendServer::ChargeFees -- found uncooperative node (didn't %s transaction), charging fees: %s", - (nState == POOL_STATE_SIGNING) ? "sign" : "send", vecOffendersCollaterals[0]->ToString()); + (nState == POOL_STATE_SIGNING) ? "sign" : "send", vecOffendersCollaterals[0]->ToString()); LOCK(cs_main); CValidationState state; - if(!AcceptToMemoryPool(mempool, state, vecOffendersCollaterals[0], false, NULL, false, maxTxFee)) { + if (!AcceptToMemoryPool(mempool, state, vecOffendersCollaterals[0], false, NULL, false, maxTxFee)) { // should never really happen LogPrintf("CPrivateSendServer::ChargeFees -- ERROR: AcceptToMemoryPool failed!\n"); } else { @@ -460,16 +451,16 @@ void CPrivateSendServer::ChargeFees(CConnman& connman) */ void CPrivateSendServer::ChargeRandomFees(CConnman& connman) { - if(!fMasternodeMode) return; + if (!fMasternodeMode) return; LOCK(cs_main); for (const auto& txCollateral : vecSessionCollaterals) { - if(GetRandInt(100) > 10) return; + if (GetRandInt(100) > 10) return; LogPrintf("CPrivateSendServer::ChargeRandomFees -- charging random fees, txCollateral=%s", txCollateral->ToString()); CValidationState state; - if(!AcceptToMemoryPool(mempool, state, txCollateral, false, NULL, false, maxTxFee)) { + if (!AcceptToMemoryPool(mempool, state, txCollateral, false, NULL, false, maxTxFee)) { // should never really happen LogPrintf("CPrivateSendServer::ChargeRandomFees -- ERROR: AcceptToMemoryPool failed!\n"); } else { @@ -483,16 +474,16 @@ void CPrivateSendServer::ChargeRandomFees(CConnman& connman) // void CPrivateSendServer::CheckTimeout(CConnman& connman) { - if(!fMasternodeMode) return; + if (!fMasternodeMode) return; CheckQueue(); int nTimeout = (nState == POOL_STATE_SIGNING) ? PRIVATESEND_SIGNING_TIMEOUT : PRIVATESEND_QUEUE_TIMEOUT; bool fTimeout = GetTime() - nTimeLastSuccessfulStep >= nTimeout; - if(nState != POOL_STATE_IDLE && fTimeout) { + if (nState != POOL_STATE_IDLE && fTimeout) { LogPrint("privatesend", "CPrivateSendServer::CheckTimeout -- %s timed out (%ds) -- resetting\n", - (nState == POOL_STATE_SIGNING) ? "Signing" : "Session", nTimeout); + (nState == POOL_STATE_SIGNING) ? "Signing" : "Session", nTimeout); ChargeFees(connman); SetNull(); } @@ -505,9 +496,9 @@ void CPrivateSendServer::CheckTimeout(CConnman& connman) */ void CPrivateSendServer::CheckForCompleteQueue(CConnman& connman) { - if(!fMasternodeMode) return; + if (!fMasternodeMode) return; - if(nState == POOL_STATE_QUEUE && IsSessionReady()) { + if (nState == POOL_STATE_QUEUE && IsSessionReady()) { SetState(POOL_STATE_ACCEPTING_ENTRIES); CDarksendQueue dsq(nSessionDenom, activeMasternodeInfo.outpoint, GetAdjustedTime(), true); @@ -529,14 +520,13 @@ bool CPrivateSendServer::IsInputScriptSigValid(const CTxIn& txin) CScript sigPubKey = CScript(); for (const auto& entry : vecEntries) { - for (const auto& txout : entry.vecTxOut) txNew.vout.push_back(txout); for (const auto& txdsin : entry.vecTxDSIn) { txNew.vin.push_back(txdsin); - if(txdsin.prevout == txin.prevout) { + if (txdsin.prevout == txin.prevout) { nTxInIndex = i; sigPubKey = txdsin.prevPubKey; } @@ -544,10 +534,10 @@ bool CPrivateSendServer::IsInputScriptSigValid(const CTxIn& txin) } } - if(nTxInIndex >= 0) { //might have to do this one input at a time? + if (nTxInIndex >= 0) { //might have to do this one input at a time? txNew.vin[nTxInIndex].scriptSig = txin.scriptSig; - LogPrint("privatesend", "CPrivateSendServer::IsInputScriptSigValid -- verifying scriptSig %s\n", ScriptToAsmStr(txin.scriptSig).substr(0,24)); - if(!VerifyScript(txNew.vin[nTxInIndex].scriptSig, sigPubKey, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, MutableTransactionSignatureChecker(&txNew, nTxInIndex))) { + LogPrint("privatesend", "CPrivateSendServer::IsInputScriptSigValid -- verifying scriptSig %s\n", ScriptToAsmStr(txin.scriptSig).substr(0, 24)); + if (!VerifyScript(txNew.vin[nTxInIndex].scriptSig, sigPubKey, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, MutableTransactionSignatureChecker(&txNew, nTxInIndex))) { LogPrint("privatesend", "CPrivateSendServer::IsInputScriptSigValid -- VerifyScript() failed on input %d\n", nTxInIndex); return false; } @@ -565,23 +555,23 @@ bool CPrivateSendServer::IsInputScriptSigValid(const CTxIn& txin) // bool CPrivateSendServer::AddEntry(const CDarkSendEntry& entryNew, PoolMessage& nMessageIDRet) { - if(!fMasternodeMode) return false; + if (!fMasternodeMode) return false; for (const auto& txin : entryNew.vecTxDSIn) { - if(txin.prevout.IsNull()) { + if (txin.prevout.IsNull()) { LogPrint("privatesend", "CPrivateSendServer::AddEntry -- input not valid!\n"); nMessageIDRet = ERR_INVALID_INPUT; return false; } } - if(!CPrivateSend::IsCollateralValid(*entryNew.txCollateral)) { + if (!CPrivateSend::IsCollateralValid(*entryNew.txCollateral)) { LogPrint("privatesend", "CPrivateSendServer::AddEntry -- collateral not valid!\n"); nMessageIDRet = ERR_INVALID_COLLATERAL; return false; } - if(GetEntriesCount() >= CPrivateSend::GetMaxPoolTransactions()) { + if (GetEntriesCount() >= CPrivateSend::GetMaxPoolTransactions()) { LogPrint("privatesend", "CPrivateSendServer::AddEntry -- entries is full!\n"); nMessageIDRet = ERR_ENTRIES_FULL; return false; @@ -591,7 +581,7 @@ bool CPrivateSendServer::AddEntry(const CDarkSendEntry& entryNew, PoolMessage& n LogPrint("privatesend", "looking for txin -- %s\n", txin.ToString()); for (const auto& entry : vecEntries) { for (const auto& txdsin : entry.vecTxDSIn) { - if(txdsin.prevout == txin.prevout) { + if (txdsin.prevout == txin.prevout) { LogPrint("privatesend", "CPrivateSendServer::AddEntry -- found in txin\n"); nMessageIDRet = ERR_ALREADY_HAVE; return false; @@ -611,38 +601,38 @@ bool CPrivateSendServer::AddEntry(const CDarkSendEntry& entryNew, PoolMessage& n bool CPrivateSendServer::AddScriptSig(const CTxIn& txinNew) { - LogPrint("privatesend", "CPrivateSendServer::AddScriptSig -- scriptSig=%s\n", ScriptToAsmStr(txinNew.scriptSig).substr(0,24)); + LogPrint("privatesend", "CPrivateSendServer::AddScriptSig -- scriptSig=%s\n", ScriptToAsmStr(txinNew.scriptSig).substr(0, 24)); for (const auto& entry : vecEntries) { for (const auto& txdsin : entry.vecTxDSIn) { - if(txdsin.scriptSig == txinNew.scriptSig) { + if (txdsin.scriptSig == txinNew.scriptSig) { LogPrint("privatesend", "CPrivateSendServer::AddScriptSig -- already exists\n"); return false; } } } - if(!IsInputScriptSigValid(txinNew)) { + if (!IsInputScriptSigValid(txinNew)) { LogPrint("privatesend", "CPrivateSendServer::AddScriptSig -- Invalid scriptSig\n"); return false; } - LogPrint("privatesend", "CPrivateSendServer::AddScriptSig -- scriptSig=%s new\n", ScriptToAsmStr(txinNew.scriptSig).substr(0,24)); + LogPrint("privatesend", "CPrivateSendServer::AddScriptSig -- scriptSig=%s new\n", ScriptToAsmStr(txinNew.scriptSig).substr(0, 24)); for (auto& txin : finalMutableTransaction.vin) { - if(txin.prevout == txinNew.prevout && txin.nSequence == txinNew.nSequence) { + if (txin.prevout == txinNew.prevout && txin.nSequence == txinNew.nSequence) { txin.scriptSig = txinNew.scriptSig; - LogPrint("privatesend", "CPrivateSendServer::AddScriptSig -- adding to finalMutableTransaction, scriptSig=%s\n", ScriptToAsmStr(txinNew.scriptSig).substr(0,24)); + LogPrint("privatesend", "CPrivateSendServer::AddScriptSig -- adding to finalMutableTransaction, scriptSig=%s\n", ScriptToAsmStr(txinNew.scriptSig).substr(0, 24)); } } - for(int i = 0; i < GetEntriesCount(); i++) { - if(vecEntries[i].AddScriptSig(txinNew)) { - LogPrint("privatesend", "CPrivateSendServer::AddScriptSig -- adding to entries, scriptSig=%s\n", ScriptToAsmStr(txinNew.scriptSig).substr(0,24)); + for (int i = 0; i < GetEntriesCount(); i++) { + if (vecEntries[i].AddScriptSig(txinNew)) { + LogPrint("privatesend", "CPrivateSendServer::AddScriptSig -- adding to entries, scriptSig=%s\n", ScriptToAsmStr(txinNew.scriptSig).substr(0, 24)); return true; } } - LogPrintf("CPrivateSendServer::AddScriptSig -- Couldn't set sig!\n" ); + LogPrintf("CPrivateSendServer::AddScriptSig -- Couldn't set sig!\n"); return false; } @@ -651,19 +641,19 @@ bool CPrivateSendServer::IsSignaturesComplete() { for (const auto& entry : vecEntries) for (const auto& txdsin : entry.vecTxDSIn) - if(!txdsin.fHasSig) return false; + if (!txdsin.fHasSig) return false; return true; } bool CPrivateSendServer::IsOutputsCompatibleWithSessionDenom(const std::vector& vecTxOut) { - if(CPrivateSend::GetDenominations(vecTxOut) == 0) return false; + if (CPrivateSend::GetDenominations(vecTxOut) == 0) return false; for (const auto& entry : vecEntries) { LogPrintf("CPrivateSendServer::IsOutputsCompatibleWithSessionDenom -- vecTxOut denom %d, entry.vecTxOut denom %d\n", - CPrivateSend::GetDenominations(vecTxOut), CPrivateSend::GetDenominations(entry.vecTxOut)); - if(CPrivateSend::GetDenominations(vecTxOut) != CPrivateSend::GetDenominations(entry.vecTxOut)) return false; + CPrivateSend::GetDenominations(vecTxOut), CPrivateSend::GetDenominations(entry.vecTxOut)); + if (CPrivateSend::GetDenominations(vecTxOut) != CPrivateSend::GetDenominations(entry.vecTxOut)) return false; } return true; @@ -671,18 +661,18 @@ bool CPrivateSendServer::IsOutputsCompatibleWithSessionDenom(const std::vector vecBits; - if(!CPrivateSend::GetDenominationsBits(dsa.nDenom, vecBits)) { + if (!CPrivateSend::GetDenominationsBits(dsa.nDenom, vecBits)) { LogPrint("privatesend", "CPrivateSendServer::%s -- denom not valid!\n", __func__); nMessageIDRet = ERR_DENOM; return false; } // check collateral - if(!fUnitTest && !CPrivateSend::IsCollateralValid(dsa.txCollateral)) { + if (!fUnitTest && !CPrivateSend::IsCollateralValid(dsa.txCollateral)) { LogPrint("privatesend", "CPrivateSendServer::%s -- collateral not valid!\n", __func__); nMessageIDRet = ERR_INVALID_COLLATERAL; return false; @@ -693,28 +683,28 @@ bool CPrivateSendServer::IsAcceptableDSA(const CDarksendAccept& dsa, PoolMessage bool CPrivateSendServer::CreateNewSession(const CDarksendAccept& dsa, PoolMessage& nMessageIDRet, CConnman& connman) { - if(!fMasternodeMode || nSessionID != 0) return false; + if (!fMasternodeMode || nSessionID != 0) return false; // new session can only be started in idle mode - if(nState != POOL_STATE_IDLE) { + if (nState != POOL_STATE_IDLE) { nMessageIDRet = ERR_MODE; LogPrintf("CPrivateSendServer::CreateNewSession -- incompatible mode: nState=%d\n", nState); return false; } - if(!IsAcceptableDSA(dsa, nMessageIDRet)) { + if (!IsAcceptableDSA(dsa, nMessageIDRet)) { return false; } // start new session nMessageIDRet = MSG_NOERR; - nSessionID = GetRandInt(999999)+1; + nSessionID = GetRandInt(999999) + 1; nSessionDenom = dsa.nDenom; SetState(POOL_STATE_QUEUE); nTimeLastSuccessfulStep = GetTime(); - if(!fUnitTest) { + if (!fUnitTest) { //broadcast that I'm accepting entries, only if it's the first entry through CDarksendQueue dsq(nSessionDenom, activeMasternodeInfo.outpoint, GetAdjustedTime(), false); LogPrint("privatesend", "CPrivateSendServer::CreateNewSession -- signing and relaying new queue: %s\n", dsq.ToString()); @@ -725,29 +715,29 @@ bool CPrivateSendServer::CreateNewSession(const CDarksendAccept& dsa, PoolMessag vecSessionCollaterals.push_back(MakeTransactionRef(dsa.txCollateral)); LogPrintf("CPrivateSendServer::CreateNewSession -- new session created, nSessionID: %d nSessionDenom: %d (%s) vecSessionCollaterals.size(): %d\n", - nSessionID, nSessionDenom, CPrivateSend::GetDenominationsToString(nSessionDenom), vecSessionCollaterals.size()); + nSessionID, nSessionDenom, CPrivateSend::GetDenominationsToString(nSessionDenom), vecSessionCollaterals.size()); return true; } bool CPrivateSendServer::AddUserToExistingSession(const CDarksendAccept& dsa, PoolMessage& nMessageIDRet) { - if(!fMasternodeMode || nSessionID == 0 || IsSessionReady()) return false; + if (!fMasternodeMode || nSessionID == 0 || IsSessionReady()) return false; - if(!IsAcceptableDSA(dsa, nMessageIDRet)) { + if (!IsAcceptableDSA(dsa, nMessageIDRet)) { return false; } // we only add new users to an existing session when we are in queue mode - if(nState != POOL_STATE_QUEUE) { + if (nState != POOL_STATE_QUEUE) { nMessageIDRet = ERR_MODE; LogPrintf("CPrivateSendServer::AddUserToExistingSession -- incompatible mode: nState=%d\n", nState); return false; } - if(dsa.nDenom != nSessionDenom) { + if (dsa.nDenom != nSessionDenom) { LogPrintf("CPrivateSendServer::AddUserToExistingSession -- incompatible denom %d (%s) != nSessionDenom %d (%s)\n", - dsa.nDenom, CPrivateSend::GetDenominationsToString(dsa.nDenom), nSessionDenom, CPrivateSend::GetDenominationsToString(nSessionDenom)); + dsa.nDenom, CPrivateSend::GetDenominationsToString(dsa.nDenom), nSessionDenom, CPrivateSend::GetDenominationsToString(nSessionDenom)); nMessageIDRet = ERR_DENOM; return false; } @@ -759,7 +749,7 @@ bool CPrivateSendServer::AddUserToExistingSession(const CDarksendAccept& dsa, Po vecSessionCollaterals.push_back(MakeTransactionRef(dsa.txCollateral)); LogPrintf("CPrivateSendServer::AddUserToExistingSession -- new user accepted, nSessionID: %d nSessionDenom: %d (%s) vecSessionCollaterals.size(): %d\n", - nSessionID, nSessionDenom, CPrivateSend::GetDenominationsToString(nSessionDenom), vecSessionCollaterals.size()); + nSessionID, nSessionDenom, CPrivateSend::GetDenominationsToString(nSessionDenom), vecSessionCollaterals.size()); return true; } @@ -767,7 +757,7 @@ bool CPrivateSendServer::AddUserToExistingSession(const CDarksendAccept& dsa, Po void CPrivateSendServer::RelayFinalTransaction(const CTransaction& txFinal, CConnman& connman) { LogPrint("privatesend", "CPrivateSendServer::%s -- nSessionID: %d nSessionDenom: %d (%s)\n", - __func__, nSessionID, nSessionDenom, CPrivateSend::GetDenominationsToString(nSessionDenom)); + __func__, nSessionID, nSessionDenom, CPrivateSend::GetDenominationsToString(nSessionDenom)); // final mixing tx with empty signatures should be relayed to mixing participants only for (const auto entry : vecEntries) { @@ -776,7 +766,7 @@ void CPrivateSendServer::RelayFinalTransaction(const CTransaction& txFinal, CCon connman.PushMessage(pnode, msgMaker.Make(NetMsgType::DSFINALTX, nSessionID, txFinal)); return true; }); - if(!fOk) { + if (!fOk) { // no such node? maybe this client disconnected or our own connection went down RelayStatus(STATUS_REJECTED, connman); break; @@ -786,7 +776,7 @@ void CPrivateSendServer::RelayFinalTransaction(const CTransaction& txFinal, CCon void CPrivateSendServer::PushStatus(CNode* pnode, PoolStatusUpdate nStatusUpdate, PoolMessage nMessageID, CConnman& connman) { - if(!pnode) return; + if (!pnode) return; CNetMsgMaker msgMaker(pnode->GetSendVersion()); connman.PushMessage(pnode, msgMaker.Make(NetMsgType::DSSTATUSUPDATE, nSessionID, (int)nState, (int)vecEntries.size(), (int)nStatusUpdate, (int)nMessageID)); } @@ -801,7 +791,7 @@ void CPrivateSendServer::RelayStatus(PoolStatusUpdate nStatusUpdate, CConnman& c PushStatus(pnode, nStatusUpdate, nMessageID, connman); return true; }); - if(!fOk) { + if (!fOk) { // no such node? maybe this client disconnected or our own connection went down ++nDisconnected; } @@ -810,7 +800,7 @@ void CPrivateSendServer::RelayStatus(PoolStatusUpdate nStatusUpdate, CConnman& c // smth went wrong LogPrintf("CPrivateSendServer::%s -- can't continue, %llu client(s) disconnected, nSessionID: %d nSessionDenom: %d (%s)\n", - __func__, nDisconnected, nSessionID, nSessionDenom, CPrivateSend::GetDenominationsToString(nSessionDenom)); + __func__, nDisconnected, nSessionID, nSessionDenom, CPrivateSend::GetDenominationsToString(nSessionDenom)); // notify everyone else that this session should be terminated for (const auto& entry : vecEntries) { @@ -820,7 +810,7 @@ void CPrivateSendServer::RelayStatus(PoolStatusUpdate nStatusUpdate, CConnman& c }); } - if(nDisconnected == vecEntries.size()) { + if (nDisconnected == vecEntries.size()) { // all clients disconnected, there is probably some issues with our own connection // do not charge any fees, just reset the pool SetNull(); @@ -830,7 +820,7 @@ void CPrivateSendServer::RelayStatus(PoolStatusUpdate nStatusUpdate, CConnman& c void CPrivateSendServer::RelayCompletedTransaction(PoolMessage nMessageID, CConnman& connman) { LogPrint("privatesend", "CPrivateSendServer::%s -- nSessionID: %d nSessionDenom: %d (%s)\n", - __func__, nSessionID, nSessionDenom, CPrivateSend::GetDenominationsToString(nSessionDenom)); + __func__, nSessionID, nSessionDenom, CPrivateSend::GetDenominationsToString(nSessionDenom)); // final mixing tx with empty signatures should be relayed to mixing participants only for (const auto& entry : vecEntries) { @@ -839,7 +829,7 @@ void CPrivateSendServer::RelayCompletedTransaction(PoolMessage nMessageID, CConn connman.PushMessage(pnode, msgMaker.Make(NetMsgType::DSCOMPLETE, nSessionID, (int)nMessageID)); return true; }); - if(!fOk) { + if (!fOk) { // no such node? maybe client disconnected or our own connection went down RelayStatus(STATUS_REJECTED, connman); break; @@ -849,9 +839,9 @@ void CPrivateSendServer::RelayCompletedTransaction(PoolMessage nMessageID, CConn void CPrivateSendServer::SetState(PoolState nStateNew) { - if(!fMasternodeMode) return; + if (!fMasternodeMode) return; - if(nStateNew == POOL_STATE_ERROR || nStateNew == POOL_STATE_SUCCESS) { + if (nStateNew == POOL_STATE_ERROR || nStateNew == POOL_STATE_SUCCESS) { LogPrint("privatesend", "CPrivateSendServer::SetState -- Can't set state to ERROR or SUCCESS as a Masternode. \n"); return; } @@ -862,10 +852,10 @@ void CPrivateSendServer::SetState(PoolState nStateNew) void CPrivateSendServer::DoMaintenance(CConnman& connman) { - if(fLiteMode) return; // disable all Dash specific functionality - if(!fMasternodeMode) return; // only run on masternodes + if (fLiteMode) return; // disable all Dash specific functionality + if (!fMasternodeMode) return; // only run on masternodes - if(!masternodeSync.IsBlockchainSynced() || ShutdownRequested()) + if (!masternodeSync.IsBlockchainSynced() || ShutdownRequested()) return; privateSendServer.CheckTimeout(connman); diff --git a/src/privatesend-server.h b/src/privatesend-server.h index f9219627ca8b..48b3176a9cd6 100644 --- a/src/privatesend-server.h +++ b/src/privatesend-server.h @@ -41,9 +41,9 @@ class CPrivateSendServer : public CPrivateSendBaseSession, public CPrivateSendBa void CommitFinalTransaction(CConnman& connman); /// Is this nDenom and txCollateral acceptable? - bool IsAcceptableDSA(const CDarksendAccept& dsa, PoolMessage &nMessageIDRet); - bool CreateNewSession(const CDarksendAccept& dsa, PoolMessage &nMessageIDRet, CConnman& connman); - bool AddUserToExistingSession(const CDarksendAccept& dsa, PoolMessage &nMessageIDRet); + bool IsAcceptableDSA(const CDarksendAccept& dsa, PoolMessage& nMessageIDRet); + bool CreateNewSession(const CDarksendAccept& dsa, PoolMessage& nMessageIDRet, CConnman& connman); + bool AddUserToExistingSession(const CDarksendAccept& dsa, PoolMessage& nMessageIDRet); /// Do we have enough users to take entries? bool IsSessionReady() { return (int)vecSessionCollaterals.size() >= CPrivateSend::GetMaxPoolTransactions(); } @@ -66,7 +66,8 @@ class CPrivateSendServer : public CPrivateSendBaseSession, public CPrivateSendBa void SetNull(); public: - CPrivateSendServer() : vecSessionCollaterals(), fUnitTest(false) {} + CPrivateSendServer() : + vecSessionCollaterals(), fUnitTest(false) {} void ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman); diff --git a/src/privatesend-util.cpp b/src/privatesend-util.cpp index 4fc59eaaab63..ad96b58d3e6f 100644 --- a/src/privatesend-util.cpp +++ b/src/privatesend-util.cpp @@ -38,7 +38,7 @@ CScript CKeyHolderStorage::AddKey(CWallet* pwallet) void CKeyHolderStorage::KeepAll() { - std::vector> tmp; + std::vector > tmp; { // don't hold cs_storage while calling KeepKey(), which might lock cs_wallet LOCK(cs_storage); @@ -46,7 +46,7 @@ void CKeyHolderStorage::KeepAll() } if (tmp.size() > 0) { - for (auto &key : tmp) { + for (auto& key : tmp) { key->KeepKey(); } LogPrintf("CKeyHolderStorage::%s -- %lld keys kept\n", __func__, tmp.size()); @@ -55,7 +55,7 @@ void CKeyHolderStorage::KeepAll() void CKeyHolderStorage::ReturnAll() { - std::vector> tmp; + std::vector > tmp; { // don't hold cs_storage while calling ReturnKey(), which might lock cs_wallet LOCK(cs_storage); @@ -63,7 +63,7 @@ void CKeyHolderStorage::ReturnAll() } if (tmp.size() > 0) { - for (auto &key : tmp) { + for (auto& key : tmp) { key->ReturnKey(); } LogPrintf("CKeyHolderStorage::%s -- %lld keys returned\n", __func__, tmp.size()); diff --git a/src/privatesend-util.h b/src/privatesend-util.h index 9040eb011a0f..4cae27318eda 100644 --- a/src/privatesend-util.h +++ b/src/privatesend-util.h @@ -12,6 +12,7 @@ class CKeyHolder private: CReserveKey reserveKey; CPubKey pubKey; + public: CKeyHolder(CWallet* pwalletIn); CKeyHolder(CKeyHolder&&) = default; @@ -20,7 +21,6 @@ class CKeyHolder void ReturnKey(); CScript GetScriptForDestination() const; - }; class CKeyHolderStorage @@ -33,6 +33,5 @@ class CKeyHolderStorage CScript AddKey(CWallet* pwalletIn); void KeepAll(); void ReturnAll(); - }; #endif //PRIVATESENDUTIL_H diff --git a/src/privatesend.cpp b/src/privatesend.cpp index 0e3c3bf670b3..9fb7f84c3b75 100644 --- a/src/privatesend.cpp +++ b/src/privatesend.cpp @@ -20,8 +20,8 @@ bool CDarkSendEntry::AddScriptSig(const CTxIn& txin) { for (auto& txdsin : vecTxDSIn) { - if(txdsin.prevout == txin.prevout && txdsin.nSequence == txin.nSequence) { - if(txdsin.fHasSig) return false; + if (txdsin.prevout == txin.prevout && txdsin.nSequence == txin.nSequence) { + if (txdsin.fHasSig) return false; txdsin.scriptSig = txin.scriptSig; txdsin.fHasSig = true; @@ -37,9 +37,9 @@ uint256 CDarksendQueue::GetSignatureHash() const { // Remove after migration to 70211 { - masternode_info_t mnInfo; - mnodeman.GetMasternodeInfo(masternodeOutpoint, mnInfo); - return SerializeHash(*this, SER_GETHASH, mnInfo.nProtocolVersion); + masternode_info_t mnInfo; + mnodeman.GetMasternodeInfo(masternodeOutpoint, mnInfo); + return SerializeHash(*this, SER_GETHASH, mnInfo.nProtocolVersion); } // END remove, replace with the code below // return SerializeHash(*this); @@ -47,7 +47,7 @@ uint256 CDarksendQueue::GetSignatureHash() const bool CDarksendQueue::Sign() { - if(!fMasternodeMode) return false; + if (!fMasternodeMode) return false; std::string strError = ""; @@ -65,16 +65,16 @@ bool CDarksendQueue::Sign() } } else { std::string strMessage = CTxIn(masternodeOutpoint).ToString() + - std::to_string(nDenom) + - std::to_string(nTime) + - std::to_string(fReady); + std::to_string(nDenom) + + std::to_string(nTime) + + std::to_string(fReady); - if(!CMessageSigner::SignMessage(strMessage, vchSig, activeMasternodeInfo.keyOperator)) { + if (!CMessageSigner::SignMessage(strMessage, vchSig, activeMasternodeInfo.keyOperator)) { LogPrintf("CDarksendQueue::Sign -- SignMessage() failed, %s\n", ToString()); return false; } - if(!CMessageSigner::VerifyMessage(activeMasternodeInfo.keyIDOperator, vchSig, strMessage, strError)) { + if (!CMessageSigner::VerifyMessage(activeMasternodeInfo.keyIDOperator, vchSig, strMessage, strError)) { LogPrintf("CDarksendQueue::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } @@ -97,11 +97,11 @@ bool CDarksendQueue::CheckSignature(const CKeyID& keyIDOperator) const } } else { std::string strMessage = CTxIn(masternodeOutpoint).ToString() + - std::to_string(nDenom) + - std::to_string(nTime) + - std::to_string(fReady); + std::to_string(nDenom) + + std::to_string(nTime) + + std::to_string(fReady); - if(!CMessageSigner::VerifyMessage(keyIDOperator, vchSig, strMessage, strError)) { + if (!CMessageSigner::VerifyMessage(keyIDOperator, vchSig, strMessage, strError)) { LogPrintf("CDarksendQueue::CheckSignature -- Got bad Masternode queue signature: %s; error: %s\n", ToString(), strError); return false; } @@ -127,7 +127,7 @@ uint256 CDarksendBroadcastTx::GetSignatureHash() const bool CDarksendBroadcastTx::Sign() { - if(!fMasternodeMode) return false; + if (!fMasternodeMode) return false; std::string strError = ""; @@ -146,12 +146,12 @@ bool CDarksendBroadcastTx::Sign() } else { std::string strMessage = tx->GetHash().ToString() + std::to_string(sigTime); - if(!CMessageSigner::SignMessage(strMessage, vchSig, activeMasternodeInfo.keyOperator)) { + if (!CMessageSigner::SignMessage(strMessage, vchSig, activeMasternodeInfo.keyOperator)) { LogPrintf("CDarksendBroadcastTx::Sign -- SignMessage() failed\n"); return false; } - if(!CMessageSigner::VerifyMessage(activeMasternodeInfo.keyIDOperator, vchSig, strMessage, strError)) { + if (!CMessageSigner::VerifyMessage(activeMasternodeInfo.keyIDOperator, vchSig, strMessage, strError)) { LogPrintf("CDarksendBroadcastTx::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } @@ -175,7 +175,7 @@ bool CDarksendBroadcastTx::CheckSignature(const CKeyID& keyIDOperator) const } else { std::string strMessage = tx->GetHash().ToString() + std::to_string(sigTime); - if(!CMessageSigner::VerifyMessage(keyIDOperator, vchSig, strMessage, strError)) { + if (!CMessageSigner::VerifyMessage(keyIDOperator, vchSig, strMessage, strError)) { LogPrintf("CDarksendBroadcastTx::CheckSignature -- Got bad dstx signature, error: %s\n", strError); return false; } @@ -212,26 +212,27 @@ void CPrivateSendBaseManager::SetNull() void CPrivateSendBaseManager::CheckQueue() { TRY_LOCK(cs_vecqueue, lockDS); - if(!lockDS) return; // it's ok to fail here, we run this quite frequently + if (!lockDS) return; // it's ok to fail here, we run this quite frequently // check mixing queue objects for timeouts std::vector::iterator it = vecDarksendQueue.begin(); - while(it != vecDarksendQueue.end()) { - if((*it).IsExpired()) { + while (it != vecDarksendQueue.end()) { + if ((*it).IsExpired()) { LogPrint("privatesend", "CPrivateSendBaseManager::%s -- Removing expired queue (%s)\n", __func__, (*it).ToString()); it = vecDarksendQueue.erase(it); - } else ++it; + } else + ++it; } } bool CPrivateSendBaseManager::GetQueueItemAndTry(CDarksendQueue& dsqRet) { TRY_LOCK(cs_vecqueue, lockDS); - if(!lockDS) return false; // it's ok to fail here, we run this quite frequently + if (!lockDS) return false; // it's ok to fail here, we run this quite frequently for (auto& dsq : vecDarksendQueue) { // only try each queue once - if(dsq.fTried || dsq.IsExpired()) continue; + if (dsq.fTried || dsq.IsExpired()) continue; dsq.fTried = true; dsqRet = dsq; return true; @@ -242,14 +243,21 @@ bool CPrivateSendBaseManager::GetQueueItemAndTry(CDarksendQueue& dsqRet) std::string CPrivateSendBaseSession::GetStateString() const { - switch(nState) { - case POOL_STATE_IDLE: return "IDLE"; - case POOL_STATE_QUEUE: return "QUEUE"; - case POOL_STATE_ACCEPTING_ENTRIES: return "ACCEPTING_ENTRIES"; - case POOL_STATE_SIGNING: return "SIGNING"; - case POOL_STATE_ERROR: return "ERROR"; - case POOL_STATE_SUCCESS: return "SUCCESS"; - default: return "UNKNOWN"; + switch (nState) { + case POOL_STATE_IDLE: + return "IDLE"; + case POOL_STATE_QUEUE: + return "QUEUE"; + case POOL_STATE_ACCEPTING_ENTRIES: + return "ACCEPTING_ENTRIES"; + case POOL_STATE_SIGNING: + return "SIGNING"; + case POOL_STATE_ERROR: + return "ERROR"; + case POOL_STATE_SUCCESS: + return "SUCCESS"; + default: + return "UNKNOWN"; } } @@ -273,10 +281,10 @@ void CPrivateSend::InitStandardDenominations() /* Disabled vecStandardDenominations.push_back( (100 * COIN)+100000 ); */ - vecStandardDenominations.push_back( (10 * COIN)+10000 ); - vecStandardDenominations.push_back( (1 * COIN)+1000 ); - vecStandardDenominations.push_back( (.1 * COIN)+100 ); - vecStandardDenominations.push_back( (.01 * COIN)+10 ); + vecStandardDenominations.push_back((10 * COIN) + 10000); + vecStandardDenominations.push_back((1 * COIN) + 1000); + vecStandardDenominations.push_back((.1 * COIN) + 100); + vecStandardDenominations.push_back((.01 * COIN) + 10); /* Disabled till we need them vecStandardDenominations.push_back( (.001 * COIN)+1 ); */ @@ -285,8 +293,8 @@ void CPrivateSend::InitStandardDenominations() // check to make sure the collateral provided by the client is valid bool CPrivateSend::IsCollateralValid(const CTransaction& txCollateral) { - if(txCollateral.vout.empty()) return false; - if(txCollateral.nLockTime != 0) return false; + if (txCollateral.vout.empty()) return false; + if (txCollateral.nLockTime != 0) return false; CAmount nValueIn = 0; CAmount nValueOut = 0; @@ -295,15 +303,15 @@ bool CPrivateSend::IsCollateralValid(const CTransaction& txCollateral) nValueOut += txout.nValue; bool fAllowData = mnpayments.GetMinMasternodePaymentsProto() > 70208; - if(!txout.scriptPubKey.IsPayToPublicKeyHash() && !(fAllowData && txout.scriptPubKey.IsUnspendable())) { - LogPrintf ("CPrivateSend::IsCollateralValid -- Invalid Script, txCollateral=%s", txCollateral.ToString()); + if (!txout.scriptPubKey.IsPayToPublicKeyHash() && !(fAllowData && txout.scriptPubKey.IsUnspendable())) { + LogPrintf("CPrivateSend::IsCollateralValid -- Invalid Script, txCollateral=%s", txCollateral.ToString()); return false; } } for (const auto& txin : txCollateral.vin) { Coin coin; - if(!GetUTXOCoin(txin.prevout, coin)) { + if (!GetUTXOCoin(txin.prevout, coin)) { LogPrint("privatesend", "CPrivateSend::IsCollateralValid -- Unknown inputs in collateral transaction, txCollateral=%s", txCollateral.ToString()); return false; } @@ -311,7 +319,7 @@ bool CPrivateSend::IsCollateralValid(const CTransaction& txCollateral) } //collateral transactions are required to pay out a small fee to the miners - if(nValueIn - nValueOut < GetCollateralAmount()) { + if (nValueIn - nValueOut < GetCollateralAmount()) { LogPrint("privatesend", "CPrivateSend::IsCollateralValid -- did not include enough fees in transaction: fees: %d, txCollateral=%s", nValueOut - nValueIn, txCollateral.ToString()); return false; } @@ -321,7 +329,7 @@ bool CPrivateSend::IsCollateralValid(const CTransaction& txCollateral) { LOCK(cs_main); CValidationState validationState; - if(!AcceptToMemoryPool(mempool, validationState, MakeTransactionRef(txCollateral), false, NULL, false, maxTxFee, true)) { + if (!AcceptToMemoryPool(mempool, validationState, MakeTransactionRef(txCollateral), false, NULL, false, maxTxFee, true)) { LogPrint("privatesend", "CPrivateSend::IsCollateralValid -- didn't pass AcceptToMemoryPool()\n"); return false; } @@ -356,17 +364,17 @@ std::string CPrivateSend::GetDenominationsToString(int nDenom) std::string strDenom = ""; int nMaxDenoms = vecStandardDenominations.size(); - if(nDenom >= (1 << nMaxDenoms)) { + if (nDenom >= (1 << nMaxDenoms)) { return "out-of-bounds"; } for (int i = 0; i < nMaxDenoms; ++i) { - if(nDenom & (1 << i)) { + if (nDenom & (1 << i)) { strDenom += (strDenom.empty() ? "" : "+") + FormatMoney(vecStandardDenominations[i]); } } - if(strDenom.empty()) { + if (strDenom.empty()) { return "non-denom"; } @@ -394,12 +402,12 @@ int CPrivateSend::GetDenominations(const std::vector& vecTxOut, bool fSi for (const auto& txout : vecTxOut) { bool found = false; for (auto& s : vecDenomUsed) { - if(txout.nValue == s.first) { + if (txout.nValue == s.first) { s.second = 1; found = true; } } - if(!found) return 0; + if (!found) return 0; } int nDenom = 0; @@ -408,13 +416,13 @@ int CPrivateSend::GetDenominations(const std::vector& vecTxOut, bool fSi for (const auto& s : vecDenomUsed) { int bit = (fSingleRandomDenom ? GetRandInt(2) : 1) & s.second; nDenom |= bit << c++; - if(fSingleRandomDenom && bit) break; // use just one random denomination + if (fSingleRandomDenom && bit) break; // use just one random denomination } return nDenom; } -bool CPrivateSend::GetDenominationsBits(int nDenom, std::vector &vecBitsRet) +bool CPrivateSend::GetDenominationsBits(int nDenom, std::vector& vecBitsRet) { // ( bit on if present, 4 denominations example ) // bit 0 - 100DASH+1 @@ -424,12 +432,12 @@ bool CPrivateSend::GetDenominationsBits(int nDenom, std::vector &vecBitsRet int nMaxDenoms = vecStandardDenominations.size(); - if(nDenom >= (1 << nMaxDenoms)) return false; + if (nDenom >= (1 << nMaxDenoms)) return false; vecBitsRet.clear(); for (int i = 0; i < nMaxDenoms; ++i) { - if(nDenom & (1 << i)) { + if (nDenom & (1 << i)) { vecBitsRet.push_back(i); } } @@ -453,7 +461,7 @@ int CPrivateSend::GetDenominationsByAmounts(const std::vector& vecAmoun bool CPrivateSend::IsDenominatedAmount(CAmount nInputAmount) { for (const auto& nDenomValue : vecStandardDenominations) - if(nInputAmount == nDenomValue) + if (nInputAmount == nDenomValue) return true; return false; } @@ -461,29 +469,52 @@ bool CPrivateSend::IsDenominatedAmount(CAmount nInputAmount) std::string CPrivateSend::GetMessageByID(PoolMessage nMessageID) { switch (nMessageID) { - case ERR_ALREADY_HAVE: return _("Already have that input."); - case ERR_DENOM: return _("No matching denominations found for mixing."); - case ERR_ENTRIES_FULL: return _("Entries are full."); - case ERR_EXISTING_TX: return _("Not compatible with existing transactions."); - case ERR_FEES: return _("Transaction fees are too high."); - case ERR_INVALID_COLLATERAL: return _("Collateral not valid."); - case ERR_INVALID_INPUT: return _("Input is not valid."); - case ERR_INVALID_SCRIPT: return _("Invalid script detected."); - case ERR_INVALID_TX: return _("Transaction not valid."); - case ERR_MAXIMUM: return _("Entry exceeds maximum size."); - case ERR_MN_LIST: return _("Not in the Masternode list."); - case ERR_MODE: return _("Incompatible mode."); - case ERR_NON_STANDARD_PUBKEY: return _("Non-standard public key detected."); - case ERR_NOT_A_MN: return _("This is not a Masternode."); // not used - case ERR_QUEUE_FULL: return _("Masternode queue is full."); - case ERR_RECENT: return _("Last PrivateSend was too recent."); - case ERR_SESSION: return _("Session not complete!"); - case ERR_MISSING_TX: return _("Missing input transaction information."); - case ERR_VERSION: return _("Incompatible version."); - case MSG_NOERR: return _("No errors detected."); - case MSG_SUCCESS: return _("Transaction created successfully."); - case MSG_ENTRIES_ADDED: return _("Your entries added successfully."); - default: return _("Unknown response."); + case ERR_ALREADY_HAVE: + return _("Already have that input."); + case ERR_DENOM: + return _("No matching denominations found for mixing."); + case ERR_ENTRIES_FULL: + return _("Entries are full."); + case ERR_EXISTING_TX: + return _("Not compatible with existing transactions."); + case ERR_FEES: + return _("Transaction fees are too high."); + case ERR_INVALID_COLLATERAL: + return _("Collateral not valid."); + case ERR_INVALID_INPUT: + return _("Input is not valid."); + case ERR_INVALID_SCRIPT: + return _("Invalid script detected."); + case ERR_INVALID_TX: + return _("Transaction not valid."); + case ERR_MAXIMUM: + return _("Entry exceeds maximum size."); + case ERR_MN_LIST: + return _("Not in the Masternode list."); + case ERR_MODE: + return _("Incompatible mode."); + case ERR_NON_STANDARD_PUBKEY: + return _("Non-standard public key detected."); + case ERR_NOT_A_MN: + return _("This is not a Masternode."); // not used + case ERR_QUEUE_FULL: + return _("Masternode queue is full."); + case ERR_RECENT: + return _("Last PrivateSend was too recent."); + case ERR_SESSION: + return _("Session not complete!"); + case ERR_MISSING_TX: + return _("Missing input transaction information."); + case ERR_VERSION: + return _("Incompatible version."); + case MSG_NOERR: + return _("No errors detected."); + case MSG_SUCCESS: + return _("Transaction created successfully."); + case MSG_ENTRIES_ADDED: + return _("Your entries added successfully."); + default: + return _("Unknown response."); } } @@ -504,7 +535,7 @@ void CPrivateSend::CheckDSTXes(int nHeight) { LOCK(cs_mapdstx); std::map::iterator it = mapDSTX.begin(); - while(it != mapDSTX.end()) { + while (it != mapDSTX.end()) { if (it->second.IsExpired(nHeight)) { mapDSTX.erase(it++); } else { @@ -514,14 +545,14 @@ void CPrivateSend::CheckDSTXes(int nHeight) LogPrint("privatesend", "CPrivateSend::CheckDSTXes -- mapDSTX.size()=%llu\n", mapDSTX.size()); } -void CPrivateSend::UpdatedBlockTip(const CBlockIndex *pindex) +void CPrivateSend::UpdatedBlockTip(const CBlockIndex* pindex) { - if(pindex && !fLiteMode && masternodeSync.IsMasternodeListSynced()) { + if (pindex && !fLiteMode && masternodeSync.IsMasternodeListSynced()) { CheckDSTXes(pindex->nHeight); } } -void CPrivateSend::SyncTransaction(const CTransaction& tx, const CBlockIndex *pindex, int posInBlock) +void CPrivateSend::SyncTransaction(const CTransaction& tx, const CBlockIndex* pindex, int posInBlock) { if (tx.IsCoinBase()) return; diff --git a/src/privatesend.h b/src/privatesend.h index b505c7fbc15a..f7256ae579d7 100644 --- a/src/privatesend.h +++ b/src/privatesend.h @@ -10,22 +10,22 @@ #include "primitives/transaction.h" #include "pubkey.h" #include "sync.h" -#include "tinyformat.h" #include "timedata.h" +#include "tinyformat.h" class CPrivateSend; class CConnman; // timeouts -static const int PRIVATESEND_AUTO_TIMEOUT_MIN = 5; -static const int PRIVATESEND_AUTO_TIMEOUT_MAX = 15; -static const int PRIVATESEND_QUEUE_TIMEOUT = 30; -static const int PRIVATESEND_SIGNING_TIMEOUT = 15; +static const int PRIVATESEND_AUTO_TIMEOUT_MIN = 5; +static const int PRIVATESEND_AUTO_TIMEOUT_MAX = 15; +static const int PRIVATESEND_QUEUE_TIMEOUT = 30; +static const int PRIVATESEND_SIGNING_TIMEOUT = 15; //! minimum peer version accepted by mixing pool static const int MIN_PRIVATESEND_PEER_PROTO_VERSION = 70210; -static const size_t PRIVATESEND_ENTRY_MAX_SIZE = 9; +static const size_t PRIVATESEND_ENTRY_MAX_SIZE = 9; // pool responses enum PoolMessage { @@ -86,13 +86,15 @@ class CTxDSIn : public CTxIn CTxIn(txin), prevPubKey(script), fHasSig(false) - {} + { + } CTxDSIn() : CTxIn(), prevPubKey(), fHasSig(false) - {} + { + } }; class CDarksendAccept @@ -103,18 +105,17 @@ class CDarksendAccept CDarksendAccept() : nDenom(0), - txCollateral(CMutableTransaction()) - {}; + txCollateral(CMutableTransaction()){}; CDarksendAccept(int nDenom, const CMutableTransaction& txCollateral) : nDenom(nDenom), - txCollateral(txCollateral) - {}; + txCollateral(txCollateral){}; ADD_SERIALIZE_METHODS; template - inline void SerializationOp(Stream& s, Operation ser_action) { + inline void SerializationOp(Stream& s, Operation ser_action) + { READWRITE(nDenom); int nVersion = s.GetVersion(); if (nVersion > 70208 && nVersion <= 70210) { @@ -145,19 +146,22 @@ class CDarkSendEntry vecTxOut(std::vector()), txCollateral(MakeTransactionRef()), addr(CService()) - {} + { + } CDarkSendEntry(const std::vector& vecTxDSIn, const std::vector& vecTxOut, const CTransaction& txCollateral) : vecTxDSIn(vecTxDSIn), vecTxOut(vecTxOut), txCollateral(MakeTransactionRef(txCollateral)), addr(CService()) - {} + { + } ADD_SERIALIZE_METHODS; template - inline void SerializationOp(Stream& s, Operation ser_action) { + inline void SerializationOp(Stream& s, Operation ser_action) + { READWRITE(vecTxDSIn); READWRITE(txCollateral); READWRITE(vecTxOut); @@ -190,7 +194,8 @@ class CDarksendQueue fReady(false), vchSig(std::vector()), fTried(false) - {} + { + } CDarksendQueue(int nDenom, COutPoint outpoint, int64_t nTime, bool fReady) : nDenom(nDenom), @@ -200,12 +205,14 @@ class CDarksendQueue fReady(fReady), vchSig(std::vector()), fTried(false) - {} + { + } ADD_SERIALIZE_METHODS; template - inline void SerializationOp(Stream& s, Operation ser_action) { + inline void SerializationOp(Stream& s, Operation ser_action) + { READWRITE(nDenom); int nVersion = s.GetVersion(); if (nVersion > 70208 && nVersion <= 70210) { @@ -231,7 +238,7 @@ class CDarksendQueue /// Check if we have a valid Masternode address bool CheckSignature(const CKeyID& keyIDOperator) const; - bool Relay(CConnman &connman); + bool Relay(CConnman& connman); /// Is this queue expired? bool IsExpired() { return GetAdjustedTime() - nTime > PRIVATESEND_QUEUE_TIMEOUT; } @@ -239,7 +246,7 @@ class CDarksendQueue std::string ToString() const { return strprintf("nDenom=%d, nTime=%lld, fReady=%s, fTried=%s, masternode=%s", - nDenom, nTime, fReady ? "true" : "false", fTried ? "true" : "false", masternodeOutpoint.ToStringShort()); + nDenom, nTime, fReady ? "true" : "false", fTried ? "true" : "false", masternodeOutpoint.ToStringShort()); } friend bool operator==(const CDarksendQueue& a, const CDarksendQueue& b) @@ -269,7 +276,8 @@ class CDarksendBroadcastTx masternodeOutpoint(), vchSig(), sigTime(0) - {} + { + } CDarksendBroadcastTx(const CTransactionRef& _tx, COutPoint _outpoint, int64_t _sigTime) : nConfirmedHeight(-1), @@ -277,12 +285,14 @@ class CDarksendBroadcastTx masternodeOutpoint(_outpoint), vchSig(), sigTime(_sigTime) - {} + { + } ADD_SERIALIZE_METHODS; template - inline void SerializationOp(Stream& s, Operation ser_action) { + inline void SerializationOp(Stream& s, Operation ser_action) + { READWRITE(tx); READWRITE(masternodeOutpoint); if (!(s.GetType() & SER_GETHASH)) { @@ -321,7 +331,7 @@ class CPrivateSendBaseSession std::vector vecEntries; // Masternode/clients entries - PoolState nState; // should be one of the POOL_STATE_XXX values + PoolState nState; // should be one of the POOL_STATE_XXX values int64_t nTimeLastSuccessfulStep; // the time when last successful mixing step was performed int nSessionID; // 0 if no mixing session is active @@ -340,7 +350,8 @@ class CPrivateSendBaseSession nSessionID(0), finalMutableTransaction(), nSessionDenom(0) - {} + { + } int GetState() const { return nState; } std::string GetStateString() const; @@ -361,7 +372,8 @@ class CPrivateSendBaseManager void CheckQueue(); public: - CPrivateSendBaseManager() : vecDarksendQueue() {} + CPrivateSendBaseManager() : + vecDarksendQueue() {} int GetQueueSize() const { return vecDarksendQueue.size(); } bool GetQueueItemAndTry(CDarksendQueue& dsqRet); @@ -375,7 +387,7 @@ class CPrivateSend CPrivateSend() {} ~CPrivateSend() {} CPrivateSend(CPrivateSend const&) = delete; - CPrivateSend& operator= (CPrivateSend const&) = delete; + CPrivateSend& operator=(CPrivateSend const&) = delete; static const CAmount COLLATERAL = 0.001 * COIN; @@ -400,7 +412,7 @@ class CPrivateSend /// Get the denominations for a list of outputs (returns a bitshifted integer) static int GetDenominations(const std::vector& vecTxOut, bool fSingleRandomDenom = false); static std::string GetDenominationsToString(int nDenom); - static bool GetDenominationsBits(int nDenom, std::vector &vecBitsRet); + static bool GetDenominationsBits(int nDenom, std::vector& vecBitsRet); static std::string GetMessageByID(PoolMessage nMessageID); @@ -412,15 +424,15 @@ class CPrivateSend /// If the collateral is valid given by a client static bool IsCollateralValid(const CTransaction& txCollateral); static CAmount GetCollateralAmount() { return COLLATERAL; } - static CAmount GetMaxCollateralAmount() { return COLLATERAL*4; } + static CAmount GetMaxCollateralAmount() { return COLLATERAL * 4; } static bool IsCollateralAmount(CAmount nInputAmount); static void AddDSTX(const CDarksendBroadcastTx& dstx); static CDarksendBroadcastTx GetDSTX(const uint256& hash); - static void UpdatedBlockTip(const CBlockIndex *pindex); - static void SyncTransaction(const CTransaction& tx, const CBlockIndex *pindex, int posInBlock); + static void UpdatedBlockTip(const CBlockIndex* pindex); + static void SyncTransaction(const CTransaction& tx, const CBlockIndex* pindex, int posInBlock); }; #endif diff --git a/src/qt/masternodelist.cpp b/src/qt/masternodelist.cpp index ce8e19784faa..b83761c2442a 100644 --- a/src/qt/masternodelist.cpp +++ b/src/qt/masternodelist.cpp @@ -4,8 +4,8 @@ #include "activemasternode.h" #include "clientmodel.h" #include "clientversion.h" -#include "init.h" #include "guiutil.h" +#include "init.h" #include "masternode-sync.h" #include "masternodeconfig.h" #include "masternodeman.h" @@ -14,8 +14,8 @@ #include "wallet/wallet.h" #include "walletmodel.h" -#include #include +#include int GetOffsetFromUtc() { @@ -28,7 +28,7 @@ int GetOffsetFromUtc() #endif } -MasternodeList::MasternodeList(const PlatformStyle *platformStyle, QWidget *parent) : +MasternodeList::MasternodeList(const PlatformStyle* platformStyle, QWidget* parent) : QWidget(parent), ui(new Ui::MasternodeList), clientModel(0), @@ -60,7 +60,7 @@ MasternodeList::MasternodeList(const PlatformStyle *platformStyle, QWidget *pare ui->tableWidgetMyMasternodes->setContextMenuPolicy(Qt::CustomContextMenu); - QAction *startAliasAction = new QAction(tr("Start alias"), this); + QAction* startAliasAction = new QAction(tr("Start alias"), this); contextMenu = new QMenu(); contextMenu->addAction(startAliasAction); connect(ui->tableWidgetMyMasternodes, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showContextMenu(const QPoint&))); @@ -82,24 +82,24 @@ MasternodeList::~MasternodeList() delete ui; } -void MasternodeList::setClientModel(ClientModel *model) +void MasternodeList::setClientModel(ClientModel* model) { this->clientModel = model; - if(model) { + if (model) { // try to update list when masternode count changes connect(clientModel, SIGNAL(strMasternodesChanged(QString)), this, SLOT(updateNodeList())); } } -void MasternodeList::setWalletModel(WalletModel *model) +void MasternodeList::setWalletModel(WalletModel* model) { this->walletModel = model; } -void MasternodeList::showContextMenu(const QPoint &point) +void MasternodeList::showContextMenu(const QPoint& point) { - QTableWidgetItem *item = ui->tableWidgetMyMasternodes->itemAt(point); - if(item) contextMenu->exec(QCursor::pos()); + QTableWidgetItem* item = ui->tableWidgetMyMasternodes->itemAt(point); + if (item) contextMenu->exec(QCursor::pos()); } void MasternodeList::StartAlias(std::string strAlias) @@ -108,7 +108,7 @@ void MasternodeList::StartAlias(std::string strAlias) strStatusHtml += "
Alias: " + strAlias; for (const auto& mne : masternodeConfig.getEntries()) { - if(mne.getAlias() == strAlias) { + if (mne.getAlias() == strAlias) { std::string strError; CMasternodeBroadcast mnb; @@ -120,7 +120,7 @@ void MasternodeList::StartAlias(std::string strAlias) fSuccess = false; } - if(fSuccess) { + if (fSuccess) { strStatusHtml += "
Successfully started masternode."; mnodeman.NotifyMasternodeUpdates(*g_connman); } else { @@ -149,13 +149,13 @@ void MasternodeList::StartAll(std::string strCommand) CMasternodeBroadcast mnb; int32_t nOutputIndex = 0; - if(!ParseInt32(mne.getOutputIndex(), &nOutputIndex)) { + if (!ParseInt32(mne.getOutputIndex(), &nOutputIndex)) { continue; } COutPoint outpoint = COutPoint(uint256S(mne.getTxHash()), nOutputIndex); - if(strCommand == "start-missing" && mnodeman.Has(outpoint)) continue; + if (strCommand == "start-missing" && mnodeman.Has(outpoint)) continue; bool fSuccess = CMasternodeBroadcast::Create(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), strError, mnb); @@ -165,7 +165,7 @@ void MasternodeList::StartAll(std::string strCommand) fSuccess = false; } - if(fSuccess) { + if (fSuccess) { nCountSuccessful++; mnodeman.NotifyMasternodeUpdates(*g_connman); } else { @@ -192,15 +192,15 @@ void MasternodeList::updateMyMasternodeInfo(QString strAlias, QString strAddr, c bool fOldRowFound = false; int nNewRow = 0; - for(int i = 0; i < ui->tableWidgetMyMasternodes->rowCount(); i++) { - if(ui->tableWidgetMyMasternodes->item(i, 0)->text() == strAlias) { + for (int i = 0; i < ui->tableWidgetMyMasternodes->rowCount(); i++) { + if (ui->tableWidgetMyMasternodes->item(i, 0)->text() == strAlias) { fOldRowFound = true; nNewRow = i; break; } } - if(nNewRow == 0 && !fOldRowFound) { + if (nNewRow == 0 && !fOldRowFound) { nNewRow = ui->tableWidgetMyMasternodes->rowCount(); ui->tableWidgetMyMasternodes->insertRow(nNewRow); } @@ -208,14 +208,14 @@ void MasternodeList::updateMyMasternodeInfo(QString strAlias, QString strAddr, c masternode_info_t infoMn; bool fFound = mnodeman.GetMasternodeInfo(outpoint, infoMn); - QTableWidgetItem *aliasItem = new QTableWidgetItem(strAlias); - QTableWidgetItem *addrItem = new QTableWidgetItem(fFound ? QString::fromStdString(infoMn.addr.ToString()) : strAddr); - QTableWidgetItem *protocolItem = new QTableWidgetItem(QString::number(fFound ? infoMn.nProtocolVersion : -1)); - QTableWidgetItem *statusItem = new QTableWidgetItem(QString::fromStdString(fFound ? CMasternode::StateToString(infoMn.nActiveState) : "MISSING")); - QTableWidgetItem *activeSecondsItem = new QTableWidgetItem(QString::fromStdString(DurationToDHMS(fFound ? (infoMn.nTimeLastPing - infoMn.sigTime) : 0))); - QTableWidgetItem *lastSeenItem = new QTableWidgetItem(QString::fromStdString(DateTimeStrFormat("%Y-%m-%d %H:%M", - fFound ? infoMn.nTimeLastPing + GetOffsetFromUtc() : 0))); - QTableWidgetItem *pubkeyItem = new QTableWidgetItem(QString::fromStdString(fFound ? CBitcoinAddress(infoMn.keyIDCollateralAddress).ToString() : "")); + QTableWidgetItem* aliasItem = new QTableWidgetItem(strAlias); + QTableWidgetItem* addrItem = new QTableWidgetItem(fFound ? QString::fromStdString(infoMn.addr.ToString()) : strAddr); + QTableWidgetItem* protocolItem = new QTableWidgetItem(QString::number(fFound ? infoMn.nProtocolVersion : -1)); + QTableWidgetItem* statusItem = new QTableWidgetItem(QString::fromStdString(fFound ? CMasternode::StateToString(infoMn.nActiveState) : "MISSING")); + QTableWidgetItem* activeSecondsItem = new QTableWidgetItem(QString::fromStdString(DurationToDHMS(fFound ? (infoMn.nTimeLastPing - infoMn.sigTime) : 0))); + QTableWidgetItem* lastSeenItem = new QTableWidgetItem(QString::fromStdString(DateTimeStrFormat("%Y-%m-%d %H:%M", + fFound ? infoMn.nTimeLastPing + GetOffsetFromUtc() : 0))); + QTableWidgetItem* pubkeyItem = new QTableWidgetItem(QString::fromStdString(fFound ? CBitcoinAddress(infoMn.keyIDCollateralAddress).ToString() : "")); ui->tableWidgetMyMasternodes->setItem(nNewRow, 0, aliasItem); ui->tableWidgetMyMasternodes->setItem(nNewRow, 1, addrItem); @@ -229,7 +229,7 @@ void MasternodeList::updateMyMasternodeInfo(QString strAlias, QString strAddr, c void MasternodeList::updateMyNodeList(bool fForce) { TRY_LOCK(cs_mymnlist, fLockAcquired); - if(!fLockAcquired) { + if (!fLockAcquired) { return; } static int64_t nTimeMyListUpdated = 0; @@ -239,7 +239,7 @@ void MasternodeList::updateMyNodeList(bool fForce) int64_t nSecondsTillUpdate = nTimeMyListUpdated + MY_MASTERNODELIST_UPDATE_SECONDS - GetTime(); ui->secondsLabel->setText(QString::number(nSecondsTillUpdate)); - if(nSecondsTillUpdate > 0 && !fForce) return; + if (nSecondsTillUpdate > 0 && !fForce) return; nTimeMyListUpdated = GetTime(); // Find selected row @@ -250,7 +250,7 @@ void MasternodeList::updateMyNodeList(bool fForce) ui->tableWidgetMyMasternodes->setSortingEnabled(false); for (const auto& mne : masternodeConfig.getEntries()) { int32_t nOutputIndex = 0; - if(!ParseInt32(mne.getOutputIndex(), &nOutputIndex)) { + if (!ParseInt32(mne.getOutputIndex(), &nOutputIndex)) { continue; } @@ -266,7 +266,7 @@ void MasternodeList::updateMyNodeList(bool fForce) void MasternodeList::updateNodeList() { TRY_LOCK(cs_mnlist, fLockAcquired); - if(!fLockAcquired) { + if (!fLockAcquired) { return; } @@ -275,11 +275,11 @@ void MasternodeList::updateNodeList() // to prevent high cpu usage update only once in MASTERNODELIST_UPDATE_SECONDS seconds // or MASTERNODELIST_FILTER_COOLDOWN_SECONDS seconds after filter was last changed int64_t nSecondsToWait = fFilterUpdated - ? nTimeFilterUpdated - GetTime() + MASTERNODELIST_FILTER_COOLDOWN_SECONDS - : nTimeListUpdated - GetTime() + MASTERNODELIST_UPDATE_SECONDS; + ? nTimeFilterUpdated - GetTime() + MASTERNODELIST_FILTER_COOLDOWN_SECONDS + : nTimeListUpdated - GetTime() + MASTERNODELIST_UPDATE_SECONDS; - if(fFilterUpdated) ui->countLabel->setText(QString::fromStdString(strprintf("Please wait... %d", nSecondsToWait))); - if(nSecondsToWait > 0) return; + if (fFilterUpdated) ui->countLabel->setText(QString::fromStdString(strprintf("Please wait... %d", nSecondsToWait))); + if (nSecondsToWait > 0) return; nTimeListUpdated = GetTime(); fFilterUpdated = false; @@ -292,26 +292,24 @@ void MasternodeList::updateNodeList() std::map mapMasternodes = mnodeman.GetFullMasternodeMap(); int offsetFromUtc = GetOffsetFromUtc(); - for (const auto& mnpair : mapMasternodes) - { + for (const auto& mnpair : mapMasternodes) { CMasternode mn = mnpair.second; // populate list // Address, Protocol, Status, Active Seconds, Last Seen, Pub Key - QTableWidgetItem *addressItem = new QTableWidgetItem(QString::fromStdString(mn.addr.ToString())); - QTableWidgetItem *protocolItem = new QTableWidgetItem(QString::number(mn.nProtocolVersion)); - QTableWidgetItem *statusItem = new QTableWidgetItem(QString::fromStdString(mn.GetStatus())); - QTableWidgetItem *activeSecondsItem = new QTableWidgetItem(QString::fromStdString(DurationToDHMS(mn.lastPing.sigTime - mn.sigTime))); - QTableWidgetItem *lastSeenItem = new QTableWidgetItem(QString::fromStdString(DateTimeStrFormat("%Y-%m-%d %H:%M", mn.lastPing.sigTime + offsetFromUtc))); - QTableWidgetItem *pubkeyItem = new QTableWidgetItem(QString::fromStdString(CBitcoinAddress(mn.keyIDCollateralAddress).ToString())); - - if (strCurrentFilter != "") - { - strToFilter = addressItem->text() + " " + - protocolItem->text() + " " + - statusItem->text() + " " + - activeSecondsItem->text() + " " + - lastSeenItem->text() + " " + - pubkeyItem->text(); + QTableWidgetItem* addressItem = new QTableWidgetItem(QString::fromStdString(mn.addr.ToString())); + QTableWidgetItem* protocolItem = new QTableWidgetItem(QString::number(mn.nProtocolVersion)); + QTableWidgetItem* statusItem = new QTableWidgetItem(QString::fromStdString(mn.GetStatus())); + QTableWidgetItem* activeSecondsItem = new QTableWidgetItem(QString::fromStdString(DurationToDHMS(mn.lastPing.sigTime - mn.sigTime))); + QTableWidgetItem* lastSeenItem = new QTableWidgetItem(QString::fromStdString(DateTimeStrFormat("%Y-%m-%d %H:%M", mn.lastPing.sigTime + offsetFromUtc))); + QTableWidgetItem* pubkeyItem = new QTableWidgetItem(QString::fromStdString(CBitcoinAddress(mn.keyIDCollateralAddress).ToString())); + + if (strCurrentFilter != "") { + strToFilter = addressItem->text() + " " + + protocolItem->text() + " " + + statusItem->text() + " " + + activeSecondsItem->text() + " " + + lastSeenItem->text() + " " + + pubkeyItem->text(); if (!strToFilter.contains(strCurrentFilter)) continue; } @@ -328,7 +326,7 @@ void MasternodeList::updateNodeList() ui->tableWidgetMasternodes->setSortingEnabled(true); } -void MasternodeList::on_filterLineEdit_textChanged(const QString &strFilterIn) +void MasternodeList::on_filterLineEdit_textChanged(const QString& strFilterIn) { strCurrentFilter = strFilterIn; nTimeFilterUpdated = GetTime(); @@ -345,7 +343,7 @@ void MasternodeList::on_startButton_clicked() QItemSelectionModel* selectionModel = ui->tableWidgetMyMasternodes->selectionModel(); QModelIndexList selected = selectionModel->selectedRows(); - if(selected.count() == 0) return; + if (selected.count() == 0) return; QModelIndex index = selected.at(0); int nSelectedRow = index.row(); @@ -358,14 +356,14 @@ void MasternodeList::on_startButton_clicked() QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); - if(retval != QMessageBox::Yes) return; + if (retval != QMessageBox::Yes) return; WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus(); - if(encStatus == walletModel->Locked || encStatus == walletModel->UnlockedForMixingOnly) { + if (encStatus == walletModel->Locked || encStatus == walletModel->UnlockedForMixingOnly) { WalletModel::UnlockContext ctx(walletModel->requestUnlock()); - if(!ctx.isValid()) return; // Unlock wallet was cancelled + if (!ctx.isValid()) return; // Unlock wallet was cancelled StartAlias(strAlias); return; @@ -382,14 +380,14 @@ void MasternodeList::on_startAllButton_clicked() QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); - if(retval != QMessageBox::Yes) return; + if (retval != QMessageBox::Yes) return; WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus(); - if(encStatus == walletModel->Locked || encStatus == walletModel->UnlockedForMixingOnly) { + if (encStatus == walletModel->Locked || encStatus == walletModel->UnlockedForMixingOnly) { WalletModel::UnlockContext ctx(walletModel->requestUnlock()); - if(!ctx.isValid()) return; // Unlock wallet was cancelled + if (!ctx.isValid()) return; // Unlock wallet was cancelled StartAll(); return; @@ -400,8 +398,7 @@ void MasternodeList::on_startAllButton_clicked() void MasternodeList::on_startMissingButton_clicked() { - - if(!masternodeSync.IsMasternodeListSynced()) { + if (!masternodeSync.IsMasternodeListSynced()) { QMessageBox::critical(this, tr("Command is not available right now"), tr("You can't use this command until masternode list is synced")); return; @@ -414,14 +411,14 @@ void MasternodeList::on_startMissingButton_clicked() QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); - if(retval != QMessageBox::Yes) return; + if (retval != QMessageBox::Yes) return; WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus(); - if(encStatus == walletModel->Locked || encStatus == walletModel->UnlockedForMixingOnly) { + if (encStatus == walletModel->Locked || encStatus == walletModel->UnlockedForMixingOnly) { WalletModel::UnlockContext ctx(walletModel->requestUnlock()); - if(!ctx.isValid()) return; // Unlock wallet was cancelled + if (!ctx.isValid()) return; // Unlock wallet was cancelled StartAll("start-missing"); return; @@ -432,7 +429,7 @@ void MasternodeList::on_startMissingButton_clicked() void MasternodeList::on_tableWidgetMyMasternodes_itemSelectionChanged() { - if(ui->tableWidgetMyMasternodes->selectedItems().count() > 0) { + if (ui->tableWidgetMyMasternodes->selectedItems().count() > 0) { ui->startButton->setEnabled(true); } } @@ -451,7 +448,7 @@ void MasternodeList::on_QRButton_clicked() QItemSelectionModel* selectionModel = ui->tableWidgetMyMasternodes->selectionModel(); QModelIndexList selected = selectionModel->selectedRows(); - if(selected.count() == 0) return; + if (selected.count() == 0) return; QModelIndex index = selected.at(0); int nSelectedRow = index.row(); @@ -461,9 +458,9 @@ void MasternodeList::on_QRButton_clicked() ShowQRCode(strAlias); } -void MasternodeList::ShowQRCode(std::string strAlias) { - - if(!walletModel || !walletModel->getOptionsModel()) +void MasternodeList::ShowQRCode(std::string strAlias) +{ + if (!walletModel || !walletModel->getOptionsModel()) return; // Get private key for this alias @@ -491,22 +488,22 @@ void MasternodeList::ShowQRCode(std::string strAlias) { // Create dialog text as HTML QString strHTML = ""; - strHTML += "" + tr("Alias") + ": " + GUIUtil::HtmlEscape(strAlias) + "
"; - strHTML += "" + tr("Private Key") + ": " + GUIUtil::HtmlEscape(strMNPrivKey) + "
"; - strHTML += "" + tr("Collateral") + ": " + GUIUtil::HtmlEscape(strCollateral) + "
"; - strHTML += "" + tr("IP") + ": " + GUIUtil::HtmlEscape(strIP) + "
"; + strHTML += "" + tr("Alias") + ": " + GUIUtil::HtmlEscape(strAlias) + "
"; + strHTML += "" + tr("Private Key") + ": " + GUIUtil::HtmlEscape(strMNPrivKey) + "
"; + strHTML += "" + tr("Collateral") + ": " + GUIUtil::HtmlEscape(strCollateral) + "
"; + strHTML += "" + tr("IP") + ": " + GUIUtil::HtmlEscape(strIP) + "
"; if (fFound) { - strHTML += "" + tr("Protocol") + ": " + QString::number(mn.nProtocolVersion) + "
"; - strHTML += "" + tr("Version") + ": " + (mn.lastPing.nDaemonVersion > DEFAULT_DAEMON_VERSION ? GUIUtil::HtmlEscape(FormatVersion(mn.lastPing.nDaemonVersion)) : tr("Unknown")) + "
"; - strHTML += "" + tr("Sentinel") + ": " + (mn.lastPing.nSentinelVersion > DEFAULT_SENTINEL_VERSION ? GUIUtil::HtmlEscape(SafeIntVersionToString(mn.lastPing.nSentinelVersion)) : tr("Unknown")) + "
"; - strHTML += "" + tr("Status") + ": " + GUIUtil::HtmlEscape(CMasternode::StateToString(mn.nActiveState)) + "
"; - strHTML += "" + tr("Payee") + ": " + GUIUtil::HtmlEscape(CBitcoinAddress(mn.pubKeyCollateralAddress.GetID()).ToString()) + "
"; - strHTML += "" + tr("Active") + ": " + GUIUtil::HtmlEscape(DurationToDHMS(mn.lastPing.sigTime - mn.sigTime)) + "
"; - strHTML += "" + tr("Last Seen") + ": " + GUIUtil::HtmlEscape(DateTimeStrFormat("%Y-%m-%d %H:%M", mn.lastPing.sigTime + GetOffsetFromUtc())) + "
"; + strHTML += "" + tr("Protocol") + ": " + QString::number(mn.nProtocolVersion) + "
"; + strHTML += "" + tr("Version") + ": " + (mn.lastPing.nDaemonVersion > DEFAULT_DAEMON_VERSION ? GUIUtil::HtmlEscape(FormatVersion(mn.lastPing.nDaemonVersion)) : tr("Unknown")) + "
"; + strHTML += "" + tr("Sentinel") + ": " + (mn.lastPing.nSentinelVersion > DEFAULT_SENTINEL_VERSION ? GUIUtil::HtmlEscape(SafeIntVersionToString(mn.lastPing.nSentinelVersion)) : tr("Unknown")) + "
"; + strHTML += "" + tr("Status") + ": " + GUIUtil::HtmlEscape(CMasternode::StateToString(mn.nActiveState)) + "
"; + strHTML += "" + tr("Payee") + ": " + GUIUtil::HtmlEscape(CBitcoinAddress(mn.pubKeyCollateralAddress.GetID()).ToString()) + "
"; + strHTML += "" + tr("Active") + ": " + GUIUtil::HtmlEscape(DurationToDHMS(mn.lastPing.sigTime - mn.sigTime)) + "
"; + strHTML += "" + tr("Last Seen") + ": " + GUIUtil::HtmlEscape(DateTimeStrFormat("%Y-%m-%d %H:%M", mn.lastPing.sigTime + GetOffsetFromUtc())) + "
"; } // Open QR dialog - QRDialog *dialog = new QRDialog(this); + QRDialog* dialog = new QRDialog(this); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setModel(walletModel->getOptionsModel()); dialog->setInfo(strWindowtitle, QString::fromStdString(strMNPrivKey), strHTML, strQRCodeTitle); diff --git a/src/qt/masternodelist.h b/src/qt/masternodelist.h index 8a6ef5445e53..34eb3d0b89f4 100644 --- a/src/qt/masternodelist.h +++ b/src/qt/masternodelist.h @@ -1,8 +1,8 @@ #ifndef MASTERNODELIST_H #define MASTERNODELIST_H -#include "primitives/transaction.h" #include "platformstyle.h" +#include "primitives/transaction.h" #include "sync.h" #include "util.h" @@ -10,12 +10,13 @@ #include #include -#define MY_MASTERNODELIST_UPDATE_SECONDS 60 -#define MASTERNODELIST_UPDATE_SECONDS 15 -#define MASTERNODELIST_FILTER_COOLDOWN_SECONDS 3 +#define MY_MASTERNODELIST_UPDATE_SECONDS 60 +#define MASTERNODELIST_UPDATE_SECONDS 15 +#define MASTERNODELIST_FILTER_COOLDOWN_SECONDS 3 -namespace Ui { - class MasternodeList; +namespace Ui +{ +class MasternodeList; } class ClientModel; @@ -31,17 +32,17 @@ class MasternodeList : public QWidget Q_OBJECT public: - explicit MasternodeList(const PlatformStyle *platformStyle, QWidget *parent = 0); + explicit MasternodeList(const PlatformStyle* platformStyle, QWidget* parent = 0); ~MasternodeList(); - void setClientModel(ClientModel *clientModel); - void setWalletModel(WalletModel *walletModel); + void setClientModel(ClientModel* clientModel); + void setWalletModel(WalletModel* walletModel); void ShowQRCode(std::string strAlias); void StartAlias(std::string strAlias); void StartAll(std::string strCommand = "start-all"); private: - QMenu *contextMenu; + QMenu* contextMenu; int64_t nTimeFilterUpdated; bool fFilterUpdated; @@ -54,10 +55,10 @@ public Q_SLOTS: void doubleClicked(const QModelIndex&); private: - QTimer *timer; - Ui::MasternodeList *ui; - ClientModel *clientModel; - WalletModel *walletModel; + QTimer* timer; + Ui::MasternodeList* ui; + ClientModel* clientModel; + WalletModel* walletModel; // Protects tableWidgetMasternodes CCriticalSection cs_mnlist; @@ -68,8 +69,8 @@ public Q_SLOTS: QString strCurrentFilter; private Q_SLOTS: - void showContextMenu(const QPoint &); - void on_filterLineEdit_textChanged(const QString &strFilterIn); + void showContextMenu(const QPoint&); + void on_filterLineEdit_textChanged(const QString& strFilterIn); void on_QRButton_clicked(); void on_startButton_clicked(); void on_startAllButton_clicked(); diff --git a/src/rpc/governance.cpp b/src/rpc/governance.cpp index 4084fbfbcade..a84e49212697 100644 --- a/src/rpc/governance.cpp +++ b/src/rpc/governance.cpp @@ -4,22 +4,22 @@ //#define ENABLE_DASH_DEBUG +#include "governance.h" #include "activemasternode.h" #include "consensus/validation.h" -#include "governance.h" -#include "governance-vote.h" #include "governance-classes.h" #include "governance-validators.h" +#include "governance-vote.h" #include "init.h" -#include "validation.h" -#include "masternode.h" #include "masternode-sync.h" +#include "masternode.h" #include "masternodeconfig.h" #include "masternodeman.h" #include "messagesigner.h" #include "rpc/server.h" #include "util.h" #include "utilmoneystr.h" +#include "validation.h" #ifdef ENABLE_WALLET #include "wallet/wallet.h" #endif // ENABLE_WALLET @@ -29,11 +29,10 @@ bool EnsureWalletIsAvailable(bool avoidException); void gobject_count_help() { throw std::runtime_error( - "gobject count (\"mode\")\n" - "Count governance objects and votes\n" - "\nArguments:\n" - "1. \"mode\" (string, optional, default: \"json\") Output format: json (\"json\") or string in free form (\"all\")\n" - ); + "gobject count (\"mode\")\n" + "Count governance objects and votes\n" + "\nArguments:\n" + "1. \"mode\" (string, optional, default: \"json\") Output format: json (\"json\") or string in free form (\"all\")\n"); } UniValue gobject_count(const JSONRPCRequest& request) @@ -56,11 +55,10 @@ UniValue gobject_count(const JSONRPCRequest& request) void gobject_deserialize_help() { throw std::runtime_error( - "gobject deserialize \"hex_data\"\n" - "Deserialize governance object from hex string to JSON\n" - "\nArguments:\n" - "1. \"hex_data\" (string, required) data in hex string form\n" - ); + "gobject deserialize \"hex_data\"\n" + "Deserialize governance object from hex string to JSON\n" + "\nArguments:\n" + "1. \"hex_data\" (string, required) data in hex string form\n"); } UniValue gobject_deserialize(const JSONRPCRequest& request) @@ -82,11 +80,10 @@ UniValue gobject_deserialize(const JSONRPCRequest& request) void gobject_check_help() { throw std::runtime_error( - "gobject check \"hex_data\"\n" - "Validate governance object data (proposal only)\n" - "\nArguments:\n" - "1. \"hex_data\" (string, required) data in hex string form\n" - ); + "gobject check \"hex_data\"\n" + "Validate governance object data (proposal only)\n" + "\nArguments:\n" + "1. \"hex_data\" (string, required) data in hex string form\n"); } UniValue gobject_check(const JSONRPCRequest& request) @@ -107,7 +104,7 @@ UniValue gobject_check(const JSONRPCRequest& request) if (govobj.GetObjectType() == GOVERNANCE_OBJECT_PROPOSAL) { CProposalValidator validator(strDataHex); - if (!validator.Validate()) { + if (!validator.Validate()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid proposal data, error messages:" + validator.GetErrorMessages()); } } else { @@ -125,14 +122,13 @@ UniValue gobject_check(const JSONRPCRequest& request) void gobject_prepare_help() { throw std::runtime_error( - "gobject prepare