Repository navigation
Expand file tree
/
Copy pathllmq_commitment_tests.cpp
More file actions
626 lines (543 loc) · 29.4 KB
/
Copy pathllmq_commitment_tests.cpp
File metadata and controls
626 lines (543 loc) · 29.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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
// 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 <test/util/bls.h>
#include <test/util/llmq_tests.h>
#include <test/util/masternode.h>
#include <test/util/mining.h>
#include <test/util/setup_common.h>
#include <chain.h>
#include <checkqueue.h>
#include <consensus/validation.h>
#include <core_io.h>
#include <deploymentstatus.h>
#include <evo/deterministicmns.h>
#include <evo/evochainstate.h>
#include <evo/specialtx.h>
#include <llmq/blockprocessor.h>
#include <llmq/commitment.h>
#include <llmq/context.h>
#include <llmq/utils.h>
#include <logging.h>
#include <node/context.h>
#include <primitives/transaction.h>
#include <script/solver.h>
#include <streams.h>
#include <util/check.h>
#include <util/strencodings.h>
#include <validation.h>
#include <validationinterface.h>
#include <boost/test/unit_test.hpp>
#include <algorithm>
#include <optional>
using namespace llmq;
using namespace llmq::testutils;
BOOST_FIXTURE_TEST_SUITE(llmq_commitment_tests, BasicTestingSetup)
// Get test params for use in tests
static const Consensus::LLMQParams& TEST_PARAMS = GetLLMQParams(Consensus::LLMQType::LLMQ_TEST_V17);
BOOST_AUTO_TEST_CASE(commitment_counting_test)
{
CFinalCommitment commitment;
// Test empty vectors
BOOST_CHECK_EQUAL(commitment.CountSigners(), 0);
BOOST_CHECK_EQUAL(commitment.CountValidMembers(), 0);
// Test with various patterns
commitment.signers = {true, false, true, true, false};
commitment.validMembers = {true, true, false, true, true};
BOOST_CHECK_EQUAL(commitment.CountSigners(), 3);
BOOST_CHECK_EQUAL(commitment.CountValidMembers(), 4);
// Test all true
commitment.signers = std::vector<bool>(10, true);
commitment.validMembers = std::vector<bool>(10, true);
BOOST_CHECK_EQUAL(commitment.CountSigners(), 10);
BOOST_CHECK_EQUAL(commitment.CountValidMembers(), 10);
// Test all false
commitment.signers = std::vector<bool>(10, false);
commitment.validMembers = std::vector<bool>(10, false);
BOOST_CHECK_EQUAL(commitment.CountSigners(), 0);
BOOST_CHECK_EQUAL(commitment.CountValidMembers(), 0);
}
BOOST_AUTO_TEST_CASE(commitment_verify_sizes_test)
{
CFinalCommitment commitment;
commitment.llmqType = TEST_PARAMS.type;
// Test with incorrect sizes (TEST_PARAMS.size is 3, so use a different size)
commitment.validMembers = std::vector<bool>(5, true);
commitment.signers = std::vector<bool>(5, true);
BOOST_CHECK(!commitment.VerifySizes(TEST_PARAMS));
// Test with correct sizes
commitment.validMembers = std::vector<bool>(TEST_PARAMS.size, true);
commitment.signers = std::vector<bool>(TEST_PARAMS.size, true);
BOOST_CHECK(commitment.VerifySizes(TEST_PARAMS));
// Test with mismatched sizes
commitment.validMembers = std::vector<bool>(TEST_PARAMS.size, true);
commitment.signers = std::vector<bool>(TEST_PARAMS.size + 1, true);
BOOST_CHECK(!commitment.VerifySizes(TEST_PARAMS));
}
BOOST_FIXTURE_TEST_CASE(commitment_check_undersized_bitset_debug_log_test, RegTestingSetup)
{
// Catches the OOB-read regression in CheckLLMQCommitment's debug-log loop
// by capturing log output rather than relying on undefined behaviour to
// trip a sanitizer. The wire-format validMembers DYNBITSET can deserialize
// smaller than llmq_params.size; before the clamp the loop iterated up to
// llmq_params.size and emitted v[0], v[1], ... reading past the bitset.
// With the clamp an empty bitset must produce "validMembers[]".
struct LogCaptureGuard {
const uint64_t saved_categories{LogInstance().GetCategoryMask()};
std::list<std::function<void(const std::string&)>>::iterator it;
explicit LogCaptureGuard(std::vector<std::string>& sink)
{
LogInstance().EnableCategory(BCLog::LLMQ);
it = LogInstance().PushBackCallback(
[&sink](const std::string& msg) { sink.push_back(msg); });
}
~LogCaptureGuard()
{
LogInstance().DeleteCallback(it);
if (!(saved_categories & BCLog::LLMQ)) {
LogInstance().DisableCategory(BCLog::LLMQ);
}
}
};
std::vector<std::string> log_lines;
std::optional<LogCaptureGuard> guard{std::in_place, log_lines};
BOOST_REQUIRE(LogAcceptDebug(BCLog::LLMQ));
CFinalCommitmentTxPayload payload;
payload.nVersion = CFinalCommitmentTxPayload::CURRENT_VERSION;
// base_index below sits at height 0, so CheckLLMQCommitment expects
// qcTx.nHeight == 1. Setting it to 2 forces the function to fail with
// "bad-qc-height" after the pre-validation debug-log block but before
// LookupBlockIndex / Verify / VerifySizes, which is the path the clamp
// is meant to harden.
payload.nHeight = 2;
payload.commitment.nVersion = CFinalCommitment::LEGACY_BLS_NON_INDEXED_QUORUM_VERSION;
payload.commitment.llmqType = TEST_PARAMS.type;
payload.commitment.quorumHash = GetTestQuorumHash(1);
// TEST_PARAMS.size is 3; an empty bitset models a malformed mined commitment.
payload.commitment.signers = std::vector<bool>();
payload.commitment.validMembers = std::vector<bool>();
CMutableTransaction mtx;
mtx.nVersion = CTransaction::SPECIAL_VERSION;
mtx.nType = TRANSACTION_QUORUM_COMMITMENT;
SetTxPayload(mtx, payload);
const CTransaction tx{mtx};
// Sanity check that the undersized bitsets survive payload round-trip,
// so the call below is genuinely exercising the OOB-prone code path.
const auto opt_round_trip = GetTxPayload<CFinalCommitmentTxPayload>(tx);
BOOST_REQUIRE(opt_round_trip.has_value());
BOOST_CHECK_LT(opt_round_trip->commitment.validMembers.size(), static_cast<size_t>(TEST_PARAMS.size));
BOOST_CHECK_LT(opt_round_trip->commitment.signers.size(), static_cast<size_t>(TEST_PARAMS.size));
CBlockIndex base_index;
base_index.nHeight = 0;
const llmq::UtilParameters util_params{*m_node.chainman->ActiveEvo().dmnman,
*m_node.chainman->ActiveEvo().qsnapman,
*Assert(m_node.chainman),
&base_index};
TxValidationState state;
BOOST_CHECK(!llmq::CheckLLMQCommitment(util_params, *opt_round_trip, state));
BOOST_CHECK(state.IsInvalid());
BOOST_CHECK_EQUAL(state.GetRejectReason(), "bad-qc-height");
// Remove the callback before reading log_lines: callbacks run under the
// logger mutex from whichever thread logs, and RegTestingSetup has
// background threads that log concurrently. DeleteCallback takes the same
// mutex, so after this reset no thread can still be mutating log_lines.
guard.reset();
// Locate the validMembers debug line emitted by CheckLLMQCommitment and
// assert the loop was clamped: with an empty bitset the rendered list must
// be empty. Old code emitted "v[0]=..." here even though the bitset had no
// elements, so checking for the absence of "v[0]" pins down the regression.
const std::string marker = "CFinalCommitment -- CheckLLMQCommitment";
const auto it = std::find_if(log_lines.begin(), log_lines.end(),
[&marker](const std::string& s) {
return s.find(marker) != std::string::npos;
});
BOOST_REQUIRE_MESSAGE(it != log_lines.end(),
"CheckLLMQCommitment debug line not captured");
BOOST_CHECK_MESSAGE(it->find("validMembers[]") != std::string::npos,
"expected clamped 'validMembers[]', got: " + *it);
BOOST_CHECK_MESSAGE(it->find("v[0]") == std::string::npos,
"unexpected v[0] in clamped log line: " + *it);
}
BOOST_AUTO_TEST_CASE(commitment_serialization_test)
{
// Test with valid commitment
CFinalCommitment commitment = CreateValidCommitment(TEST_PARAMS, GetTestQuorumHash(1));
// Test serialization preserves all fields
DataStream ss{};
ss << commitment;
CFinalCommitment deserialized;
ss >> deserialized;
BOOST_CHECK_EQUAL(commitment.llmqType, deserialized.llmqType);
BOOST_CHECK(commitment.quorumHash == deserialized.quorumHash);
BOOST_CHECK(commitment.validMembers == deserialized.validMembers);
BOOST_CHECK(commitment.signers == deserialized.signers);
BOOST_CHECK(commitment.quorumVvecHash == deserialized.quorumVvecHash);
BOOST_CHECK(commitment.quorumPublicKey == deserialized.quorumPublicKey);
BOOST_CHECK(commitment.quorumSig == deserialized.quorumSig);
BOOST_CHECK(commitment.membersSig == deserialized.membersSig);
BOOST_CHECK_EQUAL(commitment.IsNull(), deserialized.IsNull());
}
BOOST_AUTO_TEST_CASE(commitment_version_test)
{
// Test version calculation (first param is rotation enabled, second is basic scheme active)
// With rotation enabled and basic scheme
BOOST_CHECK_EQUAL(CFinalCommitment::GetVersion(true, true), CFinalCommitment::BASIC_BLS_INDEXED_QUORUM_VERSION);
// With rotation enabled but legacy scheme
BOOST_CHECK_EQUAL(CFinalCommitment::GetVersion(true, false), CFinalCommitment::LEGACY_BLS_INDEXED_QUORUM_VERSION);
// Without rotation but basic scheme
BOOST_CHECK_EQUAL(CFinalCommitment::GetVersion(false, true), CFinalCommitment::BASIC_BLS_NON_INDEXED_QUORUM_VERSION);
// Without rotation and legacy scheme
BOOST_CHECK_EQUAL(CFinalCommitment::GetVersion(false, false), CFinalCommitment::LEGACY_BLS_NON_INDEXED_QUORUM_VERSION);
}
BOOST_AUTO_TEST_CASE(commitment_json_test)
{
CFinalCommitment commitment = CreateValidCommitment(TEST_PARAMS, GetTestQuorumHash(1));
UniValue json = commitment.ToJson();
// Verify JSON contains expected fields
BOOST_CHECK(json.exists("llmqType"));
BOOST_CHECK(json.exists("quorumHash"));
BOOST_CHECK(json.exists("signers"));
BOOST_CHECK(json.exists("validMembers"));
BOOST_CHECK(json.exists("quorumPublicKey"));
BOOST_CHECK(json.exists("quorumVvecHash"));
BOOST_CHECK(json.exists("quorumSig"));
BOOST_CHECK(json.exists("membersSig"));
// Verify counts are included
BOOST_CHECK(json.exists("signersCount"));
BOOST_CHECK(json.exists("validMembersCount"));
BOOST_CHECK_EQUAL(json["signersCount"].getInt<int>(), commitment.CountSigners());
BOOST_CHECK_EQUAL(json["validMembersCount"].getInt<int>(), commitment.CountValidMembers());
}
BOOST_AUTO_TEST_CASE(commitment_bitvector_json_test)
{
// Test bit vector serialization through JSON output
CFinalCommitment commitment;
commitment.llmqType = TEST_PARAMS.type;
commitment.quorumHash = GetTestQuorumHash(1);
// Test empty vectors
commitment.validMembers.clear();
commitment.signers.clear();
UniValue json = commitment.ToJson();
BOOST_CHECK_EQUAL(json["validMembers"].get_str(), "");
BOOST_CHECK_EQUAL(json["signers"].get_str(), "");
// Test single byte patterns
commitment.validMembers = std::vector<bool>(8, false);
commitment.signers = std::vector<bool>(8, false);
json = commitment.ToJson();
BOOST_CHECK_EQUAL(json["validMembers"].get_str(), "00");
BOOST_CHECK_EQUAL(json["signers"].get_str(), "00");
commitment.validMembers = std::vector<bool>(8, true);
commitment.signers = std::vector<bool>(8, true);
json = commitment.ToJson();
BOOST_CHECK_EQUAL(json["validMembers"].get_str(), "ff");
BOOST_CHECK_EQUAL(json["signers"].get_str(), "ff");
// Test specific patterns
// Note: Bit order in serialization is LSB first within each byte
commitment.validMembers = {true, false, true, false, true, false, true, false}; // 0x55 (01010101 in LSB)
commitment.signers = {false, true, false, true, false, true, false, true}; // 0xAA (10101010 in LSB)
json = commitment.ToJson();
BOOST_CHECK_EQUAL(json["validMembers"].get_str(), "55");
BOOST_CHECK_EQUAL(json["signers"].get_str(), "aa");
// Test non-byte-aligned sizes (should pad with zeros)
commitment.validMembers = {true, true, true, true, true}; // 0x1F padded
commitment.signers = commitment.validMembers;
json = commitment.ToJson();
BOOST_CHECK_EQUAL(json["validMembers"].get_str(), "1f");
BOOST_CHECK_EQUAL(json["signers"].get_str(), "1f");
}
BOOST_AUTO_TEST_CASE(commitment_verify_null_edge_cases)
{
CFinalCommitment commitment;
// Fresh commitment should be null
BOOST_CHECK(commitment.IsNull());
// Setting quorumHash alone doesn't make it non-null
// (IsNull() doesn't check quorumHash)
commitment.quorumHash = GetTestQuorumHash(1);
BOOST_CHECK(commitment.IsNull());
commitment.quorumHash.SetNull();
// Setting llmqType alone doesn't make it non-null
commitment.llmqType = Consensus::LLMQType::LLMQ_TEST;
BOOST_CHECK(commitment.IsNull());
commitment.llmqType = Consensus::LLMQType::LLMQ_NONE;
// Setting validMembers with true values makes it non-null
commitment.validMembers = {true};
BOOST_CHECK(!commitment.IsNull());
commitment.validMembers.clear();
// Setting signers with only false values keeps it null
commitment.signers = {false};
BOOST_CHECK(commitment.IsNull());
// Setting signers with true values makes it non-null
commitment.signers = {true};
BOOST_CHECK(!commitment.IsNull());
commitment.signers.clear();
// Setting quorumPublicKey makes it non-null
commitment.quorumPublicKey = CreateRandomBLSPublicKey();
BOOST_CHECK(!commitment.IsNull());
// Reset and test quorumVvecHash
commitment = CFinalCommitment{};
commitment.quorumVvecHash = GetTestQuorumHash(2);
BOOST_CHECK(!commitment.IsNull());
// Reset and test signatures
commitment = CFinalCommitment{};
commitment.membersSig = CreateRandomBLSSignature();
BOOST_CHECK(!commitment.IsNull());
commitment = CFinalCommitment{};
commitment.quorumSig = CreateRandomBLSSignature();
BOOST_CHECK(!commitment.IsNull());
}
namespace {
CFinalCommitment NullSizedCommitment(uint16_t version, const CBLSPublicKey& pubkey)
{
const auto params = Params().GetLLMQ(Consensus::LLMQType::LLMQ_50_60);
BOOST_REQUIRE(params);
CFinalCommitment commitment;
commitment.nVersion = version;
commitment.llmqType = params->type;
commitment.signers.assign(params->size, false);
commitment.validMembers.assign(params->size, false);
commitment.quorumPublicKey = pubkey;
return commitment;
}
CFinalCommitment RoundTripWithVersion(const CFinalCommitment& commitment, uint16_t wire_version)
{
std::vector<unsigned char> buf;
VectorWriter ds{buf, 0};
ds << commitment;
BOOST_REQUIRE_GE(buf.size(), 2U);
BOOST_REQUIRE_EQUAL(buf[0], static_cast<unsigned char>(commitment.nVersion));
BOOST_REQUIRE_EQUAL(buf[1], 0);
buf[0] = static_cast<unsigned char>(wire_version);
buf[1] = static_cast<unsigned char>(wire_version >> 8);
DataStream in{buf};
CFinalCommitment out;
BOOST_CHECK_NO_THROW(in >> out);
BOOST_CHECK(in.empty());
return out;
}
} // namespace
BOOST_AUTO_TEST_CASE(commitment_opposite_scheme_pubkey_deserializes_null)
{
// Scalar 1's legacy encoding is canonical only under legacy. A basic-version
// commitment carrying those bytes must drop the key instead of throwing.
const auto legacy_only = NullSizedCommitment(CFinalCommitment::LEGACY_BLS_NON_INDEXED_QUORUM_VERSION,
SecretFromScalar(1).GetPublicKey());
const auto as_basic = RoundTripWithVersion(legacy_only, CFinalCommitment::BASIC_BLS_NON_INDEXED_QUORUM_VERSION);
BOOST_CHECK(!as_basic.quorumPublicKey.IsValid());
BOOST_CHECK(!as_basic.quorumSig.IsValid());
BOOST_CHECK(!as_basic.membersSig.IsValid());
BOOST_CHECK(as_basic.IsNull());
BOOST_CHECK(as_basic.VerifyNull());
// Scalar 2's basic encoding is canonical only under basic. Mirror case.
const auto basic_only = NullSizedCommitment(CFinalCommitment::BASIC_BLS_NON_INDEXED_QUORUM_VERSION,
SecretFromScalar(2).GetPublicKey());
const auto as_legacy = RoundTripWithVersion(basic_only, CFinalCommitment::LEGACY_BLS_NON_INDEXED_QUORUM_VERSION);
BOOST_CHECK(!as_legacy.quorumPublicKey.IsValid());
BOOST_CHECK(!as_legacy.quorumSig.IsValid());
BOOST_CHECK(!as_legacy.membersSig.IsValid());
BOOST_CHECK(as_legacy.IsNull());
BOOST_CHECK(as_legacy.VerifyNull());
}
BOOST_AUTO_TEST_CASE(commitment_mainnet_pre_v19_verifies_legacy_only)
{
// Mainnet height 1898412, txid 2f9731e46562f18dd1b135b14433b3927e4d3ccc0fb89ecdf27ec8532b44b8d0.
const std::string raw_tx =
"03000600000000000000fd55010100acf71c00010004ecf84b2fa47aa7a68074c6002e40d27650465704c0e386700f0000000000000064"
"ffffffffffffffffffffffff0f64ffffffffffffffffffffffff0f0ee6b155297c084fd6ae7a1551ed69587479c8210007fd86275723a5"
"f1ea9816faa80da16d18563489e450b9e6fbbb880e1334987cccb3bda273adc5e9d0c335d664e9bb25208ac80e304c1fcdf207db827bd1"
"63b2a93ea99df01c01c4fb892fe1207ec35f126fc0fe6e52698f59d5005f03af5b0aafd109822d3e1ba616c63a0f0fb3081c4b615696cd"
"f2b28af910790b89791ebad4b747607195f91b95d4b60596c69aee3845cc49ff4818323d358f806458face507e60f8412792251a7d5b9b"
"edd62cb27dd48378dd97b52e585845b7c7fa9fe54afe024fb5ca481e38b5d10dd928dd3b459d0057cda002b52d4819f3e37b4cf2a1319d"
"a0c4142aff6d244109907c9757fed010503d746c4a6ec6e7";
CMutableTransaction mtx;
BOOST_REQUIRE(DecodeHexTx(mtx, raw_tx));
const auto payload = GetTxPayload<CFinalCommitmentTxPayload>(CTransaction{mtx});
BOOST_REQUIRE(payload);
const auto& qc = payload->commitment;
const auto json = qc.ToJson();
BOOST_CHECK_EQUAL(payload->nHeight, 1898412U);
BOOST_CHECK_EQUAL(json["version"].getInt<int>(), 1);
BOOST_CHECK_EQUAL(json["llmqType"].getInt<int>(), 4);
BOOST_CHECK_EQUAL(json["quorumHash"].get_str(), "000000000000000f7086e3c00457465076d2402e00c67480a6a77aa42f4bf8ec");
BOOST_CHECK_EQUAL(json["quorumPublicKey"].get_str(), "0ee6b155297c084fd6ae7a1551ed69587479c8210007fd86275723a5f1ea9"
"816faa80da16d18563489e450b9e6fbbb88");
BOOST_CHECK_EQUAL(json["quorumVvecHash"].get_str(),
"db07f2cd1f4c300ec88a2025bbe964d635c3d0e9c5ad73a2bdb3cc7c9834130e");
BOOST_CHECK_EQUAL(json["quorumSig"].get_str(), "827bd163b2a93ea99df01c01c4fb892fe1207ec35f126fc0fe6e52698f59d5005f0"
"3af5b0aafd109822d3e1ba616c63a0f0fb3081c4b615696cdf2b28af910790b8979"
"1ebad4b747607195f91b95d4b60596c69aee3845cc49ff4818323d358f");
BOOST_CHECK_EQUAL(json["validMembers"].get_str(), "ffffffffffffffffffffffff0f");
BOOST_CHECK_EQUAL(json["validMembersCount"].getInt<int>(), 100);
const uint256 hash_legacy{BuildCommitmentHash(qc.llmqType, qc.quorumHash, qc.validMembers, qc.quorumPublicKey,
qc.quorumVvecHash, BLSScheme::Legacy)};
const uint256 hash_basic{BuildCommitmentHash(qc.llmqType, qc.quorumHash, qc.validMembers, qc.quorumPublicKey,
qc.quorumVvecHash, BLSScheme::Basic)};
BOOST_CHECK(hash_legacy != hash_basic);
BOOST_CHECK(qc.quorumSig.VerifyInsecure(qc.quorumPublicKey, hash_legacy, BLSScheme::Legacy));
BOOST_CHECK(!qc.quorumSig.VerifyInsecure(qc.quorumPublicKey, hash_legacy, BLSScheme::Basic));
BOOST_CHECK(!qc.quorumSig.VerifyInsecure(qc.quorumPublicKey, hash_basic, BLSScheme::Legacy));
BOOST_CHECK(!qc.quorumSig.VerifyInsecure(qc.quorumPublicKey, hash_basic, BLSScheme::Basic));
}
namespace {
//! v19 activates at 150, between the LLMQ_TEST quorum bases at 120 and 168, and LLMQ_TEST is cut
//! down to one member so a single masternode can sign a commitment. The base chain is the
//! checkpointed 101 blocks; registration is mined afterwards.
struct CommitmentSchemeSetup : public TestChainSetup {
CBLSSecretKey operator_key;
CommitmentSchemeSetup() :
TestChainSetup{101, ChainType::REGTEST, {"-dip3params=2:500", "-testactivationheight=v19@150", "-llmqtestparams=1:1"}}
{
// Two coinbases have to be mature before a 1000 DASH collateral can be funded.
mineBlocks(8);
auto utxos = BuildSimpleUtxoMap(m_coinbase_txns);
CKey owner_key;
const auto tx_reg = CreateProRegTx(*Assert(m_node.chainman), utxos, /*port=*/21001, GenerateRandomAddress(),
coinbaseKey, owner_key, operator_key);
CreateAndProcessBlock({tx_reg}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
}
//! Member and quorum signatures are chosen separately. Passing the same scheme for both matches
//! a commitment signed entirely under one scheme.
CFinalCommitment MakeCommitment(const CBlockIndex* base, BLSScheme member_scheme, BLSScheme quorum_scheme) const
{
const auto& chainman = *Assert(m_node.chainman);
const auto& consensus = chainman.GetConsensus();
const auto llmq_params = *Assert(Params().GetLLMQ(Consensus::LLMQType::LLMQ_TEST));
CFinalCommitment qc(llmq_params, base->GetBlockHash());
qc.nVersion = CFinalCommitment::GetVersion(/*is_rotation_enabled=*/false,
DeploymentActiveAfter(base, consensus, Consensus::DEPLOYMENT_V19));
qc.quorumIndex = 0;
qc.signers.assign(llmq_params.size, true);
qc.validMembers.assign(llmq_params.size, true);
qc.quorumPublicKey = operator_key.GetPublicKey();
const uint256 member_hash = BuildCommitmentHash(llmq_params.type, qc.quorumHash, qc.validMembers,
qc.quorumPublicKey, qc.quorumVvecHash, member_scheme);
const uint256 quorum_hash = BuildCommitmentHash(llmq_params.type, qc.quorumHash, qc.validMembers,
qc.quorumPublicKey, qc.quorumVvecHash, quorum_scheme);
qc.membersSig = SignBLS(operator_key, member_hash, member_scheme);
qc.quorumSig = SignBLS(operator_key, quorum_hash, quorum_scheme);
return qc;
}
};
} // namespace
BOOST_FIXTURE_TEST_CASE(commitment_signatures_follow_the_given_scheme, CommitmentSchemeSetup)
{
ChainstateManager& chainman = *Assert(m_node.chainman);
auto& dmnman = *m_node.chainman->ActiveEvo().dmnman;
const CScript coinbase_pk = GetScriptForRawPubKey(coinbaseKey.GetPubKey());
mineBlocks(168 - WITH_LOCK(::cs_main, return chainman.ActiveHeight()));
dmnman.UpdatedBlockTip(WITH_LOCK(::cs_main, return chainman.ActiveChain().Tip()));
const CBlockIndex* legacy_base{WITH_LOCK(::cs_main, return chainman.ActiveChain()[120])};
const CBlockIndex* basic_base{WITH_LOCK(::cs_main, return chainman.ActiveChain()[168])};
const auto& consensus = chainman.GetConsensus();
BOOST_REQUIRE(!DeploymentActiveAfter(legacy_base, consensus, Consensus::DEPLOYMENT_V19));
BOOST_REQUIRE(DeploymentActiveAfter(basic_base, consensus, Consensus::DEPLOYMENT_V19));
// The commitment's version, and with it the encoding of its BLS fields, follows the quorum
// base. The scheme it is signed under is chosen separately.
auto verify = [&](const CBlockIndex* base, BLSScheme sign_scheme, BLSScheme verify_scheme) {
const UtilParameters util_params{dmnman, *m_node.chainman->ActiveEvo().qsnapman, chainman, base};
const CFinalCommitment qc{MakeCommitment(base, sign_scheme, sign_scheme)};
const bool direct{qc.Verify(util_params, verify_scheme)};
// Block validation queues the checks instead of running them inline.
CCheckQueue<utils::BlsCheck> queue{/*batch_size=*/4, /*worker_threads_num=*/0};
CCheckQueueControl<utils::BlsCheck> control{&queue};
const bool queued{qc.VerifySignatureAsync(util_params, &control, verify_scheme) && control.Wait()};
BOOST_CHECK_EQUAL(direct, queued);
return direct;
};
struct Case {
const CBlockIndex* base;
BLSScheme sign_scheme;
BLSScheme verify_scheme;
bool expected;
};
const Case cases[]{
{legacy_base, BLSScheme::Legacy, BLSScheme::Legacy, true},
{legacy_base, BLSScheme::Legacy, BLSScheme::Basic, false},
{legacy_base, BLSScheme::Basic, BLSScheme::Legacy, false},
// A legacy-version commitment mined after v19 is verified under basic.
{legacy_base, BLSScheme::Basic, BLSScheme::Basic, true},
{basic_base, BLSScheme::Basic, BLSScheme::Basic, true},
{basic_base, BLSScheme::Legacy, BLSScheme::Basic, false},
};
for (const auto& c : cases) {
BOOST_TEST_CONTEXT("base=" << c.base->nHeight << " signed_legacy=" << (c.sign_scheme == BLSScheme::Legacy)
<< " verified_legacy=" << (c.verify_scheme == BLSScheme::Legacy))
{
BOOST_CHECK_EQUAL(verify(c.base, c.sign_scheme, c.verify_scheme), c.expected);
}
}
}
BOOST_FIXTURE_TEST_CASE(mined_commitment_scheme_follows_the_block, CommitmentSchemeSetup)
{
ChainstateManager& chainman = *Assert(m_node.chainman);
auto& dmnman = *m_node.chainman->ActiveEvo().dmnman;
auto& qblockman = *Assert(m_node.chainman->ActiveEvo().quorum_block_processor);
const CScript coinbase_pk = GetScriptForRawPubKey(coinbaseKey.GetPubKey());
const auto& consensus = chainman.GetConsensus();
const auto tip_height = [&] { return WITH_LOCK(::cs_main, return chainman.ActiveHeight()); };
mineBlocks(129 - tip_height());
BOOST_REQUIRE_EQUAL(tip_height(), 129);
dmnman.UpdatedBlockTip(WITH_LOCK(::cs_main, return chainman.ActiveChain().Tip()));
// A size-1 quorum checks the member signature inline and returns before queueing the quorum
// signature. ProcessBlock only fails the block from the queue, so the member signature is made
// under the block scheme and the quorum signature is the one under test.
// A wrong-scheme commitment is spliced into the assembler's block. It is never cached, so a
// rejected fully-signed commitment cannot block the good one.
auto reject_reason = [&](const CFinalCommitment& qc) {
const int height = tip_height() + 1;
bool replaced = false;
CBlock block = CreateBlock({}, coinbase_pk, chainman.ActiveChainstate(), [&](CBlock& assembled) {
for (auto& tx : assembled.vtx) {
if (!tx->IsSpecialTxVersion() || tx->nType != TRANSACTION_QUORUM_COMMITMENT) continue;
const auto payload = GetTxPayload<CFinalCommitmentTxPayload>(*tx);
if (!payload || payload->commitment.llmqType != Consensus::LLMQType::LLMQ_TEST) continue;
CFinalCommitmentTxPayload next;
next.nVersion = CFinalCommitmentTxPayload::CURRENT_VERSION;
next.nHeight = height;
next.commitment = qc;
CMutableTransaction mtx{*tx};
SetTxPayload(mtx, next);
tx = MakeTransactionRef(std::move(mtx));
replaced = true;
break;
}
});
BOOST_REQUIRE(replaced);
const auto shared = std::make_shared<const CBlock>(block);
BlockValidationStateCatcher catcher{shared->GetHash()};
const int tip = tip_height();
RegisterValidationInterface(&catcher);
chainman.ProcessNewBlock(shared, /*force_processing=*/true, /*new_block=*/nullptr);
UnregisterValidationInterface(&catcher);
SyncWithValidationInterfaceQueue();
BOOST_CHECK_EQUAL(tip_height(), tip);
BOOST_REQUIRE(catcher.m_state);
return catcher.m_state->GetRejectReason();
};
const auto accept = [&](const CFinalCommitment& qc, const CBlockIndex* base) {
BOOST_REQUIRE(qblockman.AddMineableCommitment(qc));
const int tip = tip_height();
CreateAndProcessBlock({}, coinbase_pk);
BOOST_CHECK_EQUAL(tip_height(), tip + 1);
BOOST_CHECK(WITH_LOCK(::cs_main,
return qblockman.HasMinedCommitment(Consensus::LLMQType::LLMQ_TEST, base->GetBlockHash())));
};
const CBlockIndex* base_120{WITH_LOCK(::cs_main, return chainman.ActiveChain()[120])};
BOOST_REQUIRE(!DeploymentActiveAfter(base_120, consensus, Consensus::DEPLOYMENT_V19));
BOOST_REQUIRE(BLSSchemeAfter(WITH_LOCK(::cs_main, return chainman.ActiveChain().Tip()), consensus) == BLSScheme::Legacy);
BOOST_CHECK_EQUAL(reject_reason(MakeCommitment(base_120, BLSScheme::Legacy, BLSScheme::Basic)), "bad-qc-invalid");
BOOST_CHECK(!WITH_LOCK(::cs_main, return qblockman.HasMinedCommitment(Consensus::LLMQType::LLMQ_TEST,
base_120->GetBlockHash())));
accept(MakeCommitment(base_120, BLSScheme::Legacy, BLSScheme::Legacy), base_120);
mineBlocks(153 - tip_height());
BOOST_REQUIRE_EQUAL(tip_height(), 153);
dmnman.UpdatedBlockTip(WITH_LOCK(::cs_main, return chainman.ActiveChain().Tip()));
const CBlockIndex* base_144{WITH_LOCK(::cs_main, return chainman.ActiveChain()[144])};
BOOST_REQUIRE(!DeploymentActiveAfter(base_144, consensus, Consensus::DEPLOYMENT_V19));
BOOST_REQUIRE(BLSSchemeAfter(WITH_LOCK(::cs_main, return chainman.ActiveChain().Tip()), consensus) == BLSScheme::Basic);
const auto basic_signed = MakeCommitment(base_144, BLSScheme::Basic, BLSScheme::Basic);
BOOST_CHECK_EQUAL(basic_signed.nVersion,
CFinalCommitment::GetVersion(/*is_rotation_enabled=*/false, /*is_basic_scheme_active=*/false));
BOOST_CHECK_EQUAL(reject_reason(MakeCommitment(base_144, BLSScheme::Basic, BLSScheme::Legacy)), "bad-qc-invalid");
accept(basic_signed, base_144);
}
BOOST_AUTO_TEST_SUITE_END()