publet-core 0.2.0

Objects, canonical CBOR, content identifiers, and signatures.
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
//! Objects and the verification type state (Sections 4.3 and 4.5).
//!
//! Parsing yields an [`Unverified<Object>`]. Only [`Verified<Object>`] is
//! accepted by the graph, evaluation, and store crates, and the sole way to
//! obtain one is [`Unverified::verify`], which checks the bytes against the
//! identifier the caller asked for. Indexing an object whose identity was
//! never confirmed is therefore not a mistake that can be made: no function
//! exists that would accept it.
//!
//! # Examples
//!
//! ```
//! use publet_core::{Cid, HashAlg, Object};
//!
//! const AUTHOR: &str =
//!     "pub:sha2-256:z7uu6enmjz5gfxa5jtqjx4kynsm3chepcvqtv5s5g7zfj4y2iwra";
//!
//! let bytes = Object::builder("claim.prose", AUTHOR)
//!     .created("2026-09-12T10:00:00Z")
//!     .build()?;
//! let cid = Cid::of(&bytes, HashAlg::Sha2_256);
//!
//! let parsed = Object::parse(&bytes)?;
//! let verified = parsed.verify(&cid)?;
//! assert_eq!(verified.object().kind(), "claim.prose");
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use std::collections::BTreeMap;

use thiserror::Error;

use crate::cbor::{self, Value};
use crate::{CanonError, Cid, CidError};

/// Reasons an object is not well formed.
#[derive(Debug, Error, PartialEq, Eq, Clone)]
#[non_exhaustive]
pub enum ObjectError {
    /// The bytes were not canonical CBOR.
    #[error(transparent)]
    Canonical(#[from] CanonError),

    /// The top-level item was not a map.
    #[error("an object must be a map, found {found}")]
    NotAMap {
        /// What the top-level item actually was.
        found: &'static str,
    },

    /// A required header field was absent.
    #[error("missing required field `{field}`")]
    MissingField {
        /// The absent field.
        field: &'static str,
    },

    /// A header field had the wrong type.
    #[error("field `{field}` must be {expected}")]
    WrongType {
        /// The offending field.
        field: &'static str,
        /// What the specification requires.
        expected: &'static str,
    },

    /// The object declares a protocol version this build does not implement.
    ///
    /// Section 15 requires rejecting rather than attempting partial
    /// interpretation: a later version may give an existing field a
    /// different meaning, and reading it under this version's rules would
    /// produce a confident wrong answer rather than an error.
    #[error("unsupported protocol version {found}; this build implements {expected}")]
    UnsupportedVersion {
        /// The version the object declares.
        found: String,
        /// The version this build implements.
        expected: &'static str,
    },

    /// An unrecognized field appeared at the top level.
    #[error("unknown top-level field `{field}`; extensions belong in `ext`")]
    UnknownField {
        /// The offending field.
        field: String,
    },

    /// A CID-valued field did not parse.
    #[error("field `{field}`: {source}")]
    BadCid {
        /// The offending field.
        field: &'static str,
        /// Why it did not parse.
        #[source]
        source: CidError,
    },

    /// The bytes did not hash to the identifier the caller asked for.
    #[error("identifier mismatch: bytes hash to {actual}, not {expected}")]
    IdentifierMismatch {
        /// The identifier requested.
        expected: String,
        /// The identifier the bytes actually have.
        actual: String,
    },
}

/// The protocol major version this build implements.
pub const PROTOCOL_VERSION: &str = "1";

/// A parsed object: its header, its body, and the bytes it came from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Object {
    protocol: String,
    kind: String,
    created: String,
    author: Cid,
    body: BTreeMap<String, Value>,
    prev: Option<Cid>,
    basis: Option<Cid>,
    ext: Option<BTreeMap<String, Value>>,
    bytes: Vec<u8>,
}

const HEADER_FIELDS: [&str; 8] = [
    "author", "basis", "body", "created", "ext", "prev", "pub", "type",
];

