Coverage Report

Created: 2026-09-14 20:36

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.25M
{
23
1.25M
    auto it = map.find(key);
24
1.25M
    if (it != map.end()) {
25
828k
        value = it->second;
26
828k
        return true;
27
828k
    }
28
424k
    return false;
29
1.25M
}
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.6k
{
23
29.6k
    auto it = map.find(key);
24
29.6k
    if (it != map.end()) {
25
24.1k
        value = it->second;
26
24.1k
        return true;
27
24.1k
    }
28
5.49k
    return false;
29
29.6k
}
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
294k
{
23
294k
    auto it = map.find(key);
24
294k
    if (it != map.end()) {
25
264k
        value = it->second;
26
264k
        return true;
27
264k
    }
28
30.6k
    return false;
29
294k
}
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
582k
{
23
582k
    auto it = map.find(key);
24
582k
    if (it != map.end()) {
25
457k
        value = it->second;
26
457k
        return true;
27
457k
    }
28
125k
    return false;
29
582k
}
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
322k
{
23
322k
    auto it = map.find(key);
24
322k
    if (it != map.end()) {
25
74.5k
        value = it->second;
26
74.5k
        return true;
27
74.5k
    }
28
248k
    return false;
29
322k
}
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.26k
        value = it->second;
26
8.26k
        return true;
27
8.26k
    }
