|
4 | 4 | // file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
5 | 5 |
|
6 | 6 | #include <script/keyorigin.h>
|
| 7 | +#include <script/interpreter.h> |
7 | 8 | #include <script/signingprovider.h>
|
8 | 9 | #include <script/standard.h>
|
9 | 10 |
|
@@ -225,3 +226,297 @@ CKeyID GetKeyForDestination(const SigningProvider& store, const CTxDestination&
|
225 | 226 | }
|
226 | 227 | return CKeyID();
|
227 | 228 | }
|
| 229 | +/*static*/ TaprootBuilder::NodeInfo TaprootBuilder::Combine(NodeInfo&& a, NodeInfo&& b) |
| 230 | +{ |
| 231 | + NodeInfo ret; |
| 232 | + /* Iterate over all tracked leaves in a, add b's hash to their Merkle branch, and move them to ret. */ |
| 233 | + for (auto& leaf : a.leaves) { |
| 234 | + leaf.merkle_branch.push_back(b.hash); |
| 235 | + ret.leaves.emplace_back(std::move(leaf)); |
| 236 | + } |
| 237 | + /* Iterate over all tracked leaves in b, add a's hash to their Merkle branch, and move them to ret. */ |
| 238 | + for (auto& leaf : b.leaves) { |
| 239 | + leaf.merkle_branch.push_back(a.hash); |
| 240 | + ret.leaves.emplace_back(std::move(leaf)); |
| 241 | + } |
| 242 | + ret.hash = ComputeTapbranchHash(a.hash, b.hash); |
| 243 | + return ret; |
| 244 | +} |
| 245 | + |
| 246 | +void TaprootSpendData::Merge(TaprootSpendData other) |
| 247 | +{ |
| 248 | + // TODO: figure out how to better deal with conflicting information |
| 249 | + // being merged. |
| 250 | + if (internal_key.IsNull() && !other.internal_key.IsNull()) { |
| 251 | + internal_key = other.internal_key; |
| 252 | + } |
| 253 | + if (merkle_root.IsNull() && !other.merkle_root.IsNull()) { |
| 254 | + merkle_root = other.merkle_root; |
| 255 | + } |
| 256 | + for (auto& [key, control_blocks] : other.scripts) { |
| 257 | + scripts[key].merge(std::move(control_blocks)); |
| 258 | + } |
| 259 | +} |
| 260 | + |
| 261 | +void TaprootBuilder::Insert(TaprootBuilder::NodeInfo&& node, int depth) |
| 262 | +{ |
| 263 | + assert(depth >= 0 && (size_t)depth <= TAPROOT_CONTROL_MAX_NODE_COUNT); |
| 264 | + /* We cannot insert a leaf at a lower depth while a deeper branch is unfinished. Doing |
| 265 | + * so would mean the Add() invocations do not correspond to a DFS traversal of a |
| 266 | + * binary tree. */ |
| 267 | + if ((size_t)depth + 1 < m_branch.size()) { |
| 268 | + m_valid = false; |
| 269 | + return; |
| 270 | + } |
| 271 | + /* As long as an entry in the branch exists at the specified depth, combine it and propagate up. |
| 272 | + * The 'node' variable is overwritten here with the newly combined node. */ |
| 273 | + while (m_valid && m_branch.size() > (size_t)depth && m_branch[depth].has_value()) { |
| 274 | + node = Combine(std::move(node), std::move(*m_branch[depth])); |
| 275 | + m_branch.pop_back(); |
| 276 | + if (depth == 0) m_valid = false; /* Can't propagate further up than the root */ |
| 277 | + --depth; |
| 278 | + } |
| 279 | + if (m_valid) { |
| 280 | + /* Make sure the branch is big enough to place the new node. */ |
| 281 | + if (m_branch.size() <= (size_t)depth) m_branch.resize((size_t)depth + 1); |
| 282 | + assert(!m_branch[depth].has_value()); |
| 283 | + m_branch[depth] = std::move(node); |
| 284 | + } |
| 285 | +} |
| 286 | + |
| 287 | +/*static*/ bool TaprootBuilder::ValidDepths(const std::vector<int>& depths) |
| 288 | +{ |
| 289 | + std::vector<bool> branch; |
| 290 | + for (int depth : depths) { |
| 291 | + // This inner loop corresponds to effectively the same logic on branch |
| 292 | + // as what Insert() performs on the m_branch variable. Instead of |
| 293 | + // storing a NodeInfo object, just remember whether or not there is one |
| 294 | + // at that depth. |
| 295 | + if (depth < 0 || (size_t)depth > TAPROOT_CONTROL_MAX_NODE_COUNT) return false; |
| 296 | + if ((size_t)depth + 1 < branch.size()) return false; |
| 297 | + while (branch.size() > (size_t)depth && branch[depth]) { |
| 298 | + branch.pop_back(); |
| 299 | + if (depth == 0) return false; |
| 300 | + --depth; |
| 301 | + } |
| 302 | + if (branch.size() <= (size_t)depth) branch.resize((size_t)depth + 1); |
| 303 | + assert(!branch[depth]); |
| 304 | + branch[depth] = true; |
| 305 | + } |
| 306 | + // And this check corresponds to the IsComplete() check on m_branch. |
| 307 | + return branch.size() == 0 || (branch.size() == 1 && branch[0]); |
| 308 | +} |
| 309 | + |
| 310 | +TaprootBuilder& TaprootBuilder::Add(int depth, Span<const unsigned char> script, int leaf_version, bool track) |
| 311 | +{ |
| 312 | + assert((leaf_version & ~TAPROOT_LEAF_MASK) == 0); |
| 313 | + if (!IsValid()) return *this; |
| 314 | + /* Construct NodeInfo object with leaf hash and (if track is true) also leaf information. */ |
| 315 | + NodeInfo node; |
| 316 | + node.hash = ComputeTapleafHash(leaf_version, script); |
| 317 | + if (track) node.leaves.emplace_back(LeafInfo{std::vector<unsigned char>(script.begin(), script.end()), leaf_version, {}}); |
| 318 | + /* Insert into the branch. */ |
| 319 | + Insert(std::move(node), depth); |
| 320 | + return *this; |
| 321 | +} |
| 322 | + |
| 323 | +TaprootBuilder& TaprootBuilder::AddOmitted(int depth, const uint256& hash) |
| 324 | +{ |
| 325 | + if (!IsValid()) return *this; |
| 326 | + /* Construct NodeInfo object with the hash directly, and insert it into the branch. */ |
| 327 | + NodeInfo node; |
| 328 | + node.hash = hash; |
| 329 | + Insert(std::move(node), depth); |
| 330 | + return *this; |
| 331 | +} |
| 332 | + |
| 333 | +TaprootBuilder& TaprootBuilder::Finalize(const XOnlyPubKey& internal_key) |
| 334 | +{ |
| 335 | + /* Can only call this function when IsComplete() is true. */ |
| 336 | + assert(IsComplete()); |
| 337 | + m_internal_key = internal_key; |
| 338 | + auto ret = m_internal_key.CreateTapTweak(m_branch.size() == 0 ? nullptr : &m_branch[0]->hash); |
| 339 | + assert(ret.has_value()); |
| 340 | + std::tie(m_output_key, m_parity) = *ret; |
| 341 | + return *this; |
| 342 | +} |
| 343 | + |
| 344 | +WitnessV1Taproot TaprootBuilder::GetOutput() { return WitnessV1Taproot{m_output_key}; } |
| 345 | + |
| 346 | +TaprootSpendData TaprootBuilder::GetSpendData() const |
| 347 | +{ |
| 348 | + assert(IsComplete()); |
| 349 | + assert(m_output_key.IsFullyValid()); |
| 350 | + TaprootSpendData spd; |
| 351 | + spd.merkle_root = m_branch.size() == 0 ? uint256() : m_branch[0]->hash; |
| 352 | + spd.internal_key = m_internal_key; |
| 353 | + if (m_branch.size()) { |
| 354 | + // If any script paths exist, they have been combined into the root m_branch[0] |
| 355 | + // by now. Compute the control block for each of its tracked leaves, and put them in |
| 356 | + // spd.scripts. |
| 357 | + for (const auto& leaf : m_branch[0]->leaves) { |
| 358 | + std::vector<unsigned char> control_block; |
| 359 | + control_block.resize(TAPROOT_CONTROL_BASE_SIZE + TAPROOT_CONTROL_NODE_SIZE * leaf.merkle_branch.size()); |
| 360 | + control_block[0] = leaf.leaf_version | (m_parity ? 1 : 0); |
| 361 | + std::copy(m_internal_key.begin(), m_internal_key.end(), control_block.begin() + 1); |
| 362 | + if (leaf.merkle_branch.size()) { |
| 363 | + std::copy(leaf.merkle_branch[0].begin(), |
| 364 | + leaf.merkle_branch[0].begin() + TAPROOT_CONTROL_NODE_SIZE * leaf.merkle_branch.size(), |
| 365 | + control_block.begin() + TAPROOT_CONTROL_BASE_SIZE); |
| 366 | + } |
| 367 | + spd.scripts[{leaf.script, leaf.leaf_version}].insert(std::move(control_block)); |
| 368 | + } |
| 369 | + } |
| 370 | + return spd; |
| 371 | +} |
| 372 | + |
| 373 | +std::optional<std::vector<std::tuple<int, std::vector<unsigned char>, int>>> InferTaprootTree(const TaprootSpendData& spenddata, const XOnlyPubKey& output) |
| 374 | +{ |
| 375 | + // Verify that the output matches the assumed Merkle root and internal key. |
| 376 | + auto tweak = spenddata.internal_key.CreateTapTweak(spenddata.merkle_root.IsNull() ? nullptr : &spenddata.merkle_root); |
| 377 | + if (!tweak || tweak->first != output) return std::nullopt; |
| 378 | + // If the Merkle root is 0, the tree is empty, and we're done. |
| 379 | + std::vector<std::tuple<int, std::vector<unsigned char>, int>> ret; |
| 380 | + if (spenddata.merkle_root.IsNull()) return ret; |
| 381 | + |
| 382 | + /** Data structure to represent the nodes of the tree we're going to build. */ |
| 383 | + struct TreeNode { |
| 384 | + /** Hash of this node, if known; 0 otherwise. */ |
| 385 | + uint256 hash; |
| 386 | + /** The left and right subtrees (note that their order is irrelevant). */ |
| 387 | + std::unique_ptr<TreeNode> sub[2]; |
| 388 | + /** If this is known to be a leaf node, a pointer to the (script, leaf_ver) pair. |
| 389 | + * nullptr otherwise. */ |
| 390 | + const std::pair<std::vector<unsigned char>, int>* leaf = nullptr; |
| 391 | + /** Whether or not this node has been explored (is known to be a leaf, or known to have children). */ |
| 392 | + bool explored = false; |
| 393 | + /** Whether or not this node is an inner node (unknown until explored = true). */ |
| 394 | + bool inner; |
| 395 | + /** Whether or not we have produced output for this subtree. */ |
| 396 | + bool done = false; |
| 397 | + }; |
| 398 | + |
| 399 | + // Build tree from the provided branches. |
| 400 | + TreeNode root; |
| 401 | + root.hash = spenddata.merkle_root; |
| 402 | + for (const auto& [key, control_blocks] : spenddata.scripts) { |
| 403 | + const auto& [script, leaf_ver] = key; |
| 404 | + for (const auto& control : control_blocks) { |
| 405 | + // Skip script records with nonsensical leaf version. |
| 406 | + if (leaf_ver < 0 || leaf_ver >= 0x100 || leaf_ver & 1) continue; |
| 407 | + // Skip script records with invalid control block sizes. |
| 408 | + if (control.size() < TAPROOT_CONTROL_BASE_SIZE || control.size() > TAPROOT_CONTROL_MAX_SIZE || |
| 409 | + ((control.size() - TAPROOT_CONTROL_BASE_SIZE) % TAPROOT_CONTROL_NODE_SIZE) != 0) continue; |
| 410 | + // Skip script records that don't match the control block. |
| 411 | + if ((control[0] & TAPROOT_LEAF_MASK) != leaf_ver) continue; |
| 412 | + // Skip script records that don't match the provided Merkle root. |
| 413 | + const uint256 leaf_hash = ComputeTapleafHash(leaf_ver, script); |
| 414 | + const uint256 merkle_root = ComputeTaprootMerkleRoot(control, leaf_hash); |
| 415 | + if (merkle_root != spenddata.merkle_root) continue; |
| 416 | + |
| 417 | + TreeNode* node = &root; |
| 418 | + size_t levels = (control.size() - TAPROOT_CONTROL_BASE_SIZE) / TAPROOT_CONTROL_NODE_SIZE; |
| 419 | + for (size_t depth = 0; depth < levels; ++depth) { |
| 420 | + // Can't descend into a node which we already know is a leaf. |
| 421 | + if (node->explored && !node->inner) return std::nullopt; |
| 422 | + |
| 423 | + // Extract partner hash from Merkle branch in control block. |
| 424 | + uint256 hash; |
| 425 | + std::copy(control.begin() + TAPROOT_CONTROL_BASE_SIZE + (levels - 1 - depth) * TAPROOT_CONTROL_NODE_SIZE, |
| 426 | + control.begin() + TAPROOT_CONTROL_BASE_SIZE + (levels - depth) * TAPROOT_CONTROL_NODE_SIZE, |
| 427 | + hash.begin()); |
| 428 | + |
| 429 | + if (node->sub[0]) { |
| 430 | + // Descend into the existing left or right branch. |
| 431 | + bool desc = false; |
| 432 | + for (int i = 0; i < 2; ++i) { |
| 433 | + if (node->sub[i]->hash == hash || (node->sub[i]->hash.IsNull() && node->sub[1-i]->hash != hash)) { |
| 434 | + node->sub[i]->hash = hash; |
| 435 | + node = &*node->sub[1-i]; |
| 436 | + desc = true; |
| 437 | + break; |
| 438 | + } |
| 439 | + } |
| 440 | + if (!desc) return std::nullopt; // This probably requires a hash collision to hit. |
| 441 | + } else { |
| 442 | + // We're in an unexplored node. Create subtrees and descend. |
| 443 | + node->explored = true; |
| 444 | + node->inner = true; |
| 445 | + node->sub[0] = std::make_unique<TreeNode>(); |
| 446 | + node->sub[1] = std::make_unique<TreeNode>(); |
| 447 | + node->sub[1]->hash = hash; |
| 448 | + node = &*node->sub[0]; |
| 449 | + } |
| 450 | + } |
| 451 | + // Cannot turn a known inner node into a leaf. |
| 452 | + if (node->sub[0]) return std::nullopt; |
| 453 | + node->explored = true; |
| 454 | + node->inner = false; |
| 455 | + node->leaf = &key; |
| 456 | + node->hash = leaf_hash; |
| 457 | + } |
| 458 | + } |
| 459 | + |
| 460 | + // Recursive processing to turn the tree into flattened output. Use an explicit stack here to avoid |
| 461 | + // overflowing the call stack (the tree may be 128 levels deep). |
| 462 | + std::vector<TreeNode*> stack{&root}; |
| 463 | + while (!stack.empty()) { |
| 464 | + TreeNode& node = *stack.back(); |
| 465 | + if (!node.explored) { |
| 466 | + // Unexplored node, which means the tree is incomplete. |
| 467 | + return std::nullopt; |
| 468 | + } else if (!node.inner) { |
| 469 | + // Leaf node; produce output. |
| 470 | + ret.emplace_back(stack.size() - 1, node.leaf->first, node.leaf->second); |
| 471 | + node.done = true; |
| 472 | + stack.pop_back(); |
| 473 | + } else if (node.sub[0]->done && !node.sub[1]->done && !node.sub[1]->explored && !node.sub[1]->hash.IsNull() && |
| 474 | + ComputeTapbranchHash(node.sub[1]->hash, node.sub[1]->hash) == node.hash) { |
| 475 | + // Whenever there are nodes with two identical subtrees under it, we run into a problem: |
| 476 | + // the control blocks for the leaves underneath those will be identical as well, and thus |
| 477 | + // they will all be matched to the same path in the tree. The result is that at the location |
| 478 | + // where the duplicate occurred, the left child will contain a normal tree that can be explored |
| 479 | + // and processed, but the right one will remain unexplored. |
| 480 | + // |
| 481 | + // This situation can be detected, by encountering an inner node with unexplored right subtree |
| 482 | + // with known hash, and H_TapBranch(hash, hash) is equal to the parent node (this node)'s hash. |
| 483 | + // |
| 484 | + // To deal with this, simply process the left tree a second time (set its done flag to false; |
| 485 | + // noting that the done flag of its children have already been set to false after processing |
| 486 | + // those). To avoid ending up in an infinite loop, set the done flag of the right (unexplored) |
| 487 | + // subtree to true. |
| 488 | + node.sub[0]->done = false; |
| 489 | + node.sub[1]->done = true; |
| 490 | + } else if (node.sub[0]->done && node.sub[1]->done) { |
| 491 | + // An internal node which we're finished with. |
| 492 | + node.sub[0]->done = false; |
| 493 | + node.sub[1]->done = false; |
| 494 | + node.done = true; |
| 495 | + stack.pop_back(); |
| 496 | + } else if (!node.sub[0]->done) { |
| 497 | + // An internal node whose left branch hasn't been processed yet. Do so first. |
| 498 | + stack.push_back(&*node.sub[0]); |
| 499 | + } else if (!node.sub[1]->done) { |
| 500 | + // An internal node whose right branch hasn't been processed yet. Do so first. |
| 501 | + stack.push_back(&*node.sub[1]); |
| 502 | + } |
| 503 | + } |
| 504 | + |
| 505 | + return ret; |
| 506 | +} |
| 507 | + |
| 508 | +std::vector<std::tuple<uint8_t, uint8_t, std::vector<unsigned char>>> TaprootBuilder::GetTreeTuples() const |
| 509 | +{ |
| 510 | + assert(IsComplete()); |
| 511 | + std::vector<std::tuple<uint8_t, uint8_t, std::vector<unsigned char>>> tuples; |
| 512 | + if (m_branch.size()) { |
| 513 | + const auto& leaves = m_branch[0]->leaves; |
| 514 | + for (const auto& leaf : leaves) { |
| 515 | + assert(leaf.merkle_branch.size() <= TAPROOT_CONTROL_MAX_NODE_COUNT); |
| 516 | + uint8_t depth = (uint8_t)leaf.merkle_branch.size(); |
| 517 | + uint8_t leaf_ver = (uint8_t)leaf.leaf_version; |
| 518 | + tuples.push_back(std::make_tuple(depth, leaf_ver, leaf.script)); |
| 519 | + } |
| 520 | + } |
| 521 | + return tuples; |
| 522 | +} |
0 commit comments