impl Object {
    /// Parse canonical bytes into an object whose identity is not yet checked.
    ///
    /// # Errors
    ///
    /// Returns [`ObjectError`] if the bytes are not canonical, if a required
    /// header field is absent or ill-typed, or if an unrecognized field
    /// appears at the top level.
    ///
    /// # Example
    ///
    /// ```
    /// use publet_core::{Cid, HashAlg, Object};
    ///
    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
    /// let bytes = Object::builder("claim.prose", AUTHOR)
    ///     .created("2026-10-05T00:00:00Z")
    ///     .build()?;
    ///
    /// // Parsing checks the form; verifying checks the identity.
    /// let unverified = Object::parse(&bytes)?;
    /// let verified = unverified.verify(&Cid::of(&bytes, HashAlg::Sha2_256))?;
    /// assert_eq!(verified.object().kind(), "claim.prose");
    /// # Ok::<(), publet_core::ObjectError>(())
    /// ```
    ///
    /// # Example: what is refused
    ///
    /// ```
    /// use publet_core::{Object, ObjectError};
    ///
    /// // The integer 1 written in two bytes instead of one: not canonical.
    /// assert!(matches!(Object::parse(&[0x18, 0x01]), Err(ObjectError::Canonical(_))));
    ///
    /// // Canonical CBOR, but not a map.
    /// assert!(matches!(Object::parse(&[0x01]), Err(ObjectError::NotAMap { .. })));
    /// ```
    pub fn parse(bytes: &[u8]) -> Result<Unverified<Self>, ObjectError> {
        let value = cbor::decode(bytes)?;
        let Value::Map(map) = value else {
            return Err(ObjectError::NotAMap {
                found: describe(&value),
            });
        };

        for key in map.keys() {
            if !HEADER_FIELDS.contains(&key.as_str()) {
                return Err(ObjectError::UnknownField { field: key.clone() });
            }
        }

        let protocol = text_field(&map, "pub")?;
        if protocol != PROTOCOL_VERSION {
            return Err(ObjectError::UnsupportedVersion {
                found: protocol,
                expected: PROTOCOL_VERSION,
            });
        }

        let object = Self {
            protocol,
            kind: text_field(&map, "type")?,
            created: text_field(&map, "created")?,
            author: cid_field(&map, "author")?,
            body: match map.get("body") {
                Some(Value::Map(m)) => m.clone(),
                Some(_) => {
                    return Err(ObjectError::WrongType {
                        field: "body",
                        expected: "a map",
                    });
                }
                None => return Err(ObjectError::MissingField { field: "body" }),
            },
            prev: match map.get("prev") {
                Some(_) => Some(cid_field(&map, "prev")?),
                None => None,
            },
            basis: match map.get("basis") {
                Some(_) => Some(cid_field(&map, "basis")?),
                None => None,
            },
            ext: match map.get("ext") {
                Some(Value::Map(m)) => Some(m.clone()),
                Some(_) => {
                    return Err(ObjectError::WrongType {
                        field: "ext",
                        expected: "a map",
                    });
                }
                None => None,
            },
            bytes: bytes.to_vec(),
        };
        Ok(Unverified(object))
    }

    /// Start building an object of `kind` authored by `author`.
    ///
    /// # Example
    ///
    /// ```
    /// use publet_core::{Object, cbor::Value};
    ///
    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
    /// let bytes = Object::builder("claim.prose", AUTHOR)
    ///     .created("2026-10-05T00:00:00Z")
    ///     .field("content", Value::Text("Water boils at 100 °C at sea level.".into()))
    ///     .build()?;
    /// assert_eq!(Object::parse(&bytes)?.peek().kind(), "claim.prose");
    /// # Ok::<(), publet_core::ObjectError>(())
    /// ```
    #[must_use]
    pub fn builder(kind: &str, author: &str) -> Builder {
        Builder {
            kind: kind.to_owned(),
            author: author.to_owned(),
            protocol: "1".to_owned(),
            created: None,
            body: BTreeMap::new(),
            prev: None,
            basis: None,
            ext: None,
        }
    }

    /// The protocol major version.
    ///
    /// # Example
    ///
    /// ```
    /// # use publet_core::{Cid, HashAlg, Object, cbor::Value};
    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
    /// # let bytes = Object::builder("claim.prose", AUTHOR)
    /// #     .created("2026-10-05T00:00:00Z")
    /// #     .field("content", Value::Text("Water boils at 100 °C at sea level.".into()))
    /// #     .build()?;
    /// # let object = Object::parse(&bytes)?.verify(&Cid::of(&bytes, HashAlg::Sha2_256))?.into_inner();
    /// assert_eq!(object.protocol(), publet_core::PROTOCOL_VERSION);
    /// # Ok::<(), publet_core::ObjectError>(())
    /// ```
    #[must_use]
    pub fn protocol(&self) -> &str {
        &self.protocol
    }

