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

impl Assertion {
    /// Creates an attachment assertion. See:
    /// [BCR-2023-006](https://github.com/BlockchainCommons/Research/blob/master/papers/bcr-2023-006-envelope-attachment.md)
    pub fn new_attachment<A>(payload: A, vendor: &str, conforms_to: Option<&str>) -> Self
    where
        A: EnvelopeEncodable,
    {
        let conforms_to: Option<String> = conforms_to.map(|c| c.to_string());
        Self::new(
            known_values::ATTACHMENT,
            payload.envelope()
                .wrap_envelope()
                .add_assertion(known_values::VENDOR, vendor.to_string())
                .add_optional_assertion(known_values::CONFORMS_TO, conforms_to)
        )
    }

    /// Returns the payload of the given attachment assertion.
    pub fn attachment_payload(&self) -> Result<Envelope, EnvelopeError> {
        self.object().unwrap_envelope()
    }

    /// Returns the `vendor` of the given attachment assertion.
    pub fn attachment_vendor(&self) -> anyhow::Result<String> {
        self.object().extract_object_for_predicate(known_values::VENDOR)
    }

    /// Returns the `conformsTo` of the given attachment assertion.
    pub fn attachment_conforms_to(&self) -> anyhow::Result<Option<String>> {
        self.object().extract_optional_object_for_predicate(known_values::CONFORMS_TO)
    }

    /// Validates the given attachment assertion.
    ///
    /// 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.
    pub fn validate_attachment(&self) -> anyhow::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 = assertion.envelope();
        if !e.is_equivalent_to(self.clone().envelope()) {
            anyhow::bail!(EnvelopeError::InvalidAttachment);
        }
        Ok(())
    }
}

impl Envelope {
    /// Returns a new attachment envelope.
    ///
    /// The payload envelope has a `'vendor': String` assertion and an optional
    /// `'conformsTo': String` assertion.
    pub fn new_attachment<A>(payload: A, vendor: &str, conforms_to: Option<&str>) -> Self
    where
        A: EnvelopeEncodable,
    {
        Assertion::new_attachment(payload, vendor, conforms_to).envelope()
    }

    /// Returns a new envelope with an added `'attachment': Envelope` assertion.
    ///
    /// The payload envelope has a `'vendor': String` assertion and an optional
    /// `'conformsTo': String` assertion.
    pub fn add_attachment<A>(&self, payload: A, vendor: &str, conforms_to: Option<&str>) -> Self
    where
        A: EnvelopeEncodable,
    {
        self.add_assertion_envelope(
            Assertion::new_attachment(payload, vendor, conforms_to).envelope()
        ).unwrap()
    }
}

impl Envelope {
    /// Returns the payload of the given attachment envelope.
    pub fn attachment_payload(&self) -> Result<Self, EnvelopeError> {
        if let EnvelopeCase::Assertion(assertion) = self.case() {
            Ok(assertion.attachment_payload()?)
        } else {
            Err(EnvelopeError::InvalidAttachment)
        }
    }

    /// Returns the `vendor` of the given attachment envelope.
    pub fn attachment_vendor(&self) -> anyhow::Result<String> {
        if let EnvelopeCase::Assertion(assertion) = self.case() {
            Ok(assertion.clone().attachment_vendor()?)
        } else {
            anyhow::bail!(EnvelopeError::InvalidAttachment);
        }
    }

    /// Returns the `conformsTo` of the given attachment envelope.
    pub fn attachment_conforms_to(&self) -> anyhow::Result<Option<String>> {
        if let EnvelopeCase::Assertion(assertion) = self.case() {
            Ok(assertion.clone().attachment_conforms_to()?)
        } else {
            anyhow::bail!(EnvelopeError::InvalidAttachment);
        }
    }

    /// Searches the envelope's attachments for any that match the given
    /// `vendor` and `conformsTo`.
    ///
    /// If `vendor` is `None`, matches any vendor. If `conformsTo` is `None`,
    /// matches any `conformsTo`. If both are `None`, matches any attachment. On
    /// success, returns a vector of matching attachments. Returns an error if
    /// any of the attachments are invalid.
    pub fn attachments_with_vendor_and_conforms_to(&self, vendor: Option<&str>, conforms_to: Option<&str>)
    -> anyhow::Result<Vec<Self>>
    {
        let assertions = self.assertions_with_predicate(known_values::ATTACHMENT);
        for assertion in assertions.clone() {
            Self::validate_attachment(&assertion)?;
        }
        let matching_assertions: Vec<_> = assertions
            .into_iter()
            .filter(|assertion| {
                if let Some(vendor) = vendor {
                    if let Ok(v) = assertion.clone().attachment_vendor() {
                        if v != vendor {
                            return false;
                        }
                    }
                }
                if let Some(conforms_to) = conforms_to {
                    if let Ok(c) = assertion.clone().attachment_conforms_to() {
                        if let Some(c) = c {
                            if c != conforms_to {
                                return false;
                            }
                        } else {
                            return false;
                        }
                    }
                }
                true
            })
            .collect();
        anyhow::Result::Ok(matching_assertions)
    }

    pub fn attachments(&self) -> anyhow::Result<Vec<Self>> {
        self.attachments_with_vendor_and_conforms_to(None::<&str>, None::<&str>)
    }

    /// Validates the given attachment envelope.
    ///
    /// Ensures:
    /// - The attachment envelope is a valid assertion envelope.
    /// - The attachment envelope's predicate is `known_values::ATTACHMENT`.
    /// - The attachment envelope's object is an envelope.
    /// - The attachment envelope's object has a `'vendor': String` assertion.
    /// - The attachment envelope's object has an optional `'conformsTo': String` assertion.
    pub fn validate_attachment(&self) -> anyhow::Result<()> {
        if let EnvelopeCase::Assertion(assertion) = self.case() {
            assertion.validate_attachment()?;
            Ok(())
        } else {
            anyhow::bail!(EnvelopeError::InvalidAttachment);
        }
    }

    /// Searches the envelope's attachments for any that match the given
    /// `vendor` and `conformsTo`.
    ///
    /// If `vendor` is `None`, matches any vendor. If `conformsTo` is `None`,
    /// matches any `conformsTo`. If both are `None`, matches any attachment. On
    /// success, returns the first matching attachment. Returns an error if
    /// more than one attachment matches, or if any of the attachments are
    /// invalid.
    pub fn attachment_with_vendor_and_conforms_to(&self, vendor: Option<&str>, conforms_to: Option<&str>)
    -> anyhow::Result<Self>
    {
        let attachments = self.attachments_with_vendor_and_conforms_to(vendor, conforms_to)?;
        if attachments.is_empty() {
            anyhow::bail!(EnvelopeError::NonexistentAttachment);
        }
        if attachments.len() > 1 {
            anyhow::bail!(EnvelopeError::AmbiguousAttachment);
        }
        Ok(attachments.first().unwrap().clone())
    }
}