1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
use std::collections::HashSet;
use bc_components::{Digest, DigestProvider};
#[cfg(feature = "encrypt")]
use bc_components::{Nonce, SymmetricKey};
#[cfg(feature = "encrypt")]
use dcbor::prelude::*;
use super::envelope::EnvelopeCase;
use crate::{Assertion, Envelope, Error, Result};
/// Types of obscuration that can be applied to envelope elements.
///
/// This enum identifies the different ways an envelope element can be obscured.
/// Unlike `ObscureAction` which is used to perform obscuration operations,
/// `ObscureType` is used to identify and filter elements based on their
/// obscuration state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ObscureType {
/// The element has been elided, showing only its digest.
Elided,
/// The element has been encrypted using symmetric encryption.
///
/// This variant is only available when the `encrypt` feature is enabled.
#[cfg(feature = "encrypt")]
Encrypted,
/// The element has been compressed to reduce its size.
///
/// This variant is only available when the `compress` feature is enabled.
#[cfg(feature = "compress")]
Compressed,
}
/// Actions that can be performed on parts of an envelope to obscure them.
///
/// Gordian Envelope supports several ways to obscure parts of an envelope while
/// maintaining its semantic integrity and digest tree. This enum defines the
/// possible actions that can be taken when obscuring envelope elements.
///
/// Obscuring parts of an envelope is a key feature for privacy and selective
/// disclosure, allowing the holder of an envelope to share only specific parts
/// while hiding, encrypting, or compressing others.
pub enum ObscureAction {
/// Elide the target, leaving only its digest.
///
/// Elision replaces the targeted envelope element with just its digest,
/// hiding its actual content while maintaining the integrity of the
/// envelope's digest tree. This is the most basic form of selective
/// disclosure.
///
/// Elided elements can be revealed later by providing the original unelided
/// envelope to the recipient, who can verify that the revealed content
/// matches the digest in the elided version.
Elide,
/// Encrypt the target using the specified symmetric key.
///
/// This encrypts the targeted envelope element using authenticated
/// encryption with the provided key. The encrypted content can only be
/// accessed by those who possess the symmetric key.
///
/// This action is only available when the `encrypt` feature is enabled.
#[cfg(feature = "encrypt")]
Encrypt(SymmetricKey),
/// Compress the target using a compression algorithm.
///
/// This compresses the targeted envelope element to reduce its size while
/// still allowing it to be decompressed by any recipient. Unlike elision or
/// encryption, compression doesn't provide privacy but can reduce the size
/// of large envelope components.
///
/// This action is only available when the `compress` feature is enabled.
#[cfg(feature = "compress")]
Compress,
}
/// Support for eliding elements from envelopes.
///
/// This includes eliding, encrypting and compressing (obscuring) elements.
impl Envelope {
/// Returns the elided variant of this envelope.
///
/// Elision replaces an envelope with just its digest, hiding its content
/// while maintaining the integrity of the envelope's digest tree. This
/// is a fundamental privacy feature of Gordian Envelope that enables
/// selective disclosure.
///
/// Returns the same envelope if it is already elided.
///
/// # Examples
///
/// ```
/// # use bc_envelope::prelude::*;
/// # use indoc::indoc;
/// let envelope = Envelope::new("Hello.");
/// let elided = envelope.elide();
///
/// // The elided envelope shows only "ELIDED" in formatting
/// assert_eq!(elided.format_flat(), "ELIDED");
///
/// // But it maintains the same digest as the original
/// assert!(envelope.is_equivalent_to(&elided));
/// ```
pub fn elide(&self) -> Self {
match self.case() {
EnvelopeCase::Elided(_) => self.clone(),
_ => Self::new_elided(self.digest()),
}
}
/// Returns a version of this envelope with elements in the `target` set
/// elided.
///
/// This function obscures elements in the envelope whose digests are in the
/// provided target set, applying the specified action (elision,
/// encryption, or compression) to those elements while leaving other
/// elements intact.
///
/// # Parameters
///
/// * `target` - The set of digests that identify elements to be obscured
/// * `action` - The action to perform on the targeted elements (elide,
/// encrypt, or compress)
///
/// # Examples
///
/// ```
/// # use bc_envelope::prelude::*;
/// # use std::collections::HashSet;
/// let envelope = Envelope::new("Alice")
/// .add_assertion("knows", "Bob")
/// .add_assertion("livesAt", "123 Main St.");
///
/// // Create a set of digests targeting the "livesAt" assertion
/// let mut target = HashSet::new();
/// let livesAt_assertion = envelope.assertion_with_predicate("livesAt").unwrap();
/// target.insert(livesAt_assertion.digest());
///
/// // Elide that specific assertion
/// let elided = envelope.elide_removing_set_with_action(&target, &ObscureAction::Elide);
///
/// // The result will have the "livesAt" assertion elided but "knows" still visible
/// ```
pub fn elide_removing_set_with_action(
&self,
target: &HashSet<Digest>,
action: &ObscureAction,
) -> Self {
self.elide_set_with_action(target, false, action)
}
/// Returns a version of this envelope with elements in the `target` set
/// elided.
///
/// This is a convenience function that calls `elide_set` with
/// `is_revealing` set to `false`, using the standard elision action.
/// Use this when you want to simply elide elements rather than encrypt
/// or compress them.
///
/// # Parameters
///
/// * `target` - The set of digests that identify elements to be elided
///
/// # Examples
///
/// ```
/// # use bc_envelope::prelude::*;
/// # use std::collections::HashSet;
/// let envelope = Envelope::new("Alice")
/// .add_assertion("knows", "Bob")
/// .add_assertion("email", "alice@example.com");
///
/// // Create a set of digests targeting the email assertion
/// let mut target = HashSet::new();
/// let email_assertion = envelope.assertion_with_predicate("email").unwrap();
/// target.insert(email_assertion.digest());
///
/// // Elide the email assertion for privacy
/// let redacted = envelope.elide_removing_set(&target);
/// ```
pub fn elide_removing_set(&self, target: &HashSet<Digest>) -> Self {
self.elide_set(target, false)
}
/// Returns a version of this envelope with elements in the `target` set
/// elided.
///
/// - Parameters:
/// - target: An array of `DigestProvider`s.
/// - action: Perform the specified action (elision, encryption or
/// compression).
///
/// - Returns: The elided envelope.
pub fn elide_removing_array_with_action(
&self,
target: &[&dyn DigestProvider],
action: &ObscureAction,
) -> Self {
self.elide_array_with_action(target, false, action)
}
/// Returns a version of this envelope with elements in the `target` set
/// elided.
///
/// - Parameters:
/// - target: An array of `DigestProvider`s.
/// - action: Perform the specified action (elision, encryption or
/// compression).
///
/// - Returns: The elided envelope.
pub fn elide_removing_array(&self, target: &[&dyn DigestProvider]) -> Self {
self.elide_array(target, false)
}
/// Returns a version of this envelope with the target element elided.
///
/// - Parameters:
/// - target: A `DigestProvider`.
/// - action: Perform the specified action (elision, encryption or
/// compression).
///
/// - Returns: The elided envelope.
pub fn elide_removing_target_with_action(
&self,
target: &dyn DigestProvider,
action: &ObscureAction,
) -> Self {
self.elide_target_with_action(target, false, action)
}
/// Returns a version of this envelope with the target element elided.
///
/// - Parameters:
/// - target: A `DigestProvider`.
///
/// - Returns: The elided envelope.
pub fn elide_removing_target(&self, target: &dyn DigestProvider) -> Self {
self.elide_target(target, false)
}
/// Returns a version of this envelope with only elements in the `target`
/// set revealed, and all other elements elided.
///
/// This function performs the opposite operation of
/// `elide_removing_set_with_action`. Instead of specifying which
/// elements to obscure, you specify which elements to reveal,
/// and everything else will be obscured using the specified action.
///
/// This is particularly useful for selective disclosure where you want to
/// reveal only specific portions of an envelope while keeping the rest
/// private.
///
/// # Parameters
///
/// * `target` - The set of digests that identify elements to be revealed
/// * `action` - The action to perform on all other elements (elide,
/// encrypt, or compress)
///
/// # Examples
///
/// ```
/// # use bc_envelope::prelude::*;
/// # use std::collections::HashSet;
/// let envelope = Envelope::new("Alice")
/// .add_assertion("name", "Alice Smith")
/// .add_assertion("age", 30)
/// .add_assertion("ssn", "123-45-6789");
///
/// // Create a set of digests for elements we want to reveal
/// let mut reveal_set = HashSet::new();
///
/// // Add the subject and the name assertion to the set to reveal
/// reveal_set.insert(envelope.subject().digest());
/// reveal_set
/// .insert(envelope.assertion_with_predicate("name").unwrap().digest());
///
/// // Create an envelope that only reveals name and hides age and SSN
/// let selective = envelope
/// .elide_revealing_set_with_action(&reveal_set, &ObscureAction::Elide);
/// ```
pub fn elide_revealing_set_with_action(
&self,
target: &HashSet<Digest>,
action: &ObscureAction,
) -> Self {
self.elide_set_with_action(target, true, action)
}
/// Returns a version of this envelope with elements *not* in the `target`
/// set elided.
///
/// - Parameters:
/// - target: The target set of digests.
///
/// - Returns: The elided envelope.
pub fn elide_revealing_set(&self, target: &HashSet<Digest>) -> Self {
self.elide_set(target, true)
}
/// Returns a version of this envelope with elements *not* in the `target`
/// set elided.
///
/// - Parameters:
/// - target: An array of `DigestProvider`s.
/// - action: Perform the specified action (elision, encryption or
/// compression).
///
/// - Returns: The elided envelope.
pub fn elide_revealing_array_with_action(
&self,
target: &[&dyn DigestProvider],
action: &ObscureAction,
) -> Self {
self.elide_array_with_action(target, true, action)
}
/// Returns a version of this envelope with elements *not* in the `target`
/// set elided.
///
/// - Parameters:
/// - target: An array of `DigestProvider`s.
///
/// - Returns: The elided envelope.
pub fn elide_revealing_array(
&self,
target: &[&dyn DigestProvider],
) -> Self {
self.elide_array(target, true)
}
/// Returns a version of this envelope with all elements *except* the target
/// element elided.
///
/// - Parameters:
/// - target: A `DigestProvider`.
/// - action: Perform the specified action (elision, encryption or
/// compression).
///
/// - Returns: The elided envelope.
pub fn elide_revealing_target_with_action(
&self,
target: &dyn DigestProvider,
action: &ObscureAction,
) -> Self {
self.elide_target_with_action(target, true, action)
}
/// Returns a version of this envelope with all elements *except* the target
/// element elided.
///
/// - Parameters:
/// - target: A `DigestProvider`.
///
/// - Returns: The elided envelope.
pub fn elide_revealing_target(&self, target: &dyn DigestProvider) -> Self {
self.elide_target(target, true)
}
// Target Matches isRevealing elide
// ----------------------------------------
// false false false
// false true true
// true false true
// true true false
/// Returns an elided version of this envelope.
///
/// - Parameters:
/// - target: The target set of digests.
/// - isRevealing: If `true`, the target set contains the digests of the
/// elements to leave revealed. If it is `false`, the target set
/// contains the digests of the elements to elide.
/// - action: Perform the specified action (elision, encryption or
/// compression).
///
/// - Returns: The elided envelope.
pub fn elide_set_with_action(
&self,
target: &HashSet<Digest>,
is_revealing: bool,
action: &ObscureAction,
) -> Self {
let self_digest = self.digest();
if target.contains(&self_digest) != is_revealing {
match action {
ObscureAction::Elide => self.elide(),
#[cfg(feature = "encrypt")]
ObscureAction::Encrypt(key) => {
let message = key.encrypt_with_digest(
self.tagged_cbor().to_cbor_data(),
self_digest,
None::<Nonce>,
);
Self::new_with_encrypted(message).unwrap()
}
#[cfg(feature = "compress")]
ObscureAction::Compress => self.compress().unwrap(),
}
} else if let EnvelopeCase::Assertion(assertion) = self.case() {
let predicate = assertion.predicate().elide_set_with_action(
target,
is_revealing,
action,
);
let object = assertion.object().elide_set_with_action(
target,
is_revealing,
action,
);
let elided_assertion = Assertion::new(predicate, object);
assert!(&elided_assertion == assertion);
Self::new_with_assertion(elided_assertion)
} else if let EnvelopeCase::Node { subject, assertions, .. } =
self.case()
{
let elided_subject =
subject.elide_set_with_action(target, is_revealing, action);
assert!(elided_subject.digest() == subject.digest());
let elided_assertions = assertions
.iter()
.map(|assertion| {
let elided_assertion = assertion.elide_set_with_action(
target,
is_revealing,
action,
);
assert!(elided_assertion.digest() == assertion.digest());
elided_assertion
})
.collect();
Self::new_with_unchecked_assertions(
elided_subject,
elided_assertions,
)
} else if let EnvelopeCase::Wrapped { envelope, .. } = self.case() {
let elided_envelope =
envelope.elide_set_with_action(target, is_revealing, action);
assert!(elided_envelope.digest() == envelope.digest());
Self::new_wrapped(elided_envelope)
} else {
self.clone()
}
}
/// Returns an elided version of this envelope.
///
/// - Parameters:
/// - target: The target set of digests.
/// - isRevealing: If `true`, the target set contains the digests of the
/// elements to leave revealed. If it is `false`, the target set
/// contains the digests of the elements to elide.
///
/// - Returns: The elided envelope.
pub fn elide_set(
&self,
target: &HashSet<Digest>,
is_revealing: bool,
) -> Self {
self.elide_set_with_action(target, is_revealing, &ObscureAction::Elide)
}
/// Returns an elided version of this envelope.
///
/// - Parameters:
/// - target: An array of `DigestProvider`s.
/// - isRevealing: If `true`, the target set contains the digests of the
/// elements to leave revealed. If it is `false`, the target set
/// contains the digests of the elements to elide.
/// - action: Perform the specified action (elision, encryption or
/// compression).
///
/// - Returns: The elided envelope.
pub fn elide_array_with_action(
&self,
target: &[&dyn DigestProvider],
is_revealing: bool,
action: &ObscureAction,
) -> Self {
self.elide_set_with_action(
&target.iter().map(|provider| provider.digest()).collect(),
is_revealing,
action,
)
}
/// Returns an elided version of this envelope.
///
/// - Parameters:
/// - target: An array of `DigestProvider`s.
/// - isRevealing: If `true`, the target set contains the digests of the
/// elements to leave revealed. If it is `false`, the target set
/// contains the digests of the elements to elide.
///
/// - Returns: The elided envelope.
pub fn elide_array(
&self,
target: &[&dyn DigestProvider],
is_revealing: bool,
) -> Self {
self.elide_array_with_action(
target,
is_revealing,
&ObscureAction::Elide,
)
}
/// Returns an elided version of this envelope.
///
/// - Parameters:
/// - target: A `DigestProvider`.
/// - isRevealing: If `true`, the target is the element to leave revealed,
/// eliding all others. If it is `false`, the target is the element to
/// elide, leaving all others revealed.
/// - action: Perform the specified action (elision, encryption or
/// compression).
///
/// - Returns: The elided envelope.
pub fn elide_target_with_action(
&self,
target: &dyn DigestProvider,
is_revealing: bool,
action: &ObscureAction,
) -> Self {
self.elide_array_with_action(&[target], is_revealing, action)
}
/// Returns an elided version of this envelope.
///
/// - Parameters:
/// - target: A `DigestProvider`.
/// - isRevealing: If `true`, the target is the element to leave revealed,
/// eliding all others. If it is `false`, the target is the element to
/// elide, leaving all others revealed.
///
/// - Returns: The elided envelope.
pub fn elide_target(
&self,
target: &dyn DigestProvider,
is_revealing: bool,
) -> Self {
self.elide_target_with_action(
target,
is_revealing,
&ObscureAction::Elide,
)
}
/// Returns the unelided variant of this envelope by revealing the original
/// content.
///
/// This function allows restoring an elided envelope to its original form,
/// but only if the provided envelope's digest matches the elided
/// envelope's digest. This ensures the integrity of the revealed
/// content.
///
/// Returns the same envelope if it is already unelided.
///
/// # Errors
///
/// Returns `EnvelopeError::InvalidDigest` if the provided envelope's digest
/// doesn't match the current envelope's digest.
///
/// # Examples
///
/// ```
/// # use bc_envelope::prelude::*;
/// let original = Envelope::new("Hello.");
/// let elided = original.elide();
///
/// // Later, we can unelide the envelope if we have the original
/// let revealed = elided.unelide(&original).unwrap();
/// assert_eq!(revealed.format(), "\"Hello.\"");
///
/// // Attempting to unelide with a different envelope will fail
/// let different = Envelope::new("Different");
/// assert!(elided.unelide(&different).is_err());
/// ```
pub fn unelide(&self, envelope: impl Into<Envelope>) -> Result<Self> {
let envelope = envelope.into();
if self.digest() == envelope.digest() {
Ok(envelope)
} else {
Err(Error::InvalidDigest)
}
}
/// Returns the set of digests of nodes matching the specified criteria.
///
/// This function walks the envelope hierarchy and returns digests of nodes
/// that match both:
/// - The optional target digest set (if provided; otherwise all nodes
/// match)
/// - Any of the specified obscuration types
///
/// If no obscuration types are provided, all nodes in the target set (or
/// all nodes if no target set) are returned.
///
/// # Parameters
///
/// * `target_digests` - Optional set of digests to filter by. If `None`,
/// all nodes are considered for matching.
/// * `obscure_types` - Slice of `ObscureType` values to match against. Only
/// nodes obscured in one of these ways will be included.
///
/// # Returns
///
/// A `HashSet` of digests for nodes matching the specified criteria.
///
/// # Examples
///
/// ```
/// # use bc_envelope::prelude::*;
/// # use std::collections::HashSet;
/// let envelope = Envelope::new("Alice")
/// .add_assertion("knows", "Bob")
/// .add_assertion("age", 30);
///
/// // Elide one assertion
/// let knows_digest =
/// envelope.assertion_with_predicate("knows").unwrap().digest();
/// let mut target = HashSet::new();
/// target.insert(knows_digest.clone());
///
/// let elided = envelope.elide_removing_set(&target);
///
/// // Find all elided nodes
/// let elided_digests = elided.nodes_matching(None, &[ObscureType::Elided]);
/// assert!(elided_digests.contains(&knows_digest));
/// ```
pub fn nodes_matching(
&self,
target_digests: Option<&HashSet<Digest>>,
obscure_types: &[ObscureType],
) -> HashSet<Digest> {
use std::cell::RefCell;
use super::walk::EdgeType;
let result = RefCell::new(HashSet::new());
let visitor = |envelope: &Envelope,
_level: usize,
_edge: EdgeType,
_state: ()|
-> ((), bool) {
// Check if this node matches the target digests (or if no target
// specified)
let digest_matches = target_digests
.map(|targets| targets.contains(&envelope.digest()))
.unwrap_or(true);
if !digest_matches {
return ((), false);
}
// If no obscure types specified, include all nodes
if obscure_types.is_empty() {
result.borrow_mut().insert(envelope.digest());
return ((), false);
}
// Check if this node matches any of the specified obscure types
let type_matches =
obscure_types.iter().any(|obscure_type| {
match (obscure_type, envelope.case()) {
(ObscureType::Elided, EnvelopeCase::Elided(_)) => true,
#[cfg(feature = "encrypt")]
(
ObscureType::Encrypted,
EnvelopeCase::Encrypted(_),
) => true,
#[cfg(feature = "compress")]
(
ObscureType::Compressed,
EnvelopeCase::Compressed(_),
) => true,
_ => false,
}
});
if type_matches {
result.borrow_mut().insert(envelope.digest());
}
((), false)
};
self.walk(false, (), &visitor);
result.into_inner()
}
/// Returns a new envelope with elided nodes restored from the provided set.
///
/// This function walks the envelope hierarchy and attempts to restore any
/// elided nodes by matching their digests against the provided set of
/// envelopes. If a match is found, the elided node is replaced with the
/// matching envelope.
///
/// If no matches are found, the original envelope is returned unchanged.
///
/// # Parameters
///
/// * `envelopes` - A slice of envelopes that may match elided nodes in
/// `self`
///
/// # Returns
///
/// A new envelope with elided nodes restored where possible.
///
/// # Examples
///
/// ```
/// # use bc_envelope::prelude::*;
/// let alice = Envelope::new("Alice");
/// let bob = Envelope::new("Bob");
/// let envelope = Envelope::new("Alice").add_assertion("knows", "Bob");
///
/// // Elide both the subject and an assertion
/// let elided = envelope
/// .elide_removing_target(&alice)
/// .elide_removing_target(&bob);
///
/// // Restore the elided nodes
/// let restored = elided.walk_unelide(&[alice, bob]);
///
/// // The restored envelope should match the original
/// assert_eq!(restored.format(), envelope.format());
/// ```
pub fn walk_unelide(&self, envelopes: &[Envelope]) -> Self {
use std::collections::HashMap;
// Build a lookup map of digest -> envelope
let mut envelope_map = HashMap::new();
for envelope in envelopes {
envelope_map.insert(envelope.digest(), envelope.clone());
}
self.walk_unelide_with_map(&envelope_map)
}
fn walk_unelide_with_map(
&self,
envelope_map: &std::collections::HashMap<Digest, Envelope>,
) -> Self {
match self.case() {
EnvelopeCase::Elided(_) => {
// Try to find a matching envelope to restore
if let Some(replacement) = envelope_map.get(&self.digest()) {
replacement.clone()
} else {
self.clone()
}
}
EnvelopeCase::Node { subject, assertions, .. } => {
// Recursively unelide subject and assertions
let new_subject = subject.walk_unelide_with_map(envelope_map);
let new_assertions: Vec<_> = assertions
.iter()
.map(|a| a.walk_unelide_with_map(envelope_map))
.collect();
if new_subject.is_identical_to(subject)
&& new_assertions
.iter()
.zip(assertions.iter())
.all(|(a, b)| a.is_identical_to(b))
{
self.clone()
} else {
Self::new_with_unchecked_assertions(
new_subject,
new_assertions,
)
}
}
EnvelopeCase::Wrapped { envelope, .. } => {
let new_envelope = envelope.walk_unelide_with_map(envelope_map);
if new_envelope.is_identical_to(envelope) {
self.clone()
} else {
new_envelope.wrap()
}
}
EnvelopeCase::Assertion(assertion) => {
// Recursively unelide predicate and object
let new_predicate =
assertion.predicate().walk_unelide_with_map(envelope_map);
let new_object =
assertion.object().walk_unelide_with_map(envelope_map);
if new_predicate.is_identical_to(&assertion.predicate())
&& new_object.is_identical_to(&assertion.object())
{
self.clone()
} else {
Envelope::new_assertion(new_predicate, new_object)
}
}
_ => self.clone(),
}
}
/// Returns a new envelope with nodes matching target digests replaced.
///
/// This function walks the envelope hierarchy and replaces any nodes whose
/// digests match those in the provided target set with clones of the
/// replacement envelope. Unlike `walk_unelide`, the replacement envelope
/// does not need to have the same digest as the node being replaced.
///
/// This enables transforming specific elements in an envelope structure
/// while preserving the overall hierarchy. The replacement is applied
/// recursively throughout the tree.
///
/// # Parameters
///
/// * `target` - Set of digests identifying nodes to replace
/// * `replacement` - The envelope to clone for each matching node
///
/// # Returns
///
/// A new envelope with matching nodes replaced.
///
/// # Errors
///
/// Returns `Error::InvalidFormat` if attempting to replace an assertion
/// with a non-assertion that is also not obscured (elided, encrypted,
/// or compressed). Assertions in a node's assertions array must be
/// either assertions or obscured elements (which are presumed to be
/// obscured assertions).
///
/// # Examples
///
/// ```
/// # use bc_envelope::prelude::*;
/// # use std::collections::HashSet;
/// let alice = Envelope::new("Alice");
/// let bob = Envelope::new("Bob");
/// let charlie = Envelope::new("Charlie");
///
/// let envelope = Envelope::new("Alice")
/// .add_assertion("knows", "Bob")
/// .add_assertion("likes", "Bob");
///
/// // Replace all instances of "Bob" with "Charlie"
/// let mut target = HashSet::new();
/// target.insert(bob.digest());
///
/// let modified = envelope.walk_replace(&target, &charlie).unwrap();
///
/// // Both assertions now reference Charlie instead of Bob
/// assert!(modified.format().contains("Charlie"));
/// assert!(!modified.format().contains("Bob"));
/// ```
pub fn walk_replace(
&self,
target: &HashSet<Digest>,
replacement: &Envelope,
) -> Result<Self> {
// Check if this node matches the target
if target.contains(&self.digest()) {
return Ok(replacement.clone());
}
// Recursively process children
match self.case() {
EnvelopeCase::Node { subject, assertions, .. } => {
let new_subject = subject.walk_replace(target, replacement)?;
let new_assertions: Vec<_> = assertions
.iter()
.map(|a| a.walk_replace(target, replacement))
.collect::<Result<Vec<_>>>()?;
if new_subject.is_identical_to(subject)
&& new_assertions
.iter()
.zip(assertions.iter())
.all(|(a, b)| a.is_identical_to(b))
{
Ok(self.clone())
} else {
// Use new_with_assertions to validate that all assertions
// are either assertions or obscured
Self::new_with_assertions(new_subject, new_assertions)
}
}
EnvelopeCase::Wrapped { envelope, .. } => {
let new_envelope =
envelope.walk_replace(target, replacement)?;
if new_envelope.is_identical_to(envelope) {
Ok(self.clone())
} else {
Ok(new_envelope.wrap())
}
}
EnvelopeCase::Assertion(assertion) => {
let new_predicate =
assertion.predicate().walk_replace(target, replacement)?;
let new_object =
assertion.object().walk_replace(target, replacement)?;
if new_predicate.is_identical_to(&assertion.predicate())
&& new_object.is_identical_to(&assertion.object())
{
Ok(self.clone())
} else {
Ok(Envelope::new_assertion(new_predicate, new_object))
}
}
_ => Ok(self.clone()),
}
}
/// Returns a new envelope with encrypted nodes decrypted using the
/// provided keys.
///
/// This function walks the envelope hierarchy and attempts to decrypt any
/// encrypted nodes using the provided set of symmetric keys. Each key is
/// tried in sequence until one succeeds or all fail.
///
/// If no nodes can be decrypted, the original envelope is returned
/// unchanged.
///
/// This function is only available when the `encrypt` feature is enabled.
///
/// # Parameters
///
/// * `keys` - A slice of `SymmetricKey` values to use for decryption
///
/// # Returns
///
/// A new envelope with encrypted nodes decrypted where possible.
///
/// # Examples
///
/// ```
/// # use bc_envelope::prelude::*;
/// # use bc_components::SymmetricKey;
/// let key1 = SymmetricKey::new();
/// let key2 = SymmetricKey::new();
///
/// let envelope = Envelope::new("Alice")
/// .add_assertion("knows", "Bob")
/// .add_assertion("age", 30);
///
/// // Encrypt different parts with different keys
/// let encrypted = envelope.elide_removing_set_with_action(
/// &std::collections::HashSet::from([envelope
/// .assertion_with_predicate("knows")
/// .unwrap()
/// .digest()]),
/// &ObscureAction::Encrypt(key1.clone()),
/// );
///
/// // Decrypt with a set of keys
/// let decrypted = encrypted.walk_decrypt(&[key1, key2]);
///
/// // The decrypted envelope should match the original
/// assert!(decrypted.is_equivalent_to(&envelope));
/// ```
#[cfg(feature = "encrypt")]
pub fn walk_decrypt(&self, keys: &[SymmetricKey]) -> Self {
match self.case() {
EnvelopeCase::Encrypted(_) => {
// Try each key until one works
for key in keys {
if let Ok(decrypted) = self.decrypt_subject(key) {
return decrypted.walk_decrypt(keys);
}
}
// No key worked, return unchanged
self.clone()
}
EnvelopeCase::Node { subject, assertions, .. } => {
// Recursively decrypt subject and assertions
let new_subject = subject.walk_decrypt(keys);
let new_assertions: Vec<_> =
assertions.iter().map(|a| a.walk_decrypt(keys)).collect();
if new_subject.is_identical_to(subject)
&& new_assertions
.iter()
.zip(assertions.iter())
.all(|(a, b)| a.is_identical_to(b))
{
self.clone()
} else {
Self::new_with_unchecked_assertions(
new_subject,
new_assertions,
)
}
}
EnvelopeCase::Wrapped { envelope, .. } => {
let new_envelope = envelope.walk_decrypt(keys);
if new_envelope.is_identical_to(envelope) {
self.clone()
} else {
new_envelope.wrap()
}
}
EnvelopeCase::Assertion(assertion) => {
// Recursively decrypt predicate and object
let new_predicate = assertion.predicate().walk_decrypt(keys);
let new_object = assertion.object().walk_decrypt(keys);
if new_predicate.is_identical_to(&assertion.predicate())
&& new_object.is_identical_to(&assertion.object())
{
self.clone()
} else {
Envelope::new_assertion(new_predicate, new_object)
}
}
_ => self.clone(),
}
}
/// Returns a new envelope with compressed nodes decompressed.
///
/// This function walks the envelope hierarchy and decompresses nodes that:
/// - Are compressed, AND
/// - Match the target digest set (if provided), OR all compressed nodes if
/// no target set is provided
///
/// If no nodes can be decompressed, the original envelope is returned
/// unchanged.
///
/// This function is only available when the `compress` feature is enabled.
///
/// # Parameters
///
/// * `target_digests` - Optional set of digests to filter by. If `None`,
/// all compressed nodes will be decompressed.
///
/// # Returns
///
/// A new envelope with compressed nodes decompressed where they match the
/// criteria.
///
/// # Examples
///
/// ```
/// # use bc_envelope::prelude::*;
/// # use std::collections::HashSet;
/// let envelope = Envelope::new("Alice")
/// .add_assertion("knows", "Bob")
/// .add_assertion("bio", "A".repeat(1000));
///
/// // Compress one assertion
/// let bio_assertion = envelope.assertion_with_predicate("bio").unwrap();
/// let bio_digest = bio_assertion.digest();
/// let mut target = HashSet::new();
/// target.insert(bio_digest);
///
/// let compressed = envelope
/// .elide_removing_set_with_action(&target, &ObscureAction::Compress);
///
/// // Decompress just the targeted node
/// let decompressed = compressed.walk_decompress(Some(&target));
///
/// // The decompressed envelope should match the original
/// assert!(decompressed.is_equivalent_to(&envelope));
/// ```
#[cfg(feature = "compress")]
pub fn walk_decompress(
&self,
target_digests: Option<&HashSet<Digest>>,
) -> Self {
match self.case() {
EnvelopeCase::Compressed(_) => {
// Check if this node matches the target (if target specified)
let matches_target = target_digests
.map(|targets| targets.contains(&self.digest()))
.unwrap_or(true);
if matches_target {
// Try to decompress
if let Ok(decompressed) = self.decompress() {
return decompressed.walk_decompress(target_digests);
}
}
// Either doesn't match target or decompress failed
self.clone()
}
EnvelopeCase::Node { subject, assertions, .. } => {
// Recursively decompress subject and assertions
let new_subject = subject.walk_decompress(target_digests);
let new_assertions: Vec<_> = assertions
.iter()
.map(|a| a.walk_decompress(target_digests))
.collect();
if new_subject.is_identical_to(subject)
&& new_assertions
.iter()
.zip(assertions.iter())
.all(|(a, b)| a.is_identical_to(b))
{
self.clone()
} else {
Self::new_with_unchecked_assertions(
new_subject,
new_assertions,
)
}
}
EnvelopeCase::Wrapped { envelope, .. } => {
let new_envelope = envelope.walk_decompress(target_digests);
if new_envelope.is_identical_to(envelope) {
self.clone()
} else {
new_envelope.wrap()
}
}
EnvelopeCase::Assertion(assertion) => {
// Recursively decompress predicate and object
let new_predicate =
assertion.predicate().walk_decompress(target_digests);
let new_object =
assertion.object().walk_decompress(target_digests);
if new_predicate.is_identical_to(&assertion.predicate())
&& new_object.is_identical_to(&assertion.object())
{
self.clone()
} else {
Envelope::new_assertion(new_predicate, new_object)
}
}
_ => self.clone(),
}
}
}