fuzz coverage

Coverage Report

Created: 2025-09-17 22:41

/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_
Unexecuted instantiation: _Z12LookupHelperINSt3__13mapI7CPubKeyNS0_6vectorIS2_NS0_9allocatorIS2_EEEENS0_4lessIS2_EENS4_INS0_4pairIKS2_S6_EEEEEES2_S6_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
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
0
bool FlatSigningProvider::GetCScript(const CScriptID& scriptid, CScript& script) const { return LookupHelper(scripts, scriptid, script); }
62
0
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
0
{
65
0
    std::pair<CPubKey, KeyOriginInfo> out;
66
0
    bool ret = LookupHelper(origins, keyid, out);
67
0
    if (ret) info = std::move(out.second);
68
0
    return ret;
69
0
}
70
bool FlatSigningProvider::HaveKey(const CKeyID &keyid) const
71
0
{
72
0
    CKey key;
73
0
    return LookupHelper(keys, keyid, key);
74
0
}
75
0
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
0
{
78
0
    TaprootBuilder builder;
79
0
    if (LookupHelper(tr_trees, output_key, builder)) {
80
0
        spenddata = builder.GetSpendData();
81
0
        return true;
82
0
    }
83
0
    return false;
84
0
}
85
bool FlatSigningProvider::GetTaprootBuilder(const XOnlyPubKey& output_key, TaprootBuilder& builder) const
86
0
{
87
0
    return LookupHelper(tr_trees, output_key, builder);
88
0
}
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
0
{
99
0
    scripts.merge(b.scripts);
100
0
    pubkeys.merge(b.pubkeys);
101
0
    keys.merge(b.keys);
102
0
    origins.merge(b.origins);
103
0
    tr_trees.merge(b.tr_trees);
104
0
    aggregate_pubkeys.merge(b.aggregate_pubkeys);
105
0
    return *this;
106
0
}
107
108
void FillableSigningProvider::ImplicitlyLearnRelatedKeyScripts(const CPubKey& pubkey)
109
0
{
110
0
    AssertLockHeld(cs_KeyStore);
Line
Count
Source
137
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
111
0
    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
0
    if (pubkey.IsCompressed()) {
124
0
        CScript script = GetScriptForDestination(WitnessV0KeyHash(key_id));
125
        // This does not use AddCScript, as it may be overridden.
126
0
        CScriptID id(script);
127
0
        mapScripts[id] = std::move(script);
128
0
    }
129
0
}
130
131
bool FillableSigningProvider::GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const
132
0
{
133
0
    CKey key;
134
0
    if (!GetKey(address, key)) {
135
0
        return false;
136
0
    }
137
0
    vchPubKeyOut = key.GetPubKey();
138
0
    return true;
139
0
}
140
141
bool FillableSigningProvider::AddKeyPubKey(const CKey& key, const CPubKey &pubkey)
142
0
{
143
0
    LOCK(cs_KeyStore);
Line
Count
Source
259
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
144
0
    mapKeys[pubkey.GetID()] = key;
145
0
    ImplicitlyLearnRelatedKeyScripts(pubkey);
146
0
    return true;
147
0
}
148
149
bool FillableSigningProvider::HaveKey(const CKeyID &address) const
150
0
{
151
0
    LOCK(cs_KeyStore);
Line
Count
Source
259
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
152
0
    return mapKeys.count(address) > 0;
153
0
}
154
155
std::set<CKeyID> FillableSigningProvider::GetKeys() const
156
0
{
157
0
    LOCK(cs_KeyStore);
Line
Count
Source
259
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
158
0
    std::set<CKeyID> set_address;
159
0
    for (const auto& mi : mapKeys) {
160
0
        set_address.insert(mi.first);
161
0
    }
162
0
    return set_address;
163
0
}
164
165
bool FillableSigningProvider::GetKey(const CKeyID &address, CKey &keyOut) const
166
0
{
167
0
    LOCK(cs_KeyStore);
Line
Count
Source
259
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
168
0
    KeyMap::const_iterator mi = mapKeys.find(address);
169
0
    if (mi != mapKeys.end()) {
170
0
        keyOut = mi->second;
171
0
        return true;
172
0
    }
173
0
    return false;
174
0
}
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);
Line
Count
Source
358
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
350
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__)
180
0
        return false;
