Skip to content
Merged
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
7 changes: 7 additions & 0 deletions doc/release-notes-7755.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Proof of Service
----------------

DKG members now also vote a member bad if none of their masternode connections to it advertise:

* transaction relay (`relay=1` in the `version` message);
* compact block filters (`NODE_COMPACT_FILTERS`).
32 changes: 27 additions & 5 deletions src/active/dkgsession.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -233,28 +233,50 @@ void ActiveDKGSession::VerifyConnectionAndMinProtoVersions(CConnman& connman) co

CDKGLogger logger(*this, __func__, __LINE__);

Uint256HashMap<int> protoMap;
struct PeerInfo {
int version{0};
// Only masternode connections are judged: block-relay-only connections always advertise
// relay=0, and one connection that provides a service is enough.
bool has_mn_connection{false};
bool relays_txs{false};
bool serves_compact_filters{false};
};
Uint256HashMap<PeerInfo> peerInfo;
connman.ForEachNode([&](const CNode* pnode) {
auto verifiedProRegTxHash = pnode->GetVerifiedProRegTxHash();
if (verifiedProRegTxHash.IsNull()) {
return;
}
protoMap.emplace(verifiedProRegTxHash, pnode->nVersion);
auto [it, inserted] = peerInfo.try_emplace(verifiedProRegTxHash);
if (inserted) it->second.version = pnode->nVersion;
if (pnode->m_masternode_connection) {
it->second.has_mn_connection = true;
it->second.relays_txs |= pnode->m_version_relay_txs;
it->second.serves_compact_filters |= (pnode->m_version_services & NODE_COMPACT_FILTERS) != 0;
}
});

