dash/src/masternode.h

410 lines
14 KiB
C
Raw Normal View History

2016-12-20 14:26:45 +01:00
// Copyright (c) 2014-2017 The Dash Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef MASTERNODE_H
#define MASTERNODE_H
#include "key.h"
#include "validation.h"
#include "spork.h"
class CMasternode;
class CMasternodeBroadcast;
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_EXPIRATION_SECONDS = 65 * 60;
static const int MASTERNODE_WATCHDOG_MAX_SECONDS = 120 * 60;
static const int MASTERNODE_NEW_START_REQUIRED_SECONDS = 180 * 60;
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
//
// sentinel version before sentinel ping implementation
#define DEFAULT_SENTINEL_VERSION 0x010001
class CMasternodePing
{
public:
CTxIn vin{};
uint256 blockHash{};
int64_t sigTime{}; //mnb message times
std::vector<unsigned char> vchSig{};
bool fSentinelIsCurrent = false; // true if last sentinel ping was actual
// MSB is always 0, other 3 bits corresponds to x.x.x version scheme
uint32_t nSentinelVersion{DEFAULT_SENTINEL_VERSION};
CMasternodePing() = default;
CMasternodePing(const COutPoint& outpoint);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(vin);
READWRITE(blockHash);
READWRITE(sigTime);
READWRITE(vchSig);
if(ser_action.ForRead() && (s.size() == 0))
{
fSentinelIsCurrent = false;
nSentinelVersion = DEFAULT_SENTINEL_VERSION;
return;
}
READWRITE(fSentinelIsCurrent);
READWRITE(nSentinelVersion);
}
uint256 GetHash() const
{
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << vin;
ss << sigTime;
return ss.GetHash();
}
bool IsExpired() const { return GetAdjustedTime() - sigTime > MASTERNODE_NEW_START_REQUIRED_SECONDS; }
bool Sign(const CKey& keyMasternode, const CPubKey& pubKeyMasternode);
bool CheckSignature(CPubKey& pubKeyMasternode, int &nDos);
bool SimpleCheck(int& nDos);
2016-12-26 07:44:48 +01:00
bool CheckAndUpdate(CMasternode* pmn, bool fFromNewBroadcast, int& nDos);
void Relay();
};
inline bool operator==(const CMasternodePing& a, const CMasternodePing& b)
{
return a.vin == b.vin && a.blockHash == b.blockHash;
}
inline bool operator!=(const CMasternodePing& a, const CMasternodePing& b)
{
return !(a == b);
}
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;
masternode_info_t(masternode_info_t const&) = default;
masternode_info_t(int activeState, int protoVer, int64_t sTime) :
nActiveState{activeState}, nProtocolVersion{protoVer}, sigTime{sTime} {}
masternode_info_t(int activeState, int protoVer, int64_t sTime,
COutPoint const& outpoint, CService const& addr,
CPubKey const& pkCollAddr, CPubKey const& pkMN,
int64_t tWatchdogV = 0) :
nActiveState{activeState}, nProtocolVersion{protoVer}, sigTime{sTime},
vin{outpoint}, addr{addr},
pubKeyCollateralAddress{pkCollAddr}, pubKeyMasternode{pkMN},
nTimeLastWatchdogVote{tWatchdogV} {}
int nActiveState = 0;
int nProtocolVersion = 0;
int64_t sigTime = 0; //mnb message time
CTxIn vin{};
CService addr{};
CPubKey pubKeyCollateralAddress{};
CPubKey pubKeyMasternode{};
int64_t nTimeLastWatchdogVote = 0;
int64_t nLastDsq = 0; //the dsq count from the last dsq broadcast of this node
int64_t nTimeLastChecked = 0;
int64_t nTimeLastPaid = 0;
int64_t nTimeLastPing = 0; //* not in CMN
bool fInfoValid = false; //* not in CMN
V0.12.1.x sentinel watchdog pr (#1079) Squashed: * Replaced unsafe mnodeman.Find function with Get in governance-vote.cpp * Reject unparsable governance objects * Implemented sentinel watchdog objects (separated out from locking changes) * Added WATCHDOG support to rpcgovernance.cpp * Implemented WATCHDOG_EXPIRED state for masternodes * Added serialization of watchdog timestamps * Masternode fixes - Added version check to CMasternodeMan deserialization - Added several missing locking calls in CMasternodeMan * Fixed missing member initialization in CMasternode constructor and added more logging * Added MASTERNODE_WATCHDOG_MAX_SECONDS to governanceinfo * Added masternodewatchdogmaxseconds info to getgovernanceinfo help * Make masternodes remain in WATCHDOG_EXPIRED state unless removed or collateral expires * Allow watchdog object creation by WATCHDOG_EXPIRED MN * Fixed MN validation logic for governance object creation * Count total masternodes instead of enabled masternodes in masternode-sync * Transition out of WATCHDOG_EXPIRED state if the watchdog is inactive * Fixed IsWatchdogExpired bug * Fixed rate check for watchdog objects and no longer check MN state when validating governance objects * Applied PR #1061 patch * Ported locking changes from other branch * Require only 1 block between new watchdog objects * Accept pings for WATCHDOG_EXPIRED masternodes * Lock CmasternodeMan::cs in CmasternodeMan::ProcessMessage * Several governance changes - Fixed uninitialized value in CGovernancePayment class - Return an error on submission if any superblock payment cannot be parsed - Added logging more statements * Explicitly initialize all governance object members * Fix deadlock * Fixed non-threadsafe access to masternode in activemasternode.cpp * Revert added wallet lock * Changed CActiveMasternode so that watchdog expired nodes can still send pings * Modified CActiveMasternode to run pinger regardless of state when MN is in list * Added voter and time information to getvotes command * Improved CActiveMasternode state management * Implemented GetInfo functions for more efficient thread-safe access to masternode information * Added CActiveMasternode debug logging messages * Fixed initial type setting and error message for incorrect protocol version * Changes based on code review comments * Set active state for local mode
2016-10-17 20:54:28 +02:00
};
//
2015-03-05 09:10:15 +01:00
// The Masternode Class. For managing the Darksend process. It contains the input of the 1000DRK, signature to prove
// it's the one who own that ip address and code for calculating the payment election.
//
class CMasternode : public masternode_info_t
{
private:
// critical section to protect the inner data structures
mutable CCriticalSection cs;
public:
2015-03-24 02:59:12 +01:00
enum state {
MASTERNODE_PRE_ENABLED,
MASTERNODE_ENABLED,
MASTERNODE_EXPIRED,
MASTERNODE_OUTPOINT_SPENT,
MASTERNODE_UPDATE_REQUIRED,
2016-10-20 23:11:30 +02:00
MASTERNODE_WATCHDOG_EXPIRED,
MASTERNODE_NEW_START_REQUIRED,
2016-10-20 23:11:30 +02:00
MASTERNODE_POSE_BAN
2015-03-24 02:59:12 +01:00
};
enum CollateralStatus {
COLLATERAL_OK,
COLLATERAL_UTXO_NOT_FOUND,
COLLATERAL_INVALID_AMOUNT
};
CMasternodePing lastPing{};
std::vector<unsigned char> vchSig{};
uint256 nCollateralMinConfBlockHash{};
int nBlockLastPaid{};
int nPoSeBanScore{};
int nPoSeBanHeight{};
bool fAllowMixingTx{};
bool fUnitTest = false;
Merge #944: V0.12.1.x governance pr - part 1 - base functionality 068c178 Added DBG macro in util.h to facilitate debugging - This macro allows debugging statements (typically printf's or cout's) to be activated or deactivated with a single comment. Uncomment the line: //#define ENABLE_DASH_DEBUG in util.h to enable debugging statements. - When commented any code wrapped with the DBG() macro will simply be removed by the preprocessor. When not commented all such wrapped statements will be present. - For maximum effectiveness it is best that util.h be the first effective include in all source files. It is also possible to enable the macro for a single file by temporarily adding #define ENABLE_DASH_DEBUG to the top of the file. - Code committed to non-development branches should always have the define commented. d125d9b V0.12.1.x -- merging trigger/generic object/superblock changes for testnet phase II - This commit contains the core governance system changes for 0.12.1. Any unrelated changes have either been removed or moved to separate commits. 120724c File mode fixes - Changed mode 0755->0644 on several source files. c7f9e11 Updated todo reminders - Added reminder to revert temporary reduction of number of votes required to trigger superblock to 1 for testing 92adc98 Made CSuperblockManager::IsValidSuperblockHeight an inline function - This is for efficiency since this function is called often and is only 1 line of code. c050ed7 Added comment explaining rationale for no LOCK(cs) in CSuperblock::IsValid dc933fe Removed unused CSuperblockManager::IsBlockValid function decec88 Moved calls to SuperblockManager::IsValidSuperblockHeight into IsSuperblockTriggered. - Since calls to the later function are always protected by the former there's no reason to keep these separate and this simplifies the code in masternode-payments.cpp. 8672885 Reestablished expected value check for non-superblocks in IsBlockValueValid b01cbe0 Changes to IsBlockValueValid to fix rpc test failure a937c76 Changed include order to allow per file activation of the DBG macro d116aa5 Fixed IsValidSuperblockHeight logic - Note this has an effect on testing because we can now only create 1 superblock per day. Devs may need to temporarily change testnet params for easier testing. 2d0c2de Convert superblock payments to CAmount - We assume that payment values in JSON are in units of DASH for consistency with other RPC functions, such as createrawtransaction. 376b833 Revert temporary testing value for nAbsVoteReq - Also ensure that number of votes required is never smaller than 1 8c89f4b Cleaned up CSuperblock error handling - Exceptions are now thrown consistently rather than using a mix of exceptions and return code checking. Exceptions are now caught only in AddNewTrigger when the CSuperblock constructor is called. Unnecessary object status members have been removed. d7c8a6b Removed utilstrencodings header - This appears to help with travis tests, for unknown reasons. c4dfc7a Fixed some minor code review issues 63c3580 Reverted locking change in miner. - This should have been done in the original PR but was overlooked. 4ab72de Fixed variable name to match common practice and bracket formatting 886a678 Improvements to vote conversion code - Replaced redundantly defined function with inclusion of governance-vote.h - Replaced magic numbers with their corresponding constant symbols 0a37966 Reordered governance message handling
2016-08-17 09:08:25 +02:00
// KEEP TRACK OF GOVERNANCE ITEMS EACH MASTERNODE HAS VOTE UPON FOR RECALCULATION
V0.12.1.x sentinel watchdog pr (#1079) Squashed: * Replaced unsafe mnodeman.Find function with Get in governance-vote.cpp * Reject unparsable governance objects * Implemented sentinel watchdog objects (separated out from locking changes) * Added WATCHDOG support to rpcgovernance.cpp * Implemented WATCHDOG_EXPIRED state for masternodes * Added serialization of watchdog timestamps * Masternode fixes - Added version check to CMasternodeMan deserialization - Added several missing locking calls in CMasternodeMan * Fixed missing member initialization in CMasternode constructor and added more logging * Added MASTERNODE_WATCHDOG_MAX_SECONDS to governanceinfo * Added masternodewatchdogmaxseconds info to getgovernanceinfo help * Make masternodes remain in WATCHDOG_EXPIRED state unless removed or collateral expires * Allow watchdog object creation by WATCHDOG_EXPIRED MN * Fixed MN validation logic for governance object creation * Count total masternodes instead of enabled masternodes in masternode-sync * Transition out of WATCHDOG_EXPIRED state if the watchdog is inactive * Fixed IsWatchdogExpired bug * Fixed rate check for watchdog objects and no longer check MN state when validating governance objects * Applied PR #1061 patch * Ported locking changes from other branch * Require only 1 block between new watchdog objects * Accept pings for WATCHDOG_EXPIRED masternodes * Lock CmasternodeMan::cs in CmasternodeMan::ProcessMessage * Several governance changes - Fixed uninitialized value in CGovernancePayment class - Return an error on submission if any superblock payment cannot be parsed - Added logging more statements * Explicitly initialize all governance object members * Fix deadlock * Fixed non-threadsafe access to masternode in activemasternode.cpp * Revert added wallet lock * Changed CActiveMasternode so that watchdog expired nodes can still send pings * Modified CActiveMasternode to run pinger regardless of state when MN is in list * Added voter and time information to getvotes command * Improved CActiveMasternode state management * Implemented GetInfo functions for more efficient thread-safe access to masternode information * Added CActiveMasternode debug logging messages * Fixed initial type setting and error message for incorrect protocol version * Changes based on code review comments * Set active state for local mode
2016-10-17 20:54:28 +02:00
std::map<uint256, int> mapGovernanceObjectsVotedOn;
Merge #944: V0.12.1.x governance pr - part 1 - base functionality 068c178 Added DBG macro in util.h to facilitate debugging - This macro allows debugging statements (typically printf's or cout's) to be activated or deactivated with a single comment. Uncomment the line: //#define ENABLE_DASH_DEBUG in util.h to enable debugging statements. - When commented any code wrapped with the DBG() macro will simply be removed by the preprocessor. When not commented all such wrapped statements will be present. - For maximum effectiveness it is best that util.h be the first effective include in all source files. It is also possible to enable the macro for a single file by temporarily adding #define ENABLE_DASH_DEBUG to the top of the file. - Code committed to non-development branches should always have the define commented. d125d9b V0.12.1.x -- merging trigger/generic object/superblock changes for testnet phase II - This commit contains the core governance system changes for 0.12.1. Any unrelated changes have either been removed or moved to separate commits. 120724c File mode fixes - Changed mode 0755->0644 on several source files. c7f9e11 Updated todo reminders - Added reminder to revert temporary reduction of number of votes required to trigger superblock to 1 for testing 92adc98 Made CSuperblockManager::IsValidSuperblockHeight an inline function - This is for efficiency since this function is called often and is only 1 line of code. c050ed7 Added comment explaining rationale for no LOCK(cs) in CSuperblock::IsValid dc933fe Removed unused CSuperblockManager::IsBlockValid function decec88 Moved calls to SuperblockManager::IsValidSuperblockHeight into IsSuperblockTriggered. - Since calls to the later function are always protected by the former there's no reason to keep these separate and this simplifies the code in masternode-payments.cpp. 8672885 Reestablished expected value check for non-superblocks in IsBlockValueValid b01cbe0 Changes to IsBlockValueValid to fix rpc test failure a937c76 Changed include order to allow per file activation of the DBG macro d116aa5 Fixed IsValidSuperblockHeight logic - Note this has an effect on testing because we can now only create 1 superblock per day. Devs may need to temporarily change testnet params for easier testing. 2d0c2de Convert superblock payments to CAmount - We assume that payment values in JSON are in units of DASH for consistency with other RPC functions, such as createrawtransaction. 376b833 Revert temporary testing value for nAbsVoteReq - Also ensure that number of votes required is never smaller than 1 8c89f4b Cleaned up CSuperblock error handling - Exceptions are now thrown consistently rather than using a mix of exceptions and return code checking. Exceptions are now caught only in AddNewTrigger when the CSuperblock constructor is called. Unnecessary object status members have been removed. d7c8a6b Removed utilstrencodings header - This appears to help with travis tests, for unknown reasons. c4dfc7a Fixed some minor code review issues 63c3580 Reverted locking change in miner. - This should have been done in the original PR but was overlooked. 4ab72de Fixed variable name to match common practice and bracket formatting 886a678 Improvements to vote conversion code - Replaced redundantly defined function with inclusion of governance-vote.h - Replaced magic numbers with their corresponding constant symbols 0a37966 Reordered governance message handling
2016-08-17 09:08:25 +02:00
CMasternode();
CMasternode(const CMasternode& other);
CMasternode(const CMasternodeBroadcast& mnb);
CMasternode(CService addrNew, COutPoint outpointNew, CPubKey pubKeyCollateralAddressNew, CPubKey pubKeyMasternodeNew, int nProtocolVersionIn);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
LOCK(cs);
READWRITE(vin);
READWRITE(addr);
READWRITE(pubKeyCollateralAddress);
READWRITE(pubKeyMasternode);
READWRITE(lastPing);
READWRITE(vchSig);
READWRITE(sigTime);
READWRITE(nLastDsq);
READWRITE(nTimeLastChecked);
READWRITE(nTimeLastPaid);
V0.12.1.x sentinel watchdog pr (#1079) Squashed: * Replaced unsafe mnodeman.Find function with Get in governance-vote.cpp * Reject unparsable governance objects * Implemented sentinel watchdog objects (separated out from locking changes) * Added WATCHDOG support to rpcgovernance.cpp * Implemented WATCHDOG_EXPIRED state for masternodes * Added serialization of watchdog timestamps * Masternode fixes - Added version check to CMasternodeMan deserialization - Added several missing locking calls in CMasternodeMan * Fixed missing member initialization in CMasternode constructor and added more logging * Added MASTERNODE_WATCHDOG_MAX_SECONDS to governanceinfo * Added masternodewatchdogmaxseconds info to getgovernanceinfo help * Make masternodes remain in WATCHDOG_EXPIRED state unless removed or collateral expires * Allow watchdog object creation by WATCHDOG_EXPIRED MN * Fixed MN validation logic for governance object creation * Count total masternodes instead of enabled masternodes in masternode-sync * Transition out of WATCHDOG_EXPIRED state if the watchdog is inactive * Fixed IsWatchdogExpired bug * Fixed rate check for watchdog objects and no longer check MN state when validating governance objects * Applied PR #1061 patch * Ported locking changes from other branch * Require only 1 block between new watchdog objects * Accept pings for WATCHDOG_EXPIRED masternodes * Lock CmasternodeMan::cs in CmasternodeMan::ProcessMessage * Several governance changes - Fixed uninitialized value in CGovernancePayment class - Return an error on submission if any superblock payment cannot be parsed - Added logging more statements * Explicitly initialize all governance object members * Fix deadlock * Fixed non-threadsafe access to masternode in activemasternode.cpp * Revert added wallet lock * Changed CActiveMasternode so that watchdog expired nodes can still send pings * Modified CActiveMasternode to run pinger regardless of state when MN is in list * Added voter and time information to getvotes command * Improved CActiveMasternode state management * Implemented GetInfo functions for more efficient thread-safe access to masternode information * Added CActiveMasternode debug logging messages * Fixed initial type setting and error message for incorrect protocol version * Changes based on code review comments * Set active state for local mode
2016-10-17 20:54:28 +02:00
READWRITE(nTimeLastWatchdogVote);
READWRITE(nActiveState);
READWRITE(nCollateralMinConfBlockHash);
READWRITE(nBlockLastPaid);
READWRITE(nProtocolVersion);
2016-10-20 23:11:30 +02:00
READWRITE(nPoSeBanScore);
READWRITE(nPoSeBanHeight);
READWRITE(fAllowMixingTx);
READWRITE(fUnitTest);
V0.12.1.x sentinel watchdog pr (#1079) Squashed: * Replaced unsafe mnodeman.Find function with Get in governance-vote.cpp * Reject unparsable governance objects * Implemented sentinel watchdog objects (separated out from locking changes) * Added WATCHDOG support to rpcgovernance.cpp * Implemented WATCHDOG_EXPIRED state for masternodes * Added serialization of watchdog timestamps * Masternode fixes - Added version check to CMasternodeMan deserialization - Added several missing locking calls in CMasternodeMan * Fixed missing member initialization in CMasternode constructor and added more logging * Added MASTERNODE_WATCHDOG_MAX_SECONDS to governanceinfo * Added masternodewatchdogmaxseconds info to getgovernanceinfo help * Make masternodes remain in WATCHDOG_EXPIRED state unless removed or collateral expires * Allow watchdog object creation by WATCHDOG_EXPIRED MN * Fixed MN validation logic for governance object creation * Count total masternodes instead of enabled masternodes in masternode-sync * Transition out of WATCHDOG_EXPIRED state if the watchdog is inactive * Fixed IsWatchdogExpired bug * Fixed rate check for watchdog objects and no longer check MN state when validating governance objects * Applied PR #1061 patch * Ported locking changes from other branch * Require only 1 block between new watchdog objects * Accept pings for WATCHDOG_EXPIRED masternodes * Lock CmasternodeMan::cs in CmasternodeMan::ProcessMessage * Several governance changes - Fixed uninitialized value in CGovernancePayment class - Return an error on submission if any superblock payment cannot be parsed - Added logging more statements * Explicitly initialize all governance object members * Fix deadlock * Fixed non-threadsafe access to masternode in activemasternode.cpp * Revert added wallet lock * Changed CActiveMasternode so that watchdog expired nodes can still send pings * Modified CActiveMasternode to run pinger regardless of state when MN is in list * Added voter and time information to getvotes command * Improved CActiveMasternode state management * Implemented GetInfo functions for more efficient thread-safe access to masternode information * Added CActiveMasternode debug logging messages * Fixed initial type setting and error message for incorrect protocol version * Changes based on code review comments * Set active state for local mode
2016-10-17 20:54:28 +02:00
READWRITE(mapGovernanceObjectsVotedOn);
}
Merge #944: V0.12.1.x governance pr - part 1 - base functionality 068c178 Added DBG macro in util.h to facilitate debugging - This macro allows debugging statements (typically printf's or cout's) to be activated or deactivated with a single comment. Uncomment the line: //#define ENABLE_DASH_DEBUG in util.h to enable debugging statements. - When commented any code wrapped with the DBG() macro will simply be removed by the preprocessor. When not commented all such wrapped statements will be present. - For maximum effectiveness it is best that util.h be the first effective include in all source files. It is also possible to enable the macro for a single file by temporarily adding #define ENABLE_DASH_DEBUG to the top of the file. - Code committed to non-development branches should always have the define commented. d125d9b V0.12.1.x -- merging trigger/generic object/superblock changes for testnet phase II - This commit contains the core governance system changes for 0.12.1. Any unrelated changes have either been removed or moved to separate commits. 120724c File mode fixes - Changed mode 0755->0644 on several source files. c7f9e11 Updated todo reminders - Added reminder to revert temporary reduction of number of votes required to trigger superblock to 1 for testing 92adc98 Made CSuperblockManager::IsValidSuperblockHeight an inline function - This is for efficiency since this function is called often and is only 1 line of code. c050ed7 Added comment explaining rationale for no LOCK(cs) in CSuperblock::IsValid dc933fe Removed unused CSuperblockManager::IsBlockValid function decec88 Moved calls to SuperblockManager::IsValidSuperblockHeight into IsSuperblockTriggered. - Since calls to the later function are always protected by the former there's no reason to keep these separate and this simplifies the code in masternode-payments.cpp. 8672885 Reestablished expected value check for non-superblocks in IsBlockValueValid b01cbe0 Changes to IsBlockValueValid to fix rpc test failure a937c76 Changed include order to allow per file activation of the DBG macro d116aa5 Fixed IsValidSuperblockHeight logic - Note this has an effect on testing because we can now only create 1 superblock per day. Devs may need to temporarily change testnet params for easier testing. 2d0c2de Convert superblock payments to CAmount - We assume that payment values in JSON are in units of DASH for consistency with other RPC functions, such as createrawtransaction. 376b833 Revert temporary testing value for nAbsVoteReq - Also ensure that number of votes required is never smaller than 1 8c89f4b Cleaned up CSuperblock error handling - Exceptions are now thrown consistently rather than using a mix of exceptions and return code checking. Exceptions are now caught only in AddNewTrigger when the CSuperblock constructor is called. Unnecessary object status members have been removed. d7c8a6b Removed utilstrencodings header - This appears to help with travis tests, for unknown reasons. c4dfc7a Fixed some minor code review issues 63c3580 Reverted locking change in miner. - This should have been done in the original PR but was overlooked. 4ab72de Fixed variable name to match common practice and bracket formatting 886a678 Improvements to vote conversion code - Replaced redundantly defined function with inclusion of governance-vote.h - Replaced magic numbers with their corresponding constant symbols 0a37966 Reordered governance message handling
2016-08-17 09:08:25 +02:00
// CALCULATE A RANK AGAINST OF GIVEN BLOCK
arith_uint256 CalculateScore(const uint256& blockHash);
bool UpdateFromNewBroadcast(CMasternodeBroadcast& mnb);
static CollateralStatus CheckCollateral(const COutPoint& outpoint);
static CollateralStatus CheckCollateral(const COutPoint& outpoint, int& nHeightRet);
void Check(bool fForce = false);
bool IsBroadcastedWithin(int nSeconds) { return GetAdjustedTime() - sigTime < nSeconds; }
bool IsPingedWithin(int nSeconds, int64_t nTimeToCheckAt = -1)
{
if(lastPing == CMasternodePing()) return false;
if(nTimeToCheckAt == -1) {
nTimeToCheckAt = GetAdjustedTime();
}
return nTimeToCheckAt - lastPing.sigTime < nSeconds;
}
bool IsEnabled() { return nActiveState == MASTERNODE_ENABLED; }
bool IsPreEnabled() { return nActiveState == MASTERNODE_PRE_ENABLED; }
2016-10-20 23:11:30 +02:00
bool IsPoSeBanned() { return nActiveState == MASTERNODE_POSE_BAN; }
// NOTE: this one relies on nPoSeBanScore, not on nActiveState as everything else here
2016-10-20 23:11:30 +02:00
bool IsPoSeVerified() { return nPoSeBanScore <= -MASTERNODE_POSE_BAN_MAX_SCORE; }
bool IsExpired() { return nActiveState == MASTERNODE_EXPIRED; }
bool IsOutpointSpent() { return nActiveState == MASTERNODE_OUTPOINT_SPENT; }
bool IsUpdateRequired() { return nActiveState == MASTERNODE_UPDATE_REQUIRED; }
V0.12.1.x sentinel watchdog pr (#1079) Squashed: * Replaced unsafe mnodeman.Find function with Get in governance-vote.cpp * Reject unparsable governance objects * Implemented sentinel watchdog objects (separated out from locking changes) * Added WATCHDOG support to rpcgovernance.cpp * Implemented WATCHDOG_EXPIRED state for masternodes * Added serialization of watchdog timestamps * Masternode fixes - Added version check to CMasternodeMan deserialization - Added several missing locking calls in CMasternodeMan * Fixed missing member initialization in CMasternode constructor and added more logging * Added MASTERNODE_WATCHDOG_MAX_SECONDS to governanceinfo * Added masternodewatchdogmaxseconds info to getgovernanceinfo help * Make masternodes remain in WATCHDOG_EXPIRED state unless removed or collateral expires * Allow watchdog object creation by WATCHDOG_EXPIRED MN * Fixed MN validation logic for governance object creation * Count total masternodes instead of enabled masternodes in masternode-sync * Transition out of WATCHDOG_EXPIRED state if the watchdog is inactive * Fixed IsWatchdogExpired bug * Fixed rate check for watchdog objects and no longer check MN state when validating governance objects * Applied PR #1061 patch * Ported locking changes from other branch * Require only 1 block between new watchdog objects * Accept pings for WATCHDOG_EXPIRED masternodes * Lock CmasternodeMan::cs in CmasternodeMan::ProcessMessage * Several governance changes - Fixed uninitialized value in CGovernancePayment class - Return an error on submission if any superblock payment cannot be parsed - Added logging more statements * Explicitly initialize all governance object members * Fix deadlock * Fixed non-threadsafe access to masternode in activemasternode.cpp * Revert added wallet lock * Changed CActiveMasternode so that watchdog expired nodes can still send pings * Modified CActiveMasternode to run pinger regardless of state when MN is in list * Added voter and time information to getvotes command * Improved CActiveMasternode state management * Implemented GetInfo functions for more efficient thread-safe access to masternode information * Added CActiveMasternode debug logging messages * Fixed initial type setting and error message for incorrect protocol version * Changes based on code review comments * Set active state for local mode
2016-10-17 20:54:28 +02:00
bool IsWatchdogExpired() { return nActiveState == MASTERNODE_WATCHDOG_EXPIRED; }
bool IsNewStartRequired() { return nActiveState == MASTERNODE_NEW_START_REQUIRED; }
static bool IsValidStateForAutoStart(int nActiveStateIn)
{
return nActiveStateIn == MASTERNODE_ENABLED ||
nActiveStateIn == MASTERNODE_PRE_ENABLED ||
nActiveStateIn == MASTERNODE_EXPIRED ||
nActiveStateIn == MASTERNODE_WATCHDOG_EXPIRED;
}
V0.12.1.x sentinel watchdog pr (#1079) Squashed: * Replaced unsafe mnodeman.Find function with Get in governance-vote.cpp * Reject unparsable governance objects * Implemented sentinel watchdog objects (separated out from locking changes) * Added WATCHDOG support to rpcgovernance.cpp * Implemented WATCHDOG_EXPIRED state for masternodes * Added serialization of watchdog timestamps * Masternode fixes - Added version check to CMasternodeMan deserialization - Added several missing locking calls in CMasternodeMan * Fixed missing member initialization in CMasternode constructor and added more logging * Added MASTERNODE_WATCHDOG_MAX_SECONDS to governanceinfo * Added masternodewatchdogmaxseconds info to getgovernanceinfo help * Make masternodes remain in WATCHDOG_EXPIRED state unless removed or collateral expires * Allow watchdog object creation by WATCHDOG_EXPIRED MN * Fixed MN validation logic for governance object creation * Count total masternodes instead of enabled masternodes in masternode-sync * Transition out of WATCHDOG_EXPIRED state if the watchdog is inactive * Fixed IsWatchdogExpired bug * Fixed rate check for watchdog objects and no longer check MN state when validating governance objects * Applied PR #1061 patch * Ported locking changes from other branch * Require only 1 block between new watchdog objects * Accept pings for WATCHDOG_EXPIRED masternodes * Lock CmasternodeMan::cs in CmasternodeMan::ProcessMessage * Several governance changes - Fixed uninitialized value in CGovernancePayment class - Return an error on submission if any superblock payment cannot be parsed - Added logging more statements * Explicitly initialize all governance object members * Fix deadlock * Fixed non-threadsafe access to masternode in activemasternode.cpp * Revert added wallet lock * Changed CActiveMasternode so that watchdog expired nodes can still send pings * Modified CActiveMasternode to run pinger regardless of state when MN is in list * Added voter and time information to getvotes command * Improved CActiveMasternode state management * Implemented GetInfo functions for more efficient thread-safe access to masternode information * Added CActiveMasternode debug logging messages * Fixed initial type setting and error message for incorrect protocol version * Changes based on code review comments * Set active state for local mode
2016-10-17 20:54:28 +02:00
bool IsValidForPayment()
{
if(nActiveState == MASTERNODE_ENABLED) {
return true;
}
if(!sporkManager.IsSporkActive(SPORK_14_REQUIRE_SENTINEL_FLAG) &&
(nActiveState == MASTERNODE_WATCHDOG_EXPIRED)) {
return true;
}
return false;
}
/// Is the input associated with collateral public key? (and there is 1000 DASH - checking if valid masternode)
bool IsInputAssociatedWithPubkey();
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 PoSeBan() { nPoSeBanScore = MASTERNODE_POSE_BAN_MAX_SCORE; }
V0.12.1.x sentinel watchdog pr (#1079) Squashed: * Replaced unsafe mnodeman.Find function with Get in governance-vote.cpp * Reject unparsable governance objects * Implemented sentinel watchdog objects (separated out from locking changes) * Added WATCHDOG support to rpcgovernance.cpp * Implemented WATCHDOG_EXPIRED state for masternodes * Added serialization of watchdog timestamps * Masternode fixes - Added version check to CMasternodeMan deserialization - Added several missing locking calls in CMasternodeMan * Fixed missing member initialization in CMasternode constructor and added more logging * Added MASTERNODE_WATCHDOG_MAX_SECONDS to governanceinfo * Added masternodewatchdogmaxseconds info to getgovernanceinfo help * Make masternodes remain in WATCHDOG_EXPIRED state unless removed or collateral expires * Allow watchdog object creation by WATCHDOG_EXPIRED MN * Fixed MN validation logic for governance object creation * Count total masternodes instead of enabled masternodes in masternode-sync * Transition out of WATCHDOG_EXPIRED state if the watchdog is inactive * Fixed IsWatchdogExpired bug * Fixed rate check for watchdog objects and no longer check MN state when validating governance objects * Applied PR #1061 patch * Ported locking changes from other branch * Require only 1 block between new watchdog objects * Accept pings for WATCHDOG_EXPIRED masternodes * Lock CmasternodeMan::cs in CmasternodeMan::ProcessMessage * Several governance changes - Fixed uninitialized value in CGovernancePayment class - Return an error on submission if any superblock payment cannot be parsed - Added logging more statements * Explicitly initialize all governance object members * Fix deadlock * Fixed non-threadsafe access to masternode in activemasternode.cpp * Revert added wallet lock * Changed CActiveMasternode so that watchdog expired nodes can still send pings * Modified CActiveMasternode to run pinger regardless of state when MN is in list * Added voter and time information to getvotes command * Improved CActiveMasternode state management * Implemented GetInfo functions for more efficient thread-safe access to masternode information * Added CActiveMasternode debug logging messages * Fixed initial type setting and error message for incorrect protocol version * Changes based on code review comments * Set active state for local mode
2016-10-17 20:54:28 +02:00
masternode_info_t GetInfo();
static std::string StateToString(int nStateIn);
std::string GetStateString() const;
std::string GetStatus() const;
int GetLastPaidTime() { return nTimeLastPaid; }
int GetLastPaidBlock() { return nBlockLastPaid; }
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);
// RECALCULATE CACHED STATUS FLAGS FOR ALL AFFECTED OBJECTS
void FlagGovernanceItemsAsDirty();
V0.12.1.x sentinel watchdog pr (#1079) Squashed: * Replaced unsafe mnodeman.Find function with Get in governance-vote.cpp * Reject unparsable governance objects * Implemented sentinel watchdog objects (separated out from locking changes) * Added WATCHDOG support to rpcgovernance.cpp * Implemented WATCHDOG_EXPIRED state for masternodes * Added serialization of watchdog timestamps * Masternode fixes - Added version check to CMasternodeMan deserialization - Added several missing locking calls in CMasternodeMan * Fixed missing member initialization in CMasternode constructor and added more logging * Added MASTERNODE_WATCHDOG_MAX_SECONDS to governanceinfo * Added masternodewatchdogmaxseconds info to getgovernanceinfo help * Make masternodes remain in WATCHDOG_EXPIRED state unless removed or collateral expires * Allow watchdog object creation by WATCHDOG_EXPIRED MN * Fixed MN validation logic for governance object creation * Count total masternodes instead of enabled masternodes in masternode-sync * Transition out of WATCHDOG_EXPIRED state if the watchdog is inactive * Fixed IsWatchdogExpired bug * Fixed rate check for watchdog objects and no longer check MN state when validating governance objects * Applied PR #1061 patch * Ported locking changes from other branch * Require only 1 block between new watchdog objects * Accept pings for WATCHDOG_EXPIRED masternodes * Lock CmasternodeMan::cs in CmasternodeMan::ProcessMessage * Several governance changes - Fixed uninitialized value in CGovernancePayment class - Return an error on submission if any superblock payment cannot be parsed - Added logging more statements * Explicitly initialize all governance object members * Fix deadlock * Fixed non-threadsafe access to masternode in activemasternode.cpp * Revert added wallet lock * Changed CActiveMasternode so that watchdog expired nodes can still send pings * Modified CActiveMasternode to run pinger regardless of state when MN is in list * Added voter and time information to getvotes command * Improved CActiveMasternode state management * Implemented GetInfo functions for more efficient thread-safe access to masternode information * Added CActiveMasternode debug logging messages * Fixed initial type setting and error message for incorrect protocol version * Changes based on code review comments * Set active state for local mode
2016-10-17 20:54:28 +02:00
void RemoveGovernanceObject(uint256 nGovernanceObjectHash);
void UpdateWatchdogVoteTime(uint64_t nVoteTime = 0);
CMasternode& operator=(CMasternode const& from)
{
static_cast<masternode_info_t&>(*this)=from;
lastPing = from.lastPing;
vchSig = from.vchSig;
nCollateralMinConfBlockHash = from.nCollateralMinConfBlockHash;
nBlockLastPaid = from.nBlockLastPaid;
nPoSeBanScore = from.nPoSeBanScore;
nPoSeBanHeight = from.nPoSeBanHeight;
fAllowMixingTx = from.fAllowMixingTx;
fUnitTest = from.fUnitTest;
mapGovernanceObjectsVotedOn = from.mapGovernanceObjectsVotedOn;
return *this;
}
};
inline bool operator==(const CMasternode& a, const CMasternode& b)
{
return a.vin == b.vin;
}
inline bool operator!=(const CMasternode& a, const CMasternode& b)
{
return !(a.vin == b.vin);
}
//
// The Masternode Broadcast Class : Contains a different serialize method for sending masternodes through the network
//
class CMasternodeBroadcast : public CMasternode
{
public:
bool fRecovery;
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 <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(vin);
READWRITE(addr);
READWRITE(pubKeyCollateralAddress);
READWRITE(pubKeyMasternode);
READWRITE(vchSig);
READWRITE(sigTime);
READWRITE(nProtocolVersion);
READWRITE(lastPing);
}
uint256 GetHash() const
{
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << vin;
ss << pubKeyCollateralAddress;
ss << sigTime;
return ss.GetHash();
}
/// 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(std::string strService, std::string strKey, std::string strTxHash, std::string strOutputIndex, std::string& strErrorRet, CMasternodeBroadcast &mnbRet, bool fOffline = false);
2016-10-20 23:11:30 +02:00
bool SimpleCheck(int& nDos);
bool Update(CMasternode* pmn, int& nDos);
bool CheckOutpoint(int& nDos);
bool Sign(const CKey& keyCollateralAddress);
bool CheckSignature(int& nDos);
void Relay();
};
2016-10-20 23:11:30 +02:00
class CMasternodeVerification
{
public:
CTxIn vin1{};
CTxIn vin2{};
CService addr{};
int nonce{};
int nBlockHeight{};
std::vector<unsigned char> vchSig1{};
std::vector<unsigned char> vchSig2{};
CMasternodeVerification() = default;
2016-10-20 23:11:30 +02:00
CMasternodeVerification(CService addr, int nonce, int nBlockHeight) :
addr(addr),
nonce(nonce),
nBlockHeight(nBlockHeight)
{}
2016-10-20 23:11:30 +02:00
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(vin1);
READWRITE(vin2);
READWRITE(addr);
READWRITE(nonce);
READWRITE(nBlockHeight);
READWRITE(vchSig1);
READWRITE(vchSig2);
}
uint256 GetHash() const
{
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << vin1;
ss << vin2;
ss << addr;
ss << nonce;
ss << nBlockHeight;
return ss.GetHash();
}
void Relay() const
{
CInv inv(MSG_MASTERNODE_VERIFY, GetHash());
Backport Bitcoin PR#8085: p2p: Begin encapsulation (#1537) * net: move CBanDB and CAddrDB out of net.h/cpp This will eventually solve a circular dependency * net: Create CConnman to encapsulate p2p connections * net: Move socket binding into CConnman * net: move OpenNetworkConnection into CConnman * net: move ban and addrman functions into CConnman * net: Add oneshot functions to CConnman * net: move added node functions to CConnman * net: Add most functions needed for vNodes to CConnman * net: handle nodesignals in CConnman * net: Pass CConnection to wallet rather than using the global * net: Add rpc error for missing/disabled p2p functionality * net: Pass CConnman around as needed * gui: add NodeID to the peer table * net: create generic functor accessors and move vNodes to CConnman * net: move whitelist functions into CConnman * net: move nLastNodeId to CConnman * net: move nLocalHostNonce to CConnman This behavior seems to have been quite racy and broken. Move nLocalHostNonce into CNode, and check received nonces against all non-fully-connected nodes. If there's a match, assume we've connected to ourself. * net: move messageHandlerCondition to CConnman * net: move send/recv statistics to CConnman * net: move SendBufferSize/ReceiveFloodSize to CConnman * net: move nLocalServices/nRelevantServices to CConnman These are in-turn passed to CNode at connection time. This allows us to offer different services to different peers (or test the effects of doing so). * net: move semOutbound and semMasternodeOutbound to CConnman * net: SocketSendData returns written size * net: move max/max-outbound to CConnman * net: Pass best block known height into CConnman CConnman then passes the current best height into CNode at creation time. This way CConnman/CNode have no dependency on main for height, and the signals only move in one direction. This also helps to prevent identity leakage a tiny bit. Before this change, an attacker could theoretically make 2 connections on different interfaces. They would connect fully on one, and only establish the initial connection on the other. Once they receive a new block, they would relay it to your first connection, and immediately commence the version handshake on the second. Since the new block height is reflected immediately, they could attempt to learn whether the two connections were correlated. This is, of course, incredibly unlikely to work due to the small timings involved and receipt from other senders. But it doesn't hurt to lock-in nBestHeight at the time of connection, rather than letting the remote choose the time. * net: pass CClientUIInterface into CConnman * net: Drop StartNode/StopNode and use CConnman directly * net: Introduce CConnection::Options to avoid passing so many params * net: add nSendBufferMaxSize/nReceiveFloodSize to CConnection::Options * net: move vNodesDisconnected into CConnman * Made the ForEachNode* functions in src/net.cpp more pragmatic and self documenting * Convert ForEachNode* functions to take a templated function argument rather than a std::function to eliminate std::function overhead * net: move MAX_FEELER_CONNECTIONS into connman
2017-07-21 11:35:19 +02:00
g_connman->RelayInv(inv);
2016-10-20 23:11:30 +02:00
}
};
#endif