atomic_lib 0.41.0-beta.2

Library for creating, storing, querying, validating and converting Atomic Data.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//! Self-verifying genesis certificate.
//!
//! A DID resource's identity is its genesis: the resource subject is
//! `did:ad:<base64url(signature)>`, where the signature is an Ed25519 signature
//! by the creating agent over this certificate's canonical bytes. The
//! certificate is carried *inline* on the resource (an immutable `genesis`
//! propval), so authorship + identity can be verified offline with no commit
//! fetch.
//!
//! The signed bytes ARE [`GenesisCert::encode`]'s output — a fixed binary
//! layout, deliberately *not* JSON, so there is no canonicalization ambiguity
//! in the trust path. The signature is not stored in the certificate: it is the
//! resource subject.
//!
//! See `planning/genesis-self-verifying.md`.

use crate::agents::{decode_base64, encode_base64};
use crate::errors::AtomicResult;

/// Current certificate format version. A signed layout can never change
/// retroactively — only new versions may be added, and verifiers dispatch on
/// this byte.
pub const GENESIS_VERSION_V1: u8 = 0x01;

/// `flags` bit 0: a 32-byte `stateHash` is present after the nonce.
const FLAG_HAS_STATE_HASH: u8 = 0b0000_0001;

/// The signed identity payload of a DID resource.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GenesisCert {
    /// Ed25519 public key of the creating agent (raw 32 bytes).
    pub signer_pubkey: [u8; 32],
    /// Creation time, Unix milliseconds.
    pub created_at: i64,
    /// CSPRNG uniqueness salt — guarantees a distinct DID even for the same
    /// agent + parent + millisecond (Ed25519 is deterministic).
    pub nonce: [u8; 16],
    /// Optional Blake3 of the canonical genesis projection — binds the initial
    /// content (authorship of the exact starting state).
    pub state_hash: Option<[u8; 32]>,
    /// The ORIGINAL parent subject (immutable provenance — distinct from the
    /// resource's current, mutable `parent` propval).
    pub parent: String,
    /// The resource's drive DID. Immutable — a resource effectively never moves
    /// between drives. Binding it into the signed identity makes rights checks
    /// drive-first and race-free, and lets did: subjects be drive-scoped in the
    /// watched-query index. See `planning/genesis-self-verifying.md`.
    pub drive: String,
}

impl GenesisCert {
    /// Serialize to the canonical v1 binary layout (little-endian integers).
    /// These bytes are exactly what gets signed/verified.
    pub fn encode(&self) -> Vec<u8> {
        let parent_bytes = self.parent.as_bytes();
        let drive_bytes = self.drive.as_bytes();
        let mut out = Vec::with_capacity(
            2 + 32 + 8 + 16 + 32 + 2 + parent_bytes.len() + 2 + drive_bytes.len(),
        );

        out.push(GENESIS_VERSION_V1);
        let mut flags = 0u8;
        if self.state_hash.is_some() {
            flags |= FLAG_HAS_STATE_HASH;
        }
        out.push(flags);

        out.extend_from_slice(&self.signer_pubkey);
        out.extend_from_slice(&self.created_at.to_le_bytes());
        out.extend_from_slice(&self.nonce);

        if let Some(hash) = &self.state_hash {
            out.extend_from_slice(hash);
        }

        // parent: u16 length prefix + UTF-8.
        let parent_len: u16 = parent_bytes
            .len()
            .try_into()
            .expect("genesis parent subject exceeds 65535 bytes");
        out.extend_from_slice(&parent_len.to_le_bytes());
        out.extend_from_slice(parent_bytes);

        // drive: u16 length prefix + UTF-8.
        let drive_len: u16 = drive_bytes
            .len()
            .try_into()
            .expect("genesis drive subject exceeds 65535 bytes");
        out.extend_from_slice(&drive_len.to_le_bytes());
        out.extend_from_slice(drive_bytes);

        out
    }

