Branch data Line data Source code
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 : 21607 : bool LookupHelper(const M& map, const K& key, V& value)
16 : : {
17 [ + + ]: 21607 : auto it = map.find(key);
18 [ + + ]: 21607 : if (it != map.end()) {
19 : 20393 : value = it->second;
20 : 20393 : return true;
21 : : }
22 : : return false;
23 : : }
24 : :
25 : 8 : bool HidingSigningProvider::GetCScript(const CScriptID& scriptid, CScript& script) const
26 : : {
27 : 8 : return m_provider->GetCScript(scriptid, script);
28 : : }
29 : :
30 : 2 : bool HidingSigningProvider::GetPubKey(const CKeyID& keyid, CPubKey& pubkey) const
31 : : {
32 : 2 : return m_provider->GetPubKey(keyid, pubkey);
33 : : }
34 : :
35 : 12 : bool HidingSigningProvider::GetKey(const CKeyID& keyid, CKey& key) const
36 : : {
37 [ - + ]: 12 : if (m_hide_secret) return false;
38 : 0 : return m_provider->GetKey(keyid, key);
39 : : }
40 : :
41 : 12 : bool HidingSigningProvider::GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const
42 : : {
43 [ + - ]: 12 : if (m_hide_origin) return false;
44 : 12 : return m_provider->GetKeyOrigin(keyid, info);
45 : : }
46 : :
47 : 0 : bool HidingSigningProvider::GetTaprootSpendData(const XOnlyPubKey& output_key, TaprootSpendData& spenddata) const
48 : : {
49 : 0 : return m_provider->GetTaprootSpendData(output_key, spenddata);
50 : : }
51 : 0 : bool HidingSigningProvider::GetTaprootBuilder(const XOnlyPubKey& output_key, TaprootBuilder& builder) const
52 : : {
53 : 0 : return m_provider->GetTaprootBuilder(output_key, builder);
54 : : }
55 : 0 : std::vector<CPubKey> HidingSigningProvider::GetMuSig2ParticipantPubkeys(const CPubKey& pubkey) const
56 : : {
57 [ # # ]: 0 : if (m_hide_origin) return {};
58 : 0 : return m_provider->GetMuSig2ParticipantPubkeys(pubkey);
59 : : }
60 : :
61 : 854 : bool FlatSigningProvider::GetCScript(const CScriptID& scriptid, CScript& script) const { return LookupHelper(scripts, scriptid, script); }
62 : 6375 : bool FlatSigningProvider::GetPubKey(const CKeyID& keyid, CPubKey& pubkey) const { return LookupHelper(pubkeys, keyid, pubkey); }
63 : 9964 : bool FlatSigningProvider::GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const
64 : : {
65 [ + - ]: 9964 : std::pair<CPubKey, KeyOriginInfo> out;
66 [ + - ]: 9964 : bool ret = LookupHelper(origins, keyid, out);
67 [ + + ]: 9964 : if (ret) info = std::move(out.second);
68 : 9964 : return ret;
69 : 9964 : }
70 : 6 : bool FlatSigningProvider::HaveKey(const CKeyID &keyid) const
71 : : {
72 : 6 : CKey key;
73 [ + - ]: 6 : return LookupHelper(keys, keyid, key);
74 : 6 : }
75 : 3809 : bool FlatSigningProvider::GetKey(const CKeyID& keyid, CKey& key) const { return LookupHelper(keys, keyid, key); }
76 : 545 : bool FlatSigningProvider::GetTaprootSpendData(const XOnlyPubKey& output_key, TaprootSpendData& spenddata) const
77 : : {
78 [ + - ]: 545 : TaprootBuilder builder;
79 [ + - + + ]: 545 : if (LookupHelper(tr_trees, output_key, builder)) {
80 [ + - ]: 383 : spenddata = builder.GetSpendData();
81 : 383 : return true;
82 : : }
83 : : return false;
84 : 545 : }
85 : 54 : bool FlatSigningProvider::GetTaprootBuilder(const XOnlyPubKey& output_key, TaprootBuilder& builder) const
86 : : {
87 : 54 : return LookupHelper(tr_trees, output_key, builder);
88 : : }
89 : :
90 : 0 : std::vector<CPubKey> FlatSigningProvider::GetMuSig2ParticipantPubkeys(const CPubKey& pubkey) const
91 : : {
92 : 0 : std::vector<CPubKey> participant_pubkeys;
93 [ # # ]: 0 : LookupHelper(aggregate_pubkeys, pubkey, participant_pubkeys);
94 : 0 : return participant_pubkeys;
95 : 0 : }
96 : :
97 : 365571 : FlatSigningProvider& FlatSigningProvider::Merge(FlatSigningProvider&& b)
98 : : {
99 : 365571 : scripts.merge(b.scripts);
100 : 365571 : pubkeys.merge(b.pubkeys);
101 : 365571 : keys.merge(b.keys);
102 : 365571 : origins.merge(b.origins);
103 : 365571 : tr_trees.merge(b.tr_trees);
104 : 365571 : aggregate_pubkeys.merge(b.aggregate_pubkeys);
105 : 365571 : return *this;
106 : : }
107 : :
108 : 171 : void FillableSigningProvider::ImplicitlyLearnRelatedKeyScripts(const CPubKey& pubkey)
109 : : {
110 : 171 : AssertLockHeld(cs_KeyStore);
111 : 171 : 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 [ + + ]: 171 : if (pubkey.IsCompressed()) {
124 [ + - ]: 163 : CScript script = GetScriptForDestination(WitnessV0KeyHash(key_id));
125 : : // This does not use AddCScript, as it may be overridden.
126 [ + - ]: 163 : CScriptID id(script);
127 [ + - ]: 163 : mapScripts[id] = std::move(script);
128 : 163 : }
129 : 171 : }
130 : :
131 : 4639 : bool FillableSigningProvider::GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const
132 : : {
133 : 4639 : CKey key;
134 [ + - + - ]: 4639 : if (!GetKey(address, key)) {
135 : : return false;
136 : : }
137 [ + - ]: 4639 : vchPubKeyOut = key.GetPubKey();
138 : : return true;
139 : 4639 : }
140 : :
141 : 171 : bool FillableSigningProvider::AddKeyPubKey(const CKey& key, const CPubKey &pubkey)
142 : : {
143 : 171 : LOCK(cs_KeyStore);
144 [ + - + - : 171 : mapKeys[pubkey.GetID()] = key;
+ - ]
145 [ + - ]: 171 : ImplicitlyLearnRelatedKeyScripts(pubkey);
146 [ + - ]: 171 : return true;
147 : 171 : }
148 : :
149 : 0 : bool FillableSigningProvider::HaveKey(const CKeyID &address) const
150 : : {
151 : 0 : LOCK(cs_KeyStore);
152 [ # # ]: 0 : return mapKeys.count(address) > 0;
153 : 0 : }
154 : :
155 : 0 : std::set<CKeyID> FillableSigningProvider::GetKeys() const
156 : : {
157 : 0 : LOCK(cs_KeyStore);
158 : 0 : std::set<CKeyID> set_address;
159 [ # # ]: 0 : for (const auto& mi : mapKeys) {
160 [ # # ]: 0 : set_address.insert(mi.first);
161 : : }
162 [ # # ]: 0 : return set_address;
163 : 0 : }
164 : :
165 : 9430 : bool FillableSigningProvider::GetKey(const CKeyID &address, CKey &keyOut) const
166 : : {
167 : 9430 : LOCK(cs_KeyStore);
168 : 9430 : KeyMap::const_iterator mi = mapKeys.find(address);
169 [ + + ]: 9430 : if (mi != mapKeys.end()) {
170 [ + - ]: 9418 : keyOut = mi->second;
171 : : return true;
172 : : }
173 : : return false;
174 : 9430 : }
175 : :
176 : 30 : bool FillableSigningProvider::AddCScript(const CScript& redeemScript)
177 : : {
178 [ + + - + ]: 30 : 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 : : }
182 : :
183 : 30 : LOCK(cs_KeyStore);
184 [ + - + - ]: 30 : mapScripts[CScriptID(redeemScript)] = redeemScript;
185 [ + - ]: 30 : return true;
186 : 30 : }
187 : :
188 : 0 : bool FillableSigningProvider::HaveCScript(const CScriptID& hash) const
189 : : {
190 : 0 : LOCK(cs_KeyStore);
191 [ # # ]: 0 : return mapScripts.count(hash) > 0;
192 : 0 : }
193 : :
194 : 0 : std::set<CScriptID> FillableSigningProvider::GetCScripts() const
195 : : {
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 : : }
201 [ # # ]: 0 : return set_script;
202 : 0 : }
203 : :
204 : 30 : bool FillableSigningProvider::GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const
205 : : {
206 : 30 : LOCK(cs_KeyStore);
207 : 30 : ScriptMap::const_iterator mi = mapScripts.find(hash);
208 [ + - ]: 30 : if (mi != mapScripts.end())
209 : : {
210 : 30 : redeemScriptOut = (*mi).second;
211 : 30 : return true;
212 : : }
213 : : return false;
214 : 30 : }
215 : :
216 : 0 : CKeyID GetKeyForDestination(const SigningProvider& store, const CTxDestination& dest)
217 : : {
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 : : }
223 [ # # ]: 0 : if (auto witness_id = std::get_if<WitnessV0KeyHash>(&dest)) {
224 : 0 : return ToKeyID(*witness_id);
225 : : }
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 : : }
234 : : }
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 : : }
245 : 0 : }
246 : 0 : return CKeyID();
247 : : }
248 : :
249 : 52 : void MultiSigningProvider::AddProvider(std::unique_ptr<SigningProvider> provider)
250 : : {
251 : 52 : m_providers.push_back(std::move(provider));
252 : 52 : }
253 : :
254 : 0 : bool MultiSigningProvider::GetCScript(const CScriptID& scriptid, CScript& script) const
255 : : {
256 [ # # ]: 0 : for (const auto& provider: m_providers) {
257 [ # # ]: 0 : if (provider->GetCScript(scriptid, script)) return true;
258 : : }
259 : : return false;
260 : : }
261 : :
262 : 0 : bool MultiSigningProvider::GetPubKey(const CKeyID& keyid, CPubKey& pubkey) const
263 : : {
264 [ # # ]: 0 : for (const auto& provider: m_providers) {
265 [ # # ]: 0 : if (provider->GetPubKey(keyid, pubkey)) return true;
266 : : }
267 : : return false;
268 : : }
269 : :
270 : :
271 : 26 : bool MultiSigningProvider::GetKeyOrigin(const CKeyID& keyid, KeyOriginInfo& info) const
272 : : {
273 [ + - ]: 26 : for (const auto& provider: m_providers) {
274 [ - + ]: 26 : if (provider->GetKeyOrigin(keyid, info)) return true;
275 : : }
276 : : return false;
277 : : }
278 : :
279 : 0 : bool MultiSigningProvider::GetKey(const CKeyID& keyid, CKey& key) const
280 : : {
281 [ # # ]: 0 : for (const auto& provider: m_providers) {
282 [ # # ]: 0 : if (provider->GetKey(keyid, key)) return true;
283 : : }
284 : : return false;
285 : : }
286 : :
287 : 0 : bool MultiSigningProvider::GetTaprootSpendData(const XOnlyPubKey& output_key, TaprootSpendData& spenddata) const
288 : : {
289 [ # # ]: 0 : for (const auto& provider: m_providers) {
290 [ # # ]: 0 : if (provider->GetTaprootSpendData(output_key, spenddata)) return true;
291 : : }
292 : : return false;
293 : : }
294 : :
295 : 0 : bool MultiSigningProvider::GetTaprootBuilder(const XOnlyPubKey& output_key, TaprootBuilder& builder) const
296 : : {
297 [ # # ]: 0 : for (const auto& provider: m_providers) {
298 [ # # ]: 0 : if (provider->GetTaprootBuilder(output_key, builder)) return true;
299 : : }
300 : : return false;
301 : : }
302 : :
303 : 380 : /*static*/ TaprootBuilder::NodeInfo TaprootBuilder::Combine(NodeInfo&& a, NodeInfo&& b)
304 : : {
305 : 380 : NodeInfo ret;
306 : : /* Iterate over all tracked leaves in a, add b's hash to their Merkle branch, and move them to ret. */
307 [ + + ]: 791 : for (auto& leaf : a.leaves) {
308 [ + - ]: 411 : leaf.merkle_branch.push_back(b.hash);
309 [ + - ]: 411 : ret.leaves.emplace_back(std::move(leaf));
310 : : }
311 : : /* Iterate over all tracked leaves in b, add a's hash to their Merkle branch, and move them to ret. */
312 [ + + ]: 790 : for (auto& leaf : b.leaves) {
313 [ + - ]: 410 : leaf.merkle_branch.push_back(a.hash);
314 [ + - ]: 410 : ret.leaves.emplace_back(std::move(leaf));
315 : : }
316 [ + - ]: 380 : ret.hash = ComputeTapbranchHash(a.hash, b.hash);
317 : 380 : return ret;
318 : 0 : }
319 : :
320 : 48 : void TaprootSpendData::Merge(TaprootSpendData other)
321 : : {
322 : : // TODO: figure out how to better deal with conflicting information
323 : : // being merged.
324 [ + - + - ]: 144 : if (internal_key.IsNull() && !other.internal_key.IsNull()) {
325 : 48 : internal_key = other.internal_key;
326 : : }
327 [ + - + + ]: 144 : if (merkle_root.IsNull() && !other.merkle_root.IsNull()) {
328 : 42 : merkle_root = other.merkle_root;
329 : : }
330 [ + + ]: 108 : for (auto& [key, control_blocks] : other.scripts) {
331 : 60 : scripts[key].merge(std::move(control_blocks));
332 : : }
333 : 48 : }
334 : :
335 : 2943 : void TaprootBuilder::Insert(TaprootBuilder::NodeInfo&& node, int depth)
336 : : {
337 [ - + ]: 2943 : 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 [ - + - + ]: 2943 : if ((size_t)depth + 1 < m_branch.size()) {
342 : 0 : m_valid = false;
343 : 0 : return;
344 : : }
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 [ + - - + : 3323 : while (m_valid && m_branch.size() > (size_t)depth && m_branch[depth].has_value()) {
+ + + + ]
348 : 380 : node = Combine(std::move(node), std::move(*m_branch[depth]));
349 : 380 : m_branch.pop_back();
350 [ - + ]: 380 : if (depth == 0) m_valid = false; /* Can't propagate further up than the root */
351 : 380 : --depth;
352 : : }
353 [ + - ]: 2943 : if (m_valid) {
354 : : /* Make sure the branch is big enough to place the new node. */
355 [ - + + + ]: 2943 : if (m_branch.size() <= (size_t)depth) m_branch.resize((size_t)depth + 1);
356 [ - + ]: 2943 : assert(!m_branch[depth].has_value());
357 : 2943 : m_branch[depth] = std::move(node);
358 : : }
359 : : }
360 : :
361 : 181 : /*static*/ bool TaprootBuilder::ValidDepths(const std::vector<int>& depths)
362 : : {
363 : 181 : std::vector<bool> branch;
364 [ + + ]: 608 : 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 [ + + ]: 452 : if (depth < 0 || (size_t)depth > TAPROOT_CONTROL_MAX_NODE_COUNT) return false;
370 [ + + ]: 451 : if ((size_t)depth + 1 < branch.size()) return false;
371 [ + + + + ]: 742 : while (branch.size() > (size_t)depth && branch[depth]) {
372 [ - + ]: 315 : branch.pop_back();
373 [ + + ]: 315 : if (depth == 0) return false;
374 : 309 : --depth;
375 : : }
376 [ + + + - ]: 427 : if (branch.size() <= (size_t)depth) branch.resize((size_t)depth + 1);
377 [ - + ]: 427 : assert(!branch[depth]);
378 : 427 : branch[depth] = true;
379 : : }
380 : : // And this check corresponds to the IsComplete() check on m_branch.
381 [ + + + + : 156 : return branch.size() == 0 || (branch.size() == 1 && branch[0]);
+ - ]
382 : 181 : }
383 : :
384 : 2942 : TaprootBuilder& TaprootBuilder::Add(int depth, std::span<const unsigned char> script, int leaf_version, bool track)
385 : : {
386 [ - + ]: 2942 : assert((leaf_version & ~TAPROOT_LEAF_MASK) == 0);
387 [ + - ]: 2942 : if (!IsValid()) return *this;
388 : : /* Construct NodeInfo object with leaf hash and (if track is true) also leaf information. */
389 : 2942 : NodeInfo node;
390 [ + - ]: 2942 : node.hash = ComputeTapleafHash(leaf_version, script);
391 [ + - + - : 5884 : if (track) node.leaves.emplace_back(LeafInfo{std::vector<unsigned char>(script.begin(), script.end()), leaf_version, {}});
+ - ]
392 : : /* Insert into the branch. */
393 [ + - ]: 2942 : Insert(std::move(node), depth);
394 : 2942 : return *this;
395 : 2942 : }
396 : :
397 : 1 : TaprootBuilder& TaprootBuilder::AddOmitted(int depth, const uint256& hash)
398 : : {
399 [ + - ]: 1 : if (!IsValid()) return *this;
400 : : /* Construct NodeInfo object with the hash directly, and insert it into the branch. */
401 : 1 : NodeInfo node;
402 : 1 : node.hash = hash;
403 [ + - ]: 1 : Insert(std::move(node), depth);
404 : 1 : return *this;
405 : 1 : }
406 : :
407 : 70663 : TaprootBuilder& TaprootBuilder::Finalize(const XOnlyPubKey& internal_key)
408 : : {
409 : : /* Can only call this function when IsComplete() is true. */
410 [ - + ]: 70663 : assert(IsComplete());
411 : 70663 : m_internal_key = internal_key;
412 [ - + + + ]: 70663 : auto ret = m_internal_key.CreateTapTweak(m_branch.size() == 0 ? nullptr : &m_branch[0]->hash);
413 [ - + ]: 70663 : assert(ret.has_value());
414 : 70663 : std::tie(m_output_key, m_parity) = *ret;
415 : 70663 : return *this;
416 : : }
417 : :
418 : 70670 : WitnessV1Taproot TaprootBuilder::GetOutput() { return WitnessV1Taproot{m_output_key}; }
419 : :
420 : 4019 : TaprootSpendData TaprootBuilder::GetSpendData() const
421 : : {
422 [ - + ]: 4019 : assert(IsComplete());
423 [ - + ]: 4019 : assert(m_output_key.IsFullyValid());
424 [ - + ]: 4019 : TaprootSpendData spd;
425 [ - + + + ]: 4019 : spd.merkle_root = m_branch.size() == 0 ? uint256() : m_branch[0]->hash;
426 : 4019 : spd.internal_key = m_internal_key;
427 [ - + + + ]: 4019 : 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 [ + + ]: 8116 : for (const auto& leaf : m_branch[0]->leaves) {
432 : 4147 : std::vector<unsigned char> control_block;
433 [ - + + - ]: 4147 : control_block.resize(TAPROOT_CONTROL_BASE_SIZE + TAPROOT_CONTROL_NODE_SIZE * leaf.merkle_branch.size());
434 [ + + ]: 6873 : control_block[0] = leaf.leaf_version | (m_parity ? 1 : 0);
435 : 4147 : std::copy(m_internal_key.begin(), m_internal_key.end(), control_block.begin() + 1);
436 [ - + + + ]: 4147 : if (leaf.merkle_branch.size()) {
437 : 324 : std::copy(leaf.merkle_branch[0].begin(),
438 : 324 : leaf.merkle_branch[0].begin() + TAPROOT_CONTROL_NODE_SIZE * leaf.merkle_branch.size(),
439 : 324 : control_block.begin() + TAPROOT_CONTROL_BASE_SIZE);
440 : : }
441 [ + - + - : 8294 : spd.scripts[{leaf.script, leaf.leaf_version}].insert(std::move(control_block));
+ - ]
442 : 4147 : }
443 : : }
444 : 4019 : return spd;
445 : 0 : }
446 : :
447 : 335 : std::optional<std::vector<std::tuple<int, std::vector<unsigned char>, int>>> InferTaprootTree(const TaprootSpendData& spenddata, const XOnlyPubKey& output)
448 : : {
449 : : // Verify that the output matches the assumed Merkle root and internal key.
450 [ + + ]: 670 : auto tweak = spenddata.internal_key.CreateTapTweak(spenddata.merkle_root.IsNull() ? nullptr : &spenddata.merkle_root);
451 [ + - - + ]: 335 : if (!tweak || tweak->first != output) return std::nullopt;
452 : : // If the Merkle root is 0, the tree is empty, and we're done.
453 : 335 : std::vector<std::tuple<int, std::vector<unsigned char>, int>> ret;
454 [ + + ]: 670 : if (spenddata.merkle_root.IsNull()) return ret;
455 : :
456 : : /** Data structure to represent the nodes of the tree we're going to build. */
457 [ + + - - ]: 876 : struct TreeNode {
458 : : /** Hash of this node, if known; 0 otherwise. */
459 : : uint256 hash;
460 : : /** The left and right subtrees (note that their order is irrelevant). */
461 : : 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 : : 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 : : bool explored = false;
467 : : /** Whether or not this node is an inner node (unknown until explored = true). */
468 : : bool inner;
469 : : /** Whether or not we have produced output for this subtree. */
470 : : bool done = false;
471 : : };
472 : :
473 : : // Build tree from the provided branches.
474 : 292 : TreeNode root;
475 : 292 : root.hash = spenddata.merkle_root;
476 [ + + ]: 720 : for (const auto& [key, control_blocks] : spenddata.scripts) {
477 : 428 : const auto& [script, leaf_ver] = key;
478 [ + + ]: 868 : for (const auto& control : control_blocks) {
479 : : // Skip script records with nonsensical leaf version.
480 [ + - - + ]: 440 : if (leaf_ver < 0 || leaf_ver >= 0x100 || leaf_ver & 1) continue;
481 : : // Skip script records with invalid control block sizes.
482 [ - + + - : 440 : if (control.size() < TAPROOT_CONTROL_BASE_SIZE || control.size() > TAPROOT_CONTROL_MAX_SIZE ||
+ - ]
483 [ + - ]: 440 : ((control.size() - TAPROOT_CONTROL_BASE_SIZE) % TAPROOT_CONTROL_NODE_SIZE) != 0) continue;
484 : : // Skip script records that don't match the control block.
485 [ - + ]: 440 : if ((control[0] & TAPROOT_LEAF_MASK) != leaf_ver) continue;
486 : : // Skip script records that don't match the provided Merkle root.
487 [ - + + - ]: 440 : const uint256 leaf_hash = ComputeTapleafHash(leaf_ver, script);
488 [ - + + - ]: 440 : const uint256 merkle_root = ComputeTaprootMerkleRoot(control, leaf_hash);
489 [ - + ]: 440 : if (merkle_root != spenddata.merkle_root) continue;
490 : :
491 : 440 : TreeNode* node = &root;
492 [ - + ]: 440 : size_t levels = (control.size() - TAPROOT_CONTROL_BASE_SIZE) / TAPROOT_CONTROL_NODE_SIZE;
493 [ + + ]: 760 : for (size_t depth = 0; depth < levels; ++depth) {
494 : : // Can't descend into a node which we already know is a leaf.
495 [ + + - + ]: 320 : if (node->explored && !node->inner) return std::nullopt;
496 : :
497 : : // Extract partner hash from Merkle branch in control block.
498 : 320 : uint256 hash;
499 : 320 : std::copy(control.begin() + TAPROOT_CONTROL_BASE_SIZE + (levels - 1 - depth) * TAPROOT_CONTROL_NODE_SIZE,
500 : 320 : control.begin() + TAPROOT_CONTROL_BASE_SIZE + (levels - depth) * TAPROOT_CONTROL_NODE_SIZE,
501 : : hash.begin());
502 : :
503 [ + + ]: 320 : if (node->sub[0]) {
504 : : // Descend into the existing left or right branch.
505 : 184 : bool desc = false;
506 [ + - ]: 184 : for (int i = 0; i < 2; ++i) {
507 [ + + + + : 208 : if (node->sub[i]->hash == hash || (node->sub[i]->hash.IsNull() && node->sub[1-i]->hash != hash)) {
+ - ]
508 : 172 : node->sub[i]->hash = hash;
509 : 172 : node = &*node->sub[1-i];
510 : 172 : desc = true;
511 : 172 : break;
512 : : }
513 : : }
514 : 172 : if (!desc) return std::nullopt; // This probably requires a hash collision to hit.
515 : : } else {
516 : : // We're in an unexplored node. Create subtrees and descend.
517 : 148 : node->explored = true;
518 : 148 : node->inner = true;
519 [ + - ]: 148 : node->sub[0] = std::make_unique<TreeNode>();
520 [ + - ]: 148 : node->sub[1] = std::make_unique<TreeNode>();
521 : 148 : node->sub[1]->hash = hash;
522 : 148 : node = &*node->sub[0];
523 : : }
524 : : }
525 : : // Cannot turn a known inner node into a leaf.
526 [ - + ]: 440 : if (node->sub[0]) return std::nullopt;
527 : 440 : node->explored = true;
528 : 440 : node->inner = false;
529 : 440 : node->leaf = &key;
530 : 440 : node->hash = leaf_hash;
531 : : }
532 : : }
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 [ + - ]: 292 : std::vector<TreeNode*> stack{&root};
537 : 1176 : while (!stack.empty()) {
538 : 884 : TreeNode& node = *stack.back();
539 [ - + ]: 884 : if (!node.explored) {
540 : : // Unexplored node, which means the tree is incomplete.
541 : 0 : return std::nullopt;
542 [ + + ]: 884 : } else if (!node.inner) {
543 : : // Leaf node; produce output.
544 [ - + + - ]: 440 : ret.emplace_back(stack.size() - 1, node.leaf->first, node.leaf->second);
545 : 440 : node.done = true;
546 : 440 : stack.pop_back();
547 [ + + + + : 444 : } 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 [ + + + + ]: 444 : } else if (node.sub[0]->done && node.sub[1]->done) {
565 : : // An internal node which we're finished with.
566 : 148 : node.sub[0]->done = false;
567 : 148 : node.sub[1]->done = false;
568 : 148 : node.done = true;
569 : 148 : stack.pop_back();
570 [ + + ]: 296 : } else if (!node.sub[0]->done) {
571 : : // An internal node whose left branch hasn't been processed yet. Do so first.
572 [ + - ]: 148 : stack.push_back(&*node.sub[0]);
573 [ + - ]: 148 : } else if (!node.sub[1]->done) {
574 : : // An internal node whose right branch hasn't been processed yet. Do so first.
575 [ + - + + ]: 1324 : stack.push_back(&*node.sub[1]);
576 : : }
577 : : }
578 : :
579 : 292 : return ret;
580 : 627 : }
581 : :
582 : 0 : std::vector<std::tuple<uint8_t, uint8_t, std::vector<unsigned char>>> TaprootBuilder::GetTreeTuples() const
583 : : {
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 : : }
594 : : }
595 : 0 : return tuples;
596 : 0 : }
|