Skip to main content

publet_core/
object.rs

1//! Objects and the verification type state (Sections 4.3 and 4.5).
2//!
3//! Parsing yields an [`Unverified<Object>`]. Only [`Verified<Object>`] is
4//! accepted by the graph, evaluation, and store crates, and the sole way to
5//! obtain one is [`Unverified::verify`], which checks the bytes against the
6//! identifier the caller asked for. Indexing an object whose identity was
7//! never confirmed is therefore not a mistake that can be made: no function
8//! exists that would accept it.
9//!
10//! # Examples
11//!
12//! ```
13//! use publet_core::{Cid, HashAlg, Object};
14//!
15//! const AUTHOR: &str =
16//!     "pub:sha2-256:z7uu6enmjz5gfxa5jtqjx4kynsm3chepcvqtv5s5g7zfj4y2iwra";
17//!
18//! let bytes = Object::builder("claim.prose", AUTHOR)
19//!     .created("2026-09-12T10:00:00Z")
20//!     .build()?;
21//! let cid = Cid::of(&bytes, HashAlg::Sha2_256);
22//!
23//! let parsed = Object::parse(&bytes)?;
24//! let verified = parsed.verify(&cid)?;
25//! assert_eq!(verified.object().kind(), "claim.prose");
26//! # Ok::<(), Box<dyn std::error::Error>>(())
27//! ```
28
29use std::collections::BTreeMap;
30
31use thiserror::Error;
32
33use crate::cbor::{self, Value};
34use crate::{CanonError, Cid, CidError};
35
36/// Reasons an object is not well formed.
37#[derive(Debug, Error, PartialEq, Eq, Clone)]
38#[non_exhaustive]
39pub enum ObjectError {
40    /// The bytes were not canonical CBOR.
41    #[error(transparent)]
42    Canonical(#[from] CanonError),
43
44    /// The top-level item was not a map.
45    #[error("an object must be a map, found {found}")]
46    NotAMap {
47        /// What the top-level item actually was.
48        found: &'static str,
49    },
50
51    /// A required header field was absent.
52    #[error("missing required field `{field}`")]
53    MissingField {
54        /// The absent field.
55        field: &'static str,
56    },
57
58    /// A header field had the wrong type.
59    #[error("field `{field}` must be {expected}")]
60    WrongType {
61        /// The offending field.
62        field: &'static str,
63        /// What the specification requires.
64        expected: &'static str,
65    },
66
67    /// The object declares a protocol version this build does not implement.
68    ///
69    /// Section 15 requires rejecting rather than attempting partial
70    /// interpretation: a later version may give an existing field a
71    /// different meaning, and reading it under this version's rules would
72    /// produce a confident wrong answer rather than an error.
73    #[error("unsupported protocol version {found}; this build implements {expected}")]
74    UnsupportedVersion {
75        /// The version the object declares.
76        found: String,
77        /// The version this build implements.
78        expected: &'static str,
79    },
80
81    /// An unrecognized field appeared at the top level.
82    #[error("unknown top-level field `{field}`; extensions belong in `ext`")]
83    UnknownField {
84        /// The offending field.
85        field: String,
86    },
87
88    /// A CID-valued field did not parse.
89    #[error("field `{field}`: {source}")]
90    BadCid {
91        /// The offending field.
92        field: &'static str,
93        /// Why it did not parse.
94        #[source]
95        source: CidError,
96    },
97
98    /// The bytes did not hash to the identifier the caller asked for.
99    #[error("identifier mismatch: bytes hash to {actual}, not {expected}")]
100    IdentifierMismatch {
101        /// The identifier requested.
102        expected: String,
103        /// The identifier the bytes actually have.
104        actual: String,
105    },
106}
107
108/// The protocol major version this build implements.
109pub const PROTOCOL_VERSION: &str = "1";
110
111/// A parsed object: its header, its body, and the bytes it came from.
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct Object {
114    protocol: String,
115    kind: String,
116    created: String,
117    author: Cid,
118    body: BTreeMap<String, Value>,
119    prev: Option<Cid>,
120    basis: Option<Cid>,
121    ext: Option<BTreeMap<String, Value>>,
122    bytes: Vec<u8>,
123}
124
125const HEADER_FIELDS: [&str; 8] = [
126    "author", "basis", "body", "created", "ext", "prev", "pub", "type",
127];
128
129impl Object {
130    /// Parse canonical bytes into an object whose identity is not yet checked.
131    ///
132    /// # Errors
133    ///
134    /// Returns [`ObjectError`] if the bytes are not canonical, if a required
135    /// header field is absent or ill-typed, or if an unrecognized field
136    /// appears at the top level.
137    ///
138    /// # Example
139    ///
140    /// ```
141    /// use publet_core::{Cid, HashAlg, Object};
142    ///
143    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
144    /// let bytes = Object::builder("claim.prose", AUTHOR)
145    ///     .created("2026-10-05T00:00:00Z")
146    ///     .build()?;
147    ///
148    /// // Parsing checks the form; verifying checks the identity.
149    /// let unverified = Object::parse(&bytes)?;
150    /// let verified = unverified.verify(&Cid::of(&bytes, HashAlg::Sha2_256))?;
151    /// assert_eq!(verified.object().kind(), "claim.prose");
152    /// # Ok::<(), publet_core::ObjectError>(())
153    /// ```
154    ///
155    /// # Example: what is refused
156    ///
157    /// ```
158    /// use publet_core::{Object, ObjectError};
159    ///
160    /// // The integer 1 written in two bytes instead of one: not canonical.
161    /// assert!(matches!(Object::parse(&[0x18, 0x01]), Err(ObjectError::Canonical(_))));
162    ///
163    /// // Canonical CBOR, but not a map.
164    /// assert!(matches!(Object::parse(&[0x01]), Err(ObjectError::NotAMap { .. })));
165    /// ```
166    pub fn parse(bytes: &[u8]) -> Result<Unverified<Self>, ObjectError> {
167        let value = cbor::decode(bytes)?;
168        let Value::Map(map) = value else {
169            return Err(ObjectError::NotAMap {
170                found: describe(&value),
171            });
172        };
173
174        for key in map.keys() {
175            if !HEADER_FIELDS.contains(&key.as_str()) {
176                return Err(ObjectError::UnknownField { field: key.clone() });
177            }
178        }
179
180        let protocol = text_field(&map, "pub")?;
181        if protocol != PROTOCOL_VERSION {
182            return Err(ObjectError::UnsupportedVersion {
183                found: protocol,
184                expected: PROTOCOL_VERSION,
185            });
186        }
187
188        let object = Self {
189            protocol,
190            kind: text_field(&map, "type")?,
191            created: text_field(&map, "created")?,
192            author: cid_field(&map, "author")?,
193            body: match map.get("body") {
194                Some(Value::Map(m)) => m.clone(),
195                Some(_) => {
196                    return Err(ObjectError::WrongType {
197                        field: "body",
198                        expected: "a map",
199                    });
200                }
201                None => return Err(ObjectError::MissingField { field: "body" }),
202            },
203            prev: match map.get("prev") {
204                Some(_) => Some(cid_field(&map, "prev")?),
205                None => None,
206            },
207            basis: match map.get("basis") {
208                Some(_) => Some(cid_field(&map, "basis")?),
209                None => None,
210            },
211            ext: match map.get("ext") {
212                Some(Value::Map(m)) => Some(m.clone()),
213                Some(_) => {
214                    return Err(ObjectError::WrongType {
215                        field: "ext",
216                        expected: "a map",
217                    });
218                }
219                None => None,
220            },
221            bytes: bytes.to_vec(),
222        };
223        Ok(Unverified(object))
224    }
225
226    /// Start building an object of `kind` authored by `author`.
227    ///
228    /// # Example
229    ///
230    /// ```
231    /// use publet_core::{Object, cbor::Value};
232    ///
233    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
234    /// let bytes = Object::builder("claim.prose", AUTHOR)
235    ///     .created("2026-10-05T00:00:00Z")
236    ///     .field("content", Value::Text("Water boils at 100 °C at sea level.".into()))
237    ///     .build()?;
238    /// assert_eq!(Object::parse(&bytes)?.peek().kind(), "claim.prose");
239    /// # Ok::<(), publet_core::ObjectError>(())
240    /// ```
241    #[must_use]
242    pub fn builder(kind: &str, author: &str) -> Builder {
243        Builder {
244            kind: kind.to_owned(),
245            author: author.to_owned(),
246            protocol: "1".to_owned(),
247            created: None,
248            body: BTreeMap::new(),
249            prev: None,
250            basis: None,
251            ext: None,
252        }
253    }
254
255    /// The protocol major version.
256    ///
257    /// # Example
258    ///
259    /// ```
260    /// # use publet_core::{Cid, HashAlg, Object, cbor::Value};
261    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
262    /// # let bytes = Object::builder("claim.prose", AUTHOR)
263    /// #     .created("2026-10-05T00:00:00Z")
264    /// #     .field("content", Value::Text("Water boils at 100 °C at sea level.".into()))
265    /// #     .build()?;
266    /// # let object = Object::parse(&bytes)?.verify(&Cid::of(&bytes, HashAlg::Sha2_256))?.into_inner();
267    /// assert_eq!(object.protocol(), publet_core::PROTOCOL_VERSION);
268    /// # Ok::<(), publet_core::ObjectError>(())
269    /// ```
270    #[must_use]
271    pub fn protocol(&self) -> &str {
272        &self.protocol
273    }
274
275    /// The object type.
276    ///
277    /// # Example
278    ///
279    /// ```
280    /// # use publet_core::{Cid, HashAlg, Object, cbor::Value};
281    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
282    /// # let bytes = Object::builder("claim.prose", AUTHOR)
283    /// #     .created("2026-10-05T00:00:00Z")
284    /// #     .field("content", Value::Text("Water boils at 100 °C at sea level.".into()))
285    /// #     .build()?;
286    /// # let object = Object::parse(&bytes)?.verify(&Cid::of(&bytes, HashAlg::Sha2_256))?.into_inner();
287    /// assert_eq!(object.kind(), "claim.prose");
288    /// # Ok::<(), publet_core::ObjectError>(())
289    /// ```
290    #[must_use]
291    pub fn kind(&self) -> &str {
292        &self.kind
293    }
294
295    /// The author's claimed creation instant.
296    ///
297    /// Section 4.3: this is an unverified claim. Use a timestamp
298    /// attestation where correctness depends on time.
299    ///
300    /// # Example
301    ///
302    /// ```
303    /// # use publet_core::{Cid, HashAlg, Object, cbor::Value};
304    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
305    /// # let bytes = Object::builder("claim.prose", AUTHOR)
306    /// #     .created("2026-10-05T00:00:00Z")
307    /// #     .field("content", Value::Text("Water boils at 100 °C at sea level.".into()))
308    /// #     .build()?;
309    /// # let object = Object::parse(&bytes)?.verify(&Cid::of(&bytes, HashAlg::Sha2_256))?.into_inner();
310    /// assert_eq!(object.created(), "2026-10-05T00:00:00Z");
311    /// # Ok::<(), publet_core::ObjectError>(())
312    /// ```
313    #[must_use]
314    pub fn created(&self) -> &str {
315        &self.created
316    }
317
318    /// The identifier of the signing key object.
319    ///
320    /// # Example
321    ///
322    /// ```
323    /// # use publet_core::{Cid, HashAlg, Object, cbor::Value};
324    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
325    /// # let bytes = Object::builder("claim.prose", AUTHOR)
326    /// #     .created("2026-10-05T00:00:00Z")
327    /// #     .field("content", Value::Text("Water boils at 100 °C at sea level.".into()))
328    /// #     .build()?;
329    /// # let object = Object::parse(&bytes)?.verify(&Cid::of(&bytes, HashAlg::Sha2_256))?.into_inner();
330    /// assert_eq!(object.author().to_string(), AUTHOR);
331    /// # Ok::<(), publet_core::ObjectError>(())
332    /// ```
333    #[must_use]
334    pub fn author(&self) -> &Cid {
335        &self.author
336    }
337
338    /// The type-specific payload.
339    ///
340    /// # Example
341    ///
342    /// ```
343    /// # use publet_core::{Cid, HashAlg, Object, cbor::Value};
344    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
345    /// # let bytes = Object::builder("claim.prose", AUTHOR)
346    /// #     .created("2026-10-05T00:00:00Z")
347    /// #     .field("content", Value::Text("Water boils at 100 °C at sea level.".into()))
348    /// #     .build()?;
349    /// # let object = Object::parse(&bytes)?.verify(&Cid::of(&bytes, HashAlg::Sha2_256))?.into_inner();
350    /// assert_eq!(
351    ///     object.body().get("content"),
352    ///     Some(&Value::Text("Water boils at 100 °C at sea level.".into())),
353    /// );
354    /// # Ok::<(), publet_core::ObjectError>(())
355    /// ```
356    #[must_use]
357    pub fn body(&self) -> &BTreeMap<String, Value> {
358        &self.body
359    }
360
361    /// The author's previous object, if this one names it.
362    ///
363    /// # Example
364    ///
365    /// ```
366    /// # use publet_core::{Cid, HashAlg, Object, cbor::Value};
367    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
368    /// # let bytes = Object::builder("claim.prose", AUTHOR)
369    /// #     .created("2026-10-05T00:00:00Z")
370    /// #     .field("content", Value::Text("Water boils at 100 °C at sea level.".into()))
371    /// #     .build()?;
372    /// # let object = Object::parse(&bytes)?.verify(&Cid::of(&bytes, HashAlg::Sha2_256))?.into_inner();
373    /// // This object names no previous object.
374    /// assert_eq!(object.prev(), None);
375    /// # Ok::<(), publet_core::ObjectError>(())
376    /// ```
377    #[must_use]
378    pub fn prev(&self) -> Option<&Cid> {
379        self.prev.as_ref()
380    }
381
382    /// The state the author was looking at, if this one names it.
383    ///
384    /// Section 4.6. Advisory and never gating: nothing is overwritten
385    /// (R1), so a stale basis cannot clobber anything. What it buys is
386    /// that the interval between what an author read and what was true
387    /// when their work landed is recorded rather than reconstructed.
388    ///
389    /// # Example
390    ///
391    /// ```
392    /// # use publet_core::{Cid, HashAlg, Object, cbor::Value};
393    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
394    /// # let bytes = Object::builder("claim.prose", AUTHOR)
395    /// #     .created("2026-10-05T00:00:00Z")
396    /// #     .field("content", Value::Text("Water boils at 100 °C at sea level.".into()))
397    /// #     .build()?;
398    /// # let object = Object::parse(&bytes)?.verify(&Cid::of(&bytes, HashAlg::Sha2_256))?.into_inner();
399    /// // This object names no basis.
400    /// assert_eq!(object.basis(), None);
401    /// # Ok::<(), publet_core::ObjectError>(())
402    /// ```
403    #[must_use]
404    pub fn basis(&self) -> Option<&Cid> {
405        self.basis.as_ref()
406    }
407
408    /// Extension fields, if present.
409    ///
410    /// # Example
411    ///
412    /// ```
413    /// # use publet_core::{Cid, HashAlg, Object, cbor::Value};
414    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
415    /// # let bytes = Object::builder("claim.prose", AUTHOR)
416    /// #     .created("2026-10-05T00:00:00Z")
417    /// #     .field("content", Value::Text("Water boils at 100 °C at sea level.".into()))
418    /// #     .build()?;
419    /// # let object = Object::parse(&bytes)?.verify(&Cid::of(&bytes, HashAlg::Sha2_256))?.into_inner();
420    /// // This object carries no extension fields.
421    /// assert_eq!(object.ext(), None);
422    /// # Ok::<(), publet_core::ObjectError>(())
423    /// ```
424    #[must_use]
425    pub fn ext(&self) -> Option<&BTreeMap<String, Value>> {
426        self.ext.as_ref()
427    }
428
429    /// The canonical bytes this object was parsed from.
430    ///
431    /// # Example
432    ///
433    /// ```
434    /// # use publet_core::{Cid, HashAlg, Object, cbor::Value};
435    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
436    /// # let bytes = Object::builder("claim.prose", AUTHOR)
437    /// #     .created("2026-10-05T00:00:00Z")
438    /// #     .field("content", Value::Text("Water boils at 100 °C at sea level.".into()))
439    /// #     .build()?;
440    /// # let object = Object::parse(&bytes)?.verify(&Cid::of(&bytes, HashAlg::Sha2_256))?.into_inner();
441    /// // The bytes are what the identifier is computed from.
442    /// assert_eq!(object.bytes(), bytes.as_slice());
443    /// assert!(Cid::of(&bytes, HashAlg::Sha2_256).verifies(object.bytes()));
444    /// # Ok::<(), publet_core::ObjectError>(())
445    /// ```
446    #[must_use]
447    pub fn bytes(&self) -> &[u8] {
448        &self.bytes
449    }
450}
451
452/// An object whose identity has not been checked.
453///
454/// Deliberately opaque: the inner object is reachable only by verifying it,
455/// or by [`Unverified::peek`] for diagnostics that must not feed the graph.
456#[derive(Debug, Clone, PartialEq, Eq)]
457pub struct Unverified<T>(T);
458
459impl Unverified<Object> {
460    /// Confirm the bytes hash to `expected`.
461    ///
462    /// # Errors
463    ///
464    /// Returns [`ObjectError::IdentifierMismatch`] if they do not.
465    ///
466    /// # Example
467    ///
468    /// ```
469    /// use publet_core::{Cid, HashAlg, Object, ObjectError};
470    ///
471    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
472    /// let bytes = Object::builder("claim.prose", AUTHOR).created("2026-10-05T00:00:00Z").build()?;
473    ///
474    /// assert!(Object::parse(&bytes)?.verify(&Cid::of(&bytes, HashAlg::Sha2_256)).is_ok());
475    ///
476    /// // Bytes that are not the ones the identifier names are refused.
477    /// let asked_for = Cid::of(b"something else", HashAlg::Sha2_256);
478    /// assert!(matches!(
479    ///     Object::parse(&bytes)?.verify(&asked_for),
480    ///     Err(ObjectError::IdentifierMismatch { .. }),
481    /// ));
482    /// # Ok::<(), publet_core::ObjectError>(())
483    /// ```
484    pub fn verify(self, expected: &Cid) -> Result<Verified<Object>, ObjectError> {
485        if expected.verifies(&self.0.bytes) {
486            Ok(Verified(self.0))
487        } else {
488            Err(ObjectError::IdentifierMismatch {
489                expected: expected.to_string(),
490                actual: Cid::of(&self.0.bytes, expected.alg()).to_string(),
491            })
492        }
493    }
494
495    /// Borrow the object without verifying it.
496    ///
497    /// For error messages and inspection tools only. Nothing that indexes,
498    /// evaluates, or stores should take this path.
499    ///
500    /// # Example
501    ///
502    /// ```
503    /// use publet_core::Object;
504    ///
505    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
506    /// let bytes = Object::builder("claim.prose", AUTHOR).created("2026-10-05T00:00:00Z").build()?;
507    ///
508    /// // For a diagnostic message only; nothing should act on an unverified object.
509    /// let unverified = Object::parse(&bytes)?;
510    /// assert_eq!(unverified.peek().kind(), "claim.prose");
511    /// # Ok::<(), publet_core::ObjectError>(())
512    /// ```
513    #[must_use]
514    pub fn peek(&self) -> &Object {
515        &self.0
516    }
517}
518
519/// An object whose bytes have been confirmed against its identifier.
520#[derive(Debug, Clone, PartialEq, Eq)]
521pub struct Verified<T>(T);
522
523impl Verified<Object> {
524    /// Borrow the verified object.
525    ///
526    /// # Example
527    ///
528    /// ```
529    /// use publet_core::{Cid, HashAlg, Object};
530    ///
531    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
532    /// let bytes = Object::builder("claim.prose", AUTHOR).created("2026-10-05T00:00:00Z").build()?;
533    /// let verified = Object::parse(&bytes)?.verify(&Cid::of(&bytes, HashAlg::Sha2_256))?;
534    /// assert_eq!(verified.object().kind(), "claim.prose");
535    /// # Ok::<(), publet_core::ObjectError>(())
536    /// ```
537    #[must_use]
538    pub fn object(&self) -> &Object {
539        &self.0
540    }
541
542    /// Take ownership of the verified object.
543    ///
544    /// # Example
545    ///
546    /// ```
547    /// use publet_core::{Cid, HashAlg, Object};
548    ///
549    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
550    /// let bytes = Object::builder("claim.prose", AUTHOR).created("2026-10-05T00:00:00Z").build()?;
551    /// let object: Object = Object::parse(&bytes)?
552    ///     .verify(&Cid::of(&bytes, HashAlg::Sha2_256))?
553    ///     .into_inner();
554    /// assert_eq!(object.kind(), "claim.prose");
555    /// # Ok::<(), publet_core::ObjectError>(())
556    /// ```
557    #[must_use]
558    pub fn into_inner(self) -> Object {
559        self.0
560    }
561}
562
563/// Builds an object and emits its canonical bytes.
564#[derive(Debug, Clone)]
565pub struct Builder {
566    kind: String,
567    author: String,
568    protocol: String,
569    created: Option<String>,
570    body: BTreeMap<String, Value>,
571    prev: Option<String>,
572    basis: Option<String>,
573    ext: Option<BTreeMap<String, Value>>,
574}
575
576impl Builder {
577    /// Set the creation instant (RFC 3339 UTC, second precision).
578    ///
579    /// # Example
580    ///
581    /// ```
582    /// use publet_core::Object;
583    ///
584    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
585    /// let bytes = Object::builder("claim.prose", AUTHOR)
586    ///     .created("2026-10-05T00:00:00Z")
587    ///     .build()?;
588    /// assert_eq!(Object::parse(&bytes)?.peek().created(), "2026-10-05T00:00:00Z");
589    /// # Ok::<(), publet_core::ObjectError>(())
590    /// ```
591    #[must_use]
592    pub fn created(mut self, when: &str) -> Self {
593        self.created = Some(when.to_owned());
594        self
595    }
596
597    /// Insert a body field.
598    ///
599    /// # Example
600    ///
601    /// ```
602    /// use publet_core::{Object, cbor::Value};
603    ///
604    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
605    /// // Fields may be added in any order; the encoding sorts them.
606    /// let one = Object::builder("note", AUTHOR)
607    ///     .created("2026-10-05T00:00:00Z")
608    ///     .field("b", Value::Uint(2))
609    ///     .field("a", Value::Uint(1))
610    ///     .build()?;
611    /// let other = Object::builder("note", AUTHOR)
612    ///     .created("2026-10-05T00:00:00Z")
613    ///     .field("a", Value::Uint(1))
614    ///     .field("b", Value::Uint(2))
615    ///     .build()?;
616    /// assert_eq!(one, other);
617    /// # Ok::<(), publet_core::ObjectError>(())
618    /// ```
619    #[must_use]
620    pub fn field(mut self, key: &str, value: Value) -> Self {
621        self.body.insert(key.to_owned(), value);
622        self
623    }
624
625    /// Name the author's previous object.
626    ///
627    /// # Example
628    ///
629    /// ```
630    /// use publet_core::{Cid, HashAlg, Object};
631    ///
632    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
633    /// let first = Object::builder("note", AUTHOR).created("2026-10-05T00:00:00Z").build()?;
634    /// let first_cid = Cid::of(&first, HashAlg::Sha2_256);
635    ///
636    /// let second = Object::builder("note", AUTHOR)
637    ///     .created("2026-10-06T00:00:00Z")
638    ///     .prev(&first_cid.to_string())
639    ///     .build()?;
640    /// assert_eq!(Object::parse(&second)?.peek().prev(), Some(&first_cid));
641    /// # Ok::<(), publet_core::ObjectError>(())
642    /// ```
643    #[must_use]
644    pub fn prev(mut self, cid: &str) -> Self {
645        self.prev = Some(cid.to_owned());
646        self
647    }
648
649    /// Name the state the author was looking at (Section 4.6).
650    ///
651    /// # Example
652    ///
653    /// ```
654    /// use publet_core::{Cid, HashAlg, Object};
655    ///
656    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
657    /// // The state the author had read when writing this.
658    /// let read = Cid::of(b"the head the author was looking at", HashAlg::Sha2_256);
659    /// let bytes = Object::builder("note", AUTHOR)
660    ///     .created("2026-10-05T00:00:00Z")
661    ///     .basis(&read.to_string())
662    ///     .build()?;
663    /// assert_eq!(Object::parse(&bytes)?.peek().basis(), Some(&read));
664    /// # Ok::<(), publet_core::ObjectError>(())
665    /// ```
666    #[must_use]
667    pub fn basis(mut self, cid: &str) -> Self {
668        self.basis = Some(cid.to_owned());
669        self
670    }
671
672    /// Emit canonical bytes.
673    ///
674    /// # Errors
675    ///
676    /// Returns [`ObjectError`] if a CID-valued field does not parse or if
677    /// no creation instant was set.
678    ///
679    /// # Example
680    ///
681    /// ```
682    /// use publet_core::{Object, ObjectError};
683    ///
684    /// # const AUTHOR: &str = "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq";
685    /// let bytes = Object::builder("note", AUTHOR).created("2026-10-05T00:00:00Z").build()?;
686    /// assert!(Object::parse(&bytes).is_ok());
687    ///
688    /// // A creation instant is required.
689    /// assert_eq!(
690    ///     Object::builder("note", AUTHOR).build(),
691    ///     Err(ObjectError::MissingField { field: "created" }),
692    /// );
693    ///
694    /// // The author must be an identifier.
695    /// assert!(matches!(
696    ///     Object::builder("note", "not an identifier").created("2026-10-05T00:00:00Z").build(),
697    ///     Err(ObjectError::BadCid { field: "author", .. }),
698    /// ));
699    /// # Ok::<(), publet_core::ObjectError>(())
700    /// ```
701    pub fn build(self) -> Result<Vec<u8>, ObjectError> {
702        let created = self
703            .created
704            .ok_or(ObjectError::MissingField { field: "created" })?;
705        let author: Cid = self.author.parse().map_err(|source| ObjectError::BadCid {
706            field: "author",
707            source,
708        })?;
709
710        let mut map = BTreeMap::new();
711        map.insert("author".to_owned(), Value::Text(author.to_string()));
712        map.insert("body".to_owned(), Value::Map(self.body));
713        map.insert("created".to_owned(), Value::Text(created));
714        map.insert("pub".to_owned(), Value::Text(self.protocol));
715        map.insert("type".to_owned(), Value::Text(self.kind));
716        if let Some(prev) = self.prev {
717            let parsed: Cid = prev.parse().map_err(|source| ObjectError::BadCid {
718                field: "prev",
719                source,
720            })?;
721            map.insert("prev".to_owned(), Value::Text(parsed.to_string()));
722        }
723        if let Some(basis) = self.basis {
724            let parsed: Cid = basis.parse().map_err(|source| ObjectError::BadCid {
725                field: "basis",
726                source,
727            })?;
728            map.insert("basis".to_owned(), Value::Text(parsed.to_string()));
729        }
730        if let Some(ext) = self.ext {
731            map.insert("ext".to_owned(), Value::Map(ext));
732        }
733        Ok(cbor::encode(&Value::Map(map)))
734    }
735}
736
737fn describe(value: &Value) -> &'static str {
738    match value {
739        Value::Uint(_) | Value::Nint(_) => "an integer",
740        Value::Bytes(_) => "a byte string",
741        Value::Text(_) => "a text string",
742        Value::Array(_) => "an array",
743        Value::Map(_) => "a map",
744        Value::Bool(_) => "a boolean",
745        Value::Null => "null",
746    }
747}
748
749fn text_field(map: &BTreeMap<String, Value>, field: &'static str) -> Result<String, ObjectError> {
750    match map.get(field) {
751        Some(Value::Text(s)) => Ok(s.clone()),
752        Some(_) => Err(ObjectError::WrongType {
753            field,
754            expected: "a text string",
755        }),
756        None => Err(ObjectError::MissingField { field }),
757    }
758}
759
760fn cid_field(map: &BTreeMap<String, Value>, field: &'static str) -> Result<Cid, ObjectError> {
761    let text = text_field(map, field)?;
762    text.parse()
763        .map_err(|source| ObjectError::BadCid { field, source })
764}