From 3f1353f9d5c9a17a17df92682762d90a8b317996 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 13 Nov 2026 15:28:23 -0600 Subject: [PATCH 01/29] test: pin BLS scheme behaviour ahead of the scheme refactor Pin the decode matrix for public keys and signatures under both schemes, scheme-independent plain aggregation, and scheme-dependent secure aggregation and VerifyInsecure. Pin lazy-wrapper bytes, equality, hashes and the undecoded cross-scheme serialize. Pin null commitments carrying an opposite-scheme-only key, a pre-V19 mainnet quorum commitment and ProUpServTx that verify only under the legacy scheme, the rule that an operator signature is checked under the connecting block's scheme rather than the payload version, per-encoding operator-key uniqueness, and when a state diff records an operator key. Co-Authored-By: Claude Fable 5.2 --- src/test/bls_tests.cpp | 329 ++++++++++++++++++++++++ src/test/evo_deterministicmns_tests.cpp | 196 ++++++++++++++ src/test/llmq_commitment_tests.cpp | 135 ++++++++++ 3 files changed, 660 insertions(+) diff --git a/src/test/bls_tests.cpp b/src/test/bls_tests.cpp index 83715e84f296..33c69ece5203 100644 --- a/src/test/bls_tests.cpp +++ b/src/test/bls_tests.cpp @@ -995,4 +995,333 @@ BOOST_AUTO_TEST_CASE(v19_boundary_validation_failure_restores_bls_scheme) BOOST_CHECK(bls::bls_legacy_scheme.load()); } +namespace { + +// Restores the process-wide scheme. Callers that still read bls::bls_legacy_scheme go through this. +class ScopedBLSScheme +{ +public: + explicit ScopedBLSScheme(bool legacy) : + m_prev{bls::bls_legacy_scheme.load()} + { + bls::bls_legacy_scheme.store(legacy); + } + ~ScopedBLSScheme() { bls::bls_legacy_scheme.store(m_prev); } + ScopedBLSScheme(const ScopedBLSScheme&) = delete; + ScopedBLSScheme& operator=(const ScopedBLSScheme&) = delete; + +private: + bool m_prev; +}; + +CBLSSecretKey SecretFromScalar(uint8_t scalar) +{ + std::vector bytes(32, 0); + bytes.back() = scalar; + CBLSSecretKey sk; + sk.SetBytes(bytes, false); + BOOST_REQUIRE(sk.IsValid()); + return sk; +} + +enum class DecodeKind { + Invalid, + Throws, + Valid +}; + +struct DecodeRow { + const char* name; + const char* hex; + bool legacy; + DecodeKind kind; + // Re-encodings of the decoded point. Null unless kind == Valid. + const char* point_legacy; + const char* point_basic; +}; + +std::string RepeatByteHex(uint8_t byte, size_t size) { return HexStr(std::vector(size, byte)); } + +// Both schemes serialize the identity as 0xc0 followed by zeros. +std::string InfinityHex(size_t size) +{ + std::vector bytes(size, 0); + bytes[0] = 0xc0; + return HexStr(bytes); +} + +template +void CheckDecode(const DecodeRow& row) +{ + const auto bytes = ParseHex(row.hex); + BOOST_REQUIRE_EQUAL(bytes.size(), T::SerSize); + T obj; + CDataStream ds(bytes, SER_NETWORK, PROTOCOL_VERSION); + bool threw = false; + std::string what; + try { + obj.Unserialize(ds, row.legacy); + } catch (const std::ios_base::failure& e) { + threw = true; + what = e.what(); + } + if (row.kind == DecodeKind::Throws) { + BOOST_CHECK(threw); + BOOST_CHECK(what.find("malleable BLS object") != std::string::npos); + return; + } + BOOST_CHECK(!threw); + if (row.kind == DecodeKind::Invalid) { + BOOST_CHECK(!obj.IsValid()); + return; + } + BOOST_REQUIRE(obj.IsValid()); + BOOST_CHECK_EQUAL(obj.ToString(true), row.point_legacy); + BOOST_CHECK_EQUAL(obj.ToString(false), row.point_basic); +} + +// Public key of secret scalar 1, and the different point its basic encoding decodes to under legacy. +const char* PK1_LEG = "17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6b" + "b"; +const char* PK1_BAS = "97f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6b" + "b"; +const char* PK1_BAS_AS_LEG_BAS = "b7f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af" + "00adb22c6bb"; +// Public key of secret scalar 2, and the different point its legacy encoding decodes to under basic. +const char* PK2_LEG = "8572cbea904d67468808c8eb50a9450c9721db309128012543902d0ac358a62ae28f75bb8f1c7c42c39a8c5529bf0f4" + "e"; +const char* PK2_BAS = "a572cbea904d67468808c8eb50a9450c9721db309128012543902d0ac358a62ae28f75bb8f1c7c42c39a8c5529bf0f4" + "e"; +const char* PK2_LEG_AS_BAS_LEG = "0572cbea904d67468808c8eb50a9450c9721db309128012543902d0ac358a62ae28f75bb8f1c7c42c39a8" + "c5529bf0f4e"; +// Legacy signature of scalar 1 over uint256::ONE. Its legacy encoding is not canonical under basic, and its basic encoding is not canonical under legacy. +const char* SIG1_LEG = "8f8cde907769bb0b753efe4dd1cfddd85d8ac1878dc724884347acea5dd5d8f92bbd42a8bd34ecc134951435231d6c1" + "9184450feca2ff2fb723308f7d5c64d3234e64bf508158f99144bed1ed20d34b2db63baaef121b29143102882b6d13a" + "97"; +const char* SIG1_BAS = "b84450feca2ff2fb723308f7d5c64d3234e64bf508158f99144bed1ed20d34b2db63baaef121b29143102882b6d13a9" + "70f8cde907769bb0b753efe4dd1cfddd85d8ac1878dc724884347acea5dd5d8f92bbd42a8bd34ecc134951435231d6c" + "19"; +// Legacy signature of scalar 6 over uint256::ONE. Its basic encoding is canonical under both schemes and decodes to two different points. +const char* SIG6_LEG = "029305a30c9830695358432443b30d29ac40cc60aba2df4df195c4144521613840b984e0ebd5e934d2b00d13b07e813" + "212d170dd5a79b4b1a30b5e345f8a1d14472d40d885c8e55c9406159f5de8909e0b85f923b6290dac61bd6cafcc7f9d" + "ba"; +const char* SIG6_BAS = "92d170dd5a79b4b1a30b5e345f8a1d14472d40d885c8e55c9406159f5de8909e0b85f923b6290dac61bd6cafcc7f9db" + "a029305a30c9830695358432443b30d29ac40cc60aba2df4df195c4144521613840b984e0ebd5e934d2b00d13b07e81" + "32"; +const char* SIG6_BAS_AS_LEG_BAS = "a29305a30c9830695358432443b30d29ac40cc60aba2df4df195c4144521613840b984e0ebd5e934d2b0" + "0d13b07e813212d170dd5a79b4b1a30b5e345f8a1d14472d40d885c8e55c9406159f5de8909e0b85f923" + "b6290dac61bd6cafcc7f9dba"; + +template +void CheckLazy(const Object& point, const Object& other) +{ + const auto legacy_arr = point.ToBytes(true); + const auto basic_arr = point.ToBytes(false); + const auto other_arr = other.ToBytes(true); + const std::vector legacy_bytes(legacy_arr.begin(), legacy_arr.end()); + const std::vector basic_bytes(basic_arr.begin(), basic_arr.end()); + const std::vector other_bytes(other_arr.begin(), other_arr.end()); + const std::vector garbage(Object::SerSize, 0xff); + + for (const bool scheme : {true, false}) { + Lazy lazy; + CDataStream in(garbage, SER_DISK, CLIENT_VERSION); + lazy.Unserialize(in, scheme); + std::vector out; + CVectorWriter writer(SER_DISK, CLIENT_VERSION, out, 0); + BOOST_CHECK_NO_THROW(lazy.Serialize(writer, scheme)); + BOOST_CHECK(out == garbage); + + Lazy invalid; + CDataStream invalid_in(garbage, SER_DISK, CLIENT_VERSION); + invalid.Unserialize(invalid_in, scheme); + const Object* decoded = nullptr; + BOOST_CHECK_NO_THROW(decoded = &invalid.Get()); + BOOST_REQUIRE(decoded != nullptr); + BOOST_CHECK(!decoded->IsValid()); + } + + Lazy legacy_wrapped; + CDataStream legacy_in(legacy_bytes, SER_DISK, CLIENT_VERSION); + legacy_wrapped.Unserialize(legacy_in, true); + Lazy basic_wrapped; + CDataStream basic_in(basic_bytes, SER_DISK, CLIENT_VERSION); + basic_wrapped.Unserialize(basic_in, false); + BOOST_CHECK(legacy_wrapped == basic_wrapped); + + Lazy other_wrapped; + CDataStream other_in(other_bytes, SER_DISK, CLIENT_VERSION); + other_wrapped.Unserialize(other_in, true); + BOOST_CHECK(legacy_wrapped != other_wrapped); + + Lazy unset_a; + Lazy unset_b; + BOOST_CHECK(unset_a == unset_b); + + auto hash_of = [](const std::vector& bytes) { + CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); + ss.write(MakeByteSpan(bytes)); + return ss.GetHash(); + }; + BOOST_CHECK(legacy_wrapped.GetHash() == hash_of(legacy_bytes)); + BOOST_CHECK(basic_wrapped.GetHash() == hash_of(basic_bytes)); + + for (const bool from_legacy : {true, false}) { + Lazy raw; + const auto& bytes = from_legacy ? legacy_bytes : basic_bytes; + CDataStream raw_in(bytes, SER_DISK, CLIENT_VERSION); + raw.Unserialize(raw_in, from_legacy); + std::vector raw_out; + CVectorWriter raw_writer(SER_DISK, CLIENT_VERSION, raw_out, 0); + // Existing behavior, changed by a later commit: an undecoded wrapper serialized under the other scheme writes all zeros. + BOOST_CHECK_NO_THROW(raw.Serialize(raw_writer, !from_legacy)); + const std::vector zeros(Object::SerSize, 0); + BOOST_CHECK(raw_out == zeros); + } +} + +} // namespace + +BOOST_AUTO_TEST_CASE(bls_scheme_decode_matrix) +{ + const std::string pk_zero = RepeatByteHex(0x00, CBLSPublicKey::SerSize); + const std::string pk_inf = InfinityHex(CBLSPublicKey::SerSize); + const std::string pk_ff = RepeatByteHex(0xff, CBLSPublicKey::SerSize); + const DecodeRow pk_rows[]{ + {"pk all-zero", pk_zero.c_str(), true, DecodeKind::Invalid, nullptr, nullptr}, + {"pk all-zero", pk_zero.c_str(), false, DecodeKind::Invalid, nullptr, nullptr}, + {"pk infinity", pk_inf.c_str(), true, DecodeKind::Throws, nullptr, nullptr}, + {"pk infinity", pk_inf.c_str(), false, DecodeKind::Throws, nullptr, nullptr}, + {"pk garbage", pk_ff.c_str(), true, DecodeKind::Throws, nullptr, nullptr}, + {"pk garbage", pk_ff.c_str(), false, DecodeKind::Throws, nullptr, nullptr}, + {"pk1 legacy encoding", PK1_LEG, true, DecodeKind::Valid, PK1_LEG, PK1_BAS}, + {"pk1 legacy encoding", PK1_LEG, false, DecodeKind::Invalid, nullptr, nullptr}, + {"pk1 basic encoding", PK1_BAS, false, DecodeKind::Valid, PK1_LEG, PK1_BAS}, + {"pk1 basic encoding", PK1_BAS, true, DecodeKind::Valid, PK1_BAS, PK1_BAS_AS_LEG_BAS}, + {"pk2 legacy encoding", PK2_LEG, true, DecodeKind::Valid, PK2_LEG, PK2_BAS}, + {"pk2 legacy encoding", PK2_LEG, false, DecodeKind::Valid, PK2_LEG_AS_BAS_LEG, PK2_LEG}, + {"pk2 basic encoding", PK2_BAS, false, DecodeKind::Valid, PK2_LEG, PK2_BAS}, + {"pk2 basic encoding", PK2_BAS, true, DecodeKind::Invalid, nullptr, nullptr}, + }; + for (const auto& row : pk_rows) { + BOOST_TEST_CONTEXT(row.name << " legacy=" << row.legacy) { CheckDecode(row); } + } + + const std::string sig_zero = RepeatByteHex(0x00, CBLSSignature::SerSize); + const std::string sig_inf = InfinityHex(CBLSSignature::SerSize); + const std::string sig_ff = RepeatByteHex(0xff, CBLSSignature::SerSize); + const DecodeRow sig_rows[]{ + {"sig all-zero", sig_zero.c_str(), true, DecodeKind::Invalid, nullptr, nullptr}, + {"sig all-zero", sig_zero.c_str(), false, DecodeKind::Invalid, nullptr, nullptr}, + {"sig infinity", sig_inf.c_str(), true, DecodeKind::Throws, nullptr, nullptr}, + {"sig infinity", sig_inf.c_str(), false, DecodeKind::Throws, nullptr, nullptr}, + {"sig garbage", sig_ff.c_str(), true, DecodeKind::Throws, nullptr, nullptr}, + {"sig garbage", sig_ff.c_str(), false, DecodeKind::Throws, nullptr, nullptr}, + {"sig1 legacy encoding", SIG1_LEG, true, DecodeKind::Valid, SIG1_LEG, SIG1_BAS}, + {"sig1 legacy encoding", SIG1_LEG, false, DecodeKind::Invalid, nullptr, nullptr}, + {"sig1 basic encoding", SIG1_BAS, false, DecodeKind::Valid, SIG1_LEG, SIG1_BAS}, + {"sig1 basic encoding", SIG1_BAS, true, DecodeKind::Invalid, nullptr, nullptr}, + {"sig6 legacy encoding", SIG6_LEG, true, DecodeKind::Valid, SIG6_LEG, SIG6_BAS}, + {"sig6 legacy encoding", SIG6_LEG, false, DecodeKind::Invalid, nullptr, nullptr}, + {"sig6 basic encoding", SIG6_BAS, false, DecodeKind::Valid, SIG6_LEG, SIG6_BAS}, + {"sig6 basic encoding", SIG6_BAS, true, DecodeKind::Valid, SIG6_BAS, SIG6_BAS_AS_LEG_BAS}, + }; + for (const auto& row : sig_rows) { + BOOST_TEST_CONTEXT(row.name << " legacy=" << row.legacy) { CheckDecode(row); } + } +} + +BOOST_AUTO_TEST_CASE(bls_plain_aggregation_scheme_independent) +{ + const auto sk1 = SecretFromScalar(1); + const auto sk2 = SecretFromScalar(2); + const auto pk1 = sk1.GetPublicKey(); + const auto pk2 = sk2.GetPublicKey(); + const auto sig1 = sk1.Sign(uint256::ONE, true); + const auto sig2 = sk2.Sign(uint256::ONE, true); + + CBLSPublicKey pk_member_legacy; + CBLSPublicKey pk_member_basic; + CBLSPublicKey pk_span_legacy; + CBLSPublicKey pk_span_basic; + CBLSSignature sig_member_legacy; + CBLSSignature sig_member_basic; + CBLSSignature sig_span_legacy; + CBLSSignature sig_span_basic; + { + ScopedBLSScheme guard(true); + pk_member_legacy = pk1; + pk_member_legacy.AggregateInsecure(pk2); + std::vector pks{pk1, pk2}; + pk_span_legacy = CBLSPublicKey::AggregateInsecure(pks); + sig_member_legacy = sig1; + sig_member_legacy.AggregateInsecure(sig2); + std::vector sigs{sig1, sig2}; + sig_span_legacy = CBLSSignature::AggregateInsecure(sigs); + } + { + ScopedBLSScheme guard(false); + pk_member_basic = pk1; + pk_member_basic.AggregateInsecure(pk2); + std::vector pks{pk1, pk2}; + pk_span_basic = CBLSPublicKey::AggregateInsecure(pks); + sig_member_basic = sig1; + sig_member_basic.AggregateInsecure(sig2); + std::vector sigs{sig1, sig2}; + sig_span_basic = CBLSSignature::AggregateInsecure(sigs); + } + BOOST_CHECK(pk_member_legacy.IsValid()); + BOOST_CHECK(pk_member_legacy == pk_member_basic); + BOOST_CHECK(pk_span_legacy == pk_span_basic); + BOOST_CHECK(pk_member_legacy == pk_span_legacy); + BOOST_CHECK(sig_member_legacy.IsValid()); + BOOST_CHECK(sig_member_legacy == sig_member_basic); + BOOST_CHECK(sig_span_legacy == sig_span_basic); + BOOST_CHECK(sig_member_legacy == sig_span_legacy); +} + +BOOST_AUTO_TEST_CASE(bls_secure_aggregation_scheme_dependent) +{ + const auto sk1 = SecretFromScalar(1); + const auto sk2 = SecretFromScalar(2); + const uint256 hash = uint256::ONE; + for (const bool scheme : {true, false}) { + std::vector pks{sk1.GetPublicKey(), sk2.GetPublicKey()}; + std::vector sigs{sk1.Sign(hash, scheme), sk2.Sign(hash, scheme)}; + CBLSSignature agg; + { + ScopedBLSScheme guard(scheme); + agg = CBLSSignature::AggregateSecure(sigs, pks, hash); + BOOST_CHECK(agg.IsValid()); + BOOST_CHECK(agg.VerifySecureAggregated(pks, hash)); + } + { + ScopedBLSScheme guard(!scheme); + BOOST_CHECK(!agg.VerifySecureAggregated(pks, hash)); + } + } +} + +BOOST_AUTO_TEST_CASE(bls_verify_insecure_scheme_dependent) +{ + const auto sk = SecretFromScalar(1); + const auto pk = sk.GetPublicKey(); + const uint256 hash = uint256::ONE; + const auto legacy_sig = sk.Sign(hash, true); + const auto basic_sig = sk.Sign(hash, false); + BOOST_CHECK(legacy_sig.VerifyInsecure(pk, hash, true)); + BOOST_CHECK(!legacy_sig.VerifyInsecure(pk, hash, false)); + BOOST_CHECK(basic_sig.VerifyInsecure(pk, hash, false)); + BOOST_CHECK(!basic_sig.VerifyInsecure(pk, hash, true)); +} + +BOOST_AUTO_TEST_CASE(bls_lazy_wrapper_scheme_bytes) +{ + const auto sk1 = SecretFromScalar(1); + const auto sk2 = SecretFromScalar(2); + const uint256 hash = uint256::ONE; + CheckLazy(sk1.GetPublicKey(), sk2.GetPublicKey()); + CheckLazy(sk1.Sign(hash, true), sk2.Sign(hash, true)); +} + BOOST_AUTO_TEST_SUITE_END() diff --git a/src/test/evo_deterministicmns_tests.cpp b/src/test/evo_deterministicmns_tests.cpp index b3842b7ffca6..f6940adebbf3 100644 --- a/src/test/evo_deterministicmns_tests.cpp +++ b/src/test/evo_deterministicmns_tests.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -4447,6 +4448,201 @@ BOOST_AUTO_TEST_CASE(statediff_captures_operator_key_reencoding) BOOST_CHECK(::SerializeHash(reconstructed.pubKeyOperator) == ::SerializeHash(b.pubKeyOperator)); } } + + { + BOOST_TEST_CONTEXT("different operator key") + { + CBLSSecretKey other; + other.MakeNewKey(); + CDeterministicMNState changed_from; + changed_from.nVersion = ProTxVersion::LegacyBLS; + changed_from.pubKeyOperator.Set(sk.GetPublicKey(), /*specificLegacyScheme=*/true); + changed_from.netInfo = NetInfoInterface::MakeNetInfo(changed_from.nVersion); + CDeterministicMNState changed_to{changed_from}; + changed_to.pubKeyOperator.Set(other.GetPublicKey(), /*specificLegacyScheme=*/true); + const CDeterministicMNStateDiff diff{changed_from, changed_to}; + BOOST_CHECK(diff.fields & CDeterministicMNStateDiff::Field_pubKeyOperator); + } + } + { + BOOST_TEST_CONTEXT("unchanged operator key") + { + CDeterministicMNState unchanged; + unchanged.nVersion = ProTxVersion::LegacyBLS; + unchanged.pubKeyOperator.Set(sk.GetPublicKey(), /*specificLegacyScheme=*/true); + unchanged.netInfo = NetInfoInterface::MakeNetInfo(unchanged.nVersion); + const CDeterministicMNState copy{unchanged}; + const CDeterministicMNStateDiff diff{unchanged, copy}; + BOOST_CHECK((diff.fields & CDeterministicMNStateDiff::Field_pubKeyOperator) == 0); + } + } +} + +BOOST_AUTO_TEST_CASE(proupserv_mainnet_pre_v19_verifies_legacy_only) +{ + // Mainnet height 1898717, txid b227237ecf56d44e5f1cc69ae87e73a75c80a9c1cc6959faad4232fd22f5efc5. + const std::string raw_tx = + "030002000176aae4e31867298db9e95e158f97603cd304c502a3298a5e655207bd72f84af5000000006a473044022002233382e7c2c48e" + "e382404a961ae592310806b7817bb85dfd7e7a8dd4029bf602205d5b5a513e1ae44af571cf84752f13ebd93f8e304711f589860e56a779" + "c3ff7e012103b40af40be1b2a12d9a7296c990750878832d146fd686b5776a9fd4d961820a3afeffffff01a6820100000000001976a914" + "56e5b213afbc7879e9932223f1f18a6e3606d5bf88ac00000000b5010086bda1a615c1d3c1f57ff42a3ea4fc4236eb9c3693350ca31272" + "9abf7c72b89400000000000000000000ffff6c3daa8b270f007e82b17db3f564a6b8051b49b6d3f0d08ac019ee30a09ecc6216678d39d7" + "a363805c989927a85cdcfc41b0c8afa06635682d1639544de64301d5d6bb16e5f4ef1c2c2cc702fdd84a6853f60631cd5b540355a09ff0" + "d293a1547ad021c0d09baa8e305b55e4cea97a4f3a555e3330ed999833242dcd823cc07b781ccfef03a75c"; + CMutableTransaction mtx; + BOOST_REQUIRE(DecodeHexTx(mtx, raw_tx)); + const auto payload = GetTxPayload(CTransaction{mtx}); + BOOST_REQUIRE(payload); + CBLSPublicKey operator_key; + BOOST_REQUIRE(operator_key.SetHexStr("1379c53e87019f8a6082ef5083f66955e65a646412721d557be40b4ab4014fa95066c4e627bbf" + "a7bd77b4ccb8d37cc05", + /*specificLegacyScheme=*/true)); + const uint256 hash{::SerializeHash(*payload)}; + BOOST_CHECK(payload->sig.VerifyInsecure(operator_key, hash, /*specificLegacyScheme=*/true)); + BOOST_CHECK(!payload->sig.VerifyInsecure(operator_key, hash, /*specificLegacyScheme=*/false)); +} + +void FuncProUpServSignatureFollowsBlockHeight(TestChainV19BeforeActivationSetup& setup) +{ + struct ScopedBLSScheme { + bool prev; + explicit ScopedBLSScheme(bool legacy) : + prev{bls::bls_legacy_scheme.load()} + { + bls::bls_legacy_scheme.store(legacy); + } + ~ScopedBLSScheme() { bls::bls_legacy_scheme.store(prev); } + }; + + auto& chainman = *Assert(setup.m_node.chainman.get()); + auto& dmnman = *Assert(setup.m_node.dmnman); + const CScript coinbase_pk = GetScriptForRawPubKey(setup.coinbaseKey.GetPubKey()); + auto sync_tip = [&] { dmnman.UpdatedBlockTip(WITH_LOCK(::cs_main, return chainman.ActiveChain().Tip())); }; + + // The fixture stops five blocks before the block whose connect switches the scheme. + // Register before that block so the pre-switch checks still see a legacy tip. + for (int i = 0; i < 3; ++i) { + setup.CreateAndProcessBlock({}, coinbase_pk); + sync_tip(); + } + BOOST_REQUIRE(bls::bls_legacy_scheme.load()); + + auto utxos = BuildSimpleUtxoMap(setup.m_coinbase_txns); + CKey owner_key; + CBLSSecretKey operator_key; + auto tx_reg = CreateProRegTx(chainman, utxos, /*port=*/21001, GenerateRandomAddress(), setup.coinbaseKey, owner_key, + operator_key); + const uint256 proTxHash{tx_reg.GetHash()}; + setup.CreateAndProcessBlock({tx_reg}, coinbase_pk); + sync_tip(); + BOOST_REQUIRE(bls::bls_legacy_scheme.load()); + const auto registered = dmnman.GetListAtChainTip().GetMN(proTxHash); + BOOST_REQUIRE(registered); + BOOST_REQUIRE(registered->pdmnState->nVersion == ProTxVersion::LegacyBLS); + + int port{21002}; + auto make_upserv = [&](bool sign_legacy) { + ScopedBLSScheme guard(sign_legacy); + auto tx = CreateProUpServTx(chainman, utxos, proTxHash, operator_key, port++, CScript(), setup.coinbaseKey, + ProTxVersion::LegacyBLS); + if (tx.vout.size() >= 2) { + utxos.emplace(COutPoint(tx.GetHash(), tx.vout.size() - 1), Coin(tx.vout.back(), /*nHeightIn=*/1, false)); + } + return tx; + }; + auto check = [&](const CMutableTransaction& tx) { + TxValidationState state; + LOCK(cs_main); + const bool ok = CheckProUpServTx(CTransaction(tx), chainman.ActiveChain().Tip(), dmnman, + chainman.GetConsensus(), TipRules(chainman), state, /*check_sigs=*/true); + return std::pair{ok, state.GetRejectReason()}; + }; + + { + const auto [ok, reason] = check(make_upserv(/*sign_legacy=*/true)); + BOOST_CHECK_MESSAGE(ok, reason); + } + { + const auto [ok, reason] = check(make_upserv(/*sign_legacy=*/false)); + BOOST_CHECK(!ok); + BOOST_CHECK_EQUAL(reason, "bad-protx-sig"); + } + + setup.CreateAndProcessBlock({}, coinbase_pk); + sync_tip(); + BOOST_REQUIRE(!bls::bls_legacy_scheme.load()); + BOOST_REQUIRE(dmnman.GetListAtChainTip().GetMN(proTxHash)->pdmnState->nVersion == ProTxVersion::LegacyBLS); + + { + const auto [ok, reason] = check(make_upserv(/*sign_legacy=*/false)); + BOOST_CHECK_MESSAGE(ok, reason); + } + { + const auto [ok, reason] = check(make_upserv(/*sign_legacy=*/true)); + BOOST_CHECK(!ok); + BOOST_CHECK_EQUAL(reason, "bad-protx-sig"); + } +} + +BOOST_AUTO_TEST_CASE(proupserv_signature_scheme_follows_block_height) +{ + TestChainV19BeforeActivationSetup setup; + FuncProUpServSignatureFollowsBlockHeight(setup); +} + +BOOST_AUTO_TEST_CASE(operator_key_uniqueness_is_per_encoding) +{ + CBLSSecretKey key_p; + key_p.MakeNewKey(); + CBLSSecretKey key_q; + key_q.MakeNewKey(); + const CBLSPublicKey p = key_p.GetPublicKey(); + const CBLSPublicKey q = key_q.GetPublicKey(); + + auto make_mn = [](uint64_t internal_id, uint8_t tag, const CBLSPublicKey& pubkey, bool legacy) { + auto state = std::make_shared(); + state->nVersion = legacy ? ProTxVersion::LegacyBLS : ProTxVersion::BasicBLS; + state->pubKeyOperator.Set(pubkey, /*specificLegacyScheme=*/legacy); + uint160 owner_id; + owner_id.begin()[0] = tag; + state->keyIDOwner = CKeyID{owner_id}; + state->keyIDVoting = state->keyIDOwner; + state->netInfo = NetInfoInterface::MakeNetInfo(state->nVersion); + auto dmn = std::make_shared(internal_id); + uint256 protx; + protx.begin()[0] = tag; + dmn->proTxHash = protx; + dmn->collateralOutpoint = COutPoint(protx, 1); + dmn->pdmnState = std::move(state); + return dmn; + }; + + CDeterministicMNList list; + const auto mn_p = make_mn(1, 1, p, /*legacy=*/true); + const auto mn_q = make_mn(2, 2, q, /*legacy=*/false); + list.AddMN(mn_p); + list.AddMN(mn_q); + BOOST_REQUIRE(mn_p->pdmnState->pubKeyOperator.IsLegacy()); + BOOST_REQUIRE(!mn_q->pdmnState->pubKeyOperator.IsLegacy()); + + auto expect_found = [&](const CBLSPublicKey& pubkey, bool legacy, const uint256& protx) { + CBLSLazyPublicKey wrapped; + wrapped.Set(pubkey, /*specificLegacyScheme=*/legacy); + BOOST_CHECK_EQUAL(list.HasUniqueProperty(wrapped), !protx.IsNull()); + const auto found = list.GetUniquePropertyMN(wrapped); + if (protx.IsNull()) { + BOOST_CHECK(!found); + } else { + BOOST_REQUIRE(found); + BOOST_CHECK(found->proTxHash == protx); + } + }; + expect_found(p, /*legacy=*/true, mn_p->proTxHash); + expect_found(p, /*legacy=*/false, uint256()); + expect_found(q, /*legacy=*/false, mn_q->proTxHash); + expect_found(q, /*legacy=*/true, uint256()); + BOOST_CHECK(list.HasOperatorKeyUnderAnyScheme(p, uint256())); + BOOST_CHECK(list.HasOperatorKeyUnderAnyScheme(q, uint256())); } BOOST_AUTO_TEST_CASE(has_operator_key_under_any_scheme) diff --git a/src/test/llmq_commitment_tests.cpp b/src/test/llmq_commitment_tests.cpp index 53368cdc09ef..e1c22a690a8a 100644 --- a/src/test/llmq_commitment_tests.cpp +++ b/src/test/llmq_commitment_tests.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -393,4 +394,138 @@ BOOST_AUTO_TEST_CASE(build_commitment_hash_test) BOOST_CHECK(hash4 == hash5); } +namespace { + +class ScopedBLSScheme +{ +public: + explicit ScopedBLSScheme(bool legacy) : + m_prev{bls::bls_legacy_scheme.load()} + { + bls::bls_legacy_scheme.store(legacy); + } + ~ScopedBLSScheme() { bls::bls_legacy_scheme.store(m_prev); } + ScopedBLSScheme(const ScopedBLSScheme&) = delete; + ScopedBLSScheme& operator=(const ScopedBLSScheme&) = delete; + +private: + bool m_prev; +}; + +CBLSSecretKey SecretFromScalar(uint8_t scalar) +{ + std::vector bytes(32, 0); + bytes.back() = scalar; + CBLSSecretKey sk; + sk.SetBytes(bytes, false); + BOOST_REQUIRE(sk.IsValid()); + return sk; +} + +CFinalCommitment NullSizedCommitment(uint16_t version, const CBLSPublicKey& pubkey) +{ + const auto params = Params().GetLLMQ(Consensus::LLMQType::LLMQ_50_60); + BOOST_REQUIRE(params); + CFinalCommitment commitment; + commitment.nVersion = version; + commitment.llmqType = params->type; + commitment.signers.assign(params->size, false); + commitment.validMembers.assign(params->size, false); + commitment.quorumPublicKey = pubkey; + return commitment; +} + +CFinalCommitment RoundTripWithVersion(const CFinalCommitment& commitment, uint16_t wire_version) +{ + std::vector buf; + CVectorWriter ds(SER_NETWORK, PROTOCOL_VERSION, buf, 0); + ds << commitment; + BOOST_REQUIRE_GE(buf.size(), 2U); + BOOST_REQUIRE_EQUAL(buf[0], static_cast(commitment.nVersion)); + BOOST_REQUIRE_EQUAL(buf[1], 0); + buf[0] = static_cast(wire_version); + buf[1] = static_cast(wire_version >> 8); + CDataStream in(buf, SER_NETWORK, PROTOCOL_VERSION); + CFinalCommitment out; + BOOST_CHECK_NO_THROW(in >> out); + BOOST_CHECK(in.empty()); + return out; +} + +} // namespace + +BOOST_AUTO_TEST_CASE(commitment_opposite_scheme_pubkey_deserializes_null) +{ + // Scalar 1's legacy encoding is canonical only under legacy. A basic-version + // commitment carrying those bytes must drop the key instead of throwing. + const auto legacy_only = NullSizedCommitment(CFinalCommitment::LEGACY_BLS_NON_INDEXED_QUORUM_VERSION, + SecretFromScalar(1).GetPublicKey()); + const auto as_basic = RoundTripWithVersion(legacy_only, CFinalCommitment::BASIC_BLS_NON_INDEXED_QUORUM_VERSION); + BOOST_CHECK(!as_basic.quorumPublicKey.IsValid()); + BOOST_CHECK(!as_basic.quorumSig.IsValid()); + BOOST_CHECK(!as_basic.membersSig.IsValid()); + BOOST_CHECK(as_basic.IsNull()); + BOOST_CHECK(as_basic.VerifyNull()); + + // Scalar 2's basic encoding is canonical only under basic. Mirror case. + const auto basic_only = NullSizedCommitment(CFinalCommitment::BASIC_BLS_NON_INDEXED_QUORUM_VERSION, + SecretFromScalar(2).GetPublicKey()); + const auto as_legacy = RoundTripWithVersion(basic_only, CFinalCommitment::LEGACY_BLS_NON_INDEXED_QUORUM_VERSION); + BOOST_CHECK(!as_legacy.quorumPublicKey.IsValid()); + BOOST_CHECK(!as_legacy.quorumSig.IsValid()); + BOOST_CHECK(!as_legacy.membersSig.IsValid()); + BOOST_CHECK(as_legacy.IsNull()); + BOOST_CHECK(as_legacy.VerifyNull()); +} + +BOOST_AUTO_TEST_CASE(commitment_mainnet_pre_v19_verifies_legacy_only) +{ + // Mainnet height 1898412, txid 2f9731e46562f18dd1b135b14433b3927e4d3ccc0fb89ecdf27ec8532b44b8d0. + const std::string raw_tx = + "03000600000000000000fd55010100acf71c00010004ecf84b2fa47aa7a68074c6002e40d27650465704c0e386700f0000000000000064" + "ffffffffffffffffffffffff0f64ffffffffffffffffffffffff0f0ee6b155297c084fd6ae7a1551ed69587479c8210007fd86275723a5" + "f1ea9816faa80da16d18563489e450b9e6fbbb880e1334987cccb3bda273adc5e9d0c335d664e9bb25208ac80e304c1fcdf207db827bd1" + "63b2a93ea99df01c01c4fb892fe1207ec35f126fc0fe6e52698f59d5005f03af5b0aafd109822d3e1ba616c63a0f0fb3081c4b615696cd" + "f2b28af910790b89791ebad4b747607195f91b95d4b60596c69aee3845cc49ff4818323d358f806458face507e60f8412792251a7d5b9b" + "edd62cb27dd48378dd97b52e585845b7c7fa9fe54afe024fb5ca481e38b5d10dd928dd3b459d0057cda002b52d4819f3e37b4cf2a1319d" + "a0c4142aff6d244109907c9757fed010503d746c4a6ec6e7"; + CMutableTransaction mtx; + BOOST_REQUIRE(DecodeHexTx(mtx, raw_tx)); + const auto payload = GetTxPayload(CTransaction{mtx}); + BOOST_REQUIRE(payload); + const auto& qc = payload->commitment; + const auto json = qc.ToJson(); + BOOST_CHECK_EQUAL(payload->nHeight, 1898412U); + BOOST_CHECK_EQUAL(json["version"].getInt(), 1); + BOOST_CHECK_EQUAL(json["llmqType"].getInt(), 4); + BOOST_CHECK_EQUAL(json["quorumHash"].get_str(), "000000000000000f7086e3c00457465076d2402e00c67480a6a77aa42f4bf8ec"); + BOOST_CHECK_EQUAL(json["quorumPublicKey"].get_str(), "0ee6b155297c084fd6ae7a1551ed69587479c8210007fd86275723a5f1ea9" + "816faa80da16d18563489e450b9e6fbbb88"); + BOOST_CHECK_EQUAL(json["quorumVvecHash"].get_str(), + "db07f2cd1f4c300ec88a2025bbe964d635c3d0e9c5ad73a2bdb3cc7c9834130e"); + BOOST_CHECK_EQUAL(json["quorumSig"].get_str(), "827bd163b2a93ea99df01c01c4fb892fe1207ec35f126fc0fe6e52698f59d5005f0" + "3af5b0aafd109822d3e1ba616c63a0f0fb3081c4b615696cdf2b28af910790b8979" + "1ebad4b747607195f91b95d4b60596c69aee3845cc49ff4818323d358f"); + BOOST_CHECK_EQUAL(json["validMembers"].get_str(), "ffffffffffffffffffffffff0f"); + BOOST_CHECK_EQUAL(json["validMembersCount"].getInt(), 100); + + uint256 hash_legacy; + uint256 hash_basic; + { + ScopedBLSScheme guard(true); + hash_legacy = BuildCommitmentHash(qc.llmqType, qc.quorumHash, qc.validMembers, qc.quorumPublicKey, + qc.quorumVvecHash); + } + { + ScopedBLSScheme guard(false); + hash_basic = BuildCommitmentHash(qc.llmqType, qc.quorumHash, qc.validMembers, qc.quorumPublicKey, + qc.quorumVvecHash); + } + BOOST_CHECK(hash_legacy != hash_basic); + BOOST_CHECK(qc.quorumSig.VerifyInsecure(qc.quorumPublicKey, hash_legacy, true)); + BOOST_CHECK(!qc.quorumSig.VerifyInsecure(qc.quorumPublicKey, hash_legacy, false)); + BOOST_CHECK(!qc.quorumSig.VerifyInsecure(qc.quorumPublicKey, hash_basic, true)); + BOOST_CHECK(!qc.quorumSig.VerifyInsecure(qc.quorumPublicKey, hash_basic, false)); +} + BOOST_AUTO_TEST_SUITE_END() From ddc59008d9c8c825b982d856a3e3d3e2579ada66 Mon Sep 17 00:00:00 2001 From: pasta Date: Fri, 13 Nov 2026 15:53:48 -0600 Subject: [PATCH 02/29] refactor(bls): replace bool scheme arguments with BLSScheme Every BLS wrapper call that selected a scheme took a bare bool, named specificLegacyScheme in most places, is_legacy or legacy in others, and the same position meant modOrder for secret keys. Use a scoped enum so a scheme argument cannot be confused with another flag and every legacy use is greppable. The three version wrapper classes collapse into one BLSEncoded, and the version-to-scheme mapping for provider transactions and final commitments moves into one helper each instead of being spelled out at every serializer. No behaviour change: each call selects the scheme it selected before, and implicit reads of the process-wide flag go through GetAmbientBLSScheme(). Co-Authored-By: Claude Fable 5.2 --- src/Makefile.am | 1 + src/active/dkgsession.cpp | 6 +- src/active/dkgsession.h | 2 +- src/active/masternode.cpp | 13 +- src/active/masternode.h | 2 +- src/bench/bls.cpp | 10 +- src/bench/bls_dkg.cpp | 6 +- src/bls/bls.cpp | 29 +- src/bls/bls.h | 170 ++++------ src/bls/bls_ies.cpp | 6 +- src/bls/bls_worker.cpp | 5 +- src/bls/scheme.h | 15 + src/chainlock/clsig.cpp | 6 +- src/coinjoin/coinjoin.cpp | 4 +- src/evo/deterministicmns.h | 4 +- src/evo/dmnstate.h | 7 +- src/evo/mnauth.cpp | 6 +- src/evo/mnhftx.h | 2 +- src/evo/providertx.cpp | 3 +- src/evo/providertx.h | 38 +-- src/evo/providertx_service.cpp | 19 +- src/evo/simplifiedmns.h | 13 +- src/evo/snapshot.h | 13 +- src/evo/specialtxman.cpp | 2 +- src/evo/types.h | 8 + src/governance/object.cpp | 4 +- src/governance/vote.cpp | 8 +- src/llmq/commitment.h | 20 +- src/llmq/core_write.cpp | 6 +- src/llmq/dkgmessages.h | 6 +- src/llmq/dkgsession.h | 2 +- src/llmq/dkgsessionmgr.cpp | 4 +- src/llmq/quorumproofs.cpp | 10 +- src/llmq/quorums.cpp | 4 +- src/llmq/signing.h | 9 +- src/llmq/signing_shares.cpp | 4 +- src/masternode/meta.h | 2 +- src/node/interfaces.cpp | 2 +- src/node/miner.cpp | 2 +- src/qt/masternodedialogs.cpp | 12 +- src/qt/masternodemodel.cpp | 14 +- src/qt/masternodemodel.h | 5 +- src/qt/masternodewidgets.cpp | 6 +- src/qt/masternodewizard.cpp | 3 +- src/qt/mnsharesession.cpp | 2 +- src/qt/sharedmncreatedialog.cpp | 2 +- src/qt/sharedmndialogs.cpp | 9 +- src/qt/test/masternodemaintenancetests.cpp | 46 +-- src/qt/test/masternodetestutil.cpp | 4 +- src/qt/test/masternodewidgettests.cpp | 2 +- src/qt/test/mnsharesessiontests.cpp | 3 +- src/qt/test/sharedmnwizardtests.cpp | 8 +- src/rpc/evo.cpp | 10 +- src/rpc/governance.cpp | 2 +- src/rpc/node.cpp | 2 +- src/rpc/quorums.cpp | 26 +- src/test/blockfilter_tests.cpp | 6 +- src/test/bls_tests.cpp | 292 +++++++++--------- src/test/coinjoin_queue_tests.cpp | 3 +- src/test/evo_assetlocks_tests.cpp | 4 +- src/test/evo_cbtx_tests.cpp | 2 +- src/test/evo_deterministicmns_tests.cpp | 112 +++---- src/test/evo_islock_tests.cpp | 4 +- src/test/evo_mnhf_tests.cpp | 5 +- src/test/evo_sharedmn_tests.cpp | 4 +- src/test/evo_simplifiedmns_tests.cpp | 4 +- src/test/evo_snapshot_tests.cpp | 29 +- src/test/evo_trivialvalidation.cpp | 2 +- src/test/governance_vote_processing_tests.cpp | 8 +- src/test/governance_vote_sync_tests.cpp | 2 +- src/test/interfaces_tests.cpp | 6 +- src/test/llmq_chainlock_tests.cpp | 4 +- src/test/llmq_commitment_tests.cpp | 10 +- src/test/llmq_dkg_tests.cpp | 6 +- src/test/llmq_utils_tests.cpp | 14 +- src/test/quorum_proofs_tests.cpp | 10 +- src/test/util/llmq_tests.h | 2 +- src/test/util/masternode.cpp | 2 +- src/txmempool.cpp | 4 +- test/util/data/non-backported.txt | 1 + 80 files changed, 577 insertions(+), 588 deletions(-) create mode 100644 src/bls/scheme.h diff --git a/src/Makefile.am b/src/Makefile.am index 4bd5da7cdc72..6736b8e2bd3a 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -955,6 +955,7 @@ libbitcoin_consensus_a_SOURCES = \ arith_uint256.h \ bls/bls.cpp \ bls/bls.h \ + bls/scheme.h \ consensus/amount.h \ consensus/merkle.cpp \ consensus/merkle.h \ diff --git a/src/active/dkgsession.cpp b/src/active/dkgsession.cpp index 1fdad45fd7d5..e321bdf55119 100644 --- a/src/active/dkgsession.cpp +++ b/src/active/dkgsession.cpp @@ -32,7 +32,9 @@ ActiveDKGSession::ActiveDKGSession(CBLSWorker& bls_worker, CDeterministicMNManag m_mn_metaman{mn_metaman}, m_mn_activeman{mn_activeman}, m_sporkman{sporkman}, - m_use_legacy_bls{!DeploymentActiveAfter(m_quorum_base_block_index, Params().GetConsensus(), Consensus::DEPLOYMENT_V19)} + m_use_legacy_bls{DeploymentActiveAfter(m_quorum_base_block_index, Params().GetConsensus(), Consensus::DEPLOYMENT_V19) + ? BLSScheme::Basic + : BLSScheme::Legacy} { } @@ -166,7 +168,7 @@ void ActiveDKGSession::VerifyPendingContributions() } memberIndexes.emplace_back(idx); vvecs.emplace_back(receivedVvecs[idx]); - anyLegacyVvec |= receivedVvecsLegacyScheme[idx]; + anyLegacyVvec |= receivedVvecsLegacyScheme[idx] == BLSScheme::Legacy; skContributions.emplace_back(receivedSkContributions[idx]); // Write here to definitely store one contribution for each member no matter if // our share is valid or not, could be that others are still correct diff --git a/src/active/dkgsession.h b/src/active/dkgsession.h index 6ea2f71a510d..0bf4a90fab71 100644 --- a/src/active/dkgsession.h +++ b/src/active/dkgsession.h @@ -20,7 +20,7 @@ class ActiveDKGSession final : public llmq::CDKGSession CMasternodeMetaMan& m_mn_metaman; const CActiveMasternodeManager& m_mn_activeman; const CSporkManager& m_sporkman; - const bool m_use_legacy_bls{false}; + const BLSScheme m_use_legacy_bls{BLSScheme::Basic}; public: ActiveDKGSession() = delete; diff --git a/src/active/masternode.cpp b/src/active/masternode.cpp index 20561768e686..3ebde84c899d 100644 --- a/src/active/masternode.cpp +++ b/src/active/masternode.cpp @@ -59,8 +59,7 @@ CActiveMasternodeManager::CActiveMasternodeManager(CConnman& connman, CDetermini { assert(sk.IsValid()); /* We can assume pk is valid if sk is valid */ LogPrintf("MASTERNODE:\n blsPubKeyOperator legacy: %s\n blsPubKeyOperator basic: %s\n", - m_operator_pk.ToString(/*specificLegacyScheme=*/true), - m_operator_pk.ToString(/*specificLegacyScheme=*/false)); + m_operator_pk.ToString(BLSScheme::Legacy), m_operator_pk.ToString(BLSScheme::Basic)); } CActiveMasternodeManager::~CActiveMasternodeManager() = default; @@ -288,21 +287,21 @@ template bool CActiveMasternodeManager::Decrypt(const CBLSIESEncryptedObject& obj, size_t idx, CBLSSecretKey& ret_obj, int version) const; -[[nodiscard]] CBLSSignature CActiveMasternodeManager::Sign(const uint256& hash, const bool is_legacy) const +[[nodiscard]] CBLSSignature CActiveMasternodeManager::Sign(const uint256& hash, const BLSScheme scheme) const { AssertLockNotHeld(cs); - return WITH_READ_LOCK(cs, return m_operator_sk.Sign(hash, is_legacy)); + return WITH_READ_LOCK(cs, return m_operator_sk.Sign(hash, scheme)); } [[nodiscard]] std::vector CActiveMasternodeManager::SignBasic(const uint256& hash) const { AssertLockNotHeld(cs); - auto sig = Sign(hash, /*is_legacy=*/false); + auto sig = Sign(hash, BLSScheme::Basic); assert(sig.IsValid()); - return sig.ToByteVector(/*specificLegacyScheme=*/false); + return sig.ToByteVector(BLSScheme::Basic); } -// We need to pass a copy as opposed to a const ref because CBLSPublicKeyVersionWrapper +// We need to pass a copy as opposed to a const ref because BLSEncoded // does not accept a const ref in its construction args [[nodiscard]] CBLSPublicKey CActiveMasternodeManager::GetPubKey() const { diff --git a/src/active/masternode.h b/src/active/masternode.h index e189fba0ea02..11939907de68 100644 --- a/src/active/masternode.h +++ b/src/active/masternode.h @@ -61,7 +61,7 @@ class CActiveMasternodeManager template