28
14.6k
    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.13k
{
33
6.13k
    return m_provider->GetCScript(scriptid, script);
34
6.13k
}
35
36
bool HidingSigningProvider::GetPubKey(const CKeyID& keyid, CPubKey& pubkey) const
37
5.48k
{
38
5.48k
    return m_provider->GetPubKey(keyid, pubkey);
39
5.48k
}
40
41
bool HidingSigningProvider::GetKey(const CKeyID& keyid, CKey& key) const
42
196k
{
43
196k
    if (m_hide_secret) return false;
44
120k
    return m_provider->GetKey(keyid, key);
45
196k
}
46
47
bool HidingSigningProvider::GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const
48
175k
{
49
175k
    if (m_hide_origin) return false;
50
153k
    return m_provider->GetKeyOrigin(keyid, info);
51
175k
}
52
53
bool HidingSigningProvider::GetTaprootSpendData(const XOnlyPubKey& output_key, TaprootSpendData& spenddata) const
54
4.97k
{
55
4.97k
    return m_provider->GetTaprootSpendData(output_key, spenddata);
56
4.97k
}
57
bool HidingSigningProvider::GetTaprootBuilder(const XOnlyPubKey& output_key, TaprootBuilder& builder) const
58
4.97k
{
59
4.97k
    return m_provider->GetTaprootBuilder(output_key, builder);
60
4.97k
}
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.97k
{
69
4.97k
    return m_provider->GetAllMuSig2ParticipantPubkeys();
70
4.97k
}
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.6k
bool FlatSigningProvider::GetCScript(const CScriptID& scriptid, CScript& script) const { return LookupHelper(scripts, scriptid, script); }
88
294k
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
582k
{
91
582k
    std::pair<CPubKey, KeyOriginInfo> out;
92
582k
    bool ret = LookupHelper(origins, keyid, out);
93
582k
    if (ret) info = std::move(out.second);
94
582k
    return ret;
95
582k
}
96
bool FlatSigningProvider::HaveKey(const CKeyID &keyid) const
97
1.33k
{
98
1.33k
    CKey key;
99
1.33k
    return LookupHelper(keys, keyid, key);
100
1.33k
}
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.8k
{
104
14.8k
    TaprootBuilder builder;
105
14.8k
    if (LookupHelper(tr_trees, output_key, builder)) {
106
6.75k
        spenddata = builder.GetSpendData();
107
6.75k
        return true;
108
6.75k
    }
109
8.09k
    return false;
110
14.8k
}
111
bool FlatSigningProvider::GetTaprootBuilder(const XOnlyPubKey& output_key, TaprootBuilder& builder) const
112
8.09k
{
113
8.09k
    return LookupHelper(tr_trees, output_key, builder);
114
8.09k
}
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.09k
{
125
8.09k
    return aggregate_pubkeys;
126
8.09k
}
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.10M
{
152
1.10M
    scripts.merge(b.scripts);
153
1.10M
    pubkeys.merge(b.pubkeys);
154
1.10M
    keys.merge(b.keys);
155
1.10M
    origins.merge(b.origins);
156
1.10M
    tr_trees.merge(b.tr_trees);
157
1.10M
    aggregate_pubkeys.merge(b.aggregate_pubkeys);
158
    // We shouldn't be merging 2 different sessions, just overwrite with b's sessions.
159
1.10M
    if (!musig2_secnonces) musig2_secnonces = b.musig2_secnonces;
160
1.10M
    return *this;
161
1.10M
}
162
163
void FillableSigningProvider::ImplicitlyLearnRelatedKeyScripts(const CPubKey& pubkey)
164
514
{
165
514
    AssertLockHeld(cs_KeyStore);
166
514
    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
514
    if (pubkey.IsCompressed()) {
179
497
        CScript script = GetScriptForDestination(WitnessV0KeyHash(key_id));
180
        // This does not use AddCScript, as it may be overridden.
181
497
        CScriptID id(script);
182
497
        mapScripts[id] = std::move(script);
183
497
    }
184
514
}
185
186
bool FillableSigningProvider::GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const
187
5.94k
{
188
5.94k
    CKey key;
189
5.94k
    if (!GetKey(address, key)) {
190
77
        return false;
191
77
    }
192
5.86k
    vchPubKeyOut = key.GetPubKey();
193
5.86k
    return true;
194
5.94k
}
195
196
bool FillableSigningProvider::AddKeyPubKey(const CKey& key, const CPubKey &pubkey)
197
421
{
198
421
    LOCK(cs_KeyStore);
199
421
    mapKeys[pubkey.GetID()] = key;
200
421
    ImplicitlyLearnRelatedKeyScripts(pubkey);
201
421
    return true;
202
421
}
203
204
bool FillableSigningProvider::HaveKey(const CKeyID &address) const
205
2.37k
{
206
2.37k
    LOCK(cs_KeyStore);
207
2.37k
    return mapKeys.contains(address);
208
2.37k
}
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
10.9k
{
222
10.9k
    LOCK(cs_KeyStore);
223
10.9k
    KeyMap::const_iterator mi = mapKeys.find(address);
224
10.9k
    if (mi != mapKeys.end()) {
225
10.8k
        keyOut = mi->second;
226
10.8k
        return true;
227
10.8k
    }
228
129
    return false;
229
10.9k
}
230
231
bool FillableSigningProvider::AddCScript(const CScript& redeemScript)
232
116
{
233
116
    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
116
    LOCK(cs_KeyStore);
239
116
    mapScripts[CScriptID(redeemScript)] = redeemScript;
240
116
    return true;
241
116
}
242
243
bool FillableSigningProvider::HaveCScript(const CScriptID& hash) const
244
1.77k
{
245
1.77k
    LOCK(cs_KeyStore);
246
1.77k
    return mapScripts.contains(hash);
247
1.77k
}
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.15k
{
261
3.15k
    LOCK(cs_KeyStore);
262
3.15k
    ScriptMap::const_iterator mi = mapScripts.find(hash);
263
3.15k
    if (mi != mapScripts.end())
264
1.54k
    {
265
1.54k
        redeemScriptOut = (*mi).second;
266
1.54k
        return true;
267
1.54k
    }
268
1.61k
    return false;
269
3.15k
}
270
271
CKeyID GetKeyForDestination(const SigningProvider& store, const CTxDestination& dest)
272
650
{
273
    // Only supports destinations which map to single public keys:
274
    // P2PKH, P2WPKH, P2SH-P2WPKH, P2TR
275
650
    if (auto id = std::get_if<PKHash>(&dest)) {
276
105
        return ToKeyID(*id);
277
105
    }
278
545
    if (auto witness_id = std::get_if<WitnessV0KeyHash>(&dest)) {
279
319
        return ToKeyID(*witness_id);
280
319
    }
281
226
    if (auto script_hash = std::get_if<ScriptHash>(&dest)) {
282
92
        CScript script;
283
92
        CScriptID script_id = ToScriptID(*script_hash);
284
92
        CTxDestination inner_dest;
285
92
        if (store.GetCScript(script_id, script) && ExtractDestination(script, inner_dest)) {
286
92
            if (auto inner_witness_id = std::get_if<WitnessV0KeyHash>(&inner_dest)) {
287
89
                return ToKeyID(*inner_witness_id);
288
89
            }
289
92
        }
290
92
    }
291
137
    if (auto output_key = std::get_if<WitnessV1Taproot>(&dest)) {
292
112
        TaprootSpendData spenddata;
293
112
        CPubKey pub;
294
112
        if (store.GetTaprootSpendData(*output_key, spenddata)
295
112
            && !spenddata.internal_key.IsNull()
296
112
            && spenddata.merkle_root.IsNull()
297
112
            && store.GetPubKeyByXOnly(spenddata.internal_key, pub)) {
298
53
            return pub.GetID();
299
53
        }
300
112
    }
301
84
    return CKeyID();
302
137
}
303
304
void MultiSigningProvider::AddProvider(std::unique_ptr<SigningProvider> provider)
305
60.2k
{
306
60.2k
    m_providers.push_back(std::move(provider));
307
60.2k
}
308
309
bool MultiSigningProvider::GetCScript(const CScriptID& scriptid, CScript& script) const
310
807
{
311
807
    for (const auto& provider: m_providers) {
312
807
        if (provider->GetCScript(scriptid, script)) return true;
313
807
    }
314
20
    return false;
315
807
}
316
317
bool MultiSigningProvider::GetPubKey(const CKeyID& keyid, CPubKey& pubkey) const
318
30.2k
{
319
30.2k
    for (const auto& provider: m_providers) {
320
30.2k
        if (provider->GetPubKey(keyid, pubkey)) return true;
321
30.2k
    }
322
0
    return false;
323
30.2k
}
324
325
326
bool MultiSigningProvider::GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const
327
79.8k
{
328
80.7k
    for (const auto& provider: m_providers) {
329
80.7k
        if (provider->GetKeyOrigin(keyid, info)) return true;
330
80.7k
    }
331
1.08k
    return false;
332
79.8k
}
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.30k
{
344
1.37k
    for (const auto& provider: m_providers) {
345
1.37k
        if (provider->GetTaprootSpendData(output_key, spenddata)) return true;
346
1.37k
    }
347
70
    return false;
348
1.30k
}
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.3k
{
360
22.3k
    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.1k
    for (auto& leaf : a.leaves) {
363
40.1k
        leaf.merkle_branch.push_back(b.hash);
364
40.1k
        ret.leaves.emplace_back(std::move(leaf));
365
40.1k
    }
366
    /* Iterate over all tracked leaves in b, add a's hash to their Merkle branch, and move them to ret. */
367
37.0k
    for (auto& leaf : b.leaves) {
368
37.0k
        leaf.merkle_branch.push_back(a.hash);
369
37.0k
        ret.leaves.emplace_back(std::move(leaf));
370
37.0k
    }
371
22.3k
    ret.hash = ComputeTapbranchHash(a.hash, b.hash);
372
22.3k
    return ret;
373
22.3k
}
374
375
void TaprootSpendData::Merge(TaprootSpendData other)
376
1.66k
{
377
    // TODO: figure out how to better deal with conflicting information
378
    // being merged.
379
1.66k
    if (internal_key.IsNull() && !other.internal_key.IsNull()) {
380
876
        internal_key = other.internal_key;
381
876
    }
382
1.66k
    if (merkle_root.IsNull() && !other.merkle_root.IsNull()) {
383
549
        merkle_root = other.merkle_root;
384
549
    }
385
1.66k
    for (auto& [key, control_blocks] : other.scripts) {
386
1.64k
        scripts[key].merge(std::move(control_blocks));
387
1.64k
    }
388
1.66k
}
389
390
void TaprootBuilder::Insert(TaprootBuilder::NodeInfo&& node, int depth)
391
41.1k
{
392
41.1k
    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.1k
    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.4k
    while (m_valid && m_branch.size() > (size_t)depth && m_branch[depth].has_value()) {
403
22.3k
        node = Combine(std::move(node), std::move(*m_branch[depth]));
404
22.3k
        m_branch.pop_back();
405
22.3k
        if (depth == 0) m_valid = false; /* Can't propagate further up than the root */
406
22.3k
        --depth;
407
22.3k
    }
408
41.1k
    if (m_valid) {
409
        /* Make sure the branch is big enough to place the new node. */
410
41.1k
        if (m_branch.size() <= (size_t)depth) m_branch.resize((size_t)depth + 1);
411
41.1k
        assert(!m_branch[depth].has_value());
412
41.1k
        m_branch[depth] = std::move(node);
413
41.1k
    }
414
41.1k
}
415
416
/*static*/ bool TaprootBuilder::ValidDepths(const std::vector<int>& depths)
417
2.20k
{
418
2.20k
    std::vector<bool> branch;
419
2.20k
    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.32k
        if (depth < 0 || (size_t)depth > TAPROOT_CONTROL_MAX_NODE_COUNT) return false;
425
1.32k
        if ((size_t)depth + 1 < branch.size()) return false;
426
2.16k
        while (branch.size() > (size_t)depth && branch[depth]) {
427
869
            branch.pop_back();
428
869
            if (depth == 0) return false;
429
863
            --depth;
430
863
        }
431
1.30k
        if (branch.size() <= (size_t)depth) branch.resize((size_t)depth + 1);
432
1.30k
        assert(!branch[depth]);
433
1.30k
        branch[depth] = true;
434
1.30k
    }
