bc-envelope 0.43.0

Gordian Envelope for Rust.
Documentation
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
#[cfg(not(feature = "multithreaded"))]
use std::rc::Rc as RefCounted;
#[cfg(feature = "multithreaded")]
use std::sync::Arc as RefCounted;

#[cfg(feature = "compress")]
use bc_components::Compressed;
#[cfg(feature = "encrypt")]
use bc_components::EncryptedMessage;
use bc_components::{Digest, DigestProvider};
use dcbor::prelude::*;

#[cfg(feature = "known_value")]
use crate::extension::KnownValue;
use crate::{EnvelopeEncodable, Error, Result, base::Assertion};

/// A flexible container for structured data with built-in integrity
/// verification.
///
/// Gordian Envelope is the primary data structure of this crate. It provides a
/// way to encapsulate and organize data with cryptographic integrity, privacy
/// features, and selective disclosure capabilities.
///
/// Key characteristics of envelopes:
///
/// - **Immutability**: Envelopes are immutable. Operations that appear to
///   "modify" an envelope actually create a new envelope. This immutability is
///   fundamental to maintaining the integrity of the envelope's digest tree.
///
/// - **O(1) Cloning**: Envelopes use reference counting (`Rc` or `Arc` when the
///   `multithreaded` feature is enabled) and structure sharing to enable
///   efficient O(1) cloning of an `Envelope` or recursively, any `Envelope`s it
///   contains. Cloning an `Envelope` simply increments the reference count,
///   allowing multiple owners without duplicating the underlying data.
///
/// - **Semantic Structure**: Envelopes can represent various semantic
///   relationships through subjects, predicates, and objects (similar to RDF
///   triples).
///
/// - **Digest Tree**: Each envelope maintains a Merkle-like digest tree that
///   ensures the integrity of its contents and enables verification of
///   individual parts.
///
/// - **Privacy Features**: Envelopes support selective disclosure through
///   elision, encryption, and compression of specific parts, while maintaining
///   the overall integrity of the structure.
///
/// - **Deterministic Representation**: Envelopes use deterministic CBOR
///   encoding to ensure consistent serialization across platforms.
///
/// The Gordian Envelope specification is defined in an IETF Internet Draft, and
/// this implementation closely follows that specification.
///
/// # Example
///
/// ```
/// use bc_envelope::prelude::*;
///
/// // Create an envelope representing a person
/// let person = Envelope::new("person")
///     .add_assertion("name", "Alice")
///     .add_assertion("age", 30)
///     .add_assertion("email", "alice@example.com");
///
/// // Create a partially redacted version by eliding the email
/// let redacted = person.elide_removing_target(
///     &person.assertion_with_predicate("email").unwrap(),
/// );
///
/// // The digest of both envelopes remains the same
/// assert_eq!(person.digest(), redacted.digest());
/// ```
#[derive(Debug, Clone, Eq)]
pub struct Envelope(RefCounted<EnvelopeCase>);

impl Envelope {
    /// Returns a reference to the underlying envelope case.
    ///
    /// The `EnvelopeCase` enum represents the specific structural variant of
    /// this envelope. This method provides access to that underlying
    /// variant for operations that need to differentiate between the
    /// different envelope types.
    ///
    /// # Returns
    ///
    /// A reference to the `EnvelopeCase` that defines this envelope's
    /// structure.
    pub fn case(&self) -> &EnvelopeCase { &self.0 }
}

/// Conversion from `EnvelopeCase` to `Envelope`.
///
/// This allows creating an envelope directly from an envelope case variant.
impl From<EnvelopeCase> for Envelope {
    fn from(case: EnvelopeCase) -> Self { Self(RefCounted::new(case)) }
}

/// Conversion from `&Envelope` to `Envelope`.
///
/// This creates a clone of the envelope. Since envelopes use reference
/// counting, this is a relatively inexpensive operation.
impl From<&Envelope> for Envelope {
    fn from(envelope: &Envelope) -> Self { envelope.clone() }
}

/// The core structural variants of a Gordian Envelope.
///
/// Each variant of this enum represents a different structural form that an
/// envelope can take, as defined in the Gordian Envelope IETF Internet Draft.
/// The different cases provide different capabilities and serve different
/// purposes in the envelope ecosystem.
///
/// The `EnvelopeCase` is the internal representation of an envelope's
/// structure. While each case has unique properties, they all maintain a digest
/// that ensures the integrity of the envelope.
///
/// It is advised to use the other Envelop APIs for most uses. Please see the
/// queries module for more information on how to interact with envelopes.
#[derive(Debug, PartialEq, Eq)]
pub enum EnvelopeCase {
    /// Represents an envelope with a subject and one or more assertions.
    ///
    /// A node is the fundamental structural component for building complex data
    /// structures with Gordian Envelope. It consists of a subject and a set of
    /// assertions about that subject.
    ///
    /// The digest of a node is derived from the digests of its subject and all
    /// assertions, ensuring that any change to the node or its components would
    /// result in a different digest.
    Node {
        /// The subject of the node
        subject: Envelope,
        /// The assertions attached to the subject
        assertions: Vec<Envelope>,
        /// The digest of the node
        digest: Digest,
    },

