Coverage Report

Created: 2026-09-02 14:16

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