    /// The object type.
    ///
    /// # Example
    ///
    /// ```
    /// # use publet_core::{Cid, HashAlg, Object, cbor::Value};
    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
    /// # let bytes = Object::builder("claim.prose", AUTHOR)
    /// #     .created("2026-10-05T00:00:00Z")
    /// #     .field("content", Value::Text("Water boils at 100 °C at sea level.".into()))
    /// #     .build()?;
    /// # let object = Object::parse(&bytes)?.verify(&Cid::of(&bytes, HashAlg::Sha2_256))?.into_inner();
    /// assert_eq!(object.kind(), "claim.prose");
    /// # Ok::<(), publet_core::ObjectError>(())
    /// ```
    #[must_use]
    pub fn kind(&self) -> &str {
        &self.kind
    }

    /// The author's claimed creation instant.
    ///
    /// Section 4.3: this is an unverified claim. Use a timestamp
    /// attestation where correctness depends on time.
    ///
    /// # Example
    ///
    /// ```
    /// # use publet_core::{Cid, HashAlg, Object, cbor::Value};
    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
    /// # let bytes = Object::builder("claim.prose", AUTHOR)
    /// #     .created("2026-10-05T00:00:00Z")
    /// #     .field("content", Value::Text("Water boils at 100 °C at sea level.".into()))
    /// #     .build()?;
    /// # let object = Object::parse(&bytes)?.verify(&Cid::of(&bytes, HashAlg::Sha2_256))?.into_inner();
    /// assert_eq!(object.created(), "2026-10-05T00:00:00Z");
    /// # Ok::<(), publet_core::ObjectError>(())
    /// ```
    #[must_use]
    pub fn created(&self) -> &str {
        &self.created
    }

    /// The identifier of the signing key object.
    ///
    /// # Example
    ///
    /// ```
    /// # use publet_core::{Cid, HashAlg, Object, cbor::Value};
    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
    /// # let bytes = Object::builder("claim.prose", AUTHOR)
    /// #     .created("2026-10-05T00:00:00Z")
    /// #     .field("content", Value::Text("Water boils at 100 °C at sea level.".into()))
    /// #     .build()?;
    /// # let object = Object::parse(&bytes)?.verify(&Cid::of(&bytes, HashAlg::Sha2_256))?.into_inner();
    /// assert_eq!(object.author().to_string(), AUTHOR);
    /// # Ok::<(), publet_core::ObjectError>(())
    /// ```
    #[must_use]
    pub fn author(&self) -> &Cid {
        &self.author
    }

    /// The type-specific payload.
    ///
    /// # Example
    ///
    /// ```
    /// # use publet_core::{Cid, HashAlg, Object, cbor::Value};
    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
    /// # let bytes = Object::builder("claim.prose", AUTHOR)
    /// #     .created("2026-10-05T00:00:00Z")
    /// #     .field("content", Value::Text("Water boils at 100 °C at sea level.".into()))
    /// #     .build()?;
    /// # let object = Object::parse(&bytes)?.verify(&Cid::of(&bytes, HashAlg::Sha2_256))?.into_inner();
    /// assert_eq!(
    ///     object.body().get("content"),
    ///     Some(&Value::Text("Water boils at 100 °C at sea level.".into())),
    /// );
    /// # Ok::<(), publet_core::ObjectError>(())
    /// ```
    #[must_use]
    pub fn body(&self) -> &BTreeMap<String, Value> {
        &self.body
    }

    /// The author's previous object, if this one names it.
    ///
    /// # Example
    ///
    /// ```
    /// # use publet_core::{Cid, HashAlg, Object, cbor::Value};
    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
    /// # let bytes = Object::builder("claim.prose", AUTHOR)
    /// #     .created("2026-10-05T00:00:00Z")
    /// #     .field("content", Value::Text("Water boils at 100 °C at sea level.".into()))
    /// #     .build()?;
    /// # let object = Object::parse(&bytes)?.verify(&Cid::of(&bytes, HashAlg::Sha2_256))?.into_inner();
    /// // This object names no previous object.
    /// assert_eq!(object.prev(), None);
    /// # Ok::<(), publet_core::ObjectError>(())
    /// ```
    #[must_use]
    pub fn prev(&self) -> Option<&Cid> {
        self.prev.as_ref()
    }