    /// Represents an envelope containing a primitive CBOR value.
    ///
    /// A leaf is the simplest form of envelope, containing a single CBOR value
    /// such as a string, number, or boolean. Leaves are the terminal nodes in
    /// the envelope structure.
    ///
    /// The digest of a leaf is derived directly from its CBOR representation.
    Leaf {
        /// The CBOR value contained in the leaf
        cbor: CBOR,
        /// The digest of the leaf
        digest: Digest,
    },

    /// Represents an envelope that wraps another envelope.
    ///
    /// Wrapping provides a way to encapsulate an entire envelope as the subject
    /// of another envelope, enabling hierarchical structures and metadata
    /// attachment.
    ///
    /// The digest of a wrapped envelope is derived from the digest of the
    /// envelope it wraps.
    Wrapped {
        /// The envelope being wrapped
        envelope: Envelope,
        /// The digest of the wrapped envelope
        digest: Digest,
    },

    /// Represents a predicate-object assertion.
    ///
    /// An assertion is a statement about a subject, consisting of a predicate
    /// (what is being asserted) and an object (the value of the assertion).
    /// Assertions are attached to envelope subjects to form semantic
    /// statements.
    ///
    /// For example, in the statement "Alice hasEmail alice@example.com":
    /// - The subject is "Alice"
    /// - The predicate is "hasEmail"
    /// - The object is "alice@example.com"
    Assertion(Assertion),

    /// Represents an envelope that has been elided, leaving only its digest.
    ///
    /// Elision is a key privacy feature of Gordian Envelope, allowing parts of
    /// an envelope to be removed while maintaining the integrity of the digest
    /// tree. This enables selective disclosure of information.
    Elided(Digest),

    /// Represents a value from a namespace of unsigned integers used for
    /// ontological concepts.
    ///
    /// Known Values are 64-bit unsigned integers used to represent stand-alone
    /// ontological concepts like relationships (`isA`, `containedIn`),
    /// classes (`Seed`, `PrivateKey`), or enumerated values (`MainNet`,
    /// `OK`). They provide a compact, deterministic alternative to URIs for
    /// representing common predicates and values.
    ///
    /// Using Known Values instead of strings for common predicates offers
    /// several advantages:
    /// - More compact representation (integers vs. long strings/URIs)
    /// - Standardized semantics across implementations
    /// - Deterministic encoding for cryptographic operations
    /// - Resistance to manipulation attacks that target string representations
    ///
    /// Known Values are displayed with single quotes, e.g., `'isA'` or by their
    /// numeric value like `'1'` (when no name is assigned).
    ///
    /// This variant is only available when the `known_value` feature is
    /// enabled.
    #[cfg(feature = "known_value")]
    KnownValue {
        /// The Known Value instance containing the integer value and optional
        /// name
        value: KnownValue,
        /// The digest of the known value
        digest: Digest,
    },

    /// Represents an envelope that has been encrypted.
    ///
    /// Encryption is a privacy feature that allows parts of an envelope to be
    /// encrypted while maintaining the integrity of the digest tree. The
    /// encrypted content can only be accessed by those with the appropriate
    /// key.
    ///
    /// This variant is only available when the `encrypt` feature is enabled.
    #[cfg(feature = "encrypt")]
    Encrypted(EncryptedMessage),

    /// Represents an envelope that has been compressed.
    ///
    /// Compression reduces the size of an envelope while maintaining its full
    /// content and digest integrity. Unlike elision or encryption, compression
    /// doesn't restrict access to the content, but simply makes it more
    /// compact.
    ///
    /// This variant is only available when the `compress` feature is enabled.
    #[cfg(feature = "compress")]
    Compressed(Compressed),
}

/// Support for basic envelope creation.
impl Envelope {
    /// Creates an envelope with a `subject`, which
    /// can be any instance that implements ``EnvelopeEncodable``.
    pub fn new(subject: impl EnvelopeEncodable) -> Self {
        subject.into_envelope()
    }

    /// Creates an envelope with a `subject`, which
    /// can be any instance that implements ``EnvelopeEncodable``.
    ///
    /// If `subject` is `None`, returns a null envelope.
    pub fn new_or_null(subject: Option<impl EnvelopeEncodable>) -> Self {
        subject.map_or_else(Self::null, Self::new)
    }

    /// Creates an envelope with a `subject`, which
    /// can be any instance that implements ``EnvelopeEncodable``.
    ///
    /// If `subject` is `None`, returns `None`.
    pub fn new_or_none(
        subject: Option<impl EnvelopeEncodable>,
    ) -> Option<Self> {
        subject.map(Self::new)
    }

