Skip to main content

qualia_core_db/net/qdnf/profiles/
budget.rs

1//! Profile overhead budgets. Charge each component separately (Recipe F).
2//!
3//! Padding, relay copies, handshakes, cover traffic, retries, storage and
4//! cryptographic work are never lumped into a single opaque total before
5//! the checked add in [`OverheadBudget::total_bytes`].
6
7use crate::crypto::network::types::{
8    ED25519_SIG_LEN, ML_DSA_65_SIG_LEN, ML_KEM_768_CT_LEN, ML_KEM_768_PK_LEN, X25519_LEN,
9};
10use crate::net::peer::runtime::ResourceBudget;
11use crate::net::qdnf::errors::QdnfError;
12
13use super::catalog::{ControlPredicate, ControlSet, ProtectionProfile};
14
15/// P1 pads application size up to the next 256-byte bucket.
16pub const P1_PADDING_BUCKET: u64 = 256;
17/// P2 default application record size (last-record padding uses this bucket).
18pub const P2_RECORD_BYTES: u64 = 4096;
19/// P3/P4 traffic-cell target. A 4 KiB record is not an MTU claim.
20pub const P3_CELL_BYTES: u64 = 4096;
21/// P3 initial optional cover budget: 4 KiB/s per direction.
22pub const P3_COVER_BYTES_PER_SEC: u64 = 4096;
23/// P3 approved-relay hop count when relays are selected (not isolated bearer).
24pub const P3_RELAY_HOPS: u64 = 2;
25
26/// Hybrid handshake byte count:
27/// initiator (ML-KEM-768 pk + X25519 pk) + responder (ML-KEM-768 ct + X25519 pk)
28/// + ML-DSA-65 signature + Ed25519 signature.
29pub const fn handshake_bytes_hybrid() -> u64 {
30    (ML_KEM_768_PK_LEN
31        + X25519_LEN
32        + ML_KEM_768_CT_LEN
33        + X25519_LEN
34        + ML_DSA_65_SIG_LEN
35        + ED25519_SIG_LEN) as u64
36}
37
38/// Round `size` up to the next multiple of `bucket`.
39///
40/// Formula (`bucket > 0`, `size > 0`):
41/// `((size + bucket - 1) / bucket) * bucket`
42///
43/// `size == 0` stays 0 (no payload to pad). P1 uses `bucket = 256`:
44/// 1 → 256, 256 → 256, 257 → 512.
45pub fn pad_to_next_bucket(size: u64, bucket: u64) -> Result<u64, QdnfError> {
46    if bucket == 0 {
47        return Err(QdnfError::Range);
48    }
49    if size == 0 {
50        return Ok(0);
51    }
52    let rounded = size.checked_add(bucket - 1).ok_or(QdnfError::Range)?;
53    rounded
54        .checked_div(bucket)
55        .ok_or(QdnfError::Range)?
56        .checked_mul(bucket)
57        .ok_or(QdnfError::Range)
58}
59
60/// Records `bucket`.
61pub fn record_bucket(profile: ProtectionProfile) -> u64 {
62    match profile {
63        ProtectionProfile::P0 => 0,
64        ProtectionProfile::P1 => P1_PADDING_BUCKET,
65        ProtectionProfile::P2 | ProtectionProfile::P3 | ProtectionProfile::P4 => P2_RECORD_BYTES,
66    }
67}
68
69/// Per-component overhead. Fields are independent charges.
70#[repr(C)]
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub struct OverheadBudget {
73    pub padding_bytes: u64,
74    pub relay_copies: u64,
75    pub handshake_bytes: u64,
76    pub cover_bytes: u64,
77    pub retry_bytes: u64,
78    pub storage_bytes: u64,
79    pub crypto_work: u64,
80}
81
82impl OverheadBudget {
83    pub const ZERO: Self = Self {
84        padding_bytes: 0,
85        relay_copies: 0,
86        handshake_bytes: 0,
87        cover_bytes: 0,
88        retry_bytes: 0,
89        storage_bytes: 0,
90        crypto_work: 0,
91    };
92
93    /// `total` size in bytes.
94    pub fn total_bytes(&self) -> Result<u64, QdnfError> {
95        self.padding_bytes
96            .checked_add(self.relay_copies)
97            .and_then(|n| n.checked_add(self.handshake_bytes))
98            .and_then(|n| n.checked_add(self.cover_bytes))
99            .and_then(|n| n.checked_add(self.retry_bytes))
100            .and_then(|n| n.checked_add(self.storage_bytes))
101            .ok_or(QdnfError::Range)
102    }
103
104    /// Converts to `resource_budget`.
105    pub fn to_resource_budget(&self) -> Result<ResourceBudget, QdnfError> {
106        Ok(ResourceBudget {
107            bytes: self.total_bytes()?,
108            work: self.crypto_work,
109            io: if self.relay_copies > 0 {
110                P3_RELAY_HOPS
111            } else {
112                1
113            },
114        })
115    }
116}
117
118fn cover_bytes_for(duration_ms: u64, mandatory: bool) -> Result<u64, QdnfError> {
119    if !mandatory {
120        return Ok(0);
121    }
122    P3_COVER_BYTES_PER_SEC
123        .checked_mul(duration_ms)
124        .ok_or(QdnfError::Range)?
125        .checked_div(1000)
126        .ok_or(QdnfError::Range)
127}
128
129fn relay_hops(controls: &ControlSet) -> u64 {
130    if controls.contains_predicate(ControlPredicate::IsolatedBearer) {
131        0
132    } else if controls.contains_predicate(ControlPredicate::ApprovedRelay) {
133        P3_RELAY_HOPS
134    } else {
135        0
136    }
137}
138
139/// Crypto work units: `1 << profile_rank` (P0=1, P1=2, P2=4, P3=8, P4=16).
140pub fn crypto_work_units(profile: ProtectionProfile) -> u64 {
141    1u64 << profile.floor_rank()
142}
143
144/// `OverheadBudget::estimate_overhead`.
145pub fn estimate_overhead(
146    profile: ProtectionProfile,
147    controls: &ControlSet,
148    application_bytes: u64,
149    session_duration_ms: u64,
150    retry_count: u64,
151    drop_cover: bool,
152) -> Result<OverheadBudget, QdnfError> {
153    let cover_mandatory = controls.contains_predicate(ControlPredicate::CoverTraffic);
154    if drop_cover && cover_mandatory {
155        return Err(QdnfError::Downgrade);
156    }
157    let cover_on = cover_mandatory && !drop_cover;
158
159    if profile == ProtectionProfile::P0 && application_bytes != 0 {
160        return Err(QdnfError::Denied);
161    }
162
163    let bucket = record_bucket(profile);
164    let padded = if bucket == 0 {
165        0
166    } else {
167        pad_to_next_bucket(application_bytes, bucket)?
168    };
169    let padding_bytes = padded
170        .checked_sub(application_bytes)
171        .ok_or(QdnfError::Range)?;
172    let hops = relay_hops(controls);
173    let relay_copies = hops.checked_mul(padded).ok_or(QdnfError::Range)?;
174    let retry_bytes = retry_count.checked_mul(padded).ok_or(QdnfError::Range)?;
175
176    Ok(OverheadBudget {
177        padding_bytes,
178        relay_copies,
179        handshake_bytes: handshake_bytes_hybrid(),
180        cover_bytes: cover_bytes_for(session_duration_ms, cover_on)?,
181        retry_bytes,
182        storage_bytes: padded,
183        crypto_work: crypto_work_units(profile),
184    })
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190    use crate::net::qdnf::profiles::catalog::{catalog_entry, control_set_from_predicates};
191
192    #[test]
193    fn padding_bucket_256() {
194        assert_eq!(pad_to_next_bucket(1, P1_PADDING_BUCKET).unwrap(), 256);
195        assert_eq!(pad_to_next_bucket(256, P1_PADDING_BUCKET).unwrap(), 256);
196        assert_eq!(pad_to_next_bucket(257, P1_PADDING_BUCKET).unwrap(), 512);
197        assert_eq!(pad_to_next_bucket(0, P1_PADDING_BUCKET).unwrap(), 0);
198    }
199
200    #[test]
201    fn padding_formula_is_ceiling_not_a_lookup() {
202        let bucket = P1_PADDING_BUCKET;
203        let size = 257u64;
204        let expected = ((size + bucket - 1) / bucket) * bucket;
205        assert_eq!(expected, 512);
206        assert_eq!(pad_to_next_bucket(size, bucket).unwrap(), expected);
207    }
208
209    #[test]
210    fn p1_one_byte_charges_padding_and_storage_separately() {
211        let controls = catalog_entry(ProtectionProfile::P1);
212        let app = 1u64;
213        let budget = estimate_overhead(ProtectionProfile::P1, &controls, app, 0, 0, false).unwrap();
214        let padded = pad_to_next_bucket(app, P1_PADDING_BUCKET).unwrap();
215        assert_eq!(padded, 256);
216        assert_eq!(budget.padding_bytes, padded - app);
217        assert_eq!(budget.padding_bytes, 255);
218        assert_eq!(budget.storage_bytes, padded);
219        assert_eq!(budget.relay_copies, 0);
220        assert_eq!(budget.cover_bytes, 0);
221        assert_eq!(budget.handshake_bytes, handshake_bytes_hybrid());
222        assert_eq!(budget.retry_bytes, 0);
223        let total = budget.padding_bytes
224            + budget.relay_copies
225            + budget.handshake_bytes
226            + budget.cover_bytes
227            + budget.retry_bytes
228            + budget.storage_bytes;
229        assert_eq!(budget.total_bytes().unwrap(), total);
230        assert_eq!(total, 255 + handshake_bytes_hybrid() + 256);
231        assert_eq!(budget.crypto_work, 2);
232    }
233
234    #[test]
235    fn p2_default_record_is_4kib() {
236        let controls = catalog_entry(ProtectionProfile::P2);
237        let budget = estimate_overhead(ProtectionProfile::P2, &controls, 1, 0, 0, false).unwrap();
238        assert_eq!(pad_to_next_bucket(1, P2_RECORD_BYTES).unwrap(), 4096);
239        assert_eq!(budget.padding_bytes, 4095);
240        assert_eq!(budget.storage_bytes, 4096);
241        assert_eq!(budget.crypto_work, 4);
242    }
243
244    #[test]
245    fn p3_relay_copies_are_two_hops_of_padded_record() {
246        let controls = catalog_entry(ProtectionProfile::P3);
247        let app = 1u64;
248        let budget = estimate_overhead(ProtectionProfile::P3, &controls, app, 0, 0, false).unwrap();
249        let padded = pad_to_next_bucket(app, P3_CELL_BYTES).unwrap();
250        assert_eq!(padded, 4096);
251        assert_eq!(budget.relay_copies, P3_RELAY_HOPS * padded);
252        assert_eq!(budget.relay_copies, 8192);
253        assert_eq!(budget.cover_bytes, 0);
254        assert_eq!(budget.crypto_work, 8);
255    }
256
257    #[test]
258    fn mandatory_cover_cannot_be_dropped() {
259        let mut predicates = [ControlPredicate::Authenticity; 10];
260        predicates[0] = ControlPredicate::Authenticity;
261        predicates[1] = ControlPredicate::Provenance;
262        predicates[2] = ControlPredicate::Integrity;
263        predicates[3] = ControlPredicate::ResourceControls;
264        predicates[4] = ControlPredicate::E2eConfidentiality;
265        predicates[5] = ControlPredicate::PrivateContacts;
266        predicates[6] = ControlPredicate::LabelInheritance;
267        predicates[7] = ControlPredicate::Revocation;
268        predicates[8] = ControlPredicate::ProtectedLocalKeys;
269        predicates[9] = ControlPredicate::CoverTraffic;
270        let controls = control_set_from_predicates(ProtectionProfile::P1, &predicates).unwrap();
271        assert_eq!(
272            estimate_overhead(ProtectionProfile::P1, &controls, 1, 1000, 0, true),
273            Err(QdnfError::Downgrade)
274        );
275        let kept = estimate_overhead(ProtectionProfile::P1, &controls, 1, 1000, 0, false).unwrap();
276        assert_eq!(kept.cover_bytes, P3_COVER_BYTES_PER_SEC);
277    }
278
279    #[test]
280    fn optional_cover_may_be_dropped() {
281        let controls = catalog_entry(ProtectionProfile::P1);
282        assert!(!controls.contains_predicate(ControlPredicate::CoverTraffic));
283        let dropped =
284            estimate_overhead(ProtectionProfile::P1, &controls, 1, 1000, 0, true).unwrap();
285        assert_eq!(dropped.cover_bytes, 0);
286    }
287
288    #[test]
289    fn isolated_bearer_has_zero_relay_copies() {
290        let controls = catalog_entry(ProtectionProfile::P4);
291        let budget = estimate_overhead(ProtectionProfile::P4, &controls, 1, 0, 0, false).unwrap();
292        assert_eq!(budget.relay_copies, 0);
293        assert_eq!(budget.crypto_work, 16);
294    }
295
296    #[test]
297    fn handshake_bytes_match_named_lengths() {
298        let expected = (ML_KEM_768_PK_LEN
299            + X25519_LEN
300            + ML_KEM_768_CT_LEN
301            + X25519_LEN
302            + ML_DSA_65_SIG_LEN
303            + ED25519_SIG_LEN) as u64;
304        assert_eq!(handshake_bytes_hybrid(), expected);
305        assert_eq!(handshake_bytes_hybrid(), 5709);
306    }
307
308    #[test]
309    fn total_bytes_checked_add_overflows() {
310        let budget = OverheadBudget {
311            padding_bytes: u64::MAX,
312            relay_copies: 1,
313            handshake_bytes: 0,
314            cover_bytes: 0,
315            retry_bytes: 0,
316            storage_bytes: 0,
317            crypto_work: 0,
318        };
319        assert_eq!(budget.total_bytes(), Err(QdnfError::Range));
320    }
321
322    #[test]
323    fn p0_rejects_application_payload() {
324        let controls = catalog_entry(ProtectionProfile::P0);
325        assert_eq!(
326            estimate_overhead(ProtectionProfile::P0, &controls, 1, 0, 0, false),
327            Err(QdnfError::Denied)
328        );
329        let empty = estimate_overhead(ProtectionProfile::P0, &controls, 0, 0, 0, false).unwrap();
330        assert_eq!(empty.padding_bytes, 0);
331        assert_eq!(empty.storage_bytes, 0);
332        assert_eq!(empty.handshake_bytes, handshake_bytes_hybrid());
333    }
334}