435
    // And this check corresponds to the IsComplete() check on m_branch.
436
2.18k
    return branch.size() == 0 || (branch.size() == 1 && branch[0]);
437
2.20k
}
438
439
TaprootBuilder& TaprootBuilder::Add(int depth, std::span<const unsigned char> script, int leaf_version, bool track)
440
41.1k
{
441
41.1k
    assert((leaf_version & ~TAPROOT_LEAF_MASK) == 0);
442
41.1k
    if (!IsValid()) return *this;
443
    /* Construct NodeInfo object with leaf hash and (if track is true) also leaf information. */
444
41.1k
    NodeInfo node;
445
41.1k
    node.hash = ComputeTapleafHash(leaf_version, script);
446
41.1k
    if (track) node.leaves.emplace_back(LeafInfo{std::vector<unsigned char>(script.begin(), script.end()), leaf_version, {}});
447
    /* Insert into the branch. */
448
41.1k
    Insert(std::move(node), depth);
449
41.1k
    return *this;
450
41.1k
}
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
141k
{
464
    /* Can only call this function when IsComplete() is true. */
465
141k
    assert(IsComplete());
466
141k
    m_internal_key = internal_key;
467
141k
    auto ret = m_internal_key.CreateTapTweak(m_branch.size() == 0 ? nullptr : &m_branch[0]->hash);
468
141k
    assert(ret.has_value());
469
141k
    std::tie(m_output_key, m_parity) = *ret;
470
141k
    return *this;
471
141k
}
472
473
141k
WitnessV1Taproot TaprootBuilder::GetOutput() { return WitnessV1Taproot{m_output_key}; }
474
475
TaprootSpendData TaprootBuilder::GetSpendData() const
476
10.5k
{
477
10.5k
    assert(IsComplete());
478
10.5k
    assert(m_output_key.IsFullyValid());
479
10.5k
    TaprootSpendData spd;
480
10.5k
    spd.merkle_root = m_branch.size() == 0 ? uint256() : m_branch[0]->hash;
481
10.5k
    spd.internal_key = m_internal_key;
482
10.5k
    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.7k
        for (const auto& leaf : m_branch[0]->leaves) {
487
10.7k
            std::vector<unsigned char> control_block;
488
10.7k
            control_block.resize(TAPROOT_CONTROL_BASE_SIZE + TAPROOT_CONTROL_NODE_SIZE * leaf.merkle_branch.size());
489
10.7k
            control_block[0] = leaf.leaf_version | (m_parity ? 1 : 0);
490
10.7k
            std::copy(m_internal_key.begin(), m_internal_key.end(), control_block.begin() + 1);
491
10.7k
            if (leaf.merkle_branch.size()) {
492
5.56k
                std::copy(leaf.merkle_branch[0].begin(),
493
5.56k
                          leaf.merkle_branch[0].begin() + TAPROOT_CONTROL_NODE_SIZE * leaf.merkle_branch.size(),
494
5.56k
                          control_block.begin() + TAPROOT_CONTROL_BASE_SIZE);
495
5.56k
            }
496
10.7k
            spd.scripts[{leaf.script, leaf.leaf_version}].insert(std::move(control_block));
497
10.7k
        }
498
6.71k
    }