181
0
    }
182
183
0
    LOCK(cs_KeyStore);
Line
Count
Source
259
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
    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);
Line
Count
Source
259
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
191
0
    return mapScripts.count(hash) > 0;
192
0
}
193
194
std::set<CScriptID> FillableSigningProvider::GetCScripts() const
195
0
{
196
0
    LOCK(cs_KeyStore);
Line
Count
Source
259
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
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
0
{
206
0
    LOCK(cs_KeyStore);
Line
Count
Source
259
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
207
0
    ScriptMap::const_iterator mi = mapScripts.find(hash);
208
0
    if (mi != mapScripts.end())
209
0
    {
210
0
        redeemScriptOut = (*mi).second;
211
0
        return true;
212
0
    }
213
0
    return false;
214
0
}
215
216
CKeyID GetKeyForDestination(const SigningProvider& store, const CTxDestination& dest)
217
0
{
218
    // Only supports destinations which map to single public keys:
219
    // P2PKH, P2WPKH, P2SH-P2WPKH, P2TR
220
0
    if (auto id = std::get_if<PKHash>(&dest)) {
221
0
        return ToKeyID(*id);
222
0
    }
223
0
    if (auto witness_id = std::get_if<WitnessV0KeyHash>(&dest)) {
224
0
        return ToKeyID(*witness_id);
225
0
    }
226
0
    if (auto script_hash = std::get_if<ScriptHash>(&dest)) {
227
0
        CScript script;
228
0
        CScriptID script_id = ToScriptID(*script_hash);
229
0
        CTxDestination inner_dest;
230
0
        if (store.GetCScript(script_id, script) && ExtractDestination(script, inner_dest)) {
231
0
            if (auto inner_witness_id = std::get_if<WitnessV0KeyHash>(&inner_dest)) {
232
0
                return ToKeyID(*inner_witness_id);
233
0
            }
234
0
        }
235
0
    }
236
0
    if (auto output_key = std::get_if<WitnessV1Taproot>(&dest)) {
237
0
        TaprootSpendData spenddata;
238
0
        CPubKey pub;
239
0
        if (store.GetTaprootSpendData(*output_key, spenddata)
240
0
            && !spenddata.internal_key.IsNull()
241
0
            && spenddata.merkle_root.IsNull()
242
0
            && store.GetPubKeyByXOnly(spenddata.internal_key, pub)) {
243
0
            return pub.GetID();
244
0
        }
245
0
    }
246
0
    return CKeyID();
247
0
}
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
0
{
305
0
    NodeInfo ret;
306
    /* Iterate over all tracked leaves in a, add b's hash to their Merkle branch, and move them to ret. */
307
0
    for (auto& leaf : a.leaves) {
308
0
        leaf.merkle_branch.push_back(b.hash);
309
0
        ret.leaves.emplace_back(std::move(leaf));
310
0
    }
311
    /* Iterate over all tracked leaves in b, add a's hash to their Merkle branch, and move them to ret. */
312
0
    for (auto& leaf : b.leaves) {
313
0
        leaf.merkle_branch.push_back(a.hash);
314
0
        ret.leaves.emplace_back(std::move(leaf));
315
0
    }
316
0
    ret.hash = ComputeTapbranchHash(a.hash, b.hash);
317
0
    return ret;
318
0
}
319
320
void TaprootSpendData::Merge(TaprootSpendData other)
321
0
{
322
    // TODO: figure out how to better deal with conflicting information
323
    // being merged.
324
0
    if (internal_key.IsNull() && !other.internal_key.IsNull()) {
325
0
        internal_key = other.internal_key;
326
0
    }
327
0
    if (merkle_root.IsNull() && !other.merkle_root.IsNull()) {
328
0
        merkle_root = other.merkle_root;
329
0
    }
330
0
    for (auto& [key, control_blocks] : other.scripts) {
331
0
        scripts[key].merge(std::move(control_blocks));
332
0
    }
333
0
}
334
335
void TaprootBuilder::Insert(TaprootBuilder::NodeInfo&& node, int depth)
336
0
{
337
0
    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
0
    if ((size_t)depth + 1 < m_branch.size()) {
342
0
        m_valid = false;
343
0
        return;
344
0
    }
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
0
    while (m_valid && m_branch.size() > (size_t)depth && m_branch[depth].has_value()) {
348
0
        node = Combine(std::move(node), std::move(*m_branch[depth]));
349
0
        m_branch.pop_back();
350
0
        if (depth == 0) m_valid = false; /* Can't propagate further up than the root */
351
0
        --depth;
352
0
    }
353
0
    if (m_valid) {
354
        /* Make sure the branch is big enough to place the new node. */
355
0
        if (m_branch.size() <= (size_t)depth) m_branch.resize((size_t)depth + 1);
356
0
        assert(!m_branch[depth].has_value());
357
0
        m_branch[depth] = std::move(node);
358
0
    }
359
0
}
360
361
/*static*/ bool TaprootBuilder::ValidDepths(const std::vector<int>& depths)
362
0
{
363
0
    std::vector<bool> branch;
364
0
    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
0
        if (depth < 0 || (size_t)depth > TAPROOT_CONTROL_MAX_NODE_COUNT) return false;
370
0
        if ((size_t)depth + 1 < branch.size()) return false;
371
0
        while (branch.size() > (size_t)depth && branch[depth]) {
372
0
            branch.pop_back();
373
0
            if (depth == 0) return false;
374
0
            --depth;
375
0
        }
376
0
        if (branch.size() <= (size_t)depth) branch.resize((size_t)depth + 1);
377
0
        assert(!branch[depth]);
378
0
        branch[depth] = true;
379
0
    }
380
    // And this check corresponds to the IsComplete() check on m_branch.
381
0
    return branch.size() == 0 || (branch.size() == 1 && branch[0]);
382
0
}
383
384
TaprootBuilder& TaprootBuilder::Add(int depth, std::span<const unsigned char> script, int leaf_version, bool track)
385
0
{
386
0
    assert((leaf_version & ~TAPROOT_LEAF_MASK) == 0);
387
0
    if (!IsValid()) return *this;
388
    /* Construct NodeInfo object with leaf hash and (if track is true) also leaf information. */
389
0
    NodeInfo node;
390
0
    node.hash = ComputeTapleafHash(leaf_version, script);
391
0
    if (track) node.leaves.emplace_back(LeafInfo{std::vector<unsigned char>(script.begin(), script.end()), leaf_version, {}});
392
    /* Insert into the branch. */
393
0
    Insert(std::move(node), depth);
394
0
    return *this;
395
0
}
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
0
{
409
    /* Can only call this function when IsComplete() is true. */
410
0
    assert(IsComplete());
411
0
    m_internal_key = internal_key;
412
0
    auto ret = m_internal_key.CreateTapTweak(m_branch.size() == 0 ? nullptr : &m_branch[0]->hash);
413
0
    assert(ret.has_value());
414
0
    std::tie(m_output_key, m_parity) = *ret;
415
0
    return *this;
416
0
}
417
418
0
WitnessV1Taproot TaprootBuilder::GetOutput() { return WitnessV1Taproot{m_output_key}; }
419
420
TaprootSpendData TaprootBuilder::GetSpendData() const
421
0
{
422
0
    assert(IsComplete());
423
0
    assert(m_output_key.IsFullyValid());
424
0
    TaprootSpendData spd;
425
0
    spd.merkle_root = m_branch.size() == 0 ? uint256() : m_branch[0]->hash;
426
0
    spd.internal_key = m_internal_key;
427
0
    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
0
        for (const auto& leaf : m_branch[0]->leaves) {
432
0
            std::vector<unsigned char> control_block;
433
0
            control_block.resize(TAPROOT_CONTROL_BASE_SIZE + TAPROOT_CONTROL_NODE_SIZE * leaf.merkle_branch.size());
434
0
            control_block[0] = leaf.leaf_version | (m_parity ? 1 : 0);
435
0
            std::copy(m_internal_key.begin(), m_internal_key.end(), control_block.begin() + 1);
436
0
            if (leaf.merkle_branch.size()) {
437
0
                std::copy(leaf.merkle_branch[0].begin(),
438
0
                          leaf.merkle_branch[0].begin() + TAPROOT_CONTROL_NODE_SIZE * leaf.merkle_branch.size(),
439
0
                          control_block.begin() + TAPROOT_CONTROL_BASE_SIZE);
440
0
            }
441
0
            spd.scripts[{leaf.script, leaf.leaf_version}].insert(std::move(control_block));
442
0
        }
443
0
    }
