Coverage Report

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