Bitcoin Core Fuzz Coverage Report for wallet_tx_can_be_bumped

Coverage Report

Created: 2025-11-19 11:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/Users/brunogarcia/projects/bitcoin-core-dev/src/script/signingprovider.cpp
Line
Count
Source
1
// Copyright (c) 2009-2010 Satoshi Nakamoto
2
// Copyright (c) 2009-present The Bitcoin Core developers
3
// Distributed under the MIT software license, see the accompanying
4
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6
#include <script/keyorigin.h>
7
#include <script/interpreter.h>
8
#include <script/signingprovider.h>
9
10
#include <logging.h>
11
12
const SigningProvider& DUMMY_SIGNING_PROVIDER = SigningProvider();
13
14
template<typename M, typename K, typename V>
15
bool LookupHelper(const M& map, const K& key, V& value)
16
0
{
17
0
    auto it = map.find(key);
18
0
    if (it != map.end()) {
19
0
        value = it->second;
20
0
        return true;
21
0
    }
22
0
    return false;
23
0
}
Unexecuted instantiation: bool LookupHelper<std::__1::map<CScriptID, CScript, std::__1::less<CScriptID>, std::__1::allocator<std::__1::pair<CScriptID const, CScript>>>, CScriptID, CScript>(std::__1::map<CScriptID, CScript, std::__1::less<CScriptID>, std::__1::allocator<std::__1::pair<CScriptID const, CScript>>> const&, CScriptID const&, CScript&)
Unexecuted instantiation: bool LookupHelper<std::__1::map<CKeyID, CPubKey, std::__1::less<CKeyID>, std::__1::allocator<std::__1::pair<CKeyID const, CPubKey>>>, CKeyID, CPubKey>(std::__1::map<CKeyID, CPubKey, std::__1::less<CKeyID>, std::__1::allocator<std::__1::pair<CKeyID const, CPubKey>>> const&, CKeyID const&, CPubKey&)
Unexecuted instantiation: bool LookupHelper<std::__1::map<CKeyID, std::__1::pair<CPubKey, KeyOriginInfo>, std::__1::less<CKeyID>, std::__1::allocator<std::__1::pair<CKeyID const, std::__1::pair<CPubKey, KeyOriginInfo>>>>, CKeyID, std::__1::pair<CPubKey, KeyOriginInfo>>(std::__1::map<CKeyID, std::__1::pair<CPubKey, KeyOriginInfo>, std::__1::less<CKeyID>, std::__1::allocator<std::__1::pair<CKeyID const, std::__1::pair<CPubKey, KeyOriginInfo>>>> const&, CKeyID const&, std::__1::pair<CPubKey, KeyOriginInfo>&)
Unexecuted instantiation: bool LookupHelper<std::__1::map<CKeyID, CKey, std::__1::less<CKeyID>, std::__1::allocator<std::__1::pair<CKeyID const, CKey>>>, CKeyID, CKey>(std::__1::map<CKeyID, CKey, std::__1::less<CKeyID>, std::__1::allocator<std::__1::pair<CKeyID const, CKey>>> const&, CKeyID const&, CKey&)
Unexecuted instantiation: bool LookupHelper<std::__1::map<XOnlyPubKey, TaprootBuilder, std::__1::less<XOnlyPubKey>, std::__1::allocator<std::__1::pair<XOnlyPubKey const, TaprootBuilder>>>, XOnlyPubKey, TaprootBuilder>(std::__1::map<XOnlyPubKey, TaprootBuilder, std::__1::less<XOnlyPubKey>, std::__1::allocator<std::__1::pair<XOnlyPubKey const, TaprootBuilder>>> const&, XOnlyPubKey const&, TaprootBuilder&)
Unexecuted instantiation: bool LookupHelper<std::__1::map<CPubKey, std::__1::vector<CPubKey, std::__1::allocator<CPubKey>>, std::__1::less<CPubKey>, std::__1::allocator<std::__1::pair<CPubKey const, std::__1::vector<CPubKey, std::__1::allocator<CPubKey>>>>>, CPubKey, std::__1::vector<CPubKey, std::__1::allocator<CPubKey>>>(std::__1::map<CPubKey, std::__1::vector<CPubKey, std::__1::allocator<CPubKey>>, std::__1::less<CPubKey>, std::__1::allocator<std::__1::pair<CPubKey const, std::__1::vector<CPubKey, std::__1::allocator<CPubKey>>>>> const&, CPubKey const&, std::__1::vector<CPubKey, std::__1::allocator<CPubKey>>&)
24
25
bool HidingSigningProvider::GetCScript(const CScriptID& scriptid, CScript& script) const
26
0
{
27
0
    return m_provider->GetCScript(scriptid, script);
28
0
}
29
30
bool HidingSigningProvider::GetPubKey(const CKeyID& keyid, CPubKey& pubkey) const
31
0
{
32
0
    return m_provider->GetPubKey(keyid, pubkey);
33
0
}
34
35
bool HidingSigningProvider::GetKey(const CKeyID& keyid, CKey& key) const
36
0
{
37
0
    if (m_hide_secret) return false;
38
0
    return m_provider->GetKey(keyid, key);
39
0
}
40
41
bool HidingSigningProvider::GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const
42
0
{
43
0
    if (m_hide_origin) return false;
44
0
    return m_provider->GetKeyOrigin(keyid, info);
45
0
}
46
47
bool HidingSigningProvider::GetTaprootSpendData(const XOnlyPubKey& output_key, TaprootSpendData& spenddata) const
48
0
{
49
0
    return m_provider->GetTaprootSpendData(output_key, spenddata);
50
0
}
51
bool HidingSigningProvider::GetTaprootBuilder(const XOnlyPubKey& output_key, TaprootBuilder& builder) const
52
0
{
53
0
    return m_provider->GetTaprootBuilder(output_key, builder);
54
0
}
55
std::vector<CPubKey> HidingSigningProvider::GetMuSig2ParticipantPubkeys(const CPubKey& pubkey) const
56
0
{
57
0
    if (m_hide_origin) return {};
58
0
    return m_provider->GetMuSig2ParticipantPubkeys(pubkey);
59
0
}
60
61
std::map<CPubKey, std::vector<CPubKey>> HidingSigningProvider::GetAllMuSig2ParticipantPubkeys() const
62
0
{
63
0
    return m_provider->GetAllMuSig2ParticipantPubkeys();
64
0
}
65
66
void HidingSigningProvider::SetMuSig2SecNonce(const uint256& id, MuSig2SecNonce&& nonce) const
67
0
{
68
0
    m_provider->SetMuSig2SecNonce(id, std::move(nonce));
69
0
}
70
71
std::optional<std::reference_wrapper<MuSig2SecNonce>> HidingSigningProvider::GetMuSig2SecNonce(const uint256& session_id) const
72
0
{
73
0
    return m_provider->GetMuSig2SecNonce(session_id);
74
0
}
75
76
void HidingSigningProvider::DeleteMuSig2Session(const uint256& session_id) const
77
0
{
78
0
    m_provider->DeleteMuSig2Session(session_id);
79
0
}
80
81
0
bool FlatSigningProvider::GetCScript(const CScriptID& scriptid, CScript& script) const { return LookupHelper(scripts, scriptid, script); }
82
0
bool FlatSigningProvider::GetPubKey(const CKeyID& keyid, CPubKey& pubkey) const { return LookupHelper(pubkeys, keyid, pubkey); }
83
bool FlatSigningProvider::GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const
84
0
{
85
0
    std::pair<CPubKey, KeyOriginInfo> out;
86
0
    bool ret = LookupHelper(origins, keyid, out);
87
0
    if (ret) info = std::move(out.second);
88
0
    return ret;
89
0
}
90
bool FlatSigningProvider::HaveKey(const CKeyID &keyid) const
91
0
{
92
0
    CKey key;
93
0
    return LookupHelper(keys, keyid, key);
94
0
}
95
0
bool FlatSigningProvider::GetKey(const CKeyID& keyid, CKey& key) const { return LookupHelper(keys, keyid, key); }
96
bool FlatSigningProvider::GetTaprootSpendData(const XOnlyPubKey& output_key, TaprootSpendData& spenddata) const
97
0
{
98
0
    TaprootBuilder builder;
99
0
    if (LookupHelper(tr_trees, output_key, builder)) {
100
0
        spenddata = builder.GetSpendData();
101
0
        return true;
102
0
    }
103
0
    return false;
104
0
}
105
bool FlatSigningProvider::GetTaprootBuilder(const XOnlyPubKey& output_key, TaprootBuilder& builder) const
106
0
{
107
0
    return LookupHelper(tr_trees, output_key, builder);
108
0
}
109
110
std::vector<CPubKey> FlatSigningProvider::GetMuSig2ParticipantPubkeys(const CPubKey& pubkey) const
111
0
{
112
0
    std::vector<CPubKey> participant_pubkeys;
113
0
    LookupHelper(aggregate_pubkeys, pubkey, participant_pubkeys);
114
0
    return participant_pubkeys;
115
0
}
116
117
std::map<CPubKey, std::vector<CPubKey>> FlatSigningProvider::GetAllMuSig2ParticipantPubkeys() const
118
0
{
119
0
    return aggregate_pubkeys;
120
0
}
121
122
void FlatSigningProvider::SetMuSig2SecNonce(const uint256& session_id, MuSig2SecNonce&& nonce) const
123
0
{
124
0
    if (!Assume(musig2_secnonces)) return;
Line
Count
Source
125
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
125
0
    musig2_secnonces->emplace(session_id, std::move(nonce));
126
0
}
127
128
std::optional<std::reference_wrapper<MuSig2SecNonce>> FlatSigningProvider::GetMuSig2SecNonce(const uint256& session_id) const
129
0
{
130
0
    if (!Assume(musig2_secnonces)) return std::nullopt;
Line
Count
Source
125
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
131
0
    const auto& it = musig2_secnonces->find(session_id);
132
0
    if (it == musig2_secnonces->end()) return std::nullopt;
133
0
    return it->second;
134
0
}
135
136
void FlatSigningProvider::DeleteMuSig2Session(const uint256& session_id) const
137
0
{
138
0
    if (!Assume(musig2_secnonces)) return;
Line
Count
Source
125
0
#define Assume(val) inline_assertion_check<false>(val, std::source_location::current(), #val)
139
0
    musig2_secnonces->erase(session_id);
140
0
}
141
142
FlatSigningProvider& FlatSigningProvider::Merge(FlatSigningProvider&& b)
143
118k
{
144
118k
    scripts.merge(b.scripts);
145
118k
    pubkeys.merge(b.pubkeys);
146
118k
    keys.merge(b.keys);
147
118k
    origins.merge(b.origins);
148
118k
    tr_trees.merge(b.tr_trees);
149
118k
    aggregate_pubkeys.merge(b.aggregate_pubkeys);
150
    // We shouldn't be merging 2 different sessions, just overwrite with b's sessions.
151
118k
    if (!musig2_secnonces) musig2_secnonces = b.musig2_secnonces;
152
118k
    return *this;
153
118k
}
154
155
void FillableSigningProvider::ImplicitlyLearnRelatedKeyScripts(const CPubKey& pubkey)
156
0
{
157
0
    AssertLockHeld(cs_KeyStore);
Line
Count
Source
137
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
158
0
    CKeyID key_id = pubkey.GetID();
159
    // This adds the redeemscripts necessary to detect P2WPKH and P2SH-P2WPKH
160
    // outputs. Technically P2WPKH outputs don't have a redeemscript to be
161
    // spent. However, our current IsMine logic requires the corresponding
162
    // P2SH-P2WPKH redeemscript to be present in the wallet in order to accept
163
    // payment even to P2WPKH outputs.
164
    // Also note that having superfluous scripts in the keystore never hurts.
165
    // They're only used to guide recursion in signing and IsMine logic - if
166
    // a script is present but we can't do anything with it, it has no effect.
167
    // "Implicitly" refers to fact that scripts are derived automatically from
168
    // existing keys, and are present in memory, even without being explicitly
169
    // loaded (e.g. from a file).
170
0
    if (pubkey.IsCompressed()) {
171
0
        CScript script = GetScriptForDestination(WitnessV0KeyHash(key_id));
172
        // This does not use AddCScript, as it may be overridden.
173
0
        CScriptID id(script);
174
0
        mapScripts[id] = std::move(script);
175
0
    }
176
0
}
177
178
bool FillableSigningProvider::GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const
179
0
{
180
0
    CKey key;
181
0
    if (!GetKey(address, key)) {
182
0
        return false;
183
0
    }
184
0
    vchPubKeyOut = key.GetPubKey();
185
0
    return true;
186
0
}
187
188
bool FillableSigningProvider::AddKeyPubKey(const CKey& key, const CPubKey &pubkey)
189
0
{
190
0
    LOCK(cs_KeyStore);
Line
Count
Source
259
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
191
0
    mapKeys[pubkey.GetID()] = key;
192
0
    ImplicitlyLearnRelatedKeyScripts(pubkey);
193
0
    return true;
194
0
}
195
196
bool FillableSigningProvider::HaveKey(const CKeyID &address) const
197
0
{
198
0
    LOCK(cs_KeyStore);
Line
Count
Source
259
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
199
0
    return mapKeys.count(address) > 0;
200
0
}
201
202
std::set<CKeyID> FillableSigningProvider::GetKeys() const
203
0
{
204
0
    LOCK(cs_KeyStore);
Line
Count
Source
259
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
205
0
    std::set<CKeyID> set_address;
206
0
    for (const auto& mi : mapKeys) {
207
0
        set_address.insert(mi.first);
208
0
    }
209
0
    return set_address;
210
0
}
211
212
bool FillableSigningProvider::GetKey(const CKeyID &address, CKey &keyOut) const
213
0
{
214
0
    LOCK(cs_KeyStore);
Line
Count
Source
259
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
215
0
    KeyMap::const_iterator mi = mapKeys.find(address);
216
0
    if (mi != mapKeys.end()) {
217
0
        keyOut = mi->second;
218
0
        return true;
219
0
    }
220
0
    return false;
221
0
}
222
223
bool FillableSigningProvider::AddCScript(const CScript& redeemScript)
224
0
{
225
0
    if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE) {
226
0
        LogError("FillableSigningProvider::AddCScript(): redeemScripts > %i bytes are invalid\n", MAX_SCRIPT_ELEMENT_SIZE);
Line
Count
Source
370
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
362
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__)
227
0
        return false;
