forked from dashpay/dash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoinjoin_inouts_tests.cpp
More file actions
1710 lines (1433 loc) · 73.3 KB
/
Copy pathcoinjoin_inouts_tests.cpp
File metadata and controls
1710 lines (1433 loc) · 73.3 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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 The Dash Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <active/masternode.h>
#include <bls/bls.h>
#include <chain.h>
#include <chainlock/chainlock.h>
#include <coinjoin/coinjoin.h>
#include <coinjoin/common.h>
#include <coinjoin/options.h>
#include <coinjoin/server.h>
#include <evo/chainhelper.h>
#include <llmq/context.h>
#include <masternode/sync.h>
#include <net.h>
#include <node/connection_types.h>
#include <protocol.h>
#include <script/script.h>
#include <streams.h>
#include <test/util/setup_common.h>
#include <uint256.h>
#include <util/check.h>
#include <util/time.h>
#include <validation.h>
#include <boost/test/unit_test.hpp>
#include <algorithm>
#include <array>
#include <cstdint>
#include <memory>
#include <vector>
BOOST_FIXTURE_TEST_SUITE(coinjoin_inouts_tests, TestingSetup)
static CBLSSecretKey MakeSecretKey()
{
CBLSSecretKey sk;
sk.MakeNewKey();
return sk;
}
static CScript P2PKHScript(uint8_t tag = 0x01)
{
// OP_DUP OP_HASH160 <20-byte-tag> OP_EQUALVERIFY OP_CHECKSIG
std::vector<unsigned char> hash(20, tag);
return CScript{} << OP_DUP << OP_HASH160 << hash << OP_EQUALVERIFY << OP_CHECKSIG;
}
BOOST_AUTO_TEST_CASE(broadcasttx_isvalidstructure_good_and_bad)
{
// Good: equal vin/vout sizes, vin count >= min participants, <= max*entry_size, P2PKH outputs with standard denominations
CCoinJoinBroadcastTx good;
{
CMutableTransaction mtx;
// Use min pool participants (e.g. 3). Build 3 inputs and 3 denominated outputs
const int participants = std::max(3, CoinJoin::GetMinPoolParticipants());
for (int i = 0; i < participants; ++i) {
CTxIn in;
in.prevout = COutPoint(uint256::ONE, static_cast<uint32_t>(i));
mtx.vin.push_back(in);
// Pick the smallest denomination
CTxOut out{CoinJoin::GetSmallestDenomination(), P2PKHScript(static_cast<uint8_t>(i))};
mtx.vout.push_back(out);
}
good.tx = MakeTransactionRef(mtx);
good.m_protxHash = uint256::ONE; // at least one of (outpoint, protxhash) must be set
}
// Pre-V24 behavior (nullptr pindex = pre-fork)
BOOST_CHECK(good.IsValidStructure(nullptr, *Assert(m_node.chainman)));
// Bad: both identifiers null
CCoinJoinBroadcastTx bad_ids = good;
bad_ids.m_protxHash = uint256{};
bad_ids.masternodeOutpoint.SetNull();
BOOST_CHECK(!bad_ids.IsValidStructure(nullptr, *Assert(m_node.chainman)));
// Bad: vin/vout size mismatch (invalid pre-V24)
CCoinJoinBroadcastTx bad_sizes = good;
{
CMutableTransaction mtx(*good.tx);
mtx.vout.pop_back();
bad_sizes.tx = MakeTransactionRef(mtx);
}
BOOST_CHECK(!bad_sizes.IsValidStructure(nullptr, *Assert(m_node.chainman)));
// Bad: non-P2PKH output
CCoinJoinBroadcastTx bad_script = good;
{
CMutableTransaction mtx(*good.tx);
mtx.vout[0].scriptPubKey = CScript() << OP_RETURN << std::vector<unsigned char>{'x'};
bad_script.tx = MakeTransactionRef(mtx);
}
BOOST_CHECK(!bad_script.IsValidStructure(nullptr, *Assert(m_node.chainman)));
// Bad: non-denominated amount
CCoinJoinBroadcastTx bad_amount = good;
{
CMutableTransaction mtx(*good.tx);
mtx.vout[0].nValue = 42; // not a valid denom
bad_amount.tx = MakeTransactionRef(mtx);
}
BOOST_CHECK(!bad_amount.IsValidStructure(nullptr, *Assert(m_node.chainman)));
}
BOOST_AUTO_TEST_CASE(entry_addscriptsig_matches_and_rejects)
{
// Build an entry with two distinct inputs so we can check both the match
// and the isolation (only the matching input mutates).
const COutPoint op0(uint256::ONE, 0);
const COutPoint op1(uint256::ONE, 1);
const uint32_t seq0 = 0xfffffffeU;
const uint32_t seq1 = 0xfffffffdU;
auto make_dsin = [](const COutPoint& op, uint32_t seq) {
CTxIn in(op);
in.nSequence = seq;
return CTxDSIn(in, P2PKHScript(0x10), /*nRounds=*/0);
};
std::vector<CTxDSIn> dsins{make_dsin(op0, seq0), make_dsin(op1, seq1)};
CCoinJoinEntry entry(dsins, /*vecTxOut=*/{}, CTransaction{CMutableTransaction{}});
// The scriptSig we expect to be copied across on a successful match.
const CScript scriptSig0 = CScript() << std::vector<unsigned char>{0xde, 0xad} << std::vector<unsigned char>{0xbe, 0xef};
// Matching prevout + matching sequence -> copies scriptSig, sets fHasSig.
{
CTxIn signed_in(op0, scriptSig0, seq0);
BOOST_CHECK(entry.AddScriptSig(signed_in));
BOOST_CHECK(entry.vecTxDSIn[0].fHasSig);
BOOST_CHECK(entry.vecTxDSIn[0].scriptSig == scriptSig0);
// Other input is untouched.
BOOST_CHECK(!entry.vecTxDSIn[1].fHasSig);
BOOST_CHECK(entry.vecTxDSIn[1].scriptSig.empty());
}
// Duplicate signature for the already-signed input -> rejected, no overwrite.
{
const CScript scriptSig_other = CScript() << std::vector<unsigned char>{0x01};
CTxIn dup_in(op0, scriptSig_other, seq0);
BOOST_CHECK(!entry.AddScriptSig(dup_in));
// Still holds the original signature.
BOOST_CHECK(entry.vecTxDSIn[0].scriptSig == scriptSig0);
BOOST_CHECK(entry.vecTxDSIn[0].fHasSig);
}
// Wrong prevout (sequence matches an existing input) -> rejected.
{
const COutPoint op_wrong(uint256S("ff"), 9);
CTxIn wrong_in(op_wrong, scriptSig0, seq1);
BOOST_CHECK(!entry.AddScriptSig(wrong_in));
BOOST_CHECK(!entry.vecTxDSIn[1].fHasSig);
BOOST_CHECK(entry.vecTxDSIn[1].scriptSig.empty());
}
// Right prevout but wrong sequence -> rejected (guards against malleated nSequence).
{
CTxIn badseq_in(op1, scriptSig0, /*nSequence=*/seq1 ^ 0xffU);
BOOST_CHECK(!entry.AddScriptSig(badseq_in));
BOOST_CHECK(!entry.vecTxDSIn[1].fHasSig);
BOOST_CHECK(entry.vecTxDSIn[1].scriptSig.empty());
}
// Correct prevout + correct sequence on the second input -> succeeds, doesn't disturb the first.
{
const CScript scriptSig1 = CScript() << std::vector<unsigned char>{0xca, 0xfe};
CTxIn signed_in(op1, scriptSig1, seq1);
BOOST_CHECK(entry.AddScriptSig(signed_in));
BOOST_CHECK(entry.vecTxDSIn[1].fHasSig);
BOOST_CHECK(entry.vecTxDSIn[1].scriptSig == scriptSig1);
// First input unchanged.
BOOST_CHECK(entry.vecTxDSIn[0].scriptSig == scriptSig0);
}
}
// Test-only subclass exposing the minimal seams needed to observe how
// ProcessDSSIGNFINALTX treats messages from participants vs. non-participants
// without standing up a full DKG-backed signing session.
class TestableCoinJoinServer : public CCoinJoinServer
{
public:
using CCoinJoinServer::AddEntry;
using CCoinJoinServer::CCoinJoinServer;
using CCoinJoinServer::CreateFinalTransaction;
// A live session always carries a non-zero id, and AddEntry rejects entries that don't
// belong to one, so seed an id along with the state.
void EnterSigningState() { nSessionID = 1; nState = POOL_STATE_SIGNING; }
void EnterAcceptingEntriesState() { nSessionID = 1; nState = POOL_STATE_ACCEPTING_ENTRIES; }
void SeedParticipant(const CService& addr) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin)
{
CCoinJoinEntry entry;
entry.addr = addr;
LOCK(cs_coinjoin);
vecEntries.push_back(std::move(entry));
}
void SeedSessionCollateral(const CMutableTransaction& txCollateral, CoinJoin::MixShape shape)
EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin)
{
LOCK(cs_coinjoin);
m_mapDeclaredShapes.emplace(txCollateral.GetHash(), shape);
CommitSessionCollateral(txCollateral);
}
void SeedEntry(CCoinJoinEntry entry) EXCLUSIVE_LOCKS_REQUIRED(!cs_coinjoin)
{
LOCK(cs_coinjoin);
vecEntries.push_back(std::move(entry));
}
};
static std::unique_ptr<CNode> MakePeer(NodeId id, uint32_t ipv4)
{
in_addr peer_in_addr{};
peer_in_addr.s_addr = htonl(ipv4);
auto peer = std::make_unique<CNode>(id,
/*sock=*/nullptr,
/*addrIn=*/CAddress{CService{peer_in_addr, 8333}, NODE_NETWORK},
/*nKeyedNetGroupIn=*/0,
/*nLocalHostNonceIn=*/0,
/*addrBindIn=*/CAddress{},
/*addrNameIn=*/std::string{},
/*conn_type_in=*/ConnectionType::INBOUND,
/*inbound_onion=*/false);
peer->nVersion = PROTOCOL_VERSION;
peer->SetCommonVersion(PROTOCOL_VERSION);
return peer;
}
BOOST_AUTO_TEST_CASE(server_signfinaltx_nonparticipant_cannot_abort_session)
{
BOOST_REQUIRE(m_node.mn_sync);
m_node.mn_sync->SwitchToNextAsset();
BOOST_REQUIRE(m_node.mn_sync->IsBlockchainSynced());
CActiveMasternodeManager mn_activeman(*Assert(m_node.connman), *Assert(m_node.dmnman), MakeSecretKey());
TestableCoinJoinServer server(m_node.peerman.get(), *Assert(m_node.chainman), *Assert(m_node.connman),
*Assert(m_node.dmnman), *Assert(m_node.dstxman), *Assert(m_node.mn_metaman),
*Assert(m_node.mempool), mn_activeman, *Assert(m_node.mn_sync),
*Assert(m_node.isman));
// Seed an active signing session with one participant. That participant's
// addr is deliberately not registered with connman -- a session-wide
// RelayStatus(REJECTED) would therefore see nDisconnected == vecEntries.size()
// and reset the pool state to POOL_STATE_IDLE via SetNull().
auto participant = MakePeer(/*id=*/7, /*ipv4=*/0x0a000001);
server.SeedParticipant(participant->addr);
server.EnterSigningState();
BOOST_REQUIRE_EQUAL(server.GetState(), int{POOL_STATE_SIGNING});
auto nonparticipant = MakePeer(/*id=*/42, /*ipv4=*/0x01020304);
BOOST_REQUIRE(!(nonparticipant->addr == participant->addr));
const size_t max_txins{CoinJoin::GetMaxPoolInputOutputCount()};
CDataStream stream{SER_NETWORK, PROTOCOL_VERSION};
WriteCompactSize(stream, max_txins + 1);
BOOST_CHECK_NO_THROW(server.ProcessMessage(*nonparticipant, NetMsgType::DSSIGNFINALTX, stream));
// The non-participant must be rejected without touching session-wide state:
// the stream body must not have been read past the compact-size prefix, and
// the pool must still be in POOL_STATE_SIGNING with its entry intact.
BOOST_CHECK_EQUAL(stream.size(), GetSizeOfCompactSize(max_txins + 1));
BOOST_CHECK_EQUAL(server.GetState(), int{POOL_STATE_SIGNING});
BOOST_CHECK_EQUAL(server.GetEntriesCount(), 1);
}
BOOST_AUTO_TEST_CASE(server_signfinaltx_participant_oversized_count_is_rejected_locally)
{
BOOST_REQUIRE(m_node.mn_sync);
m_node.mn_sync->SwitchToNextAsset();
BOOST_REQUIRE(m_node.mn_sync->IsBlockchainSynced());
CActiveMasternodeManager mn_activeman(*Assert(m_node.connman), *Assert(m_node.dmnman), MakeSecretKey());
TestableCoinJoinServer server(m_node.peerman.get(), *Assert(m_node.chainman), *Assert(m_node.connman),
*Assert(m_node.dmnman), *Assert(m_node.dstxman), *Assert(m_node.mn_metaman),
*Assert(m_node.mempool), mn_activeman, *Assert(m_node.mn_sync),
*Assert(m_node.isman));
// Same setup, but this time the oversized DSSIGNFINALTX comes from the
// session participant itself. It must still be rejected without materializing
// the txin vector and without collapsing the session for everyone else.
auto participant = MakePeer(/*id=*/7, /*ipv4=*/0x0a000001);
server.SeedParticipant(participant->addr);
server.EnterSigningState();
const size_t max_txins{CoinJoin::GetMaxPoolInputOutputCount()};
CDataStream stream{SER_NETWORK, PROTOCOL_VERSION};
WriteCompactSize(stream, max_txins + 1);
BOOST_CHECK_NO_THROW(server.ProcessMessage(*participant, NetMsgType::DSSIGNFINALTX, stream));
BOOST_CHECK_EQUAL(stream.size(), 0U);
BOOST_CHECK_EQUAL(server.GetState(), int{POOL_STATE_SIGNING});
BOOST_CHECK_EQUAL(server.GetEntriesCount(), 1);
// A count beyond the generic CompactSize cap is a malformed message, not a
// CoinJoin-level violation: it throws the standard deserialization error out
// to net processing. No txin is materialized and the session is left intact,
// so honest participants are unaffected.
CDataStream huge_stream{SER_NETWORK, PROTOCOL_VERSION};
WriteCompactSize(huge_stream, uint64_t{MAX_SIZE} + 1);
BOOST_CHECK_THROW(server.ProcessMessage(*participant, NetMsgType::DSSIGNFINALTX, huge_stream),
std::ios_base::failure);
BOOST_CHECK_EQUAL(server.GetState(), int{POOL_STATE_SIGNING});
BOOST_CHECK_EQUAL(server.GetEntriesCount(), 1);
}
//! Re-export the protected static validation helper so it can be called
//! directly, without standing up a CCoinJoinServer.
struct InOutsChecker : CCoinJoinBaseSession
{
using CCoinJoinBaseSession::IsValidInOuts;
};
BOOST_AUTO_TEST_CASE(validation_uses_session_denom_snapshot)
{
Chainstate& chainstate{Assert(m_node.chainman)->ActiveChainstate()};
const auto& isman{*Assert(m_node.isman)};
const auto& mempool{*Assert(m_node.mempool)};
const int session_denom{CoinJoin::AmountToDenomination(CoinJoin::GetSmallestDenomination())};
const std::vector<CTxIn> vin{CTxIn{COutPoint{uint256::ONE, 0}}};
const std::vector<CTxOut> vout{CTxOut{CoinJoin::GetSmallestDenomination(), P2PKHScript()}};
PoolMessage message{MSG_NOERR};
bool consume_collateral{false};
// Outputs matching the captured denomination pass the denom check and fail
// only later on the unknown input.
BOOST_CHECK(!InOutsChecker::IsValidInOuts(chainstate, isman, mempool, vin, vout, session_denom,
/*fAllowRebalanceShapes=*/false, message, &consume_collateral));
BOOST_CHECK_EQUAL(message, ERR_MISSING_TX);
BOOST_CHECK(!consume_collateral);
// A mismatched captured denomination is rejected up front and flags the
// entry's collateral for consumption.
const int other_denom{CoinJoin::AmountToDenomination(CoinJoin::GetStandardDenominations().front())};
BOOST_REQUIRE(other_denom != session_denom);
BOOST_CHECK(!InOutsChecker::IsValidInOuts(chainstate, isman, mempool, vin, vout, other_denom,
/*fAllowRebalanceShapes=*/false, message, &consume_collateral));
BOOST_CHECK_EQUAL(message, ERR_DENOM);
BOOST_CHECK(consume_collateral);
}
BOOST_AUTO_TEST_CASE(server_addentry_binds_entries_to_accepted_collaterals)
{
CActiveMasternodeManager mn_activeman(*Assert(m_node.connman), *Assert(m_node.dmnman), MakeSecretKey());
TestableCoinJoinServer server(m_node.peerman.get(), *Assert(m_node.chainman), *Assert(m_node.connman),
*Assert(m_node.dmnman), *Assert(m_node.dstxman), *Assert(m_node.mn_metaman),
*Assert(m_node.mempool), mn_activeman, *Assert(m_node.mn_sync),
*Assert(m_node.isman));
auto make_collateral = [](uint8_t tag) {
CMutableTransaction tx;
tx.vin.emplace_back(COutPoint(uint256::ONE, tag));
tx.vout.emplace_back(COIN / 10, P2PKHScript(tag));
return tx;
};
// Distinct mixing inputs per entry so none of the checks below trip the duplicate-txin path.
auto make_entry = [](const CMutableTransaction& txCollateral, uint8_t tag) {
std::vector<CTxDSIn> dsins{CTxDSIn(CTxIn(COutPoint(uint256S("aa"), tag)), P2PKHScript(tag), /*nRounds=*/0)};
std::vector<CTxOut> outs{CTxOut(COIN / 1000 + 1, P2PKHScript(tag))};
return CCoinJoinEntry(dsins, outs, CTransaction(txCollateral));
};
const CMutableTransaction collateral_a = make_collateral(1);
const CMutableTransaction collateral_b = make_collateral(2);
const CMutableTransaction collateral_unadmitted = make_collateral(3);
server.SeedSessionCollateral(collateral_a, CoinJoin::MixShape::STANDARD);
server.SeedSessionCollateral(collateral_b, CoinJoin::MixShape::STANDARD);
server.EnterAcceptingEntriesState();
// A collateral that never went through dsa acceptance cannot submit an entry, even
// though the session still has free slots.
PoolMessage msg{MSG_NOERR};
BOOST_CHECK(!server.AddEntry(make_entry(collateral_unadmitted, 0x10), msg));
BOOST_CHECK_EQUAL(msg, ERR_SESSION);
BOOST_CHECK_EQUAL(server.GetEntriesCount(), 0);
// An accepted collateral covers exactly one entry: a second entry reusing the
// collateral of an existing entry is rejected.
server.SeedEntry(make_entry(collateral_a, 0x11));
msg = MSG_NOERR;
BOOST_CHECK(!server.AddEntry(make_entry(collateral_a, 0x12), msg));
BOOST_CHECK_EQUAL(msg, ERR_ALREADY_HAVE);
BOOST_CHECK_EQUAL(server.GetEntriesCount(), 1);
// An accepted, unused collateral passes both checks and proceeds to collateral
// validation (which fails here because the fake collateral has no UTXO backing).
msg = MSG_NOERR;
BOOST_CHECK(!server.AddEntry(make_entry(collateral_b, 0x13), msg));
BOOST_CHECK_EQUAL(msg, ERR_INVALID_COLLATERAL);
BOOST_CHECK_EQUAL(server.GetEntriesCount(), 1);
}
BOOST_AUTO_TEST_CASE(server_addentry_rejects_entries_once_the_session_finalized)
{
CActiveMasternodeManager mn_activeman(*Assert(m_node.connman), *Assert(m_node.dmnman), MakeSecretKey());
TestableCoinJoinServer server(m_node.peerman.get(), *Assert(m_node.chainman), *Assert(m_node.connman),
*Assert(m_node.dmnman), *Assert(m_node.dstxman), *Assert(m_node.mn_metaman),
*Assert(m_node.mempool), mn_activeman, *Assert(m_node.mn_sync),
*Assert(m_node.isman));
CMutableTransaction txCollateral;
txCollateral.vin.emplace_back(COutPoint(uint256::ONE, 1));
txCollateral.vout.emplace_back(COIN / 10, P2PKHScript(1));
std::vector<CTxDSIn> dsins{CTxDSIn(CTxIn(COutPoint(uint256S("aa"), 1)), P2PKHScript(1), /*nRounds=*/0)};
std::vector<CTxOut> outs{CTxOut(COIN / 1000 + 1, P2PKHScript(1))};
const CCoinJoinEntry entry(dsins, outs, CTransaction(txCollateral));
server.SeedSessionCollateral(txCollateral, CoinJoin::MixShape::STANDARD);
// The scheduler thread can finalize a timed-out session while a straggler's entry is still
// being validated. Its collateral is still committed and it still has no entry, so the
// membership and duplicate checks alone would let it in - after the final transaction was
// already built without it, leaving inputs nobody can sign.
server.EnterSigningState();
PoolMessage msg{MSG_NOERR};
BOOST_CHECK(!server.AddEntry(entry, msg));
BOOST_CHECK_EQUAL(msg, ERR_SESSION);
BOOST_CHECK_EQUAL(server.GetEntriesCount(), 0);
}
BOOST_AUTO_TEST_CASE(server_finalization_rechecks_live_side_coverage)
{
CActiveMasternodeManager mn_activeman(*Assert(m_node.connman), *Assert(m_node.dmnman), MakeSecretKey());
TestableCoinJoinServer server(m_node.peerman.get(), *Assert(m_node.chainman), *Assert(m_node.connman),
*Assert(m_node.dmnman), *Assert(m_node.dstxman), *Assert(m_node.mn_metaman),
*Assert(m_node.mempool), mn_activeman, *Assert(m_node.mn_sync),
*Assert(m_node.isman));
const auto make_entry = [](CoinJoin::MixShape shape, uint32_t tag) {
const size_t input_count{shape == CoinJoin::MixShape::PROMOTION ? size_t{CoinJoin::PROMOTION_RATIO} : 1};
const size_t output_count{shape == CoinJoin::MixShape::DEMOTION ? size_t{CoinJoin::PROMOTION_RATIO} : 1};
std::vector<CTxDSIn> inputs;
std::vector<CTxOut> outputs;
for (size_t i{0}; i < input_count; ++i) {
inputs.emplace_back(CTxIn{COutPoint{uint256::ONE, tag + static_cast<uint32_t>(i)}}, P2PKHScript(), 0);
}
for (size_t i{0}; i < output_count; ++i) {
outputs.emplace_back(CoinJoin::GetSmallestDenomination(), P2PKHScript(static_cast<uint8_t>(tag + i)));
}
return CCoinJoinEntry{inputs, outputs, CTransaction{CMutableTransaction{}}};
};
server.SeedEntry(make_entry(CoinJoin::MixShape::DEMOTION, 0));
server.SeedEntry(make_entry(CoinJoin::MixShape::DEMOTION, 10));
server.SeedEntry(make_entry(CoinJoin::MixShape::DEMOTION, 20));
server.SeedEntry(make_entry(CoinJoin::MixShape::PROMOTION, 30));
server.EnterAcceptingEntriesState();
// A timeout snapshot could have observed only the three demotions as covered (0/3), then
// this first promotion could commit while ChargeFees() ran. Finalization must use the live
// 1/3 side counts and refuse to build the uncovered transaction, staying out of
// POOL_STATE_SIGNING; the still-timed-out session is then reset by the scheduler's
// regular CheckTimeout() pass instead of leaking a lone promoter on-chain.
server.CreateFinalTransaction(/*session_id=*/1);
BOOST_CHECK_EQUAL(server.GetState(), int{POOL_STATE_ACCEPTING_ENTRIES});
BOOST_CHECK_EQUAL(server.GetEntriesCount(), 4);
}
BOOST_AUTO_TEST_CASE(entry_deserializes_vectors_through_wire_cap)
{
const size_t wire_cap{CoinJoin::GetMaxPoolInputOutputCount()};
BOOST_REQUIRE_GT(wire_cap, COINJOIN_ENTRY_MAX_SIZE);
for (const size_t count : {size_t{0}, COINJOIN_ENTRY_MAX_SIZE, COINJOIN_ENTRY_MAX_SIZE + 1, wire_cap}) {
BOOST_TEST_CONTEXT("count=" << count)
{
CCoinJoinEntry entry;
entry.vecTxDSIn.resize(count);
entry.vecTxOut.resize(count);
CDataStream stream{SER_NETWORK, PROTOCOL_VERSION};
stream << entry;
CCoinJoinEntry roundtripped;
BOOST_CHECK_NO_THROW(stream >> roundtripped);
BOOST_CHECK_EQUAL(roundtripped.vecTxDSIn.size(), count);
BOOST_CHECK_EQUAL(roundtripped.vecTxOut.size(), count);
}
}
}
BOOST_AUTO_TEST_CASE(entry_rejects_inputs_above_wire_cap_before_materializing)
{
const size_t wire_cap{CoinJoin::GetMaxPoolInputOutputCount()};
CDataStream stream{SER_NETWORK, PROTOCOL_VERSION};
WriteCompactSize(stream, wire_cap + 1);
CCoinJoinEntry entry;
BOOST_CHECK_THROW(stream >> entry, std::ios_base::failure);
BOOST_CHECK(entry.vecTxDSIn.empty());
}
BOOST_AUTO_TEST_CASE(entry_rejects_outputs_above_wire_cap_before_materializing)
{
const size_t wire_cap{CoinJoin::GetMaxPoolInputOutputCount()};
CDataStream stream{SER_NETWORK, PROTOCOL_VERSION};
WriteCompactSize(stream, 0);
stream << MakeTransactionRef(CMutableTransaction{});
WriteCompactSize(stream, wire_cap + 1);
CCoinJoinEntry entry;
BOOST_CHECK_THROW(stream >> entry, std::ios_base::failure);
BOOST_CHECK(entry.vecTxOut.empty());
}
BOOST_AUTO_TEST_CASE(queue_timeout_bounds)
{
const auto now{std::chrono::time_point_cast<std::chrono::seconds>(GetAdjustedTime())};
CCoinJoinQueue dsq{CoinJoin::AmountToDenomination(CoinJoin::GetSmallestDenomination()),
COutPoint{}, uint256::ONE, now, /*fReady=*/false};
// current time -> not out of bounds
BOOST_CHECK(!dsq.IsTimeOutOfBounds());
// Too old (beyond COINJOIN_QUEUE_TIMEOUT)
SetMockTime((now + std::chrono::seconds{COINJOIN_QUEUE_TIMEOUT + 1}).time_since_epoch());
BOOST_CHECK(dsq.IsTimeOutOfBounds());
// Too far in the future
SetMockTime((now - std::chrono::seconds{COINJOIN_QUEUE_TIMEOUT + 1}).time_since_epoch());
dsq.nTime = TicksSinceEpoch<std::chrono::seconds>(now + std::chrono::seconds{COINJOIN_QUEUE_TIMEOUT + 1});
BOOST_CHECK(dsq.IsTimeOutOfBounds());
// Reset mock time
SetMockTime(0s);
}
BOOST_AUTO_TEST_CASE(broadcasttx_expiry_height_logic)
{
// Build a valid-looking CCoinJoinBroadcastTx with confirmed height
CCoinJoinBroadcastTx dstx;
{
CMutableTransaction mtx;
const int participants = std::max(3, CoinJoin::GetMinPoolParticipants());
for (int i = 0; i < participants; ++i) {
mtx.vin.emplace_back(COutPoint(uint256::TWO, i));
mtx.vout.emplace_back(CoinJoin::GetSmallestDenomination(), P2PKHScript(static_cast<uint8_t>(i)));
}
dstx.tx = MakeTransactionRef(mtx);
dstx.m_protxHash = uint256::ONE;
// mark as confirmed at height 100
dstx.SetConfirmedHeight(100);
}
// Minimal CBlockIndex with required fields
// Create a minimal block index to satisfy the interface
CBlockIndex index;
uint256 blk_hash = uint256S("03");
index.nHeight = 125; // 125 - 100 == 25 > 24 → expired by height
index.phashBlock = &blk_hash;
BOOST_CHECK(dstx.IsExpired(&index, *Assert(m_node.chainlocks)));
}
// Helper to create a denominated CTxIn with a specific denomination value
static CTxIn MakeDenomInput(uint8_t index)
{
CTxIn in;
in.prevout = COutPoint(uint256::ONE, index);
return in;
}
// Helper to create a denominated CTxOut
static CTxOut MakeDenomOutput(CAmount nAmount, uint8_t tag = 0x01)
{
return CTxOut{nAmount, P2PKHScript(tag)};
}
BOOST_AUTO_TEST_CASE(validate_promotion_entry_valid)
{
// Valid promotion: 10 inputs of 0.1 DASH → 1 output of 1.0 DASH
std::vector<CTxIn> vecTxIn;
std::vector<CTxOut> vecTxOut;
// Get the 0.1 DASH denomination (index 2: 1 << 2 = 4)
const int nSmallerDenom = 1 << 2; // 0.1 DASH
const int nLargerDenom = 1 << 1; // 1.0 DASH
const CAmount nLargerAmount = CoinJoin::DenominationToAmount(nLargerDenom);
BOOST_CHECK(CoinJoin::IsValidDenomination(nSmallerDenom));
BOOST_CHECK(CoinJoin::IsValidDenomination(nLargerDenom));
// Create 10 inputs of smaller denomination
for (int i = 0; i < CoinJoin::PROMOTION_RATIO; ++i) {
vecTxIn.push_back(MakeDenomInput(static_cast<uint8_t>(i)));
}
// Create 1 output of larger denomination
vecTxOut.push_back(MakeDenomOutput(nLargerAmount, 0x01));
PoolMessage nMessageID = MSG_NOERR;
BOOST_CHECK(CoinJoin::ValidatePromotionEntry(vecTxIn, vecTxOut, nSmallerDenom, nMessageID));
}
BOOST_AUTO_TEST_CASE(validate_promotion_entry_wrong_input_count)
{
// Invalid: only 9 inputs instead of 10
std::vector<CTxIn> vecTxIn;
std::vector<CTxOut> vecTxOut;
const int nSmallerDenom = 1 << 2; // 0.1 DASH
const int nLargerDenom = 1 << 1; // 1.0 DASH
const CAmount nLargerAmount = CoinJoin::DenominationToAmount(nLargerDenom);
// Create only 9 inputs
for (int i = 0; i < CoinJoin::PROMOTION_RATIO - 1; ++i) {
vecTxIn.push_back(MakeDenomInput(static_cast<uint8_t>(i)));
}
vecTxOut.push_back(MakeDenomOutput(nLargerAmount, 0x01));
PoolMessage nMessageID = MSG_NOERR;
BOOST_CHECK(!CoinJoin::ValidatePromotionEntry(vecTxIn, vecTxOut, nSmallerDenom, nMessageID));
}
BOOST_AUTO_TEST_CASE(validate_promotion_entry_wrong_output_count)
{
// Invalid: 2 outputs instead of 1
std::vector<CTxIn> vecTxIn;
std::vector<CTxOut> vecTxOut;
const int nSmallerDenom = 1 << 2;
const int nLargerDenom = 1 << 1;
const CAmount nLargerAmount = CoinJoin::DenominationToAmount(nLargerDenom);
for (int i = 0; i < CoinJoin::PROMOTION_RATIO; ++i) {
vecTxIn.push_back(MakeDenomInput(static_cast<uint8_t>(i)));
}
// Two outputs instead of one
vecTxOut.push_back(MakeDenomOutput(nLargerAmount, 0x01));
vecTxOut.push_back(MakeDenomOutput(nLargerAmount, 0x02));
PoolMessage nMessageID = MSG_NOERR;
BOOST_CHECK(!CoinJoin::ValidatePromotionEntry(vecTxIn, vecTxOut, nSmallerDenom, nMessageID));
}
BOOST_AUTO_TEST_CASE(validate_promotion_entry_non_adjacent_denoms)
{
// Invalid: trying to promote 0.01 to 1.0 (not adjacent)
std::vector<CTxIn> vecTxIn;
std::vector<CTxOut> vecTxOut;
const int nSmallerDenom = 1 << 3; // 0.01 DASH
const int nLargerDenom = 1 << 1; // 1.0 DASH (not adjacent to 0.01)
const CAmount nLargerAmount = CoinJoin::DenominationToAmount(nLargerDenom);
for (int i = 0; i < CoinJoin::PROMOTION_RATIO; ++i) {
vecTxIn.push_back(MakeDenomInput(static_cast<uint8_t>(i)));
}
vecTxOut.push_back(MakeDenomOutput(nLargerAmount, 0x01));
PoolMessage nMessageID = MSG_NOERR;
BOOST_CHECK(!CoinJoin::ValidatePromotionEntry(vecTxIn, vecTxOut, nSmallerDenom, nMessageID));
}
BOOST_AUTO_TEST_CASE(validate_demotion_entry_valid)
{
// Valid demotion: 1 input of 1.0 DASH → 10 outputs of 0.1 DASH
std::vector<CTxIn> vecTxIn;
std::vector<CTxOut> vecTxOut;
const int nSmallerDenom = 1 << 2; // 0.1 DASH
const CAmount nSmallerAmount = CoinJoin::DenominationToAmount(nSmallerDenom);
const int nLargerDenom = 1 << 1; // 1.0 DASH
BOOST_CHECK(CoinJoin::IsValidDenomination(nSmallerDenom));
BOOST_CHECK(CoinJoin::IsValidDenomination(nLargerDenom));
BOOST_CHECK(CoinJoin::AreAdjacentDenominations(nSmallerDenom, nLargerDenom));
// 1 input of larger denomination
vecTxIn.push_back(MakeDenomInput(0));
// 10 outputs of smaller denomination
for (int i = 0; i < CoinJoin::PROMOTION_RATIO; ++i) {
vecTxOut.push_back(MakeDenomOutput(nSmallerAmount, static_cast<uint8_t>(i)));
}
PoolMessage nMessageID = MSG_NOERR;
BOOST_CHECK(CoinJoin::ValidateDemotionEntry(vecTxIn, vecTxOut, nSmallerDenom, nMessageID));
}
BOOST_AUTO_TEST_CASE(validate_demotion_entry_wrong_input_count)
{
// Invalid: 2 inputs instead of 1
std::vector<CTxIn> vecTxIn;
std::vector<CTxOut> vecTxOut;
const int nSmallerDenom = 1 << 2;
const CAmount nSmallerAmount = CoinJoin::DenominationToAmount(nSmallerDenom);
// 2 inputs instead of 1
vecTxIn.push_back(MakeDenomInput(0));
vecTxIn.push_back(MakeDenomInput(1));
for (int i = 0; i < CoinJoin::PROMOTION_RATIO; ++i) {
vecTxOut.push_back(MakeDenomOutput(nSmallerAmount, static_cast<uint8_t>(i)));
}
PoolMessage nMessageID = MSG_NOERR;
BOOST_CHECK(!CoinJoin::ValidateDemotionEntry(vecTxIn, vecTxOut, nSmallerDenom, nMessageID));
}
BOOST_AUTO_TEST_CASE(validate_demotion_entry_wrong_output_count)
{
// Invalid: 9 outputs instead of 10
std::vector<CTxIn> vecTxIn;
std::vector<CTxOut> vecTxOut;
const int nSmallerDenom = 1 << 2;
const CAmount nSmallerAmount = CoinJoin::DenominationToAmount(nSmallerDenom);
vecTxIn.push_back(MakeDenomInput(0));
// Only 9 outputs
for (int i = 0; i < CoinJoin::PROMOTION_RATIO - 1; ++i) {
vecTxOut.push_back(MakeDenomOutput(nSmallerAmount, static_cast<uint8_t>(i)));
}
PoolMessage nMessageID = MSG_NOERR;
BOOST_CHECK(!CoinJoin::ValidateDemotionEntry(vecTxIn, vecTxOut, nSmallerDenom, nMessageID));
}
BOOST_AUTO_TEST_CASE(denomination_adjacency_checks)
{
// Test AreAdjacentDenominations function
// Denomination indices: 0=10.0, 1=1.0, 2=0.1, 3=0.01, 4=0.001
// Adjacent pairs should return true
BOOST_CHECK(CoinJoin::AreAdjacentDenominations(1 << 0, 1 << 1)); // 10.0 and 1.0
BOOST_CHECK(CoinJoin::AreAdjacentDenominations(1 << 1, 1 << 2)); // 1.0 and 0.1
BOOST_CHECK(CoinJoin::AreAdjacentDenominations(1 << 2, 1 << 3)); // 0.1 and 0.01
BOOST_CHECK(CoinJoin::AreAdjacentDenominations(1 << 3, 1 << 4)); // 0.01 and 0.001
// Non-adjacent pairs should return false
BOOST_CHECK(!CoinJoin::AreAdjacentDenominations(1 << 0, 1 << 2)); // 10.0 and 0.1 (skip 1.0)
BOOST_CHECK(!CoinJoin::AreAdjacentDenominations(1 << 1, 1 << 3)); // 1.0 and 0.01 (skip 0.1)
BOOST_CHECK(!CoinJoin::AreAdjacentDenominations(1 << 0, 1 << 4)); // 10.0 and 0.001
// Same denomination is not adjacent to itself
BOOST_CHECK(!CoinJoin::AreAdjacentDenominations(1 << 2, 1 << 2));
// Invalid denominations
BOOST_CHECK(!CoinJoin::AreAdjacentDenominations(0, 1 << 1));
BOOST_CHECK(!CoinJoin::AreAdjacentDenominations(1 << 1, 0));
BOOST_CHECK(!CoinJoin::AreAdjacentDenominations(999, 1 << 1));
}
BOOST_AUTO_TEST_CASE(get_adjacent_denomination_helpers)
{
// Test GetLargerAdjacentDenom and GetSmallerAdjacentDenom
// Indices: 0=10.0, 1=1.0, 2=0.1, 3=0.01, 4=0.001
// GetLargerAdjacentDenom
BOOST_CHECK_EQUAL(CoinJoin::GetLargerAdjacentDenom(1 << 1), 1 << 0); // 1.0 → 10.0
BOOST_CHECK_EQUAL(CoinJoin::GetLargerAdjacentDenom(1 << 2), 1 << 1); // 0.1 → 1.0
BOOST_CHECK_EQUAL(CoinJoin::GetLargerAdjacentDenom(1 << 3), 1 << 2); // 0.01 → 0.1
BOOST_CHECK_EQUAL(CoinJoin::GetLargerAdjacentDenom(1 << 4), 1 << 3); // 0.001 → 0.01
BOOST_CHECK_EQUAL(CoinJoin::GetLargerAdjacentDenom(1 << 0), 0); // 10.0 has no larger
BOOST_CHECK_EQUAL(CoinJoin::GetLargerAdjacentDenom(0), 0); // Invalid denominations
BOOST_CHECK_EQUAL(CoinJoin::GetLargerAdjacentDenom(999), 0); // Invalid denominations
// GetSmallerAdjacentDenom
BOOST_CHECK_EQUAL(CoinJoin::GetSmallerAdjacentDenom(1 << 0), 1 << 1); // 10.0 → 1.0
BOOST_CHECK_EQUAL(CoinJoin::GetSmallerAdjacentDenom(1 << 1), 1 << 2); // 1.0 → 0.1
BOOST_CHECK_EQUAL(CoinJoin::GetSmallerAdjacentDenom(1 << 2), 1 << 3); // 0.1 → 0.01
BOOST_CHECK_EQUAL(CoinJoin::GetSmallerAdjacentDenom(1 << 3), 1 << 4); // 0.01 → 0.001
BOOST_CHECK_EQUAL(CoinJoin::GetSmallerAdjacentDenom(1 << 4), 0); // 0.001 has no smaller
BOOST_CHECK_EQUAL(CoinJoin::GetSmallerAdjacentDenom(0), 0); // Invalid denominations
BOOST_CHECK_EQUAL(CoinJoin::GetSmallerAdjacentDenom(999), 0); // Invalid denominations
}
BOOST_AUTO_TEST_CASE(isvalidstructure_postfork_unbalanced_valid)
{
// Post-V24: Unbalanced vin/vout (promotion: 10 inputs, 1 output) should be valid
// We need a mock pindex that signals V24 active - for this test we use nullptr which means pre-fork
// This test validates that the structure check correctly identifies promotion structure
CCoinJoinBroadcastTx promo;
{
CMutableTransaction mtx;
// Promotion: 10 inputs of smaller denom -> 1 output of larger denom
const int nInputCount = CoinJoin::PROMOTION_RATIO;
const CAmount nLargerAmount = CoinJoin::DenominationToAmount(1 << 1); // 1.0 DASH
for (int i = 0; i < nInputCount; ++i) {
CTxIn in;
in.prevout = COutPoint(uint256::ONE, static_cast<uint32_t>(i));
mtx.vin.push_back(in);
}
// 1 output of larger denom
CTxOut out{nLargerAmount, P2PKHScript(0x01)};
mtx.vout.push_back(out);
promo.tx = MakeTransactionRef(mtx);
promo.m_protxHash = uint256::ONE;
}
// Pre-V24 (nullptr): unbalanced should fail, but be reported as possibly valid post-V24
// so relaying peers aren't fully punished around the activation boundary
bool fPossiblyValidPostV24{false};
BOOST_CHECK(!promo.IsValidStructure(nullptr, *Assert(m_node.chainman), &fPossiblyValidPostV24));
BOOST_CHECK(fPossiblyValidPostV24);
// Note: Post-V24 test would require a valid CBlockIndex with V24 deployment active
// which requires more setup. The above confirms pre-fork rejection works.
}
BOOST_AUTO_TEST_CASE(isvalidstructure_demotion_structure)
{
// Demotion: 1 input of larger denom -> 10 outputs of smaller denom
CCoinJoinBroadcastTx demo;
{
CMutableTransaction mtx;
const CAmount nSmallerAmount = CoinJoin::DenominationToAmount(1 << 2); // 0.1 DASH
// 1 input
CTxIn in;
in.prevout = COutPoint(uint256::ONE, 0);
mtx.vin.push_back(in);
// 10 outputs of smaller denom
for (int i = 0; i < CoinJoin::PROMOTION_RATIO; ++i) {
CTxOut out{nSmallerAmount, P2PKHScript(static_cast<uint8_t>(i))};
mtx.vout.push_back(out);
}
demo.tx = MakeTransactionRef(mtx);
demo.m_protxHash = uint256::ONE;
}
// Pre-V24 (nullptr): unbalanced should fail. A single-entry demotion DSTX has just 1
// input - below GetMinPoolParticipants() under either ruleset - so it must not be
// reported as possibly valid post-V24 either
bool fPossiblyValidPostV24{true};
BOOST_CHECK(!demo.IsValidStructure(nullptr, *Assert(m_node.chainman), &fPossiblyValidPostV24));
BOOST_CHECK(!fPossiblyValidPostV24);
// An unbalanced tx that is garbage under post-V24 rules too (non-denominated output)
// must not be reported as possibly valid
CCoinJoinBroadcastTx garbage;
{
CMutableTransaction mtx;
for (int i = 0; i < CoinJoin::PROMOTION_RATIO; ++i) {
CTxIn in;
in.prevout = COutPoint(uint256::ONE, static_cast<uint32_t>(i));
mtx.vin.push_back(in);
}
CTxOut out{1234567, P2PKHScript(0x01)}; // not a denomination
mtx.vout.push_back(out);
garbage.tx = MakeTransactionRef(mtx);
garbage.m_protxHash = uint256::ONE;
}
fPossiblyValidPostV24 = true;
BOOST_CHECK(!garbage.IsValidStructure(nullptr, *Assert(m_node.chainman), &fPossiblyValidPostV24));
BOOST_CHECK(!fPossiblyValidPostV24);
}
BOOST_AUTO_TEST_CASE(input_limit_prefork)
{
// Pre-V24: max inputs = GetMaxPoolParticipants() * COINJOIN_ENTRY_MAX_SIZE
// Typically 20 * 9 = 180
const size_t nMaxPreFork = CoinJoin::GetMaxPoolParticipants() * COINJOIN_ENTRY_MAX_SIZE;
BOOST_CHECK_EQUAL(nMaxPreFork, 180);
// Transaction with exactly max inputs should be valid
CCoinJoinBroadcastTx maxValid;
{
CMutableTransaction mtx;
for (size_t i = 0; i < nMaxPreFork; ++i) {
CTxIn in;
in.prevout = COutPoint(uint256::ONE, static_cast<uint32_t>(i));
mtx.vin.push_back(in);
CTxOut out{CoinJoin::GetSmallestDenomination(), P2PKHScript(static_cast<uint8_t>(i % 256))};
mtx.vout.push_back(out);
}
maxValid.tx = MakeTransactionRef(mtx);
maxValid.m_protxHash = uint256::ONE;
}
BOOST_CHECK(maxValid.IsValidStructure(nullptr, *Assert(m_node.chainman)));
// Transaction with max+1 inputs should be invalid
CCoinJoinBroadcastTx tooMany;
{
CMutableTransaction mtx;
for (size_t i = 0; i < nMaxPreFork + 1; ++i) {
CTxIn in;
in.prevout = COutPoint(uint256::ONE, static_cast<uint32_t>(i));
mtx.vin.push_back(in);
CTxOut out{CoinJoin::GetSmallestDenomination(), P2PKHScript(static_cast<uint8_t>(i % 256))};
mtx.vout.push_back(out);
}
tooMany.tx = MakeTransactionRef(mtx);
tooMany.m_protxHash = uint256::ONE;
}
BOOST_CHECK(!tooMany.IsValidStructure(nullptr, *Assert(m_node.chainman)));
}
BOOST_AUTO_TEST_CASE(input_limit_postfork_constants)
{
// Post-V24: max inputs = GetMaxPoolParticipants() * PROMOTION_RATIO
// Typically 20 * 10 = 200
const size_t nMaxPostFork = CoinJoin::GetMaxPoolParticipants() * CoinJoin::PROMOTION_RATIO;
BOOST_CHECK_EQUAL(nMaxPostFork, 200);
// Verify the increase from pre-fork
const size_t nMaxPreFork = CoinJoin::GetMaxPoolParticipants() * COINJOIN_ENTRY_MAX_SIZE;
BOOST_CHECK(nMaxPostFork > nMaxPreFork);
BOOST_CHECK_EQUAL(nMaxPostFork - nMaxPreFork, 20); // Increase of 20
}
BOOST_AUTO_TEST_CASE(output_limit_postfork)
{
// Post-V24 the vin/vout counts no longer bound each other, so outputs get their own cap
// of GetMaxPoolParticipants() * PROMOTION_RATIO. Exercised through the
// fPossiblyValidPostV24 flag: a tx that busts the output cap must not be reported as
// possibly valid under post-V24 rules either.
const size_t nMaxPostFork = CoinJoin::GetMaxPoolParticipants() * CoinJoin::PROMOTION_RATIO;
const CAmount nSmallestDenom = CoinJoin::GetSmallestDenomination();
auto MakeUnbalancedTx = [&](size_t nInputs, size_t nOutputs) {
CCoinJoinBroadcastTx dstx;
CMutableTransaction mtx;
for (size_t i = 0; i < nInputs; ++i) {
CTxIn in;
in.prevout = COutPoint(uint256::ONE, static_cast<uint32_t>(i));
mtx.vin.push_back(in);
}
for (size_t i = 0; i < nOutputs; ++i) {
mtx.vout.push_back(CTxOut{nSmallestDenom, P2PKHScript(static_cast<uint8_t>(i % 256))});
}
dstx.tx = MakeTransactionRef(mtx);
dstx.m_protxHash = uint256::ONE;
return dstx;
};
// Outputs at the cap, inputs the matching count for an all-demotion session: rejected
// pre-V24, possibly valid post-V24
bool fPossiblyValidPostV24{false};
const auto withinCaps = MakeUnbalancedTx(nMaxPostFork / CoinJoin::PROMOTION_RATIO, nMaxPostFork);
BOOST_CHECK(!withinCaps.IsValidStructure(nullptr, *Assert(m_node.chainman), &fPossiblyValidPostV24));
BOOST_CHECK(fPossiblyValidPostV24);
// The same shape scaled past the cap: rejected under either ruleset, and by the cap alone -
// it satisfies the input/output count relation (see isvalidstructure_postv24_count_relations)
fPossiblyValidPostV24 = true;
const auto tooManyOutputs = MakeUnbalancedTx(nMaxPostFork / CoinJoin::PROMOTION_RATIO + 1, nMaxPostFork + 10);
BOOST_CHECK(!tooManyOutputs.IsValidStructure(nullptr, *Assert(m_node.chainman), &fPossiblyValidPostV24));
BOOST_CHECK(!fPossiblyValidPostV24);
}
BOOST_AUTO_TEST_CASE(validate_final_tx_composition)
{
constexpr size_t R = CoinJoin::PROMOTION_RATIO;
// Standard-only session: N inputs, N outputs, no larger-denom in/outs
BOOST_CHECK(CoinJoin::ValidateFinalTxComposition(5, 5, 0, 0));
// 3 standard + 1 promotion: 3 + 10 inputs, 3 + 1 outputs (1 at larger denom)
BOOST_CHECK(CoinJoin::ValidateFinalTxComposition(3 + R, 3 + 1, 0, 1));
// 3 standard + 1 demotion: 3 + 1 inputs (1 at larger denom), 3 + 10 outputs
BOOST_CHECK(CoinJoin::ValidateFinalTxComposition(3 + 1, 3 + R, 1, 0));
// 3 standard + 1 promotion + 1 demotion
BOOST_CHECK(CoinJoin::ValidateFinalTxComposition(3 + R + 1, 3 + 1 + R, 1, 1));
// Promotion-only shape is composable (the side-coverage invariant - each side of the
// session denom occupied by nobody or at least two participants - is enforced by the
// server in IsSessionReady/CheckPool, not by the composition check)
BOOST_CHECK(CoinJoin::ValidateFinalTxComposition(R, 1, 0, 1));
// Not enough session-denom inputs to back the promotion output
BOOST_CHECK(!CoinJoin::ValidateFinalTxComposition(R - 1, 1, 0, 1));
// Not enough session-denom outputs to back the demotion input
BOOST_CHECK(!CoinJoin::ValidateFinalTxComposition(1, R - 1, 1, 0));
// Larger-denom counts exceeding the totals are inconsistent
BOOST_CHECK(!CoinJoin::ValidateFinalTxComposition(5, 5, 6, 0));
BOOST_CHECK(!CoinJoin::ValidateFinalTxComposition(5, 5, 0, 6));
// Two promotions with only one ratio's worth of session inputs
BOOST_CHECK(!CoinJoin::ValidateFinalTxComposition(R, 2, 0, 2));
}
BOOST_AUTO_TEST_CASE(promotion_demotion_value_preservation)
{
// Verify that 10 smaller = 1 larger (value is preserved exactly)
// CoinJoin denominations are designed so that 10 * smaller == larger
// e.g., 10 * (0.1 DASH + 100 sat) = 1.0 DASH + 1000 sat