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
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
use crate::{
    Assertion, Envelope, EnvelopeEncodable, Error, Result,
    base::envelope::EnvelopeCase, known_values,
};

/// Support for adding vendor-specific attachments to Gordian Envelopes.
///
/// This module extends Gordian Envelope with the ability to add vendor-specific
/// attachments to an envelope. Attachments provide a standardized way for
/// different applications to include their own data in an envelope without
/// interfering with the main data structure or with other attachments.
///
/// Each attachment has:
/// * A payload (arbitrary data)
/// * A required vendor identifier (typically a reverse domain name)
/// * An optional conformsTo URI that indicates the format of the attachment
///
/// This allows for a common envelope format that can be extended by different
/// vendors while maintaining interoperability.
///
/// # Example
///
/// ```
/// use bc_envelope::prelude::*;
///
/// // Create a base envelope
/// let envelope = Envelope::new("Alice").add_assertion("knows", "Bob");
///
/// // Add a vendor-specific attachment
/// let with_attachment = envelope.add_attachment(
///     "Custom data for this envelope",
///     "com.example",
///     Some("https://example.com/attachment-format/v1"),
/// );
///
/// // The attachment is added as an assertion with the 'attachment' predicate
/// assert!(
///     !with_attachment
///         .assertions_with_predicate(known_values::ATTACHMENT)
///         .is_empty()
/// );
///
/// // The attachment can be extracted later
/// let attachment = with_attachment.attachments().unwrap()[0].clone();
/// let payload = attachment.attachment_payload().unwrap();
/// let vendor = attachment.attachment_vendor().unwrap();
/// let format = attachment.attachment_conforms_to().unwrap();
///
/// assert_eq!(payload.format_flat(), r#""Custom data for this envelope""#);
/// assert_eq!(vendor, "com.example");
/// assert_eq!(
///     format,
///     Some("https://example.com/attachment-format/v1".to_string())
/// );
/// ```
/// Methods for creating and accessing attachments at the assertion level
impl Assertion {
    /// Creates a new attachment assertion.
    ///
    /// An attachment assertion consists of:
    /// * The predicate `known_values::ATTACHMENT`
    /// * An object that is a wrapped envelope containing:
    ///   * The payload (as the subject)
    ///   * A required `'vendor': String` assertion
    ///   * An optional `'conformsTo': String` assertion
    ///
    /// See [BCR-2023-006](https://github.com/BlockchainCommons/Research/blob/master/papers/bcr-2023-006-envelope-attachment.md)
    /// for the detailed specification.
    ///
    /// # Parameters
    ///
    /// * `payload` - The content of the attachment
    /// * `vendor` - A string that uniquely identifies the vendor (typically a
    ///   reverse domain name)
    /// * `conforms_to` - An optional URI that identifies the format of the
    ///   attachment
    ///
    /// # Returns
    ///
    /// A new attachment assertion
    ///
    /// # Examples
    ///
    /// Example:
    ///
    /// Create an attachment assertion that contains vendor-specific data,
    /// then use it to access the payload, vendor ID, and conformsTo value.
    ///
    /// The assertion will have a predicate of "attachment" and an object that's
    /// a wrapped envelope containing the payload with vendor and conformsTo
    /// assertions added to it.
    pub fn new_attachment(
        payload: impl EnvelopeEncodable,
        vendor: &str,
        conforms_to: Option<&str>,
    ) -> Self {
        let conforms_to: Option<String> = conforms_to.map(|c| c.to_string());
        Self::new(
            known_values::ATTACHMENT,
            payload
                .into_envelope()
                .wrap()
                .add_assertion(known_values::VENDOR, vendor.to_string())
                .add_optional_assertion(known_values::CONFORMS_TO, conforms_to),
        )
    }

    /// Returns the payload of an attachment assertion.
    ///
    /// This extracts the subject of the wrapped envelope that is the object of
    /// this attachment assertion.
    ///
    /// # Returns
    ///
    /// The payload envelope
    ///
    /// # Errors
    ///
    /// Returns an error if the assertion is not a valid attachment assertion
    pub fn attachment_payload(&self) -> Result<Envelope> {
        self.object().try_unwrap()
    }