    /// Creates an assertion envelope with a `predicate` and `object`,
    /// each of which can be any instance that implements ``EnvelopeEncodable``.
    pub fn new_assertion(
        predicate: impl EnvelopeEncodable,
        object: impl EnvelopeEncodable,
    ) -> Self {
        Self::new_with_assertion(Assertion::new(predicate, object))
    }
}

/// Internal constructors
impl Envelope {
    pub(crate) fn new_with_unchecked_assertions(
        subject: Self,
        unchecked_assertions: Vec<Self>,
    ) -> Self {
        assert!(!unchecked_assertions.is_empty());
        let mut sorted_assertions = unchecked_assertions;
        sorted_assertions.sort_by_key(|a| a.digest());
        let mut digests = vec![subject.digest()];
        digests.extend(sorted_assertions.iter().map(|a| a.digest()));
        let digest = Digest::from_digests(&digests);
        (EnvelopeCase::Node { subject, assertions: sorted_assertions, digest })
            .into()
    }

    pub(crate) fn new_with_assertions(
        subject: Self,
        assertions: Vec<Self>,
    ) -> Result<Self> {
        if !assertions
            .iter()
            .all(|a| a.is_subject_assertion() || a.is_subject_obscured())
        {
            return Err(Error::InvalidFormat);
        }
        Ok(Self::new_with_unchecked_assertions(subject, assertions))
    }

    pub(crate) fn new_with_assertion(assertion: Assertion) -> Self {
        EnvelopeCase::Assertion(assertion).into()
    }

    #[cfg(feature = "known_value")]
    pub(crate) fn new_with_known_value(value: KnownValue) -> Self {
        let digest = value.digest();
        (EnvelopeCase::KnownValue { value, digest }).into()
    }

    #[cfg(feature = "encrypt")]
    pub(crate) fn new_with_encrypted(
        encrypted_message: EncryptedMessage,
    ) -> Result<Self> {
        if !encrypted_message.has_digest() {
            return Err(Error::MissingDigest);
        }
        Ok(EnvelopeCase::Encrypted(encrypted_message).into())
    }

    #[cfg(feature = "compress")]
    pub(crate) fn new_with_compressed(compressed: Compressed) -> Result<Self> {
        if !compressed.has_digest() {
            return Err(Error::MissingDigest);
        }
        Ok(EnvelopeCase::Compressed(compressed).into())
    }

    pub(crate) fn new_elided(digest: Digest) -> Self {
        EnvelopeCase::Elided(digest).into()
    }

    pub(crate) fn new_leaf(value: impl Into<CBOR>) -> Self {
        let cbor: CBOR = value.into();
        let digest = Digest::from_image(cbor.to_cbor_data());
        (EnvelopeCase::Leaf { cbor, digest }).into()
    }

    pub(crate) fn new_wrapped(envelope: Self) -> Self {
        let digest = Digest::from_digests(&[envelope.digest()]);
        (EnvelopeCase::Wrapped { envelope, digest }).into()
    }
}

impl AsRef<Envelope> for Envelope {
    fn as_ref(&self) -> &Envelope { self }
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "compress")]
    use bc_components::Compressed;
    use bc_components::DigestProvider;

    #[cfg(feature = "known_value")]
    use crate::extension::KnownValue;
    use crate::{Assertion, Envelope};

    #[test]
    fn test_any_envelope() {
        let e1 = Envelope::new_leaf("Hello");
        let e2 = Envelope::new("Hello");
        assert_eq!(e1.format(), e2.format());
        assert_eq!(e1.digest(), e2.digest());
    }

    #[cfg(feature = "known_value")]
    #[test]
    fn test_any_known_value() {
        let known_value = KnownValue::new(100);
        let e1 = Envelope::new_with_known_value(known_value.clone());
        let e2 = Envelope::new(known_value);
        assert_eq!(e1.format(), e2.format());
        assert_eq!(e1.digest(), e2.digest());
    }

    #[test]
    fn test_any_assertion() {
        let assertion = Assertion::new("knows", "Bob");
        let e1 = Envelope::new_with_assertion(assertion.clone());
        let e2 = Envelope::new(assertion);
        assert_eq!(e1.format(), e2.format());
        assert_eq!(e1.digest(), e2.digest());
    }

    #[test]
    fn test_any_encrypted() {
        //todo!()
    }

    #[cfg(feature = "compress")]
    #[test]
    fn test_any_compressed() {
        let data = "Hello".as_bytes();
        let digest = data.digest();
        let compressed = Compressed::from_decompressed_data(data, Some(digest));
        let e1 = Envelope::new_with_compressed(compressed.clone()).unwrap();
        let e2 = Envelope::try_from(compressed).unwrap();
        assert_eq!(e1.format(), e2.format());
        assert_eq!(e1.digest(), e2.digest());
    }

    #[test]
    fn test_any_cbor_encodable() {
        let e1 = Envelope::new_leaf(1);
        let e2 = Envelope::new(1);
        assert_eq!(e1.format(), e2.format());
        assert_eq!(e1.digest(), e2.digest());
    }
}