444
0
    return spd;
445
0
}
446
447
std::optional<std::vector<std::tuple<int, std::vector<unsigned char>, int>>> InferTaprootTree(const TaprootSpendData& spenddata, const XOnlyPubKey& output)
448
0
{
449
    // Verify that the output matches the assumed Merkle root and internal key.
450
0
    auto tweak = spenddata.internal_key.CreateTapTweak(spenddata.merkle_root.IsNull() ? nullptr : &spenddata.merkle_root);
451
0
    if (!tweak || tweak->first != output) return std::nullopt;
452
    // If the Merkle root is 0, the tree is empty, and we're done.
453
0
    std::vector<std::tuple<int, std::vector<unsigned char>, int>> ret;
454
0
    if (spenddata.merkle_root.IsNull()) return ret;
455
456
    /** Data structure to represent the nodes of the tree we're going to build. */
457
0
    struct TreeNode {
458
        /** Hash of this node, if known; 0 otherwise. */
459
0
        uint256 hash;
460
        /** The left and right subtrees (note that their order is irrelevant). */
461
0
        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
0
        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
0
        bool explored = false;
467
        /** Whether or not this node is an inner node (unknown until explored = true). */
468
0
        bool inner;
469
        /** Whether or not we have produced output for this subtree. */
470
0
        bool done = false;
471
0
    };
472
473
    // Build tree from the provided branches.
474
0
    TreeNode root;
475
0
    root.hash = spenddata.merkle_root;
476
0
    for (const auto& [key, control_blocks] : spenddata.scripts) {
477
0
        const auto& [script, leaf_ver] = key;
478
0
        for (const auto& control : control_blocks) {
479
            // Skip script records with nonsensical leaf version.
480
0
            if (leaf_ver < 0 || leaf_ver >= 0x100 || leaf_ver & 1) continue;
481
            // Skip script records with invalid control block sizes.
482
0
            if (control.size() < TAPROOT_CONTROL_BASE_SIZE || control.size() > TAPROOT_CONTROL_MAX_SIZE ||
483
0
                ((control.size() - TAPROOT_CONTROL_BASE_SIZE) % TAPROOT_CONTROL_NODE_SIZE) != 0) continue;
484
            // Skip script records that don't match the control block.
485
0
            if ((control[0] & TAPROOT_LEAF_MASK) != leaf_ver) continue;
486
            // Skip script records that don't match the provided Merkle root.
487
0
            const uint256 leaf_hash = ComputeTapleafHash(leaf_ver, script);
488
0
            const uint256 merkle_root = ComputeTaprootMerkleRoot(control, leaf_hash);
489
0
            if (merkle_root != spenddata.merkle_root) continue;
490
491
0
            TreeNode* node = &root;
492
0
            size_t levels = (control.size() - TAPROOT_CONTROL_BASE_SIZE) / TAPROOT_CONTROL_NODE_SIZE;
493
0
            for (size_t depth = 0; depth < levels; ++depth) {
494
                // Can't descend into a node which we already know is a leaf.
495
0
                if (node->explored && !node->inner) return std::nullopt;
496
497
                // Extract partner hash from Merkle branch in control block.
498
0
                uint256 hash;
499
0
                std::copy(control.begin() + TAPROOT_CONTROL_BASE_SIZE + (levels - 1 - depth) * TAPROOT_CONTROL_NODE_SIZE,
500
0
                          control.begin() + TAPROOT_CONTROL_BASE_SIZE + (levels - depth) * TAPROOT_CONTROL_NODE_SIZE,
501
0
                          hash.begin());
502
503
0
                if (node->sub[0]) {
504
                    // Descend into the existing left or right branch.
505
0
                    bool desc = false;
506
0
                    for (int i = 0; i < 2; ++i) {
507
0
                        if (node->sub[i]->hash == hash || (node->sub[i]->hash.IsNull() && node->sub[1-i]->hash != hash)) {
508
0
                            node->sub[i]->hash = hash;
509
0
                            node = &*node->sub[1-i];
510
0
                            desc = true;
511
0
                            break;
512
0
                        }
513
0
                    }
514
0
                    if (!desc) return std::nullopt; // This probably requires a hash collision to hit.
515
0
                } else {
516
                    // We're in an unexplored node. Create subtrees and descend.
517
0
                    node->explored = true;
518
0
                    node->inner = true;
519
0
                    node->sub[0] = std::make_unique<TreeNode>();
520
0
                    node->sub[1] = std::make_unique<TreeNode>();
521
0
                    node->sub[1]->hash = hash;
522
0
                    node = &*node->sub[0];
523
0
                }
524
0
            }
525
            // Cannot turn a known inner node into a leaf.
526
0
            if (node->sub[0]) return std::nullopt;
527
0
            node->explored = true;
528
0
            node->inner = false;
529
0
            node->leaf = &key;
530
0
            node->hash = leaf_hash;
531
0
        }
532
0
    }
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
0
    std::vector<TreeNode*> stack{&root};
537
0
    while (!stack.empty()) {
538
0
        TreeNode& node = *stack.back();
539
0
        if (!node.explored) {
540
            // Unexplored node, which means the tree is incomplete.
541
0
            return std::nullopt;
542
0
        } else if (!node.inner) {
543
            // Leaf node; produce output.
544
0
            ret.emplace_back(stack.size() - 1, node.leaf->first, node.leaf->second);
545
0
            node.done = true;
546
0
            stack.pop_back();
547
0
        } else if (node.sub[0]->done && !node.sub[1]->done && !node.sub[1]->explored && !node.sub[1]->hash.IsNull() &&
548
0
                   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
0
            node.sub[0]->done = false;
563
0
            node.sub[1]->done = true;
564
0
        } else if (node.sub[0]->done && node.sub[1]->done) {
565
            // An internal node which we're finished with.
566
0
            node.sub[0]->done = false;
567
0
            node.sub[1]->done = false;
568
0
            node.done = true;
569
0
            stack.pop_back();
570
0
        } else if (!node.sub[0]->done) {
571
            // An internal node whose left branch hasn't been processed yet. Do so first.
572
0
            stack.push_back(&*node.sub[0]);
573
0
        } else if (!node.sub[1]->done) {
574
            // An internal node whose right branch hasn't been processed yet. Do so first.
575
0
            stack.push_back(&*node.sub[1]);
576
0
        }
577
0
    }
578
579
0
    return ret;
580
0
}
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
}