fix(import): strip Unicode whitespace from pasted keys before import/sweep

Users (notably in the Chinese community) hit "Invalid spending key" when
importing/sweeping an otherwise-valid shielded spending key. Root cause: the
Import Key dialog classified the TRIMMED key (so the UI showed it as valid) but
handed the RAW import_key_input_ buffer to z_importkey/sweep — and the trim was
ASCII-only (' ' \t \n \r). CJK clipboards commonly inject whitespace that an
ASCII trim leaves behind — above all a trailing U+3000 ideographic space, plus
NBSP / zero-width / BOM — so a trailing such character passed the prefix
classifier (UI "valid") but reached the daemon's DecodeSpendingKey() verbatim,
which failed the Bech32 decode → "Invalid spending key". Native Ctrl+V also
bypassed the paste-button trim entirely, so even plain ASCII whitespace reached
the RPC. This is why it hit CJK users systematically and others rarely.

Add util::stripAllWhitespaceForKey (UTF-8 aware; removes every whitespace code
point, ASCII + Unicode, including internal ones — a key is a single token). The
dialog now classifies AND sends this cleaned key (keyTrim), the key Paste button
cleans the field with it, and trimmedClipboardText (addresses etc.) now
edge-trims Unicode whitespace too. Covers spending, viewing, and WIF imports and
the sweep path. Present in v2.0.2 and current dev (same gate).

