ralph

Outcomes

What happened to findings after review.

Addressed after review

Best-effort automated assessment of whether later PR updates addressed findings from previous reviews. This is not a causal claim or human validation.

3,404 assessed findings from 3,404 published findings across 1,109 source reviews. Follow-up was unavailable for 1 reviews because their engine did not export findings.

StatusFindings
addressed646
partially_addressed70
still_present1,373
unclear1,315

Assessment jobs: 540

Assessment usage: 657 request records; 35,165,206 (partial) input tokens; 478,883 (partial) output tokens.

Finding assessments

PRFindingOutcomeEvidence
bitcoin#36885WalletHDKeys() scans every descriptor manager twicesrc/wallet/descriptor_analyzer.cppstill_present
Assessment

The new-head WalletHDKeys() still initializes with GetHDPubKeys(All) and limits inventory-loop insertion to MuSig participants, leaving the extra traversal and descriptor copy in place.

new_source: src/wallet/descriptor_analyzer.cpp

[
  {
    "bounded": true,
    "end_line": 230,
    "evidence_id": "56dd78af70134733a64df05834d59b8a",
    "finding_id": "finding:5",
    "kind": "new_source",
    "line": 130,
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "8721e96cc46f544eb8505e6fb3502e934dd0906b",
    "path": "src/wallet/descriptor_analyzer.cpp",
    "revision": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "source_generation": 9,
    "source_job_id": 3168,
    "text": "    const bool xonly{key.xonly || role == Role::TAPROOT_INTERNAL || role == Role::TAPROOT_OUTPUT || role == Role::TAPSCRIPT};\n    const std::vector<CPubKey> pubkeys{xonly ? XOnlyPubKey{key.pubkey}.GetCPubKeys() : std::vector<CPubKey>{key.pubkey}};\n    std::vector<KeyOriginInfo> origins;\n    if (origin) origins.push_back(*origin);\n    bool derived{false};\n    for (const auto* spkm : wallet.GetAllScriptPubKeyMans()) {\n        const auto* desc_spkm{dynamic_cast<const DescriptorScriptPubKeyMan*>(spkm)};\n        if (!desc_spkm) continue;\n        for (const CPubKey& pubkey : pubkeys) {\n            if (WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->HasPrivKey(pubkey.GetID()))) return KeyMatch::MINE;\n            if (auto recorded{desc_spkm->GetPubKeyOrigin(pubkey)}) {\n                derived = true;\n                origins.push_back(std::move(*recorded));\n            }\n        }\n    }\n\n    const auto same = [&](const CExtPubKey& candidate) {\n        return xonly ? XOnlyPubKey{candidate.pubkey} == XOnlyPubKey{key.pubkey} : candidate.pubkey == key.pubkey;\n    };\n    KeyMatch result{derived ? KeyMatch::WATCH_ONLY : KeyMatch::NOT_MINE};\n    for (const KeyOriginInfo& candidate : origins) result = Best(result, MatchHDKeys(wallet, hd_keys, candidate, same));\n    return result;\n}\n\n/** The wallet's HD keys, plus those it holds only as musig() participants,\n *  which GetHDPubKeys() leaves out because they have no single key to list,\n *  and the origins its descriptors give them. */\nHDKeys WalletHDKeys(const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n{\n    HDKeys hd_keys{.keys = wallet.GetHDPubKeys(CWallet::HDKeyFilter::All), .origins = {}};\n    for (auto* spkm : wallet.GetAllScriptPubKeyMans()) {\n        auto* desc_spkm{dynamic_cast<DescriptorScriptPubKeyMan*>(spkm)};\n        if (!desc_spkm) continue;\n        const auto inventory{WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->GetWalletDescriptor().descriptor->GetKeyInventory())};\n        for (const auto& occurrence : inventory.occurrences) {\n            const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&occurrence.expression.key)};\n            if (!key) continue;\n            if (occurrence.role == DescriptorKeyInventory::Role::MUSIG_PARTICIPANT) hd_keys.keys[key->root].insert(desc_spkm);\n            if (const auto& origin{occurrence.expression.origin}) hd_keys.origins.emplace_back(*origin, key->root);\n        }\n    }\n    return hd_keys;\n}\n\nstd::optional<CTxDestination> FirstAddress(const Descriptor& descriptor, const SigningProvider& provider)\n{\n    std::vector<CScript> scripts;\n    FlatSigningProvider out;\n    if (!descriptor.Expand(/*pos=*/0, provider, scripts, out)) return std::nullopt;\n    // The first script with an address, as deriveaddresses lists: combo() starts with P2PK, which has none.\n    for (const CScript& script : scripts) {\n        if (CTxDestination dest; ExtractDestination(script, dest)) return dest;\n    }\n    return std::nullopt;\n}\n\n} // namespace\n\nstd::optional<bool> WalletDescriptorAnalysis::CanSign() const\n{\n    // MuSig aggregates are never MINE; their participants are matched instead.\n    bool unknown{false};\n    for (const KeyMatch match : keys) {\n        if (match == KeyMatch::MINE) return true;\n        unknown |= match == KeyMatch::UNKNOWN;\n    }\n    if (unknown) return std::nullopt;\n    return false;\n}\n\nWalletDescriptorAnalysis AnalyzeDescriptor(const CWallet& wallet, std::span<const std::unique_ptr<Descriptor>> descriptors, const SigningProvider& provider)\n{\n    WalletDescriptorAnalysis result;\n    result.analysis = AnalyzeDescriptor(descriptors);\n    if (descriptors.empty()) return result;\n    for (const auto& descriptor : descriptors) {\n        const auto address{FirstAddress(*descriptor, provider)};\n        if (!address) {\n            result.first_addresses.clear();\n            break;\n        }\n        result.first_addresses.push_back(*address);\n    }\n\n    LOCK(wallet.cs_wallet);\n    const HDKeys hd_keys{WalletHDKeys(wallet)};\n    for (const auto& occurrence : result.analysis.policy.keys.occurrences) {\n        const auto& node{occurrence.expression};\n        if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) {\n            result.keys.push_back(MatchExtKey(wallet, hd_keys, key->root, node.origin));\n        } else if (const auto* key{std::get_if<DescriptorKeyInfo::ConstKey>(&node.key)}) {\n            result.keys.push_back(MatchConstKey(wallet, hd_keys, *key, node.origin, occurrence.role));\n        } else {\n            result.keys.push_back(KeyMatch::NOT_MINE);\n        }\n    }\n    return result;\n}\n\n} // namespace wallet",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 8721e96cc46f..386c55a4bfcb

2026-11-26T06:52:03Z · gpt-6-luna

bitcoin#36885External signing is absent from can_signsrc/wallet/descriptor_analyzer.cppunclear
Assessment

The follow-up assessment was invalid: follow-up evidence belongs to another finding or comparison.

invalid_assessment

Source report · 8721e96cc46f..386c55a4bfcb

2026-11-26T06:52:03Z · gpt-6-luna

bitcoin#36885Shared cosigner origin fingerprints get no advisorysrc/script/descriptor_analyzer.cppstill_present
Assessment

The new-head CheckRepeatedKeys() excerpt still contains no origin-fingerprint check or separate warning channel for cosigners sharing a fingerprint.

new_source: src/script/descriptor_analyzer.cpp

[
  {
    "bounded": true,
    "end_line": 301,
    "evidence_id": "278bd9c1f449441a81161655e3ac643c",
    "finding_id": "finding:3",
    "kind": "new_source",
    "line": 152,
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "8721e96cc46f544eb8505e6fb3502e934dd0906b",
    "path": "src/script/descriptor_analyzer.cpp",
    "revision": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "source_generation": 9,
    "source_job_id": 3168,
    "text": "            if (!inserted) Link(it->second, i);\n        }\n    }\n\n    //! Groups of at least two indices, each in index order, listed by its first index.\n    std::vector<std::vector<size_t>> Repeated()\n    {\n        std::vector<std::vector<size_t>> groups(m_parent.size());\n        for (size_t i{0}; i < m_parent.size(); ++i) groups[First(i)].push_back(i);\n        std::erase_if(groups, [](const auto& group) { return group.size() < 2; });\n        return groups;\n    }\n};\n\n/** Report each group of `groups` as one REPEATED_KEY issue, with the occurrence\n *  IDs `ids` gives for its indices. */\nvoid ReportRepeated(DescriptorAnalysis& result, LinkedGroups& groups, const std::vector<size_t>& ids)\n{\n    for (const auto& group : groups.Repeated()) {\n        std::vector<size_t> keys;\n        keys.reserve(group.size());\n        for (const size_t i : group) keys.push_back(ids[i]);\n        result.issues.push_back({IssueKind::REPEATED_KEY, std::move(keys)});\n    }\n}\n\n/** Report every group of cosigner slots held by the same key: slots that share\n *  a root key (e.g. the same xpub with two paths), that derive the same key, or\n *  where one xpub is the direct child of another. Slots linked through a chain\n *  of these are one group. */\nvoid CheckRepeatedKeys(DescriptorAnalysis& result)\n{\n    const auto& occurrences{result.policy.keys.occurrences};\n    const size_t count{result.cosigners.size()};\n    std::vector<std::optional<XOnlyPubKey>> roots, derived;\n    std::vector<const CExtPubKey*> ext_roots;\n    roots.reserve(count);\n    derived.reserve(count);\n    ext_roots.reserve(count);\n    for (const size_t id : result.cosigners) {\n        const auto& node{occurrences.at(id).expression};\n        roots.push_back(RootKey(node));\n        derived.push_back(FirstDerivedKey(node));\n        ext_roots.push_back(RootExtKey(node));\n    }\n    LinkedGroups groups{count};\n    groups.LinkEqual(roots);\n    groups.LinkEqual(derived);\n\n    // Only an xpub whose fingerprint a child names can be its parent, so a\n    // child is derived again only from those, and not when the two slots are\n    // already in one group. Xpubs sharing a root key are one group already, and\n    // can share a fingerprint with any number of chain codes, so only the first\n    // of them is a candidate parent: a child of a later one is left out of the\n    // group, which is reported either way.\n    std::multimap<KeyFingerprint, size_t> by_fingerprint;\n    std::set<XOnlyPubKey> parent_roots;\n    for (size_t i{0}; i < count; ++i) {\n        if (ext_roots[i] && parent_roots.insert(*roots[i]).second) by_fingerprint.emplace(ext_roots[i]->id_key_fingerprint(), i);\n    }\n    for (size_t child{0}; child < count; ++child) {\n        if (!ext_roots[child]) continue;\n        const auto [begin, end]{by_fingerprint.equal_range(ext_roots[child]->fingerprint)};\n        for (auto it{begin}; it != end; ++it) {\n            const size_t parent{it->second};\n            if (groups.First(parent) != groups.First(child) && IsDirectChild(*ext_roots[parent], *ext_roots[child])) {\n                groups.Link(parent, child);\n            }\n        }\n    }\n    ReportRepeated(result, groups, result.cosigners);\n}\n\n/** Check that every cosigner can derive each participant of a musig()\n *  internal key, and that no participant is repeated: participants with the\n *  same root key, or that derive the same key, are one. */\nvoid CheckMuSigParticipants(DescriptorAnalysis& result, size_t internal_id)\n{\n    const auto& occurrences{result.policy.keys.occurrences};\n    const auto* musig{std::get_if<DescriptorKeyInfo::MuSigKey>(&occurrences.at(internal_id).expression.key)};\n    if (!musig) return;\n    const auto& participants{musig->participants};\n    std::vector<std::optional<XOnlyPubKey>> roots, derived;\n    roots.reserve(participants.size());\n    derived.reserve(participants.size());\n    for (const size_t id : participants) {\n        const auto& participant{occurrences.at(id).expression};\n        roots.push_back(RootKey(participant));\n        derived.push_back(roots.back());\n        const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&participant.key)};\n        if (!key) continue;\n        derived.back() = DeriveFirstKey(*key);\n        if (NeedsPrivateDerivation(*key)) {\n            // Other cosigners couldn't derive the key path.\n            result.issues.push_back({IssueKind::HARDENED_DERIVATION, {id}});\n        } else if (!derived.back()) {\n            result.issues.push_back({IssueKind::NOT_DERIVABLE, {id}});\n        }\n    }\n    LinkedGroups groups{participants.size()};\n    groups.LinkEqual(roots);\n    groups.LinkEqual(derived);\n    ReportRepeated(result, groups, participants);\n}\n\n/** Whether a NUMS or musig() internal key can derive its first key. Deriving\n *  fails past the maximum BIP32 depth, and a musig() aggregate starts as an\n *  xpub at depth 0. */\nbool CanDeriveInternalKey(const DescriptorKeyInfo::Node& node)\n{\n    if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) return DeriveFirstKey(*key).has_value();\n    if (const auto* key{std::get_if<DescriptorKeyInfo::MuSigKey>(&node.key)}) {\n        const bool ranged{key->derivation.type == DescriptorKeyInfo::DeriveType::UNHARDENED_RANGED};\n        return key->derivation.path.size() + (ranged ? 1 : 0) <= std::numeric_limits<unsigned char>::max();\n    }\n    return true;\n}\n\n/** Classify the Taproot internal key against the cosigners of the leaf, or\n *  nullopt if it may let fewer than `threshold` cosigners spend. */\nstd::optional<DescriptorAnalysis::KeyPath> ClassifyKeyPath(const DescriptorAnalysis& result, size_t internal_id)\n{\n    const auto& occurrences{result.policy.keys.occurrences};\n    const auto& internal{occurrences.at(internal_id).expression};\n\n    if (const auto* key{std::get_if<DescriptorKeyInfo::ConstKey>(&internal.key)}) {\n        if (XOnlyPubKey{key->pubkey} == XOnlyPubKey::NUMS_H) return DescriptorAnalysis::KeyPath::NUMS;\n    }\n    if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&internal.key)}) {\n        // Unhardened children of H are as unspendable as H.\n        if (XOnlyPubKey{key->root.pubkey} == XOnlyPubKey::NUMS_H && !HasHardenedStep(key->derivation) &&\n            key->derivation.type != DescriptorKeyInfo::DeriveType::HARDENED_RANGED) {\n            return DescriptorAnalysis::KeyPath::NUMS;\n        }\n    }\n    if (const auto* key{std::get_if<DescriptorKeyInfo::MuSigKey>(&internal.key)}) {\n        // Any `threshold` cosigners can already spend through the leaf, so an\n        // aggregate of at least that many distinct cosigners adds no new way to spend.\n        std::set<XOnlyPubKey> cosigner_roots;\n        for (const size_t id : result.cosigners) {\n            if (const auto root{RootKey(occurrences.at(id).expression)}) cosigner_roots.insert(*root);\n        }\n        // A repeated participant adds no cosigner.\n        std::set<XOnlyPubKey> participants;\n        for (const size_t id : key->participants) {\n            const auto root{RootKey(occurrences.at(id).expression)};\n            if (!root || !cosigner_roots.contains(*root)) return std::nullopt;\n            participants.insert(*root);\n        }\n        if (participants.size() >= result.threshold) return DescriptorAnalysis::KeyPath::MUSIG;",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 8721e96cc46f..386c55a4bfcb

2026-11-26T06:52:03Z · gpt-6-luna

bitcoin#36885No advisory when this wallet holds enough cosigner slotssrc/wallet/descriptor_analyzer.cppstill_present
Assessment

The new-head implementation still provides no aggregate of owned cosigner slots or threshold advisory: CanSign() returns upon the first MINE match, and the RPC response only conditionally includes can_sign.

new_source: src/wallet/descriptor_analyzer.cpp

[
  {
    "bounded": true,
    "end_line": 230,
    "evidence_id": "608ad661d729480f872f8a1183c6174c",
    "finding_id": "finding:2",
    "kind": "new_source",
    "line": 164,
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "8721e96cc46f544eb8505e6fb3502e934dd0906b",
    "path": "src/wallet/descriptor_analyzer.cpp",
    "revision": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "source_generation": 9,
    "source_job_id": 3168,
    "text": "        const auto inventory{WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->GetWalletDescriptor().descriptor->GetKeyInventory())};\n        for (const auto& occurrence : inventory.occurrences) {\n            const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&occurrence.expression.key)};\n            if (!key) continue;\n            if (occurrence.role == DescriptorKeyInventory::Role::MUSIG_PARTICIPANT) hd_keys.keys[key->root].insert(desc_spkm);\n            if (const auto& origin{occurrence.expression.origin}) hd_keys.origins.emplace_back(*origin, key->root);\n        }\n    }\n    return hd_keys;\n}\n\nstd::optional<CTxDestination> FirstAddress(const Descriptor& descriptor, const SigningProvider& provider)\n{\n    std::vector<CScript> scripts;\n    FlatSigningProvider out;\n    if (!descriptor.Expand(/*pos=*/0, provider, scripts, out)) return std::nullopt;\n    // The first script with an address, as deriveaddresses lists: combo() starts with P2PK, which has none.\n    for (const CScript& script : scripts) {\n        if (CTxDestination dest; ExtractDestination(script, dest)) return dest;\n    }\n    return std::nullopt;\n}\n\n} // namespace\n\nstd::optional<bool> WalletDescriptorAnalysis::CanSign() const\n{\n    // MuSig aggregates are never MINE; their participants are matched instead.\n    bool unknown{false};\n    for (const KeyMatch match : keys) {\n        if (match == KeyMatch::MINE) return true;\n        unknown |= match == KeyMatch::UNKNOWN;\n    }\n    if (unknown) return std::nullopt;\n    return false;\n}\n\nWalletDescriptorAnalysis AnalyzeDescriptor(const CWallet& wallet, std::span<const std::unique_ptr<Descriptor>> descriptors, const SigningProvider& provider)\n{\n    WalletDescriptorAnalysis result;\n    result.analysis = AnalyzeDescriptor(descriptors);\n    if (descriptors.empty()) return result;\n    for (const auto& descriptor : descriptors) {\n        const auto address{FirstAddress(*descriptor, provider)};\n        if (!address) {\n            result.first_addresses.clear();\n            break;\n        }\n        result.first_addresses.push_back(*address);\n    }\n\n    LOCK(wallet.cs_wallet);\n    const HDKeys hd_keys{WalletHDKeys(wallet)};\n    for (const auto& occurrence : result.analysis.policy.keys.occurrences) {\n        const auto& node{occurrence.expression};\n        if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) {\n            result.keys.push_back(MatchExtKey(wallet, hd_keys, key->root, node.origin));\n        } else if (const auto* key{std::get_if<DescriptorKeyInfo::ConstKey>(&node.key)}) {\n            result.keys.push_back(MatchConstKey(wallet, hd_keys, *key, node.origin, occurrence.role));\n        } else {\n            result.keys.push_back(KeyMatch::NOT_MINE);\n        }\n    }\n    return result;\n}\n\n} // namespace wallet",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 8721e96cc46f..386c55a4bfcb

2026-11-26T06:52:03Z · gpt-6-luna

bitcoin#36885The can_sign help overstates what recognition provessrc/wallet/rpc/wallet.cpppartially_addressed
Assessment

The author changed “safe k-of-n” to “recognized k-of-n” in both the CanSign() header comment and RPC help, correcting the safety overstatement. The supplied text does not add the requested explicit statement that recognition does not prove cosigner independence or signing capability, so that material caveat remains unstated there.

path_diff: src/wallet/rpc/wallet.cpp

[
  {
    "evidence_id": "5013231ae44d4b6e89f5fa2e47d352db",
    "finding_id": "finding:1",
    "kind": "path_diff",
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "8721e96cc46f544eb8505e6fb3502e934dd0906b",
    "path": "src/wallet/rpc/wallet.cpp",
    "source_generation": 9,
    "source_job_id": 3168,
    "text": "diff --git a/src/wallet/rpc/wallet.cpp b/src/wallet/rpc/wallet.cpp\nindex 01b4073523..151a7f7677 100644\n--- a/src/wallet/rpc/wallet.cpp\n+++ b/src/wallet/rpc/wallet.cpp\n@@ -1102,7 +1102,8 @@ static RPCMethod analyzedescriptor()\n                 }},\n                 {RPCResult::Type::OBJ, \"analysis\", HELP_DESCRIPTOR_ANALYSIS, DescriptorAnalysisResultFields()},\n                 {RPCResult::Type::BOOL, \"can_sign\", /*optional=*/true, \"Whether this wallet holds the private key for at least one key. \"\n-                    \"Whether the descriptor is a safe k-of-n is analysis.recognized. Absent if it can't tell because the wallet is locked: see the keys marked \\\"unknown\\\"\"},\n+                    \"Whether the descriptor is a recognized k-of-n is analysis.recognized. Keys held on an external signer don't count, since the wallet doesn't hold their private keys. \"\n+                    \"Absent if it can't tell because the wallet is locked: see the keys marked \\\"unknown\\\"\"},\n                 {RPCResult::Type::ARR, \"first_addresses\", /*optional=*/true, \"The address at index 0 of each path, in path order \"\n                     \"(e.g. receive, then change for /<0;1>/*), which every participant should see. Absent if they can't be derived\",\n                 {\n",
    "truncated": false,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 8721e96cc46f..386c55a4bfcb

2026-11-26T06:52:03Z · gpt-6-luna

bitcoin#36885WalletHDKeys walks every descriptor manager twicesrc/wallet/descriptor_analyzer.cppstill_present
Assessment

The new-head WalletHDKeys() still initializes its map with GetHDPubKeys(All) and only adds inventory roots for MUSIG_PARTICIPANT occurrences, rather than building the map from all BIP32 occurrences in the inventory loop.

new_source: src/wallet/descriptor_analyzer.cpp

[
  {
    "bounded": true,
    "end_line": 230,
    "evidence_id": "6b32461939e0487aa490b4166ce71a3a",
    "finding_id": "finding:6",
    "kind": "new_source",
    "line": 130,
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "c2d5322d4238be81fcbeb317032e148134f16aad",
    "path": "src/wallet/descriptor_analyzer.cpp",
    "revision": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "source_generation": 8,
    "source_job_id": 3167,
    "text": "    const bool xonly{key.xonly || role == Role::TAPROOT_INTERNAL || role == Role::TAPROOT_OUTPUT || role == Role::TAPSCRIPT};\n    const std::vector<CPubKey> pubkeys{xonly ? XOnlyPubKey{key.pubkey}.GetCPubKeys() : std::vector<CPubKey>{key.pubkey}};\n    std::vector<KeyOriginInfo> origins;\n    if (origin) origins.push_back(*origin);\n    bool derived{false};\n    for (const auto* spkm : wallet.GetAllScriptPubKeyMans()) {\n        const auto* desc_spkm{dynamic_cast<const DescriptorScriptPubKeyMan*>(spkm)};\n        if (!desc_spkm) continue;\n        for (const CPubKey& pubkey : pubkeys) {\n            if (WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->HasPrivKey(pubkey.GetID()))) return KeyMatch::MINE;\n            if (auto recorded{desc_spkm->GetPubKeyOrigin(pubkey)}) {\n                derived = true;\n                origins.push_back(std::move(*recorded));\n            }\n        }\n    }\n\n    const auto same = [&](const CExtPubKey& candidate) {\n        return xonly ? XOnlyPubKey{candidate.pubkey} == XOnlyPubKey{key.pubkey} : candidate.pubkey == key.pubkey;\n    };\n    KeyMatch result{derived ? KeyMatch::WATCH_ONLY : KeyMatch::NOT_MINE};\n    for (const KeyOriginInfo& candidate : origins) result = Best(result, MatchHDKeys(wallet, hd_keys, candidate, same));\n    return result;\n}\n\n/** The wallet's HD keys, plus those it holds only as musig() participants,\n *  which GetHDPubKeys() leaves out because they have no single key to list,\n *  and the origins its descriptors give them. */\nHDKeys WalletHDKeys(const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n{\n    HDKeys hd_keys{.keys = wallet.GetHDPubKeys(CWallet::HDKeyFilter::All), .origins = {}};\n    for (auto* spkm : wallet.GetAllScriptPubKeyMans()) {\n        auto* desc_spkm{dynamic_cast<DescriptorScriptPubKeyMan*>(spkm)};\n        if (!desc_spkm) continue;\n        const auto inventory{WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->GetWalletDescriptor().descriptor->GetKeyInventory())};\n        for (const auto& occurrence : inventory.occurrences) {\n            const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&occurrence.expression.key)};\n            if (!key) continue;\n            if (occurrence.role == DescriptorKeyInventory::Role::MUSIG_PARTICIPANT) hd_keys.keys[key->root].insert(desc_spkm);\n            if (const auto& origin{occurrence.expression.origin}) hd_keys.origins.emplace_back(*origin, key->root);\n        }\n    }\n    return hd_keys;\n}\n\nstd::optional<CTxDestination> FirstAddress(const Descriptor& descriptor, const SigningProvider& provider)\n{\n    std::vector<CScript> scripts;\n    FlatSigningProvider out;\n    if (!descriptor.Expand(/*pos=*/0, provider, scripts, out)) return std::nullopt;\n    // The first script with an address, as deriveaddresses lists: combo() starts with P2PK, which has none.\n    for (const CScript& script : scripts) {\n        if (CTxDestination dest; ExtractDestination(script, dest)) return dest;\n    }\n    return std::nullopt;\n}\n\n} // namespace\n\nstd::optional<bool> WalletDescriptorAnalysis::CanSign() const\n{\n    // MuSig aggregates are never MINE; their participants are matched instead.\n    bool unknown{false};\n    for (const KeyMatch match : keys) {\n        if (match == KeyMatch::MINE) return true;\n        unknown |= match == KeyMatch::UNKNOWN;\n    }\n    if (unknown) return std::nullopt;\n    return false;\n}\n\nWalletDescriptorAnalysis AnalyzeDescriptor(const CWallet& wallet, std::span<const std::unique_ptr<Descriptor>> descriptors, const SigningProvider& provider)\n{\n    WalletDescriptorAnalysis result;\n    result.analysis = AnalyzeDescriptor(descriptors);\n    if (descriptors.empty()) return result;\n    for (const auto& descriptor : descriptors) {\n        const auto address{FirstAddress(*descriptor, provider)};\n        if (!address) {\n            result.first_addresses.clear();\n            break;\n        }\n        result.first_addresses.push_back(*address);\n    }\n\n    LOCK(wallet.cs_wallet);\n    const HDKeys hd_keys{WalletHDKeys(wallet)};\n    for (const auto& occurrence : result.analysis.policy.keys.occurrences) {\n        const auto& node{occurrence.expression};\n        if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) {\n            result.keys.push_back(MatchExtKey(wallet, hd_keys, key->root, node.origin));\n        } else if (const auto* key{std::get_if<DescriptorKeyInfo::ConstKey>(&node.key)}) {\n            result.keys.push_back(MatchConstKey(wallet, hd_keys, *key, node.origin, occurrence.role));\n        } else {\n            result.keys.push_back(KeyMatch::NOT_MINE);\n        }\n    }\n    return result;\n}\n\n} // namespace wallet",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · c2d5322d4238..386c55a4bfcb

2026-11-26T06:52:03Z · gpt-6-luna

bitcoin#36885Analysis JSON helpers take an avoidable intermediate locationsrc/rpc/output_script.cppunclear
Assessment

The finding concerns review sequencing and intermediate commit placement, which cannot be determined from the supplied final-file excerpts or old-to-new diff.

new_source: src/rpc/output_script.cpp

[
  {
    "bounded": true,
    "end_line": 484,
    "evidence_id": "3f81f23d241f4327b58d5bbc57b59a5e",
    "finding_id": "finding:5",
    "kind": "new_source",
    "line": 335,
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "c2d5322d4238be81fcbeb317032e148134f16aad",
    "path": "src/rpc/output_script.cpp",
    "revision": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "source_generation": 8,
    "source_job_id": 3167,
    "text": "                            {RPCResult::Type::OBJ, \"\", \"\",\n                            {\n                                {RPCResult::Type::NUM, \"node\", \"The node ID of the child\"},\n                                {RPCResult::Type::STR, \"role\", \"The role of the child in this node: \\\"script\\\", \\\"tapleaf\\\", \\\"wrapped\\\", \\\"left\\\", \\\"right\\\", \\\"condition\\\", \\\"if_true\\\", \\\"if_false\\\" or \\\"threshold_input\\\"\"},\n                                {RPCResult::Type::NUM, \"depth\", /*optional=*/true, \"For a \\\"tapleaf\\\": its depth in the Taproot tree\"},\n                            }},\n                        }},\n                    }},\n                }},\n                {RPCResult::Type::OBJ, \"analysis\", /*optional=*/true, \"Only if verbose is true. \" + HELP_DESCRIPTOR_ANALYSIS, DescriptorAnalysisResultFields()},\n            }\n        },\n        RPCExamples{\n            \"Analyse a descriptor\\n\" +\n            HelpExampleCli(\"getdescriptorinfo\", \"\\\"\" + EXAMPLE_DESCRIPTOR + \"\\\"\") +\n            HelpExampleRpc(\"getdescriptorinfo\", \"\\\"\" + EXAMPLE_DESCRIPTOR + \"\\\"\") +\n            \"Analyse a descriptor, including its keys, policy and multisig analysis\\n\" +\n            HelpExampleCli(\"getdescriptorinfo\", \"\\\"\" + EXAMPLE_DESCRIPTOR + \"\\\" true\")\n        },\n        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue\n        {\n            FlatSigningProvider provider;\n            std::string error;\n            auto descs = Parse(self.Arg<std::string_view>(\"descriptor\"), provider, error);\n            if (descs.empty()) {\n                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);\n            }\n\n            UniValue result(UniValue::VOBJ);\n            result.pushKV(\"descriptor\", descs.at(0)->ToString());\n\n            if (descs.size() > 1) {\n                UniValue multipath_descs(UniValue::VARR);\n                for (const auto& d : descs) {\n                    multipath_descs.push_back(d->ToString());\n                }\n                result.pushKV(\"multipath_expansion\", multipath_descs);\n            }\n\n            result.pushKV(\"checksum\", GetDescriptorChecksum(request.params[0].get_str()));\n            result.pushKV(\"isrange\", descs.at(0)->IsRange());\n            result.pushKV(\"issolvable\", descs.at(0)->IsSolvable());\n            result.pushKV(\"hasprivatekeys\", provider.keys.size() > 0);\n\n            if (self.Arg<bool>(\"verbose\")) {\n                // The analysis refers to the first path's keys and policy.\n                const DescriptorAnalysis analysis{AnalyzeDescriptor(descs)};\n                result.pushKV(\"keys\", DescriptorKeysToUniv(analysis.policy.keys));\n                result.pushKV(\"policy\", DescriptorPolicyToUniv(analysis.policy));\n                result.pushKV(\"analysis\", DescriptorAnalysisToUniv(analysis));\n            }\n            return result;\n        },\n    };\n}\n\nstatic UniValue DeriveAddresses(const Descriptor* desc, int64_t range_begin, int64_t range_end, FlatSigningProvider& key_provider)\n{\n    UniValue addresses(UniValue::VARR);\n\n    for (int64_t i = range_begin; i <= range_end; ++i) {\n        FlatSigningProvider provider;\n        std::vector<CScript> scripts;\n        if (!desc->Expand(i, key_provider, scripts, provider)) {\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Cannot derive script without private keys\");\n        }\n\n        for (const CScript& script : scripts) {\n            CTxDestination dest;\n            if (!ExtractDestination(script, dest)) {\n                // ExtractDestination no longer returns true for P2PK since it doesn't have a corresponding address\n                // However combo will output P2PK and should just ignore that script\n                if (scripts.size() > 1 && std::get_if<PubKeyDestination>(&dest)) {\n                    continue;\n                }\n                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Descriptor does not have a corresponding address\");\n            }\n\n            addresses.push_back(EncodeDestination(dest));\n        }\n    }\n\n    // This should not be possible, but an assert seems overkill:\n    if (addresses.empty()) {\n        throw JSONRPCError(RPC_MISC_ERROR, \"Unexpected empty result\");\n    }\n\n    return addresses;\n}\n\nstatic RPCMethod deriveaddresses()\n{\n    const std::string EXAMPLE_DESCRIPTOR = \"wpkh([d34db33f/84h/0h/0h]xpub6DJ2dNUysrn5Vt36jH2KLBT2i1auw1tTSSomg8PhqNiUtx8QX2SvC9nrHu81fT41fvDUnhMjEzQgXnQjKEu3oaqMSzhSrHMxyyoEAmUHQbY/0/*)#cjjspncu\";\n\n    return RPCMethod{\n        \"deriveaddresses\",\n        \"Derives one or more addresses corresponding to an output descriptor.\\n\"\n         \"Examples of output descriptors are:\\n\"\n         \"    pkh(<pubkey>)                                     P2PKH outputs for the given pubkey\\n\"\n         \"    wpkh(<pubkey>)                                    Native segwit P2PKH outputs for the given pubkey\\n\"\n         \"    sh(multi(<n>,<pubkey>,<pubkey>,...))              P2SH-multisig outputs for the given threshold and pubkeys\\n\"\n         \"    raw(<hex script>)                                 Outputs whose output script equals the specified hex-encoded bytes\\n\"\n         \"    tr(<pubkey>,multi_a(<n>,<pubkey>,<pubkey>,...))   P2TR-multisig outputs for the given threshold and pubkeys\\n\"\n         \"\\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\\n\"\n         \"or more path elements separated by \\\"/\\\", where \\\"h\\\" represents a hardened child key.\\n\"\n        \"For more information on output descriptors, see the documentation in the doc/descriptors.md file.\\n\",\n        {\n            {\"descriptor\", RPCArg::Type::STR, RPCArg::Optional::NO, \"The descriptor.\"},\n            {\"range\", RPCArg::Type::RANGE, RPCArg::Optional::OMITTED, \"If a ranged descriptor is used, this specifies the end or the range (in [begin,end] notation) to derive.\"},\n        },\n        {\n            RPCResult{\"for single derivation descriptors\",\n                RPCResult::Type::ARR, \"\", \"\",\n                {\n                    {RPCResult::Type::STR, \"address\", \"the derived addresses\"},\n                }\n            },\n            RPCResult{\"for multipath descriptors\",\n                RPCResult::Type::ARR, \"\", \"The derived addresses for each of the multipath expansions of the descriptor, in multipath specifier order\",\n                {\n                    {\n                        RPCResult::Type::ARR, \"\", \"The derived addresses for a multipath descriptor expansion\",\n                        {\n                            {RPCResult::Type::STR, \"address\", \"the derived address\"},\n                        },\n                    },\n                },\n            },\n        },\n        RPCExamples{\n            \"First three native segwit receive addresses\\n\" +\n            HelpExampleCli(\"deriveaddresses\", \"\\\"\" + EXAMPLE_DESCRIPTOR + \"\\\" \\\"[0,2]\\\"\") +\n            HelpExampleRpc(\"deriveaddresses\", \"\\\"\" + EXAMPLE_DESCRIPTOR + \"\\\", \\\"[0,2]\\\"\")\n        },\n        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue\n        {\n            auto desc_str{self.Arg<std::string_view>(\"descriptor\")};\n\n            int64_t range_begin = 0;\n            int64_t range_end = 0;\n\n            const UniValue* range = self.MaybeArg<UniValue>(\"range\");\n            if (range) {\n                std::tie(range_begin, range_end) = ParseDescriptorRange(*range);\n            }\n\n            FlatSigningProvider key_provider;\n            std::string error;\n            auto descs = Parse(desc_str, key_provider, error, /* require_checksum = */ true);\n            if (descs.empty()) {",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · c2d5322d4238..386c55a4bfcb

2026-11-26T06:52:03Z · gpt-6-luna

bitcoin#36885Wallet tests miss first-address failure on a later multipath branchsrc/wallet/descriptor_analyzer.cppstill_present
Assessment

The requested regression test for a multipath descriptor whose later branch fails is not present in the supplied evidence. The implementation's clearing behavior already exists in both the old and new excerpts, so it does not establish that the requested test was added.

new_source: src/wallet/descriptor_analyzer.cpp

[
  {
    "bounded": true,
    "end_line": 230,
    "evidence_id": "3132db44bd4a49a8a8e51c44f77649cc",
    "finding_id": "finding:4",
    "kind": "new_source",
    "line": 179,
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "c2d5322d4238be81fcbeb317032e148134f16aad",
    "path": "src/wallet/descriptor_analyzer.cpp",
    "revision": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "source_generation": 8,
    "source_job_id": 3167,
    "text": "    if (!descriptor.Expand(/*pos=*/0, provider, scripts, out)) return std::nullopt;\n    // The first script with an address, as deriveaddresses lists: combo() starts with P2PK, which has none.\n    for (const CScript& script : scripts) {\n        if (CTxDestination dest; ExtractDestination(script, dest)) return dest;\n    }\n    return std::nullopt;\n}\n\n} // namespace\n\nstd::optional<bool> WalletDescriptorAnalysis::CanSign() const\n{\n    // MuSig aggregates are never MINE; their participants are matched instead.\n    bool unknown{false};\n    for (const KeyMatch match : keys) {\n        if (match == KeyMatch::MINE) return true;\n        unknown |= match == KeyMatch::UNKNOWN;\n    }\n    if (unknown) return std::nullopt;\n    return false;\n}\n\nWalletDescriptorAnalysis AnalyzeDescriptor(const CWallet& wallet, std::span<const std::unique_ptr<Descriptor>> descriptors, const SigningProvider& provider)\n{\n    WalletDescriptorAnalysis result;\n    result.analysis = AnalyzeDescriptor(descriptors);\n    if (descriptors.empty()) return result;\n    for (const auto& descriptor : descriptors) {\n        const auto address{FirstAddress(*descriptor, provider)};\n        if (!address) {\n            result.first_addresses.clear();\n            break;\n        }\n        result.first_addresses.push_back(*address);\n    }\n\n    LOCK(wallet.cs_wallet);\n    const HDKeys hd_keys{WalletHDKeys(wallet)};\n    for (const auto& occurrence : result.analysis.policy.keys.occurrences) {\n        const auto& node{occurrence.expression};\n        if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) {\n            result.keys.push_back(MatchExtKey(wallet, hd_keys, key->root, node.origin));\n        } else if (const auto* key{std::get_if<DescriptorKeyInfo::ConstKey>(&node.key)}) {\n            result.keys.push_back(MatchConstKey(wallet, hd_keys, *key, node.origin, occurrence.role));\n        } else {\n            result.keys.push_back(KeyMatch::NOT_MINE);\n        }\n    }\n    return result;\n}\n\n} // namespace wallet",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · c2d5322d4238..386c55a4bfcb

2026-11-26T06:52:03Z · gpt-6-luna

bitcoin#36885Shared origin fingerprints produce no cosigner advisorysrc/script/descriptor_analyzer.cppstill_present
Assessment

The new-head CheckRepeatedKeys() still groups keys using roots, derived keys, and direct-child checks, with no origin-fingerprint warning or separate advisory channel evident in the supplied excerpt.

new_source: src/script/descriptor_analyzer.cpp

[
  {
    "bounded": true,
    "end_line": 301,
    "evidence_id": "b95a961c906a43919a0a91023ddb8d8c",
    "finding_id": "finding:3",
    "kind": "new_source",
    "line": 152,
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "c2d5322d4238be81fcbeb317032e148134f16aad",
    "path": "src/script/descriptor_analyzer.cpp",
    "revision": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "source_generation": 8,
    "source_job_id": 3167,
    "text": "            if (!inserted) Link(it->second, i);\n        }\n    }\n\n    //! Groups of at least two indices, each in index order, listed by its first index.\n    std::vector<std::vector<size_t>> Repeated()\n    {\n        std::vector<std::vector<size_t>> groups(m_parent.size());\n        for (size_t i{0}; i < m_parent.size(); ++i) groups[First(i)].push_back(i);\n        std::erase_if(groups, [](const auto& group) { return group.size() < 2; });\n        return groups;\n    }\n};\n\n/** Report each group of `groups` as one REPEATED_KEY issue, with the occurrence\n *  IDs `ids` gives for its indices. */\nvoid ReportRepeated(DescriptorAnalysis& result, LinkedGroups& groups, const std::vector<size_t>& ids)\n{\n    for (const auto& group : groups.Repeated()) {\n        std::vector<size_t> keys;\n        keys.reserve(group.size());\n        for (const size_t i : group) keys.push_back(ids[i]);\n        result.issues.push_back({IssueKind::REPEATED_KEY, std::move(keys)});\n    }\n}\n\n/** Report every group of cosigner slots held by the same key: slots that share\n *  a root key (e.g. the same xpub with two paths), that derive the same key, or\n *  where one xpub is the direct child of another. Slots linked through a chain\n *  of these are one group. */\nvoid CheckRepeatedKeys(DescriptorAnalysis& result)\n{\n    const auto& occurrences{result.policy.keys.occurrences};\n    const size_t count{result.cosigners.size()};\n    std::vector<std::optional<XOnlyPubKey>> roots, derived;\n    std::vector<const CExtPubKey*> ext_roots;\n    roots.reserve(count);\n    derived.reserve(count);\n    ext_roots.reserve(count);\n    for (const size_t id : result.cosigners) {\n        const auto& node{occurrences.at(id).expression};\n        roots.push_back(RootKey(node));\n        derived.push_back(FirstDerivedKey(node));\n        ext_roots.push_back(RootExtKey(node));\n    }\n    LinkedGroups groups{count};\n    groups.LinkEqual(roots);\n    groups.LinkEqual(derived);\n\n    // Only an xpub whose fingerprint a child names can be its parent, so a\n    // child is derived again only from those, and not when the two slots are\n    // already in one group. Xpubs sharing a root key are one group already, and\n    // can share a fingerprint with any number of chain codes, so only the first\n    // of them is a candidate parent: a child of a later one is left out of the\n    // group, which is reported either way.\n    std::multimap<KeyFingerprint, size_t> by_fingerprint;\n    std::set<XOnlyPubKey> parent_roots;\n    for (size_t i{0}; i < count; ++i) {\n        if (ext_roots[i] && parent_roots.insert(*roots[i]).second) by_fingerprint.emplace(ext_roots[i]->id_key_fingerprint(), i);\n    }\n    for (size_t child{0}; child < count; ++child) {\n        if (!ext_roots[child]) continue;\n        const auto [begin, end]{by_fingerprint.equal_range(ext_roots[child]->fingerprint)};\n        for (auto it{begin}; it != end; ++it) {\n            const size_t parent{it->second};\n            if (groups.First(parent) != groups.First(child) && IsDirectChild(*ext_roots[parent], *ext_roots[child])) {\n                groups.Link(parent, child);\n            }\n        }\n    }\n    ReportRepeated(result, groups, result.cosigners);\n}\n\n/** Check that every cosigner can derive each participant of a musig()\n *  internal key, and that no participant is repeated: participants with the\n *  same root key, or that derive the same key, are one. */\nvoid CheckMuSigParticipants(DescriptorAnalysis& result, size_t internal_id)\n{\n    const auto& occurrences{result.policy.keys.occurrences};\n    const auto* musig{std::get_if<DescriptorKeyInfo::MuSigKey>(&occurrences.at(internal_id).expression.key)};\n    if (!musig) return;\n    const auto& participants{musig->participants};\n    std::vector<std::optional<XOnlyPubKey>> roots, derived;\n    roots.reserve(participants.size());\n    derived.reserve(participants.size());\n    for (const size_t id : participants) {\n        const auto& participant{occurrences.at(id).expression};\n        roots.push_back(RootKey(participant));\n        derived.push_back(roots.back());\n        const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&participant.key)};\n        if (!key) continue;\n        derived.back() = DeriveFirstKey(*key);\n        if (NeedsPrivateDerivation(*key)) {\n            // Other cosigners couldn't derive the key path.\n            result.issues.push_back({IssueKind::HARDENED_DERIVATION, {id}});\n        } else if (!derived.back()) {\n            result.issues.push_back({IssueKind::NOT_DERIVABLE, {id}});\n        }\n    }\n    LinkedGroups groups{participants.size()};\n    groups.LinkEqual(roots);\n    groups.LinkEqual(derived);\n    ReportRepeated(result, groups, participants);\n}\n\n/** Whether a NUMS or musig() internal key can derive its first key. Deriving\n *  fails past the maximum BIP32 depth, and a musig() aggregate starts as an\n *  xpub at depth 0. */\nbool CanDeriveInternalKey(const DescriptorKeyInfo::Node& node)\n{\n    if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) return DeriveFirstKey(*key).has_value();\n    if (const auto* key{std::get_if<DescriptorKeyInfo::MuSigKey>(&node.key)}) {\n        const bool ranged{key->derivation.type == DescriptorKeyInfo::DeriveType::UNHARDENED_RANGED};\n        return key->derivation.path.size() + (ranged ? 1 : 0) <= std::numeric_limits<unsigned char>::max();\n    }\n    return true;\n}\n\n/** Classify the Taproot internal key against the cosigners of the leaf, or\n *  nullopt if it may let fewer than `threshold` cosigners spend. */\nstd::optional<DescriptorAnalysis::KeyPath> ClassifyKeyPath(const DescriptorAnalysis& result, size_t internal_id)\n{\n    const auto& occurrences{result.policy.keys.occurrences};\n    const auto& internal{occurrences.at(internal_id).expression};\n\n    if (const auto* key{std::get_if<DescriptorKeyInfo::ConstKey>(&internal.key)}) {\n        if (XOnlyPubKey{key->pubkey} == XOnlyPubKey::NUMS_H) return DescriptorAnalysis::KeyPath::NUMS;\n    }\n    if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&internal.key)}) {\n        // Unhardened children of H are as unspendable as H.\n        if (XOnlyPubKey{key->root.pubkey} == XOnlyPubKey::NUMS_H && !HasHardenedStep(key->derivation) &&\n            key->derivation.type != DescriptorKeyInfo::DeriveType::HARDENED_RANGED) {\n            return DescriptorAnalysis::KeyPath::NUMS;\n        }\n    }\n    if (const auto* key{std::get_if<DescriptorKeyInfo::MuSigKey>(&internal.key)}) {\n        // Any `threshold` cosigners can already spend through the leaf, so an\n        // aggregate of at least that many distinct cosigners adds no new way to spend.\n        std::set<XOnlyPubKey> cosigner_roots;\n        for (const size_t id : result.cosigners) {\n            if (const auto root{RootKey(occurrences.at(id).expression)}) cosigner_roots.insert(*root);\n        }\n        // A repeated participant adds no cosigner.\n        std::set<XOnlyPubKey> participants;\n        for (const size_t id : key->participants) {\n            const auto root{RootKey(occurrences.at(id).expression)};\n            if (!root || !cosigner_roots.contains(*root)) return std::nullopt;\n            participants.insert(*root);\n        }\n        if (participants.size() >= result.threshold) return DescriptorAnalysis::KeyPath::MUSIG;",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · c2d5322d4238..386c55a4bfcb

2026-11-26T06:52:03Z · gpt-6-luna

bitcoin#36885A wallet meeting the threshold alone has no ownership summarysrc/wallet/descriptor_analyzer.cppstill_present
Assessment

The new-head wallet analyzer still exposes only the per-key match vector and the existing CanSign() result; it adds no owned-cosigner IDs or threshold advisory. The excerpt shows CanSign() returns true on the first MINE key, and the new source retains that behavior.

new_source: src/wallet/descriptor_analyzer.cpp

[
  {
    "bounded": true,
    "end_line": 230,
    "evidence_id": "58574911a85c4d3f925ba8c4951ae1ee",
    "finding_id": "finding:2",
    "kind": "new_source",
    "line": 159,
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "c2d5322d4238be81fcbeb317032e148134f16aad",
    "path": "src/wallet/descriptor_analyzer.cpp",
    "revision": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "source_generation": 8,
    "source_job_id": 3167,
    "text": "{\n    HDKeys hd_keys{.keys = wallet.GetHDPubKeys(CWallet::HDKeyFilter::All), .origins = {}};\n    for (auto* spkm : wallet.GetAllScriptPubKeyMans()) {\n        auto* desc_spkm{dynamic_cast<DescriptorScriptPubKeyMan*>(spkm)};\n        if (!desc_spkm) continue;\n        const auto inventory{WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->GetWalletDescriptor().descriptor->GetKeyInventory())};\n        for (const auto& occurrence : inventory.occurrences) {\n            const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&occurrence.expression.key)};\n            if (!key) continue;\n            if (occurrence.role == DescriptorKeyInventory::Role::MUSIG_PARTICIPANT) hd_keys.keys[key->root].insert(desc_spkm);\n            if (const auto& origin{occurrence.expression.origin}) hd_keys.origins.emplace_back(*origin, key->root);\n        }\n    }\n    return hd_keys;\n}\n\nstd::optional<CTxDestination> FirstAddress(const Descriptor& descriptor, const SigningProvider& provider)\n{\n    std::vector<CScript> scripts;\n    FlatSigningProvider out;\n    if (!descriptor.Expand(/*pos=*/0, provider, scripts, out)) return std::nullopt;\n    // The first script with an address, as deriveaddresses lists: combo() starts with P2PK, which has none.\n    for (const CScript& script : scripts) {\n        if (CTxDestination dest; ExtractDestination(script, dest)) return dest;\n    }\n    return std::nullopt;\n}\n\n} // namespace\n\nstd::optional<bool> WalletDescriptorAnalysis::CanSign() const\n{\n    // MuSig aggregates are never MINE; their participants are matched instead.\n    bool unknown{false};\n    for (const KeyMatch match : keys) {\n        if (match == KeyMatch::MINE) return true;\n        unknown |= match == KeyMatch::UNKNOWN;\n    }\n    if (unknown) return std::nullopt;\n    return false;\n}\n\nWalletDescriptorAnalysis AnalyzeDescriptor(const CWallet& wallet, std::span<const std::unique_ptr<Descriptor>> descriptors, const SigningProvider& provider)\n{\n    WalletDescriptorAnalysis result;\n    result.analysis = AnalyzeDescriptor(descriptors);\n    if (descriptors.empty()) return result;\n    for (const auto& descriptor : descriptors) {\n        const auto address{FirstAddress(*descriptor, provider)};\n        if (!address) {\n            result.first_addresses.clear();\n            break;\n        }\n        result.first_addresses.push_back(*address);\n    }\n\n    LOCK(wallet.cs_wallet);\n    const HDKeys hd_keys{WalletHDKeys(wallet)};\n    for (const auto& occurrence : result.analysis.policy.keys.occurrences) {\n        const auto& node{occurrence.expression};\n        if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) {\n            result.keys.push_back(MatchExtKey(wallet, hd_keys, key->root, node.origin));\n        } else if (const auto* key{std::get_if<DescriptorKeyInfo::ConstKey>(&node.key)}) {\n            result.keys.push_back(MatchConstKey(wallet, hd_keys, *key, node.origin, occurrence.role));\n        } else {\n            result.keys.push_back(KeyMatch::NOT_MINE);\n        }\n    }\n    return result;\n}\n\n} // namespace wallet",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · c2d5322d4238..386c55a4bfcb

2026-11-26T06:52:03Z · gpt-6-luna

bitcoin#36885Locked-wallet tests never combine MINE and UNKNOWNsrc/wallet/test/wallet_interfaces_tests.cppaddressed
Assessment

The locked-wallet test now combines UNKNOWN and MINE entries and asserts CanSign() is true, demonstrating that the uncertain key does not mask a later known-owned key.

path_diff: src/wallet/test/wallet_interfaces_tests.cpp; new_source: src/wallet/test/wallet_interfaces_tests.cpp

[
  {
    "evidence_id": "3dd14c5d0db14deea67cc7f9cedcb29c",
    "finding_id": "finding:9",
    "kind": "path_diff",
    "new_head": "8721e96cc46f544eb8505e6fb3502e934dd0906b",
    "old_head": "cc57e7ad8a31d4a8ca4cd1ddcaa2c5dda6a95aaa",
    "path": "src/wallet/test/wallet_interfaces_tests.cpp",
    "source_generation": 7,
    "source_job_id": 3158,
    "text": "diff --git a/src/wallet/test/wallet_interfaces_tests.cpp b/src/wallet/test/wallet_interfaces_tests.cpp\nindex 515e5b4fca..0ced97b31a 100644\n--- a/src/wallet/test/wallet_interfaces_tests.cpp\n+++ b/src/wallet/test/wallet_interfaces_tests.cpp\n@@ -221,6 +221,13 @@ BOOST_AUTO_TEST_CASE(analyzedescriptor)\n     result = interface->analyzeDescriptor(\"wpkh(\" + EncodeExtPubKey(other.Neuter()) + \"/84h/1h/0h/0/*)\");\n     BOOST_REQUIRE(result);\n     BOOST_CHECK(result->first_addresses.empty());\n+    // All paths or none: a change path that can't be derived leaves out the receive address too.\n+    result = interface->analyzeDescriptor(\"wpkh(\" + EncodeExtPubKey(other.Neuter()) + \"/<0;1h>/*)\");\n+    BOOST_REQUIRE(result);\n+    BOOST_CHECK(result->first_addresses.empty());\n+    result = interface->analyzeDescriptor(\"wpkh(\" + EncodeExtPubKey(other.Neuter()) + \"/<0;1>/*)\");\n+    BOOST_REQUIRE(result);\n+    BOOST_CHECK_EQUAL(result->first_addresses.size(), 2U);\n \n     result = interface->analyzeDescriptor(\"wsh(sortedmulti(2,\");\n     BOOST_REQUIRE(!result);\n@@ -258,6 +265,12 @@ BOOST_AUTO_TEST_CASE(analyzedescriptor_wallet_locked)\n     BOOST_CHECK(result->CanSign() == true);\n     BOOST_CHECK(wallet->IsLocked());\n \n+    // One key it can't tell doesn't hide another that is the wallet's.\n+    result = interface->analyzeDescriptor(\"wsh(sortedmulti(1,\" + AccountKey(master) + \"/0/*,\" + OriginKey(master, {0, 1}) + \"/0/*))\");\n+    BOOST_REQUIRE(result);\n+    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::UNKNOWN, KeyMatch::MINE}));\n+    BOOST_CHECK(result->CanSign() == true);\n+\n     // The account xpub is also held without its private key, but the locked\n     // master may still hold it, so the key stays \"unknown\".\n     AddDescriptor(*wallet, \"wpkh(\" + AccountKey(master) + \"/0/*)\");\n@@ -393,6 +406,44 @@ BOOST_AUTO_TEST_CASE(analyzedescriptor_derived_constant_keys)\n     BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE}));\n }\n \n+BOOST_AUTO_TEST_CASE(analyzedescriptor_account_keys)\n+{\n+    WalletContext context;\n+    context.args = &m_args;\n+    auto wallet = TestCreateWallet(context);\n+    auto interface = interfaces::MakeWallet(context, wallet);\n+\n+    // An account xprv imported with its master's origin, without the master.\n+    const CExtKey master{NewHDKey()};\n+    const std::vector<uint32_t> account_path{0x80000054, 0x80000001, 0x80000000};\n+    const CExtKey account{Assert(DeriveExtKey(master, account_path))->first};\n+    const std::string fingerprint{HexStr(master.Neuter().id_key_fingerprint())};\n+    AddDescriptor(*wallet, \"wpkh([\" + fingerprint + \"/84h/1h/0h]\" + EncodeExtKey(account) + \"/0/*)\");\n+    const auto key_at = [&](const std::vector<uint32_t>& path) { return Assert(DeriveExtKey(account, path))->first.Neuter(); };\n+\n+    // A key the wallet derived, matched through the origin it recorded, which starts at the master.\n+    auto result{interface->analyzeDescriptor(\"wpkh(\" + HexStr(key_at({0, 0}).pubkey) + \")\")};\n+    BOOST_REQUIRE(result);\n+    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE}));\n+    BOOST_CHECK(result->CanSign() == true);\n+\n+    // Keys with an origin below the account's: derived from the account key.\n+    const std::string later{\"[\" + fingerprint + \"/84h/1h/0h/0/5000]\" + HexStr(key_at({0, 5000}).pubkey)};\n+    const std::string child{\"[\" + fingerprint + \"/84h/1h/0h/0]\" + EncodeExtPubKey(key_at({0})) + \"/*\"};\n+    const std::string hardened{\"[\" + fingerprint + \"/84h/1h/0h/1h]\" + EncodeExtPubKey(key_at({0x80000001})) + \"/*\"};\n+    const std::string impostor{\"[\" + fingerprint + \"/84h/1h/0h/0/5000]\" + HexStr(GenerateRandomKey().GetPubKey())};\n+    result = interface->analyzeDescriptor(\"wsh(multi(1,\" + later + \",\" + child + \",\" + hardened + \",\" + impostor + \"))\");\n+    BOOST_REQUIRE(result);\n+    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE, KeyMatch::MINE, KeyMatch::MINE, KeyMatch::NOT_MINE}));\n+\n+    // Only the hardened step needs the private key.\n+    BOOST_REQUIRE(wallet->EncryptWallet(\"hunter2\"));\n+    BOOST_REQUIRE(wallet->Lock());\n+    result = interface->analyzeDescriptor(\"wsh(multi(1,\" + later + \",\" + child + \",\" + hardened + \",\" + impostor + \"))\");\n+    BOOST_REQUIRE(result);\n+    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE, KeyMatch::MINE, KeyMatch::UNKNOWN, KeyMatch::NOT_MINE}));\n+}\n+\n BOOST_AUTO_TEST_CASE(analyzedescriptor_musig_only_keys)\n {\n     WalletContext context;\n",
    "truncated": false,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 365,
    "evidence_id": "acb19800187d45d0bd4ae6d3a938a11c",
    "finding_id": "finding:9",
    "kind": "new_source",
    "line": 216,
    "new_head": "8721e96cc46f544eb8505e6fb3502e934dd0906b",
    "old_head": "cc57e7ad8a31d4a8ca4cd1ddcaa2c5dda6a95aaa",
    "path": "src/wallet/test/wallet_interfaces_tests.cpp",
    "revision": "8721e96cc46f544eb8505e6fb3502e934dd0906b",
    "source_generation": 7,
    "source_job_id": 3158,
    "text": "    BOOST_REQUIRE(result);\n    const auto receive_key{Assert(DeriveExtKey(other, {0x80000054, 0x80000001, 0x80000000, 0, 0}))};\n    BOOST_CHECK(result->first_addresses == std::vector<CTxDestination>({WitnessV0KeyHash{receive_key->first.Neuter().pubkey}}));\n\n    // Without the private key, the hardened steps can't be derived.\n    result = interface->analyzeDescriptor(\"wpkh(\" + EncodeExtPubKey(other.Neuter()) + \"/84h/1h/0h/0/*)\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->first_addresses.empty());\n    // All paths or none: a change path that can't be derived leaves out the receive address too.\n    result = interface->analyzeDescriptor(\"wpkh(\" + EncodeExtPubKey(other.Neuter()) + \"/<0;1h>/*)\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->first_addresses.empty());\n    result = interface->analyzeDescriptor(\"wpkh(\" + EncodeExtPubKey(other.Neuter()) + \"/<0;1>/*)\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK_EQUAL(result->first_addresses.size(), 2U);\n\n    result = interface->analyzeDescriptor(\"wsh(sortedmulti(2,\");\n    BOOST_REQUIRE(!result);\n    BOOST_CHECK(result.error().code == WalletErrorCode::GenericError);\n}\n\nBOOST_AUTO_TEST_CASE(analyzedescriptor_wallet_locked)\n{\n    WalletContext context;\n    context.args = &m_args;\n    auto wallet = TestCreateWallet(context);\n    auto interface = interfaces::MakeWallet(context, wallet);\n    const CExtKey master{NewHDKey()};\n    BOOST_REQUIRE(interface->addHDKey(master));\n    BOOST_REQUIRE(wallet->EncryptWallet(\"hunter2\"));\n    BOOST_REQUIRE(wallet->Lock());\n\n    // Deriving a hardened path needs the private key: a locked wallet can't tell.\n    const std::string derived{\"wsh(sortedmulti(2,\" + AccountKey(master) + R + \",\" + AccountKey(NewHDKey()) + R + \"))\"};\n    auto result{interface->analyzeDescriptor(derived)};\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::UNKNOWN, KeyMatch::NOT_MINE}));\n    BOOST_CHECK(result->CanSign() == std::nullopt);\n\n    // The HD key itself is found without decrypting anything.\n    result = interface->analyzeDescriptor(\"wsh(sortedmulti(1,\" + EncodeExtPubKey(master.Neuter()) + \"/0/*,\" + AccountKey(NewHDKey()) + \"/0/*))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE, KeyMatch::NOT_MINE}));\n    BOOST_CHECK(wallet->IsLocked());\n\n    // So is a key with an unhardened origin path: public derivation needs no private key.\n    result = interface->analyzeDescriptor(\"wsh(sortedmulti(1,\" + OriginKey(master, {0, 1}) + \"/0/*,\" + AccountKey(NewHDKey()) + \"/0/*))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE, KeyMatch::NOT_MINE}));\n    BOOST_CHECK(result->CanSign() == true);\n    BOOST_CHECK(wallet->IsLocked());\n\n    // One key it can't tell doesn't hide another that is the wallet's.\n    result = interface->analyzeDescriptor(\"wsh(sortedmulti(1,\" + AccountKey(master) + \"/0/*,\" + OriginKey(master, {0, 1}) + \"/0/*))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::UNKNOWN, KeyMatch::MINE}));\n    BOOST_CHECK(result->CanSign() == true);\n\n    // The account xpub is also held without its private key, but the locked\n    // master may still hold it, so the key stays \"unknown\".\n    AddDescriptor(*wallet, \"wpkh(\" + AccountKey(master) + \"/0/*)\");\n    result = interface->analyzeDescriptor(derived);\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::UNKNOWN, KeyMatch::NOT_MINE}));\n    BOOST_CHECK(result->CanSign() == std::nullopt);\n\n    BOOST_REQUIRE(wallet->Unlock(\"hunter2\"));\n    result = interface->analyzeDescriptor(derived);\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE, KeyMatch::NOT_MINE}));\n    BOOST_CHECK(result->CanSign() == true);\n}\n\nBOOST_AUTO_TEST_CASE(analyzedescriptor_watch_only_and_constant_keys)\n{\n    WalletContext context;\n    context.args = &m_args;\n    auto wallet = TestCreateWallet(context);\n    auto interface = interfaces::MakeWallet(context, wallet);\n\n    // An xpub the wallet has without its private key.\n    const CExtKey watched_master{NewHDKey()};\n    const std::string watched{EncodeExtPubKey(watched_master.Neuter())};\n    AddDescriptor(*wallet, \"wpkh(\" + watched + \"/0/*)\");\n\n    // A private key whose public key has an odd Y: its x-only form must still match.\n    const CKey key{OddKey()};\n    AddKey(*wallet, key);\n\n    const std::string desc{\"tr(\" + HexStr(XOnlyPubKey::NUMS_H) + \",multi_a(1,\" + watched + \"/0/*,\" + HexStr(XOnlyPubKey{key.GetPubKey()}) + \"))\"};\n    auto result{interface->analyzeDescriptor(desc)};\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::NOT_MINE, KeyMatch::WATCH_ONLY, KeyMatch::MINE}));\n    // A constant cosigner key makes the setup unrecognized, but the wallet can still sign with it.\n    BOOST_CHECK(!result->analysis.IsRecognized());\n    BOOST_CHECK(result->CanSign() == true);\n\n    // In Taproot the even-Y full key is the same key; for ECDSA it is not.\n    const std::string even{\"02\" + HexStr(XOnlyPubKey{key.GetPubKey()})};\n    result = interface->analyzeDescriptor(\"tr(\" + HexStr(XOnlyPubKey::NUMS_H) + \",multi_a(1,\" + even + \"))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::NOT_MINE, KeyMatch::MINE}));\n    result = interface->analyzeDescriptor(\"wsh(multi(1,\" + even + \"))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::NOT_MINE}));\n\n    // Deriving a hardened origin path from a watched xpub is impossible even\n    // when unlocked, so the key is not \"unknown\" and doesn't hide can_sign.\n    result = interface->analyzeDescriptor(\"wsh(sortedmulti(1,\" + AccountKey(watched_master) + \"/0/*,\" + AccountKey(NewHDKey()) + \"/0/*))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::NOT_MINE, KeyMatch::NOT_MINE}));\n    BOOST_CHECK(result->CanSign() == false);\n\n    // A plain public key the wallet has without its private key.\n    const std::string watched_key{HexStr(GenerateRandomKey().GetPubKey())};\n    AddDescriptor(*wallet, \"wpkh(\" + watched_key + \")\");\n    result = interface->analyzeDescriptor(\"wsh(multi(1,\" + watched_key + \"))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::WATCH_ONLY}));\n    BOOST_CHECK(result->CanSign() == false);\n\n    // The watched xpub's private key, imported alone in another descriptor: the\n    // wallet signs with each descriptor's own keys, and none has both the private\n    // key and the chain code, so the xpub is still watch-only, as in gethdkeys.\n    AddDescriptor(*wallet, \"pk(\" + EncodeSecret(watched_master.key) + \")\");\n    result = interface->analyzeDescriptor(\"wsh(multi(1,\" + watched + \"/0/*))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::WATCH_ONLY}));\n    BOOST_CHECK(result->CanSign() == false);\n}\n\nBOOST_AUTO_TEST_CASE(analyzedescriptor_derived_constant_keys)\n{\n    WalletContext context;\n    context.args = &m_args;\n    auto wallet = TestCreateWallet(context);\n    auto interface = interfaces::MakeWallet(context, wallet);\n\n    // The wallet derives receive keys from its HD key, so it stores no private\n    // key for them, only where it derived them.\n    const CExtKey master{NewHDKey()};\n    AddDescriptor(*wallet, \"wpkh(\" + EncodeExtKey(master) + \"/84h/1h/0h/0/*)\");\n    const auto receive_key = [&](uint32_t index) {\n        return HexStr(Assert(DeriveExtKey(master, {0x80000054, 0x80000001, 0x80000000, 0, index}))->first.Neuter().pubkey);\n    };\n    const std::string mine{receive_key(0)};\n    const std::string other{HexStr(GenerateRandomKey().GetPubKey())};\n\n    auto result{interface->analyzeDescriptor(\"wpkh(\" + mine + \")\")};\n    BOOST_REQUIRE(result);",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · cc57e7ad8a31..8721e96cc46f

2026-11-26T05:50:43Z · gpt-6-luna

bitcoin#36885analyzedescriptor omits multipath and format-stability qualificationssrc/wallet/rpc/wallet.cppaddressed
Assessment

The new analyzedescriptor help explicitly says that keys show only the first multipath path while analysis checks every path, and adds the EXPERIMENTAL warning for the keys and analysis formats.

path_diff: src/wallet/rpc/wallet.cpp

[
  {
    "evidence_id": "dd7eb38bd0b14bb0b617b86f64baeacb",
    "finding_id": "finding:7",
    "kind": "path_diff",
    "new_head": "c2d5322d4238be81fcbeb317032e148134f16aad",
    "old_head": "cc57e7ad8a31d4a8ca4cd1ddcaa2c5dda6a95aaa",
    "path": "src/wallet/rpc/wallet.cpp",
    "source_generation": 7,
    "source_job_id": 3158,
    "text": "diff --git a/src/wallet/rpc/wallet.cpp b/src/wallet/rpc/wallet.cpp\nindex 0e7fc16d19..01b4073523 100644\n--- a/src/wallet/rpc/wallet.cpp\n+++ b/src/wallet/rpc/wallet.cpp\n@@ -1082,8 +1082,9 @@ static RPCMethod analyzedescriptor()\n         \"analyzedescriptor\",\n         \"Analyze any descriptor: which of its keys this wallet holds, whether it can sign, its first address on each path, \"\n         \"and whether it is a recognized multisig setup.\\n\"\n-        \"A cosigner key is the wallet's if it is one of the wallet's HD keys, or if its origin fingerprint is one of theirs and deriving \"\n-        \"the origin path gives the same key. That derivation is usually hardened, so it needs the private key: a locked wallet does not \"\n+        \"A cosigner key is the wallet's if it is one of the wallet's HD keys, or if deriving the rest of its origin path from one of them gives the same key: \"\n+        \"from the HD key with the origin fingerprint, or after the origin the wallet's descriptors give that HD key (e.g. an imported account xprv). \"\n+        \"That derivation is usually hardened, so it needs the private key: a locked wallet does not \"\n         \"return an error, but reports such keys as \\\"unknown\\\".\\n\"\n         \"To analyze a descriptor without a wallet, use getdescriptorinfo with verbose set to true.\\n\",\n         {\n@@ -1093,7 +1094,9 @@ static RPCMethod analyzedescriptor()\n             RPCResult::Type::OBJ, \"\", \"\",\n             {\n                 {RPCResult::Type::ARR, \"keys\", \"The public key occurrences, in descriptor order. \"\n-                    \"Array indices are the key IDs used in this result; equal keys remain separate occurrences.\",\n+                    \"Array indices are the key IDs used in this result; equal keys remain separate occurrences. \"\n+                    \"For a multipath descriptor, the keys describe only the first path, while the analysis checks every path.\\n\"\n+                    \"EXPERIMENTAL warning: the format of the keys and analysis may be changed in future releases.\",\n                 {\n                     {RPCResult::Type::OBJ, \"\", \"\", key_fields},\n                 }},\n",
    "truncated": false,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · cc57e7ad8a31..c2d5322d4238

2026-11-26T04:13:37Z · gpt-6-luna

bitcoin#36885Analysis help omits direct-child detection's metadata dependencysrc/rpc/descriptor_util.cppaddressed
Assessment

The help now states that direct-child detection uses the child's parent fingerprint and child number, and explicitly notes that a child with changed metadata cannot be found.

path_diff: src/rpc/descriptor_util.cpp; new_source: src/rpc/descriptor_util.cpp

[
  {
    "evidence_id": "81bdacff386c474299df239356c80fa4",
    "finding_id": "finding:5",
    "kind": "path_diff",
    "new_head": "8721e96cc46f544eb8505e6fb3502e934dd0906b",
    "old_head": "cc57e7ad8a31d4a8ca4cd1ddcaa2c5dda6a95aaa",
    "path": "src/rpc/descriptor_util.cpp",
    "source_generation": 7,
    "source_job_id": 3158,
    "text": "diff --git a/src/rpc/descriptor_util.cpp b/src/rpc/descriptor_util.cpp\nindex df2a5ea328..6ef1542c68 100644\n--- a/src/rpc/descriptor_util.cpp\n+++ b/src/rpc/descriptor_util.cpp\n@@ -27,7 +27,8 @@ const std::string HELP_DESCRIPTOR_ANALYSIS{\"Whether the descriptor is a recogniz\n     \"one where any threshold of the cosigners can spend, and nothing else can. Recognized shapes are wsh(multi) and wsh(sortedmulti), \"\n     \"and tr(K,multi_a) and tr(K,sortedmulti_a) with a single leaf, where K is the BIP 341 NUMS point H or a musig() of at least threshold distinct cosigners. \"\n     \"Every cosigner must be an extended key other than H, with an unhardened ranged derivation that can derive addresses, and no two cosigners may be found to be the same key: \"\n-    \"the same xpub, the same key at the first address, or an xpub and its unhardened child xpub. Other related keys, like a grandchild xpub, can't be found. \"\n+    \"the same xpub, the same key at the first address, or an xpub and its unhardened child xpub, as named by the child's parent fingerprint and child number. \"\n+    \"Other related keys, like a grandchild xpub or a child with that metadata changed, can't be found. \"\n     \"This looks at the descriptor only: it does not say which keys belong to whom. Each cosigner can check their own key with analyzedescriptor.\"};\n \n std::vector<RPCResult> DescriptorKeyResultFields()\n",
    "truncated": false,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 150,
    "evidence_id": "81520483b7aa4e9ba3b61c76043c4e0a",
    "finding_id": "finding:5",
    "kind": "new_source",
    "line": 1,
    "new_head": "8721e96cc46f544eb8505e6fb3502e934dd0906b",
    "old_head": "cc57e7ad8a31d4a8ca4cd1ddcaa2c5dda6a95aaa",
    "path": "src/rpc/descriptor_util.cpp",
    "revision": "8721e96cc46f544eb8505e6fb3502e934dd0906b",
    "source_generation": 7,
    "source_job_id": 3158,
    "text": "// Copyright (c) 2026-present The Bitcoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or https://opensource.org/license/mit.\n\n#include <rpc/descriptor_util.h>\n\n#include <crypto/hex_base.h>\n#include <key_io.h>\n#include <pubkey.h>\n#include <rpc/util.h>\n#include <script/descriptor_analysis.h>\n#include <script/descriptor_analyzer.h>\n#include <script/keyorigin.h>\n#include <univalue.h>\n#include <util/bip32.h>\n#include <util/check.h>\n#include <util/overloaded.h>\n\n#include <optional>\n#include <span>\n#include <string>\n#include <utility>\n#include <variant>\n#include <vector>\n\nconst std::string HELP_DESCRIPTOR_ANALYSIS{\"Whether the descriptor is a recognized k-of-n multisig setup: \"\n    \"one where any threshold of the cosigners can spend, and nothing else can. Recognized shapes are wsh(multi) and wsh(sortedmulti), \"\n    \"and tr(K,multi_a) and tr(K,sortedmulti_a) with a single leaf, where K is the BIP 341 NUMS point H or a musig() of at least threshold distinct cosigners. \"\n    \"Every cosigner must be an extended key other than H, with an unhardened ranged derivation that can derive addresses, and no two cosigners may be found to be the same key: \"\n    \"the same xpub, the same key at the first address, or an xpub and its unhardened child xpub, as named by the child's parent fingerprint and child number. \"\n    \"Other related keys, like a grandchild xpub or a child with that metadata changed, can't be found. \"\n    \"This looks at the descriptor only: it does not say which keys belong to whom. Each cosigner can check their own key with analyzedescriptor.\"};\n\nstd::vector<RPCResult> DescriptorKeyResultFields()\n{\n    return {\n        {RPCResult::Type::STR, \"role\", \"How the key is used: \\\"ecdsa\\\", \\\"taproot_internal\\\", \\\"taproot_output\\\", \\\"tapscript\\\", \\\"musig_participant\\\" or \\\"unused\\\"\"},\n        {RPCResult::Type::STR, \"type\", \"The kind of key expression: \\\"pubkey\\\", \\\"bip32\\\" or \\\"musig\\\"\"},\n        {RPCResult::Type::STR_HEX, \"pubkey\", /*optional=*/true, \"For a \\\"pubkey\\\": the public key, as 32 bytes if x-only\"},\n        {RPCResult::Type::STR, \"xpub\", /*optional=*/true, \"For a \\\"bip32\\\": the extended public key\"},\n        {RPCResult::Type::ARR, \"participants\", /*optional=*/true, \"For a \\\"musig\\\": the key IDs of its participants, in expression order\",\n        {\n            {RPCResult::Type::NUM, \"\", \"Key ID\"},\n        }},\n        {RPCResult::Type::STR, \"derivation\", /*optional=*/true, \"For a \\\"bip32\\\" or \\\"musig\\\": the derivation applied to it, if any, e.g. \\\"/1/*\\\"\"},\n        {RPCResult::Type::OBJ, \"origin\", /*optional=*/true, \"The key origin, if given\",\n        {\n            {RPCResult::Type::STR_HEX, \"master_fingerprint\", \"The fingerprint of the master key\"},\n            {RPCResult::Type::STR, \"path\", \"The derivation path from the master key\"},\n        }},\n    };\n}\n\nstd::vector<RPCResult> DescriptorAnalysisResultFields()\n{\n    return {\n        {RPCResult::Type::BOOL, \"recognized\", \"Whether the descriptor is a recognized setup. If false, only the issues are returned\"},\n        {RPCResult::Type::STR, \"shape\", /*optional=*/true, \"The setup: \\\"wsh_multi\\\" or \\\"tr_multi_a\\\"\"},\n        {RPCResult::Type::BOOL, \"sorted\", /*optional=*/true, \"Whether the keys are sorted (sortedmulti or sortedmulti_a)\"},\n        {RPCResult::Type::STR, \"key_path\", /*optional=*/true, \"For \\\"tr_multi_a\\\": the Taproot internal key, \\\"nums\\\" (unspendable) or \\\"musig\\\" (an aggregate of cosigners)\"},\n        {RPCResult::Type::NUM, \"threshold\", /*optional=*/true, \"The number of cosigners needed to spend\"},\n        {RPCResult::Type::ARR, \"cosigners\", /*optional=*/true, \"The key IDs of the cosigner slots, in expression order\",\n        {\n            {RPCResult::Type::NUM, \"\", \"Key ID\"},\n        }},\n        {RPCResult::Type::ARR, \"issues\", \"Why the descriptor is not recognized. Empty if it is\",\n        {\n            {RPCResult::Type::OBJ, \"\", \"\",\n            {\n                {RPCResult::Type::STR, \"type\", \"\\\"unsupported_shape\\\" (not a recognized shape), \"\n                    \"\\\"repeated_key\\\" (cosigner slots, or musig() participants, held by the same key), \"\n                    \"\\\"key_path_spendable\\\" (the Taproot internal key may let fewer than threshold cosigners spend), \"\n                    \"\\\"not_extended_key\\\" (a cosigner is not an extended key), \"\n                    \"\\\"not_ranged\\\" (a cosigner does not end in an unhardened wildcard), \"\n                    \"\\\"hardened_derivation\\\" (a cosigner or musig() participant needs a private key to derive addresses), \"\n                    \"\\\"not_derivable\\\" (a cosigner, musig() participant or Taproot internal key can't derive addresses, e.g. past the maximum BIP32 depth), \"\n                    \"\\\"unspendable_key\\\" (a cosigner is the NUMS point H, which no one can sign for), or \"\n                    \"\\\"branches_differ\\\" (the paths of a multipath descriptor are not the same setup)\"},\n                {RPCResult::Type::ARR, \"keys\", \"The key IDs involved, if any\",\n                {\n                    {RPCResult::Type::NUM, \"\", \"Key ID\"},\n                }},\n            }},\n        }},\n    };\n}\n\nstatic std::string KeyRoleName(DescriptorKeyInventory::Role role)\n{\n    using Role = DescriptorKeyInventory::Role;\n    switch (role) {\n    case Role::ECDSA: return \"ecdsa\";\n    case Role::TAPROOT_INTERNAL: return \"taproot_internal\";\n    case Role::TAPROOT_OUTPUT: return \"taproot_output\";\n    case Role::TAPSCRIPT: return \"tapscript\";\n    case Role::MUSIG_PARTICIPANT: return \"musig_participant\";\n    case Role::UNUSED: return \"unused\";\n    } // no default case, so the compiler can warn about missing cases\n    NONFATAL_UNREACHABLE();\n}\n\n//! Format a derivation in descriptor syntax, e.g. \"/1/*\". Empty if there is none.\nstatic std::string FormatDerivation(const DescriptorKeyInfo::Derivation& derivation)\n{\n    std::string result{FormatHDKeypath(derivation.path)};\n    switch (derivation.type) {\n    case DescriptorKeyInfo::DeriveType::NON_RANGED: return result;\n    case DescriptorKeyInfo::DeriveType::UNHARDENED_RANGED: return result + \"/*\";\n    case DescriptorKeyInfo::DeriveType::HARDENED_RANGED: return result + \"/*h\";\n    } // no default case, so the compiler can warn about missing cases\n    NONFATAL_UNREACHABLE();\n}\n\nUniValue IdsToUniv(const std::vector<size_t>& ids)\n{\n    UniValue result(UniValue::VARR);\n    for (const size_t id : ids) {\n        result.push_back(id);\n    }\n    return result;\n}\n\nUniValue DescriptorKeysToUniv(const DescriptorKeyInventory& inventory)\n{\n    UniValue keys(UniValue::VARR);\n    for (const auto& occurrence : inventory.occurrences) {\n        UniValue key(UniValue::VOBJ);\n        key.pushKV(\"role\", KeyRoleName(occurrence.role));\n        std::string derivation;\n        std::visit(util::Overloaded{\n            [&](const DescriptorKeyInfo::ConstKey& constant) {\n                key.pushKV(\"type\", \"pubkey\");\n                key.pushKV(\"pubkey\", constant.xonly ? HexStr(XOnlyPubKey{constant.pubkey}) : HexStr(constant.pubkey));\n            },\n            [&](const DescriptorKeyInfo::BIP32Key& bip32) {\n                key.pushKV(\"type\", \"bip32\");\n                key.pushKV(\"xpub\", EncodeExtPubKey(bip32.root));\n                derivation = FormatDerivation(bip32.derivation);\n            },\n            [&](const DescriptorKeyInfo::MuSigKey& musig) {\n                key.pushKV(\"type\", \"musig\");\n                key.pushKV(\"participants\", IdsToUniv(musig.participants));\n                derivation = FormatDerivation(musig.derivation);\n            },\n        }, occurrence.expression.key);\n        if (!derivation.empty()) {\n            key.pushKV(\"derivation\", derivation);\n        }\n        if (const auto& origin{occurrence.expression.origin}) {\n            UniValue origin_obj(UniValue::VOBJ);",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · cc57e7ad8a31..8721e96cc46f

2026-11-26T05:50:43Z · gpt-6-luna

bitcoin#36885No wallet-level advisory identifies threshold-sized local ownershipsrc/wallet/descriptor_analyzer.cppstill_present
Assessment

The wallet analysis continues to provide per-key matches and a `CanSign()` result, while the RPC output still adds only `can_sign` and per-key wallet statuses. No count or IDs of `MINE` cosigner slots and no advisory triggered by reaching the threshold are shown.

path_diff: src/wallet/descriptor_analyzer.cpp; new_source: src/wallet/descriptor_analyzer.cpp

[
  {
    "evidence_id": "25c6502f6e1244e18aca703259171f6b",
    "finding_id": "finding:3",
    "kind": "path_diff",
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "cc57e7ad8a31d4a8ca4cd1ddcaa2c5dda6a95aaa",
    "path": "src/wallet/descriptor_analyzer.cpp",
    "source_generation": 7,
    "source_job_id": 3158,
    "text": "diff --git a/src/wallet/descriptor_analyzer.cpp b/src/wallet/descriptor_analyzer.cpp\nindex 166bd1e8951..33ea2c5431d 100644\n--- a/src/wallet/descriptor_analyzer.cpp\n+++ b/src/wallet/descriptor_analyzer.cpp\n@@ -7,6 +7,7 @@\n #include <key.h>\n #include <pubkey.h>\n #include <script/descriptor.h>\n+#include <script/keyorigin.h>\n #include <script/signingprovider.h>\n #include <sync.h>\n #include <util/bip32.h>\n@@ -45,51 +46,71 @@ KeyMatch Best(KeyMatch a, KeyMatch b)\n     return KeyMatch::NOT_MINE;\n }\n \n+//! The wallet's HD keys, and the origins its descriptors give them.\n+struct HDKeys {\n+    CWallet::HDPubKeyMap keys;\n+    //! E.g. an account xprv imported with its master's origin.\n+    std::vector<std::pair<KeyOriginInfo, CExtPubKey>> origins;\n+};\n+\n+/** Match a key against what deriving `path` from the wallet's HD key `hd_key`\n+ *  gives. `same` tells whether an extended public key is the key. */\n+template <typename Same>\n+KeyMatch MatchPath(const CWallet& wallet, const CExtPubKey& hd_key, const std::set<DescriptorScriptPubKeyMan*>& spkms, const std::vector<uint32_t>& path, Same same)\n+    EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n+{\n+    // Only the descriptors with this key count, as in gethdkeys: the wallet\n+    // signs with each descriptor's own keys, so a private key held alone in\n+    // another descriptor can't sign for it.\n+    const bool has_private{HasPrivKey(spkms, hd_key.pubkey.GetID())};\n+    std::optional<CExtPubKey> derived;\n+    if (!HasHardenedDerivation(path)) {\n+        // Public derivation needs no private key, even when locked.\n+        derived = hd_key;\n+        for (const uint32_t step : path) {\n+            if (!derived->Derive(*derived, step)) return KeyMatch::NOT_MINE;\n+        }\n+    } else if (!has_private) {\n+        // Without the private key this candidate can't be derived; unlocking wouldn't help.\n+        return KeyMatch::NOT_MINE;\n+    } else if (wallet.IsLocked()) {\n+        return KeyMatch::UNKNOWN;\n+    } else if (const auto xprv{wallet.GetExtKey(hd_key)}) {\n+        // Decrypts only this candidate's key.\n+        if (const auto child{DeriveExtKey(*xprv, path)}) derived = child->first.Neuter();\n+    }\n+    if (derived && same(*derived)) return has_private ? KeyMatch::MINE : KeyMatch::WATCH_ONLY;\n+    return KeyMatch::NOT_MINE;\n+}\n+\n /** Match a key against the wallet's HD keys: the key is one of them, or\n- *  deriving `origin`'s path from the one with its fingerprint gives the key.\n- *  `same` tells whether an extended public key is the key. */\n+ *  deriving the rest of `origin`'s path from one of them gives the key. The\n+ *  path starts at the HD key with the origin's fingerprint, or after an origin\n+ *  the wallet's descriptors give an HD key. `same` tells whether an extended\n+ *  public key is the key. */\n template <typename Same>\n-KeyMatch MatchHDKeys(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys, const std::optional<KeyOriginInfo>& origin, Same same)\n+KeyMatch MatchHDKeys(const CWallet& wallet, const HDKeys& hd_keys, const std::optional<KeyOriginInfo>& origin, Same same)\n     EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n     KeyMatch result{KeyMatch::NOT_MINE};\n-    for (const auto& [hd_key, spkms] : hd_keys) {\n-        // Only the descriptors with this key count, as in gethdkeys: the wallet\n-        // signs with each descriptor's own keys, so a private key held alone in\n-        // another descriptor can't sign for it.\n-        const bool has_private{HasPrivKey(spkms, hd_key.pubkey.GetID())};\n-        if (same(hd_key)) {\n-            result = Best(result, has_private ? KeyMatch::MINE : KeyMatch::WATCH_ONLY);\n-            continue;\n-        }\n-        if (!origin || origin->fingerprint != hd_key.id_key_fingerprint()) continue;\n-\n-        std::optional<CExtPubKey> derived;\n-        if (!HasHardenedDerivation(origin->path)) {\n-            // Public derivation needs no private key, even when locked.\n-            derived = hd_key;\n-            for (const uint32_t step : origin->path) {\n-                if (!derived->Derive(*derived, step)) {\n-                    derived.reset();\n-                    break;\n-                }\n-            }\n-        } else if (!has_private) {\n-            // Without the private key this candidate can't be derived; unlocking wouldn't help.\n-            continue;\n-        } else if (wallet.IsLocked()) {\n-            result = Best(result, KeyMatch::UNKNOWN);\n-            continue;\n-        } else if (const auto xprv{wallet.GetExtKey(hd_key)}) {\n-            // Decrypts only this candidate's key.\n-            if (const auto child{DeriveExtKey(*xprv, origin->path)}) derived = child->first.Neuter();\n-        }\n-        if (derived && same(*derived)) result = Best(result, has_private ? KeyMatch::MINE : KeyMatch::WATCH_ONLY);\n+    for (const auto& [hd_key, spkms] : hd_keys.keys) {\n+        result = Best(result, MatchPath(wallet, hd_key, spkms, {}, same));\n+        if (origin && origin->fingerprint == hd_key.id_key_fingerprint()) result = Best(result, MatchPath(wallet, hd_key, spkms, origin->path, same));\n+    }\n+    if (!origin) return result;\n+    for (const auto& [hd_origin, hd_key] : hd_keys.origins) {\n+        const auto& prefix{hd_origin.path};\n+        if (hd_origin.fingerprint != origin->fingerprint || origin->path.size() < prefix.size() ||\n+            !std::equal(prefix.begin(), prefix.end(), origin->path.begin())) continue;\n+        const auto it{hd_keys.keys.find(hd_key)};\n+        if (it == hd_keys.keys.end()) continue;\n+        const std::vector<uint32_t> rest(origin->path.begin() + prefix.size(), origin->path.end());\n+        result = Best(result, MatchPath(wallet, hd_key, it->second, rest, same));\n     }\n     return result;\n }\n \n-KeyMatch MatchExtKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys, const CExtPubKey& key, const std::optional<KeyOriginInfo>& origin)\n+KeyMatch MatchExtKey(const CWallet& wallet, const HDKeys& hd_keys, const CExtPubKey& key, const std::optional<KeyOriginInfo>& origin)\n     EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n     return MatchHDKeys(wallet, hd_keys, origin, [&](const CExtPubKey& candidate) { return SameKey(candidate, key); });\n@@ -99,7 +120,7 @@ KeyMatch MatchExtKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys,\n  *  from one of the wallet's HD keys, with the origin given in the descriptor\n  *  or the one the wallet recorded when it derived the key. A key the wallet\n  *  has derived is at least WATCH_ONLY. */\n-KeyMatch MatchConstKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys, const DescriptorKeyInfo::ConstKey& key,\n+KeyMatch MatchConstKey(const CWallet& wallet, const HDKeys& hd_keys, const DescriptorKeyInfo::ConstKey& key,\n                        const std::optional<KeyOriginInfo>& origin, DescriptorKeyInventory::Role role)\n     EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n@@ -132,17 +153,20 @@ KeyMatch MatchConstKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_key\n }\n \n /** The wallet's HD keys, plus those it holds only as musig() participants,\n- *  which GetHDPubKeys() leaves out because they have no single key to list. */\n-CWallet::HDPubKeyMap WalletHDKeys(const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n+ *  which GetHDPubKeys() leaves out because they have no single key to list,\n+ *  and the origins its descriptors give them. */\n+HDKeys WalletHDKeys(const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n-    CWallet::HDPubKeyMap hd_keys{wallet.GetHDPubKeys(CWallet::HDKeyFilter::All)};\n+    HDKeys hd_keys{.keys = wallet.GetHDPubKeys(CWallet::HDKeyFilter::All), .origins = {}};\n     for (auto* spkm : wallet.GetAllScriptPubKeyMans()) {\n         auto* desc_spkm{dynamic_cast<DescriptorScriptPubKeyMan*>(spkm)};\n         if (!desc_spkm) continue;\n         const auto inventory{WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->GetWalletDescriptor().descriptor->GetKeyInventory())};\n         for (const auto& occurrence : inventory.occurrences) {\n-            if (occurrence.role != DescriptorKeyInventory::Role::MUSIG_PARTICIPANT) continue;\n-            if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&occurrence.expression.key)}) hd_keys[key->root].insert(desc_spkm);\n+            const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&occurrence.expression.key)};\n+            if (!key) continue;\n+            if (occurrence.role == DescriptorKeyInventory::Role::MUSIG_PARTICIPANT) hd_keys.keys[key->root].insert(desc_spkm);\n+            if (const auto& origin{occurrence.expression.origin}) hd_keys.origins.emplace_back(*origin, key->root);\n         }\n     }\n     return hd_keys;\n@@ -189,7 +213,7 @@ WalletDescriptorAnalysis AnalyzeDescriptor(const CWallet& wallet, std::span<cons\n     }\n \n     LOCK(wallet.cs_wallet);\n-    const CWallet::HDPubKeyMap hd_keys{WalletHDKeys(wallet)};\n+    const HDKeys hd_keys{WalletHDKeys(wallet)};\n     for (const auto& occurrence : result.analysis.policy.keys.occurrences) {\n         const auto& node{occurrence.expression};\n         if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) {\n",
    "truncated": false,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 230,
    "evidence_id": "c81f3f5fea374444a9856c075791108f",
    "finding_id": "finding:3",
    "kind": "new_source",
    "line": 140,
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "cc57e7ad8a31d4a8ca4cd1ddcaa2c5dda6a95aaa",
    "path": "src/wallet/descriptor_analyzer.cpp",
    "revision": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "source_generation": 7,
    "source_job_id": 3158,
    "text": "            if (auto recorded{desc_spkm->GetPubKeyOrigin(pubkey)}) {\n                derived = true;\n                origins.push_back(std::move(*recorded));\n            }\n        }\n    }\n\n    const auto same = [&](const CExtPubKey& candidate) {\n        return xonly ? XOnlyPubKey{candidate.pubkey} == XOnlyPubKey{key.pubkey} : candidate.pubkey == key.pubkey;\n    };\n    KeyMatch result{derived ? KeyMatch::WATCH_ONLY : KeyMatch::NOT_MINE};\n    for (const KeyOriginInfo& candidate : origins) result = Best(result, MatchHDKeys(wallet, hd_keys, candidate, same));\n    return result;\n}\n\n/** The wallet's HD keys, plus those it holds only as musig() participants,\n *  which GetHDPubKeys() leaves out because they have no single key to list,\n *  and the origins its descriptors give them. */\nHDKeys WalletHDKeys(const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n{\n    HDKeys hd_keys{.keys = wallet.GetHDPubKeys(CWallet::HDKeyFilter::All), .origins = {}};\n    for (auto* spkm : wallet.GetAllScriptPubKeyMans()) {\n        auto* desc_spkm{dynamic_cast<DescriptorScriptPubKeyMan*>(spkm)};\n        if (!desc_spkm) continue;\n        const auto inventory{WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->GetWalletDescriptor().descriptor->GetKeyInventory())};\n        for (const auto& occurrence : inventory.occurrences) {\n            const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&occurrence.expression.key)};\n            if (!key) continue;\n            if (occurrence.role == DescriptorKeyInventory::Role::MUSIG_PARTICIPANT) hd_keys.keys[key->root].insert(desc_spkm);\n            if (const auto& origin{occurrence.expression.origin}) hd_keys.origins.emplace_back(*origin, key->root);\n        }\n    }\n    return hd_keys;\n}\n\nstd::optional<CTxDestination> FirstAddress(const Descriptor& descriptor, const SigningProvider& provider)\n{\n    std::vector<CScript> scripts;\n    FlatSigningProvider out;\n    if (!descriptor.Expand(/*pos=*/0, provider, scripts, out)) return std::nullopt;\n    // The first script with an address, as deriveaddresses lists: combo() starts with P2PK, which has none.\n    for (const CScript& script : scripts) {\n        if (CTxDestination dest; ExtractDestination(script, dest)) return dest;\n    }\n    return std::nullopt;\n}\n\n} // namespace\n\nstd::optional<bool> WalletDescriptorAnalysis::CanSign() const\n{\n    // MuSig aggregates are never MINE; their participants are matched instead.\n    bool unknown{false};\n    for (const KeyMatch match : keys) {\n        if (match == KeyMatch::MINE) return true;\n        unknown |= match == KeyMatch::UNKNOWN;\n    }\n    if (unknown) return std::nullopt;\n    return false;\n}\n\nWalletDescriptorAnalysis AnalyzeDescriptor(const CWallet& wallet, std::span<const std::unique_ptr<Descriptor>> descriptors, const SigningProvider& provider)\n{\n    WalletDescriptorAnalysis result;\n    result.analysis = AnalyzeDescriptor(descriptors);\n    if (descriptors.empty()) return result;\n    for (const auto& descriptor : descriptors) {\n        const auto address{FirstAddress(*descriptor, provider)};\n        if (!address) {\n            result.first_addresses.clear();\n            break;\n        }\n        result.first_addresses.push_back(*address);\n    }\n\n    LOCK(wallet.cs_wallet);\n    const HDKeys hd_keys{WalletHDKeys(wallet)};\n    for (const auto& occurrence : result.analysis.policy.keys.occurrences) {\n        const auto& node{occurrence.expression};\n        if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) {\n            result.keys.push_back(MatchExtKey(wallet, hd_keys, key->root, node.origin));\n        } else if (const auto* key{std::get_if<DescriptorKeyInfo::ConstKey>(&node.key)}) {\n            result.keys.push_back(MatchConstKey(wallet, hd_keys, *key, node.origin, occurrence.role));\n        } else {\n            result.keys.push_back(KeyMatch::NOT_MINE);\n        }\n    }\n    return result;\n}\n\n} // namespace wallet",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · cc57e7ad8a31..386c55a4bfcb

2026-11-26T06:52:03Z · gpt-6-luna

bitcoin#36885CheckRepeatedKeys repeats quadratic public derivationssrc/script/descriptor_analyzer.cpppartially_addressed
Assessment

The change deduplicates candidate parents that share the same root key, substantially reducing the repeated derivations in the described duplicate-root scenario. It does not cache repeated `(parent xpub, nChild)` derivations or bound work for distinct parent xpubs sharing the relevant fingerprint, so the adversarial candidate-parent cost is not fully addressed.

path_diff: src/script/descriptor_analyzer.cpp; new_source: src/script/descriptor_analyzer.cpp

[
  {
    "evidence_id": "4c59c6ffeac04b5488ce1c45e9975790",
    "finding_id": "finding:2",
    "kind": "path_diff",
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "cc57e7ad8a31d4a8ca4cd1ddcaa2c5dda6a95aaa",
    "path": "src/script/descriptor_analyzer.cpp",
    "source_generation": 7,
    "source_job_id": 3158,
    "text": "diff --git a/src/script/descriptor_analyzer.cpp b/src/script/descriptor_analyzer.cpp\nindex 7610169e02b..f7c893485cd 100644\n--- a/src/script/descriptor_analyzer.cpp\n+++ b/src/script/descriptor_analyzer.cpp\n@@ -200,10 +200,14 @@ void CheckRepeatedKeys(DescriptorAnalysis& result)\n \n     // Only an xpub whose fingerprint a child names can be its parent, so a\n     // child is derived again only from those, and not when the two slots are\n-    // already in one group (e.g. xpubs sharing a root key).\n+    // already in one group. Xpubs sharing a root key are one group already, and\n+    // can share a fingerprint with any number of chain codes, so only the first\n+    // of them is a candidate parent: a child of a later one is left out of the\n+    // group, which is reported either way.\n     std::multimap<KeyFingerprint, size_t> by_fingerprint;\n+    std::set<XOnlyPubKey> parent_roots;\n     for (size_t i{0}; i < count; ++i) {\n-        if (ext_roots[i]) by_fingerprint.emplace(ext_roots[i]->id_key_fingerprint(), i);\n+        if (ext_roots[i] && parent_roots.insert(*roots[i]).second) by_fingerprint.emplace(ext_roots[i]->id_key_fingerprint(), i);\n     }\n     for (size_t child{0}; child < count; ++child) {\n         if (!ext_roots[child]) continue;\n",
    "truncated": false,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 332,
    "evidence_id": "5e272017307b4b0994f3ab98296bdb48",
    "finding_id": "finding:2",
    "kind": "new_source",
    "line": 183,
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "cc57e7ad8a31d4a8ca4cd1ddcaa2c5dda6a95aaa",
    "path": "src/script/descriptor_analyzer.cpp",
    "revision": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "source_generation": 7,
    "source_job_id": 3158,
    "text": "{\n    const auto& occurrences{result.policy.keys.occurrences};\n    const size_t count{result.cosigners.size()};\n    std::vector<std::optional<XOnlyPubKey>> roots, derived;\n    std::vector<const CExtPubKey*> ext_roots;\n    roots.reserve(count);\n    derived.reserve(count);\n    ext_roots.reserve(count);\n    for (const size_t id : result.cosigners) {\n        const auto& node{occurrences.at(id).expression};\n        roots.push_back(RootKey(node));\n        derived.push_back(FirstDerivedKey(node));\n        ext_roots.push_back(RootExtKey(node));\n    }\n    LinkedGroups groups{count};\n    groups.LinkEqual(roots);\n    groups.LinkEqual(derived);\n\n    // Only an xpub whose fingerprint a child names can be its parent, so a\n    // child is derived again only from those, and not when the two slots are\n    // already in one group. Xpubs sharing a root key are one group already, and\n    // can share a fingerprint with any number of chain codes, so only the first\n    // of them is a candidate parent: a child of a later one is left out of the\n    // group, which is reported either way.\n    std::multimap<KeyFingerprint, size_t> by_fingerprint;\n    std::set<XOnlyPubKey> parent_roots;\n    for (size_t i{0}; i < count; ++i) {\n        if (ext_roots[i] && parent_roots.insert(*roots[i]).second) by_fingerprint.emplace(ext_roots[i]->id_key_fingerprint(), i);\n    }\n    for (size_t child{0}; child < count; ++child) {\n        if (!ext_roots[child]) continue;\n        const auto [begin, end]{by_fingerprint.equal_range(ext_roots[child]->fingerprint)};\n        for (auto it{begin}; it != end; ++it) {\n            const size_t parent{it->second};\n            if (groups.First(parent) != groups.First(child) && IsDirectChild(*ext_roots[parent], *ext_roots[child])) {\n                groups.Link(parent, child);\n            }\n        }\n    }\n    ReportRepeated(result, groups, result.cosigners);\n}\n\n/** Check that every cosigner can derive each participant of a musig()\n *  internal key, and that no participant is repeated: participants with the\n *  same root key, or that derive the same key, are one. */\nvoid CheckMuSigParticipants(DescriptorAnalysis& result, size_t internal_id)\n{\n    const auto& occurrences{result.policy.keys.occurrences};\n    const auto* musig{std::get_if<DescriptorKeyInfo::MuSigKey>(&occurrences.at(internal_id).expression.key)};\n    if (!musig) return;\n    const auto& participants{musig->participants};\n    std::vector<std::optional<XOnlyPubKey>> roots, derived;\n    roots.reserve(participants.size());\n    derived.reserve(participants.size());\n    for (const size_t id : participants) {\n        const auto& participant{occurrences.at(id).expression};\n        roots.push_back(RootKey(participant));\n        derived.push_back(roots.back());\n        const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&participant.key)};\n        if (!key) continue;\n        derived.back() = DeriveFirstKey(*key);\n        if (NeedsPrivateDerivation(*key)) {\n            // Other cosigners couldn't derive the key path.\n            result.issues.push_back({IssueKind::HARDENED_DERIVATION, {id}});\n        } else if (!derived.back()) {\n            result.issues.push_back({IssueKind::NOT_DERIVABLE, {id}});\n        }\n    }\n    LinkedGroups groups{participants.size()};\n    groups.LinkEqual(roots);\n    groups.LinkEqual(derived);\n    ReportRepeated(result, groups, participants);\n}\n\n/** Whether a NUMS or musig() internal key can derive its first key. Deriving\n *  fails past the maximum BIP32 depth, and a musig() aggregate starts as an\n *  xpub at depth 0. */\nbool CanDeriveInternalKey(const DescriptorKeyInfo::Node& node)\n{\n    if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) return DeriveFirstKey(*key).has_value();\n    if (const auto* key{std::get_if<DescriptorKeyInfo::MuSigKey>(&node.key)}) {\n        const bool ranged{key->derivation.type == DescriptorKeyInfo::DeriveType::UNHARDENED_RANGED};\n        return key->derivation.path.size() + (ranged ? 1 : 0) <= std::numeric_limits<unsigned char>::max();\n    }\n    return true;\n}\n\n/** Classify the Taproot internal key against the cosigners of the leaf, or\n *  nullopt if it may let fewer than `threshold` cosigners spend. */\nstd::optional<DescriptorAnalysis::KeyPath> ClassifyKeyPath(const DescriptorAnalysis& result, size_t internal_id)\n{\n    const auto& occurrences{result.policy.keys.occurrences};\n    const auto& internal{occurrences.at(internal_id).expression};\n\n    if (const auto* key{std::get_if<DescriptorKeyInfo::ConstKey>(&internal.key)}) {\n        if (XOnlyPubKey{key->pubkey} == XOnlyPubKey::NUMS_H) return DescriptorAnalysis::KeyPath::NUMS;\n    }\n    if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&internal.key)}) {\n        // Unhardened children of H are as unspendable as H.\n        if (XOnlyPubKey{key->root.pubkey} == XOnlyPubKey::NUMS_H && !HasHardenedStep(key->derivation) &&\n            key->derivation.type != DescriptorKeyInfo::DeriveType::HARDENED_RANGED) {\n            return DescriptorAnalysis::KeyPath::NUMS;\n        }\n    }\n    if (const auto* key{std::get_if<DescriptorKeyInfo::MuSigKey>(&internal.key)}) {\n        // Any `threshold` cosigners can already spend through the leaf, so an\n        // aggregate of at least that many distinct cosigners adds no new way to spend.\n        std::set<XOnlyPubKey> cosigner_roots;\n        for (const size_t id : result.cosigners) {\n            if (const auto root{RootKey(occurrences.at(id).expression)}) cosigner_roots.insert(*root);\n        }\n        // A repeated participant adds no cosigner.\n        std::set<XOnlyPubKey> participants;\n        for (const size_t id : key->participants) {\n            const auto root{RootKey(occurrences.at(id).expression)};\n            if (!root || !cosigner_roots.contains(*root)) return std::nullopt;\n            participants.insert(*root);\n        }\n        if (participants.size() >= result.threshold) return DescriptorAnalysis::KeyPath::MUSIG;\n    }\n    return std::nullopt;\n}\n\n/** Mark the result unrecognized and drop the setup it would have claimed. */\nvoid Unrecognize(DescriptorAnalysis& result)\n{\n    result.shape = DescriptorAnalysis::Shape::UNRECOGNIZED;\n    result.sorted = false;\n    result.key_path = DescriptorAnalysis::KeyPath::NONE;\n    result.threshold = 0;\n    result.cosigners.clear();\n}\n\n/** Find the multisig node of a recognized shape, or nullptr. */\nconst DescriptorPolicy::Node* FindMultisig(DescriptorAnalysis& result)\n{\n    const auto& nodes{result.policy.nodes};\n    if (nodes.empty()) return nullptr;\n    const auto* root_kind{NodeKind(nodes[0])};\n    if (!root_kind || nodes[0].children.size() != 1) return nullptr;\n    const auto& child{nodes[0].children[0]};\n    const auto& multisig{nodes.at(child.node)};\n    const auto* kind{NodeKind(multisig)};\n    if (!kind || !multisig.children.empty()) return nullptr;\n\n    if (*root_kind == Kind::WSH && (*kind == Kind::MULTI || *kind == Kind::SORTEDMULTI)) {\n        result.shape = DescriptorAnalysis::Shape::WSH_MULTI;\n        result.sorted = *kind == Kind::SORTEDMULTI;\n        return &multisig;\n    }",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · cc57e7ad8a31..386c55a4bfcb

2026-11-26T06:52:03Z · gpt-6-luna

bitcoin#36885Analysis helpers are introduced and repackaged two commits latersrc/rpc/output_script.cppunclear
Assessment

The supplied diff changes the RPC help wording about recognition and external signers, but does not show the referenced helper extraction/repackaging commits or the final shared-file implementation history. The supplied evidence therefore cannot establish whether the requested staged commit organization was corrected.

old_source: src/rpc/output_script.cpp; new_source: src/rpc/output_script.cpp

[
  {
    "bounded": true,
    "end_line": 484,
    "evidence_id": "02d057c7cdaf4618b81474a0eeba7361",
    "finding_id": "finding:12",
    "kind": "old_source",
    "line": 335,
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "cc57e7ad8a31d4a8ca4cd1ddcaa2c5dda6a95aaa",
    "path": "src/rpc/output_script.cpp",
    "revision": "cc57e7ad8a31d4a8ca4cd1ddcaa2c5dda6a95aaa",
    "source_generation": 7,
    "source_job_id": 3158,
    "text": "                            {RPCResult::Type::OBJ, \"\", \"\",\n                            {\n                                {RPCResult::Type::NUM, \"node\", \"The node ID of the child\"},\n                                {RPCResult::Type::STR, \"role\", \"The role of the child in this node: \\\"script\\\", \\\"tapleaf\\\", \\\"wrapped\\\", \\\"left\\\", \\\"right\\\", \\\"condition\\\", \\\"if_true\\\", \\\"if_false\\\" or \\\"threshold_input\\\"\"},\n                                {RPCResult::Type::NUM, \"depth\", /*optional=*/true, \"For a \\\"tapleaf\\\": its depth in the Taproot tree\"},\n                            }},\n                        }},\n                    }},\n                }},\n                {RPCResult::Type::OBJ, \"analysis\", /*optional=*/true, \"Only if verbose is true. \" + HELP_DESCRIPTOR_ANALYSIS, DescriptorAnalysisResultFields()},\n            }\n        },\n        RPCExamples{\n            \"Analyse a descriptor\\n\" +\n            HelpExampleCli(\"getdescriptorinfo\", \"\\\"\" + EXAMPLE_DESCRIPTOR + \"\\\"\") +\n            HelpExampleRpc(\"getdescriptorinfo\", \"\\\"\" + EXAMPLE_DESCRIPTOR + \"\\\"\") +\n            \"Analyse a descriptor, including its keys, policy and multisig analysis\\n\" +\n            HelpExampleCli(\"getdescriptorinfo\", \"\\\"\" + EXAMPLE_DESCRIPTOR + \"\\\" true\")\n        },\n        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue\n        {\n            FlatSigningProvider provider;\n            std::string error;\n            auto descs = Parse(self.Arg<std::string_view>(\"descriptor\"), provider, error);\n            if (descs.empty()) {\n                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);\n            }\n\n            UniValue result(UniValue::VOBJ);\n            result.pushKV(\"descriptor\", descs.at(0)->ToString());\n\n            if (descs.size() > 1) {\n                UniValue multipath_descs(UniValue::VARR);\n                for (const auto& d : descs) {\n                    multipath_descs.push_back(d->ToString());\n                }\n                result.pushKV(\"multipath_expansion\", multipath_descs);\n            }\n\n            result.pushKV(\"checksum\", GetDescriptorChecksum(request.params[0].get_str()));\n            result.pushKV(\"isrange\", descs.at(0)->IsRange());\n            result.pushKV(\"issolvable\", descs.at(0)->IsSolvable());\n            result.pushKV(\"hasprivatekeys\", provider.keys.size() > 0);\n\n            if (self.Arg<bool>(\"verbose\")) {\n                // The analysis refers to the first path's keys and policy.\n                const DescriptorAnalysis analysis{AnalyzeDescriptor(descs)};\n                result.pushKV(\"keys\", DescriptorKeysToUniv(analysis.policy.keys));\n                result.pushKV(\"policy\", DescriptorPolicyToUniv(analysis.policy));\n                result.pushKV(\"analysis\", DescriptorAnalysisToUniv(analysis));\n            }\n            return result;\n        },\n    };\n}\n\nstatic UniValue DeriveAddresses(const Descriptor* desc, int64_t range_begin, int64_t range_end, FlatSigningProvider& key_provider)\n{\n    UniValue addresses(UniValue::VARR);\n\n    for (int64_t i = range_begin; i <= range_end; ++i) {\n        FlatSigningProvider provider;\n        std::vector<CScript> scripts;\n        if (!desc->Expand(i, key_provider, scripts, provider)) {\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Cannot derive script without private keys\");\n        }\n\n        for (const CScript& script : scripts) {\n            CTxDestination dest;\n            if (!ExtractDestination(script, dest)) {\n                // ExtractDestination no longer returns true for P2PK since it doesn't have a corresponding address\n                // However combo will output P2PK and should just ignore that script\n                if (scripts.size() > 1 && std::get_if<PubKeyDestination>(&dest)) {\n                    continue;\n                }\n                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Descriptor does not have a corresponding address\");\n            }\n\n            addresses.push_back(EncodeDestination(dest));\n        }\n    }\n\n    // This should not be possible, but an assert seems overkill:\n    if (addresses.empty()) {\n        throw JSONRPCError(RPC_MISC_ERROR, \"Unexpected empty result\");\n    }\n\n    return addresses;\n}\n\nstatic RPCMethod deriveaddresses()\n{\n    const std::string EXAMPLE_DESCRIPTOR = \"wpkh([d34db33f/84h/0h/0h]xpub6DJ2dNUysrn5Vt36jH2KLBT2i1auw1tTSSomg8PhqNiUtx8QX2SvC9nrHu81fT41fvDUnhMjEzQgXnQjKEu3oaqMSzhSrHMxyyoEAmUHQbY/0/*)#cjjspncu\";\n\n    return RPCMethod{\n        \"deriveaddresses\",\n        \"Derives one or more addresses corresponding to an output descriptor.\\n\"\n         \"Examples of output descriptors are:\\n\"\n         \"    pkh(<pubkey>)                                     P2PKH outputs for the given pubkey\\n\"\n         \"    wpkh(<pubkey>)                                    Native segwit P2PKH outputs for the given pubkey\\n\"\n         \"    sh(multi(<n>,<pubkey>,<pubkey>,...))              P2SH-multisig outputs for the given threshold and pubkeys\\n\"\n         \"    raw(<hex script>)                                 Outputs whose output script equals the specified hex-encoded bytes\\n\"\n         \"    tr(<pubkey>,multi_a(<n>,<pubkey>,<pubkey>,...))   P2TR-multisig outputs for the given threshold and pubkeys\\n\"\n         \"\\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\\n\"\n         \"or more path elements separated by \\\"/\\\", where \\\"h\\\" represents a hardened child key.\\n\"\n        \"For more information on output descriptors, see the documentation in the doc/descriptors.md file.\\n\",\n        {\n            {\"descriptor\", RPCArg::Type::STR, RPCArg::Optional::NO, \"The descriptor.\"},\n            {\"range\", RPCArg::Type::RANGE, RPCArg::Optional::OMITTED, \"If a ranged descriptor is used, this specifies the end or the range (in [begin,end] notation) to derive.\"},\n        },\n        {\n            RPCResult{\"for single derivation descriptors\",\n                RPCResult::Type::ARR, \"\", \"\",\n                {\n                    {RPCResult::Type::STR, \"address\", \"the derived addresses\"},\n                }\n            },\n            RPCResult{\"for multipath descriptors\",\n                RPCResult::Type::ARR, \"\", \"The derived addresses for each of the multipath expansions of the descriptor, in multipath specifier order\",\n                {\n                    {\n                        RPCResult::Type::ARR, \"\", \"The derived addresses for a multipath descriptor expansion\",\n                        {\n                            {RPCResult::Type::STR, \"address\", \"the derived address\"},\n                        },\n                    },\n                },\n            },\n        },\n        RPCExamples{\n            \"First three native segwit receive addresses\\n\" +\n            HelpExampleCli(\"deriveaddresses\", \"\\\"\" + EXAMPLE_DESCRIPTOR + \"\\\" \\\"[0,2]\\\"\") +\n            HelpExampleRpc(\"deriveaddresses\", \"\\\"\" + EXAMPLE_DESCRIPTOR + \"\\\", \\\"[0,2]\\\"\")\n        },\n        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue\n        {\n            auto desc_str{self.Arg<std::string_view>(\"descriptor\")};\n\n            int64_t range_begin = 0;\n            int64_t range_end = 0;\n\n            const UniValue* range = self.MaybeArg<UniValue>(\"range\");\n            if (range) {\n                std::tie(range_begin, range_end) = ParseDescriptorRange(*range);\n            }\n\n            FlatSigningProvider key_provider;\n            std::string error;\n            auto descs = Parse(desc_str, key_provider, error, /* require_checksum = */ true);\n            if (descs.empty()) {",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 484,
    "evidence_id": "cf74002297964cc6853519336ca900dd",
    "finding_id": "finding:12",
    "kind": "new_source",
    "line": 335,
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "cc57e7ad8a31d4a8ca4cd1ddcaa2c5dda6a95aaa",
    "path": "src/rpc/output_script.cpp",
    "revision": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "source_generation": 7,
    "source_job_id": 3158,
    "text": "                            {RPCResult::Type::OBJ, \"\", \"\",\n                            {\n                                {RPCResult::Type::NUM, \"node\", \"The node ID of the child\"},\n                                {RPCResult::Type::STR, \"role\", \"The role of the child in this node: \\\"script\\\", \\\"tapleaf\\\", \\\"wrapped\\\", \\\"left\\\", \\\"right\\\", \\\"condition\\\", \\\"if_true\\\", \\\"if_false\\\" or \\\"threshold_input\\\"\"},\n                                {RPCResult::Type::NUM, \"depth\", /*optional=*/true, \"For a \\\"tapleaf\\\": its depth in the Taproot tree\"},\n                            }},\n                        }},\n                    }},\n                }},\n                {RPCResult::Type::OBJ, \"analysis\", /*optional=*/true, \"Only if verbose is true. \" + HELP_DESCRIPTOR_ANALYSIS, DescriptorAnalysisResultFields()},\n            }\n        },\n        RPCExamples{\n            \"Analyse a descriptor\\n\" +\n            HelpExampleCli(\"getdescriptorinfo\", \"\\\"\" + EXAMPLE_DESCRIPTOR + \"\\\"\") +\n            HelpExampleRpc(\"getdescriptorinfo\", \"\\\"\" + EXAMPLE_DESCRIPTOR + \"\\\"\") +\n            \"Analyse a descriptor, including its keys, policy and multisig analysis\\n\" +\n            HelpExampleCli(\"getdescriptorinfo\", \"\\\"\" + EXAMPLE_DESCRIPTOR + \"\\\" true\")\n        },\n        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue\n        {\n            FlatSigningProvider provider;\n            std::string error;\n            auto descs = Parse(self.Arg<std::string_view>(\"descriptor\"), provider, error);\n            if (descs.empty()) {\n                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);\n            }\n\n            UniValue result(UniValue::VOBJ);\n            result.pushKV(\"descriptor\", descs.at(0)->ToString());\n\n            if (descs.size() > 1) {\n                UniValue multipath_descs(UniValue::VARR);\n                for (const auto& d : descs) {\n                    multipath_descs.push_back(d->ToString());\n                }\n                result.pushKV(\"multipath_expansion\", multipath_descs);\n            }\n\n            result.pushKV(\"checksum\", GetDescriptorChecksum(request.params[0].get_str()));\n            result.pushKV(\"isrange\", descs.at(0)->IsRange());\n            result.pushKV(\"issolvable\", descs.at(0)->IsSolvable());\n            result.pushKV(\"hasprivatekeys\", provider.keys.size() > 0);\n\n            if (self.Arg<bool>(\"verbose\")) {\n                // The analysis refers to the first path's keys and policy.\n                const DescriptorAnalysis analysis{AnalyzeDescriptor(descs)};\n                result.pushKV(\"keys\", DescriptorKeysToUniv(analysis.policy.keys));\n                result.pushKV(\"policy\", DescriptorPolicyToUniv(analysis.policy));\n                result.pushKV(\"analysis\", DescriptorAnalysisToUniv(analysis));\n            }\n            return result;\n        },\n    };\n}\n\nstatic UniValue DeriveAddresses(const Descriptor* desc, int64_t range_begin, int64_t range_end, FlatSigningProvider& key_provider)\n{\n    UniValue addresses(UniValue::VARR);\n\n    for (int64_t i = range_begin; i <= range_end; ++i) {\n        FlatSigningProvider provider;\n        std::vector<CScript> scripts;\n        if (!desc->Expand(i, key_provider, scripts, provider)) {\n            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Cannot derive script without private keys\");\n        }\n\n        for (const CScript& script : scripts) {\n            CTxDestination dest;\n            if (!ExtractDestination(script, dest)) {\n                // ExtractDestination no longer returns true for P2PK since it doesn't have a corresponding address\n                // However combo will output P2PK and should just ignore that script\n                if (scripts.size() > 1 && std::get_if<PubKeyDestination>(&dest)) {\n                    continue;\n                }\n                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Descriptor does not have a corresponding address\");\n            }\n\n            addresses.push_back(EncodeDestination(dest));\n        }\n    }\n\n    // This should not be possible, but an assert seems overkill:\n    if (addresses.empty()) {\n        throw JSONRPCError(RPC_MISC_ERROR, \"Unexpected empty result\");\n    }\n\n    return addresses;\n}\n\nstatic RPCMethod deriveaddresses()\n{\n    const std::string EXAMPLE_DESCRIPTOR = \"wpkh([d34db33f/84h/0h/0h]xpub6DJ2dNUysrn5Vt36jH2KLBT2i1auw1tTSSomg8PhqNiUtx8QX2SvC9nrHu81fT41fvDUnhMjEzQgXnQjKEu3oaqMSzhSrHMxyyoEAmUHQbY/0/*)#cjjspncu\";\n\n    return RPCMethod{\n        \"deriveaddresses\",\n        \"Derives one or more addresses corresponding to an output descriptor.\\n\"\n         \"Examples of output descriptors are:\\n\"\n         \"    pkh(<pubkey>)                                     P2PKH outputs for the given pubkey\\n\"\n         \"    wpkh(<pubkey>)                                    Native segwit P2PKH outputs for the given pubkey\\n\"\n         \"    sh(multi(<n>,<pubkey>,<pubkey>,...))              P2SH-multisig outputs for the given threshold and pubkeys\\n\"\n         \"    raw(<hex script>)                                 Outputs whose output script equals the specified hex-encoded bytes\\n\"\n         \"    tr(<pubkey>,multi_a(<n>,<pubkey>,<pubkey>,...))   P2TR-multisig outputs for the given threshold and pubkeys\\n\"\n         \"\\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\\n\"\n         \"or more path elements separated by \\\"/\\\", where \\\"h\\\" represents a hardened child key.\\n\"\n        \"For more information on output descriptors, see the documentation in the doc/descriptors.md file.\\n\",\n        {\n            {\"descriptor\", RPCArg::Type::STR, RPCArg::Optional::NO, \"The descriptor.\"},\n            {\"range\", RPCArg::Type::RANGE, RPCArg::Optional::OMITTED, \"If a ranged descriptor is used, this specifies the end or the range (in [begin,end] notation) to derive.\"},\n        },\n        {\n            RPCResult{\"for single derivation descriptors\",\n                RPCResult::Type::ARR, \"\", \"\",\n                {\n                    {RPCResult::Type::STR, \"address\", \"the derived addresses\"},\n                }\n            },\n            RPCResult{\"for multipath descriptors\",\n                RPCResult::Type::ARR, \"\", \"The derived addresses for each of the multipath expansions of the descriptor, in multipath specifier order\",\n                {\n                    {\n                        RPCResult::Type::ARR, \"\", \"The derived addresses for a multipath descriptor expansion\",\n                        {\n                            {RPCResult::Type::STR, \"address\", \"the derived address\"},\n                        },\n                    },\n                },\n            },\n        },\n        RPCExamples{\n            \"First three native segwit receive addresses\\n\" +\n            HelpExampleCli(\"deriveaddresses\", \"\\\"\" + EXAMPLE_DESCRIPTOR + \"\\\" \\\"[0,2]\\\"\") +\n            HelpExampleRpc(\"deriveaddresses\", \"\\\"\" + EXAMPLE_DESCRIPTOR + \"\\\", \\\"[0,2]\\\"\")\n        },\n        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue\n        {\n            auto desc_str{self.Arg<std::string_view>(\"descriptor\")};\n\n            int64_t range_begin = 0;\n            int64_t range_end = 0;\n\n            const UniValue* range = self.MaybeArg<UniValue>(\"range\");\n            if (range) {\n                std::tie(range_begin, range_end) = ParseDescriptorRange(*range);\n            }\n\n            FlatSigningProvider key_provider;\n            std::string error;\n            auto descs = Parse(desc_str, key_provider, error, /* require_checksum = */ true);\n            if (descs.empty()) {",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · cc57e7ad8a31..386c55a4bfcb

2026-11-26T06:52:03Z · gpt-6-luna

bitcoin#36885WalletHDKeys duplicates descriptor traversal and cache copies under cs_walletsrc/wallet/descriptor_analyzer.cppstill_present
Assessment

Although the inventory loop now processes every BIP32 occurrence, `WalletHDKeys()` still initializes the keys map from `wallet.GetHDPubKeys(...)`, which independently traverses descriptors and copies wallet descriptors. The requested empty-map, inventory-only construction and accessor avoiding the second cache copy are not present.

path_diff: src/wallet/descriptor_analyzer.cpp; new_source: src/wallet/descriptor_analyzer.cpp

[
  {
    "evidence_id": "dd89b3b1185c40158376b3fb49718499",
    "finding_id": "finding:11",
    "kind": "path_diff",
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "cc57e7ad8a31d4a8ca4cd1ddcaa2c5dda6a95aaa",
    "path": "src/wallet/descriptor_analyzer.cpp",
    "source_generation": 7,
    "source_job_id": 3158,
    "text": "diff --git a/src/wallet/descriptor_analyzer.cpp b/src/wallet/descriptor_analyzer.cpp\nindex 166bd1e8951..33ea2c5431d 100644\n--- a/src/wallet/descriptor_analyzer.cpp\n+++ b/src/wallet/descriptor_analyzer.cpp\n@@ -7,6 +7,7 @@\n #include <key.h>\n #include <pubkey.h>\n #include <script/descriptor.h>\n+#include <script/keyorigin.h>\n #include <script/signingprovider.h>\n #include <sync.h>\n #include <util/bip32.h>\n@@ -45,51 +46,71 @@ KeyMatch Best(KeyMatch a, KeyMatch b)\n     return KeyMatch::NOT_MINE;\n }\n \n+//! The wallet's HD keys, and the origins its descriptors give them.\n+struct HDKeys {\n+    CWallet::HDPubKeyMap keys;\n+    //! E.g. an account xprv imported with its master's origin.\n+    std::vector<std::pair<KeyOriginInfo, CExtPubKey>> origins;\n+};\n+\n+/** Match a key against what deriving `path` from the wallet's HD key `hd_key`\n+ *  gives. `same` tells whether an extended public key is the key. */\n+template <typename Same>\n+KeyMatch MatchPath(const CWallet& wallet, const CExtPubKey& hd_key, const std::set<DescriptorScriptPubKeyMan*>& spkms, const std::vector<uint32_t>& path, Same same)\n+    EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n+{\n+    // Only the descriptors with this key count, as in gethdkeys: the wallet\n+    // signs with each descriptor's own keys, so a private key held alone in\n+    // another descriptor can't sign for it.\n+    const bool has_private{HasPrivKey(spkms, hd_key.pubkey.GetID())};\n+    std::optional<CExtPubKey> derived;\n+    if (!HasHardenedDerivation(path)) {\n+        // Public derivation needs no private key, even when locked.\n+        derived = hd_key;\n+        for (const uint32_t step : path) {\n+            if (!derived->Derive(*derived, step)) return KeyMatch::NOT_MINE;\n+        }\n+    } else if (!has_private) {\n+        // Without the private key this candidate can't be derived; unlocking wouldn't help.\n+        return KeyMatch::NOT_MINE;\n+    } else if (wallet.IsLocked()) {\n+        return KeyMatch::UNKNOWN;\n+    } else if (const auto xprv{wallet.GetExtKey(hd_key)}) {\n+        // Decrypts only this candidate's key.\n+        if (const auto child{DeriveExtKey(*xprv, path)}) derived = child->first.Neuter();\n+    }\n+    if (derived && same(*derived)) return has_private ? KeyMatch::MINE : KeyMatch::WATCH_ONLY;\n+    return KeyMatch::NOT_MINE;\n+}\n+\n /** Match a key against the wallet's HD keys: the key is one of them, or\n- *  deriving `origin`'s path from the one with its fingerprint gives the key.\n- *  `same` tells whether an extended public key is the key. */\n+ *  deriving the rest of `origin`'s path from one of them gives the key. The\n+ *  path starts at the HD key with the origin's fingerprint, or after an origin\n+ *  the wallet's descriptors give an HD key. `same` tells whether an extended\n+ *  public key is the key. */\n template <typename Same>\n-KeyMatch MatchHDKeys(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys, const std::optional<KeyOriginInfo>& origin, Same same)\n+KeyMatch MatchHDKeys(const CWallet& wallet, const HDKeys& hd_keys, const std::optional<KeyOriginInfo>& origin, Same same)\n     EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n     KeyMatch result{KeyMatch::NOT_MINE};\n-    for (const auto& [hd_key, spkms] : hd_keys) {\n-        // Only the descriptors with this key count, as in gethdkeys: the wallet\n-        // signs with each descriptor's own keys, so a private key held alone in\n-        // another descriptor can't sign for it.\n-        const bool has_private{HasPrivKey(spkms, hd_key.pubkey.GetID())};\n-        if (same(hd_key)) {\n-            result = Best(result, has_private ? KeyMatch::MINE : KeyMatch::WATCH_ONLY);\n-            continue;\n-        }\n-        if (!origin || origin->fingerprint != hd_key.id_key_fingerprint()) continue;\n-\n-        std::optional<CExtPubKey> derived;\n-        if (!HasHardenedDerivation(origin->path)) {\n-            // Public derivation needs no private key, even when locked.\n-            derived = hd_key;\n-            for (const uint32_t step : origin->path) {\n-                if (!derived->Derive(*derived, step)) {\n-                    derived.reset();\n-                    break;\n-                }\n-            }\n-        } else if (!has_private) {\n-            // Without the private key this candidate can't be derived; unlocking wouldn't help.\n-            continue;\n-        } else if (wallet.IsLocked()) {\n-            result = Best(result, KeyMatch::UNKNOWN);\n-            continue;\n-        } else if (const auto xprv{wallet.GetExtKey(hd_key)}) {\n-            // Decrypts only this candidate's key.\n-            if (const auto child{DeriveExtKey(*xprv, origin->path)}) derived = child->first.Neuter();\n-        }\n-        if (derived && same(*derived)) result = Best(result, has_private ? KeyMatch::MINE : KeyMatch::WATCH_ONLY);\n+    for (const auto& [hd_key, spkms] : hd_keys.keys) {\n+        result = Best(result, MatchPath(wallet, hd_key, spkms, {}, same));\n+        if (origin && origin->fingerprint == hd_key.id_key_fingerprint()) result = Best(result, MatchPath(wallet, hd_key, spkms, origin->path, same));\n+    }\n+    if (!origin) return result;\n+    for (const auto& [hd_origin, hd_key] : hd_keys.origins) {\n+        const auto& prefix{hd_origin.path};\n+        if (hd_origin.fingerprint != origin->fingerprint || origin->path.size() < prefix.size() ||\n+            !std::equal(prefix.begin(), prefix.end(), origin->path.begin())) continue;\n+        const auto it{hd_keys.keys.find(hd_key)};\n+        if (it == hd_keys.keys.end()) continue;\n+        const std::vector<uint32_t> rest(origin->path.begin() + prefix.size(), origin->path.end());\n+        result = Best(result, MatchPath(wallet, hd_key, it->second, rest, same));\n     }\n     return result;\n }\n \n-KeyMatch MatchExtKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys, const CExtPubKey& key, const std::optional<KeyOriginInfo>& origin)\n+KeyMatch MatchExtKey(const CWallet& wallet, const HDKeys& hd_keys, const CExtPubKey& key, const std::optional<KeyOriginInfo>& origin)\n     EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n     return MatchHDKeys(wallet, hd_keys, origin, [&](const CExtPubKey& candidate) { return SameKey(candidate, key); });\n@@ -99,7 +120,7 @@ KeyMatch MatchExtKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys,\n  *  from one of the wallet's HD keys, with the origin given in the descriptor\n  *  or the one the wallet recorded when it derived the key. A key the wallet\n  *  has derived is at least WATCH_ONLY. */\n-KeyMatch MatchConstKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys, const DescriptorKeyInfo::ConstKey& key,\n+KeyMatch MatchConstKey(const CWallet& wallet, const HDKeys& hd_keys, const DescriptorKeyInfo::ConstKey& key,\n                        const std::optional<KeyOriginInfo>& origin, DescriptorKeyInventory::Role role)\n     EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n@@ -132,17 +153,20 @@ KeyMatch MatchConstKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_key\n }\n \n /** The wallet's HD keys, plus those it holds only as musig() participants,\n- *  which GetHDPubKeys() leaves out because they have no single key to list. */\n-CWallet::HDPubKeyMap WalletHDKeys(const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n+ *  which GetHDPubKeys() leaves out because they have no single key to list,\n+ *  and the origins its descriptors give them. */\n+HDKeys WalletHDKeys(const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n-    CWallet::HDPubKeyMap hd_keys{wallet.GetHDPubKeys(CWallet::HDKeyFilter::All)};\n+    HDKeys hd_keys{.keys = wallet.GetHDPubKeys(CWallet::HDKeyFilter::All), .origins = {}};\n     for (auto* spkm : wallet.GetAllScriptPubKeyMans()) {\n         auto* desc_spkm{dynamic_cast<DescriptorScriptPubKeyMan*>(spkm)};\n         if (!desc_spkm) continue;\n         const auto inventory{WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->GetWalletDescriptor().descriptor->GetKeyInventory())};\n         for (const auto& occurrence : inventory.occurrences) {\n-            if (occurrence.role != DescriptorKeyInventory::Role::MUSIG_PARTICIPANT) continue;\n-            if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&occurrence.expression.key)}) hd_keys[key->root].insert(desc_spkm);\n+            const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&occurrence.expression.key)};\n+            if (!key) continue;\n+            if (occurrence.role == DescriptorKeyInventory::Role::MUSIG_PARTICIPANT) hd_keys.keys[key->root].insert(desc_spkm);\n+            if (const auto& origin{occurrence.expression.origin}) hd_keys.origins.emplace_back(*origin, key->root);\n         }\n     }\n     return hd_keys;\n@@ -189,7 +213,7 @@ WalletDescriptorAnalysis AnalyzeDescriptor(const CWallet& wallet, std::span<cons\n     }\n \n     LOCK(wallet.cs_wallet);\n-    const CWallet::HDPubKeyMap hd_keys{WalletHDKeys(wallet)};\n+    const HDKeys hd_keys{WalletHDKeys(wallet)};\n     for (const auto& occurrence : result.analysis.policy.keys.occurrences) {\n         const auto& node{occurrence.expression};\n         if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) {\n",
    "truncated": false,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 230,
    "evidence_id": "81f4f6192da743908367370bc2c0bdee",
    "finding_id": "finding:11",
    "kind": "new_source",
    "line": 112,
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "cc57e7ad8a31d4a8ca4cd1ddcaa2c5dda6a95aaa",
    "path": "src/wallet/descriptor_analyzer.cpp",
    "revision": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "source_generation": 7,
    "source_job_id": 3158,
    "text": "\nKeyMatch MatchExtKey(const CWallet& wallet, const HDKeys& hd_keys, const CExtPubKey& key, const std::optional<KeyOriginInfo>& origin)\n    EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n{\n    return MatchHDKeys(wallet, hd_keys, origin, [&](const CExtPubKey& candidate) { return SameKey(candidate, key); });\n}\n\n/** Match a constant key: the wallet stores its private key, or it is derived\n *  from one of the wallet's HD keys, with the origin given in the descriptor\n *  or the one the wallet recorded when it derived the key. A key the wallet\n *  has derived is at least WATCH_ONLY. */\nKeyMatch MatchConstKey(const CWallet& wallet, const HDKeys& hd_keys, const DescriptorKeyInfo::ConstKey& key,\n                       const std::optional<KeyOriginInfo>& origin, DescriptorKeyInventory::Role role)\n    EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n{\n    // Taproot signing uses the x-only key, so either parity is the same key there,\n    // even when written as a full key.\n    using Role = DescriptorKeyInventory::Role;\n    const bool xonly{key.xonly || role == Role::TAPROOT_INTERNAL || role == Role::TAPROOT_OUTPUT || role == Role::TAPSCRIPT};\n    const std::vector<CPubKey> pubkeys{xonly ? XOnlyPubKey{key.pubkey}.GetCPubKeys() : std::vector<CPubKey>{key.pubkey}};\n    std::vector<KeyOriginInfo> origins;\n    if (origin) origins.push_back(*origin);\n    bool derived{false};\n    for (const auto* spkm : wallet.GetAllScriptPubKeyMans()) {\n        const auto* desc_spkm{dynamic_cast<const DescriptorScriptPubKeyMan*>(spkm)};\n        if (!desc_spkm) continue;\n        for (const CPubKey& pubkey : pubkeys) {\n            if (WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->HasPrivKey(pubkey.GetID()))) return KeyMatch::MINE;\n            if (auto recorded{desc_spkm->GetPubKeyOrigin(pubkey)}) {\n                derived = true;\n                origins.push_back(std::move(*recorded));\n            }\n        }\n    }\n\n    const auto same = [&](const CExtPubKey& candidate) {\n        return xonly ? XOnlyPubKey{candidate.pubkey} == XOnlyPubKey{key.pubkey} : candidate.pubkey == key.pubkey;\n    };\n    KeyMatch result{derived ? KeyMatch::WATCH_ONLY : KeyMatch::NOT_MINE};\n    for (const KeyOriginInfo& candidate : origins) result = Best(result, MatchHDKeys(wallet, hd_keys, candidate, same));\n    return result;\n}\n\n/** The wallet's HD keys, plus those it holds only as musig() participants,\n *  which GetHDPubKeys() leaves out because they have no single key to list,\n *  and the origins its descriptors give them. */\nHDKeys WalletHDKeys(const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n{\n    HDKeys hd_keys{.keys = wallet.GetHDPubKeys(CWallet::HDKeyFilter::All), .origins = {}};\n    for (auto* spkm : wallet.GetAllScriptPubKeyMans()) {\n        auto* desc_spkm{dynamic_cast<DescriptorScriptPubKeyMan*>(spkm)};\n        if (!desc_spkm) continue;\n        const auto inventory{WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->GetWalletDescriptor().descriptor->GetKeyInventory())};\n        for (const auto& occurrence : inventory.occurrences) {\n            const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&occurrence.expression.key)};\n            if (!key) continue;\n            if (occurrence.role == DescriptorKeyInventory::Role::MUSIG_PARTICIPANT) hd_keys.keys[key->root].insert(desc_spkm);\n            if (const auto& origin{occurrence.expression.origin}) hd_keys.origins.emplace_back(*origin, key->root);\n        }\n    }\n    return hd_keys;\n}\n\nstd::optional<CTxDestination> FirstAddress(const Descriptor& descriptor, const SigningProvider& provider)\n{\n    std::vector<CScript> scripts;\n    FlatSigningProvider out;\n    if (!descriptor.Expand(/*pos=*/0, provider, scripts, out)) return std::nullopt;\n    // The first script with an address, as deriveaddresses lists: combo() starts with P2PK, which has none.\n    for (const CScript& script : scripts) {\n        if (CTxDestination dest; ExtractDestination(script, dest)) return dest;\n    }\n    return std::nullopt;\n}\n\n} // namespace\n\nstd::optional<bool> WalletDescriptorAnalysis::CanSign() const\n{\n    // MuSig aggregates are never MINE; their participants are matched instead.\n    bool unknown{false};\n    for (const KeyMatch match : keys) {\n        if (match == KeyMatch::MINE) return true;\n        unknown |= match == KeyMatch::UNKNOWN;\n    }\n    if (unknown) return std::nullopt;\n    return false;\n}\n\nWalletDescriptorAnalysis AnalyzeDescriptor(const CWallet& wallet, std::span<const std::unique_ptr<Descriptor>> descriptors, const SigningProvider& provider)\n{\n    WalletDescriptorAnalysis result;\n    result.analysis = AnalyzeDescriptor(descriptors);\n    if (descriptors.empty()) return result;\n    for (const auto& descriptor : descriptors) {\n        const auto address{FirstAddress(*descriptor, provider)};\n        if (!address) {\n            result.first_addresses.clear();\n            break;\n        }\n        result.first_addresses.push_back(*address);\n    }\n\n    LOCK(wallet.cs_wallet);\n    const HDKeys hd_keys{WalletHDKeys(wallet)};\n    for (const auto& occurrence : result.analysis.policy.keys.occurrences) {\n        const auto& node{occurrence.expression};\n        if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) {\n            result.keys.push_back(MatchExtKey(wallet, hd_keys, key->root, node.origin));\n        } else if (const auto* key{std::get_if<DescriptorKeyInfo::ConstKey>(&node.key)}) {\n            result.keys.push_back(MatchConstKey(wallet, hd_keys, *key, node.origin, occurrence.role));\n        } else {\n            result.keys.push_back(KeyMatch::NOT_MINE);\n        }\n    }\n    return result;\n}\n\n} // namespace wallet",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · cc57e7ad8a31..386c55a4bfcb

2026-11-26T06:52:03Z · gpt-6-luna

bitcoin#36885Address tests miss failure after a successful multipath branchsrc/wallet/test/wallet_interfaces_tests.cppaddressed
Assessment

The new test uses a multipath descriptor whose first branch derives publicly and whose second hardened branch cannot derive from the foreign xpub; it asserts that first_addresses is empty. A successful multipath control is also added.

path_diff: src/wallet/test/wallet_interfaces_tests.cpp; new_source: src/wallet/test/wallet_interfaces_tests.cpp

[
  {
    "evidence_id": "9461a1c6ea05424688a81ab20964dd89",
    "finding_id": "finding:10",
    "kind": "path_diff",
    "new_head": "8721e96cc46f544eb8505e6fb3502e934dd0906b",
    "old_head": "cc57e7ad8a31d4a8ca4cd1ddcaa2c5dda6a95aaa",
    "path": "src/wallet/test/wallet_interfaces_tests.cpp",
    "source_generation": 7,
    "source_job_id": 3158,
    "text": "diff --git a/src/wallet/test/wallet_interfaces_tests.cpp b/src/wallet/test/wallet_interfaces_tests.cpp\nindex 515e5b4fca..0ced97b31a 100644\n--- a/src/wallet/test/wallet_interfaces_tests.cpp\n+++ b/src/wallet/test/wallet_interfaces_tests.cpp\n@@ -221,6 +221,13 @@ BOOST_AUTO_TEST_CASE(analyzedescriptor)\n     result = interface->analyzeDescriptor(\"wpkh(\" + EncodeExtPubKey(other.Neuter()) + \"/84h/1h/0h/0/*)\");\n     BOOST_REQUIRE(result);\n     BOOST_CHECK(result->first_addresses.empty());\n+    // All paths or none: a change path that can't be derived leaves out the receive address too.\n+    result = interface->analyzeDescriptor(\"wpkh(\" + EncodeExtPubKey(other.Neuter()) + \"/<0;1h>/*)\");\n+    BOOST_REQUIRE(result);\n+    BOOST_CHECK(result->first_addresses.empty());\n+    result = interface->analyzeDescriptor(\"wpkh(\" + EncodeExtPubKey(other.Neuter()) + \"/<0;1>/*)\");\n+    BOOST_REQUIRE(result);\n+    BOOST_CHECK_EQUAL(result->first_addresses.size(), 2U);\n \n     result = interface->analyzeDescriptor(\"wsh(sortedmulti(2,\");\n     BOOST_REQUIRE(!result);\n@@ -258,6 +265,12 @@ BOOST_AUTO_TEST_CASE(analyzedescriptor_wallet_locked)\n     BOOST_CHECK(result->CanSign() == true);\n     BOOST_CHECK(wallet->IsLocked());\n \n+    // One key it can't tell doesn't hide another that is the wallet's.\n+    result = interface->analyzeDescriptor(\"wsh(sortedmulti(1,\" + AccountKey(master) + \"/0/*,\" + OriginKey(master, {0, 1}) + \"/0/*))\");\n+    BOOST_REQUIRE(result);\n+    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::UNKNOWN, KeyMatch::MINE}));\n+    BOOST_CHECK(result->CanSign() == true);\n+\n     // The account xpub is also held without its private key, but the locked\n     // master may still hold it, so the key stays \"unknown\".\n     AddDescriptor(*wallet, \"wpkh(\" + AccountKey(master) + \"/0/*)\");\n@@ -393,6 +406,44 @@ BOOST_AUTO_TEST_CASE(analyzedescriptor_derived_constant_keys)\n     BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE}));\n }\n \n+BOOST_AUTO_TEST_CASE(analyzedescriptor_account_keys)\n+{\n+    WalletContext context;\n+    context.args = &m_args;\n+    auto wallet = TestCreateWallet(context);\n+    auto interface = interfaces::MakeWallet(context, wallet);\n+\n+    // An account xprv imported with its master's origin, without the master.\n+    const CExtKey master{NewHDKey()};\n+    const std::vector<uint32_t> account_path{0x80000054, 0x80000001, 0x80000000};\n+    const CExtKey account{Assert(DeriveExtKey(master, account_path))->first};\n+    const std::string fingerprint{HexStr(master.Neuter().id_key_fingerprint())};\n+    AddDescriptor(*wallet, \"wpkh([\" + fingerprint + \"/84h/1h/0h]\" + EncodeExtKey(account) + \"/0/*)\");\n+    const auto key_at = [&](const std::vector<uint32_t>& path) { return Assert(DeriveExtKey(account, path))->first.Neuter(); };\n+\n+    // A key the wallet derived, matched through the origin it recorded, which starts at the master.\n+    auto result{interface->analyzeDescriptor(\"wpkh(\" + HexStr(key_at({0, 0}).pubkey) + \")\")};\n+    BOOST_REQUIRE(result);\n+    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE}));\n+    BOOST_CHECK(result->CanSign() == true);\n+\n+    // Keys with an origin below the account's: derived from the account key.\n+    const std::string later{\"[\" + fingerprint + \"/84h/1h/0h/0/5000]\" + HexStr(key_at({0, 5000}).pubkey)};\n+    const std::string child{\"[\" + fingerprint + \"/84h/1h/0h/0]\" + EncodeExtPubKey(key_at({0})) + \"/*\"};\n+    const std::string hardened{\"[\" + fingerprint + \"/84h/1h/0h/1h]\" + EncodeExtPubKey(key_at({0x80000001})) + \"/*\"};\n+    const std::string impostor{\"[\" + fingerprint + \"/84h/1h/0h/0/5000]\" + HexStr(GenerateRandomKey().GetPubKey())};\n+    result = interface->analyzeDescriptor(\"wsh(multi(1,\" + later + \",\" + child + \",\" + hardened + \",\" + impostor + \"))\");\n+    BOOST_REQUIRE(result);\n+    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE, KeyMatch::MINE, KeyMatch::MINE, KeyMatch::NOT_MINE}));\n+\n+    // Only the hardened step needs the private key.\n+    BOOST_REQUIRE(wallet->EncryptWallet(\"hunter2\"));\n+    BOOST_REQUIRE(wallet->Lock());\n+    result = interface->analyzeDescriptor(\"wsh(multi(1,\" + later + \",\" + child + \",\" + hardened + \",\" + impostor + \"))\");\n+    BOOST_REQUIRE(result);\n+    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE, KeyMatch::MINE, KeyMatch::UNKNOWN, KeyMatch::NOT_MINE}));\n+}\n+\n BOOST_AUTO_TEST_CASE(analyzedescriptor_musig_only_keys)\n {\n     WalletContext context;\n",
    "truncated": false,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 342,
    "evidence_id": "f2d96c3b76d749678fce7d362adc1d26",
    "finding_id": "finding:10",
    "kind": "new_source",
    "line": 193,
    "new_head": "8721e96cc46f544eb8505e6fb3502e934dd0906b",
    "old_head": "cc57e7ad8a31d4a8ca4cd1ddcaa2c5dda6a95aaa",
    "path": "src/wallet/test/wallet_interfaces_tests.cpp",
    "revision": "8721e96cc46f544eb8505e6fb3502e934dd0906b",
    "source_generation": 7,
    "source_job_id": 3158,
    "text": "                                                       KeyMatch::MINE, KeyMatch::NOT_MINE, KeyMatch::NOT_MINE}));\n\n    // A single-sig descriptor is not a multisig setup, but its key is matched and the wallet can sign.\n    result = interface->analyzeDescriptor(\"wpkh(\" + mine + \"/0/*)\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(!result->analysis.IsRecognized());\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE}));\n    BOOST_CHECK(result->CanSign() == true);\n    BOOST_CHECK_EQUAL(result->first_addresses.size(), 1U);\n\n    // combo() starts with a P2PK script, which has no address: its first address is the P2PKH one.\n    const auto first_key{Assert(DeriveExtKey(master, {0x80000030, 0x80000001, 0x80000000, 0x80000002, 0, 0}))};\n    result = interface->analyzeDescriptor(\"combo(\" + mine + \"/0/*)\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->first_addresses == std::vector<CTxDestination>({PKHash{first_key->first.Neuter().pubkey}}));\n    // A P2PK script alone has no address.\n    result = interface->analyzeDescriptor(\"pk(\" + mine + \"/0/*)\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->first_addresses.empty());\n\n    // Private keys in the descriptor derive the first address through hardened steps.\n    const CExtKey other{NewHDKey()};\n    result = interface->analyzeDescriptor(\"wpkh(\" + EncodeExtKey(other) + \"/84h/1h/0h/0/*)\");\n    BOOST_REQUIRE(result);\n    const auto receive_key{Assert(DeriveExtKey(other, {0x80000054, 0x80000001, 0x80000000, 0, 0}))};\n    BOOST_CHECK(result->first_addresses == std::vector<CTxDestination>({WitnessV0KeyHash{receive_key->first.Neuter().pubkey}}));\n\n    // Without the private key, the hardened steps can't be derived.\n    result = interface->analyzeDescriptor(\"wpkh(\" + EncodeExtPubKey(other.Neuter()) + \"/84h/1h/0h/0/*)\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->first_addresses.empty());\n    // All paths or none: a change path that can't be derived leaves out the receive address too.\n    result = interface->analyzeDescriptor(\"wpkh(\" + EncodeExtPubKey(other.Neuter()) + \"/<0;1h>/*)\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->first_addresses.empty());\n    result = interface->analyzeDescriptor(\"wpkh(\" + EncodeExtPubKey(other.Neuter()) + \"/<0;1>/*)\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK_EQUAL(result->first_addresses.size(), 2U);\n\n    result = interface->analyzeDescriptor(\"wsh(sortedmulti(2,\");\n    BOOST_REQUIRE(!result);\n    BOOST_CHECK(result.error().code == WalletErrorCode::GenericError);\n}\n\nBOOST_AUTO_TEST_CASE(analyzedescriptor_wallet_locked)\n{\n    WalletContext context;\n    context.args = &m_args;\n    auto wallet = TestCreateWallet(context);\n    auto interface = interfaces::MakeWallet(context, wallet);\n    const CExtKey master{NewHDKey()};\n    BOOST_REQUIRE(interface->addHDKey(master));\n    BOOST_REQUIRE(wallet->EncryptWallet(\"hunter2\"));\n    BOOST_REQUIRE(wallet->Lock());\n\n    // Deriving a hardened path needs the private key: a locked wallet can't tell.\n    const std::string derived{\"wsh(sortedmulti(2,\" + AccountKey(master) + R + \",\" + AccountKey(NewHDKey()) + R + \"))\"};\n    auto result{interface->analyzeDescriptor(derived)};\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::UNKNOWN, KeyMatch::NOT_MINE}));\n    BOOST_CHECK(result->CanSign() == std::nullopt);\n\n    // The HD key itself is found without decrypting anything.\n    result = interface->analyzeDescriptor(\"wsh(sortedmulti(1,\" + EncodeExtPubKey(master.Neuter()) + \"/0/*,\" + AccountKey(NewHDKey()) + \"/0/*))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE, KeyMatch::NOT_MINE}));\n    BOOST_CHECK(wallet->IsLocked());\n\n    // So is a key with an unhardened origin path: public derivation needs no private key.\n    result = interface->analyzeDescriptor(\"wsh(sortedmulti(1,\" + OriginKey(master, {0, 1}) + \"/0/*,\" + AccountKey(NewHDKey()) + \"/0/*))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE, KeyMatch::NOT_MINE}));\n    BOOST_CHECK(result->CanSign() == true);\n    BOOST_CHECK(wallet->IsLocked());\n\n    // One key it can't tell doesn't hide another that is the wallet's.\n    result = interface->analyzeDescriptor(\"wsh(sortedmulti(1,\" + AccountKey(master) + \"/0/*,\" + OriginKey(master, {0, 1}) + \"/0/*))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::UNKNOWN, KeyMatch::MINE}));\n    BOOST_CHECK(result->CanSign() == true);\n\n    // The account xpub is also held without its private key, but the locked\n    // master may still hold it, so the key stays \"unknown\".\n    AddDescriptor(*wallet, \"wpkh(\" + AccountKey(master) + \"/0/*)\");\n    result = interface->analyzeDescriptor(derived);\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::UNKNOWN, KeyMatch::NOT_MINE}));\n    BOOST_CHECK(result->CanSign() == std::nullopt);\n\n    BOOST_REQUIRE(wallet->Unlock(\"hunter2\"));\n    result = interface->analyzeDescriptor(derived);\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE, KeyMatch::NOT_MINE}));\n    BOOST_CHECK(result->CanSign() == true);\n}\n\nBOOST_AUTO_TEST_CASE(analyzedescriptor_watch_only_and_constant_keys)\n{\n    WalletContext context;\n    context.args = &m_args;\n    auto wallet = TestCreateWallet(context);\n    auto interface = interfaces::MakeWallet(context, wallet);\n\n    // An xpub the wallet has without its private key.\n    const CExtKey watched_master{NewHDKey()};\n    const std::string watched{EncodeExtPubKey(watched_master.Neuter())};\n    AddDescriptor(*wallet, \"wpkh(\" + watched + \"/0/*)\");\n\n    // A private key whose public key has an odd Y: its x-only form must still match.\n    const CKey key{OddKey()};\n    AddKey(*wallet, key);\n\n    const std::string desc{\"tr(\" + HexStr(XOnlyPubKey::NUMS_H) + \",multi_a(1,\" + watched + \"/0/*,\" + HexStr(XOnlyPubKey{key.GetPubKey()}) + \"))\"};\n    auto result{interface->analyzeDescriptor(desc)};\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::NOT_MINE, KeyMatch::WATCH_ONLY, KeyMatch::MINE}));\n    // A constant cosigner key makes the setup unrecognized, but the wallet can still sign with it.\n    BOOST_CHECK(!result->analysis.IsRecognized());\n    BOOST_CHECK(result->CanSign() == true);\n\n    // In Taproot the even-Y full key is the same key; for ECDSA it is not.\n    const std::string even{\"02\" + HexStr(XOnlyPubKey{key.GetPubKey()})};\n    result = interface->analyzeDescriptor(\"tr(\" + HexStr(XOnlyPubKey::NUMS_H) + \",multi_a(1,\" + even + \"))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::NOT_MINE, KeyMatch::MINE}));\n    result = interface->analyzeDescriptor(\"wsh(multi(1,\" + even + \"))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::NOT_MINE}));\n\n    // Deriving a hardened origin path from a watched xpub is impossible even\n    // when unlocked, so the key is not \"unknown\" and doesn't hide can_sign.\n    result = interface->analyzeDescriptor(\"wsh(sortedmulti(1,\" + AccountKey(watched_master) + \"/0/*,\" + AccountKey(NewHDKey()) + \"/0/*))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::NOT_MINE, KeyMatch::NOT_MINE}));\n    BOOST_CHECK(result->CanSign() == false);\n\n    // A plain public key the wallet has without its private key.\n    const std::string watched_key{HexStr(GenerateRandomKey().GetPubKey())};\n    AddDescriptor(*wallet, \"wpkh(\" + watched_key + \")\");\n    result = interface->analyzeDescriptor(\"wsh(multi(1,\" + watched_key + \"))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::WATCH_ONLY}));\n    BOOST_CHECK(result->CanSign() == false);\n\n    // The watched xpub's private key, imported alone in another descriptor: the\n    // wallet signs with each descriptor's own keys, and none has both the private\n    // key and the chain code, so the xpub is still watch-only, as in gethdkeys.\n    AddDescriptor(*wallet, \"pk(\" + EncodeSecret(watched_master.key) + \")\");\n    result = interface->analyzeDescriptor(\"wsh(multi(1,\" + watched + \"/0/*))\");\n    BOOST_REQUIRE(result);",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · cc57e7ad8a31..8721e96cc46f

2026-11-26T05:50:43Z · gpt-6-luna

bitcoin#36885Cached account-derived constants are misreported as watch_onlysrc/wallet/descriptor_analyzer.cppunclear
Assessment

The new code adds origin-prefix matching and derives the remaining path from a stored HD key, which appears relevant to account-derived constants. However, the supplied excerpt does not show that this path can obtain the manager's cached private derivation capability for the constant key when the account xprv lacks a matching HD-root entry. No targeted locked/unlocked regression evidence is supplied, so whether the reported case is fixed cannot be established.

path_diff: src/wallet/descriptor_analyzer.cpp; new_source: src/wallet/descriptor_analyzer.cpp

[
  {
    "evidence_id": "c34b25c4b011443984bb30362d4022c6",
    "finding_id": "finding:1",
    "kind": "path_diff",
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "cc57e7ad8a31d4a8ca4cd1ddcaa2c5dda6a95aaa",
    "path": "src/wallet/descriptor_analyzer.cpp",
    "source_generation": 7,
    "source_job_id": 3158,
    "text": "diff --git a/src/wallet/descriptor_analyzer.cpp b/src/wallet/descriptor_analyzer.cpp\nindex 166bd1e8951..33ea2c5431d 100644\n--- a/src/wallet/descriptor_analyzer.cpp\n+++ b/src/wallet/descriptor_analyzer.cpp\n@@ -7,6 +7,7 @@\n #include <key.h>\n #include <pubkey.h>\n #include <script/descriptor.h>\n+#include <script/keyorigin.h>\n #include <script/signingprovider.h>\n #include <sync.h>\n #include <util/bip32.h>\n@@ -45,51 +46,71 @@ KeyMatch Best(KeyMatch a, KeyMatch b)\n     return KeyMatch::NOT_MINE;\n }\n \n+//! The wallet's HD keys, and the origins its descriptors give them.\n+struct HDKeys {\n+    CWallet::HDPubKeyMap keys;\n+    //! E.g. an account xprv imported with its master's origin.\n+    std::vector<std::pair<KeyOriginInfo, CExtPubKey>> origins;\n+};\n+\n+/** Match a key against what deriving `path` from the wallet's HD key `hd_key`\n+ *  gives. `same` tells whether an extended public key is the key. */\n+template <typename Same>\n+KeyMatch MatchPath(const CWallet& wallet, const CExtPubKey& hd_key, const std::set<DescriptorScriptPubKeyMan*>& spkms, const std::vector<uint32_t>& path, Same same)\n+    EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n+{\n+    // Only the descriptors with this key count, as in gethdkeys: the wallet\n+    // signs with each descriptor's own keys, so a private key held alone in\n+    // another descriptor can't sign for it.\n+    const bool has_private{HasPrivKey(spkms, hd_key.pubkey.GetID())};\n+    std::optional<CExtPubKey> derived;\n+    if (!HasHardenedDerivation(path)) {\n+        // Public derivation needs no private key, even when locked.\n+        derived = hd_key;\n+        for (const uint32_t step : path) {\n+            if (!derived->Derive(*derived, step)) return KeyMatch::NOT_MINE;\n+        }\n+    } else if (!has_private) {\n+        // Without the private key this candidate can't be derived; unlocking wouldn't help.\n+        return KeyMatch::NOT_MINE;\n+    } else if (wallet.IsLocked()) {\n+        return KeyMatch::UNKNOWN;\n+    } else if (const auto xprv{wallet.GetExtKey(hd_key)}) {\n+        // Decrypts only this candidate's key.\n+        if (const auto child{DeriveExtKey(*xprv, path)}) derived = child->first.Neuter();\n+    }\n+    if (derived && same(*derived)) return has_private ? KeyMatch::MINE : KeyMatch::WATCH_ONLY;\n+    return KeyMatch::NOT_MINE;\n+}\n+\n /** Match a key against the wallet's HD keys: the key is one of them, or\n- *  deriving `origin`'s path from the one with its fingerprint gives the key.\n- *  `same` tells whether an extended public key is the key. */\n+ *  deriving the rest of `origin`'s path from one of them gives the key. The\n+ *  path starts at the HD key with the origin's fingerprint, or after an origin\n+ *  the wallet's descriptors give an HD key. `same` tells whether an extended\n+ *  public key is the key. */\n template <typename Same>\n-KeyMatch MatchHDKeys(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys, const std::optional<KeyOriginInfo>& origin, Same same)\n+KeyMatch MatchHDKeys(const CWallet& wallet, const HDKeys& hd_keys, const std::optional<KeyOriginInfo>& origin, Same same)\n     EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n     KeyMatch result{KeyMatch::NOT_MINE};\n-    for (const auto& [hd_key, spkms] : hd_keys) {\n-        // Only the descriptors with this key count, as in gethdkeys: the wallet\n-        // signs with each descriptor's own keys, so a private key held alone in\n-        // another descriptor can't sign for it.\n-        const bool has_private{HasPrivKey(spkms, hd_key.pubkey.GetID())};\n-        if (same(hd_key)) {\n-            result = Best(result, has_private ? KeyMatch::MINE : KeyMatch::WATCH_ONLY);\n-            continue;\n-        }\n-        if (!origin || origin->fingerprint != hd_key.id_key_fingerprint()) continue;\n-\n-        std::optional<CExtPubKey> derived;\n-        if (!HasHardenedDerivation(origin->path)) {\n-            // Public derivation needs no private key, even when locked.\n-            derived = hd_key;\n-            for (const uint32_t step : origin->path) {\n-                if (!derived->Derive(*derived, step)) {\n-                    derived.reset();\n-                    break;\n-                }\n-            }\n-        } else if (!has_private) {\n-            // Without the private key this candidate can't be derived; unlocking wouldn't help.\n-            continue;\n-        } else if (wallet.IsLocked()) {\n-            result = Best(result, KeyMatch::UNKNOWN);\n-            continue;\n-        } else if (const auto xprv{wallet.GetExtKey(hd_key)}) {\n-            // Decrypts only this candidate's key.\n-            if (const auto child{DeriveExtKey(*xprv, origin->path)}) derived = child->first.Neuter();\n-        }\n-        if (derived && same(*derived)) result = Best(result, has_private ? KeyMatch::MINE : KeyMatch::WATCH_ONLY);\n+    for (const auto& [hd_key, spkms] : hd_keys.keys) {\n+        result = Best(result, MatchPath(wallet, hd_key, spkms, {}, same));\n+        if (origin && origin->fingerprint == hd_key.id_key_fingerprint()) result = Best(result, MatchPath(wallet, hd_key, spkms, origin->path, same));\n+    }\n+    if (!origin) return result;\n+    for (const auto& [hd_origin, hd_key] : hd_keys.origins) {\n+        const auto& prefix{hd_origin.path};\n+        if (hd_origin.fingerprint != origin->fingerprint || origin->path.size() < prefix.size() ||\n+            !std::equal(prefix.begin(), prefix.end(), origin->path.begin())) continue;\n+        const auto it{hd_keys.keys.find(hd_key)};\n+        if (it == hd_keys.keys.end()) continue;\n+        const std::vector<uint32_t> rest(origin->path.begin() + prefix.size(), origin->path.end());\n+        result = Best(result, MatchPath(wallet, hd_key, it->second, rest, same));\n     }\n     return result;\n }\n \n-KeyMatch MatchExtKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys, const CExtPubKey& key, const std::optional<KeyOriginInfo>& origin)\n+KeyMatch MatchExtKey(const CWallet& wallet, const HDKeys& hd_keys, const CExtPubKey& key, const std::optional<KeyOriginInfo>& origin)\n     EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n     return MatchHDKeys(wallet, hd_keys, origin, [&](const CExtPubKey& candidate) { return SameKey(candidate, key); });\n@@ -99,7 +120,7 @@ KeyMatch MatchExtKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys,\n  *  from one of the wallet's HD keys, with the origin given in the descriptor\n  *  or the one the wallet recorded when it derived the key. A key the wallet\n  *  has derived is at least WATCH_ONLY. */\n-KeyMatch MatchConstKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys, const DescriptorKeyInfo::ConstKey& key,\n+KeyMatch MatchConstKey(const CWallet& wallet, const HDKeys& hd_keys, const DescriptorKeyInfo::ConstKey& key,\n                        const std::optional<KeyOriginInfo>& origin, DescriptorKeyInventory::Role role)\n     EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n@@ -132,17 +153,20 @@ KeyMatch MatchConstKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_key\n }\n \n /** The wallet's HD keys, plus those it holds only as musig() participants,\n- *  which GetHDPubKeys() leaves out because they have no single key to list. */\n-CWallet::HDPubKeyMap WalletHDKeys(const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n+ *  which GetHDPubKeys() leaves out because they have no single key to list,\n+ *  and the origins its descriptors give them. */\n+HDKeys WalletHDKeys(const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n-    CWallet::HDPubKeyMap hd_keys{wallet.GetHDPubKeys(CWallet::HDKeyFilter::All)};\n+    HDKeys hd_keys{.keys = wallet.GetHDPubKeys(CWallet::HDKeyFilter::All), .origins = {}};\n     for (auto* spkm : wallet.GetAllScriptPubKeyMans()) {\n         auto* desc_spkm{dynamic_cast<DescriptorScriptPubKeyMan*>(spkm)};\n         if (!desc_spkm) continue;\n         const auto inventory{WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->GetWalletDescriptor().descriptor->GetKeyInventory())};\n         for (const auto& occurrence : inventory.occurrences) {\n-            if (occurrence.role != DescriptorKeyInventory::Role::MUSIG_PARTICIPANT) continue;\n-            if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&occurrence.expression.key)}) hd_keys[key->root].insert(desc_spkm);\n+            const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&occurrence.expression.key)};\n+            if (!key) continue;\n+            if (occurrence.role == DescriptorKeyInventory::Role::MUSIG_PARTICIPANT) hd_keys.keys[key->root].insert(desc_spkm);\n+            if (const auto& origin{occurrence.expression.origin}) hd_keys.origins.emplace_back(*origin, key->root);\n         }\n     }\n     return hd_keys;\n@@ -189,7 +213,7 @@ WalletDescriptorAnalysis AnalyzeDescriptor(const CWallet& wallet, std::span<cons\n     }\n \n     LOCK(wallet.cs_wallet);\n-    const CWallet::HDPubKeyMap hd_keys{WalletHDKeys(wallet)};\n+    const HDKeys hd_keys{WalletHDKeys(wallet)};\n     for (const auto& occurrence : result.analysis.policy.keys.occurrences) {\n         const auto& node{occurrence.expression};\n         if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) {\n",
    "truncated": false,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 230,
    "evidence_id": "44ee62c5d1ef44ba9f27e55de978d863",
    "finding_id": "finding:1",
    "kind": "new_source",
    "line": 100,
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "cc57e7ad8a31d4a8ca4cd1ddcaa2c5dda6a95aaa",
    "path": "src/wallet/descriptor_analyzer.cpp",
    "revision": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "source_generation": 7,
    "source_job_id": 3158,
    "text": "    if (!origin) return result;\n    for (const auto& [hd_origin, hd_key] : hd_keys.origins) {\n        const auto& prefix{hd_origin.path};\n        if (hd_origin.fingerprint != origin->fingerprint || origin->path.size() < prefix.size() ||\n            !std::equal(prefix.begin(), prefix.end(), origin->path.begin())) continue;\n        const auto it{hd_keys.keys.find(hd_key)};\n        if (it == hd_keys.keys.end()) continue;\n        const std::vector<uint32_t> rest(origin->path.begin() + prefix.size(), origin->path.end());\n        result = Best(result, MatchPath(wallet, hd_key, it->second, rest, same));\n    }\n    return result;\n}\n\nKeyMatch MatchExtKey(const CWallet& wallet, const HDKeys& hd_keys, const CExtPubKey& key, const std::optional<KeyOriginInfo>& origin)\n    EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n{\n    return MatchHDKeys(wallet, hd_keys, origin, [&](const CExtPubKey& candidate) { return SameKey(candidate, key); });\n}\n\n/** Match a constant key: the wallet stores its private key, or it is derived\n *  from one of the wallet's HD keys, with the origin given in the descriptor\n *  or the one the wallet recorded when it derived the key. A key the wallet\n *  has derived is at least WATCH_ONLY. */\nKeyMatch MatchConstKey(const CWallet& wallet, const HDKeys& hd_keys, const DescriptorKeyInfo::ConstKey& key,\n                       const std::optional<KeyOriginInfo>& origin, DescriptorKeyInventory::Role role)\n    EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n{\n    // Taproot signing uses the x-only key, so either parity is the same key there,\n    // even when written as a full key.\n    using Role = DescriptorKeyInventory::Role;\n    const bool xonly{key.xonly || role == Role::TAPROOT_INTERNAL || role == Role::TAPROOT_OUTPUT || role == Role::TAPSCRIPT};\n    const std::vector<CPubKey> pubkeys{xonly ? XOnlyPubKey{key.pubkey}.GetCPubKeys() : std::vector<CPubKey>{key.pubkey}};\n    std::vector<KeyOriginInfo> origins;\n    if (origin) origins.push_back(*origin);\n    bool derived{false};\n    for (const auto* spkm : wallet.GetAllScriptPubKeyMans()) {\n        const auto* desc_spkm{dynamic_cast<const DescriptorScriptPubKeyMan*>(spkm)};\n        if (!desc_spkm) continue;\n        for (const CPubKey& pubkey : pubkeys) {\n            if (WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->HasPrivKey(pubkey.GetID()))) return KeyMatch::MINE;\n            if (auto recorded{desc_spkm->GetPubKeyOrigin(pubkey)}) {\n                derived = true;\n                origins.push_back(std::move(*recorded));\n            }\n        }\n    }\n\n    const auto same = [&](const CExtPubKey& candidate) {\n        return xonly ? XOnlyPubKey{candidate.pubkey} == XOnlyPubKey{key.pubkey} : candidate.pubkey == key.pubkey;\n    };\n    KeyMatch result{derived ? KeyMatch::WATCH_ONLY : KeyMatch::NOT_MINE};\n    for (const KeyOriginInfo& candidate : origins) result = Best(result, MatchHDKeys(wallet, hd_keys, candidate, same));\n    return result;\n}\n\n/** The wallet's HD keys, plus those it holds only as musig() participants,\n *  which GetHDPubKeys() leaves out because they have no single key to list,\n *  and the origins its descriptors give them. */\nHDKeys WalletHDKeys(const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n{\n    HDKeys hd_keys{.keys = wallet.GetHDPubKeys(CWallet::HDKeyFilter::All), .origins = {}};\n    for (auto* spkm : wallet.GetAllScriptPubKeyMans()) {\n        auto* desc_spkm{dynamic_cast<DescriptorScriptPubKeyMan*>(spkm)};\n        if (!desc_spkm) continue;\n        const auto inventory{WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->GetWalletDescriptor().descriptor->GetKeyInventory())};\n        for (const auto& occurrence : inventory.occurrences) {\n            const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&occurrence.expression.key)};\n            if (!key) continue;\n            if (occurrence.role == DescriptorKeyInventory::Role::MUSIG_PARTICIPANT) hd_keys.keys[key->root].insert(desc_spkm);\n            if (const auto& origin{occurrence.expression.origin}) hd_keys.origins.emplace_back(*origin, key->root);\n        }\n    }\n    return hd_keys;\n}\n\nstd::optional<CTxDestination> FirstAddress(const Descriptor& descriptor, const SigningProvider& provider)\n{\n    std::vector<CScript> scripts;\n    FlatSigningProvider out;\n    if (!descriptor.Expand(/*pos=*/0, provider, scripts, out)) return std::nullopt;\n    // The first script with an address, as deriveaddresses lists: combo() starts with P2PK, which has none.\n    for (const CScript& script : scripts) {\n        if (CTxDestination dest; ExtractDestination(script, dest)) return dest;\n    }\n    return std::nullopt;\n}\n\n} // namespace\n\nstd::optional<bool> WalletDescriptorAnalysis::CanSign() const\n{\n    // MuSig aggregates are never MINE; their participants are matched instead.\n    bool unknown{false};\n    for (const KeyMatch match : keys) {\n        if (match == KeyMatch::MINE) return true;\n        unknown |= match == KeyMatch::UNKNOWN;\n    }\n    if (unknown) return std::nullopt;\n    return false;\n}\n\nWalletDescriptorAnalysis AnalyzeDescriptor(const CWallet& wallet, std::span<const std::unique_ptr<Descriptor>> descriptors, const SigningProvider& provider)\n{\n    WalletDescriptorAnalysis result;\n    result.analysis = AnalyzeDescriptor(descriptors);\n    if (descriptors.empty()) return result;\n    for (const auto& descriptor : descriptors) {\n        const auto address{FirstAddress(*descriptor, provider)};\n        if (!address) {\n            result.first_addresses.clear();\n            break;\n        }\n        result.first_addresses.push_back(*address);\n    }\n\n    LOCK(wallet.cs_wallet);\n    const HDKeys hd_keys{WalletHDKeys(wallet)};\n    for (const auto& occurrence : result.analysis.policy.keys.occurrences) {\n        const auto& node{occurrence.expression};\n        if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) {\n            result.keys.push_back(MatchExtKey(wallet, hd_keys, key->root, node.origin));\n        } else if (const auto* key{std::get_if<DescriptorKeyInfo::ConstKey>(&node.key)}) {\n            result.keys.push_back(MatchConstKey(wallet, hd_keys, *key, node.origin, occurrence.role));\n        } else {\n            result.keys.push_back(KeyMatch::NOT_MINE);\n        }\n    }\n    return result;\n}\n\n} // namespace wallet",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · cc57e7ad8a31..386c55a4bfcb

2026-11-26T06:52:03Z · gpt-6-luna

bitcoin#36823The mapWallet emptiness check still rejects fully transferred historysrc/wallet/migration.cppunclear
Assessment

The follow-up assessment was invalid: unknown follow-up evidence ID.

invalid_assessment

Source report · e4c9aca57cda..7ba8d3e888f7

2026-11-26T01:11:49Z · gpt-6-luna

bitcoin#36823Interrupted migration can expose a flagless source as an empty walletsrc/wallet/migration.cppstill_present
Assessment

The new migration code still creates and commits a filtered SQLite database before semantic descriptor migration, and the supplied changes show no load-blocking migration marker or equivalent mechanism to detect an interrupted migration.

path_diff: src/wallet/migration.cpp; new_source: src/wallet/migration.cpp

[
  {
    "evidence_id": "438864ea11ea46c79eca737b2b418a12",
    "finding_id": "finding:3",
    "kind": "path_diff",
    "new_head": "7ba8d3e888f79649bf3b26502625880fa2e68908",
    "old_head": "e4c9aca57cda1643a7cd5ec45a8dab28be17f2e9",
    "path": "src/wallet/migration.cpp",
    "source_generation": 7,
    "source_job_id": 3147,
    "text": "diff --git a/src/wallet/migration.cpp b/src/wallet/migration.cpp\nindex 3c42a6067d..6b06131484 100644\n--- a/src/wallet/migration.cpp\n+++ b/src/wallet/migration.cpp\n@@ -40,7 +40,63 @@ void CWallet::SetupLegacyDataSPKM()\n     AddScriptPubKeyMan(id, std::move(spk_manager));\n }\n \n-bool CWallet::MigrateToSQLite(const std::unordered_set<std::string>& skip_types, bilingual_str& error, bool& had_legacy_records)\n+// Returns wallet prefix for migration.\n+// Used to name the backup file and newly created wallets.\n+// E.g. a watch-only wallet is named \"<prefix>_watchonly\".\n+static std::string MigrationPrefixName(CWallet& wallet)\n+{\n+    const std::string& name{wallet.GetName()};\n+    return name.empty() ? \"default_wallet\" : name;\n+}\n+\n+// Returns prefix for files created in the wallets directory during migration:\n+// the backup file and the temporary database. Unlike MigrationPrefixName(),\n+// this is a single path component, because the wallet name can be a path.\n+static std::string MigrationFilePrefix(CWallet& wallet)\n+{\n+    const std::string& name{wallet.GetName()};\n+    if (name.empty()) return MigrationPrefixName(wallet);\n+    // fs::weakly_canonical resolves relative specifiers and removes trailing slashes.\n+    const fs::path legacy_wallet_path{fs::weakly_canonical(GetWalletDir() / fs::PathFromString(name))};\n+    return fs::PathToString(legacy_wallet_path.filename());\n+}\n+\n+static bool CopyMigrationRecords(std::vector<std::pair<SerializeData, SerializeData>> records, WalletDatabase& new_db, bool& had_legacy_records)\n+{\n+    // Write existing records into the new DB\n+    had_legacy_records = false;\n+\n+    std::unordered_set<std::string> SKIP_TYPES = DBKeys::LEGACY_TYPES;\n+    SKIP_TYPES.insert({\n+        // legacy wallet types\n+        DBKeys::CRYPTED_KEY, DBKeys::CSCRIPT, DBKeys::DEFAULTKEY, DBKeys::HDCHAIN, DBKeys::KEYMETA, DBKeys::KEY, DBKeys::OLD_KEY, DBKeys::POOL, DBKeys::WATCHMETA, DBKeys::WATCHS,\n+        // Descriptor wallet types that shouldn't be in the db\n+        DBKeys::ACTIVEEXTERNALSPK, DBKeys::ACTIVEINTERNALSPK, DBKeys::WALLETDESCRIPTOR, DBKeys::WALLETDESCRIPTORCACHE, DBKeys::WALLETDESCRIPTORLHCACHE, DBKeys::WALLETDESCRIPTORCKEY, DBKeys::WALLETDESCRIPTORKEY,\n+        // Transaction types that will be explicitly inserted\n+        DBKeys::TX, DBKeys::WTX_VARIANT,\n+        // Address book types that will be explicitly inserted\n+        DBKeys::DESTDATA, DBKeys::NAME, DBKeys::PURPOSE,\n+    });\n+\n+    return RunWithinTxn(new_db, \"migration: write records to new db\", [&records, &had_legacy_records, &SKIP_TYPES](DatabaseBatch& in_batch) {\n+        for (const auto& [key, value] : records) {\n+            DataStream ss_key{key};\n+            std::string type;\n+            ss_key >> type;\n+            if (!had_legacy_records && DBKeys::LEGACY_TYPES.contains(type)) {\n+                had_legacy_records = true;\n+            }\n+            if (SKIP_TYPES.contains(type)) {\n+                continue;\n+            }\n+\n+            if (!in_batch.Write(std::span{key}, std::span{value})) return false;\n+        }\n+        return true;\n+    });\n+}\n+\n+bool CWallet::MigrateToSQLite(bilingual_str& error, bool& had_legacy_records)\n {\n     AssertLockHeld(cs_wallet);\n \n@@ -69,14 +125,6 @@ bool CWallet::MigrateToSQLite(const std::unordered_set<std::string>& skip_types,\n         }\n         SerializeData key(ss_key.begin(), ss_key.end());\n         SerializeData value(ss_value.begin(), ss_value.end());\n-\n-        std::string type;\n-        ss_key >> type;\n-        if (skip_types.contains(type)) {\n-            had_legacy_records = true;\n-            continue;\n-        }\n-\n         records.emplace_back(key, value);\n     }\n     cursor.reset();\n@@ -86,39 +134,82 @@ bool CWallet::MigrateToSQLite(const std::unordered_set<std::string>& skip_types,\n         return false;\n     }\n \n-    // Close this database and delete the file\n-    fs::path db_path = fs::PathFromString(m_database->Filename());\n-    m_database->Close();\n-    fs::remove(db_path);\n+    // Create a temporary database next to the original db file\n+    const fs::path db_file = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_database->Filename()));\n+    const std::string new_db_name = strprintf(\"%s_sqlite_%d.tmp\", MigrationFilePrefix(*this), GetTime());\n+    const fs::path tmp_wallet_path = fs::path{db_file.parent_path()} / fs::PathFromString(new_db_name);\n+    // Refuse any existing path, not just an existing database (all that require_create checks), so cleanup only\n+    // deletes files this function created.\n+    if (std::error_code ec; fs::exists(fs::symlink_status(tmp_wallet_path, ec))) {\n+        error = strprintf(_(\"Error: Unable to create the new database for wallet '%s'. Temporary path '%s' already exists.\"), GetName(), fs::PathToString(tmp_wallet_path));\n+        return false;\n+    }\n \n     // Generate the path for the location of the migrated wallet\n     // Wallets that are plain files rather than wallet directories will be migrated to be wallet directories.\n-    const fs::path wallet_path = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_name));\n+    const fs::path dst_wallet_dir = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_name));\n \n     // Make new DB\n     DatabaseOptions opts;\n     opts.require_create = true;\n     opts.require_format = DatabaseFormat::SQLITE;\n     DatabaseStatus db_status;\n-    std::unique_ptr<WalletDatabase> new_db = MakeDatabase(wallet_path, opts, db_status, error);\n-    assert(new_db); // This is to prevent doing anything further with this wallet. The original file was deleted, but a backup exists.\n-    m_database.reset();\n-    m_database = std::move(new_db);\n+    std::unique_ptr<WalletDatabase> new_db = MakeDatabase(tmp_wallet_path, opts, db_status, error);\n+\n+    // Set the error, then delete the temporary database and its directory. The directory did not exist before, so it\n+    // only holds files of the new db, including any left by a failed creation.\n+    const auto remove_tmp_and_fail = [&](bilingual_str err) {\n+        error = std::move(err);\n+        new_db.reset(); // Close the db before deleting its files\n+        std::error_code ec;\n+        for (auto it{fs::directory_iterator(tmp_wallet_path, ec)}; !ec && it != fs::directory_iterator(); it.increment(ec)) {\n+            fs::remove(it->path(), ec);\n+        }\n+        fs::remove(tmp_wallet_path, ec);\n+        if (ec) {\n+            error += Untranslated(\" \") + strprintf(_(\"The temporary database at %s could not be removed.\"), fs::PathToString(tmp_wallet_path));\n+        }\n+        return false;\n+    };\n+\n+    if (!new_db) {\n+        return remove_tmp_and_fail(strprintf(_(\"Error: Unable to create the new database for wallet '%s'.\"), GetName()) + Untranslated(\" \") + error);\n+    }\n \n     // Write existing records into the new DB\n-    batch = m_database->MakeBatch();\n-    bool began = batch->TxnBegin();\n-    assert(began); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.\n-    for (const auto& [key, value] : records) {\n-        if (!batch->Write(std::span{key}, std::span{value})) {\n-            batch->TxnAbort();\n-            m_database->Close();\n-            fs::remove(m_database->Filename());\n-            AssertUnreachable(); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.\n-        }\n-    }\n-    bool committed = batch->TxnCommit();\n-    assert(committed); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.\n+    {\n+        const bool written = CopyMigrationRecords(records, *new_db, had_legacy_records);\n+        if (!written) {\n+            return remove_tmp_and_fail(strprintf(_(\"Error: Unable to write records into the new database for wallet '%s'\"), GetName()));\n+        }\n+    }\n+\n+    // ######################################################################\n+    // At this point, the new database has all records.                     #\n+    // Move it into the wallet location, replacing the original db file.    #\n+    // ######################################################################\n+\n+    // A plain wallet file (its db file is the wallet path itself) becomes a wallet directory. As a file cannot be\n+    // atomically replaced by a directory, the original db is erased first in that case. The original db is a single\n+    // file, so if Erase() fails nothing was removed, and returning false is still correct.\n+    if (db_file == dst_wallet_dir) {\n+        Assume(m_database->Files().size() == 1);\n+        if (auto res{m_database->Erase()}; !res) return remove_tmp_and_fail(util::ErrorString(res));\n+    }\n+\n+    // From here on, the original db may have been erased or replaced. Never return false after this point, as the\n+    // caller would skip the restore. Throw instead, so it deletes the wallet files and restores the backup.\n+    if (auto res{MoveDatabase(new_db, dst_wallet_dir, opts)}; !res) {\n+        remove_tmp_and_fail(util::ErrorString(res));\n+        throw std::runtime_error(error.original);\n+    }\n+    // The caller's rollback deletes m_database's files, so point it at the new db as soon as it replaces the original\n+    m_database = std::move(new_db);\n+    // The temporary dir only held the new db files, which were just moved out. If it can't be removed, something\n+    // unexpected happened, so stop and let the caller restore the backup.\n+    if (std::error_code ec; !fs::remove(tmp_wallet_path, ec)) {\n+        throw std::runtime_error(strprintf(\"Unable to remove temporary directory %s after moving the new database: %s\", fs::PathToString(tmp_wallet_path), ec ? ec.message() : \"it no longer exists\"));\n+    }\n     return true;\n }\n \n@@ -268,9 +359,10 @@ util::Result<void> CWallet::ApplyMigrationData(WalletBatch& local_wallet_batch,\n     }\n \n     // Pair external wallets with their corresponding db handler\n-    std::vector<std::pair<std::shared_ptr<CWallet>, std::unique_ptr<WalletBatch>>> wallets_vec;\n-    if (data.watchonly_wallet) wallets_vec.emplace_back(data.watchonly_wallet, std::move(watchonly_batch));\n-    if (data.solvable_wallet) wallets_vec.emplace_back(data.solvable_wallet, std::move(solvables_batch));\n+    std::vector<std::pair<CWallet*, WalletBatch*>> wallets_vec;\n+    wallets_vec.emplace_back(this, &local_wallet_batch);\n+    if (data.watchonly_wallet) wallets_vec.emplace_back(data.watchonly_wallet.get(), watchonly_batch.get());\n+    if (data.solvable_wallet) wallets_vec.emplace_back(data.solvable_wallet.get(), solvables_batch.get());\n \n     // Write address book entry to disk\n     auto func_store_addr = [](WalletBatch& batch, const CTxDestination& dest, const CAddressBookData& entry) {\n@@ -284,59 +376,39 @@ util::Result<void> CWallet::ApplyMigrationData(WalletBatch& local_wallet_batch,\n     };\n \n     // Check the address book data in the same way we did for transactions\n-    std::vector<CTxDestination> dests_to_delete;\n-    for (const auto& [dest, record] : m_address_book) {\n+    std::map<CTxDestination, CAddressBookData> address_book = m_address_book;\n+    m_address_book.clear();\n+    for (const auto& [dest, record] : address_book) {\n         // Ensure \"receive\" entries that are no longer part of the original wallet are transferred to another wallet\n         // Entries for everything else (\"send\") will be cloned to all wallets.\n-        bool require_transfer = record.purpose == AddressPurpose::RECEIVE && !IsMine(dest);\n-        bool copied = false;\n+        bool written = false;\n         for (auto& [wallet, batch] : wallets_vec) {\n             LOCK(wallet->cs_wallet);\n-            if (require_transfer && !wallet->IsMine(dest)) continue;\n+            if (record.purpose == AddressPurpose::RECEIVE && !wallet->IsMine(dest)) continue;\n \n             // Copy the entire address book entry\n-            wallet->m_address_book[dest] = record;\n+            wallet->m_address_book.emplace(dest, record);\n             func_store_addr(*batch, dest, record);\n \n-            copied = true;\n-            // Only delete 'receive' records that are no longer part of the original wallet\n-            if (require_transfer) {\n-                dests_to_delete.push_back(dest);\n-                break;\n-            }\n+            written = true;\n         }\n \n-        // Fail immediately if we ever found an entry that was ours and cannot be transferred\n-        // to any of the created wallets (watch-only, solvable).\n+        // Fail immediately if we ever found an entry that could not be written into a wallet\n         // Means that no inferred descriptor maps to the stored entry. Which mustn't happen.\n-        if (require_transfer && !copied) {\n-\n-            // Skip invalid/non-watched scripts that will not be migrated\n-            if (not_migrated_dests.contains(dest)) {\n-                dests_to_delete.push_back(dest);\n-                continue;\n-            }\n-\n+        // However entires correspond to invalid or non-watched scripts that cannot be migrated\n+        if (!written && !not_migrated_dests.contains(dest)) {\n             return util::Error{_(\"Error: Address book data in wallet cannot be identified to belong to migrated wallets\")};\n         }\n     }\n \n     // Persist external wallets address book entries\n     for (auto& [wallet, batch] : wallets_vec) {\n+        if (batch == &local_wallet_batch) continue; // Committing local_wallet_batch is done by the caller\n         if (!batch->TxnCommit()) {\n             return util::Error{strprintf(_(\"Error: Unable to write data to disk for wallet %s\"), wallet->GetName())};\n         }\n     }\n \n-    // Remove the things to delete in this wallet\n-    if (dests_to_delete.size() > 0) {\n-        for (const auto& dest : dests_to_delete) {\n-            if (!DelAddressBookWithDB(local_wallet_batch, dest)) {\n-                return util::Error{_(\"Error: Unable to remove watchonly address book data\")};\n-            }\n-        }\n-    }\n-\n     // If there was no key material in the main wallet, there should be no records on it anymore.\n     // This wallet will be discarded at the end of the process. Only wallets that contain the\n     // migrated records will be presented to the user.\n@@ -348,15 +420,6 @@ util::Result<void> CWallet::ApplyMigrationData(WalletBatch& local_wallet_batch,\n     return {}; // all good\n }\n \n-// Returns wallet prefix for migration.\n-// Used to name the backup file and newly created wallets.\n-// E.g. a watch-only wallet is named \"<prefix>_watchonly\".\n-static std::string MigrationPrefixName(CWallet& wallet)\n-{\n-    const std::string& name{wallet.GetName()};\n-    return name.empty() ? \"default_wallet\" : name;\n-}\n-\n bool DoMigration(CWallet& wallet, WalletContext& context, bilingual_str& error, MigrationResult& res, const bool load_on_startup = true) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n     AssertLockHeld(wallet.cs_wallet);\n@@ -383,85 +446,63 @@ bool DoMigration(CWallet& wallet, WalletContext& context, bilingual_str& error,\n         if (wallet.IsWalletFlagSet(WALLET_FLAG_KEY_ORIGIN_METADATA)) {\n             options.create_flags |= WALLET_FLAG_KEY_ORIGIN_METADATA;\n         }\n-        if (data->watch_descs.size() > 0) {\n-            wallet.WalletLogPrintf(\"Making a new watchonly wallet containing the watched scripts\");\n \n-            DatabaseStatus status;\n-            std::vector<bilingual_str> warnings;\n-            std::string wallet_name = MigrationPrefixName(wallet) + \"_watchonly\";\n-            std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(wallet_name, options, status, error);\n-            if (!database) {\n-                error = strprintf(_(\"Wallet file creation failed: %s\"), error);\n-                return false;\n-            }\n+        const auto fn_create_wallet = [&context, &options, &empty_context, load_on_startup](const std::string& wallet_name,\n+                                                                           const std::vector<std::pair<std::string, int64_t>>& descs_to_import,\n+                                                                           std::shared_ptr<CWallet>& out_wallet, bilingual_str& error) {\n+            try {\n+                DatabaseStatus status;\n+                std::vector<bilingual_str> warnings;\n+                std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(wallet_name, options, status, error);\n+                if (!database) {\n+                    error = strprintf(_(\"Wallet file creation failed: %s\"), error);\n+                    return false;\n+                }\n \n-            data->watchonly_wallet = CWallet::CreateNew(empty_context, wallet_name, std::move(database), options.create_flags, /*born_encrypted=*/false, error, warnings);\n-            if (!data->watchonly_wallet) {\n-                error = _(\"Error: Failed to create new watchonly wallet\");\n-                return false;\n-            }\n-            res.watchonly_wallet = data->watchonly_wallet;\n-            LOCK(data->watchonly_wallet->cs_wallet);\n-\n-            // Parse the descriptors and add them to the new wallet\n-            for (const auto& [desc_str, creation_time] : data->watch_descs) {\n-                // Parse the descriptor\n-                FlatSigningProvider keys;\n-                std::string parse_err;\n-                std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, parse_err, /*require_checksum=*/ true);\n-                // LegacyDataSPKM should not produce invalid, multipath, or ranged watch-only descriptors.\n-                assert(descs.size() == 1);\n-                assert(!descs.at(0)->IsRange());\n-\n-                // Add to the wallet\n-                WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);\n-                if (auto spkm_res = data->watchonly_wallet->AddWalletDescriptor(w_desc, keys, \"\", false); !spkm_res) {\n-                    throw std::runtime_error(util::ErrorString(spkm_res).original);\n+                out_wallet = CWallet::CreateNew(empty_context, wallet_name, std::move(database), options.create_flags, /*born_encrypted=*/false, error, warnings);\n+                if (!out_wallet) {\n+                    error = strprintf(_(\"Error: Failed to create new wallet '%s'\"), wallet_name);\n+                    return false;\n                 }\n+                LOCK(out_wallet->cs_wallet);\n+\n+                // Parse the descriptors and add them to the new wallet\n+                for (const auto& [desc_str, creation_time] : descs_to_import) {\n+                    // Parse the descriptor\n+                    FlatSigningProvider keys;\n+                    std::string parse_err;\n+                    std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, parse_err, /*require_checksum=*/ true);\n+                    // LegacyDataSPKM should not produce invalid, multipath, or ranged watch-only descriptors.\n+                    assert(descs.size() == 1);\n+                    assert(!descs.at(0)->IsRange());\n+\n+                    // Add to the wallet\n+                    WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);\n+                    if (auto spkm_res = out_wallet->AddWalletDescriptor(w_desc, keys, \"\", false); !spkm_res) {\n+                        throw std::runtime_error(util::ErrorString(spkm_res).original);\n+                    }\n+                }\n+\n+                // Add the wallet to settings\n+                UpdateWalletSetting(*context.chain, wallet_name, load_on_startup, warnings);\n+                return true;\n+            } catch (std::exception& e) {\n+                error = strprintf(_(\"Failed to create new wallet '%s'. Error: %s\"), wallet_name, e.what());\n+                return false;\n             }\n+        };\n \n-            // Add the wallet to settings\n-            UpdateWalletSetting(*context.chain, wallet_name, load_on_startup, warnings);\n+        if (data->wat\n[Path diff truncated]",
    "truncated": true,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 194,
    "evidence_id": "1ec6b5a2514542d2ba751a37e769cc0d",
    "finding_id": "finding:3",
    "kind": "new_source",
    "line": 45,
    "new_head": "7ba8d3e888f79649bf3b26502625880fa2e68908",
    "old_head": "e4c9aca57cda1643a7cd5ec45a8dab28be17f2e9",
    "path": "src/wallet/migration.cpp",
    "revision": "7ba8d3e888f79649bf3b26502625880fa2e68908",
    "source_generation": 7,
    "source_job_id": 3147,
    "text": "// E.g. a watch-only wallet is named \"<prefix>_watchonly\".\nstatic std::string MigrationPrefixName(CWallet& wallet)\n{\n    const std::string& name{wallet.GetName()};\n    return name.empty() ? \"default_wallet\" : name;\n}\n\n// Returns prefix for files created in the wallets directory during migration:\n// the backup file and the temporary database. Unlike MigrationPrefixName(),\n// this is a single path component, because the wallet name can be a path.\nstatic std::string MigrationFilePrefix(CWallet& wallet)\n{\n    const std::string& name{wallet.GetName()};\n    if (name.empty()) return MigrationPrefixName(wallet);\n    // fs::weakly_canonical resolves relative specifiers and removes trailing slashes.\n    const fs::path legacy_wallet_path{fs::weakly_canonical(GetWalletDir() / fs::PathFromString(name))};\n    return fs::PathToString(legacy_wallet_path.filename());\n}\n\nstatic bool CopyMigrationRecords(std::vector<std::pair<SerializeData, SerializeData>> records, WalletDatabase& new_db, bool& had_legacy_records)\n{\n    // Write existing records into the new DB\n    had_legacy_records = false;\n\n    std::unordered_set<std::string> SKIP_TYPES = DBKeys::LEGACY_TYPES;\n    SKIP_TYPES.insert({\n        // legacy wallet types\n        DBKeys::CRYPTED_KEY, DBKeys::CSCRIPT, DBKeys::DEFAULTKEY, DBKeys::HDCHAIN, DBKeys::KEYMETA, DBKeys::KEY, DBKeys::OLD_KEY, DBKeys::POOL, DBKeys::WATCHMETA, DBKeys::WATCHS,\n        // Descriptor wallet types that shouldn't be in the db\n        DBKeys::ACTIVEEXTERNALSPK, DBKeys::ACTIVEINTERNALSPK, DBKeys::WALLETDESCRIPTOR, DBKeys::WALLETDESCRIPTORCACHE, DBKeys::WALLETDESCRIPTORLHCACHE, DBKeys::WALLETDESCRIPTORCKEY, DBKeys::WALLETDESCRIPTORKEY,\n        // Transaction types that will be explicitly inserted\n        DBKeys::TX, DBKeys::WTX_VARIANT,\n        // Address book types that will be explicitly inserted\n        DBKeys::DESTDATA, DBKeys::NAME, DBKeys::PURPOSE,\n    });\n\n    return RunWithinTxn(new_db, \"migration: write records to new db\", [&records, &had_legacy_records, &SKIP_TYPES](DatabaseBatch& in_batch) {\n        for (const auto& [key, value] : records) {\n            DataStream ss_key{key};\n            std::string type;\n            ss_key >> type;\n            if (!had_legacy_records && DBKeys::LEGACY_TYPES.contains(type)) {\n                had_legacy_records = true;\n            }\n            if (SKIP_TYPES.contains(type)) {\n                continue;\n            }\n\n            if (!in_batch.Write(std::span{key}, std::span{value})) return false;\n        }\n        return true;\n    });\n}\n\nbool CWallet::MigrateToSQLite(bilingual_str& error, bool& had_legacy_records)\n{\n    AssertLockHeld(cs_wallet);\n\n    WalletLogPrintf(\"Migrating wallet storage database from BerkeleyDB to SQLite.\");\n\n    if (m_database->Format() == \"sqlite\") {\n        error = _(\"Error: This wallet already uses SQLite\");\n        return false;\n    }\n\n    // Get all of the records for DB type migration\n    std::unique_ptr<DatabaseBatch> batch = m_database->MakeBatch();\n    std::unique_ptr<DatabaseCursor> cursor = batch->GetNewCursor();\n    std::vector<std::pair<SerializeData, SerializeData>> records;\n    if (!cursor) {\n        error = _(\"Error: Unable to begin reading all records in the database\");\n        return false;\n    }\n    DatabaseCursor::Status status = DatabaseCursor::Status::FAIL;\n    while (true) {\n        DataStream ss_key{};\n        DataStream ss_value{};\n        status = cursor->Next(ss_key, ss_value);\n        if (status != DatabaseCursor::Status::MORE) {\n            break;\n        }\n        SerializeData key(ss_key.begin(), ss_key.end());\n        SerializeData value(ss_value.begin(), ss_value.end());\n        records.emplace_back(key, value);\n    }\n    cursor.reset();\n    batch.reset();\n    if (status != DatabaseCursor::Status::DONE) {\n        error = _(\"Error: Unable to read all records in the database\");\n        return false;\n    }\n\n    // Create a temporary database next to the original db file\n    const fs::path db_file = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_database->Filename()));\n    const std::string new_db_name = strprintf(\"%s_sqlite_%d.tmp\", MigrationFilePrefix(*this), GetTime());\n    const fs::path tmp_wallet_path = fs::path{db_file.parent_path()} / fs::PathFromString(new_db_name);\n    // Refuse any existing path, not just an existing database (all that require_create checks), so cleanup only\n    // deletes files this function created.\n    if (std::error_code ec; fs::exists(fs::symlink_status(tmp_wallet_path, ec))) {\n        error = strprintf(_(\"Error: Unable to create the new database for wallet '%s'. Temporary path '%s' already exists.\"), GetName(), fs::PathToString(tmp_wallet_path));\n        return false;\n    }\n\n    // Generate the path for the location of the migrated wallet\n    // Wallets that are plain files rather than wallet directories will be migrated to be wallet directories.\n    const fs::path dst_wallet_dir = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_name));\n\n    // Make new DB\n    DatabaseOptions opts;\n    opts.require_create = true;\n    opts.require_format = DatabaseFormat::SQLITE;\n    DatabaseStatus db_status;\n    std::unique_ptr<WalletDatabase> new_db = MakeDatabase(tmp_wallet_path, opts, db_status, error);\n\n    // Set the error, then delete the temporary database and its directory. The directory did not exist before, so it\n    // only holds files of the new db, including any left by a failed creation.\n    const auto remove_tmp_and_fail = [&](bilingual_str err) {\n        error = std::move(err);\n        new_db.reset(); // Close the db before deleting its files\n        std::error_code ec;\n        for (auto it{fs::directory_iterator(tmp_wallet_path, ec)}; !ec && it != fs::directory_iterator(); it.increment(ec)) {\n            fs::remove(it->path(), ec);\n        }\n        fs::remove(tmp_wallet_path, ec);\n        if (ec) {\n            error += Untranslated(\" \") + strprintf(_(\"The temporary database at %s could not be removed.\"), fs::PathToString(tmp_wallet_path));\n        }\n        return false;\n    };\n\n    if (!new_db) {\n        return remove_tmp_and_fail(strprintf(_(\"Error: Unable to create the new database for wallet '%s'.\"), GetName()) + Untranslated(\" \") + error);\n    }\n\n    // Write existing records into the new DB\n    {\n        const bool written = CopyMigrationRecords(records, *new_db, had_legacy_records);\n        if (!written) {\n            return remove_tmp_and_fail(strprintf(_(\"Error: Unable to write records into the new database for wallet '%s'\"), GetName()));\n        }\n    }\n\n    // ######################################################################\n    // At this point, the new database has all records.                     #\n    // Move it into the wallet location, replacing the original db file.    #\n    // ######################################################################\n\n    // A plain wallet file (its db file is the wallet path itself) becomes a wallet directory. As a file cannot be\n    // atomically replaced by a directory, the original db is erased first in that case. The original db is a single\n    // file, so if Erase() fails nothing was removed, and returning false is still correct.",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · e4c9aca57cda..7ba8d3e888f7

2026-11-26T01:11:49Z · gpt-6-luna

bitcoin#36823Watch-only-only transactions leave orphaned wtxvariant recordssrc/wallet/migration.cppaddressed
Assessment

CopyMigrationRecords now includes DBKeys::WTX_VARIANT in SKIP_TYPES, preventing the initial copy from leaving orphan variants in the main wallet when a transaction is transferred exclusively to the watch-only wallet. The migration path also writes the transferred transaction with WriteFullTx.

path_diff: src/wallet/migration.cpp; new_source: src/wallet/migration.cpp

[
  {
    "evidence_id": "cfee7c88c05043a4bc6b2e7dc88582bb",
    "finding_id": "finding:2",
    "kind": "path_diff",
    "new_head": "7ba8d3e888f79649bf3b26502625880fa2e68908",
    "old_head": "e4c9aca57cda1643a7cd5ec45a8dab28be17f2e9",
    "path": "src/wallet/migration.cpp",
    "source_generation": 7,
    "source_job_id": 3147,
    "text": "diff --git a/src/wallet/migration.cpp b/src/wallet/migration.cpp\nindex 3c42a6067d..6b06131484 100644\n--- a/src/wallet/migration.cpp\n+++ b/src/wallet/migration.cpp\n@@ -40,7 +40,63 @@ void CWallet::SetupLegacyDataSPKM()\n     AddScriptPubKeyMan(id, std::move(spk_manager));\n }\n \n-bool CWallet::MigrateToSQLite(const std::unordered_set<std::string>& skip_types, bilingual_str& error, bool& had_legacy_records)\n+// Returns wallet prefix for migration.\n+// Used to name the backup file and newly created wallets.\n+// E.g. a watch-only wallet is named \"<prefix>_watchonly\".\n+static std::string MigrationPrefixName(CWallet& wallet)\n+{\n+    const std::string& name{wallet.GetName()};\n+    return name.empty() ? \"default_wallet\" : name;\n+}\n+\n+// Returns prefix for files created in the wallets directory during migration:\n+// the backup file and the temporary database. Unlike MigrationPrefixName(),\n+// this is a single path component, because the wallet name can be a path.\n+static std::string MigrationFilePrefix(CWallet& wallet)\n+{\n+    const std::string& name{wallet.GetName()};\n+    if (name.empty()) return MigrationPrefixName(wallet);\n+    // fs::weakly_canonical resolves relative specifiers and removes trailing slashes.\n+    const fs::path legacy_wallet_path{fs::weakly_canonical(GetWalletDir() / fs::PathFromString(name))};\n+    return fs::PathToString(legacy_wallet_path.filename());\n+}\n+\n+static bool CopyMigrationRecords(std::vector<std::pair<SerializeData, SerializeData>> records, WalletDatabase& new_db, bool& had_legacy_records)\n+{\n+    // Write existing records into the new DB\n+    had_legacy_records = false;\n+\n+    std::unordered_set<std::string> SKIP_TYPES = DBKeys::LEGACY_TYPES;\n+    SKIP_TYPES.insert({\n+        // legacy wallet types\n+        DBKeys::CRYPTED_KEY, DBKeys::CSCRIPT, DBKeys::DEFAULTKEY, DBKeys::HDCHAIN, DBKeys::KEYMETA, DBKeys::KEY, DBKeys::OLD_KEY, DBKeys::POOL, DBKeys::WATCHMETA, DBKeys::WATCHS,\n+        // Descriptor wallet types that shouldn't be in the db\n+        DBKeys::ACTIVEEXTERNALSPK, DBKeys::ACTIVEINTERNALSPK, DBKeys::WALLETDESCRIPTOR, DBKeys::WALLETDESCRIPTORCACHE, DBKeys::WALLETDESCRIPTORLHCACHE, DBKeys::WALLETDESCRIPTORCKEY, DBKeys::WALLETDESCRIPTORKEY,\n+        // Transaction types that will be explicitly inserted\n+        DBKeys::TX, DBKeys::WTX_VARIANT,\n+        // Address book types that will be explicitly inserted\n+        DBKeys::DESTDATA, DBKeys::NAME, DBKeys::PURPOSE,\n+    });\n+\n+    return RunWithinTxn(new_db, \"migration: write records to new db\", [&records, &had_legacy_records, &SKIP_TYPES](DatabaseBatch& in_batch) {\n+        for (const auto& [key, value] : records) {\n+            DataStream ss_key{key};\n+            std::string type;\n+            ss_key >> type;\n+            if (!had_legacy_records && DBKeys::LEGACY_TYPES.contains(type)) {\n+                had_legacy_records = true;\n+            }\n+            if (SKIP_TYPES.contains(type)) {\n+                continue;\n+            }\n+\n+            if (!in_batch.Write(std::span{key}, std::span{value})) return false;\n+        }\n+        return true;\n+    });\n+}\n+\n+bool CWallet::MigrateToSQLite(bilingual_str& error, bool& had_legacy_records)\n {\n     AssertLockHeld(cs_wallet);\n \n@@ -69,14 +125,6 @@ bool CWallet::MigrateToSQLite(const std::unordered_set<std::string>& skip_types,\n         }\n         SerializeData key(ss_key.begin(), ss_key.end());\n         SerializeData value(ss_value.begin(), ss_value.end());\n-\n-        std::string type;\n-        ss_key >> type;\n-        if (skip_types.contains(type)) {\n-            had_legacy_records = true;\n-            continue;\n-        }\n-\n         records.emplace_back(key, value);\n     }\n     cursor.reset();\n@@ -86,39 +134,82 @@ bool CWallet::MigrateToSQLite(const std::unordered_set<std::string>& skip_types,\n         return false;\n     }\n \n-    // Close this database and delete the file\n-    fs::path db_path = fs::PathFromString(m_database->Filename());\n-    m_database->Close();\n-    fs::remove(db_path);\n+    // Create a temporary database next to the original db file\n+    const fs::path db_file = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_database->Filename()));\n+    const std::string new_db_name = strprintf(\"%s_sqlite_%d.tmp\", MigrationFilePrefix(*this), GetTime());\n+    const fs::path tmp_wallet_path = fs::path{db_file.parent_path()} / fs::PathFromString(new_db_name);\n+    // Refuse any existing path, not just an existing database (all that require_create checks), so cleanup only\n+    // deletes files this function created.\n+    if (std::error_code ec; fs::exists(fs::symlink_status(tmp_wallet_path, ec))) {\n+        error = strprintf(_(\"Error: Unable to create the new database for wallet '%s'. Temporary path '%s' already exists.\"), GetName(), fs::PathToString(tmp_wallet_path));\n+        return false;\n+    }\n \n     // Generate the path for the location of the migrated wallet\n     // Wallets that are plain files rather than wallet directories will be migrated to be wallet directories.\n-    const fs::path wallet_path = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_name));\n+    const fs::path dst_wallet_dir = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_name));\n \n     // Make new DB\n     DatabaseOptions opts;\n     opts.require_create = true;\n     opts.require_format = DatabaseFormat::SQLITE;\n     DatabaseStatus db_status;\n-    std::unique_ptr<WalletDatabase> new_db = MakeDatabase(wallet_path, opts, db_status, error);\n-    assert(new_db); // This is to prevent doing anything further with this wallet. The original file was deleted, but a backup exists.\n-    m_database.reset();\n-    m_database = std::move(new_db);\n+    std::unique_ptr<WalletDatabase> new_db = MakeDatabase(tmp_wallet_path, opts, db_status, error);\n+\n+    // Set the error, then delete the temporary database and its directory. The directory did not exist before, so it\n+    // only holds files of the new db, including any left by a failed creation.\n+    const auto remove_tmp_and_fail = [&](bilingual_str err) {\n+        error = std::move(err);\n+        new_db.reset(); // Close the db before deleting its files\n+        std::error_code ec;\n+        for (auto it{fs::directory_iterator(tmp_wallet_path, ec)}; !ec && it != fs::directory_iterator(); it.increment(ec)) {\n+            fs::remove(it->path(), ec);\n+        }\n+        fs::remove(tmp_wallet_path, ec);\n+        if (ec) {\n+            error += Untranslated(\" \") + strprintf(_(\"The temporary database at %s could not be removed.\"), fs::PathToString(tmp_wallet_path));\n+        }\n+        return false;\n+    };\n+\n+    if (!new_db) {\n+        return remove_tmp_and_fail(strprintf(_(\"Error: Unable to create the new database for wallet '%s'.\"), GetName()) + Untranslated(\" \") + error);\n+    }\n \n     // Write existing records into the new DB\n-    batch = m_database->MakeBatch();\n-    bool began = batch->TxnBegin();\n-    assert(began); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.\n-    for (const auto& [key, value] : records) {\n-        if (!batch->Write(std::span{key}, std::span{value})) {\n-            batch->TxnAbort();\n-            m_database->Close();\n-            fs::remove(m_database->Filename());\n-            AssertUnreachable(); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.\n-        }\n-    }\n-    bool committed = batch->TxnCommit();\n-    assert(committed); // This is a critical error, the new db could not be written to. The original db exists as a backup, but we should not continue execution.\n+    {\n+        const bool written = CopyMigrationRecords(records, *new_db, had_legacy_records);\n+        if (!written) {\n+            return remove_tmp_and_fail(strprintf(_(\"Error: Unable to write records into the new database for wallet '%s'\"), GetName()));\n+        }\n+    }\n+\n+    // ######################################################################\n+    // At this point, the new database has all records.                     #\n+    // Move it into the wallet location, replacing the original db file.    #\n+    // ######################################################################\n+\n+    // A plain wallet file (its db file is the wallet path itself) becomes a wallet directory. As a file cannot be\n+    // atomically replaced by a directory, the original db is erased first in that case. The original db is a single\n+    // file, so if Erase() fails nothing was removed, and returning false is still correct.\n+    if (db_file == dst_wallet_dir) {\n+        Assume(m_database->Files().size() == 1);\n+        if (auto res{m_database->Erase()}; !res) return remove_tmp_and_fail(util::ErrorString(res));\n+    }\n+\n+    // From here on, the original db may have been erased or replaced. Never return false after this point, as the\n+    // caller would skip the restore. Throw instead, so it deletes the wallet files and restores the backup.\n+    if (auto res{MoveDatabase(new_db, dst_wallet_dir, opts)}; !res) {\n+        remove_tmp_and_fail(util::ErrorString(res));\n+        throw std::runtime_error(error.original);\n+    }\n+    // The caller's rollback deletes m_database's files, so point it at the new db as soon as it replaces the original\n+    m_database = std::move(new_db);\n+    // The temporary dir only held the new db files, which were just moved out. If it can't be removed, something\n+    // unexpected happened, so stop and let the caller restore the backup.\n+    if (std::error_code ec; !fs::remove(tmp_wallet_path, ec)) {\n+        throw std::runtime_error(strprintf(\"Unable to remove temporary directory %s after moving the new database: %s\", fs::PathToString(tmp_wallet_path), ec ? ec.message() : \"it no longer exists\"));\n+    }\n     return true;\n }\n \n@@ -268,9 +359,10 @@ util::Result<void> CWallet::ApplyMigrationData(WalletBatch& local_wallet_batch,\n     }\n \n     // Pair external wallets with their corresponding db handler\n-    std::vector<std::pair<std::shared_ptr<CWallet>, std::unique_ptr<WalletBatch>>> wallets_vec;\n-    if (data.watchonly_wallet) wallets_vec.emplace_back(data.watchonly_wallet, std::move(watchonly_batch));\n-    if (data.solvable_wallet) wallets_vec.emplace_back(data.solvable_wallet, std::move(solvables_batch));\n+    std::vector<std::pair<CWallet*, WalletBatch*>> wallets_vec;\n+    wallets_vec.emplace_back(this, &local_wallet_batch);\n+    if (data.watchonly_wallet) wallets_vec.emplace_back(data.watchonly_wallet.get(), watchonly_batch.get());\n+    if (data.solvable_wallet) wallets_vec.emplace_back(data.solvable_wallet.get(), solvables_batch.get());\n \n     // Write address book entry to disk\n     auto func_store_addr = [](WalletBatch& batch, const CTxDestination& dest, const CAddressBookData& entry) {\n@@ -284,59 +376,39 @@ util::Result<void> CWallet::ApplyMigrationData(WalletBatch& local_wallet_batch,\n     };\n \n     // Check the address book data in the same way we did for transactions\n-    std::vector<CTxDestination> dests_to_delete;\n-    for (const auto& [dest, record] : m_address_book) {\n+    std::map<CTxDestination, CAddressBookData> address_book = m_address_book;\n+    m_address_book.clear();\n+    for (const auto& [dest, record] : address_book) {\n         // Ensure \"receive\" entries that are no longer part of the original wallet are transferred to another wallet\n         // Entries for everything else (\"send\") will be cloned to all wallets.\n-        bool require_transfer = record.purpose == AddressPurpose::RECEIVE && !IsMine(dest);\n-        bool copied = false;\n+        bool written = false;\n         for (auto& [wallet, batch] : wallets_vec) {\n             LOCK(wallet->cs_wallet);\n-            if (require_transfer && !wallet->IsMine(dest)) continue;\n+            if (record.purpose == AddressPurpose::RECEIVE && !wallet->IsMine(dest)) continue;\n \n             // Copy the entire address book entry\n-            wallet->m_address_book[dest] = record;\n+            wallet->m_address_book.emplace(dest, record);\n             func_store_addr(*batch, dest, record);\n \n-            copied = true;\n-            // Only delete 'receive' records that are no longer part of the original wallet\n-            if (require_transfer) {\n-                dests_to_delete.push_back(dest);\n-                break;\n-            }\n+            written = true;\n         }\n \n-        // Fail immediately if we ever found an entry that was ours and cannot be transferred\n-        // to any of the created wallets (watch-only, solvable).\n+        // Fail immediately if we ever found an entry that could not be written into a wallet\n         // Means that no inferred descriptor maps to the stored entry. Which mustn't happen.\n-        if (require_transfer && !copied) {\n-\n-            // Skip invalid/non-watched scripts that will not be migrated\n-            if (not_migrated_dests.contains(dest)) {\n-                dests_to_delete.push_back(dest);\n-                continue;\n-            }\n-\n+        // However entires correspond to invalid or non-watched scripts that cannot be migrated\n+        if (!written && !not_migrated_dests.contains(dest)) {\n             return util::Error{_(\"Error: Address book data in wallet cannot be identified to belong to migrated wallets\")};\n         }\n     }\n \n     // Persist external wallets address book entries\n     for (auto& [wallet, batch] : wallets_vec) {\n+        if (batch == &local_wallet_batch) continue; // Committing local_wallet_batch is done by the caller\n         if (!batch->TxnCommit()) {\n             return util::Error{strprintf(_(\"Error: Unable to write data to disk for wallet %s\"), wallet->GetName())};\n         }\n     }\n \n-    // Remove the things to delete in this wallet\n-    if (dests_to_delete.size() > 0) {\n-        for (const auto& dest : dests_to_delete) {\n-            if (!DelAddressBookWithDB(local_wallet_batch, dest)) {\n-                return util::Error{_(\"Error: Unable to remove watchonly address book data\")};\n-            }\n-        }\n-    }\n-\n     // If there was no key material in the main wallet, there should be no records on it anymore.\n     // This wallet will be discarded at the end of the process. Only wallets that contain the\n     // migrated records will be presented to the user.\n@@ -348,15 +420,6 @@ util::Result<void> CWallet::ApplyMigrationData(WalletBatch& local_wallet_batch,\n     return {}; // all good\n }\n \n-// Returns wallet prefix for migration.\n-// Used to name the backup file and newly created wallets.\n-// E.g. a watch-only wallet is named \"<prefix>_watchonly\".\n-static std::string MigrationPrefixName(CWallet& wallet)\n-{\n-    const std::string& name{wallet.GetName()};\n-    return name.empty() ? \"default_wallet\" : name;\n-}\n-\n bool DoMigration(CWallet& wallet, WalletContext& context, bilingual_str& error, MigrationResult& res, const bool load_on_startup = true) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n     AssertLockHeld(wallet.cs_wallet);\n@@ -383,85 +446,63 @@ bool DoMigration(CWallet& wallet, WalletContext& context, bilingual_str& error,\n         if (wallet.IsWalletFlagSet(WALLET_FLAG_KEY_ORIGIN_METADATA)) {\n             options.create_flags |= WALLET_FLAG_KEY_ORIGIN_METADATA;\n         }\n-        if (data->watch_descs.size() > 0) {\n-            wallet.WalletLogPrintf(\"Making a new watchonly wallet containing the watched scripts\");\n \n-            DatabaseStatus status;\n-            std::vector<bilingual_str> warnings;\n-            std::string wallet_name = MigrationPrefixName(wallet) + \"_watchonly\";\n-            std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(wallet_name, options, status, error);\n-            if (!database) {\n-                error = strprintf(_(\"Wallet file creation failed: %s\"), error);\n-                return false;\n-            }\n+        const auto fn_create_wallet = [&context, &options, &empty_context, load_on_startup](const std::string& wallet_name,\n+                                                                           const std::vector<std::pair<std::string, int64_t>>& descs_to_import,\n+                                                                           std::shared_ptr<CWallet>& out_wallet, bilingual_str& error) {\n+            try {\n+                DatabaseStatus status;\n+                std::vector<bilingual_str> warnings;\n+                std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(wallet_name, options, status, error);\n+                if (!database) {\n+                    error = strprintf(_(\"Wallet file creation failed: %s\"), error);\n+                    return false;\n+                }\n \n-            data->watchonly_wallet = CWallet::CreateNew(empty_context, wallet_name, std::move(database), options.create_flags, /*born_encrypted=*/false, error, warnings);\n-            if (!data->watchonly_wallet) {\n-                error = _(\"Error: Failed to create new watchonly wallet\");\n-                return false;\n-            }\n-            res.watchonly_wallet = data->watchonly_wallet;\n-            LOCK(data->watchonly_wallet->cs_wallet);\n-\n-            // Parse the descriptors and add them to the new wallet\n-            for (const auto& [desc_str, creation_time] : data->watch_descs) {\n-                // Parse the descriptor\n-                FlatSigningProvider keys;\n-                std::string parse_err;\n-                std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, parse_err, /*require_checksum=*/ true);\n-                // LegacyDataSPKM should not produce invalid, multipath, or ranged watch-only descriptors.\n-                assert(descs.size() == 1);\n-                assert(!descs.at(0)->IsRange());\n-\n-                // Add to the wallet\n-                WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);\n-                if (auto spkm_res = data->watchonly_wallet->AddWalletDescriptor(w_desc, keys, \"\", false); !spkm_res) {\n-                    throw std::runtime_error(util::ErrorString(spkm_res).original);\n+                out_wallet = CWallet::CreateNew(empty_context, wallet_name, std::move(database), options.create_flags, /*born_encrypted=*/false, error, warnings);\n+                if (!out_wallet) {\n+                    error = strprintf(_(\"Error: Failed to create new wallet '%s'\"), wallet_name);\n+                    return false;\n                 }\n+                LOCK(out_wallet->cs_wallet);\n+\n+                // Parse the descriptors and add them to the new wallet\n+                for (const auto& [desc_str, creation_time] : descs_to_import) {\n+                    // Parse the descriptor\n+                    FlatSigningProvider keys;\n+                    std::string parse_err;\n+                    std::vector<std::unique_ptr<Descriptor>> descs = Parse(desc_str, keys, parse_err, /*require_checksum=*/ true);\n+                    // LegacyDataSPKM should not produce invalid, multipath, or ranged watch-only descriptors.\n+                    assert(descs.size() == 1);\n+                    assert(!descs.at(0)->IsRange());\n+\n+                    // Add to the wallet\n+                    WalletDescriptor w_desc(std::move(descs.at(0)), creation_time, 0, 0, 0);\n+                    if (auto spkm_res = out_wallet->AddWalletDescriptor(w_desc, keys, \"\", false); !spkm_res) {\n+                        throw std::runtime_error(util::ErrorString(spkm_res).original);\n+                    }\n+                }\n+\n+                // Add the wallet to settings\n+                UpdateWalletSetting(*context.chain, wallet_name, load_on_startup, warnings);\n+                return true;\n+            } catch (std::exception& e) {\n+                error = strprintf(_(\"Failed to create new wallet '%s'. Error: %s\"), wallet_name, e.what());\n+                return false;\n             }\n+        };\n \n-            // Add the wallet to settings\n-            UpdateWalletSetting(*context.chain, wallet_name, load_on_startup, warnings);\n+        if (data->wat\n[Path diff truncated]",
    "truncated": true,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 391,
    "evidence_id": "f03e609e58f94a56ae32700db444d6a6",
    "finding_id": "finding:2",
    "kind": "new_source",
    "line": 242,
    "new_head": "7ba8d3e888f79649bf3b26502625880fa2e68908",
    "old_head": "e4c9aca57cda1643a7cd5ec45a8dab28be17f2e9",
    "path": "src/wallet/migration.cpp",
    "revision": "7ba8d3e888f79649bf3b26502625880fa2e68908",
    "source_generation": 7,
    "source_job_id": 3147,
    "text": "        return util::Error{Untranslated(STR_INTERNAL_BUG(\"Error: Legacy wallet data missing\"))};\n    }\n\n    // Note: when the legacy wallet has no spendable scripts, it must be empty at the end of the process.\n    bool has_spendable_material = !data.desc_spkms.empty() || data.master_key.key.IsValid();\n\n    // Get all invalid or non-watched scripts that will not be migrated\n    std::set<CTxDestination> not_migrated_dests;\n    for (const auto& script : legacy_spkm->GetNotMineScriptPubKeys()) {\n        CTxDestination dest;\n        if (ExtractDestination(script, dest)) not_migrated_dests.emplace(dest);\n    }\n\n    // When the legacy wallet has no spendable scripts, the main wallet will be empty, leaving its script cache empty as well.\n    // The watch-only and/or solvable wallet(s) will contain the scripts in their respective caches.\n    if (!data.desc_spkms.empty()) Assume(!m_cached_spks.empty());\n    if (!data.watch_descs.empty()) Assume(!data.watchonly_wallet->m_cached_spks.empty());\n    if (!data.solvable_descs.empty()) Assume(!data.solvable_wallet->m_cached_spks.empty());\n\n    for (auto& desc_spkm : data.desc_spkms) {\n        if (m_spk_managers.contains(desc_spkm->GetID())) {\n            return util::Error{_(\"Error: Duplicate descriptors created during migration. Your wallet may be corrupted.\")};\n        }\n        uint256 id = desc_spkm->GetID();\n        AddScriptPubKeyMan(id, std::move(desc_spkm));\n    }\n\n    // Remove the LegacyDataSPKM from memory\n    m_spk_managers.erase(legacy_spkm->GetID());\n    m_external_spk_managers.clear();\n    m_internal_spk_managers.clear();\n\n    // Setup new descriptors (only if we are migrating any key material)\n    SetWalletFlagWithDB(local_wallet_batch, WALLET_FLAG_DESCRIPTORS | WALLET_FLAG_LAST_HARDENED_XPUB_CACHED);\n    if (has_spendable_material && !IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {\n        // Use the existing master key if we have it\n        if (data.master_key.key.IsValid()) {\n            SetupDescriptorScriptPubKeyMans(local_wallet_batch, data.master_key);\n        } else {\n            // Setup with a new seed if we don't.\n            SetupOwnDescriptorScriptPubKeyMans(local_wallet_batch);\n        }\n    }\n\n    // Set the last opened version and features\n    if (!local_wallet_batch.WriteLastOpenedVersion()) {\n        return util::Error{_(\"Error: Unable to write last opened version\")};\n    }\n    if (!local_wallet_batch.WriteLastOpenedFeatures()) {\n        return util::Error{_(\"Error: Unable to write last opened features\")};\n    }\n    if (HasEncryptionKeys()) {\n        if (!local_wallet_batch.WriteLastDecryptedFeatures()) {\n            return util::Error{_(\"Error: Unable to write last decrypted features\")};\n        }\n    }\n\n    // Get best block locator so that we can copy it to the watchonly and solvables\n    // Note: The best block locator was introduced in #152 so ancient wallets do not have it\n    CBlockLocator best_block_locator;\n    (void)local_wallet_batch.ReadBestBlock(best_block_locator);\n\n    // Update m_txos to match the descriptors remaining in this wallet\n    m_txos.clear();\n    RefreshAllTXOs();\n\n    // Check if the transactions in the wallet are still ours. Either they belong here, or they belong in the watchonly wallet.\n    // We need to go through these in the tx insertion order so that lookups to spends works.\n    std::unique_ptr<WalletBatch> watchonly_batch;\n    if (data.watchonly_wallet) {\n        watchonly_batch = std::make_unique<WalletBatch>(data.watchonly_wallet->GetDatabase());\n        if (!watchonly_batch->TxnBegin()) return util::Error{strprintf(_(\"Error: database transaction cannot be executed for wallet %s\"), data.watchonly_wallet->GetName())};\n        // Copy the next tx order pos to the watchonly wallet\n        LOCK(data.watchonly_wallet->cs_wallet);\n        data.watchonly_wallet->nOrderPosNext = nOrderPosNext;\n        watchonly_batch->WriteOrderPosNext(data.watchonly_wallet->nOrderPosNext);\n        // Write the locator record. An empty locator is valid and triggers rescan on load.\n        if (!watchonly_batch->WriteBestBlock(best_block_locator)) {\n            return util::Error{_(\"Error: Unable to write watchonly wallet best block locator record\")};\n        }\n    }\n    std::unique_ptr<WalletBatch> solvables_batch;\n    if (data.solvable_wallet) {\n        solvables_batch = std::make_unique<WalletBatch>(data.solvable_wallet->GetDatabase());\n        if (!solvables_batch->TxnBegin()) return util::Error{strprintf(_(\"Error: database transaction cannot be executed for wallet %s\"), data.solvable_wallet->GetName())};\n        // Write the locator record. An empty locator is valid and triggers rescan on load.\n        if (!solvables_batch->WriteBestBlock(best_block_locator)) {\n            return util::Error{_(\"Error: Unable to write solvable wallet best block locator record\")};\n        }\n    }\n    for (const auto& [_pos, wtx] : wtxOrdered) {\n        // Check it is the watchonly wallet's\n        // solvable_wallet doesn't need to be checked because transactions for those scripts weren't being watched for\n        bool is_mine = IsMine(*wtx->GetTx()) || IsFromMe(*wtx->GetTx());\n        if (data.watchonly_wallet) {\n            LOCK(data.watchonly_wallet->cs_wallet);\n            if (data.watchonly_wallet->IsMine(*wtx->GetTx()) || data.watchonly_wallet->IsFromMe(*wtx->GetTx())) {\n                // Add to watchonly wallet\n                const Txid& hash = wtx->GetHash();\n                DataStream wtx_ser;\n                wtx_ser << *wtx;\n                CWalletTx copy_wtx(deserialize, wtx_ser, wtx->GetTxs());\n                if (!data.watchonly_wallet->LoadToWallet(std::move(copy_wtx))) {\n                    return util::Error{strprintf(_(\"Error: Could not add watchonly tx %s to watchonly wallet\"), wtx->GetHash().GetHex())};\n                }\n                watchonly_batch->WriteFullTx(data.watchonly_wallet->mapWallet.at(hash));\n                if (!is_mine) {\n                    continue;\n                }\n            }\n        }\n        if (!is_mine) {\n            // Both not ours and not in the watchonly wallet\n            return util::Error{strprintf(_(\"Error: Transaction %s in wallet cannot be identified to belong to migrated wallets\"), wtx->GetHash().GetHex())};\n        }\n        // Rewrite the transaction so that anything that may have changed about it in memory also persists to disk\n        local_wallet_batch.WriteTxMetadata(*wtx);\n    }\n\n    // Pair external wallets with their corresponding db handler\n    std::vector<std::pair<CWallet*, WalletBatch*>> wallets_vec;\n    wallets_vec.emplace_back(this, &local_wallet_batch);\n    if (data.watchonly_wallet) wallets_vec.emplace_back(data.watchonly_wallet.get(), watchonly_batch.get());\n    if (data.solvable_wallet) wallets_vec.emplace_back(data.solvable_wallet.get(), solvables_batch.get());\n\n    // Write address book entry to disk\n    auto func_store_addr = [](WalletBatch& batch, const CTxDestination& dest, const CAddressBookData& entry) {\n        auto address{EncodeDestination(dest)};\n        if (entry.purpose) batch.WritePurpose(address, PurposeToString(*entry.purpose));\n        if (entry.label) batch.WriteName(address, *entry.label);\n        for (const auto& [id, request] : entry.receive_requests) {\n            batch.WriteAddressReceiveRequest(dest, id, request);\n        }\n        if (entry.previously_spent) batch.WriteAddressPreviouslySpent(dest, true);\n    };\n\n    // Check the address book data in the same way we did for transactions\n    std::map<CTxDestination, CAddressBookData> address_book = m_address_book;\n    m_address_book.clear();\n    for (const auto& [dest, record] : address_book) {\n        // Ensure \"receive\" entries that are no longer part of the original wallet are transferred to another wallet\n        // Entries for everything else (\"send\") will be cloned to all wallets.\n        bool written = false;\n        for (auto& [wallet, batch] : wallets_vec) {\n            LOCK(wallet->cs_wallet);\n            if (record.purpose == AddressPurpose::RECEIVE && !wallet->IsMine(dest)) continue;\n\n            // Copy the entire address book entry\n            wallet->m_address_book.emplace(dest, record);\n            func_store_addr(*batch, dest, record);",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · e4c9aca57cda..7ba8d3e888f7

2026-11-26T01:11:49Z · gpt-6-luna

bitcoin#36823The sole write of each retained tx record is uncheckedsrc/wallet/migration.cppunclear
Assessment

The follow-up assessment was invalid: follow-up evidence belongs to another finding or comparison.

invalid_assessment

Source report · e4c9aca57cda..7ba8d3e888f7

2026-11-26T01:11:49Z · gpt-6-luna

bitcoin#36861One commit couples arithmetic fixes to compatibility restrictionssrc/wallet/wallet.cppstill_present
Assessment

The supplied new-head excerpt shows no change to the reported commit-organization concern, and the supplied diff only changes a release-note newline. The requested separation into commits cannot be established as addressed.

new_source: src/wallet/wallet.cpp

[
  {
    "bounded": true,
    "end_line": 3061,
    "evidence_id": "6e5fa9d9ea394565a3c64f8823a1a6eb",
    "finding_id": "finding:9",
    "kind": "new_source",
    "line": 2912,
    "new_head": "0b33a8cca3815c7592277abb6acd6c7ea5ef85a0",
    "old_head": "a210aeebe7ebb66d35c9f51d700e21b41add60de",
    "path": "src/wallet/wallet.cpp",
    "revision": "0b33a8cca3815c7592277abb6acd6c7ea5ef85a0",
    "source_generation": 9,
    "source_job_id": 3138,
    "text": "            warnings.push_back(strprintf(_(\"%s is set very high! Fee rate this large could be paid on a single transaction.\"), \"-maxfeerate\"));\n        }\n\n        wallet->m_max_tx_fee_rate = CFeeRate(*max_tx_fee_rate);\n    }\n\n    if (const auto arg{args.GetArg(\"-consolidatefeerate\")}) {\n        if (std::optional<CAmount> consolidate_feerate = ParseMoney(*arg)) {\n            wallet->m_consolidate_feerate = CFeeRate(*consolidate_feerate);\n        } else {\n            error = AmountErrMsg(\"consolidatefeerate\", *arg);\n            return false;\n        }\n    }\n\n    if (chain && chain->relayMinFee().GetFeePerK() > HIGH_TX_FEE_PER_KB) {\n        warnings.push_back(AmountHighWarn(\"-minrelaytxfee\") + Untranslated(\" \") +\n                           _(\"The wallet will avoid paying less than the minimum relay fee.\"));\n    }\n\n    // m_confirm_target is unsigned, so a negative value would wrap to a huge\n    // target. Fee estimation rejects targets above the maximum it tracks, which\n    // makes every transaction silently fall back to -fallbackfee, so bound the\n    // target by what the estimator can actually serve. A maximum of 0 means no\n    // estimator is running (e.g. -blocksonly), in which case there is no bound\n    // to enforce.\n    if (const auto confirm_target{args.GetIntArg(\"-txconfirmtarget\", DEFAULT_TX_CONFIRM_TARGET)};\n        confirm_target < 1 || confirm_target > std::numeric_limits<unsigned int>::max()) {\n        error = strprintf(_(\"-txconfirmtarget must be between 1 and %u (got %d).\"), std::numeric_limits<unsigned int>::max(), confirm_target);\n        return false;\n    } else if (const unsigned int max_target{chain ? chain->maximumFeeEstimationTargetBlocks() : 0};\n               max_target != 0 && static_cast<unsigned int>(confirm_target) > max_target) {\n        error = strprintf(_(\"-txconfirmtarget must be between 1 and %u (got %d).\"), max_target, confirm_target);\n        return false;\n    } else {\n        wallet->m_confirm_target = static_cast<unsigned int>(confirm_target);\n    }\n\n    wallet->m_spend_zero_conf_change = args.GetBoolArg(\"-spendzeroconfchange\", DEFAULT_SPEND_ZEROCONF_CHANGE);\n    wallet->m_signal_rbf = DEFAULT_WALLET_RBF;\n    if (auto value{args.GetBoolArg(\"-walletrbf\")}) {\n        warnings.push_back(_(\"-walletrbf is deprecated and will be fully removed in the next release.\"));\n        wallet->m_signal_rbf = *value;\n    }\n\n    wallet->m_keypool_size = std::max(args.GetIntArg(\"-keypool\", DEFAULT_KEYPOOL_SIZE), int64_t{1});\n    wallet->m_notify_tx_changed_script = args.GetArg(\"-walletnotify\", \"\");\n    wallet->SetBroadcastTransactions(args.GetBoolArg(\"-walletbroadcast\", DEFAULT_WALLETBROADCAST));\n\n    return true;\n}\n\nstd::shared_ptr<CWallet> CWallet::CreateNew(WalletContext& context, const std::string& name, std::unique_ptr<WalletDatabase> database, uint64_t wallet_creation_flags, bool born_encrypted, bilingual_str& error, std::vector<bilingual_str>& warnings)\n{\n    interfaces::Chain* chain = context.chain;\n    const std::string& walletFile = database->Filename();\n\n    const auto start{SteadyClock::now()};\n    // TODO: Can't use std::make_shared because we need a custom deleter but\n    // should be possible to use std::allocate_shared.\n    std::shared_ptr<CWallet> walletInstance(new CWallet(chain, name, std::move(database)), FlushAndDeleteWallet);\n\n    if (!LoadWalletArgs(walletInstance, context, error, warnings)) {\n        return nullptr;\n    }\n\n    // Initialize version key.\n    {\n        WalletBatch batch(walletInstance->GetDatabase());\n        if(!batch.WriteLastOpenedVersion()) {\n            error = strprintf(_(\"Error creating %s: Could not write version metadata.\"), walletFile);\n            return nullptr;\n        }\n        if(!batch.WriteLastOpenedFeatures()) {\n            error = strprintf(_(\"Error creating %s: Could not write features metadata.\"), walletFile);\n            return nullptr;\n        }\n    }\n    {\n        LOCK(walletInstance->cs_wallet);\n\n        // Init with passed flags.\n        // Always set the cache upgrade flag as this feature is supported from the beginning.\n        walletInstance->InitWalletFlags(wallet_creation_flags | WALLET_FLAG_LAST_HARDENED_XPUB_CACHED);\n\n        // Only descriptor wallets can be created\n        assert(walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));\n\n        // Born encrypted wallets will have their keys generated later\n        if (!born_encrypted) {\n            walletInstance->SetupWalletGeneration();\n        }\n\n        if (chain) {\n            std::optional<int> tip_height = chain->getHeight();\n            if (tip_height) {\n                walletInstance->SetLastBlockProcessed(*tip_height, chain->getBlockHash(*tip_height));\n            }\n        }\n    }\n\n    walletInstance->WalletLogPrintf(\"Wallet completed creation in %15dms\", Ticks<std::chrono::milliseconds>(SteadyClock::now() - start));\n\n    // Try to top up keypool. No-op if the wallet is locked.\n    walletInstance->TopUpKeyPool();\n\n    if (chain && !AttachChain(walletInstance, *chain, /*rescan_required=*/false, error, warnings)) {\n        walletInstance->DisconnectChainNotifications();\n        return nullptr;\n    }\n\n    return walletInstance;\n}\n\nstd::shared_ptr<CWallet> CWallet::LoadExisting(WalletContext& context, const std::string& name, std::unique_ptr<WalletDatabase> database, bilingual_str& error, std::vector<bilingual_str>& warnings)\n{\n    interfaces::Chain* chain = context.chain;\n    const std::string& walletFile = database->Filename();\n\n    const auto start{SteadyClock::now()};\n    std::shared_ptr<CWallet> walletInstance(new CWallet(chain, name, std::move(database)), FlushAndDeleteWallet);\n\n    if (!LoadWalletArgs(walletInstance, context, error, warnings)) {\n        return nullptr;\n    }\n\n    // Load wallet\n    auto nLoadWalletRet = walletInstance->PopulateWalletFromDB(error, warnings);\n    bool rescan_required = nLoadWalletRet == DBErrors::NEED_RESCAN;\n    if (nLoadWalletRet != DBErrors::LOAD_OK && nLoadWalletRet != DBErrors::NONCRITICAL_ERROR && !rescan_required) {\n        return nullptr;\n    }\n\n    if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {\n        for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {\n            if (spk_man->HavePrivateKeys()) {\n                warnings.push_back(strprintf(_(\"Warning: Private keys detected in wallet {%s} with disabled private keys\"), walletFile));\n                break;\n            }\n        }\n    }\n\n    walletInstance->WalletLogPrintf(\"Wallet completed loading in %15dms\", Ticks<std::chrono::milliseconds>(SteadyClock::now() - start));\n\n    // Try to top up keypool. No-op if the wallet is locked.\n    walletInstance->TopUpKeyPool();\n\n    if (chain && !AttachChain(walletInstance, *chain, rescan_required, error, warnings)) {\n        walletInstance->DisconnectChainNotifications();\n        return nullptr;",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · a210aeebe7eb..0b33a8cca381

2026-11-26T00:52:07Z · gpt-6-luna

bitcoin#36861mempool_args_validation never checks the stored accepted valuessrc/test/mempool_tests.cppstill_present
Assessment

The new-head test helper still returns only `ApplyArgsManOptions`'s status. It does not expose the populated options or assert the stored seconds value for a large accepted expiry.

new_source: src/test/mempool_tests.cpp

[
  {
    "bounded": true,
    "end_line": 591,
    "evidence_id": "a329472335764f76a980e6e4bbb08540",
    "finding_id": "finding:7",
    "kind": "new_source",
    "line": 527,
    "new_head": "0b33a8cca3815c7592277abb6acd6c7ea5ef85a0",
    "old_head": "a210aeebe7ebb66d35c9f51d700e21b41add60de",
    "path": "src/test/mempool_tests.cpp",
    "revision": "0b33a8cca3815c7592277abb6acd6c7ea5ef85a0",
    "source_generation": 9,
    "source_job_id": 3138,
    "text": "\n    auto tx{make_tx({10 * COIN})};\n    auto txid{tx->GetHash()};\n    TryAddToMempool(pool, TestMemPoolEntryHelper{}.Fee(1000).FromTx(tx));\n\n    auto usage_before{pool.DynamicMemoryUsage()};\n    pool.AddUnbroadcastTx(txid);\n    BOOST_CHECK_GT(pool.DynamicMemoryUsage(), usage_before);\n\n    pool.RemoveUnbroadcastTx(txid);\n    BOOST_CHECK_EQUAL(pool.DynamicMemoryUsage(), usage_before);\n}\n\nBOOST_AUTO_TEST_CASE(mempool_args_validation)\n{\n    // ApplyArgsManOptions is applied once during startup, so values that would\n    // wrap when narrowed into the options struct must be rejected instead.\n    auto get_opts = [&](const std::vector<const char*>& args) {\n        ArgsManager args_man;\n        args_man.ClearArgs();\n        for (const char* arg : {\"-limitclustercount=<n>\", \"-limitclustersize=<n>\",\n                                \"-limitancestorcount=<n>\", \"-limitdescendantcount=<n>\",\n                                \"-mempoolexpiry=<n>\", \"-datacarriersize=<n>\",\n                                \"-maxmempool=<n>\", \"-permitbaremultisig\", \"-datacarrier\"}) {\n            args_man.AddArg(arg, \"\", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n        }\n        const auto argv{Cat({\"ignore\"}, args)};\n        std::string error{};\n        BOOST_REQUIRE(args_man.ParseParameters(argv.size(), argv.data(), error));\n        kernel::MemPoolOptions opts{};\n        return ApplyArgsManOptions(args_man, ::Params(), opts);\n    };\n\n    // Cluster limits must fit the range TxGraph accepts.\n    BOOST_CHECK(get_opts({}).has_value());\n    BOOST_CHECK(get_opts({\"-limitclustercount=1\"}).has_value());\n    BOOST_CHECK(get_opts({\"-limitclustercount=64\"}).has_value());\n    BOOST_CHECK(!get_opts({\"-limitclustercount=0\"}));   // TxGraph requires at least one\n    BOOST_CHECK(!get_opts({\"-limitclustercount=65\"}));  // above MAX_CLUSTER_COUNT_LIMIT\n    BOOST_CHECK(!get_opts({\"-limitclustercount=-1\"}));\n\n    BOOST_CHECK(!get_opts({\"-limitclustersize=0\"})); // would make every tx oversized\n    BOOST_CHECK(get_opts({\"-limitclustersize=1\"}).has_value());\n    BOOST_CHECK(!get_opts({\"-limitclustersize=-1\"})); // would wrap to an effectively unlimited cluster\n\n    BOOST_CHECK(get_opts({\"-limitancestorcount=0\"}).has_value());\n    BOOST_CHECK(!get_opts({\"-limitancestorcount=-1\"}));\n    BOOST_CHECK(get_opts({\"-limitdescendantcount=0\"}).has_value());\n    BOOST_CHECK(!get_opts({\"-limitdescendantcount=-1\"}));\n\n    // A negative expiry would move the expiration cutoff past the current time,\n    // expiring ordinary transactions on the next limiting pass, and a huge one\n    // would overflow the hours-to-seconds conversion.\n    BOOST_CHECK(get_opts({\"-mempoolexpiry=0\"}).has_value());\n    BOOST_CHECK(!get_opts({\"-mempoolexpiry=-1\"}));\n    BOOST_CHECK(!get_opts({\"-mempoolexpiry=2562047788015216\"})); // first hour count that overflows int64 seconds\n\n    // A negative carrier size would wrap to an unlimited OP_RETURN budget.\n    BOOST_CHECK(get_opts({\"-datacarriersize=0\"}).has_value());\n    BOOST_CHECK(!get_opts({\"-datacarriersize=-1\"}));\n    BOOST_CHECK(!get_opts({\"-datacarriersize=4294967296\"})); // above UINT_MAX would wrap to a tiny budget\n    BOOST_CHECK(get_opts({\"-datacarrier=0\", \"-datacarriersize=-1\"}).has_value()); // ignored when disabled\n}\n\nBOOST_AUTO_TEST_SUITE_END()",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · a210aeebe7eb..0b33a8cca381

2026-11-26T00:52:07Z · gpt-6-luna

bitcoin#36861-txconfirmtarget validity changes with relay modesrc/wallet/wallet.cppstill_present
Assessment

The new-head excerpt retains the estimator-dependent ceiling: it checks `max_target` only when nonzero, so the target limit still varies with relay mode.

new_source: src/wallet/wallet.cpp

[
  {
    "bounded": true,
    "end_line": 3062,
    "evidence_id": "f4bda169517147b2aea71996b77295e9",
    "finding_id": "finding:6",
    "kind": "new_source",
    "line": 2913,
    "new_head": "0b33a8cca3815c7592277abb6acd6c7ea5ef85a0",
    "old_head": "a210aeebe7ebb66d35c9f51d700e21b41add60de",
    "path": "src/wallet/wallet.cpp",
    "revision": "0b33a8cca3815c7592277abb6acd6c7ea5ef85a0",
    "source_generation": 9,
    "source_job_id": 3138,
    "text": "        }\n\n        wallet->m_max_tx_fee_rate = CFeeRate(*max_tx_fee_rate);\n    }\n\n    if (const auto arg{args.GetArg(\"-consolidatefeerate\")}) {\n        if (std::optional<CAmount> consolidate_feerate = ParseMoney(*arg)) {\n            wallet->m_consolidate_feerate = CFeeRate(*consolidate_feerate);\n        } else {\n            error = AmountErrMsg(\"consolidatefeerate\", *arg);\n            return false;\n        }\n    }\n\n    if (chain && chain->relayMinFee().GetFeePerK() > HIGH_TX_FEE_PER_KB) {\n        warnings.push_back(AmountHighWarn(\"-minrelaytxfee\") + Untranslated(\" \") +\n                           _(\"The wallet will avoid paying less than the minimum relay fee.\"));\n    }\n\n    // m_confirm_target is unsigned, so a negative value would wrap to a huge\n    // target. Fee estimation rejects targets above the maximum it tracks, which\n    // makes every transaction silently fall back to -fallbackfee, so bound the\n    // target by what the estimator can actually serve. A maximum of 0 means no\n    // estimator is running (e.g. -blocksonly), in which case there is no bound\n    // to enforce.\n    if (const auto confirm_target{args.GetIntArg(\"-txconfirmtarget\", DEFAULT_TX_CONFIRM_TARGET)};\n        confirm_target < 1 || confirm_target > std::numeric_limits<unsigned int>::max()) {\n        error = strprintf(_(\"-txconfirmtarget must be between 1 and %u (got %d).\"), std::numeric_limits<unsigned int>::max(), confirm_target);\n        return false;\n    } else if (const unsigned int max_target{chain ? chain->maximumFeeEstimationTargetBlocks() : 0};\n               max_target != 0 && static_cast<unsigned int>(confirm_target) > max_target) {\n        error = strprintf(_(\"-txconfirmtarget must be between 1 and %u (got %d).\"), max_target, confirm_target);\n        return false;\n    } else {\n        wallet->m_confirm_target = static_cast<unsigned int>(confirm_target);\n    }\n\n    wallet->m_spend_zero_conf_change = args.GetBoolArg(\"-spendzeroconfchange\", DEFAULT_SPEND_ZEROCONF_CHANGE);\n    wallet->m_signal_rbf = DEFAULT_WALLET_RBF;\n    if (auto value{args.GetBoolArg(\"-walletrbf\")}) {\n        warnings.push_back(_(\"-walletrbf is deprecated and will be fully removed in the next release.\"));\n        wallet->m_signal_rbf = *value;\n    }\n\n    wallet->m_keypool_size = std::max(args.GetIntArg(\"-keypool\", DEFAULT_KEYPOOL_SIZE), int64_t{1});\n    wallet->m_notify_tx_changed_script = args.GetArg(\"-walletnotify\", \"\");\n    wallet->SetBroadcastTransactions(args.GetBoolArg(\"-walletbroadcast\", DEFAULT_WALLETBROADCAST));\n\n    return true;\n}\n\nstd::shared_ptr<CWallet> CWallet::CreateNew(WalletContext& context, const std::string& name, std::unique_ptr<WalletDatabase> database, uint64_t wallet_creation_flags, bool born_encrypted, bilingual_str& error, std::vector<bilingual_str>& warnings)\n{\n    interfaces::Chain* chain = context.chain;\n    const std::string& walletFile = database->Filename();\n\n    const auto start{SteadyClock::now()};\n    // TODO: Can't use std::make_shared because we need a custom deleter but\n    // should be possible to use std::allocate_shared.\n    std::shared_ptr<CWallet> walletInstance(new CWallet(chain, name, std::move(database)), FlushAndDeleteWallet);\n\n    if (!LoadWalletArgs(walletInstance, context, error, warnings)) {\n        return nullptr;\n    }\n\n    // Initialize version key.\n    {\n        WalletBatch batch(walletInstance->GetDatabase());\n        if(!batch.WriteLastOpenedVersion()) {\n            error = strprintf(_(\"Error creating %s: Could not write version metadata.\"), walletFile);\n            return nullptr;\n        }\n        if(!batch.WriteLastOpenedFeatures()) {\n            error = strprintf(_(\"Error creating %s: Could not write features metadata.\"), walletFile);\n            return nullptr;\n        }\n    }\n    {\n        LOCK(walletInstance->cs_wallet);\n\n        // Init with passed flags.\n        // Always set the cache upgrade flag as this feature is supported from the beginning.\n        walletInstance->InitWalletFlags(wallet_creation_flags | WALLET_FLAG_LAST_HARDENED_XPUB_CACHED);\n\n        // Only descriptor wallets can be created\n        assert(walletInstance->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS));\n\n        // Born encrypted wallets will have their keys generated later\n        if (!born_encrypted) {\n            walletInstance->SetupWalletGeneration();\n        }\n\n        if (chain) {\n            std::optional<int> tip_height = chain->getHeight();\n            if (tip_height) {\n                walletInstance->SetLastBlockProcessed(*tip_height, chain->getBlockHash(*tip_height));\n            }\n        }\n    }\n\n    walletInstance->WalletLogPrintf(\"Wallet completed creation in %15dms\", Ticks<std::chrono::milliseconds>(SteadyClock::now() - start));\n\n    // Try to top up keypool. No-op if the wallet is locked.\n    walletInstance->TopUpKeyPool();\n\n    if (chain && !AttachChain(walletInstance, *chain, /*rescan_required=*/false, error, warnings)) {\n        walletInstance->DisconnectChainNotifications();\n        return nullptr;\n    }\n\n    return walletInstance;\n}\n\nstd::shared_ptr<CWallet> CWallet::LoadExisting(WalletContext& context, const std::string& name, std::unique_ptr<WalletDatabase> database, bilingual_str& error, std::vector<bilingual_str>& warnings)\n{\n    interfaces::Chain* chain = context.chain;\n    const std::string& walletFile = database->Filename();\n\n    const auto start{SteadyClock::now()};\n    std::shared_ptr<CWallet> walletInstance(new CWallet(chain, name, std::move(database)), FlushAndDeleteWallet);\n\n    if (!LoadWalletArgs(walletInstance, context, error, warnings)) {\n        return nullptr;\n    }\n\n    // Load wallet\n    auto nLoadWalletRet = walletInstance->PopulateWalletFromDB(error, warnings);\n    bool rescan_required = nLoadWalletRet == DBErrors::NEED_RESCAN;\n    if (nLoadWalletRet != DBErrors::LOAD_OK && nLoadWalletRet != DBErrors::NONCRITICAL_ERROR && !rescan_required) {\n        return nullptr;\n    }\n\n    if (walletInstance->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {\n        for (auto spk_man : walletInstance->GetActiveScriptPubKeyMans()) {\n            if (spk_man->HavePrivateKeys()) {\n                warnings.push_back(strprintf(_(\"Warning: Private keys detected in wallet {%s} with disabled private keys\"), walletFile));\n                break;\n            }\n        }\n    }\n\n    walletInstance->WalletLogPrintf(\"Wallet completed loading in %15dms\", Ticks<std::chrono::milliseconds>(SteadyClock::now() - start));\n\n    // Try to top up keypool. No-op if the wallet is locked.\n    walletInstance->TopUpKeyPool();\n\n    if (chain && !AttachChain(walletInstance, *chain, rescan_required, error, warnings)) {\n        walletInstance->DisconnectChainNotifications();\n        return nullptr;\n    }",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · a210aeebe7eb..0b33a8cca381

2026-11-26T00:52:07Z · gpt-6-luna

bitcoin#36861The -maxtipage ceiling rejects a regression-tested supported valuesrc/node/chainstatemanager_args.cppstill_present
Assessment

The new-head excerpt still parses `-maxtipage` with `ToIntegral<uint32_t>` and rejects values above `UINT32_MAX`; it does not preserve the reported `INT64_MAX` case.

new_source: src/node/chainstatemanager_args.cpp

[
  {
    "bounded": true,
    "end_line": 101,
    "evidence_id": "55a224f88df74d60be67410baee2d8ee",
    "finding_id": "finding:2",
    "kind": "new_source",
    "line": 33,
    "new_head": "0b33a8cca3815c7592277abb6acd6c7ea5ef85a0",
    "old_head": "a210aeebe7ebb66d35c9f51d700e21b41add60de",
    "path": "src/node/chainstatemanager_args.cpp",
    "revision": "0b33a8cca3815c7592277abb6acd6c7ea5ef85a0",
    "source_generation": 9,
    "source_job_id": 3138,
    "text": "    }\n\n    if (auto value{args.GetArg(\"-minimumchainwork\")}) {\n        if (auto min_work{uint256::FromUserHex(*value)}) {\n            opts.minimum_chain_work = UintToArith256(*min_work);\n        } else {\n            return util::Error{Untranslated(strprintf(\"Invalid minimum work specified (%s), must be up to %d hex digits\", *value, uint256::size() * 2))};\n        }\n    }\n\n    if (auto value{args.GetArg(\"-assumevalid\")}) {\n        if (auto block_hash{uint256::FromUserHex(*value)}) {\n            opts.assumed_valid_block = *block_hash;\n        } else {\n            return util::Error{Untranslated(strprintf(\"Invalid assumevalid block hash specified (%s), must be up to %d hex digits (or 0 to disable)\", *value, uint256::size() * 2))};\n        }\n    }\n\n    if (const auto arg{args.GetArg(\"-maxtipage\")}) {\n        // Parse directly into the widest type the destination can hold. max_tip_age\n        // is a std::chrono::seconds, which the standard only guarantees can represent\n        // 35 bits, so every uint32_t fits (asserted below) and no manual upper bound\n        // is needed. A negative value would put the IBD cutoff in the future, so the\n        // node would never consider its tip recent and would stay in IBD.\n        //\n        // ToIntegral is used rather than GetArg<uint32_t>() because the typed getter\n        // saturates values that fail to parse, and a leading '-' is not valid for an\n        // unsigned type, so \"-maxtipage=-1\" would silently become 0 instead of being\n        // rejected.\n        static_assert(std::numeric_limits<uint32_t>::max() <= std::chrono::seconds::max().count());\n        const auto seconds{ToIntegral<uint32_t>(*arg)};\n        if (!seconds) {\n            return util::Error{Untranslated(strprintf(\"-maxtipage must be between 0 and %u seconds (got %s).\", std::numeric_limits<uint32_t>::max(), *arg))};\n        }\n        opts.max_tip_age = std::chrono::seconds{*seconds};\n    }\n\n    ReadDatabaseArgs(args, opts.coins_db);\n    if (auto result{ReadCoinsViewArgs(args, opts.coins_view)}; !result) return util::Error{util::ErrorString(result)};\n\n    int script_threads = args.GetIntArg(\"-par\", DEFAULT_SCRIPTCHECK_THREADS);\n    if (script_threads <= 0) {\n        // -par=0 means autodetect (number of cores - 1 script threads)\n        // -par=-n means \"leave n cores free\" (number of cores - n - 1 script threads)\n        script_threads += GetNumCores();\n    }\n    // Subtract 1 because the main thread counts towards the par threads.\n    opts.worker_threads_num = script_threads - 1;\n\n    if (auto value{args.GetArg<int32_t>(\"-prevoutfetchthreads\")}) {\n        if (*value < 0) {\n            return util::Error{Untranslated(strprintf(\"-prevoutfetchthreads must be non-negative (got %d). Use 0 to disable parallel input fetching.\", *value))};\n        }\n        opts.prevoutfetch_threads_num = std::min(*value, MAX_PREVOUTFETCH_THREADS);\n    }\n\n    if (auto max_size = args.GetIntArg(\"-maxsigcachesize\")) {\n        // 1. When supplied with a max_size of 0, both the signature cache and\n        //    script execution cache create the minimum possible cache (2\n        //    elements). Therefore, we can use 0 as a floor here.\n        // 2. Multiply first, divide after to avoid integer truncation.\n        size_t clamped_size_each{size_t(std::max<int64_t>(*max_size, 0) * 1_MiB / 2)};\n        opts.script_execution_cache_bytes = clamped_size_each;\n        opts.signature_cache_bytes = clamped_size_each;\n    }\n\n    return {};\n}\n} // namespace node",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · a210aeebe7eb..0b33a8cca381

2026-11-26T00:52:07Z · gpt-6-luna

bitcoin#36861Release notes describe literal-zero limits as disabled or unlimiteddoc/release-notes-36861.mdunclear
Assessment

The follow-up assessment was invalid: unknown follow-up evidence ID.

invalid_assessment

Source report · a210aeebe7eb..0b33a8cca381

2026-11-26T00:52:07Z · gpt-6-luna

bitcoin#36885No advisory identifies a threshold owned by this walletsrc/wallet/rpc/wallet.cpppartially_addressed
Assessment

The RPC help now correctly calls the result a recognized k-of-n rather than a safe k-of-n and clarifies the local-key meaning of `can_sign`. But no wallet-level advisory identifies when `MINE` cosigner slots meet the threshold, and the help still does not explicitly distinguish recognition from proof of cosigner independence or signing capability.

path_diff: src/wallet/rpc/wallet.cpp; new_source: src/wallet/rpc/wallet.cpp

[
  {
    "evidence_id": "659e2f88900b408c98d737c220cea0cc",
    "finding_id": "finding:9",
    "kind": "path_diff",
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/wallet/rpc/wallet.cpp",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "diff --git a/src/wallet/rpc/wallet.cpp b/src/wallet/rpc/wallet.cpp\nindex 0e7fc16d193..151a7f7677a 100644\n--- a/src/wallet/rpc/wallet.cpp\n+++ b/src/wallet/rpc/wallet.cpp\n@@ -1082,8 +1082,9 @@ static RPCMethod analyzedescriptor()\n         \"analyzedescriptor\",\n         \"Analyze any descriptor: which of its keys this wallet holds, whether it can sign, its first address on each path, \"\n         \"and whether it is a recognized multisig setup.\\n\"\n-        \"A cosigner key is the wallet's if it is one of the wallet's HD keys, or if its origin fingerprint is one of theirs and deriving \"\n-        \"the origin path gives the same key. That derivation is usually hardened, so it needs the private key: a locked wallet does not \"\n+        \"A cosigner key is the wallet's if it is one of the wallet's HD keys, or if deriving the rest of its origin path from one of them gives the same key: \"\n+        \"from the HD key with the origin fingerprint, or after the origin the wallet's descriptors give that HD key (e.g. an imported account xprv). \"\n+        \"That derivation is usually hardened, so it needs the private key: a locked wallet does not \"\n         \"return an error, but reports such keys as \\\"unknown\\\".\\n\"\n         \"To analyze a descriptor without a wallet, use getdescriptorinfo with verbose set to true.\\n\",\n         {\n@@ -1093,13 +1094,16 @@ static RPCMethod analyzedescriptor()\n             RPCResult::Type::OBJ, \"\", \"\",\n             {\n                 {RPCResult::Type::ARR, \"keys\", \"The public key occurrences, in descriptor order. \"\n-                    \"Array indices are the key IDs used in this result; equal keys remain separate occurrences.\",\n+                    \"Array indices are the key IDs used in this result; equal keys remain separate occurrences. \"\n+                    \"For a multipath descriptor, the keys describe only the first path, while the analysis checks every path.\\n\"\n+                    \"EXPERIMENTAL warning: the format of the keys and analysis may be changed in future releases.\",\n                 {\n                     {RPCResult::Type::OBJ, \"\", \"\", key_fields},\n                 }},\n                 {RPCResult::Type::OBJ, \"analysis\", HELP_DESCRIPTOR_ANALYSIS, DescriptorAnalysisResultFields()},\n                 {RPCResult::Type::BOOL, \"can_sign\", /*optional=*/true, \"Whether this wallet holds the private key for at least one key. \"\n-                    \"Whether the descriptor is a safe k-of-n is analysis.recognized. Absent if it can't tell because the wallet is locked: see the keys marked \\\"unknown\\\"\"},\n+                    \"Whether the descriptor is a recognized k-of-n is analysis.recognized. Keys held on an external signer don't count, since the wallet doesn't hold their private keys. \"\n+                    \"Absent if it can't tell because the wallet is locked: see the keys marked \\\"unknown\\\"\"},\n                 {RPCResult::Type::ARR, \"first_addresses\", /*optional=*/true, \"The address at index 0 of each path, in path order \"\n                     \"(e.g. receive, then change for /<0;1>/*), which every participant should see. Absent if they can't be derived\",\n                 {\n",
    "truncated": false,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 1221,
    "evidence_id": "1eb9aad5487e46dc98d04a1e3232a52f",
    "finding_id": "finding:9",
    "kind": "new_source",
    "line": 1072,
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/wallet/rpc/wallet.cpp",
    "revision": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "}\n\nstatic RPCMethod analyzedescriptor()\n{\n    std::vector<RPCResult> key_fields{DescriptorKeyResultFields()};\n    key_fields.emplace_back(RPCResult::Type::STR, \"wallet\", \"Whether this wallet holds the key: \\\"mine\\\" (with its private key), \"\n        \"\\\"watch_only\\\" (without its private key), \\\"unknown\\\" (the wallet is locked, and checking needs a private key) or \\\"not_mine\\\". \"\n        \"A musig() aggregate is always \\\"not_mine\\\"; its participants are checked\");\n\n    return RPCMethod{\n        \"analyzedescriptor\",\n        \"Analyze any descriptor: which of its keys this wallet holds, whether it can sign, its first address on each path, \"\n        \"and whether it is a recognized multisig setup.\\n\"\n        \"A cosigner key is the wallet's if it is one of the wallet's HD keys, or if deriving the rest of its origin path from one of them gives the same key: \"\n        \"from the HD key with the origin fingerprint, or after the origin the wallet's descriptors give that HD key (e.g. an imported account xprv). \"\n        \"That derivation is usually hardened, so it needs the private key: a locked wallet does not \"\n        \"return an error, but reports such keys as \\\"unknown\\\".\\n\"\n        \"To analyze a descriptor without a wallet, use getdescriptorinfo with verbose set to true.\\n\",\n        {\n            {\"descriptor\", RPCArg::Type::STR, RPCArg::Optional::NO, \"The descriptor.\"},\n        },\n        RPCResult{\n            RPCResult::Type::OBJ, \"\", \"\",\n            {\n                {RPCResult::Type::ARR, \"keys\", \"The public key occurrences, in descriptor order. \"\n                    \"Array indices are the key IDs used in this result; equal keys remain separate occurrences. \"\n                    \"For a multipath descriptor, the keys describe only the first path, while the analysis checks every path.\\n\"\n                    \"EXPERIMENTAL warning: the format of the keys and analysis may be changed in future releases.\",\n                {\n                    {RPCResult::Type::OBJ, \"\", \"\", key_fields},\n                }},\n                {RPCResult::Type::OBJ, \"analysis\", HELP_DESCRIPTOR_ANALYSIS, DescriptorAnalysisResultFields()},\n                {RPCResult::Type::BOOL, \"can_sign\", /*optional=*/true, \"Whether this wallet holds the private key for at least one key. \"\n                    \"Whether the descriptor is a recognized k-of-n is analysis.recognized. Keys held on an external signer don't count, since the wallet doesn't hold their private keys. \"\n                    \"Absent if it can't tell because the wallet is locked: see the keys marked \\\"unknown\\\"\"},\n                {RPCResult::Type::ARR, \"first_addresses\", /*optional=*/true, \"The address at index 0 of each path, in path order \"\n                    \"(e.g. receive, then change for /<0;1>/*), which every participant should see. Absent if they can't be derived\",\n                {\n                    {RPCResult::Type::STR, \"\", \"The address\"},\n                }},\n            }\n        },\n        RPCExamples{\n            HelpExampleCli(\"analyzedescriptor\", \"\\\"wsh(sortedmulti(2,[d34db33f/48h/0h/0h/2h]xpub.../<0;1>/*,...))\\\"\")\n            + HelpExampleRpc(\"analyzedescriptor\", \"\\\"wsh(sortedmulti(2,[d34db33f/48h/0h/0h/2h]xpub.../<0;1>/*,...))\\\"\")\n        },\n        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue\n        {\n            const std::shared_ptr<const CWallet> wallet = GetWalletForJSONRPCRequest(request);\n            if (!wallet) return UniValue::VNULL;\n\n            FlatSigningProvider provider;\n            std::string error;\n            const auto descs{Parse(self.Arg<std::string_view>(\"descriptor\"), provider, error)};\n            if (descs.empty()) {\n                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);\n            }\n\n            // A locked wallet is not an error: keys it can't check are \"unknown\".\n            const WalletDescriptorAnalysis analysis{AnalyzeDescriptor(*wallet, descs, provider)};\n\n            UniValue keys(UniValue::VARR);\n            const UniValue key_objs{DescriptorKeysToUniv(analysis.analysis.policy.keys)};\n            for (size_t id{0}; id < key_objs.size(); ++id) {\n                UniValue key{key_objs[id]};\n                key.pushKV(\"wallet\", KeyMatchName(analysis.keys.at(id)));\n                keys.push_back(std::move(key));\n            }\n\n            UniValue result(UniValue::VOBJ);\n            result.pushKV(\"keys\", std::move(keys));\n            result.pushKV(\"analysis\", DescriptorAnalysisToUniv(analysis.analysis));\n            if (const auto can_sign{analysis.CanSign()}) result.pushKV(\"can_sign\", *can_sign);\n            if (!analysis.first_addresses.empty()) {\n                UniValue addresses(UniValue::VARR);\n                for (const CTxDestination& dest : analysis.first_addresses) addresses.push_back(EncodeDestination(dest));\n                result.pushKV(\"first_addresses\", std::move(addresses));\n            }\n            return result;\n        },\n    };\n}\n\n// addresses\nRPCMethod getaddressinfo();\nRPCMethod getnewaddress();\nRPCMethod getrawchangeaddress();\nRPCMethod setlabel();\nRPCMethod listaddressgroupings();\nRPCMethod keypoolrefill();\nRPCMethod getaddressesbylabel();\nRPCMethod listlabels();\n#ifdef ENABLE_EXTERNAL_SIGNER\nRPCMethod walletdisplayaddress();\n#endif // ENABLE_EXTERNAL_SIGNER\n\n// backup\nRPCMethod importprunedfunds();\nRPCMethod importdescriptors();\nRPCMethod listdescriptors();\nRPCMethod backupwallet();\nRPCMethod restorewallet();\n\n// coins\nRPCMethod getreceivedbyaddress();\nRPCMethod getreceivedbylabel();\nRPCMethod getbalance();\nRPCMethod lockunspent();\nRPCMethod listlockunspent();\nRPCMethod getbalances();\nRPCMethod listunspent();\n\n// encryption\nRPCMethod walletpassphrase();\nRPCMethod walletpassphrasechange();\nRPCMethod walletlock();\nRPCMethod encryptwallet();\n\n// spend\nRPCMethod sendtoaddress();\nRPCMethod sendmany();\nRPCMethod fundrawtransaction();\nRPCMethod bumpfee();\nRPCMethod psbtbumpfee();\nRPCMethod send();\nRPCMethod sendall();\nRPCMethod walletprocesspsbt();\nRPCMethod walletcreatefundedpsbt();\nRPCMethod signrawtransactionwithwallet();\n\n// signmessage\nRPCMethod signmessage();\n\n// transactions\nRPCMethod listreceivedbyaddress();\nRPCMethod listreceivedbylabel();\nRPCMethod listtransactions();\nRPCMethod listrawtransactions();\nRPCMethod listsinceblock();\nRPCMethod gettransaction();\nRPCMethod abandontransaction();\nRPCMethod rescanblockchain();\nRPCMethod abortrescan();\n\nstd::span<const CRPCCommand> GetWalletRPCCommands()\n{\n    static const CRPCCommand commands[]{\n        {\"rawtransactions\", &fundrawtransaction},\n        {\"wallet\", &abandontransaction},\n        {\"wallet\", &abortrescan},",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 0997b0116b82..386c55a4bfcb

2026-11-26T06:52:03Z · gpt-6-luna

bitcoin#36885Child-xpub detection has an undocumented metadata dependencysrc/rpc/descriptor_util.cppaddressed
Assessment

The shared analysis help now states that direct-child detection depends on the child's parent fingerprint and child number, and explicitly says a child with changed metadata cannot be found.

path_diff: src/rpc/descriptor_util.cpp; new_source: src/rpc/descriptor_util.cpp

[
  {
    "evidence_id": "0559477366e64452ae486e43c32cfec0",
    "finding_id": "finding:8",
    "kind": "path_diff",
    "new_head": "c2d5322d4238be81fcbeb317032e148134f16aad",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/rpc/descriptor_util.cpp",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "diff --git a/src/rpc/descriptor_util.cpp b/src/rpc/descriptor_util.cpp\nindex 33685b7cd0..6ef1542c68 100644\n--- a/src/rpc/descriptor_util.cpp\n+++ b/src/rpc/descriptor_util.cpp\n@@ -26,8 +26,9 @@\n const std::string HELP_DESCRIPTOR_ANALYSIS{\"Whether the descriptor is a recognized k-of-n multisig setup: \"\n     \"one where any threshold of the cosigners can spend, and nothing else can. Recognized shapes are wsh(multi) and wsh(sortedmulti), \"\n     \"and tr(K,multi_a) and tr(K,sortedmulti_a) with a single leaf, where K is the BIP 341 NUMS point H or a musig() of at least threshold distinct cosigners. \"\n-    \"Every cosigner must be an extended key with an unhardened ranged derivation that can derive addresses, and no two cosigners may be found to be the same key: \"\n-    \"the same xpub, the same key at the first address, or an xpub and its unhardened child xpub. Other related keys, like a grandchild xpub, can't be found. \"\n+    \"Every cosigner must be an extended key other than H, with an unhardened ranged derivation that can derive addresses, and no two cosigners may be found to be the same key: \"\n+    \"the same xpub, the same key at the first address, or an xpub and its unhardened child xpub, as named by the child's parent fingerprint and child number. \"\n+    \"Other related keys, like a grandchild xpub or a child with that metadata changed, can't be found. \"\n     \"This looks at the descriptor only: it does not say which keys belong to whom. Each cosigner can check their own key with analyzedescriptor.\"};\n \n std::vector<RPCResult> DescriptorKeyResultFields()\n@@ -72,7 +73,8 @@ std::vector<RPCResult> DescriptorAnalysisResultFields()\n                     \"\\\"not_extended_key\\\" (a cosigner is not an extended key), \"\n                     \"\\\"not_ranged\\\" (a cosigner does not end in an unhardened wildcard), \"\n                     \"\\\"hardened_derivation\\\" (a cosigner or musig() participant needs a private key to derive addresses), \"\n-                    \"\\\"not_derivable\\\" (a cosigner or musig() participant can't derive addresses, e.g. past the maximum BIP32 depth), or \"\n+                    \"\\\"not_derivable\\\" (a cosigner, musig() participant or Taproot internal key can't derive addresses, e.g. past the maximum BIP32 depth), \"\n+                    \"\\\"unspendable_key\\\" (a cosigner is the NUMS point H, which no one can sign for), or \"\n                     \"\\\"branches_differ\\\" (the paths of a multipath descriptor are not the same setup)\"},\n                 {RPCResult::Type::ARR, \"keys\", \"The key IDs involved, if any\",\n                 {\n@@ -188,6 +190,7 @@ static std::string IssueName(DescriptorAnalysis::Issue::Kind kind)\n     case Kind::NOT_RANGED: return \"not_ranged\";\n     case Kind::HARDENED_DERIVATION: return \"hardened_derivation\";\n     case Kind::NOT_DERIVABLE: return \"not_derivable\";\n+    case Kind::UNSPENDABLE_KEY: return \"unspendable_key\";\n     case Kind::BRANCHES_DIFFER: return \"branches_differ\";\n     } // no default case, so the compiler can warn about missing cases\n     NONFATAL_UNREACHABLE();\n",
    "truncated": false,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 150,
    "evidence_id": "cdbaabb5add04502bb94ecafe4ab4e8f",
    "finding_id": "finding:8",
    "kind": "new_source",
    "line": 1,
    "new_head": "c2d5322d4238be81fcbeb317032e148134f16aad",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/rpc/descriptor_util.cpp",
    "revision": "c2d5322d4238be81fcbeb317032e148134f16aad",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "// Copyright (c) 2026-present The Bitcoin Core developers\n// Distributed under the MIT software license, see the accompanying\n// file COPYING or https://opensource.org/license/mit.\n\n#include <rpc/descriptor_util.h>\n\n#include <crypto/hex_base.h>\n#include <key_io.h>\n#include <pubkey.h>\n#include <rpc/util.h>\n#include <script/descriptor_analysis.h>\n#include <script/descriptor_analyzer.h>\n#include <script/keyorigin.h>\n#include <univalue.h>\n#include <util/bip32.h>\n#include <util/check.h>\n#include <util/overloaded.h>\n\n#include <optional>\n#include <span>\n#include <string>\n#include <utility>\n#include <variant>\n#include <vector>\n\nconst std::string HELP_DESCRIPTOR_ANALYSIS{\"Whether the descriptor is a recognized k-of-n multisig setup: \"\n    \"one where any threshold of the cosigners can spend, and nothing else can. Recognized shapes are wsh(multi) and wsh(sortedmulti), \"\n    \"and tr(K,multi_a) and tr(K,sortedmulti_a) with a single leaf, where K is the BIP 341 NUMS point H or a musig() of at least threshold distinct cosigners. \"\n    \"Every cosigner must be an extended key other than H, with an unhardened ranged derivation that can derive addresses, and no two cosigners may be found to be the same key: \"\n    \"the same xpub, the same key at the first address, or an xpub and its unhardened child xpub, as named by the child's parent fingerprint and child number. \"\n    \"Other related keys, like a grandchild xpub or a child with that metadata changed, can't be found. \"\n    \"This looks at the descriptor only: it does not say which keys belong to whom. Each cosigner can check their own key with analyzedescriptor.\"};\n\nstd::vector<RPCResult> DescriptorKeyResultFields()\n{\n    return {\n        {RPCResult::Type::STR, \"role\", \"How the key is used: \\\"ecdsa\\\", \\\"taproot_internal\\\", \\\"taproot_output\\\", \\\"tapscript\\\", \\\"musig_participant\\\" or \\\"unused\\\"\"},\n        {RPCResult::Type::STR, \"type\", \"The kind of key expression: \\\"pubkey\\\", \\\"bip32\\\" or \\\"musig\\\"\"},\n        {RPCResult::Type::STR_HEX, \"pubkey\", /*optional=*/true, \"For a \\\"pubkey\\\": the public key, as 32 bytes if x-only\"},\n        {RPCResult::Type::STR, \"xpub\", /*optional=*/true, \"For a \\\"bip32\\\": the extended public key\"},\n        {RPCResult::Type::ARR, \"participants\", /*optional=*/true, \"For a \\\"musig\\\": the key IDs of its participants, in expression order\",\n        {\n            {RPCResult::Type::NUM, \"\", \"Key ID\"},\n        }},\n        {RPCResult::Type::STR, \"derivation\", /*optional=*/true, \"For a \\\"bip32\\\" or \\\"musig\\\": the derivation applied to it, if any, e.g. \\\"/1/*\\\"\"},\n        {RPCResult::Type::OBJ, \"origin\", /*optional=*/true, \"The key origin, if given\",\n        {\n            {RPCResult::Type::STR_HEX, \"master_fingerprint\", \"The fingerprint of the master key\"},\n            {RPCResult::Type::STR, \"path\", \"The derivation path from the master key\"},\n        }},\n    };\n}\n\nstd::vector<RPCResult> DescriptorAnalysisResultFields()\n{\n    return {\n        {RPCResult::Type::BOOL, \"recognized\", \"Whether the descriptor is a recognized setup. If false, only the issues are returned\"},\n        {RPCResult::Type::STR, \"shape\", /*optional=*/true, \"The setup: \\\"wsh_multi\\\" or \\\"tr_multi_a\\\"\"},\n        {RPCResult::Type::BOOL, \"sorted\", /*optional=*/true, \"Whether the keys are sorted (sortedmulti or sortedmulti_a)\"},\n        {RPCResult::Type::STR, \"key_path\", /*optional=*/true, \"For \\\"tr_multi_a\\\": the Taproot internal key, \\\"nums\\\" (unspendable) or \\\"musig\\\" (an aggregate of cosigners)\"},\n        {RPCResult::Type::NUM, \"threshold\", /*optional=*/true, \"The number of cosigners needed to spend\"},\n        {RPCResult::Type::ARR, \"cosigners\", /*optional=*/true, \"The key IDs of the cosigner slots, in expression order\",\n        {\n            {RPCResult::Type::NUM, \"\", \"Key ID\"},\n        }},\n        {RPCResult::Type::ARR, \"issues\", \"Why the descriptor is not recognized. Empty if it is\",\n        {\n            {RPCResult::Type::OBJ, \"\", \"\",\n            {\n                {RPCResult::Type::STR, \"type\", \"\\\"unsupported_shape\\\" (not a recognized shape), \"\n                    \"\\\"repeated_key\\\" (cosigner slots, or musig() participants, held by the same key), \"\n                    \"\\\"key_path_spendable\\\" (the Taproot internal key may let fewer than threshold cosigners spend), \"\n                    \"\\\"not_extended_key\\\" (a cosigner is not an extended key), \"\n                    \"\\\"not_ranged\\\" (a cosigner does not end in an unhardened wildcard), \"\n                    \"\\\"hardened_derivation\\\" (a cosigner or musig() participant needs a private key to derive addresses), \"\n                    \"\\\"not_derivable\\\" (a cosigner, musig() participant or Taproot internal key can't derive addresses, e.g. past the maximum BIP32 depth), \"\n                    \"\\\"unspendable_key\\\" (a cosigner is the NUMS point H, which no one can sign for), or \"\n                    \"\\\"branches_differ\\\" (the paths of a multipath descriptor are not the same setup)\"},\n                {RPCResult::Type::ARR, \"keys\", \"The key IDs involved, if any\",\n                {\n                    {RPCResult::Type::NUM, \"\", \"Key ID\"},\n                }},\n            }},\n        }},\n    };\n}\n\nstatic std::string KeyRoleName(DescriptorKeyInventory::Role role)\n{\n    using Role = DescriptorKeyInventory::Role;\n    switch (role) {\n    case Role::ECDSA: return \"ecdsa\";\n    case Role::TAPROOT_INTERNAL: return \"taproot_internal\";\n    case Role::TAPROOT_OUTPUT: return \"taproot_output\";\n    case Role::TAPSCRIPT: return \"tapscript\";\n    case Role::MUSIG_PARTICIPANT: return \"musig_participant\";\n    case Role::UNUSED: return \"unused\";\n    } // no default case, so the compiler can warn about missing cases\n    NONFATAL_UNREACHABLE();\n}\n\n//! Format a derivation in descriptor syntax, e.g. \"/1/*\". Empty if there is none.\nstatic std::string FormatDerivation(const DescriptorKeyInfo::Derivation& derivation)\n{\n    std::string result{FormatHDKeypath(derivation.path)};\n    switch (derivation.type) {\n    case DescriptorKeyInfo::DeriveType::NON_RANGED: return result;\n    case DescriptorKeyInfo::DeriveType::UNHARDENED_RANGED: return result + \"/*\";\n    case DescriptorKeyInfo::DeriveType::HARDENED_RANGED: return result + \"/*h\";\n    } // no default case, so the compiler can warn about missing cases\n    NONFATAL_UNREACHABLE();\n}\n\nUniValue IdsToUniv(const std::vector<size_t>& ids)\n{\n    UniValue result(UniValue::VARR);\n    for (const size_t id : ids) {\n        result.push_back(id);\n    }\n    return result;\n}\n\nUniValue DescriptorKeysToUniv(const DescriptorKeyInventory& inventory)\n{\n    UniValue keys(UniValue::VARR);\n    for (const auto& occurrence : inventory.occurrences) {\n        UniValue key(UniValue::VOBJ);\n        key.pushKV(\"role\", KeyRoleName(occurrence.role));\n        std::string derivation;\n        std::visit(util::Overloaded{\n            [&](const DescriptorKeyInfo::ConstKey& constant) {\n                key.pushKV(\"type\", \"pubkey\");\n                key.pushKV(\"pubkey\", constant.xonly ? HexStr(XOnlyPubKey{constant.pubkey}) : HexStr(constant.pubkey));\n            },\n            [&](const DescriptorKeyInfo::BIP32Key& bip32) {\n                key.pushKV(\"type\", \"bip32\");\n                key.pushKV(\"xpub\", EncodeExtPubKey(bip32.root));\n                derivation = FormatDerivation(bip32.derivation);\n            },\n            [&](const DescriptorKeyInfo::MuSigKey& musig) {\n                key.pushKV(\"type\", \"musig\");\n                key.pushKV(\"participants\", IdsToUniv(musig.participants));\n                derivation = FormatDerivation(musig.derivation);\n            },\n        }, occurrence.expression.key);\n        if (!derivation.empty()) {\n            key.pushKV(\"derivation\", derivation);\n        }\n        if (const auto& origin{occurrence.expression.origin}) {\n            UniValue origin_obj(UniValue::VOBJ);",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 0997b0116b82..c2d5322d4238

2026-11-26T04:13:37Z · gpt-6-luna

bitcoin#36885analyzedescriptor omits the shared format's caveatssrc/wallet/rpc/wallet.cppaddressed
Assessment

The wallet RPC help now says that multipath keys describe only the first path while analysis checks every path, and marks the keys and analysis format EXPERIMENTAL.

path_diff: src/wallet/rpc/wallet.cpp; new_source: src/wallet/rpc/wallet.cpp

[
  {
    "evidence_id": "1ebe0de029e84cf89e3429b2947797e0",
    "finding_id": "finding:7",
    "kind": "path_diff",
    "new_head": "c2d5322d4238be81fcbeb317032e148134f16aad",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/wallet/rpc/wallet.cpp",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "diff --git a/src/wallet/rpc/wallet.cpp b/src/wallet/rpc/wallet.cpp\nindex 0e7fc16d19..01b4073523 100644\n--- a/src/wallet/rpc/wallet.cpp\n+++ b/src/wallet/rpc/wallet.cpp\n@@ -1082,8 +1082,9 @@ static RPCMethod analyzedescriptor()\n         \"analyzedescriptor\",\n         \"Analyze any descriptor: which of its keys this wallet holds, whether it can sign, its first address on each path, \"\n         \"and whether it is a recognized multisig setup.\\n\"\n-        \"A cosigner key is the wallet's if it is one of the wallet's HD keys, or if its origin fingerprint is one of theirs and deriving \"\n-        \"the origin path gives the same key. That derivation is usually hardened, so it needs the private key: a locked wallet does not \"\n+        \"A cosigner key is the wallet's if it is one of the wallet's HD keys, or if deriving the rest of its origin path from one of them gives the same key: \"\n+        \"from the HD key with the origin fingerprint, or after the origin the wallet's descriptors give that HD key (e.g. an imported account xprv). \"\n+        \"That derivation is usually hardened, so it needs the private key: a locked wallet does not \"\n         \"return an error, but reports such keys as \\\"unknown\\\".\\n\"\n         \"To analyze a descriptor without a wallet, use getdescriptorinfo with verbose set to true.\\n\",\n         {\n@@ -1093,7 +1094,9 @@ static RPCMethod analyzedescriptor()\n             RPCResult::Type::OBJ, \"\", \"\",\n             {\n                 {RPCResult::Type::ARR, \"keys\", \"The public key occurrences, in descriptor order. \"\n-                    \"Array indices are the key IDs used in this result; equal keys remain separate occurrences.\",\n+                    \"Array indices are the key IDs used in this result; equal keys remain separate occurrences. \"\n+                    \"For a multipath descriptor, the keys describe only the first path, while the analysis checks every path.\\n\"\n+                    \"EXPERIMENTAL warning: the format of the keys and analysis may be changed in future releases.\",\n                 {\n                     {RPCResult::Type::OBJ, \"\", \"\", key_fields},\n                 }},\n",
    "truncated": false,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 1214,
    "evidence_id": "469e7985683042c899dd10b734ff7f60",
    "finding_id": "finding:7",
    "kind": "new_source",
    "line": 1065,
    "new_head": "c2d5322d4238be81fcbeb317032e148134f16aad",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/wallet/rpc/wallet.cpp",
    "revision": "c2d5322d4238be81fcbeb317032e148134f16aad",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "    switch (match) {\n    case KeyMatch::NOT_MINE: return \"not_mine\";\n    case KeyMatch::MINE: return \"mine\";\n    case KeyMatch::WATCH_ONLY: return \"watch_only\";\n    case KeyMatch::UNKNOWN: return \"unknown\";\n    } // no default case, so the compiler can warn about missing cases\n    NONFATAL_UNREACHABLE();\n}\n\nstatic RPCMethod analyzedescriptor()\n{\n    std::vector<RPCResult> key_fields{DescriptorKeyResultFields()};\n    key_fields.emplace_back(RPCResult::Type::STR, \"wallet\", \"Whether this wallet holds the key: \\\"mine\\\" (with its private key), \"\n        \"\\\"watch_only\\\" (without its private key), \\\"unknown\\\" (the wallet is locked, and checking needs a private key) or \\\"not_mine\\\". \"\n        \"A musig() aggregate is always \\\"not_mine\\\"; its participants are checked\");\n\n    return RPCMethod{\n        \"analyzedescriptor\",\n        \"Analyze any descriptor: which of its keys this wallet holds, whether it can sign, its first address on each path, \"\n        \"and whether it is a recognized multisig setup.\\n\"\n        \"A cosigner key is the wallet's if it is one of the wallet's HD keys, or if deriving the rest of its origin path from one of them gives the same key: \"\n        \"from the HD key with the origin fingerprint, or after the origin the wallet's descriptors give that HD key (e.g. an imported account xprv). \"\n        \"That derivation is usually hardened, so it needs the private key: a locked wallet does not \"\n        \"return an error, but reports such keys as \\\"unknown\\\".\\n\"\n        \"To analyze a descriptor without a wallet, use getdescriptorinfo with verbose set to true.\\n\",\n        {\n            {\"descriptor\", RPCArg::Type::STR, RPCArg::Optional::NO, \"The descriptor.\"},\n        },\n        RPCResult{\n            RPCResult::Type::OBJ, \"\", \"\",\n            {\n                {RPCResult::Type::ARR, \"keys\", \"The public key occurrences, in descriptor order. \"\n                    \"Array indices are the key IDs used in this result; equal keys remain separate occurrences. \"\n                    \"For a multipath descriptor, the keys describe only the first path, while the analysis checks every path.\\n\"\n                    \"EXPERIMENTAL warning: the format of the keys and analysis may be changed in future releases.\",\n                {\n                    {RPCResult::Type::OBJ, \"\", \"\", key_fields},\n                }},\n                {RPCResult::Type::OBJ, \"analysis\", HELP_DESCRIPTOR_ANALYSIS, DescriptorAnalysisResultFields()},\n                {RPCResult::Type::BOOL, \"can_sign\", /*optional=*/true, \"Whether this wallet holds the private key for at least one key. \"\n                    \"Whether the descriptor is a safe k-of-n is analysis.recognized. Absent if it can't tell because the wallet is locked: see the keys marked \\\"unknown\\\"\"},\n                {RPCResult::Type::ARR, \"first_addresses\", /*optional=*/true, \"The address at index 0 of each path, in path order \"\n                    \"(e.g. receive, then change for /<0;1>/*), which every participant should see. Absent if they can't be derived\",\n                {\n                    {RPCResult::Type::STR, \"\", \"The address\"},\n                }},\n            }\n        },\n        RPCExamples{\n            HelpExampleCli(\"analyzedescriptor\", \"\\\"wsh(sortedmulti(2,[d34db33f/48h/0h/0h/2h]xpub.../<0;1>/*,...))\\\"\")\n            + HelpExampleRpc(\"analyzedescriptor\", \"\\\"wsh(sortedmulti(2,[d34db33f/48h/0h/0h/2h]xpub.../<0;1>/*,...))\\\"\")\n        },\n        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue\n        {\n            const std::shared_ptr<const CWallet> wallet = GetWalletForJSONRPCRequest(request);\n            if (!wallet) return UniValue::VNULL;\n\n            FlatSigningProvider provider;\n            std::string error;\n            const auto descs{Parse(self.Arg<std::string_view>(\"descriptor\"), provider, error)};\n            if (descs.empty()) {\n                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);\n            }\n\n            // A locked wallet is not an error: keys it can't check are \"unknown\".\n            const WalletDescriptorAnalysis analysis{AnalyzeDescriptor(*wallet, descs, provider)};\n\n            UniValue keys(UniValue::VARR);\n            const UniValue key_objs{DescriptorKeysToUniv(analysis.analysis.policy.keys)};\n            for (size_t id{0}; id < key_objs.size(); ++id) {\n                UniValue key{key_objs[id]};\n                key.pushKV(\"wallet\", KeyMatchName(analysis.keys.at(id)));\n                keys.push_back(std::move(key));\n            }\n\n            UniValue result(UniValue::VOBJ);\n            result.pushKV(\"keys\", std::move(keys));\n            result.pushKV(\"analysis\", DescriptorAnalysisToUniv(analysis.analysis));\n            if (const auto can_sign{analysis.CanSign()}) result.pushKV(\"can_sign\", *can_sign);\n            if (!analysis.first_addresses.empty()) {\n                UniValue addresses(UniValue::VARR);\n                for (const CTxDestination& dest : analysis.first_addresses) addresses.push_back(EncodeDestination(dest));\n                result.pushKV(\"first_addresses\", std::move(addresses));\n            }\n            return result;\n        },\n    };\n}\n\n// addresses\nRPCMethod getaddressinfo();\nRPCMethod getnewaddress();\nRPCMethod getrawchangeaddress();\nRPCMethod setlabel();\nRPCMethod listaddressgroupings();\nRPCMethod keypoolrefill();\nRPCMethod getaddressesbylabel();\nRPCMethod listlabels();\n#ifdef ENABLE_EXTERNAL_SIGNER\nRPCMethod walletdisplayaddress();\n#endif // ENABLE_EXTERNAL_SIGNER\n\n// backup\nRPCMethod importprunedfunds();\nRPCMethod importdescriptors();\nRPCMethod listdescriptors();\nRPCMethod backupwallet();\nRPCMethod restorewallet();\n\n// coins\nRPCMethod getreceivedbyaddress();\nRPCMethod getreceivedbylabel();\nRPCMethod getbalance();\nRPCMethod lockunspent();\nRPCMethod listlockunspent();\nRPCMethod getbalances();\nRPCMethod listunspent();\n\n// encryption\nRPCMethod walletpassphrase();\nRPCMethod walletpassphrasechange();\nRPCMethod walletlock();\nRPCMethod encryptwallet();\n\n// spend\nRPCMethod sendtoaddress();\nRPCMethod sendmany();\nRPCMethod fundrawtransaction();\nRPCMethod bumpfee();\nRPCMethod psbtbumpfee();\nRPCMethod send();\nRPCMethod sendall();\nRPCMethod walletprocesspsbt();\nRPCMethod walletcreatefundedpsbt();\nRPCMethod signrawtransactionwithwallet();\n\n// signmessage\nRPCMethod signmessage();\n\n// transactions\nRPCMethod listreceivedbyaddress();\nRPCMethod listreceivedbylabel();\nRPCMethod listtransactions();\nRPCMethod listrawtransactions();\nRPCMethod listsinceblock();\nRPCMethod gettransaction();\nRPCMethod abandontransaction();\nRPCMethod rescanblockchain();\nRPCMethod abortrescan();\n",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 0997b0116b82..c2d5322d4238

2026-11-26T04:13:37Z · gpt-6-luna

bitcoin#36885Later multipath branches lose their issue detailssrc/script/descriptor_analyzer.cppaddressed
Assessment

The multipath overload now accumulates issues from every branch, deduplicates them, tracks setup differences separately, and adds branches_differ when appropriate. Tests exercise reversed branch order and distinct issues across branches.

new_source: src/script/descriptor_analyzer.cpp; path_diff: src/script/descriptor_analyzer.cpp

[
  {
    "bounded": true,
    "end_line": 401,
    "evidence_id": "c42c69c1d9b343058f3b0e45e51502ee",
    "finding_id": "finding:6",
    "kind": "new_source",
    "line": 299,
    "new_head": "cc57e7ad8a31d4a8ca4cd1ddcaa2c5dda6a95aaa",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/script/descriptor_analyzer.cpp",
    "revision": "cc57e7ad8a31d4a8ca4cd1ddcaa2c5dda6a95aaa",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "    return std::nullopt;\n}\n\n/** Mark the result unrecognized and drop the setup it would have claimed. */\nvoid Unrecognize(DescriptorAnalysis& result)\n{\n    result.shape = DescriptorAnalysis::Shape::UNRECOGNIZED;\n    result.sorted = false;\n    result.key_path = DescriptorAnalysis::KeyPath::NONE;\n    result.threshold = 0;\n    result.cosigners.clear();\n}\n\n/** Find the multisig node of a recognized shape, or nullptr. */\nconst DescriptorPolicy::Node* FindMultisig(DescriptorAnalysis& result)\n{\n    const auto& nodes{result.policy.nodes};\n    if (nodes.empty()) return nullptr;\n    const auto* root_kind{NodeKind(nodes[0])};\n    if (!root_kind || nodes[0].children.size() != 1) return nullptr;\n    const auto& child{nodes[0].children[0]};\n    const auto& multisig{nodes.at(child.node)};\n    const auto* kind{NodeKind(multisig)};\n    if (!kind || !multisig.children.empty()) return nullptr;\n\n    if (*root_kind == Kind::WSH && (*kind == Kind::MULTI || *kind == Kind::SORTEDMULTI)) {\n        result.shape = DescriptorAnalysis::Shape::WSH_MULTI;\n        result.sorted = *kind == Kind::SORTEDMULTI;\n        return &multisig;\n    }\n    if (*root_kind == Kind::TR && (*kind == Kind::MULTI_A || *kind == Kind::SORTEDMULTI_A)) {\n        const auto* leaf{std::get_if<DescriptorPolicy::TapLeaf>(&child.role)};\n        if (!leaf || leaf->depth != 0 || nodes[0].keys.size() != 1) return nullptr;\n        result.shape = DescriptorAnalysis::Shape::TR_MULTI_A;\n        result.sorted = *kind == Kind::SORTEDMULTI_A;\n        return &multisig;\n    }\n    return nullptr;\n}\n\n} // namespace\n\nDescriptorAnalysis AnalyzeDescriptor(const Descriptor& descriptor)\n{\n    DescriptorAnalysis result;\n    result.policy = descriptor.GetPolicy();\n\n    const auto* multisig{FindMultisig(result)};\n    if (!multisig) {\n        result.issues.push_back({IssueKind::UNSUPPORTED_SHAPE, {}});\n        return result;\n    }\n    result.threshold = multisig->value;\n    result.cosigners = multisig->keys;\n\n    CheckCosignerKeys(result);\n    CheckRepeatedKeys(result);\n    if (result.shape == DescriptorAnalysis::Shape::TR_MULTI_A) {\n        const size_t internal_id{result.policy.nodes[0].keys[0]};\n        CheckMuSigParticipants(result, internal_id);\n        if (const auto key_path{ClassifyKeyPath(result, internal_id)}) {\n            result.key_path = *key_path;\n            if (!CanDeriveInternalKey(result.policy.keys.occurrences.at(internal_id).expression)) {\n                result.issues.push_back({IssueKind::NOT_DERIVABLE, {internal_id}});\n            }\n        } else {\n            result.issues.push_back({IssueKind::KEY_PATH_SPENDABLE, {internal_id}});\n        }\n    }\n\n    // Checked last: the checks above need the cosigners.\n    if (!result.issues.empty()) Unrecognize(result);\n    return result;\n}\n\nDescriptorAnalysis AnalyzeDescriptor(std::span<const std::unique_ptr<Descriptor>> descriptors)\n{\n    Assume(!descriptors.empty());\n    if (descriptors.empty()) return {};\n    DescriptorAnalysis first{AnalyzeDescriptor(*descriptors.front())};\n\n    const auto cosigner_roots = [](const DescriptorAnalysis& analysis) {\n        std::vector<std::optional<XOnlyPubKey>> roots;\n        roots.reserve(analysis.cosigners.size());\n        for (const size_t id : analysis.cosigners) roots.push_back(RootKey(analysis.policy.keys.occurrences.at(id).expression));\n        return roots;\n    };\n    // The branches share their key IDs, so each issue is reported once,\n    // whichever branch it comes from.\n    std::set<DescriptorAnalysis::Issue> seen(first.issues.begin(), first.issues.end());\n    bool differ{false};\n    for (const auto& descriptor : descriptors.subspan(1)) {\n        const DescriptorAnalysis other{AnalyzeDescriptor(*descriptor)};\n        differ |= other.shape != first.shape || other.sorted != first.sorted || other.key_path != first.key_path ||\n                  other.threshold != first.threshold || cosigner_roots(other) != cosigner_roots(first);\n        for (const auto& issue : other.issues) {\n            if (seen.insert(issue).second) first.issues.push_back(issue);\n        }\n    }\n    if (differ) first.issues.push_back({IssueKind::BRANCHES_DIFFER, {}});\n    if (!first.issues.empty()) Unrecognize(first);\n    return first;\n}",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  },
  {
    "evidence_id": "b24754cfeed04d0ead6ed53cd6e847b9",
    "finding_id": "finding:6",
    "kind": "path_diff",
    "new_head": "cc57e7ad8a31d4a8ca4cd1ddcaa2c5dda6a95aaa",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/script/descriptor_analyzer.cpp",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "diff --git a/src/script/descriptor_analyzer.cpp b/src/script/descriptor_analyzer.cpp\nindex 7958f6792c..7610169e02 100644\n--- a/src/script/descriptor_analyzer.cpp\n+++ b/src/script/descriptor_analyzer.cpp\n@@ -13,9 +13,11 @@\n #include <algorithm>\n #include <array>\n #include <cstddef>\n+#include <limits>\n+#include <map>\n #include <numeric>\n #include <optional>\n-#include <ranges>\n+#include <set>\n #include <utility>\n #include <variant>\n #include <vector>\n@@ -82,13 +84,16 @@ std::optional<XOnlyPubKey> DeriveFirstKey(const DescriptorKeyInfo::BIP32Key& key\n     return XOnlyPubKey{derived.pubkey};\n }\n \n-/** Check that every cosigner slot can derive addresses on its own. */\n+/** Check that every cosigner slot can derive addresses on its own, and that\n+ *  someone can sign for it. */\n void CheckCosignerKeys(DescriptorAnalysis& result)\n {\n     for (const size_t id : result.cosigners) {\n         const auto& node{result.policy.keys.occurrences.at(id).expression};\n         const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)};\n-        if (!key) {\n+        if (RootKey(node) == XOnlyPubKey::NUMS_H) {\n+            result.issues.push_back({IssueKind::UNSPENDABLE_KEY, {id}});\n+        } else if (!key) {\n             result.issues.push_back({IssueKind::NOT_EXTENDED_KEY, {id}});\n         } else if (NeedsPrivateDerivation(*key)) {\n             result.issues.push_back({IssueKind::HARDENED_DERIVATION, {id}});\n@@ -109,29 +114,65 @@ std::optional<XOnlyPubKey> FirstDerivedKey(const DescriptorKeyInfo::Node& node)\n     return DeriveFirstKey(*key);\n }\n \n-/** Group the indices below `count` that `linked` connects, directly or through\n- *  a chain of links. Each group is in index order, listed by its first index. */\n-template <typename Linked>\n-std::vector<std::vector<size_t>> LinkedGroups(size_t count, Linked linked)\n+/** Indices below a count, grouped by links: two indices are in one group if\n+ *  a chain of links connects them. */\n+class LinkedGroups\n {\n-    // Each index points to an earlier index of its group, the first one pointing to itself.\n-    std::vector<size_t> parent(count);\n-    std::iota(parent.begin(), parent.end(), size_t{0});\n-    const auto first_of = [&](size_t i) {\n-        while (parent[i] != i) i = parent[i];\n+    //! Each index points to an earlier index of its group, the first one pointing to itself.\n+    std::vector<size_t> m_parent;\n+\n+public:\n+    explicit LinkedGroups(size_t count) : m_parent(count)\n+    {\n+        std::iota(m_parent.begin(), m_parent.end(), size_t{0});\n+    }\n+\n+    //! The first index of `i`'s group.\n+    size_t First(size_t i)\n+    {\n+        // Point each index visited to its grandparent, keeping later searches short.\n+        while (m_parent[i] != i) i = m_parent[i] = m_parent[m_parent[i]];\n         return i;\n-    };\n-    for (size_t i{0}; i < count; ++i) {\n-        for (size_t j{i + 1}; j < count; ++j) {\n-            if (!linked(i, j)) continue;\n-            const size_t a{first_of(i)}, b{first_of(j)};\n-            parent[std::max(a, b)] = std::min(a, b);\n+    }\n+\n+    void Link(size_t i, size_t j)\n+    {\n+        const size_t a{First(i)}, b{First(j)};\n+        m_parent[std::max(a, b)] = std::min(a, b);\n+    }\n+\n+    //! Link the indices with equal values. A missing value links nothing.\n+    template <typename T>\n+    void LinkEqual(const std::vector<std::optional<T>>& values)\n+    {\n+        std::map<T, size_t> first;\n+        for (size_t i{0}; i < values.size(); ++i) {\n+            if (!values[i]) continue;\n+            const auto [it, inserted]{first.try_emplace(*values[i], i)};\n+            if (!inserted) Link(it->second, i);\n         }\n     }\n-    std::vector<std::vector<size_t>> groups(count);\n-    for (size_t i{0}; i < count; ++i) groups[first_of(i)].push_back(i);\n-    std::erase_if(groups, [](const auto& group) { return group.empty(); });\n-    return groups;\n+\n+    //! Groups of at least two indices, each in index order, listed by its first index.\n+    std::vector<std::vector<size_t>> Repeated()\n+    {\n+        std::vector<std::vector<size_t>> groups(m_parent.size());\n+        for (size_t i{0}; i < m_parent.size(); ++i) groups[First(i)].push_back(i);\n+        std::erase_if(groups, [](const auto& group) { return group.size() < 2; });\n+        return groups;\n+    }\n+};\n+\n+/** Report each group of `groups` as one REPEATED_KEY issue, with the occurrence\n+ *  IDs `ids` gives for its indices. */\n+void ReportRepeated(DescriptorAnalysis& result, LinkedGroups& groups, const std::vector<size_t>& ids)\n+{\n+    for (const auto& group : groups.Repeated()) {\n+        std::vector<size_t> keys;\n+        keys.reserve(group.size());\n+        for (const size_t i : group) keys.push_back(ids[i]);\n+        result.issues.push_back({IssueKind::REPEATED_KEY, std::move(keys)});\n+    }\n }\n \n /** Report every group of cosigner slots held by the same key: slots that share\n@@ -153,17 +194,28 @@ void CheckRepeatedKeys(DescriptorAnalysis& result)\n         derived.push_back(FirstDerivedKey(node));\n         ext_roots.push_back(RootExtKey(node));\n     }\n-    const auto same_holder = [&](size_t i, size_t j) {\n-        if ((roots[i] && roots[i] == roots[j]) || (derived[i] && derived[i] == derived[j])) return true;\n-        return ext_roots[i] && ext_roots[j] && (IsDirectChild(*ext_roots[i], *ext_roots[j]) || IsDirectChild(*ext_roots[j], *ext_roots[i]));\n-    };\n-    for (const auto& group : LinkedGroups(count, same_holder)) {\n-        if (group.size() < 2) continue;\n-        std::vector<size_t> ids;\n-        ids.reserve(group.size());\n-        for (const size_t i : group) ids.push_back(result.cosigners[i]);\n-        result.issues.push_back({IssueKind::REPEATED_KEY, std::move(ids)});\n+    LinkedGroups groups{count};\n+    groups.LinkEqual(roots);\n+    groups.LinkEqual(derived);\n+\n+    // Only an xpub whose fingerprint a child names can be its parent, so a\n+    // child is derived again only from those, and not when the two slots are\n+    // already in one group (e.g. xpubs sharing a root key).\n+    std::multimap<KeyFingerprint, size_t> by_fingerprint;\n+    for (size_t i{0}; i < count; ++i) {\n+        if (ext_roots[i]) by_fingerprint.emplace(ext_roots[i]->id_key_fingerprint(), i);\n     }\n+    for (size_t child{0}; child < count; ++child) {\n+        if (!ext_roots[child]) continue;\n+        const auto [begin, end]{by_fingerprint.equal_range(ext_roots[child]->fingerprint)};\n+        for (auto it{begin}; it != end; ++it) {\n+            const size_t parent{it->second};\n+            if (groups.First(parent) != groups.First(child) && IsDirectChild(*ext_roots[parent], *ext_roots[child])) {\n+                groups.Link(parent, child);\n+            }\n+        }\n+    }\n+    ReportRepeated(result, groups, result.cosigners);\n }\n \n /** Check that every cosigner can derive each participant of a musig()\n@@ -192,16 +244,23 @@ void CheckMuSigParticipants(DescriptorAnalysis& result, size_t internal_id)\n             result.issues.push_back({IssueKind::NOT_DERIVABLE, {id}});\n         }\n     }\n-    const auto same_key = [&](size_t i, size_t j) {\n-        return (roots[i] && roots[i] == roots[j]) || (derived[i] && derived[i] == derived[j]);\n-    };\n-    for (const auto& group : LinkedGroups(participants.size(), same_key)) {\n-        if (group.size() < 2) continue;\n-        std::vector<size_t> ids;\n-        ids.reserve(group.size());\n-        for (const size_t i : group) ids.push_back(participants[i]);\n-        result.issues.push_back({IssueKind::REPEATED_KEY, std::move(ids)});\n+    LinkedGroups groups{participants.size()};\n+    groups.LinkEqual(roots);\n+    groups.LinkEqual(derived);\n+    ReportRepeated(result, groups, participants);\n+}\n+\n+/** Whether a NUMS or musig() internal key can derive its first key. Deriving\n+ *  fails past the maximum BIP32 depth, and a musig() aggregate starts as an\n+ *  xpub at depth 0. */\n+bool CanDeriveInternalKey(const DescriptorKeyInfo::Node& node)\n+{\n+    if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) return DeriveFirstKey(*key).has_value();\n+    if (const auto* key{std::get_if<DescriptorKeyInfo::MuSigKey>(&node.key)}) {\n+        const bool ranged{key->derivation.type == DescriptorKeyInfo::DeriveType::UNHARDENED_RANGED};\n+        return key->derivation.path.size() + (ranged ? 1 : 0) <= std::numeric_limits<unsigned char>::max();\n     }\n+    return true;\n }\n \n /** Classify the Taproot internal key against the cosigners of the leaf, or\n@@ -224,16 +283,16 @@ std::optional<DescriptorAnalysis::KeyPath> ClassifyKeyPath(const DescriptorAnaly\n     if (const auto* key{std::get_if<DescriptorKeyInfo::MuSigKey>(&internal.key)}) {\n         // Any `threshold` cosigners can already spend through the leaf, so an\n         // aggregate of at least that many distinct cosigners adds no new way to spend.\n-        std::vector<XOnlyPubKey> cosigner_roots;\n+        std::set<XOnlyPubKey> cosigner_roots;\n         for (const size_t id : result.cosigners) {\n-            if (const auto root{RootKey(occurrences.at(id).expression)}) cosigner_roots.push_back(*root);\n+            if (const auto root{RootKey(occurrences.at(id).expression)}) cosigner_roots.insert(*root);\n         }\n-        std::vector<XOnlyPubKey> participants;\n+        // A repeated participant adds no cosigner.\n+        std::set<XOnlyPubKey> participants;\n         for (const size_t id : key->participants) {\n             const auto root{RootKey(occurrences.at(id).expression)};\n-            if (!root || std::ranges::find(cosigner_roots, *root) == cosigner_roots.end()) return std::nullopt;\n-            // A repeated participant adds no cosigner.\n-            if (std::ranges::find(participants, *root) == participants.end()) participants.push_back(*root);\n+            if (!root || !cosigner_roots.contains(*root)) return std::nullopt;\n+            participants.insert(*root);\n         }\n         if (participants.size() >= result.threshold) return DescriptorAnalysis::KeyPath::MUSIG;\n     }\n@@ -299,6 +358,9 @@ DescriptorAnalysis AnalyzeDescriptor(const Descriptor& descriptor)\n         CheckMuSigParticipants(result, internal_id);\n         if (const auto key_path{ClassifyKeyPath(result, internal_id)}) {\n             result.key_path = *key_path;\n+            if (!CanDeriveInternalKey(result.policy.keys.occurrences.at(internal_id).expression)) {\n+                result.issues.push_back({IssueKind::NOT_DERIVABLE, {internal_id}});\n+            }\n         } else {\n             result.issues.push_back({IssueKind::KEY_PATH_SPENDABLE, {internal_id}});\n         }\n@@ -321,14 +383,19 @@ DescriptorAnalysis AnalyzeDescriptor(std::span<const std::unique_ptr<Descriptor>\n         for (const size_t id : analysis.cosigners) roots.push_back(RootKey(analysis.policy.keys.occurrences.at(id).expression));\n         return roots;\n     };\n+    // The branches share their key IDs, so each issue is reported once,\n+    // whichever branch it comes from.\n+    std::set<DescriptorAnalysis::Issue> seen(first.issues.begin(), first.issues.end());\n+    bool differ{false};\n     for (const auto& descriptor : descriptors.subspan(1)) {\n         const DescriptorAnalysis other{AnalyzeDescriptor(*descriptor)};\n-        if (other.shape != first.shape || other.sorted != first.sorted || other.key_path != first.key_path ||\n-            other.threshold != first.threshold || cosigner_roots(other) != cosigner_roots(first)) {\n-            Unrecognize(first);\n-            first.issues.push_back({DescriptorAnalysis::Issue::Kind::BRANCHES_DIFFER, {}});\n-            break;\n+        differ |= other.shape != first.shape || other.sorted != first.sorted || other.key_path != first.key_path ||\n+                  other.threshold != first.threshold || cosigner_roots(other) != cosigner_roots(first);\n+        for (const auto& issue : other.issues) {\n+            if (seen.insert(issue).second) first.issues.push_back(issue);\n         }\n     }\n+    if (differ) first.issues.push_back({IssueKind::BRANCHES_DIFFER, {}});\n+    if (!first.issues.empty()) Unrecognize(first);\n     return first;\n }\n",
    "truncated": false,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 0997b0116b82..cc57e7ad8a31

2026-11-26T00:19:56Z · gpt-6-luna

bitcoin#36885combo() loses its derivable first addresssrc/wallet/descriptor_analyzer.cppaddressed
Assessment

FirstAddress now scans expanded scripts and returns the first one for which ExtractDestination succeeds, rather than stopping at the addressless first script. The added comment specifically identifies combo()'s P2PK output.

path_diff: src/wallet/descriptor_analyzer.cpp; new_source: src/wallet/descriptor_analyzer.cpp

[
  {
    "evidence_id": "2996c3ac8636450eb76f553dcbab2f82",
    "finding_id": "finding:5",
    "kind": "path_diff",
    "new_head": "c2d5322d4238be81fcbeb317032e148134f16aad",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/wallet/descriptor_analyzer.cpp",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "diff --git a/src/wallet/descriptor_analyzer.cpp b/src/wallet/descriptor_analyzer.cpp\nindex cb3e443ec2..33ea2c5431 100644\n--- a/src/wallet/descriptor_analyzer.cpp\n+++ b/src/wallet/descriptor_analyzer.cpp\n@@ -7,6 +7,7 @@\n #include <key.h>\n #include <pubkey.h>\n #include <script/descriptor.h>\n+#include <script/keyorigin.h>\n #include <script/signingprovider.h>\n #include <sync.h>\n #include <util/bip32.h>\n@@ -45,48 +46,71 @@ KeyMatch Best(KeyMatch a, KeyMatch b)\n     return KeyMatch::NOT_MINE;\n }\n \n+//! The wallet's HD keys, and the origins its descriptors give them.\n+struct HDKeys {\n+    CWallet::HDPubKeyMap keys;\n+    //! E.g. an account xprv imported with its master's origin.\n+    std::vector<std::pair<KeyOriginInfo, CExtPubKey>> origins;\n+};\n+\n+/** Match a key against what deriving `path` from the wallet's HD key `hd_key`\n+ *  gives. `same` tells whether an extended public key is the key. */\n+template <typename Same>\n+KeyMatch MatchPath(const CWallet& wallet, const CExtPubKey& hd_key, const std::set<DescriptorScriptPubKeyMan*>& spkms, const std::vector<uint32_t>& path, Same same)\n+    EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n+{\n+    // Only the descriptors with this key count, as in gethdkeys: the wallet\n+    // signs with each descriptor's own keys, so a private key held alone in\n+    // another descriptor can't sign for it.\n+    const bool has_private{HasPrivKey(spkms, hd_key.pubkey.GetID())};\n+    std::optional<CExtPubKey> derived;\n+    if (!HasHardenedDerivation(path)) {\n+        // Public derivation needs no private key, even when locked.\n+        derived = hd_key;\n+        for (const uint32_t step : path) {\n+            if (!derived->Derive(*derived, step)) return KeyMatch::NOT_MINE;\n+        }\n+    } else if (!has_private) {\n+        // Without the private key this candidate can't be derived; unlocking wouldn't help.\n+        return KeyMatch::NOT_MINE;\n+    } else if (wallet.IsLocked()) {\n+        return KeyMatch::UNKNOWN;\n+    } else if (const auto xprv{wallet.GetExtKey(hd_key)}) {\n+        // Decrypts only this candidate's key.\n+        if (const auto child{DeriveExtKey(*xprv, path)}) derived = child->first.Neuter();\n+    }\n+    if (derived && same(*derived)) return has_private ? KeyMatch::MINE : KeyMatch::WATCH_ONLY;\n+    return KeyMatch::NOT_MINE;\n+}\n+\n /** Match a key against the wallet's HD keys: the key is one of them, or\n- *  deriving `origin`'s path from the one with its fingerprint gives the key.\n- *  `same` tells whether an extended public key is the key. */\n+ *  deriving the rest of `origin`'s path from one of them gives the key. The\n+ *  path starts at the HD key with the origin's fingerprint, or after an origin\n+ *  the wallet's descriptors give an HD key. `same` tells whether an extended\n+ *  public key is the key. */\n template <typename Same>\n-KeyMatch MatchHDKeys(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys, const std::optional<KeyOriginInfo>& origin, Same same)\n+KeyMatch MatchHDKeys(const CWallet& wallet, const HDKeys& hd_keys, const std::optional<KeyOriginInfo>& origin, Same same)\n     EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n     KeyMatch result{KeyMatch::NOT_MINE};\n-    for (const auto& [hd_key, spkms] : hd_keys) {\n-        const bool has_private{HasPrivKey(spkms, hd_key.pubkey.GetID())};\n-        if (same(hd_key)) {\n-            result = Best(result, has_private ? KeyMatch::MINE : KeyMatch::WATCH_ONLY);\n-            continue;\n-        }\n-        if (!origin || origin->fingerprint != hd_key.id_key_fingerprint()) continue;\n-\n-        std::optional<CExtPubKey> derived;\n-        if (!HasHardenedDerivation(origin->path)) {\n-            // Public derivation needs no private key, even when locked.\n-            derived = hd_key;\n-            for (const uint32_t step : origin->path) {\n-                if (!derived->Derive(*derived, step)) {\n-                    derived.reset();\n-                    break;\n-                }\n-            }\n-        } else if (!has_private) {\n-            // Without the private key this candidate can't be derived; unlocking wouldn't help.\n-            continue;\n-        } else if (wallet.IsLocked()) {\n-            result = Best(result, KeyMatch::UNKNOWN);\n-            continue;\n-        } else if (const auto xprv{wallet.GetExtKey(hd_key)}) {\n-            // Decrypts only this candidate's key.\n-            if (const auto child{DeriveExtKey(*xprv, origin->path)}) derived = child->first.Neuter();\n-        }\n-        if (derived && same(*derived)) result = Best(result, has_private ? KeyMatch::MINE : KeyMatch::WATCH_ONLY);\n+    for (const auto& [hd_key, spkms] : hd_keys.keys) {\n+        result = Best(result, MatchPath(wallet, hd_key, spkms, {}, same));\n+        if (origin && origin->fingerprint == hd_key.id_key_fingerprint()) result = Best(result, MatchPath(wallet, hd_key, spkms, origin->path, same));\n+    }\n+    if (!origin) return result;\n+    for (const auto& [hd_origin, hd_key] : hd_keys.origins) {\n+        const auto& prefix{hd_origin.path};\n+        if (hd_origin.fingerprint != origin->fingerprint || origin->path.size() < prefix.size() ||\n+            !std::equal(prefix.begin(), prefix.end(), origin->path.begin())) continue;\n+        const auto it{hd_keys.keys.find(hd_key)};\n+        if (it == hd_keys.keys.end()) continue;\n+        const std::vector<uint32_t> rest(origin->path.begin() + prefix.size(), origin->path.end());\n+        result = Best(result, MatchPath(wallet, hd_key, it->second, rest, same));\n     }\n     return result;\n }\n \n-KeyMatch MatchExtKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys, const CExtPubKey& key, const std::optional<KeyOriginInfo>& origin)\n+KeyMatch MatchExtKey(const CWallet& wallet, const HDKeys& hd_keys, const CExtPubKey& key, const std::optional<KeyOriginInfo>& origin)\n     EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n     return MatchHDKeys(wallet, hd_keys, origin, [&](const CExtPubKey& candidate) { return SameKey(candidate, key); });\n@@ -96,7 +120,7 @@ KeyMatch MatchExtKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys,\n  *  from one of the wallet's HD keys, with the origin given in the descriptor\n  *  or the one the wallet recorded when it derived the key. A key the wallet\n  *  has derived is at least WATCH_ONLY. */\n-KeyMatch MatchConstKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys, const DescriptorKeyInfo::ConstKey& key,\n+KeyMatch MatchConstKey(const CWallet& wallet, const HDKeys& hd_keys, const DescriptorKeyInfo::ConstKey& key,\n                        const std::optional<KeyOriginInfo>& origin, DescriptorKeyInventory::Role role)\n     EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n@@ -129,17 +153,20 @@ KeyMatch MatchConstKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_key\n }\n \n /** The wallet's HD keys, plus those it holds only as musig() participants,\n- *  which GetHDPubKeys() leaves out because they have no single key to list. */\n-CWallet::HDPubKeyMap WalletHDKeys(const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n+ *  which GetHDPubKeys() leaves out because they have no single key to list,\n+ *  and the origins its descriptors give them. */\n+HDKeys WalletHDKeys(const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n-    CWallet::HDPubKeyMap hd_keys{wallet.GetHDPubKeys(CWallet::HDKeyFilter::All)};\n+    HDKeys hd_keys{.keys = wallet.GetHDPubKeys(CWallet::HDKeyFilter::All), .origins = {}};\n     for (auto* spkm : wallet.GetAllScriptPubKeyMans()) {\n         auto* desc_spkm{dynamic_cast<DescriptorScriptPubKeyMan*>(spkm)};\n         if (!desc_spkm) continue;\n         const auto inventory{WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->GetWalletDescriptor().descriptor->GetKeyInventory())};\n         for (const auto& occurrence : inventory.occurrences) {\n-            if (occurrence.role != DescriptorKeyInventory::Role::MUSIG_PARTICIPANT) continue;\n-            if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&occurrence.expression.key)}) hd_keys[key->root].insert(desc_spkm);\n+            const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&occurrence.expression.key)};\n+            if (!key) continue;\n+            if (occurrence.role == DescriptorKeyInventory::Role::MUSIG_PARTICIPANT) hd_keys.keys[key->root].insert(desc_spkm);\n+            if (const auto& origin{occurrence.expression.origin}) hd_keys.origins.emplace_back(*origin, key->root);\n         }\n     }\n     return hd_keys;\n@@ -149,10 +176,12 @@ std::optional<CTxDestination> FirstAddress(const Descriptor& descriptor, const S\n {\n     std::vector<CScript> scripts;\n     FlatSigningProvider out;\n-    if (!descriptor.Expand(/*pos=*/0, provider, scripts, out) || scripts.empty()) return std::nullopt;\n-    CTxDestination dest;\n-    if (!ExtractDestination(scripts.front(), dest)) return std::nullopt;\n-    return dest;\n+    if (!descriptor.Expand(/*pos=*/0, provider, scripts, out)) return std::nullopt;\n+    // The first script with an address, as deriveaddresses lists: combo() starts with P2PK, which has none.\n+    for (const CScript& script : scripts) {\n+        if (CTxDestination dest; ExtractDestination(script, dest)) return dest;\n+    }\n+    return std::nullopt;\n }\n \n } // namespace\n@@ -184,7 +213,7 @@ WalletDescriptorAnalysis AnalyzeDescriptor(const CWallet& wallet, std::span<cons\n     }\n \n     LOCK(wallet.cs_wallet);\n-    const CWallet::HDPubKeyMap hd_keys{WalletHDKeys(wallet)};\n+    const HDKeys hd_keys{WalletHDKeys(wallet)};\n     for (const auto& occurrence : result.analysis.policy.keys.occurrences) {\n         const auto& node{occurrence.expression};\n         if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) {\n",
    "truncated": false,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 230,
    "evidence_id": "49b5aae781a34d90b38d4dd71baff544",
    "finding_id": "finding:5",
    "kind": "new_source",
    "line": 124,
    "new_head": "c2d5322d4238be81fcbeb317032e148134f16aad",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/wallet/descriptor_analyzer.cpp",
    "revision": "c2d5322d4238be81fcbeb317032e148134f16aad",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "                       const std::optional<KeyOriginInfo>& origin, DescriptorKeyInventory::Role role)\n    EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n{\n    // Taproot signing uses the x-only key, so either parity is the same key there,\n    // even when written as a full key.\n    using Role = DescriptorKeyInventory::Role;\n    const bool xonly{key.xonly || role == Role::TAPROOT_INTERNAL || role == Role::TAPROOT_OUTPUT || role == Role::TAPSCRIPT};\n    const std::vector<CPubKey> pubkeys{xonly ? XOnlyPubKey{key.pubkey}.GetCPubKeys() : std::vector<CPubKey>{key.pubkey}};\n    std::vector<KeyOriginInfo> origins;\n    if (origin) origins.push_back(*origin);\n    bool derived{false};\n    for (const auto* spkm : wallet.GetAllScriptPubKeyMans()) {\n        const auto* desc_spkm{dynamic_cast<const DescriptorScriptPubKeyMan*>(spkm)};\n        if (!desc_spkm) continue;\n        for (const CPubKey& pubkey : pubkeys) {\n            if (WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->HasPrivKey(pubkey.GetID()))) return KeyMatch::MINE;\n            if (auto recorded{desc_spkm->GetPubKeyOrigin(pubkey)}) {\n                derived = true;\n                origins.push_back(std::move(*recorded));\n            }\n        }\n    }\n\n    const auto same = [&](const CExtPubKey& candidate) {\n        return xonly ? XOnlyPubKey{candidate.pubkey} == XOnlyPubKey{key.pubkey} : candidate.pubkey == key.pubkey;\n    };\n    KeyMatch result{derived ? KeyMatch::WATCH_ONLY : KeyMatch::NOT_MINE};\n    for (const KeyOriginInfo& candidate : origins) result = Best(result, MatchHDKeys(wallet, hd_keys, candidate, same));\n    return result;\n}\n\n/** The wallet's HD keys, plus those it holds only as musig() participants,\n *  which GetHDPubKeys() leaves out because they have no single key to list,\n *  and the origins its descriptors give them. */\nHDKeys WalletHDKeys(const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n{\n    HDKeys hd_keys{.keys = wallet.GetHDPubKeys(CWallet::HDKeyFilter::All), .origins = {}};\n    for (auto* spkm : wallet.GetAllScriptPubKeyMans()) {\n        auto* desc_spkm{dynamic_cast<DescriptorScriptPubKeyMan*>(spkm)};\n        if (!desc_spkm) continue;\n        const auto inventory{WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->GetWalletDescriptor().descriptor->GetKeyInventory())};\n        for (const auto& occurrence : inventory.occurrences) {\n            const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&occurrence.expression.key)};\n            if (!key) continue;\n            if (occurrence.role == DescriptorKeyInventory::Role::MUSIG_PARTICIPANT) hd_keys.keys[key->root].insert(desc_spkm);\n            if (const auto& origin{occurrence.expression.origin}) hd_keys.origins.emplace_back(*origin, key->root);\n        }\n    }\n    return hd_keys;\n}\n\nstd::optional<CTxDestination> FirstAddress(const Descriptor& descriptor, const SigningProvider& provider)\n{\n    std::vector<CScript> scripts;\n    FlatSigningProvider out;\n    if (!descriptor.Expand(/*pos=*/0, provider, scripts, out)) return std::nullopt;\n    // The first script with an address, as deriveaddresses lists: combo() starts with P2PK, which has none.\n    for (const CScript& script : scripts) {\n        if (CTxDestination dest; ExtractDestination(script, dest)) return dest;\n    }\n    return std::nullopt;\n}\n\n} // namespace\n\nstd::optional<bool> WalletDescriptorAnalysis::CanSign() const\n{\n    // MuSig aggregates are never MINE; their participants are matched instead.\n    bool unknown{false};\n    for (const KeyMatch match : keys) {\n        if (match == KeyMatch::MINE) return true;\n        unknown |= match == KeyMatch::UNKNOWN;\n    }\n    if (unknown) return std::nullopt;\n    return false;\n}\n\nWalletDescriptorAnalysis AnalyzeDescriptor(const CWallet& wallet, std::span<const std::unique_ptr<Descriptor>> descriptors, const SigningProvider& provider)\n{\n    WalletDescriptorAnalysis result;\n    result.analysis = AnalyzeDescriptor(descriptors);\n    if (descriptors.empty()) return result;\n    for (const auto& descriptor : descriptors) {\n        const auto address{FirstAddress(*descriptor, provider)};\n        if (!address) {\n            result.first_addresses.clear();\n            break;\n        }\n        result.first_addresses.push_back(*address);\n    }\n\n    LOCK(wallet.cs_wallet);\n    const HDKeys hd_keys{WalletHDKeys(wallet)};\n    for (const auto& occurrence : result.analysis.policy.keys.occurrences) {\n        const auto& node{occurrence.expression};\n        if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) {\n            result.keys.push_back(MatchExtKey(wallet, hd_keys, key->root, node.origin));\n        } else if (const auto* key{std::get_if<DescriptorKeyInfo::ConstKey>(&node.key)}) {\n            result.keys.push_back(MatchConstKey(wallet, hd_keys, *key, node.origin, occurrence.role));\n        } else {\n            result.keys.push_back(KeyMatch::NOT_MINE);\n        }\n    }\n    return result;\n}\n\n} // namespace wallet",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 0997b0116b82..c2d5322d4238

2026-11-26T04:13:37Z · gpt-6-luna

bitcoin#36885HD-key ownership misses private keys in other managerssrc/wallet/descriptor_analyzer.cppstill_present
Assessment

The code still determines HD-root private-key availability using `HasPrivKey(spkms, hd_key.pubkey.GetID())` on managers associated with that root. The supplied change does not broaden that check to all descriptor managers, so split storage of the root's public key and private scalar can still be missed.

path_diff: src/wallet/descriptor_analyzer.cpp; new_source: src/wallet/descriptor_analyzer.cpp

[
  {
    "evidence_id": "c06b06d9375247ab931ffb2eeb087435",
    "finding_id": "finding:4",
    "kind": "path_diff",
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/wallet/descriptor_analyzer.cpp",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "diff --git a/src/wallet/descriptor_analyzer.cpp b/src/wallet/descriptor_analyzer.cpp\nindex cb3e443ec23..33ea2c5431d 100644\n--- a/src/wallet/descriptor_analyzer.cpp\n+++ b/src/wallet/descriptor_analyzer.cpp\n@@ -7,6 +7,7 @@\n #include <key.h>\n #include <pubkey.h>\n #include <script/descriptor.h>\n+#include <script/keyorigin.h>\n #include <script/signingprovider.h>\n #include <sync.h>\n #include <util/bip32.h>\n@@ -45,48 +46,71 @@ KeyMatch Best(KeyMatch a, KeyMatch b)\n     return KeyMatch::NOT_MINE;\n }\n \n+//! The wallet's HD keys, and the origins its descriptors give them.\n+struct HDKeys {\n+    CWallet::HDPubKeyMap keys;\n+    //! E.g. an account xprv imported with its master's origin.\n+    std::vector<std::pair<KeyOriginInfo, CExtPubKey>> origins;\n+};\n+\n+/** Match a key against what deriving `path` from the wallet's HD key `hd_key`\n+ *  gives. `same` tells whether an extended public key is the key. */\n+template <typename Same>\n+KeyMatch MatchPath(const CWallet& wallet, const CExtPubKey& hd_key, const std::set<DescriptorScriptPubKeyMan*>& spkms, const std::vector<uint32_t>& path, Same same)\n+    EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n+{\n+    // Only the descriptors with this key count, as in gethdkeys: the wallet\n+    // signs with each descriptor's own keys, so a private key held alone in\n+    // another descriptor can't sign for it.\n+    const bool has_private{HasPrivKey(spkms, hd_key.pubkey.GetID())};\n+    std::optional<CExtPubKey> derived;\n+    if (!HasHardenedDerivation(path)) {\n+        // Public derivation needs no private key, even when locked.\n+        derived = hd_key;\n+        for (const uint32_t step : path) {\n+            if (!derived->Derive(*derived, step)) return KeyMatch::NOT_MINE;\n+        }\n+    } else if (!has_private) {\n+        // Without the private key this candidate can't be derived; unlocking wouldn't help.\n+        return KeyMatch::NOT_MINE;\n+    } else if (wallet.IsLocked()) {\n+        return KeyMatch::UNKNOWN;\n+    } else if (const auto xprv{wallet.GetExtKey(hd_key)}) {\n+        // Decrypts only this candidate's key.\n+        if (const auto child{DeriveExtKey(*xprv, path)}) derived = child->first.Neuter();\n+    }\n+    if (derived && same(*derived)) return has_private ? KeyMatch::MINE : KeyMatch::WATCH_ONLY;\n+    return KeyMatch::NOT_MINE;\n+}\n+\n /** Match a key against the wallet's HD keys: the key is one of them, or\n- *  deriving `origin`'s path from the one with its fingerprint gives the key.\n- *  `same` tells whether an extended public key is the key. */\n+ *  deriving the rest of `origin`'s path from one of them gives the key. The\n+ *  path starts at the HD key with the origin's fingerprint, or after an origin\n+ *  the wallet's descriptors give an HD key. `same` tells whether an extended\n+ *  public key is the key. */\n template <typename Same>\n-KeyMatch MatchHDKeys(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys, const std::optional<KeyOriginInfo>& origin, Same same)\n+KeyMatch MatchHDKeys(const CWallet& wallet, const HDKeys& hd_keys, const std::optional<KeyOriginInfo>& origin, Same same)\n     EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n     KeyMatch result{KeyMatch::NOT_MINE};\n-    for (const auto& [hd_key, spkms] : hd_keys) {\n-        const bool has_private{HasPrivKey(spkms, hd_key.pubkey.GetID())};\n-        if (same(hd_key)) {\n-            result = Best(result, has_private ? KeyMatch::MINE : KeyMatch::WATCH_ONLY);\n-            continue;\n-        }\n-        if (!origin || origin->fingerprint != hd_key.id_key_fingerprint()) continue;\n-\n-        std::optional<CExtPubKey> derived;\n-        if (!HasHardenedDerivation(origin->path)) {\n-            // Public derivation needs no private key, even when locked.\n-            derived = hd_key;\n-            for (const uint32_t step : origin->path) {\n-                if (!derived->Derive(*derived, step)) {\n-                    derived.reset();\n-                    break;\n-                }\n-            }\n-        } else if (!has_private) {\n-            // Without the private key this candidate can't be derived; unlocking wouldn't help.\n-            continue;\n-        } else if (wallet.IsLocked()) {\n-            result = Best(result, KeyMatch::UNKNOWN);\n-            continue;\n-        } else if (const auto xprv{wallet.GetExtKey(hd_key)}) {\n-            // Decrypts only this candidate's key.\n-            if (const auto child{DeriveExtKey(*xprv, origin->path)}) derived = child->first.Neuter();\n-        }\n-        if (derived && same(*derived)) result = Best(result, has_private ? KeyMatch::MINE : KeyMatch::WATCH_ONLY);\n+    for (const auto& [hd_key, spkms] : hd_keys.keys) {\n+        result = Best(result, MatchPath(wallet, hd_key, spkms, {}, same));\n+        if (origin && origin->fingerprint == hd_key.id_key_fingerprint()) result = Best(result, MatchPath(wallet, hd_key, spkms, origin->path, same));\n+    }\n+    if (!origin) return result;\n+    for (const auto& [hd_origin, hd_key] : hd_keys.origins) {\n+        const auto& prefix{hd_origin.path};\n+        if (hd_origin.fingerprint != origin->fingerprint || origin->path.size() < prefix.size() ||\n+            !std::equal(prefix.begin(), prefix.end(), origin->path.begin())) continue;\n+        const auto it{hd_keys.keys.find(hd_key)};\n+        if (it == hd_keys.keys.end()) continue;\n+        const std::vector<uint32_t> rest(origin->path.begin() + prefix.size(), origin->path.end());\n+        result = Best(result, MatchPath(wallet, hd_key, it->second, rest, same));\n     }\n     return result;\n }\n \n-KeyMatch MatchExtKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys, const CExtPubKey& key, const std::optional<KeyOriginInfo>& origin)\n+KeyMatch MatchExtKey(const CWallet& wallet, const HDKeys& hd_keys, const CExtPubKey& key, const std::optional<KeyOriginInfo>& origin)\n     EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n     return MatchHDKeys(wallet, hd_keys, origin, [&](const CExtPubKey& candidate) { return SameKey(candidate, key); });\n@@ -96,7 +120,7 @@ KeyMatch MatchExtKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys,\n  *  from one of the wallet's HD keys, with the origin given in the descriptor\n  *  or the one the wallet recorded when it derived the key. A key the wallet\n  *  has derived is at least WATCH_ONLY. */\n-KeyMatch MatchConstKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys, const DescriptorKeyInfo::ConstKey& key,\n+KeyMatch MatchConstKey(const CWallet& wallet, const HDKeys& hd_keys, const DescriptorKeyInfo::ConstKey& key,\n                        const std::optional<KeyOriginInfo>& origin, DescriptorKeyInventory::Role role)\n     EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n@@ -129,17 +153,20 @@ KeyMatch MatchConstKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_key\n }\n \n /** The wallet's HD keys, plus those it holds only as musig() participants,\n- *  which GetHDPubKeys() leaves out because they have no single key to list. */\n-CWallet::HDPubKeyMap WalletHDKeys(const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n+ *  which GetHDPubKeys() leaves out because they have no single key to list,\n+ *  and the origins its descriptors give them. */\n+HDKeys WalletHDKeys(const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n-    CWallet::HDPubKeyMap hd_keys{wallet.GetHDPubKeys(CWallet::HDKeyFilter::All)};\n+    HDKeys hd_keys{.keys = wallet.GetHDPubKeys(CWallet::HDKeyFilter::All), .origins = {}};\n     for (auto* spkm : wallet.GetAllScriptPubKeyMans()) {\n         auto* desc_spkm{dynamic_cast<DescriptorScriptPubKeyMan*>(spkm)};\n         if (!desc_spkm) continue;\n         const auto inventory{WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->GetWalletDescriptor().descriptor->GetKeyInventory())};\n         for (const auto& occurrence : inventory.occurrences) {\n-            if (occurrence.role != DescriptorKeyInventory::Role::MUSIG_PARTICIPANT) continue;\n-            if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&occurrence.expression.key)}) hd_keys[key->root].insert(desc_spkm);\n+            const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&occurrence.expression.key)};\n+            if (!key) continue;\n+            if (occurrence.role == DescriptorKeyInventory::Role::MUSIG_PARTICIPANT) hd_keys.keys[key->root].insert(desc_spkm);\n+            if (const auto& origin{occurrence.expression.origin}) hd_keys.origins.emplace_back(*origin, key->root);\n         }\n     }\n     return hd_keys;\n@@ -149,10 +176,12 @@ std::optional<CTxDestination> FirstAddress(const Descriptor& descriptor, const S\n {\n     std::vector<CScript> scripts;\n     FlatSigningProvider out;\n-    if (!descriptor.Expand(/*pos=*/0, provider, scripts, out) || scripts.empty()) return std::nullopt;\n-    CTxDestination dest;\n-    if (!ExtractDestination(scripts.front(), dest)) return std::nullopt;\n-    return dest;\n+    if (!descriptor.Expand(/*pos=*/0, provider, scripts, out)) return std::nullopt;\n+    // The first script with an address, as deriveaddresses lists: combo() starts with P2PK, which has none.\n+    for (const CScript& script : scripts) {\n+        if (CTxDestination dest; ExtractDestination(script, dest)) return dest;\n+    }\n+    return std::nullopt;\n }\n \n } // namespace\n@@ -184,7 +213,7 @@ WalletDescriptorAnalysis AnalyzeDescriptor(const CWallet& wallet, std::span<cons\n     }\n \n     LOCK(wallet.cs_wallet);\n-    const CWallet::HDPubKeyMap hd_keys{WalletHDKeys(wallet)};\n+    const HDKeys hd_keys{WalletHDKeys(wallet)};\n     for (const auto& occurrence : result.analysis.policy.keys.occurrences) {\n         const auto& node{occurrence.expression};\n         if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) {\n",
    "truncated": false,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 176,
    "evidence_id": "a3430e44a5f94269b6d4bb8170f0f32b",
    "finding_id": "finding:4",
    "kind": "new_source",
    "line": 27,
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/wallet/descriptor_analyzer.cpp",
    "revision": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "\n//! Same key material, ignoring depth, parent fingerprint and child number metadata.\nbool SameKey(const CExtPubKey& a, const CExtPubKey& b)\n{\n    return a.pubkey == b.pubkey && a.chaincode == b.chaincode;\n}\n\nbool HasPrivKey(const std::set<DescriptorScriptPubKeyMan*>& spkms, const CKeyID& id)\n{\n    return std::ranges::any_of(spkms, [&](const auto* spkm) { LOCK(spkm->cs_desc_man); return spkm->HasPrivKey(id); });\n}\n\n//! Prefer the most useful answer when several wallet keys are candidates. A\n//! locked wallet may still hold the private key, so UNKNOWN beats WATCH_ONLY.\nKeyMatch Best(KeyMatch a, KeyMatch b)\n{\n    for (const KeyMatch match : {KeyMatch::MINE, KeyMatch::UNKNOWN, KeyMatch::WATCH_ONLY}) {\n        if (a == match || b == match) return match;\n    }\n    return KeyMatch::NOT_MINE;\n}\n\n//! The wallet's HD keys, and the origins its descriptors give them.\nstruct HDKeys {\n    CWallet::HDPubKeyMap keys;\n    //! E.g. an account xprv imported with its master's origin.\n    std::vector<std::pair<KeyOriginInfo, CExtPubKey>> origins;\n};\n\n/** Match a key against what deriving `path` from the wallet's HD key `hd_key`\n *  gives. `same` tells whether an extended public key is the key. */\ntemplate <typename Same>\nKeyMatch MatchPath(const CWallet& wallet, const CExtPubKey& hd_key, const std::set<DescriptorScriptPubKeyMan*>& spkms, const std::vector<uint32_t>& path, Same same)\n    EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n{\n    // Only the descriptors with this key count, as in gethdkeys: the wallet\n    // signs with each descriptor's own keys, so a private key held alone in\n    // another descriptor can't sign for it.\n    const bool has_private{HasPrivKey(spkms, hd_key.pubkey.GetID())};\n    std::optional<CExtPubKey> derived;\n    if (!HasHardenedDerivation(path)) {\n        // Public derivation needs no private key, even when locked.\n        derived = hd_key;\n        for (const uint32_t step : path) {\n            if (!derived->Derive(*derived, step)) return KeyMatch::NOT_MINE;\n        }\n    } else if (!has_private) {\n        // Without the private key this candidate can't be derived; unlocking wouldn't help.\n        return KeyMatch::NOT_MINE;\n    } else if (wallet.IsLocked()) {\n        return KeyMatch::UNKNOWN;\n    } else if (const auto xprv{wallet.GetExtKey(hd_key)}) {\n        // Decrypts only this candidate's key.\n        if (const auto child{DeriveExtKey(*xprv, path)}) derived = child->first.Neuter();\n    }\n    if (derived && same(*derived)) return has_private ? KeyMatch::MINE : KeyMatch::WATCH_ONLY;\n    return KeyMatch::NOT_MINE;\n}\n\n/** Match a key against the wallet's HD keys: the key is one of them, or\n *  deriving the rest of `origin`'s path from one of them gives the key. The\n *  path starts at the HD key with the origin's fingerprint, or after an origin\n *  the wallet's descriptors give an HD key. `same` tells whether an extended\n *  public key is the key. */\ntemplate <typename Same>\nKeyMatch MatchHDKeys(const CWallet& wallet, const HDKeys& hd_keys, const std::optional<KeyOriginInfo>& origin, Same same)\n    EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n{\n    KeyMatch result{KeyMatch::NOT_MINE};\n    for (const auto& [hd_key, spkms] : hd_keys.keys) {\n        result = Best(result, MatchPath(wallet, hd_key, spkms, {}, same));\n        if (origin && origin->fingerprint == hd_key.id_key_fingerprint()) result = Best(result, MatchPath(wallet, hd_key, spkms, origin->path, same));\n    }\n    if (!origin) return result;\n    for (const auto& [hd_origin, hd_key] : hd_keys.origins) {\n        const auto& prefix{hd_origin.path};\n        if (hd_origin.fingerprint != origin->fingerprint || origin->path.size() < prefix.size() ||\n            !std::equal(prefix.begin(), prefix.end(), origin->path.begin())) continue;\n        const auto it{hd_keys.keys.find(hd_key)};\n        if (it == hd_keys.keys.end()) continue;\n        const std::vector<uint32_t> rest(origin->path.begin() + prefix.size(), origin->path.end());\n        result = Best(result, MatchPath(wallet, hd_key, it->second, rest, same));\n    }\n    return result;\n}\n\nKeyMatch MatchExtKey(const CWallet& wallet, const HDKeys& hd_keys, const CExtPubKey& key, const std::optional<KeyOriginInfo>& origin)\n    EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n{\n    return MatchHDKeys(wallet, hd_keys, origin, [&](const CExtPubKey& candidate) { return SameKey(candidate, key); });\n}\n\n/** Match a constant key: the wallet stores its private key, or it is derived\n *  from one of the wallet's HD keys, with the origin given in the descriptor\n *  or the one the wallet recorded when it derived the key. A key the wallet\n *  has derived is at least WATCH_ONLY. */\nKeyMatch MatchConstKey(const CWallet& wallet, const HDKeys& hd_keys, const DescriptorKeyInfo::ConstKey& key,\n                       const std::optional<KeyOriginInfo>& origin, DescriptorKeyInventory::Role role)\n    EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n{\n    // Taproot signing uses the x-only key, so either parity is the same key there,\n    // even when written as a full key.\n    using Role = DescriptorKeyInventory::Role;\n    const bool xonly{key.xonly || role == Role::TAPROOT_INTERNAL || role == Role::TAPROOT_OUTPUT || role == Role::TAPSCRIPT};\n    const std::vector<CPubKey> pubkeys{xonly ? XOnlyPubKey{key.pubkey}.GetCPubKeys() : std::vector<CPubKey>{key.pubkey}};\n    std::vector<KeyOriginInfo> origins;\n    if (origin) origins.push_back(*origin);\n    bool derived{false};\n    for (const auto* spkm : wallet.GetAllScriptPubKeyMans()) {\n        const auto* desc_spkm{dynamic_cast<const DescriptorScriptPubKeyMan*>(spkm)};\n        if (!desc_spkm) continue;\n        for (const CPubKey& pubkey : pubkeys) {\n            if (WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->HasPrivKey(pubkey.GetID()))) return KeyMatch::MINE;\n            if (auto recorded{desc_spkm->GetPubKeyOrigin(pubkey)}) {\n                derived = true;\n                origins.push_back(std::move(*recorded));\n            }\n        }\n    }\n\n    const auto same = [&](const CExtPubKey& candidate) {\n        return xonly ? XOnlyPubKey{candidate.pubkey} == XOnlyPubKey{key.pubkey} : candidate.pubkey == key.pubkey;\n    };\n    KeyMatch result{derived ? KeyMatch::WATCH_ONLY : KeyMatch::NOT_MINE};\n    for (const KeyOriginInfo& candidate : origins) result = Best(result, MatchHDKeys(wallet, hd_keys, candidate, same));\n    return result;\n}\n\n/** The wallet's HD keys, plus those it holds only as musig() participants,\n *  which GetHDPubKeys() leaves out because they have no single key to list,\n *  and the origins its descriptors give them. */\nHDKeys WalletHDKeys(const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n{\n    HDKeys hd_keys{.keys = wallet.GetHDPubKeys(CWallet::HDKeyFilter::All), .origins = {}};\n    for (auto* spkm : wallet.GetAllScriptPubKeyMans()) {\n        auto* desc_spkm{dynamic_cast<DescriptorScriptPubKeyMan*>(spkm)};\n        if (!desc_spkm) continue;\n        const auto inventory{WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->GetWalletDescriptor().descriptor->GetKeyInventory())};\n        for (const auto& occurrence : inventory.occurrences) {\n            const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&occurrence.expression.key)};\n            if (!key) continue;\n            if (occurrence.role == DescriptorKeyInventory::Role::MUSIG_PARTICIPANT) hd_keys.keys[key->root].insert(desc_spkm);\n            if (const auto& origin{occurrence.expression.origin}) hd_keys.origins.emplace_back(*origin, key->root);\n        }\n    }\n    return hd_keys;\n}\n\nstd::optional<CTxDestination> FirstAddress(const Descriptor& descriptor, const SigningProvider& provider)\n{",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 0997b0116b82..386c55a4bfcb

2026-11-26T06:52:03Z · gpt-6-luna

bitcoin#36885Duplicate detection scales quadratically with descriptor sizesrc/script/descriptor_analyzer.cppaddressed
Assessment

Repeated-key grouping no longer evaluates every pair for equal roots and derived keys: it groups equal values through maps, and indexes candidate direct parents by fingerprint before verifying derivation. This removes the cited quadratic all-pairs work for the described large duplicate and candidate-parent cases.

path_diff: src/script/descriptor_analyzer.cpp; new_source: src/script/descriptor_analyzer.cpp

[
  {
    "evidence_id": "e7727ee37fa54fb69c1fefbc74ba9ca6",
    "finding_id": "finding:3",
    "kind": "path_diff",
    "new_head": "8721e96cc46f544eb8505e6fb3502e934dd0906b",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/script/descriptor_analyzer.cpp",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "diff --git a/src/script/descriptor_analyzer.cpp b/src/script/descriptor_analyzer.cpp\nindex 7958f6792c..f7c893485c 100644\n--- a/src/script/descriptor_analyzer.cpp\n+++ b/src/script/descriptor_analyzer.cpp\n@@ -13,9 +13,11 @@\n #include <algorithm>\n #include <array>\n #include <cstddef>\n+#include <limits>\n+#include <map>\n #include <numeric>\n #include <optional>\n-#include <ranges>\n+#include <set>\n #include <utility>\n #include <variant>\n #include <vector>\n@@ -82,13 +84,16 @@ std::optional<XOnlyPubKey> DeriveFirstKey(const DescriptorKeyInfo::BIP32Key& key\n     return XOnlyPubKey{derived.pubkey};\n }\n \n-/** Check that every cosigner slot can derive addresses on its own. */\n+/** Check that every cosigner slot can derive addresses on its own, and that\n+ *  someone can sign for it. */\n void CheckCosignerKeys(DescriptorAnalysis& result)\n {\n     for (const size_t id : result.cosigners) {\n         const auto& node{result.policy.keys.occurrences.at(id).expression};\n         const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)};\n-        if (!key) {\n+        if (RootKey(node) == XOnlyPubKey::NUMS_H) {\n+            result.issues.push_back({IssueKind::UNSPENDABLE_KEY, {id}});\n+        } else if (!key) {\n             result.issues.push_back({IssueKind::NOT_EXTENDED_KEY, {id}});\n         } else if (NeedsPrivateDerivation(*key)) {\n             result.issues.push_back({IssueKind::HARDENED_DERIVATION, {id}});\n@@ -109,29 +114,65 @@ std::optional<XOnlyPubKey> FirstDerivedKey(const DescriptorKeyInfo::Node& node)\n     return DeriveFirstKey(*key);\n }\n \n-/** Group the indices below `count` that `linked` connects, directly or through\n- *  a chain of links. Each group is in index order, listed by its first index. */\n-template <typename Linked>\n-std::vector<std::vector<size_t>> LinkedGroups(size_t count, Linked linked)\n+/** Indices below a count, grouped by links: two indices are in one group if\n+ *  a chain of links connects them. */\n+class LinkedGroups\n {\n-    // Each index points to an earlier index of its group, the first one pointing to itself.\n-    std::vector<size_t> parent(count);\n-    std::iota(parent.begin(), parent.end(), size_t{0});\n-    const auto first_of = [&](size_t i) {\n-        while (parent[i] != i) i = parent[i];\n+    //! Each index points to an earlier index of its group, the first one pointing to itself.\n+    std::vector<size_t> m_parent;\n+\n+public:\n+    explicit LinkedGroups(size_t count) : m_parent(count)\n+    {\n+        std::iota(m_parent.begin(), m_parent.end(), size_t{0});\n+    }\n+\n+    //! The first index of `i`'s group.\n+    size_t First(size_t i)\n+    {\n+        // Point each index visited to its grandparent, keeping later searches short.\n+        while (m_parent[i] != i) i = m_parent[i] = m_parent[m_parent[i]];\n         return i;\n-    };\n-    for (size_t i{0}; i < count; ++i) {\n-        for (size_t j{i + 1}; j < count; ++j) {\n-            if (!linked(i, j)) continue;\n-            const size_t a{first_of(i)}, b{first_of(j)};\n-            parent[std::max(a, b)] = std::min(a, b);\n+    }\n+\n+    void Link(size_t i, size_t j)\n+    {\n+        const size_t a{First(i)}, b{First(j)};\n+        m_parent[std::max(a, b)] = std::min(a, b);\n+    }\n+\n+    //! Link the indices with equal values. A missing value links nothing.\n+    template <typename T>\n+    void LinkEqual(const std::vector<std::optional<T>>& values)\n+    {\n+        std::map<T, size_t> first;\n+        for (size_t i{0}; i < values.size(); ++i) {\n+            if (!values[i]) continue;\n+            const auto [it, inserted]{first.try_emplace(*values[i], i)};\n+            if (!inserted) Link(it->second, i);\n         }\n     }\n-    std::vector<std::vector<size_t>> groups(count);\n-    for (size_t i{0}; i < count; ++i) groups[first_of(i)].push_back(i);\n-    std::erase_if(groups, [](const auto& group) { return group.empty(); });\n-    return groups;\n+\n+    //! Groups of at least two indices, each in index order, listed by its first index.\n+    std::vector<std::vector<size_t>> Repeated()\n+    {\n+        std::vector<std::vector<size_t>> groups(m_parent.size());\n+        for (size_t i{0}; i < m_parent.size(); ++i) groups[First(i)].push_back(i);\n+        std::erase_if(groups, [](const auto& group) { return group.size() < 2; });\n+        return groups;\n+    }\n+};\n+\n+/** Report each group of `groups` as one REPEATED_KEY issue, with the occurrence\n+ *  IDs `ids` gives for its indices. */\n+void ReportRepeated(DescriptorAnalysis& result, LinkedGroups& groups, const std::vector<size_t>& ids)\n+{\n+    for (const auto& group : groups.Repeated()) {\n+        std::vector<size_t> keys;\n+        keys.reserve(group.size());\n+        for (const size_t i : group) keys.push_back(ids[i]);\n+        result.issues.push_back({IssueKind::REPEATED_KEY, std::move(keys)});\n+    }\n }\n \n /** Report every group of cosigner slots held by the same key: slots that share\n@@ -153,17 +194,32 @@ void CheckRepeatedKeys(DescriptorAnalysis& result)\n         derived.push_back(FirstDerivedKey(node));\n         ext_roots.push_back(RootExtKey(node));\n     }\n-    const auto same_holder = [&](size_t i, size_t j) {\n-        if ((roots[i] && roots[i] == roots[j]) || (derived[i] && derived[i] == derived[j])) return true;\n-        return ext_roots[i] && ext_roots[j] && (IsDirectChild(*ext_roots[i], *ext_roots[j]) || IsDirectChild(*ext_roots[j], *ext_roots[i]));\n-    };\n-    for (const auto& group : LinkedGroups(count, same_holder)) {\n-        if (group.size() < 2) continue;\n-        std::vector<size_t> ids;\n-        ids.reserve(group.size());\n-        for (const size_t i : group) ids.push_back(result.cosigners[i]);\n-        result.issues.push_back({IssueKind::REPEATED_KEY, std::move(ids)});\n+    LinkedGroups groups{count};\n+    groups.LinkEqual(roots);\n+    groups.LinkEqual(derived);\n+\n+    // Only an xpub whose fingerprint a child names can be its parent, so a\n+    // child is derived again only from those, and not when the two slots are\n+    // already in one group. Xpubs sharing a root key are one group already, and\n+    // can share a fingerprint with any number of chain codes, so only the first\n+    // of them is a candidate parent: a child of a later one is left out of the\n+    // group, which is reported either way.\n+    std::multimap<KeyFingerprint, size_t> by_fingerprint;\n+    std::set<XOnlyPubKey> parent_roots;\n+    for (size_t i{0}; i < count; ++i) {\n+        if (ext_roots[i] && parent_roots.insert(*roots[i]).second) by_fingerprint.emplace(ext_roots[i]->id_key_fingerprint(), i);\n     }\n+    for (size_t child{0}; child < count; ++child) {\n+        if (!ext_roots[child]) continue;\n+        const auto [begin, end]{by_fingerprint.equal_range(ext_roots[child]->fingerprint)};\n+        for (auto it{begin}; it != end; ++it) {\n+            const size_t parent{it->second};\n+            if (groups.First(parent) != groups.First(child) && IsDirectChild(*ext_roots[parent], *ext_roots[child])) {\n+                groups.Link(parent, child);\n+            }\n+        }\n+    }\n+    ReportRepeated(result, groups, result.cosigners);\n }\n \n /** Check that every cosigner can derive each participant of a musig()\n@@ -192,16 +248,23 @@ void CheckMuSigParticipants(DescriptorAnalysis& result, size_t internal_id)\n             result.issues.push_back({IssueKind::NOT_DERIVABLE, {id}});\n         }\n     }\n-    const auto same_key = [&](size_t i, size_t j) {\n-        return (roots[i] && roots[i] == roots[j]) || (derived[i] && derived[i] == derived[j]);\n-    };\n-    for (const auto& group : LinkedGroups(participants.size(), same_key)) {\n-        if (group.size() < 2) continue;\n-        std::vector<size_t> ids;\n-        ids.reserve(group.size());\n-        for (const size_t i : group) ids.push_back(participants[i]);\n-        result.issues.push_back({IssueKind::REPEATED_KEY, std::move(ids)});\n+    LinkedGroups groups{participants.size()};\n+    groups.LinkEqual(roots);\n+    groups.LinkEqual(derived);\n+    ReportRepeated(result, groups, participants);\n+}\n+\n+/** Whether a NUMS or musig() internal key can derive its first key. Deriving\n+ *  fails past the maximum BIP32 depth, and a musig() aggregate starts as an\n+ *  xpub at depth 0. */\n+bool CanDeriveInternalKey(const DescriptorKeyInfo::Node& node)\n+{\n+    if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) return DeriveFirstKey(*key).has_value();\n+    if (const auto* key{std::get_if<DescriptorKeyInfo::MuSigKey>(&node.key)}) {\n+        const bool ranged{key->derivation.type == DescriptorKeyInfo::DeriveType::UNHARDENED_RANGED};\n+        return key->derivation.path.size() + (ranged ? 1 : 0) <= std::numeric_limits<unsigned char>::max();\n     }\n+    return true;\n }\n \n /** Classify the Taproot internal key against the cosigners of the leaf, or\n@@ -224,16 +287,16 @@ std::optional<DescriptorAnalysis::KeyPath> ClassifyKeyPath(const DescriptorAnaly\n     if (const auto* key{std::get_if<DescriptorKeyInfo::MuSigKey>(&internal.key)}) {\n         // Any `threshold` cosigners can already spend through the leaf, so an\n         // aggregate of at least that many distinct cosigners adds no new way to spend.\n-        std::vector<XOnlyPubKey> cosigner_roots;\n+        std::set<XOnlyPubKey> cosigner_roots;\n         for (const size_t id : result.cosigners) {\n-            if (const auto root{RootKey(occurrences.at(id).expression)}) cosigner_roots.push_back(*root);\n+            if (const auto root{RootKey(occurrences.at(id).expression)}) cosigner_roots.insert(*root);\n         }\n-        std::vector<XOnlyPubKey> participants;\n+        // A repeated participant adds no cosigner.\n+        std::set<XOnlyPubKey> participants;\n         for (const size_t id : key->participants) {\n             const auto root{RootKey(occurrences.at(id).expression)};\n-            if (!root || std::ranges::find(cosigner_roots, *root) == cosigner_roots.end()) return std::nullopt;\n-            // A repeated participant adds no cosigner.\n-            if (std::ranges::find(participants, *root) == participants.end()) participants.push_back(*root);\n+            if (!root || !cosigner_roots.contains(*root)) return std::nullopt;\n+            participants.insert(*root);\n         }\n         if (participants.size() >= result.threshold) return DescriptorAnalysis::KeyPath::MUSIG;\n     }\n@@ -299,6 +362,9 @@ DescriptorAnalysis AnalyzeDescriptor(const Descriptor& descriptor)\n         CheckMuSigParticipants(result, internal_id);\n         if (const auto key_path{ClassifyKeyPath(result, internal_id)}) {\n             result.key_path = *key_path;\n+            if (!CanDeriveInternalKey(result.policy.keys.occurrences.at(internal_id).expression)) {\n+                result.issues.push_back({IssueKind::NOT_DERIVABLE, {internal_id}});\n+            }\n         } else {\n             result.issues.push_back({IssueKind::KEY_PATH_SPENDABLE, {internal_id}});\n         }\n@@ -321,14 +387,19 @@ DescriptorAnalysis AnalyzeDescriptor(std::span<const std::unique_ptr<Descriptor>\n         for (const size_t id : analysis.cosigners) roots.push_back(RootKey(analysis.policy.keys.occurrences.at(id).expression));\n         return roots;\n     };\n+    // The branches share their key IDs, so each issue is reported once,\n+    // whichever branch it comes from.\n+    std::set<DescriptorAnalysis::Issue> seen(first.issues.begin(), first.issues.end());\n+    bool differ{false};\n     for (const auto& descriptor : descriptors.subspan(1)) {\n         const DescriptorAnalysis other{AnalyzeDescriptor(*descriptor)};\n-        if (other.shape != first.shape || other.sorted != first.sorted || other.key_path != first.key_path ||\n-            other.threshold != first.threshold || cosigner_roots(other) != cosigner_roots(first)) {\n-            Unrecognize(first);\n-            first.issues.push_back({DescriptorAnalysis::Issue::Kind::BRANCHES_DIFFER, {}});\n-            break;\n+        differ |= other.shape != first.shape || other.sorted != first.sorted || other.key_path != first.key_path ||\n+                  other.threshold != first.threshold || cosigner_roots(other) != cosigner_roots(first);\n+        for (const auto& issue : other.issues) {\n+            if (seen.insert(issue).second) first.issues.push_back(issue);\n         }\n     }\n+    if (differ) first.issues.push_back({IssueKind::BRANCHES_DIFFER, {}});\n+    if (!first.issues.empty()) Unrecognize(first);\n     return first;\n }\n",
    "truncated": false,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 245,
    "evidence_id": "d2e5d4a156bd4aa897493cf564879b04",
    "finding_id": "finding:3",
    "kind": "new_source",
    "line": 96,
    "new_head": "8721e96cc46f544eb8505e6fb3502e934dd0906b",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/script/descriptor_analyzer.cpp",
    "revision": "8721e96cc46f544eb8505e6fb3502e934dd0906b",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "        } else if (!key) {\n            result.issues.push_back({IssueKind::NOT_EXTENDED_KEY, {id}});\n        } else if (NeedsPrivateDerivation(*key)) {\n            result.issues.push_back({IssueKind::HARDENED_DERIVATION, {id}});\n        } else if (key->derivation.type != DescriptorKeyInfo::DeriveType::UNHARDENED_RANGED) {\n            result.issues.push_back({IssueKind::NOT_RANGED, {id}});\n        } else if (!DeriveFirstKey(*key)) {\n            result.issues.push_back({IssueKind::NOT_DERIVABLE, {id}});\n        }\n    }\n}\n\n/** Public key a cosigner slot derives at the first address, if it derives\n *  without private keys. */\nstd::optional<XOnlyPubKey> FirstDerivedKey(const DescriptorKeyInfo::Node& node)\n{\n    const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)};\n    if (!key || key->derivation.type != DescriptorKeyInfo::DeriveType::UNHARDENED_RANGED) return std::nullopt;\n    return DeriveFirstKey(*key);\n}\n\n/** Indices below a count, grouped by links: two indices are in one group if\n *  a chain of links connects them. */\nclass LinkedGroups\n{\n    //! Each index points to an earlier index of its group, the first one pointing to itself.\n    std::vector<size_t> m_parent;\n\npublic:\n    explicit LinkedGroups(size_t count) : m_parent(count)\n    {\n        std::iota(m_parent.begin(), m_parent.end(), size_t{0});\n    }\n\n    //! The first index of `i`'s group.\n    size_t First(size_t i)\n    {\n        // Point each index visited to its grandparent, keeping later searches short.\n        while (m_parent[i] != i) i = m_parent[i] = m_parent[m_parent[i]];\n        return i;\n    }\n\n    void Link(size_t i, size_t j)\n    {\n        const size_t a{First(i)}, b{First(j)};\n        m_parent[std::max(a, b)] = std::min(a, b);\n    }\n\n    //! Link the indices with equal values. A missing value links nothing.\n    template <typename T>\n    void LinkEqual(const std::vector<std::optional<T>>& values)\n    {\n        std::map<T, size_t> first;\n        for (size_t i{0}; i < values.size(); ++i) {\n            if (!values[i]) continue;\n            const auto [it, inserted]{first.try_emplace(*values[i], i)};\n            if (!inserted) Link(it->second, i);\n        }\n    }\n\n    //! Groups of at least two indices, each in index order, listed by its first index.\n    std::vector<std::vector<size_t>> Repeated()\n    {\n        std::vector<std::vector<size_t>> groups(m_parent.size());\n        for (size_t i{0}; i < m_parent.size(); ++i) groups[First(i)].push_back(i);\n        std::erase_if(groups, [](const auto& group) { return group.size() < 2; });\n        return groups;\n    }\n};\n\n/** Report each group of `groups` as one REPEATED_KEY issue, with the occurrence\n *  IDs `ids` gives for its indices. */\nvoid ReportRepeated(DescriptorAnalysis& result, LinkedGroups& groups, const std::vector<size_t>& ids)\n{\n    for (const auto& group : groups.Repeated()) {\n        std::vector<size_t> keys;\n        keys.reserve(group.size());\n        for (const size_t i : group) keys.push_back(ids[i]);\n        result.issues.push_back({IssueKind::REPEATED_KEY, std::move(keys)});\n    }\n}\n\n/** Report every group of cosigner slots held by the same key: slots that share\n *  a root key (e.g. the same xpub with two paths), that derive the same key, or\n *  where one xpub is the direct child of another. Slots linked through a chain\n *  of these are one group. */\nvoid CheckRepeatedKeys(DescriptorAnalysis& result)\n{\n    const auto& occurrences{result.policy.keys.occurrences};\n    const size_t count{result.cosigners.size()};\n    std::vector<std::optional<XOnlyPubKey>> roots, derived;\n    std::vector<const CExtPubKey*> ext_roots;\n    roots.reserve(count);\n    derived.reserve(count);\n    ext_roots.reserve(count);\n    for (const size_t id : result.cosigners) {\n        const auto& node{occurrences.at(id).expression};\n        roots.push_back(RootKey(node));\n        derived.push_back(FirstDerivedKey(node));\n        ext_roots.push_back(RootExtKey(node));\n    }\n    LinkedGroups groups{count};\n    groups.LinkEqual(roots);\n    groups.LinkEqual(derived);\n\n    // Only an xpub whose fingerprint a child names can be its parent, so a\n    // child is derived again only from those, and not when the two slots are\n    // already in one group. Xpubs sharing a root key are one group already, and\n    // can share a fingerprint with any number of chain codes, so only the first\n    // of them is a candidate parent: a child of a later one is left out of the\n    // group, which is reported either way.\n    std::multimap<KeyFingerprint, size_t> by_fingerprint;\n    std::set<XOnlyPubKey> parent_roots;\n    for (size_t i{0}; i < count; ++i) {\n        if (ext_roots[i] && parent_roots.insert(*roots[i]).second) by_fingerprint.emplace(ext_roots[i]->id_key_fingerprint(), i);\n    }\n    for (size_t child{0}; child < count; ++child) {\n        if (!ext_roots[child]) continue;\n        const auto [begin, end]{by_fingerprint.equal_range(ext_roots[child]->fingerprint)};\n        for (auto it{begin}; it != end; ++it) {\n            const size_t parent{it->second};\n            if (groups.First(parent) != groups.First(child) && IsDirectChild(*ext_roots[parent], *ext_roots[child])) {\n                groups.Link(parent, child);\n            }\n        }\n    }\n    ReportRepeated(result, groups, result.cosigners);\n}\n\n/** Check that every cosigner can derive each participant of a musig()\n *  internal key, and that no participant is repeated: participants with the\n *  same root key, or that derive the same key, are one. */\nvoid CheckMuSigParticipants(DescriptorAnalysis& result, size_t internal_id)\n{\n    const auto& occurrences{result.policy.keys.occurrences};\n    const auto* musig{std::get_if<DescriptorKeyInfo::MuSigKey>(&occurrences.at(internal_id).expression.key)};\n    if (!musig) return;\n    const auto& participants{musig->participants};\n    std::vector<std::optional<XOnlyPubKey>> roots, derived;\n    roots.reserve(participants.size());\n    derived.reserve(participants.size());\n    for (const size_t id : participants) {\n        const auto& participant{occurrences.at(id).expression};\n        roots.push_back(RootKey(participant));\n        derived.push_back(roots.back());\n        const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&participant.key)};\n        if (!key) continue;\n        derived.back() = DeriveFirstKey(*key);\n        if (NeedsPrivateDerivation(*key)) {\n            // Other cosigners couldn't derive the key path.",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 0997b0116b82..8721e96cc46f

2026-11-26T05:50:43Z · gpt-6-luna

bitcoin#36885Over-depth internal keys still receive a recognized verdictsrc/script/descriptor_analyzer.cppaddressed
Assessment

The new `CanDeriveInternalKey` check rejects over-depth BIP32 internal keys by deriving their first key and bounds MuSig derivation depth including a ranged wildcard; failure adds `NOT_DERIVABLE` against the internal-key ID before recognition is finalized.

path_diff: src/script/descriptor_analyzer.cpp; new_source: src/script/descriptor_analyzer.cpp

[
  {
    "evidence_id": "bde62e51bfdb4f6fa6be6abd1c689392",
    "finding_id": "finding:2",
    "kind": "path_diff",
    "new_head": "8721e96cc46f544eb8505e6fb3502e934dd0906b",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/script/descriptor_analyzer.cpp",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "diff --git a/src/script/descriptor_analyzer.cpp b/src/script/descriptor_analyzer.cpp\nindex 7958f6792c..f7c893485c 100644\n--- a/src/script/descriptor_analyzer.cpp\n+++ b/src/script/descriptor_analyzer.cpp\n@@ -13,9 +13,11 @@\n #include <algorithm>\n #include <array>\n #include <cstddef>\n+#include <limits>\n+#include <map>\n #include <numeric>\n #include <optional>\n-#include <ranges>\n+#include <set>\n #include <utility>\n #include <variant>\n #include <vector>\n@@ -82,13 +84,16 @@ std::optional<XOnlyPubKey> DeriveFirstKey(const DescriptorKeyInfo::BIP32Key& key\n     return XOnlyPubKey{derived.pubkey};\n }\n \n-/** Check that every cosigner slot can derive addresses on its own. */\n+/** Check that every cosigner slot can derive addresses on its own, and that\n+ *  someone can sign for it. */\n void CheckCosignerKeys(DescriptorAnalysis& result)\n {\n     for (const size_t id : result.cosigners) {\n         const auto& node{result.policy.keys.occurrences.at(id).expression};\n         const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)};\n-        if (!key) {\n+        if (RootKey(node) == XOnlyPubKey::NUMS_H) {\n+            result.issues.push_back({IssueKind::UNSPENDABLE_KEY, {id}});\n+        } else if (!key) {\n             result.issues.push_back({IssueKind::NOT_EXTENDED_KEY, {id}});\n         } else if (NeedsPrivateDerivation(*key)) {\n             result.issues.push_back({IssueKind::HARDENED_DERIVATION, {id}});\n@@ -109,29 +114,65 @@ std::optional<XOnlyPubKey> FirstDerivedKey(const DescriptorKeyInfo::Node& node)\n     return DeriveFirstKey(*key);\n }\n \n-/** Group the indices below `count` that `linked` connects, directly or through\n- *  a chain of links. Each group is in index order, listed by its first index. */\n-template <typename Linked>\n-std::vector<std::vector<size_t>> LinkedGroups(size_t count, Linked linked)\n+/** Indices below a count, grouped by links: two indices are in one group if\n+ *  a chain of links connects them. */\n+class LinkedGroups\n {\n-    // Each index points to an earlier index of its group, the first one pointing to itself.\n-    std::vector<size_t> parent(count);\n-    std::iota(parent.begin(), parent.end(), size_t{0});\n-    const auto first_of = [&](size_t i) {\n-        while (parent[i] != i) i = parent[i];\n+    //! Each index points to an earlier index of its group, the first one pointing to itself.\n+    std::vector<size_t> m_parent;\n+\n+public:\n+    explicit LinkedGroups(size_t count) : m_parent(count)\n+    {\n+        std::iota(m_parent.begin(), m_parent.end(), size_t{0});\n+    }\n+\n+    //! The first index of `i`'s group.\n+    size_t First(size_t i)\n+    {\n+        // Point each index visited to its grandparent, keeping later searches short.\n+        while (m_parent[i] != i) i = m_parent[i] = m_parent[m_parent[i]];\n         return i;\n-    };\n-    for (size_t i{0}; i < count; ++i) {\n-        for (size_t j{i + 1}; j < count; ++j) {\n-            if (!linked(i, j)) continue;\n-            const size_t a{first_of(i)}, b{first_of(j)};\n-            parent[std::max(a, b)] = std::min(a, b);\n+    }\n+\n+    void Link(size_t i, size_t j)\n+    {\n+        const size_t a{First(i)}, b{First(j)};\n+        m_parent[std::max(a, b)] = std::min(a, b);\n+    }\n+\n+    //! Link the indices with equal values. A missing value links nothing.\n+    template <typename T>\n+    void LinkEqual(const std::vector<std::optional<T>>& values)\n+    {\n+        std::map<T, size_t> first;\n+        for (size_t i{0}; i < values.size(); ++i) {\n+            if (!values[i]) continue;\n+            const auto [it, inserted]{first.try_emplace(*values[i], i)};\n+            if (!inserted) Link(it->second, i);\n         }\n     }\n-    std::vector<std::vector<size_t>> groups(count);\n-    for (size_t i{0}; i < count; ++i) groups[first_of(i)].push_back(i);\n-    std::erase_if(groups, [](const auto& group) { return group.empty(); });\n-    return groups;\n+\n+    //! Groups of at least two indices, each in index order, listed by its first index.\n+    std::vector<std::vector<size_t>> Repeated()\n+    {\n+        std::vector<std::vector<size_t>> groups(m_parent.size());\n+        for (size_t i{0}; i < m_parent.size(); ++i) groups[First(i)].push_back(i);\n+        std::erase_if(groups, [](const auto& group) { return group.size() < 2; });\n+        return groups;\n+    }\n+};\n+\n+/** Report each group of `groups` as one REPEATED_KEY issue, with the occurrence\n+ *  IDs `ids` gives for its indices. */\n+void ReportRepeated(DescriptorAnalysis& result, LinkedGroups& groups, const std::vector<size_t>& ids)\n+{\n+    for (const auto& group : groups.Repeated()) {\n+        std::vector<size_t> keys;\n+        keys.reserve(group.size());\n+        for (const size_t i : group) keys.push_back(ids[i]);\n+        result.issues.push_back({IssueKind::REPEATED_KEY, std::move(keys)});\n+    }\n }\n \n /** Report every group of cosigner slots held by the same key: slots that share\n@@ -153,17 +194,32 @@ void CheckRepeatedKeys(DescriptorAnalysis& result)\n         derived.push_back(FirstDerivedKey(node));\n         ext_roots.push_back(RootExtKey(node));\n     }\n-    const auto same_holder = [&](size_t i, size_t j) {\n-        if ((roots[i] && roots[i] == roots[j]) || (derived[i] && derived[i] == derived[j])) return true;\n-        return ext_roots[i] && ext_roots[j] && (IsDirectChild(*ext_roots[i], *ext_roots[j]) || IsDirectChild(*ext_roots[j], *ext_roots[i]));\n-    };\n-    for (const auto& group : LinkedGroups(count, same_holder)) {\n-        if (group.size() < 2) continue;\n-        std::vector<size_t> ids;\n-        ids.reserve(group.size());\n-        for (const size_t i : group) ids.push_back(result.cosigners[i]);\n-        result.issues.push_back({IssueKind::REPEATED_KEY, std::move(ids)});\n+    LinkedGroups groups{count};\n+    groups.LinkEqual(roots);\n+    groups.LinkEqual(derived);\n+\n+    // Only an xpub whose fingerprint a child names can be its parent, so a\n+    // child is derived again only from those, and not when the two slots are\n+    // already in one group. Xpubs sharing a root key are one group already, and\n+    // can share a fingerprint with any number of chain codes, so only the first\n+    // of them is a candidate parent: a child of a later one is left out of the\n+    // group, which is reported either way.\n+    std::multimap<KeyFingerprint, size_t> by_fingerprint;\n+    std::set<XOnlyPubKey> parent_roots;\n+    for (size_t i{0}; i < count; ++i) {\n+        if (ext_roots[i] && parent_roots.insert(*roots[i]).second) by_fingerprint.emplace(ext_roots[i]->id_key_fingerprint(), i);\n     }\n+    for (size_t child{0}; child < count; ++child) {\n+        if (!ext_roots[child]) continue;\n+        const auto [begin, end]{by_fingerprint.equal_range(ext_roots[child]->fingerprint)};\n+        for (auto it{begin}; it != end; ++it) {\n+            const size_t parent{it->second};\n+            if (groups.First(parent) != groups.First(child) && IsDirectChild(*ext_roots[parent], *ext_roots[child])) {\n+                groups.Link(parent, child);\n+            }\n+        }\n+    }\n+    ReportRepeated(result, groups, result.cosigners);\n }\n \n /** Check that every cosigner can derive each participant of a musig()\n@@ -192,16 +248,23 @@ void CheckMuSigParticipants(DescriptorAnalysis& result, size_t internal_id)\n             result.issues.push_back({IssueKind::NOT_DERIVABLE, {id}});\n         }\n     }\n-    const auto same_key = [&](size_t i, size_t j) {\n-        return (roots[i] && roots[i] == roots[j]) || (derived[i] && derived[i] == derived[j]);\n-    };\n-    for (const auto& group : LinkedGroups(participants.size(), same_key)) {\n-        if (group.size() < 2) continue;\n-        std::vector<size_t> ids;\n-        ids.reserve(group.size());\n-        for (const size_t i : group) ids.push_back(participants[i]);\n-        result.issues.push_back({IssueKind::REPEATED_KEY, std::move(ids)});\n+    LinkedGroups groups{participants.size()};\n+    groups.LinkEqual(roots);\n+    groups.LinkEqual(derived);\n+    ReportRepeated(result, groups, participants);\n+}\n+\n+/** Whether a NUMS or musig() internal key can derive its first key. Deriving\n+ *  fails past the maximum BIP32 depth, and a musig() aggregate starts as an\n+ *  xpub at depth 0. */\n+bool CanDeriveInternalKey(const DescriptorKeyInfo::Node& node)\n+{\n+    if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) return DeriveFirstKey(*key).has_value();\n+    if (const auto* key{std::get_if<DescriptorKeyInfo::MuSigKey>(&node.key)}) {\n+        const bool ranged{key->derivation.type == DescriptorKeyInfo::DeriveType::UNHARDENED_RANGED};\n+        return key->derivation.path.size() + (ranged ? 1 : 0) <= std::numeric_limits<unsigned char>::max();\n     }\n+    return true;\n }\n \n /** Classify the Taproot internal key against the cosigners of the leaf, or\n@@ -224,16 +287,16 @@ std::optional<DescriptorAnalysis::KeyPath> ClassifyKeyPath(const DescriptorAnaly\n     if (const auto* key{std::get_if<DescriptorKeyInfo::MuSigKey>(&internal.key)}) {\n         // Any `threshold` cosigners can already spend through the leaf, so an\n         // aggregate of at least that many distinct cosigners adds no new way to spend.\n-        std::vector<XOnlyPubKey> cosigner_roots;\n+        std::set<XOnlyPubKey> cosigner_roots;\n         for (const size_t id : result.cosigners) {\n-            if (const auto root{RootKey(occurrences.at(id).expression)}) cosigner_roots.push_back(*root);\n+            if (const auto root{RootKey(occurrences.at(id).expression)}) cosigner_roots.insert(*root);\n         }\n-        std::vector<XOnlyPubKey> participants;\n+        // A repeated participant adds no cosigner.\n+        std::set<XOnlyPubKey> participants;\n         for (const size_t id : key->participants) {\n             const auto root{RootKey(occurrences.at(id).expression)};\n-            if (!root || std::ranges::find(cosigner_roots, *root) == cosigner_roots.end()) return std::nullopt;\n-            // A repeated participant adds no cosigner.\n-            if (std::ranges::find(participants, *root) == participants.end()) participants.push_back(*root);\n+            if (!root || !cosigner_roots.contains(*root)) return std::nullopt;\n+            participants.insert(*root);\n         }\n         if (participants.size() >= result.threshold) return DescriptorAnalysis::KeyPath::MUSIG;\n     }\n@@ -299,6 +362,9 @@ DescriptorAnalysis AnalyzeDescriptor(const Descriptor& descriptor)\n         CheckMuSigParticipants(result, internal_id);\n         if (const auto key_path{ClassifyKeyPath(result, internal_id)}) {\n             result.key_path = *key_path;\n+            if (!CanDeriveInternalKey(result.policy.keys.occurrences.at(internal_id).expression)) {\n+                result.issues.push_back({IssueKind::NOT_DERIVABLE, {internal_id}});\n+            }\n         } else {\n             result.issues.push_back({IssueKind::KEY_PATH_SPENDABLE, {internal_id}});\n         }\n@@ -321,14 +387,19 @@ DescriptorAnalysis AnalyzeDescriptor(std::span<const std::unique_ptr<Descriptor>\n         for (const size_t id : analysis.cosigners) roots.push_back(RootKey(analysis.policy.keys.occurrences.at(id).expression));\n         return roots;\n     };\n+    // The branches share their key IDs, so each issue is reported once,\n+    // whichever branch it comes from.\n+    std::set<DescriptorAnalysis::Issue> seen(first.issues.begin(), first.issues.end());\n+    bool differ{false};\n     for (const auto& descriptor : descriptors.subspan(1)) {\n         const DescriptorAnalysis other{AnalyzeDescriptor(*descriptor)};\n-        if (other.shape != first.shape || other.sorted != first.sorted || other.key_path != first.key_path ||\n-            other.threshold != first.threshold || cosigner_roots(other) != cosigner_roots(first)) {\n-            Unrecognize(first);\n-            first.issues.push_back({DescriptorAnalysis::Issue::Kind::BRANCHES_DIFFER, {}});\n-            break;\n+        differ |= other.shape != first.shape || other.sorted != first.sorted || other.key_path != first.key_path ||\n+                  other.threshold != first.threshold || cosigner_roots(other) != cosigner_roots(first);\n+        for (const auto& issue : other.issues) {\n+            if (seen.insert(issue).second) first.issues.push_back(issue);\n         }\n     }\n+    if (differ) first.issues.push_back({IssueKind::BRANCHES_DIFFER, {}});\n+    if (!first.issues.empty()) Unrecognize(first);\n     return first;\n }\n",
    "truncated": false,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 340,
    "evidence_id": "6472edd18fa848d49864c2be90e8db13",
    "finding_id": "finding:2",
    "kind": "new_source",
    "line": 191,
    "new_head": "8721e96cc46f544eb8505e6fb3502e934dd0906b",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/script/descriptor_analyzer.cpp",
    "revision": "8721e96cc46f544eb8505e6fb3502e934dd0906b",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "    for (const size_t id : result.cosigners) {\n        const auto& node{occurrences.at(id).expression};\n        roots.push_back(RootKey(node));\n        derived.push_back(FirstDerivedKey(node));\n        ext_roots.push_back(RootExtKey(node));\n    }\n    LinkedGroups groups{count};\n    groups.LinkEqual(roots);\n    groups.LinkEqual(derived);\n\n    // Only an xpub whose fingerprint a child names can be its parent, so a\n    // child is derived again only from those, and not when the two slots are\n    // already in one group. Xpubs sharing a root key are one group already, and\n    // can share a fingerprint with any number of chain codes, so only the first\n    // of them is a candidate parent: a child of a later one is left out of the\n    // group, which is reported either way.\n    std::multimap<KeyFingerprint, size_t> by_fingerprint;\n    std::set<XOnlyPubKey> parent_roots;\n    for (size_t i{0}; i < count; ++i) {\n        if (ext_roots[i] && parent_roots.insert(*roots[i]).second) by_fingerprint.emplace(ext_roots[i]->id_key_fingerprint(), i);\n    }\n    for (size_t child{0}; child < count; ++child) {\n        if (!ext_roots[child]) continue;\n        const auto [begin, end]{by_fingerprint.equal_range(ext_roots[child]->fingerprint)};\n        for (auto it{begin}; it != end; ++it) {\n            const size_t parent{it->second};\n            if (groups.First(parent) != groups.First(child) && IsDirectChild(*ext_roots[parent], *ext_roots[child])) {\n                groups.Link(parent, child);\n            }\n        }\n    }\n    ReportRepeated(result, groups, result.cosigners);\n}\n\n/** Check that every cosigner can derive each participant of a musig()\n *  internal key, and that no participant is repeated: participants with the\n *  same root key, or that derive the same key, are one. */\nvoid CheckMuSigParticipants(DescriptorAnalysis& result, size_t internal_id)\n{\n    const auto& occurrences{result.policy.keys.occurrences};\n    const auto* musig{std::get_if<DescriptorKeyInfo::MuSigKey>(&occurrences.at(internal_id).expression.key)};\n    if (!musig) return;\n    const auto& participants{musig->participants};\n    std::vector<std::optional<XOnlyPubKey>> roots, derived;\n    roots.reserve(participants.size());\n    derived.reserve(participants.size());\n    for (const size_t id : participants) {\n        const auto& participant{occurrences.at(id).expression};\n        roots.push_back(RootKey(participant));\n        derived.push_back(roots.back());\n        const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&participant.key)};\n        if (!key) continue;\n        derived.back() = DeriveFirstKey(*key);\n        if (NeedsPrivateDerivation(*key)) {\n            // Other cosigners couldn't derive the key path.\n            result.issues.push_back({IssueKind::HARDENED_DERIVATION, {id}});\n        } else if (!derived.back()) {\n            result.issues.push_back({IssueKind::NOT_DERIVABLE, {id}});\n        }\n    }\n    LinkedGroups groups{participants.size()};\n    groups.LinkEqual(roots);\n    groups.LinkEqual(derived);\n    ReportRepeated(result, groups, participants);\n}\n\n/** Whether a NUMS or musig() internal key can derive its first key. Deriving\n *  fails past the maximum BIP32 depth, and a musig() aggregate starts as an\n *  xpub at depth 0. */\nbool CanDeriveInternalKey(const DescriptorKeyInfo::Node& node)\n{\n    if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) return DeriveFirstKey(*key).has_value();\n    if (const auto* key{std::get_if<DescriptorKeyInfo::MuSigKey>(&node.key)}) {\n        const bool ranged{key->derivation.type == DescriptorKeyInfo::DeriveType::UNHARDENED_RANGED};\n        return key->derivation.path.size() + (ranged ? 1 : 0) <= std::numeric_limits<unsigned char>::max();\n    }\n    return true;\n}\n\n/** Classify the Taproot internal key against the cosigners of the leaf, or\n *  nullopt if it may let fewer than `threshold` cosigners spend. */\nstd::optional<DescriptorAnalysis::KeyPath> ClassifyKeyPath(const DescriptorAnalysis& result, size_t internal_id)\n{\n    const auto& occurrences{result.policy.keys.occurrences};\n    const auto& internal{occurrences.at(internal_id).expression};\n\n    if (const auto* key{std::get_if<DescriptorKeyInfo::ConstKey>(&internal.key)}) {\n        if (XOnlyPubKey{key->pubkey} == XOnlyPubKey::NUMS_H) return DescriptorAnalysis::KeyPath::NUMS;\n    }\n    if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&internal.key)}) {\n        // Unhardened children of H are as unspendable as H.\n        if (XOnlyPubKey{key->root.pubkey} == XOnlyPubKey::NUMS_H && !HasHardenedStep(key->derivation) &&\n            key->derivation.type != DescriptorKeyInfo::DeriveType::HARDENED_RANGED) {\n            return DescriptorAnalysis::KeyPath::NUMS;\n        }\n    }\n    if (const auto* key{std::get_if<DescriptorKeyInfo::MuSigKey>(&internal.key)}) {\n        // Any `threshold` cosigners can already spend through the leaf, so an\n        // aggregate of at least that many distinct cosigners adds no new way to spend.\n        std::set<XOnlyPubKey> cosigner_roots;\n        for (const size_t id : result.cosigners) {\n            if (const auto root{RootKey(occurrences.at(id).expression)}) cosigner_roots.insert(*root);\n        }\n        // A repeated participant adds no cosigner.\n        std::set<XOnlyPubKey> participants;\n        for (const size_t id : key->participants) {\n            const auto root{RootKey(occurrences.at(id).expression)};\n            if (!root || !cosigner_roots.contains(*root)) return std::nullopt;\n            participants.insert(*root);\n        }\n        if (participants.size() >= result.threshold) return DescriptorAnalysis::KeyPath::MUSIG;\n    }\n    return std::nullopt;\n}\n\n/** Mark the result unrecognized and drop the setup it would have claimed. */\nvoid Unrecognize(DescriptorAnalysis& result)\n{\n    result.shape = DescriptorAnalysis::Shape::UNRECOGNIZED;\n    result.sorted = false;\n    result.key_path = DescriptorAnalysis::KeyPath::NONE;\n    result.threshold = 0;\n    result.cosigners.clear();\n}\n\n/** Find the multisig node of a recognized shape, or nullptr. */\nconst DescriptorPolicy::Node* FindMultisig(DescriptorAnalysis& result)\n{\n    const auto& nodes{result.policy.nodes};\n    if (nodes.empty()) return nullptr;\n    const auto* root_kind{NodeKind(nodes[0])};\n    if (!root_kind || nodes[0].children.size() != 1) return nullptr;\n    const auto& child{nodes[0].children[0]};\n    const auto& multisig{nodes.at(child.node)};\n    const auto* kind{NodeKind(multisig)};\n    if (!kind || !multisig.children.empty()) return nullptr;\n\n    if (*root_kind == Kind::WSH && (*kind == Kind::MULTI || *kind == Kind::SORTEDMULTI)) {\n        result.shape = DescriptorAnalysis::Shape::WSH_MULTI;\n        result.sorted = *kind == Kind::SORTEDMULTI;\n        return &multisig;\n    }\n    if (*root_kind == Kind::TR && (*kind == Kind::MULTI_A || *kind == Kind::SORTEDMULTI_A)) {\n        const auto* leaf{std::get_if<DescriptorPolicy::TapLeaf>(&child.role)};\n        if (!leaf || leaf->depth != 0 || nodes[0].keys.size() != 1) return nullptr;\n        result.shape = DescriptorAnalysis::Shape::TR_MULTI_A;\n        result.sorted = *kind == Kind::SORTEDMULTI_A;\n        return &multisig;\n    }\n    return nullptr;",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 0997b0116b82..8721e96cc46f

2026-11-26T05:50:43Z · gpt-6-luna

bitcoin#36885WalletHDKeys() traverses the wallet's descriptors twicesrc/wallet/descriptor_analyzer.cpppartially_addressed
Assessment

The inventory loop now inserts every BIP32 occurrence into `hd_keys.origins`, avoiding the earlier role-filtered second inventory pass for origins. However, the map is still initialized with `wallet.GetHDPubKeys(...)`, and ordinary BIP32 roots are still obtained through that separate traversal; the requested single inventory pass building the full root-to-manager map from an empty map is not implemented.

path_diff: src/wallet/descriptor_analyzer.cpp; new_source: src/wallet/descriptor_analyzer.cpp

[
  {
    "evidence_id": "3e62b42d171e48b799e127fcc9c816a8",
    "finding_id": "finding:12",
    "kind": "path_diff",
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/wallet/descriptor_analyzer.cpp",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "diff --git a/src/wallet/descriptor_analyzer.cpp b/src/wallet/descriptor_analyzer.cpp\nindex cb3e443ec23..33ea2c5431d 100644\n--- a/src/wallet/descriptor_analyzer.cpp\n+++ b/src/wallet/descriptor_analyzer.cpp\n@@ -7,6 +7,7 @@\n #include <key.h>\n #include <pubkey.h>\n #include <script/descriptor.h>\n+#include <script/keyorigin.h>\n #include <script/signingprovider.h>\n #include <sync.h>\n #include <util/bip32.h>\n@@ -45,48 +46,71 @@ KeyMatch Best(KeyMatch a, KeyMatch b)\n     return KeyMatch::NOT_MINE;\n }\n \n+//! The wallet's HD keys, and the origins its descriptors give them.\n+struct HDKeys {\n+    CWallet::HDPubKeyMap keys;\n+    //! E.g. an account xprv imported with its master's origin.\n+    std::vector<std::pair<KeyOriginInfo, CExtPubKey>> origins;\n+};\n+\n+/** Match a key against what deriving `path` from the wallet's HD key `hd_key`\n+ *  gives. `same` tells whether an extended public key is the key. */\n+template <typename Same>\n+KeyMatch MatchPath(const CWallet& wallet, const CExtPubKey& hd_key, const std::set<DescriptorScriptPubKeyMan*>& spkms, const std::vector<uint32_t>& path, Same same)\n+    EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n+{\n+    // Only the descriptors with this key count, as in gethdkeys: the wallet\n+    // signs with each descriptor's own keys, so a private key held alone in\n+    // another descriptor can't sign for it.\n+    const bool has_private{HasPrivKey(spkms, hd_key.pubkey.GetID())};\n+    std::optional<CExtPubKey> derived;\n+    if (!HasHardenedDerivation(path)) {\n+        // Public derivation needs no private key, even when locked.\n+        derived = hd_key;\n+        for (const uint32_t step : path) {\n+            if (!derived->Derive(*derived, step)) return KeyMatch::NOT_MINE;\n+        }\n+    } else if (!has_private) {\n+        // Without the private key this candidate can't be derived; unlocking wouldn't help.\n+        return KeyMatch::NOT_MINE;\n+    } else if (wallet.IsLocked()) {\n+        return KeyMatch::UNKNOWN;\n+    } else if (const auto xprv{wallet.GetExtKey(hd_key)}) {\n+        // Decrypts only this candidate's key.\n+        if (const auto child{DeriveExtKey(*xprv, path)}) derived = child->first.Neuter();\n+    }\n+    if (derived && same(*derived)) return has_private ? KeyMatch::MINE : KeyMatch::WATCH_ONLY;\n+    return KeyMatch::NOT_MINE;\n+}\n+\n /** Match a key against the wallet's HD keys: the key is one of them, or\n- *  deriving `origin`'s path from the one with its fingerprint gives the key.\n- *  `same` tells whether an extended public key is the key. */\n+ *  deriving the rest of `origin`'s path from one of them gives the key. The\n+ *  path starts at the HD key with the origin's fingerprint, or after an origin\n+ *  the wallet's descriptors give an HD key. `same` tells whether an extended\n+ *  public key is the key. */\n template <typename Same>\n-KeyMatch MatchHDKeys(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys, const std::optional<KeyOriginInfo>& origin, Same same)\n+KeyMatch MatchHDKeys(const CWallet& wallet, const HDKeys& hd_keys, const std::optional<KeyOriginInfo>& origin, Same same)\n     EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n     KeyMatch result{KeyMatch::NOT_MINE};\n-    for (const auto& [hd_key, spkms] : hd_keys) {\n-        const bool has_private{HasPrivKey(spkms, hd_key.pubkey.GetID())};\n-        if (same(hd_key)) {\n-            result = Best(result, has_private ? KeyMatch::MINE : KeyMatch::WATCH_ONLY);\n-            continue;\n-        }\n-        if (!origin || origin->fingerprint != hd_key.id_key_fingerprint()) continue;\n-\n-        std::optional<CExtPubKey> derived;\n-        if (!HasHardenedDerivation(origin->path)) {\n-            // Public derivation needs no private key, even when locked.\n-            derived = hd_key;\n-            for (const uint32_t step : origin->path) {\n-                if (!derived->Derive(*derived, step)) {\n-                    derived.reset();\n-                    break;\n-                }\n-            }\n-        } else if (!has_private) {\n-            // Without the private key this candidate can't be derived; unlocking wouldn't help.\n-            continue;\n-        } else if (wallet.IsLocked()) {\n-            result = Best(result, KeyMatch::UNKNOWN);\n-            continue;\n-        } else if (const auto xprv{wallet.GetExtKey(hd_key)}) {\n-            // Decrypts only this candidate's key.\n-            if (const auto child{DeriveExtKey(*xprv, origin->path)}) derived = child->first.Neuter();\n-        }\n-        if (derived && same(*derived)) result = Best(result, has_private ? KeyMatch::MINE : KeyMatch::WATCH_ONLY);\n+    for (const auto& [hd_key, spkms] : hd_keys.keys) {\n+        result = Best(result, MatchPath(wallet, hd_key, spkms, {}, same));\n+        if (origin && origin->fingerprint == hd_key.id_key_fingerprint()) result = Best(result, MatchPath(wallet, hd_key, spkms, origin->path, same));\n+    }\n+    if (!origin) return result;\n+    for (const auto& [hd_origin, hd_key] : hd_keys.origins) {\n+        const auto& prefix{hd_origin.path};\n+        if (hd_origin.fingerprint != origin->fingerprint || origin->path.size() < prefix.size() ||\n+            !std::equal(prefix.begin(), prefix.end(), origin->path.begin())) continue;\n+        const auto it{hd_keys.keys.find(hd_key)};\n+        if (it == hd_keys.keys.end()) continue;\n+        const std::vector<uint32_t> rest(origin->path.begin() + prefix.size(), origin->path.end());\n+        result = Best(result, MatchPath(wallet, hd_key, it->second, rest, same));\n     }\n     return result;\n }\n \n-KeyMatch MatchExtKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys, const CExtPubKey& key, const std::optional<KeyOriginInfo>& origin)\n+KeyMatch MatchExtKey(const CWallet& wallet, const HDKeys& hd_keys, const CExtPubKey& key, const std::optional<KeyOriginInfo>& origin)\n     EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n     return MatchHDKeys(wallet, hd_keys, origin, [&](const CExtPubKey& candidate) { return SameKey(candidate, key); });\n@@ -96,7 +120,7 @@ KeyMatch MatchExtKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys,\n  *  from one of the wallet's HD keys, with the origin given in the descriptor\n  *  or the one the wallet recorded when it derived the key. A key the wallet\n  *  has derived is at least WATCH_ONLY. */\n-KeyMatch MatchConstKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_keys, const DescriptorKeyInfo::ConstKey& key,\n+KeyMatch MatchConstKey(const CWallet& wallet, const HDKeys& hd_keys, const DescriptorKeyInfo::ConstKey& key,\n                        const std::optional<KeyOriginInfo>& origin, DescriptorKeyInventory::Role role)\n     EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n@@ -129,17 +153,20 @@ KeyMatch MatchConstKey(const CWallet& wallet, const CWallet::HDPubKeyMap& hd_key\n }\n \n /** The wallet's HD keys, plus those it holds only as musig() participants,\n- *  which GetHDPubKeys() leaves out because they have no single key to list. */\n-CWallet::HDPubKeyMap WalletHDKeys(const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n+ *  which GetHDPubKeys() leaves out because they have no single key to list,\n+ *  and the origins its descriptors give them. */\n+HDKeys WalletHDKeys(const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n {\n-    CWallet::HDPubKeyMap hd_keys{wallet.GetHDPubKeys(CWallet::HDKeyFilter::All)};\n+    HDKeys hd_keys{.keys = wallet.GetHDPubKeys(CWallet::HDKeyFilter::All), .origins = {}};\n     for (auto* spkm : wallet.GetAllScriptPubKeyMans()) {\n         auto* desc_spkm{dynamic_cast<DescriptorScriptPubKeyMan*>(spkm)};\n         if (!desc_spkm) continue;\n         const auto inventory{WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->GetWalletDescriptor().descriptor->GetKeyInventory())};\n         for (const auto& occurrence : inventory.occurrences) {\n-            if (occurrence.role != DescriptorKeyInventory::Role::MUSIG_PARTICIPANT) continue;\n-            if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&occurrence.expression.key)}) hd_keys[key->root].insert(desc_spkm);\n+            const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&occurrence.expression.key)};\n+            if (!key) continue;\n+            if (occurrence.role == DescriptorKeyInventory::Role::MUSIG_PARTICIPANT) hd_keys.keys[key->root].insert(desc_spkm);\n+            if (const auto& origin{occurrence.expression.origin}) hd_keys.origins.emplace_back(*origin, key->root);\n         }\n     }\n     return hd_keys;\n@@ -149,10 +176,12 @@ std::optional<CTxDestination> FirstAddress(const Descriptor& descriptor, const S\n {\n     std::vector<CScript> scripts;\n     FlatSigningProvider out;\n-    if (!descriptor.Expand(/*pos=*/0, provider, scripts, out) || scripts.empty()) return std::nullopt;\n-    CTxDestination dest;\n-    if (!ExtractDestination(scripts.front(), dest)) return std::nullopt;\n-    return dest;\n+    if (!descriptor.Expand(/*pos=*/0, provider, scripts, out)) return std::nullopt;\n+    // The first script with an address, as deriveaddresses lists: combo() starts with P2PK, which has none.\n+    for (const CScript& script : scripts) {\n+        if (CTxDestination dest; ExtractDestination(script, dest)) return dest;\n+    }\n+    return std::nullopt;\n }\n \n } // namespace\n@@ -184,7 +213,7 @@ WalletDescriptorAnalysis AnalyzeDescriptor(const CWallet& wallet, std::span<cons\n     }\n \n     LOCK(wallet.cs_wallet);\n-    const CWallet::HDPubKeyMap hd_keys{WalletHDKeys(wallet)};\n+    const HDKeys hd_keys{WalletHDKeys(wallet)};\n     for (const auto& occurrence : result.analysis.policy.keys.occurrences) {\n         const auto& node{occurrence.expression};\n         if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) {\n",
    "truncated": false,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 230,
    "evidence_id": "d670897cb83d4575a6bd6f3bee93c14e",
    "finding_id": "finding:12",
    "kind": "new_source",
    "line": 105,
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/wallet/descriptor_analyzer.cpp",
    "revision": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "        const auto it{hd_keys.keys.find(hd_key)};\n        if (it == hd_keys.keys.end()) continue;\n        const std::vector<uint32_t> rest(origin->path.begin() + prefix.size(), origin->path.end());\n        result = Best(result, MatchPath(wallet, hd_key, it->second, rest, same));\n    }\n    return result;\n}\n\nKeyMatch MatchExtKey(const CWallet& wallet, const HDKeys& hd_keys, const CExtPubKey& key, const std::optional<KeyOriginInfo>& origin)\n    EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n{\n    return MatchHDKeys(wallet, hd_keys, origin, [&](const CExtPubKey& candidate) { return SameKey(candidate, key); });\n}\n\n/** Match a constant key: the wallet stores its private key, or it is derived\n *  from one of the wallet's HD keys, with the origin given in the descriptor\n *  or the one the wallet recorded when it derived the key. A key the wallet\n *  has derived is at least WATCH_ONLY. */\nKeyMatch MatchConstKey(const CWallet& wallet, const HDKeys& hd_keys, const DescriptorKeyInfo::ConstKey& key,\n                       const std::optional<KeyOriginInfo>& origin, DescriptorKeyInventory::Role role)\n    EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n{\n    // Taproot signing uses the x-only key, so either parity is the same key there,\n    // even when written as a full key.\n    using Role = DescriptorKeyInventory::Role;\n    const bool xonly{key.xonly || role == Role::TAPROOT_INTERNAL || role == Role::TAPROOT_OUTPUT || role == Role::TAPSCRIPT};\n    const std::vector<CPubKey> pubkeys{xonly ? XOnlyPubKey{key.pubkey}.GetCPubKeys() : std::vector<CPubKey>{key.pubkey}};\n    std::vector<KeyOriginInfo> origins;\n    if (origin) origins.push_back(*origin);\n    bool derived{false};\n    for (const auto* spkm : wallet.GetAllScriptPubKeyMans()) {\n        const auto* desc_spkm{dynamic_cast<const DescriptorScriptPubKeyMan*>(spkm)};\n        if (!desc_spkm) continue;\n        for (const CPubKey& pubkey : pubkeys) {\n            if (WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->HasPrivKey(pubkey.GetID()))) return KeyMatch::MINE;\n            if (auto recorded{desc_spkm->GetPubKeyOrigin(pubkey)}) {\n                derived = true;\n                origins.push_back(std::move(*recorded));\n            }\n        }\n    }\n\n    const auto same = [&](const CExtPubKey& candidate) {\n        return xonly ? XOnlyPubKey{candidate.pubkey} == XOnlyPubKey{key.pubkey} : candidate.pubkey == key.pubkey;\n    };\n    KeyMatch result{derived ? KeyMatch::WATCH_ONLY : KeyMatch::NOT_MINE};\n    for (const KeyOriginInfo& candidate : origins) result = Best(result, MatchHDKeys(wallet, hd_keys, candidate, same));\n    return result;\n}\n\n/** The wallet's HD keys, plus those it holds only as musig() participants,\n *  which GetHDPubKeys() leaves out because they have no single key to list,\n *  and the origins its descriptors give them. */\nHDKeys WalletHDKeys(const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)\n{\n    HDKeys hd_keys{.keys = wallet.GetHDPubKeys(CWallet::HDKeyFilter::All), .origins = {}};\n    for (auto* spkm : wallet.GetAllScriptPubKeyMans()) {\n        auto* desc_spkm{dynamic_cast<DescriptorScriptPubKeyMan*>(spkm)};\n        if (!desc_spkm) continue;\n        const auto inventory{WITH_LOCK(desc_spkm->cs_desc_man, return desc_spkm->GetWalletDescriptor().descriptor->GetKeyInventory())};\n        for (const auto& occurrence : inventory.occurrences) {\n            const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&occurrence.expression.key)};\n            if (!key) continue;\n            if (occurrence.role == DescriptorKeyInventory::Role::MUSIG_PARTICIPANT) hd_keys.keys[key->root].insert(desc_spkm);\n            if (const auto& origin{occurrence.expression.origin}) hd_keys.origins.emplace_back(*origin, key->root);\n        }\n    }\n    return hd_keys;\n}\n\nstd::optional<CTxDestination> FirstAddress(const Descriptor& descriptor, const SigningProvider& provider)\n{\n    std::vector<CScript> scripts;\n    FlatSigningProvider out;\n    if (!descriptor.Expand(/*pos=*/0, provider, scripts, out)) return std::nullopt;\n    // The first script with an address, as deriveaddresses lists: combo() starts with P2PK, which has none.\n    for (const CScript& script : scripts) {\n        if (CTxDestination dest; ExtractDestination(script, dest)) return dest;\n    }\n    return std::nullopt;\n}\n\n} // namespace\n\nstd::optional<bool> WalletDescriptorAnalysis::CanSign() const\n{\n    // MuSig aggregates are never MINE; their participants are matched instead.\n    bool unknown{false};\n    for (const KeyMatch match : keys) {\n        if (match == KeyMatch::MINE) return true;\n        unknown |= match == KeyMatch::UNKNOWN;\n    }\n    if (unknown) return std::nullopt;\n    return false;\n}\n\nWalletDescriptorAnalysis AnalyzeDescriptor(const CWallet& wallet, std::span<const std::unique_ptr<Descriptor>> descriptors, const SigningProvider& provider)\n{\n    WalletDescriptorAnalysis result;\n    result.analysis = AnalyzeDescriptor(descriptors);\n    if (descriptors.empty()) return result;\n    for (const auto& descriptor : descriptors) {\n        const auto address{FirstAddress(*descriptor, provider)};\n        if (!address) {\n            result.first_addresses.clear();\n            break;\n        }\n        result.first_addresses.push_back(*address);\n    }\n\n    LOCK(wallet.cs_wallet);\n    const HDKeys hd_keys{WalletHDKeys(wallet)};\n    for (const auto& occurrence : result.analysis.policy.keys.occurrences) {\n        const auto& node{occurrence.expression};\n        if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) {\n            result.keys.push_back(MatchExtKey(wallet, hd_keys, key->root, node.origin));\n        } else if (const auto* key{std::get_if<DescriptorKeyInfo::ConstKey>(&node.key)}) {\n            result.keys.push_back(MatchConstKey(wallet, hd_keys, *key, node.origin, occurrence.role));\n        } else {\n            result.keys.push_back(KeyMatch::NOT_MINE);\n        }\n    }\n    return result;\n}\n\n} // namespace wallet",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 0997b0116b82..386c55a4bfcb

2026-11-26T06:52:03Z · gpt-6-luna

bitcoin#36885The mixed UNKNOWN and MINE case is untestedsrc/wallet/test/wallet_interfaces_tests.cppaddressed
Assessment

The locked-wallet test now puts an UNKNOWN account-derived key before a MINE key in the same descriptor and asserts CanSign() is true while the wallet remains locked. This directly exercises the reported ordering case.

path_diff: src/wallet/test/wallet_interfaces_tests.cpp; new_source: src/wallet/test/wallet_interfaces_tests.cpp

[
  {
    "evidence_id": "a19a9bf702fc4d4590493bdca0078905",
    "finding_id": "finding:11",
    "kind": "path_diff",
    "new_head": "c2d5322d4238be81fcbeb317032e148134f16aad",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/wallet/test/wallet_interfaces_tests.cpp",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "diff --git a/src/wallet/test/wallet_interfaces_tests.cpp b/src/wallet/test/wallet_interfaces_tests.cpp\nindex d51421574be..8999d94af33 100644\n--- a/src/wallet/test/wallet_interfaces_tests.cpp\n+++ b/src/wallet/test/wallet_interfaces_tests.cpp\n@@ -200,6 +200,16 @@ BOOST_AUTO_TEST_CASE(analyzedescriptor)\n     BOOST_CHECK(result->CanSign() == true);\n     BOOST_CHECK_EQUAL(result->first_addresses.size(), 1U);\n \n+    // combo() starts with a P2PK script, which has no address: its first address is the P2PKH one.\n+    const auto first_key{Assert(DeriveExtKey(master, {0x80000030, 0x80000001, 0x80000000, 0x80000002, 0, 0}))};\n+    result = interface->analyzeDescriptor(\"combo(\" + mine + \"/0/*)\");\n+    BOOST_REQUIRE(result);\n+    BOOST_CHECK(result->first_addresses == std::vector<CTxDestination>({PKHash{first_key->first.Neuter().pubkey}}));\n+    // A P2PK script alone has no address.\n+    result = interface->analyzeDescriptor(\"pk(\" + mine + \"/0/*)\");\n+    BOOST_REQUIRE(result);\n+    BOOST_CHECK(result->first_addresses.empty());\n+\n     // Private keys in the descriptor derive the first address through hardened steps.\n     const CExtKey other{NewHDKey()};\n     result = interface->analyzeDescriptor(\"wpkh(\" + EncodeExtKey(other) + \"/84h/1h/0h/0/*)\");\n@@ -248,6 +258,12 @@ BOOST_AUTO_TEST_CASE(analyzedescriptor_wallet_locked)\n     BOOST_CHECK(result->CanSign() == true);\n     BOOST_CHECK(wallet->IsLocked());\n \n+    // One key it can't tell doesn't hide another that is the wallet's.\n+    result = interface->analyzeDescriptor(\"wsh(sortedmulti(1,\" + AccountKey(master) + \"/0/*,\" + OriginKey(master, {0, 1}) + \"/0/*))\");\n+    BOOST_REQUIRE(result);\n+    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::UNKNOWN, KeyMatch::MINE}));\n+    BOOST_CHECK(result->CanSign() == true);\n+\n     // The account xpub is also held without its private key, but the locked\n     // master may still hold it, so the key stays \"unknown\".\n     AddDescriptor(*wallet, \"wpkh(\" + AccountKey(master) + \"/0/*)\");\n@@ -310,6 +326,15 @@ BOOST_AUTO_TEST_CASE(analyzedescriptor_watch_only_and_constant_keys)\n     BOOST_REQUIRE(result);\n     BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::WATCH_ONLY}));\n     BOOST_CHECK(result->CanSign() == false);\n+\n+    // The watched xpub's private key, imported alone in another descriptor: the\n+    // wallet signs with each descriptor's own keys, and none has both the private\n+    // key and the chain code, so the xpub is still watch-only, as in gethdkeys.\n+    AddDescriptor(*wallet, \"pk(\" + EncodeSecret(watched_master.key) + \")\");\n+    result = interface->analyzeDescriptor(\"wsh(multi(1,\" + watched + \"/0/*))\");\n+    BOOST_REQUIRE(result);\n+    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::WATCH_ONLY}));\n+    BOOST_CHECK(result->CanSign() == false);\n }\n \n BOOST_AUTO_TEST_CASE(analyzedescriptor_derived_constant_keys)\n@@ -374,6 +399,44 @@ BOOST_AUTO_TEST_CASE(analyzedescriptor_derived_constant_keys)\n     BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE}));\n }\n \n+BOOST_AUTO_TEST_CASE(analyzedescriptor_account_keys)\n+{\n+    WalletContext context;\n+    context.args = &m_args;\n+    auto wallet = TestCreateWallet(context);\n+    auto interface = interfaces::MakeWallet(context, wallet);\n+\n+    // An account xprv imported with its master's origin, without the master.\n+    const CExtKey master{NewHDKey()};\n+    const std::vector<uint32_t> account_path{0x80000054, 0x80000001, 0x80000000};\n+    const CExtKey account{Assert(DeriveExtKey(master, account_path))->first};\n+    const std::string fingerprint{HexStr(master.Neuter().id_key_fingerprint())};\n+    AddDescriptor(*wallet, \"wpkh([\" + fingerprint + \"/84h/1h/0h]\" + EncodeExtKey(account) + \"/0/*)\");\n+    const auto key_at = [&](const std::vector<uint32_t>& path) { return Assert(DeriveExtKey(account, path))->first.Neuter(); };\n+\n+    // A key the wallet derived, matched through the origin it recorded, which starts at the master.\n+    auto result{interface->analyzeDescriptor(\"wpkh(\" + HexStr(key_at({0, 0}).pubkey) + \")\")};\n+    BOOST_REQUIRE(result);\n+    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE}));\n+    BOOST_CHECK(result->CanSign() == true);\n+\n+    // Keys with an origin below the account's: derived from the account key.\n+    const std::string later{\"[\" + fingerprint + \"/84h/1h/0h/0/5000]\" + HexStr(key_at({0, 5000}).pubkey)};\n+    const std::string child{\"[\" + fingerprint + \"/84h/1h/0h/0]\" + EncodeExtPubKey(key_at({0})) + \"/*\"};\n+    const std::string hardened{\"[\" + fingerprint + \"/84h/1h/0h/1h]\" + EncodeExtPubKey(key_at({0x80000001})) + \"/*\"};\n+    const std::string impostor{\"[\" + fingerprint + \"/84h/1h/0h/0/5000]\" + HexStr(GenerateRandomKey().GetPubKey())};\n+    result = interface->analyzeDescriptor(\"wsh(multi(1,\" + later + \",\" + child + \",\" + hardened + \",\" + impostor + \"))\");\n+    BOOST_REQUIRE(result);\n+    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE, KeyMatch::MINE, KeyMatch::MINE, KeyMatch::NOT_MINE}));\n+\n+    // Only the hardened step needs the private key.\n+    BOOST_REQUIRE(wallet->EncryptWallet(\"hunter2\"));\n+    BOOST_REQUIRE(wallet->Lock());\n+    result = interface->analyzeDescriptor(\"wsh(multi(1,\" + later + \",\" + child + \",\" + hardened + \",\" + impostor + \"))\");\n+    BOOST_REQUIRE(result);\n+    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE, KeyMatch::MINE, KeyMatch::UNKNOWN, KeyMatch::NOT_MINE}));\n+}\n+\n BOOST_AUTO_TEST_CASE(analyzedescriptor_musig_only_keys)\n {\n     WalletContext context;\n",
    "truncated": false,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 367,
    "evidence_id": "2b0c2b7e68344514873c69dd8911b683",
    "finding_id": "finding:11",
    "kind": "new_source",
    "line": 218,
    "new_head": "c2d5322d4238be81fcbeb317032e148134f16aad",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/wallet/test/wallet_interfaces_tests.cpp",
    "revision": "c2d5322d4238be81fcbeb317032e148134f16aad",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "    BOOST_CHECK(result->first_addresses == std::vector<CTxDestination>({WitnessV0KeyHash{receive_key->first.Neuter().pubkey}}));\n\n    // Without the private key, the hardened steps can't be derived.\n    result = interface->analyzeDescriptor(\"wpkh(\" + EncodeExtPubKey(other.Neuter()) + \"/84h/1h/0h/0/*)\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->first_addresses.empty());\n\n    result = interface->analyzeDescriptor(\"wsh(sortedmulti(2,\");\n    BOOST_REQUIRE(!result);\n    BOOST_CHECK(result.error().code == WalletErrorCode::GenericError);\n}\n\nBOOST_AUTO_TEST_CASE(analyzedescriptor_wallet_locked)\n{\n    WalletContext context;\n    context.args = &m_args;\n    auto wallet = TestCreateWallet(context);\n    auto interface = interfaces::MakeWallet(context, wallet);\n    const CExtKey master{NewHDKey()};\n    BOOST_REQUIRE(interface->addHDKey(master));\n    BOOST_REQUIRE(wallet->EncryptWallet(\"hunter2\"));\n    BOOST_REQUIRE(wallet->Lock());\n\n    // Deriving a hardened path needs the private key: a locked wallet can't tell.\n    const std::string derived{\"wsh(sortedmulti(2,\" + AccountKey(master) + R + \",\" + AccountKey(NewHDKey()) + R + \"))\"};\n    auto result{interface->analyzeDescriptor(derived)};\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::UNKNOWN, KeyMatch::NOT_MINE}));\n    BOOST_CHECK(result->CanSign() == std::nullopt);\n\n    // The HD key itself is found without decrypting anything.\n    result = interface->analyzeDescriptor(\"wsh(sortedmulti(1,\" + EncodeExtPubKey(master.Neuter()) + \"/0/*,\" + AccountKey(NewHDKey()) + \"/0/*))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE, KeyMatch::NOT_MINE}));\n    BOOST_CHECK(wallet->IsLocked());\n\n    // So is a key with an unhardened origin path: public derivation needs no private key.\n    result = interface->analyzeDescriptor(\"wsh(sortedmulti(1,\" + OriginKey(master, {0, 1}) + \"/0/*,\" + AccountKey(NewHDKey()) + \"/0/*))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE, KeyMatch::NOT_MINE}));\n    BOOST_CHECK(result->CanSign() == true);\n    BOOST_CHECK(wallet->IsLocked());\n\n    // One key it can't tell doesn't hide another that is the wallet's.\n    result = interface->analyzeDescriptor(\"wsh(sortedmulti(1,\" + AccountKey(master) + \"/0/*,\" + OriginKey(master, {0, 1}) + \"/0/*))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::UNKNOWN, KeyMatch::MINE}));\n    BOOST_CHECK(result->CanSign() == true);\n\n    // The account xpub is also held without its private key, but the locked\n    // master may still hold it, so the key stays \"unknown\".\n    AddDescriptor(*wallet, \"wpkh(\" + AccountKey(master) + \"/0/*)\");\n    result = interface->analyzeDescriptor(derived);\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::UNKNOWN, KeyMatch::NOT_MINE}));\n    BOOST_CHECK(result->CanSign() == std::nullopt);\n\n    BOOST_REQUIRE(wallet->Unlock(\"hunter2\"));\n    result = interface->analyzeDescriptor(derived);\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE, KeyMatch::NOT_MINE}));\n    BOOST_CHECK(result->CanSign() == true);\n}\n\nBOOST_AUTO_TEST_CASE(analyzedescriptor_watch_only_and_constant_keys)\n{\n    WalletContext context;\n    context.args = &m_args;\n    auto wallet = TestCreateWallet(context);\n    auto interface = interfaces::MakeWallet(context, wallet);\n\n    // An xpub the wallet has without its private key.\n    const CExtKey watched_master{NewHDKey()};\n    const std::string watched{EncodeExtPubKey(watched_master.Neuter())};\n    AddDescriptor(*wallet, \"wpkh(\" + watched + \"/0/*)\");\n\n    // A private key whose public key has an odd Y: its x-only form must still match.\n    const CKey key{OddKey()};\n    AddKey(*wallet, key);\n\n    const std::string desc{\"tr(\" + HexStr(XOnlyPubKey::NUMS_H) + \",multi_a(1,\" + watched + \"/0/*,\" + HexStr(XOnlyPubKey{key.GetPubKey()}) + \"))\"};\n    auto result{interface->analyzeDescriptor(desc)};\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::NOT_MINE, KeyMatch::WATCH_ONLY, KeyMatch::MINE}));\n    // A constant cosigner key makes the setup unrecognized, but the wallet can still sign with it.\n    BOOST_CHECK(!result->analysis.IsRecognized());\n    BOOST_CHECK(result->CanSign() == true);\n\n    // In Taproot the even-Y full key is the same key; for ECDSA it is not.\n    const std::string even{\"02\" + HexStr(XOnlyPubKey{key.GetPubKey()})};\n    result = interface->analyzeDescriptor(\"tr(\" + HexStr(XOnlyPubKey::NUMS_H) + \",multi_a(1,\" + even + \"))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::NOT_MINE, KeyMatch::MINE}));\n    result = interface->analyzeDescriptor(\"wsh(multi(1,\" + even + \"))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::NOT_MINE}));\n\n    // Deriving a hardened origin path from a watched xpub is impossible even\n    // when unlocked, so the key is not \"unknown\" and doesn't hide can_sign.\n    result = interface->analyzeDescriptor(\"wsh(sortedmulti(1,\" + AccountKey(watched_master) + \"/0/*,\" + AccountKey(NewHDKey()) + \"/0/*))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::NOT_MINE, KeyMatch::NOT_MINE}));\n    BOOST_CHECK(result->CanSign() == false);\n\n    // A plain public key the wallet has without its private key.\n    const std::string watched_key{HexStr(GenerateRandomKey().GetPubKey())};\n    AddDescriptor(*wallet, \"wpkh(\" + watched_key + \")\");\n    result = interface->analyzeDescriptor(\"wsh(multi(1,\" + watched_key + \"))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::WATCH_ONLY}));\n    BOOST_CHECK(result->CanSign() == false);\n\n    // The watched xpub's private key, imported alone in another descriptor: the\n    // wallet signs with each descriptor's own keys, and none has both the private\n    // key and the chain code, so the xpub is still watch-only, as in gethdkeys.\n    AddDescriptor(*wallet, \"pk(\" + EncodeSecret(watched_master.key) + \")\");\n    result = interface->analyzeDescriptor(\"wsh(multi(1,\" + watched + \"/0/*))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::WATCH_ONLY}));\n    BOOST_CHECK(result->CanSign() == false);\n}\n\nBOOST_AUTO_TEST_CASE(analyzedescriptor_derived_constant_keys)\n{\n    WalletContext context;\n    context.args = &m_args;\n    auto wallet = TestCreateWallet(context);\n    auto interface = interfaces::MakeWallet(context, wallet);\n\n    // The wallet derives receive keys from its HD key, so it stores no private\n    // key for them, only where it derived them.\n    const CExtKey master{NewHDKey()};\n    AddDescriptor(*wallet, \"wpkh(\" + EncodeExtKey(master) + \"/84h/1h/0h/0/*)\");\n    const auto receive_key = [&](uint32_t index) {\n        return HexStr(Assert(DeriveExtKey(master, {0x80000054, 0x80000001, 0x80000000, 0, index}))->first.Neuter().pubkey);\n    };\n    const std::string mine{receive_key(0)};\n    const std::string other{HexStr(GenerateRandomKey().GetPubKey())};\n\n    auto result{interface->analyzeDescriptor(\"wpkh(\" + mine + \")\")};\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE}));\n    BOOST_CHECK(result->CanSign() == true);\n    result = interface->analyzeDescriptor(\"wsh(multi(1,\" + mine + \",\" + other + \"))\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE, KeyMatch::NOT_MINE}));\n    // In Taproot, as an x-only key.\n    result = interface->analyzeDescriptor(\"tr(\" + mine.substr(2) + \")\");\n    BOOST_REQUIRE(result);\n    BOOST_CHECK(result->keys == std::vector<KeyMatch>({KeyMatch::MINE}));",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 0997b0116b82..c2d5322d4238

2026-11-26T04:13:37Z · gpt-6-luna

bitcoin#36885Shared origin fingerprints receive no setup advisorysrc/script/descriptor_analyzer.cppstill_present
Assessment

The new repeated-key logic remains based on root keys, derived keys, and direct-child derivation. No shared-origin-fingerprint warning is added, and no distinct advisory field appears in the supplied evidence.

path_diff: src/script/descriptor_analyzer.cpp; new_source: src/script/descriptor_analyzer.cpp

[
  {
    "evidence_id": "2a5786bccc0a410683807ff549f70ef6",
    "finding_id": "finding:10",
    "kind": "path_diff",
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/script/descriptor_analyzer.cpp",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "diff --git a/src/script/descriptor_analyzer.cpp b/src/script/descriptor_analyzer.cpp\nindex 7958f6792cc..f7c893485cd 100644\n--- a/src/script/descriptor_analyzer.cpp\n+++ b/src/script/descriptor_analyzer.cpp\n@@ -13,9 +13,11 @@\n #include <algorithm>\n #include <array>\n #include <cstddef>\n+#include <limits>\n+#include <map>\n #include <numeric>\n #include <optional>\n-#include <ranges>\n+#include <set>\n #include <utility>\n #include <variant>\n #include <vector>\n@@ -82,13 +84,16 @@ std::optional<XOnlyPubKey> DeriveFirstKey(const DescriptorKeyInfo::BIP32Key& key\n     return XOnlyPubKey{derived.pubkey};\n }\n \n-/** Check that every cosigner slot can derive addresses on its own. */\n+/** Check that every cosigner slot can derive addresses on its own, and that\n+ *  someone can sign for it. */\n void CheckCosignerKeys(DescriptorAnalysis& result)\n {\n     for (const size_t id : result.cosigners) {\n         const auto& node{result.policy.keys.occurrences.at(id).expression};\n         const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)};\n-        if (!key) {\n+        if (RootKey(node) == XOnlyPubKey::NUMS_H) {\n+            result.issues.push_back({IssueKind::UNSPENDABLE_KEY, {id}});\n+        } else if (!key) {\n             result.issues.push_back({IssueKind::NOT_EXTENDED_KEY, {id}});\n         } else if (NeedsPrivateDerivation(*key)) {\n             result.issues.push_back({IssueKind::HARDENED_DERIVATION, {id}});\n@@ -109,29 +114,65 @@ std::optional<XOnlyPubKey> FirstDerivedKey(const DescriptorKeyInfo::Node& node)\n     return DeriveFirstKey(*key);\n }\n \n-/** Group the indices below `count` that `linked` connects, directly or through\n- *  a chain of links. Each group is in index order, listed by its first index. */\n-template <typename Linked>\n-std::vector<std::vector<size_t>> LinkedGroups(size_t count, Linked linked)\n+/** Indices below a count, grouped by links: two indices are in one group if\n+ *  a chain of links connects them. */\n+class LinkedGroups\n {\n-    // Each index points to an earlier index of its group, the first one pointing to itself.\n-    std::vector<size_t> parent(count);\n-    std::iota(parent.begin(), parent.end(), size_t{0});\n-    const auto first_of = [&](size_t i) {\n-        while (parent[i] != i) i = parent[i];\n+    //! Each index points to an earlier index of its group, the first one pointing to itself.\n+    std::vector<size_t> m_parent;\n+\n+public:\n+    explicit LinkedGroups(size_t count) : m_parent(count)\n+    {\n+        std::iota(m_parent.begin(), m_parent.end(), size_t{0});\n+    }\n+\n+    //! The first index of `i`'s group.\n+    size_t First(size_t i)\n+    {\n+        // Point each index visited to its grandparent, keeping later searches short.\n+        while (m_parent[i] != i) i = m_parent[i] = m_parent[m_parent[i]];\n         return i;\n-    };\n-    for (size_t i{0}; i < count; ++i) {\n-        for (size_t j{i + 1}; j < count; ++j) {\n-            if (!linked(i, j)) continue;\n-            const size_t a{first_of(i)}, b{first_of(j)};\n-            parent[std::max(a, b)] = std::min(a, b);\n+    }\n+\n+    void Link(size_t i, size_t j)\n+    {\n+        const size_t a{First(i)}, b{First(j)};\n+        m_parent[std::max(a, b)] = std::min(a, b);\n+    }\n+\n+    //! Link the indices with equal values. A missing value links nothing.\n+    template <typename T>\n+    void LinkEqual(const std::vector<std::optional<T>>& values)\n+    {\n+        std::map<T, size_t> first;\n+        for (size_t i{0}; i < values.size(); ++i) {\n+            if (!values[i]) continue;\n+            const auto [it, inserted]{first.try_emplace(*values[i], i)};\n+            if (!inserted) Link(it->second, i);\n         }\n     }\n-    std::vector<std::vector<size_t>> groups(count);\n-    for (size_t i{0}; i < count; ++i) groups[first_of(i)].push_back(i);\n-    std::erase_if(groups, [](const auto& group) { return group.empty(); });\n-    return groups;\n+\n+    //! Groups of at least two indices, each in index order, listed by its first index.\n+    std::vector<std::vector<size_t>> Repeated()\n+    {\n+        std::vector<std::vector<size_t>> groups(m_parent.size());\n+        for (size_t i{0}; i < m_parent.size(); ++i) groups[First(i)].push_back(i);\n+        std::erase_if(groups, [](const auto& group) { return group.size() < 2; });\n+        return groups;\n+    }\n+};\n+\n+/** Report each group of `groups` as one REPEATED_KEY issue, with the occurrence\n+ *  IDs `ids` gives for its indices. */\n+void ReportRepeated(DescriptorAnalysis& result, LinkedGroups& groups, const std::vector<size_t>& ids)\n+{\n+    for (const auto& group : groups.Repeated()) {\n+        std::vector<size_t> keys;\n+        keys.reserve(group.size());\n+        for (const size_t i : group) keys.push_back(ids[i]);\n+        result.issues.push_back({IssueKind::REPEATED_KEY, std::move(keys)});\n+    }\n }\n \n /** Report every group of cosigner slots held by the same key: slots that share\n@@ -153,17 +194,32 @@ void CheckRepeatedKeys(DescriptorAnalysis& result)\n         derived.push_back(FirstDerivedKey(node));\n         ext_roots.push_back(RootExtKey(node));\n     }\n-    const auto same_holder = [&](size_t i, size_t j) {\n-        if ((roots[i] && roots[i] == roots[j]) || (derived[i] && derived[i] == derived[j])) return true;\n-        return ext_roots[i] && ext_roots[j] && (IsDirectChild(*ext_roots[i], *ext_roots[j]) || IsDirectChild(*ext_roots[j], *ext_roots[i]));\n-    };\n-    for (const auto& group : LinkedGroups(count, same_holder)) {\n-        if (group.size() < 2) continue;\n-        std::vector<size_t> ids;\n-        ids.reserve(group.size());\n-        for (const size_t i : group) ids.push_back(result.cosigners[i]);\n-        result.issues.push_back({IssueKind::REPEATED_KEY, std::move(ids)});\n+    LinkedGroups groups{count};\n+    groups.LinkEqual(roots);\n+    groups.LinkEqual(derived);\n+\n+    // Only an xpub whose fingerprint a child names can be its parent, so a\n+    // child is derived again only from those, and not when the two slots are\n+    // already in one group. Xpubs sharing a root key are one group already, and\n+    // can share a fingerprint with any number of chain codes, so only the first\n+    // of them is a candidate parent: a child of a later one is left out of the\n+    // group, which is reported either way.\n+    std::multimap<KeyFingerprint, size_t> by_fingerprint;\n+    std::set<XOnlyPubKey> parent_roots;\n+    for (size_t i{0}; i < count; ++i) {\n+        if (ext_roots[i] && parent_roots.insert(*roots[i]).second) by_fingerprint.emplace(ext_roots[i]->id_key_fingerprint(), i);\n     }\n+    for (size_t child{0}; child < count; ++child) {\n+        if (!ext_roots[child]) continue;\n+        const auto [begin, end]{by_fingerprint.equal_range(ext_roots[child]->fingerprint)};\n+        for (auto it{begin}; it != end; ++it) {\n+            const size_t parent{it->second};\n+            if (groups.First(parent) != groups.First(child) && IsDirectChild(*ext_roots[parent], *ext_roots[child])) {\n+                groups.Link(parent, child);\n+            }\n+        }\n+    }\n+    ReportRepeated(result, groups, result.cosigners);\n }\n \n /** Check that every cosigner can derive each participant of a musig()\n@@ -192,16 +248,23 @@ void CheckMuSigParticipants(DescriptorAnalysis& result, size_t internal_id)\n             result.issues.push_back({IssueKind::NOT_DERIVABLE, {id}});\n         }\n     }\n-    const auto same_key = [&](size_t i, size_t j) {\n-        return (roots[i] && roots[i] == roots[j]) || (derived[i] && derived[i] == derived[j]);\n-    };\n-    for (const auto& group : LinkedGroups(participants.size(), same_key)) {\n-        if (group.size() < 2) continue;\n-        std::vector<size_t> ids;\n-        ids.reserve(group.size());\n-        for (const size_t i : group) ids.push_back(participants[i]);\n-        result.issues.push_back({IssueKind::REPEATED_KEY, std::move(ids)});\n+    LinkedGroups groups{participants.size()};\n+    groups.LinkEqual(roots);\n+    groups.LinkEqual(derived);\n+    ReportRepeated(result, groups, participants);\n+}\n+\n+/** Whether a NUMS or musig() internal key can derive its first key. Deriving\n+ *  fails past the maximum BIP32 depth, and a musig() aggregate starts as an\n+ *  xpub at depth 0. */\n+bool CanDeriveInternalKey(const DescriptorKeyInfo::Node& node)\n+{\n+    if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) return DeriveFirstKey(*key).has_value();\n+    if (const auto* key{std::get_if<DescriptorKeyInfo::MuSigKey>(&node.key)}) {\n+        const bool ranged{key->derivation.type == DescriptorKeyInfo::DeriveType::UNHARDENED_RANGED};\n+        return key->derivation.path.size() + (ranged ? 1 : 0) <= std::numeric_limits<unsigned char>::max();\n     }\n+    return true;\n }\n \n /** Classify the Taproot internal key against the cosigners of the leaf, or\n@@ -224,16 +287,16 @@ std::optional<DescriptorAnalysis::KeyPath> ClassifyKeyPath(const DescriptorAnaly\n     if (const auto* key{std::get_if<DescriptorKeyInfo::MuSigKey>(&internal.key)}) {\n         // Any `threshold` cosigners can already spend through the leaf, so an\n         // aggregate of at least that many distinct cosigners adds no new way to spend.\n-        std::vector<XOnlyPubKey> cosigner_roots;\n+        std::set<XOnlyPubKey> cosigner_roots;\n         for (const size_t id : result.cosigners) {\n-            if (const auto root{RootKey(occurrences.at(id).expression)}) cosigner_roots.push_back(*root);\n+            if (const auto root{RootKey(occurrences.at(id).expression)}) cosigner_roots.insert(*root);\n         }\n-        std::vector<XOnlyPubKey> participants;\n+        // A repeated participant adds no cosigner.\n+        std::set<XOnlyPubKey> participants;\n         for (const size_t id : key->participants) {\n             const auto root{RootKey(occurrences.at(id).expression)};\n-            if (!root || std::ranges::find(cosigner_roots, *root) == cosigner_roots.end()) return std::nullopt;\n-            // A repeated participant adds no cosigner.\n-            if (std::ranges::find(participants, *root) == participants.end()) participants.push_back(*root);\n+            if (!root || !cosigner_roots.contains(*root)) return std::nullopt;\n+            participants.insert(*root);\n         }\n         if (participants.size() >= result.threshold) return DescriptorAnalysis::KeyPath::MUSIG;\n     }\n@@ -299,6 +362,9 @@ DescriptorAnalysis AnalyzeDescriptor(const Descriptor& descriptor)\n         CheckMuSigParticipants(result, internal_id);\n         if (const auto key_path{ClassifyKeyPath(result, internal_id)}) {\n             result.key_path = *key_path;\n+            if (!CanDeriveInternalKey(result.policy.keys.occurrences.at(internal_id).expression)) {\n+                result.issues.push_back({IssueKind::NOT_DERIVABLE, {internal_id}});\n+            }\n         } else {\n             result.issues.push_back({IssueKind::KEY_PATH_SPENDABLE, {internal_id}});\n         }\n@@ -321,14 +387,19 @@ DescriptorAnalysis AnalyzeDescriptor(std::span<const std::unique_ptr<Descriptor>\n         for (const size_t id : analysis.cosigners) roots.push_back(RootKey(analysis.policy.keys.occurrences.at(id).expression));\n         return roots;\n     };\n+    // The branches share their key IDs, so each issue is reported once,\n+    // whichever branch it comes from.\n+    std::set<DescriptorAnalysis::Issue> seen(first.issues.begin(), first.issues.end());\n+    bool differ{false};\n     for (const auto& descriptor : descriptors.subspan(1)) {\n         const DescriptorAnalysis other{AnalyzeDescriptor(*descriptor)};\n-        if (other.shape != first.shape || other.sorted != first.sorted || other.key_path != first.key_path ||\n-            other.threshold != first.threshold || cosigner_roots(other) != cosigner_roots(first)) {\n-            Unrecognize(first);\n-            first.issues.push_back({DescriptorAnalysis::Issue::Kind::BRANCHES_DIFFER, {}});\n-            break;\n+        differ |= other.shape != first.shape || other.sorted != first.sorted || other.key_path != first.key_path ||\n+                  other.threshold != first.threshold || cosigner_roots(other) != cosigner_roots(first);\n+        for (const auto& issue : other.issues) {\n+            if (seen.insert(issue).second) first.issues.push_back(issue);\n         }\n     }\n+    if (differ) first.issues.push_back({IssueKind::BRANCHES_DIFFER, {}});\n+    if (!first.issues.empty()) Unrecognize(first);\n     return first;\n }\n",
    "truncated": false,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 276,
    "evidence_id": "d1189a5a24c04355a59ce0d7f299b302",
    "finding_id": "finding:10",
    "kind": "new_source",
    "line": 127,
    "new_head": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/script/descriptor_analyzer.cpp",
    "revision": "386c55a4bfcb47a49320ec928b86aedf25101a02",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "        std::iota(m_parent.begin(), m_parent.end(), size_t{0});\n    }\n\n    //! The first index of `i`'s group.\n    size_t First(size_t i)\n    {\n        // Point each index visited to its grandparent, keeping later searches short.\n        while (m_parent[i] != i) i = m_parent[i] = m_parent[m_parent[i]];\n        return i;\n    }\n\n    void Link(size_t i, size_t j)\n    {\n        const size_t a{First(i)}, b{First(j)};\n        m_parent[std::max(a, b)] = std::min(a, b);\n    }\n\n    //! Link the indices with equal values. A missing value links nothing.\n    template <typename T>\n    void LinkEqual(const std::vector<std::optional<T>>& values)\n    {\n        std::map<T, size_t> first;\n        for (size_t i{0}; i < values.size(); ++i) {\n            if (!values[i]) continue;\n            const auto [it, inserted]{first.try_emplace(*values[i], i)};\n            if (!inserted) Link(it->second, i);\n        }\n    }\n\n    //! Groups of at least two indices, each in index order, listed by its first index.\n    std::vector<std::vector<size_t>> Repeated()\n    {\n        std::vector<std::vector<size_t>> groups(m_parent.size());\n        for (size_t i{0}; i < m_parent.size(); ++i) groups[First(i)].push_back(i);\n        std::erase_if(groups, [](const auto& group) { return group.size() < 2; });\n        return groups;\n    }\n};\n\n/** Report each group of `groups` as one REPEATED_KEY issue, with the occurrence\n *  IDs `ids` gives for its indices. */\nvoid ReportRepeated(DescriptorAnalysis& result, LinkedGroups& groups, const std::vector<size_t>& ids)\n{\n    for (const auto& group : groups.Repeated()) {\n        std::vector<size_t> keys;\n        keys.reserve(group.size());\n        for (const size_t i : group) keys.push_back(ids[i]);\n        result.issues.push_back({IssueKind::REPEATED_KEY, std::move(keys)});\n    }\n}\n\n/** Report every group of cosigner slots held by the same key: slots that share\n *  a root key (e.g. the same xpub with two paths), that derive the same key, or\n *  where one xpub is the direct child of another. Slots linked through a chain\n *  of these are one group. */\nvoid CheckRepeatedKeys(DescriptorAnalysis& result)\n{\n    const auto& occurrences{result.policy.keys.occurrences};\n    const size_t count{result.cosigners.size()};\n    std::vector<std::optional<XOnlyPubKey>> roots, derived;\n    std::vector<const CExtPubKey*> ext_roots;\n    roots.reserve(count);\n    derived.reserve(count);\n    ext_roots.reserve(count);\n    for (const size_t id : result.cosigners) {\n        const auto& node{occurrences.at(id).expression};\n        roots.push_back(RootKey(node));\n        derived.push_back(FirstDerivedKey(node));\n        ext_roots.push_back(RootExtKey(node));\n    }\n    LinkedGroups groups{count};\n    groups.LinkEqual(roots);\n    groups.LinkEqual(derived);\n\n    // Only an xpub whose fingerprint a child names can be its parent, so a\n    // child is derived again only from those, and not when the two slots are\n    // already in one group. Xpubs sharing a root key are one group already, and\n    // can share a fingerprint with any number of chain codes, so only the first\n    // of them is a candidate parent: a child of a later one is left out of the\n    // group, which is reported either way.\n    std::multimap<KeyFingerprint, size_t> by_fingerprint;\n    std::set<XOnlyPubKey> parent_roots;\n    for (size_t i{0}; i < count; ++i) {\n        if (ext_roots[i] && parent_roots.insert(*roots[i]).second) by_fingerprint.emplace(ext_roots[i]->id_key_fingerprint(), i);\n    }\n    for (size_t child{0}; child < count; ++child) {\n        if (!ext_roots[child]) continue;\n        const auto [begin, end]{by_fingerprint.equal_range(ext_roots[child]->fingerprint)};\n        for (auto it{begin}; it != end; ++it) {\n            const size_t parent{it->second};\n            if (groups.First(parent) != groups.First(child) && IsDirectChild(*ext_roots[parent], *ext_roots[child])) {\n                groups.Link(parent, child);\n            }\n        }\n    }\n    ReportRepeated(result, groups, result.cosigners);\n}\n\n/** Check that every cosigner can derive each participant of a musig()\n *  internal key, and that no participant is repeated: participants with the\n *  same root key, or that derive the same key, are one. */\nvoid CheckMuSigParticipants(DescriptorAnalysis& result, size_t internal_id)\n{\n    const auto& occurrences{result.policy.keys.occurrences};\n    const auto* musig{std::get_if<DescriptorKeyInfo::MuSigKey>(&occurrences.at(internal_id).expression.key)};\n    if (!musig) return;\n    const auto& participants{musig->participants};\n    std::vector<std::optional<XOnlyPubKey>> roots, derived;\n    roots.reserve(participants.size());\n    derived.reserve(participants.size());\n    for (const size_t id : participants) {\n        const auto& participant{occurrences.at(id).expression};\n        roots.push_back(RootKey(participant));\n        derived.push_back(roots.back());\n        const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&participant.key)};\n        if (!key) continue;\n        derived.back() = DeriveFirstKey(*key);\n        if (NeedsPrivateDerivation(*key)) {\n            // Other cosigners couldn't derive the key path.\n            result.issues.push_back({IssueKind::HARDENED_DERIVATION, {id}});\n        } else if (!derived.back()) {\n            result.issues.push_back({IssueKind::NOT_DERIVABLE, {id}});\n        }\n    }\n    LinkedGroups groups{participants.size()};\n    groups.LinkEqual(roots);\n    groups.LinkEqual(derived);\n    ReportRepeated(result, groups, participants);\n}\n\n/** Whether a NUMS or musig() internal key can derive its first key. Deriving\n *  fails past the maximum BIP32 depth, and a musig() aggregate starts as an\n *  xpub at depth 0. */\nbool CanDeriveInternalKey(const DescriptorKeyInfo::Node& node)\n{\n    if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) return DeriveFirstKey(*key).has_value();\n    if (const auto* key{std::get_if<DescriptorKeyInfo::MuSigKey>(&node.key)}) {\n        const bool ranged{key->derivation.type == DescriptorKeyInfo::DeriveType::UNHARDENED_RANGED};\n        return key->derivation.path.size() + (ranged ? 1 : 0) <= std::numeric_limits<unsigned char>::max();\n    }\n    return true;\n}\n\n/** Classify the Taproot internal key against the cosigners of the leaf, or\n *  nullopt if it may let fewer than `threshold` cosigners spend. */\nstd::optional<DescriptorAnalysis::KeyPath> ClassifyKeyPath(const DescriptorAnalysis& result, size_t internal_id)\n{\n    const auto& occurrences{result.policy.keys.occurrences};\n    const auto& internal{occurrences.at(internal_id).expression};\n",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 0997b0116b82..386c55a4bfcb

2026-11-26T06:52:03Z · gpt-6-luna

bitcoin#36885NUMS-rooted xpubs pass the cosigner checkssrc/script/descriptor_analyzer.cppaddressed
Assessment

CheckCosignerKeys now reports UNSPENDABLE_KEY for a cosigner whose root key is NUMS, including the NUMS-rooted extended-key case. The change supplies the issue with the affected occurrence ID, preventing recognition through the later issue-based validation.

path_diff: src/script/descriptor_analyzer.cpp; new_source: src/script/descriptor_analyzer.cpp

[
  {
    "evidence_id": "fc4e584cab084e889b77639a5b1882a7",
    "finding_id": "finding:1",
    "kind": "path_diff",
    "new_head": "c2d5322d4238be81fcbeb317032e148134f16aad",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/script/descriptor_analyzer.cpp",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "diff --git a/src/script/descriptor_analyzer.cpp b/src/script/descriptor_analyzer.cpp\nindex 7958f6792cc..f7c893485cd 100644\n--- a/src/script/descriptor_analyzer.cpp\n+++ b/src/script/descriptor_analyzer.cpp\n@@ -13,9 +13,11 @@\n #include <algorithm>\n #include <array>\n #include <cstddef>\n+#include <limits>\n+#include <map>\n #include <numeric>\n #include <optional>\n-#include <ranges>\n+#include <set>\n #include <utility>\n #include <variant>\n #include <vector>\n@@ -82,13 +84,16 @@ std::optional<XOnlyPubKey> DeriveFirstKey(const DescriptorKeyInfo::BIP32Key& key\n     return XOnlyPubKey{derived.pubkey};\n }\n \n-/** Check that every cosigner slot can derive addresses on its own. */\n+/** Check that every cosigner slot can derive addresses on its own, and that\n+ *  someone can sign for it. */\n void CheckCosignerKeys(DescriptorAnalysis& result)\n {\n     for (const size_t id : result.cosigners) {\n         const auto& node{result.policy.keys.occurrences.at(id).expression};\n         const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)};\n-        if (!key) {\n+        if (RootKey(node) == XOnlyPubKey::NUMS_H) {\n+            result.issues.push_back({IssueKind::UNSPENDABLE_KEY, {id}});\n+        } else if (!key) {\n             result.issues.push_back({IssueKind::NOT_EXTENDED_KEY, {id}});\n         } else if (NeedsPrivateDerivation(*key)) {\n             result.issues.push_back({IssueKind::HARDENED_DERIVATION, {id}});\n@@ -109,29 +114,65 @@ std::optional<XOnlyPubKey> FirstDerivedKey(const DescriptorKeyInfo::Node& node)\n     return DeriveFirstKey(*key);\n }\n \n-/** Group the indices below `count` that `linked` connects, directly or through\n- *  a chain of links. Each group is in index order, listed by its first index. */\n-template <typename Linked>\n-std::vector<std::vector<size_t>> LinkedGroups(size_t count, Linked linked)\n+/** Indices below a count, grouped by links: two indices are in one group if\n+ *  a chain of links connects them. */\n+class LinkedGroups\n {\n-    // Each index points to an earlier index of its group, the first one pointing to itself.\n-    std::vector<size_t> parent(count);\n-    std::iota(parent.begin(), parent.end(), size_t{0});\n-    const auto first_of = [&](size_t i) {\n-        while (parent[i] != i) i = parent[i];\n+    //! Each index points to an earlier index of its group, the first one pointing to itself.\n+    std::vector<size_t> m_parent;\n+\n+public:\n+    explicit LinkedGroups(size_t count) : m_parent(count)\n+    {\n+        std::iota(m_parent.begin(), m_parent.end(), size_t{0});\n+    }\n+\n+    //! The first index of `i`'s group.\n+    size_t First(size_t i)\n+    {\n+        // Point each index visited to its grandparent, keeping later searches short.\n+        while (m_parent[i] != i) i = m_parent[i] = m_parent[m_parent[i]];\n         return i;\n-    };\n-    for (size_t i{0}; i < count; ++i) {\n-        for (size_t j{i + 1}; j < count; ++j) {\n-            if (!linked(i, j)) continue;\n-            const size_t a{first_of(i)}, b{first_of(j)};\n-            parent[std::max(a, b)] = std::min(a, b);\n+    }\n+\n+    void Link(size_t i, size_t j)\n+    {\n+        const size_t a{First(i)}, b{First(j)};\n+        m_parent[std::max(a, b)] = std::min(a, b);\n+    }\n+\n+    //! Link the indices with equal values. A missing value links nothing.\n+    template <typename T>\n+    void LinkEqual(const std::vector<std::optional<T>>& values)\n+    {\n+        std::map<T, size_t> first;\n+        for (size_t i{0}; i < values.size(); ++i) {\n+            if (!values[i]) continue;\n+            const auto [it, inserted]{first.try_emplace(*values[i], i)};\n+            if (!inserted) Link(it->second, i);\n         }\n     }\n-    std::vector<std::vector<size_t>> groups(count);\n-    for (size_t i{0}; i < count; ++i) groups[first_of(i)].push_back(i);\n-    std::erase_if(groups, [](const auto& group) { return group.empty(); });\n-    return groups;\n+\n+    //! Groups of at least two indices, each in index order, listed by its first index.\n+    std::vector<std::vector<size_t>> Repeated()\n+    {\n+        std::vector<std::vector<size_t>> groups(m_parent.size());\n+        for (size_t i{0}; i < m_parent.size(); ++i) groups[First(i)].push_back(i);\n+        std::erase_if(groups, [](const auto& group) { return group.size() < 2; });\n+        return groups;\n+    }\n+};\n+\n+/** Report each group of `groups` as one REPEATED_KEY issue, with the occurrence\n+ *  IDs `ids` gives for its indices. */\n+void ReportRepeated(DescriptorAnalysis& result, LinkedGroups& groups, const std::vector<size_t>& ids)\n+{\n+    for (const auto& group : groups.Repeated()) {\n+        std::vector<size_t> keys;\n+        keys.reserve(group.size());\n+        for (const size_t i : group) keys.push_back(ids[i]);\n+        result.issues.push_back({IssueKind::REPEATED_KEY, std::move(keys)});\n+    }\n }\n \n /** Report every group of cosigner slots held by the same key: slots that share\n@@ -153,17 +194,32 @@ void CheckRepeatedKeys(DescriptorAnalysis& result)\n         derived.push_back(FirstDerivedKey(node));\n         ext_roots.push_back(RootExtKey(node));\n     }\n-    const auto same_holder = [&](size_t i, size_t j) {\n-        if ((roots[i] && roots[i] == roots[j]) || (derived[i] && derived[i] == derived[j])) return true;\n-        return ext_roots[i] && ext_roots[j] && (IsDirectChild(*ext_roots[i], *ext_roots[j]) || IsDirectChild(*ext_roots[j], *ext_roots[i]));\n-    };\n-    for (const auto& group : LinkedGroups(count, same_holder)) {\n-        if (group.size() < 2) continue;\n-        std::vector<size_t> ids;\n-        ids.reserve(group.size());\n-        for (const size_t i : group) ids.push_back(result.cosigners[i]);\n-        result.issues.push_back({IssueKind::REPEATED_KEY, std::move(ids)});\n+    LinkedGroups groups{count};\n+    groups.LinkEqual(roots);\n+    groups.LinkEqual(derived);\n+\n+    // Only an xpub whose fingerprint a child names can be its parent, so a\n+    // child is derived again only from those, and not when the two slots are\n+    // already in one group. Xpubs sharing a root key are one group already, and\n+    // can share a fingerprint with any number of chain codes, so only the first\n+    // of them is a candidate parent: a child of a later one is left out of the\n+    // group, which is reported either way.\n+    std::multimap<KeyFingerprint, size_t> by_fingerprint;\n+    std::set<XOnlyPubKey> parent_roots;\n+    for (size_t i{0}; i < count; ++i) {\n+        if (ext_roots[i] && parent_roots.insert(*roots[i]).second) by_fingerprint.emplace(ext_roots[i]->id_key_fingerprint(), i);\n     }\n+    for (size_t child{0}; child < count; ++child) {\n+        if (!ext_roots[child]) continue;\n+        const auto [begin, end]{by_fingerprint.equal_range(ext_roots[child]->fingerprint)};\n+        for (auto it{begin}; it != end; ++it) {\n+            const size_t parent{it->second};\n+            if (groups.First(parent) != groups.First(child) && IsDirectChild(*ext_roots[parent], *ext_roots[child])) {\n+                groups.Link(parent, child);\n+            }\n+        }\n+    }\n+    ReportRepeated(result, groups, result.cosigners);\n }\n \n /** Check that every cosigner can derive each participant of a musig()\n@@ -192,16 +248,23 @@ void CheckMuSigParticipants(DescriptorAnalysis& result, size_t internal_id)\n             result.issues.push_back({IssueKind::NOT_DERIVABLE, {id}});\n         }\n     }\n-    const auto same_key = [&](size_t i, size_t j) {\n-        return (roots[i] && roots[i] == roots[j]) || (derived[i] && derived[i] == derived[j]);\n-    };\n-    for (const auto& group : LinkedGroups(participants.size(), same_key)) {\n-        if (group.size() < 2) continue;\n-        std::vector<size_t> ids;\n-        ids.reserve(group.size());\n-        for (const size_t i : group) ids.push_back(participants[i]);\n-        result.issues.push_back({IssueKind::REPEATED_KEY, std::move(ids)});\n+    LinkedGroups groups{participants.size()};\n+    groups.LinkEqual(roots);\n+    groups.LinkEqual(derived);\n+    ReportRepeated(result, groups, participants);\n+}\n+\n+/** Whether a NUMS or musig() internal key can derive its first key. Deriving\n+ *  fails past the maximum BIP32 depth, and a musig() aggregate starts as an\n+ *  xpub at depth 0. */\n+bool CanDeriveInternalKey(const DescriptorKeyInfo::Node& node)\n+{\n+    if (const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)}) return DeriveFirstKey(*key).has_value();\n+    if (const auto* key{std::get_if<DescriptorKeyInfo::MuSigKey>(&node.key)}) {\n+        const bool ranged{key->derivation.type == DescriptorKeyInfo::DeriveType::UNHARDENED_RANGED};\n+        return key->derivation.path.size() + (ranged ? 1 : 0) <= std::numeric_limits<unsigned char>::max();\n     }\n+    return true;\n }\n \n /** Classify the Taproot internal key against the cosigners of the leaf, or\n@@ -224,16 +287,16 @@ std::optional<DescriptorAnalysis::KeyPath> ClassifyKeyPath(const DescriptorAnaly\n     if (const auto* key{std::get_if<DescriptorKeyInfo::MuSigKey>(&internal.key)}) {\n         // Any `threshold` cosigners can already spend through the leaf, so an\n         // aggregate of at least that many distinct cosigners adds no new way to spend.\n-        std::vector<XOnlyPubKey> cosigner_roots;\n+        std::set<XOnlyPubKey> cosigner_roots;\n         for (const size_t id : result.cosigners) {\n-            if (const auto root{RootKey(occurrences.at(id).expression)}) cosigner_roots.push_back(*root);\n+            if (const auto root{RootKey(occurrences.at(id).expression)}) cosigner_roots.insert(*root);\n         }\n-        std::vector<XOnlyPubKey> participants;\n+        // A repeated participant adds no cosigner.\n+        std::set<XOnlyPubKey> participants;\n         for (const size_t id : key->participants) {\n             const auto root{RootKey(occurrences.at(id).expression)};\n-            if (!root || std::ranges::find(cosigner_roots, *root) == cosigner_roots.end()) return std::nullopt;\n-            // A repeated participant adds no cosigner.\n-            if (std::ranges::find(participants, *root) == participants.end()) participants.push_back(*root);\n+            if (!root || !cosigner_roots.contains(*root)) return std::nullopt;\n+            participants.insert(*root);\n         }\n         if (participants.size() >= result.threshold) return DescriptorAnalysis::KeyPath::MUSIG;\n     }\n@@ -299,6 +362,9 @@ DescriptorAnalysis AnalyzeDescriptor(const Descriptor& descriptor)\n         CheckMuSigParticipants(result, internal_id);\n         if (const auto key_path{ClassifyKeyPath(result, internal_id)}) {\n             result.key_path = *key_path;\n+            if (!CanDeriveInternalKey(result.policy.keys.occurrences.at(internal_id).expression)) {\n+                result.issues.push_back({IssueKind::NOT_DERIVABLE, {internal_id}});\n+            }\n         } else {\n             result.issues.push_back({IssueKind::KEY_PATH_SPENDABLE, {internal_id}});\n         }\n@@ -321,14 +387,19 @@ DescriptorAnalysis AnalyzeDescriptor(std::span<const std::unique_ptr<Descriptor>\n         for (const size_t id : analysis.cosigners) roots.push_back(RootKey(analysis.policy.keys.occurrences.at(id).expression));\n         return roots;\n     };\n+    // The branches share their key IDs, so each issue is reported once,\n+    // whichever branch it comes from.\n+    std::set<DescriptorAnalysis::Issue> seen(first.issues.begin(), first.issues.end());\n+    bool differ{false};\n     for (const auto& descriptor : descriptors.subspan(1)) {\n         const DescriptorAnalysis other{AnalyzeDescriptor(*descriptor)};\n-        if (other.shape != first.shape || other.sorted != first.sorted || other.key_path != first.key_path ||\n-            other.threshold != first.threshold || cosigner_roots(other) != cosigner_roots(first)) {\n-            Unrecognize(first);\n-            first.issues.push_back({DescriptorAnalysis::Issue::Kind::BRANCHES_DIFFER, {}});\n-            break;\n+        differ |= other.shape != first.shape || other.sorted != first.sorted || other.key_path != first.key_path ||\n+                  other.threshold != first.threshold || cosigner_roots(other) != cosigner_roots(first);\n+        for (const auto& issue : other.issues) {\n+            if (seen.insert(issue).second) first.issues.push_back(issue);\n         }\n     }\n+    if (differ) first.issues.push_back({IssueKind::BRANCHES_DIFFER, {}});\n+    if (!first.issues.empty()) Unrecognize(first);\n     return first;\n }\n",
    "truncated": false,
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  },
  {
    "bounded": true,
    "end_line": 205,
    "evidence_id": "728c1cb8ee52424d85c6fa9c67117cac",
    "finding_id": "finding:1",
    "kind": "new_source",
    "line": 56,
    "new_head": "c2d5322d4238be81fcbeb317032e148134f16aad",
    "old_head": "0997b0116b826df8d0ebfc823c2716bfdf4f230e",
    "path": "src/script/descriptor_analyzer.cpp",
    "revision": "c2d5322d4238be81fcbeb317032e148134f16aad",
    "source_generation": 5,
    "source_job_id": 3104,
    "text": "    // Deriving a hardened child needs the private key.\n    if (child.nChild & BIP32_HARDENED_FLAG) return false;\n    CExtPubKey derived;\n    return parent.Derive(derived, child.nChild) && derived.pubkey == child.pubkey && derived.chaincode == child.chaincode;\n}\n\n//! Root extended public key of a key occurrence, if it has one.\nconst CExtPubKey* RootExtKey(const DescriptorKeyInfo::Node& node)\n{\n    const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)};\n    return key ? &key->root : nullptr;\n}\n\nconst Kind* NodeKind(const DescriptorPolicy::Node& node)\n{\n    return std::get_if<Kind>(&node.kind);\n}\n\n/** Public key an extended key derives at index 0, if it can be derived\n *  without private keys. Deriving fails past the maximum BIP32 depth. */\nstd::optional<XOnlyPubKey> DeriveFirstKey(const DescriptorKeyInfo::BIP32Key& key)\n{\n    if (NeedsPrivateDerivation(key)) return std::nullopt;\n    CExtPubKey derived{key.root};\n    for (const uint32_t step : key.derivation.path) {\n        if (!derived.Derive(derived, step)) return std::nullopt;\n    }\n    if (key.derivation.type == DescriptorKeyInfo::DeriveType::UNHARDENED_RANGED && !derived.Derive(derived, 0)) return std::nullopt;\n    return XOnlyPubKey{derived.pubkey};\n}\n\n/** Check that every cosigner slot can derive addresses on its own, and that\n *  someone can sign for it. */\nvoid CheckCosignerKeys(DescriptorAnalysis& result)\n{\n    for (const size_t id : result.cosigners) {\n        const auto& node{result.policy.keys.occurrences.at(id).expression};\n        const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)};\n        if (RootKey(node) == XOnlyPubKey::NUMS_H) {\n            result.issues.push_back({IssueKind::UNSPENDABLE_KEY, {id}});\n        } else if (!key) {\n            result.issues.push_back({IssueKind::NOT_EXTENDED_KEY, {id}});\n        } else if (NeedsPrivateDerivation(*key)) {\n            result.issues.push_back({IssueKind::HARDENED_DERIVATION, {id}});\n        } else if (key->derivation.type != DescriptorKeyInfo::DeriveType::UNHARDENED_RANGED) {\n            result.issues.push_back({IssueKind::NOT_RANGED, {id}});\n        } else if (!DeriveFirstKey(*key)) {\n            result.issues.push_back({IssueKind::NOT_DERIVABLE, {id}});\n        }\n    }\n}\n\n/** Public key a cosigner slot derives at the first address, if it derives\n *  without private keys. */\nstd::optional<XOnlyPubKey> FirstDerivedKey(const DescriptorKeyInfo::Node& node)\n{\n    const auto* key{std::get_if<DescriptorKeyInfo::BIP32Key>(&node.key)};\n    if (!key || key->derivation.type != DescriptorKeyInfo::DeriveType::UNHARDENED_RANGED) return std::nullopt;\n    return DeriveFirstKey(*key);\n}\n\n/** Indices below a count, grouped by links: two indices are in one group if\n *  a chain of links connects them. */\nclass LinkedGroups\n{\n    //! Each index points to an earlier index of its group, the first one pointing to itself.\n    std::vector<size_t> m_parent;\n\npublic:\n    explicit LinkedGroups(size_t count) : m_parent(count)\n    {\n        std::iota(m_parent.begin(), m_parent.end(), size_t{0});\n    }\n\n    //! The first index of `i`'s group.\n    size_t First(size_t i)\n    {\n        // Point each index visited to its grandparent, keeping later searches short.\n        while (m_parent[i] != i) i = m_parent[i] = m_parent[m_parent[i]];\n        return i;\n    }\n\n    void Link(size_t i, size_t j)\n    {\n        const size_t a{First(i)}, b{First(j)};\n        m_parent[std::max(a, b)] = std::min(a, b);\n    }\n\n    //! Link the indices with equal values. A missing value links nothing.\n    template <typename T>\n    void LinkEqual(const std::vector<std::optional<T>>& values)\n    {\n        std::map<T, size_t> first;\n        for (size_t i{0}; i < values.size(); ++i) {\n            if (!values[i]) continue;\n            const auto [it, inserted]{first.try_emplace(*values[i], i)};\n            if (!inserted) Link(it->second, i);\n        }\n    }\n\n    //! Groups of at least two indices, each in index order, listed by its first index.\n    std::vector<std::vector<size_t>> Repeated()\n    {\n        std::vector<std::vector<size_t>> groups(m_parent.size());\n        for (size_t i{0}; i < m_parent.size(); ++i) groups[First(i)].push_back(i);\n        std::erase_if(groups, [](const auto& group) { return group.size() < 2; });\n        return groups;\n    }\n};\n\n/** Report each group of `groups` as one REPEATED_KEY issue, with the occurrence\n *  IDs `ids` gives for its indices. */\nvoid ReportRepeated(DescriptorAnalysis& result, LinkedGroups& groups, const std::vector<size_t>& ids)\n{\n    for (const auto& group : groups.Repeated()) {\n        std::vector<size_t> keys;\n        keys.reserve(group.size());\n        for (const size_t i : group) keys.push_back(ids[i]);\n        result.issues.push_back({IssueKind::REPEATED_KEY, std::move(keys)});\n    }\n}\n\n/** Report every group of cosigner slots held by the same key: slots that share\n *  a root key (e.g. the same xpub with two paths), that derive the same key, or\n *  where one xpub is the direct child of another. Slots linked through a chain\n *  of these are one group. */\nvoid CheckRepeatedKeys(DescriptorAnalysis& result)\n{\n    const auto& occurrences{result.policy.keys.occurrences};\n    const size_t count{result.cosigners.size()};\n    std::vector<std::optional<XOnlyPubKey>> roots, derived;\n    std::vector<const CExtPubKey*> ext_roots;\n    roots.reserve(count);\n    derived.reserve(count);\n    ext_roots.reserve(count);\n    for (const size_t id : result.cosigners) {\n        const auto& node{occurrences.at(id).expression};\n        roots.push_back(RootKey(node));\n        derived.push_back(FirstDerivedKey(node));\n        ext_roots.push_back(RootExtKey(node));\n    }\n    LinkedGroups groups{count};\n    groups.LinkEqual(roots);\n    groups.LinkEqual(derived);\n\n    // Only an xpub whose fingerprint a child names can be its parent, so a\n    // child is derived again only from those, and not when the two slots are\n    // already in one group. Xpubs sharing a root key are one group already, and\n    // can share a fingerprint with any number of chain codes, so only the first\n    // of them is a candidate parent: a child of a later one is left out of the",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 0997b0116b82..c2d5322d4238

2026-11-26T04:13:37Z · gpt-6-luna

bitcoin#36897Skipping legacy keys extends the backup-only recovery windowsrc/wallet/legacy/migration.cppunclear
Assessment

The supplied new-head excerpt shows the same migration call and skip-types setup but does not include the `MigrateToSQLite` record-copy/skip implementation or the transaction that applies migration data. The evidence is insufficient to determine whether legacy key records remain available in the live database during descriptor generation.

new_source: src/wallet/legacy/migration.cpp

[
  {
    "bounded": true,
    "end_line": 768,
    "evidence_id": "a4fbea79ae8744188b2a84b7a607bf12",
    "finding_id": "finding:9",
    "kind": "new_source",
    "line": 619,
    "new_head": "d5a3f21864021b03bfbc7441c357e47e4ae4722f",
    "old_head": "7d6b7094731837d7b80def7317146acba9c23a15",
    "path": "src/wallet/legacy/migration.cpp",
    "revision": "d5a3f21864021b03bfbc7441c357e47e4ae4722f",
    "source_generation": 5,
    "source_job_id": 3092,
    "text": "    // the name of the data file is used, and in the case where the wallet name\n    // is blank, \"default_wallet\" is used.\n    const std::string backup_prefix = MigrationFilePrefix(*local_wallet);\n\n    fs::path backup_filename = fs::PathFromString(strprintf(\"%s_%d.legacy.bak\", backup_prefix, GetTime()));\n    fs::path backup_path = fsbridge::AbsPathJoin(GetWalletDir(), backup_filename);\n    if (!local_wallet->BackupWallet(fs::PathToString(backup_path))) {\n        return util::Error{_(\"Error: Unable to make a backup of your wallet\")};\n    }\n    res.backup_path = backup_path;\n\n    bool success = false;\n\n    // Unlock the wallet if needed\n    if (local_wallet->IsLocked()) {\n        if (auto unlocked{local_wallet->Unlock(passphrase)}; !unlocked) return util::Error{unlocked.error().message};\n    }\n\n    // Indicates whether the current wallet is empty after migration.\n    // Notes:\n    // When non-empty: the local wallet becomes the main spendable wallet.\n    // When empty: The local wallet is excluded from the result, as the\n    //             user does not expect an empty spendable wallet after\n    //             migrating only watch-only scripts.\n    bool empty_local_wallet = false;\n\n    try {\n        std::shared_ptr<LegacyWallet> legacy_local_wallet = static_pointer_cast<LegacyWallet>(local_wallet);\n        LOCK(local_wallet->cs_wallet);\n        // First change to using SQLite\n        std::unordered_set<std::string> skip_types = DBKeys::LEGACY_TYPES;\n        skip_types.insert(DBKeys::TX);\n        bool had_legacy_records = false;\n        if (!legacy_local_wallet->MigrateToSQLite(skip_types, error, had_legacy_records)) return util::Error{error};\n\n        // Do the migration of keys and scripts for non-empty wallets, and cleanup if it fails\n        if (had_legacy_records) {\n            success = DoMigration(*legacy_local_wallet, context, error, res, load_wallet);\n            // No scripts mean empty wallet after migration\n            empty_local_wallet = legacy_local_wallet->GetAllScriptPubKeyMans().empty();\n        } else {\n            // Make sure that descriptors flag is actually set\n            local_wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);\n            success = true;\n        }\n    } catch (const std::exception& e) {\n        error = Untranslated(strprintf(\"Migration failed: %s\", e.what()));\n    }\n\n    // In case of loading failure, we need to remember the wallet files we have created to remove.\n    // A `set` is used as it may be populated with the same wallet directory paths multiple times,\n    // both before and after loading. This ensures the set is complete even if one of the wallets\n    // fails to load.\n    std::set<fs::path> wallet_files_to_remove;\n    std::set<fs::path> wallet_empty_dirs_to_remove;\n\n    // Helper to track wallet files and directories for cleanup on failure.\n    // Only directories of wallets created during migration (not the main wallet) are tracked.\n    auto track_for_cleanup = [&](const CWallet& wallet) {\n        const auto files = wallet.GetDatabase().Files();\n        wallet_files_to_remove.insert(files.begin(), files.end());\n        if (wallet.GetName() != wallet_name) {\n            // If this isn’t the main wallet, mark its directory for removal.\n            // This applies to the watch-only and solvable wallets.\n            // Wallets stored directly as files in the top-level directory\n            // (e.g. default unnamed wallets) don’t have a removable parent directory.\n            wallet_empty_dirs_to_remove.insert(fs::PathFromString(wallet.GetDatabase().Filename()).parent_path());\n        }\n    };\n\n\n    if (success) {\n        Assume(!res.wallet); // We will set it here.\n        // Check if the local wallet is empty after migration\n        if (empty_local_wallet) {\n            // This wallet has no records. We can safely remove it.\n            std::vector<fs::path> paths_to_remove = local_wallet->GetDatabase().Files();\n            local_wallet.reset();\n            for (const auto& path_to_remove : paths_to_remove) fs::remove(path_to_remove);\n        }\n\n        if (load_wallet) {\n            LogInfo(\"Loading new wallets after migration...\\n\");\n            /** We only override the load_on_startup setting in case the user explicitly said\n             * that he does not want to load the wallet, otherwise keep the old wallet configuration */\n        } else {\n            UpdateWalletSetting(*context.chain, wallet_name, /*load_on_startup=*/false, warnings);\n        }\n        // Migration successful, if load_wallet is set load all the migrated wallets.\n        bool main_wallet_set{false};\n        for (std::shared_ptr<CWallet>* wallet_ptr : std::array<std::shared_ptr<CWallet>*, 3>{&local_wallet, &res.watchonly_wallet, &res.solvables_wallet}) {\n            if (success && *wallet_ptr) {\n                std::shared_ptr<CWallet>& wallet = *wallet_ptr;\n                // Track db path\n                track_for_cleanup(*wallet);\n                assert(wallet.use_count() == 1);\n                std::string wallet_name = wallet->GetName();\n                wallet.reset();\n                if (load_wallet) {\n                    wallet = LoadWallet(context, wallet_name, /*load_on_start=*/std::nullopt, options, status, error, warnings);\n                    if (!wallet) {\n                        LogError(\"Failed to load wallet '%s' after migration. Rolling back migration to preserve consistency. \"\n                                 \"Error cause: %s\\n\", wallet_name, error.original);\n                        success = false;\n                        break;\n                    }\n                }\n                // Set the first wallet as the main one.\n                // The loop order is intentional and must always start with the local wallet.\n                if (!main_wallet_set) {\n                    res.wallet_name = wallet_name;\n                    if (load_wallet) res.wallet = std::move(wallet);\n                    main_wallet_set = true;\n                }\n                if (wallet_ptr == &res.watchonly_wallet) {\n                    res.watchonly_wallet_name = wallet_name;\n                } else if (wallet_ptr == &res.solvables_wallet) {\n                    res.solvables_wallet_name = wallet_name;\n                }\n            }\n        }\n    }\n    if (!success) {\n        // Make list of wallets to cleanup\n        std::vector<std::shared_ptr<CWallet>> created_wallets;\n        if (local_wallet) created_wallets.push_back(std::move(local_wallet));\n        if (res.watchonly_wallet) created_wallets.push_back(std::move(res.watchonly_wallet));\n        if (res.solvables_wallet) created_wallets.push_back(std::move(res.solvables_wallet));\n\n        // Get the directories to remove after unloading\n        for (std::shared_ptr<CWallet>& wallet : created_wallets) {\n            track_for_cleanup(*wallet);\n        }\n\n        // Unload the wallets\n        for (std::shared_ptr<CWallet>& w : created_wallets) {\n            if (w->HaveChain()) {\n                // Unloading for wallets that were loaded for normal use\n                if (!RemoveWallet(context, w, /*load_on_start=*/false)) {\n                    error += _(\"\\nUnable to cleanup failed migration\");\n                    return util::Error{error};\n                }\n                WaitForDeleteWallet(std::move(w));\n            } else {\n                // Unloading for wallets in local context\n                assert(w.use_count() == 1);\n                w.reset();\n            }\n        }\n",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 7d6b70947318..d5a3f2186402

2026-11-26T00:08:30Z · gpt-6-luna

bitcoin#36897The migration overload does not enforce its LegacyWallet requirementsrc/wallet/legacy/migration.cppstill_present
Assessment

The new-head excerpt still performs `static_pointer_cast<LegacyWallet>(local_wallet)` inside the overload. It does not show that the entry-point parameter was changed to `shared_ptr<LegacyWallet>`, so the invalid-downcast risk described remains.

new_source: src/wallet/legacy/migration.cpp

[
  {
    "bounded": true,
    "end_line": 765,
    "evidence_id": "d38e386b6479405e8f27f3fa842d1850",
    "finding_id": "finding:8",
    "kind": "new_source",
    "line": 616,
    "new_head": "d5a3f21864021b03bfbc7441c357e47e4ae4722f",
    "old_head": "7d6b7094731837d7b80def7317146acba9c23a15",
    "path": "src/wallet/legacy/migration.cpp",
    "revision": "d5a3f21864021b03bfbc7441c357e47e4ae4722f",
    "source_generation": 5,
    "source_job_id": 3092,
    "text": "    // using the wallet name and current timestamp. The backup filename is based\n    // on the name of the parent directory containing the wallet data in most\n    // cases, but in the case where the wallet name is a path to a data file,\n    // the name of the data file is used, and in the case where the wallet name\n    // is blank, \"default_wallet\" is used.\n    const std::string backup_prefix = MigrationFilePrefix(*local_wallet);\n\n    fs::path backup_filename = fs::PathFromString(strprintf(\"%s_%d.legacy.bak\", backup_prefix, GetTime()));\n    fs::path backup_path = fsbridge::AbsPathJoin(GetWalletDir(), backup_filename);\n    if (!local_wallet->BackupWallet(fs::PathToString(backup_path))) {\n        return util::Error{_(\"Error: Unable to make a backup of your wallet\")};\n    }\n    res.backup_path = backup_path;\n\n    bool success = false;\n\n    // Unlock the wallet if needed\n    if (local_wallet->IsLocked()) {\n        if (auto unlocked{local_wallet->Unlock(passphrase)}; !unlocked) return util::Error{unlocked.error().message};\n    }\n\n    // Indicates whether the current wallet is empty after migration.\n    // Notes:\n    // When non-empty: the local wallet becomes the main spendable wallet.\n    // When empty: The local wallet is excluded from the result, as the\n    //             user does not expect an empty spendable wallet after\n    //             migrating only watch-only scripts.\n    bool empty_local_wallet = false;\n\n    try {\n        std::shared_ptr<LegacyWallet> legacy_local_wallet = static_pointer_cast<LegacyWallet>(local_wallet);\n        LOCK(local_wallet->cs_wallet);\n        // First change to using SQLite\n        std::unordered_set<std::string> skip_types = DBKeys::LEGACY_TYPES;\n        skip_types.insert(DBKeys::TX);\n        bool had_legacy_records = false;\n        if (!legacy_local_wallet->MigrateToSQLite(skip_types, error, had_legacy_records)) return util::Error{error};\n\n        // Do the migration of keys and scripts for non-empty wallets, and cleanup if it fails\n        if (had_legacy_records) {\n            success = DoMigration(*legacy_local_wallet, context, error, res, load_wallet);\n            // No scripts mean empty wallet after migration\n            empty_local_wallet = legacy_local_wallet->GetAllScriptPubKeyMans().empty();\n        } else {\n            // Make sure that descriptors flag is actually set\n            local_wallet->SetWalletFlag(WALLET_FLAG_DESCRIPTORS);\n            success = true;\n        }\n    } catch (const std::exception& e) {\n        error = Untranslated(strprintf(\"Migration failed: %s\", e.what()));\n    }\n\n    // In case of loading failure, we need to remember the wallet files we have created to remove.\n    // A `set` is used as it may be populated with the same wallet directory paths multiple times,\n    // both before and after loading. This ensures the set is complete even if one of the wallets\n    // fails to load.\n    std::set<fs::path> wallet_files_to_remove;\n    std::set<fs::path> wallet_empty_dirs_to_remove;\n\n    // Helper to track wallet files and directories for cleanup on failure.\n    // Only directories of wallets created during migration (not the main wallet) are tracked.\n    auto track_for_cleanup = [&](const CWallet& wallet) {\n        const auto files = wallet.GetDatabase().Files();\n        wallet_files_to_remove.insert(files.begin(), files.end());\n        if (wallet.GetName() != wallet_name) {\n            // If this isn’t the main wallet, mark its directory for removal.\n            // This applies to the watch-only and solvable wallets.\n            // Wallets stored directly as files in the top-level directory\n            // (e.g. default unnamed wallets) don’t have a removable parent directory.\n            wallet_empty_dirs_to_remove.insert(fs::PathFromString(wallet.GetDatabase().Filename()).parent_path());\n        }\n    };\n\n\n    if (success) {\n        Assume(!res.wallet); // We will set it here.\n        // Check if the local wallet is empty after migration\n        if (empty_local_wallet) {\n            // This wallet has no records. We can safely remove it.\n            std::vector<fs::path> paths_to_remove = local_wallet->GetDatabase().Files();\n            local_wallet.reset();\n            for (const auto& path_to_remove : paths_to_remove) fs::remove(path_to_remove);\n        }\n\n        if (load_wallet) {\n            LogInfo(\"Loading new wallets after migration...\\n\");\n            /** We only override the load_on_startup setting in case the user explicitly said\n             * that he does not want to load the wallet, otherwise keep the old wallet configuration */\n        } else {\n            UpdateWalletSetting(*context.chain, wallet_name, /*load_on_startup=*/false, warnings);\n        }\n        // Migration successful, if load_wallet is set load all the migrated wallets.\n        bool main_wallet_set{false};\n        for (std::shared_ptr<CWallet>* wallet_ptr : std::array<std::shared_ptr<CWallet>*, 3>{&local_wallet, &res.watchonly_wallet, &res.solvables_wallet}) {\n            if (success && *wallet_ptr) {\n                std::shared_ptr<CWallet>& wallet = *wallet_ptr;\n                // Track db path\n                track_for_cleanup(*wallet);\n                assert(wallet.use_count() == 1);\n                std::string wallet_name = wallet->GetName();\n                wallet.reset();\n                if (load_wallet) {\n                    wallet = LoadWallet(context, wallet_name, /*load_on_start=*/std::nullopt, options, status, error, warnings);\n                    if (!wallet) {\n                        LogError(\"Failed to load wallet '%s' after migration. Rolling back migration to preserve consistency. \"\n                                 \"Error cause: %s\\n\", wallet_name, error.original);\n                        success = false;\n                        break;\n                    }\n                }\n                // Set the first wallet as the main one.\n                // The loop order is intentional and must always start with the local wallet.\n                if (!main_wallet_set) {\n                    res.wallet_name = wallet_name;\n                    if (load_wallet) res.wallet = std::move(wallet);\n                    main_wallet_set = true;\n                }\n                if (wallet_ptr == &res.watchonly_wallet) {\n                    res.watchonly_wallet_name = wallet_name;\n                } else if (wallet_ptr == &res.solvables_wallet) {\n                    res.solvables_wallet_name = wallet_name;\n                }\n            }\n        }\n    }\n    if (!success) {\n        // Make list of wallets to cleanup\n        std::vector<std::shared_ptr<CWallet>> created_wallets;\n        if (local_wallet) created_wallets.push_back(std::move(local_wallet));\n        if (res.watchonly_wallet) created_wallets.push_back(std::move(res.watchonly_wallet));\n        if (res.solvables_wallet) created_wallets.push_back(std::move(res.solvables_wallet));\n\n        // Get the directories to remove after unloading\n        for (std::shared_ptr<CWallet>& wallet : created_wallets) {\n            track_for_cleanup(*wallet);\n        }\n\n        // Unload the wallets\n        for (std::shared_ptr<CWallet>& w : created_wallets) {\n            if (w->HaveChain()) {\n                // Unloading for wallets that were loaded for normal use\n                if (!RemoveWallet(context, w, /*load_on_start=*/false)) {\n                    error += _(\"\\nUnable to cleanup failed migration\");\n                    return util::Error{error};\n                }\n                WaitForDeleteWallet(std::move(w));\n            } else {\n                // Unloading for wallets in local context\n                assert(w.use_count() == 1);\n                w.reset();",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 7d6b70947318..d5a3f2186402

2026-11-26T00:08:30Z · gpt-6-luna

bitcoin#36897Concurrent migrations can delete each other's temporary databasesrc/wallet/legacy/migration.cppstill_present
Assessment

The new-head excerpt still builds the temporary path from the wallet prefix and current second, checks for existence without reserving it exclusively, and uses cleanup that removes entries from the path after database creation fails. The concurrent collision and cross-cleanup risk therefore remain.

new_source: src/wallet/legacy/migration.cpp

[
  {
    "bounded": true,
    "end_line": 287,
    "evidence_id": "54b5db548afa4af38fbc430569755354",
    "finding_id": "finding:7",
    "kind": "new_source",
    "line": 138,
    "new_head": "d5a3f21864021b03bfbc7441c357e47e4ae4722f",
    "old_head": "7d6b7094731837d7b80def7317146acba9c23a15",
    "path": "src/wallet/legacy/migration.cpp",
    "revision": "d5a3f21864021b03bfbc7441c357e47e4ae4722f",
    "source_generation": 5,
    "source_job_id": 3092,
    "text": "            break;\n        }\n        SerializeData key(ss_key.begin(), ss_key.end());\n        SerializeData value(ss_value.begin(), ss_value.end());\n\n        std::string type;\n        ss_key >> type;\n        if (skip_types.contains(type)) {\n            had_legacy_records = true;\n            continue;\n        }\n\n        records.emplace_back(key, value);\n    }\n    cursor.reset();\n    batch.reset();\n    if (status != DatabaseCursor::Status::DONE) {\n        error = _(\"Error: Unable to read all records in the database\");\n        return false;\n    }\n\n    // Close this database. It stays untouched until the new one is fully built\n    const fs::path db_file = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_database->Filename()));\n    m_database->Close();\n\n    // Create a temporary database next to the original db file\n    const std::string new_db_name = strprintf(\"%s_sqlite_%d.tmp\", MigrationFilePrefix(*this), GetTime());\n    const fs::path tmp_wallet_path = fs::path{db_file.parent_path()} / fs::PathFromString(new_db_name);\n    // Refuse any existing path, not just an existing database (all that require_create checks), so cleanup only\n    // deletes files this function created.\n    if (std::error_code ec; fs::exists(fs::symlink_status(tmp_wallet_path, ec))) {\n        error = strprintf(_(\"Error: Unable to create the new database for wallet '%s'. Temporary path '%s' already exists.\"), GetName(), fs::PathToString(tmp_wallet_path));\n        return false;\n    }\n\n    // Generate the path for the location of the migrated wallet\n    // Wallets that are plain files rather than wallet directories will be migrated to be wallet directories.\n    const fs::path dst_wallet_dir = fsbridge::AbsPathJoin(GetWalletDir(), fs::PathFromString(m_name));\n\n    // Make new DB\n    DatabaseOptions opts;\n    opts.require_create = true;\n    opts.require_format = DatabaseFormat::SQLITE;\n    DatabaseStatus db_status;\n    std::unique_ptr<WalletDatabase> new_db = MakeDatabase(tmp_wallet_path, opts, db_status, error);\n\n    // Set the error, then delete the temporary database and its directory. The directory did not exist before, so it\n    // only holds files of the new db, including any left by a failed creation.\n    const auto remove_tmp_and_fail = [&](bilingual_str err) {\n        error = std::move(err);\n        new_db.reset(); // Close the db before deleting its files\n        std::error_code ec;\n        for (auto it{fs::directory_iterator(tmp_wallet_path, ec)}; !ec && it != fs::directory_iterator(); it.increment(ec)) {\n            fs::remove(it->path(), ec);\n        }\n        fs::remove(tmp_wallet_path, ec);\n        if (ec) {\n            error += Untranslated(\" \") + strprintf(_(\"The temporary database at %s could not be removed.\"), fs::PathToString(tmp_wallet_path));\n        }\n        return false;\n    };\n\n    if (!new_db) {\n        return remove_tmp_and_fail(strprintf(_(\"Error: Unable to create the new database for wallet '%s'.\"), GetName()) + Untranslated(\" \") + error);\n    }\n\n    // Write existing records into the new DB\n    const bool written = RunWithinTxn(*new_db, \"migration: write records to new db\", [&records](DatabaseBatch& in_batch) {\n        for (const auto& [key, value] : records) {\n            if (!in_batch.Write(std::span{key}, std::span{value})) return false;\n        }\n        return true;\n    });\n    if (!written) {\n        return remove_tmp_and_fail(strprintf(_(\"Error: Unable to write records into the new database for wallet '%s'\"), GetName()));\n    }\n\n    // ######################################################################\n    // At this point, the new database has all records.                     #\n    // Move it into the wallet location, replacing the original db file.    #\n    // ######################################################################\n\n    // A plain wallet file (its db file is the wallet path itself) becomes a wallet directory. As a file cannot be\n    // atomically replaced by a directory, the original db is erased first in that case. The original db is a single\n    // file, so if Erase() fails nothing was removed, and returning false is still correct.\n    if (db_file == dst_wallet_dir) {\n        Assume(m_database->Files().size() == 1);\n        if (auto res{m_database->Erase()}; !res) return remove_tmp_and_fail(util::ErrorString(res));\n    }\n\n    // From here on, the original db may have been erased or replaced. Never return false after this point, as the\n    // caller would skip the restore. Throw instead, so it deletes the wallet files and restores the backup.\n    if (auto res{MoveDatabase(new_db, dst_wallet_dir, opts)}; !res) {\n        remove_tmp_and_fail(util::ErrorString(res));\n        throw std::runtime_error(error.original);\n    }\n    // The caller's rollback deletes m_database's files, so point it at the new db as soon as it replaces the original\n    m_database = std::move(new_db);\n    // The temporary dir only held the new db files, which were just moved out. If it can't be removed, something\n    // unexpected happened, so stop and let the caller restore the backup.\n    if (std::error_code ec; !fs::remove(tmp_wallet_path, ec)) {\n        throw std::runtime_error(strprintf(\"Unable to remove temporary directory %s after moving the new database: %s\", fs::PathToString(tmp_wallet_path), ec ? ec.message() : \"it no longer exists\"));\n    }\n    return true;\n}\n\nstd::optional<MigrationData> LegacyWallet::GetDescriptorsForLegacy(bilingual_str& error) const\n{\n    AssertLockHeld(cs_wallet);\n\n    LegacyDataSPKM* legacy_spkm = GetLegacyDataSPKM();\n    if (!Assume(legacy_spkm)) {\n        // This shouldn't happen\n        error = Untranslated(STR_INTERNAL_BUG(\"Error: Legacy wallet data missing\"));\n        return std::nullopt;\n    }\n\n    std::optional<MigrationData> res = legacy_spkm->MigrateToDescriptor();\n    if (res == std::nullopt) {\n        error = _(\"Error: Unable to produce descriptors for this legacy wallet. Make sure to provide the wallet's passphrase if it is encrypted.\");\n        return std::nullopt;\n    }\n    return res;\n}\n\nutil::Result<void> LegacyWallet::ApplyMigrationData(WalletBatch& local_wallet_batch, MigrationData& data)\n{\n    AssertLockHeld(cs_wallet);\n\n    LegacyDataSPKM* legacy_spkm = GetLegacyDataSPKM();\n    if (!Assume(legacy_spkm)) {\n        // This shouldn't happen\n        return util::Error{Untranslated(STR_INTERNAL_BUG(\"Error: Legacy wallet data missing\"))};\n    }\n\n    // Note: when the legacy wallet has no spendable scripts, it must be empty at the end of the process.\n    bool has_spendable_material = !data.desc_spkms.empty() || data.master_key.key.IsValid();\n\n    // Get all invalid or non-watched scripts that will not be migrated\n    std::set<CTxDestination> not_migrated_dests;\n    for (const auto& script : legacy_spkm->GetNotMineScriptPubKeys()) {\n        CTxDestination dest;\n        if (ExtractDestination(script, dest)) not_migrated_dests.emplace(dest);\n    }\n\n    // When the legacy wallet has no spendable scripts, the main wallet will be empty, leaving its script cache empty as well.\n    // The watch-only and/or solvable wallet(s) will contain the scripts in their respective caches.\n    if (!data.desc_spkms.empty()) Assume(GetCachedSPKsSize() != 0);\n    if (!data.watch_descs.empty()) Assume(data.watchonly_wallet->GetCachedSPKsSize() != 0);\n    if (!data.solvable_descs.empty()) Assume(data.solvable_wallet->GetCachedSPKsSize() != 0);",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 7d6b70947318..d5a3f2186402

2026-11-26T00:08:30Z · gpt-6-luna

bitcoin#36897Unused &batch capture causes a Clang warning-as-error failuresrc/wallet/legacy/load.cppstill_present
Assessment

The new-head excerpt retains the capture `[&any_unordered, &batch]`, while the lambda body shown does not use `batch`; the reported unused capture remains.

new_source: src/wallet/legacy/load.cpp

[
  {
    "bounded": true,
    "end_line": 602,
    "evidence_id": "49887bd86cec4195bb12cdd4060fa746",
    "finding_id": "finding:6",
    "kind": "new_source",
    "line": 453,
    "new_head": "d5a3f21864021b03bfbc7441c357e47e4ae4722f",
    "old_head": "7d6b7094731837d7b80def7317146acba9c23a15",
    "path": "src/wallet/legacy/load.cpp",
    "revision": "d5a3f21864021b03bfbc7441c357e47e4ae4722f",
    "source_generation": 5,
    "source_job_id": 3092,
    "text": "        return DBErrors::LOAD_OK;\n    });\n    result = std::max(result, dest_res.m_result);\n\n    return result;\n}\n\nstatic DBErrors LoadDecryptionKeys(LegacyWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)\n{\n    AssertLockHeld(pwallet->cs_wallet);\n\n    // Load decryption key (mkey) records\n    LoadResult mkey_res = LoadRecords(pwallet, batch, DBKeys::MASTER_KEY,\n        [] (LegacyWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {\n        if (!LoadEncryptionKey(pwallet, key, value, err)) {\n            return DBErrors::CORRUPT;\n        }\n        return DBErrors::LOAD_OK;\n    });\n    return mkey_res.m_result;\n}\n\nstatic DBErrors LoadTxRecords(LegacyWallet* pwallet, DatabaseBatch& batch, bool& any_unordered) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)\n{\n    AssertLockHeld(pwallet->cs_wallet);\n    DBErrors result = DBErrors::LOAD_OK;\n\n    // Load tx record\n    any_unordered = false;\n    LoadResult tx_res = LoadRecords(pwallet, batch, DBKeys::TX,\n        [&any_unordered, &batch] (LegacyWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {\n        DBErrors result = DBErrors::LOAD_OK;\n        Txid hash;\n        key >> hash;\n        try {\n            CWalletTx wtx{deserialize, value, {}};\n            if (wtx.GetHash() != hash) {\n                result = std::max(result, DBErrors::NEED_RESCAN);\n            }\n\n            if (wtx.nOrderPos == -1) {\n                any_unordered = true;\n            }\n\n            if (!pwallet->LoadToWallet(std::move(wtx))) {\n                err = \"Error: Corrupt transaction found. This can be fixed by removing transactions from wallet and rescanning.\";\n                return DBErrors::CORRUPT;\n            }\n        } catch (const std::exception& e) {\n            err = strprintf(\"Error: Corrupt tx record found: %s\" ,e.what());\n            return DBErrors::CORRUPT;\n        }\n        return result;\n    });\n    result = std::max(result, tx_res.m_result);\n\n    // Load locked utxo record\n    LoadResult locked_utxo_res = LoadRecords(pwallet, batch, DBKeys::LOCKED_UTXO,\n        [] (LegacyWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {\n        Txid hash;\n        uint32_t n;\n        key >> hash;\n        key >> n;\n        pwallet->LoadLockedCoin(COutPoint(hash, n), /*persistent=*/true);\n        return DBErrors::LOAD_OK;\n    });\n    result = std::max(result, locked_utxo_res.m_result);\n\n    // Load orderposnext record\n    // Note: There should only be one ORDERPOSNEXT record with nothing trailing the type\n    LoadResult order_pos_res = LoadRecords(pwallet, batch, DBKeys::ORDERPOSNEXT,\n        [] (LegacyWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {\n        try {\n            value >> pwallet->nOrderPosNext;\n        } catch (const std::exception& e) {\n            err = e.what();\n            return DBErrors::NONCRITICAL_ERROR;\n        }\n        return DBErrors::LOAD_OK;\n    });\n    result = std::max(result, order_pos_res.m_result);\n\n    // After loading all tx records, abandon any coinbase that is no longer in the active chain.\n    // This could happen during an external wallet load, or if the user replaced the chain data.\n    for (auto& [id, wtx] : pwallet->mapWallet) {\n        if (wtx.IsCoinBase() && wtx.isInactive()) {\n            pwallet->AbandonTransaction(wtx);\n        }\n    }\n\n    return result;\n}\n\nstatic DBErrors LoadWalletFromBDBRO(LegacyWallet* pwallet) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)\n{\n    AssertLockHeld(pwallet->cs_wallet);\n    DBErrors result = DBErrors::LOAD_OK;\n    bool any_unordered = false;\n\n    std::unique_ptr<DatabaseBatch> batch = pwallet->GetDatabase().MakeBatch();\n    if (!batch) {\n        pwallet->WalletLogPrintf(\"Migration: Unable to create BerkeleyROBatch\");\n        return DBErrors::CORRUPT;\n    }\n\n    try {\n        // Load wallet flags, so they are known when processing other records.\n        // The FLAGS key is absent during wallet creation.\n        if ((result = LoadWalletFlags(pwallet, *batch)) != DBErrors::LOAD_OK) return result;\n\n        // Load legacy wallet keys\n        result = std::max(LoadLegacyWalletRecords(pwallet, *batch), result);\n\n        // Load address book\n        result = std::max(LoadAddressBookRecords(pwallet, *batch), result);\n\n        // Load decryption keys\n        result = std::max(LoadDecryptionKeys(pwallet, *batch), result);\n\n        // Load tx records\n        result = std::max(LoadTxRecords(pwallet, *batch, any_unordered), result);\n    } catch (std::runtime_error& e) {\n        // Exceptions that can be ignored or treated as non-critical are handled by the individual loading functions.\n        // Any uncaught exceptions will be caught here and treated as critical.\n        // Catch std::runtime_error specifically as many functions throw these and they at least have some message that\n        // we can log\n        pwallet->WalletLogPrintf(\"%s\", e.what());\n        result = DBErrors::CORRUPT;\n    } catch (...) {\n        // All other exceptions are still problematic, but we can't log them\n        result = DBErrors::CORRUPT;\n    }\n\n    // Any wallet corruption at all: skip any rewriting or\n    // upgrading, we don't want to make it worse.\n    if (result != DBErrors::LOAD_OK)\n        return result;\n\n    if (any_unordered)\n        result = pwallet->ReorderTransactions();\n\n    return result;\n}\n\nstatic DBErrors PopulateWalletFromBDBRO(LegacyWallet *pwallet, bilingual_str& error)\n{\n    LOCK(pwallet->cs_wallet);\n\n    DBErrors nLoadWalletRet = LoadWalletFromBDBRO(pwallet);\n",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 7d6b70947318..d5a3f2186402

2026-11-26T00:08:30Z · gpt-6-luna

bitcoin#36897Legacy header closing guards violate the include-guard lintsrc/wallet/legacy/bdbro.hstill_present
Assessment

The new-head bdbro.h closing comment remains BITCOIN_WALLET_BDBRO_H, not the required BITCOIN_WALLET_LEGACY_BDBRO_H.

new_source: src/wallet/legacy/bdbro.h

[
  {
    "bounded": true,
    "end_line": 112,
    "evidence_id": "76a90aecf7674513985baf150631509e",
    "finding_id": "finding:4",
    "kind": "new_source",
    "line": 82,
    "new_head": "d5a3f21864021b03bfbc7441c357e47e4ae4722f",
    "old_head": "7d6b7094731837d7b80def7317146acba9c23a15",
    "path": "src/wallet/legacy/bdbro.h",
    "revision": "d5a3f21864021b03bfbc7441c357e47e4ae4722f",
    "source_generation": 5,
    "source_job_id": 3092,
    "text": "    bool ReadKey(DataStream&& key, DataStream& value) override;\n    // WriteKey returns true since various automatic upgrades for older wallets will expect writing to not fail.\n    // It is okay for this batch type to not actually write anything as those automatic upgrades will occur again after migration.\n    bool WriteKey(DataStream&& key, DataStream&& value, bool overwrite = true) override { return true; }\n    bool EraseKey(DataStream&& key) override { return false; }\n    bool HasKey(DataStream&& key) override;\n    bool ErasePrefix(std::span<const std::byte> prefix) override { return false; }\n\npublic:\n    explicit BerkeleyROBatch(const BerkeleyRODatabase& database) : m_database(database) {}\n    ~BerkeleyROBatch() = default;\n\n    BerkeleyROBatch(const BerkeleyROBatch&) = delete;\n    BerkeleyROBatch& operator=(const BerkeleyROBatch&) = delete;\n\n    void Close() override {}\n\n    std::unique_ptr<DatabaseCursor> GetNewCursor() override { return std::make_unique<BerkeleyROCursor>(m_database); }\n    std::unique_ptr<DatabaseCursor> GetNewPrefixCursor(std::span<const std::byte> prefix) override;\n    bool TxnBegin() override { return false; }\n    bool TxnCommit() override { return false; }\n    bool TxnAbort() override { return false; }\n    bool HasActiveTxn() override { return false; }\n};\n\n//! Return object giving access to Berkeley Read Only database at specified path.\nstd::unique_ptr<BerkeleyRODatabase> MakeBerkeleyRODatabase(const fs::path& path, const DatabaseOptions& options, DatabaseStatus& status, bilingual_str& error);\n} // namespace legacy_migration\n} // namespace wallet\n\n#endif // BITCOIN_WALLET_BDBRO_H",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 7d6b70947318..d5a3f2186402

2026-11-26T00:08:30Z · gpt-6-luna

bitcoin#36897Migration ignores -keypool when generating active descriptorssrc/wallet/legacy/load.cppstill_present
Assessment

The new-head specialized loader still constructs LegacyWallet without applying a configured keypool value.

new_source: src/wallet/legacy/load.cpp

[
  {
    "bounded": true,
    "end_line": 654,
    "evidence_id": "2aa9ed0b204d4121bdbd083976434d4f",
    "finding_id": "finding:3",
    "kind": "new_source",
    "line": 613,
    "new_head": "d5a3f21864021b03bfbc7441c357e47e4ae4722f",
    "old_head": "7d6b7094731837d7b80def7317146acba9c23a15",
    "path": "src/wallet/legacy/load.cpp",
    "revision": "d5a3f21864021b03bfbc7441c357e47e4ae4722f",
    "source_generation": 5,
    "source_job_id": 3092,
    "text": "        error = strprintf(_(\"Error loading %s: Wallet requires newer version of %s\"), wallet_file, CLIENT_NAME);\n        break;\n    case DBErrors::EXTERNAL_SIGNER_SUPPORT_REQUIRED:\n        error = strprintf(_(\"Error loading %s: External signer wallet being loaded without external signer support compiled\"), wallet_file);\n        break;\n    case DBErrors::UNKNOWN_DESCRIPTOR:\n    case DBErrors::UNEXPECTED_LEGACY_ENTRY:\n    case DBErrors::LEGACY_WALLET:\n        // These errors should never happen\n        Assert(false);\n        break;\n    case DBErrors::LOAD_FAIL:\n        error = strprintf(_(\"Error loading %s\"), wallet_file);\n        break;\n    } // no default case, so the compiler can warn about missing cases\n    return nLoadWalletRet;\n}\n\nstd::shared_ptr<LegacyWallet> LoadWalletForMigration(const std::string& name, bilingual_str& error)\n{\n    // Load the wallet but only in the context of migration.\n    // No signals should be connected nor should anything else be aware of this wallet\n    WalletContext empty_context;\n    DatabaseOptions options;\n    options.require_existing = true;\n    options.require_format = DatabaseFormat::BERKELEY_RO;\n    DatabaseStatus status;\n    std::unique_ptr<WalletDatabase> database = MakeWalletDatabase(name, options, status, error);\n    if (!database) return nullptr;\n\n    std::shared_ptr<LegacyWallet> wallet(new LegacyWallet(name, std::move(database)));\n\n    // Load wallet\n    auto res = PopulateWalletFromBDBRO(wallet.get(), error);\n    if (res != DBErrors::LOAD_OK && res != DBErrors::NONCRITICAL_ERROR && res != DBErrors::NEED_RESCAN) {\n        return nullptr;\n    }\n\n    return wallet;\n}\n} // namespace legacy_migration\n} // namespace wallet",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 7d6b70947318..d5a3f2186402

2026-11-26T00:08:30Z · gpt-6-luna

bitcoin#36897Accepted legacy-load errors can leave migrated transactions without orderingsrc/wallet/walletdb.cppstill_present
Assessment

The new-head excerpt retains the Assume(nOrderPos >= 0) check and CORRUPT return, and does not show the migration loader reordering for tolerated load statuses.

new_source: src/wallet/walletdb.cpp

[
  {
    "bounded": true,
    "end_line": 831,
    "evidence_id": "48c0f895442f4bf1aa48e79f845f8286",
    "finding_id": "finding:2",
    "kind": "new_source",
    "line": 682,
    "new_head": "d5a3f21864021b03bfbc7441c357e47e4ae4722f",
    "old_head": "7d6b7094731837d7b80def7317146acba9c23a15",
    "path": "src/wallet/walletdb.cpp",
    "revision": "d5a3f21864021b03bfbc7441c357e47e4ae4722f",
    "source_generation": 5,
    "source_job_id": 3092,
    "text": "        }\n        CTransactionRef tx;\n        value >> TX_WITH_WITNESS(tx);\n        if (tx->GetHash() != txid) {\n            throw std::runtime_error(strprintf(\"Corrupted witness variant, tx hash differs\"));\n        }\n        if (!variants.emplace(tx->GetWitnessHash(), std::move(tx)).second) {\n            throw std::runtime_error(strprintf(\"Duplicate witness variant\"));\n        }\n    }\n    return variants;\n}\n\nstatic DBErrors LoadTxRecords(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)\n{\n    AssertLockHeld(pwallet->cs_wallet);\n    DBErrors result = DBErrors::LOAD_OK;\n\n    // Load tx record\n    LoadResult tx_res = LoadRecords(pwallet, batch, DBKeys::TX,\n        [&batch] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {\n        DBErrors result = DBErrors::LOAD_OK;\n        Txid hash;\n        key >> hash;\n        try {\n            CWalletTx wtx{deserialize, value, ReadWtxVariants(batch, hash)};\n            if (wtx.GetHash() != hash) {\n                result = std::max(result, DBErrors::NEED_RESCAN);\n            }\n\n            if (!Assume(wtx.nOrderPos >= 0)) {\n                err = \"Error: Transaction missing nOrderPos\";\n                return DBErrors::CORRUPT;\n            }\n\n            if (!pwallet->LoadToWallet(std::move(wtx))) {\n                err = \"Error: Corrupt transaction found. This can be fixed by removing transactions from wallet and rescanning.\";\n                return DBErrors::CORRUPT;\n            }\n        } catch (const std::exception& e) {\n            err = strprintf(\"Error: Corrupt tx record found: %s\" ,e.what());\n            return DBErrors::CORRUPT;\n        }\n        return result;\n    });\n    result = std::max(result, tx_res.m_result);\n\n    // Load locked utxo record\n    LoadResult locked_utxo_res = LoadRecords(pwallet, batch, DBKeys::LOCKED_UTXO,\n        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {\n        Txid hash;\n        uint32_t n;\n        key >> hash;\n        key >> n;\n        pwallet->LoadLockedCoin(COutPoint(hash, n), /*persistent=*/true);\n        return DBErrors::LOAD_OK;\n    });\n    result = std::max(result, locked_utxo_res.m_result);\n\n    // Load orderposnext record\n    // Note: There should only be one ORDERPOSNEXT record with nothing trailing the type\n    LoadResult order_pos_res = LoadRecords(pwallet, batch, DBKeys::ORDERPOSNEXT,\n        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {\n        try {\n            value >> pwallet->nOrderPosNext;\n        } catch (const std::exception& e) {\n            err = e.what();\n            return DBErrors::NONCRITICAL_ERROR;\n        }\n        return DBErrors::LOAD_OK;\n    });\n    result = std::max(result, order_pos_res.m_result);\n\n    // After loading all tx records, abandon any coinbase that is no longer in the active chain.\n    // This could happen during an external wallet load, or if the user replaced the chain data.\n    for (auto& [id, wtx] : pwallet->mapWallet) {\n        if (wtx.IsCoinBase() && wtx.isInactive()) {\n            pwallet->AbandonTransaction(wtx);\n        }\n    }\n\n    return result;\n}\n\nstatic DBErrors LoadActiveSPKMs(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)\n{\n    AssertLockHeld(pwallet->cs_wallet);\n    DBErrors result = DBErrors::LOAD_OK;\n\n    // Load spk records\n    std::set<std::pair<OutputType, bool>> seen_spks;\n    for (const auto& spk_key : {DBKeys::ACTIVEEXTERNALSPK, DBKeys::ACTIVEINTERNALSPK}) {\n        LoadResult spkm_res = LoadRecords(pwallet, batch, spk_key,\n            [&seen_spks, &spk_key] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {\n            uint8_t output_type;\n            key >> output_type;\n            uint256 id;\n            value >> id;\n\n            bool internal = spk_key == DBKeys::ACTIVEINTERNALSPK;\n            auto [it, insert] = seen_spks.emplace(static_cast<OutputType>(output_type), internal);\n            if (!insert) {\n                strErr = \"Multiple ScriptpubKeyMans specified for a single type\";\n                return DBErrors::CORRUPT;\n            }\n            pwallet->LoadActiveScriptPubKeyMan(id, static_cast<OutputType>(output_type), /*internal=*/internal);\n            return DBErrors::LOAD_OK;\n        });\n        result = std::max(result, spkm_res.m_result);\n    }\n    return result;\n}\n\nstatic DBErrors LoadDecryptionKeys(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)\n{\n    AssertLockHeld(pwallet->cs_wallet);\n\n    // Load decryption key (mkey) records\n    LoadResult mkey_res = LoadRecords(pwallet, batch, DBKeys::MASTER_KEY,\n        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {\n        if (!LoadEncryptionKey(pwallet, key, value, err)) {\n            return DBErrors::CORRUPT;\n        }\n        return DBErrors::LOAD_OK;\n    });\n    return mkey_res.m_result;\n}\n\nDBErrors WalletBatch::LoadWallet(CWallet* pwallet)\n{\n    DBErrors result = DBErrors::LOAD_OK;\n\n    LOCK(pwallet->cs_wallet);\n\n    // Last client version to open this wallet\n    int last_client = VERSION_LATEST;\n    bool has_last_client = m_batch->Read(DBKeys::VERSION, last_client);\n    if (has_last_client) pwallet->WalletLogPrintf(\"Last client version = %d\", last_client);\n\n    std::optional<uint64_t> last_client_features;\n    if (last_client >= VERSION_LAST_CLIENT_FEATURES) {\n        // Features of last client to open this wallet\n        if (uint64_t features; m_batch->Read(DBKeys::LAST_OPENED_FEATURES, features)) {\n            last_client_features = features;\n        }\n\n        // Features of last client to decrypt this wallet\n        if (uint64_t last_decrypted; m_batch->Read(DBKeys::LAST_DECRYPTED_FEATURES, last_decrypted)) {\n            pwallet->SetLastDecryptedFeatures(last_decrypted);\n        }",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 7d6b70947318..d5a3f2186402

2026-11-26T00:08:30Z · gpt-6-luna

bitcoin#36897The journal-test commit message describes deletion instead of preservationtest/functional/wallet_migration.pyunclear
Assessment

The finding concerns commit-message wording, while the supplied evidence shows only source and a diff, not the commit message at the new head.

new_source: test/functional/wallet_migration.py

[
  {
    "bounded": true,
    "end_line": 336,
    "evidence_id": "d761f88d91e04b629a9363b189766355",
    "finding_id": "finding:15",
    "kind": "new_source",
    "line": 187,
    "new_head": "d5a3f21864021b03bfbc7441c357e47e4ae4722f",
    "old_head": "7d6b7094731837d7b80def7317146acba9c23a15",
    "path": "test/functional/wallet_migration.py",
    "revision": "d5a3f21864021b03bfbc7441c357e47e4ae4722f",
    "source_generation": 5,
    "source_job_id": 3092,
    "text": "                assert_greater_than(len(lh_cache_recs), 0)\n\n        inspect_path = os.path.join(self.options.tmpdir, os.path.basename(f\"{migrated_wallet_name}_inspect.dat\"))\n        wallet.backupwallet(inspect_path)\n        self.inspect_sqlite_db(inspect_path, check_last_hardened)\n\n        return migrate_info, wallet\n\n    def test_unwritable_dir_failure(self):\n        self.log.info(\"Test migration failure due to non-writable directory\")\n        wallet_name = \"bad_permissions\"\n        wallet = self.create_legacy_wallet(wallet_name)\n        wallet.unloadwallet()\n        shutil.copytree(self.old_node.wallets_path / wallet_name, self.master_node.wallets_path / wallet_name, dirs_exist_ok=True)\n\n        # Change dir perms and migrate\n        wallet_path = self.master_node.wallets_path / wallet_name\n        original_dir_perms = wallet_path.stat().st_mode\n        wallet_path.chmod(original_dir_perms & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH))\n        if is_dir_writable(wallet_path):\n            self.log.warning(\"Skipping migration non-writable directory test: unable to enforce read-only permissions\")\n        else:\n            assert_raises_rpc_error(-4, \"Error: Unable to create the new database for wallet 'bad_permissions'.\", self.master_node.migratewallet, wallet_name)\n        # Reset directory permissions\n        wallet_path.chmod(original_dir_perms)\n        self.assert_no_tmp_db(self.master_node.wallets_path)\n\n        # Check the wallet we tried to migrate is still BDB\n        self.assert_is_bdb(wallet_name)\n\n    def test_stale_journal(self):\n        self.log.info(\"Test migration fails if a leftover database journal is found at the wallet location\")\n        try:\n            import sqlite3  # type: ignore[import]\n        except ImportError:\n            self.log.warning(\"Skipping stale journal test: sqlite3 module not available\")\n            return\n        wallet_name = \"stale_journal\"\n        wallet = self.create_legacy_wallet(wallet_name)\n        wallet.unloadwallet()\n        wallet_path = self.master_node.wallets_path / wallet_name\n        shutil.copytree(self.old_node.wallets_path / wallet_name, wallet_path, dirs_exist_ok=True)\n        journal_path = wallet_path / \"wallet.dat-journal\"\n\n        # Leave the journal of an unrelated db at the wallet location, as a write interrupted by a crash would.\n        # Copying it in the middle of a transaction makes it \"hot\": SQLite rolls it back on the next open.\n        src_db = os.path.join(self.options.tmpdir, \"unrelated.dat\")\n        conn = sqlite3.connect(src_db, isolation_level=None)\n        conn.execute(\"CREATE TABLE t(v BLOB)\")\n        conn.execute(\"BEGIN\")\n        for _ in range(400):\n            conn.execute(\"INSERT INTO t VALUES (randomblob(200))\")\n        conn.execute(\"COMMIT\")\n        conn.execute(\"PRAGMA cache_size=2\")  # Make the next transaction write its changes to disk\n        conn.execute(\"BEGIN\")\n        conn.execute(\"UPDATE t SET v = randomblob(200)\")\n        shutil.copyfile(f\"{src_db}-journal\", journal_path)\n        conn.close()\n\n        # Migration must fail and keep the journal. Otherwise, SQLite rolls it back into the migrated wallet when opening\n        # it, and corrupts it.\n        assert_raises_rpc_error(-4, f\"Migration failed: Error: Unable to move the wallet db, unexpected file {journal_path} found at the destination. Move it elsewhere and try again.\", self.master_node.migratewallet, wallet_name)\n        assert journal_path.exists()\n        self.assert_no_tmp_db(self.master_node.wallets_path)\n        self.assert_is_bdb(wallet_name)\n\n    def test_db_named_as_journal(self):\n        self.log.info(\"Test migration does not remove a wallet database named like a journal of the migrated wallet\")\n        wallet_name = \"db_named_as_journal\"\n        wallet = self.create_legacy_wallet(wallet_name)\n        wallet.unloadwallet()\n        wallet_path = self.master_node.wallets_path / wallet_name\n        shutil.copytree(self.old_node.wallets_path / wallet_name, wallet_path, dirs_exist_ok=True)\n        journal_path = wallet_path / \"wallet.dat-journal\"\n        shutil.copyfile(wallet_path / \"wallet.dat\", journal_path)\n\n        assert_raises_rpc_error(-4, f\"Migration failed: Error: Unable to move the wallet db, unexpected file {journal_path} found at the destination. Move it elsewhere and try again.\", self.master_node.migratewallet, wallet_name)\n        assert journal_path.exists()\n        self.assert_no_tmp_db(self.master_node.wallets_path)\n        self.assert_is_bdb(wallet_name)\n\n    def test_other_filesystem(self):\n        self.log.info(\"Test migration of a wallet located on a different filesystem than the wallets directory\")\n        wallets_dev = os.stat(self.master_node.wallets_path).st_dev\n        other_fs = next((p for p in [Path(\"/dev/shm\"), Path(tempfile.gettempdir())] if p.is_dir() and os.stat(p).st_dev != wallets_dev), None)\n        if other_fs is None:\n            self.log.warning(\"Skipping migration on other filesystem test: no other filesystem available\")\n            return\n\n        with tempfile.TemporaryDirectory(prefix=\"wallet_migration_\", dir=other_fs) as parent_dir:\n            wallet_name = str(Path(parent_dir) / \"wallet\")\n            wallet = self.create_legacy_wallet(wallet_name)\n            addr = wallet.getnewaddress()\n\n            migrate_res, wallet = self.migrate_and_get_rpc(wallet_name)\n            assert_equal(wallet.getaddressinfo(addr)[\"ismine\"], True)\n            self.assert_no_tmp_db(parent_dir)  # tmp db is created next to the wallet, check it was cleaned up\n            wallet.unloadwallet()\n        os.remove(migrate_res[\"backup_path\"])\n\n    def test_basic(self):\n        # Update listtransctions' output from old nodes to be compatible\n        def listtransactions_compatibility(list):\n            deprecated_keys = {\"bip125-replaceable\"}\n            for obj in list:\n                for key in deprecated_keys:\n                    obj.pop(key)\n                obj[\"alternate_wtxids\"] = []\n            return list\n\n        default = self.master_node.get_wallet_rpc(self.default_wallet_name)\n\n        self.log.info(\"Test migration of a basic keys only wallet without balance\")\n        basic0 = self.create_legacy_wallet(\"basic0\")\n\n        addr = basic0.getnewaddress()\n        change = basic0.getrawchangeaddress()\n\n        old_addr_info = basic0.getaddressinfo(addr)\n        old_change_addr_info = basic0.getaddressinfo(change)\n        assert_equal(old_addr_info[\"ismine\"], True)\n        assert_equal(old_addr_info[\"hdkeypath\"], \"m/0'/0'/0'\")\n        assert_equal(old_change_addr_info[\"ismine\"], True)\n        assert_equal(old_change_addr_info[\"hdkeypath\"], \"m/0'/1'/0'\")\n\n        # Note: migration could take a while.\n        _, basic0 = self.migrate_and_get_rpc(\"basic0\")\n\n        # The wallet should create the following descriptors:\n        # * BIP32 descriptors in the form of \"0h/0h/*\" and \"0h/1h/*\" (2 descriptors)\n        # * BIP44 descriptors in the form of \"44h/1h/0h/0/*\" and \"44h/1h/0h/1/*\" (2 descriptors)\n        # * BIP49 descriptors, P2SH(P2WPKH), in the form of \"86h/1h/0h/0/*\" and \"86h/1h/0h/1/*\" (2 descriptors)\n        # * BIP84 descriptors, P2WPKH, in the form of \"84h/1h/0h/1/*\" and \"84h/1h/0h/1/*\" (2 descriptors)\n        # * BIP86 descriptors, P2TR, in the form of \"86h/1h/0h/0/*\" and \"86h/1h/0h/1/*\" (2 descriptors)\n        # * A combo(PK) descriptor for the wallet master key.\n        # So, should have a total of 11 descriptors on it.\n        assert_equal(len(basic0.listdescriptors()[\"descriptors\"]), 11)\n\n        # Compare addresses info\n        addr_info = basic0.getaddressinfo(addr)\n        change_addr_info = basic0.getaddressinfo(change)\n        self.assert_addr_info_equal(addr_info, old_addr_info)\n        self.assert_addr_info_equal(change_addr_info, old_change_addr_info)\n\n        addr_info = basic0.getaddressinfo(basic0.getnewaddress(\"\", \"bech32\"))\n        assert_equal(addr_info[\"hdkeypath\"], \"m/84h/1h/0h/0/0\")\n\n        self.log.info(\"Test migration of a basic keys only wallet with a balance\")\n        basic1 = self.create_legacy_wallet(\"basic1\")\n",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 7d6b70947318..d5a3f2186402

2026-11-26T00:08:30Z · gpt-6-luna

bitcoin#36897The ReorderTransactions move also changes descriptor-load compatibilitysrc/wallet/walletdb.cppstill_present
Assessment

The new-head excerpt still rejects transactions with missing nOrderPos through Assume and returns CORRUPT; it provides no evidence of a separate behavior change before the method move.

new_source: src/wallet/walletdb.cpp

[
  {
    "bounded": true,
    "end_line": 831,
    "evidence_id": "39266af7afcc46b1982645b2c985a42d",
    "finding_id": "finding:14",
    "kind": "new_source",
    "line": 682,
    "new_head": "d5a3f21864021b03bfbc7441c357e47e4ae4722f",
    "old_head": "7d6b7094731837d7b80def7317146acba9c23a15",
    "path": "src/wallet/walletdb.cpp",
    "revision": "d5a3f21864021b03bfbc7441c357e47e4ae4722f",
    "source_generation": 5,
    "source_job_id": 3092,
    "text": "        }\n        CTransactionRef tx;\n        value >> TX_WITH_WITNESS(tx);\n        if (tx->GetHash() != txid) {\n            throw std::runtime_error(strprintf(\"Corrupted witness variant, tx hash differs\"));\n        }\n        if (!variants.emplace(tx->GetWitnessHash(), std::move(tx)).second) {\n            throw std::runtime_error(strprintf(\"Duplicate witness variant\"));\n        }\n    }\n    return variants;\n}\n\nstatic DBErrors LoadTxRecords(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)\n{\n    AssertLockHeld(pwallet->cs_wallet);\n    DBErrors result = DBErrors::LOAD_OK;\n\n    // Load tx record\n    LoadResult tx_res = LoadRecords(pwallet, batch, DBKeys::TX,\n        [&batch] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {\n        DBErrors result = DBErrors::LOAD_OK;\n        Txid hash;\n        key >> hash;\n        try {\n            CWalletTx wtx{deserialize, value, ReadWtxVariants(batch, hash)};\n            if (wtx.GetHash() != hash) {\n                result = std::max(result, DBErrors::NEED_RESCAN);\n            }\n\n            if (!Assume(wtx.nOrderPos >= 0)) {\n                err = \"Error: Transaction missing nOrderPos\";\n                return DBErrors::CORRUPT;\n            }\n\n            if (!pwallet->LoadToWallet(std::move(wtx))) {\n                err = \"Error: Corrupt transaction found. This can be fixed by removing transactions from wallet and rescanning.\";\n                return DBErrors::CORRUPT;\n            }\n        } catch (const std::exception& e) {\n            err = strprintf(\"Error: Corrupt tx record found: %s\" ,e.what());\n            return DBErrors::CORRUPT;\n        }\n        return result;\n    });\n    result = std::max(result, tx_res.m_result);\n\n    // Load locked utxo record\n    LoadResult locked_utxo_res = LoadRecords(pwallet, batch, DBKeys::LOCKED_UTXO,\n        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {\n        Txid hash;\n        uint32_t n;\n        key >> hash;\n        key >> n;\n        pwallet->LoadLockedCoin(COutPoint(hash, n), /*persistent=*/true);\n        return DBErrors::LOAD_OK;\n    });\n    result = std::max(result, locked_utxo_res.m_result);\n\n    // Load orderposnext record\n    // Note: There should only be one ORDERPOSNEXT record with nothing trailing the type\n    LoadResult order_pos_res = LoadRecords(pwallet, batch, DBKeys::ORDERPOSNEXT,\n        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {\n        try {\n            value >> pwallet->nOrderPosNext;\n        } catch (const std::exception& e) {\n            err = e.what();\n            return DBErrors::NONCRITICAL_ERROR;\n        }\n        return DBErrors::LOAD_OK;\n    });\n    result = std::max(result, order_pos_res.m_result);\n\n    // After loading all tx records, abandon any coinbase that is no longer in the active chain.\n    // This could happen during an external wallet load, or if the user replaced the chain data.\n    for (auto& [id, wtx] : pwallet->mapWallet) {\n        if (wtx.IsCoinBase() && wtx.isInactive()) {\n            pwallet->AbandonTransaction(wtx);\n        }\n    }\n\n    return result;\n}\n\nstatic DBErrors LoadActiveSPKMs(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)\n{\n    AssertLockHeld(pwallet->cs_wallet);\n    DBErrors result = DBErrors::LOAD_OK;\n\n    // Load spk records\n    std::set<std::pair<OutputType, bool>> seen_spks;\n    for (const auto& spk_key : {DBKeys::ACTIVEEXTERNALSPK, DBKeys::ACTIVEINTERNALSPK}) {\n        LoadResult spkm_res = LoadRecords(pwallet, batch, spk_key,\n            [&seen_spks, &spk_key] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& strErr) {\n            uint8_t output_type;\n            key >> output_type;\n            uint256 id;\n            value >> id;\n\n            bool internal = spk_key == DBKeys::ACTIVEINTERNALSPK;\n            auto [it, insert] = seen_spks.emplace(static_cast<OutputType>(output_type), internal);\n            if (!insert) {\n                strErr = \"Multiple ScriptpubKeyMans specified for a single type\";\n                return DBErrors::CORRUPT;\n            }\n            pwallet->LoadActiveScriptPubKeyMan(id, static_cast<OutputType>(output_type), /*internal=*/internal);\n            return DBErrors::LOAD_OK;\n        });\n        result = std::max(result, spkm_res.m_result);\n    }\n    return result;\n}\n\nstatic DBErrors LoadDecryptionKeys(CWallet* pwallet, DatabaseBatch& batch) EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet)\n{\n    AssertLockHeld(pwallet->cs_wallet);\n\n    // Load decryption key (mkey) records\n    LoadResult mkey_res = LoadRecords(pwallet, batch, DBKeys::MASTER_KEY,\n        [] (CWallet* pwallet, DataStream& key, DataStream& value, std::string& err) {\n        if (!LoadEncryptionKey(pwallet, key, value, err)) {\n            return DBErrors::CORRUPT;\n        }\n        return DBErrors::LOAD_OK;\n    });\n    return mkey_res.m_result;\n}\n\nDBErrors WalletBatch::LoadWallet(CWallet* pwallet)\n{\n    DBErrors result = DBErrors::LOAD_OK;\n\n    LOCK(pwallet->cs_wallet);\n\n    // Last client version to open this wallet\n    int last_client = VERSION_LATEST;\n    bool has_last_client = m_batch->Read(DBKeys::VERSION, last_client);\n    if (has_last_client) pwallet->WalletLogPrintf(\"Last client version = %d\", last_client);\n\n    std::optional<uint64_t> last_client_features;\n    if (last_client >= VERSION_LAST_CLIENT_FEATURES) {\n        // Features of last client to open this wallet\n        if (uint64_t features; m_batch->Read(DBKeys::LAST_OPENED_FEATURES, features)) {\n            last_client_features = features;\n        }\n\n        // Features of last client to decrypt this wallet\n        if (uint64_t last_decrypted; m_batch->Read(DBKeys::LAST_DECRYPTED_FEATURES, last_decrypted)) {\n            pwallet->SetLastDecryptedFeatures(last_decrypted);\n        }",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 7d6b70947318..d5a3f2186402

2026-11-26T00:08:30Z · gpt-6-luna

bitcoin#36897Migration-failure tests do not verify file preservation or retryabilitytest/functional/wallet_migration.pystill_present
Assessment

The new-head journal tests still only check journal existence, temporary-file cleanup, and the BDB header. They do not hash/compare the wallet or blocker, retry migration, or verify prior address ownership.

new_source: test/functional/wallet_migration.py

[
  {
    "bounded": true,
    "end_line": 368,
    "evidence_id": "fa699399708b4c8c8bb9efd9a10e5c00",
    "finding_id": "finding:13",
    "kind": "new_source",
    "line": 219,
    "new_head": "d5a3f21864021b03bfbc7441c357e47e4ae4722f",
    "old_head": "7d6b7094731837d7b80def7317146acba9c23a15",
    "path": "test/functional/wallet_migration.py",
    "revision": "d5a3f21864021b03bfbc7441c357e47e4ae4722f",
    "source_generation": 5,
    "source_job_id": 3092,
    "text": "        try:\n            import sqlite3  # type: ignore[import]\n        except ImportError:\n            self.log.warning(\"Skipping stale journal test: sqlite3 module not available\")\n            return\n        wallet_name = \"stale_journal\"\n        wallet = self.create_legacy_wallet(wallet_name)\n        wallet.unloadwallet()\n        wallet_path = self.master_node.wallets_path / wallet_name\n        shutil.copytree(self.old_node.wallets_path / wallet_name, wallet_path, dirs_exist_ok=True)\n        journal_path = wallet_path / \"wallet.dat-journal\"\n\n        # Leave the journal of an unrelated db at the wallet location, as a write interrupted by a crash would.\n        # Copying it in the middle of a transaction makes it \"hot\": SQLite rolls it back on the next open.\n        src_db = os.path.join(self.options.tmpdir, \"unrelated.dat\")\n        conn = sqlite3.connect(src_db, isolation_level=None)\n        conn.execute(\"CREATE TABLE t(v BLOB)\")\n        conn.execute(\"BEGIN\")\n        for _ in range(400):\n            conn.execute(\"INSERT INTO t VALUES (randomblob(200))\")\n        conn.execute(\"COMMIT\")\n        conn.execute(\"PRAGMA cache_size=2\")  # Make the next transaction write its changes to disk\n        conn.execute(\"BEGIN\")\n        conn.execute(\"UPDATE t SET v = randomblob(200)\")\n        shutil.copyfile(f\"{src_db}-journal\", journal_path)\n        conn.close()\n\n        # Migration must fail and keep the journal. Otherwise, SQLite rolls it back into the migrated wallet when opening\n        # it, and corrupts it.\n        assert_raises_rpc_error(-4, f\"Migration failed: Error: Unable to move the wallet db, unexpected file {journal_path} found at the destination. Move it elsewhere and try again.\", self.master_node.migratewallet, wallet_name)\n        assert journal_path.exists()\n        self.assert_no_tmp_db(self.master_node.wallets_path)\n        self.assert_is_bdb(wallet_name)\n\n    def test_db_named_as_journal(self):\n        self.log.info(\"Test migration does not remove a wallet database named like a journal of the migrated wallet\")\n        wallet_name = \"db_named_as_journal\"\n        wallet = self.create_legacy_wallet(wallet_name)\n        wallet.unloadwallet()\n        wallet_path = self.master_node.wallets_path / wallet_name\n        shutil.copytree(self.old_node.wallets_path / wallet_name, wallet_path, dirs_exist_ok=True)\n        journal_path = wallet_path / \"wallet.dat-journal\"\n        shutil.copyfile(wallet_path / \"wallet.dat\", journal_path)\n\n        assert_raises_rpc_error(-4, f\"Migration failed: Error: Unable to move the wallet db, unexpected file {journal_path} found at the destination. Move it elsewhere and try again.\", self.master_node.migratewallet, wallet_name)\n        assert journal_path.exists()\n        self.assert_no_tmp_db(self.master_node.wallets_path)\n        self.assert_is_bdb(wallet_name)\n\n    def test_other_filesystem(self):\n        self.log.info(\"Test migration of a wallet located on a different filesystem than the wallets directory\")\n        wallets_dev = os.stat(self.master_node.wallets_path).st_dev\n        other_fs = next((p for p in [Path(\"/dev/shm\"), Path(tempfile.gettempdir())] if p.is_dir() and os.stat(p).st_dev != wallets_dev), None)\n        if other_fs is None:\n            self.log.warning(\"Skipping migration on other filesystem test: no other filesystem available\")\n            return\n\n        with tempfile.TemporaryDirectory(prefix=\"wallet_migration_\", dir=other_fs) as parent_dir:\n            wallet_name = str(Path(parent_dir) / \"wallet\")\n            wallet = self.create_legacy_wallet(wallet_name)\n            addr = wallet.getnewaddress()\n\n            migrate_res, wallet = self.migrate_and_get_rpc(wallet_name)\n            assert_equal(wallet.getaddressinfo(addr)[\"ismine\"], True)\n            self.assert_no_tmp_db(parent_dir)  # tmp db is created next to the wallet, check it was cleaned up\n            wallet.unloadwallet()\n        os.remove(migrate_res[\"backup_path\"])\n\n    def test_basic(self):\n        # Update listtransctions' output from old nodes to be compatible\n        def listtransactions_compatibility(list):\n            deprecated_keys = {\"bip125-replaceable\"}\n            for obj in list:\n                for key in deprecated_keys:\n                    obj.pop(key)\n                obj[\"alternate_wtxids\"] = []\n            return list\n\n        default = self.master_node.get_wallet_rpc(self.default_wallet_name)\n\n        self.log.info(\"Test migration of a basic keys only wallet without balance\")\n        basic0 = self.create_legacy_wallet(\"basic0\")\n\n        addr = basic0.getnewaddress()\n        change = basic0.getrawchangeaddress()\n\n        old_addr_info = basic0.getaddressinfo(addr)\n        old_change_addr_info = basic0.getaddressinfo(change)\n        assert_equal(old_addr_info[\"ismine\"], True)\n        assert_equal(old_addr_info[\"hdkeypath\"], \"m/0'/0'/0'\")\n        assert_equal(old_change_addr_info[\"ismine\"], True)\n        assert_equal(old_change_addr_info[\"hdkeypath\"], \"m/0'/1'/0'\")\n\n        # Note: migration could take a while.\n        _, basic0 = self.migrate_and_get_rpc(\"basic0\")\n\n        # The wallet should create the following descriptors:\n        # * BIP32 descriptors in the form of \"0h/0h/*\" and \"0h/1h/*\" (2 descriptors)\n        # * BIP44 descriptors in the form of \"44h/1h/0h/0/*\" and \"44h/1h/0h/1/*\" (2 descriptors)\n        # * BIP49 descriptors, P2SH(P2WPKH), in the form of \"86h/1h/0h/0/*\" and \"86h/1h/0h/1/*\" (2 descriptors)\n        # * BIP84 descriptors, P2WPKH, in the form of \"84h/1h/0h/1/*\" and \"84h/1h/0h/1/*\" (2 descriptors)\n        # * BIP86 descriptors, P2TR, in the form of \"86h/1h/0h/0/*\" and \"86h/1h/0h/1/*\" (2 descriptors)\n        # * A combo(PK) descriptor for the wallet master key.\n        # So, should have a total of 11 descriptors on it.\n        assert_equal(len(basic0.listdescriptors()[\"descriptors\"]), 11)\n\n        # Compare addresses info\n        addr_info = basic0.getaddressinfo(addr)\n        change_addr_info = basic0.getaddressinfo(change)\n        self.assert_addr_info_equal(addr_info, old_addr_info)\n        self.assert_addr_info_equal(change_addr_info, old_change_addr_info)\n\n        addr_info = basic0.getaddressinfo(basic0.getnewaddress(\"\", \"bech32\"))\n        assert_equal(addr_info[\"hdkeypath\"], \"m/84h/1h/0h/0/0\")\n\n        self.log.info(\"Test migration of a basic keys only wallet with a balance\")\n        basic1 = self.create_legacy_wallet(\"basic1\")\n\n        for _ in range(0, 10):\n            default.sendtoaddress(basic1.getnewaddress(), 1)\n\n        self.generate(self.master_node, 1)\n\n        for _ in range(0, 5):\n            basic1.sendtoaddress(default.getnewaddress(), 0.5)\n\n        self.generate(self.master_node, 1)\n        bal = basic1.getbalance()\n        txs = basic1.listtransactions()\n        addr_gps = basic1.listaddressgroupings()\n\n        basic1_migrate, basic1 = self.migrate_and_get_rpc(\"basic1\")\n        assert_equal(basic1.getbalance(), bal)\n        self.assert_list_txs_equal(basic1.listtransactions(), listtransactions_compatibility(txs))\n\n        self.log.info(\"Test backup file can be successfully restored\")\n        self.old_node.restorewallet(\"basic1_restored\", basic1_migrate['backup_path'])\n        basic1_restored = self.old_node.get_wallet_rpc(\"basic1_restored\")\n        basic1_restored_wi = basic1_restored.getwalletinfo()\n        assert_equal(basic1_restored_wi['balance'], bal)\n        assert_equal(basic1_restored.listaddressgroupings(), addr_gps)\n        self.assert_list_txs_equal(listtransactions_compatibility(basic1_restored.listtransactions()), txs)\n\n        # restart master node and verify that everything is still there\n        self.restart_node(0)\n        self.connect_nodes(0, 1)\n        default = self.master_node.get_wallet_rpc(self.default_wallet_name)\n        self.master_node.loadwallet(\"basic1\")\n        basic1 = self.master_node.get_wallet_rpc(\"basic1\")\n        assert_equal(basic1.getbalance(), bal)",
    "repository_id": "core",
    "repository": "bitcoin/bitcoin",
    "repository_url": "https://github.com/bitcoin/bitcoin"
  }
]

Source report · 7d6b70947318..d5a3f2186402

2026-11-26T00:08:30Z · gpt-6-luna

Conceptual concerns

The archaeology pass can complete without publishing a concern. Published conceptual concerns are tracked separately from code findings.

1,574 saved reviews completed archaeology research; 22 saved and 22 published a conceptual concern.

StatusReviews
candidate42
drop41
failed18
no_concern1,427
unresolved42
verified22

Median citations: 2.5; median alternatives: 1.0.