Bitcoin Core Fuzz Coverage Report

Coverage Report

Created: 2026-03-24 13:57

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