Adds testKeyInputSanitization (trailing U+3000 / NBSP / BOM / zero-width /
internal newline → clean key; and the end-to-end classify-after-clean case).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 11:04:20 -06:00
co-authored by Claude Opus 4.8
parent 6ffe3bc526
commit 0a957e9555
4 changed files with 114 additions and 15 deletions
+13 -8
View File
@@ -4122,7 +4122,10 @@ void App::renderImportKeyDialog()
if (pasteClicked) {
const char* clipboard = ImGui::GetClipboardText();
if (clipboard) {
std::string trimmed = dragonx::util::trimmedClipboardText(clipboard);
// A key is a single token — strip ALL whitespace (ASCII + Unicode), not just the ends, so the
// field shows exactly what will be imported. (Native Ctrl+V into the field is handled too: the
// action re-strips via keyTrim above.)
std::string trimmed = dragonx::util::stripAllWhitespaceForKey(clipboard);
snprintf(import_key_input_, sizeof(import_key_input_), "%s", trimmed.c_str());
}
}
@@ -4183,11 +4186,13 @@ void App::renderImportKeyDialog()
}
}
// Trimmed field content drives the type indicator, the Import/Sweep guard, and the scan panel — NOT
// the hover preview, so hovering can neither shift the layout nor enable the action button.
std::string keyTrim(import_key_input_);
while (!keyTrim.empty() && (keyTrim.front()==' '||keyTrim.front()=='\t'||keyTrim.front()=='\n'||keyTrim.front()=='\r')) keyTrim.erase(keyTrim.begin());
while (!keyTrim.empty() && (keyTrim.back()==' '||keyTrim.back()=='\t'||keyTrim.back()=='\n'||keyTrim.back()=='\r')) keyTrim.pop_back();
// Whitespace-stripped field content drives the type indicator, the Import/Sweep guard, the scan panel,
// AND the key actually handed to the import/sweep RPC below (NOT the raw buffer — otherwise a pasted
// key carrying leading/trailing/line-wrapped whitespace classifies as valid here but the daemon
// rejects it as "Invalid spending key"). stripAllWhitespaceForKey removes ASCII and Unicode
// whitespace, including the full-width (U+3000) / zero-width characters CJK clipboards inject that an
// ASCII-only trim left behind. Not the hover preview, so hovering can't shift layout or enable the button.
std::string keyTrim = dragonx::util::stripAllWhitespaceForKey(import_key_input_);
bool isView = services::WalletSecurityController::isViewingKey(keyTrim);
bool isSpend = services::WalletSecurityController::isRecognizedPrivateKey(keyTrim);
bool shielded = services::WalletSecurityController::classifyPrivateKey(keyTrim)
@@ -4365,14 +4370,14 @@ void App::renderImportKeyDialog()
startHeight = state_.sync.blocks; // never past the chain tip
}
if (sweepMode) {
sweepPrivateKey(std::string(import_key_input_), startHeight, sweep_dest_mode_,
sweepPrivateKey(keyTrim, startHeight, sweep_dest_mode_,
sweep_dest_mode_ == 1 ? std::string(sweep_dest_pick_) : std::string());
} else {
import_in_progress_ = true;
import_success_ = false;
import_status_.clear();
import_result_address_.clear();
importPrivateKey(std::string(import_key_input_), startHeight,
importPrivateKey(keyTrim, startHeight,
[this](bool ok, const std::string& err, const std::string& addr) {
import_in_progress_ = false;
import_success_ = ok;
+63 -5
View File
@@ -7,6 +7,8 @@
#include <algorithm>
#include <cctype>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <ctime>
@@ -118,17 +120,73 @@ bool containsIgnoreCase(std::string_view haystack, std::string_view needle)
return false;
}
namespace {
// Decode the UTF-8 code point starting at s[i], store its byte length in `len`, and return whether it is
// a whitespace code point. Covers ASCII whitespace PLUS the Unicode space / zero-width / BOM characters
// that clipboards — CJK ones especially — commonly inject (U+00A0 NBSP, U+3000 IDEOGRAPHIC SPACE,
// U+200B ZERO WIDTH SPACE, U+FEFF, the U+2000–200A spaces, line/paragraph separators, …). An ASCII-only
// trim leaves these in place, which then breaks downstream Bech32/Base58 validation (e.g. a pasted
// spending key the daemon rejects as "Invalid spending key").
bool isWhitespaceCpAt(const std::string& s, std::size_t i, std::size_t& len)
{
const std::size_t n = s.size();
const unsigned char c = static_cast<unsigned char>(s[i]);
std::uint32_t cp;
if (c < 0x80) { len = 1; cp = c; }
else if ((c >> 5) == 0x6 && i + 1 < n) { len = 2; cp = ((c & 0x1Fu) << 6) | (static_cast<unsigned char>(s[i+1]) & 0x3Fu); }
else if ((c >> 4) == 0xE && i + 2 < n) { len = 3; cp = ((c & 0x0Fu) << 12) | ((static_cast<unsigned char>(s[i+1]) & 0x3Fu) << 6) | (static_cast<unsigned char>(s[i+2]) & 0x3Fu); }
else if ((c >> 3) == 0x1Eu && i + 3 < n){ len = 4; cp = ((c & 0x07u) << 18) | ((static_cast<unsigned char>(s[i+1]) & 0x3Fu) << 12) | ((static_cast<unsigned char>(s[i+2]) & 0x3Fu) << 6) | (static_cast<unsigned char>(s[i+3]) & 0x3Fu); }
else { len = 1; cp = c; }
switch (cp) {
case 0x09: case 0x0A: case 0x0B: case 0x0C: case 0x0D: case 0x20:
case 0x85: case 0xA0: case 0x1680:
case 0x2000: case 0x2001: case 0x2002: case 0x2003: case 0x2004: case 0x2005:
case 0x2006: case 0x2007: case 0x2008: case 0x2009: case 0x200A:
case 0x200B: case 0x200C: case 0x200D: case 0x2028: case 0x2029:
case 0x202F: case 0x205F: case 0x2060: case 0x3000: case 0xFEFF:
return true;
default:
return false;
}
}
} // namespace
std::string stripAllWhitespaceForKey(const std::string& s)
{
// Keys (spending / viewing / WIF) are single contiguous Bech32/Base58 tokens with no valid internal
// whitespace, so removing EVERY whitespace code point (not just the ends) robustly cleans a paste that
// carried leading, trailing, or line-wrapped whitespace — including the full-width / zero-width
// characters CJK clipboards inject that an ASCII trim leaves behind and the daemon then rejects.
std::string out;
out.reserve(s.size());
std::size_t i = 0, len = 0;
while (i < s.size()) {
const bool ws = isWhitespaceCpAt(s, i, len);
if (len == 0) len = 1;
if (!ws) out.append(s, i, len);
i += len;
}
return out;
}
std::string trimmedClipboardText(const char* clip, std::size_t maxBytes)
{
if (!clip || clip[0] == '\0') return {};
std::size_t n = 0;
while (n <= maxBytes && clip[n] != '\0') ++n;
if (n > maxBytes) return {};
const auto ws = [](char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r'; };
std::size_t b = 0, e = n;
while (b < e && ws(clip[b])) ++b;
while (e > b && ws(clip[e - 1])) --e;
return std::string(clip + b, e - b);
const std::string s(clip, n);
// Edge-trim ASCII AND Unicode whitespace (see isWhitespaceCpAt): walk the code points, remember the
// first and the end-of-last non-whitespace one.
std::size_t i = 0, len = 0, start = n, end = 0;
while (i < s.size()) {
const bool ws = isWhitespaceCpAt(s, i, len);
if (len == 0) len = 1;
if (!ws) { if (start == n) start = i; end = i + len; }
i += len;
}
if (start >= end) return {};
return s.substr(start, end - start);
}
} // namespace util
+11 -2
View File
@@ -82,9 +82,18 @@ std::string truncateMiddleToFit(const std::string& s, int minFront, int minBack,
return build(lo);
}
// Clipboard text -> trimmed (ASCII whitespace ' ', \t, \n, \r) candidate string. Empty for a null/empty clip or one
// longer than maxBytes (an address is < 100 bytes; this bounds the copy of a pathological multi-MB clipboard).
// Clipboard text -> edge-trimmed candidate string. Trims ASCII whitespace AND the Unicode space /
// zero-width / BOM code points clipboards inject (NBSP, U+3000 ideographic space, U+200B, U+FEFF, …).
// Empty for a null/empty clip or one longer than maxBytes (an address is < 100 bytes; this bounds the
// copy of a pathological multi-MB clipboard).
std::string trimmedClipboardText(const char* clip, std::size_t maxBytes = 1024);
// Remove EVERY whitespace code point (ASCII + Unicode, including internal ones) from a key string. Use
// for spending/viewing/WIF key input, which is a single contiguous token: this cleans leading, trailing,
// and line-wrapped whitespace — notably the full-width / zero-width characters CJK clipboards inject —
// before classification and before the key is handed to z_importkey (which otherwise rejects it as
// "Invalid spending key"). NOT for addresses or amounts (use trimmedClipboardText for those).
std::string stripAllWhitespaceForKey(const std::string& s);
} // namespace util
} // namespace dragonx
+27
View File
@@ -3325,6 +3325,32 @@ void testInstalledDaemonInfoPosix()
}
#endif
// Regression: a pasted spending key carrying whitespace (notably the full-width/zero-width characters CJK
// clipboards inject) must be fully cleaned before classification AND before it reaches z_importkey — else
// the UI shows "valid" but the daemon rejects the raw key as "Invalid spending key". (Chinese-community
// import bug, V2.0.2.)
void testKeyInputSanitization()
{
using dragonx::util::stripAllWhitespaceForKey;
using dragonx::services::WalletSecurityController;
// DragonX mainnet Sapling spending key HRP is "secret-extended-key-main"; the import gate prefix-matches
// it (the key exceeds the Bech32 length cap), so a well-formed-looking stand-in exercises the path.
const std::string key = "secret-extended-key-main1qabcdefghijklmnop";
EXPECT_EQ(stripAllWhitespaceForKey(" " + key + " \n\r\t"), key); // ASCII edge whitespace
EXPECT_EQ(stripAllWhitespaceForKey(key + "\xE3\x80\x80"), key); // trailing U+3000 (the reported CJK case)
EXPECT_EQ(stripAllWhitespaceForKey("\xC2\xA0" + key), key); // leading U+00A0 NBSP
EXPECT_EQ(stripAllWhitespaceForKey(key + "\xEF\xBB\xBF"), key); // trailing U+FEFF BOM/ZWNBSP
EXPECT_EQ(stripAllWhitespaceForKey(key + "\xE2\x80\x8B"), key); // trailing U+200B zero-width space
// Internal whitespace from a line-wrapped paste is removed too (keys are single tokens).
EXPECT_EQ(stripAllWhitespaceForKey("secret-extended-key-main1qabc\ndefghijklmnop"), key);
EXPECT_EQ(stripAllWhitespaceForKey(key), key); // clean key unchanged
// End-to-end: a trailing full-width space classified as valid only AFTER sanitizing — this is exactly
// what the raw-buffer path got wrong (UI said valid, z_importkey saw the stray byte and refused).
EXPECT_TRUE(WalletSecurityController::isRecognizedPrivateKey(stripAllWhitespaceForKey(key + "\xE3\x80\x80")));
}
void testWalletSecurityController()
{
using dragonx::services::WalletSecurityController;
@@ -20374,6 +20400,7 @@ int main()
testSecureVaultWellFormed();
testInstalledDaemonInfoPosix();
#endif
testKeyInputSanitization();
testWalletSecurityController();
testWalletSecurityWorkflow();
testWalletSecurityWorkflowExecutor();