Merge branch 'fix/reject-unpayable-sapling-addr' into dev

This commit is contained in:
2026-11-20 16:45:35 -06:00
7 changed files with 215 additions and 3 deletions
+2 -1
View File
@@ -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)
+183
View File
@@ -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 <gtest/gtest.h>
#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 <boost/variant.hpp>
#include <string>
#include <vector>
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<libzcash::InvalidEncoding>(&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<libzcash::SaplingPaymentAddress>(&decoded) != nullptr) << s;
EXPECT_TRUE(IsValidPaymentAddress(decoded)) << s;
EXPECT_EQ(EncodePaymentAddress(decoded), s);
}
libzcash::SaplingExtendedSpendingKey TestKey(uint32_t i)
{
std::vector<unsigned char, secure_allocator<unsigned char>> 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<std::string> 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);
}
+8 -1
View File
@@ -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();
+2
View File
@@ -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"
+3 -1
View File
@@ -236,7 +236,9 @@ boost::optional<CTransaction> 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;
}
+10
View File
@@ -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;
+7
View File
@@ -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;
}