Skip to main content

rings_core/message/protocols/
verify.rs

1#![deny(missing_docs)]
2
3//! Implementation of Message Verification.
4//!
5//! A [`MessageVerification`] is a delegatee signature over a *domain-separated* transcript:
6//!
7//! ```text
8//! transcript(d, ts, ttl, m) = len(tag(d)) || tag(d) || network_id(d) || ts || ttl || m
9//! ```
10//!
11//! where `d : SigningDomain = (tag, network_id)` names the message family and the overlay, all
12//! integers are big-endian, and `len(tag)` is one byte. The length prefix makes the tag component
13//! prefix-free, so transcripts of distinct domains never collide for any `m`. Binding `network_id`
14//! makes a signature non-portable across overlays that share a delegatee key; binding the tag makes
15//! it non-portable across message families that share a signing surface.
16//!
17//! Authority: every signature is issued by a [`MessageSigner`], a delegatee key paired with the
18//! overlay it acts in, and every verification is performed against the *receiver's* domain, never
19//! against a value carried in the message. A type that embeds a verification implements
20//! [`MessageVerificationExt`] with its own [`DomainTag`] and verifies under the receiver's
21//! `network_id`.
22
23use std::borrow::Borrow;
24
25use serde::Deserialize;
26use serde::Serialize;
27
28use crate::consts::DEFAULT_TTL_MS;
29use crate::consts::MAX_TTL_MS;
30use crate::consts::TS_OFFSET_TOLERANCE_MS;
31use crate::delegation::DelegateeKey;
32use crate::delegation::Delegation;
33use crate::delegation::DelegatorAuthorization;
34use crate::dht::Did;
35use crate::ecc::PublicKey;
36use crate::error::Result;
37use crate::utils::get_epoch_ms;
38
39/// Name of one signed message family; the first component of a [`SigningDomain`].
40///
41/// Law: `label.len() <= u8::MAX`, so the label fits its one-byte length prefix in the
42/// transcript. Construct tags with [`domain_tag!`](crate::domain_tag), which enforces the law at
43/// compile time; [`DomainTag::new`] enforces the same precondition at runtime when called outside a
44/// `const` context.
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub struct DomainTag(&'static str);
47
48impl DomainTag {
49    /// Name a message family.
50    ///
51    /// # Panics
52    ///
53    /// Panics (or fails `const` evaluation) if `label.len() > u8::MAX as usize`, because the
54    /// signing transcript prefixes `label` with a one-byte length.
55    pub const fn new(label: &'static str) -> Self {
56        assert!(
57            label.len() <= u8::MAX as usize,
58            "domain tag label must fit its one-byte length prefix"
59        );
60        Self(label)
61    }
62
63    /// The label bytes.
64    pub const fn as_bytes(self) -> &'static [u8] {
65        self.0.as_bytes()
66    }
67
68    /// The label as one byte, valid by the constructor law.
69    const fn len_byte(self) -> u8 {
70        self.0.len() as u8
71    }
72}
73
74/// Name a message family from a literal in a `const`, so a label longer than the one-byte
75/// length prefix allows is refused at compile time.
76#[macro_export]
77macro_rules! domain_tag {
78    ($label:literal) => {{
79        const TAG: $crate::message::DomainTag = $crate::message::DomainTag::new($label);
80        TAG
81    }};
82}
83
84/// The message family and overlay a signature transcript is bound to.
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86pub struct SigningDomain {
87    tag: DomainTag,
88    network_id: u32,
89}
90
91impl SigningDomain {
92    /// Bind a message family to an overlay.
93    pub const fn new(tag: DomainTag, network_id: u32) -> Self {
94        Self { tag, network_id }
95    }
96
97    /// The message family.
98    pub const fn tag(self) -> DomainTag {
99        self.tag
100    }
101
102    /// The overlay.
103    pub const fn network_id(self) -> u32 {
104        self.network_id
105    }
106
107    /// The signed bytes for `data` stamped `(ts_ms, ttl_ms)` under this domain.
108    ///
109    /// Law (injectivity): `transcript(d, ts, ttl, m) = transcript(d', ts', ttl', m')` implies
110    /// `(d, ts, ttl, m) = (d', ts', ttl', m')`, because every component before `m` has a fixed
111    /// width or a length prefix.
112    pub(crate) fn transcript(self, data: &[u8], ts_ms: u128, ttl_ms: u64) -> Vec<u8> {
113        let tag = self.tag.as_bytes();
114        let mut msg = Vec::with_capacity(1 + tag.len() + 4 + 16 + 8 + data.len());
115
116        msg.push(self.tag.len_byte());
117        msg.extend_from_slice(tag);
118        msg.extend_from_slice(&self.network_id.to_be_bytes());
119        msg.extend_from_slice(&ts_ms.to_be_bytes());
120        msg.extend_from_slice(&ttl_ms.to_be_bytes());
121        msg.extend_from_slice(data);
122
123        msg
124    }
125}
126
127/// A delegatee key acting inside one overlay: the authority that issues every
128/// [`MessageVerification`] a node signs.
129///
130/// Signing is the map `(delegatee_key, network_id) × (tag, data) → MessageVerification`. This
131/// type fixes the first component, so message constructors take one authority instead of a key
132/// and an overlay that could be paired inconsistently. `S` is how the key is held: a borrowed
133/// authority `MessageSigner<&DelegateeKey>` is `Copy` and is what signing functions take; an owned
134/// authority `MessageSigner<DelegateeKey>` is what long-lived runtimes store, so the pairing is
135/// never split across two fields.
136///
137/// Law: copying or cloning an authority is semantically invisible, since it names the same key
138/// and the same overlay.
139#[derive(Clone, Copy, Debug)]
140pub struct MessageSigner<S> {
141    delegatee_key: S,
142    network_id: u32,
143}
144
145impl<S> MessageSigner<S>
146where S: Borrow<DelegateeKey>
147{
148    /// Let `delegatee_key` sign on behalf of the overlay `network_id`.
149    pub const fn new(delegatee_key: S, network_id: u32) -> Self {
150        Self {
151            delegatee_key,
152            network_id,
153        }
154    }
155
156    fn delegatee_key(&self) -> &DelegateeKey {
157        self.delegatee_key.borrow()
158    }
159
160    /// The public key of the session this authority signs with.
161    pub fn delegatee_public_key(&self) -> PublicKey<33> {
162        self.delegatee_key().delegatee_public_key()
163    }
164
165    /// The overlay this authority signs for.
166    pub const fn network_id(&self) -> u32 {
167        self.network_id
168    }
169
170    /// The account DID that authorized the delegatee key.
171    pub fn delegator_did(&self) -> Did {
172        self.delegatee_key().delegator_did()
173    }
174
175    /// This authority borrowing its key: the form signing functions take.
176    pub fn by_ref(&self) -> MessageSigner<&DelegateeKey> {
177        MessageSigner::new(self.delegatee_key(), self.network_id)
178    }
179
180    /// This authority owning a copy of its key: the form long-lived runtimes store.
181    pub fn owned(&self) -> MessageSigner<DelegateeKey> {
182        MessageSigner::new(self.delegatee_key().clone(), self.network_id)
183    }
184
185    /// Sign `data` as a member of the message family `tag` inside this overlay, stamped with
186    /// the current time and the default TTL.
187    pub fn sign(&self, tag: DomainTag, data: &[u8]) -> Result<MessageVerification> {
188        self.sign_at(tag, data, get_epoch_ms())
189    }
190
191    /// Sign `data` as a member of the message family `tag` inside this overlay, stamped with
192    /// the instant `ts_ms` and the default TTL.
193    pub fn sign_at(&self, tag: DomainTag, data: &[u8], ts_ms: u128) -> Result<MessageVerification> {
194        let domain = SigningDomain::new(tag, self.network_id);
195        let ttl_ms = DEFAULT_TTL_MS;
196        let msg = domain.transcript(data, ts_ms, ttl_ms);
197        Ok(MessageVerification {
198            delegation: self.delegatee_key().delegation(),
199            sig: self.delegatee_key().sign(&msg)?,
200            ttl_ms,
201            ts_ms,
202        })
203    }
204}
205
206/// Message Verification is based on session, and sig.
207/// it also included ttl time and created ts.
208#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
209pub struct MessageVerification {
210    /// The [Delegation] of the [DelegateeKey]. Used to identify a sender and verify the signature.
211    pub delegation: Delegation,
212    /// The time to live of the message in milliseconds.
213    pub ttl_ms: u64,
214    /// The timestamp of the message in milliseconds.
215    pub ts_ms: u128,
216    /// The signature of the message. Signed by [DelegateeKey]. Can be verified by [Delegation].
217    pub sig: Vec<u8>,
218}
219
220impl MessageVerification {
221    /// Verify the signature over `data` under the receiver's `domain`, with the signing session
222    /// judged as of now.
223    pub fn verify(&self, domain: SigningDomain, data: &[u8]) -> bool {
224        self.verify_at(domain, data, get_epoch_ms())
225    }
226
227    /// Verify the signature over `data` under the receiver's `domain`, with the signing session
228    /// judged as of the instant `at_ms`.
229    ///
230    /// Post: `true` implies the session was authorized and live at `at_ms` and signed the
231    /// transcript of `(domain, data, ts_ms, ttl_ms)`. Proof liveness is not judged here; see
232    /// [`Self::is_live_at`].
233    pub fn verify_at(&self, domain: SigningDomain, data: &[u8], at_ms: u128) -> bool {
234        self.verify_under(domain, data, at_ms, DelegatorAuthorization::Verify)
235    }
236
237    /// The delegatee public key that made this signature over `data` under `domain`, when it
238    /// verifies as of `at_ms`: the key the signature recovers to, so a reader learns the
239    /// signer's key from the signature alone.
240    ///
241    /// Law: `signer_key_at(d, m, t) = Some(k)` iff `verify_at(d, m, t)`, and then
242    /// `Did::from(k.address()) = self.delegation.delegatee_did()`: both run one crate-private
243    /// path, `signer_under`, which recovers the key once.
244    pub fn signer_key_at(
245        &self,
246        domain: SigningDomain,
247        data: &[u8],
248        at_ms: u128,
249    ) -> Option<PublicKey<33>> {
250        self.signer_under(domain, data, at_ms, DelegatorAuthorization::Verify)
251    }
252
253    /// [`Self::verify_at`] with the delegation's delegator authorization treated as
254    /// `authorization` says (see [`DelegatorAuthorization`]).
255    pub(crate) fn verify_under(
256        &self,
257        domain: SigningDomain,
258        data: &[u8],
259        at_ms: u128,
260        authorization: DelegatorAuthorization,
261    ) -> bool {
262        self.signer_under(domain, data, at_ms, authorization)
263            .is_some()
264    }
265
266    /// The delegatee key that signed `data` under `domain`, judged at `at_ms` under
267    /// `authorization` (`Delegation::signer_under`); a failure is logged and is `None`.
268    fn signer_under(
269        &self,
270        domain: SigningDomain,
271        data: &[u8],
272        at_ms: u128,
273        authorization: DelegatorAuthorization,
274    ) -> Option<PublicKey<33>> {
275        let msg = domain.transcript(data, self.ts_ms, self.ttl_ms);
276        self.delegation
277            .signer_under(&msg, &self.sig, at_ms, authorization)
278            .map_err(|e| {
279                tracing::warn!("MessageVerification verify failed: {:?}", e);
280            })
281            .ok()
282    }
283
284    /// Return whether the verification timestamp is outside its accepted lifetime.
285    pub fn is_expired(&self) -> bool {
286        !self.is_live_at(get_epoch_ms())
287    }
288
289    /// Return whether the verification timestamp and TTL describe a currently live proof: the
290    /// one liveness predicate.
291    ///
292    /// Pre: `now_ms` is the receiver's current wall-clock time.
293    /// Post: `true` implies `ttl_ms <= MAX_TTL_MS`, the timestamp is not beyond the accepted future
294    /// skew, and `now_ms` has not passed `ts_ms + ttl_ms`.
295    pub fn is_live_at(&self, now_ms: u128) -> bool {
296        self.ttl_ms <= MAX_TTL_MS
297            && self.ts_ms.saturating_sub(TS_OFFSET_TOLERANCE_MS) <= now_ms
298            && now_ms <= self.ts_ms.saturating_add(u128::from(self.ttl_ms))
299    }
300
301    /// Verify the signature only when the proof is live now.
302    pub fn verify_live(&self, domain: SigningDomain, data: &[u8]) -> bool {
303        self.verify_live_at(domain, data, get_epoch_ms())
304    }
305
306    /// Verify the signature as of `at_ms`, requiring the proof to have been live then: the one
307    /// composition of liveness, session validity, and signature every verifying path uses.
308    pub fn verify_live_at(&self, domain: SigningDomain, data: &[u8], at_ms: u128) -> bool {
309        self.verify_live_under(domain, data, at_ms, DelegatorAuthorization::Verify)
310    }
311
312    /// [`Self::verify_live_at`] with the delegator authorization treated as `authorization`
313    /// says.
314    pub(crate) fn verify_live_under(
315        &self,
316        domain: SigningDomain,
317        data: &[u8],
318        at_ms: u128,
319        authorization: DelegatorAuthorization,
320    ) -> bool {
321        if !self.is_live_at(at_ms) {
322            tracing::warn!("message proof not live at the judged instant");
323            return false;
324        }
325        self.verify_under(domain, data, at_ms, authorization)
326    }
327}
328
329/// [`MessageVerificationExt::verify_at`] with the delegator authorization of `message`'s
330/// delegation treated as `authorization` says. Crate-private, as [`DelegatorAuthorization`] is:
331/// outside the crate every verification checks the delegator's signature.
332pub(crate) fn verify_message_under<M: MessageVerificationExt + ?Sized>(
333    message: &M,
334    network_id: u32,
335    at_ms: u128,
336    authorization: DelegatorAuthorization,
337) -> bool {
338    let Ok(data) = message.verification_data() else {
339        tracing::warn!("MessageVerificationExt verify get verification_data failed");
340        return false;
341    };
342
343    message.verification().verify_live_under(
344        SigningDomain::new(M::DOMAIN_TAG, network_id),
345        &data,
346        at_ms,
347        authorization,
348    )
349}
350
351/// This trait helps a struct with `MessageVerification` field to `verify` itself.
352/// It also provides a `signer` method to let receiver know who sent the message.
353pub trait MessageVerificationExt {
354    /// The message family this type is signed under. Paired with the receiver's overlay it
355    /// fixes the [`SigningDomain`] of [`Self::verification`].
356    const DOMAIN_TAG: DomainTag;
357
358    /// Give the data to be verified.
359    fn verification_data(&self) -> Result<Vec<u8>>;
360
361    /// Give the verification field for verifying.
362    fn verification(&self) -> &MessageVerification;
363
364    /// Checks whether the message is expired.
365    fn is_expired(&self) -> bool {
366        self.verification().is_expired()
367    }
368
369    /// Verifies the message as of the instant `at_ms`: its proof was live then, its session was
370    /// authorized and live then, and the signature was issued for this message family inside
371    /// the overlay `network_id`.
372    ///
373    /// Every transport path judges as of now through [`Self::verify`]; a relay inbox judges a
374    /// held message as of the instant its holder received it, so a sender's session expiring
375    /// afterwards does not retroactively unverify a message that was valid when held.
376    fn verify_at(&self, network_id: u32, at_ms: u128) -> bool {
377        verify_message_under(self, network_id, at_ms, DelegatorAuthorization::Verify)
378    }
379
380    /// Verifies that the message is not expired and that the signature was issued for this
381    /// message family inside the overlay `network_id`, as of now.
382    fn verify(&self, network_id: u32) -> bool {
383        self.verify_at(network_id, get_epoch_ms())
384    }
385
386    /// Get signer did from verification.
387    fn signer(&self) -> Did {
388        self.verification().delegation.delegator_did()
389    }
390}
391
392#[cfg(test)]
393mod tests {
394    use super::*;
395    use crate::ecc::SecretKey;
396
397    const FIXTURE_TAG: DomainTag = domain_tag!("rings-core:test:fixture");
398    const OTHER_TAG: DomainTag = domain_tag!("rings-core:test:other");
399    const NETWORK_ID: u32 = 7;
400
401    struct VerifiedFixture {
402        verification: MessageVerification,
403    }
404
405    impl MessageVerificationExt for VerifiedFixture {
406        const DOMAIN_TAG: DomainTag = FIXTURE_TAG;
407
408        fn verification_data(&self) -> Result<Vec<u8>> {
409            Ok(Vec::new())
410        }
411
412        fn verification(&self) -> &MessageVerification {
413            &self.verification
414        }
415    }
416
417    fn fixture_domain() -> SigningDomain {
418        SigningDomain::new(FIXTURE_TAG, NETWORK_ID)
419    }
420
421    fn fixture_signer(delegatee_key: &DelegateeKey) -> MessageSigner<&DelegateeKey> {
422        MessageSigner::new(delegatee_key, NETWORK_ID)
423    }
424
425    #[test]
426    fn test_expiration_handles_timestamp_below_tolerance_without_underflow() -> Result<()> {
427        let key = SecretKey::random();
428        let delegatee_key = DelegateeKey::new_with_seckey(&key)?;
429        let mut verification = fixture_signer(&delegatee_key).sign(FIXTURE_TAG, &[])?;
430        verification.ts_ms = 0;
431        let fixture = VerifiedFixture { verification };
432
433        assert!(fixture.is_expired());
434        Ok(())
435    }
436
437    fn signed_verification(
438        data: &[u8],
439        delegatee_key: &DelegateeKey,
440        ts_ms: u128,
441        ttl_ms: u64,
442    ) -> Result<MessageVerification> {
443        let msg = fixture_domain().transcript(data, ts_ms, ttl_ms);
444        Ok(MessageVerification {
445            delegation: delegatee_key.delegation(),
446            ttl_ms,
447            ts_ms,
448            sig: delegatee_key.sign(&msg)?,
449        })
450    }
451
452    #[test]
453    fn test_verify_live_rejects_ttl_above_max() -> Result<()> {
454        let key = SecretKey::random();
455        let delegatee_key = DelegateeKey::new_with_seckey(&key)?;
456        let proof = signed_verification(&[], &delegatee_key, get_epoch_ms(), MAX_TTL_MS + 1)?;
457
458        assert!(proof.is_expired());
459        assert!(!proof.verify_live(fixture_domain(), &[]));
460        Ok(())
461    }
462
463    #[test]
464    fn test_verify_live_rejects_timestamp_beyond_future_tolerance() -> Result<()> {
465        let key = SecretKey::random();
466        let delegatee_key = DelegateeKey::new_with_seckey(&key)?;
467        let proof = signed_verification(
468            &[],
469            &delegatee_key,
470            get_epoch_ms() + TS_OFFSET_TOLERANCE_MS + 60_000,
471            1_000,
472        )?;
473
474        assert!(proof.is_expired());
475        assert!(!proof.verify_live(fixture_domain(), &[]));
476        Ok(())
477    }
478
479    /// The signer-key law: a verifying signature recovers to its delegatee's key, and one that
480    /// does not verify, here under another overlay, recovers to nothing.
481    #[test]
482    fn test_signer_key_is_the_delegatee_key_of_a_verifying_signature() -> Result<()> {
483        let delegatee_key = DelegateeKey::new_with_seckey(&SecretKey::random())?;
484        let proof = fixture_signer(&delegatee_key).sign(FIXTURE_TAG, b"data")?;
485        let now_ms = get_epoch_ms();
486
487        let key = proof.signer_key_at(fixture_domain(), b"data", now_ms);
488        assert_eq!(key, Some(delegatee_key.delegatee_public_key()));
489        let other_overlay = SigningDomain::new(FIXTURE_TAG, NETWORK_ID + 1);
490        assert_eq!(proof.signer_key_at(other_overlay, b"data", now_ms), None);
491        Ok(())
492    }
493
494    /// Law: the transcript is the length-prefixed tag, the overlay, the stamp, then the data.
495    #[test]
496    fn test_transcript_layout_is_length_prefixed_tag_then_overlay_then_stamp() {
497        let transcript = fixture_domain().transcript(b"data", 3, 5);
498        let tag = FIXTURE_TAG.as_bytes();
499
500        let mut expected = vec![tag.len() as u8];
501        expected.extend_from_slice(tag);
502        expected.extend_from_slice(&NETWORK_ID.to_be_bytes());
503        expected.extend_from_slice(&3u128.to_be_bytes());
504        expected.extend_from_slice(&5u64.to_be_bytes());
505        expected.extend_from_slice(b"data");
506        assert_eq!(transcript, expected);
507    }
508
509    /// Law: a label longer than the one-byte length prefix is not a tag.
510    #[test]
511    #[should_panic(expected = "domain tag label must fit its one-byte length prefix")]
512    fn test_domain_tag_rejects_label_beyond_length_prefix() {
513        const LONG: &str = "rings-core:test:long-label - 0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789";
514        assert!(LONG.len() > usize::from(u8::MAX));
515        let _ = DomainTag::new(LONG);
516    }
517
518    /// Law: a signature issued for overlay `n` does not verify under overlay `n' != n`.
519    #[test]
520    fn test_signature_is_bound_to_the_overlay() -> Result<()> {
521        let key = SecretKey::random();
522        let delegatee_key = DelegateeKey::new_with_seckey(&key)?;
523        let verification = fixture_signer(&delegatee_key).sign(FIXTURE_TAG, b"data")?;
524
525        assert!(verification.verify(fixture_domain(), b"data"));
526        assert!(!verification.verify(SigningDomain::new(FIXTURE_TAG, NETWORK_ID + 1), b"data"));
527        Ok(())
528    }
529
530    /// Law: a signature issued for message family `t` does not verify under `t' != t`.
531    #[test]
532    fn test_signature_is_bound_to_the_message_family() -> Result<()> {
533        let key = SecretKey::random();
534        let delegatee_key = DelegateeKey::new_with_seckey(&key)?;
535        let verification = fixture_signer(&delegatee_key).sign(FIXTURE_TAG, b"data")?;
536
537        assert!(!verification.verify(SigningDomain::new(OTHER_TAG, NETWORK_ID), b"data"));
538        Ok(())
539    }
540
541    /// Law: `MessageVerificationExt::verify` checks the type's own tag against the receiver's
542    /// overlay, so a fixture signed elsewhere is rejected even with identical data.
543    #[test]
544    fn test_ext_verify_uses_type_tag_and_receiver_overlay() -> Result<()> {
545        let key = SecretKey::random();
546        let delegatee_key = DelegateeKey::new_with_seckey(&key)?;
547        let signer = fixture_signer(&delegatee_key);
548        let fixture = VerifiedFixture {
549            verification: signer.sign(FIXTURE_TAG, &[])?,
550        };
551
552        assert!(fixture.verify(NETWORK_ID));
553        assert!(!fixture.verify(NETWORK_ID + 1));
554
555        let mislabeled = VerifiedFixture {
556            verification: signer.sign(OTHER_TAG, &[])?,
557        };
558        assert!(!mislabeled.verify(NETWORK_ID));
559        Ok(())
560    }
561
562    /// Law: the owned and borrowed forms of one authority sign identically verifiable proofs.
563    #[test]
564    fn test_owned_and_borrowed_authorities_are_the_same_signer() -> Result<()> {
565        let key = SecretKey::random();
566        let delegatee_key = DelegateeKey::new_with_seckey(&key)?;
567        let owned = fixture_signer(&delegatee_key).owned();
568        let proof = owned.by_ref().sign(FIXTURE_TAG, b"data")?;
569
570        assert_eq!(owned.network_id(), NETWORK_ID);
571        assert_eq!(owned.delegator_did(), delegatee_key.delegator_did());
572        assert!(proof.verify(fixture_domain(), b"data"));
573        Ok(())
574    }
575}