Coverage Report

Created: 2026-11-13 17:38

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.29M
{
23
1.29M
    auto it = map.find(key);
24
1.29M
    if (it != map.end()) {
25
839k
        value = it->second;
26
839k
        return true;
27
839k
    }
28
457k
    return false;
29
1.29M
}
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.9k
{
23
29.9k
    auto it = map.find(key);
24
29.9k
    if (it != map.end()) {
25
24.4k
        value = it->second;
26
24.4k
        return true;
27
24.4k
    }
28
5.50k
    return false;
29
29.9k
}
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
267k
        value = it->second;
26
267k
        return true;
27
267k
    }
28
51.9k
    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
595k
{
23
595k
    auto it = map.find(key);
24
595k
    if (it != map.end()) {
25
463k
        value = it->second;
26
463k
        return true;
27
463k
    }
28
132k
    return false;
29
595k
}
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
329k
{
23
329k
    auto it = map.find(key);
24
329k
    if (it != map.end()) {
25
75.8k
        value = it->second;
26
75.8k
        return true;
27
75.8k
    }
28
253k
    return false;
29
329k
}
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.20k
        value = it->second;
26
8.20k
        return true;
27
8.20k
    }
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.07k
{
33
6.07k
    return m_provider->GetCScript(scriptid, script);
34
6.07k
}
35
36
bool HidingSigningProvider::GetPubKey(const CKeyID& keyid, CPubKey& pubkey) const
37
4.73k
{
38
4.73k
    return m_provider->GetPubKey(keyid, pubkey);
39
4.73k
}
40
41
bool HidingSigningProvider::GetKey(const CKeyID& keyid, CKey& key) const
42
203k
{
43
203k
    if (m_hide_secret) return false;
44
125k
    return m_provider->GetKey(keyid, key);
45
203k
}
46
47
bool HidingSigningProvider::GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const
48
182k
{
49
182k
    if (m_hide_origin) return false;
50
160k
    return m_provider->GetKeyOrigin(keyid, info);
51
182k
}
52
53
bool HidingSigningProvider::GetTaprootSpendData(const XOnlyPubKey& output_key, TaprootSpendData& spenddata) const
54
5.04k
{
55
5.04k
    return m_provider->GetTaprootSpendData(output_key, spenddata);
56
5.04k
}
57
bool HidingSigningProvider::GetTaprootBuilder(const XOnlyPubKey& output_key, TaprootBuilder& builder) const
58
5.04k
{
59
5.04k
    return m_provider->GetTaprootBuilder(output_key, builder);
60
5.04k
}
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
5.04k
{
69
5.04k
    return m_provider->GetAllMuSig2ParticipantPubkeys();
70
5.04k
}
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.9k
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
595k
{
91
595k
    std::pair<CPubKey, KeyOriginInfo> out;
92
595k
    bool ret = LookupHelper(origins, keyid, out);
93
595k
    if (ret) info = std::move(out.second);
94
595k
    return ret;
95
595k
}
96
bool FlatSigningProvider::HaveKey(const CKeyID &keyid) const
97
1.38k
{
98
1.38k
    CKey key;
99
1.38k
    return LookupHelper(keys, keyid, key);
100
1.38k
}
101
327k
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.67k
        spenddata = builder.GetSpendData();
107
6.67k
        return true;
108
6.67k
    }
109
8.12k
    return false;
