forked from dashpay/dash
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcoinjoin_tests.cpp
More file actions
643 lines (571 loc) · 30.5 KB
/
Copy pathcoinjoin_tests.cpp
File metadata and controls
643 lines (571 loc) · 30.5 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
// Copyright (c) 2020-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/setup_common.h>
#include <test/util/txmempool.h>
#include <coinjoin/client.h>
#include <coinjoin/coinjoin.h>
#include <coinjoin/walletman.h>
#include <coinjoin/options.h>
#include <coinjoin/util.h>
#include <consensus/amount.h>
#include <interfaces/coinjoin.h>
#include <masternode/sync.h>
#include <node/context.h>
#include <util/system.h>
#include <util/translation.h>
#include <util/time.h>
#include <validation.h>
#include <txmempool.h>
#include <wallet/context.h>
#include <wallet/db.h>
#include <wallet/spend.h>
#include <wallet/wallet.h>
#include <wallet/walletdb.h>
#include <boost/test/unit_test.hpp>
namespace wallet {
BOOST_FIXTURE_TEST_SUITE(coinjoin_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(coinjoin_options_tests)
{
gArgs.ForceSetArg("-enablecoinjoin", "0");
const auto loader{interfaces::MakeCoinJoinLoader(m_node)};
BOOST_CHECK_EQUAL(CCoinJoinClientOptions::GetSessions(), DEFAULT_COINJOIN_SESSIONS);
BOOST_CHECK_EQUAL(CCoinJoinClientOptions::GetRounds(), DEFAULT_COINJOIN_ROUNDS);
BOOST_CHECK_EQUAL(CCoinJoinClientOptions::GetRandomRounds(), COINJOIN_RANDOM_ROUNDS);
BOOST_CHECK_EQUAL(CCoinJoinClientOptions::GetAmount(), DEFAULT_COINJOIN_AMOUNT);
BOOST_CHECK_EQUAL(CCoinJoinClientOptions::GetDenomsGoal(), DEFAULT_COINJOIN_DENOMS_GOAL);
BOOST_CHECK_EQUAL(CCoinJoinClientOptions::GetDenomsHardCap(), DEFAULT_COINJOIN_DENOMS_HARDCAP);
BOOST_CHECK_EQUAL(CCoinJoinClientOptions::IsEnabled(), false);
BOOST_CHECK_EQUAL(CCoinJoinClientOptions::IsMultiSessionEnabled(), DEFAULT_COINJOIN_MULTISESSION);
CCoinJoinClientOptions::SetEnabled(true);
BOOST_CHECK_EQUAL(CCoinJoinClientOptions::IsEnabled(), true);
CCoinJoinClientOptions::SetEnabled(false);
BOOST_CHECK_EQUAL(CCoinJoinClientOptions::IsEnabled(), false);
CCoinJoinClientOptions::SetMultiSessionEnabled(!DEFAULT_COINJOIN_MULTISESSION);
BOOST_CHECK_EQUAL(CCoinJoinClientOptions::IsMultiSessionEnabled(), !DEFAULT_COINJOIN_MULTISESSION);
CCoinJoinClientOptions::SetMultiSessionEnabled(DEFAULT_COINJOIN_MULTISESSION);
BOOST_CHECK_EQUAL(CCoinJoinClientOptions::IsMultiSessionEnabled(), DEFAULT_COINJOIN_MULTISESSION);
CCoinJoinClientOptions::SetRounds(DEFAULT_COINJOIN_ROUNDS + 10);
BOOST_CHECK_EQUAL(CCoinJoinClientOptions::GetRounds(), DEFAULT_COINJOIN_ROUNDS + 10);
CCoinJoinClientOptions::SetAmount(DEFAULT_COINJOIN_AMOUNT + 50);
BOOST_CHECK_EQUAL(CCoinJoinClientOptions::GetAmount(), DEFAULT_COINJOIN_AMOUNT + 50);
}
BOOST_AUTO_TEST_CASE(coinjoin_collateral_tests)
{
// Good collateral values
static_assert(CoinJoin::IsCollateralAmount(0.00010000 * COIN));
static_assert(CoinJoin::IsCollateralAmount(0.00012345 * COIN));
static_assert(CoinJoin::IsCollateralAmount(0.00032123 * COIN));
static_assert(CoinJoin::IsCollateralAmount(0.00019000 * COIN));
// Bad collateral values
static_assert(!CoinJoin::IsCollateralAmount(0.00009999 * COIN));
static_assert(!CoinJoin::IsCollateralAmount(0.00040001 * COIN));
static_assert(!CoinJoin::IsCollateralAmount(0.00100000 * COIN));
static_assert(!CoinJoin::IsCollateralAmount(0.00100001 * COIN));
}
BOOST_AUTO_TEST_CASE(coinjoin_pending_dsa_request_tests)
{
CPendingDsaRequest dsa_request;
BOOST_CHECK(dsa_request.GetProTxHash() == uint256());
BOOST_CHECK(dsa_request.GetDSA() == CCoinJoinAccept());
BOOST_CHECK_EQUAL(dsa_request.IsExpired(), true);
CPendingDsaRequest dsa_request_2;
BOOST_CHECK(dsa_request == dsa_request_2);
CCoinJoinAccept cja;
cja.nDenom = 4;
uint256 proTxHash{uint256::ONE};
CPendingDsaRequest custom_request(proTxHash, cja);
BOOST_CHECK(custom_request.GetProTxHash() == proTxHash);
BOOST_CHECK(custom_request.GetDSA() == cja);
BOOST_CHECK_EQUAL(custom_request.IsExpired(), false);
SetMockTime(GetTime() + 15);
BOOST_CHECK_EQUAL(custom_request.IsExpired(), false);
SetMockTime(GetTime() + 1);
BOOST_CHECK_EQUAL(custom_request.IsExpired(), true);
BOOST_CHECK(dsa_request != custom_request);
BOOST_CHECK(!(dsa_request == custom_request));
BOOST_CHECK(!dsa_request);
BOOST_CHECK(custom_request);
}
BOOST_AUTO_TEST_CASE(coinjoin_dstxin_tests)
{
CTxDSIn txin;
BOOST_CHECK(txin.prevPubKey == CScript());
BOOST_CHECK_EQUAL(txin.fHasSig, false);
BOOST_CHECK_EQUAL(txin.nRounds, -10);
CTxDSIn custom_txin(txin, CScript(4), -9);
BOOST_CHECK(custom_txin.prevPubKey == CScript(4));
BOOST_CHECK_EQUAL(custom_txin.fHasSig, false);
BOOST_CHECK_EQUAL(custom_txin.nRounds, -9);
}
BOOST_AUTO_TEST_CASE(coinjoin_status_update_tests)
{
CCoinJoinStatusUpdate cjsu;
BOOST_CHECK_EQUAL(cjsu.nSessionID, 0);
BOOST_CHECK_EQUAL(cjsu.nState, POOL_STATE_IDLE);
BOOST_CHECK_EQUAL(cjsu.nEntriesCount, 0);
BOOST_CHECK_EQUAL(cjsu.nStatusUpdate, STATUS_ACCEPTED);
BOOST_CHECK_EQUAL(cjsu.nMessageID, MSG_NOERR);
CCoinJoinStatusUpdate custom_cjsu(1, POOL_STATE_QUEUE, 1, STATUS_REJECTED, ERR_QUEUE_FULL);
BOOST_CHECK_EQUAL(custom_cjsu.nSessionID, 1);
BOOST_CHECK_EQUAL(custom_cjsu.nState, POOL_STATE_QUEUE);
BOOST_CHECK_EQUAL(custom_cjsu.nEntriesCount, 1);
BOOST_CHECK_EQUAL(custom_cjsu.nStatusUpdate, STATUS_REJECTED);
BOOST_CHECK_EQUAL(custom_cjsu.nMessageID, ERR_QUEUE_FULL);
}
BOOST_AUTO_TEST_CASE(coinjoin_accept_tests)
{
CCoinJoinAccept cja;
BOOST_CHECK_EQUAL(cja.nDenom, 0);
BOOST_CHECK_EQUAL(cja.txCollateral.GetHash(), CMutableTransaction().GetHash());
// CMutableTransaction custom_cmt()
}
class CTransactionBuilderTestSetup : public TestChain100Setup
{
public:
CTransactionBuilderTestSetup() :
wallet{std::make_unique<CWallet>(m_node.chain.get(), m_node.coinjoin_loader.get(), "", m_args, CreateMockWalletDatabase())}
{
context.args = &m_args;
context.chain = m_node.chain.get();
context.coinjoin_loader = m_node.coinjoin_loader.get();
CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
wallet->SetupLegacyScriptPubKeyMan();
wallet->LoadWallet();
AddWallet(context, wallet);
{
LOCK2(wallet->cs_wallet, ::cs_main);
wallet->GetLegacyScriptPubKeyMan()->AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
wallet->SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
}
WalletRescanReserver reserver(*wallet);
reserver.reserve();
CWallet::ScanResult result = wallet->ScanForWalletTransactions(/*start_block=*/wallet->chain().getBlockHash(0),
/*start_height=*/0, /*max_height=*/{}, reserver,
/*fUpdate=*/true, /*save_progress=*/false);
BOOST_CHECK_EQUAL(result.status, CWallet::ScanResult::SUCCESS);
}
~CTransactionBuilderTestSetup()
{
RemoveWallet(context, wallet, /*load_on_start=*/std::nullopt);
}
WalletContext context;
const std::shared_ptr<CWallet> wallet;
CWalletTx& AddTxToChain(uint256 nTxHash)
{
decltype(wallet->mapWallet)::iterator it;
CMutableTransaction blocktx;
{
LOCK(wallet->cs_wallet);
it = wallet->mapWallet.find(nTxHash);
BOOST_REQUIRE(it != wallet->mapWallet.end());
blocktx = CMutableTransaction(*it->second.tx);
}
CreateAndProcessBlock({blocktx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
LOCK2(wallet->cs_wallet, ::cs_main);
wallet->SetLastBlockProcessed(m_node.chainman->ActiveChain().Height(), m_node.chainman->ActiveChain().Tip()->GetBlockHash());
it->second.m_state = TxStateConfirmed{m_node.chainman->ActiveChain().Tip()->GetBlockHash(), m_node.chainman->ActiveChain().Height(), /*index=*/1};
return it->second;
}
CompactTallyItem GetTallyItem(const std::vector<CAmount>& vecAmounts)
{
CompactTallyItem tallyItem;
ReserveDestination reserveDest(wallet.get());
int nChangePosRet{RANDOM_CHANGE_POSITION};
CCoinControl coinControl;
coinControl.m_feerate = CFeeRate(1000);
{
LOCK(wallet->cs_wallet);
auto dest_opt = reserveDest.GetReservedDestination(false);
BOOST_REQUIRE(dest_opt);
tallyItem.txdest = *dest_opt;
}
for (CAmount nAmount : vecAmounts) {
CTransactionRef tx;
{
auto res = CreateTransaction(*wallet, {{GetScriptForDestination(tallyItem.txdest), nAmount, false}}, nChangePosRet, coinControl);
// Report why it failed, a bare "critical check res has failed" says nothing
BOOST_REQUIRE_MESSAGE(res, strprintf("CreateTransaction(%d) failed: %s", nAmount,
util::ErrorString(res).original));
tx = res->tx;
nChangePosRet = res->change_pos;
}
{
LOCK2(wallet->cs_wallet, ::cs_main);
wallet->CommitTransaction(tx, {}, {});
}
AddTxToChain(tx->GetHash());
for (uint32_t n = 0; n < tx->vout.size(); ++n) {
if (nChangePosRet != RANDOM_CHANGE_POSITION && int(n) == nChangePosRet) {
// Skip the change output to only return the requested coins
continue;
}
tallyItem.outpoints.emplace_back(COutPoint{tx->GetHash(), n});
tallyItem.nAmount += tx->vout[n].nValue;
}
}
BOOST_REQUIRE_EQUAL(tallyItem.outpoints.size(), vecAmounts.size());
reserveDest.KeepDestination();
return tallyItem;
}
};
BOOST_FIXTURE_TEST_CASE(coinjoin_pending_observation_tests, CTransactionBuilderTestSetup)
{
// 0.100001 DASH, a valid CoinJoin denomination
constexpr CAmount nDenomAmount{10000100};
BOOST_REQUIRE(CoinJoin::IsDenominatedAmount(nDenomAmount));
CompactTallyItem tallyItem = GetTallyItem({nDenomAmount, nDenomAmount, nDenomAmount, nDenomAmount});
const COutPoint outpointUserLocked = tallyItem.outpoints[0];
const COutPoint outpointPending = tallyItem.outpoints[1];
const COutPoint outpointTimeout = tallyItem.outpoints[2];
const COutPoint outpointInMempool = tallyItem.outpoints[3];
// A denominated coin the user locked themselves, e.g. via `lockunspent`
WITH_LOCK(wallet->cs_wallet, wallet->LockCoin(outpointUserLocked));
BOOST_CHECK(m_node.cj_walletman->doForClient("", [&](CCoinJoinClientManager& cj_man) {
// A user-created lock is never adopted as a pending observation: it has no
// CoinJoin record backing it, so it is left strictly alone
cj_man.CheckPendingObservations(*m_node.mempool);
BOOST_CHECK(!cj_man.IsPendingObservation(outpointUserLocked));
BOOST_CHECK_EQUAL(cj_man.GetPendingObservationCount(), 0);
const int64_t nStart{GetTime()};
SetMockTime(nStart);
cj_man.AddPendingObservation({outpointPending});
BOOST_CHECK(cj_man.IsPendingObservation(outpointPending));
BOOST_CHECK_EQUAL(cj_man.GetPendingObservationCount(), 1);
BOOST_CHECK(WITH_LOCK(wallet->cs_wallet, return wallet->IsLockedCoin(outpointPending)));
// Pending inputs are excluded from coin selection while unrelated inputs are not
{
LOCK(wallet->cs_wallet);
bool fFoundPending{false};
bool fFoundFree{false};
for (const auto& out : AvailableCoinsListUnspent(*wallet).all()) {
fFoundPending |= out.outpoint == outpointPending;
fFoundFree |= out.outpoint == outpointTimeout;
}
BOOST_CHECK(!fFoundPending);
BOOST_CHECK(fFoundFree);
}
// The pending set is mirrored to the wallet database so it survives a restart
{
std::map<COutPoint, int64_t> persisted;
WalletBatch batch(wallet->GetDatabase());
BOOST_REQUIRE(batch.ReadCoinJoinPendingObs(persisted));
BOOST_CHECK_EQUAL(persisted.size(), 1);
BOOST_CHECK(persisted.count(outpointPending) > 0);
BOOST_CHECK_EQUAL(persisted.at(outpointPending), nStart);
}
// Nothing is released while the inputs remain unspent and the timeout has not passed
cj_man.CheckPendingObservations(*m_node.mempool);
BOOST_CHECK_EQUAL(cj_man.GetPendingObservationCount(), 1);
// Once the wallet observes a transaction spending a pending input its lock is dropped
CMutableTransaction mtxSpend;
mtxSpend.vin.emplace_back(outpointPending);
mtxSpend.vout.emplace_back(nDenomAmount - 1000, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
BOOST_REQUIRE(wallet->AddToWallet(MakeTransactionRef(mtxSpend), TxStateInMempool{}));
cj_man.CheckPendingObservations(*m_node.mempool);
BOOST_CHECK(!cj_man.IsPendingObservation(outpointPending));
BOOST_CHECK(!WITH_LOCK(wallet->cs_wallet, return wallet->IsLockedCoin(outpointPending)));
BOOST_CHECK_EQUAL(cj_man.GetPendingObservationCount(), 0);
// An input whose spending transaction sits in the mempool but has not reached the
// wallet yet must NOT be released: findCoins() reports it as unspent (it only
// knows outputs mempool transactions create, not the ones they spend), so the
// mempool has to be consulted separately
CMutableTransaction mtxMempool;
mtxMempool.vin.emplace_back(outpointInMempool);
mtxMempool.vout.emplace_back(nDenomAmount - 1000, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
{
LOCK2(::cs_main, m_node.mempool->cs);
m_node.mempool->addUnchecked(TestMemPoolEntryHelper().FromTx(MakeTransactionRef(mtxMempool)));
}
BOOST_REQUIRE(m_node.mempool->isSpent(outpointInMempool));
BOOST_REQUIRE(WITH_LOCK(wallet->cs_wallet, return wallet->GetWalletTx(mtxMempool.GetHash())) == nullptr);
cj_man.AddPendingObservation({outpointTimeout, outpointInMempool});
BOOST_CHECK_EQUAL(cj_man.GetPendingObservationCount(), 2);
SetMockTime(nStart + COINJOIN_PENDING_OBSERVATION_TIMEOUT + 1);
// The timeout never fires while the chain is still catching up: the spending
// transaction could be sitting in a block we have not downloaded yet
BOOST_REQUIRE(!m_node.mn_sync->IsBlockchainSynced());
cj_man.CheckPendingObservations(*m_node.mempool);
BOOST_CHECK_EQUAL(cj_man.GetPendingObservationCount(), 2);
BOOST_CHECK(WITH_LOCK(wallet->cs_wallet, return wallet->IsLockedCoin(outpointTimeout)));
m_node.mn_sync->SwitchToNextAsset();
BOOST_REQUIRE(m_node.mn_sync->IsBlockchainSynced());
cj_man.CheckPendingObservations(*m_node.mempool);
// Unspent everywhere - released (with a warning) after the terminal timeout
BOOST_CHECK(!cj_man.IsPendingObservation(outpointTimeout));
BOOST_CHECK(!WITH_LOCK(wallet->cs_wallet, return wallet->IsLockedCoin(outpointTimeout)));
// Spent by an unconfirmed transaction the wallet has not recorded - kept locked
BOOST_CHECK(cj_man.IsPendingObservation(outpointInMempool));
BOOST_CHECK(WITH_LOCK(wallet->cs_wallet, return wallet->IsLockedCoin(outpointInMempool)));
BOOST_CHECK_EQUAL(cj_man.GetPendingObservationCount(), 1);
// A manual unlock (e.g. via lockunspent) purges the pending entry
WITH_LOCK(wallet->cs_wallet, wallet->UnlockCoin(outpointInMempool));
cj_man.CheckPendingObservations(*m_node.mempool);
BOOST_CHECK(!cj_man.IsPendingObservation(outpointInMempool));
BOOST_CHECK_EQUAL(cj_man.GetPendingObservationCount(), 0);
// The user's own lock was never touched throughout
BOOST_CHECK(WITH_LOCK(wallet->cs_wallet, return wallet->IsLockedCoin(outpointUserLocked)));
SetMockTime(0);
}));
}
BOOST_FIXTURE_TEST_CASE(coinjoin_pending_observation_reload_tests, CTransactionBuilderTestSetup)
{
// 0.100001 DASH, a valid CoinJoin denomination
constexpr CAmount nDenomAmount{10000100};
CompactTallyItem tallyItem = GetTallyItem({nDenomAmount});
const COutPoint outpointPending = tallyItem.outpoints[0];
const int64_t nStart{GetTime()};
SetMockTime(nStart);
BOOST_CHECK(m_node.cj_walletman->doForClient("", [&](CCoinJoinClientManager& cj_man) {
cj_man.AddPendingObservation({outpointPending});
BOOST_CHECK(cj_man.IsPendingObservation(outpointPending));
}));
BOOST_CHECK(WITH_LOCK(wallet->cs_wallet, return wallet->IsLockedCoin(outpointPending)));
// Drop the client manager and create a fresh one for the same wallet: it has to pick
// the pending observation back up from the wallet database, the way it would after a
// restart, otherwise the persisted lock would be left with nothing to release it
m_node.cj_walletman->removeWallet(wallet->GetName());
m_node.cj_walletman->addWallet(wallet);
BOOST_CHECK(m_node.cj_walletman->doForClient("", [&](CCoinJoinClientManager& cj_man) {
// The record is read lazily, on the first check
BOOST_CHECK_EQUAL(cj_man.GetPendingObservationCount(), 0);
cj_man.CheckPendingObservations(*m_node.mempool);
BOOST_CHECK(cj_man.IsPendingObservation(outpointPending));
BOOST_CHECK_EQUAL(cj_man.GetPendingObservationCount(), 1);
BOOST_CHECK(WITH_LOCK(wallet->cs_wallet, return wallet->IsLockedCoin(outpointPending)));
m_node.mn_sync->SwitchToNextAsset();
BOOST_REQUIRE(m_node.mn_sync->IsBlockchainSynced());
// The grace period was restored along with the entry rather than restarted: the
// terminal timeout is measured from when the session completed, not from reload
SetMockTime(nStart + COINJOIN_PENDING_OBSERVATION_TIMEOUT - 1);
cj_man.CheckPendingObservations(*m_node.mempool);
BOOST_CHECK(cj_man.IsPendingObservation(outpointPending));
SetMockTime(nStart + COINJOIN_PENDING_OBSERVATION_TIMEOUT + 1);
cj_man.CheckPendingObservations(*m_node.mempool);
BOOST_CHECK(!cj_man.IsPendingObservation(outpointPending));
BOOST_CHECK(!WITH_LOCK(wallet->cs_wallet, return wallet->IsLockedCoin(outpointPending)));
}));
SetMockTime(0);
}
BOOST_FIXTURE_TEST_CASE(coinjoin_pending_observation_unreadable_tests, CTransactionBuilderTestSetup)
{
// 0.100001 DASH, a valid CoinJoin denomination
constexpr CAmount nDenomAmount{10000100};
CompactTallyItem tallyItem = GetTallyItem({nDenomAmount, nDenomAmount});
const COutPoint outpointPersisted = tallyItem.outpoints[0];
const COutPoint outpointInMemory = tallyItem.outpoints[1];
const int64_t nStart{GetTime()};
SetMockTime(nStart);
BOOST_CHECK(m_node.cj_walletman->doForClient("", [&](CCoinJoinClientManager& cj_man) {
cj_man.AddPendingObservation({outpointPersisted});
}));
BOOST_CHECK(WITH_LOCK(wallet->cs_wallet, return wallet->IsLockedCoin(outpointPersisted)));
// Corrupt the record behind the manager's back: it exists but cannot be deserialized
// into the pending map anymore. This must not read as "nothing was ever pending", the
// locks it tracks would be left with nothing to ever release them.
BOOST_REQUIRE(wallet->GetDatabase().MakeBatch()->Write(std::string(DBKeys::COINJOIN_PENDING_OBS),
std::string("not a pending observation map")));
// A fresh manager for the same wallet, the way a restart would build one
m_node.cj_walletman->removeWallet(wallet->GetName());
m_node.cj_walletman->addWallet(wallet);
BOOST_CHECK(m_node.cj_walletman->doForClient("", [&](CCoinJoinClientManager& cj_man) {
// The read fails, so nothing is loaded and the persisted lock is left in place
cj_man.CheckPendingObservations(*m_node.mempool);
BOOST_CHECK_EQUAL(cj_man.GetPendingObservationCount(), 0);
BOOST_CHECK(WITH_LOCK(wallet->cs_wallet, return wallet->IsLockedCoin(outpointPersisted)));
// Adding a new observation while the record is unreadable must not overwrite it,
// that would orphan the locks it still tracks for good. The new entry is kept in
// memory (and its coin locked) but deliberately not persisted.
cj_man.AddPendingObservation({outpointInMemory});
BOOST_CHECK(cj_man.IsPendingObservation(outpointInMemory));
BOOST_CHECK(WITH_LOCK(wallet->cs_wallet, return wallet->IsLockedCoin(outpointInMemory)));
{
std::map<COutPoint, int64_t> persisted;
WalletBatch batch(wallet->GetDatabase());
BOOST_CHECK(!batch.ReadCoinJoinPendingObs(persisted));
BOOST_CHECK(persisted.empty());
}
// Same for the release path: a pass which changes the pending set must not write
// the record out either while its contents are still unknown
WITH_LOCK(wallet->cs_wallet, wallet->UnlockCoin(outpointInMemory));
cj_man.CheckPendingObservations(*m_node.mempool);
BOOST_CHECK(!cj_man.IsPendingObservation(outpointInMemory));
BOOST_CHECK(WITH_LOCK(wallet->cs_wallet, return wallet->IsLockedCoin(outpointPersisted)));
{
std::map<COutPoint, int64_t> persisted;
WalletBatch batch(wallet->GetDatabase());
BOOST_CHECK(!batch.ReadCoinJoinPendingObs(persisted));
}
// Once the record is readable again the entry it tracks is picked back up and the
// lock behind it can finally be released
{
WalletBatch batch(wallet->GetDatabase());
BOOST_REQUIRE(batch.WriteCoinJoinPendingObs({{outpointPersisted, nStart}}));
}
cj_man.CheckPendingObservations(*m_node.mempool);
BOOST_CHECK(cj_man.IsPendingObservation(outpointPersisted));
BOOST_CHECK_EQUAL(cj_man.GetPendingObservationCount(), 1);
m_node.mn_sync->SwitchToNextAsset();
BOOST_REQUIRE(m_node.mn_sync->IsBlockchainSynced());
SetMockTime(nStart + COINJOIN_PENDING_OBSERVATION_TIMEOUT + 1);
cj_man.CheckPendingObservations(*m_node.mempool);
BOOST_CHECK(!cj_man.IsPendingObservation(outpointPersisted));
BOOST_CHECK(!WITH_LOCK(wallet->cs_wallet, return wallet->IsLockedCoin(outpointPersisted)));
}));
SetMockTime(0);
}
BOOST_FIXTURE_TEST_CASE(coinjoin_manager_start_stop_tests, CTransactionBuilderTestSetup)
{
BOOST_CHECK(m_node.cj_walletman->doForClient("", [](auto& cj_man) {
BOOST_CHECK_EQUAL(cj_man.isMixing(), false);
BOOST_CHECK_EQUAL(cj_man.startMixing(), true);
BOOST_CHECK_EQUAL(cj_man.isMixing(), true);
BOOST_CHECK_EQUAL(cj_man.startMixing(), false);
cj_man.stopMixing();
BOOST_CHECK_EQUAL(cj_man.isMixing(), false);
}));
}
// End-to-end check that NewKeyPool() stops mixing
BOOST_FIXTURE_TEST_CASE(coinjoin_newkeypool_stops_mixing_tests, CTransactionBuilderTestSetup)
{
BOOST_CHECK(m_node.cj_walletman->doForClient("", [](auto& cj_man) {
BOOST_REQUIRE(cj_man.startMixing());
BOOST_CHECK_EQUAL(cj_man.isMixing(), true);
}));
{
LOCK(wallet->cs_wallet);
BOOST_REQUIRE(wallet->GetLegacyScriptPubKeyMan()->NewKeyPool());
}
BOOST_CHECK(m_node.cj_walletman->doForClient("", [](auto& cj_man) {
BOOST_CHECK_EQUAL(cj_man.isMixing(), false);
}));
}
BOOST_FIXTURE_TEST_CASE(coinjoin_rebalance_rounds_reset_tests, CTransactionBuilderTestSetup)
{
// 0.100001 DASH and its larger adjacent denomination 1.00001 DASH; the standard
// denominations are constructed so PROMOTION_RATIO smaller coins equal one larger coin
constexpr CAmount nSmallerAmount{10000100};
constexpr CAmount nLargerAmount{nSmallerAmount * CoinJoin::PROMOTION_RATIO};
BOOST_REQUIRE(CoinJoin::IsDenominatedAmount(nSmallerAmount));
BOOST_REQUIRE(CoinJoin::IsDenominatedAmount(nLargerAmount));
// PROMOTION_RATIO coins for the promotion plus one to demonstrate standard mixing
CompactTallyItem tallyItem = GetTallyItem(std::vector<CAmount>(CoinJoin::PROMOTION_RATIO + 1, nSmallerAmount));
const CScript scriptOurs = GetScriptForRawPubKey(coinbaseKey.GetPubKey());
// The funding transactions pay fees, so their denominated outputs start at 0 rounds
BOOST_CHECK_EQUAL(wallet->GetRealOutpointCoinJoinRounds(tallyItem.outpoints[0]), 0);
// Standard mixing shape (1 in -> 1 out, same denomination): rounds advance by one
CMutableTransaction mtxMix;
mtxMix.vin.emplace_back(tallyItem.outpoints[0]);
mtxMix.vout.emplace_back(nSmallerAmount, scriptOurs);
BOOST_REQUIRE(wallet->AddToWallet(MakeTransactionRef(mtxMix), TxStateInMempool{}));
const COutPoint outpointMixed{mtxMix.GetHash(), 0};
BOOST_CHECK_EQUAL(wallet->GetRealOutpointCoinJoinRounds(outpointMixed), 1);
// Promotion shape (PROMOTION_RATIO inputs -> 1 output at the larger adjacent
// denomination): the conversion's public 10:1 shape clusters the participant's coins,
// so the promoted output starts mixing over instead of inheriting its inputs' rounds
CMutableTransaction mtxPromo;
for (int i = 1; i <= CoinJoin::PROMOTION_RATIO; ++i) {
mtxPromo.vin.emplace_back(tallyItem.outpoints[i]);
}
mtxPromo.vout.emplace_back(nLargerAmount, scriptOurs);
BOOST_REQUIRE(wallet->AddToWallet(MakeTransactionRef(mtxPromo), TxStateInMempool{}));
const COutPoint outpointPromoted{mtxPromo.GetHash(), 0};
BOOST_CHECK_EQUAL(wallet->GetRealOutpointCoinJoinRounds(outpointPromoted), 0);
// A promoted coin re-enters mixing normally: one standard round at the new
// denomination advances it to 1
CMutableTransaction mtxRemix;
mtxRemix.vin.emplace_back(outpointPromoted);
mtxRemix.vout.emplace_back(nLargerAmount, scriptOurs);
BOOST_REQUIRE(wallet->AddToWallet(MakeTransactionRef(mtxRemix), TxStateInMempool{}));
const COutPoint outpointRemixed{mtxRemix.GetHash(), 0};
BOOST_CHECK_EQUAL(wallet->GetRealOutpointCoinJoinRounds(outpointRemixed), 1);
// Demotion shape (1 input -> PROMOTION_RATIO outputs at the smaller adjacent
// denomination): the mirror image, every demoted output starts mixing over
CMutableTransaction mtxDemo;
mtxDemo.vin.emplace_back(outpointRemixed);
for (int i = 0; i < CoinJoin::PROMOTION_RATIO; ++i) {
mtxDemo.vout.emplace_back(nSmallerAmount, scriptOurs);
}
BOOST_REQUIRE(wallet->AddToWallet(MakeTransactionRef(mtxDemo), TxStateInMempool{}));
for (uint32_t n = 0; n < uint32_t(CoinJoin::PROMOTION_RATIO); ++n) {
BOOST_CHECK_EQUAL(wallet->GetRealOutpointCoinJoinRounds(COutPoint{mtxDemo.GetHash(), n}), 0);
}
}
BOOST_FIXTURE_TEST_CASE(CTransactionBuilderTest, CTransactionBuilderTestSetup)
{
// NOTE: Mock wallet version is FEATURE_BASE which means that it uses uncompressed pubkeys
// (65 bytes instead of 33 bytes) and we use Low R signatures, so CTxIn size is 179 bytes.
// Each output is 34 bytes, vin and vout compact sizes are 1 byte each.
// Therefore base size (i.e. for a tx with 1 input, 0 outputs) is expected to be
// 4(n32bitVersion) + 1(vin size) + 179(vin[0]) + 1(vout size) + 4(nLockTime) = 189 bytes.
// Tests with single outpoint tallyItem
{
CompactTallyItem tallyItem = GetTallyItem({4999});
CTransactionBuilder txBuilder(*wallet, tallyItem);
BOOST_CHECK_EQUAL(txBuilder.CountOutputs(), 0);
BOOST_CHECK_EQUAL(txBuilder.GetAmountInitial(), tallyItem.nAmount);
BOOST_CHECK_EQUAL(txBuilder.GetAmountLeft(), 4810); // 4999 - 189
BOOST_CHECK(txBuilder.CouldAddOutput(4776)); // 4810 - 34
BOOST_CHECK(!txBuilder.CouldAddOutput(4777));
BOOST_CHECK(txBuilder.CouldAddOutput(0));
BOOST_CHECK(!txBuilder.CouldAddOutput(-1));
BOOST_CHECK(txBuilder.CouldAddOutputs({1000, 1000, 2708})); // (4810 - 34 * 3) split in 3 outputs
BOOST_CHECK(!txBuilder.CouldAddOutputs({1000, 1000, 2709}));
BOOST_CHECK_EQUAL(txBuilder.AddOutput(4999), nullptr);
BOOST_CHECK_EQUAL(txBuilder.AddOutput(-1), nullptr);
CTransactionBuilderOutput* output = txBuilder.AddOutput();
BOOST_CHECK(output->UpdateAmount(txBuilder.GetAmountLeft()));
BOOST_CHECK(output->UpdateAmount(1));
BOOST_CHECK(output->UpdateAmount(output->GetAmount() + txBuilder.GetAmountLeft()));
BOOST_CHECK(!output->UpdateAmount(output->GetAmount() + 1));
BOOST_CHECK(!output->UpdateAmount(0));
BOOST_CHECK(!output->UpdateAmount(-1));
BOOST_CHECK_EQUAL(txBuilder.CountOutputs(), 1);
bilingual_str strResult;
BOOST_REQUIRE(txBuilder.Commit(strResult));
CWalletTx& wtx = AddTxToChain(uint256S(strResult.original));
BOOST_CHECK_EQUAL(wtx.tx->vout.size(), txBuilder.CountOutputs()); // should have no change output
BOOST_CHECK_EQUAL(wtx.tx->vout[0].nValue, output->GetAmount());
BOOST_CHECK(wtx.tx->vout[0].scriptPubKey == output->GetScript());
}
// Tests with multiple outpoint tallyItem
{
CompactTallyItem tallyItem = GetTallyItem({10000, 20000, 30000, 40000, 50000});
CTransactionBuilder txBuilder(*wallet, tallyItem);
std::vector<CTransactionBuilderOutput*> vecOutputs;
bilingual_str strResult;
auto output = txBuilder.AddOutput(100);
BOOST_CHECK(output != nullptr);
BOOST_CHECK(!txBuilder.Commit(strResult));
if (output != nullptr) {
output->UpdateAmount(1000);
vecOutputs.push_back(output);
}
while (vecOutputs.size() < 100) {
output = txBuilder.AddOutput(1000 + vecOutputs.size());
if (output == nullptr) {
break;
}
vecOutputs.push_back(output);
}
BOOST_CHECK_EQUAL(vecOutputs.size(), 100);
BOOST_CHECK_EQUAL(txBuilder.CountOutputs(), vecOutputs.size());
BOOST_REQUIRE(txBuilder.Commit(strResult));
CWalletTx& wtx = AddTxToChain(uint256S(strResult.original));
BOOST_CHECK_EQUAL(wtx.tx->vout.size(), txBuilder.CountOutputs() + 1); // should have change output
for (const auto& out : wtx.tx->vout) {
auto it = std::find_if(vecOutputs.begin(), vecOutputs.end(), [&](CTransactionBuilderOutput* output) -> bool {
return output->GetAmount() == out.nValue && output->GetScript() == out.scriptPubKey;
});
if (it != vecOutputs.end()) {
vecOutputs.erase(it);
} else {
// change output
BOOST_CHECK_EQUAL(txBuilder.GetAmountLeft() - 34, out.nValue);
}
}
BOOST_CHECK(vecOutputs.size() == 0);
}
}
BOOST_AUTO_TEST_SUITE_END()
} // namespace wallet