    /// Returns the vendor identifier of an attachment assertion.
    ///
    /// # Returns
    ///
    /// The vendor string
    ///
    /// # Errors
    ///
    /// Returns an error if the assertion is not a valid attachment assertion
    pub fn attachment_vendor(&self) -> Result<String> {
        self.object()
            .extract_object_for_predicate(known_values::VENDOR)
    }

    /// Returns the optional conformsTo URI of an attachment assertion.
    ///
    /// # Returns
    ///
    /// The conformsTo string if present, or None
    ///
    /// # Errors
    ///
    /// Returns an error if the assertion is not a valid attachment assertion
    pub fn attachment_conforms_to(&self) -> Result<Option<String>> {
        self.object()
            .extract_optional_object_for_predicate(known_values::CONFORMS_TO)
    }

    /// Validates that an assertion is a proper attachment assertion.
    ///
    /// This ensures:
    /// - The attachment assertion's predicate is `known_values::ATTACHMENT`
    /// - The attachment assertion's object is an envelope
    /// - The attachment assertion's object has a `'vendor': String` assertion
    /// - The attachment assertion's object has an optional `'conformsTo':
    ///   String` assertion
    ///
    /// # Returns
    ///
    /// Ok(()) if the assertion is a valid attachment assertion
    ///
    /// # Errors
    ///
    /// Returns `EnvelopeError::InvalidAttachment` if the assertion is not a
    /// valid attachment assertion
    pub fn validate_attachment(&self) -> Result<()> {
        let payload = self.attachment_payload()?;
        let vendor = self.attachment_vendor()?;
        let conforms_to: Option<String> = self.attachment_conforms_to()?;
        let assertion = Assertion::new_attachment(
            payload,
            vendor.as_str(),
            conforms_to.as_deref(),
        );
        let e: Envelope = assertion.to_envelope();
        if !e.is_equivalent_to(&self.clone().to_envelope()) {
            return Err(Error::InvalidAttachment);
        }
        Ok(())
    }
}

/// Methods for creating attachment envelopes
impl Envelope {
    /// Creates a new envelope with an attachment as its subject.
    ///
    /// This creates an envelope whose subject is an attachment assertion, using
    /// the provided payload, vendor, and optional conformsTo URI.
    ///
    /// # Parameters
    ///
    /// * `payload` - The content of the attachment
    /// * `vendor` - A string that uniquely identifies the vendor (typically a
    ///   reverse domain name)
    /// * `conforms_to` - An optional URI that identifies the format of the
    ///   attachment
    ///
    /// # Returns
    ///
    /// A new envelope with the attachment as its subject
    ///
    /// # Examples
    ///
    /// ```
    /// use bc_envelope::{base::envelope::EnvelopeCase, prelude::*};
    ///
    /// // Create an attachment envelope
    /// let envelope = Envelope::new_attachment(
    ///     "Attachment data",
    ///     "com.example",
    ///     Some("https://example.com/format/v1"),
    /// );
    ///
    /// // The envelope is an assertion
    /// assert!(matches!(envelope.case(), EnvelopeCase::Assertion(_)));
    /// ```
    pub fn new_attachment(
        payload: impl EnvelopeEncodable,
        vendor: &str,
        conforms_to: Option<&str>,
    ) -> Self {
        Assertion::new_attachment(payload, vendor, conforms_to).to_envelope()
    }

    /// Returns a new envelope with an added `'attachment': Envelope` assertion.
    ///
    /// This adds an attachment assertion to an existing envelope.
    ///
    /// # Parameters
    ///
    /// * `payload` - The content of the attachment
    /// * `vendor` - A string that uniquely identifies the vendor (typically a
    ///   reverse domain name)
    /// * `conforms_to` - An optional URI that identifies the format of the
    ///   attachment
    ///
    /// # Returns
    ///
    /// A new envelope with the attachment assertion added
    ///
    /// # Examples
    ///
    /// ```
    /// use bc_envelope::prelude::*;
    ///
    /// // Create a base envelope
    /// let envelope = Envelope::new("User data").add_assertion("name", "Alice");
    ///
    /// // Add an attachment
    /// let with_attachment = envelope.add_attachment(
    ///     "Vendor-specific metadata",
    ///     "com.example",
    ///     Some("https://example.com/metadata/v1"),
    /// );
    ///
    /// // The original envelope is unchanged
    /// assert_eq!(envelope.assertions().len(), 1);
    ///
    /// // The new envelope has an additional attachment assertion
    /// assert_eq!(with_attachment.assertions().len(), 2);
    /// assert!(
    ///     with_attachment
    ///         .assertions_with_predicate(known_values::ATTACHMENT)
    ///         .len()
    ///         > 0
    /// );
    /// ```
    pub fn add_attachment(
        &self,
        payload: impl EnvelopeEncodable,
        vendor: &str,
        conforms_to: Option<&str>,
    ) -> Self {
        self.add_assertion_envelope(Assertion::new_attachment(
            payload,
            vendor,
            conforms_to,
        ))
        .unwrap()
    }
}