    /// The state the author was looking at, if this one names it.
    ///
    /// Section 4.6. Advisory and never gating: nothing is overwritten
    /// (R1), so a stale basis cannot clobber anything. What it buys is
    /// that the interval between what an author read and what was true
    /// when their work landed is recorded rather than reconstructed.
    ///
    /// # Example
    ///
    /// ```
    /// # use publet_core::{Cid, HashAlg, Object, cbor::Value};
    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
    /// # let bytes = Object::builder("claim.prose", AUTHOR)
    /// #     .created("2026-10-05T00:00:00Z")
    /// #     .field("content", Value::Text("Water boils at 100 °C at sea level.".into()))
    /// #     .build()?;
    /// # let object = Object::parse(&bytes)?.verify(&Cid::of(&bytes, HashAlg::Sha2_256))?.into_inner();
    /// // This object names no basis.
    /// assert_eq!(object.basis(), None);
    /// # Ok::<(), publet_core::ObjectError>(())
    /// ```
    #[must_use]
    pub fn basis(&self) -> Option<&Cid> {
        self.basis.as_ref()
    }

    /// Extension fields, if present.
    ///
    /// # Example
    ///
    /// ```
    /// # use publet_core::{Cid, HashAlg, Object, cbor::Value};
    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
    /// # let bytes = Object::builder("claim.prose", AUTHOR)
    /// #     .created("2026-10-05T00:00:00Z")
    /// #     .field("content", Value::Text("Water boils at 100 °C at sea level.".into()))
    /// #     .build()?;
    /// # let object = Object::parse(&bytes)?.verify(&Cid::of(&bytes, HashAlg::Sha2_256))?.into_inner();
    /// // This object carries no extension fields.
    /// assert_eq!(object.ext(), None);
    /// # Ok::<(), publet_core::ObjectError>(())
    /// ```
    #[must_use]
    pub fn ext(&self) -> Option<&BTreeMap<String, Value>> {
        self.ext.as_ref()
    }

    /// The canonical bytes this object was parsed from.
    ///
    /// # Example
    ///
    /// ```
    /// # use publet_core::{Cid, HashAlg, Object, cbor::Value};
    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
    /// # let bytes = Object::builder("claim.prose", AUTHOR)
    /// #     .created("2026-10-05T00:00:00Z")
    /// #     .field("content", Value::Text("Water boils at 100 °C at sea level.".into()))
    /// #     .build()?;
    /// # let object = Object::parse(&bytes)?.verify(&Cid::of(&bytes, HashAlg::Sha2_256))?.into_inner();
    /// // The bytes are what the identifier is computed from.
    /// assert_eq!(object.bytes(), bytes.as_slice());
    /// assert!(Cid::of(&bytes, HashAlg::Sha2_256).verifies(object.bytes()));
    /// # Ok::<(), publet_core::ObjectError>(())
    /// ```
    #[must_use]
    pub fn bytes(&self) -> &[u8] {
        &self.bytes
    }
}

/// An object whose identity has not been checked.
///
/// Deliberately opaque: the inner object is reachable only by verifying it,
/// or by [`Unverified::peek`] for diagnostics that must not feed the graph.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unverified<T>(T);

impl Unverified<Object> {
    /// Confirm the bytes hash to `expected`.
    ///
    /// # Errors
    ///
    /// Returns [`ObjectError::IdentifierMismatch`] if they do not.
    ///
    /// # Example
    ///
    /// ```
    /// use publet_core::{Cid, HashAlg, Object, ObjectError};
    ///
    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
    /// let bytes = Object::builder("claim.prose", AUTHOR).created("2026-10-05T00:00:00Z").build()?;
    ///
    /// assert!(Object::parse(&bytes)?.verify(&Cid::of(&bytes, HashAlg::Sha2_256)).is_ok());
    ///
    /// // Bytes that are not the ones the identifier names are refused.
    /// let asked_for = Cid::of(b"something else", HashAlg::Sha2_256);
    /// assert!(matches!(
    ///     Object::parse(&bytes)?.verify(&asked_for),
    ///     Err(ObjectError::IdentifierMismatch { .. }),
    /// ));
    /// # Ok::<(), publet_core::ObjectError>(())
    /// ```
    pub fn verify(self, expected: &Cid) -> Result<Verified<Object>, ObjectError> {
        if expected.verifies(&self.0.bytes) {
            Ok(Verified(self.0))
        } else {
            Err(ObjectError::IdentifierMismatch {
                expected: expected.to_string(),
                actual: Cid::of(&self.0.bytes, expected.alg()).to_string(),
            })
        }
    }

