Coverage Report

Created: 2026-06-18 19:06

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/bitcoin/src/script/signingprovider.cpp
Line
Count
Source
1
// Copyright (c) 2009-2010 Satoshi Nakamoto
2
// Copyright (c) 2009-present The Bitcoin Core developers
3
// Distributed under the MIT software license, see the accompanying
4
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6
#include <script/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
0
{
22
0
    auto it = map.find(key);
23
0
    if (it != map.end()) {
  Branch (23:9): [True: 0, False: 0]
  Branch (23:9): [True: 0, False: 0]
  Branch (23:9): [True: 0, False: 0]
  Branch (23:9): [True: 0, False: 0]
  Branch (23:9): [True: 0, False: 0]
  Branch (23:9): [True: 0, False: 0]
24
0
        value = it->second;
25
0
        return true;
26
0
    }
27
0
    return false;
28
0
}
Unexecuted instantiation: _Z12LookupHelperISt3mapI9CScriptID7CScriptSt4lessIS1_ESaISt4pairIKS1_S2_EEES1_S2_EbRKT_RKT0_RT1_
Unexecuted instantiation: _Z12LookupHelperISt3mapI6CKeyID7CPubKeySt4lessIS1_ESaISt4pairIKS1_S2_EEES1_S2_EbRKT_RKT0_RT1_
Unexecuted instantiation: _Z12LookupHelperISt3mapI6CKeyIDSt4pairI7CPubKey13KeyOriginInfoESt4lessIS1_ESaIS2_IKS1_S5_EEES1_S5_EbRKT_RKT0_RT1_
Unexecuted instantiation: _Z12LookupHelperISt3mapI6CKeyID4CKeySt4lessIS1_ESaISt4pairIKS1_S2_EEES1_S2_EbRKT_RKT0_RT1_
Unexecuted instantiation: _Z12LookupHelperISt3mapI11XOnlyPubKey14TaprootBuilderSt4lessIS1_ESaISt4pairIKS1_S2_EEES1_S2_EbRKT_RKT0_RT1_
Unexecuted instantiation: _Z12LookupHelperISt3mapI7CPubKeySt6vectorIS1_SaIS1_EESt4lessIS1_ESaISt4pairIKS1_S4_EEES1_S4_EbRKT_RKT0_RT1_
29
30
bool HidingSigningProvider::GetCScript(const CScriptID& scriptid, CScript& script) const
31
0
{
32
0
    return m_provider->GetCScript(scriptid, script);
33
0
}
34
35
bool HidingSigningProvider::GetPubKey(const CKeyID& keyid, CPubKey& pubkey) const
36
0
{
37
0
    return m_provider->GetPubKey(keyid, pubkey);
38
0
}
39
40
bool HidingSigningProvider::GetKey(const CKeyID& keyid, CKey& key) const
41
0
{
42
0
    if (m_hide_secret) return false;
  Branch (42:9): [True: 0, False: 0]
43
0
    return m_provider->GetKey(keyid, key);
44
0
}
45
46
bool HidingSigningProvider::GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const
47
0
{
48
0
    if (m_hide_origin) return false;
  Branch (48:9): [True: 0, False: 0]
49
0
    return m_provider->GetKeyOrigin(keyid, info);
50
0
}
51
52
bool HidingSigningProvider::GetTaprootSpendData(const XOnlyPubKey& output_key, TaprootSpendData& spenddata) const
53
0
{
54
0
    return m_provider->GetTaprootSpendData(output_key, spenddata);
55
0
}
56
bool HidingSigningProvider::GetTaprootBuilder(const XOnlyPubKey& output_key, TaprootBuilder& builder) const
57
0
{
58
0
    return m_provider->GetTaprootBuilder(output_key, builder);
59
0
}
60
std::vector<CPubKey> HidingSigningProvider::GetMuSig2ParticipantPubkeys(const CPubKey& pubkey) const
61
0
{
62
0
    if (m_hide_origin) return {};
  Branch (62:9): [True: 0, False: 0]
63
0
    return m_provider->GetMuSig2ParticipantPubkeys(pubkey);
64
0
}
65
66
std::map<CPubKey, std::vector<CPubKey>> HidingSigningProvider::GetAllMuSig2ParticipantPubkeys() const
67
0
{
68
0
    return m_provider->GetAllMuSig2ParticipantPubkeys();
69
0
}
70
71
void HidingSigningProvider::SetMuSig2SecNonce(const uint256& id, MuSig2SecNonce&& nonce) const
72
0
{
73
0
    m_provider->SetMuSig2SecNonce(id, std::move(nonce));
74
0
}
75
76
std::optional<std::reference_wrapper<MuSig2SecNonce>> HidingSigningProvider::GetMuSig2SecNonce(const uint256& session_id) const
77
0
{
78
0
    return m_provider->GetMuSig2SecNonce(session_id);
79
0
}
80
81
void HidingSigningProvider::DeleteMuSig2Session(const uint256& session_id) const
82
0
{
83
0
    m_provider->DeleteMuSig2Session(session_id);
84
0
}
85
86
0
bool FlatSigningProvider::GetCScript(const CScriptID& scriptid, CScript& script) const { return LookupHelper(scripts, scriptid, script); }
87
0
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
0
{
90
0
    std::pair<CPubKey, KeyOriginInfo> out;
91
0
    bool ret = LookupHelper(origins, keyid, out);
92
0
    if (ret) info = std::move(out.second);
  Branch (92:9): [True: 0, False: 0]
93
0
    return ret;
94
0
}
95
bool FlatSigningProvider::HaveKey(const CKeyID &keyid) const
96
0
{
97
0
    CKey key;
98
0
    return LookupHelper(keys, keyid, key);
99
0
}
100
0
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
0
{
103
0
    TaprootBuilder builder;
104
0
    if (LookupHelper(tr_trees, output_key, builder)) {
  Branch (104:9): [True: 0, False: 0]
105
0
        spenddata = builder.GetSpendData();
106
0
        return true;
107
0
    }
108
0
    return false;
109
0
}
110
bool FlatSigningProvider::GetTaprootBuilder(const XOnlyPubKey& output_key, TaprootBuilder& builder) const
111
0
{
112
0
    return LookupHelper(tr_trees, output_key, builder);
113
0
}
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
0
{
124
0
    return aggregate_pubkeys;
125
0
}
126
127
void FlatSigningProvider::SetMuSig2SecNonce(const uint256& session_id, MuSig2SecNonce&& nonce) const
128
0
{
129
0
    if (!Assume(musig2_secnonces)) return;
  Branch (129:9): [True: 0, False: 0]
130
0
    auto [it, inserted] = musig2_secnonces->try_emplace(session_id, std::move(nonce));
131
    // No secnonce should exist for this session yet.
132
0
    Assert(inserted);
133
0
}
134
135
std::optional<std::reference_wrapper<MuSig2SecNonce>> FlatSigningProvider::GetMuSig2SecNonce(const uint256& session_id) const
136
0
{
137
0
    if (!Assume(musig2_secnonces)) return std::nullopt;
  Branch (137:9): [True: 0, False: 0]
138
0
    const auto& it = musig2_secnonces->find(session_id);
139
0
    if (it == musig2_secnonces->end()) return std::nullopt;
  Branch (139:9): [True: 0, False: 0]
140
0
    return it->second;
141
0
}
142
143
void FlatSigningProvider::DeleteMuSig2Session(const uint256& session_id) const
144
0
{
145
0
    if (!Assume(musig2_secnonces)) return;
  Branch (145:9): [True: 0, False: 0]
146
0
    musig2_secnonces->erase(session_id);
147
0
}
148
149
FlatSigningProvider& FlatSigningProvider::Merge(FlatSigningProvider&& b)
150
0
{
151
0
    scripts.merge(b.scripts);
152
0
    pubkeys.merge(b.pubkeys);
153
0
    keys.merge(b.keys);
154
0
    origins.merge(b.origins);
155
0
    tr_trees.merge(b.tr_trees);
156
0
    aggregate_pubkeys.merge(b.aggregate_pubkeys);
157
    // We shouldn't be merging 2 different sessions, just overwrite with b's sessions.
158
0
    if (!musig2_secnonces) musig2_secnonces = b.musig2_secnonces;
  Branch (158:9): [True: 0, False: 0]
159
0
    return *this;
160
0
}
161
162
void FillableSigningProvider::ImplicitlyLearnRelatedKeyScripts(const CPubKey& pubkey)
163
0
{
164
0
    AssertLockHeld(cs_KeyStore);
165
0
    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
0
    if (pubkey.IsCompressed()) {
  Branch (177:9): [True: 0, False: 0]
178
0
        CScript script = GetScriptForDestination(WitnessV0KeyHash(key_id));
179
        // This does not use AddCScript, as it may be overridden.
180
0
        CScriptID id(script);
181
0
        mapScripts[id] = std::move(script);
182
0
    }
183
0
}
184
185
bool FillableSigningProvider::GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const
186
0
{
187
0
    CKey key;
188
0
    if (!GetKey(address, key)) {
  Branch (188:9): [True: 0, False: 0]
189
0
        return false;
190
0
    }
191
0
    vchPubKeyOut = key.GetPubKey();
192
0
    return true;
193
0
}
194
195
bool FillableSigningProvider::AddKeyPubKey(const CKey& key, const CPubKey &pubkey)
196
0
{
197
0
    LOCK(cs_KeyStore);
198
0
    mapKeys[pubkey.GetID()] = key;
199
0
    ImplicitlyLearnRelatedKeyScripts(pubkey);
200
0
    return true;
201
0
}
202
203
bool FillableSigningProvider::HaveKey(const CKeyID &address) const
204
0
{
205
0
    LOCK(cs_KeyStore);
206
0
    return mapKeys.contains(address);
207
0
}
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) {
  Branch (213:25): [True: 0, False: 0]
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
0
{
221
0
    LOCK(cs_KeyStore);
222
0
    KeyMap::const_iterator mi = mapKeys.find(address);
223
0
    if (mi != mapKeys.end()) {
  Branch (223:9): [True: 0, False: 0]
224
0
        keyOut = mi->second;
225
0
        return true;
226
0
    }
227
0
    return false;
228
0
}
229
230
bool FillableSigningProvider::AddCScript(const CScript& redeemScript)
231
0
{
232
0
    if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE) {
  Branch (232:9): [True: 0, False: 0]
233
0
        LogError("FillableSigningProvider::AddCScript(): redeemScripts > %i bytes are invalid\n", MAX_SCRIPT_ELEMENT_SIZE);
234
0
        return false;
235
0
    }
236
237
0
    LOCK(cs_KeyStore);
238
0
    mapScripts[CScriptID(redeemScript)] = redeemScript;
239
0
    return true;
240
0
}
241
242
bool FillableSigningProvider::HaveCScript(const CScriptID& hash) const
243
0
{
244
0
    LOCK(cs_KeyStore);
245
0
    return mapScripts.contains(hash);
246
0
}
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) {
  Branch (252:25): [True: 0, False: 0]
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
0
{
260
0
    LOCK(cs_KeyStore);
261
0
    ScriptMap::const_iterator mi = mapScripts.find(hash);
262
0
    if (mi != mapScripts.end())
  Branch (262:9): [True: 0, False: 0]
263
0
    {
264
0
        redeemScriptOut = (*mi).second;
265
0
        return true;
266
0
    }
267
0
    return false;
268
0
}
269
270
CKeyID GetKeyForDestination(const SigningProvider& store, const CTxDestination& dest)
271
0
{
272
    // Only supports destinations which map to single public keys:
273
    // P2PKH, P2WPKH, P2SH-P2WPKH, P2TR
274
0
    if (auto id = std::get_if<PKHash>(&dest)) {
  Branch (274:14): [True: 0, False: 0]
275
0
        return ToKeyID(*id);
276
0
    }
277
0
    if (auto witness_id = std::get_if<WitnessV0KeyHash>(&dest)) {
  Branch (277:14): [True: 0, False: 0]
278
0
        return ToKeyID(*witness_id);
279
0
    }
280
0
    if (auto script_hash = std::get_if<ScriptHash>(&dest)) {
  Branch (280:14): [True: 0, False: 0]
281
0
        CScript script;
282
0
        CScriptID script_id = ToScriptID(*script_hash);
283
0
        CTxDestination inner_dest;
284
0
        if (store.GetCScript(script_id, script) && ExtractDestination(script, inner_dest)) {
  Branch (284:13): [True: 0, False: 0]
  Branch (284:52): [True: 0, False: 0]
285
0
            if (auto inner_witness_id = std::get_if<WitnessV0KeyHash>(&inner_dest)) {
  Branch (285:22): [True: 0, False: 0]
286
0
                return ToKeyID(*inner_witness_id);
287
0
            }
288
0
        }
289
0
    }
290
0
    if (auto output_key = std::get_if<WitnessV1Taproot>(&dest)) {
  Branch (290:14): [True: 0, False: 0]
291
0
        TaprootSpendData spenddata;
292
0
        CPubKey pub;
293
0
        if (store.GetTaprootSpendData(*output_key, spenddata)
  Branch (293:13): [True: 0, False: 0]
294
0
            && !spenddata.internal_key.IsNull()
  Branch (294:16): [True: 0, False: 0]
295
0
            && spenddata.merkle_root.IsNull()
  Branch (295:16): [True: 0, False: 0]
296
0
            && store.GetPubKeyByXOnly(spenddata.internal_key, pub)) {
  Branch (296:16): [True: 0, False: 0]
297
0
            return pub.GetID();
298
0
        }
299
0
    }
300
0
    return CKeyID();
301
0
}
302
303
void MultiSigningProvider::AddProvider(std::unique_ptr<SigningProvider> provider)
304
0
{
305
0
    m_providers.push_back(std::move(provider));
306
0
}
307
308
bool MultiSigningProvider::GetCScript(const CScriptID& scriptid, CScript& script) const
309
0
{
310
0
    for (const auto& provider: m_providers) {
  Branch (310:30): [True: 0, False: 0]
311
0
        if (provider->GetCScript(scriptid, script)) return true;
  Branch (311:13): [True: 0, False: 0]
312
0
    }
313
0
    return false;
314
0
}
315
316
bool MultiSigningProvider::GetPubKey(const CKeyID& keyid, CPubKey& pubkey) const
317
0
{
318
0
    for (const auto& provider: m_providers) {
  Branch (318:30): [True: 0, False: 0]
319
0
        if (provider->GetPubKey(keyid, pubkey)) return true;
  Branch (319:13): [True: 0, False: 0]
320
0
    }
321
0
    return false;
322
0
}
323
324
325
bool MultiSigningProvider::GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const
326
0
{
327
0
    for (const auto& provider: m_providers) {
  Branch (327:30): [True: 0, False: 0]
328
0
        if (provider->GetKeyOrigin(keyid, info)) return true;
  Branch (328:13): [True: 0, False: 0]
329
0
    }
330
0
    return false;
331
0
}
332
333
bool MultiSigningProvider::GetKey(const CKeyID& keyid, CKey& key) const
334
0
{
335
0
    for (const auto& provider: m_providers) {
  Branch (335:30): [True: 0, False: 0]
336
0
        if (provider->GetKey(keyid, key)) return true;
  Branch (336:13): [True: 0, False: 0]
337
0
    }
338
0
    return false;
339
0
}
340
341
bool MultiSigningProvider::GetTaprootSpendData(const XOnlyPubKey& output_key, TaprootSpendData& spenddata) const
342
0
{
343
0
    for (const auto& provider: m_providers) {
  Branch (343:30): [True: 0, False: 0]
344
0
        if (provider->GetTaprootSpendData(output_key, spenddata)) return true;
  Branch (344:13): [True: 0, False: 0]
345
0
    }
346
0
    return false;
347
0
}
348
349
bool MultiSigningProvider::GetTaprootBuilder(const XOnlyPubKey& output_key, TaprootBuilder& builder) const
350
0
{
351
0
    for (const auto& provider: m_providers) {
  Branch (351:30): [True: 0, False: 0]
352
0
        if (provider->GetTaprootBuilder(output_key, builder)) return true;
  Branch (352:13): [True: 0, False: 0]
353
0
    }
354
0
    return false;
355
0
}
356
357
/*static*/ TaprootBuilder::NodeInfo TaprootBuilder::Combine(NodeInfo&& a, NodeInfo&& b)
358
0
{
359
0
    NodeInfo ret;
360
    /* Iterate over all tracked leaves in a, add b's hash to their Merkle branch, and move them to ret. */
361
0
    for (auto& leaf : a.leaves) {
  Branch (361:21): [True: 0, False: 0]
362
0
        leaf.merkle_branch.push_back(b.hash);
363
0
        ret.leaves.emplace_back(std::move(leaf));
364
0
    }
365
    /* Iterate over all tracked leaves in b, add a's hash to their Merkle branch, and move them to ret. */
366
0
    for (auto& leaf : b.leaves) {
  Branch (366:21): [True: 0, False: 0]
367
0
        leaf.merkle_branch.push_back(a.hash);
368
0
        ret.leaves.emplace_back(std::move(leaf));
369
0
    }
370
0
    ret.hash = ComputeTapbranchHash(a.hash, b.hash);
371
0
    return ret;
372
0
}
373
374
void TaprootSpendData::Merge(TaprootSpendData other)
375
0
{
376
    // TODO: figure out how to better deal with conflicting information
377
    // being merged.
378
0
    if (internal_key.IsNull() && !other.internal_key.IsNull()) {
  Branch (378:9): [True: 0, False: 0]
  Branch (378:34): [True: 0, False: 0]
379
0
        internal_key = other.internal_key;
380
0
    }
381
0
    if (merkle_root.IsNull() && !other.merkle_root.IsNull()) {
  Branch (381:9): [True: 0, False: 0]
  Branch (381:33): [True: 0, False: 0]
382
0
        merkle_root = other.merkle_root;
383
0
    }
384
0
    for (auto& [key, control_blocks] : other.scripts) {
  Branch (384:38): [True: 0, False: 0]
385
0
        scripts[key].merge(std::move(control_blocks));
386
0
    }
387
0
}
388
389
void TaprootBuilder::Insert(TaprootBuilder::NodeInfo&& node, int depth)
390
0
{
391
0
    assert(depth >= 0 && (size_t)depth <= TAPROOT_CONTROL_MAX_NODE_COUNT);
  Branch (391:5): [True: 0, False: 0]
  Branch (391:5): [True: 0, False: 0]
  Branch (391:5): [True: 0, False: 0]
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
0
    if ((size_t)depth + 1 < m_branch.size()) {
  Branch (395:9): [True: 0, False: 0]
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
0
    while (m_valid && m_branch.size() > (size_t)depth && m_branch[depth].has_value()) {
  Branch (401:12): [True: 0, False: 0]
  Branch (401:23): [True: 0, False: 0]
  Branch (401:58): [True: 0, False: 0]
402
0
        node = Combine(std::move(node), std::move(*m_branch[depth]));
403
0
        m_branch.pop_back();
404
0
        if (depth == 0) m_valid = false; /* Can't propagate further up than the root */
  Branch (404:13): [True: 0, False: 0]
405
0
        --depth;
406
0
    }
407
0
    if (m_valid) {
  Branch (407:9): [True: 0, False: 0]
408
        /* Make sure the branch is big enough to place the new node. */
409
0
        if (m_branch.size() <= (size_t)depth) m_branch.resize((size_t)depth + 1);
  Branch (409:13): [True: 0, False: 0]
410
0
        assert(!m_branch[depth].has_value());
  Branch (410:9): [True: 0, False: 0]
411
0
        m_branch[depth] = std::move(node);
412
0
    }
413
0
}
414
415
/*static*/ bool TaprootBuilder::ValidDepths(const std::vector<int>& depths)
416
0
{
417
0
    std::vector<bool> branch;
418
0
    for (int depth : depths) {
  Branch (418:20): [True: 0, False: 0]
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
0
        if (depth < 0 || (size_t)depth > TAPROOT_CONTROL_MAX_NODE_COUNT) return false;
  Branch (423:13): [True: 0, False: 0]
  Branch (423:26): [True: 0, False: 0]
424
0
        if ((size_t)depth + 1 < branch.size()) return false;
  Branch (424:13): [True: 0, False: 0]
425
0
        while (branch.size() > (size_t)depth && branch[depth]) {
  Branch (425:16): [True: 0, False: 0]
  Branch (425:16): [True: 0, False: 0]
  Branch (425:49): [True: 0, False: 0]
426
0
            branch.pop_back();
427
0
            if (depth == 0) return false;
  Branch (427:17): [True: 0, False: 0]
428
0
            --depth;
429
0
        }
430
0
        if (branch.size() <= (size_t)depth) branch.resize((size_t)depth + 1);
  Branch (430:13): [True: 0, False: 0]
431
0
        assert(!branch[depth]);
  Branch (431:9): [True: 0, False: 0]
432
0
        branch[depth] = true;
433
0
    }
434
    // And this check corresponds to the IsComplete() check on m_branch.
435
0
    return branch.size() == 0 || (branch.size() == 1 && branch[0]);
  Branch (435:12): [True: 0, False: 0]
  Branch (435:35): [True: 0, False: 0]
  Branch (435:57): [True: 0, False: 0]
436
0
}
437
438
TaprootBuilder& TaprootBuilder::Add(int depth, std::span<const unsigned char> script, int leaf_version, bool track)
439
0
{
440
0
    assert((leaf_version & ~TAPROOT_LEAF_MASK) == 0);
  Branch (440:5): [True: 0, False: 0]
441
0
    if (!IsValid()) return *this;
  Branch (441:9): [True: 0, False: 0]
442
    /* Construct NodeInfo object with leaf hash and (if track is true) also leaf information. */
443
0
    NodeInfo node;
444
0
    node.hash = ComputeTapleafHash(leaf_version, script);
445
0
    if (track) node.leaves.emplace_back(LeafInfo{std::vector<unsigned char>(script.begin(), script.end()), leaf_version, {}});
  Branch (445:9): [True: 0, False: 0]
446
    /* Insert into the branch. */
447
0
    Insert(std::move(node), depth);
448
0
    return *this;
449
0
}
450
451
TaprootBuilder& TaprootBuilder::AddOmitted(int depth, const uint256& hash)
452
0
{
453
0
    if (!IsValid()) return *this;
  Branch (453:9): [True: 0, False: 0]
454
    /* Construct NodeInfo object with the hash directly, and insert it into the branch. */
455
0
    NodeInfo node;
456
0
    node.hash = hash;
457
0
    Insert(std::move(node), depth);
458
0
    return *this;
459
0
}
460
461
TaprootBuilder& TaprootBuilder::Finalize(const XOnlyPubKey& internal_key)
462
0
{
463
    /* Can only call this function when IsComplete() is true. */
464
0
    assert(IsComplete());
  Branch (464:5): [True: 0, False: 0]
465
0
    m_internal_key = internal_key;
466
0
    auto ret = m_internal_key.CreateTapTweak(m_branch.size() == 0 ? nullptr : &m_branch[0]->hash);
  Branch (466:46): [True: 0, False: 0]
467
0
    assert(ret.has_value());
  Branch (467:5): [True: 0, False: 0]
468
0
    std::tie(m_output_key, m_parity) = *ret;
469
0
    return *this;
470
0
}
471
472
0
WitnessV1Taproot TaprootBuilder::GetOutput() { return WitnessV1Taproot{m_output_key}; }
473
474
TaprootSpendData TaprootBuilder::GetSpendData() const
475
0
{
476
0
    assert(IsComplete());
  Branch (476:5): [True: 0, False: 0]
477
0
    assert(m_output_key.IsFullyValid());
  Branch (477:5): [True: 0, False: 0]
478
0
    TaprootSpendData spd;
479
0
    spd.merkle_root = m_branch.size() == 0 ? uint256() : m_branch[0]->hash;
  Branch (479:23): [True: 0, False: 0]
480
0
    spd.internal_key = m_internal_key;
481
0
    if (m_branch.size()) {
  Branch (481:9): [True: 0, False: 0]
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
0
        for (const auto& leaf : m_branch[0]->leaves) {
  Branch (485:31): [True: 0, False: 0]
486
0
            std::vector<unsigned char> control_block;
487
0
            control_block.resize(TAPROOT_CONTROL_BASE_SIZE + TAPROOT_CONTROL_NODE_SIZE * leaf.merkle_branch.size());
488
0
            control_block[0] = leaf.leaf_version | (m_parity ? 1 : 0);
  Branch (488:53): [True: 0, False: 0]
489
0
            std::copy(m_internal_key.begin(), m_internal_key.end(), control_block.begin() + 1);
490
0
            if (leaf.merkle_branch.size()) {
  Branch (490:17): [True: 0, False: 0]
491
0
                std::copy(leaf.merkle_branch[0].begin(),
492
0
                          leaf.merkle_branch[0].begin() + TAPROOT_CONTROL_NODE_SIZE * leaf.merkle_branch.size(),
493
0
                          control_block.begin() + TAPROOT_CONTROL_BASE_SIZE);
494
0
            }
495
0
            spd.scripts[{leaf.script, leaf.leaf_version}].insert(std::move(control_block));
496
0
        }
497
0
    }
498
0
    return spd;
499
0
}
500
501
std::optional<std::vector<std::tuple<int, std::vector<unsigned char>, int>>> InferTaprootTree(const TaprootSpendData& spenddata, const XOnlyPubKey& output)
502
0
{
503
    // Verify that the output matches the assumed Merkle root and internal key.
504
0
    auto tweak = spenddata.internal_key.CreateTapTweak(spenddata.merkle_root.IsNull() ? nullptr : &spenddata.merkle_root);
  Branch (504:56): [True: 0, False: 0]
505
0
    if (!tweak || tweak->first != output) return std::nullopt;
  Branch (505:9): [True: 0, False: 0]
  Branch (505:19): [True: 0, False: 0]
506
    // If the Merkle root is 0, the tree is empty, and we're done.
507
0
    std::vector<std::tuple<int, std::vector<unsigned char>, int>> ret;
508
0
    if (spenddata.merkle_root.IsNull()) return ret;
  Branch (508:9): [True: 0, False: 0]
509
510
    /** Data structure to represent the nodes of the tree we're going to build. */
511
0
    struct TreeNode {
512
        /** Hash of this node, if known; 0 otherwise. */
513
0
        uint256 hash;
514
        /** The left and right subtrees (note that their order is irrelevant). */
515
0
        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
0
        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
0
        bool explored = false;
521
        /** Whether or not this node is an inner node (unknown until explored = true). */
522
0
        bool inner;
523
        /** Whether or not we have produced output for this subtree. */
524
0
        bool done = false;
525
0
    };
526
527
    // Build tree from the provided branches.
528
0
    TreeNode root;
529
0
    root.hash = spenddata.merkle_root;
530
0
    for (const auto& [key, control_blocks] : spenddata.scripts) {
  Branch (530:44): [True: 0, False: 0]
531
0
        const auto& [script, leaf_ver] = key;
532
0
        for (const auto& control : control_blocks) {
  Branch (532:34): [True: 0, False: 0]
533
            // Skip script records with nonsensical leaf version.
534
0
            if (leaf_ver < 0 || leaf_ver >= 0x100 || leaf_ver & 1) continue;
  Branch (534:17): [True: 0, False: 0]
  Branch (534:33): [True: 0, False: 0]
  Branch (534:54): [True: 0, False: 0]
535
            // Skip script records with invalid control block sizes.
536
0
            if (control.size() < TAPROOT_CONTROL_BASE_SIZE || control.size() > TAPROOT_CONTROL_MAX_SIZE ||
  Branch (536:17): [True: 0, False: 0]
  Branch (536:63): [True: 0, False: 0]
537
0
                ((control.size() - TAPROOT_CONTROL_BASE_SIZE) % TAPROOT_CONTROL_NODE_SIZE) != 0) continue;
  Branch (537:17): [True: 0, False: 0]
538
            // Skip script records that don't match the control block.
539
0
            if ((control[0] & TAPROOT_LEAF_MASK) != leaf_ver) continue;
  Branch (539:17): [True: 0, False: 0]
540
            // Skip script records that don't match the provided Merkle root.
541
0
            const uint256 leaf_hash = ComputeTapleafHash(leaf_ver, script);
542
0
            const uint256 merkle_root = ComputeTaprootMerkleRoot(control, leaf_hash);
543
0
            if (merkle_root != spenddata.merkle_root) continue;
  Branch (543:17): [True: 0, False: 0]
544
545
0
            TreeNode* node = &root;
546
0
            size_t levels = (control.size() - TAPROOT_CONTROL_BASE_SIZE) / TAPROOT_CONTROL_NODE_SIZE;
547
0
            for (size_t depth = 0; depth < levels; ++depth) {
  Branch (547:36): [True: 0, False: 0]
548
                // Can't descend into a node which we already know is a leaf.
549
0
                if (node->explored && !node->inner) return std::nullopt;
  Branch (549:21): [True: 0, False: 0]
  Branch (549:39): [True: 0, False: 0]
550
551
                // Extract partner hash from Merkle branch in control block.
552
0
                uint256 hash;
553
0
                std::copy(control.begin() + TAPROOT_CONTROL_BASE_SIZE + (levels - 1 - depth) * TAPROOT_CONTROL_NODE_SIZE,
554
0
                          control.begin() + TAPROOT_CONTROL_BASE_SIZE + (levels - depth) * TAPROOT_CONTROL_NODE_SIZE,
555
0
                          hash.begin());
556
557
0
                if (node->sub[0]) {
  Branch (557:21): [True: 0, False: 0]
558
                    // Descend into the existing left or right branch.
559
0
                    bool desc = false;
560
0
                    for (int i = 0; i < 2; ++i) {
  Branch (560:37): [True: 0, False: 0]
561
0
                        if (node->sub[i]->hash == hash || (node->sub[i]->hash.IsNull() && node->sub[1-i]->hash != hash)) {
  Branch (561:29): [True: 0, False: 0]
  Branch (561:60): [True: 0, False: 0]
  Branch (561:91): [True: 0, False: 0]
562
0
                            node->sub[i]->hash = hash;
563
0
                            node = &*node->sub[1-i];
564
0
                            desc = true;
565
0
                            break;
566
0
                        }
567
0
                    }
568
0
                    if (!desc) return std::nullopt; // This probably requires a hash collision to hit.
  Branch (568:25): [True: 0, False: 0]
569
0
                } else {
570
                    // We're in an unexplored node. Create subtrees and descend.
571
0
                    node->explored = true;
572
0
                    node->inner = true;
573
0
                    node->sub[0] = std::make_unique<TreeNode>();
574
0
                    node->sub[1] = std::make_unique<TreeNode>();
575
0
                    node->sub[1]->hash = hash;
576
0
                    node = &*node->sub[0];
577
0
                }
578
0
            }
579
            // Cannot turn a known inner node into a leaf.
580
0
            if (node->sub[0]) return std::nullopt;
  Branch (580:17): [True: 0, False: 0]
581
0
            node->explored = true;
582
0
            node->inner = false;
583
0
            node->leaf = &key;
584
0
            node->hash = leaf_hash;
585
0
        }
586
0
    }
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
0
    std::vector<TreeNode*> stack{&root};
591
0
    while (!stack.empty()) {
  Branch (591:12): [True: 0, False: 0]
592
0
        TreeNode& node = *stack.back();
593
0
        if (!node.explored) {
  Branch (593:13): [True: 0, False: 0]
594
            // Unexplored node, which means the tree is incomplete.
595
0
            return std::nullopt;
596
0
        } else if (!node.inner) {
  Branch (596:20): [True: 0, False: 0]
597
            // Leaf node; produce output.
598
0
            ret.emplace_back(stack.size() - 1, node.leaf->first, node.leaf->second);
599
0
            node.done = true;
600
0
            stack.pop_back();
601
0
        } else if (node.sub[0]->done && !node.sub[1]->done && !node.sub[1]->explored && !node.sub[1]->hash.IsNull() &&
  Branch (601:20): [True: 0, False: 0]
  Branch (601:20): [True: 0, False: 0]
  Branch (601:41): [True: 0, False: 0]
  Branch (601:63): [True: 0, False: 0]
  Branch (601:89): [True: 0, False: 0]
602
0
                   ComputeTapbranchHash(node.sub[1]->hash, node.sub[1]->hash) == node.hash) {
  Branch (602:20): [True: 0, False: 0]
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
0
            node.sub[0]->done = false;
617
0
            node.sub[1]->done = true;
618
0
        } else if (node.sub[0]->done && node.sub[1]->done) {
  Branch (618:20): [True: 0, False: 0]
  Branch (618:41): [True: 0, False: 0]
619
            // An internal node which we're finished with.
620
0
            node.sub[0]->done = false;
621
0
            node.sub[1]->done = false;
622
0
            node.done = true;
623
0
            stack.pop_back();
624
0
        } else if (!node.sub[0]->done) {
  Branch (624:20): [True: 0, False: 0]
625
            // An internal node whose left branch hasn't been processed yet. Do so first.
626
0
            stack.push_back(&*node.sub[0]);
627
0
        } else if (!node.sub[1]->done) {
  Branch (627:20): [True: 0, False: 0]
628
            // An internal node whose right branch hasn't been processed yet. Do so first.
629
0
            stack.push_back(&*node.sub[1]);
630
0
        }
631
0
    }
632
633
0
    return ret;
634
0
}
635
636
std::vector<std::tuple<uint8_t, uint8_t, std::vector<unsigned char>>> TaprootBuilder::GetTreeTuples() const
637
0
{
638
0
    assert(IsComplete());
  Branch (638:5): [True: 0, False: 0]
639
0
    std::vector<std::tuple<uint8_t, uint8_t, std::vector<unsigned char>>> tuples;
640
0
    if (m_branch.size()) {
  Branch (640:9): [True: 0, False: 0]
641
0
        const auto& leaves = m_branch[0]->leaves;
642
0
        for (const auto& leaf : leaves) {
  Branch (642:31): [True: 0, False: 0]
643
0
            assert(leaf.merkle_branch.size() <= TAPROOT_CONTROL_MAX_NODE_COUNT);
  Branch (643:13): [True: 0, False: 0]
644
0
            uint8_t depth = (uint8_t)leaf.merkle_branch.size();
645
0
            uint8_t leaf_ver = (uint8_t)leaf.leaf_version;
646
0
            tuples.emplace_back(depth, leaf_ver, leaf.script);
647
0
        }
648
0
    }
649
0
    return tuples;
650
0
}