forked from bitcoin/bitcoin
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathllmq_chainlock_tests.cpp
More file actions
579 lines (501 loc) · 24.4 KB
/
Copy pathllmq_chainlock_tests.cpp
File metadata and controls
579 lines (501 loc) · 24.4 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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
// Copyright (c) 2025 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 <bls/bls.h>
#include <test/util/llmq_tests.h>
#include <test/util/net.h>
#include <test/util/setup_common.h>
#include <evo/cbtx.h>
#include <evo/specialtx.h>
#include <hash.h>
#include <masternode/meta.h>
#include <masternode/sync.h>
#include <net.h>
#include <net_processing.h>
#include <netaddress.h>
#include <spork.h>
#include <streams.h>
#include <util/strencodings.h>
#include <validation.h>
#include <version.h>
#include <chainlock/chainlock.h>
#include <chainlock/clsig.h>
#include <chainlock/handler.h>
#include <consensus/merkle.h>
#include <llmq/context.h>
#include <msg_result.h>
#include <node/blockstorage.h>
#include <pow.h>
#include <protocol.h>
#include <boost/test/unit_test.hpp>
#include <deque>
#include <memory>
#include <vector>
using chainlock::ChainLockSig;
using namespace llmq;
using namespace llmq::testutils;
namespace {
constexpr size_t MAX_SEEN_CHAINLOCKS{2500};
constexpr size_t RECENT_CHAINLOCKS_TO_RETAIN{2};
} // namespace
BOOST_AUTO_TEST_SUITE(llmq_chainlock_tests)
BOOST_FIXTURE_TEST_CASE(historical_coinbase_lookup_from_disk, RegTestingSetup)
{
const int activation = Params().GetConsensus().V20Height;
const auto signature = CreateRandomBLSSignature();
std::deque<uint256> hashes;
std::deque<CBlockIndex> indexes;
CChain chain;
for (int height = 0; height <= activation + 17000; ++height) {
CCbTx payload;
payload.nVersion = CCbTx::Version::CLSIG_AND_BALANCE;
payload.nHeight = height;
if (height >= activation + 20) {
int certified;
if (height < activation + 80) {
certified = activation + 1;
} else if (height < activation + 110) {
certified = activation + 65;
} else if (height < activation + 17000) {
certified = activation + 99;
} else {
certified = activation + 16999;
}
payload.bestCLSignature = signature;
payload.bestCLHeightDiff = height - certified - 1;
}
CMutableTransaction coinbase;
coinbase.nVersion = 3;
coinbase.nType = TRANSACTION_COINBASE;
coinbase.vin.resize(1);
coinbase.vin[0].scriptSig = CScript() << height << OP_0;
coinbase.vout.emplace_back(0, CScript() << OP_TRUE);
SetTxPayload(coinbase, payload);
CBlock block;
block.nVersion = 1;
block.hashPrevBlock = height ? hashes.back() : uint256{};
block.nBits = Params().GenesisBlock().nBits;
block.nTime = Params().GenesisBlock().nTime + height;
block.vtx = {MakeTransactionRef(coinbase)};
block.hashMerkleRoot = BlockMerkleRoot(block);
while (!CheckProofOfWork(block.GetHash(), block.nBits, Params().GetConsensus()))
++block.nNonce;
hashes.push_back(block.GetHash());
indexes.emplace_back(block);
auto& index = indexes.back();
index.phashBlock = &hashes.back();
index.nHeight = height;
index.pprev = height ? &indexes[height - 1] : nullptr;
index.BuildSkip();
const auto pos = m_node.chainman->m_blockman.SaveBlockToDisk(block, height, nullptr);
BOOST_REQUIRE(!pos.IsNull());
{
LOCK(cs_main);
index.nFile = pos.nFile;
index.nDataPos = pos.nPos;
index.nStatus = BLOCK_HAVE_DATA;
}
chain.SetTip(index);
}
chainlock::CoinbaseChainLockReader reader(chain.Tip());
BOOST_CHECK(!reader.Read(activation + 2));
BOOST_CHECK(!reader.Find(-1, activation + 128));
BOOST_CHECK(!reader.Find(activation + 128, activation + 128));
for (int minimum = activation; minimum <= activation + 100; ++minimum) {
const int expected = minimum <= activation + 1 ? activation + 1
: minimum <= activation + 65 ? activation + 65
: activation + 99;
const auto entry = reader.Find(minimum, activation + 128);
if (minimum > activation + 99) {
BOOST_CHECK(!entry);
continue;
}
BOOST_REQUIRE(entry);
BOOST_CHECK_EQUAL(entry->height, expected);
BOOST_CHECK(entry->block_hash == chain[expected]->GetBlockHash());
BOOST_CHECK(entry->Signed().getSig() == signature);
const int carrier = expected == activation + 1 ? activation + 20
: expected == activation + 65 ? activation + 80
: activation + 110;
BOOST_CHECK_EQUAL(entry->carrier->nHeight, carrier);
BOOST_CHECK(!reader.Find(minimum, expected - 1));
}
// A repeated certificate spanning more than the request's disk-read budget
// must still allow finding the next certificate (or reporting its absence).
chainlock::CoinbaseChainLockReader long_gap(chain.Tip());
const auto late = long_gap.Find(activation + 100, activation + 16999);
BOOST_REQUIRE(late);
BOOST_CHECK_EQUAL(late->carrier->nHeight, activation + 17000);
BOOST_CHECK_EQUAL(late->height, activation + 16999);
BOOST_CHECK(!long_gap.Find(activation + 100, activation + 16998));
// A new request on a shorter chain must not reuse the old request's cache.
chainlock::CoinbaseChainLockReader after_disconnect(chain[activation + 66]);
BOOST_CHECK(!after_disconnect.Find(activation + 65, activation + 65));
BOOST_REQUIRE(after_disconnect.Find(activation + 1, activation + 1));
// What a carrier says must not depend on the process-wide BLS scheme flag at
// the time it is first read, because the answer is kept for the process.
chainlock::ClearCoinbaseChainLockCacheForTesting();
const bool scheme = bls::bls_legacy_scheme.load();
bls::bls_legacy_scheme.store(!scheme);
const auto under_other = chainlock::CoinbaseChainLockReader(chain.Tip()).Read(activation + 40);
bls::bls_legacy_scheme.store(scheme);
BOOST_REQUIRE(under_other);
BOOST_CHECK_EQUAL(under_other->height, activation + 1);
const auto after = chainlock::CoinbaseChainLockReader(chain.Tip()).Read(activation + 40);
BOOST_REQUIRE(after);
BOOST_CHECK(after->Signed().getSig() == signature);
BOOST_CHECK_EQUAL(after->height, activation + 1);
// A carrier's certificate is a fact about its block hash, so once read it is
// served from the process-wide memo even if the block data goes away...
BOOST_REQUIRE(chainlock::CoinbaseChainLockReader(chain.Tip()).Read(activation + 30));
WITH_LOCK(cs_main, indexes[activation + 30].nStatus &= ~BLOCK_HAVE_DATA);
const auto memoized = chainlock::CoinbaseChainLockReader(chain.Tip()).Read(activation + 30);
BOOST_REQUIRE(memoized);
BOOST_CHECK(memoized->Signed().getSig() == signature);
// ...while unavailable block data that was never read is an error, distinct
// from an absent certificate.
chainlock::ClearCoinbaseChainLockCacheForTesting();
chainlock::CoinbaseChainLockReader unavailable(chain.Tip());
BOOST_CHECK_THROW(unavailable.Read(activation + 30), std::runtime_error);
}
BOOST_AUTO_TEST_CASE(chainlock_construction_test)
{
// Test default constructor
ChainLockSig clsig1;
BOOST_CHECK(clsig1.IsNull());
BOOST_CHECK_EQUAL(clsig1.getHeight(), -1);
BOOST_CHECK(clsig1.getBlockHash().IsNull());
BOOST_CHECK(!clsig1.getSig().IsValid());
// Test parameterized constructor
int32_t height = 12345;
uint256 blockHash = GetTestBlockHash(1);
CBLSSignature sig = CreateRandomBLSSignature();
ChainLockSig clsig2(height, blockHash, sig);
BOOST_CHECK(!clsig2.IsNull());
BOOST_CHECK_EQUAL(clsig2.getHeight(), height);
BOOST_CHECK(clsig2.getBlockHash() == blockHash);
BOOST_CHECK(clsig2.getSig() == sig);
}
BOOST_AUTO_TEST_CASE(chainlock_null_test)
{
ChainLockSig clsig;
// Default constructed should be null
BOOST_CHECK(clsig.IsNull());
// With height set but null hash, should not be null
clsig = ChainLockSig(100, uint256(), CBLSSignature());
BOOST_CHECK(!clsig.IsNull());
// With valid data should not be null
clsig = CreateChainLock(100, GetTestBlockHash(1));
BOOST_CHECK(!clsig.IsNull());
}
BOOST_AUTO_TEST_CASE(chainlock_serialization_test)
{
// Test with valid chainlock
ChainLockSig clsig = CreateChainLock(67890, GetTestBlockHash(42));
// Test serialization preserves all fields
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << clsig;
ChainLockSig deserialized;
ss >> deserialized;
BOOST_CHECK_EQUAL(clsig.getHeight(), deserialized.getHeight());
BOOST_CHECK(clsig.getBlockHash() == deserialized.getBlockHash());
BOOST_CHECK(clsig.getSig() == deserialized.getSig());
BOOST_CHECK_EQUAL(clsig.IsNull(), deserialized.IsNull());
}
BOOST_AUTO_TEST_CASE(chainlock_tostring_test)
{
// Test null chainlock
ChainLockSig nullClsig;
std::string nullStr = nullClsig.ToString();
BOOST_CHECK(!nullStr.empty());
// Test valid chainlock
int32_t height = 123456;
uint256 blockHash = GetTestBlockHash(789);
ChainLockSig clsig = CreateChainLock(height, blockHash);
std::string str = clsig.ToString();
BOOST_CHECK(!str.empty());
// ToString should contain height and hash info
BOOST_CHECK(str.find(strprintf("%d", height)) != std::string::npos);
BOOST_CHECK(str.find(blockHash.ToString().substr(0, 10)) != std::string::npos);
}
BOOST_AUTO_TEST_CASE(chainlock_edge_cases_test)
{
// Test with edge case heights
ChainLockSig clsig1 = CreateChainLock(0, GetTestBlockHash(1));
BOOST_CHECK_EQUAL(clsig1.getHeight(), 0);
BOOST_CHECK(!clsig1.IsNull());
ChainLockSig clsig2 = CreateChainLock(std::numeric_limits<int32_t>::max(), GetTestBlockHash(2));
BOOST_CHECK_EQUAL(clsig2.getHeight(), std::numeric_limits<int32_t>::max());
// Test serialization with extreme values
CDataStream ss1(SER_NETWORK, PROTOCOL_VERSION);
ss1 << clsig1;
ChainLockSig clsig1_deserialized;
ss1 >> clsig1_deserialized;
BOOST_CHECK_EQUAL(clsig1.getHeight(), clsig1_deserialized.getHeight());
CDataStream ss2(SER_NETWORK, PROTOCOL_VERSION);
ss2 << clsig2;
ChainLockSig clsig2_deserialized;
ss2 >> clsig2_deserialized;
BOOST_CHECK_EQUAL(clsig2.getHeight(), clsig2_deserialized.getHeight());
}
BOOST_AUTO_TEST_CASE(chainlock_comparison_test)
{
// Create identical chainlocks
int32_t height = 5000;
uint256 blockHash = GetTestBlockHash(10);
CBLSSignature sig = CreateRandomBLSSignature();
ChainLockSig clsig1(height, blockHash, sig);
ChainLockSig clsig2(height, blockHash, sig);
// Verify getters return same values
BOOST_CHECK_EQUAL(clsig1.getHeight(), clsig2.getHeight());
BOOST_CHECK(clsig1.getBlockHash() == clsig2.getBlockHash());
BOOST_CHECK(clsig1.getSig() == clsig2.getSig());
// Different chainlocks
ChainLockSig clsig3(height + 1, blockHash, sig);
BOOST_CHECK(clsig1.getHeight() != clsig3.getHeight());
ChainLockSig clsig4(height, GetTestBlockHash(11), sig);
BOOST_CHECK(clsig1.getBlockHash() != clsig4.getBlockHash());
}
BOOST_AUTO_TEST_CASE(chainlock_malformed_data_test)
{
// Test deserialization of truncated data
ChainLockSig clsig = CreateChainLock(1000, GetTestBlockHash(5));
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << clsig;
// Truncate the stream
std::string data = ss.str();
for (size_t truncateAt = 1; truncateAt < data.size(); truncateAt += 10) {
CDataStream truncated(std::vector<unsigned char>(data.begin(), data.begin() + truncateAt), SER_NETWORK,
PROTOCOL_VERSION);
ChainLockSig deserialized;
try {
truncated >> deserialized;
// If no exception, verify it's either complete or default
if (truncateAt < sizeof(int32_t)) {
BOOST_CHECK(deserialized.IsNull());
}
} catch (const std::exception&) {
// Expected for most truncation points
}
}
}
BOOST_FIXTURE_TEST_CASE(stale_chainlocks_are_remembered_for_duplicate_suppression, TestingSetup)
{
m_node.clhandler->CheckActiveState();
auto best_clsig = CreateChainLock(100, GetTestBlockHash(1));
BOOST_REQUIRE(m_node.chainlocks->UpdateBestChainlock(::SerializeHash(best_clsig), best_clsig, /*pindex=*/nullptr));
BOOST_CHECK_EQUAL(m_node.clhandler->SeenChainLockCacheSizeForTesting(), 0U);
for (uint32_t i = 0; i < 10; ++i) {
auto stale_clsig = CreateChainLock(100, GetTestBlockHash(1000 + i));
const auto hash = ::SerializeHash(stale_clsig);
[[maybe_unused]] const auto result =
m_node.clhandler->ProcessNewChainLock(/*from=*/0, stale_clsig, *m_node.llmq_ctx->qman, hash);
BOOST_CHECK(m_node.clhandler->AlreadyHave(CInv{MSG_CLSIG, hash}));
BOOST_CHECK_EQUAL(m_node.clhandler->SeenChainLockCacheSizeForTesting(), static_cast<size_t>(i) + 1U);
}
}
BOOST_FIXTURE_TEST_CASE(seen_chainlock_cache_is_bounded, TestingSetup)
{
m_node.clhandler->CheckActiveState();
const auto process = [&](size_t i) {
SetMockTime(std::chrono::seconds{100000 + static_cast<int64_t>(i)});
auto clsig = CreateChainLock(100, GetTestBlockHash(static_cast<uint32_t>(2000 + i)));
const auto hash = ::SerializeHash(clsig);
[[maybe_unused]] const auto result =
m_node.clhandler->ProcessNewChainLock(/*from=*/-1, clsig, *m_node.llmq_ctx->qman, hash);
return hash;
};
std::vector<uint256> recent_hashes;
for (size_t i = 0; i <= MAX_SEEN_CHAINLOCKS; ++i) {
const auto hash = process(i);
if (i >= MAX_SEEN_CHAINLOCKS + 1 - RECENT_CHAINLOCKS_TO_RETAIN) {
recent_hashes.emplace_back(hash);
}
BOOST_CHECK_LE(m_node.clhandler->SeenChainLockCacheSizeForTesting(), MAX_SEEN_CHAINLOCKS);
}
for (const auto& hash : recent_hashes) {
BOOST_CHECK(m_node.clhandler->AlreadyHave(CInv{MSG_CLSIG, hash}));
}
SetMockTime(0s);
}
BOOST_FIXTURE_TEST_CASE(best_chainlock_is_already_have_after_seen_cache_eviction, TestingSetup)
{
m_node.clhandler->CheckActiveState();
auto best_clsig = CreateChainLock(100, GetTestBlockHash(1));
const auto best_hash = ::SerializeHash(best_clsig);
BOOST_REQUIRE(m_node.chainlocks->UpdateBestChainlock(best_hash, best_clsig, /*pindex=*/nullptr));
BOOST_CHECK(m_node.clhandler->AlreadyHave(CInv{MSG_CLSIG, best_hash}));
// Insert enough unique CLSIGs to force at least one prune of the seen cache.
for (size_t i = 0; i <= MAX_SEEN_CHAINLOCKS; ++i) {
auto clsig = CreateChainLock(static_cast<int32_t>(101 + i), GetTestBlockHash(static_cast<uint32_t>(3000 + i)));
[[maybe_unused]] const auto result =
m_node.clhandler->ProcessNewChainLock(/*from=*/-1, clsig, *m_node.llmq_ctx->qman, ::SerializeHash(clsig));
BOOST_CHECK_LE(m_node.clhandler->SeenChainLockCacheSizeForTesting(), MAX_SEEN_CHAINLOCKS);
}
BOOST_CHECK(m_node.clhandler->AlreadyHave(CInv{MSG_CLSIG, best_hash}));
}
namespace {
//! Regtest spork key matching Params().SporkAddress(), as used by the functional tests.
constexpr const char* REGTEST_SPORK_PRIVKEY{"cP4EKFyJsHT39LDqgdcB43Y3YXjNyjb5Fuas1GQSeAtjnZWmZEQK"};
} // namespace
BOOST_FIXTURE_TEST_CASE(coinbase_chainlock_processing, RegTestingSetup)
{
BOOST_REQUIRE(m_node.sporkman->SetSporkAddress(Params().SporkAddress()));
BOOST_REQUIRE(m_node.sporkman->SetPrivKey(REGTEST_SPORK_PRIVKEY));
BOOST_REQUIRE(m_node.sporkman->UpdateSpork(SPORK_19_CHAINLOCKS_ENABLED, 0).has_value());
m_node.mn_sync->SwitchToNextAsset();
BOOST_REQUIRE(m_node.mn_sync->IsBlockchainSynced());
std::vector<CBlockIndex> indexes(501);
std::vector<uint256> hashes(indexes.size());
for (size_t i = 0; i < indexes.size(); ++i) {
hashes[i] = GetTestBlockHash(i);
indexes[i].nHeight = i;
indexes[i].phashBlock = &hashes[i];
if (i > 0) indexes[i].pprev = &indexes[i - 1];
indexes[i].BuildSkip();
}
CCbTx cbtx;
cbtx.nVersion = CCbTx::Version::CLSIG_AND_BALANCE;
cbtx.bestCLSignature = CreateRandomBLSSignature();
CMutableTransaction tx;
tx.nVersion = CTransaction::SPECIAL_VERSION;
tx.nType = TRANSACTION_COINBASE;
tx.vin.resize(1);
CBlock block;
const auto set_payload = [&] {
SetTxPayload(tx, cbtx);
block.vtx = {MakeTransactionRef(tx)};
};
const auto process = [&](const CBlockIndex* index) {
const auto result = m_node.clhandler->ProcessCoinbaseChainLock(block, index, *m_node.llmq_ctx->qman);
BOOST_CHECK(!result.m_error);
BOOST_CHECK(result.m_inventory.empty());
// A structurally valid signature still requires quorum verification.
BOOST_CHECK(m_node.chainlocks->GetBestChainLock().IsNull());
};
// ProcessNewChainLock records the derived signature before verification. No quorum exists in this fixture.
for (const uint32_t offset : {0U, 5U, 499U}) {
cbtx.bestCLHeightDiff = offset;
set_payload();
process(&indexes.back());
const int32_t height = 499 - offset;
const ChainLockSig expected{height, hashes[height], cbtx.bestCLSignature};
BOOST_CHECK(m_node.clhandler->AlreadyHave(CInv{MSG_CLSIG, ::SerializeHash(expected)}));
}
const auto seen = m_node.clhandler->SeenChainLockCacheSizeForTesting();
BOOST_CHECK_EQUAL(seen, 3U);
for (const uint32_t offset :
{500U, 501U, uint32_t{std::numeric_limits<int32_t>::max()}, std::numeric_limits<uint32_t>::max()}) {
cbtx.bestCLHeightDiff = offset;
set_payload();
process(&indexes.back());
}
cbtx.bestCLHeightDiff = 1;
set_payload();
process(nullptr);
process(&indexes.front());
process(&indexes[431]); // Before v20 activation on regtest.
m_node.mn_sync->Reset(/*fForce=*/true);
process(&indexes.back());
m_node.mn_sync->SwitchToNextAsset();
BOOST_REQUIRE(m_node.sporkman->UpdateSpork(SPORK_19_CHAINLOCKS_ENABLED, 4070908800).has_value());
process(&indexes.back());
BOOST_REQUIRE(m_node.sporkman->UpdateSpork(SPORK_19_CHAINLOCKS_ENABLED, 0).has_value());
cbtx.bestCLSignature = {};
set_payload();
process(&indexes.back());
cbtx.nVersion = CCbTx::Version::MERKLE_ROOT_QUORUMS;
set_payload();
process(&indexes.back());
tx.vExtraPayload = {0xff};
block.vtx = {MakeTransactionRef(tx)};
process(&indexes.back());
tx.nType = TRANSACTION_NORMAL;
block.vtx = {MakeTransactionRef(tx)};
process(&indexes.back());
block.vtx.clear();
process(&indexes.back());
BOOST_CHECK_EQUAL(m_node.clhandler->SeenChainLockCacheSizeForTesting(), seen);
}
// A CLSIG is only ever sent in reply to a GETDATA, so one that the peer neither announced nor was
// asked for must be dropped before ProcessNewChainLock -- which would otherwise remember its hash
// and do that work again for every distinct signature blob, at no cost to the sender.
BOOST_FIXTURE_TEST_CASE(unrequested_clsig_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->ActiveChainstate().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));
// The CLSIG branch in net_processing is gated on spork 19. The test fixture builds a bare
// CSporkManager, so wire up the regtest signer before setting the spork.
BOOST_REQUIRE(m_node.sporkman->SetSporkAddress(Params().SporkAddress()));
BOOST_REQUIRE(m_node.sporkman->SetPrivKey(REGTEST_SPORK_PRIVKEY));
BOOST_REQUIRE(m_node.sporkman->UpdateSpork(SPORK_19_CHAINLOCKS_ENABLED, 0).has_value());
BOOST_REQUIRE(m_node.chainlocks->IsEnabled());
auto unsolicited_peer{MakeTestPeer(/*id=*/41)};
auto announcing_peer{MakeTestPeer(/*id=*/42)};
m_node.peerman->InitializeNode(*unsolicited_peer, NODE_NETWORK);
m_node.peerman->InitializeNode(*announcing_peer, NODE_NETWORK);
const auto unsolicited_clsig = CreateChainLock(200, GetTestBlockHash(41));
const CInv unsolicited_inv{MSG_CLSIG, ::SerializeHash(unsolicited_clsig)};
// Sent twice on purpose. Without the gate the first copy would still be scored (this chain is
// too short to resolve a signing quorum for height 200) but the second would hit the seen-cache
// dedup and cost the peer nothing -- so only charging for both proves the gate is what rejected
// them, and that an unsolicited peer cannot keep repeating the work for free.
for (int i = 0; i < 2; ++i) {
CDataStream unsolicited_payload{SER_NETWORK, PROTOCOL_VERSION};
unsolicited_payload << unsolicited_clsig;
SendMessage(*m_node.peerman, *unsolicited_peer, NetMsgType::CLSIG, std::move(unsolicited_payload));
}
// Never reached ProcessNewChainLock: the hash was not recorded in the seen cache, so the peer
// could not have displaced a genuine entry, and it was scored for each attempt.
BOOST_CHECK(!m_node.clhandler->AlreadyHave(unsolicited_inv));
BOOST_CHECK_EQUAL(MisbehaviorScore(*m_node.peerman, *unsolicited_peer),
2 * UNREQUESTED_OBJECT_MISBEHAVIOR_SCORE);
// Announcing the CLSIG 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_clsig = CreateChainLock(201, GetTestBlockHash(42));
const CInv announced_inv{MSG_CLSIG, ::SerializeHash(announced_clsig)};
AnnounceInv(*m_node.peerman, *announcing_peer, announced_inv);
{
const int score_before_race = MisbehaviorScore(*m_node.peerman, *announcing_peer);
CDataStream raced_payload{SER_NETWORK, PROTOCOL_VERSION};
raced_payload << announced_clsig;
SendMessage(*m_node.peerman, *announcing_peer, NetMsgType::CLSIG, std::move(raced_payload));
BOOST_CHECK(!m_node.clhandler->AlreadyHave(announced_inv));
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);
CDataStream announced_payload{SER_NETWORK, PROTOCOL_VERSION};
announced_payload << announced_clsig;
SendMessage(*m_node.peerman, *announcing_peer, NetMsgType::CLSIG, std::move(announced_payload));
BOOST_CHECK(m_node.clhandler->AlreadyHave(announced_inv));
// Exactly the pre-existing invalid-CLSIG penalty and nothing else. This fixture's chain is 100
// blocks, so a CLSIG at height 201 resolves to no signing quorum and ProcessNewChainLock scores
// 10 -- which is what proves the message got past the gate. Asserting the total exactly is what
// would catch the gate also charging an authorised peer.
BOOST_CHECK_EQUAL(MisbehaviorScore(*m_node.peerman, *announcing_peer), score_before + 10);
// 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.
const int score_before_replay = MisbehaviorScore(*m_node.peerman, *announcing_peer);
CDataStream replayed_payload{SER_NETWORK, PROTOCOL_VERSION};
replayed_payload << announced_clsig;
SendMessage(*m_node.peerman, *announcing_peer, NetMsgType::CLSIG, std::move(replayed_payload));
BOOST_CHECK_EQUAL(MisbehaviorScore(*m_node.peerman, *announcing_peer),
score_before_replay + UNREQUESTED_OBJECT_MISBEHAVIOR_SCORE);
m_node.peerman->FinalizeNode(*unsolicited_peer);
m_node.peerman->FinalizeNode(*announcing_peer);
SetMockTime(0s);
}
BOOST_AUTO_TEST_SUITE_END()