    /// Borrow the object without verifying it.
    ///
    /// For error messages and inspection tools only. Nothing that indexes,
    /// evaluates, or stores should take this path.
    ///
    /// # Example
    ///
    /// ```
    /// use publet_core::Object;
    ///
    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
    /// let bytes = Object::builder("claim.prose", AUTHOR).created("2026-10-05T00:00:00Z").build()?;
    ///
    /// // For a diagnostic message only; nothing should act on an unverified object.
    /// let unverified = Object::parse(&bytes)?;
    /// assert_eq!(unverified.peek().kind(), "claim.prose");
    /// # Ok::<(), publet_core::ObjectError>(())
    /// ```
    #[must_use]
    pub fn peek(&self) -> &Object {
        &self.0
    }
}

/// An object whose bytes have been confirmed against its identifier.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Verified<T>(T);

impl Verified<Object> {
    /// Borrow the verified object.
    ///
    /// # Example
    ///
    /// ```
    /// use publet_core::{Cid, HashAlg, Object};
    ///
    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
    /// let bytes = Object::builder("claim.prose", AUTHOR).created("2026-10-05T00:00:00Z").build()?;
    /// let verified = Object::parse(&bytes)?.verify(&Cid::of(&bytes, HashAlg::Sha2_256))?;
    /// assert_eq!(verified.object().kind(), "claim.prose");
    /// # Ok::<(), publet_core::ObjectError>(())
    /// ```
    #[must_use]
    pub fn object(&self) -> &Object {
        &self.0
    }

    /// Take ownership of the verified object.
    ///
    /// # Example
    ///
    /// ```
    /// use publet_core::{Cid, HashAlg, Object};
    ///
    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
    /// let bytes = Object::builder("claim.prose", AUTHOR).created("2026-10-05T00:00:00Z").build()?;
    /// let object: Object = Object::parse(&bytes)?
    ///     .verify(&Cid::of(&bytes, HashAlg::Sha2_256))?
    ///     .into_inner();
    /// assert_eq!(object.kind(), "claim.prose");
    /// # Ok::<(), publet_core::ObjectError>(())
    /// ```
    #[must_use]
    pub fn into_inner(self) -> Object {
        self.0
    }
}

/// Builds an object and emits its canonical bytes.
#[derive(Debug, Clone)]
pub struct Builder {
    kind: String,
    author: String,
    protocol: String,
    created: Option<String>,
    body: BTreeMap<String, Value>,
    prev: Option<String>,
    basis: Option<String>,
    ext: Option<BTreeMap<String, Value>>,
}

impl Builder {
    /// Set the creation instant (RFC 3339 UTC, second precision).
    ///
    /// # Example
    ///
    /// ```
    /// use publet_core::Object;
    ///
    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
    /// let bytes = Object::builder("claim.prose", AUTHOR)
    ///     .created("2026-10-05T00:00:00Z")
    ///     .build()?;
    /// assert_eq!(Object::parse(&bytes)?.peek().created(), "2026-10-05T00:00:00Z");
    /// # Ok::<(), publet_core::ObjectError>(())
    /// ```
    #[must_use]
    pub fn created(mut self, when: &str) -> Self {
        self.created = Some(when.to_owned());
        self
    }

    /// Insert a body field.
    ///
    /// # Example
    ///
    /// ```
    /// use publet_core::{Object, cbor::Value};
    ///
    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
    /// // Fields may be added in any order; the encoding sorts them.
    /// let one = Object::builder("note", AUTHOR)
    ///     .created("2026-10-05T00:00:00Z")
    ///     .field("b", Value::Uint(2))
    ///     .field("a", Value::Uint(1))
    ///     .build()?;
    /// let other = Object::builder("note", AUTHOR)
    ///     .created("2026-10-05T00:00:00Z")
    ///     .field("a", Value::Uint(1))
    ///     .field("b", Value::Uint(2))
    ///     .build()?;
    /// assert_eq!(one, other);
    /// # Ok::<(), publet_core::ObjectError>(())
    /// ```
    #[must_use]
    pub fn field(mut self, key: &str, value: Value) -> Self {
        self.body.insert(key.to_owned(), value);
        self
    }

    /// Name the author's previous object.
    ///
    /// # Example
    ///
    /// ```
    /// use publet_core::{Cid, HashAlg, Object};
    ///
    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
    /// let first = Object::builder("note", AUTHOR).created("2026-10-05T00:00:00Z").build()?;
    /// let first_cid = Cid::of(&first, HashAlg::Sha2_256);
    ///
    /// let second = Object::builder("note", AUTHOR)
    ///     .created("2026-10-06T00:00:00Z")
    ///     .prev(&first_cid.to_string())
    ///     .build()?;
    /// assert_eq!(Object::parse(&second)?.peek().prev(), Some(&first_cid));
    /// # Ok::<(), publet_core::ObjectError>(())
    /// ```
    #[must_use]
    pub fn prev(mut self, cid: &str) -> Self {
        self.prev = Some(cid.to_owned());
        self
    }

