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 edition **signed by
4//! the ACTOR's own npub**, carrying the entity id, a per-entity `version`, and the previous
5//! edition's hash (`prev_hash`, see [`super::version`]). Authorship is **member-verifiable**: the
6//! Schnorr signature *is* the proof of who acted, and members check that npub against the roster.
7//!
8//! This module is the wire encoding of one edition (build + verify + parse). It does NOT decide
9//! authorization — the signature proves WHO acted; the roster (§roles) decides WHETHER they were
10//! allowed, and [`super::version::fold`] decides which edition is current.
11
12use crate::event_ext::FinalizeUnsignedWithId;
13use super::version;
14use nostr_sdk::prelude::*;
15
16const TAG_SUBKIND: &str = "vsk";
17const TAG_ENTITY: &str = "eid";
18const TAG_EVERSION: &str = "ev";
19const TAG_EPREV: &str = "ep";
20const TAG_VERSION: &str = "v";
21const PROTOCOL_VERSION: &str = "1";
22/// Authority citation tag: `["vac", <authorizing-entity hex>, <version>, <edition-hash hex>]`.
23/// The "pinned proof" — the grant edition the actor claims their authority under. In the MVP it is a
24/// COMPLETENESS floor: a verifier confirms it has synced that exact grant to ≥ the cited version (an
25/// un-forked, complete view) before acting, and resolves the actor's actual rank against its current
26/// (refuse-downgrade-protected) roster — so a since-demoted actor is dropped there. The full
27/// "resolve rank AT the cited version" (block-until-synced re-fetch + a roster-wide snapshot version) is
28/// the deferred refinement; today it pins the actor's own grant, not a whole-roster moment. Absent when
29/// the OWNER acts (supreme, no grant to cite).
30pub const TAG_AUTHORITY_CITATION: &str = "vac";
31
32/// CORD-01 §5: a tag number rides as "its decimal form with no leading zeros".
33/// So `"4"` and `"0"` are the shape; `"04"`, `"+4"` and `""` are not.
34/// `u64::from_str` accepts a leading `+` and any number of leading zeros, and a
35/// peer that doesn't would drop an event we honored — a divergence neither side
36/// can see, because a declined parse is never logged.
37pub fn is_tag_decimal(raw: &str) -> bool {
38 !raw.is_empty()
39 && raw.bytes().all(|b| b.is_ascii_digit())
40 && !(raw.len() > 1 && raw.starts_with('0'))
41}
42
43/// The pinned authority an actor claims for an action (mechanism a). Points at the actor's own
44/// authorizing edition (their Grant — or a RoleMetadata for a role-position claim) by stable
45/// coordinate + the exact version/hash, so the verifier resolves authority against that frozen point,
46/// not its own possibly-lagging-or-ahead live roster.
47#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
48pub struct AuthorityCitation {
49 /// The authorizing edition's entity id (e.g. `grant_locator(community_id, actor)`).
50 pub entity_id: [u8; 32],
51 /// The version of that edition the actor claims authority under.
52 pub version: u64,
53 /// That edition's [`version::edition_hash`] — pins the exact content, not just the version number.
54 pub edition_hash: [u8; 32],
55}
56
57impl AuthorityCitation {
58 /// The signed `vac` tag carrying this citation.
59 pub fn to_tag(&self) -> Tag {
60 Tag::custom(
61 TAG_AUTHORITY_CITATION,
62 [
63 crate::simd::hex::bytes_to_hex_32(&self.entity_id),
64 self.version.to_string(),
65 crate::simd::hex::bytes_to_hex_32(&self.edition_hash),
66 ],
67 )
68 }
69
70 /// Extract the citation from an event's tags, or `None` if absent. A malformed `vac` (bad hex /
71 /// unparseable version) returns `None` — the verifier then treats the action as uncited (owner-only
72 /// or rejected), never trusting a corrupt citation.
73 pub fn from_tags(tags: &Tags) -> Option<AuthorityCitation> {
74 let s = tags.iter().find_map(|t| {
75 let s = t.as_slice();
76 (s.len() >= 4 && s[0] == TAG_AUTHORITY_CITATION).then(|| (s[1].clone(), s[2].clone(), s[3].clone()))
77 })?;
78 let valid_hex = |h: &str| h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit());
79 if !valid_hex(&s.0) || !valid_hex(&s.2) {
80 return None;
81 }
82 // Digit-only BEFORE the parse: CORD-01 §5 says a tag number rides as its
83 // decimal form, and `u64::from_str` accepts a leading `+` ("+5") that a
84 // digit-checking peer rejects — so the two would disagree on whether a
85 // citation exists at all, one honoring the action and the other parking
86 // it. Same guard `resolve_ms_strict` already applies to `ms`.
87 if !is_tag_decimal(&s.1) {
88 return None;
89 }
90 Some(AuthorityCitation {
91 entity_id: crate::simd::hex::hex_to_bytes_32(&s.0),
92 version: s.1.parse().ok()?,
93 edition_hash: crate::simd::hex::hex_to_bytes_32(&s.2),
94 })
95 }
96}
97
98/// Build the unsigned inner edition event. Sign it with the ACTOR's real identity keys — that
99/// signature is the authorship proof. `entity_id` is the entity's 32-byte id, `prev_hash` is the
100/// previous edition's [`version::edition_hash`] (`None` for the first edition), `content` is the
101/// entity payload JSON, and `created_at_secs` is the authored time (the version-fold tiebreak).
102#[allow(clippy::too_many_arguments)]
103pub fn build_edition_inner(
104 author: PublicKey,
105 vsk: &str,
106 entity_id: &[u8; 32],
107 version: u64,
108 prev_hash: Option<&[u8; 32]>,
109 content: &str,
110 created_at_secs: u64,
111 authority: Option<&AuthorityCitation>,
112) -> UnsignedEvent {
113 let mut tags = vec![
114 Tag::custom(TAG_SUBKIND, [vsk.to_string()]),
115 Tag::custom(TAG_ENTITY, [crate::simd::hex::bytes_to_hex_32(entity_id)]),
116 Tag::custom(TAG_EVERSION, [version.to_string()]),
117 Tag::custom(TAG_VERSION, [PROTOCOL_VERSION.to_string()]),
118 ];
119 if let Some(p) = prev_hash {
120 tags.push(Tag::custom(TAG_EPREV, [crate::simd::hex::bytes_to_hex_32(p)]));
121 }
122 // The pinned authority proof: absent when the OWNER signs (supreme), present for a delegated
123 // admin so verifiers resolve their rank at the cited grant version. Outside the version-chain
124 // self_hash (it's per-action metadata, not chain identity), but covered by the inner signature.
125 if let Some(a) = authority {
126 tags.push(a.to_tag());
127 }
128 EventBuilder::new(Kind::Custom(crate::community::v2::kind::CONTROL), content)
129 .tags(tags)
130 .custom_created_at(Timestamp::from_secs(created_at_secs))
131 .finalize_unsigned_with_id(author)
132}
133
134/// A signature-verified, parsed edition.
135#[derive(Clone, Debug)]
136pub struct ParsedEdition {
137 /// The real npub that signed (and is thus accountable for) this edition.
138 pub author: PublicKey,
139 pub vsk: String,
140 pub entity_id: [u8; 32],
141 pub version: u64,
142 pub prev_hash: Option<[u8; 32]>,
143 pub content: String,
144 /// [`version::edition_hash`] of this edition — what the next edition's `prev_hash` must cite.
145 pub self_hash: [u8; 32],
146 pub created_at: u64,
147 pub inner_id: [u8; 32],
148 /// The pinned authority proof, if the actor cited one. `None` when the OWNER signs (supreme)
149 /// or a non-authority edition carries no citation. Verified separately against the roster (#3c).
150 pub authority: Option<AuthorityCitation>,
151 /// The Community a marked edition binds itself to (CORD-02), or `None` for an unmarked
152 /// edition, whose hash covers no signer.
153 pub binding: Option<[u8; 32]>,
154}
155
156#[derive(Debug, PartialEq, Eq)]
157pub enum EditionError {
158 BadSignature,
159 MissingField(&'static str),
160 BadField(&'static str),
161}
162
163fn decode_hash(hex: &str, field: &'static str) -> Result<[u8; 32], EditionError> {
164 if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
165 return Err(EditionError::BadField(field));
166 }
167 Ok(crate::simd::hex::hex_to_bytes_32(hex))
168}
169
170/// Verify + parse an inner edition event. Checks the inner Schnorr signature (the real-npub
171/// authorship proof) and extracts the edition fields, computing `self_hash` over the canonical
172/// edition bytes. Does NOT check roster authorization — that is the caller's separate step.
173pub fn parse_edition_inner(inner: &Event) -> Result<ParsedEdition, EditionError> {
174 inner.verify().map_err(|_| EditionError::BadSignature)?;
175 // Reject duplicate authority tags: the signature covers all of them, but if two clients picked a
176 // different duplicate they would compute a different `self_hash` for the same signed event and
177 // diverge on the chain. The map signed-event → canonical bytes must be total and unambiguous.
178 for name in [TAG_SUBKIND, TAG_ENTITY, TAG_EVERSION, TAG_EPREV, TAG_AUTHORITY_CITATION] {
179 let count = inner
180 .tags
181 .iter()
182 .filter(|t| t.as_slice().first().map(|s| s.as_str() == name).unwrap_or(false))
183 .count();
184 if count > 1 {
185 return Err(EditionError::BadField("duplicate authority tag"));
186 }
187 }
188 let get = |name: &str| -> Option<String> {
189 inner.tags.iter().find_map(|t| {
190 let s = t.as_slice();
191 (s.len() >= 2 && s[0] == name).then(|| s[1].clone())
192 })
193 };
194 let vsk = get(TAG_SUBKIND).ok_or(EditionError::MissingField("vsk"))?;
195 let entity_id = decode_hash(&get(TAG_ENTITY).ok_or(EditionError::MissingField("eid"))?, "eid")?;
196 // Digit-only: `u64::from_str` accepts a leading `+`, so "+5"/"5" would fold to
197 // one version as distinct signed inners (a convergence fork).
198 let ev_raw = get(TAG_EVERSION).ok_or(EditionError::MissingField("ev"))?;
199 if !is_tag_decimal(&ev_raw) {
200 return Err(EditionError::BadField("ev"));
201 }
202 let version: u64 = ev_raw.parse().map_err(|_| EditionError::BadField("ev"))?;
203 let prev_hash = match get(TAG_EPREV) {
204 Some(h) => Some(decode_hash(&h, "ep")?),
205 None => None,
206 };
207 let content = inner.content.clone();
208 let self_hash = version::edition_hash(&entity_id, version, prev_hash.as_ref(), content.as_bytes());
209 Ok(ParsedEdition {
210 author: inner.pubkey,
211 vsk,
212 entity_id,
213 version,
214 prev_hash,
215 content,
216 self_hash,
217 created_at: inner.created_at.as_secs(),
218 inner_id: inner.id.to_bytes(),
219 authority: AuthorityCitation::from_tags(&inner.tags),
220 binding: None,
221 })
222}
223
224impl ParsedEdition {
225 /// The [`version::Edition`] view used by [`version::fold`], every author ranked alike: right
226 /// wherever one author writes the whole entity (an owner-only document, a creator's own registry).
227 pub fn to_fold_edition(&self) -> version::Edition {
228 self.to_fold_edition_ranked(0)
229 }
230
231 /// As [`Self::to_fold_edition`], carrying the author's authority rank for fork tiebreaks.
232 pub fn to_fold_edition_ranked(&self, rank: u32) -> version::Edition {
233 version::Edition {
234 version: self.version,
235 prev_hash: self.prev_hash,
236 self_hash: self.self_hash,
237 created_at: self.created_at,
238 tiebreak_id: self.inner_id,
239 rank,
240 }
241 }
242}
243
244/// The folded current head of one control entity — what the caller persists via `set_edition_head`
245/// (the monotonic refuse-downgrade floor) and the send side reads to emit the next version.
246#[derive(Clone)]
247pub struct EntityHead {
248 /// The entity coordinate (role_id for roles, grant_locator for grants), lowercase hex.
249 pub entity_hex: String,
250 pub version: u64,
251 pub self_hash: [u8; 32],
252 /// The head edition's deterministic tiebreak key (the inner edition id). Used to resolve a
253 /// same-version concurrent fork: every client converges on the lower `inner_id` among authorized
254 /// editions, and the persisted head ranks by it so a same-version adopt only moves toward the min.
255 pub inner_id: [u8; 32],
256 /// The authority citation the head edition carried, if any — the actor's pinned proof of
257 /// the authority they claimed for this edit. `None` for an owner-signed edition (supreme, cites
258 /// nothing) or an uncited one. Verifiers resolve the actor's standing at the cited grant version
259 /// via [`authority_citation_satisfied`].
260 pub citation: Option<AuthorityCitation>,
261}
262
263/// version-pinned authority **completeness** check for an action that carries an
264/// [`AuthorityCitation`] (a ban, a hide, a delegated grant). The action names the authorizing
265/// grant edition it claims authority under; this confirms we have folded a COMPLETE, un-forked view of
266/// that grant — synced to AT LEAST the cited version, with the cited hash matching ours at equality.
267///
268/// It does NOT decide the permission/outrank — that stays with the caller's `can_act_on_member` against
269/// the CURRENT authorized roster, so a since-demoted actor is refused there (refuse-superseded falls out:
270/// we hold a later head of their grant that dropped the role). This check is the orthogonal half: it
271/// guarantees the verdict is computed over the same authority view the actor cited, not a stale or
272/// partial one.
273///
274/// `heads` is the fold's per-entity head set — the haystack the cited grant
275/// must appear in. `actor_grant_hex` is the entity coordinate of the ACTOR's OWN authorizing grant
276/// (`grant_locator(community_id, actor)`, lowercase hex): the citation MUST name it, so an actor can't
277/// borrow completeness by citing some other synced edition. Returns true iff:
278/// - the actor is the proven owner (supreme — cites nothing), OR
279/// - the citation names the actor's own grant AND we surfaced it at version ≥ the cited version, and —
280/// when our head is EXACTLY the cited version — the cited hash equals ours (a cited fork is rejected).
281///
282/// A non-owner who cited nothing, cited a foreign entity, or whose cited grant we have NOT folded up to
283/// the cited version (a withholding relay, or we are simply behind), returns false: FAIL CLOSED — never
284/// act on an incomplete authority view (the §"never act on a partial view" tenet). The block-until-synced
285/// re-fetch escalation across a relay quorum is deferred (one signature suffices, per the MVP directive);
286/// MVP fails closed here and self-heals on the next sync once the cited grant arrives.
287pub fn authority_citation_satisfied(
288 heads: &[EntityHead],
289 owner_hex: Option<&str>,
290 actor_hex: &str,
291 actor_grant_hex: &str,
292 citation: Option<&AuthorityCitation>,
293) -> bool {
294 let head_of = |entity_hex: &str| heads.iter().find(|h| h.entity_hex == entity_hex).map(|h| (h.version, h.self_hash));
295 authority_citation_satisfied_by(head_of, owner_hex, actor_hex, actor_grant_hex, citation)
296}
297
298/// [`authority_citation_satisfied`] with the heads looked up by `head_of`: an entity's
299/// `(version, self_hash)` as the first head held for it would give them.
300pub fn authority_citation_satisfied_by(
301 head_of: impl Fn(&str) -> Option<(u64, [u8; 32])>,
302 owner_hex: Option<&str>,
303 actor_hex: &str,
304 actor_grant_hex: &str,
305 citation: Option<&AuthorityCitation>,
306) -> bool {
307 if owner_hex == Some(actor_hex) {
308 return true;
309 }
310 let Some(c) = citation else { return false };
311 let entity_hex = crate::simd::hex::bytes_to_hex_32(&c.entity_id);
312 // The citation must name the ACTOR's OWN authorizing grant — citing a foreign synced edition can't
313 // borrow completeness (the permission check keys on the actor, but pinning to their grant keeps the
314 // sync-floor honest and is the coordinate the delegation verifier will resolve rank at).
315 if entity_hex != actor_grant_hex {
316 return false;
317 }
318 match head_of(&entity_hex) {
319 // We hold a LATER edition of the actor's grant than they cited — synced past it. Whether the
320 // actor is STILL authorized is the caller's roster check (which reflects this later head).
321 Some((version, _)) if version > c.version => true,
322 // Synced to exactly the cited version: the cited hash must be the one that won our fold (else
323 // the actor cited a non-canonical fork of their own grant).
324 Some((version, self_hash)) if version == c.version => self_hash == c.edition_hash,
325 // Not surfaced, or our head is BEHIND the cited version → we cannot confirm the authority.
326 _ => false,
327 }
328}
329
330#[cfg(test)]
331mod tests {
332 use super::*;
333
334 #[test]
335 fn authority_citation_satisfied_pins_to_a_synced_complete_grant() {
336 let owner = "ow".repeat(32);
337 let actor = "ac".repeat(32);
338 let entity = [0x55u8; 32];
339 let hash = [0x66u8; 32];
340 let eh = crate::simd::hex::bytes_to_hex_32(&entity); // the actor's own grant locator
341 let head = |v: u64, h: [u8; 32]| {
342 vec![EntityHead { entity_hex: eh.clone(), version: v, self_hash: h, inner_id: [0u8; 32], citation: None }]
343 };
344 let cite = AuthorityCitation { entity_id: entity, version: 3, edition_hash: hash };
345
346 // Owner is supreme and cites nothing.
347 assert!(authority_citation_satisfied(&[], Some(&owner), &owner, &eh, None));
348 // A non-owner with no citation fails closed.
349 assert!(!authority_citation_satisfied(&head(3, hash), Some(&owner), &actor, &eh, None));
350 // Synced to exactly the cited version with the matching hash → satisfied.
351 assert!(authority_citation_satisfied(&head(3, hash), Some(&owner), &actor, &eh, Some(&cite)));
352 // Same version, wrong hash (a cited fork at the tip) → rejected.
353 assert!(!authority_citation_satisfied(&head(3, [0xEE; 32]), Some(&owner), &actor, &eh, Some(&cite)));
354 // We hold a LATER head of the actor's grant → synced past it (the roster check handles supersession).
355 assert!(authority_citation_satisfied(&head(4, [0x77; 32]), Some(&owner), &actor, &eh, Some(&cite)));
356 // We are BEHIND the cited version → fail closed.
357 assert!(!authority_citation_satisfied(&head(2, hash), Some(&owner), &actor, &eh, Some(&cite)));
358 // The cited grant isn't surfaced at all → fail closed.
359 assert!(!authority_citation_satisfied(&[], Some(&owner), &actor, &eh, Some(&cite)));
360 // The citation names a FOREIGN entity (not the actor's grant) → rejected even if surfaced.
361 let foreign = "ff".repeat(32);
362 assert!(!authority_citation_satisfied(&head(3, hash), Some(&owner), &actor, &foreign, Some(&cite)));
363 }
364
365 const VSK_GRANT: &str = "3";
366
367 fn eid() -> [u8; 32] {
368 [0x42; 32]
369 }
370
371 #[test]
372 fn round_trips_authorship_version_and_chain_hash() {
373 let actor = Keys::generate();
374 let prev = version::edition_hash(&eid(), 1, None, b"{}");
375 let inner = build_edition_inner(actor.public_key(), VSK_GRANT, &eid(), 2, Some(&prev), "{\"role_ids\":[]}", 1_700_000_000, None)
376 .finalize(&actor)
377 .unwrap();
378
379 let parsed = parse_edition_inner(&inner).expect("valid edition parses");
380 assert_eq!(parsed.author, actor.public_key(), "authorship = the real signer");
381 assert_eq!(parsed.vsk, VSK_GRANT);
382 assert_eq!(parsed.entity_id, eid());
383 assert_eq!(parsed.version, 2);
384 assert_eq!(parsed.prev_hash, Some(prev));
385 assert_eq!(parsed.created_at, 1_700_000_000);
386 // self_hash matches the canonical recomputation (what the next edition will cite).
387 assert_eq!(
388 parsed.self_hash,
389 version::edition_hash(&eid(), 2, Some(&prev), b"{\"role_ids\":[]}")
390 );
391 // Folds into a version::Edition cleanly.
392 let fe = parsed.to_fold_edition();
393 assert_eq!(fe.version, 2);
394 assert_eq!(fe.prev_hash, Some(prev));
395 }
396
397 #[test]
398 fn authority_citation_round_trips_on_an_edition() {
399 // A delegated admin's edition carries the pinned authority citation; it survives sign→parse,
400 // covered by the inner signature, and does NOT alter the chain self_hash (per-action metadata).
401 let actor = Keys::generate();
402 let cite = AuthorityCitation { entity_id: [0xab; 32], version: 7, edition_hash: [0xcd; 32] };
403 let inner = build_edition_inner(actor.public_key(), VSK_GRANT, &eid(), 1, None, "{}", 100, Some(&cite))
404 .finalize(&actor)
405 .unwrap();
406 let parsed = parse_edition_inner(&inner).unwrap();
407 assert_eq!(parsed.authority.as_ref(), Some(&cite), "citation round-trips");
408 // self_hash is over (entity, version, prev, content) only — the citation doesn't perturb it.
409 assert_eq!(parsed.self_hash, version::edition_hash(&eid(), 1, None, b"{}"));
410
411 // An uncited edition (owner-signed) parses with authority == None.
412 let owner = build_edition_inner(actor.public_key(), VSK_GRANT, &eid(), 1, None, "{}", 100, None)
413 .finalize(&actor)
414 .unwrap();
415 assert_eq!(parse_edition_inner(&owner).unwrap().authority, None);
416 }
417
418 #[test]
419 fn authority_citation_tag_layout_is_frozen() {
420 // FROZEN wire layout: the citation rides as a 4-element `vac` tag
421 // `["vac", <entity hex>, <version>, <edition-hash hex>]`. A change here reshuffles how every
422 // verifier reads pinned authority, so pin the exact shape (not just a round-trip).
423 let cite = AuthorityCitation { entity_id: [0x11; 32], version: 9, edition_hash: [0x22; 32] };
424 let tag = cite.to_tag();
425 let s = tag.as_slice();
426 assert_eq!(s.len(), 4, "vac is a 4-element tag");
427 assert_eq!(s[0], TAG_AUTHORITY_CITATION);
428 assert_eq!(s[1], "11".repeat(32), "entity id is lowercase hex");
429 assert_eq!(s[2], "9", "version is the decimal string");
430 assert_eq!(s[3], "22".repeat(32), "edition hash is lowercase hex");
431 }
432
433 #[test]
434 fn genesis_edition_has_no_prev() {
435 let actor = Keys::generate();
436 let inner = build_edition_inner(actor.public_key(), "1", &eid(), 1, None, "{}", 100, None)
437 .finalize(&actor)
438 .unwrap();
439 let parsed = parse_edition_inner(&inner).unwrap();
440 assert_eq!(parsed.prev_hash, None, "first edition cites no predecessor");
441 assert_eq!(parsed.version, 1);
442 }
443
444 #[test]
445 fn tampered_content_fails_verification() {
446 // Re-sign integrity: flipping the content after signing breaks the inner Schnorr sig.
447 let actor = Keys::generate();
448 let inner = build_edition_inner(actor.public_key(), "3", &eid(), 1, None, "{\"a\":1}", 100, None)
449 .finalize(&actor)
450 .unwrap();
451 let mut json: serde_json::Value = serde_json::from_str(&inner.as_json()).unwrap();
452 json["content"] = serde_json::Value::String("{\"a\":2}".into()); // tamper
453 let tampered: Event = serde_json::from_value(json).unwrap();
454 assert!(matches!(parse_edition_inner(&tampered), Err(EditionError::BadSignature)));
455 }
456
457 #[test]
458 fn missing_required_field_is_rejected_not_panicked() {
459 // An inner event lacking the entity-id tag is a parse error, never a panic.
460 let actor = Keys::generate();
461 let inner = EventBuilder::new(Kind::Custom(crate::community::v2::kind::CONTROL), "{}")
462 .tags([Tag::custom("vsk", ["3".to_string()])])
463 .finalize(&actor)
464 .unwrap();
465 assert!(matches!(parse_edition_inner(&inner), Err(EditionError::MissingField("eid"))));
466 }
467
468 #[test]
469 fn duplicate_authority_tag_is_rejected() {
470 // A duplicate of ANY of the 5 authority tags (vsk/eid/ev/ep/vac) makes signed-event → canonical
471 // bytes ambiguous (clients could pick different ones) → chain divergence, so it must be rejected.
472 // Parameterized across all 5 — a regression dropping any one from the dedup loop is caught.
473 let actor = Keys::generate();
474 let hash = crate::simd::hex::bytes_to_hex_32(&[0xAB; 32]);
475 let base = || -> Vec<Tag> {
476 vec![
477 Tag::custom("vsk", ["1".to_string()]),
478 Tag::custom("eid", [crate::simd::hex::bytes_to_hex_32(&eid())]),
479 Tag::custom("ev", ["1".to_string()]),
480 Tag::custom("ep", [hash.clone()]),
481 Tag::custom("vac", [crate::simd::hex::bytes_to_hex_32(&eid()), "1".to_string(), hash.clone()]),
482 ]
483 };
484 let build = |tags: Vec<Tag>| EventBuilder::new(Kind::Custom(crate::community::v2::kind::CONTROL), "{}")
485 .tags(tags).finalize(&actor).unwrap();
486 assert!(parse_edition_inner(&build(base())).is_ok(), "a clean 5-tag base edition parses");
487 for name in ["vsk", "eid", "ev", "ep", "vac"] {
488 let mut tags = base();
489 let dup = tags.iter().find(|t| t.as_slice().first().map(|s| s == name).unwrap_or(false)).cloned().unwrap();
490 tags.push(dup);
491 assert!(
492 matches!(parse_edition_inner(&build(tags)), Err(EditionError::BadField("duplicate authority tag"))),
493 "a duplicate `{name}` tag must be rejected"
494 );
495 }
496 }
497}