110
14.8k
}
111
bool FlatSigningProvider::GetTaprootBuilder(const XOnlyPubKey& output_key, TaprootBuilder& builder) const
112
8.12k
{
113
8.12k
    return LookupHelper(tr_trees, output_key, builder);
114
8.12k
}
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.12k
{
125
8.12k
    return aggregate_pubkeys;
126
8.12k
}
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.11M
{
152
1.11M
    scripts.merge(b.scripts);
153
1.11M
    pubkeys.merge(b.pubkeys);
154
1.11M
    keys.merge(b.keys);
155
1.11M
    origins.merge(b.origins);
156
1.11M
    tr_trees.merge(b.tr_trees);
157
1.11M
    aggregate_pubkeys.merge(b.aggregate_pubkeys);
158
    // We shouldn't be merging 2 different sessions, just overwrite with b's sessions.
159
1.11M
    if (!musig2_secnonces) musig2_secnonces = b.musig2_secnonces;
160
1.11M
    return *this;
161
1.11M
}
162
163
void FillableSigningProvider::ImplicitlyLearnRelatedKeyScripts(const CPubKey& pubkey)
164
522
{
165
522
    AssertLockHeld(cs_KeyStore);
166
522
    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
522
    if (pubkey.IsCompressed()) {
179
505
        CScript script = GetScriptForDestination(WitnessV0KeyHash(key_id));
180
        // This does not use AddCScript, as it may be overridden.
181
505
        CScriptID id(script);
182
505
        mapScripts[id] = std::move(script);
183
505
    }
184
522
}
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
429
{
198
429
    LOCK(cs_KeyStore);
199
429
    mapKeys[pubkey.GetID()] = key;
200
429
    ImplicitlyLearnRelatedKeyScripts(pubkey);
201
429
    return true;
202
429
}
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
131
    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
        LogInfo("FillableSigningProvider::AddCScript(): redeemScripts > %i bytes are invalid", MAX_SCRIPT_ELEMENT_SIZE); // TODO: remove, callers should take care of checking input / reporting errors
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
bool FillableSigningProvider::GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const
250
3.15k
{
251
3.15k
    LOCK(cs_KeyStore);
252
3.15k
    ScriptMap::const_iterator mi = mapScripts.find(hash);
253
3.15k
    if (mi != mapScripts.end())
254
1.54k
    {
255
1.54k
        redeemScriptOut = (*mi).second;
256
1.54k
        return true;
257
1.54k
    }
258
1.61k
    return false;
259
3.15k
}
260
261
CKeyID GetKeyForDestination(const SigningProvider& store, const CTxDestination& dest)
262
652
{
263
    // Only supports destinations which map to single public keys:
264
    // P2PKH, P2WPKH, P2SH-P2WPKH, P2TR
265
652
    if (auto id = std::get_if<PKHash>(&dest)) {
266
109
        return ToKeyID(*id);
267
109
    }
268
543
    if (auto witness_id = std::get_if<WitnessV0KeyHash>(&dest)) {
269
317
        return ToKeyID(*witness_id);
270
317
    }
271
226
    if (auto script_hash = std::get_if<ScriptHash>(&dest)) {
272
92
        CScript script;
273
92
        CScriptID script_id = ToScriptID(*script_hash);
274
92
        CTxDestination inner_dest;
275
92
        if (store.GetCScript(script_id, script) && ExtractDestination(script, inner_dest)) {
276
92
            if (auto inner_witness_id = std::get_if<WitnessV0KeyHash>(&inner_dest)) {
277
89
                return ToKeyID(*inner_witness_id);
278
89
            }
279
92
        }
280
92
    }
281
137
    if (auto output_key = std::get_if<WitnessV1Taproot>(&dest)) {
282
112
        TaprootSpendData spenddata;
283
112
        CPubKey pub;
284
112
        if (store.GetTaprootSpendData(*output_key, spenddata)
285
112
            && !spenddata.internal_key.IsNull()
286
112
            && spenddata.merkle_root.IsNull()
287
112
            && store.GetPubKeyByXOnly(spenddata.internal_key, pub)) {
288
53
            return pub.GetID();
289
53
        }
290
112
    }
291
84
    return CKeyID();
292
137
}
293
294
void MultiSigningProvider::AddProvider(std::unique_ptr<SigningProvider> provider)
295
61.7k
{
296
61.7k
    m_providers.push_back(std::move(provider));
297
61.7k
}
298
299
bool MultiSigningProvider::GetCScript(const CScriptID& scriptid, CScript& script) const
300
825
{
301
825
    for (const auto& provider: m_providers) {
302
825
        if (provider->GetCScript(scriptid, script)) return true;
303
825
    }
304
20
    return false;
305
825
}
306
307
bool MultiSigningProvider::GetPubKey(const CKeyID& keyid, CPubKey& pubkey) const
308
30.9k
{
309
30.9k
    for (const auto& provider: m_providers) {
310
30.9k
        if (provider->GetPubKey(keyid, pubkey)) return true;
311
30.9k
    }
312
0
    return false;
313
30.9k
}
314
315
316
bool MultiSigningProvider::GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const
317
80.6k
{
318
81.6k
    for (const auto& provider: m_providers) {
319
81.6k
        if (provider->GetKeyOrigin(keyid, info)) return true;
320
81.6k
    }
321
1.16k
    return false;
322
80.6k
}
323
324
bool MultiSigningProvider::GetKey(const CKeyID& keyid, CKey& key) const
325
0
{
326
0
    for (const auto& provider: m_providers) {
327
0
        if (provider->GetKey(keyid, key)) return true;
328
0
    }
329
0
    return false;
330
0
}
331
332
bool MultiSigningProvider::GetTaprootSpendData(const XOnlyPubKey& output_key, TaprootSpendData& spenddata) const
333
1.31k
{
334
1.37k
    for (const auto& provider: m_providers) {
335
1.37k
        if (provider->GetTaprootSpendData(output_key, spenddata)) return true;
336
1.37k
    }
337
68
    return false;
338
1.31k
}
339
340
bool MultiSigningProvider::GetTaprootBuilder(const XOnlyPubKey& output_key, TaprootBuilder& builder) const
341
0
{
342
0
    for (const auto& provider: m_providers) {
343
0
        if (provider->GetTaprootBuilder(output_key, builder)) return true;
344
0
    }
345
0
    return false;
346
0
}
347
348
/*static*/ TaprootBuilder::NodeInfo TaprootBuilder::Combine(NodeInfo&& a, NodeInfo&& b)
349
22.3k
{
350
22.3k
    NodeInfo ret;
351
    /* Iterate over all tracked leaves in a, add b's hash to their Merkle branch, and move them to ret. */
352
40.1k
    for (auto& leaf : a.leaves) {
353
40.1k
        leaf.merkle_branch.push_back(b.hash);
354
40.1k
        ret.leaves.emplace_back(std::move(leaf));
355
40.1k
    }
356
    /* Iterate over all tracked leaves in b, add a's hash to their Merkle branch, and move them to ret. */
357
37.0k
    for (auto& leaf : b.leaves) {
358
37.0k
        leaf.merkle_branch.push_back(a.hash);
359
37.0k
        ret.leaves.emplace_back(std::move(leaf));
360
37.0k
    }
361
22.3k
    ret.hash = ComputeTapbranchHash(a.hash, b.hash);
362
22.3k
    return ret;
363
22.3k
}
364
365
void TaprootSpendData::Merge(TaprootSpendData other)
366
1.66k
{
367
    // TODO: figure out how to better deal with conflicting information
368
    // being merged.
369
1.66k
    if (internal_key.IsNull() && !other.internal_key.IsNull()) {
370
876
        internal_key = other.internal_key;
371
876
    }
372
1.66k
    if (merkle_root.IsNull() && !other.merkle_root.IsNull()) {
373
546
        merkle_root = other.merkle_root;
374
546
    }
375
1.66k
    for (auto& [key, control_blocks] : other.scripts) {
376
1.64k
        scripts[key].merge(std::move(control_blocks));
377
1.64k
    }
378
1.66k
}
379
380
void TaprootBuilder::Insert(TaprootBuilder::NodeInfo&& node, int depth)
381
41.1k
{
382
41.1k
    assert(depth >= 0 && (size_t)depth <= TAPROOT_CONTROL_MAX_NODE_COUNT);
383
    /* We cannot insert a leaf at a lower depth while a deeper branch is unfinished. Doing
384
     * so would mean the Add() invocations do not correspond to a DFS traversal of a
385
     * binary tree. */
386
41.1k
    if ((size_t)depth + 1 < m_branch.size()) {
387
0
        m_valid = false;
388
0
        return;
389
0
    }
390
    /* As long as an entry in the branch exists at the specified depth, combine it and propagate up.
391
     * The 'node' variable is overwritten here with the newly combined node. */
392
63.4k
    while (m_valid && m_branch.size() > (size_t)depth && m_branch[depth].has_value()) {
393
22.3k
        node = Combine(std::move(node), std::move(*m_branch[depth]));
394
22.3k
        m_branch.pop_back();
395
22.3k
        if (depth == 0) m_valid = false; /* Can't propagate further up than the root */
396
22.3k
        --depth;
397
22.3k
    }
398
41.1k
    if (m_valid) {
399
        /* Make sure the branch is big enough to place the new node. */
400
41.1k
        if (m_branch.size() <= (size_t)depth) m_branch.resize((size_t)depth + 1);
401
41.1k
        assert(!m_branch[depth].has_value());
402
41.1k
        m_branch[depth] = std::move(node);
403
41.1k
    }
404
41.1k
}
405
406
/*static*/ bool TaprootBuilder::ValidDepths(const std::vector<int>& depths)
407
2.29k
{
408
2.29k
    std::vector<bool> branch;
409
2.29k
    for (int depth : depths) {
410
        // This inner loop corresponds to effectively the same logic on branch
411
        // as what Insert() performs on the m_branch variable. Instead of
412
        // storing a NodeInfo object, just remember whether or not there is one
413
        // at that depth.
414
1.32k
        if (depth < 0 || (size_t)depth > TAPROOT_CONTROL_MAX_NODE_COUNT) return false;
415
1.32k
        if ((size_t)depth + 1 < branch.size()) return false;
416
2.16k
        while (branch.size() > (size_t)depth && branch[depth]) {
417
869
            branch.pop_back();
418
869
            if (depth == 0) return false;
419
863
            --depth;
420
863
        }
421
1.30k
        if (branch.size() <= (size_t)depth) branch.resize((size_t)depth + 1);
422
1.30k
        assert(!branch[depth]);
423
1.30k
        branch[depth] = true;
424
1.30k
    }
425
    // And this check corresponds to the IsComplete() check on m_branch.
426
2.26k
    return branch.size() == 0 || (branch.size() == 1 && branch[0]);
427
2.29k
}
428
429
TaprootBuilder& TaprootBuilder::Add(int depth, std::span<const unsigned char> script, int leaf_version, bool track)
430
41.1k
{
431
41.1k
    assert((leaf_version & ~TAPROOT_LEAF_MASK) == 0);
432
41.1k
    if (!IsValid()) return *this;
433
    /* Construct NodeInfo object with leaf hash and (if track is true) also leaf information. */
434
41.1k
    NodeInfo node;
435
41.1k
    node.hash = ComputeTapleafHash(leaf_version, script);
436
41.1k
    if (track) node.leaves.emplace_back(LeafInfo{std::vector<unsigned char>(script.begin(), script.end()), leaf_version, {}});
437
    /* Insert into the branch. */
438
41.1k
    Insert(std::move(node), depth);
439
41.1k
    return *this;
440
41.1k
}
441
442
TaprootBuilder& TaprootBuilder::AddOmitted(int depth, const uint256& hash)
443
1
{
444
1
    if (!IsValid()) return *this;
445
    /* Construct NodeInfo object with the hash directly, and insert it into the branch. */
446
1
    NodeInfo node;
447
1
    node.hash = hash;
448
1
    Insert(std::move(node), depth);
449
1
    return *this;
450
1
}
451
452
TaprootBuilder& TaprootBuilder::Finalize(const XOnlyPubKey& internal_key)
453
142k
{
454
    /* Can only call this function when IsComplete() is true. */
455
142k
    assert(IsComplete());
456
142k
    m_internal_key = internal_key;
457
142k
    auto ret = m_internal_key.CreateTapTweak(m_branch.size() == 0 ? nullptr : &m_branch[0]->hash);
458
142k
    assert(ret.has_value());
459
142k
    std::tie(m_output_key, m_parity) = *ret;
460
142k
    return *this;
461
142k
}
462
463
141k
WitnessV1Taproot TaprootBuilder::GetOutput() { return WitnessV1Taproot{m_output_key}; }
464
465
TaprootSpendData TaprootBuilder::GetSpendData() const
466
10.4k
{
467
10.4k
    assert(IsComplete());
468
10.4k
    assert(m_output_key.IsFullyValid());
469
10.4k
    TaprootSpendData spd;
470
10.4k
    spd.merkle_root = m_branch.size() == 0 ? uint256() : m_branch[0]->hash;
471
10.4k
    spd.internal_key = m_internal_key;
472
10.4k
    if (m_branch.size()) {
473
        // If any script paths exist, they have been combined into the root m_branch[0]
474
        // by now. Compute the control block for each of its tracked leaves, and put them in
475
        // spd.scripts.
476
10.7k
        for (const auto& leaf : m_branch[0]->leaves) {
477
10.7k
            std::vector<unsigned char> control_block;
478
10.7k
            control_block.resize(TAPROOT_CONTROL_BASE_SIZE + TAPROOT_CONTROL_NODE_SIZE * leaf.merkle_branch.size());
479
10.7k
            control_block[0] = leaf.leaf_version | (m_parity ? 1 : 0);
480
10.7k
            std::copy(m_internal_key.begin(), m_internal_key.end(), control_block.begin() + 1);
481
10.7k
            if (leaf.merkle_branch.size()) {
482
5.58k
                std::copy(leaf.merkle_branch[0].begin(),
483
5.58k
                          leaf.merkle_branch[0].begin() + TAPROOT_CONTROL_NODE_SIZE * leaf.merkle_branch.size(),
484
5.58k
                          control_block.begin() + TAPROOT_CONTROL_BASE_SIZE);
485
5.58k
            }
486
10.7k
            spd.scripts[{leaf.script, leaf.leaf_version}].insert(std::move(control_block));
487
10.7k
        }
488
6.72k
    }
489
10.4k
    return spd;
490
10.4k
}
491
492
std::optional<std::vector<std::tuple<int, std::vector<unsigned char>, int>>> InferTaprootTree(const TaprootSpendData& spenddata, const XOnlyPubKey& output)
493
5.05k
{
494
    // Verify that the output matches the assumed Merkle root and internal key.
495
5.05k
    auto tweak = spenddata.internal_key.CreateTapTweak(spenddata.merkle_root.IsNull() ? nullptr : &spenddata.merkle_root);
496
5.05k
    if (!tweak || tweak->first != output) return std::nullopt;
497
    // If the Merkle root is 0, the tree is empty, and we're done.
498
5.05k
    std::vector<std::tuple<int, std::vector<unsigned char>, int>> ret;
499
5.05k
    if (spenddata.merkle_root.IsNull()) return ret;
500
501
    /** Data structure to represent the nodes of the tree we're going to build. */
502
1.93k
    struct TreeNode {
503
        /** Hash of this node, if known; 0 otherwise. */
504
1.93k
        uint256 hash;
505
        /** The left and right subtrees (note that their order is irrelevant). */
506
1.93k
        std::unique_ptr<TreeNode> sub[2];
507
        /** If this is known to be a leaf node, a pointer to the (script, leaf_ver) pair.
508
         *  nullptr otherwise. */
509
1.93k
        const std::pair<std::vector<unsigned char>, int>* leaf = nullptr;
510
        /** Whether or not this node has been explored (is known to be a leaf, or known to have children). */
511
1.93k
        bool explored = false;
512
        /** Whether or not this node is an inner node (unknown until explored = true). */
513
1.93k
        bool inner;
514
        /** Whether or not we have produced output for this subtree. */
515
1.93k
        bool done = false;
516
1.93k
    };
517
518
    // Build tree from the provided branches.
519
1.93k
    TreeNode root;
520
1.93k
    root.hash = spenddata.merkle_root;
521
2.92k
    for (const auto& [key, control_blocks] : spenddata.scripts) {
522
2.92k
        const auto& [script, leaf_ver] = key;
523
3.69k
        for (const auto& control : control_blocks) {
524
            // Skip script records with nonsensical leaf version.
525
3.69k
            if (leaf_ver < 0 || leaf_ver >= 0x100 || leaf_ver & 1) continue;
526
            // Skip script records with invalid control block sizes.
527
3.69k
            if (control.size() < TAPROOT_CONTROL_BASE_SIZE || control.size() > TAPROOT_CONTROL_MAX_SIZE ||
528
3.69k
                ((control.size() - TAPROOT_CONTROL_BASE_SIZE) % TAPROOT_CONTROL_NODE_SIZE) != 0) continue;
529
            // Skip script records that don't match the control block.
530
3.69k
            if ((control[0] & TAPROOT_LEAF_MASK) != leaf_ver) continue;
531
            // Skip script records that don't match the provided Merkle root.
532
3.69k
            const uint256 leaf_hash = ComputeTapleafHash(leaf_ver, script);
533
3.69k
            const uint256 merkle_root = ComputeTaprootMerkleRoot(control, leaf_hash);
534
3.69k
            if (merkle_root != spenddata.merkle_root) continue;
535
536
3.69k
            TreeNode* node = &root;
537
3.69k
            size_t levels = (control.size() - TAPROOT_CONTROL_BASE_SIZE) / TAPROOT_CONTROL_NODE_SIZE;
538
9.23k
            for (size_t depth = 0; depth < levels; ++depth) {
539
                // Can't descend into a node which we already know is a leaf.
540
5.53k
                if (node->explored && !node->inner) return std::nullopt;
541
542
                // Extract partner hash from Merkle branch in control block.
543
5.53k
                uint256 hash;
544
5.53k
                std::copy(control.begin() + TAPROOT_CONTROL_BASE_SIZE + (levels - 1 - depth) * TAPROOT_CONTROL_NODE_SIZE,
545
5.53k
                          control.begin() + TAPROOT_CONTROL_BASE_SIZE + (levels - depth) * TAPROOT_CONTROL_NODE_SIZE,
546
5.53k
                          hash.begin());
547
548
5.53k
                if (node->sub[0]) {
549
                    // Descend into the existing left or right branch.
550
3.32k
                    bool desc = false;
551
4.13k
                    for (int i = 0; i < 2; ++i) {
552
4.13k
                        if (node->sub[i]->hash == hash || (node->sub[i]->hash.IsNull() && node->sub[1-i]->hash != hash)) {
553
3.32k
                            node->sub[i]->hash = hash;
554
3.32k
                            node = &*node->sub[1-i];
555
3.32k
                            desc = true;
556
3.32k
                            break;
557
3.32k
                        }
558
4.13k
                    }
559
3.32k
                    if (!desc) return std::nullopt; // This probably requires a hash collision to hit.
560
3.32k
                } else {
561
                    // We're in an unexplored node. Create subtrees and descend.
562
2.20k
                    node->explored = true;
563
2.20k
                    node->inner = true;
564
2.20k
                    node->sub[0] = std::make_unique<TreeNode>();
565
2.20k
                    node->sub[1] = std::make_unique<TreeNode>();
566
2.20k
                    node->sub[1]->hash = hash;
567
2.20k
                    node = &*node->sub[0];
568
2.20k
                }
569
5.53k
            }
570
            // Cannot turn a known inner node into a leaf.
571
3.69k
            if (node->sub[0]) return std::nullopt;
572
3.69k
            node->explored = true;
573
3.69k
            node->inner = false;
574
3.69k
            node->leaf = &key;
575
3.69k
            node->hash = leaf_hash;
576
3.69k
        }
577
2.92k
    }
578
579
    // Recursive processing to turn the tree into flattened output. Use an explicit stack here to avoid
580
    // overflowing the call stack (the tree may be 128 levels deep).
581
1.93k
    std::vector<TreeNode*> stack{&root};
582
14.5k
    while (!stack.empty()) {
583
12.6k
        TreeNode& node = *stack.back();
584
12.6k
        if (!node.explored) {
585
            // Unexplored node, which means the tree is incomplete.
586
0
            return std::nullopt;
587
12.6k
        } else if (!node.inner) {
588
            // Leaf node; produce output.
589
4.46k
            ret.emplace_back(stack.size() - 1, node.leaf->first, node.leaf->second);
590
4.46k
            node.done = true;
591
4.46k
            stack.pop_back();
592
8.16k
        } else if (node.sub[0]->done && !node.sub[1]->done && !node.sub[1]->explored && !node.sub[1]->hash.IsNull() &&
593
8.16k
                   ComputeTapbranchHash(node.sub[1]->hash, node.sub[1]->hash) == node.hash) {
594
            // Whenever there are nodes with two identical subtrees under it, we run into a problem:
595
            // the control blocks for the leaves underneath those will be identical as well, and thus
596
            // they will all be matched to the same path in the tree. The result is that at the location
597
            // where the duplicate occurred, the left child will contain a normal tree that can be explored
598
            // and processed, but the right one will remain unexplored.
599
            //
600
            // This situation can be detected, by encountering an inner node with unexplored right subtree
601
            // with known hash, and H_TapBranch(hash, hash) is equal to the parent node (this node)'s hash.
602
            //
603
            // To deal with this, simply process the left tree a second time (set its done flag to false;
604
            // noting that the done flag of its children have already been set to false after processing
605
            // those). To avoid ending up in an infinite loop, set the done flag of the right (unexplored)
606
            // subtree to true.
607
551
            node.sub[0]->done = false;
608
551
            node.sub[1]->done = true;
609
7.61k
        } else if (node.sub[0]->done && node.sub[1]->done) {
610
            // An internal node which we're finished with.
611
2.53k
            node.sub[0]->done = false;
612
2.53k
            node.sub[1]->done = false;
613
2.53k
            node.done = true;
614
2.53k
            stack.pop_back();
615
5.07k
        } else if (!node.sub[0]->done) {
616
            // An internal node whose left branch hasn't been processed yet. Do so first.
617
3.09k
            stack.push_back(&*node.sub[0]);
618
3.09k
        } else if (!node.sub[1]->done) {
619
            // An internal node whose right branch hasn't been processed yet. Do so first.
620
1.98k
            stack.push_back(&*node.sub[1]);
621
1.98k
        }
622
12.6k
    }
623
624
1.93k
    return ret;
625
1.93k
}
626
627
std::vector<std::tuple<uint8_t, uint8_t, std::vector<unsigned char>>> TaprootBuilder::GetTreeTuples() const
628
209
{
629
209
    assert(IsComplete());
630
209
    std::vector<std::tuple<uint8_t, uint8_t, std::vector<unsigned char>>> tuples;
631
209
    if (m_branch.size()) {
632
209
        const auto& leaves = m_branch[0]->leaves;
633
477
        for (const auto& leaf : leaves) {
634
477
            assert(leaf.merkle_branch.size() <= TAPROOT_CONTROL_MAX_NODE_COUNT);
635
477
            uint8_t depth = (uint8_t)leaf.merkle_branch.size();
636
477
            uint8_t leaf_ver = (uint8_t)leaf.leaf_version;
637
477
            tuples.emplace_back(depth, leaf_ver, leaf.script);
638
477
        }
639
209
    }
640
209
    return tuples;
641
209
}