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
#![doc(html_root_url = "https://docs.rs/bc-envelope/0.13.0")]
#![warn(rust_2018_idioms)]

//! # Gordian Envelope: A Flexible Container for Structured Data
//!
//! ## Introduction
//!
//! The [Gordian
//! Envelope](https://www.blockchaincommons.com/introduction/Envelope-Intro/)
//! protocol specifies a structured format for hierarchical binary data focused
//! on the ability to transmit it in a privacy-focused way. Envelopes are
//! designed to facilitate "smart documents" and have a number of unique
//! features including: easy representation of a variety of semantic structures,
//! a built-in Merkle-like digest tree, deterministic representation using CBOR,
//! and the ability for the holder of a document to selectively encrypt or elide
//! specific parts of a document without invalidating the document structure
//! including the digest tree, or any cryptographic signatures that rely on it.
//!
//! ## Getting Started
//!
//! ```toml
//! [dependencies]
//! bc-envelope = "0.13.0"
//! ```
//!
//! ## Specification
//!
//! Gordian Envelope is currently specified in [this IETF Internet
//! Draft](https://datatracker.ietf.org/doc/draft-mcnally-envelope/).
//!
//! Envelopes are immutable. You create "mutations" by creating new envelopes
//! from old envelopes.
//!
//! # Basic Envelope Creation
//!
//! * [`Envelope::new`] Creates an envelope with a `subject`.
//! * [`Envelope::new_assertion`] Creates an assertion envelope with a
//!   `predicate` and `object`.
//!
//! # Adding Assertions
//!
//! ### Adding Assertions with a Predicate and Object
//!
//! * [`Envelope::add_assertion`] Adds an assertion to an envelope.
//! * [`Envelope::add_assertion_salted`] Adds an optionally salted assertion to
//!   an envelope.
//! * [`Envelope::add_optional_assertion`] Optionally adds an assertion to an
//!   envelope.
//!
//! ### Adding Assertions with an Assertion Envelope
//!
//! * [`Envelope::add_assertion_envelope`] Adds an assertion envelope to an
//!   envelope.
//! * [`Envelope::add_assertion_envelope_salted`] Adds an optionally salted
//!   assertion envelope to an envelope.
//! * [`Envelope::add_assertion_envelopes`] Adds a vector of assertion envelopes
//!   to an envelope.
//! * [`Envelope::add_optional_assertion_envelope_salted`] Optionally adds an
//!   assertion envelope to an envelope.
//!
//! # Removing and Replacing Assertions
//!
//! * [`Envelope::remove_assertion`] Removes an assertion from an envelope.
//! * [`Envelope::replace_assertion`] Replaces an assertion in an envelope.
//! * [`Envelope::replace_subject`] Replaces the subject of an envelope.
//!
//! # Queries
//!
//! ### Getting the basic parts of an envelope
//!
//! * [`Envelope::subject`] Returns the subject of an envelope.
//! * [`Envelope::predicate`] If the envelope’s subject is an assertion return
//!   its predicate, else return `None`.
//! * [`Envelope::object`] If the envelope’s subject is an assertion return its
//!   object, else return `None`.
//!
//! ### Getting assertions on an envelope
//!
//! * [`Envelope::assertions`] Returns the assertions of an envelope.
//! * [`Envelope::has_assertions`] Returns whether an envelope has assertions.
//! * [`Envelope::assertion`] If the envelope’s subject is an assertion return
//!   it, else return `None`.
//!
//! ### Getting the specific types of an envelope
//!
//! * [`Envelope::leaf`] The envelope’s leaf CBOR object, or `None` if the
//!   envelope is not a leaf.
//! * [`Envelope::known_value`] The envelope’s known value, or `None` if the
//!   envelope is not a known value.
//!
//! ### Determining the type of an envelope
//!
//! * [`Envelope::is_leaf`] Returns whether an envelope is a leaf.
//! * [`Envelope::is_node`] Returns whether an envelope is a node (whether it
//!   has at least one assertion).
//! * [`Envelope::is_wrapped`] Returns whether an envelope is wrapped.
//! * [`Envelope::is_known_value`] Returns whether an envelope is a known value.
//! * [`Envelope::is_assertion`] Returns whether an envelope is an assertion.
//! * [`Envelope::is_encrypted`] Returns whether an envelope is encrypted.
//! * [`Envelope::is_compressed`] Returns whether an envelope is compressed.
//! * [`Envelope::is_elided`] Returns whether an envelope is elided.
//!
//! ### Determining the type of an envelope’s subject
//!
//! * [`Envelope::is_subject_assertion`] Returns whether an envelope’s subject
//!   is an assertion.
//! * [`Envelope::is_subject_encrypted`] Returns whether an envelope’s subject
//!   is encrypted.
//! * [`Envelope::is_subject_compressed`] Returns whether an envelope’s subject
//!   is compressed.
//! * [`Envelope::is_subject_elided`] Returns whether an envelope’s subject is
//!   elided.
//! * [`Envelope::is_subject_obscured`] Returns whether an envelope’s subject is
//!   obscured.
//!
//! ### Getting assertions and parts of assertions
//!
//! * [`Envelope::assertion_with_predicate`] Returns the assertion with the
//!   given predicate.
//! * [`Envelope::assertions_with_predicate`] Returns all assertions with the
//!   given predicate.
//! * [`Envelope::object_for_predicate`] Returns the object of the assertion
//!   with the given predicate.
//! * [`Envelope::objects_for_predicate`] Returns the objects of all assertions
//!   with the matching predicate.
//! * [`Envelope::elements_count`] Returns the number of elements in the
//!   envelope.
//!
//! ### Extracting parts of envelopes as specific types
//!
//! * [`Envelope::extract_subject`] Returns the envelope’s subject, decoded as
//!   the given type.
//! * [`Envelope::extract_object_for_predicate`] Returns the object of the
//!   assertion with the given predicate, decoded as the given type.
//! * [`Envelope::extract_objects_for_predicate`] Returns the objects of all
//!   assertions with the matching predicate, decoded as the given type.
//!
//! ### Other queries
//!
//! * [`Envelope::is_internal`] Returns whether an envelope is internal, that
//!   is, if it has child elements.
//! * [`Envelope::is_obscured`] Returns whether an envelope is obscured (elided,
//!   encrypted, or compressed).
//!
//! # Wrapping and Unwrapping Envelopes
//!
//! * [`Envelope::wrap_envelope`] Wraps an envelope in a new envelope.
//! * [`Envelope::unwrap_envelope`] Unwraps an envelope.
//!
//! # Formatting Envelopes
//!
//! ### Envelope notation
//!
//! * [`Envelope::format`] Formats an envelope in envelope notation.
//! * [`Envelope::format_opt`] Formats an envelope in envelope notation, with
//!   optional annotations.
//!
//! ### Tree notation
//!
//! * [`Envelope::tree_format`] Formats an envelope in envelope tree notation.
//! * [`Envelope::tree_format_with_target`] Formats an envelope in envelope tree
//!   notation, highlighting a target set of elements.
//!
//! ### CBOR diagnostic notation
//!
//! * [`Envelope::diagnostic`] Formats an envelope in CBOR diagnostic notation.
//! * [`Envelope::diagnostic_opt`] Formats an envelope in CBOR diagnostic
//!   notation, with optional annotations.
//!
//! ### CBOR hexadecimal notation
//!
//! * [`Envelope::hex`] Formats an envelope in CBOR hexadecimal notation.
//! * [`Envelope::hex_opt`] Formats an envelope in CBOR hexadecimal notation,
//!   with optional annotations.
//!
//! # Working with the Digest Tree
//!
//! ### Semantic equivalence
//!
//! * [`bc_components::DigestProvider::digest`] Returns the digest of an
//!   envelope.
//! * [`Envelope::digests`] Returns the set of digests contained in the
//!   envelope’s elements, down to the specified level.
//! * [`Envelope::deep_digests`] Returns the set of all digests in the envelope.
//! * [`Envelope::shallow_digests`] Returns the set of all digests in the
//!   envelope, down to its second level.
//! * [`Envelope::is_equivalent_to`] Tests two envelopes for semantic
//!   equivalence.
//!
//! ### Structural identicality
//!
//! * [`Envelope::structural_digest`] Produce a value that will necessarily be
//!   different if two envelopes differ structurally, even if they are
//!   semantically equivalent.
//! * [`Envelope::is_identical_to`] Tests two envelopes for structural equality.
//!
//! # Signing and Verifying Signatures
//!
//! ### Signing
//!
//! * [`Envelope::sign_with`] Creates a signature for the envelope's subject and
//!   returns a new envelope with a `verifiedBy: Signature` assertion.
//! * [`Envelope::sign_with_opt`] Creates a signature for the envelope's subject
//!   and returns a new envelope with a `verifiedBy: Signature` assertion.
//! * [`Envelope::sign_with_keys`] Creates several signatures for the envelope's
//!   subject and returns a new envelope with additional `verifiedBy: Signature`
//!   assertions.
//! * [`Envelope::sign_with_keys_opt`] Creates several signatures for the
//!   envelope's subject and returns a new envelope with additional `verifiedBy:
//!   Signature` assertions.
//! * [`Envelope::sign_with_uncovered_assertions`] Creates a signature for the
//!   envelope's subject and returns a new envelope with a `verifiedBy:
//!   Signature` assertion.
//!
//! ### Verifying by returning a boolean
//!
//! * [`Envelope::is_verified_signature`] Returns whether the given signature is
//!   valid.
//! * [`Envelope::has_signature_from`] Returns whether the envelope's subject
//!   has a valid signature from the given public key.
//! * [`Envelope::has_signatures_from`] Returns whether the envelope's subject
//!   has a set of signatures.
//! * [`Envelope::has_signatures_from_threshold`] Returns whether the envelope's
//!   subject has some threshold of signatures.
//!
//! ### Verifying by returning a result
//!
//! * [`Envelope::verify_signature`] Checks whether the given signature is valid
//!   for the given public key.
//! * [`Envelope::verify_signature_from`] Checks whether the envelope's subject
//!   has a valid signature from the given public key.
//! * [`Envelope::verify_signatures_from`] Checks whether the envelope's subject
//!   has a set of signatures.
//! * [`Envelope::verify_signatures_from_threshold`] Checks whether the
//!   envelope's subject has some threshold of signatures.
//!
//! ### Helpers
//!
//! * [`Envelope::signatures`] Returns an array of `Signature`s from all of the
//!   envelope's `verifiedBy` predicates.
//! * [`Envelope::make_verified_by_signature`] Convenience constructor for a
//!   `verifiedBy: Signature` assertion envelope.
//!
//! # Splitting Envelopes with SSKR
//!
//! * [`Envelope::sskr_split`] Splits the envelope into a set of SSKR shares.
//! * [`Envelope::sskr_join`] Creates a new envelope resulting from the joining
//!   a set of envelopes split by SSKR.
//!
//! # Encryption
//!
//! * [`Envelope::encrypt_subject`] Returns a new envelope with its subject
//!   encrypted.
//! * [`Envelope::decrypt_subject`] Returns a new envelope with its subject
//!   decrypted.
//!
//! # Public Key Encryption
//!
//! * [`Envelope::add_recipient`] Returns a new envelope with an added
//!   `hasRecipient: SealedMessage` assertion.
//! * [`Envelope::recipients`] Returns an array of `SealedMessage`s from all of
//!   the envelope's `hasRecipient` assertions.
//! * [`Envelope::encrypt_subject_to_recipients`] Returns an new envelope with
//!   its subject encrypted and a `hasRecipient`
//! * [`Envelope::encrypt_subject_to_recipient`] Returns a new envelope with its
//!   subject encrypted and a `hasRecipient` assertion added for the
//!   `recipient`.
//! * [`Envelope::decrypt_to_recipient`] Returns a new envelope with its subject
//!   decrypted using the recipient's `PrivateKeyBase`.
//!
//! # Compression
//!
//! * [`Envelope::compress`] Returns the compressed variant of this envelope.
//! * [`Envelope::uncompress`] Returns the uncompressed variant of this
//!   envelope.
//! * [`Envelope::compress_subject`] Returns this envelope with its subject
//!   compressed.
//! * [`Envelope::uncompress_subject`] Returns this envelope with its subject
//!   uncompressed.
//!
//! # Eliding, Encrypting, or Compressing Parts of an Envelope
//!
//! * [`Envelope::elide`] Returns the elided variant of this envelope.
//!
//! * Returns a version of this envelope with the given element(s) elided:
//!     * [`Envelope::elide_removing_set`]
//!     * [`Envelope::elide_removing_array`]
//!     * [`Envelope::elide_removing_target`]
//!
//! * Returns a version with all elements except the given element(s) elided:
//!     * [`Envelope::elide_revealing_set`]
//!     * [`Envelope::elide_revealing_array`]
//!     * [`Envelope::elide_revealing_target`]
//!
//! * As above, but takes a boolean to determine whether to remove or reveal:
//!     * [`Envelope::elide_set`]
//!     * [`Envelope::elide_array`]
//!     * [`Envelope::elide_target`]
//!
//! * Returns a version with the given element(s) elided, encrypted, or
//! compressed:
//!     * [`Envelope::elide_removing_set_with_action`]
//!     * [`Envelope::elide_removing_array_with_action`]
//!     * [`Envelope::elide_removing_target_with_action`]
//!
//! * Returns a version with all elements except the given element(s) elided,
//! encrypted, or compressed:
//!     * [`Envelope::elide_revealing_set_with_action`]
//!     * [`Envelope::elide_revealing_array_with_action`]
//!     * [`Envelope::elide_revealing_target_with_action`]
//!
//! * As above, but takes a boolean to determine whether to remove or reveal:
//!     * [`Envelope::elide_set_with_action`]
//!     * [`Envelope::elide_array_with_action`]
//!     * [`Envelope::elide_target_with_action`]
//!
//! * [`Envelope::unelide`] Returns the unelided variant of this envelope, given
//!   the envelope that was elided.
//!
//! # Decorrelating Envelopes using Salt
//!
//! * [`Envelope::add_salt`] Add a number of bytes of salt generally
//!   proportionate to the size of the object being salted.
//! * [`Envelope::add_salt_with_len`] Add a specified number of bytes of salt.
//! * [`Envelope::add_salt_in_range`] Add a number of bytes of salt chosen
//!   randomly from the given range.
//!
//! # Walking an Envelope's Hierarchy
//!
//! * [`Envelope::walk`] Walk the envelope, calling the visitor function for
//!   each element.
//!
//! # Envelope Expressions
//!
//! ### Constructing Expressions, Requests, and Responses
//!
//! * [`Envelope::new_function`] Creates an envelope with a `«function»`
//!   subject.
//! * [`Envelope::new_parameter`] Creates a new envelope containing a
//!   `❰parameter❱: value` assertion.
//! * [`Envelope::new_optional_parameter`] Optionally adds a `❰parameter❱:
//!   value` assertion to the envelope.
//! * [`Envelope::add_parameter`] Adds a `❰parameter❱: value` assertion to the
//!   envelope.
//! * [`Envelope::add_optional_parameter`] Optionally adds a `❰parameter❱:
//!   value` assertion to the envelope.
//! * [`Envelope::new_request`] Creates an envelope with an `ARID` subject and a
//!   `body: «function»` assertion.
//! * [`Envelope::new_response`] Creates an envelope with an `ARID` subject and a
//!   `result: value` assertion.
//! * [`Envelope::new_response_with_result`] Creates an envelope with an `ARID`
//!   subject and a `result: value` assertion for each provided result.
//! * [`Envelope::new_error_response_with_id`] Creates an envelope with an `ARID`
//!   subject and a `error: value` assertion.
//! * [`Envelope::new_error_response`] Creates an envelope with an `unknown`
//!   subject and a `error: value` assertion.
//!
//! ### Decoding Parameters and Results
//!
//! * [`Envelope::extract_object_for_parameter`] Returns the argument for the
//!   given parameter, decoded as the given type.
//! * [`Envelope::extract_objects_for_parameter`] Returns an array of arguments
//!   for the given parameter, decoded as the given type.
//! * [`Envelope::result`] Returns the object of the `result` predicate.
//! * [`Envelope::results`] Returns the objects of every `result` predicate.
//! * [`Envelope::extract_result`] Returns the object of the `result` predicate,
//!   decoded as the given type.
//! * [`Envelope::extract_results`] Returns the objects of every `result`
//!   predicate, decoded as the given type.
//! * [`Envelope::is_result_ok`] Returns whether the `result` predicate has the
//!   `KnownValue` `.ok`.
//! * [`Envelope::error`] Returns the error value, decoded as the given type.