228
0
    }
229
230
0
    LOCK(cs_KeyStore);
Line
Count
Source
259
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
231
0
    mapScripts[CScriptID(redeemScript)] = redeemScript;
232
0
    return true;
233
0
}
234
235
bool FillableSigningProvider::HaveCScript(const CScriptID& hash) const
236
0
{
237
0
    LOCK(cs_KeyStore);
Line
Count
Source
259
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
238
0
    return mapScripts.count(hash) > 0;
239
0
}
240
241
std::set<CScriptID> FillableSigningProvider::GetCScripts() const
242
0
{
243
0
    LOCK(cs_KeyStore);
Line
Count
Source
259
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
244
0
    std::set<CScriptID> set_script;
245
0
    for (const auto& mi : mapScripts) {
246
0
        set_script.insert(mi.first);
247
0
    }
248
0
    return set_script;
249
0
}
250
251
bool FillableSigningProvider::GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const
252
0
{
253
0
    LOCK(cs_KeyStore);
Line
Count
Source
259
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
254
0
    ScriptMap::const_iterator mi = mapScripts.find(hash);
255
0
    if (mi != mapScripts.end())
256
0
    {
257
0
        redeemScriptOut = (*mi).second;
258
0
        return true;
259
0
    }
260
0
    return false;
261
0
}
262
263
CKeyID GetKeyForDestination(const SigningProvider& store, const CTxDestination& dest)
264
0
{
265
    // Only supports destinations which map to single public keys:
266
    // P2PKH, P2WPKH, P2SH-P2WPKH, P2TR
267
0
    if (auto id = std::get_if<PKHash>(&dest)) {
268
0
        return ToKeyID(*id);
269
0
    }
270
0
    if (auto witness_id = std::get_if<WitnessV0KeyHash>(&dest)) {
271
0
        return ToKeyID(*witness_id);
272
0
    }
273
0
    if (auto script_hash = std::get_if<ScriptHash>(&dest)) {
274
0
        CScript script;
275
0
        CScriptID script_id = ToScriptID(*script_hash);
276
0
        CTxDestination inner_dest;
277
0
        if (store.GetCScript(script_id, script) && ExtractDestination(script, inner_dest)) {
278
0
            if (auto inner_witness_id = std::get_if<WitnessV0KeyHash>(&inner_dest)) {
279
0
                return ToKeyID(*inner_witness_id);
280
0
            }
281
0
        }
282
0
    }
283
0
    if (auto output_key = std::get_if<WitnessV1Taproot>(&dest)) {
284
0
        TaprootSpendData spenddata;
285
0
        CPubKey pub;
286
0
        if (store.GetTaprootSpendData(*output_key, spenddata)
287
0
            && !spenddata.internal_key.IsNull()
288
0
            && spenddata.merkle_root.IsNull()
289
0
            && store.GetPubKeyByXOnly(spenddata.internal_key, pub)) {
290
0
            return pub.GetID();
291
0
        }
292
0
    }
293
0
    return CKeyID();
294
0
}
295
296
void MultiSigningProvider::AddProvider(std::unique_ptr<SigningProvider> provider)
297
0
{
298
0
    m_providers.push_back(std::move(provider));
299
0
}
300
301
bool MultiSigningProvider::GetCScript(const CScriptID& scriptid, CScript& script) const
302
0
{
303
0
    for (const auto& provider: m_providers) {
304
0
        if (provider->GetCScript(scriptid, script)) return true;
305
0
    }
306
0
    return false;
307
0
}
308
309
bool MultiSigningProvider::GetPubKey(const CKeyID& keyid, CPubKey& pubkey) const
310
0
{
311
0
    for (const auto& provider: m_providers) {
312
0
        if (provider->GetPubKey(keyid, pubkey)) return true;
313
0
    }
314
0
    return false;
315
0
}
316
317
318
bool MultiSigningProvider::GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const
319
0
{
320
0
    for (const auto& provider: m_providers) {
321
0
        if (provider->GetKeyOrigin(keyid, info)) return true;
322
0
    }
323
0
    return false;
324
0
}
325
326
bool MultiSigningProvider::GetKey(const CKeyID& keyid, CKey& key) const
327
0
{
328
0
    for (const auto& provider: m_providers) {
329
0
        if (provider->GetKey(keyid, key)) return true;
330
0
    }
331
0
    return false;
332
0
}
333
334
bool MultiSigningProvider::GetTaprootSpendData(const XOnlyPubKey& output_key, TaprootSpendData& spenddata) const
335
0
{
336
0
    for (const auto& provider: m_providers) {
337
0
        if (provider->GetTaprootSpendData(output_key, spenddata)) return true;
338
0
    }
339
0
    return false;
340
0
}
341
342
bool MultiSigningProvider::GetTaprootBuilder(const XOnlyPubKey& output_key, TaprootBuilder& builder) const
343
0
{
344
0
    for (const auto& provider: m_providers) {
345
0
        if (provider->GetTaprootBuilder(output_key, builder)) return true;
346
0
    }
347
0
    return false;
348
0
}
349
350
/*static*/ TaprootBuilder::NodeInfo TaprootBuilder::Combine(NodeInfo&& a, NodeInfo&& b)
351
0
{
352
0
    NodeInfo ret;
353
    /* Iterate over all tracked leaves in a, add b's hash to their Merkle branch, and move them to ret. */
354
0
    for (auto& leaf : a.leaves) {
355
0
        leaf.merkle_branch.push_back(b.hash);
356
0
        ret.leaves.emplace_back(std::move(leaf));
357
0
    }
358
    /* Iterate over all tracked leaves in b, add a's hash to their Merkle branch, and move them to ret. */
359
0
    for (auto& leaf : b.leaves) {
360
0
        leaf.merkle_branch.push_back(a.hash);
361
0
        ret.leaves.emplace_back(std::move(leaf));
362
0
    }
363
0
    ret.hash = ComputeTapbranchHash(a.hash, b.hash);
364
0
    return ret;
365
0
}
366
367
void TaprootSpendData::Merge(TaprootSpendData other)
368
0
{
369
    // TODO: figure out how to better deal with conflicting information
370
    // being merged.
371
0
    if (internal_key.IsNull() && !other.internal_key.IsNull()) {
372
0
        internal_key = other.internal_key;
373
0
    }
374
0
    if (merkle_root.IsNull() && !other.merkle_root.IsNull()) {
375
0
        merkle_root = other.merkle_root;
376
0
    }
377
0
    for (auto& [key, control_blocks] : other.scripts) {
378
0
        scripts[key].merge(std::move(control_blocks));
379
0
    }
380
0
}
381
382
void TaprootBuilder::Insert(TaprootBuilder::NodeInfo&& node, int depth)
383
0
{
384
0
    assert(depth >= 0 && (size_t)depth <= TAPROOT_CONTROL_MAX_NODE_COUNT);
385
    /* We cannot insert a leaf at a lower depth while a deeper branch is unfinished. Doing
386
     * so would mean the Add() invocations do not correspond to a DFS traversal of a
387
     * binary tree. */
388
0
    if ((size_t)depth + 1 < m_branch.size()) {
389
0
        m_valid = false;
390
0
        return;
391
0
    }
392
    /* As long as an entry in the branch exists at the specified depth, combine it and propagate up.
393
     * The 'node' variable is overwritten here with the newly combined node. */
394
0
    while (m_valid && m_branch.size() > (size_t)depth && m_branch[depth].has_value()) {
395
0
        node = Combine(std::move(node), std::move(*m_branch[depth]));
396
0
        m_branch.pop_back();
397
0
        if (depth == 0) m_valid = false; /* Can't propagate further up than the root */
398
0
        --depth;
399
0
    }
400
0
    if (m_valid) {
401
        /* Make sure the branch is big enough to place the new node. */
402
0
        if (m_branch.size() <= (size_t)depth) m_branch.resize((size_t)depth + 1);
403
0
        assert(!m_branch[depth].has_value());
404
0
        m_branch[depth] = std::move(node);
405
0
    }
406
0
}
407
408
/*static*/ bool TaprootBuilder::ValidDepths(const std::vector<int>& depths)
409
19.8k
{
410
19.8k
    std::vector<bool> branch;
411
19.8k
    for (int depth : depths) {
412
        // This inner loop corresponds to effectively the same logic on branch
413
        // as what Insert() performs on the m_branch variable. Instead of
414
        // storing a NodeInfo object, just remember whether or not there is one
415
        // at that depth.
416
0
        if (depth < 0 || (size_t)depth > TAPROOT_CONTROL_MAX_NODE_COUNT) return false;
417
0
        if ((size_t)depth + 1 < branch.size()) return false;
418
0
        while (branch.size() > (size_t)depth && branch[depth]) {
419
0
            branch.pop_back();
420
0
            if (depth == 0) return false;
421
0
            --depth;
422
0
        }
423
0
        if (branch.size() <= (size_t)depth) branch.resize((size_t)depth + 1);
424
0
        assert(!branch[depth]);
425
0
        branch[depth] = true;
426
0
    }
427
    // And this check corresponds to the IsComplete() check on m_branch.
428
19.8k
    return branch.size() == 0 || 
(0
branch.size() == 10
&&
branch[0]0
);
429
19.8k
}
430
431
TaprootBuilder& TaprootBuilder::Add(int depth, std::span<const unsigned char> script, int leaf_version, bool track)
432
0
{
433
0
    assert((leaf_version & ~TAPROOT_LEAF_MASK) == 0);
434
0
    if (!IsValid()) return *this;
435
    /* Construct NodeInfo object with leaf hash and (if track is true) also leaf information. */
436
0
    NodeInfo node;
437
0
    node.hash = ComputeTapleafHash(leaf_version, script);
438
0
    if (track) node.leaves.emplace_back(LeafInfo{std::vector<unsigned char>(script.begin(), script.end()), leaf_version, {}});
439
    /* Insert into the branch. */
440
0
    Insert(std::move(node), depth);
441
0
    return *this;
442
0
}
443
444
TaprootBuilder& TaprootBuilder::AddOmitted(int depth, const uint256& hash)
445
0
{
446
0
    if (!IsValid()) return *this;
447
    /* Construct NodeInfo object with the hash directly, and insert it into the branch. */
448
0
    NodeInfo node;
449
0
    node.hash = hash;
450
0
    Insert(std::move(node), depth);
451
0
    return *this;
452
0
}
453
454
TaprootBuilder& TaprootBuilder::Finalize(const XOnlyPubKey& internal_key)
455
24.5k
{
456
    /* Can only call this function when IsComplete() is true. */
457
24.5k
    assert(IsComplete());
458
24.5k
    m_internal_key = internal_key;
459
24.5k
    auto ret = m_internal_key.CreateTapTweak(m_branch.size() == 0 ? nullptr : 
&m_branch[0]->hash0
);
460
24.5k
    assert(ret.has_value());
461
24.5k
    std::tie(m_output_key, m_parity) = *ret;
462
24.5k
    return *this;
463
24.5k
}
464
465
24.5k
WitnessV1Taproot TaprootBuilder::GetOutput() { return WitnessV1Taproot{m_output_key}; }
466
467
TaprootSpendData TaprootBuilder::GetSpendData() const
468
0
{
469
0
    assert(IsComplete());
470
0
    assert(m_output_key.IsFullyValid());
471
0
    TaprootSpendData spd;
472
0
    spd.merkle_root = m_branch.size() == 0 ? uint256() : m_branch[0]->hash;
473
0
    spd.internal_key = m_internal_key;
474
0
    if (m_branch.size()) {
475
        // If any script paths exist, they have been combined into the root m_branch[0]
476
        // by now. Compute the control block for each of its tracked leaves, and put them in
477
        // spd.scripts.
478
0
        for (const auto& leaf : m_branch[0]->leaves) {
479
0
            std::vector<unsigned char> control_block;
480
0
            control_block.resize(TAPROOT_CONTROL_BASE_SIZE + TAPROOT_CONTROL_NODE_SIZE * leaf.merkle_branch.size());
481
0
            control_block[0] = leaf.leaf_version | (m_parity ? 1 : 0);
482
0
            std::copy(m_internal_key.begin(), m_internal_key.end(), control_block.begin() + 1);
483
0
            if (leaf.merkle_branch.size()) {
484
0
                std::copy(leaf.merkle_branch[0].begin(),
485
0
                          leaf.merkle_branch[0].begin() + TAPROOT_CONTROL_NODE_SIZE * leaf.merkle_branch.size(),
486
0
                          control_block.begin() + TAPROOT_CONTROL_BASE_SIZE);
487
0
            }
488
0
            spd.scripts[{leaf.script, leaf.leaf_version}].insert(std::move(control_block));
489
0
        }
490
0
    }
491
0
    return spd;
492
0
}
493
494
std::optional<std::vector<std::tuple<int, std::vector<unsigned char>, int>>> InferTaprootTree(const TaprootSpendData& spenddata, const XOnlyPubKey& output)
495
0
{
496
    // Verify that the output matches the assumed Merkle root and internal key.
497
0
    auto tweak = spenddata.internal_key.CreateTapTweak(spenddata.merkle_root.IsNull() ? nullptr : &spenddata.merkle_root);
498
0
    if (!tweak || tweak->first != output) return std::nullopt;
499
    // If the Merkle root is 0, the tree is empty, and we're done.
500
0
    std::vector<std::tuple<int, std::vector<unsigned char>, int>> ret;
501
0
    if (spenddata.merkle_root.IsNull()) return ret;
502
503
    /** Data structure to represent the nodes of the tree we're going to build. */
504
0
    struct TreeNode {
505
        /** Hash of this node, if known; 0 otherwise. */
506
0
        uint256 hash;
507
        /** The left and right subtrees (note that their order is irrelevant). */
508
0
        std::unique_ptr<TreeNode> sub[2];
509
        /** If this is known to be a leaf node, a pointer to the (script, leaf_ver) pair.
510
         *  nullptr otherwise. */
511
0
        const std::pair<std::vector<unsigned char>, int>* leaf = nullptr;
512
        /** Whether or not this node has been explored (is known to be a leaf, or known to have children). */
513
0
        bool explored = false;
514
        /** Whether or not this node is an inner node (unknown until explored = true). */
515
0
        bool inner;
516
        /** Whether or not we have produced output for this subtree. */
517
0
        bool done = false;
518
0
    };
519
520
    // Build tree from the provided branches.
521
0
    TreeNode root;
522
0
    root.hash = spenddata.merkle_root;
523
0
    for (const auto& [key, control_blocks] : spenddata.scripts) {
524
0
        const auto& [script, leaf_ver] = key;
525
0
        for (const auto& control : control_blocks) {
526
            // Skip script records with nonsensical leaf version.
527
0
            if (leaf_ver < 0 || leaf_ver >= 0x100 || leaf_ver & 1) continue;
528
            // Skip script records with invalid control block sizes.
529
0
            if (control.size() < TAPROOT_CONTROL_BASE_SIZE || control.size() > TAPROOT_CONTROL_MAX_SIZE ||
530
0
                ((control.size() - TAPROOT_CONTROL_BASE_SIZE) % TAPROOT_CONTROL_NODE_SIZE) != 0) continue;
531
            // Skip script records that don't match the control block.
532
0
            if ((control[0] & TAPROOT_LEAF_MASK) != leaf_ver) continue;
533
            // Skip script records that don't match the provided Merkle root.
534
0
            const uint256 leaf_hash = ComputeTapleafHash(leaf_ver, script);
535
0
            const uint256 merkle_root = ComputeTaprootMerkleRoot(control, leaf_hash);
536
0
            if (merkle_root != spenddata.merkle_root) continue;
537
538
0
            TreeNode* node = &root;
539
0
            size_t levels = (control.size() - TAPROOT_CONTROL_BASE_SIZE) / TAPROOT_CONTROL_NODE_SIZE;
540
0
            for (size_t depth = 0; depth < levels; ++depth) {
541
                // Can't descend into a node which we already know is a leaf.
542
0
                if (node->explored && !node->inner) return std::nullopt;
543
544
                // Extract partner hash from Merkle branch in control block.
545
0
                uint256 hash;
546
0
                std::copy(control.begin() + TAPROOT_CONTROL_BASE_SIZE + (levels - 1 - depth) * TAPROOT_CONTROL_NODE_SIZE,
547
0
                          control.begin() + TAPROOT_CONTROL_BASE_SIZE + (levels - depth) * TAPROOT_CONTROL_NODE_SIZE,
548
0
                          hash.begin());
549
550
0
                if (node->sub[0]) {
551
                    // Descend into the existing left or right branch.
552
0
                    bool desc = false;
553
0
                    for (int i = 0; i < 2; ++i) {
554
0
                        if (node->sub[i]->hash == hash || (node->sub[i]->hash.IsNull() && node->sub[1-i]->hash != hash)) {
555
0
                            node->sub[i]->hash = hash;
556
0
                            node = &*node->sub[1-i];
557
0
                            desc = true;
558
0
                            break;
559
0
                        }
560
0
                    }
561
0
                    if (!desc) return std::nullopt; // This probably requires a hash collision to hit.
562
0
                } else {
563
                    // We're in an unexplored node. Create subtrees and descend.
564
0
                    node->explored = true;
565
0
                    node->inner = true;
566
0
                    node->sub[0] = std::make_unique<TreeNode>();
567
0
                    node->sub[1] = std::make_unique<TreeNode>();
568
0
                    node->sub[1]->hash = hash;
569
0
                    node = &*node->sub[0];
570
0
                }
571
0
            }
572
            // Cannot turn a known inner node into a leaf.
573
0
            if (node->sub[0]) return std::nullopt;
574
0
            node->explored = true;
575
0
            node->inner = false;
576
0
            node->leaf = &key;
577
0
            node->hash = leaf_hash;
578
0
        }
579
0
    }
580
581
    // Recursive processing to turn the tree into flattened output. Use an explicit stack here to avoid
582
    // overflowing the call stack (the tree may be 128 levels deep).
583
0
    std::vector<TreeNode*> stack{&root};
584
0
    while (!stack.empty()) {
585
0
        TreeNode& node = *stack.back();
586
0
        if (!node.explored) {
587
            // Unexplored node, which means the tree is incomplete.
588
0
            return std::nullopt;
589
0
        } else if (!node.inner) {
590
            // Leaf node; produce output.
591
0
            ret.emplace_back(stack.size() - 1, node.leaf->first, node.leaf->second);
592
0
            node.done = true;
593
0
            stack.pop_back();
594
0
        } else if (node.sub[0]->done && !node.sub[1]->done && !node.sub[1]->explored && !node.sub[1]->hash.IsNull() &&
595
0
                   ComputeTapbranchHash(node.sub[1]->hash, node.sub[1]->hash) == node.hash) {
596
            // Whenever there are nodes with two identical subtrees under it, we run into a problem:
597
            // the control blocks for the leaves underneath those will be identical as well, and thus
598
            // they will all be matched to the same path in the tree. The result is that at the location
599
            // where the duplicate occurred, the left child will contain a normal tree that can be explored
600
            // and processed, but the right one will remain unexplored.
601
            //
602
            // This situation can be detected, by encountering an inner node with unexplored right subtree
603
            // with known hash, and H_TapBranch(hash, hash) is equal to the parent node (this node)'s hash.
604
            //
605
            // To deal with this, simply process the left tree a second time (set its done flag to false;
606
            // noting that the done flag of its children have already been set to false after processing
607
            // those). To avoid ending up in an infinite loop, set the done flag of the right (unexplored)
608
            // subtree to true.
609
0
            node.sub[0]->done = false;
610
0
            node.sub[1]->done = true;
611
0
        } else if (node.sub[0]->done && node.sub[1]->done) {
612
            // An internal node which we're finished with.
613
0
            node.sub[0]->done = false;
614
0
            node.sub[1]->done = false;
615
0
            node.done = true;
616
0
            stack.pop_back();
617
0
        } else if (!node.sub[0]->done) {
618
            // An internal node whose left branch hasn't been processed yet. Do so first.
619
0
            stack.push_back(&*node.sub[0]);
620
0
        } else if (!node.sub[1]->done) {
621
            // An internal node whose right branch hasn't been processed yet. Do so first.
622
0
            stack.push_back(&*node.sub[1]);
623
0
        }
624
0
    }
625
626
0
    return ret;
627
0
}
628
629
std::vector<std::tuple<uint8_t, uint8_t, std::vector<unsigned char>>> TaprootBuilder::GetTreeTuples() const
630
0
{
631
0
    assert(IsComplete());
632
0
    std::vector<std::tuple<uint8_t, uint8_t, std::vector<unsigned char>>> tuples;
633
0
    if (m_branch.size()) {
634
0
        const auto& leaves = m_branch[0]->leaves;
635
0
        for (const auto& leaf : leaves) {
636
0
            assert(leaf.merkle_branch.size() <= TAPROOT_CONTROL_MAX_NODE_COUNT);
637
0
            uint8_t depth = (uint8_t)leaf.merkle_branch.size();
638
0
            uint8_t leaf_ver = (uint8_t)leaf.leaf_version;
639
0
            tuples.emplace_back(depth, leaf_ver, leaf.script);
640
0
        }
641
0
    }
642
0
    return tuples;
643
0
}