bool fShouldAllMembersBeConnected = IsAllMembersConnectedEnabled(params.type, m_sporkman);
for (const auto& m : members) {
if (m->dmn->proTxHash == myProTxHash) {
continue;
}
if (auto it = protoMap.find(m->dmn->proTxHash); it == protoMap.end()) {
if (auto it = peerInfo.find(m->dmn->proTxHash); it == peerInfo.end()) {
m->badConnection = fShouldAllMembersBeConnected;
if (m->badConnection) {
logger.Batch("%s is not connected to us, badConnection=1", m->dmn->proTxHash.ToString());
}
} else if (it->second < MIN_MASTERNODE_PROTO_VERSION) {
} else if (it->second.version < MIN_MASTERNODE_PROTO_VERSION) {
m->badConnection = true;
logger.Batch("%s does not have min proto version %d (has %d)", m->dmn->proTxHash.ToString(),
MIN_MASTERNODE_PROTO_VERSION, it->second.version);
} else if (it->second.has_mn_connection && !it->second.relays_txs) {
// A masternode signs InstantSend locks only for transactions in its own mempool
m->badConnection = true;
logger.Batch("%s does not relay transactions", m->dmn->proTxHash.ToString());
} else if (it->second.has_mn_connection && !it->second.serves_compact_filters) {
m->badConnection = true;
logger.Batch("%s does not have min proto version %d (has %d)", m->dmn->proTxHash.ToString(), MIN_MASTERNODE_PROTO_VERSION, it->second);
logger.Batch("%s does not serve compact block filters", m->dmn->proTxHash.ToString());
}
if (m_mn_metaman.OutboundFailedTooManyTimes(m->dmn->proTxHash)) {
m->badConnection = true;
Expand Down
4 changes: 4 additions & 0 deletions src/net.h
Original file line number Diff line number Diff line change
Expand Up @@ -817,6 +817,10 @@ class CNode
std::atomic<bool> m_masternode_probe_connection{false};
// If 'true', we identified it as an intra-quorum relay connection
std::atomic<bool> m_masternode_iqr_connection{false};
// Whether the peer asked for transaction relay in its VERSION message (fRelay)
std::atomic<bool> m_version_relay_txs{false};
// Service flags the peer advertised in its VERSION message
std::atomic<ServiceFlags> m_version_services{NODE_NONE};
CSemaphoreGrant grantOutbound;
std::atomic<int> nRefCount{0};

Expand Down
2 changes: 2 additions & 0 deletions src/net_processing.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4057,6 +4057,8 @@ void PeerManagerImpl::ProcessMessage(
}

pfrom.m_has_all_wanted_services = HasAllDesirableServiceFlags(nServices);
pfrom.m_version_services = nServices;
pfrom.m_version_relay_txs = fRelay;
peer->m_their_services = nServices;
pfrom.SetAddrLocal(addrMe);
{
Expand Down
126 changes: 126 additions & 0 deletions test/functional/feature_llmq_simplepose.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import time

from test_framework.masternodes import check_banned, check_punished
from test_framework.messages import NODE_COMPACT_FILTERS
from test_framework.p2p import P2P_SERVICES, P2PInterface
from test_framework.test_framework import (
DashTestFramework,
MasternodeInfo,
Expand All @@ -22,6 +24,19 @@
# See version.h
MIN_MASTERNODE_PROTO_VERSION = 70242


class MasternodePeer(P2PInterface):
"""Connects to a masternode the way another masternode does, advertising the given relay flag"""
def __init__(self, relay):
super().__init__()
self.version_relay = relay

def peer_connect_send_version(self, services):
super().peer_connect_send_version(services)
self.on_connection_send_msg.relay = self.version_relay
self.on_connection_send_msg.other_masternode = True


class LLMQSimplePoSeTest(DashTestFramework):
def set_test_params(self):
# rotating quorums add instability for this functional tests
Expand Down Expand Up @@ -84,6 +99,15 @@ def run_test(self):
# With PoSe off there should be no punishing for outdated nodes
self.test_no_banning(self.force_old_mn_proto, 3)

self.repair_masternodes(True)
self.reset_probe_timeouts()

for relay, services, reason in [(0, P2P_SERVICES | NODE_COMPACT_FILTERS, "does not relay transactions"),
(1, P2P_SERVICES, "does not serve compact block filters")]:
self.test_no_service(relay, services, reason, banned=not self.options.disable_spork23)
self.repair_masternodes(True)
self.reset_probe_timeouts()

def isolate_mn(self, mn: MasternodeInfo):
mn.get_node(self).setnetworkactive(False)
self.wait_until(lambda: mn.get_node(self).getconnectioncount() == 0)
Expand All @@ -108,6 +132,108 @@ def force_old_mn_proto(self, mn: MasternodeInfo):
self.reset_probe_timeouts()
return False, True

def test_no_service(self, relay, services, reason, banned):
# A member is judged by what our masternode connections to it advertise in their version message. A stock
# masternode always advertises both services, so a P2P peer stands in for the connections to one member.
mn = self.mninfo[0]
node = mn.get_node(self)
others = [m for m in self.mninfo if m is not mn]
expected_complaints = len(others) if banned else 0
for i in range(2):
self.log.info(f"Testing PoSe {'banning' if banned else 'no banning'} of a masternode that {reason} {i + 1}/2")
self.reset_probe_timeouts()
with others[0].get_node(self).assert_debug_log([reason] if banned else [], unexpected_msgs=[] if banned else [reason]):
self.mine_quorum_no_service(mn, others, relay, services, expected_complaints)
for other in others:
other.get_node(self).disconnect_p2ps()
node.setnetworkactive(True)
force_finish_mnsync(node)
self.connect_nodes(mn.nodeIdx, 0)
self.sync_blocks()
if check_banned(self.nodes[0], mn):
break
assert_equal(check_banned(self.nodes[0], mn), banned)
if not banned:
assert not check_punished(self.nodes[0], mn)

def mine_quorum_no_service(self, mn, others, relay, services, expected_complaints):
# Like mine_quorum, except that mn goes offline once every member holds its contribution and a peer stands
# in for it on each other member with a masternode connection that lacks the service, so that the complain
# phase judges mn by that connection alone.
self.log.info(f"Mining quorum with a stand-in for {mn.proTxHash}: expected_complaints={expected_complaints}")
nodes = [self.nodes[0]] + [m.get_node(self) for m in others]
spork23_active = self.nodes[0].spork('show')['SPORK_23_QUORUM_POSE'] <= 1

# move forward to next DKG
skip_count = 24 - (self.nodes[0].getblockcount() % 24)
self.bump_mocktime(1)
self.generate(self.nodes[0], skip_count)

q = self.nodes[0].getbestblockhash()
self.log.info("Expected quorum_hash:"+str(q))
self.log.info("Waiting for phase 1 (init)")
self.wait_for_quorum_phase(q, 1, len(others), None, 0, others)
self.wait_for_quorum_connections(q, self.llmq_size - 1, others, wait_proc=lambda: self.bump_mocktime(1))
if spork23_active:
self.wait_for_masternode_probes(q, others, wait_proc=lambda: self.bump_mocktime(1))

self.move_blocks(self.nodes, 2)

self.log.info("Waiting for phase 2 (contribute)")
self.wait_for_quorum_phase(q, 2, len(others), "receivedContributions", self.llmq_size, others)

self.log.info("Replacing the connections to the masternode with stand-ins")
mn.get_node(self).setnetworkactive(False)
for other in others:
other_node = other.get_node(self)
self.wait_until(lambda: all(p.get("verified_proregtx_hash") != mn.proTxHash for p in other_node.getpeerinfo()))
peer = other_node.add_p2p_connection(MasternodePeer(relay), services=services)
peer_ids = [p["id"] for p in other_node.getpeerinfo() if p["subver"] == peer.strSubVer]
assert_equal(len(peer_ids), 1)
assert other_node.mnauth(peer_ids[0], mn.proTxHash, mn.pubKeyOperator)

self.move_blocks(nodes, 2)

self.log.info("Waiting for phase 3 (complain)")
self.wait_for_quorum_phase(q, 3, len(others), "receivedComplaints", expected_complaints, others)

self.move_blocks(nodes, 2)

self.log.info("Waiting for phase 4 (justify)")
self.wait_for_quorum_phase(q, 4, len(others), "receivedJustifications", 0, others)

self.move_blocks(nodes, 2)

self.log.info("Waiting for phase 5 (commit)")
self.wait_for_quorum_phase(q, 5, len(others), "receivedPrematureCommitments", len(others), others)

self.move_blocks(nodes, 2)

self.log.info("Waiting for phase 6 (mining)")
self.wait_for_quorum_phase(q, 6, len(others), None, 0, others)

self.log.info("Waiting final commitment")
self.wait_for_quorum_commitment(q, others)

self.log.info("Waiting final commitments on mining node")
self.wait_for_quorum_commitments_on_miner(q, others)

self.log.info("Mining final commitment")
self.bump_mocktime(1)
self.nodes[0].getblocktemplate() # this calls CreateNewBlock
self.generate(self.nodes[0], 1, sync_fun=lambda: self.sync_blocks(nodes))

self.log.info("Waiting for quorum to appear in the list")
self.wait_for_quorum_list(q, nodes)
assert_equal(q, self.nodes[0].quorum("list", 1)["llmq_test"][0])

# Mine 8 (SIGN_HEIGHT_OFFSET) more blocks to make sure that the new quorum gets eligible for signing sessions
self.generate(self.nodes[0], 8, sync_fun=lambda: self.sync_blocks(nodes))

for m in others:
assert not check_punished(self.nodes[0], m)
assert not check_banned(self.nodes[0], m)

def test_no_banning(self, invalidate_proc, expected_connections=None):
[_, instant_ban] = invalidate_proc(self.mninfo[0])
iters = 2 if instant_ban else 6
Expand Down
16 changes: 13 additions & 3 deletions test/functional/test_framework/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -1633,7 +1633,7 @@ def serialize(self):

# Objects that correspond to messages on the wire
class msg_version:
__slots__ = ("addrFrom", "addrTo", "nNonce", "relay", "nServices",
__slots__ = ("addrFrom", "addrTo", "mnauth_challenge", "nNonce", "other_masternode", "relay", "nServices",
"nStartingHeight", "nTime", "nVersion", "strSubVer")
msgtype = b"version"

Expand All @@ -1647,6 +1647,8 @@ def __init__(self):
self.strSubVer = ''
self.nStartingHeight = -1
self.relay = 0
self.mnauth_challenge = 0
self.other_masternode = False

def deserialize(self, f):
self.nVersion = struct.unpack("<i", f.read(4))[0]
Expand All @@ -1669,6 +1671,12 @@ def deserialize(self, f):
except struct.error:
self.relay = 0

# Dash appends the MNAUTH challenge and whether the sender opened a masternode connection
rest = f.read(33)
if len(rest) == 33:
self.mnauth_challenge = int.from_bytes(rest[:32], 'little')
self.other_masternode = bool(rest[32])

def serialize(self):
r = b""
r += struct.pack("<i", self.nVersion)
Expand All @@ -1680,13 +1688,15 @@ def serialize(self):
r += ser_string(self.strSubVer.encode('utf-8'))
r += struct.pack("<i", self.nStartingHeight)
r += struct.pack("<b", self.relay)
r += ser_uint256(self.mnauth_challenge)
r += struct.pack("<?", self.other_masternode)
return r

def __repr__(self):
return 'msg_version(nVersion=%i nServices=%i nTime=%s addrTo=%s addrFrom=%s nNonce=0x%016X strSubVer=%s nStartingHeight=%i relay=%i)' \
return 'msg_version(nVersion=%i nServices=%i nTime=%s addrTo=%s addrFrom=%s nNonce=0x%016X strSubVer=%s nStartingHeight=%i relay=%i mnauth_challenge=%064x other_masternode=%s)' \
% (self.nVersion, self.nServices, time.ctime(self.nTime),
repr(self.addrTo), repr(self.addrFrom), self.nNonce,
self.strSubVer, self.nStartingHeight, self.relay)
self.strSubVer, self.nStartingHeight, self.relay, self.mnauth_challenge, self.other_masternode)


class msg_verack:
Expand Down
Loading