From c59b445ac166be39c007a81dc59bba2e91f31f91 Mon Sep 17 00:00:00 2001 From: DanS Date: Wed, 18 Nov 2026 10:33:00 -0600 Subject: [PATCH] zaddr: reject Sapling addresses that cannot receive funds DecodePaymentAddress accepted any 43 bytes with a valid bech32 checksum. An address whose diversifier has no valid g_d, or whose pk_d is not a point in Jubjub's prime-order subgroup, can never receive a note, yet z_validateaddress reported it as valid and z_sendmany queued the send. The async operation then failed in TransactionBuilder::Build ("Invalid sapling note commitment!", surfaced as "Failed to build transaction.") and took every other recipient in the batch with it. A mining pool's payouts stalled for 10.5 hours on one such miner address. Add SaplingPaymentAddress::is_valid(), which runs librustzcash_sapling_compute_cm: the same check the builder runs on every output. DecodePaymentAddress now returns InvalidEncoding when it fails. As a result: - z_validateaddress returns isvalid:false for these addresses. - z_sendmany fails up front with -8 "unknown address format: ". - Every other RPC and startup option that takes a zaddr rejects them through its existing invalid-address path. The check is the builder's own, so it cannot reject an address the builder would accept. Wallet-derived addresses are always valid, and wallet.dat stores addresses in binary rather than decoding these strings, so existing wallets are unaffected. Tests: new gtest SaplingAddressValidity covers three real-world unpayable addresses, constructed small-order, non-canonical, off-curve and bad-diversifier cases, derived and hardcoded good addresses, and is_valid() agreeing with SaplingNote::cm(). With the decoder check reverted, 2 of the 4 tests fail. The full gtest suite passes (100/100), and the change was verified end to end on regtest. Co-Authored-By: Claude Opus 5.5 --- src/Makefile.gtest.include | 3 +- src/gtest/test_sapling_addr_validity.cpp | 183 +++++++++++++++++++++++ src/key_io.cpp | 9 +- src/rpc/misc.cpp | 2 + src/transaction_builder.cpp | 4 +- src/zcash/Address.cpp | 10 ++ src/zcash/Address.hpp | 7 + 7 files changed, 215 insertions(+), 3 deletions(-) create mode 100644 src/gtest/test_sapling_addr_validity.cpp diff --git a/src/Makefile.gtest.include b/src/Makefile.gtest.include index 7fb806c61..cd868225b 100644 --- a/src/Makefile.gtest.include +++ b/src/Makefile.gtest.include @@ -24,7 +24,8 @@ hush_gtest_SOURCES = \ gtest/test_wallet_history.cpp \ gtest/test_wallet_consolidation.cpp \ gtest/test_wallet_shutdownsave.cpp \ - gtest/test_wallet_witnessroots.cpp + gtest/test_wallet_witnessroots.cpp \ + gtest/test_sapling_addr_validity.cpp hush_gtest_CPPFLAGS = $(AM_CPPFLAGS) -DMULTICORE -fopenmp -DBINARY_OUTPUT -DCURVE_ALT_BN128 -DSTATIC $(BITCOIN_INCLUDES) hush_gtest_CXXFLAGS = $(AM_CXXFLAGS) $(PIE_FLAGS) diff --git a/src/gtest/test_sapling_addr_validity.cpp b/src/gtest/test_sapling_addr_validity.cpp new file mode 100644 index 000000000..0f8fd3dbc --- /dev/null +++ b/src/gtest/test_sapling_addr_validity.cpp @@ -0,0 +1,183 @@ +// Copyright (c) 2016-2024 The Hush developers +// Distributed under the GPLv3 software license, see the accompanying +// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html +// +// DecodePaymentAddress must reject Sapling addresses that pass the bech32 checksum but +// cannot receive funds (diversifier with no valid g_d, or pk_d not a prime-order Jubjub +// point). Before this check, z_validateaddress said isvalid:true for them and z_sendmany +// accepted them, then the async op failed with "Failed to build transaction." and took +// every other recipient in the batch down with it (a mining pool's payouts stalled for +// 10.5h on one such miner address). + +#include + +#include "arith_uint256.h" +#include "bech32.h" +#include "chainparams.h" +#include "key_io.h" +#include "uint256.h" +#include "zcash/Address.hpp" +#include "zcash/Note.hpp" +#include "zcash/zip32.h" + +#include + +#include +#include + +namespace { + +// Bech32 checksum and length are fine, so these test the curve check, not the decoder. +void ExpectWellFormed(const std::string& s) +{ + auto bech = bech32::Decode(s); + ASSERT_EQ(bech.first, Params().Bech32HRP(CChainParams::SAPLING_PAYMENT_ADDRESS)) << s; + ASSERT_EQ(bech.second.size(), (size_t)(((32 + 11) * 8 + 4) / 5)) << s; +} + +void ExpectRejected(const std::string& s) +{ + auto decoded = DecodePaymentAddress(s); + EXPECT_TRUE(boost::get(&decoded) != nullptr) << s; + EXPECT_FALSE(IsValidPaymentAddress(decoded)) << s; + EXPECT_FALSE(IsValidPaymentAddressString(s, SAPLING_BRANCH_ID)) << s; +} + +void ExpectAccepted(const std::string& s) +{ + auto decoded = DecodePaymentAddress(s); + ASSERT_TRUE(boost::get(&decoded) != nullptr) << s; + EXPECT_TRUE(IsValidPaymentAddress(decoded)) << s; + EXPECT_EQ(EncodePaymentAddress(decoded), s); +} + +libzcash::SaplingExtendedSpendingKey TestKey(uint32_t i) +{ + std::vector> rawSeed(32, 0x5a); + HDSeed seed(rawSeed); + return libzcash::SaplingExtendedSpendingKey::Master(seed).Derive(i | ZIP32_HARDENED_KEY_LIMIT); +} + +// is_valid() must agree with what the transaction builder sees: SaplingNote::cm() is the +// call that fails in TransactionBuilder::Build for a bad recipient. +bool BuilderCanCommit(const libzcash::SaplingPaymentAddress& addr) +{ + return libzcash::SaplingNote(addr, 1).cm() != boost::none; +} + +} // namespace + +TEST(SaplingAddressValidity, RejectsRealWorldUnpayableAddresses) +{ + SelectParams(CBaseChainParams::MAIN); + const std::vector unpayable = { + // pk_d is on the curve but not in the prime-order subgroup (the 2026-11-14 payout stall) + "zs1w3jhmncfz0qkwkm857pt8g4dplvrnq42xg9xuas9uer0m05lugqjgvf8eum6gmc9ltd72e60t9u", + // diversifier has no valid g_d + "zs1d6w54jpkh28acqcknjc5alvnw649far8qv36smygszh27cg74f3g5cka3ahfsgqg03gr5e54d42", + "zs1q9fnfa74uqpejjuwvs6h8zh7hh878s4n28u8vqzjzyyx06lawqn65lxl5enfn6k5q9d02pvlqak", + }; + for (const auto& s : unpayable) { + ExpectWellFormed(s); + ExpectRejected(s); + } +} + +TEST(SaplingAddressValidity, AcceptsDerivedAndHardcodedAddresses) +{ + SelectParams(CBaseChainParams::MAIN); + + for (uint32_t i = 0; i < 20; i++) { + auto sk = TestKey(i); + ExpectAccepted(EncodePaymentAddress(sk.DefaultAddress())); + + // Non-default diversifiers too: every valid d must give a payable address. + auto ivk = sk.ToXFVK().fvk.in_viewing_key(); + int found = 0; + for (uint32_t j = 0; j < 64 && found < 5; j++) { + libzcash::diversifier_t d = {}; + d[0] = (unsigned char)j; + d[1] = (unsigned char)i; + auto addr = ivk.address(d); + if (!addr) continue; + found++; + EXPECT_TRUE(addr->is_valid()); + ExpectAccepted(EncodePaymentAddress(*addr)); + } + EXPECT_GT(found, 0); + } + + // Addresses hardcoded in the daemon (shieldcoinbase donation address and RPC help + // examples) must keep decoding. + ExpectAccepted("zs1uhmry4jjaymhh2x7x53fkahp57u60qr54ydtcd6c2nzu73lgm78a4kml2x7ylm547hu2qqtsnw5"); + ExpectAccepted("zs14d8tc0hl9q0vg5l28uec5vk6sk34fkj2n8s7jalvw5fxpy6v39yn4s2ga082lymrkjk0x2nqg37"); + ExpectAccepted("zs1z7rejlpsa98s2rrrfkwmaxu53e4ue0ulcrw0h4x5g8jl04tak0d3mm47vdtahatqrlkngh9slya"); +} + +TEST(SaplingAddressValidity, RejectsConstructedBadPoints) +{ + SelectParams(CBaseChainParams::MAIN); + auto good = TestKey(0).DefaultAddress(); + ASSERT_TRUE(good.is_valid()); + + auto withPkd = [&](const std::string& hex) { + uint256 pk_d; + pk_d.SetHex(hex); + return libzcash::SaplingPaymentAddress(good.d, pk_d); + }; + + // (0, -1) has order 2: on the curve, not in the prime-order subgroup. + auto order2 = withPkd("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000"); + // y = q + 1 would be the identity, but y >= q is not a canonical field element and is rejected. + auto noncanon = withPkd("73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000002"); + // y = 2: (y^2 - 1) / (d*y^2 + 1) is not a square, so there is no point with this y. + auto offcurve = withPkd("02"); + + for (const auto& addr : {order2, noncanon, offcurve}) { + EXPECT_FALSE(addr.is_valid()) << addr.pk_d.GetHex(); + EXPECT_FALSE(BuilderCanCommit(addr)) << addr.pk_d.GetHex(); + std::string s = EncodePaymentAddress(addr); + ExpectWellFormed(s); + ExpectRejected(s); + } + + // A diversifier with no valid g_d, paired with a good pk_d. + bool sawBadD = false; + for (uint32_t j = 0; j < 256 && !sawBadD; j++) { + libzcash::diversifier_t d = {}; + d[0] = (unsigned char)j; + d[10] = 0xa5; + libzcash::SaplingPaymentAddress addr(d, good.pk_d); + if (addr.is_valid()) continue; + sawBadD = true; + EXPECT_FALSE(BuilderCanCommit(addr)); + std::string s = EncodePaymentAddress(addr); + ExpectWellFormed(s); + ExpectRejected(s); + } + EXPECT_TRUE(sawBadD); + + // The identity point is in the prime-order subgroup, and the builder accepts it, so + // decoding does too. Funds sent there are unspendable, but that is no different from + // sending to any address whose key nobody holds. + auto identity = withPkd("01"); + EXPECT_TRUE(identity.is_valid()); + EXPECT_TRUE(BuilderCanCommit(identity)); +} + +TEST(SaplingAddressValidity, IsValidMatchesBuilder) +{ + SelectParams(CBaseChainParams::MAIN); + auto good = TestKey(1).DefaultAddress(); + // Small y values hit every case: off-curve, small-order and prime-order points. + int valid = 0, invalid = 0; + for (int y = 0; y < 200; y++) { + uint256 pk_d = ArithToUint256(arith_uint256(y)); + libzcash::SaplingPaymentAddress addr(good.d, pk_d); + bool v = addr.is_valid(); + EXPECT_EQ(v, BuilderCanCommit(addr)) << "y=" << y; + (v ? valid : invalid)++; + } + EXPECT_GT(valid, 0); + EXPECT_GT(invalid, 0); +} diff --git a/src/key_io.cpp b/src/key_io.cpp index 00f1e3563..18be5da88 100644 --- a/src/key_io.cpp +++ b/src/key_io.cpp @@ -304,7 +304,14 @@ libzcash::PaymentAddress DecodePaymentAddress(const std::string& str) CDataStream ss(data, SER_NETWORK, PROTOCOL_VERSION); libzcash::SaplingPaymentAddress ret; ss >> ret; - return ret; + // A good checksum is not enough: reject addresses whose diversifier or pk_d is + // not a valid curve point. Nothing can ever be sent to them, and before this + // check z_validateaddress called them valid and z_sendmany accepted them, only + // for the async operation to fail with "Failed to build transaction." and take + // every other recipient in the batch down with it. + if (ret.is_valid()) { + return ret; + } } } return libzcash::InvalidEncoding(); diff --git a/src/rpc/misc.cpp b/src/rpc/misc.cpp index b3a14c699..e17dbb177 100644 --- a/src/rpc/misc.cpp +++ b/src/rpc/misc.cpp @@ -425,6 +425,8 @@ UniValue z_validateaddress(const UniValue& params, bool fHelp, const CPubKey& my "\nResult:\n" "{\n" " \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n" + " An address with a good checksum is still invalid if it cannot receive funds\n" + " (its diversifier or pk_d is not a valid Sapling curve point).\n" " \"address\" : \"zaddr\", (string) The z address validated\n" " \"type\" : \"xxxx\", (string) \"sapling\"\n" " \"ismine\" : true|false, (boolean) If the address is yours or not\n" diff --git a/src/transaction_builder.cpp b/src/transaction_builder.cpp index b3d8ac758..c4dfe4d37 100644 --- a/src/transaction_builder.cpp +++ b/src/transaction_builder.cpp @@ -236,7 +236,9 @@ boost::optional TransactionBuilder::Build() for (auto output : outputs) { auto cm = output.note.cm(); if (!cm) { - LogPrintf("%s: Invalid sapling note commitment!\n", __FUNCTION__); + // Only an invalid recipient (bad diversifier, or pk_d not a prime-order point) + // gets here; DecodePaymentAddress rejects those, so this is a caller bug. + LogPrintf("%s: Invalid sapling note commitment! An output's recipient address is not a valid Sapling address\n", __FUNCTION__); librustzcash_sapling_proving_ctx_free(ctx); return boost::none; } diff --git a/src/zcash/Address.cpp b/src/zcash/Address.cpp index 2e5080a05..aac28d76b 100644 --- a/src/zcash/Address.cpp +++ b/src/zcash/Address.cpp @@ -24,6 +24,16 @@ uint256 SaplingPaymentAddress::GetHash() const { return Hash(ss.begin(), ss.end()); } +bool SaplingPaymentAddress::is_valid() const { + // librustzcash_sapling_compute_cm is the exact check the transaction builder runs + // (via SaplingNote::cm()) on every output: it fails if the diversifier gives no valid + // g_d or if pk_d does not decode to a prime-order Jubjub point. The value and rcm play + // no part in that; zero is a canonical scalar, so rcm = 0 is accepted. + uint256 rcm; + uint256 cm; + return librustzcash_sapling_compute_cm(d.data(), pk_d.begin(), 0, rcm.begin(), cm.begin()); +} + SaplingFullViewingKey SaplingExpandedSpendingKey::full_viewing_key() const { uint256 ak; uint256 nk; diff --git a/src/zcash/Address.hpp b/src/zcash/Address.hpp index 8f0f00955..72d28d9c0 100644 --- a/src/zcash/Address.hpp +++ b/src/zcash/Address.hpp @@ -89,6 +89,13 @@ public: //! Get the 256-bit SHA256d hash of this payment address. uint256 GetHash() const; + //! True if funds can actually be sent to this address: the diversifier hashes to a + //! valid g_d and pk_d is a point in Jubjub's prime-order subgroup. Any 43 bytes with a + //! good bech32 checksum decode to a SaplingPaymentAddress, but an address failing this + //! check can never receive a note, and the transaction builder fails ("Invalid sapling + //! note commitment") on any transaction with an output to it. + bool is_valid() const; + friend inline bool operator==(const SaplingPaymentAddress& a, const SaplingPaymentAddress& b) { return a.d == b.d && a.pk_d == b.pk_d; }