Skip to main content

publet_core/
lib.rs

1/*!
2Objects, canonical serialization, content identifiers and signatures for the
3[Publet Protocol]: Section 4 of the specification, and the floor every other
4publet crate and tool builds on.
5
6Here is an object built, named by its identifier, and checked against it:
7
8```
9use publet_core::{Cid, HashAlg, Object, cbor::Value};
10
11// An author is named by the identifier of their key object.
12let author = Cid::of(b"the author's key object", HashAlg::Sha2_256).to_string();
13
14let bytes = Object::builder("claim.prose", &author)
15    .created("2026-10-05T00:00:00Z")
16    .field("content", Value::Text("Water boils at 100 °C at sea level.".into()))
17    .build()?;
18let cid = Cid::of(&bytes, HashAlg::Sha2_256);
19
20// Bytes fetched from anywhere are checked against the identifier asked for.
21let object = Object::parse(&bytes)?.verify(&cid)?;
22assert_eq!(object.object().kind(), "claim.prose");
23# Ok::<(), Box<dyn std::error::Error>>(())
24```
25
26[Publet Protocol]: https://github.com/Sustenaut/publet/blob/main/spec/index.md
27
28# Overview
29
30The crate holds two invariants that everything built on it assumes:
31
32* **An object has exactly one byte representation.** Objects are CBOR under
33  a strict profile (Section 4.1): text map keys sorted by their UTF-8 bytes,
34  integers in shortest form, NFC text, and no floats, tags or
35  indefinite lengths. [`cbor::decode`] rejects anything else, naming the rule
36  broken, so equal content always has the same identifier.
37* **An object is not usable until it has been checked.** [`Object::parse`]
38  yields an [`Unverified`] object. Only [`Unverified::verify`], against the
39  identifier you asked for, gives a [`Verified`] one, and only that is worth
40  acting on.
41
42The types:
43
44* [`Object`] is a parsed object: its header, its body, and its bytes.
45  [`Object::builder`] makes one, as canonical bytes.
46* [`Cid`] is a content identifier: `pub:<algorithm>:<base32 digest>`,
47  computed by [`Cid::of`], parsed from text, printed by `Display`.
48* [`cbor::Value`] is a value in the profile, with [`cbor::encode`] and
49  [`cbor::decode`].
50* [`sign`], [`verify`] and [`verifying_key`] make and check detached Ed25519
51  signatures, each bound to a *purpose*.
52
53The rest of this page is:
54
55* [Examples](#examples): a short cookbook.
56* [Why this crate?](#why-this-crate): what a general CBOR library or IPFS
57  identifiers would get wrong here.
58* [Related crates](#related-crates): what was considered instead, and why not.
59* [Crate features](#crate-features), [Minimum Rust version](#minimum-rust-version)
60  and [Versioning](#versioning).
61
62Longer documents live in [`_documentation`]: how every item is
63[tested](crate::_documentation::testing), how each dependency is
64[vouched for](crate::_documentation::supply_chain), the project's
65[security](crate::_documentation::security) policy, and the
66[changelog](crate::_documentation::changelog).
67
68# Examples
69
70## Example: sign an object for a purpose
71
72A signature covers an object's bytes *and* a purpose. One made for
73`authored` says nothing about `retracted`, so an endorsement cannot be
74replayed as something else.
75
76```
77use publet_core::{SigAlg, sign, verify, verifying_key};
78
79let object = b"an object's canonical bytes";
80
81// A real seed comes from a random source; this crate needs no RNG.
82let seed = [7u8; 32];
83let public = verifying_key(SigAlg::Ed25519, &seed)?;
84
85let signature = sign(SigAlg::Ed25519, &seed, "authored", object)?;
86verify(SigAlg::Ed25519, &public, &signature, "authored", "authored", object)?;
87assert!(verify(SigAlg::Ed25519, &public, &signature, "authored", "retracted", object).is_err());
88# Ok::<(), publet_core::SigError>(())
89```
90
91## Example: non-canonical bytes are refused, by rule
92
93```
94use publet_core::cbor::decode;
95
96// 5 written in two bytes; its canonical form is the single byte 0x05.
97let error = decode(&[0x18, 0x05]).unwrap_err();
98assert_eq!(error.rule(), "shortest-form integers");
99
100// {"b": 1, "a": 2}: keys out of order.
101let error = decode(&[0xa2, 0x61, b'b', 0x01, 0x61, b'a', 0x02]).unwrap_err();
102assert_eq!(error.rule(), "sorted map keys");
103```
104
105## Example: identifiers are text
106
107```
108use publet_core::{Cid, CidError, HashAlg};
109
110let cid = Cid::of(b"", HashAlg::Sha2_256);
111let text = cid.to_string();
112assert_eq!(text, "pub:sha2-256:4oymiquy7qobjgx36tejs35zeqt24qpemsnzgtfeswmrw6csxbkq");
113assert_eq!(text.parse::<Cid>(), Ok(cid));
114
115assert_eq!("ipfs:bafy".parse::<Cid>(), Err(CidError::MissingScheme));
116```
117
118# Why this crate?
119
120Content addressing works only if equal content has equal bytes. CBOR allows
121many encodings of one value: integers padded to longer forms, keys in any
122order, lengths left open. General-purpose decoders accept them all; `ciborium`
123and `minicbor` both decode a padded integer to the same value as the
124canonical one (see [Related crates](#related-crates)), so a program that
125checked the decoded value would accept bytes with a different identifier. Section 4.1 requires rejecting non-canonical bytes outright, never
126repairing them. The decoder here checks every rule while parsing, so the
127first violation is reported with its offset, and no value is built from bad
128input.
129
130The identifiers are the protocol's own (Section 4.2): `pub:` and an algorithm
131name, then the digest in lowercase base32. The algorithm travels in the
132identifier, so a future migration is a new name rather than a flag day.
133
134And the types make the checks hard to skip. Nothing returns an object you can
135act on without verifying it against an identifier first, and [`verify`]
136takes the purpose you require as an argument, so a signature cannot be
137checked without one.
138
139# Related crates
140
141Crates that do similar jobs, and why this one takes another approach. Each
142was checked at the version shown. The CBOR libraries were given encodings
143Section 4.1 forbids: integers not in shortest form, indefinite lengths,
144unsorted and duplicate keys, non-text keys, floats, tags, non-NFC text, and
145trailing bytes.
146
147| Crate | What it is | Why not here |
148|---|---|---|
149| [`ciborium`](https://crates.io/crates/ciborium) 0.2.2 | General CBOR with serde | Accepted every forbidden encoding, decoding several to the same values as the canonical bytes, so a later check cannot tell them apart. Its canonical key order differs from Section 4.1's. |
150| [`minicbor`](https://crates.io/crates/minicbor) 2.3.0 | Small `no_std` CBOR codec | Lenient in the same way: it accepted the six forbidden encodings tried, reading a non-shortest integer as the plain value. |
151| [`dcbor`](https://crates.io/crates/dcbor) 0.25.2 | Deterministic CBOR | Strict, and rejects most forbidden encodings. But it orders map keys by encoded length (RFC 8949 §4.2.1), while Section 4.1 orders them by UTF-8 bytes, so it rejects this crate's canonical objects. It also admits floats, tags and non-text keys. |
152| [`serde_cbor`](https://crates.io/crates/serde_cbor) 0.11.2 | CBOR with serde | Unmaintained since 2021. |
153| [`cid`](https://crates.io/crates/cid) 0.11.3 | IPFS content identifiers | A multiformats CID carries a version, a codec and a multibase prefix (`bafy…`). Section 4.2 defines a different text form, `pub:<algorithm>:<base32>`, so its parser and printer don't apply. |
154
155What this crate builds on rather than reimplements: [`sha2`](https://crates.io/crates/sha2)
156for SHA-256, [`ed25519-dalek`](https://crates.io/crates/ed25519-dalek) for
157signatures, and [`unicode-normalization`](https://crates.io/crates/unicode-normalization)
158for the NFC check.
159
160# Crate features
161
162None. Everything in the crate is always available.
163
164# Minimum Rust version
165
166This crate requires Rust 1.85 (its `rust-version`), the first release with
167the 2024 edition; CI builds it there. The minimum may rise in a release that
168bumps the minor version, and never in a patch release.
169
170# Versioning
171
172Versions follow Cargo's convention: below 1.0, a breaking change bumps the
173minor version (`0.1.x` to `0.2.0`) and anything compatible bumps the patch.
174Each change to the public API is checked against the last release (its
175`publet-core-v` tag) by [`cargo-semver-checks`](https://crates.io/crates/cargo-semver-checks),
176so a release cannot break the API without the
177[changelog](crate::_documentation::changelog) saying so.
178*/
179
180#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))]
181#![deny(missing_docs)]
182#![warn(missing_debug_implementations)]
183
184pub mod cbor;
185mod cid;
186mod error;
187mod object;
188mod sig;
189
190pub use cid::{Cid, CidError, HashAlg};
191pub use error::CanonError;
192pub use object::{Builder, Object, ObjectError, PROTOCOL_VERSION, Unverified, Verified};
193pub use sig::{SigAlg, SigError, sign, signing_message, verify, verifying_key};
194
195/// Longer documents: testing, the supply chain, security, and the changelog.
196///
197/// These modules hold no code. Each is a document, kept in the repository as
198/// Markdown and rendered here so it is versioned with the crate.
199// Prose documents, one of them generated from release records: clippy's
200// backtick rule for API docs does not fit them.
201#[allow(clippy::doc_markdown)]
202pub mod _documentation {
203    /// How every public item is tested: the examples in its documentation, and
204    /// the tests that say they cover it.
205    #[doc = include_str!("../TESTING.md")]
206    pub mod testing {}
207
208    /// Every crate this one depends on, and how its code is vouched for.
209    #[doc = include_str!("../SUPPLY-CHAIN.md")]
210    pub mod supply_chain {}
211
212    /// How to report a vulnerability, and what is checked before each release.
213    #[doc = include_str!("../SECURITY.md")]
214    pub mod security {}
215
216    /// Every release, newest first, generated from the package publet.
217    #[doc = include_str!("../CHANGELOG.md")]
218    pub mod changelog {}
219}
220
221/// The README's examples, run as tests without being rendered twice.
222#[cfg(doctest)]
223#[doc = include_str!("../README.md")]
224struct ReadmeDoctests;