Skip to main content

vector_core/community/
edition.rs

1//! Real-npub authority editions — the keyless model's authorship + version carrier.
2//!
3//! An authority change (a Grant, RoleMetadata, RoleOrder, Banlist, ...) is an **inner event signed
4//! by the ACTOR's own npub**, carrying the entity id, a per-entity
5//! `version`, and the previous edition's hash (`prev_hash`, see [`super::version`]). That inner event
6//! lives inside the channel/server-root encryption (the outer wrapper is the usual ephemeral signer,
7//! [`super::envelope`]), so authorship is **member-verifiable**: the inner Schnorr signature *is* the
8//! proof of who acted, and members check that npub against the roster.
9//!
10//! This module is the wire encoding of one edition (build + verify + parse). It does NOT decide
11//! authorization — the signature proves WHO acted; the roster (§roles) decides WHETHER they were
12//! allowed, and [`super::version::fold`] decides which edition is current.
13
14use super::version;
15use crate::stored_event::event_kind;
16use nostr_sdk::prelude::*;
17
18const TAG_SUBKIND: &str = "vsk";
19const TAG_ENTITY: &str = "eid";
20const TAG_EVERSION: &str = "ev";
21const TAG_EPREV: &str = "ep";
22const TAG_VERSION: &str = "v";
23const PROTOCOL_VERSION: &str = "1";
24/// Authority citation tag: `["vac", <authorizing-entity hex>, <version>, <edition-hash hex>]`.
25/// The "pinned proof" — the grant edition the actor claims their authority under. In the MVP it is a
26/// COMPLETENESS floor: a verifier confirms it has synced that exact grant to ≥ the cited version (an
27/// un-forked, complete view) before acting, and resolves the actor's actual rank against its current
28/// (refuse-downgrade-protected) roster — so a since-demoted actor is dropped there. The full 
29/// "resolve rank AT the cited version" (block-until-synced re-fetch + a roster-wide snapshot version) is
30/// the deferred refinement; today it pins the actor's own grant, not a whole-roster moment. Absent when
31/// the OWNER acts (supreme, no grant to cite).
32pub const TAG_AUTHORITY_CITATION: &str = "vac";
33
34/// The pinned authority an actor claims for an action (mechanism a). Points at the actor's own
35/// authorizing edition (their Grant — or a RoleMetadata for a role-position claim) by stable
36/// coordinate + the exact version/hash, so the verifier resolves authority against that frozen point,
37/// not its own possibly-lagging-or-ahead live roster.
38#[derive(Clone, Debug, PartialEq, Eq)]
39pub struct AuthorityCitation {
40    /// The authorizing edition's entity id (e.g. `grant_locator(community_id, actor)`).
41    pub entity_id: [u8; 32],
42    /// The version of that edition the actor claims authority under.
43    pub version: u64,
44    /// That edition's [`version::edition_hash`] — pins the exact content, not just the version number.
45    pub edition_hash: [u8; 32],
46}
47
48impl AuthorityCitation {
49    /// The signed `vac` tag carrying this citation.
50    pub fn to_tag(&self) -> Tag {
51        Tag::custom(
52            TagKind::Custom(TAG_AUTHORITY_CITATION.into()),
53            [
54                crate::simd::hex::bytes_to_hex_32(&self.entity_id),
55                self.version.to_string(),
56                crate::simd::hex::bytes_to_hex_32(&self.edition_hash),
57            ],
58        )
59    }
60
61    /// Extract the citation from an event's tags, or `None` if absent. A malformed `vac` (bad hex /
62    /// unparseable version) returns `None` — the verifier then treats the action as uncited (owner-only
63    /// or rejected), never trusting a corrupt citation.
64    pub fn from_tags(tags: &Tags) -> Option<AuthorityCitation> {
65        let s = tags.iter().find_map(|t| {
66            let s = t.as_slice();
67            (s.len() >= 4 && s[0] == TAG_AUTHORITY_CITATION).then(|| (s[1].clone(), s[2].clone(), s[3].clone()))
68        })?;
69        let valid_hex = |h: &str| h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit());
70        if !valid_hex(&s.0) || !valid_hex(&s.2) {
71            return None;
72        }
73        Some(AuthorityCitation {
74            entity_id: crate::simd::hex::hex_to_bytes_32(&s.0),
75            version: s.1.parse().ok()?,
76            edition_hash: crate::simd::hex::hex_to_bytes_32(&s.2),
77        })
78    }
79}
80
81/// Build the unsigned inner edition event. Sign it with the ACTOR's real identity keys — that
82/// signature is the authorship proof. `entity_id` is the entity's 32-byte id, `prev_hash` is the
83/// previous edition's [`version::edition_hash`] (`None` for the first edition), `content` is the
84/// entity payload JSON, and `created_at_secs` is the authored time (the version-fold tiebreak).
85pub fn build_edition_inner(
86    author: PublicKey,
87    vsk: &str,
88    entity_id: &[u8; 32],
89    version: u64,
90    prev_hash: Option<&[u8; 32]>,
91    content: &str,
92    created_at_secs: u64,
93    authority: Option<&AuthorityCitation>,
94) -> UnsignedEvent {
95    let mut tags = vec![
96        Tag::custom(TagKind::Custom(TAG_SUBKIND.into()), [vsk.to_string()]),
97        Tag::custom(TagKind::Custom(TAG_ENTITY.into()), [crate::simd::hex::bytes_to_hex_32(entity_id)]),
98        Tag::custom(TagKind::Custom(TAG_EVERSION.into()), [version.to_string()]),
99        Tag::custom(TagKind::Custom(TAG_VERSION.into()), [PROTOCOL_VERSION.to_string()]),
100    ];
101    if let Some(p) = prev_hash {
102        tags.push(Tag::custom(TagKind::Custom(TAG_EPREV.into()), [crate::simd::hex::bytes_to_hex_32(p)]));
103    }
104    // The pinned authority proof: absent when the OWNER signs (supreme), present for a delegated
105    // admin so verifiers resolve their rank at the cited grant version. Outside the version-chain
106    // self_hash (it's per-action metadata, not chain identity), but covered by the inner signature.
107    if let Some(a) = authority {
108        tags.push(a.to_tag());
109    }
110    EventBuilder::new(Kind::Custom(event_kind::COMMUNITY_CONTROL), content)
111        .tags(tags)
112        .custom_created_at(Timestamp::from_secs(created_at_secs))
113        .build(author)
114}
115
116/// A signature-verified, parsed edition.
117#[derive(Clone, Debug)]
118pub struct ParsedEdition {
119    /// The real npub that signed (and is thus accountable for) this edition.
120    pub author: PublicKey,
121    pub vsk: String,
122    pub entity_id: [u8; 32],
123    pub version: u64,
124    pub prev_hash: Option<[u8; 32]>,
125    pub content: String,
126    /// [`version::edition_hash`] of this edition — what the next edition's `prev_hash` must cite.
127    pub self_hash: [u8; 32],
128    pub created_at: u64,
129    pub inner_id: [u8; 32],
130    /// The pinned authority proof, if the actor cited one. `None` when the OWNER signs (supreme)
131    /// or a non-authority edition carries no citation. Verified separately against the roster (#3c).
132    pub authority: Option<AuthorityCitation>,
133}
134
135#[derive(Debug, PartialEq, Eq)]
136pub enum EditionError {
137    BadSignature,
138    MissingField(&'static str),
139    BadField(&'static str),
140}
141
142fn decode_hash(hex: &str, field: &'static str) -> Result<[u8; 32], EditionError> {
143    if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
144        return Err(EditionError::BadField(field));
145    }
146    Ok(crate::simd::hex::hex_to_bytes_32(hex))
147}
148
149/// Verify + parse an inner edition event. Checks the inner Schnorr signature (the real-npub
150/// authorship proof) and extracts the edition fields, computing `self_hash` over the canonical
151/// edition bytes. Does NOT check roster authorization — that is the caller's separate step.
152pub fn parse_edition_inner(inner: &Event) -> Result<ParsedEdition, EditionError> {
153    inner.verify().map_err(|_| EditionError::BadSignature)?;
154    // Reject duplicate authority tags: the signature covers all of them, but if two clients picked a
155    // different duplicate they would compute a different `self_hash` for the same signed event and
156    // diverge on the chain. The map signed-event → canonical bytes must be total and unambiguous.
157    for name in [TAG_SUBKIND, TAG_ENTITY, TAG_EVERSION, TAG_EPREV, TAG_AUTHORITY_CITATION] {
158        let count = inner
159            .tags
160            .iter()
161            .filter(|t| t.as_slice().first().map(|s| s.as_str() == name).unwrap_or(false))
162            .count();
163        if count > 1 {
164            return Err(EditionError::BadField("duplicate authority tag"));
165        }
166    }
167    let get = |name: &str| -> Option<String> {
168        inner.tags.iter().find_map(|t| {
169            let s = t.as_slice();
170            (s.len() >= 2 && s[0] == name).then(|| s[1].clone())
171        })
172    };
173    let vsk = get(TAG_SUBKIND).ok_or(EditionError::MissingField("vsk"))?;
174    let entity_id = decode_hash(&get(TAG_ENTITY).ok_or(EditionError::MissingField("eid"))?, "eid")?;
175    let version: u64 = get(TAG_EVERSION)
176        .ok_or(EditionError::MissingField("ev"))?
177        .parse()
178        .map_err(|_| EditionError::BadField("ev"))?;
179    let prev_hash = match get(TAG_EPREV) {
180        Some(h) => Some(decode_hash(&h, "ep")?),
181        None => None,
182    };
183    let content = inner.content.clone();
184    let self_hash = version::edition_hash(&entity_id, version, prev_hash.as_ref(), content.as_bytes());
185    Ok(ParsedEdition {
186        author: inner.pubkey,
187        vsk,
188        entity_id,
189        version,
190        prev_hash,
191        content,
192        self_hash,
193        created_at: inner.created_at.as_secs(),
194        inner_id: inner.id.to_bytes(),
195        authority: AuthorityCitation::from_tags(&inner.tags),
196    })
197}
198
199impl ParsedEdition {
200    /// The [`version::Edition`] view used by [`version::fold`].
201    pub fn to_fold_edition(&self) -> version::Edition {
202        version::Edition {
203            version: self.version,
204            prev_hash: self.prev_hash,
205            self_hash: self.self_hash,
206            created_at: self.created_at,
207            tiebreak_id: self.inner_id,
208        }
209    }
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215
216    const VSK_GRANT: &str = "3";
217
218    fn eid() -> [u8; 32] {
219        [0x42; 32]
220    }
221
222    #[test]
223    fn round_trips_authorship_version_and_chain_hash() {
224        let actor = Keys::generate();
225        let prev = version::edition_hash(&eid(), 1, None, b"{}");
226        let inner = build_edition_inner(actor.public_key(), VSK_GRANT, &eid(), 2, Some(&prev), "{\"role_ids\":[]}", 1_700_000_000, None)
227            .sign_with_keys(&actor)
228            .unwrap();
229
230        let parsed = parse_edition_inner(&inner).expect("valid edition parses");
231        assert_eq!(parsed.author, actor.public_key(), "authorship = the real signer");
232        assert_eq!(parsed.vsk, VSK_GRANT);
233        assert_eq!(parsed.entity_id, eid());
234        assert_eq!(parsed.version, 2);
235        assert_eq!(parsed.prev_hash, Some(prev));
236        assert_eq!(parsed.created_at, 1_700_000_000);
237        // self_hash matches the canonical recomputation (what the next edition will cite).
238        assert_eq!(
239            parsed.self_hash,
240            version::edition_hash(&eid(), 2, Some(&prev), b"{\"role_ids\":[]}")
241        );
242        // Folds into a version::Edition cleanly.
243        let fe = parsed.to_fold_edition();
244        assert_eq!(fe.version, 2);
245        assert_eq!(fe.prev_hash, Some(prev));
246    }
247
248    #[test]
249    fn authority_citation_round_trips_on_an_edition() {
250        // A delegated admin's edition carries the pinned authority citation; it survives sign→parse,
251        // covered by the inner signature, and does NOT alter the chain self_hash (per-action metadata).
252        let actor = Keys::generate();
253        let cite = AuthorityCitation { entity_id: [0xab; 32], version: 7, edition_hash: [0xcd; 32] };
254        let inner = build_edition_inner(actor.public_key(), VSK_GRANT, &eid(), 1, None, "{}", 100, Some(&cite))
255            .sign_with_keys(&actor)
256            .unwrap();
257        let parsed = parse_edition_inner(&inner).unwrap();
258        assert_eq!(parsed.authority.as_ref(), Some(&cite), "citation round-trips");
259        // self_hash is over (entity, version, prev, content) only — the citation doesn't perturb it.
260        assert_eq!(parsed.self_hash, version::edition_hash(&eid(), 1, None, b"{}"));
261
262        // An uncited edition (owner-signed) parses with authority == None.
263        let owner = build_edition_inner(actor.public_key(), VSK_GRANT, &eid(), 1, None, "{}", 100, None)
264            .sign_with_keys(&actor)
265            .unwrap();
266        assert_eq!(parse_edition_inner(&owner).unwrap().authority, None);
267    }
268
269    #[test]
270    fn authority_citation_tag_layout_is_frozen() {
271        // FROZEN wire layout: the citation rides as a 4-element `vac` tag
272        // `["vac", <entity hex>, <version>, <edition-hash hex>]`. A change here reshuffles how every
273        // verifier reads pinned authority, so pin the exact shape (not just a round-trip).
274        let cite = AuthorityCitation { entity_id: [0x11; 32], version: 9, edition_hash: [0x22; 32] };
275        let tag = cite.to_tag();
276        let s = tag.as_slice();
277        assert_eq!(s.len(), 4, "vac is a 4-element tag");
278        assert_eq!(s[0], TAG_AUTHORITY_CITATION);
279        assert_eq!(s[1], "11".repeat(32), "entity id is lowercase hex");
280        assert_eq!(s[2], "9", "version is the decimal string");
281        assert_eq!(s[3], "22".repeat(32), "edition hash is lowercase hex");
282    }
283
284    #[test]
285    fn genesis_edition_has_no_prev() {
286        let actor = Keys::generate();
287        let inner = build_edition_inner(actor.public_key(), "1", &eid(), 1, None, "{}", 100, None)
288            .sign_with_keys(&actor)
289            .unwrap();
290        let parsed = parse_edition_inner(&inner).unwrap();
291        assert_eq!(parsed.prev_hash, None, "first edition cites no predecessor");
292        assert_eq!(parsed.version, 1);
293    }
294
295    #[test]
296    fn tampered_content_fails_verification() {
297        // Re-sign integrity: flipping the content after signing breaks the inner Schnorr sig.
298        let actor = Keys::generate();
299        let inner = build_edition_inner(actor.public_key(), "3", &eid(), 1, None, "{\"a\":1}", 100, None)
300            .sign_with_keys(&actor)
301            .unwrap();
302        let mut json: serde_json::Value = serde_json::from_str(&inner.as_json()).unwrap();
303        json["content"] = serde_json::Value::String("{\"a\":2}".into()); // tamper
304        let tampered: Event = serde_json::from_value(json).unwrap();
305        assert!(matches!(parse_edition_inner(&tampered), Err(EditionError::BadSignature)));
306    }
307
308    #[test]
309    fn missing_required_field_is_rejected_not_panicked() {
310        // An inner event lacking the entity-id tag is a parse error, never a panic.
311        let actor = Keys::generate();
312        let inner = EventBuilder::new(Kind::Custom(event_kind::COMMUNITY_CONTROL), "{}")
313            .tags([Tag::custom(TagKind::Custom("vsk".into()), ["3".to_string()])])
314            .sign_with_keys(&actor)
315            .unwrap();
316        assert!(matches!(parse_edition_inner(&inner), Err(EditionError::MissingField("eid"))));
317    }
318
319    #[test]
320    fn duplicate_authority_tag_is_rejected() {
321        // A duplicate of ANY of the 5 authority tags (vsk/eid/ev/ep/vac) makes signed-event → canonical
322        // bytes ambiguous (clients could pick different ones) → chain divergence, so it must be rejected.
323        // Parameterized across all 5 — a regression dropping any one from the dedup loop is caught.
324        let actor = Keys::generate();
325        let hash = crate::simd::hex::bytes_to_hex_32(&[0xAB; 32]);
326        let base = || -> Vec<Tag> {
327            vec![
328                Tag::custom(TagKind::Custom("vsk".into()), ["1".to_string()]),
329                Tag::custom(TagKind::Custom("eid".into()), [crate::simd::hex::bytes_to_hex_32(&eid())]),
330                Tag::custom(TagKind::Custom("ev".into()), ["1".to_string()]),
331                Tag::custom(TagKind::Custom("ep".into()), [hash.clone()]),
332                Tag::custom(TagKind::Custom("vac".into()), [crate::simd::hex::bytes_to_hex_32(&eid()), "1".to_string(), hash.clone()]),
333            ]
334        };
335        let build = |tags: Vec<Tag>| EventBuilder::new(Kind::Custom(event_kind::COMMUNITY_CONTROL), "{}")
336            .tags(tags).sign_with_keys(&actor).unwrap();
337        assert!(parse_edition_inner(&build(base())).is_ok(), "a clean 5-tag base edition parses");
338        for name in ["vsk", "eid", "ev", "ep", "vac"] {
339            let mut tags = base();
340            let dup = tags.iter().find(|t| t.as_slice().first().map(|s| s == name).unwrap_or(false)).cloned().unwrap();
341            tags.push(dup);
342            assert!(
343                matches!(parse_edition_inner(&build(tags)), Err(EditionError::BadField("duplicate authority tag"))),
344                "a duplicate `{name}` tag must be rejected"
345            );
346        }
347    }
348}