Skip to main content

qualia_core_db/governance/
law_packages.rs

1//! Law packages as signed content — provenance scaffold (T72).
2//!
3//! Law packages need signed content: who authored the dissolve rate;
4//! under what licence; whether it is physical or fictional. Provenance
5//! must travel with the law.
6
7use serde::{Deserialize, Serialize};
8
9/// Whether a law is grounded in physics or is fictional (narrative/game/
10/// simulation only).
11#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
12pub enum LawNature {
13    /// Grounded in physics — the law reflects real-world behaviour.
14    Physical,
15    /// Fictional — the law is for narrative, game, or simulation only.
16    Fictional,
17}
18
19/// A signed law package (T72). Provenance travels with the law.
20///
21/// The package contains the law's identity, authorship, licence, nature
22/// (physical vs fictional), content hash, and an Ed25519 signature by
23/// the author. The signature verifies that the author did indeed
24/// author this law package and that its content has not been tampered with.
25#[derive(Debug, Clone, Serialize, Deserialize)]
26pub struct LawPackage {
27    /// The law's identifier (hash of its content).
28    pub law_id: String,
29    /// Human-readable name.
30    pub name: String,
31    /// Author DID (who authored this law).
32    pub author_did: String,
33    /// Licence under which this law is published.
34    pub licence: String,
35    /// Whether this law is physical (grounded in physics) or
36    /// fictional (narrative/game/simulation only).
37    pub nature: LawNature,
38    /// Content hash of the law's formal definition.
39    pub content_hash: String,
40    /// Ed25519 signature by the author over the content hash.
41    #[serde(with = "serde_bytes")]
42    pub signature: Vec<u8>,
43    /// Unix timestamp when the law was authored.
44    pub authored_at_unix: u64,
45}
46
47impl LawPackage {
48    /// Create a new law package with the given metadata.
49    /// The signature should be set via `set_signature`.
50    pub fn new(
51        law_id: &str,
52        name: &str,
53        author_did: &str,
54        licence: &str,
55        nature: LawNature,
56        content_hash: &str,
57        authored_at_unix: u64,
58    ) -> Self {
59        Self {
60            law_id: law_id.to_string(),
61            name: name.to_string(),
62            author_did: author_did.to_string(),
63            licence: licence.to_string(),
64            nature,
65            content_hash: content_hash.to_string(),
66            signature: Vec::new(),
67            authored_at_unix,
68        }
69    }
70
71    /// The message that the signature covers: the content hash bytes.
72    /// The signature is over the content_hash string as UTF-8 bytes.
73    fn signature_message(&self) -> &[u8] {
74        self.content_hash.as_bytes()
75    }
76
77    /// Set the signature (typically after signing with the author's
78    /// private key).
79    pub fn set_signature(&mut self, signature: Vec<u8>) {
80        self.signature = signature;
81    }
82
83    /// Sign the package with the author's Ed25519 signing key.
84    pub fn sign(&mut self, signing_key: &ed25519_dalek::SigningKey) {
85        use ed25519_dalek::Signer;
86        let sig = signing_key.sign(self.signature_message());
87        self.signature = sig.to_bytes().to_vec();
88    }
89
90    /// Verify the Ed25519 signature against the author's public key.
91    ///
92    /// Returns `true` if the signature is valid for this package's
93    /// content hash, `false` otherwise (including if no signature is
94    /// set). Same dalek verifier on native and wasm32 — Ed25519 is
95    /// WASM-safe; a fail-closed stub would make signed law packages
96    /// unverifiable in the browser.
97    pub fn verify_signature(&self, public_key: &[u8]) -> bool {
98        use ed25519_dalek::{Signature, Verifier, VerifyingKey};
99        if self.signature.is_empty() || public_key.len() != 32 {
100            return false;
101        }
102        let pk_bytes: &[u8; 32] = match public_key.try_into() {
103            Ok(bytes) => bytes,
104            Err(_) => return false,
105        };
106        let pk = match VerifyingKey::from_bytes(pk_bytes) {
107            Ok(pk) => pk,
108            Err(_) => return false,
109        };
110        let sig = match Signature::from_slice(&self.signature) {
111            Ok(s) => s,
112            Err(_) => return false,
113        };
114        pk.verify(self.signature_message(), &sig).is_ok()
115    }
116
117    /// Serialize to JSON.
118    pub fn to_json(&self) -> Result<String, serde_json::Error> {
119        serde_json::to_string_pretty(self)
120    }
121
122    /// Deserialize from JSON.
123    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
124        serde_json::from_str(json)
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131    use ed25519_dalek::{Signer, SigningKey};
132
133    /// Generate a signing key from a fixed seed for deterministic tests.
134    fn test_signing_key(seed: u8) -> SigningKey {
135        let mut bytes = [0u8; 32];
136        bytes[0] = seed;
137        SigningKey::from_bytes(&bytes)
138    }
139
140    #[test]
141    fn law_package_construction() {
142        let pkg = LawPackage::new(
143            "law:crush:001",
144            "Crush Law",
145            "did:example:author",
146            "CC-BY-4.0",
147            LawNature::Physical,
148            "sha256:abc123",
149            1700000000,
150        );
151        assert_eq!(pkg.law_id, "law:crush:001");
152        assert_eq!(pkg.name, "Crush Law");
153        assert_eq!(pkg.author_did, "did:example:author");
154        assert_eq!(pkg.licence, "CC-BY-4.0");
155        assert_eq!(pkg.nature, LawNature::Physical);
156        assert_eq!(pkg.content_hash, "sha256:abc123");
157        assert!(pkg.signature.is_empty());
158        assert_eq!(pkg.authored_at_unix, 1700000000);
159    }
160
161    #[test]
162    fn law_nature_physical_vs_fictional() {
163        assert_ne!(LawNature::Physical, LawNature::Fictional);
164        assert_eq!(LawNature::Physical, LawNature::Physical);
165        assert_eq!(LawNature::Fictional, LawNature::Fictional);
166    }
167
168    #[test]
169    fn json_roundtrip() {
170        let mut pkg = LawPackage::new(
171            "law:001",
172            "Test Law",
173            "did:example:author",
174            "MIT",
175            LawNature::Fictional,
176            "sha256:deadbeef",
177            1700000000,
178        );
179        pkg.set_signature(vec![1, 2, 3, 4]);
180        let json = pkg.to_json().unwrap();
181        let restored = LawPackage::from_json(&json).unwrap();
182        assert_eq!(restored.law_id, "law:001");
183        assert_eq!(restored.name, "Test Law");
184        assert_eq!(restored.author_did, "did:example:author");
185        assert_eq!(restored.licence, "MIT");
186        assert_eq!(restored.nature, LawNature::Fictional);
187        assert_eq!(restored.content_hash, "sha256:deadbeef");
188        assert_eq!(restored.signature, vec![1, 2, 3, 4]);
189        assert_eq!(restored.authored_at_unix, 1700000000);
190    }
191
192    #[test]
193    fn verify_signature_with_correct_key() {
194        let signing_key = test_signing_key(1);
195        let verifying_key = signing_key.verifying_key();
196
197        let content_hash = "sha256:abc123def456";
198        let signature = signing_key.sign(content_hash.as_bytes());
199
200        let mut pkg = LawPackage::new(
201            "law:001",
202            "Test Law",
203            "did:example:author",
204            "MIT",
205            LawNature::Physical,
206            content_hash,
207            1700000000,
208        );
209        pkg.set_signature(signature.to_bytes().to_vec());
210
211        assert!(
212            pkg.verify_signature(&verifying_key.to_bytes()),
213            "signature should verify with correct public key"
214        );
215    }
216
217    #[test]
218    fn verify_signature_with_wrong_key_fails() {
219        let signing_key = test_signing_key(1);
220        let wrong_key = test_signing_key(2);
221        let wrong_verifying_key = wrong_key.verifying_key();
222
223        let content_hash = "sha256:abc123def456";
224        let signature = signing_key.sign(content_hash.as_bytes());
225
226        let mut pkg = LawPackage::new(
227            "law:001",
228            "Test Law",
229            "did:example:author",
230            "MIT",
231            LawNature::Physical,
232            content_hash,
233            1700000000,
234        );
235        pkg.set_signature(signature.to_bytes().to_vec());
236
237        assert!(
238            !pkg.verify_signature(&wrong_verifying_key.to_bytes()),
239            "signature should NOT verify with wrong public key"
240        );
241    }
242
243    #[test]
244    fn verify_signature_empty_signature_fails() {
245        let pkg = LawPackage::new(
246            "law:001",
247            "Test Law",
248            "did:example:author",
249            "MIT",
250            LawNature::Physical,
251            "sha256:abc",
252            1700000000,
253        );
254        assert!(
255            !pkg.verify_signature(&[0u8; 32]),
256            "empty signature should fail"
257        );
258    }
259
260    #[test]
261    fn verify_signature_tampered_content_fails() {
262        let signing_key = test_signing_key(1);
263        let verifying_key = signing_key.verifying_key();
264
265        let content_hash = "sha256:abc123def456";
266        let signature = signing_key.sign(content_hash.as_bytes());
267
268        let mut pkg = LawPackage::new(
269            "law:001",
270            "Test Law",
271            "did:example:author",
272            "MIT",
273            LawNature::Physical,
274            "sha256:TAMPERED",
275            1700000000,
276        );
277        pkg.set_signature(signature.to_bytes().to_vec());
278
279        assert!(
280            !pkg.verify_signature(&verifying_key.to_bytes()),
281            "tampered content hash should fail verification"
282        );
283    }
284
285    #[test]
286    fn sign_and_verify_roundtrip() {
287        let signing_key = test_signing_key(42);
288        let verifying_key = signing_key.verifying_key();
289
290        let mut pkg = LawPackage::new(
291            "law:dissolve:001",
292            "Dissolve Rate Law",
293            "did:example:curator",
294            "Apache-2.0",
295            LawNature::Physical,
296            "sha256:fedcba9876543210",
297            1710000000,
298        );
299        pkg.sign(&signing_key);
300        assert!(!pkg.signature.is_empty());
301        assert!(pkg.verify_signature(&verifying_key.to_bytes()));
302    }
303}