Coverage Report

Created: 2026-05-30 09:47

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