Skip to main content

rings_node/mail/
descriptor.rs

1//! The mail descriptor `μ(d)`: a recipient's opt-in to mail, and the key mail is sealed to.
2//!
3//! ```text
4//!   μ(d) = (d, pk, network, freshness, lease end, sig)          heard at the dot of its element
5//!   sig  = the delegatee's signature, carrying the delegation that authorizes it
6//!   ek   = recover(sig)                    the delegatee's secp256k1 public key, mail's key
7//! ```
8//!
9//! The service descriptor of the DNS relay carries the account key, which a wallet account
10//! (EIP-191, BIP-137) cannot decrypt with; mail is sealed to the delegatee's key instead.
11//!
12//! Law (key): `ek` is the key the signature recovers to (`MessageVerification::signer_key_at`),
13//! so it is the key of the session that signed `μ(d)`, whose holder therefore published `μ(d)`
14//! for `d`. The descriptor carries no copy of `ek` that could name another key.
15//!
16//! A recipient publishes `μ(d)` on its own [`descriptor_topic`], under the registry lease (#918,
17//! the lease law of `descriptor`), so a gateway finds it with one fetch, and the newest live
18//! descriptor wins (`latest_valid_by_did`).
19
20use std::borrow::Borrow;
21
22use rings_core::delegation::DelegateeKey;
23use rings_core::dht::Did;
24use rings_core::domain_tag;
25use rings_core::ecc::PublicKey;
26use rings_core::ecc::VerificationPublicKey;
27use rings_core::error::Error;
28use rings_core::error::Result;
29use rings_core::message::DomainTag;
30use rings_core::message::MessageSigner;
31use rings_core::message::MessageVerification;
32use rings_core::message::SigningDomain;
33use serde::Deserialize;
34use serde::Serialize;
35
36use crate::descriptor::latest_valid_by_did;
37use crate::descriptor::sign_descriptor_body;
38use crate::descriptor::RegistryElement;
39use crate::descriptor::SignedDescriptor;
40use crate::descriptor::SignedDescriptorBody;
41
42/// Message family of the mail descriptor signature.
43const MAIL_DESCRIPTOR_DOMAIN_TAG: DomainTag = domain_tag!("rings-node:mail-descriptor");
44
45/// The data topic `did` publishes its mail descriptor on: `"mail_descriptor:" ‖ d`.
46///
47/// Law: injective in `did`, and disjoint from [`mail_topic`](super::mail_topic) and from every
48/// registry and DNS relay topic, none of which starts with `mail_descriptor:`.
49pub fn descriptor_topic(did: Did) -> String {
50    format!("mail_descriptor:{did}")
51}
52
53/// Where a gateway writes a recipient's mail, and the key it seals it to: what a live
54/// [`MailDescriptor`] and its signature say.
55#[derive(Clone, Copy, Debug, Eq, PartialEq)]
56pub struct MailRecipient {
57    /// The recipient's DID, whose [`mail_topic`](super::mail_topic) the mail is written to.
58    pub did: Did,
59    /// The delegatee key the mail is sealed to.
60    pub encryption_key: PublicKey<33>,
61}
62
63/// Descriptor fields covered by the mail-descriptor signature.
64#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
65pub struct MailDescriptorBody {
66    /// DID of the recipient's account.
67    pub did: Did,
68    /// Account public key corresponding to `did`.
69    pub public_key: VerificationPublicKey,
70    /// Network identifier.
71    pub network_id: u32,
72    /// Freshness window `T` in milliseconds (see the lease law of `descriptor`).
73    pub fresh_for_ms: u64,
74    /// Lease end `ℓ` in milliseconds since Unix epoch.
75    pub expires_at_ms: u128,
76}
77
78impl MailDescriptorBody {
79    /// The bytes the signature covers.
80    fn signing_data(&self) -> Result<Vec<u8>> {
81        rings_codec::serialize(self).map_err(Error::CodecSerialize)
82    }
83}
84
85impl SignedDescriptorBody for MailDescriptorBody {
86    type Descriptor = MailDescriptor;
87
88    const DOMAIN_TAG: DomainTag = MAIL_DESCRIPTOR_DOMAIN_TAG;
89
90    fn body_did(&self) -> Did {
91        self.did
92    }
93
94    fn body_public_key(&self) -> &VerificationPublicKey {
95        &self.public_key
96    }
97
98    fn body_network_id(&self) -> u32 {
99        self.network_id
100    }
101
102    fn body_signing_data(&self) -> Result<Vec<u8>> {
103        self.signing_data()
104    }
105
106    fn into_signed_descriptor(self, signature: MessageVerification) -> Self::Descriptor {
107        MailDescriptor {
108            body: self,
109            signature,
110            heartbeat_at_ms: 0,
111        }
112    }
113}
114
115/// Signed descriptor of a recipient that takes mail.
116#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
117pub struct MailDescriptor {
118    /// The signed fields.
119    pub body: MailDescriptorBody,
120    /// Signature covering `body`, by the delegatee whose key mail is sealed to.
121    pub signature: MessageVerification,
122    /// When the reader last heard this descriptor, in milliseconds since Unix epoch: the dot of
123    /// its element. Not signed and not encoded (see the lease law of `descriptor`); `0` until
124    /// heard.
125    #[serde(skip)]
126    pub heartbeat_at_ms: u128,
127}
128
129impl MailDescriptor {
130    /// Create and sign a descriptor.
131    pub fn new_signed(
132        body: MailDescriptorBody,
133        signer: MessageSigner<impl Borrow<DelegateeKey>>,
134    ) -> Result<Self> {
135        sign_descriptor_body(
136            body,
137            signer,
138            "mail descriptor DID/public key/session mismatch",
139        )
140    }
141
142    /// The key mail to this descriptor's recipient is sealed to, `ek`: the key its signature
143    /// recovers to under the overlay `network_id` at `now_ms` (the key law), if it verifies.
144    pub fn encryption_key_at(&self, network_id: u32, now_ms: u128) -> Option<PublicKey<33>> {
145        let domain = SigningDomain::new(MAIL_DESCRIPTOR_DOMAIN_TAG, network_id);
146        let data = self.body.signing_data().ok()?;
147        self.signature.signer_key_at(domain, &data, now_ms)
148    }
149
150    /// Where mail to `did` goes and the key it is sealed to: the newest descriptor among
151    /// `descriptors` that is signed for `did`, verifies under the overlay `network_id` and is
152    /// live at `now_ms`, with its key.
153    pub fn live_recipient(
154        descriptors: impl IntoIterator<Item = Self>,
155        did: Did,
156        now_ms: u128,
157        network_id: u32,
158    ) -> Option<MailRecipient> {
159        let descriptor = latest_valid_by_did(
160            descriptors
161                .into_iter()
162                .filter(|descriptor| descriptor.body.did == did),
163            now_ms,
164            network_id,
165            false,
166        )
167        .into_iter()
168        .next()?;
169        let encryption_key = descriptor.encryption_key_at(network_id, now_ms)?;
170        Some(MailRecipient {
171            did,
172            encryption_key,
173        })
174    }
175}
176
177impl SignedDescriptor for MailDescriptor {
178    type Body = MailDescriptorBody;
179
180    fn descriptor_did(&self) -> Did {
181        self.body.did
182    }
183
184    fn descriptor_public_key(&self) -> &VerificationPublicKey {
185        &self.body.public_key
186    }
187
188    fn descriptor_network_id(&self) -> u32 {
189        self.body.network_id
190    }
191
192    fn descriptor_signature(&self) -> &MessageVerification {
193        &self.signature
194    }
195
196    fn descriptor_heartbeat_at_ms(&self) -> u128 {
197        self.heartbeat_at_ms
198    }
199
200    fn descriptor_expires_at_ms(&self) -> u128 {
201        self.body.expires_at_ms
202    }
203
204    fn descriptor_fresh_for_ms(&self) -> u64 {
205        self.body.fresh_for_ms
206    }
207
208    fn descriptor_signing_data(&self) -> Result<Vec<u8>> {
209        self.body.signing_data()
210    }
211
212    fn heard_at(self, heartbeat_at_ms: u128) -> Self {
213        Self {
214            heartbeat_at_ms,
215            ..self
216        }
217    }
218}
219
220impl RegistryElement for MailDescriptor {}