    /// Parse the canonical binary layout. Rejects unknown versions, truncated
    /// input, and trailing bytes.
    pub fn decode(bytes: &[u8]) -> AtomicResult<Self> {
        fn take<'a>(bytes: &'a [u8], cursor: &mut usize, n: usize) -> AtomicResult<&'a [u8]> {
            let end = *cursor + n;
            if end > bytes.len() {
                return Err("Genesis certificate is truncated".into());
            }
            let slice = &bytes[*cursor..end];
            *cursor = end;
            Ok(slice)
        }

        let mut cursor = 0;
        let header = take(bytes, &mut cursor, 2)?;
        let version = header[0];
        if version != GENESIS_VERSION_V1 {
            return Err(format!("Unsupported genesis certificate version {version}").into());
        }
        let flags = header[1];

        let mut signer_pubkey = [0u8; 32];
        signer_pubkey.copy_from_slice(take(bytes, &mut cursor, 32)?);

        let created_at = i64::from_le_bytes(take(bytes, &mut cursor, 8)?.try_into().unwrap());

        let mut nonce = [0u8; 16];
        nonce.copy_from_slice(take(bytes, &mut cursor, 16)?);

        let state_hash = if flags & FLAG_HAS_STATE_HASH != 0 {
            let mut hash = [0u8; 32];
            hash.copy_from_slice(take(bytes, &mut cursor, 32)?);
            Some(hash)
        } else {
            None
        };

        let parent_len =
            u16::from_le_bytes(take(bytes, &mut cursor, 2)?.try_into().unwrap()) as usize;
        let parent = String::from_utf8(take(bytes, &mut cursor, parent_len)?.to_vec())
            .map_err(|e| format!("Genesis parent is not valid UTF-8: {e}"))?;

        let drive_len =
            u16::from_le_bytes(take(bytes, &mut cursor, 2)?.try_into().unwrap()) as usize;
        let drive = String::from_utf8(take(bytes, &mut cursor, drive_len)?.to_vec())
            .map_err(|e| format!("Genesis drive is not valid UTF-8: {e}"))?;

        if cursor != bytes.len() {
            return Err("Genesis certificate has trailing bytes".into());
        }

        Ok(Self {
            signer_pubkey,
            created_at,
            nonce,
            state_hash,
            parent,
            drive,
        })
    }

    /// The signing agent's DID (`did:ad:agent:<pubkey>`), so callers can
    /// cross-check the certificate's signer against `createdBy`.
    pub fn signer_did(&self) -> String {
        format!("did:ad:agent:{}", encode_base64(&self.signer_pubkey))
    }

    /// The resource subject that a given signature implies.
    pub fn subject_for_signature(signature: &str) -> String {
        format!("did:ad:{signature}")
    }

    /// Sign the certificate with an Ed25519 private key (32-byte seed, base64).
    /// Returns the signature (base64url); the resource subject is
    /// `did:ad:<signature>`. Errors if the key does not match `signer_pubkey`.
    pub fn sign(&self, private_key: &str) -> AtomicResult<String> {
        use ed25519_dalek::{Signer, SigningKey};

        let seed: [u8; 32] = decode_base64(private_key)?
            .try_into()
            .map_err(|_| "Ed25519 private key must be 32 bytes")?;
        let signing_key = SigningKey::from_bytes(&seed);
        if signing_key.verifying_key().as_bytes() != &self.signer_pubkey {
            return Err("Genesis signer pubkey does not match the signing key".into());
        }
        let signature = signing_key.sign(&self.encode());
        Ok(encode_base64(&signature.to_bytes()))
    }

    /// Verify `signature` (base64) is a valid Ed25519 signature of this
    /// certificate by `signer_pubkey`. The caller separately confirms
    /// [`Self::subject_for_signature`] equals the resource subject (binding the
    /// signature to the DID), and that `signer_pubkey` matches `createdBy`.
    pub fn verify(&self, signature: &str) -> AtomicResult<()> {
        use ed25519_dalek::Verifier;

        let verifying_key = ed25519_dalek::VerifyingKey::from_bytes(&self.signer_pubkey)
            .map_err(|e| format!("Invalid genesis signer pubkey: {e}"))?;
        let sig_bytes: [u8; 64] = decode_base64(signature)?
            .try_into()
            .map_err(|_| "Ed25519 signature must be 64 bytes")?;
        let sig = ed25519_dalek::Signature::from_bytes(&sig_bytes);
        verifying_key
            .verify(&self.encode(), &sig)
            .map_err(|_| "Genesis certificate signature is invalid".into())
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use ed25519_dalek::SigningKey;

    /// Deterministic signing key for tests. Returns (private_key_b64, pubkey32).
    fn test_key(seed_byte: u8) -> (String, [u8; 32]) {
        let seed = [seed_byte; 32];
        let signing_key = SigningKey::from_bytes(&seed);
        let pubkey = *signing_key.verifying_key().as_bytes();
        (encode_base64(&seed), pubkey)
    }

    fn sample(pubkey: [u8; 32], state_hash: Option<[u8; 32]>) -> GenesisCert {
        GenesisCert {
            signer_pubkey: pubkey,
            created_at: 1_780_000_123_456,
            nonce: [7u8; 16],
            state_hash,
            parent: "https://example.com/parent".to_string(),
            drive: "https://example.com/drive".to_string(),
        }
    }

    #[test]
    fn encode_decode_roundtrip_without_state_hash() {
        let (_pk, pubkey) = test_key(1);
        let cert = sample(pubkey, None);
        let decoded = GenesisCert::decode(&cert.encode()).unwrap();
        assert_eq!(cert, decoded);
        // Layout: 2 header + 32 pubkey + 8 createdAt + 16 nonce
        //         + 2 len + parent + 2 len + drive.
        assert_eq!(
            cert.encode().len(),
            2 + 32
                + 8
                + 16
                + 2
                + "https://example.com/parent".len()
                + 2
                + "https://example.com/drive".len()
        );
    }

    #[test]
    fn known_byte_vector_v1() {
        // This exact vector is pinned identically in the TypeScript mirror
        // (`browser/lib/src/genesis.test.ts`). If either side drifts, a
        // browser-minted DID stops verifying server-side. Change only with a
        // new version byte + both sides updated.
        let cert = GenesisCert {
            signer_pubkey: [1u8; 32],
            created_at: 1,
            nonce: [2u8; 16],
            state_hash: None,
            parent: "x".to_string(),
            drive: "d".to_string(),
        };

        let mut expected = vec![0x01u8, 0x00]; // version, flags (no stateHash)
        expected.extend_from_slice(&[1u8; 32]); // signer pubkey
        expected.extend_from_slice(&1i64.to_le_bytes()); // createdAt
        expected.extend_from_slice(&[2u8; 16]); // nonce
        expected.extend_from_slice(&1u16.to_le_bytes()); // parent length
        expected.push(b'x');
        expected.extend_from_slice(&1u16.to_le_bytes()); // drive length
        expected.push(b'd');

        assert_eq!(cert.encode(), expected);
    }

    #[test]
    fn cross_lang_signature_vector_v1() {
        // Ed25519 is deterministic (RFC 8032), so signing the SAME cert with the
        // SAME seed must yield this EXACT signature/DID in both Rust and the TS
        // mirror (`browser/lib/src/genesis.test.ts`). That byte-for-byte match
        // is what lets a browser-minted DID verify server-side (and vice versa).
        // If either side drifts, this vector fails on one of them.
        let seed = [7u8; 32];
        let signing_key = SigningKey::from_bytes(&seed);
        let pubkey = *signing_key.verifying_key().as_bytes();
        assert_eq!(
            encode_base64(&pubkey),
            "6kpsY-KcUgq-9VB7Ey7F-ZVHdq6-vnuSQh7qaRRG0iw"
        );
        let cert = GenesisCert {
            signer_pubkey: pubkey,
            created_at: 1,
            nonce: [2u8; 16],
            state_hash: None,
            parent: "x".to_string(),
            drive: "d".to_string(),
        };
        let sig = cert.sign(&encode_base64(&seed)).unwrap();
        assert_eq!(
            sig,
            "71Igt-CKD2nhZZn4aKCe8tetVUTCgMMqJ67d97Wrb3pT3LFazyP1lGJjAw2Gg9KY0daGHhHPXj3xFMWEmYVdCw"
        );
        assert_eq!(
            GenesisCert::subject_for_signature(&sig),
            "did:ad:71Igt-CKD2nhZZn4aKCe8tetVUTCgMMqJ67d97Wrb3pT3LFazyP1lGJjAw2Gg9KY0daGHhHPXj3xFMWEmYVdCw"
        );
        cert.verify(&sig).unwrap();
    }

    #[test]
    fn encode_decode_roundtrip_with_state_hash() {
        let (_pk, pubkey) = test_key(2);
        let cert = sample(pubkey, Some([9u8; 32]));
        let bytes = cert.encode();
        assert_eq!(bytes[1] & FLAG_HAS_STATE_HASH, FLAG_HAS_STATE_HASH);
        assert_eq!(GenesisCert::decode(&bytes).unwrap(), cert);
    }

    #[test]
    fn sign_then_verify_succeeds_and_derives_subject() {
        let (private_key, pubkey) = test_key(3);
        let cert = sample(pubkey, Some([1u8; 32]));

        let signature = cert.sign(&private_key).unwrap();
        cert.verify(&signature).unwrap();

        let subject = GenesisCert::subject_for_signature(&signature);
        assert!(subject.starts_with("did:ad:"));
        assert_eq!(
            cert.signer_did(),
            format!("did:ad:agent:{}", encode_base64(&pubkey))
        );
    }

    #[test]
    fn signing_with_wrong_key_is_rejected() {
        let (_pk1, pubkey1) = test_key(4);
        let (private_key2, _pubkey2) = test_key(5);
        let cert = sample(pubkey1, None);
        // Signing key #2 does not match the cert's signer pubkey #1.
        assert!(cert.sign(&private_key2).is_err());
    }

    #[test]
    fn tampered_cert_fails_verification() {
        let (private_key, pubkey) = test_key(6);
        let cert = sample(pubkey, None);
        let signature = cert.sign(&private_key).unwrap();

        // A cert with any field changed must not verify against the signature.
        let mut tampered = cert.clone();
        tampered.created_at += 1;
        assert!(tampered.verify(&signature).is_err());

        let mut tampered2 = cert.clone();
        tampered2.parent = "https://example.com/evil".to_string();
        assert!(tampered2.verify(&signature).is_err());
    }

    #[test]
    fn decode_rejects_bad_version_truncation_and_trailing() {
        let (_pk, pubkey) = test_key(7);
        let cert = sample(pubkey, None);
        let bytes = cert.encode();

        let mut bad_version = bytes.clone();
        bad_version[0] = 0xFF;
        assert!(GenesisCert::decode(&bad_version).is_err());

        assert!(GenesisCert::decode(&bytes[..bytes.len() - 3]).is_err());

        let mut trailing = bytes.clone();
        trailing.push(0);
        assert!(GenesisCert::decode(&trailing).is_err());
    }

    fn hex(bytes: &[u8]) -> String {
        bytes.iter().map(|b| format!("{b:02x}")).collect()
    }

    fn unhex(s: &str) -> Vec<u8> {
        (0..s.len())
            .step_by(2)
            .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
            .collect()
    }

    struct VectorInput {
        seed: u8,
        created_at: i64,
        nonce: [u8; 16],
        state_hash: Option<[u8; 32]>,
        parent: &'static str,
        drive: &'static str,
    }

    /// The fixed inputs that define the golden cross-language vectors. Both the
    /// generator and the regression test below drive off this one list, so they
    /// can never drift.
    fn golden_inputs() -> Vec<VectorInput> {
        let ascending = {
            let mut n = [0u8; 16];
            for (i, b) in n.iter_mut().enumerate() {
                *b = i as u8;
            }
            n
        };
        vec![
            // Typical: DID parent + drive, no stateHash.
            VectorInput {
                seed: 1,
                created_at: 1_700_000_000_000,
                nonce: [0x11; 16],
                state_hash: None,
                parent: "did:ad:parentAAAA",
                drive: "did:ad:driveAAAA",
            },
            // Top-level: empty parent, createdAt 0, ascending nonce.
            VectorInput {
                seed: 2,
                created_at: 0,
                nonce: ascending,
                state_hash: None,
                parent: "",
                drive: "did:ad:driveBBBB",
            },
            // Flagged stateHash present + an HTTP-URL parent (u16 length-prefix,
            // UTF-8) — pins the optional-field layout the TS side must match.
            VectorInput {
                seed: 3,
                created_at: 1_699_999_999_999,
                nonce: [0xAB; 16],
                state_hash: Some([0xCD; 32]),
                parent: "https://example.com/parent",
                drive: "did:ad:driveCCCC",
            },
        ]
    }

    fn cert_for(input: &VectorInput) -> (String, GenesisCert) {
        let (private_key, pubkey) = test_key(input.seed);
        (
            private_key,
            GenesisCert {
                signer_pubkey: pubkey,
                created_at: input.created_at,
                nonce: input.nonce,
                state_hash: input.state_hash,
                parent: input.parent.into(),
                drive: input.drive.into(),
            },
        )
    }

    /// Emits the golden-vector fixture to stdout. Run with `--nocapture` and
    /// paste the block between the markers into `genesis_test_vectors.json`.
    /// `#[ignore]` so it doesn't run in the normal suite; the regression test
    /// below is what actually guards the format.
    #[test]
    #[ignore = "generator: run with --nocapture to regenerate the fixture"]
    fn generate_golden_vectors() {
        let vectors: Vec<_> = golden_inputs()
            .iter()
            .map(|input| {
                let (private_key, cert) = cert_for(input);
                let signature = cert.sign(&private_key).unwrap();
                serde_json::json!({
                    "seedByte": input.seed,
                    "privateKeyBase64": private_key,
                    "pubKeyHex": hex(&cert.signer_pubkey),
                    "createdAt": cert.created_at,
                    "nonceHex": hex(&cert.nonce),
                    "stateHashHex": cert.state_hash.map(|h| hex(&h)),
                    "parent": cert.parent,
                    "drive": cert.drive,
                    "certBytesHex": hex(&cert.encode()),
                    "signature": signature,
                    "did": GenesisCert::subject_for_signature(&signature),
                    "signerDid": cert.signer_did(),
                })
            })
            .collect();
        let doc = serde_json::json!({
            "_comment": "Golden cross-language vectors for the v1 genesis certificate. \
                Both the Rust GenesisCert and the browser TS implementation MUST reproduce \
                every field. Byte fields are hex; signature / did / signerDid use \
                base64url-no-pad. Seeds are [seedByte; 32] Ed25519 seeds — TEST KEYS ONLY. \
                Regenerate via `cargo test -p atomic_lib genesis::test::generate_golden_vectors \
                -- --ignored --nocapture`.",
            "version": 1,
            "vectors": vectors,
        });
        println!(
            "GOLDEN_START\n{}\nGOLDEN_END",
            serde_json::to_string_pretty(&doc).unwrap()
        );
    }

    /// Pins the Rust reference implementation to the committed cross-language
    /// fixture: for every golden input, Rust must produce byte-identical cert
    /// bytes, the same signature, DID, and signer DID. The browser TS
    /// `GenesisCert` runs the SAME fixture (`genesis_test_vectors.json`) — this
    /// is the contract that keeps the two byte-for-byte in agreement. If this
    /// fails after an intentional change, regenerate with `generate_golden_vectors`
    /// AND update the TS side; a signed layout must never change silently.
    #[test]
    fn matches_the_golden_vectors() {
        let fixture: serde_json::Value =
            serde_json::from_str(include_str!("genesis_test_vectors.json")).unwrap();
        let vectors = fixture["vectors"].as_array().unwrap();
        let inputs = golden_inputs();
        assert_eq!(
            vectors.len(),
            inputs.len(),
            "fixture vector count drifted from golden_inputs — regenerate the fixture"
        );

        for (input, expected) in inputs.iter().zip(vectors) {
            let (private_key, cert) = cert_for(input);
            let signature = cert.sign(&private_key).unwrap();
            let did = GenesisCert::subject_for_signature(&signature);

            assert_eq!(
                hex(&cert.encode()),
                expected["certBytesHex"].as_str().unwrap(),
                "cert bytes differ for seed {}",
                input.seed
            );
            assert_eq!(signature, expected["signature"].as_str().unwrap());
            assert_eq!(did, expected["did"].as_str().unwrap());
            assert_eq!(cert.signer_did(), expected["signerDid"].as_str().unwrap());

            // The fixture must also decode back to the same cert, so the TS
            // side has a decode target too, not just an encode one.
            assert_eq!(
                GenesisCert::decode(&unhex(expected["certBytesHex"].as_str().unwrap())).unwrap(),
                cert
            );
        }
    }
}