    /// Name the state the author was looking at (Section 4.6).
    ///
    /// # Example
    ///
    /// ```
    /// use publet_core::{Cid, HashAlg, Object};
    ///
    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
    /// // The state the author had read when writing this.
    /// let read = Cid::of(b"the head the author was looking at", HashAlg::Sha2_256);
    /// let bytes = Object::builder("note", AUTHOR)
    ///     .created("2026-10-05T00:00:00Z")
    ///     .basis(&read.to_string())
    ///     .build()?;
    /// assert_eq!(Object::parse(&bytes)?.peek().basis(), Some(&read));
    /// # Ok::<(), publet_core::ObjectError>(())
    /// ```
    #[must_use]
    pub fn basis(mut self, cid: &str) -> Self {
        self.basis = Some(cid.to_owned());
        self
    }

    /// Emit canonical bytes.
    ///
    /// # Errors
    ///
    /// Returns [`ObjectError`] if a CID-valued field does not parse or if
    /// no creation instant was set.
    ///
    /// # Example
    ///
    /// ```
    /// use publet_core::{Object, ObjectError};
    ///
    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
    /// let bytes = Object::builder("note", AUTHOR).created("2026-10-05T00:00:00Z").build()?;
    /// assert!(Object::parse(&bytes).is_ok());
    ///
    /// // A creation instant is required.
    /// assert_eq!(
    ///     Object::builder("note", AUTHOR).build(),
    ///     Err(ObjectError::MissingField { field: "created" }),
    /// );
    ///
    /// // The author must be an identifier.
    /// assert!(matches!(
    ///     Object::builder("note", "not an identifier").created("2026-10-05T00:00:00Z").build(),
    ///     Err(ObjectError::BadCid { field: "author", .. }),
    /// ));
    /// # Ok::<(), publet_core::ObjectError>(())
    /// ```
    pub fn build(self) -> Result<Vec<u8>, ObjectError> {
        let created = self
            .created
            .ok_or(ObjectError::MissingField { field: "created" })?;
        let author: Cid = self.author.parse().map_err(|source| ObjectError::BadCid {
            field: "author",
            source,
        })?;

        let mut map = BTreeMap::new();
        map.insert("author".to_owned(), Value::Text(author.to_string()));
        map.insert("body".to_owned(), Value::Map(self.body));
        map.insert("created".to_owned(), Value::Text(created));
        map.insert("pub".to_owned(), Value::Text(self.protocol));
        map.insert("type".to_owned(), Value::Text(self.kind));
        if let Some(prev) = self.prev {
            let parsed: Cid = prev.parse().map_err(|source| ObjectError::BadCid {
                field: "prev",
                source,
            })?;
            map.insert("prev".to_owned(), Value::Text(parsed.to_string()));
        }
        if let Some(basis) = self.basis {
            let parsed: Cid = basis.parse().map_err(|source| ObjectError::BadCid {
                field: "basis",
                source,
            })?;
            map.insert("basis".to_owned(), Value::Text(parsed.to_string()));
        }
        if let Some(ext) = self.ext {
            map.insert("ext".to_owned(), Value::Map(ext));
        }
        Ok(cbor::encode(&Value::Map(map)))
    }
}

fn describe(value: &Value) -> &'static str {
    match value {
        Value::Uint(_) | Value::Nint(_) => "an integer",
        Value::Bytes(_) => "a byte string",
        Value::Text(_) => "a text string",
        Value::Array(_) => "an array",
        Value::Map(_) => "a map",
        Value::Bool(_) => "a boolean",
        Value::Null => "null",
    }
}

fn text_field(map: &BTreeMap<String, Value>, field: &'static str) -> Result<String, ObjectError> {
    match map.get(field) {
        Some(Value::Text(s)) => Ok(s.clone()),
        Some(_) => Err(ObjectError::WrongType {
            field,
            expected: "a text string",
        }),
        None => Err(ObjectError::MissingField { field }),
    }
}

fn cid_field(map: &BTreeMap<String, Value>, field: &'static str) -> Result<Cid, ObjectError> {
    let text = text_field(map, field)?;
    text.parse()
        .map_err(|source| ObjectError::BadCid { field, source })
}