499
10.5k
    return spd;
500
10.5k
}
501
502
std::optional<std::vector<std::tuple<int, std::vector<unsigned char>, int>>> InferTaprootTree(const TaprootSpendData& spenddata, const XOnlyPubKey& output)
503
5.12k
{
504
    // Verify that the output matches the assumed Merkle root and internal key.
505
5.12k
    auto tweak = spenddata.internal_key.CreateTapTweak(spenddata.merkle_root.IsNull() ? nullptr : &spenddata.merkle_root);
506
5.12k
    if (!tweak || tweak->first != output) return std::nullopt;
507
    // If the Merkle root is 0, the tree is empty, and we're done.
508
5.12k
    std::vector<std::tuple<int, std::vector<unsigned char>, int>> ret;
509
5.12k
    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.92k
    struct TreeNode {
513
        /** Hash of this node, if known; 0 otherwise. */
514
1.92k
        uint256 hash;
515
        /** The left and right subtrees (note that their order is irrelevant). */
516
1.92k
        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.92k
        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.92k
        bool explored = false;
522
        /** Whether or not this node is an inner node (unknown until explored = true). */
523
1.92k
        bool inner;
524
        /** Whether or not we have produced output for this subtree. */
525
1.92k
        bool done = false;
526
1.92k
    };
527
528
    // Build tree from the provided branches.
529
1.92k
    TreeNode root;
530
1.92k
    root.hash = spenddata.merkle_root;
531
2.90k
    for (const auto& [key, control_blocks] : spenddata.scripts) {
532
2.90k
        const auto& [script, leaf_ver] = key;
533
3.68k
        for (const auto& control : control_blocks) {
534
            // Skip script records with nonsensical leaf version.
535
3.68k
            if (leaf_ver < 0 || leaf_ver >= 0x100 || leaf_ver & 1) continue;
536
            // Skip script records with invalid control block sizes.
537
3.68k
            if (control.size() < TAPROOT_CONTROL_BASE_SIZE || control.size() > TAPROOT_CONTROL_MAX_SIZE ||
538
3.68k
                ((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.68k
            if ((control[0] & TAPROOT_LEAF_MASK) != leaf_ver) continue;
541
            // Skip script records that don't match the provided Merkle root.
542
3.68k
            const uint256 leaf_hash = ComputeTapleafHash(leaf_ver, script);
543
3.68k
            const uint256 merkle_root = ComputeTaprootMerkleRoot(control, leaf_hash);
544
3.68k
            if (merkle_root != spenddata.merkle_root) continue;
545
546
3.68k
            TreeNode* node = &root;
547
3.68k
            size_t levels = (control.size() - TAPROOT_CONTROL_BASE_SIZE) / TAPROOT_CONTROL_NODE_SIZE;
548
9.19k
            for (size_t depth = 0; depth < levels; ++depth) {
549
                // Can't descend into a node which we already know is a leaf.
550
5.51k
                if (node->explored && !node->inner) return std::nullopt;
551
552
                // Extract partner hash from Merkle branch in control block.
553
5.51k
                uint256 hash;
554
5.51k
                std::copy(control.begin() + TAPROOT_CONTROL_BASE_SIZE + (levels - 1 - depth) * TAPROOT_CONTROL_NODE_SIZE,
555
5.51k
                          control.begin() + TAPROOT_CONTROL_BASE_SIZE + (levels - depth) * TAPROOT_CONTROL_NODE_SIZE,
556
5.51k
                          hash.begin());
557
558
5.51k
                if (node->sub[0]) {
559
                    // Descend into the existing left or right branch.
560
3.31k
                    bool desc = false;
561
4.06k
                    for (int i = 0; i < 2; ++i) {
562
4.06k
                        if (node->sub[i]->hash == hash || (node->sub[i]->hash.IsNull() && node->sub[1-i]->hash != hash)) {
563
3.31k
                            node->sub[i]->hash = hash;
564
3.31k
                            node = &*node->sub[1-i];
565
3.31k
                            desc = true;
566
3.31k
                            break;
567
3.31k
                        }
568
4.06k
                    }
569
3.31k
                    if (!desc) return std::nullopt; // This probably requires a hash collision to hit.
570
3.31k
                } else {
571
                    // We're in an unexplored node. Create subtrees and descend.
572
2.20k
                    node->explored = true;
573
2.20k
                    node->inner = true;
574
2.20k
                    node->sub[0] = std::make_unique<TreeNode>();
575
2.20k
                    node->sub[1] = std::make_unique<TreeNode>();
576
2.20k
                    node->sub[1]->hash = hash;
577
2.20k
                    node = &*node->sub[0];
578
2.20k
                }
579
5.51k
            }
580
            // Cannot turn a known inner node into a leaf.
581
3.68k
            if (node->sub[0]) return std::nullopt;
582
3.68k
            node->explored = true;
583
3.68k
            node->inner = false;
584
3.68k
            node->leaf = &key;
585
3.68k
            node->hash = leaf_hash;
586
3.68k
        }
587
2.90k
    }
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.92k
    std::vector<TreeNode*> stack{&root};
592
14.5k
    while (!stack.empty()) {
593
12.5k
        TreeNode& node = *stack.back();
594
12.5k
        if (!node.explored) {
595
            // Unexplored node, which means the tree is incomplete.
596
0
            return std::nullopt;
597
12.5k
        } else if (!node.inner) {
598
            // Leaf node; produce output.
599
4.45k
            ret.emplace_back(stack.size() - 1, node.leaf->first, node.leaf->second);
600
4.45k
            node.done = true;
601
4.45k
            stack.pop_back();
602
8.13k
        } else if (node.sub[0]->done && !node.sub[1]->done && !node.sub[1]->explored && !node.sub[1]->hash.IsNull() &&
603
8.13k
                   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
551
            node.sub[0]->done = false;
618
551
            node.sub[1]->done = true;
619
7.58k
        } else if (node.sub[0]->done && node.sub[1]->done) {
620
            // An internal node which we're finished with.
621
2.52k
            node.sub[0]->done = false;
622
2.52k
            node.sub[1]->done = false;
623
2.52k
            node.done = true;
624
2.52k
            stack.pop_back();
625
5.05k
        } else if (!node.sub[0]->done) {
626
            // An internal node whose left branch hasn't been processed yet. Do so first.
627
3.07k
            stack.push_back(&*node.sub[0]);
628
3.07k
        } else if (!node.sub[1]->done) {
629
            // An internal node whose right branch hasn't been processed yet. Do so first.
630
1.97k
            stack.push_back(&*node.sub[1]);
631
1.97k
        }
632
12.5k
    }
633
634
1.92k
    return ret;
635
1.92k
}
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
}