dash/src/activemasternode.cpp

194 lines
7.0 KiB
C++
Raw Normal View History

// Copyright (c) 2014-2019 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "activemasternode.h"
#include "evo/deterministicmns.h"
#include "init.h"
#include "masternode-sync.h"
#include "netbase.h"
#include "protocol.h"
#include "validation.h"
#include "warnings.h"
// Keep track of the active Masternode
CActiveMasternodeInfo activeMasternodeInfo;
CActiveMasternodeManager* activeMasternodeManager;
std::string CActiveMasternodeManager::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_OPERATOR_KEY_CHANGED:
return "OPERATOR_KEY_CHANGED";
case MASTERNODE_READY:
return "READY";
case MASTERNODE_ERROR:
return "ERROR";
default:
return "UNKNOWN";
}
}
std::string CActiveMasternodeManager::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_OPERATOR_KEY_CHANGED:
return "Operator key changed or revoked";
case MASTERNODE_READY:
return "Ready";
case MASTERNODE_ERROR:
return "Error. " + strError;
default:
return "Unknown";
}
}
void CActiveMasternodeManager::Init()
{
LOCK(cs_main);
if (!fMasternodeMode) return;
if (!deterministicMNManager->IsDIP3Enforced()) return;
// Check that our local network configuration is correct
if (!fListen) {
// listen option is probably overwritten by smth else, no good
state = MASTERNODE_ERROR;
strError = "Masternode must accept connections from outside. Make sure listen configuration option is not overwritten by some another parameter.";
LogPrintf("CActiveDeterministicMasternodeManager::Init -- ERROR: %s\n", strError);
return;
}
if (!GetLocalAddress(activeMasternodeInfo.service)) {
state = MASTERNODE_ERROR;
return;
}
CDeterministicMNList mnList = deterministicMNManager->GetListAtChainTip();
CDeterministicMNCPtr dmn = mnList.GetMNByOperatorKey(*activeMasternodeInfo.blsPubKeyOperator);
if (!dmn) {
// MN not appeared on the chain yet
return;
}
if (!mnList.IsMNValid(dmn->proTxHash)) {
if (mnList.IsMNPoSeBanned(dmn->proTxHash)) {
state = MASTERNODE_POSE_BANNED;
} else {
state = MASTERNODE_REMOVED;
}
return;
}
mnListEntry = dmn;
LogPrintf("CActiveMasternodeManager::Init -- proTxHash=%s, proTx=%s\n", mnListEntry->proTxHash.ToString(), mnListEntry->ToString());
if (activeMasternodeInfo.service != mnListEntry->pdmnState->addr) {
state = MASTERNODE_ERROR;
strError = "Local address does not match the address from ProTx";
LogPrintf("CActiveMasternodeManager::Init -- ERROR: %s", strError);
return;
}
if (Params().NetworkIDString() != CBaseChainParams::REGTEST) {
// Check socket connectivity
LogPrintf("CActiveDeterministicMasternodeManager::Init -- Checking inbound connection to '%s'\n", activeMasternodeInfo.service.ToString());
SOCKET hSocket;
bool fConnected = ConnectSocket(activeMasternodeInfo.service, hSocket, nConnectTimeout) && IsSelectableSocket(hSocket);
CloseSocket(hSocket);
if (!fConnected) {
state = MASTERNODE_ERROR;
strError = "Could not connect to " + activeMasternodeInfo.service.ToString();
LogPrintf("CActiveDeterministicMasternodeManager::Init -- ERROR: %s\n", strError);
return;
}
}
activeMasternodeInfo.proTxHash = mnListEntry->proTxHash;
2018-10-25 16:29:50 +02:00
activeMasternodeInfo.outpoint = mnListEntry->collateralOutpoint;
state = MASTERNODE_READY;
}
void CActiveMasternodeManager::UpdatedBlockTip(const CBlockIndex* pindexNew, const CBlockIndex* pindexFork, bool fInitialDownload)
{
LOCK(cs_main);
if (!fMasternodeMode) return;
if (!deterministicMNManager->IsDIP3Enforced(pindexNew->nHeight)) return;
if (state == MASTERNODE_READY) {
2018-10-25 16:29:50 +02:00
auto mnList = deterministicMNManager->GetListForBlock(pindexNew->GetBlockHash());
if (!mnList.IsMNValid(mnListEntry->proTxHash)) {
// MN disappeared from MN list
state = MASTERNODE_REMOVED;
activeMasternodeInfo.proTxHash = uint256();
activeMasternodeInfo.outpoint.SetNull();
// MN might have reappeared in same block with a new ProTx
Init();
} else if (mnList.GetMN(mnListEntry->proTxHash)->pdmnState->pubKeyOperator != mnListEntry->pdmnState->pubKeyOperator) {
// MN operator key changed or revoked
state = MASTERNODE_OPERATOR_KEY_CHANGED;
activeMasternodeInfo.proTxHash = uint256();
activeMasternodeInfo.outpoint.SetNull();
// MN might have reappeared in same block with a new ProTx
Init();
}
} else {
// MN might have (re)appeared with a new ProTx or we've found some peers and figured out our local address
Init();
}
}
bool CActiveMasternodeManager::GetLocalAddress(CService& addrRet)
{
// First try to find whatever local address is specified by externalip option
Remove all legacy/compatibility MN code (#2600) * Remove CActiveLegacyMasternodeManager * Remove sentinelping RPC * Remove unused P2P messages and inv types There are still places where these are used in the code. The next commits will clean these up. * Remove MNB/MNP/MNVERIFY related code from masternode(man).h/cpp * Remove all legacy code regarding block MN payee voting * Remove MASTERNODE_SYNC_LIST and MASTERNODE_SYNC_MNW states Also replace all uses of IsMasternodeListSynced and IsWinnersListSynced with IsBlockchainSynced. * Remove unsupported masternode RPCs * Remove UpdateLastPaid methods * Remove duplicate deterministicmns.h include * Remove masternode.conf support * Remove legacy MN lists support from masternode list GUI * Remove unnecessary AskForMN call * Remove compatibility code in CPrivateSendQueue::GetSignatureHash * Don't add locally calculated MN payee in case GetBlockTxOuts failed This is not valid in DIP3 mode * Remove check for IsDeterministicMNsSporkActive in "masternode status" * Move CMasternode::IsValidNetAddr to CActiveDeterministicMasternodeManager * Remove use of CMasternode::CheckCollateral in governance code * Remove uses of MASTERNODE_SENTINEL_PING_MAX_SECONDS/MASTERNODE_SENTINEL_PING_MAX_SECONDS * Remove support for "-masternodeprivkey" * Remove pre-DIP3 vote cleanup * Remove compatibility code for quorumModifierHash/masternodeProTxHash * Remove check for invalid nBlockHeight in CMasternodePayments::GetBlockTxOuts ...and let it crash instead. We expect this method to be called with the correct height now (after DIP3 was fully deployed). * Remove ECDSA based Sign/CheckSignature from CGovernanceObject Only masternodes sign governance objects, so there is no need for ECDSA support here anymore. * Always add superblock and MN reward payments into new block * Always check block payees (except if fLiteMode==true) * Always allow superblock and MN payees in same block * Remove/Fix a few references to masternode.conf and related stuff Also delete guide-startmany.md and masternode_conf.md * Implement NotifyMasternodeListChanged signal and call governance maintenance * Remove non-DIP3 code path from CMasternodeMan::Find * Remove remaining unused code from CMasternode/CMasternodeMan * Always load governance.dat on startup * Mine an empty block instead of incrementing nHeight from chain tip in miner tests This test is crashing otherwise in GetBlockTxOuts as it tries to access a previous block that is not existing. * Skip MN payments verification on historical blocks (pre-DIP3 blocks) Even though DIP3 was active on BIP9 level, the spork was not active yet at that point meaning that payments were not enforced at that time. * Remove unused state and CollateralStatus enums * Unconditionally return false from IsBlockPayeeValid when IsTransactionValid returns false IsTransactionValid already handles the case where IsDIP3Active() returns false, making it return true. * Add override keyword to CDSNotificationInterface::NotifyMasternodeListChanged * Fix help for masternodelist status (POSE_BANNED and no OUTPOINT_SPENT)
2019-01-03 10:17:43 +01:00
bool fFoundLocal = GetLocal(addrRet) && IsValidNetAddr(addrRet);
if (!fFoundLocal && Params().NetworkIDString() == CBaseChainParams::REGTEST) {
if (Lookup("127.0.0.1", addrRet, GetListenPort(), false)) {
fFoundLocal = true;
}
}
if (!fFoundLocal) {
bool empty = true;
// If we have some peers, let's try to find our local address from one of them
g_connman->ForEachNodeContinueIf(CConnman::AllNodes, [&fFoundLocal, &empty](CNode* pnode) {
empty = false;
if (pnode->addr.IsIPv4())
Remove all legacy/compatibility MN code (#2600) * Remove CActiveLegacyMasternodeManager * Remove sentinelping RPC * Remove unused P2P messages and inv types There are still places where these are used in the code. The next commits will clean these up. * Remove MNB/MNP/MNVERIFY related code from masternode(man).h/cpp * Remove all legacy code regarding block MN payee voting * Remove MASTERNODE_SYNC_LIST and MASTERNODE_SYNC_MNW states Also replace all uses of IsMasternodeListSynced and IsWinnersListSynced with IsBlockchainSynced. * Remove unsupported masternode RPCs * Remove UpdateLastPaid methods * Remove duplicate deterministicmns.h include * Remove masternode.conf support * Remove legacy MN lists support from masternode list GUI * Remove unnecessary AskForMN call * Remove compatibility code in CPrivateSendQueue::GetSignatureHash * Don't add locally calculated MN payee in case GetBlockTxOuts failed This is not valid in DIP3 mode * Remove check for IsDeterministicMNsSporkActive in "masternode status" * Move CMasternode::IsValidNetAddr to CActiveDeterministicMasternodeManager * Remove use of CMasternode::CheckCollateral in governance code * Remove uses of MASTERNODE_SENTINEL_PING_MAX_SECONDS/MASTERNODE_SENTINEL_PING_MAX_SECONDS * Remove support for "-masternodeprivkey" * Remove pre-DIP3 vote cleanup * Remove compatibility code for quorumModifierHash/masternodeProTxHash * Remove check for invalid nBlockHeight in CMasternodePayments::GetBlockTxOuts ...and let it crash instead. We expect this method to be called with the correct height now (after DIP3 was fully deployed). * Remove ECDSA based Sign/CheckSignature from CGovernanceObject Only masternodes sign governance objects, so there is no need for ECDSA support here anymore. * Always add superblock and MN reward payments into new block * Always check block payees (except if fLiteMode==true) * Always allow superblock and MN payees in same block * Remove/Fix a few references to masternode.conf and related stuff Also delete guide-startmany.md and masternode_conf.md * Implement NotifyMasternodeListChanged signal and call governance maintenance * Remove non-DIP3 code path from CMasternodeMan::Find * Remove remaining unused code from CMasternode/CMasternodeMan * Always load governance.dat on startup * Mine an empty block instead of incrementing nHeight from chain tip in miner tests This test is crashing otherwise in GetBlockTxOuts as it tries to access a previous block that is not existing. * Skip MN payments verification on historical blocks (pre-DIP3 blocks) Even though DIP3 was active on BIP9 level, the spork was not active yet at that point meaning that payments were not enforced at that time. * Remove unused state and CollateralStatus enums * Unconditionally return false from IsBlockPayeeValid when IsTransactionValid returns false IsTransactionValid already handles the case where IsDIP3Active() returns false, making it return true. * Add override keyword to CDSNotificationInterface::NotifyMasternodeListChanged * Fix help for masternodelist status (POSE_BANNED and no OUTPOINT_SPENT)
2019-01-03 10:17:43 +01:00
fFoundLocal = GetLocal(activeMasternodeInfo.service, &pnode->addr) && IsValidNetAddr(activeMasternodeInfo.service);
return !fFoundLocal;
});
// nothing and no live connections, can't do anything for now
if (empty) {
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("CActiveMasternodeManager::GetLocalAddress -- ERROR: %s\n", strError);
return false;
}
}
return true;
}
bool CActiveMasternodeManager::IsValidNetAddr(CService addrIn)
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
{
Remove all legacy/compatibility MN code (#2600) * Remove CActiveLegacyMasternodeManager * Remove sentinelping RPC * Remove unused P2P messages and inv types There are still places where these are used in the code. The next commits will clean these up. * Remove MNB/MNP/MNVERIFY related code from masternode(man).h/cpp * Remove all legacy code regarding block MN payee voting * Remove MASTERNODE_SYNC_LIST and MASTERNODE_SYNC_MNW states Also replace all uses of IsMasternodeListSynced and IsWinnersListSynced with IsBlockchainSynced. * Remove unsupported masternode RPCs * Remove UpdateLastPaid methods * Remove duplicate deterministicmns.h include * Remove masternode.conf support * Remove legacy MN lists support from masternode list GUI * Remove unnecessary AskForMN call * Remove compatibility code in CPrivateSendQueue::GetSignatureHash * Don't add locally calculated MN payee in case GetBlockTxOuts failed This is not valid in DIP3 mode * Remove check for IsDeterministicMNsSporkActive in "masternode status" * Move CMasternode::IsValidNetAddr to CActiveDeterministicMasternodeManager * Remove use of CMasternode::CheckCollateral in governance code * Remove uses of MASTERNODE_SENTINEL_PING_MAX_SECONDS/MASTERNODE_SENTINEL_PING_MAX_SECONDS * Remove support for "-masternodeprivkey" * Remove pre-DIP3 vote cleanup * Remove compatibility code for quorumModifierHash/masternodeProTxHash * Remove check for invalid nBlockHeight in CMasternodePayments::GetBlockTxOuts ...and let it crash instead. We expect this method to be called with the correct height now (after DIP3 was fully deployed). * Remove ECDSA based Sign/CheckSignature from CGovernanceObject Only masternodes sign governance objects, so there is no need for ECDSA support here anymore. * Always add superblock and MN reward payments into new block * Always check block payees (except if fLiteMode==true) * Always allow superblock and MN payees in same block * Remove/Fix a few references to masternode.conf and related stuff Also delete guide-startmany.md and masternode_conf.md * Implement NotifyMasternodeListChanged signal and call governance maintenance * Remove non-DIP3 code path from CMasternodeMan::Find * Remove remaining unused code from CMasternode/CMasternodeMan * Always load governance.dat on startup * Mine an empty block instead of incrementing nHeight from chain tip in miner tests This test is crashing otherwise in GetBlockTxOuts as it tries to access a previous block that is not existing. * Skip MN payments verification on historical blocks (pre-DIP3 blocks) Even though DIP3 was active on BIP9 level, the spork was not active yet at that point meaning that payments were not enforced at that time. * Remove unused state and CollateralStatus enums * Unconditionally return false from IsBlockPayeeValid when IsTransactionValid returns false IsTransactionValid already handles the case where IsDIP3Active() returns false, making it return true. * Add override keyword to CDSNotificationInterface::NotifyMasternodeListChanged * Fix help for masternodelist status (POSE_BANNED and no OUTPOINT_SPENT)
2019-01-03 10:17:43 +01:00
// 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());
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
}