/// Methods for accessing attachments in envelopes
impl Envelope {
    /// Returns the payload of an attachment envelope.
    ///
    /// # Returns
    ///
    /// The payload envelope
    ///
    /// # Errors
    ///
    /// Returns an error if the envelope is not a valid attachment envelope
    pub fn attachment_payload(&self) -> Result<Self> {
        if let EnvelopeCase::Assertion(assertion) = self.case() {
            Ok(assertion.attachment_payload()?)
        } else {
            Err(Error::InvalidAttachment)
        }
    }

    /// Returns the vendor identifier of an attachment envelope.
    ///
    /// # Returns
    ///
    /// The vendor string
    ///
    /// # Errors
    ///
    /// Returns an error if the envelope is not a valid attachment envelope
    pub fn attachment_vendor(&self) -> Result<String> {
        if let EnvelopeCase::Assertion(assertion) = self.case() {
            Ok(assertion.attachment_vendor()?)
        } else {
            Err(Error::InvalidAttachment)
        }
    }

    /// Returns the optional conformsTo URI of an attachment envelope.
    ///
    /// # Returns
    ///
    /// The conformsTo string if present, or None
    ///
    /// # Errors
    ///
    /// Returns an error if the envelope is not a valid attachment envelope
    pub fn attachment_conforms_to(&self) -> Result<Option<String>> {
        if let EnvelopeCase::Assertion(assertion) = self.case() {
            Ok(assertion.attachment_conforms_to()?)
        } else {
            Err(Error::InvalidAttachment)
        }
    }

    /// Searches the envelope's assertions for attachments that match the given
    /// vendor and conformsTo.
    ///
    /// This method finds all attachment assertions in the envelope that match
    /// the specified criteria:
    ///
    /// * If `vendor` is `None`, matches any vendor
    /// * If `conformsTo` is `None`, matches any conformsTo value
    /// * If both are `None`, matches all attachments
    ///
    /// # Parameters
    ///
    /// * `vendor` - Optional vendor identifier to match
    /// * `conforms_to` - Optional conformsTo URI to match
    ///
    /// # Returns
    ///
    /// A vector of matching attachment envelopes
    ///
    /// # Errors
    ///
    /// Returns an error if any of the envelope's attachments are invalid
    ///
    /// # Examples
    ///
    /// ```
    /// use bc_envelope::prelude::*;
    ///
    /// // Create an envelope with two attachments from the same vendor
    /// let envelope = Envelope::new("Data")
    ///     .add_attachment(
    ///         "Attachment 1",
    ///         "com.example",
    ///         Some("https://example.com/format/v1"),
    ///     )
    ///     .add_attachment(
    ///         "Attachment 2",
    ///         "com.example",
    ///         Some("https://example.com/format/v2"),
    ///     );
    ///
    /// // Find all attachments
    /// let all_attachments = envelope.attachments().unwrap();
    /// assert_eq!(all_attachments.len(), 2);
    ///
    /// // Find attachments by vendor
    /// let vendor_attachments = envelope
    ///     .attachments_with_vendor_and_conforms_to(Some("com.example"), None)
    ///     .unwrap();
    /// assert_eq!(vendor_attachments.len(), 2);
    ///
    /// // Find attachments by specific format
    /// let v1_attachments = envelope
    ///     .attachments_with_vendor_and_conforms_to(
    ///         None,
    ///         Some("https://example.com/format/v1"),
    ///     )
    ///     .unwrap();
    /// assert_eq!(v1_attachments.len(), 1);
    /// ```
    pub fn attachments_with_vendor_and_conforms_to(
        &self,
        vendor: Option<&str>,
        conforms_to: Option<&str>,
    ) -> Result<Vec<Self>> {
        let assertions =
            self.assertions_with_predicate(known_values::ATTACHMENT);
        for assertion in &assertions {
            Self::validate_attachment(assertion)?;
        }
        let matching_assertions: Vec<_> = assertions
            .into_iter()
            .filter(|assertion| {
                if let Some(vendor) = vendor
                    && let Ok(v) = assertion.attachment_vendor()
                    && v != vendor
                {
                    return false;
                }

                if let Some(conforms_to) = conforms_to {
                    if let Ok(Some(c)) = assertion.attachment_conforms_to() {
                        if c != conforms_to {
                            return false;
                        }
                    } else {
                        return false;
                    }
                }

                true
            })
            .collect();
        Result::Ok(matching_assertions)
    }

