Skip to main content

qualia_core_db/net/qdnf/fabric/
instruments.rs

1//! Crypto-backed instrument taxonomy (F1 §§5–27) and N[X] provenance polynomials (§6.2.2).
2//!
3//! Every instrument in the Identifier Fabric anchors a typed relation without
4//! becoming or merging a `NaturalAgent`. Co-attestation bundles are evaluated over
5//! the provenance semiring `N[X]`: shared generator variables (`a*b + a*c = a*(b+c)`)
6//! expose correlated controller keys, devices, or clock calibrations so correlated
7//! signatures cannot satisfy an independent co-attestation quorum.
8
9use crate::net::qdnf::authority::Plane;
10use crate::net::qdnf::errors::QdnfError;
11
12/// Maximum generator indeterminates in a single attestation monomial in `N[X]`.
13pub const MAX_MONOMIAL_GENERATORS: usize = 4;
14/// Maximum attestation members in a bounded `CoAttestationBundle`.
15pub const MAX_ATTESTATION_MEMBERS: usize = 8;
16
17/// All 20 F1 §§5–27 cryptographic and naming instrument kinds.
18#[repr(u8)]
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub enum InstrumentKind {
21    NetworkLocator = 1,
22    MachineDeviceId = 2,
23    Did = 3,
24    QrcCoordinate = 4,
25    VerifiableCredential = 5,
26    BiometricFamily = 6,
27    BiometricInstance = 7,
28    ContentDigest = 8,
29    RelationScopedLocator = 9,
30    OnlineAccount = 10,
31    Wallet = 11,
32    BearerToken = 12,
33    PasswordVerifier = 13,
34    PrivateKeyMaterial = 14,
35    ZkpProof = 15,
36    SensorId = 16,
37    PlaceBoundSecret = 17,
38    PseudonymAlias = 18,
39    RoleCapacityGrant = 19,
40    AccountabilityArtifact = 20,
41}
42
43impl InstrumentKind {
44    pub const ALL: [Self; 20] = [
45        Self::NetworkLocator,
46        Self::MachineDeviceId,
47        Self::Did,
48        Self::QrcCoordinate,
49        Self::VerifiableCredential,
50        Self::BiometricFamily,
51        Self::BiometricInstance,
52        Self::ContentDigest,
53        Self::RelationScopedLocator,
54        Self::OnlineAccount,
55        Self::Wallet,
56        Self::BearerToken,
57        Self::PasswordVerifier,
58        Self::PrivateKeyMaterial,
59        Self::ZkpProof,
60        Self::SensorId,
61        Self::PlaceBoundSecret,
62        Self::PseudonymAlias,
63        Self::RoleCapacityGrant,
64        Self::AccountabilityArtifact,
65    ];
66
67    /// Primary fabric plane for this instrument kind (never `Plane::Entity`).
68    #[inline]
69    pub const fn plane(self) -> Plane {
70        match self {
71            Self::NetworkLocator => Plane::Handle,
72            _ => Plane::Instrument,
73        }
74    }
75
76    /// No instrument kind may promote to or substitute for a `NaturalAgent`.
77    #[inline]
78    pub const fn promote_to_natural_agent(self) -> Result<(), QdnfError> {
79        Err(QdnfError::Unauthorized)
80    }
81}
82
83/// Entity / agent plane taxonomy (F1 §3, F2 §§14–16).
84#[repr(u8)]
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86pub enum EntityAgentKind {
87    NaturalAgent = 1,
88    AiAgent = 2,
89    MachineDevice = 3,
90    Organization = 4,
91    LivingFloraFauna = 5,
92}
93
94impl EntityAgentKind {
95    pub const ALL: [Self; 5] = [
96        Self::NaturalAgent,
97        Self::AiAgent,
98        Self::MachineDevice,
99        Self::Organization,
100        Self::LivingFloraFauna,
101    ];
102
103    /// True iff this entity belongs to `D_living` (`D = D_living ⊔ D_artifact`).
104    /// Living entities use `living-SHACL` framing and are rejected by the OWL 2 artifact reasoner.
105    #[inline]
106    pub const fn is_living_domain(self) -> bool {
107        matches!(self, Self::NaturalAgent | Self::LivingFloraFauna)
108    }
109
110    /// Only `NaturalAgent` is admitted as a human `NaturalAgent`; AI agents,
111    /// machines, organizations, and non-human flora/fauna cannot promote to a human person.
112    #[inline]
113    pub const fn as_natural_agent(self) -> Result<(), QdnfError> {
114        match self {
115            Self::NaturalAgent => Ok(()),
116            Self::AiAgent
117            | Self::MachineDevice
118            | Self::Organization
119            | Self::LivingFloraFauna => Err(QdnfError::Unauthorized),
120        }
121    }
122}
123
124/// A monomial term in the provenance polynomial semiring `N[X]`.
125///
126/// Each non-zero entry in `generators[..len]` is an indeterminate `X_i` (e.g.
127/// controller key hash, device ID hash, clock calibration namespace hash).
128#[repr(C)]
129#[derive(Clone, Copy, Debug, PartialEq, Eq)]
130pub struct ProvenanceMonomial {
131    pub generators: [u64; MAX_MONOMIAL_GENERATORS],
132    pub len: u8,
133    pub coeff: u32,
134}
135
136impl ProvenanceMonomial {
137    pub const EMPTY: Self = Self {
138        generators: [0; MAX_MONOMIAL_GENERATORS],
139        len: 0,
140        coeff: 0,
141    };
142
143    /// Construct a monomial from up to 4 non-zero generator hashes.
144    pub fn from_generators(gens: &[u64]) -> Result<Self, QdnfError> {
145        if gens.is_empty() || gens.len() > MAX_MONOMIAL_GENERATORS {
146            return Err(QdnfError::Range);
147        }
148        let mut out = [0u64; MAX_MONOMIAL_GENERATORS];
149        let mut i = 0usize;
150        while i < gens.len() {
151            if gens[i] == 0 {
152                return Err(QdnfError::Malformed);
153            }
154            out[i] = gens[i];
155            i += 1;
156        }
157        Ok(Self {
158            generators: out,
159            len: gens.len() as u8,
160            coeff: 1,
161        })
162    }
163
164    #[inline]
165    pub fn active_generators(&self) -> &[u64] {
166        let n = (self.len as usize).min(MAX_MONOMIAL_GENERATORS);
167        &self.generators[..n]
168    }
169}
170
171/// Detect whether two provenance monomials share a common algebraic factor `a`
172/// (`a*b + a*c = a*(b + c)` in `N[X]`).
173#[inline]
174pub fn shared_generator_factor(a: &ProvenanceMonomial, b: &ProvenanceMonomial) -> Option<u64> {
175    let ga = a.active_generators();
176    let gb = b.active_generators();
177    let mut i = 0usize;
178    while i < ga.len() {
179        let x = ga[i];
180        if x != 0 {
181            let mut j = 0usize;
182            while j < gb.len() {
183                if x == gb[j] {
184                    return Some(x);
185                }
186                j += 1;
187            }
188        }
189        i += 1;
190    }
191    None
192}
193
194/// Time-bounded multi-instrument co-attestation bundle evaluated over `N[X]`.
195#[repr(C)]
196#[derive(Clone, Copy, Debug, PartialEq, Eq)]
197pub struct CoAttestationBundle {
198    pub claim_digest_hash: u64,
199    pub not_before: u64,
200    pub expires_at: u64,
201    pub monomials: [ProvenanceMonomial; MAX_ATTESTATION_MEMBERS],
202    pub member_count: u8,
203}
204
205impl CoAttestationBundle {
206    /// Check whether any pair of attestation monomials shares a generator `a`
207    /// (`a*b + a*c = a*(b + c)`).
208    pub fn first_shared_generator(&self) -> Option<u64> {
209        let n = (self.member_count as usize).min(MAX_ATTESTATION_MEMBERS);
210        let mut i = 0usize;
211        while i < n {
212            let mut j = i + 1;
213            while j < n {
214                if let Some(shared) = shared_generator_factor(&self.monomials[i], &self.monomials[j])
215                {
216                    return Some(shared);
217                }
218                j += 1;
219            }
220            i += 1;
221        }
222        None
223    }
224
225    /// Validate that the co-attestation bundle is active at `now_epoch`, has at least
226    /// `min_independent` members, and that no two members share a generator in `N[X]`.
227    pub fn verify_independent_quorum(
228        &self,
229        now_epoch: u64,
230        min_independent: usize,
231    ) -> Result<usize, QdnfError> {
232        if self.claim_digest_hash == 0 {
233            return Err(QdnfError::Malformed);
234        }
235        if self.not_before >= self.expires_at
236            || now_epoch < self.not_before
237            || now_epoch >= self.expires_at
238        {
239            return Err(QdnfError::Expired);
240        }
241        let n = (self.member_count as usize).min(MAX_ATTESTATION_MEMBERS);
242        if n < 2 || n < min_independent {
243            return Err(QdnfError::Unauthorized);
244        }
245        let mut i = 0usize;
246        while i < n {
247            if self.monomials[i].len == 0 || self.monomials[i].coeff == 0 {
248                return Err(QdnfError::Malformed);
249            }
250            i += 1;
251        }
252        if self.first_shared_generator().is_some() {
253            return Err(QdnfError::Conflict);
254        }
255        Ok(n)
256    }
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262
263    #[test]
264    fn all_twenty_instrument_kinds_refuse_natural_agent_promotion() {
265        assert_eq!(InstrumentKind::ALL.len(), 20);
266        for kind in InstrumentKind::ALL {
267            assert_eq!(
268                kind.promote_to_natural_agent(),
269                Err(QdnfError::Unauthorized)
270            );
271            assert_ne!(kind.plane(), Plane::Entity);
272        }
273    }
274
275    #[test]
276    fn entity_agent_kinds_enforce_living_partition_and_natural_agent_guard() {
277        assert!(EntityAgentKind::NaturalAgent.is_living_domain());
278        assert!(EntityAgentKind::LivingFloraFauna.is_living_domain());
279        assert!(!EntityAgentKind::AiAgent.is_living_domain());
280        assert!(!EntityAgentKind::MachineDevice.is_living_domain());
281        assert!(!EntityAgentKind::Organization.is_living_domain());
282
283        assert_eq!(EntityAgentKind::NaturalAgent.as_natural_agent(), Ok(()));
284        for non_human in [
285            EntityAgentKind::AiAgent,
286            EntityAgentKind::MachineDevice,
287            EntityAgentKind::Organization,
288            EntityAgentKind::LivingFloraFauna,
289        ] {
290            assert_eq!(non_human.as_natural_agent(), Err(QdnfError::Unauthorized));
291        }
292    }
293
294    #[test]
295    fn provenance_polynomial_detects_shared_generator_factor() {
296        // Monomial 1: a * b (controller key 0xA1, device 0xB1)
297        // Monomial 2: a * c (controller key 0xA1, device 0xC1)
298        // Sum: a*b + a*c = a*(b + c) -> shared generator 0xA1 exposed!
299        let m1 = ProvenanceMonomial::from_generators(&[0xA1, 0xB1]).unwrap();
300        let m2 = ProvenanceMonomial::from_generators(&[0xA1, 0xC1]).unwrap();
301        let m3 = ProvenanceMonomial::from_generators(&[0xD2, 0xE2]).unwrap();
302        assert_eq!(shared_generator_factor(&m1, &m2), Some(0xA1));
303        assert_eq!(shared_generator_factor(&m1, &m3), None);
304
305        let mut monomials = [ProvenanceMonomial::EMPTY; MAX_ATTESTATION_MEMBERS];
306        monomials[0] = m1;
307        monomials[1] = m2;
308        let correlated = CoAttestationBundle {
309            claim_digest_hash: 0x99,
310            not_before: 100,
311            expires_at: 200,
312            monomials,
313            member_count: 2,
314        };
315        assert_eq!(correlated.first_shared_generator(), Some(0xA1));
316        assert_eq!(
317            correlated.verify_independent_quorum(150, 2),
318            Err(QdnfError::Conflict)
319        );
320
321        monomials[1] = m3;
322        let independent = CoAttestationBundle {
323            claim_digest_hash: 0x99,
324            not_before: 100,
325            expires_at: 200,
326            monomials,
327            member_count: 2,
328        };
329        assert_eq!(independent.first_shared_generator(), None);
330        assert_eq!(independent.verify_independent_quorum(150, 2), Ok(2));
331        assert_eq!(
332            independent.verify_independent_quorum(250, 2),
333            Err(QdnfError::Expired)
334        );
335    }
336}