Repository navigation
Expand file tree
/
Copy pathevo_islock_tests.cpp
More file actions
597 lines (517 loc) · 27.8 KB
/
Copy pathevo_islock_tests.cpp
File metadata and controls
597 lines (517 loc) · 27.8 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
// 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 <chainparams.h>
#include <consensus/consensus.h>
#include <evo/assetlocktx.h>
#include <evo/specialtx.h>
#include <hash.h>
#include <instantsend/instantsend.h>
#include <instantsend/lock.h>
#include <instantsend/net_instantsend.h>
#include <interfaces/handler.h>
#include <llmq/context.h>
#include <llmq/quorumsman.h>
#include <llmq/signhash.h>
#include <llmq/signing.h>
#include <primitives/transaction.h>
#include <script/standard.h>
#include <spork.h>
#include <streams.h>
#include <test/util/llmq_tests.h>
#include <test/util/net.h>
#include <test/util/setup_common.h>
#include <uint256.h>
#include <util/strencodings.h>
#include <validation.h>
#include <string_view>
#include <boost/test/unit_test.hpp>
struct NetInstantSendTest : TestChain100Setup {
const Consensus::LLMQParams& params{llmq::testutils::GetLLMQParams(Consensus::LLMQType::LLMQ_TEST_INSTANTSEND)};
llmq::CSigningManager& sigman{*m_node.llmq_ctx->sigman};
NetInstantSend net{m_node.peerman.get(), *m_node.isman, nullptr, sigman, *m_node.llmq_ctx->qman,
*m_node.chainlocks, *m_node.chainman, *m_node.mempool, *m_node.mn_sync};
NetInstantSendTest()
{
constexpr const char* REGTEST_SPORK_PRIVKEY{"cP4EKFyJsHT39LDqgdcB43Y3YXjNyjb5Fuas1GQSeAtjnZWmZEQK"};
BOOST_REQUIRE(m_node.sporkman->SetSporkAddress(Params().SporkAddress()));
BOOST_REQUIRE(m_node.sporkman->SetPrivKey(REGTEST_SPORK_PRIVKEY));
BOOST_REQUIRE(m_node.sporkman->UpdateSpork(SPORK_2_INSTANTSEND_ENABLED, 0).has_value());
}
static Uint256HashSet ProcessBatch(NetInstantSend& net, const Consensus::LLMQParams& params, int offset,
const std::vector<instantsend::PendingISLockEntry>& locks)
{
return net.ProcessPendingInstantSendLocks(params, offset, /*ban=*/true, locks);
}
// Returns the cycle hash of a quorum whose base block is at `height`. Mining a block afterwards drops it.
uint256 AddMinedQuorum(int height, const CBLSSecretKey& key)
{
LOCK(cs_main);
const CChain& chain = m_node.chainman->ActiveChain();
auto qc = llmq::testutils::CreateValidCommitment(params, chain[height]->GetBlockHash());
qc.quorumPublicKey = key.GetPublicKey();
llmq::testutils::WriteMinedCommitment(*m_node.evodb, qc, chain[height + 10]->GetBlockHash(), height + 10, height);
return qc.quorumHash;
}
void Sign(instantsend::InstantSendLock& islock, const CBLSSecretKey& key) const
{
const auto sign_hash = llmq::SignHash{params.type, islock.cycleHash, islock.GetRequestId(), islock.txid}.Get();
const bool legacy = bls::bls_legacy_scheme.load();
islock.sig.Set(key.Sign(sign_hash, legacy), legacy);
}
std::shared_ptr<instantsend::InstantSendLock> MakeLock(const uint256& cycle_hash, const CBLSSecretKey& key,
const uint256& txid = GetRandHash(),
const COutPoint& input = COutPoint{GetRandHash(), 0}) const
{
auto islock = std::make_shared<instantsend::InstantSendLock>();
islock->txid = txid;
islock->inputs.push_back(input);
islock->cycleHash = cycle_hash;
Sign(*islock, key);
return islock;
}
void CacheRecoveredSig(const instantsend::InstantSendLock& islock)
{
BOOST_REQUIRE(sigman.ProcessRecoveredSig(std::make_shared<llmq::CRecoveredSig>(params.type, islock.cycleHash,
islock.GetRequestId(),
islock.txid, islock.sig)));
}
void Process(NodeId node, const std::shared_ptr<instantsend::InstantSendLock>& islock)
{
ProcessBatch(net, params, /*offset=*/0, {{{node, islock}, ::SerializeHash(*islock)}});
}
};
BOOST_AUTO_TEST_SUITE(evo_islock_tests)
BOOST_FIXTURE_TEST_CASE(received_genesis_cycle_has_no_quorum, TestChain100Setup)
{
LOCK(NetEventsInterface::g_msgproc_mutex);
constexpr const char* REGTEST_SPORK_PRIVKEY{"cP4EKFyJsHT39LDqgdcB43Y3YXjNyjb5Fuas1GQSeAtjnZWmZEQK"};
BOOST_REQUIRE(m_node.sporkman->SetSporkAddress(Params().SporkAddress()));
BOOST_REQUIRE(m_node.sporkman->SetPrivKey(REGTEST_SPORK_PRIVKEY));
BOOST_REQUIRE(m_node.sporkman->UpdateSpork(SPORK_2_INSTANTSEND_ENABLED, 0).has_value());
auto& isman = *m_node.isman;
auto& qman = *m_node.llmq_ctx->qman;
auto& sigman = *m_node.llmq_ctx->sigman;
NetInstantSend net{m_node.peerman.get(), isman, nullptr, sigman, qman, *m_node.chainlocks,
*m_node.chainman, *m_node.mempool, *m_node.mn_sync};
const auto params = Params().GetLLMQ(Params().GetConsensus().llmqTypeDIP0024InstantSend).value();
BOOST_REQUIRE(params.useRotation);
const CChain& chain = *WITH_LOCK(cs_main, return &m_node.chainman->ActiveChain());
WITH_LOCK(cs_main, isman.CacheTipHeight(chain.Tip()));
BOOST_REQUIRE_GT(isman.GetTipHeight(), params.dkgInterval);
// A peer can supply a known cycle boundary from before any quorums existed.
instantsend::InstantSendLock islock;
islock.txid = GetRandHash();
islock.inputs.emplace_back(GetRandHash(), 0);
islock.cycleHash = WITH_LOCK(cs_main, return chain.Genesis()->GetBlockHash());
CBLSSecretKey key;
key.MakeNewKey();
const bool legacy = bls::bls_legacy_scheme.load();
islock.sig.Set(key.Sign(islock.GetRequestId(), legacy), legacy);
auto peer = MakeTestPeer(/*id=*/1);
m_node.peerman->InitializeNode(*peer, NODE_NETWORK);
CDataStream stream{SER_NETWORK, PROTOCOL_VERSION};
stream << islock;
net.ProcessMessage(*peer, NetMsgType::ISDLOCK, stream);
const auto pending = isman.FetchPendingLocks();
BOOST_REQUIRE_EQUAL(pending.m_pending_is.size(), 1U);
const auto hash = ::SerializeHash(islock);
BOOST_CHECK(pending.m_pending_is.front().islock_hash == hash);
BOOST_CHECK_EQUAL(pending.m_pending_is.front().node_id, peer->GetId());
BOOST_REQUIRE(pending.m_pending_is.front().islock->sig.Get().IsValid());
BOOST_REQUIRE(!sigman.HasRecoveredSig(params.type, islock.GetRequestId(), islock.txid));
for (const int offset : {0, params.dkgInterval}) {
// BuildVerificationBatch selects cycleHeight + dkgInterval - 1 for this old cycle.
BOOST_CHECK(
!llmq::SelectQuorumForSigning(params, chain, qman, islock.GetRequestId(), params.dkgInterval - 1, offset));
const auto failed = NetInstantSendTest::ProcessBatch(net, params, offset, pending.m_pending_is);
BOOST_CHECK(failed.contains(hash));
BOOST_CHECK(!isman.AlreadyHave(CInv{MSG_ISDLOCK, hash}));
}
BOOST_CHECK_EQUAL(MisbehaviorScore(*m_node.peerman, *peer), 0);
}
BOOST_FIXTURE_TEST_CASE(missing_quorum_does_not_drop_batch, NetInstantSendTest)
{
CBLSSecretKey key;
key.MakeNewKey();
const auto cycle_hash = AddMinedQuorum(/*height=*/24, key);
const auto missing_cycle = WITH_LOCK(cs_main, return m_node.chainman->ActiveChain().Genesis()->GetBlockHash());
std::vector<instantsend::PendingISLockEntry> locks;
for (int i = 0; i < 3; ++i) {
auto islock = MakeLock(i == 1 ? missing_cycle : cycle_hash, key);
if (i != 1) {
// Exercise the already-verified path on either side of an unavailable quorum.
CacheRecoveredSig(*islock);
}
locks.push_back({{i == 2 ? 2 : 1, islock}, ::SerializeHash(*islock)});
}
const auto failed = ProcessBatch(net, params, /*offset=*/0, locks);
BOOST_CHECK_EQUAL(failed.size(), 1U);
BOOST_CHECK(failed.contains(locks[1].islock_hash));
BOOST_CHECK(m_node.isman->AlreadyHave(CInv{MSG_ISDLOCK, locks[0].islock_hash}));
BOOST_CHECK(!m_node.isman->AlreadyHave(CInv{MSG_ISDLOCK, locks[1].islock_hash}));
BOOST_CHECK(m_node.isman->AlreadyHave(CInv{MSG_ISDLOCK, locks[2].islock_hash}));
const auto retried = ProcessBatch(net, params, params.dkgInterval, {locks[1]});
BOOST_CHECK(retried.contains(locks[1].islock_hash));
BOOST_CHECK(!m_node.isman->AlreadyHave(CInv{MSG_ISDLOCK, locks[1].islock_hash}));
BOOST_CHECK(!sigman.HasRecoveredSig(params.type, locks[1].islock->GetRequestId(), locks[1].islock->txid));
BOOST_CHECK(sigman.FetchPendingReconstructed().empty());
}
BOOST_FIXTURE_TEST_CASE(cached_recovered_sig_does_not_authenticate_other_lock, NetInstantSendTest)
{
CBLSSecretKey key;
key.MakeNewKey();
CBLSSecretKey other_key;
other_key.MakeNewKey();
mineBlocks(1); // Matures a second coinbase to spend.
const auto cycle_hash = AddMinedQuorum(/*height=*/24, key);
const auto other_cycle_hash = AddMinedQuorum(/*height=*/48, other_key);
for (const bool change_cycle : {false, true}) {
// A stored lock only blocks later locks for the same txid once the transaction is known.
const int coinbase_index{change_cycle};
const auto& coinbase = m_coinbase_txns[coinbase_index];
const auto tx = CreateValidMempoolTransaction(coinbase, /*input_vout=*/0, /*input_height=*/coinbase_index + 1,
coinbaseKey, GetScriptForRawPubKey(coinbaseKey.GetPubKey()),
coinbase->vout[0].nValue - 1000);
const auto authentic = MakeLock(cycle_hash, key, tx.GetHash(), tx.vin[0].prevout);
CacheRecoveredSig(*authentic);
// Same txid, but either signed by another key or claiming another cycle.
auto forged = std::make_shared<instantsend::InstantSendLock>(*authentic);
if (change_cycle) {
forged->cycleHash = other_cycle_hash;
} else {
Sign(*forged, other_key);
}
Process(/*node=*/1, forged);
BOOST_CHECK(!m_node.isman->GetInstantSendLockByTxid(authentic->txid));
Process(/*node=*/2, authentic);
const auto stored = m_node.isman->GetInstantSendLockByTxid(authentic->txid);
BOOST_REQUIRE(stored);
BOOST_CHECK(::SerializeHash(*stored) == ::SerializeHash(*authentic));
}
}
uint256 CalculateRequestId(const std::vector<COutPoint>& inputs)
{
CHashWriter hw(SER_GETHASH, 0);
hw << std::string_view("islock");
hw << inputs;
return hw.GetHash();
}
BOOST_AUTO_TEST_CASE(getrequestid)
{
// Create an empty InstantSendLock
instantsend::InstantSendLock islock;
// Compute expected hash for an empty inputs vector.
// Note: InstantSendLock::GetRequestId() serializes the prefix "islock"
// followed by the 'inputs' vector.
{
const uint256 expected = CalculateRequestId(islock.inputs);
BOOST_CHECK(islock.GetRequestId() == expected);
}
// Now add two dummy inputs to the lock
islock.inputs.clear();
// Construct two dummy outpoints (using uint256S for a dummy hash)
COutPoint op1(uint256::ONE, 0);
COutPoint op2(uint256::TWO, 1);
islock.inputs.push_back(op1);
islock.inputs.push_back(op2);
const uint256 expected = CalculateRequestId(islock.inputs);
BOOST_CHECK(islock.GetRequestId() == expected);
}
BOOST_AUTO_TEST_CASE(deserialize_instantlock_from_realdata2)
{
// Expected values from the provided getislocks output:
const std::string_view expectedTxidStr = "7b33968effa613e8ea9c1b5734c9bbbe467ff4650f8060caf8a5c213c6059d5b";
const std::string_view expectedCycleHashStr = "000000000000000bbd0b1bb95540351e7ee99c5b08efde076b3d712a57ea74d6";
const std::string_view expectedSignatureStr =
"997d0b36738a9eef46ceeb4405998ff7235317708f277402799ffe05258015cae9b6bae"
"43683f992b2f50f70f8f0cb9c0f26af340b00903e93995c1345d1b2c5b697ebecdbe581"
"1dd112e11889101dcb4553b2bc206ab304026b96c07dec4f24";
const std::string quorumHashStr = "0000000000000019756ecc9c9c5f476d3f66876b1dcfa5dde1ea82f0d99334a2";
const std::string_view expectedSignHashStr = "6a3c37bc610c4efd5babd8941068a8eca9e7bec942fe175b8ca9cae31b67e838";
// The serialized InstantSend lock from the "hex" field of getislocks:
const std::string_view islockHex =
"0101497915895c30eebfad0c5fcfb9e0e72308c7e92cd3749be2fd49c8320c4c58b6010000005b9d05c613c2a5f8ca60800f65f47f46be"
"bbc934571b9ceae813a6ff8e96337bd674ea572a713d6b07deef085b9ce97e1e354055b91b0bbd0b00000000000000997d0b36738a9eef"
"46ceeb4405998ff7235317708f277402799ffe05258015cae9b6bae43683f992b2f50f70f8f0cb9c0f26af340b00903e93995c1345d1b2"
"c5b697ebecdbe5811dd112e11889101dcb4553b2bc206ab304026b96c07dec4f24";
// This islock was created with non-legacy. Using legacy will result in the signature being all zeros.
bls::bls_legacy_scheme.store(false);
// Convert hex string to a byte vector and deserialize.
std::vector<unsigned char> islockData = ParseHex(islockHex);
CDataStream ss(islockData, SER_NETWORK, PROTOCOL_VERSION);
instantsend::InstantSendLock islock;
ss >> islock;
// Verify the calculated signHash
auto signHash =
llmq::SignHash(Consensus::LLMQType::LLMQ_60_75, uint256S(quorumHashStr), islock.GetRequestId(), islock.txid).Get();
BOOST_CHECK_EQUAL(signHash.ToString(), expectedSignHashStr);
// Verify the txid field.
BOOST_CHECK_EQUAL(islock.txid.ToString(), expectedTxidStr);
// Verify the cycleHash field.
BOOST_CHECK_EQUAL(islock.cycleHash.ToString(), expectedCycleHashStr);
// Verify the inputs vector has exactly one element.
BOOST_REQUIRE_EQUAL(islock.inputs.size(), 1U);
const COutPoint& input = islock.inputs.front();
const std::string expectedInputTxid = "b6584c0c32c849fde29b74d32ce9c70823e7e0b9cf5f0cadbfee305c89157949";
const unsigned int expectedInputN = 1;
BOOST_CHECK_EQUAL(input.hash.ToString(), expectedInputTxid);
BOOST_CHECK_EQUAL(input.n, expectedInputN);
// Compute the expected request ID: it is the hash of the constant prefix "islock" followed by the inputs.
uint256 expectedRequestId = CalculateRequestId(islock.inputs);
BOOST_CHECK_EQUAL(islock.GetRequestId().ToString(), expectedRequestId.ToString());
// Verify the signature field.
BOOST_CHECK_EQUAL(islock.sig.Get().ToString(), expectedSignatureStr);
}
BOOST_AUTO_TEST_CASE(geninputlockrequestid_basic)
{
// Test that GenInputLockRequestId generates consistent hashes for the same outpoint
const uint256 txHash = uint256S("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef");
const uint32_t outputIndex = 5;
COutPoint outpoint1(txHash, outputIndex);
COutPoint outpoint2(txHash, outputIndex);
// Same outpoints should produce identical request IDs
const uint256 requestId1 = instantsend::GenInputLockRequestId(outpoint1);
const uint256 requestId2 = instantsend::GenInputLockRequestId(outpoint2);
BOOST_CHECK(requestId1 == requestId2);
BOOST_CHECK(!requestId1.IsNull());
}
BOOST_AUTO_TEST_CASE(geninputlockrequestid_different_outpoints)
{
// Test that different outpoints produce different request IDs
const uint256 txHash1 = uint256S("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef");
const uint256 txHash2 = uint256S("0xfedcba0987654321fedcba0987654321fedcba0987654321fedcba0987654321");
COutPoint outpoint1(txHash1, 0);
COutPoint outpoint2(txHash2, 0);
COutPoint outpoint3(txHash1, 1); // Same hash, different index
const uint256 requestId1 = instantsend::GenInputLockRequestId(outpoint1);
const uint256 requestId2 = instantsend::GenInputLockRequestId(outpoint2);
const uint256 requestId3 = instantsend::GenInputLockRequestId(outpoint3);
// All should be different
BOOST_CHECK(requestId1 != requestId2);
BOOST_CHECK(requestId1 != requestId3);
BOOST_CHECK(requestId2 != requestId3);
}
BOOST_AUTO_TEST_CASE(geninputlockrequestid_only_outpoint_matters)
{
// Critical test: Verify that only the COutPoint is hashed, not scriptSig or nSequence
// This validates the fix where CTxIn was incorrectly used before
const uint256 txHash = uint256S("0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890");
const uint32_t outputIndex = 3;
COutPoint outpoint(txHash, outputIndex);
// Create two CTxIn objects with the same prevout but different scriptSig and nSequence
CTxIn txin1;
txin1.prevout = outpoint;
txin1.scriptSig = CScript() << OP_1 << OP_2;
txin1.nSequence = 0xFFFFFFFF;
CTxIn txin2;
txin2.prevout = outpoint;
txin2.scriptSig = CScript() << OP_3 << OP_4 << OP_5; // Different scriptSig
txin2.nSequence = 0x12345678; // Different nSequence
// The request IDs should be identical because they share the same prevout (COutPoint)
const uint256 requestId1 = instantsend::GenInputLockRequestId(txin1.prevout);
const uint256 requestId2 = instantsend::GenInputLockRequestId(txin2.prevout);
BOOST_CHECK(requestId1 == requestId2);
// Also verify against the direct outpoint
const uint256 requestId3 = instantsend::GenInputLockRequestId(outpoint);
BOOST_CHECK(requestId1 == requestId3);
}
BOOST_AUTO_TEST_CASE(geninputlockrequestid_serialization_format)
{
// Test that the serialization format is: SerializeHash(pair("inlock", outpoint))
const uint256 txHash = uint256S("0x0000000000000000000000000000000000000000000000000000000000000001");
const uint32_t outputIndex = 0;
COutPoint outpoint(txHash, outputIndex);
// Calculate the expected hash manually
const uint256 expectedHash = ::SerializeHash(std::make_pair(std::string_view("inlock"), outpoint));
// Get the actual hash from the function
const uint256 actualHash = instantsend::GenInputLockRequestId(outpoint);
BOOST_CHECK(actualHash == expectedHash);
}
BOOST_AUTO_TEST_CASE(geninputlockrequestid_edge_cases)
{
// Test edge cases: null hash, max index
COutPoint nullOutpoint(uint256(), 0);
COutPoint maxIndexOutpoint(uint256::ONE, COutPoint::NULL_INDEX);
const uint256 nullRequestId = instantsend::GenInputLockRequestId(nullOutpoint);
const uint256 maxIndexRequestId = instantsend::GenInputLockRequestId(maxIndexOutpoint);
// Both should produce valid (non-null) request IDs
BOOST_CHECK(!nullRequestId.IsNull());
BOOST_CHECK(!maxIndexRequestId.IsNull());
// And they should be different from each other
BOOST_CHECK(nullRequestId != maxIndexRequestId);
}
// Regression test for the islock input cap: an oversized input vector must be
// rejected by TriviallyValid(), while the cap is derived so it can never reject a valid lock.
BOOST_AUTO_TEST_CASE(trivially_valid_input_cap)
{
// A lock with a non-null txid and a few unique inputs is trivially valid.
instantsend::InstantSendLock islock;
islock.txid = uint256::ONE;
islock.inputs = {COutPoint(uint256::ONE, 0), COutPoint(uint256::ONE, 1)};
BOOST_CHECK(islock.TriviallyValid());
// MAX_INPUTS is derived from MaxBlockSize(): a consensus-valid transaction must fit in a
// block and each input is >=41 bytes on the wire, so it can never carry more than
// MaxBlockSize() / 41 inputs. The cap thus cannot reject a legitimate islock, and it
// tracks any future block-size change.
BOOST_CHECK_EQUAL(instantsend::InstantSendLock::MAX_INPUTS, MaxBlockSize() / 41);
// A lock carrying more than MAX_INPUTS inputs is rejected up front, before any O(n)
// hashing/dedup work, so a peer cannot pin an oversized input vector.
instantsend::InstantSendLock oversized;
oversized.txid = uint256::ONE;
oversized.inputs.assign(instantsend::InstantSendLock::MAX_INPUTS + 1, COutPoint(uint256::ONE, 0));
BOOST_CHECK(!oversized.TriviallyValid());
}
BOOST_AUTO_TEST_CASE(lock_inputs_of_asset_unlock)
{
// An asset unlock has no inputs; its lock pins the synthetic outpoint {DIP-27 request id, 0}
const auto make_unlock = [](uint8_t version, uint64_t index, uint32_t requested_height) {
CMutableTransaction mtx;
mtx.nVersion = 3;
mtx.nType = TRANSACTION_ASSET_UNLOCK;
mtx.vout.emplace_back(COIN, CScript{});
SetTxPayload(mtx, CAssetUnlockPayload{version, index, /*fee=*/2000, requested_height, uint256::ONE,
CBLSSignature{}});
return CTransaction{mtx};
};
const uint64_t index{0x0011223344556677ULL};
const uint256 request_id{::SerializeHash(std::make_pair(std::string{"plwdtx"}, index))};
const CTransaction unlock{make_unlock(2, index, 500)};
BOOST_CHECK(instantsend::HasLockInputs(unlock));
const auto inputs = instantsend::GetLockInputs(unlock);
BOOST_REQUIRE_EQUAL(inputs.size(), 1U);
BOOST_CHECK(inputs[0] == COutPoint(request_id, 0));
// Every instance of one withdrawal maps to the same outpoint: re-signs (same txid), and
// version 1 instances (different txid) - so any two claimants of the index conflict
BOOST_CHECK(instantsend::GetLockInputs(make_unlock(2, index, 700)) == inputs);
const CTransaction unlock_v1{make_unlock(1, index, 500)};
BOOST_CHECK(unlock_v1.GetHash() != unlock.GetHash());
BOOST_CHECK(instantsend::GetLockInputs(unlock_v1) == inputs);
// A different withdrawal maps elsewhere
BOOST_CHECK(instantsend::GetLockInputs(make_unlock(2, index + 1, 500)) != inputs);
// Ordinary transactions pin their prevouts; input-less non-unlock transactions pin nothing
CMutableTransaction spend;
spend.vin.emplace_back(COutPoint(uint256::TWO, 3));
spend.vin.emplace_back(COutPoint(uint256::ONE, 1));
BOOST_CHECK(instantsend::HasLockInputs(CTransaction{spend}));
BOOST_CHECK((instantsend::GetLockInputs(CTransaction{spend}) ==
std::vector<COutPoint>{COutPoint(uint256::TWO, 3), COutPoint(uint256::ONE, 1)}));
CMutableTransaction commitment;
commitment.nVersion = 3;
commitment.nType = TRANSACTION_QUORUM_COMMITMENT;
BOOST_CHECK(!instantsend::HasLockInputs(CTransaction{commitment}));
BOOST_CHECK(instantsend::GetLockInputs(CTransaction{commitment}).empty());
CMutableTransaction coinbase;
coinbase.vin.emplace_back(COutPoint{});
BOOST_CHECK(!instantsend::HasLockInputs(CTransaction{coinbase}));
}
BOOST_FIXTURE_TEST_CASE(nonlocked_asset_unlock_refresh_is_retried, TestChain100Setup)
{
// A re-signed instance of a tracked version 2 asset unlock shares its txid; the retry queue
// must hand out the fresh instance, not the stale one first tracked
auto& isman = *m_node.isman;
const auto make_unlock = [](uint32_t requested_height) {
CMutableTransaction mtx;
mtx.nVersion = 3;
mtx.nType = TRANSACTION_ASSET_UNLOCK;
mtx.vout.emplace_back(COIN, CScript{});
SetTxPayload(mtx, CAssetUnlockPayload{2, /*index=*/7, /*fee=*/2000, requested_height, uint256::ONE,
CBLSSignature{}});
return MakeTransactionRef(mtx);
};
const auto unlock = make_unlock(500);
const auto unlock_resigned = make_unlock(700);
BOOST_REQUIRE(unlock->GetHash() == unlock_resigned->GetHash());
BOOST_REQUIRE(unlock->GetInstanceHash() != unlock_resigned->GetInstanceHash());
isman.AddNonLockedTx(unlock, nullptr);
isman.AddNonLockedTx(unlock_resigned, nullptr);
isman.RetryUnminedAssetUnlocks();
const auto retry = isman.PrepareTxToRetry();
BOOST_REQUIRE_EQUAL(retry.size(), 1U);
BOOST_CHECK(retry[0]->GetInstanceHash() == unlock_resigned->GetInstanceHash());
// Once handed out, an unlock is not retried again until the next block or refresh re-queues
// it; otherwise the worker would re-verify its signature on every iteration
BOOST_CHECK(isman.PrepareTxToRetry().empty());
isman.RetryUnminedAssetUnlocks();
BOOST_CHECK_EQUAL(isman.PrepareTxToRetry().size(), 1U);
// A stale instance arriving after the fresh one is likewise recorded: the mempool (not this
// tracker) decides which instance is held, and the tracker mirrors the last admitted one
isman.RemoveNonLockedTx(unlock->GetHash(), false);
BOOST_CHECK(isman.PrepareTxToRetry().empty());
}
BOOST_FIXTURE_TEST_CASE(nonlocked_asset_unlock_dropped_when_removed_from_mempool, TestChain100Setup)
{
// An unlocked asset unlock leaving the mempool has no inputs for the conflict cleanup to key
// on; the removal hook must drop it from the tracker or it is re-queued on every block
auto& isman = *m_node.isman;
CMutableTransaction mtx;
mtx.nVersion = 3;
mtx.nType = TRANSACTION_ASSET_UNLOCK;
mtx.vout.emplace_back(COIN, CScript{});
SetTxPayload(mtx, CAssetUnlockPayload{2, /*index=*/9, /*fee=*/2000, /*requestedHeight=*/500, uint256::ONE,
CBLSSignature{}});
const auto unlock = MakeTransactionRef(mtx);
isman.AddNonLockedTx(unlock, nullptr);
isman.RetryUnminedAssetUnlocks();
BOOST_REQUIRE_EQUAL(isman.PrepareTxToRetry().size(), 1U);
isman.TransactionIsRemoved(unlock);
BOOST_CHECK_EQUAL(isman.GetCounts().m_unprotected_tx, 0U);
isman.RetryUnminedAssetUnlocks();
BOOST_CHECK(isman.PrepareTxToRetry().empty());
}
BOOST_FIXTURE_TEST_CASE(nonlocked_ordinary_tx_released_on_mempool_removal, TestChain100Setup)
{
auto& isman = *m_node.isman;
auto net = std::make_shared<NetInstantSend>(m_node.peerman.get(), isman, nullptr, *m_node.llmq_ctx->sigman,
*m_node.llmq_ctx->qman, *m_node.chainlocks, *m_node.chainman,
*m_node.mempool, *m_node.mn_sync);
RegisterSharedValidationInterface(net);
const auto unregister = interfaces::MakeCleanupHandler([&] { UnregisterSharedValidationInterface(net); });
for (const bool expire : {true, false}) {
auto mtx = CreateValidMempoolTransaction(m_coinbase_txns.front(), 0, 1, coinbaseKey,
GetScriptForRawPubKey(coinbaseKey.GetPubKey()),
m_coinbase_txns.front()->vout[0].nValue - (expire ? 1000 : 2000));
const auto tx = WITH_LOCK(m_node.mempool->cs, return m_node.mempool->get(mtx.GetHash()));
BOOST_REQUIRE(tx);
isman.AddNonLockedTx(tx, nullptr);
if (expire) {
WITH_LOCK(m_node.mempool->cs,
m_node.mempool->Expire(GetTime<std::chrono::seconds>() + std::chrono::seconds{1}));
} else {
WITH_LOCK(m_node.mempool->cs, m_node.mempool->TrimToSize(0));
}
SyncWithValidationInterfaceQueue();
BOOST_CHECK_EQUAL(tx.use_count(), 1);
}
unregister->disconnect();
// Block removals do not emit TransactionRemovedFromMempool. Mined tracking must still
// retain the transaction and report a conflict until confirmation cleanup removes it.
CMutableTransaction mined;
mined.vin.emplace_back(COutPoint{GetRandHash(), 0});
mined.vout.emplace_back(COIN, CScript{});
const auto tx = MakeTransactionRef(mined);
const auto* tip = WITH_LOCK(cs_main, return m_node.chainman->ActiveTip());
isman.AddNonLockedTx(tx, tip);
// Peer rejection also reaches this entry point; it must preserve still-mined conflicts.
isman.TransactionIsRemoved(tx);
BOOST_CHECK_EQUAL(tx.use_count(), 2);
// An unmined spend of the same input, e.g. admitted after a reorg, must not drop the mined
// transaction from the outpoint index when it leaves the mempool.
CMutableTransaction spend;
spend.vin = mined.vin;
spend.vout.emplace_back(COIN / 2, CScript{});
const auto spend_tx = MakeTransactionRef(spend);
isman.AddNonLockedTx(spend_tx, nullptr);
isman.TransactionIsRemoved(spend_tx);
instantsend::InstantSendLock conflict;
conflict.txid = GetRandHash();
conflict.inputs.push_back(mined.vin.front().prevout);
{
const auto conflicts = isman.RetrieveISConflicts(GetRandHash(), conflict);
BOOST_REQUIRE_EQUAL(conflicts.size(), 1U);
BOOST_CHECK(conflicts.at(tip).contains(tx->GetHash()));
}
isman.RemoveNonLockedTx(tx->GetHash(), false);
BOOST_CHECK_EQUAL(tx.use_count(), 1);
}
BOOST_AUTO_TEST_SUITE_END()