Skip to main content

rings_node/mail/
envelope.rs

1//! A mail as DHT elements: a manifest and the chunks of one ciphertext (pure).
2//!
3//! ```text
4//!   c          = AeadCiphertext(m) to ek, aad = "rings-node:mail:" ‖ d      (encoded)
5//!   chunk_i    = slice_i(c)                             each element ≤ ENTRY_PAYLOAD_MAX_BYTES
6//!   manifest   = (mail_id = H(c), [H(chunk_0) … H(chunk_{n−1})])
7//!   seal(m)    = [manifest, chunk_0, …, chunk_{n−1}]   n ≤ N_max, else TooLarge
8//! ```
9//!
10//! `H` is SHA-256 over bytes as they are carried: `H(c)` over the encoded ciphertext and
11//! `H(chunk_i)` over the chunk's element, so a reader checks a chunk before decoding it. The
12//! manifest's ordered digests fix which chunks make the mail and in which order, and `mail_id`
13//! names their concatenation, so neither needs a signature: any writer can append a manifest,
14//! but one whose chunks do not concatenate to `H⁻¹(mail_id)` is ignored (`open`). The AEAD tag
15//! covers the whole of `c`, and its associated data binds the recipient, so a mail opens only
16//! whole and only for the DID it was sealed for.
17//!
18//! Sizes (`N_max = 32`, about 1 MiB a mail; a topic keeps `ENTRY_DATA_MAX_LEN = 1024`
19//! elements, so 32 mails of the largest size fit one lifetime):
20//!
21//! ```text
22//!   |chunk element| = MAIL_CHUNK_ELEMENT_OVERHEAD + |slice| ≤ ENTRY_PAYLOAD_MAX_BYTES
23//!   |c|             = MAIL_SEAL_OVERHEAD + |m|           for MAIL_MESSAGE_MAX's neighbourhood
24//!   |m| ≤ MAIL_MESSAGE_MAX  ⇒  |c| ≤ MAIL_CIPHERTEXT_MAX = N_max · MAIL_CHUNK_SLICE_MAX
25//! ```
26
27use bytes::Bytes;
28use rand::RngCore;
29use rings_core::consts::ENTRY_PAYLOAD_MAX_BYTES;
30use rings_core::dht::Did;
31use rings_core::ecc::elgamal::impls::secp256k1::encrypt_aead_with_rng;
32use serde::Deserialize;
33use serde::Serialize;
34use sha2::Digest;
35use sha2::Sha256;
36use thiserror::Error;
37
38use super::descriptor::MailRecipient;
39use super::write_lowercase_hex;
40
41/// The most chunks one mail is cut into, `N_max`.
42pub const MAIL_CHUNKS_MAX: usize = 32;
43/// Bytes a chunk element adds to its slice: the element's variant tag (1) and the varint
44/// length of a slice of `2¹⁴` to `2²¹` bytes (3), `1 + 3 = 4`; witnessed with equality by
45/// `test_the_widest_chunk_element_is_one_entry_payload`.
46pub const MAIL_CHUNK_ELEMENT_OVERHEAD: usize = 4;
47/// The largest slice of a ciphertext one chunk carries: its element is then exactly
48/// `ENTRY_PAYLOAD_MAX_BYTES`.
49pub const MAIL_CHUNK_SLICE_MAX: usize = ENTRY_PAYLOAD_MAX_BYTES - MAIL_CHUNK_ELEMENT_OVERHEAD;
50/// The largest ciphertext one mail carries: [`MAIL_CHUNKS_MAX`] full slices.
51pub const MAIL_CIPHERTEXT_MAX: usize = MAIL_CHUNKS_MAX * MAIL_CHUNK_SLICE_MAX;
52/// Bytes an encoded ciphertext adds to its message, for a message of `2¹⁴ − 16` to `2²¹ − 17`
53/// bytes: its version (1), the length of its wrapped key (1) and the key's two blocks of two
54/// points, each a 33-byte compressed SEC1 point (`2 · 2 · 33 = 132`), the nonce (12), the
55/// varint length of the sealed message (3) and the AEAD tag (16),
56/// `1 + 1 + 132 + 12 + 3 + 16 = 165`; witnessed with equality by
57/// `test_the_largest_message_seals_into_the_most_chunks`.
58pub const MAIL_SEAL_OVERHEAD: usize = 165;
59/// The largest message one mail carries: its ciphertext is then exactly
60/// [`MAIL_CIPHERTEXT_MAX`].
61pub const MAIL_MESSAGE_MAX: usize = MAIL_CIPHERTEXT_MAX - MAIL_SEAL_OVERHEAD;
62/// The prefix of the AEAD associated data, which binds the recipient's DID.
63const MAIL_AAD_PREFIX: &str = "rings-node:mail:";
64
65/// A SHA-256 digest, `H(x)`: the id of a ciphertext (`mail_id = H(c)`) or the name of a chunk
66/// element (`H(chunk_i)`).
67#[derive(Clone, Copy, Debug, Deserialize, Serialize, Eq, Hash, Ord, PartialEq, PartialOrd)]
68pub struct MailDigest([u8; 32]);
69
70impl MailDigest {
71    /// `H(bytes)`.
72    pub fn of(bytes: &[u8]) -> Self {
73        Self(Sha256::digest(bytes).into())
74    }
75}
76
77impl std::fmt::Display for MailDigest {
78    /// The digest in lowercase hex.
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        write_lowercase_hex(f, &self.0)
81    }
82}
83
84/// A manifest: which chunks make one mail, in order.
85#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
86pub struct MailManifest {
87    /// `H(c)`.
88    pub mail_id: MailDigest,
89    /// `H(chunk_i)` of every chunk, in order; `n` is its length.
90    pub chunks: Vec<MailDigest>,
91}
92
93impl MailManifest {
94    /// Whether a reader takes this manifest: it lists at least one and at most
95    /// [`MAIL_CHUNKS_MAX`] chunks.
96    pub fn is_well_formed(&self) -> bool {
97        (1..=MAIL_CHUNKS_MAX).contains(&self.chunks.len())
98    }
99}
100
101/// One element of a recipient's mail topic.
102#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
103pub enum MailElement {
104    /// A mail's manifest.
105    Manifest(MailManifest),
106    /// A slice of a mail's ciphertext, `slice_i(c)`.
107    Chunk(Bytes),
108}
109
110impl MailElement {
111    /// This element as DHT element bytes.
112    pub fn encode(&self) -> Result<Bytes, rings_codec::Error> {
113        rings_codec::serialize(self).map(Bytes::from)
114    }
115
116    /// The element `bytes` encode.
117    pub fn decode(bytes: &[u8]) -> Result<Self, rings_codec::Error> {
118        rings_codec::deserialize(bytes)
119    }
120}
121
122/// The AEAD associated data of mail for `recipient`: `"rings-node:mail:" ‖ d`.
123pub fn mail_aad(recipient: Did) -> Vec<u8> {
124    format!("{MAIL_AAD_PREFIX}{recipient}").into_bytes()
125}
126
127/// Why a message could not be sealed.
128#[derive(Debug, Error)]
129pub enum SealError {
130    /// The ciphertext needs more than [`MAIL_CHUNKS_MAX`] chunks.
131    #[error("the mail needs {chunks} chunks, more than {MAIL_CHUNKS_MAX}")]
132    TooLarge {
133        /// The chunks it needs.
134        chunks: usize,
135    },
136    /// Encryption failed.
137    #[error("cannot seal the mail: {0}")]
138    Crypto(#[from] rings_core::error::Error),
139    /// An element could not be encoded.
140    #[error("cannot encode the mail: {0}")]
141    Encode(#[from] rings_codec::Error),
142}
143
144/// A sealed mail: its id and the elements to write, manifest first.
145#[derive(Clone, Debug, Eq, PartialEq)]
146pub struct SealedMail {
147    /// `H(c)`.
148    pub mail_id: MailDigest,
149    /// `[manifest, chunk_0, …, chunk_{n−1}]`.
150    pub elements: Vec<Bytes>,
151}
152
153/// Seal `message` for `recipient`, with ephemerals from `rng`.
154///
155/// Post: `Ok(s)` has `1 + n` elements with `1 ≤ n ≤ MAIL_CHUNKS_MAX`, each at most
156/// `ENTRY_PAYLOAD_MAX_BYTES`, and opens to `message` for the holder of
157/// `recipient.encryption_key`'s secret (the round-trip law of `open`). `TooLarge` exactly when
158/// the ciphertext needs more than `MAIL_CHUNKS_MAX` chunks, which every `message` of at most
159/// [`MAIL_MESSAGE_MAX`] bytes does not.
160pub fn seal(
161    message: &[u8],
162    recipient: &MailRecipient,
163    rng: &mut impl RngCore,
164) -> Result<SealedMail, SealError> {
165    let sealed = encrypt_aead_with_rng(
166        message,
167        &mail_aad(recipient.did),
168        recipient.encryption_key,
169        rng,
170    )?;
171    let ciphertext = rings_codec::serialize(&sealed)?;
172    let slices = ciphertext.chunks(MAIL_CHUNK_SLICE_MAX);
173    let chunks = slices.len();
174    if chunks > MAIL_CHUNKS_MAX {
175        return Err(SealError::TooLarge { chunks });
176    }
177    let chunk_elements = slices
178        .map(|slice| MailElement::Chunk(Bytes::copy_from_slice(slice)).encode())
179        .collect::<Result<Vec<_>, _>>()?;
180    let mail_id = MailDigest::of(&ciphertext);
181    let manifest = MailElement::Manifest(MailManifest {
182        mail_id,
183        chunks: chunk_elements
184            .iter()
185            .map(|element| MailDigest::of(element))
186            .collect(),
187    })
188    .encode()?;
189    Ok(SealedMail {
190        mail_id,
191        elements: std::iter::once(manifest).chain(chunk_elements).collect(),
192    })
193}