diff --git a/src/test/bls_tests.cpp b/src/test/bls_tests.cpp index 83715e84f296..6c5d35c3e9e5 100644 --- a/src/test/bls_tests.cpp +++ b/src/test/bls_tests.cpp @@ -874,52 +874,27 @@ class DummyBLS // Define a type alias for our lazy wrapper instantiated with DummyBLS. using LazyDummyBLS = CBLSLazyWrapper; -// Test 1: Two default (unset) wrappers should compare equal. -BOOST_AUTO_TEST_CASE(test_default_equality) -{ - LazyDummyBLS lazy1; - LazyDummyBLS lazy2; - // Neither instance has been set, so they represent the default/null object. - BOOST_CHECK(lazy1 == lazy2); -} - -// Test 2: A default wrapper and one initialized with a nonzero DummyBLS should compare unequal. -BOOST_AUTO_TEST_CASE(test_non_default_vs_default) -{ - LazyDummyBLS lazy_default; - LazyDummyBLS lazy_set; - DummyBLS obj; - obj.data = {1, 0, 0, 0}; // nonzero data makes the object valid - lazy_set.Set(obj, false); - BOOST_CHECK(!(lazy_default == lazy_set)); - BOOST_CHECK(lazy_default != lazy_set); -} - -// Test 2: A default wrapper and one initialized with a nonzero DummyBLS should compare unequal. -BOOST_AUTO_TEST_CASE(test_non_default_vs_different) -{ - LazyDummyBLS lazy_a; - LazyDummyBLS lazy_b; - DummyBLS obj; - obj.data = {1, 2, 3, 4}; // nonzero data makes the object valid - lazy_a.Set(obj, false); - obj.data = {2, 2, 3, 4}; // nonzero data makes the object valid - lazy_b.Set(obj, false); - BOOST_CHECK(lazy_a != lazy_b); -} - -// Test 3: Two wrappers set with the same underlying DummyBLS value compare equal. +// Unset wrappers compare equal, a set wrapper differs from unset and from a +// different value, and two wrappers set to the same value compare equal. BOOST_AUTO_TEST_CASE(test_equality_same_value) { LazyDummyBLS lazy1; LazyDummyBLS lazy2; BOOST_CHECK(lazy1 == lazy2); + DummyBLS obj; obj.data = {5, 6, 7, 8}; lazy1.Set(obj, false); BOOST_CHECK(lazy1 != lazy2); + BOOST_CHECK(!(lazy1 == lazy2)); + lazy2.Set(obj, false); BOOST_CHECK(lazy1 == lazy2); + + obj.data = {2, 2, 3, 4}; + LazyDummyBLS lazy_other; + lazy_other.Set(obj, false); + BOOST_CHECK(lazy1 != lazy_other); } // Test 4: Serialization and unserialization preserve the wrapped value. diff --git a/src/test/coinjoin_inouts_tests.cpp b/src/test/coinjoin_inouts_tests.cpp index 8c8def30154a..d15bd7abdb48 100644 --- a/src/test/coinjoin_inouts_tests.cpp +++ b/src/test/coinjoin_inouts_tests.cpp @@ -786,52 +786,6 @@ BOOST_AUTO_TEST_CASE(entry_rejects_outputs_above_wire_cap_before_materializing) BOOST_CHECK(entry.vecTxOut.empty()); } -BOOST_AUTO_TEST_CASE(queue_timeout_bounds) -{ - const auto now{std::chrono::time_point_cast(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(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(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) { @@ -846,189 +800,68 @@ 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 vecTxIn; - std::vector 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 - vecTxIn.reserve(CoinJoin::PROMOTION_RATIO); - for (int i = 0; i < CoinJoin::PROMOTION_RATIO; ++i) { - vecTxIn.push_back(MakeDenomInput(static_cast(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 vecTxIn; - std::vector 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 - vecTxIn.reserve(CoinJoin::PROMOTION_RATIO - 1); - for (int i = 0; i < CoinJoin::PROMOTION_RATIO - 1; ++i) { - vecTxIn.push_back(MakeDenomInput(static_cast(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 vecTxIn; - std::vector vecTxOut; - - const int nSmallerDenom = 1 << 2; - const int nLargerDenom = 1 << 1; - const CAmount nLargerAmount = CoinJoin::DenominationToAmount(nLargerDenom); - - vecTxIn.reserve(CoinJoin::PROMOTION_RATIO); - for (int i = 0; i < CoinJoin::PROMOTION_RATIO; ++i) { - vecTxIn.push_back(MakeDenomInput(static_cast(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) +BOOST_AUTO_TEST_CASE(validate_promotion_demotion_entries) { - // Invalid: trying to promote 0.01 to 1.0 (not adjacent) - std::vector vecTxIn; - std::vector vecTxOut; - - const int nSmallerDenom = 1 << 3; // 0.01 DASH - const int nLargerDenom = 1 << 1; // 1.0 DASH (not adjacent to 0.01) + // One keeper for the size, adjacency, and "no larger source" branches. + // ValidatePromotionEntry / ValidateDemotionEntry return on the first failure. + const int nSmallerDenom = 1 << 2; // 0.1 DASH + const int nLargerDenom = 1 << 1; // 1.0 DASH const CAmount nLargerAmount = CoinJoin::DenominationToAmount(nLargerDenom); - - vecTxIn.reserve(CoinJoin::PROMOTION_RATIO); - for (int i = 0; i < CoinJoin::PROMOTION_RATIO; ++i) { - vecTxIn.push_back(MakeDenomInput(static_cast(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 vecTxIn; - std::vector 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 - vecTxOut.reserve(CoinJoin::PROMOTION_RATIO); - for (int i = 0; i < CoinJoin::PROMOTION_RATIO; ++i) { - vecTxOut.push_back(MakeDenomOutput(nSmallerAmount, static_cast(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 vecTxIn; - std::vector 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)); - - vecTxOut.reserve(CoinJoin::PROMOTION_RATIO); - for (int i = 0; i < CoinJoin::PROMOTION_RATIO; ++i) { - vecTxOut.push_back(MakeDenomOutput(nSmallerAmount, static_cast(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 vecTxIn; - std::vector vecTxOut; + auto inputs = [](int count) { + std::vector vin; + vin.reserve(count); + for (int i = 0; i < count; ++i) { + vin.push_back(MakeDenomInput(static_cast(i))); + } + return vin; + }; + auto outputs = [](int count, CAmount amount) { + std::vector vout; + vout.reserve(count); + for (int i = 0; i < count; ++i) { + vout.push_back(MakeDenomOutput(amount, static_cast(i))); + } + return vout; + }; - const int nSmallerDenom = 1 << 2; - const CAmount nSmallerAmount = CoinJoin::DenominationToAmount(nSmallerDenom); + const auto promo_in = inputs(CoinJoin::PROMOTION_RATIO); + const auto promo_out = outputs(1, nLargerAmount); + PoolMessage msg = MSG_NOERR; + BOOST_CHECK(CoinJoin::ValidatePromotionEntry(promo_in, promo_out, nSmallerDenom, msg)); - vecTxIn.push_back(MakeDenomInput(0)); + msg = MSG_NOERR; + BOOST_CHECK(!CoinJoin::ValidatePromotionEntry(inputs(CoinJoin::PROMOTION_RATIO - 1), promo_out, nSmallerDenom, msg)); - // Only 9 outputs - vecTxOut.reserve(CoinJoin::PROMOTION_RATIO - 1); - for (int i = 0; i < CoinJoin::PROMOTION_RATIO - 1; ++i) { - vecTxOut.push_back(MakeDenomOutput(nSmallerAmount, static_cast(i))); - } + msg = MSG_NOERR; + BOOST_CHECK(!CoinJoin::ValidatePromotionEntry(promo_in, outputs(2, nLargerAmount), nSmallerDenom, msg)); - PoolMessage nMessageID = MSG_NOERR; - BOOST_CHECK(!CoinJoin::ValidateDemotionEntry(vecTxIn, vecTxOut, nSmallerDenom, nMessageID)); -} + // Output amount is not the adjacent larger denomination. + msg = MSG_NOERR; + BOOST_CHECK(!CoinJoin::ValidatePromotionEntry(promo_in, outputs(1, CoinJoin::DenominationToAmount(1 << 3)), nSmallerDenom, msg)); -BOOST_AUTO_TEST_CASE(validate_demotion_entry_largest_denom_has_no_source) -{ - // Invalid: nothing demotes into 10 DASH, there is no larger denomination to split - std::vector vecTxIn; - std::vector vecTxOut; + // Nothing promotes out of 10 DASH. + msg = MSG_NOERR; + BOOST_CHECK(!CoinJoin::ValidatePromotionEntry(promo_in, promo_out, /*nSessionDenom=*/1 << 0, msg)); + BOOST_CHECK(msg == ERR_DENOM); - const int nLargestDenom = 1 << 0; // 10 DASH - const CAmount nLargestAmount = CoinJoin::DenominationToAmount(nLargestDenom); - BOOST_CHECK_EQUAL(CoinJoin::GetLargerAdjacentDenom(nLargestDenom), 0); + const auto demo_in = inputs(1); + const auto demo_out = outputs(CoinJoin::PROMOTION_RATIO, nSmallerAmount); + msg = MSG_NOERR; + BOOST_CHECK(CoinJoin::ValidateDemotionEntry(demo_in, demo_out, nSmallerDenom, msg)); - vecTxIn.push_back(MakeDenomInput(0)); + msg = MSG_NOERR; + BOOST_CHECK(!CoinJoin::ValidateDemotionEntry(inputs(2), demo_out, nSmallerDenom, msg)); - vecTxOut.reserve(CoinJoin::PROMOTION_RATIO); - for (int i = 0; i < CoinJoin::PROMOTION_RATIO; ++i) { - vecTxOut.push_back(MakeDenomOutput(nLargestAmount, static_cast(i))); - } + msg = MSG_NOERR; + BOOST_CHECK(!CoinJoin::ValidateDemotionEntry(demo_in, outputs(CoinJoin::PROMOTION_RATIO - 1, nSmallerAmount), nSmallerDenom, msg)); - PoolMessage nMessageID = MSG_NOERR; - BOOST_CHECK(!CoinJoin::ValidateDemotionEntry(vecTxIn, vecTxOut, nLargestDenom, nMessageID)); - BOOST_CHECK(nMessageID == ERR_DENOM); + // Nothing demotes into 10 DASH. + msg = MSG_NOERR; + BOOST_CHECK_EQUAL(CoinJoin::GetLargerAdjacentDenom(1 << 0), 0); + BOOST_CHECK(!CoinJoin::ValidateDemotionEntry(demo_in, outputs(CoinJoin::PROMOTION_RATIO, CoinJoin::DenominationToAmount(1 << 0)), 1 << 0, msg)); + BOOST_CHECK(msg == ERR_DENOM); } BOOST_AUTO_TEST_CASE(denomination_adjacency_checks) @@ -1080,42 +913,6 @@ BOOST_AUTO_TEST_CASE(get_adjacent_denomination_helpers) 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(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 @@ -1206,59 +1003,6 @@ BOOST_AUTO_TEST_CASE(input_limit_prefork) 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(i)); - mtx.vin.push_back(in); - } - for (size_t i = 0; i < nOutputs; ++i) { - mtx.vout.emplace_back(nSmallestDenom, P2PKHScript(static_cast(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; @@ -1319,93 +1063,6 @@ BOOST_AUTO_TEST_CASE(promotion_demotion_value_preservation) } } -BOOST_AUTO_TEST_CASE(isvalidstructure_mixed_session_postfork) -{ - // Post-V24: A transaction with mixed entry types should be valid - // (some participants doing 1:1, others doing promotion/demotion) - // This tests that the structure validation allows mixed input/output counts - - CCoinJoinBroadcastTx mixed; - { - CMutableTransaction mtx; - // Simulate a mixed session: - // - 3 standard participants: 3 inputs, 3 outputs (smallest denom) - // - 1 promotion participant: 10 inputs, 1 output - // Total: 13 inputs, 4 outputs - - const CAmount nSmallestDenom = CoinJoin::GetSmallestDenomination(); - const CAmount nSecondSmallest = CoinJoin::DenominationToAmount(1 << 3); // 0.01 DASH - - // Standard participants (3 x 1:1) - for (int i = 0; i < 3; ++i) { - CTxIn in; - in.prevout = COutPoint(uint256::ONE, static_cast(i)); - mtx.vin.push_back(in); - mtx.vout.emplace_back(nSmallestDenom, P2PKHScript(static_cast(i))); - } - - // Promotion participant (10 inputs -> 1 output) - for (int i = 3; i < 13; ++i) { - CTxIn in; - in.prevout = COutPoint(uint256::ONE, static_cast(i)); - mtx.vin.push_back(in); - } - // One output for the promotion (larger denom) - mtx.vout.emplace_back(nSecondSmallest, P2PKHScript(0x0D)); - - mixed.tx = MakeTransactionRef(mtx); - mixed.m_protxHash = uint256::ONE; - } - - // Pre-V24: Should fail (unbalanced) - BOOST_CHECK(!mixed.IsValidStructure(nullptr, *Assert(m_node.chainman))); - - // Note: Post-V24 testing requires a valid CBlockIndex with V24 deployment active - // which requires more complex test setup with chainstate. The above verifies - // that pre-fork rejection works correctly. -} - -BOOST_AUTO_TEST_CASE(entry_type_detection_logic) -{ - // Test the entry type detection logic used in IsValidInOuts - // Entry types: - // - STANDARD: vin.size() == vout.size() - // - PROMOTION: vin.size() == PROMOTION_RATIO && vout.size() == 1 - // - DEMOTION: vin.size() == 1 && vout.size() == PROMOTION_RATIO - // - INVALID: anything else - - auto detectEntryType = [](size_t vinSize, size_t voutSize) -> std::string { - if (vinSize == voutSize) { - return "STANDARD"; - } else if (vinSize == static_cast(CoinJoin::PROMOTION_RATIO) && voutSize == 1) { - return "PROMOTION"; - } else if (vinSize == 1 && voutSize == static_cast(CoinJoin::PROMOTION_RATIO)) { - return "DEMOTION"; - } - return "INVALID"; - }; - - // Standard entries - BOOST_CHECK_EQUAL(detectEntryType(1, 1), "STANDARD"); - BOOST_CHECK_EQUAL(detectEntryType(5, 5), "STANDARD"); - BOOST_CHECK_EQUAL(detectEntryType(9, 9), "STANDARD"); // Max standard entry - - // Promotion entries - BOOST_CHECK_EQUAL(detectEntryType(10, 1), "PROMOTION"); - - // Demotion entries - BOOST_CHECK_EQUAL(detectEntryType(1, 10), "DEMOTION"); - - // Invalid entries (not valid pre or post fork) - BOOST_CHECK_EQUAL(detectEntryType(9, 1), "INVALID"); // Wrong ratio - BOOST_CHECK_EQUAL(detectEntryType(1, 9), "INVALID"); // Wrong ratio - BOOST_CHECK_EQUAL(detectEntryType(5, 3), "INVALID"); // Random mismatch - BOOST_CHECK_EQUAL(detectEntryType(2, 10), "INVALID"); // Wrong input count for demotion - BOOST_CHECK_EQUAL(detectEntryType(10, 2), "INVALID"); // Wrong output count for promotion - BOOST_CHECK_EQUAL(detectEntryType(20, 2), "INVALID"); // 20:2 is not valid - BOOST_CHECK_EQUAL(detectEntryType(11, 1), "INVALID"); // 11:1 is not valid promotion -} - BOOST_AUTO_TEST_CASE(validate_entry_session_denom_consistency) { // Test that promotion/demotion validation enforces session denomination consistency @@ -1449,61 +1106,6 @@ BOOST_AUTO_TEST_CASE(validate_entry_session_denom_consistency) BOOST_CHECK(CoinJoin::ValidateDemotionEntry(demoVin, demoVout, nSessionDenom, msg)); } -BOOST_AUTO_TEST_CASE(isvalidstructure_boundary_input_counts) -{ - // Test boundary conditions for input counts at the pre/post V24 limits - // Pre-V24: max 180 inputs (20 * 9) - // Post-V24: max 200 inputs (20 * 10) - - const size_t nPreForkMax = CoinJoin::GetMaxPoolParticipants() * COINJOIN_ENTRY_MAX_SIZE; - const size_t nPostForkMax = CoinJoin::GetMaxPoolParticipants() * CoinJoin::PROMOTION_RATIO; - - BOOST_CHECK_EQUAL(nPreForkMax, 180); - BOOST_CHECK_EQUAL(nPostForkMax, 200); - - // Create transaction with exactly 180 inputs (valid pre and post fork) - CCoinJoinBroadcastTx tx180; - { - CMutableTransaction mtx; - for (size_t i = 0; i < 180; ++i) { - mtx.vin.emplace_back(COutPoint(uint256::ONE, static_cast(i))); - mtx.vout.emplace_back(CoinJoin::GetSmallestDenomination(), P2PKHScript(static_cast(i % 256))); - } - tx180.tx = MakeTransactionRef(mtx); - tx180.m_protxHash = uint256::ONE; - } - BOOST_CHECK(tx180.IsValidStructure(nullptr, *Assert(m_node.chainman))); // Pre-fork: valid at boundary - - // Create transaction with 181 inputs (invalid pre-fork, would be valid post-fork) - CCoinJoinBroadcastTx tx181; - { - CMutableTransaction mtx; - for (size_t i = 0; i < 181; ++i) { - mtx.vin.emplace_back(COutPoint(uint256::ONE, static_cast(i))); - mtx.vout.emplace_back(CoinJoin::GetSmallestDenomination(), P2PKHScript(static_cast(i % 256))); - } - tx181.tx = MakeTransactionRef(mtx); - tx181.m_protxHash = uint256::ONE; - } - BOOST_CHECK(!tx181.IsValidStructure(nullptr, *Assert(m_node.chainman))); // Pre-fork: over limit - - // Transaction at post-fork boundary (200 inputs) - CCoinJoinBroadcastTx tx200; - { - CMutableTransaction mtx; - for (size_t i = 0; i < 200; ++i) { - mtx.vin.emplace_back(COutPoint(uint256::ONE, static_cast(i))); - mtx.vout.emplace_back(CoinJoin::GetSmallestDenomination(), P2PKHScript(static_cast(i % 256))); - } - tx200.tx = MakeTransactionRef(mtx); - tx200.m_protxHash = uint256::ONE; - } - // Pre-fork: over limit (200 > 180) - BOOST_CHECK(!tx200.IsValidStructure(nullptr, *Assert(m_node.chainman))); - - // Note: Testing post-fork behavior requires a CBlockIndex with V24 active via EHF -} - BOOST_AUTO_TEST_CASE(isvalidstructure_postv24_count_relations) { // The post-V24 branch needs a V24-active CBlockIndex, which this fixture has no chain for. @@ -1606,32 +1208,19 @@ BOOST_AUTO_TEST_CASE(should_demote_requires_fully_mixed_coin) BOOST_CHECK(!CoinJoin::ShouldDemoteDenoms(100, 0, /*nLargerFullyMixedCount=*/0, 100)); } -BOOST_AUTO_TEST_CASE(should_promote_larger_deficit_greater) -{ - const int goal = 100; - - // 60 of smaller, 0 of larger -> should promote (0.1 has surplus, 1.0 needs help) - // smallerDeficit = 40, largerDeficit = 100, gap = 60 > gap threshold (20 at this goal) - BOOST_CHECK(TestShouldPromote(60, 0, goal)); - - // 100 of smaller, 0 of larger -> should promote (0.1 full, 1.0 empty) - // smallerDeficit = 0, largerDeficit = 100, gap = 100 > gap threshold (20 at this goal) - BOOST_CHECK(TestShouldPromote(100, 0, goal)); -} - -BOOST_AUTO_TEST_CASE(should_promote_below_half_goal_false) +BOOST_AUTO_TEST_CASE(denom_rebalance_decision) { + // Count branches of ShouldPromoteDenoms / ShouldDemoteDenoms. Fully-mixed gates + // and the minimum-goal threshold stay in their own cases. const int goal = 100; - - // 30 of smaller, 0 of larger -> should NOT promote (30 < 50 = halfGoal) - BOOST_CHECK(!TestShouldPromote(30, 0, goal)); - - // 49 of smaller, 0 of larger -> should NOT promote (49 < 50 = halfGoal) BOOST_CHECK(!TestShouldPromote(49, 0, goal)); - - // 50 of smaller, 0 of larger -> CAN promote (50 >= 50 = halfGoal) - // smallerDeficit = 50, largerDeficit = 100, gap = 50 > gap threshold (20 at this goal) BOOST_CHECK(TestShouldPromote(50, 0, goal)); + BOOST_CHECK(TestShouldPromote(60, 0, goal)); + BOOST_CHECK(!TestShouldDemote(49, 0, goal)); + BOOST_CHECK(TestShouldDemote(50, 0, goal)); + BOOST_CHECK(TestShouldDemote(99, 0, goal)); + BOOST_CHECK(!TestShouldPromote(100, 100, goal)); + BOOST_CHECK(!TestShouldDemote(100, 100, goal)); } BOOST_AUTO_TEST_CASE(gap_threshold_reachable_at_every_goal) @@ -1673,212 +1262,6 @@ BOOST_AUTO_TEST_CASE(rebalance_never_immediately_reverses) } } -BOOST_AUTO_TEST_CASE(should_promote_small_gap_false) -{ - const int goal = 100; - - // 90 smaller, 80 larger -> deficits are 10 and 20, gap = 10 - // 20 > 10 + 20 is false, so no promotion - BOOST_CHECK(!TestShouldPromote(90, 80, goal)); - - // 85 smaller, 80 larger -> deficits are 15 and 20, gap = 5 - // 20 > 15 + 20 is false, so no promotion - BOOST_CHECK(!TestShouldPromote(85, 80, goal)); -} - -BOOST_AUTO_TEST_CASE(should_demote_smaller_deficit_greater) -{ - const int goal = 100; - - // 60 of larger, 0 of smaller -> should demote (1.0 has surplus, 0.1 needs help) - // largerDeficit = 40, smallerDeficit = 100, gap = 60 > gap threshold (20 at this goal) - BOOST_CHECK(TestShouldDemote(60, 0, goal)); - - // 99 of larger, 0 of smaller -> should demote - // largerDeficit = 1, smallerDeficit = 100, gap = 99 > gap threshold (20 at this goal) - BOOST_CHECK(TestShouldDemote(99, 0, goal)); -} - -BOOST_AUTO_TEST_CASE(should_demote_below_half_goal_false) -{ - const int goal = 100; - - // 30 of larger, 0 of smaller -> should NOT demote (30 < 50 = halfGoal) - BOOST_CHECK(!TestShouldDemote(30, 0, goal)); - - // 49 of larger, 0 of smaller -> should NOT demote (49 < 50 = halfGoal) - BOOST_CHECK(!TestShouldDemote(49, 0, goal)); - - // 50 of larger, 0 of smaller -> CAN demote (50 >= 50 = halfGoal) - // largerDeficit = 50, smallerDeficit = 100, gap = 50 > gap threshold (20 at this goal) - BOOST_CHECK(TestShouldDemote(50, 0, goal)); -} - -BOOST_AUTO_TEST_CASE(promote_demote_mutually_exclusive) -{ - // Test various distributions - at most one should be true - auto testMutualExclusivity = [](int smallerCount, int largerCount) { - const int testGoal = 100; - bool promote = TestShouldPromote(smallerCount, largerCount, testGoal); - bool demote = TestShouldDemote(largerCount, smallerCount, testGoal); - // At most one can be true (XOR or neither) - BOOST_CHECK(!(promote && demote)); - return std::make_pair(promote, demote); - }; - - // Equal counts - neither - auto [p1, d1] = testMutualExclusivity(100, 100); - BOOST_CHECK(!p1 && !d1); - - // 90/90 - neither (close to goal, small gap) - auto [p2, d2] = testMutualExclusivity(90, 90); - BOOST_CHECK(!p2 && !d2); - - // Large imbalance toward smaller - promote only - auto [p3, d3] = testMutualExclusivity(100, 0); - BOOST_CHECK(p3 && !d3); - - // Large imbalance toward larger - demote only - auto [p4, d4] = testMutualExclusivity(0, 100); - BOOST_CHECK(!p4 && d4); - - // Mid-range cases from the plan - auto [p5, d5] = testMutualExclusivity(0, 60); // 0.1=0, 1.0=60 -> should demote - BOOST_CHECK(!p5 && d5); - - auto [p6, d6] = testMutualExclusivity(60, 0); // 0.1=60, 1.0=0 -> should promote - BOOST_CHECK(p6 && !d6); -} - -BOOST_AUTO_TEST_CASE(decision_logic_example_cases_from_plan) -{ - // Test the specific examples from the implementation plan - const int goal = 100; - - // | 1.0 count | 0.1 count | Action | - // | 99 | 0 | Demote | - BOOST_CHECK(TestShouldDemote(99, 0, goal)); - BOOST_CHECK(!TestShouldPromote(0, 99, goal)); // 0.1 has 0, can't promote - - // | 60 | 0 | Demote | - BOOST_CHECK(TestShouldDemote(60, 0, goal)); - - // | 30 | 0 | Nothing (1.0 < halfGoal) | - BOOST_CHECK(!TestShouldDemote(30, 0, goal)); - BOOST_CHECK(!TestShouldPromote(0, 30, goal)); - - // | 0 | 60 | Promote | - BOOST_CHECK(TestShouldPromote(60, 0, goal)); - - // | 0 | 30 | Nothing (0.1 < halfGoal) | - BOOST_CHECK(!TestShouldPromote(30, 0, goal)); - - // | 100 | 100 | Nothing (both at goal) | - BOOST_CHECK(!TestShouldPromote(100, 100, goal)); - BOOST_CHECK(!TestShouldDemote(100, 100, goal)); - - // | 90 | 90 | Nothing (deficits equal) | - BOOST_CHECK(!TestShouldPromote(90, 90, goal)); - BOOST_CHECK(!TestShouldDemote(90, 90, goal)); -} - -BOOST_AUTO_TEST_CASE(validate_promotion_entry_edge_cases) -{ - // Additional edge cases for ValidatePromotionEntry - - const int nSessionDenom = 1 << 2; // 0.1 DASH - const int nLargerDenom = CoinJoin::GetLargerAdjacentDenom(nSessionDenom); - const CAmount nLargerAmount = CoinJoin::DenominationToAmount(nLargerDenom); - - // Valid case: exactly 10 inputs, 1 output of correct larger denom - std::vector validVin; - std::vector validVout; - validVin.reserve(CoinJoin::PROMOTION_RATIO); - for (int i = 0; i < CoinJoin::PROMOTION_RATIO; ++i) { - validVin.push_back(MakeDenomInput(static_cast(i))); - } - validVout.push_back(MakeDenomOutput(nLargerAmount)); - - PoolMessage msg = MSG_NOERR; - BOOST_CHECK(CoinJoin::ValidatePromotionEntry(validVin, validVout, nSessionDenom, msg)); - - // Invalid: 9 inputs (wrong count) - std::vector wrongCountVin; - wrongCountVin.reserve(9); - for (int i = 0; i < 9; ++i) { - wrongCountVin.push_back(MakeDenomInput(static_cast(i))); - } - msg = MSG_NOERR; - BOOST_CHECK(!CoinJoin::ValidatePromotionEntry(wrongCountVin, validVout, nSessionDenom, msg)); - - // Invalid: 11 inputs (wrong count) - std::vector tooManyVin; - tooManyVin.reserve(11); - for (int i = 0; i < 11; ++i) { - tooManyVin.push_back(MakeDenomInput(static_cast(i))); - } - msg = MSG_NOERR; - BOOST_CHECK(!CoinJoin::ValidatePromotionEntry(tooManyVin, validVout, nSessionDenom, msg)); - - // Invalid: 2 outputs (should be 1) - std::vector twoOutputs; - twoOutputs.push_back(MakeDenomOutput(nLargerAmount / 2)); - twoOutputs.push_back(MakeDenomOutput(nLargerAmount / 2)); - msg = MSG_NOERR; - BOOST_CHECK(!CoinJoin::ValidatePromotionEntry(validVin, twoOutputs, nSessionDenom, msg)); - - // Invalid: output is wrong denomination - std::vector wrongDenomOut; - wrongDenomOut.push_back(MakeDenomOutput(CoinJoin::DenominationToAmount(nSessionDenom))); // Same denom, not larger - msg = MSG_NOERR; - BOOST_CHECK(!CoinJoin::ValidatePromotionEntry(validVin, wrongDenomOut, nSessionDenom, msg)); -} - -BOOST_AUTO_TEST_CASE(validate_demotion_entry_edge_cases) -{ - // Additional edge cases for ValidateDemotionEntry - - const int nSessionDenom = 1 << 2; // 0.1 DASH (output denom) - const CAmount nSessionAmount = CoinJoin::DenominationToAmount(nSessionDenom); - - // Verify the larger adjacent denom exists for this test to be meaningful - BOOST_CHECK(CoinJoin::GetLargerAdjacentDenom(nSessionDenom) != 0); - - // Valid case: 1 input of larger denom, 10 outputs of session denom - std::vector validVin; - validVin.push_back(MakeDenomInput(0)); - - std::vector validVout; - validVout.reserve(CoinJoin::PROMOTION_RATIO); - for (int i = 0; i < CoinJoin::PROMOTION_RATIO; ++i) { - validVout.push_back(MakeDenomOutput(nSessionAmount, static_cast(i))); - } - - PoolMessage msg = MSG_NOERR; - BOOST_CHECK(CoinJoin::ValidateDemotionEntry(validVin, validVout, nSessionDenom, msg)); - - // Invalid: 2 inputs (should be 1) - std::vector twoInputs; - twoInputs.push_back(MakeDenomInput(0)); - twoInputs.push_back(MakeDenomInput(1)); - msg = MSG_NOERR; - BOOST_CHECK(!CoinJoin::ValidateDemotionEntry(twoInputs, validVout, nSessionDenom, msg)); - - // Invalid: 9 outputs (wrong count) - std::vector nineOutputs; - nineOutputs.reserve(9); - for (int i = 0; i < 9; ++i) { - nineOutputs.push_back(MakeDenomOutput(nSessionAmount, static_cast(i))); - } - msg = MSG_NOERR; - BOOST_CHECK(!CoinJoin::ValidateDemotionEntry(validVin, nineOutputs, nSessionDenom, msg)); - - // Test that demotion from smallest denomination (0.001 DASH) fails - // because there's no smaller denomination to demote to - const int nSmallestDenom = 1 << 4; // 0.001 DASH - BOOST_CHECK_EQUAL(CoinJoin::GetSmallerAdjacentDenom(nSmallestDenom), 0); // No smaller exists -} - // Build an entry of a given shape; only the input/output counts matter for classification static CCoinJoinEntry MakeEntry(size_t nInputs, size_t nOutputs) { diff --git a/src/test/coinjoin_queue_tests.cpp b/src/test/coinjoin_queue_tests.cpp index 258164e724f5..a0a3c496423e 100644 --- a/src/test/coinjoin_queue_tests.cpp +++ b/src/test/coinjoin_queue_tests.cpp @@ -132,17 +132,6 @@ BOOST_AUTO_TEST_CASE(queue_sign_and_verify) BOOST_CHECK(q.CheckSignature(pub)); } -BOOST_AUTO_TEST_CASE(queue_hashes_and_equality) -{ - const auto a{MakeQueue(CoinJoin::AmountToDenomination(CoinJoin::GetSmallestDenomination()), - GetAdjustedTime(), /*fReady=*/true, COutPoint{uint256S("bb"), 2})}; - const auto b{a}; // NOLINT(performance-unnecessary-copy-initialization): the copy is under test - - BOOST_CHECK(a == b); - BOOST_CHECK(a.GetHash() == b.GetHash()); - BOOST_CHECK(a.GetSignatureHash() == b.GetSignatureHash()); -} - BOOST_AUTO_TEST_CASE(queue_denomination_validation) { // Test that valid denominations pass diff --git a/src/test/dip0020opcodes_tests.cpp b/src/test/dip0020opcodes_tests.cpp index 22ed33cbce79..a13a47ab112d 100644 --- a/src/test/dip0020opcodes_tests.cpp +++ b/src/test/dip0020opcodes_tests.cpp @@ -678,15 +678,6 @@ static void CheckDivMod(const valtype& a, const valtype& b, ScriptError::SCRIPT_ERR_UNKNOWN_ERROR); CheckError(flags, {a, {0x00, 0x80}}, CScript() << OP_DIV, ScriptError::SCRIPT_ERR_UNKNOWN_ERROR); - - CheckError(flags, {b, {0x00}}, CScript() << OP_DIV, - ScriptError::SCRIPT_ERR_UNKNOWN_ERROR); - CheckError(flags, {b, {0x80}}, CScript() << OP_DIV, - ScriptError::SCRIPT_ERR_UNKNOWN_ERROR); - CheckError(flags, {b, {0x00, 0x00}}, CScript() << OP_DIV, - ScriptError::SCRIPT_ERR_UNKNOWN_ERROR); - CheckError(flags, {b, {0x00, 0x80}}, CScript() << OP_DIV, - ScriptError::SCRIPT_ERR_UNKNOWN_ERROR); } else { CheckError(flags, {a, {0x00}}, CScript() << OP_DIV, ScriptError::SCRIPT_ERR_DIV_BY_ZERO); @@ -696,15 +687,6 @@ static void CheckDivMod(const valtype& a, const valtype& b, ScriptError::SCRIPT_ERR_DIV_BY_ZERO); CheckError(flags, {a, {0x00, 0x80}}, CScript() << OP_DIV, ScriptError::SCRIPT_ERR_DIV_BY_ZERO); - - CheckError(flags, {b, {0x00}}, CScript() << OP_DIV, - ScriptError::SCRIPT_ERR_DIV_BY_ZERO); - CheckError(flags, {b, {0x80}}, CScript() << OP_DIV, - ScriptError::SCRIPT_ERR_DIV_BY_ZERO); - CheckError(flags, {b, {0x00, 0x00}}, CScript() << OP_DIV, - ScriptError::SCRIPT_ERR_DIV_BY_ZERO); - CheckError(flags, {b, {0x00, 0x80}}, CScript() << OP_DIV, - ScriptError::SCRIPT_ERR_DIV_BY_ZERO); } } @@ -715,12 +697,6 @@ static void CheckDivMod(const valtype& a, const valtype& b, CheckBinaryOp(a, NegativeValtype(a), OP_DIV, {0x81}); CheckBinaryOp(NegativeValtype(a), a, OP_DIV, {0x81}); - CheckBinaryOp(b, {0x01}, OP_DIV, b); - CheckBinaryOp(b, {0x81}, OP_DIV, NegativeValtype(b)); - CheckBinaryOp(b, b, OP_DIV, {0x01}); - CheckBinaryOp(b, NegativeValtype(b), OP_DIV, {0x81}); - CheckBinaryOp(NegativeValtype(b), b, OP_DIV, {0x81}); - // Modulo identities // a % b % b = a % b CheckTestResultForAllFlags( @@ -768,8 +744,6 @@ BOOST_AUTO_TEST_CASE(div_and_mod_opcode_tests) CheckDivMod({0x98, 0x3a}, {0x04}, {0xa6, 0x0e}, {}); // 15000/4000 = 3 (and negative operands) CheckDivMod({0x98, 0x3a}, {0xa0, 0x0f}, {0x03}, {0xb8, 0x0b}); - // 15000000/4000 = 3750 (and negative operands) - CheckDivMod({0xc0, 0xe1, 0xe4, 0x00}, {0xa0, 0x0f}, {0xa6, 0x0e}, {}); // 15000000/4 = 3750000 (and negative operands) CheckDivMod({0xc0, 0xe1, 0xe4, 0x00}, {0x04}, {0x70, 0x38, 0x39}, {}); diff --git a/src/test/evo_assetlocks_tests.cpp b/src/test/evo_assetlocks_tests.cpp index 5a396b83dcf1..099652a43c36 100644 --- a/src/test/evo_assetlocks_tests.cpp +++ b/src/test/evo_assetlocks_tests.cpp @@ -226,7 +226,7 @@ static void CheckAssetLockCommon(uint8_t version, bool is_v24_active) } { - // Sum of credit output greater than OP_RETURN + // Credits must not exceed the OP_RETURN amount std::vector wrongOutput = creditOutputs; wrongOutput[0].nValue += CENT; @@ -235,15 +235,6 @@ static void CheckAssetLockCommon(uint8_t version, bool is_v24_active) BOOST_CHECK(!CheckAssetLockTx(CTransaction(txGreaterCredits), tx_state, is_v24_active)); BOOST_CHECK(tx_state.GetRejectReason() == "bad-assetlocktx-creditamount"); - - // Sum of credit output less than OP_RETURN - wrongOutput[1].nValue -= 2 * CENT; - - CMutableTransaction txLessCredits(baseTx); - SetTxPayload(txLessCredits, CAssetLockPayload(wrongOutput, version)); - - BOOST_CHECK(!CheckAssetLockTx(CTransaction(txLessCredits), tx_state, is_v24_active)); - BOOST_CHECK(tx_state.GetRejectReason() == "bad-assetlocktx-creditamount"); } { diff --git a/src/test/evo_islock_tests.cpp b/src/test/evo_islock_tests.cpp index 43e5d9c99c29..d9d6932f3803 100644 --- a/src/test/evo_islock_tests.cpp +++ b/src/test/evo_islock_tests.cpp @@ -304,74 +304,6 @@ BOOST_AUTO_TEST_CASE(deserialize_instantlock_from_realdata2) 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)) @@ -387,23 +319,18 @@ BOOST_AUTO_TEST_CASE(geninputlockrequestid_serialization_format) 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); + // A null prevout hash and a null output index still hash as outpoints. Both + // ids stay non-null, and they stay distinct from each other. + const COutPoint null_outpoint{uint256{}, 0}; + const COutPoint null_index_outpoint{uint256::ONE, COutPoint::NULL_INDEX}; + const uint256 null_id{instantsend::GenInputLockRequestId(null_outpoint)}; + const uint256 null_index_id{instantsend::GenInputLockRequestId(null_index_outpoint)}; + BOOST_CHECK(!null_id.IsNull()); + BOOST_CHECK(!null_index_id.IsNull()); + BOOST_CHECK(null_id != null_index_id); + BOOST_CHECK(null_id == ::SerializeHash(std::make_pair(std::string_view("inlock"), null_outpoint))); + BOOST_CHECK(null_index_id == ::SerializeHash(std::make_pair(std::string_view("inlock"), null_index_outpoint))); } // Regression test for the islock input cap: an oversized input vector must be diff --git a/src/test/evo_netinfo_tests.cpp b/src/test/evo_netinfo_tests.cpp index 04c6fa39cfe0..72578ea23a8f 100644 --- a/src/test/evo_netinfo_tests.cpp +++ b/src/test/evo_netinfo_tests.cpp @@ -856,19 +856,6 @@ BOOST_AUTO_TEST_CASE(netinfoentry_domain_deser_rejects_oversized_string) BOOST_CHECK_THROW(ds >> entry, std::ios_base::failure); } -BOOST_AUTO_TEST_CASE(domainport_deser_rejects_huge_claimed_length) -{ - // CompactSize claims 1 MiB with no body. Pre-fix this would allocate 1 MiB - // then throw on short-read; post-fix LIMITED_STRING rejects before resize. - // Either way the operation must throw; the important property is that a - // declared length above DOMAIN_MAX_LEN never produces a successful DomainPort. - CDataStream ds(SER_DISK, CLIENT_VERSION); - WriteCompactSize(ds, size_t{1} << 20); - - DomainPort domain; - BOOST_CHECK_THROW(ds >> domain, std::ios_base::failure); -} - BOOST_AUTO_TEST_CASE(extnetinfo_domain_amplification_rejected) { // Simulate the attack shape: ExtNetInfo vector of Domain entries each diff --git a/src/test/llmq_chainlock_tests.cpp b/src/test/llmq_chainlock_tests.cpp index 5a59de65c1d3..dea8c02fc01f 100644 --- a/src/test/llmq_chainlock_tests.cpp +++ b/src/test/llmq_chainlock_tests.cpp @@ -271,29 +271,6 @@ BOOST_AUTO_TEST_CASE(chainlock_edge_cases_test) BOOST_CHECK_EQUAL(clsig2.getHeight(), clsig2_deserialized.getHeight()); } -BOOST_AUTO_TEST_CASE(chainlock_comparison_test) -{ - // Create identical chainlocks - int32_t height = 5000; - uint256 blockHash = GetTestBlockHash(10); - CBLSSignature sig = CreateRandomBLSSignature(); - - ChainLockSig clsig1(height, blockHash, sig); - ChainLockSig clsig2(height, blockHash, sig); - - // Verify getters return same values - BOOST_CHECK_EQUAL(clsig1.getHeight(), clsig2.getHeight()); - BOOST_CHECK(clsig1.getBlockHash() == clsig2.getBlockHash()); - BOOST_CHECK(clsig1.getSig() == clsig2.getSig()); - - // Different chainlocks - ChainLockSig clsig3(height + 1, blockHash, sig); - BOOST_CHECK(clsig1.getHeight() != clsig3.getHeight()); - - ChainLockSig clsig4(height, GetTestBlockHash(11), sig); - BOOST_CHECK(clsig1.getBlockHash() != clsig4.getBlockHash()); -} - BOOST_AUTO_TEST_CASE(chainlock_malformed_data_test) { // Test deserialization of truncated data diff --git a/src/test/llmq_commitment_tests.cpp b/src/test/llmq_commitment_tests.cpp index 53368cdc09ef..06035d1d1ea2 100644 --- a/src/test/llmq_commitment_tests.cpp +++ b/src/test/llmq_commitment_tests.cpp @@ -358,39 +358,4 @@ BOOST_AUTO_TEST_CASE(commitment_tx_payload_test) BOOST_CHECK(!payload.commitment.IsNull()); } -BOOST_AUTO_TEST_CASE(build_commitment_hash_test) -{ - // Test deterministic hash generation - uint256 hash1 = llmq::BuildCommitmentHash(TEST_PARAMS.type, GetTestQuorumHash(1), - CreateBitVector(TEST_PARAMS.size, {0, 1, 2}), CreateRandomBLSPublicKey(), - GetTestQuorumHash(2)); - - // Same inputs should produce same hash - uint256 hash2 = llmq::BuildCommitmentHash(TEST_PARAMS.type, GetTestQuorumHash(1), - CreateBitVector(TEST_PARAMS.size, {0, 1, 2}), CreateRandomBLSPublicKey(), - GetTestQuorumHash(2)); - - // Different quorum hash should produce different hash - uint256 hash3 = llmq::BuildCommitmentHash(TEST_PARAMS.type, - GetTestQuorumHash(2), // Different - CreateBitVector(TEST_PARAMS.size, {0, 1, 2}), CreateRandomBLSPublicKey(), - GetTestQuorumHash(2)); - - BOOST_CHECK(hash1 != hash2); // Different pubkeys - BOOST_CHECK(hash1 != hash3); - BOOST_CHECK(hash2 != hash3); - - // Test with same deterministic data - CBLSPublicKey fixedPubKey = CreateRandomBLSPublicKey(); - uint256 hash4 = llmq::BuildCommitmentHash(TEST_PARAMS.type, GetTestQuorumHash(1), - CreateBitVector(TEST_PARAMS.size, {0, 1, 2}), fixedPubKey, - GetTestQuorumHash(2)); - - uint256 hash5 = llmq::BuildCommitmentHash(TEST_PARAMS.type, GetTestQuorumHash(1), - CreateBitVector(TEST_PARAMS.size, {0, 1, 2}), fixedPubKey, - GetTestQuorumHash(2)); - - BOOST_CHECK(hash4 == hash5); -} - BOOST_AUTO_TEST_SUITE_END() diff --git a/src/test/llmq_snapshot_tests.cpp b/src/test/llmq_snapshot_tests.cpp index 3b6fefd0527b..825cd088567b 100644 --- a/src/test/llmq_snapshot_tests.cpp +++ b/src/test/llmq_snapshot_tests.cpp @@ -51,117 +51,61 @@ BOOST_AUTO_TEST_CASE(quorum_snapshot_construction_test) BOOST_AUTO_TEST_CASE(quorum_snapshot_serialization_test) { - // Test with various configurations std::vector activeMembers = CreateBitVector(10, {0, 2, 4, 6, 8}); - auto skipMode = SnapshotSkipMode::MODE_SKIPPING_ENTRIES; - std::vector skipList = {10, 20, 30}; + const auto skipMode = SnapshotSkipMode::MODE_SKIPPING_ENTRIES; + const std::vector skipList = {10, 20, 30}; CQuorumSnapshot snapshot(activeMembers, skipMode, skipList); + BOOST_CHECK(TestSerializationRoundtrip(snapshot)); - // Test serialization roundtrip CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << snapshot; - CQuorumSnapshot deserialized; ss >> deserialized; - BOOST_CHECK(deserialized.activeQuorumMembers == snapshot.activeQuorumMembers); BOOST_CHECK_EQUAL(deserialized.mnSkipListMode, snapshot.mnSkipListMode); BOOST_CHECK(deserialized.mnSkipList == snapshot.mnSkipList); -} -BOOST_AUTO_TEST_CASE(quorum_snapshot_skip_modes_test) -{ - // Test all skip modes - constexpr std::array skipModes{ - SnapshotSkipMode::MODE_NO_SKIPPING, - SnapshotSkipMode::MODE_SKIPPING_ENTRIES, - SnapshotSkipMode::MODE_NO_SKIPPING_ENTRIES, - SnapshotSkipMode::MODE_ALL_SKIPPED - }; - - for (auto mode : skipModes) { - CQuorumSnapshot snapshot({true, false, true}, mode, {1, 2, 3}); - - CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); - ss << snapshot; - - CQuorumSnapshot deserialized; - ss >> deserialized; - - BOOST_CHECK_EQUAL(deserialized.mnSkipListMode, mode); + for (const auto mode : {SnapshotSkipMode::MODE_NO_SKIPPING, SnapshotSkipMode::MODE_SKIPPING_ENTRIES, + SnapshotSkipMode::MODE_NO_SKIPPING_ENTRIES, SnapshotSkipMode::MODE_ALL_SKIPPED}) { + CQuorumSnapshot mode_snapshot({true, false, true}, mode, {1, 2, 3}); + CDataStream mode_stream(SER_NETWORK, PROTOCOL_VERSION); + mode_stream << mode_snapshot; + CQuorumSnapshot mode_out; + mode_stream >> mode_out; + BOOST_CHECK_EQUAL(mode_out.mnSkipListMode, mode); } -} -BOOST_AUTO_TEST_CASE(quorum_snapshot_large_data_test) -{ - // Test with large quorum (400 members) - std::vector largeActiveMembers(400); - // Create pattern: every 3rd member is inactive - for (size_t i = 0; i < largeActiveMembers.size(); i++) { - largeActiveMembers[i] = (i % 3 != 0); + std::vector large_members(400); + for (size_t i = 0; i < large_members.size(); ++i) { + large_members[i] = (i % 3 != 0); } - - // Create large skip list - std::vector largeSkipList; - largeSkipList.reserve(100); - for (int i = 0; i < 100; i++) { - largeSkipList.push_back(i * 4); + std::vector large_skip; + large_skip.reserve(100); + for (int i = 0; i < 100; ++i) { + large_skip.push_back(i * 4); } - - CQuorumSnapshot snapshot(largeActiveMembers, SnapshotSkipMode::MODE_SKIPPING_ENTRIES, largeSkipList); - - // Test serialization with large data - // Test serialization manually instead of using roundtrip helper - CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); - ss << snapshot; - CQuorumSnapshot deserialized; - ss >> deserialized; - BOOST_CHECK_EQUAL(deserialized.activeQuorumMembers.size(), 400); - BOOST_CHECK_EQUAL(deserialized.mnSkipList.size(), 100); -} - -BOOST_AUTO_TEST_CASE(quorum_snapshot_empty_data_test) -{ - // Test with empty data - CQuorumSnapshot emptySnapshot({}, SnapshotSkipMode::MODE_NO_SKIPPING, {}); - - // Test serialization roundtrip - BOOST_CHECK(TestSerializationRoundtrip(emptySnapshot)); - - // Test with empty active members but non-empty skip list - CQuorumSnapshot snapshot1({}, SnapshotSkipMode::MODE_SKIPPING_ENTRIES, {1, 2, 3}); - BOOST_CHECK(TestSerializationRoundtrip(snapshot1)); - - // Test with non-empty active members but empty skip list - CQuorumSnapshot snapshot2({true, false, true}, SnapshotSkipMode::MODE_NO_SKIPPING, {}); - BOOST_CHECK(TestSerializationRoundtrip(snapshot2)); -} - -BOOST_AUTO_TEST_CASE(quorum_snapshot_bit_serialization_test) -{ - // Test bit vector serialization edge cases - - // Test single bit - CQuorumSnapshot snapshot1({true}, SnapshotSkipMode::MODE_NO_SKIPPING, {}); - BOOST_CHECK(TestSerializationRoundtrip(snapshot1)); - - // Test 8 bits (full byte) - CQuorumSnapshot snapshot8(std::vector(8, true), SnapshotSkipMode::MODE_NO_SKIPPING, {}); - BOOST_CHECK(TestSerializationRoundtrip(snapshot8)); - - // Test 9 bits (more than one byte) - CQuorumSnapshot snapshot9(std::vector(9, false), SnapshotSkipMode::MODE_NO_SKIPPING, {}); - snapshot9.activeQuorumMembers[8] = true; // Set last bit - BOOST_CHECK(TestSerializationRoundtrip(snapshot9)); - - // Test alternating pattern + const CQuorumSnapshot large(large_members, SnapshotSkipMode::MODE_SKIPPING_ENTRIES, large_skip); + CDataStream large_stream(SER_NETWORK, PROTOCOL_VERSION); + large_stream << large; + CQuorumSnapshot large_out; + large_stream >> large_out; + BOOST_CHECK(large_out.activeQuorumMembers == large_members); + BOOST_CHECK(large_out.mnSkipList == large_skip); + + BOOST_CHECK(TestSerializationRoundtrip(CQuorumSnapshot({}, SnapshotSkipMode::MODE_NO_SKIPPING, {}))); + BOOST_CHECK(TestSerializationRoundtrip(CQuorumSnapshot({}, SnapshotSkipMode::MODE_SKIPPING_ENTRIES, {1, 2, 3}))); + BOOST_CHECK(TestSerializationRoundtrip(CQuorumSnapshot({true, false, true}, SnapshotSkipMode::MODE_NO_SKIPPING, {}))); + BOOST_CHECK(TestSerializationRoundtrip(CQuorumSnapshot({true}, SnapshotSkipMode::MODE_NO_SKIPPING, {}))); + BOOST_CHECK(TestSerializationRoundtrip(CQuorumSnapshot(std::vector(8, true), SnapshotSkipMode::MODE_NO_SKIPPING, {}))); + std::vector nine(9, false); + nine[8] = true; + BOOST_CHECK(TestSerializationRoundtrip(CQuorumSnapshot(nine, SnapshotSkipMode::MODE_NO_SKIPPING, {}))); std::vector alternating(16); - for (size_t i = 0; i < alternating.size(); i++) { + for (size_t i = 0; i < alternating.size(); ++i) { alternating[i] = (i % 2 == 0); } - CQuorumSnapshot snapshotAlt(alternating, SnapshotSkipMode::MODE_NO_SKIPPING, {}); - BOOST_CHECK(TestSerializationRoundtrip(snapshotAlt)); + BOOST_CHECK(TestSerializationRoundtrip(CQuorumSnapshot(alternating, SnapshotSkipMode::MODE_NO_SKIPPING, {}))); } BOOST_AUTO_TEST_CASE(quorum_rotation_info_construction_test) diff --git a/src/test/llmq_utils_tests.cpp b/src/test/llmq_utils_tests.cpp index 0978a2e3ba3e..cada9df878b0 100644 --- a/src/test/llmq_utils_tests.cpp +++ b/src/test/llmq_utils_tests.cpp @@ -591,43 +591,4 @@ BOOST_AUTO_TEST_CASE(deterministic_outbound_connection_edge_cases_test) BOOST_CHECK(!connSame.IsNull()); } -// Note: CalcDeterministicWatchConnections requires CBlockIndex which is complex to mock -// Testing is deferred to functional tests - -BOOST_AUTO_TEST_CASE(deterministic_connection_symmetry_test) -{ - // Test interesting properties of DeterministicOutboundConnection - uint256 proTxHash1 = GetTestQuorumHash(1); - uint256 proTxHash2 = GetTestQuorumHash(2); - uint256 proTxHash3 = GetTestQuorumHash(3); - - // Create a "network" of connections - // DeterministicOutboundConnection is symmetric - order doesn't matter - uint256 conn12 = llmq::utils::DeterministicOutboundConnection(proTxHash1, proTxHash2); - uint256 conn21 = llmq::utils::DeterministicOutboundConnection(proTxHash2, proTxHash1); - uint256 conn13 = llmq::utils::DeterministicOutboundConnection(proTxHash1, proTxHash3); - uint256 conn31 = llmq::utils::DeterministicOutboundConnection(proTxHash3, proTxHash1); - uint256 conn23 = llmq::utils::DeterministicOutboundConnection(proTxHash2, proTxHash3); - uint256 conn32 = llmq::utils::DeterministicOutboundConnection(proTxHash3, proTxHash2); - - // Verify symmetry - swapped inputs produce same output - BOOST_CHECK(conn12 == conn21); - BOOST_CHECK(conn13 == conn31); - BOOST_CHECK(conn23 == conn32); - - // Each connection returns one of the two nodes - BOOST_CHECK(conn12 == proTxHash1 || conn12 == proTxHash2); - BOOST_CHECK(conn13 == proTxHash1 || conn13 == proTxHash3); - BOOST_CHECK(conn23 == proTxHash2 || conn23 == proTxHash3); - - // The function deterministically picks which node initiates the connection - // Verify we get consistent results for each pair - std::set uniqueResults; - uniqueResults.insert(conn12); - uniqueResults.insert(conn13); - uniqueResults.insert(conn23); - // Each pair should produce one of its members, but pairs may have overlapping results - BOOST_CHECK(uniqueResults.size() >= 2 && uniqueResults.size() <= 3); -} - BOOST_AUTO_TEST_SUITE_END()