pub mod base;
pub use base::Assertion;
pub use base::Envelope;
pub use base::EnvelopeEncodable;
pub use base::EnvelopeDecodable;
pub use base::EnvelopeCodable;
pub use base::EnvelopeError;
pub use base::{FormatContext, GLOBAL_FORMAT_CONTEXT};
pub use base::elide::{self, ObscureAction};

pub mod extension;
pub mod prelude;

mod string_utils;

#[cfg(all(feature = "signature", feature = "encrypt"))]
use bc_components::{PrivateKeyBase, PublicKeyBase};

#[cfg(feature = "known_value")]
pub use extension::known_values::{self, known_value, KnownValue, KNOWN_VALUES, KnownValuesStore};

#[cfg(feature = "expression")]
pub use extension::expression;

#[cfg(feature = "expression")]
pub use extension::expression::{functions, parameters, Function, Parameter};

#[cfg(all(feature = "signature", feature = "encrypt"))]
impl Envelope {
    pub fn sign_and_encrypt(&self, sender: &PrivateKeyBase, recipient: &PublicKeyBase) -> anyhow::Result<Envelope> {
        Ok(self
            .wrap_envelope()
            .sign_with(sender)
            .wrap_envelope()
            .encrypt_subject_to_recipient(recipient)?)
    }

    pub fn verify_and_decrypt(&self, sender: &PublicKeyBase, recipient: &PrivateKeyBase) -> anyhow::Result<Envelope> {
        Ok(self
            .decrypt_to_recipient(recipient)?
            .unwrap_envelope()?
            .verify_signature_from(sender)?
            .unwrap_envelope()?)
    }
}