Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/cachemultimap.h
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,18 @@ class CacheMultiMap
return true;
}

bool GetAll(const K& key, const V& lower, const V& upper, std::vector<V>& vecValues) const
{
const map_cit mit = mapIndex.find(key);
if (mit == mapIndex.end() || upper < lower) return false;
const it_map_t& mapIt = mit->second;
const auto range_end = mapIt.upper_bound(upper);
for (auto it = mapIt.lower_bound(lower); it != range_end; ++it) {
vecValues.push_back(it->second->value);
}
return true;
}

void GetKeys(std::vector<K>& vecKeys)
{
for(map_cit it = mapIndex.begin(); it != mapIndex.end(); ++it) {
Expand Down
40 changes: 37 additions & 3 deletions src/governance/governance.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

#include <univalue.h>

#include <limits>
#include <ranges>

const std::string GovernanceStore::SERIALIZATION_VERSION_STRING = "CGovernanceManager-Version-17";
Expand All @@ -40,6 +41,39 @@ constexpr std::chrono::seconds MAX_TIME_FUTURE_DEVIATION{1h};
// Margin below MAX_TIME_FUTURE_DEVIATION so lagging-clock peers don't reject near-limit objects.
constexpr std::chrono::seconds RELIABLE_PROPAGATION_TIME{60};

// The encoding chooses which key to verify: IsValidForUnknownParent accepts only compact
// signatures by the voting key and BLS signatures by the operator key.
bool UsesVotingKey(const CGovernanceVote& vote)
{
return vote.GetSignal() == VOTE_SIGNAL_FUNDING && vote.GetSignatureSize() == CGovernanceVote::COMPACT_SIG_SIZE;
}

bool InsertOrphanVote(CacheMultiMap<uint256, governance::OrphanVote>& cache, const CDeterministicMNList& tip_mn_list,
const governance::OrphanVote& orphan_vote)
{
auto lower{orphan_vote};
auto upper{orphan_vote};
lower.vote.SetTime(std::numeric_limits<int64_t>::min());
lower.vote.SetSignature({});
upper.vote.SetTime(std::numeric_limits<int64_t>::max());
upper.vote.SetSignature(std::vector<unsigned char>(CGovernanceVote::BLS_SIG_SIZE));
std::vector<governance::OrphanVote> variants;
const auto& parent = orphan_vote.vote.GetParentHash();
cache.GetAll(parent, lower, upper, variants);
const bool use_voting_key{UsesVotingKey(orphan_vote.vote)};
for (const auto& cached : variants) {
const bool cached_uses_voting_key{UsesVotingKey(cached.vote)};
// Only current-key authentication may suppress a new vote.
if (cached.expiration < Now<NodeSeconds>() || !cached.vote.IsValid(tip_mn_list, cached_uses_voting_key)) {
cache.Erase(parent, cached);
} else if (cached_uses_voting_key == use_voting_key) {
if (cached.vote.GetTimestamp() >= orphan_vote.vote.GetTimestamp()) return false;
cache.Erase(parent, cached);
}
}
return cache.Insert(parent, orphan_vote);
}

bool IsSyncableObject(const std::shared_ptr<CGovernanceObject>& govobj)
{
const auto& obj = *Assert(govobj);
Expand Down Expand Up @@ -831,9 +865,8 @@ bool CGovernanceManager::ProcessVote(const CGovernanceVote& vote, CGovernanceExc
AssertLockNotHeld(cs_store);
hashToRequest = uint256{};

const auto tip_mn_list{m_dmnman.GetListAtChainTip()};

LOCK(cs_store);
const auto tip_mn_list{m_dmnman.GetListAtChainTip()};
uint256 nHashVote = vote.GetHash();
uint256 nHashGovobj = vote.GetParentHash();

Expand All @@ -857,7 +890,8 @@ bool CGovernanceManager::ProcessVote(const CGovernanceVote& vote, CGovernanceExc
// No penalty: the vote is signed by a masternode, it just arrived before its parent object,
// which routinely happens during governance sync. Misbehaviour scores never decay.
exception = CGovernanceException(msg, GOVERNANCE_EXCEPTION_WARNING);
if (cmmapOrphanVotes.Insert(nHashGovobj, governance::OrphanVote{vote, Now<NodeSeconds>() + GOVERNANCE_ORPHAN_EXPIRATION_TIME})) {
if (InsertOrphanVote(cmmapOrphanVotes, tip_mn_list,
governance::OrphanVote{vote, Now<NodeSeconds>() + GOVERNANCE_ORPHAN_EXPIRATION_TIME})) {
hashToRequest = nHashGovobj; // Caller should request this object
Comment on lines +893 to 895

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Suggestion: Route orphan-parent fetches through the request tracker

Each newer authenticated timestamp variant that replaces the cached candidate returns true from InsertOrphanVote, so this path sets hashToRequest again. NetGovernance::ProcessMessage then immediately sends an empty-filter MNGOVERNANCESYNC directly to the relaying peer, while the corresponding object-fetch branch is explicitly excluded from m_netfulfilledman tracking in net_governance.cpp. The cache cardinality is bounded, but the fetch-message count is not: a peer can continue submitting valid newer variants as time advances, resetting the orphan expiration and causing repeated object-fetch requests, and distinct parents or voters amplify the traffic. Move these fetches under the request tracker or otherwise deduplicate them, coordinating with #7886.

source: gpt-6.1-sol (phase2-reviewer: general)

}
LogPrint(BCLog::GOBJECT, "%s\n", msg);
Expand Down
2 changes: 2 additions & 0 deletions src/governance/governance.h
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ struct OrphanVote {

inline bool operator<(const OrphanVote& lhs, const OrphanVote& rhs)
{
// Equal signed fields may arrive authenticated by different voting/operator keys.
if (lhs.vote == rhs.vote) return lhs.vote.GetSignatureSize() < rhs.vote.GetSignatureSize();
return lhs.vote < rhs.vote;
}
} // namespace governance
Expand Down
31 changes: 4 additions & 27 deletions src/governance/vote.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
#include <timedata.h>
#include <util/string.h>

#include <tuple>

static_assert(CGovernanceVote::COMPACT_SIG_SIZE == CPubKey::COMPACT_SIGNATURE_SIZE);
static_assert(CGovernanceVote::BLS_SIG_SIZE == CBLSSignature::SerSize);

Expand Down Expand Up @@ -262,31 +264,6 @@ bool operator==(const CGovernanceVote& vote1, const CGovernanceVote& vote2)

bool operator<(const CGovernanceVote& vote1, const CGovernanceVote& vote2)
{
bool fResult = (vote1.masternodeOutpoint < vote2.masternodeOutpoint);
if (!fResult) {
return false;
}
fResult = (vote1.masternodeOutpoint == vote2.masternodeOutpoint);

fResult = fResult && (vote1.nParentHash < vote2.nParentHash);
if (!fResult) {
return false;
}
fResult = (vote1.nParentHash == vote2.nParentHash);

fResult = fResult && (vote1.nVoteOutcome < vote2.nVoteOutcome);
if (!fResult) {
return false;
}
fResult = (vote1.nVoteOutcome == vote2.nVoteOutcome);

fResult = fResult && (vote1.nVoteSignal == vote2.nVoteSignal);
if (!fResult) {
return false;
}
fResult = (vote1.nVoteSignal == vote2.nVoteSignal);

fResult = fResult && (vote1.nTime < vote2.nTime);

return fResult;
return std::tie(vote1.masternodeOutpoint, vote1.nParentHash, vote1.nVoteOutcome, vote1.nVoteSignal, vote1.nTime) <
std::tie(vote2.masternodeOutpoint, vote2.nParentHash, vote2.nVoteOutcome, vote2.nVoteSignal, vote2.nTime);
Comment thread
PastaPastaPasta marked this conversation as resolved.
Resolved
Comment thread
PastaPastaPasta marked this conversation as resolved.
Resolved
}
1 change: 1 addition & 0 deletions src/governance/vote.h
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ class CGovernanceVote
}

void SetSignature(const std::vector<unsigned char>& vchSigIn) { vchSig = vchSigIn; }
size_t GetSignatureSize() const { return vchSig.size(); }

bool CheckSignature(const CKeyID& keyID) const;
bool CheckSignature(const CBLSPublicKey& pubKey) const;
Expand Down
17 changes: 17 additions & 0 deletions src/test/cachemultimap_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -219,4 +219,21 @@ BOOST_AUTO_TEST_CASE(capacity_limits)
BOOST_CHECK(!cache.Insert(1, 1));
}

BOOST_AUTO_TEST_CASE(cachemultimap_get_all_in_value_range)
{
CacheMultiMap<int, int> cmmap(5);
for (const int value : {1, 2, 3, 4})
BOOST_REQUIRE(cmmap.Insert(1, value));
BOOST_REQUIRE(cmmap.Insert(2, 2));
std::vector<int> values;
BOOST_CHECK(cmmap.GetAll(1, 2, 3, values));
BOOST_CHECK(values == (std::vector<int>{2, 3}));
values.clear();
BOOST_CHECK(cmmap.GetAll(1, 5, 6, values));
BOOST_CHECK(values.empty());
BOOST_CHECK(!cmmap.GetAll(3, 1, 4, values));
BOOST_CHECK(!cmmap.GetAll(1, 3, 2, values));
BOOST_CHECK(values.empty());
}

BOOST_AUTO_TEST_SUITE_END()
166 changes: 166 additions & 0 deletions src/test/governance_vote_processing_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,24 @@ CGovernanceObject MakeFailedTrigger(const COutPoint& mn_collateral, const CBLSSe
return govobj;
}

struct GovernanceVoteNotifications final : CValidationInterface {
mutable Mutex cs;
std::vector<uint256> hashes GUARDED_BY(cs);

void NotifyGovernanceVote(const std::shared_ptr<CDeterministicMNList>&,
const std::shared_ptr<const CGovernanceVote>& vote) override EXCLUSIVE_LOCKS_REQUIRED(!cs)
{
LOCK(cs);
hashes.push_back(vote->GetHash());
}

std::vector<uint256> GetHashes() const EXCLUSIVE_LOCKS_REQUIRED(!cs)
{
LOCK(cs);
return hashes;
}
};

// A chain with one registered masternode whose voting (ECDSA) and operator (BLS) keys are known
// to the test, so votes can be signed for real and CGovernanceVote::CheckSignature is actually
// reached. Without a populated masternode list every CGovernanceVote::IsValid() call would
Expand All @@ -86,6 +104,7 @@ struct GovernanceVoteSetup : public TestChainSetup {
CBLSSecretKey mn_operator_key;
COutPoint mn_collateral;
SimpleUTXOMap utxos;
std::shared_ptr<GovernanceVoteNotifications> vote_notifications;
//! Fixed so a proposal can be rebuilt bit-for-bit (and keep its hash) once its fee tx is known.
int64_t proposal_time{0};
std::string proposal_payment_address;
Expand Down Expand Up @@ -139,6 +158,8 @@ struct GovernanceVoteSetup : public TestChainSetup {
*m_node.chainman, *m_node.sbman, *m_node.dmnman,
*m_node.mn_sync, m_node.gov_collateral_index.get());
BOOST_REQUIRE(m_node.govman->LoadCache(/*load_cache=*/false));
vote_notifications = std::make_shared<GovernanceVoteNotifications>();
RegisterSharedValidationInterface(vote_notifications);

proposal_time = TicksSinceEpoch<std::chrono::seconds>(GetAdjustedTime());
CKey payment_key;
Expand All @@ -148,6 +169,11 @@ struct GovernanceVoteSetup : public TestChainSetup {

void TearDown()
{
if (vote_notifications) {
SyncWithValidationInterfaceQueue();
UnregisterSharedValidationInterface(vote_notifications);
vote_notifications.reset();
}
// govman holds a reference to node.sbman, so it must go first (matches PrepareShutdown
// ordering in init.cpp).
m_node.govman.reset();
Expand Down Expand Up @@ -359,6 +385,146 @@ BOOST_AUTO_TEST_CASE(orphan_vote_is_cached_and_applied_when_parent_arrives)
BOOST_CHECK_EQUAL(stored->GetAbsoluteYesCount(tip_mn_list(), VOTE_SIGNAL_FUNDING), 1);
}

BOOST_AUTO_TEST_CASE(orphan_funding_votes_from_multiple_masternodes_are_applied)
{
CKey second_voting_key;
CBLSSecretKey second_operator_key;
const auto protx{CreateProRegTx(*m_node.chainman, utxos, /*port=*/2, payout_script(), coinbaseKey,
second_voting_key, second_operator_key)};
MineBlock({protx});
const COutPoint second_collateral{protx.GetHash(), 0};
BOOST_REQUIRE(tip_mn_list().GetMNByCollateral(second_collateral) != nullptr);

auto& govman = *m_node.govman;
const uint256 parent_hash{MakeProposal(uint256{}).GetHash()};
CGovernanceVote first_vote{MakeVote(parent_hash, VOTE_SIGNAL_FUNDING, VOTE_OUTCOME_YES)};
SignWithVotingKey(first_vote, mn_voting_key);
CGovernanceVote second_vote{second_collateral, parent_hash, VOTE_SIGNAL_FUNDING, VOTE_OUTCOME_YES};
SignWithVotingKey(second_vote, second_voting_key);

for (const auto& vote : {first_vote, second_vote, second_vote}) {
BOOST_REQUIRE(vote.IsValid(tip_mn_list(), /*useVotingKey=*/true));
CGovernanceException exception;
uint256 hash_to_request;
BOOST_CHECK(!govman.ProcessVote(vote, exception, hash_to_request));
BOOST_CHECK_EQUAL(exception.GetType(), GOVERNANCE_EXCEPTION_WARNING);
BOOST_CHECK_EQUAL(exception.GetNodePenalty(), 0);
}

const uint256 collateral_hash{ConfirmProposalCollateral(parent_hash)};
CGovernanceObject proposal{MakeProposal(collateral_hash)};
BOOST_REQUIRE_EQUAL(proposal.GetHash(), parent_hash);
govman.AddGovernanceObject(proposal, /*peer_str=*/"");
const auto stored{govman.FindConstGovernanceObject(parent_hash)};
BOOST_REQUIRE(stored != nullptr);
BOOST_CHECK_EQUAL(stored->GetAbsoluteYesCount(tip_mn_list(), VOTE_SIGNAL_FUNDING), 2);
const auto current_votes{govman.GetCurrentVotes(parent_hash, COutPoint{})};
BOOST_REQUIRE_EQUAL(current_votes.size(), 2U);
BOOST_CHECK(govman.GetOrphanVoteObjectHashes().empty());
}

BOOST_AUTO_TEST_CASE(orphan_timestamp_variants_replay_only_the_newest_vote)
{
auto& govman = *m_node.govman;
const uint256 parent_hash{MakeProposal(uint256{}).GetHash()};
uint256 newest_hash;
for (const int offset : {5, 1, 4, 3, 2, 5}) {
CGovernanceVote vote{MakeVote(parent_hash, VOTE_SIGNAL_FUNDING, VOTE_OUTCOME_YES, std::chrono::seconds{offset})};
SignWithVotingKey(vote, mn_voting_key);
if (offset == 5) newest_hash = vote.GetHash();
CGovernanceException exception;
uint256 hash_to_request;
BOOST_CHECK(!govman.ProcessVote(vote, exception, hash_to_request));
BOOST_CHECK_EQUAL(exception.GetNodePenalty(), 0);
}

const uint256 collateral_hash{ConfirmProposalCollateral(parent_hash)};
CGovernanceObject proposal{MakeProposal(collateral_hash)};
govman.AddGovernanceObject(proposal, /*peer_str=*/"");
SyncWithValidationInterfaceQueue();
BOOST_CHECK(vote_notifications->GetHashes() == std::vector<uint256>{newest_hash});
const auto stored{govman.FindConstGovernanceObject(parent_hash)};
BOOST_REQUIRE(stored != nullptr);
BOOST_CHECK_EQUAL(stored->GetAbsoluteYesCount(tip_mn_list(), VOTE_SIGNAL_FUNDING), 1);
const auto votes{govman.GetCurrentVotes(parent_hash, mn_collateral)};
BOOST_REQUIRE_EQUAL(votes.size(), 1U);
BOOST_CHECK_EQUAL(votes.front().GetHash(), newest_hash);
}

BOOST_AUTO_TEST_CASE(operator_orphans_do_not_displace_a_voting_key_orphan)
{
auto& govman = *m_node.govman;
const uint256 parent_hash{MakeProposal(uint256{}).GetHash()};
CGovernanceVote operator_vote{MakeVote(parent_hash, VOTE_SIGNAL_FUNDING, VOTE_OUTCOME_YES)};
SignWithOperatorKey(operator_vote, mn_operator_key);
CGovernanceVote voting_vote{operator_vote};
SignWithVotingKey(voting_vote, mn_voting_key);
CGovernanceVote newer_operator_vote{MakeVote(parent_hash, VOTE_SIGNAL_FUNDING, VOTE_OUTCOME_YES, 30s)};
SignWithOperatorKey(newer_operator_vote, mn_operator_key);
// The voting-key vote has the same signed fields as the first operator vote and is older than the second.
for (const auto& vote : {operator_vote, voting_vote, newer_operator_vote}) {
CGovernanceException exception;
uint256 hash_to_request;
BOOST_CHECK(!govman.ProcessVote(vote, exception, hash_to_request));
BOOST_CHECK_EQUAL(exception.GetNodePenalty(), 0);
}
const uint256 collateral_hash{ConfirmProposalCollateral(parent_hash)};
CGovernanceObject proposal{MakeProposal(collateral_hash)};
govman.AddGovernanceObject(proposal, /*peer_str=*/"");
SyncWithValidationInterfaceQueue();
BOOST_CHECK(vote_notifications->GetHashes() == std::vector<uint256>{voting_vote.GetHash()});
const auto votes{govman.GetCurrentVotes(parent_hash, mn_collateral)};
BOOST_REQUIRE_EQUAL(votes.size(), 1U);
BOOST_CHECK_EQUAL(votes.front().GetHash(), voting_vote.GetHash());
}

BOOST_AUTO_TEST_CASE(old_key_orphan_does_not_suppress_a_current_key_vote)
{
// Before DIP3 enforcement, registrar updates must keep the owner and voting keys equal.
MineBlocks(500 - tip_mn_list().GetHeight());
auto& govman = *m_node.govman;
const uint256 parent_hash{MakeProposal(uint256{}).GetHash()};
CGovernanceVote old_vote{MakeVote(parent_hash, VOTE_SIGNAL_FUNDING, VOTE_OUTCOME_YES, 30s)};
SignWithVotingKey(old_vote, mn_voting_key);
CGovernanceException exception;
uint256 hash_to_request;
BOOST_CHECK(!govman.ProcessVote(old_vote, exception, hash_to_request));
BOOST_CHECK_EQUAL(exception.GetNodePenalty(), 0);

CKey new_voting_key;
new_voting_key.MakeNewKey(true);
CProUpRegTx update;
update.nVersion = ProTxVersion::GetMax(!bls::bls_legacy_scheme, /*is_extended_addr=*/false);
update.proTxHash = mn_collateral.hash;
update.pubKeyOperator.Set(mn_operator_key.GetPublicKey(), update.nVersion == ProTxVersion::LegacyBLS);
update.keyIDVoting = new_voting_key.GetPubKey().GetID();
update.scriptPayout = payout_script();
CMutableTransaction tx;
tx.nVersion = 3;
tx.nType = TRANSACTION_PROVIDER_UPDATE_REGISTRAR;
const auto spent{FundTransaction(*m_node.chainman, tx, utxos, payout_script(), 1 * COIN)};
update.inputsHash = CalcTxInputsHash(CTransaction{tx});
BOOST_REQUIRE(CHashSigner::SignHash(SerializeHash(update), mn_voting_key, update.vchSig));
SetTxPayload(tx, update);
SignTransaction(tx, spent, coinbaseKey);
MineBlock({tx});
BOOST_REQUIRE(!old_vote.IsValid(tip_mn_list(), /*useVotingKey=*/true));

CGovernanceVote current_vote{MakeVote(parent_hash, VOTE_SIGNAL_FUNDING, VOTE_OUTCOME_YES, 1s)};
SignWithVotingKey(current_vote, new_voting_key);
BOOST_REQUIRE(current_vote.IsValid(tip_mn_list(), /*useVotingKey=*/true));
BOOST_CHECK(!govman.ProcessVote(current_vote, exception, hash_to_request));
BOOST_CHECK_EQUAL(exception.GetNodePenalty(), 0);
const uint256 collateral_hash{ConfirmProposalCollateral(parent_hash)};
CGovernanceObject proposal{MakeProposal(collateral_hash)};
govman.AddGovernanceObject(proposal, /*peer_str=*/"");
SyncWithValidationInterfaceQueue();
BOOST_CHECK(vote_notifications->GetHashes() == std::vector<uint256>{current_vote.GetHash()});
const auto votes{govman.GetCurrentVotes(parent_hash, mn_collateral)};
BOOST_REQUIRE_EQUAL(votes.size(), 1U);
BOOST_CHECK_EQUAL(votes.front().GetHash(), current_vote.GetHash());
}

// Votes are only counted if they carry a signature from a registered masternode.
BOOST_AUTO_TEST_CASE(unsigned_and_unknown_masternode_votes_are_rejected)
{
Expand Down
Loading