fuzz coverage

Coverage Report

Created: 2025-06-01 19:34

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