Debian Codegraph @

mlspp/src/treekem.cpp

raw symbols SCIP
1 #include <mls/treekem.h>
2
3 #if ENABLE_TREE_DUMP
4 #include <iostream>
5 #endif
6
7 namespace mlspp {
8
9 // Utility method used for removing leaves from a resolution
10 static void
11 remove_leaves(std::vector<NodeIndex>& res, const std::vector<LeafIndex>& except)
12 {
13 for (const auto& leaf : except) {
14 auto it = std::find(res.begin(), res.end(), NodeIndex(leaf));
15 if (it == res.end()) {
16 continue;
17 }
18
19 res.erase(it);
20 }
21 }
22
23 ///
24 /// Node
25 ///
26
27 const HPKEPublicKey&
28 Node::public_key() const
29 {
30 const auto get_key = overloaded{
31 [](const LeafNode& n) -> const HPKEPublicKey& { return n.encryption_key; },
32 [](const ParentNode& n) -> const HPKEPublicKey& { return n.public_key; },
33 };
34 return var::visit(get_key, node);
35 }
36
37 std::optional<bytes>
38 Node::parent_hash() const
39 {
40 const auto get_leaf_ph = overloaded{
41 [](const ParentHash& ph) -> std::optional<bytes> { return ph.parent_hash; },
42 [](const auto& /* other */) -> std::optional<bytes> {
43 return std::nullopt;
44 },
45 };
46
47 const auto get_ph = overloaded{
48 [&](const LeafNode& node) -> std::optional<bytes> {
49 return var::visit(get_leaf_ph, node.content);
50 },
51 [](const ParentNode& node) -> std::optional<bytes> {
52 return node.parent_hash;
53 },
54 };
55
56 return var::visit(get_ph, node);
57 }
58
59 ///
60 /// TreeKEMPrivateKey
61 ///
62
63 TreeKEMPrivateKey
64 TreeKEMPrivateKey::solo(CipherSuite suite,
65 LeafIndex index,
66 HPKEPrivateKey leaf_priv)
67 {
68 auto priv = TreeKEMPrivateKey{ suite, index, {}, {}, {} };
69 priv.private_key_cache.insert({ NodeIndex(index), std::move(leaf_priv) });
70 return priv;
71 }
72
73 TreeKEMPrivateKey
74 TreeKEMPrivateKey::create(const TreeKEMPublicKey& pub,
75 LeafIndex from,
76 const bytes& leaf_secret)
77 {
78 auto priv = TreeKEMPrivateKey{ pub.suite, from, {}, {}, {} };
79 priv.implant(pub, NodeIndex(from), leaf_secret);
80 return priv;
81 }
82
83 TreeKEMPrivateKey
84 TreeKEMPrivateKey::joiner(const TreeKEMPublicKey& pub,
85 LeafIndex index,
86 HPKEPrivateKey leaf_priv,
87 NodeIndex intersect,
88 const std::optional<bytes>& path_secret)
89 {
90 auto priv = TreeKEMPrivateKey{ pub.suite, index, {}, {}, {} };
91 priv.private_key_cache.insert({ NodeIndex(index), std::move(leaf_priv) });
92 if (path_secret) {
93 priv.implant(pub, intersect, opt::get(path_secret));
94 }
95 return priv;
96 }
97
98 void
99 TreeKEMPrivateKey::implant(const TreeKEMPublicKey& pub,
100 NodeIndex start,
101 const bytes& path_secret)
102 {
103 const auto fdp = pub.filtered_direct_path(start);
104 auto secret = path_secret;
105
106 path_secrets.insert_or_assign(start, secret);
107 private_key_cache.erase(start);
108
109 for (const auto& [n, _res] : fdp) {
110 secret = pub.suite.derive_secret(secret, "path");
111 path_secrets.insert_or_assign(n, secret);
112 private_key_cache.erase(n);
113 }
114
115 update_secret = pub.suite.derive_secret(secret, "path");
116 }
117
118 std::optional<HPKEPrivateKey>
119 TreeKEMPrivateKey::private_key(NodeIndex n) const
120 {
121 auto pki = private_key_cache.find(n);
122 if (pki != private_key_cache.end()) {
123 return pki->second;
124 }
125
126 auto i = path_secrets.find(n);
127 if (i == path_secrets.end()) {
128 return std::nullopt;
129 }
130
131 auto node_secret = suite.derive_secret(i->second, "node");
132 return HPKEPrivateKey::derive(suite, node_secret);
133 }
134
135 bool
136 TreeKEMPrivateKey::have_private_key(NodeIndex n) const
137 {
138 auto path_secret = path_secrets.find(n) != path_secrets.end();
139 auto cached_priv = private_key_cache.find(n) != private_key_cache.end();
140 return path_secret || cached_priv;
141 }
142
143 std::optional<HPKEPrivateKey>
144 TreeKEMPrivateKey::private_key(NodeIndex n)
145 {
146 auto priv = static_cast<const TreeKEMPrivateKey&>(*this).private_key(n);
147 if (priv) {
148 private_key_cache.insert_or_assign(n, opt::get(priv));
149 }
150 return priv;
151 }
152
153 void
154 TreeKEMPrivateKey::set_leaf_priv(HPKEPrivateKey priv)
155 {
156 auto n = NodeIndex(index);
157 path_secrets.erase(n);
158 private_key_cache.insert_or_assign(n, std::move(priv));
159 }
160
161 std::tuple<NodeIndex, bytes, bool>
162 TreeKEMPrivateKey::shared_path_secret(LeafIndex to) const
163 {
164 auto n = index.ancestor(to);
165 auto i = path_secrets.find(n);
166 if (i == path_secrets.end()) {
167 return std::make_tuple(n, bytes{}, false);
168 }
169
170 return std::make_tuple(n, i->second, true);
171 }
172
173 #if ENABLE_TREE_DUMP
174 // XXX(RLB) This should ultimately be deleted, but it is handy for interop
175 // debugging, so I'm keeping it around for now. If re-enabled, you'll also need
176 // to add the appropriate declarations to treekem.h and include <iostream>
177
178 void
179 TreeKEMPrivateKey::dump() const
180 {
181 for (const auto& [node, _] : path_secrets) {
182 private_key(node);
183 }
184
185 std::cout << "Tree (priv):" << std::endl;
186 std::cout << " Index: " << NodeIndex(index).val << std::endl;
187
188 std::cout << " Secrets: " << std::endl;
189 for (const auto& [n, path_secret] : path_secrets) {
190 auto node_secret = suite.derive_secret(path_secret, "node");
191 auto sk = HPKEPrivateKey::derive(suite, node_secret);
192
193 auto psm = to_hex(path_secret).substr(0, 8);
194 auto pkm = to_hex(sk.public_key.data).substr(0, 8);
195 std::cout << " " << n.val << " => " << psm << " => " << pkm << std::endl;
196 }
197
198 std::cout << " Cached key pairs: " << std::endl;
199 for (const auto& [n, sk] : private_key_cache) {
200 auto pkm = to_hex(sk.public_key.data).substr(0, 8);
201 std::cout << " " << n.val << " => " << pkm << std::endl;
202 }
203 }
204
205 void
206 TreeKEMPublicKey::dump() const
207 {
208 std::cout << "Tree:" << std::endl;
209 auto width = NodeCount(size);
210 for (auto i = NodeIndex{ 0 }; i.val < width.val; i.val++) {
211 printf(" %03d : ", i.val); // NOLINT
212 if (!node_at(i).blank()) {
213 auto pkRm = to_hex(opt::get(node_at(i).node).public_key().data);
214 std::cout << pkRm.substr(0, 8);
215 } else {
216 std::cout << " ";
217 }
218
219 std::cout << " | ";
220 for (uint32_t j = 0; j < i.level(); j++) {
221 std::cout << " ";
222 }
223
224 if (!node_at(i).blank()) {
225 std::cout << "X";
226
227 if (!i.is_leaf()) {
228 auto parent = node_at(i).parent_node();
229 std::cout << " [";
230 for (const auto u : parent.unmerged_leaves) {
231 std::cout << u.val << ", ";
232 }
233 std::cout << "]";
234 }
235
236 } else {
237 std::cout << "_";
238 }
239
240 std::cout << std::endl;
241 }
242 }
243 #endif
244
245 void
246 TreeKEMPrivateKey::decap(LeafIndex from,
247 const TreeKEMPublicKey& pub,
248 const bytes& context,
249 const UpdatePath& path,
250 const std::vector<LeafIndex>& except)
251 {
252 // Identify which node in the path secret we will be decrypting
253 auto ni = NodeIndex(index);
254 auto dp = pub.filtered_direct_path(NodeIndex(from));
255 if (dp.size() != path.nodes.size()) {
256 throw ProtocolError("Malformed direct path");
257 }
258
259 size_t dpi = 0;
260 auto overlap_node = NodeIndex{};
261 auto res = std::vector<NodeIndex>{};
262 for (dpi = 0; dpi < dp.size(); dpi++) {
263 const auto [dpn, dpres] = dp[dpi];
264 if (ni.is_below(dpn)) {
265 overlap_node = dpn;
266 res = dpres;
267 break;
268 }
269 }
270
271 if (dpi == dp.size()) {
272 throw ProtocolError("No overlap in path");
273 }
274
275 // Identify which node in the resolution of the copath we will use to decrypt
276 remove_leaves(res, except);
277 if (res.size() != path.nodes[dpi].encrypted_path_secret.size()) {
278 throw ProtocolError("Malformed direct path node");
279 }
280
281 size_t resi = 0;
282 const NodeIndex res_overlap_node;
283 for (resi = 0; resi < res.size(); resi++) {
284 if (have_private_key(res[resi])) {
285 break;
286 }
287 }
288
289 if (resi == res.size()) {
290 throw ProtocolError("No private key to decrypt path secret");
291 }
292
293 // Decrypt and implant
294 auto priv = opt::get(private_key(res[resi]));
295 auto path_secret = priv.decrypt(suite,
296 encrypt_label::update_path_node,
297 context,
298 path.nodes[dpi].encrypted_path_secret[resi]);
299 implant(pub, overlap_node, path_secret);
300
301 // Check that the resulting state is consistent with the public key
302 if (!consistent(pub)) {
303 throw ProtocolError("TreeKEMPublicKey inconsistent with TreeKEMPrivateKey");
304 }
305 }
306
307 void
308 TreeKEMPrivateKey::truncate(LeafCount size)
309 {
310 auto ni = NodeIndex(LeafIndex{ size.val - 1 });
311 auto to_remove = std::vector<NodeIndex>{};
312 for (const auto& entry : path_secrets) {
313 if (entry.first.val > ni.val) {
314 to_remove.push_back(entry.first);
315 }
316 }
317
318 for (auto n : to_remove) {
319 path_secrets.erase(n);
320 private_key_cache.erase(n);
321 }
322 }
323
324 bool
325 TreeKEMPrivateKey::consistent(const TreeKEMPrivateKey& other) const
326 {
327 if (suite != other.suite) {
328 return false;
329 }
330
331 if (update_secret != other.update_secret) {
332 return false;
333 }
334
335 const auto match_if_present = [&](const auto& entry) {
336 auto other_entry = other.path_secrets.find(entry.first);
337 if (other_entry == other.path_secrets.end()) {
338 return true;
339 }
340
341 return entry.second == other_entry->second;
342 };
343 return stdx::all_of(path_secrets, match_if_present);
344 }
345
346 bool
347 TreeKEMPrivateKey::consistent(const TreeKEMPublicKey& other) const
348 {
349 if (suite != other.suite) {
350 return false;
351 }
352
353 for (const auto& [node, _] : path_secrets) {
354 private_key(node);
355 }
356
357 return stdx::all_of(private_key_cache, [other](const auto& entry) {
358 const auto& [node, priv] = entry;
359 const auto& opt_node = other.node_at(node).node;
360 if (!opt_node) {
361 // It's OK for a TreeKEMPrivateKey to have private keys
362 // for nodes that are blank in the TreeKEMPublicKey.
363 // This will happen traniently during Commit
364 // processing, since proposals will be applied in the
365 // public tree and not in the private tree.
366 return true;
367 }
368
369 const auto& pub = opt::get(opt_node).public_key();
370 return priv.public_key == pub;
371 });
372 }
373
374 ///
375 /// TreeKEMPublicKey
376 ///
377
378 TreeKEMPublicKey::TreeKEMPublicKey(CipherSuite suite_in)
379 : suite(suite_in)
380 {
381 }
382
383 LeafIndex
384 TreeKEMPublicKey::allocate_leaf()
385 {
386 // Find the leftmost blank leaf node
387 auto index = LeafIndex(0);
388 while (index.val < size.val && !node_at(index).blank()) {
389 index.val++;
390 }
391
392 // Extend the tree if necessary
393 if (index.val >= size.val) {
394 if (size.val == 0) {
395 size.val = 1;
396 nodes.resize(1);
397 } else {
398 size.val *= 2;
399 nodes.resize(2 * nodes.size() + 1);
400 }
401 }
402
403 return index;
404 }
405
406 LeafIndex
407 TreeKEMPublicKey::add_leaf(const LeafNode& leaf)
408 {
409 // Check that the leaf node's keys are not already present in the tree
410 if (exists_in_tree(leaf.encryption_key, std::nullopt)) {
411 throw InvalidParameterError("Duplicate encryption key");
412 }
413
414 if (exists_in_tree(leaf.signature_key, std::nullopt)) {
415 throw InvalidParameterError("Duplicate signature key");
416 }
417
418 // Allocate a blank leaf for this node
419 const auto index = allocate_leaf();
420
421 // Set the leaf
422 node_at(index).node = Node{ leaf };
423
424 // Update the unmerged list
425 for (auto& n : NodeIndex(index).dirpath(size)) {
426 if (!node_at(n).node) {
427 continue;
428 }
429
430 auto& parent = var::get<ParentNode>(opt::get(node_at(n).node).node);
431
432 // Insert into unmerged leaves while maintaining order
433 const auto insert_point = stdx::upper_bound(parent.unmerged_leaves, index);
434 parent.unmerged_leaves.insert(insert_point, index);
435 }
436
437 clear_hash_path(index);
438 return index;
439 }
440
441 void
442 TreeKEMPublicKey::update_leaf(LeafIndex index, const LeafNode& leaf)
443 {
444 // Check that the leaf node's keys are not already present in the tree, except
445 // for the signature key, which is allowed to repeat.
446 if (exists_in_tree(leaf.encryption_key, std::nullopt)) {
447 throw InvalidParameterError("Duplicate encryption key");
448 }
449
450 if (exists_in_tree(leaf.signature_key, index)) {
451 throw InvalidParameterError("Duplicate signature key");
452 }
453
454 blank_path(index);
455 node_at(NodeIndex(index)).node = Node{ leaf };
456 clear_hash_path(index);
457 }
458
459 void
460 TreeKEMPublicKey::blank_path(LeafIndex index)
461 {
462 if (nodes.empty()) {
463 return;
464 }
465
466 auto ni = NodeIndex(index);
467 node_at(ni).node.reset();
468 for (auto n : ni.dirpath(size)) {
469 node_at(n).node.reset();
470 }
471
472 clear_hash_path(index);
473 }
474
475 void
476 TreeKEMPublicKey::merge(LeafIndex from, const UpdatePath& path)
477 {
478 update_leaf(from, path.leaf_node);
479
480 auto dp = filtered_direct_path(NodeIndex(from));
481 if (dp.size() != path.nodes.size()) {
482 throw ProtocolError("Malformed direct path");
483 }
484
485 auto ph = parent_hashes(from, dp, path.nodes);
486 for (size_t i = 0; i < dp.size(); i++) {
487 auto [n, _res] = dp[i];
488
489 auto parent_hash = bytes{};
490 if (i < dp.size() - 1) {
491 parent_hash = ph[i + 1];
492 }
493
494 node_at(n).node =
495 Node{ ParentNode{ path.nodes[i].public_key, parent_hash, {} } };
496 }
497
498 set_hash_all();
499 }
500
501 void
502 TreeKEMPublicKey::set_hash_all()
503 {
504 auto r = NodeIndex::root(size);
505 get_hash(r);
506 }
507
508 bytes
509 TreeKEMPublicKey::root_hash() const
510 {
511 auto r = NodeIndex::root(size);
512 if (hashes.count(r) == 0) {
513 throw InvalidParameterError("Root hash not set");
514 }
515
516 return hashes.at(r);
517 }
518
519 bool
520 TreeKEMPublicKey::has_parent_hash(NodeIndex child, const bytes& target_ph) const
521 {
522 const auto res = resolve(child);
523 return stdx::any_of(res, [&](auto nr) {
524 return opt::get(node_at(nr).node).parent_hash() == target_ph;
525 });
526 }
527
528 bool
529 TreeKEMPublicKey::parent_hash_valid() const
530 {
531 auto cache = TreeHashCache{};
532
533 auto width = NodeCount(size);
534 auto height = NodeIndex::root(size).level();
535 for (auto level = uint32_t(1); level <= height; level++) {
536 auto stride = uint32_t(2) << level;
537 auto start = NodeIndex{ (stride >> 1U) - 1 };
538
539 for (auto p = start; p.val < width.val; p.val += stride) {
540 if (node_at(p).blank()) {
541 continue;
542 }
543
544 auto l = p.left();
545 auto r = p.right();
546
547 auto lh = original_parent_hash(cache, p, r);
548 auto rh = original_parent_hash(cache, p, l);
549
550 if (!has_parent_hash(l, lh) && !has_parent_hash(r, rh)) {
551 dump();
552 return false;
553 }
554 }
555 }
556 return true;
557 }
558
559 std::vector<NodeIndex>
560 TreeKEMPublicKey::resolve(NodeIndex index) const
561 {
562 auto at_leaf = (index.level() == 0);
563 if (!node_at(index).blank()) {
564 auto out = std::vector<NodeIndex>{ index };
565 if (index.is_leaf()) {
566 return out;
567 }
568
569 const auto& node = node_at(index);
570 auto unmerged =
571 stdx::transform<NodeIndex>(node.parent_node().unmerged_leaves,
572 [](LeafIndex x) { return NodeIndex(x); });
573
574 out.insert(out.end(), unmerged.begin(), unmerged.end());
575 return out;
576 }
577
578 if (at_leaf) {
579 return {};
580 }
581
582 auto l = resolve(index.left());
583 auto r = resolve(index.right());
584 l.insert(l.end(), r.begin(), r.end());
585 return l;
586 }
587
588 TreeKEMPublicKey::FilteredDirectPath
589 TreeKEMPublicKey::filtered_direct_path(NodeIndex index) const
590 {
591 auto fdp = FilteredDirectPath{};
592
593 const auto cp = index.copath(size);
594 auto last = index;
595 for (auto n : cp) {
596 const auto p = n.parent();
597 const auto res = resolve(n);
598 last = p;
599 if (res.empty()) {
600 continue;
601 }
602
603 fdp.emplace_back(p, res);
604 }
605
606 return fdp;
607 }
608
609 bool
610 TreeKEMPublicKey::has_leaf(LeafIndex index) const
611 {
612 return !node_at(index).blank();
613 }
614
615 std::optional<LeafIndex>
616 TreeKEMPublicKey::find(const LeafNode& leaf) const
617 {
618 for (LeafIndex i{ 0 }; i < size; i.val++) {
619 const auto& node = node_at(i);
620 if (!node.blank() && node.leaf_node() == leaf) {
621 return i;
622 }
623 }
624
625 return std::nullopt;
626 }
627
628 std::optional<LeafNode>
629 TreeKEMPublicKey::leaf_node(LeafIndex index) const
630 {
631 const auto& node = node_at(index);
632 if (node.blank()) {
633 return std::nullopt;
634 }
635
636 return node.leaf_node();
637 }
638
639 TreeKEMPrivateKey
640 TreeKEMPublicKey::update(LeafIndex from,
641 const bytes& leaf_secret,
642 const bytes& group_id,
643 const SignaturePrivateKey& sig_priv,
644 const LeafNodeOptions& opts)
645 {
646 // Grab information about the sender
647 const auto& leaf_node = node_at(from);
648 if (leaf_node.blank()) {
649 throw InvalidParameterError("Cannot update from blank node");
650 }
651
652 // Generate path secrets
653 auto priv = TreeKEMPrivateKey::create(*this, from, leaf_secret);
654 auto dp = filtered_direct_path(NodeIndex(from));
655
656 // Encrypt path secrets to the copath, forming a stub UpdatePath with no
657 // encryptions
658 auto path_nodes = stdx::transform<UpdatePathNode>(dp, [&](const auto& dpn) {
659 auto [n, _res] = dpn;
660
661 auto path_secret = priv.path_secrets.at(n);
662 auto node_priv = opt::get(priv.private_key(n));
663
664 return UpdatePathNode{ node_priv.public_key, {} };
665 });
666
667 // Update and re-sign the leaf_node
668 auto ph = parent_hashes(from, dp, path_nodes);
669 auto ph0 = bytes{};
670 if (!ph.empty()) {
671 ph0 = ph[0];
672 }
673
674 auto leaf_pub = opt::get(priv.private_key(NodeIndex(from))).public_key;
675 auto new_leaf = leaf_node.leaf_node().for_commit(
676 suite, group_id, from, leaf_pub, ph0, opts, sig_priv);
677
678 // Merge the changes into the tree
679 merge(from, UpdatePath{ std::move(new_leaf), std::move(path_nodes) });
680
681 return priv;
682 }
683
684 UpdatePath
685 TreeKEMPublicKey::encap(const TreeKEMPrivateKey& priv,
686 const bytes& context,
687 const std::vector<LeafIndex>& except) const
688 {
689 auto dp = filtered_direct_path(NodeIndex(priv.index));
690
691 // Encrypt path secrets to the copath
692 auto path_nodes = stdx::transform<UpdatePathNode>(dp, [&](const auto& dpn) {
693 // We need the copy here so that we can modify the resolution.
694 // NOLINTNEXTLINE(performance-unnecessary-copy-initialization)
695 auto [n, res] = dpn;
696 remove_leaves(res, except);
697
698 auto path_secret = priv.path_secrets.at(n);
699 auto node_priv = opt::get(priv.private_key(n));
700
701 auto ct = stdx::transform<HPKECiphertext>(res, [&](auto nr) {
702 const auto& node_pub = opt::get(node_at(nr).node).public_key();
703 return node_pub.encrypt(
704 suite, encrypt_label::update_path_node, context, path_secret);
705 });
706
707 return UpdatePathNode{ node_priv.public_key, std::move(ct) };
708 });
709
710 // Package everything into an UpdatePath
711 auto new_leaf = opt::get(leaf_node(priv.index));
712 auto path = UpdatePath{ new_leaf, std::move(path_nodes) };
713
714 return path;
715 }
716
717 void
718 TreeKEMPublicKey::truncate()
719 {
720 if (size.val == 0) {
721 return;
722 }
723
724 // Clear the parent hashes across blank leaves before truncating
725 auto index = LeafIndex{ size.val - 1 };
726 for (; index.val > 0; index.val--) {
727 if (!node_at(index).blank()) {
728 break;
729 }
730 clear_hash_path(index);
731 }
732
733 if (node_at(index).blank()) {
734 nodes.clear();
735 return;
736 }
737
738 // Remove the right subtree until the tree is of minimal size
739 while (size.val / 2 > index.val) {
740 nodes.resize(nodes.size() / 2);
741 size.val /= 2;
742 }
743 }
744
745 OptionalNode&
746 TreeKEMPublicKey::node_at(NodeIndex n)
747 {
748 auto width = NodeCount(size);
749 if (n.val >= width.val) {
750 throw InvalidParameterError("Node index not in tree");
751 }
752
753 if (n.val >= nodes.size()) {
754 return blank_node;
755 }
756
757 return nodes.at(n.val);
758 }
759
760 const OptionalNode&
761 TreeKEMPublicKey::node_at(NodeIndex n) const
762 {
763 auto width = NodeCount(size);
764 if (n.val >= width.val) {
765 throw InvalidParameterError("Node index not in tree");
766 }
767
768 if (n.val >= nodes.size()) {
769 return blank_node;
770 }
771
772 return nodes.at(n.val);
773 }
774
775 OptionalNode&
776 TreeKEMPublicKey::node_at(LeafIndex n)
777 {
778 return node_at(NodeIndex(n));
779 }
780
781 const OptionalNode&
782 TreeKEMPublicKey::node_at(LeafIndex n) const
783 {
784 return node_at(NodeIndex(n));
785 }
786
787 void
788 TreeKEMPublicKey::clear_hash_all()
789 {
790 hashes.clear();
791 }
792
793 void
794 TreeKEMPublicKey::clear_hash_path(LeafIndex index)
795 {
796 auto dp = NodeIndex(index).dirpath(size);
797 hashes.erase(NodeIndex(index));
798 for (auto n : dp) {
799 hashes.erase(n);
800 }
801 }
802
803 struct LeafNodeHashInput
804 {
805 LeafIndex leaf_index;
806 std::optional<LeafNode> leaf_node;
807 TLS_SERIALIZABLE(leaf_index, leaf_node)
808 };
809
810 struct ParentNodeHashInput
811 {
812 std::optional<ParentNode> parent_node;
813 const bytes& left_hash;
814 const bytes& right_hash;
815 TLS_SERIALIZABLE(parent_node, left_hash, right_hash)
816 };
817
818 struct TreeHashInput
819 {
820 var::variant<LeafNodeHashInput, ParentNodeHashInput> node;
821 TLS_SERIALIZABLE(node);
822 TLS_TRAITS(tls::variant<NodeType>)
823 };
824
825 const bytes&
826 TreeKEMPublicKey::get_hash(NodeIndex index)
827 {
828 if (hashes.count(index) > 0) {
829 return hashes.at(index);
830 }
831
832 auto hash_input = bytes{};
833 const auto& node = node_at(index);
834 if (index.level() == 0) {
835 auto input = LeafNodeHashInput{ LeafIndex(index), {} };
836 if (!node.blank()) {
837 input.leaf_node = node.leaf_node();
838 }
839
840 hash_input = tls::marshal(TreeHashInput{ input });
841 } else {
842 auto input = ParentNodeHashInput{
843 {},
844 get_hash(index.left()),
845 get_hash(index.right()),
846 };
847
848 if (!node.blank()) {
849 input.parent_node = node.parent_node();
850 }
851
852 hash_input = tls::marshal(TreeHashInput{ input });
853 }
854
855 auto hash = suite.digest().hash(hash_input);
856 hashes.insert_or_assign(index, hash);
857 return hashes.at(index);
858 }
859
860 // struct {
861 // HPKEPublicKey encryption_key;
862 // opaque parent_hash<V>;
863 // opaque original_sibling_tree_hash<V>;
864 // } ParentHashInput;
865 struct ParentHashInput
866 {
867 const HPKEPublicKey& public_key;
868 const bytes& parent_hash;
869 const bytes& original_child_resolution;
870
871 TLS_SERIALIZABLE(public_key, parent_hash, original_child_resolution)
872 };
873
874 bytes
875 TreeKEMPublicKey::parent_hash(const ParentNode& parent,
876 NodeIndex copath_child) const
877 {
878 if (hashes.count(copath_child) == 0) {
879 throw InvalidParameterError("Child hash not set");
880 }
881
882 auto hash_input = ParentHashInput{
883 parent.public_key,
884 parent.parent_hash,
885 hashes.at(copath_child),
886 };
887
888 return suite.digest().hash(tls::marshal(hash_input));
889 }
890
891 std::vector<bytes>
892 TreeKEMPublicKey::parent_hashes(
893 LeafIndex from,
894 const FilteredDirectPath& fdp,
895 const std::vector<UpdatePathNode>& path_nodes) const
896 {
897 // An empty filtered direct path indicates a one-member tree, since there's
898 // nobody else there to encrypt with. In this special case, there's no
899 // parent hashing to be done.
900 if (fdp.empty()) {
901 return {};
902 }
903
904 // The list of nodes for whom parent hashes are computed, namely: Direct path
905 // excluding the last entry, including leaf
906 auto from_node = NodeIndex(from);
907 auto dp = fdp;
908 auto [last, _res_last] = dp.back();
909 dp.pop_back();
910 dp.insert(dp.begin(), { from_node, {} });
911
912 if (dp.size() != path_nodes.size()) {
913 throw ProtocolError("Malformed UpdatePath");
914 }
915
916 // Parent hash for all the parents, starting from the last entry of the
917 // filtered direct path
918 auto last_hash = bytes{};
919 auto ph = std::vector<bytes>(dp.size());
920 for (int i = static_cast<int>(dp.size()) - 1; i >= 0; i--) {
921 auto [n, _res] = dp[i];
922 auto s = n.sibling(last);
923
924 auto parent_node = ParentNode{ path_nodes[i].public_key, last_hash, {} };
925 last_hash = parent_hash(parent_node, s);
926 ph[i] = last_hash;
927
928 last = n;
929 }
930
931 return ph;
932 }
933
934 const bytes&
935 TreeKEMPublicKey::original_tree_hash(TreeHashCache& cache,
936 NodeIndex index,
937 std::vector<LeafIndex> parent_except) const
938 {
939 // Scope the unmerged leaves list down to this subtree
940 auto except = std::vector<LeafIndex>{};
941 std::copy_if(parent_except.begin(),
942 parent_except.end(),
943 std::back_inserter(except),
944 [&](auto i) { return NodeIndex(i).is_below(index); });
945
946 auto have_local_changes = !except.empty();
947
948 // If there are no local changes, then we can use the cached tree hash
949 if (!have_local_changes) {
950 return hashes.at(index);
951 }
952
953 // If this method has been called before with the same number of excluded
954 // leaves (which implies the same set), then use the cached value.
955 if (auto it = cache.find(index); it != cache.end()) {
956 const auto& [key, value] = *it;
957 const auto& [except_size, hash] = value;
958 if (except_size == except.size()) {
959 return hash;
960 }
961 }
962
963 // If there is no entry in either cache, recompute the value
964 auto hash = bytes{};
965 if (index.is_leaf()) {
966 // A leaf node with local changes is by definition excluded from the parent
967 // hash. So we return the hash of an empty leaf.
968 auto leaf_hash_input = LeafNodeHashInput{ LeafIndex(index), std::nullopt };
969 hash = suite.digest().hash(tls::marshal(TreeHashInput{ leaf_hash_input }));
970 } else {
971 // If there is no cached value, recalculate the child hashes with the
972 // specified `except` list, removing the `except` list from
973 // `unmerged_leaves`.
974 auto parent_hash_input = ParentNodeHashInput{
975 std::nullopt,
976 original_tree_hash(cache, index.left(), except),
977 original_tree_hash(cache, index.right(), except),
978 };
979
980 if (!node_at(index).blank()) {
981 parent_hash_input.parent_node = node_at(index).parent_node();
982 auto& unmerged_leaves =
983 opt::get(parent_hash_input.parent_node).unmerged_leaves;
984 auto end = std::remove_if(
985 unmerged_leaves.begin(), unmerged_leaves.end(), [&](auto leaf) {
986 return std::count(except.begin(), except.end(), leaf) != 0;
987 });
988 unmerged_leaves.erase(end, unmerged_leaves.end());
989 }
990
991 hash =
992 suite.digest().hash(tls::marshal(TreeHashInput{ parent_hash_input }));
993 }
994
995 cache.insert_or_assign(index, std::make_pair(except.size(), hash));
996 return cache.at(index).second;
997 }
998
999 bytes
1000 TreeKEMPublicKey::original_parent_hash(TreeHashCache& cache,
1001 NodeIndex parent,
1002 NodeIndex sibling) const
1003 {
1004 const auto& parent_node = node_at(parent).parent_node();
1005 const auto& unmerged = parent_node.unmerged_leaves;
1006 const auto& sibling_hash = original_tree_hash(cache, sibling, unmerged);
1007
1008 return suite.digest().hash(tls::marshal(ParentHashInput{
1009 parent_node.public_key,
1010 parent_node.parent_hash,
1011 sibling_hash,
1012 }));
1013 }
1014
1015 bool
1016 TreeKEMPublicKey::parent_hash_valid(LeafIndex from,
1017 const UpdatePath& path) const
1018 {
1019 auto fdp = filtered_direct_path(NodeIndex(from));
1020 auto hash_chain = parent_hashes(from, fdp, path.nodes);
1021 auto leaf_ph =
1022 var::visit(overloaded{
1023 [](const ParentHash& ph) -> std::optional<bytes> {
1024 return ph.parent_hash;
1025 },
1026 [](const auto& /* other */) -> std::optional<bytes> {
1027 return std::nullopt;
1028 },
1029 },
1030 path.leaf_node.content);
1031
1032 // If there are no nodes to hash, then ParentHash MUST be omitted
1033 if (hash_chain.empty()) {
1034 return !leaf_ph;
1035 }
1036
1037 return leaf_ph && opt::get(leaf_ph) == hash_chain[0];
1038 }
1039
1040 bool
1041 TreeKEMPublicKey::exists_in_tree(const HPKEPublicKey& key,
1042 std::optional<LeafIndex> except) const
1043 {
1044 return any_leaf([&](auto i, const auto& node) {
1045 return i != except && node.encryption_key == key;
1046 });
1047 }
1048
1049 bool
1050 TreeKEMPublicKey::exists_in_tree(const SignaturePublicKey& key,
1051 std::optional<LeafIndex> except) const
1052 {
1053 return any_leaf([&](auto i, const auto& node) {
1054 return i != except && node.signature_key == key;
1055 });
1056 }
1057
1058 tls::ostream&
1059 operator<<(tls::ostream& str, const TreeKEMPublicKey& obj)
1060 {
1061 // Empty tree
1062 if (obj.size.val == 0) {
1063 return str << std::vector<OptionalNode>{};
1064 }
1065
1066 LeafIndex cut = LeafIndex{ obj.size.val - 1 };
1067 while (cut.val > 0 && obj.node_at(cut).blank()) {
1068 cut.val -= 1;
1069 }
1070
1071 const auto begin = obj.nodes.begin();
1072 const auto end = begin + NodeIndex(cut).val + 1;
1073 const auto view = std::vector<OptionalNode>(begin, end);
1074 return str << view;
1075 }
1076
1077 tls::istream&
1078 operator>>(tls::istream& str, TreeKEMPublicKey& obj)
1079 {
1080 // Read the node list
1081 str >> obj.nodes;
1082 if (obj.nodes.empty()) {
1083 return str;
1084 }
1085
1086 // Verify that the tree is well-formed and minimal
1087 if (obj.nodes.size() % 2 == 0) {
1088 throw ProtocolError("Malformed ratchet tree: even number of nodes");
1089 }
1090
1091 if (obj.nodes.back().blank()) {
1092 throw ProtocolError("Ratchet tree does not use minimal encoding");
1093 }
1094
1095 // Adjust the size value to fit the non-blank nodes
1096 obj.size.val = 1;
1097 while (NodeCount(obj.size).val < obj.nodes.size()) {
1098 obj.size.val *= 2;
1099 }
1100
1101 // Add blank nodes to the end
1102 obj.nodes.resize(NodeCount(obj.size).val);
1103
1104 // Verify the basic structure of the tree is sane
1105 for (size_t i = 0; i < obj.nodes.size(); i++) {
1106 if (obj.nodes[i].blank()) {
1107 continue;
1108 }
1109
1110 const auto& node = opt::get(obj.nodes[i].node).node;
1111 auto at_leaf = (i % 2 == 0);
1112 auto holds_leaf = var::holds_alternative<LeafNode>(node);
1113 auto holds_parent = var::holds_alternative<ParentNode>(node);
1114
1115 if (at_leaf && !holds_leaf) {
1116 throw InvalidParameterError("Parent node in leaf node position");
1117 }
1118
1119 if (!at_leaf && !holds_parent) {
1120 throw InvalidParameterError("Leaf node in parent node position");
1121 }
1122 }
1123
1124 return str;
1125 }
1126
1127 } // namespace mlspp