Expand file tree
/
Copy pathllmq_blockprocessor_tests.cpp
More file actions
390 lines (344 loc) · 19 KB
/
Copy pathllmq_blockprocessor_tests.cpp
File metadata and controls
390 lines (344 loc) · 19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
// Copyright (c) 2026 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 <test/util/llmq_tests.h>
#include <test/util/net.h>
#include <test/util/setup_common.h>
#include <chain.h>
#include <evo/evochainstate.h>
#include <chainparams.h>
#include <consensus/params.h>
#include <deploymentstatus.h>
#include <hash.h>
#include <masternode/meta.h>
#include <net.h>
#include <net_processing.h>
#include <node/protocol_version.h>
#include <streams.h>
#include <util/time.h>
#include <validation.h>
#include <llmq/blockprocessor.h>
#include <llmq/commitment.h>
#include <llmq/context.h>
#include <msg_result.h>
#include <protocol.h>
#include <random.h>
#include <boost/test/unit_test.hpp>
#include <vector>
using namespace llmq;
using namespace llmq::testutils;
BOOST_AUTO_TEST_SUITE(llmq_blockprocessor_tests)
namespace {
DataStream Serialized(const CFinalCommitment& qc)
{
DataStream payload{};
payload << qc;
return payload;
}
} // namespace
// A QFCOMMITMENT is only ever sent in reply to a GETDATA, so one the peer was never asked for must
// be dropped before CQuorumBlockProcessor does any lookup work on its behalf. The block processor
// holds no PeerManagerInternal -- net_processing already includes its header, so a reference would
// be circular -- and reaches the in-flight check through a predicate injected at the call site.
// Everything below therefore goes through PeerManagerImpl::ProcessMessage: calling the handler
// directly would test the gate but not the injection, which is the part that has no compiler to
// keep it honest.
BOOST_FIXTURE_TEST_CASE(unrequested_qfcommit_is_dropped_and_scored, TestChain100Setup)
{
LOCK(NetEventsInterface::g_msgproc_mutex);
// INV announcements for non-spork objects are only tracked outside IBD; the 100 mined blocks
// of this fixture already take us out of it.
BOOST_REQUIRE(!m_node.chainman->IsInitialBlockDownload());
// Every Dash-specific message is offered to CMNAuth first, which asserts a loaded metadata
// manager. The fixture leaves it unloaded, so initialise an empty cache here.
BOOST_REQUIRE(m_node.mn_metaman->LoadCache(/*load_cache=*/false));
auto& blockprocessor = *m_node.chainman->ActiveEvo().quorum_block_processor;
const auto& llmq_params = GetLLMQParams(Consensus::LLMQType::LLMQ_TEST_V17);
BOOST_REQUIRE(Params().GetLLMQ(llmq_params.type).has_value());
auto unsolicited_peer{MakeTestPeer(/*id=*/51)};
auto announcing_peer{MakeTestPeer(/*id=*/52)};
m_node.peerman->InitializeNode(*unsolicited_peer, NODE_NETWORK);
m_node.peerman->InitializeNode(*announcing_peer, NODE_NETWORK);
// quorumHash names no block we know of. That is the one rejection below the gate that
// deliberately carries no penalty -- we may simply be behind or on another chain -- so any
// score this payload collects can only have come from the gate, and the checks that do score
// cannot be mistaken for it.
const auto unsolicited_qc = CreateValidCommitment(llmq_params, GetTestBlockHash(51));
const uint256 unsolicited_hash = ::SerializeHash(unsolicited_qc);
// Sent twice on purpose: an unsolicited peer must not be able to repeat the block lookups and
// mineable-commitment probes for free, so both copies have to cost it.
for (int i = 0; i < 2; ++i) {
SendMessage(*m_node.peerman, *unsolicited_peer, NetMsgType::QFCOMMITMENT, Serialized(unsolicited_qc));
}
BOOST_CHECK_EQUAL(MisbehaviorScore(*m_node.peerman, *unsolicited_peer),
2 * UNREQUESTED_OBJECT_MISBEHAVIOR_SCORE);
// Nothing below the gate ran: had the commitment been processed it could only have ended up
// here or been rejected, and this is the observable half of that.
BOOST_CHECK(!blockprocessor.HasMineableCommitment(unsolicited_hash));
// The gate also runs ahead of the null-commitment check, which scores 100. A null payload from
// a peer we never asked must still cost exactly the unsolicited price -- reaching the 100 would
// mean the gate had let it through.
{
const int score_before_null = MisbehaviorScore(*m_node.peerman, *unsolicited_peer);
SendMessage(*m_node.peerman, *unsolicited_peer, NetMsgType::QFCOMMITMENT, Serialized(CFinalCommitment{}));
BOOST_CHECK_EQUAL(MisbehaviorScore(*m_node.peerman, *unsolicited_peer),
score_before_null + UNREQUESTED_OBJECT_MISBEHAVIOR_SCORE);
}
// Announcing the commitment is NOT enough to authorise it. An INV creates a candidate
// immediately, but the GETDATA only goes out later from SendMessages, so accepting on the
// announcement alone would let a peer authorise its own payload by racing INV and payload back
// to back -- which costs it nothing and defeats the gate entirely.
const auto announced_qc = CreateValidCommitment(llmq_params, GetTestBlockHash(52));
const CInv announced_inv{MSG_QUORUM_FINAL_COMMITMENT, ::SerializeHash(announced_qc)};
AnnounceInv(*m_node.peerman, *announcing_peer, announced_inv);
{
const int score_before_race = MisbehaviorScore(*m_node.peerman, *announcing_peer);
SendMessage(*m_node.peerman, *announcing_peer, NetMsgType::QFCOMMITMENT, Serialized(announced_qc));
BOOST_CHECK_EQUAL(MisbehaviorScore(*m_node.peerman, *announcing_peer),
score_before_race + UNREQUESTED_OBJECT_MISBEHAVIOR_SCORE);
}
// Once SendMessages has actually issued the GETDATA the same payload is authorised. The
// rejection above must not have consumed the candidate, or no GETDATA would go out at all.
SetMockTime(GetTime<std::chrono::seconds>() + 61s);
m_node.peerman->SendMessages(announcing_peer.get());
const int score_before = MisbehaviorScore(*m_node.peerman, *announcing_peer);
SendMessage(*m_node.peerman, *announcing_peer, NetMsgType::QFCOMMITMENT, Serialized(announced_qc));
// Unchanged, because the unknown quorum block this commitment names is rejected without any
// penalty -- which is what proves the message got past the gate. Asserting the total exactly is
// what would catch the gate also charging a peer we did ask.
BOOST_CHECK_EQUAL(MisbehaviorScore(*m_node.peerman, *announcing_peer), score_before);
// One GETDATA authorises exactly one answer. Both the in-flight request and the late-answer
// grace are spent, so a replay of the very payload we asked for is unsolicited again -- a peer
// must not be able to induce one request and then repeat the payload for free.
SendMessage(*m_node.peerman, *announcing_peer, NetMsgType::QFCOMMITMENT, Serialized(announced_qc));
BOOST_CHECK_EQUAL(MisbehaviorScore(*m_node.peerman, *announcing_peer),
score_before + UNREQUESTED_OBJECT_MISBEHAVIOR_SCORE);
m_node.peerman->FinalizeNode(*unsolicited_peer);
m_node.peerman->FinalizeNode(*announcing_peer);
SetMockTime(0s);
}
// A relayed commitment for a quorum we already hold a mineable commitment for is only worth
// verifying, and relaying, when it has more signers than ours.
BOOST_FIXTURE_TEST_CASE(qfcommit_with_more_signers_replaces_stored_one, TestChain100Setup)
{
LOCK(NetEventsInterface::g_msgproc_mutex);
BOOST_REQUIRE(!m_node.chainman->IsInitialBlockDownload());
BOOST_REQUIRE(m_node.mn_metaman->LoadCache(/*load_cache=*/false));
auto& blockprocessor = *m_node.chainman->ActiveEvo().quorum_block_processor;
const auto& llmq_params = GetLLMQParams(Consensus::LLMQType::LLMQ_TEST_V17);
BOOST_REQUIRE(Params().GetLLMQ(llmq_params.type).has_value());
BOOST_REQUIRE_EQUAL(llmq_params.size, 3);
const CBlockIndex* base_index{WITH_LOCK(::cs_main, return m_node.chainman->ActiveChain().Tip())};
base_index = base_index->GetAncestor(base_index->nHeight - (base_index->nHeight % llmq_params.dkgInterval));
auto with_signers = [&](const CFinalCommitment& qc, size_t count) {
CFinalCommitment ret{qc};
for (size_t i = 0; i < ret.signers.size(); ++i) {
ret.signers[i] = i < count;
}
return ret;
};
const auto base_qc = CreateValidCommitment(llmq_params, base_index->GetBlockHash());
const auto qc_one = with_signers(base_qc, 1);
const auto qc_two = with_signers(base_qc, 2);
const auto qc_three = with_signers(base_qc, 3);
auto qc_two_other{qc_three};
qc_two_other.signers[0] = false;
BOOST_REQUIRE(blockprocessor.AddMineableCommitment(qc_two).has_value());
NodeId next_id{61};
// Returns the misbehavior score the peer collected. The payloads carry random signatures, so a
// commitment that reaches verification is rejected with 100, while one dropped by the
// signer-count pre-check costs nothing.
auto deliver = [&](const CFinalCommitment& qc) EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface::g_msgproc_mutex) {
auto peer{MakeTestPeer(next_id++)};
m_node.peerman->InitializeNode(*peer, NODE_NETWORK);
AnnounceInv(*m_node.peerman, *peer, CInv{MSG_QUORUM_FINAL_COMMITMENT, ::SerializeHash(qc)});
SetMockTime(GetTime<std::chrono::seconds>() + 61s);
m_node.peerman->SendMessages(peer.get());
SendMessage(*m_node.peerman, *peer, NetMsgType::QFCOMMITMENT, Serialized(qc));
const int score{MisbehaviorScore(*m_node.peerman, *peer)};
m_node.peerman->FinalizeNode(*peer);
return score;
};
BOOST_CHECK_EQUAL(deliver(qc_one), 0);
BOOST_CHECK_EQUAL(deliver(qc_two_other), 0);
BOOST_CHECK_EQUAL(deliver(qc_three), 100);
// A commitment more than one DKG interval old is dropped before verification, and its sender
// is not scored: a peer that is still catching up relays commitments recent at its own tip.
const CBlockIndex* stale_base{base_index->GetAncestor(base_index->nHeight - 2 * llmq_params.dkgInterval)};
const auto stale_qc = CreateValidCommitment(llmq_params, stale_base->GetBlockHash());
BOOST_CHECK_EQUAL(deliver(stale_qc), 0);
BOOST_CHECK(!blockprocessor.HasMineableCommitment(::SerializeHash(stale_qc)));
BOOST_CHECK(!blockprocessor.AddMineableCommitment(qc_one).has_value());
BOOST_CHECK(blockprocessor.HasMineableCommitment(::SerializeHash(qc_two)));
const auto inv = blockprocessor.AddMineableCommitment(qc_three);
BOOST_REQUIRE(inv.has_value());
BOOST_CHECK(inv->hash == ::SerializeHash(qc_three));
BOOST_CHECK(blockprocessor.HasMineableCommitment(::SerializeHash(qc_three)));
BOOST_CHECK(!blockprocessor.HasMineableCommitment(::SerializeHash(qc_two)));
SetMockTime(0s);
}
struct PreV19Setup : public TestChain100Setup {
PreV19Setup() :
TestChain100Setup{ChainType::REGTEST,
{"-testactivationheight=v19@1000", "-testactivationheight=v20@1000",
"-testactivationheight=mn_rr@1000"}}
{
}
};
// No DKG runs for a quorum base before v19, so a relayed commitment for one is ignored without
// verifying it. A stale one is ignored without scoring the peer too, as after v19: a peer that is
// still catching up relays commitments that are recent at its own tip.
BOOST_FIXTURE_TEST_CASE(pre_v19_qfcommit_is_ignored, PreV19Setup)
{
LOCK(NetEventsInterface::g_msgproc_mutex);
BOOST_REQUIRE(!m_node.chainman->IsInitialBlockDownload());
BOOST_REQUIRE(m_node.mn_metaman->LoadCache(/*load_cache=*/false));
auto& blockprocessor = *m_node.chainman->ActiveEvo().quorum_block_processor;
const auto& llmq_params = GetLLMQParams(Consensus::LLMQType::LLMQ_TEST_V17);
BOOST_REQUIRE(Params().GetLLMQ(llmq_params.type).has_value());
const CBlockIndex* tip{WITH_LOCK(::cs_main, return m_node.chainman->ActiveChain().Tip())};
const CBlockIndex* recent_base{tip->GetAncestor(tip->nHeight - (tip->nHeight % llmq_params.dkgInterval))};
const CBlockIndex* stale_base{recent_base->GetAncestor(recent_base->nHeight - 2 * llmq_params.dkgInterval)};
BOOST_REQUIRE(!DeploymentActiveAfter(recent_base, m_node.chainman->GetConsensus(), Consensus::DEPLOYMENT_V19));
NodeId next_id{71};
auto deliver = [&](const CFinalCommitment& qc) EXCLUSIVE_LOCKS_REQUIRED(NetEventsInterface::g_msgproc_mutex) {
auto peer{MakeTestPeer(next_id++)};
m_node.peerman->InitializeNode(*peer, NODE_NETWORK);
AnnounceInv(*m_node.peerman, *peer, CInv{MSG_QUORUM_FINAL_COMMITMENT, ::SerializeHash(qc)});
SetMockTime(GetTime<std::chrono::seconds>() + 61s);
m_node.peerman->SendMessages(peer.get());
SendMessage(*m_node.peerman, *peer, NetMsgType::QFCOMMITMENT, Serialized(qc));
const int score{MisbehaviorScore(*m_node.peerman, *peer)};
m_node.peerman->FinalizeNode(*peer);
return score;
};
const auto recent_qc = CreateValidCommitment(llmq_params, recent_base->GetBlockHash());
BOOST_CHECK_EQUAL(deliver(recent_qc), 0);
BOOST_CHECK(!blockprocessor.HasMineableCommitment(::SerializeHash(recent_qc)));
BOOST_CHECK_EQUAL(deliver(CreateValidCommitment(llmq_params, stale_base->GetBlockHash())), 0);
SetMockTime(0s);
}
// The ordinary scanner over a complete history, written out the way
// CQuorumBlockProcessor walks its index: newest first without rotation;
// with it, the cycle-th newest record of every index in ascending order, one
// cycle after another, until a cycle yields nothing.
std::vector<const CBlockIndex*> OrdinaryScan(bool indexed,
const std::vector<std::vector<std::pair<int, const CBlockIndex*>>>& history,
int cutoff, size_t count)
{
std::vector<const CBlockIndex*> ret;
const auto nth_eligible = [&](size_t index, size_t nth) -> const CBlockIndex* {
for (const auto& [mined, block] : history[index]) {
if (mined > cutoff) continue;
if (nth == 0) return block;
--nth;
}
return nullptr;
};
if (!indexed) {
for (size_t nth{0}; ret.size() < count; ++nth) {
const CBlockIndex* block{nth_eligible(0, nth)};
if (block == nullptr) break;
ret.push_back(block);
}
return ret;
}
for (size_t cycle{0}; ret.size() < count; ++cycle) {
std::vector<const CBlockIndex*> cycle_ret;
for (size_t index{0}; index < history.size(); ++index) {
if (const CBlockIndex * block{nth_eligible(index, cycle)}) cycle_ret.push_back(block);
}
if (cycle_ret.empty()) break;
const size_t need{count - ret.size()};
ret.insert(ret.end(), cycle_ret.begin(), cycle_ret.begin() + std::min(need, cycle_ret.size()));
}
return ret;
}
// A snapshot carries the canonical selection of a scan's history: the newest
// K records without rotation, the newest two of each quorum index with it,
// marked END when it holds fewer. On small generated histories, a scan the
// carried records prove must return exactly what the ordinary scanner returns
// over the complete history, at every cutoff and count, and coverage never
// shrinks as the cutoff rises within one fixed context.
BOOST_AUTO_TEST_CASE(scan_proofs_agree_with_full_scans)
{
FastRandomContext rng{/*fDeterministic=*/true};
size_t proven_count{0};
size_t refused_count{0};
size_t multi_rank_proofs{0};
for (int round{0}; round < 300; ++round) {
const bool indexed{round % 2 == 1};
const size_t sequence_count{indexed ? 2 + rng.randrange(3) : 1};
const size_t selected{indexed ? 2 : 1 + rng.randrange(4)};
const int base{10 + static_cast<int>(rng.randrange(30))};
// Distinct stand-in quorum blocks for every record of this round.
std::vector<CBlockIndex> blocks(sequence_count * static_cast<size_t>(base));
size_t next_block{0};
// Mined heights per sequence, newest first.
std::vector<std::vector<std::pair<int, const CBlockIndex*>>> history(sequence_count);
for (auto& sequence : history) {
for (int height{1}; height <= base; ++height) {
if (rng.randrange(3) == 0) sequence.emplace_back(height, &blocks[next_block++]);
}
std::reverse(sequence.begin(), sequence.end());
}
std::vector<std::vector<std::pair<int, const CBlockIndex*>>> carried(sequence_count);
std::vector<ScanSequenceEnd> ends;
for (size_t i{0}; i < sequence_count; ++i) {
for (const auto& record : history[i]) {
if (carried[i].size() < selected) carried[i].push_back(record);
}
ends.push_back(carried[i].size() < selected ? ScanSequenceEnd::END : ScanSequenceEnd::UNKNOWN);
}
for (size_t count{1}; count <= 3 * sequence_count + 1; ++count) {
bool was_covered{false};
for (int cutoff{0}; cutoff <= base; ++cutoff) {
std::vector<ScanSequence> proof;
for (size_t i{0}; i < sequence_count; ++i) {
ScanSequence sequence{{}, ends[i]};
for (const auto& [mined, block] : carried[i]) {
if (mined <= cutoff) sequence.records.push_back(block);
}
proof.push_back(std::move(sequence));
}
const auto expected{OrdinaryScan(indexed, history, cutoff, count)};
const auto proven{TraverseScanSequences(indexed, proof, count)};
if (proven) {
BOOST_CHECK(*proven == expected);
++proven_count;
const auto populated{std::count_if(proof.begin(), proof.end(), [](const auto& sequence) {
return sequence.records.size() >= 2;
})};
if (indexed && populated >= 2 && expected.size() > sequence_count) ++multi_rank_proofs;
} else {
BOOST_CHECK(!was_covered);
++refused_count;
}
was_covered = was_covered || proven.has_value();
}
}
}
BOOST_CHECK_GT(proven_count, 0U);
BOOST_CHECK_GT(refused_count, 0U);
BOOST_CHECK_GT(multi_rank_proofs, 0U);
}
// The rotating counterexample: four quorum indexes, index 0 never formed,
// indexes 1-3 carrying [new, old] with older ones omitted, and a cutoff
// between new and old. Rank 0 yields the three old records; rank 1 needs index
// 1's next one, which is not carried, so the scan is not proven rather than
// returning three (or the wrong four).
BOOST_AUTO_TEST_CASE(rotating_scan_counterexample_is_not_covered)
{
std::vector<CBlockIndex> blocks(6);
std::vector<ScanSequence> sequences{{{}, ScanSequenceEnd::END}};
for (size_t i{0}; i < 3; ++i) {
// After the cutoff drops each index's newest record, its old one is
// eligible and the carried sequence goes on beyond it.
sequences.push_back({{&blocks[2 * i + 1]}, ScanSequenceEnd::UNKNOWN});
}
BOOST_CHECK(!TraverseScanSequences(/*indexed=*/true, sequences, 4).has_value());
const auto three{TraverseScanSequences(/*indexed=*/true, sequences, 3)};
BOOST_REQUIRE(three.has_value());
BOOST_CHECK(*three == (std::vector<const CBlockIndex*>{&blocks[1], &blocks[3], &blocks[5]}));
}
BOOST_AUTO_TEST_SUITE_END()