    /// Returns all attachments in the envelope.
    ///
    /// This is equivalent to calling
    /// `attachments_with_vendor_and_conforms_to(None, None)`.
    ///
    /// # Returns
    ///
    /// A vector of all attachment envelopes
    ///
    /// # Errors
    ///
    /// Returns an error if any of the envelope's attachments are invalid
    pub fn attachments(&self) -> Result<Vec<Self>> {
        self.attachments_with_vendor_and_conforms_to(None::<&str>, None::<&str>)
    }

    /// Validates that an envelope is a proper attachment envelope.
    ///
    /// This ensures the envelope is an assertion envelope with the predicate
    /// `attachment` and the required structure for an attachment.
    ///
    /// # Returns
    ///
    /// Ok(()) if the envelope is a valid attachment envelope
    ///
    /// # Errors
    ///
    /// Returns `EnvelopeError::InvalidAttachment` if the envelope is not a
    /// valid attachment envelope
    pub fn validate_attachment(&self) -> Result<()> {
        if let EnvelopeCase::Assertion(assertion) = self.case() {
            assertion.validate_attachment()?;
            Ok(())
        } else {
            Err(Error::InvalidAttachment)
        }
    }

    /// Finds a single attachment matching the given vendor and conformsTo.
    ///
    /// This works like `attachments_with_vendor_and_conforms_to` but returns a
    /// single attachment envelope rather than a vector. It requires that
    /// exactly one attachment matches the criteria.
    ///
    /// # Parameters
    ///
    /// * `vendor` - Optional vendor identifier to match
    /// * `conforms_to` - Optional conformsTo URI to match
    ///
    /// # Returns
    ///
    /// The matching attachment envelope
    ///
    /// # Errors
    ///
    /// * Returns `EnvelopeError::NonexistentAttachment` if no attachments match
    /// * Returns `EnvelopeError::AmbiguousAttachment` if more than one
    ///   attachment matches
    /// * Returns an error if any of the envelope's attachments are invalid
    ///
    /// # Examples
    ///
    /// ```
    /// use bc_envelope::prelude::*;
    ///
    /// // Create an envelope with an attachment
    /// let envelope = Envelope::new("Data").add_attachment(
    ///     "Metadata",
    ///     "com.example",
    ///     Some("https://example.com/format/v1"),
    /// );
    ///
    /// // Find a specific attachment by vendor and format
    /// let attachment = envelope
    ///     .attachment_with_vendor_and_conforms_to(
    ///         Some("com.example"),
    ///         Some("https://example.com/format/v1"),
    ///     )
    ///     .unwrap();
    ///
    /// // Access the attachment payload
    /// let payload = attachment.attachment_payload().unwrap();
    /// assert_eq!(payload.extract_subject::<String>().unwrap(), "Metadata");
    /// ```
    pub fn attachment_with_vendor_and_conforms_to(
        &self,
        vendor: Option<&str>,
        conforms_to: Option<&str>,
    ) -> Result<Self> {
        let attachments =
            self.attachments_with_vendor_and_conforms_to(vendor, conforms_to)?;
        if attachments.is_empty() {
            return Err(Error::NonexistentAttachment);
        }
        if attachments.len() > 1 {
            return Err(Error::AmbiguousAttachment);
        }
        Ok(attachments.first().unwrap().clone())
    }
}