Skip to main content

vector_core/community/
migration.rs

1//! v1 → v2 community migration — the atomic dissolution-carrier wire codec (task #10).
2//!
3//! The migration rides INSIDE the vsk=10 GroupDissolved tombstone's content: a signpost
4//! (where the v2 twin lives) plus `m`, the complete v2 JoinMaterial sealed under the v1
5//! server root at publish time. One owner-signed event seals v1, signposts v2, and IS
6//! every member's invite. Shipped v0.4.0 never parses tombstone content (validity is
7//! vsk + coordinate + signer), so old clients fold this as a plain dissolution — composer
8//! lockdown, history intact — and the relays retain the event for any later re-probe.
9//!
10//! Scope discipline: the signpost is readable by anyone who can open the tombstone's
11//! id-derived envelope (it grants nothing); `m` opens only under a held server-root epoch
12//! key — exactly v1's confidentiality boundary, so a read-cut member cannot open it. Keys
13//! are NEVER placed under the id-derived envelope: the community id rides in every invite
14//! bundle ever shared and is not a secret.
15
16use super::cipher;
17use super::roster::DissolvedEdition;
18use super::transport::Transport;
19use super::{Community, CommunityId};
20use crate::state::SessionGuard;
21use serde::{Deserialize, Serialize};
22use std::collections::HashSet;
23use std::sync::{LazyLock, Mutex as StdMutex};
24
25/// v1 cids with a `drive_migration` in flight — mutual exclusion so the boot maintenance
26/// and the live carrier-fold never drive the SAME community concurrently. Without it two
27/// drives can interleave a channel-less `save_community_v2` (which prunes) after the other's
28/// re-parent commit, deleting a just-adopted row. Cleared on account swap.
29static DRIVE_INFLIGHT: LazyLock<StdMutex<HashSet<String>>> =
30    LazyLock::new(|| StdMutex::new(HashSet::new()));
31
32/// Clear the drive-in-flight set (account swap — the new account's drives must not be
33/// blocked by a stale claim from the old one).
34pub fn clear_drive_inflight() {
35    DRIVE_INFLIGHT.lock().unwrap_or_else(|e| e.into_inner()).clear();
36}
37
38/// RAII claim on [`DRIVE_INFLIGHT`]. `take` returns `None` when the cid is already claimed
39/// (drive vs drive, wizard vs drive, wizard vs wizard). Drop is generation-aware: after an
40/// account swap clears the set, a stale claim's unwind must not release the claim the NEW
41/// account just inserted for the same cid.
42struct DriveClaim(String, SessionGuard);
43impl DriveClaim {
44    fn take(cid: &str) -> Option<Self> {
45        let mut inflight = DRIVE_INFLIGHT.lock().unwrap_or_else(|e| e.into_inner());
46        if !inflight.insert(cid.to_string()) {
47            return None;
48        }
49        Some(DriveClaim(cid.to_string(), SessionGuard::capture()))
50    }
51}
52impl Drop for DriveClaim {
53    fn drop(&mut self) {
54        if self.1.is_valid() {
55            DRIVE_INFLIGHT.lock().unwrap_or_else(|e| e.into_inner()).remove(&self.0);
56        }
57    }
58}
59
60/// Test hooks: stand in for a concurrent drive holding the claim (the claim is private and
61/// RAII-scoped, so a test can't otherwise model "another drive is mid-flight").
62#[cfg(test)]
63pub fn test_hold_drive_claim(cid: &str) {
64    DRIVE_INFLIGHT.lock().unwrap_or_else(|e| e.into_inner()).insert(cid.to_string());
65}
66#[cfg(test)]
67pub fn test_release_drive_claim(cid: &str) {
68    DRIVE_INFLIGHT.lock().unwrap_or_else(|e| e.into_inner()).remove(cid);
69}
70
71/// When the owner-side migration wizard unlocks: 2026-08-04 00:00:00 UTC. Gates ONLY the
72/// wizard (UI row + command entry); the member-side machinery is live from release day, so
73/// a migration performed by a lock-bypassing build still carries every member along. A
74/// coordination gate, not a security gate.
75pub const MIGRATION_UNLOCK_AT: u64 = 1_785_801_600;
76
77/// Bound on the whole tombstone content string before any parse. The outer NIP-44 seal
78/// caps its plaintext at 65535 bytes, so anything larger is garbage by construction.
79pub const MAX_PAYLOAD_CONTENT: usize = 100_000;
80/// Bound on the base64 `m` string inside the payload (checked before decode/open).
81pub const MAX_M_B64: usize = 90_000;
82/// Display-name cap in the signpost — truncated, not rejected (fail-safe parse).
83pub const MAX_SIGNPOST_NAME: usize = 120;
84/// Conservative relay max-event-size floor (strfry default is 64 KB): the final sealed
85/// OUTER event's JSON must stay under this or common relays will reject the publish.
86pub const MAX_WIRE_EVENT: usize = 60_000;
87
88/// The plaintext signpost: where the v2 twin lives. Grants nothing by itself — every field
89/// is verified against the member's held v1 owner anchor (triple-bind) before any use.
90#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
91pub struct MigrationSignpost {
92    /// The v2 self-certifying community id. Must recompute from `owner_xonly` + `owner_salt`.
93    pub v2_community_id: String,
94    /// Must equal the member's held v1 owner anchor (owner continuity — the consent basis).
95    pub owner_xonly: String,
96    /// The v2 owner salt (public input to the self-cert id).
97    pub owner_salt: String,
98    /// The v2 relay set (capped like every other attacker-influencable relay list).
99    pub relays: Vec<String>,
100    /// Display name at migration time (informational only).
101    pub name: String,
102    /// Which stitched channel the one-row UI surfaces.
103    pub primary_channel: String,
104    /// The v1 base epoch at publish — bounds a stale member's catch-up walk before they
105    /// conclude `m` is unopenable (a member holding an epoch >= this that still cannot
106    /// open `m` is genuinely outside the member set).
107    #[serde(default)]
108    pub root_epoch: u64,
109}
110
111/// The parsed migration payload: signpost + optionally the sealed key material.
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct MigrationPayload {
114    pub signpost: MigrationSignpost,
115    /// base64 NIP-44 seal of the v2 JoinMaterial under the v1 server_root at publish.
116    /// `None` = signpost-only (still a valid pointer; the member falls back to the
117    /// straggler CTA if no key material ever opens).
118    pub m: Option<String>,
119}
120
121/// Wire shape of the tombstone content. `migrated_to` keys the signpost so a plain `{}`
122/// (the pre-migration dissolution) deserializes to "no payload" rather than erroring.
123#[derive(Serialize, Deserialize)]
124struct WirePayload {
125    migrated_to: MigrationSignpost,
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    m: Option<String>,
128}
129
130fn is_hex64(s: &str) -> bool {
131    s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())
132}
133
134/// Parse a tombstone's content into a migration payload. Fail-SAFE by contract: any bound
135/// violation, shape error, or bad field returns `None` — the event remains a plain
136/// dissolution and the SEAL is never rejected. Ids are lowercase-normalized; relays are
137/// capped by truncation (hostile payloads degrade, never amplify); the name is truncated.
138pub fn parse_migration_payload(content: &str) -> Option<MigrationPayload> {
139    if content.len() > MAX_PAYLOAD_CONTENT {
140        return None;
141    }
142    let wire: WirePayload = serde_json::from_str(content).ok()?;
143    let mut sp = wire.migrated_to;
144    if !is_hex64(&sp.v2_community_id)
145        || !is_hex64(&sp.owner_xonly)
146        || !is_hex64(&sp.owner_salt)
147        || !is_hex64(&sp.primary_channel)
148    {
149        return None;
150    }
151    sp.v2_community_id = sp.v2_community_id.to_lowercase();
152    sp.owner_xonly = sp.owner_xonly.to_lowercase();
153    sp.owner_salt = sp.owner_salt.to_lowercase();
154    sp.primary_channel = sp.primary_channel.to_lowercase();
155    sp.relays = super::cap_relays(sp.relays);
156    if sp.name.chars().count() > MAX_SIGNPOST_NAME {
157        sp.name = sp.name.chars().take(MAX_SIGNPOST_NAME).collect();
158    }
159    let m = match wire.m {
160        Some(m) if m.len() > MAX_M_B64 => return None,
161        other => other,
162    };
163    Some(MigrationPayload { signpost: sp, m })
164}
165
166/// Serialize a payload for the tombstone content (the wizard's side of [`parse_migration_payload`]).
167pub fn build_migration_content(signpost: &MigrationSignpost, m: Option<String>) -> Result<String, String> {
168    serde_json::to_string(&WirePayload { migrated_to: signpost.clone(), m })
169        .map_err(|e| format!("serialize migration payload: {e}"))
170}
171
172/// Seal the v2 JoinMaterial under the v1 server root at publish time. Errors past NIP-44's
173/// 65535-byte plaintext cap — the wizard surfaces that as a clean abort, never a truncation.
174pub fn seal_m(server_root: &[u8; 32], join_material_json: &[u8]) -> Result<String, String> {
175    cipher::seal(server_root, join_material_json)
176}
177
178/// Try to open `m` under EVERY held server-root epoch key, newest first — absorbs both a
179/// stale local head and a concurrent v1 refound that advanced past the publish root.
180/// `None` = no held root opens it (caller decides: catch-up walk, then the straggler CTA).
181pub fn open_m(held_roots: &[(u64, [u8; 32])], m_b64: &str) -> Option<Vec<u8>> {
182    if m_b64.len() > MAX_M_B64 {
183        return None;
184    }
185    let mut roots: Vec<&(u64, [u8; 32])> = held_roots.iter().collect();
186    roots.sort_by(|a, b| b.0.cmp(&a.0));
187    for (_, key) in roots {
188        if let Ok(plain) = cipher::open(key, m_b64) {
189            return Some(plain);
190        }
191    }
192    None
193}
194
195/// Total, payload-aware pointer selection over the owner's tombstones: the pointer comes
196/// from the newest PAYLOAD-CARRYING owner-signed tombstone (tiebreak lowest inner id); a
197/// payload-less `{}` tombstone SEALS the community but never shadows a payload-bearing one
198/// — otherwise a plain dissolution from a second device would silently shed the keys for
199/// every future straggler. (Corollary, deliberate: a NEWER payload-bearing tombstone
200/// WITHOUT `m` is the owner's honest-client-scoped retraction lever for the on-ramp.)
201pub fn select_pointer(editions: &[DissolvedEdition], owner_hex: &str) -> Option<(MigrationPayload, String)> {
202    let mut best: Option<(&DissolvedEdition, MigrationPayload)> = None;
203    for e in editions {
204        if e.author.to_hex() != owner_hex {
205            continue;
206        }
207        let Some(payload) = parse_migration_payload(&e.content) else { continue };
208        best = match best {
209            Some((cur, cur_p))
210                if (cur.created_at, std::cmp::Reverse(cur.inner_id))
211                    >= (e.created_at, std::cmp::Reverse(e.inner_id)) =>
212            {
213                Some((cur, cur_p))
214            }
215            _ => Some((e, payload)),
216        };
217    }
218    // The raw winning content rides along so the caller can persist the exact wire form
219    // (re-parseable later without a second serializer for the payload).
220    best.map(|(e, p)| (p, e.content.clone()))
221}
222
223/// Wire-size gate for the final sealed OUTER event — computed on the actual bytes, never
224/// estimated. Run by the wizard before publishing; failing is a clean abort.
225pub fn check_outer_size(outer: &nostr_sdk::prelude::Event) -> Result<(), String> {
226    let len = outer.as_json().len();
227    if len > MAX_WIRE_EVENT {
228        return Err(format!(
229            "migration event is {len} bytes, over the {MAX_WIRE_EVENT}-byte relay ceiling; \
230             this community is too large for a single migration event"
231        ));
232    }
233    Ok(())
234}
235
236// ── Member flow: fold a migration pointer → open `m` → flip to v2 ─────────────────────────
237
238/// The dissolved-gate exemption: a base rekey may advance a SEALED community's epoch
239/// only while a migration pointer is held, the flip hasn't happened, and the target epoch
240/// does not exceed the pointer's publish epoch. Lets a stale member walk their held root
241/// forward to the one `m` was sealed under, without ever re-opening the seal for anything
242/// else. Any read error fails closed (no exemption).
243pub fn catchup_exempt(community_id: &str, target_epoch: u64) -> bool {
244    if crate::db::community::get_migrated_to(community_id).ok().flatten().is_some() {
245        return false; // already flipped — the fence stands
246    }
247    let Ok(Some(raw)) = crate::db::community::get_migration_pointer(community_id) else {
248        return false; // no pointer → a plain dissolution, never advances
249    };
250    let Some(payload) = parse_migration_payload(&raw) else { return false };
251    target_epoch <= payload.signpost.root_epoch
252}
253
254/// Held server-root epoch keys for a community, for the multi-root `m` open.
255fn held_roots(community_id: &str) -> Vec<(u64, [u8; 32])> {
256    crate::db::community::held_epoch_keys(community_id, crate::community::SERVER_ROOT_SCOPE_HEX)
257        .unwrap_or_default()
258        .into_iter()
259        .map(|(e, k)| (e.0, k))
260        .collect()
261}
262
263/// Drive a held v1 community's migration to completion when a pointer is present and the
264/// flip hasn't happened: open `m` (catching a stale root up first, no-erase), join the v2
265/// twin through the ban-gated accept path, then run the flip transaction. Idempotent and
266/// resumable — safe to call from the boot sweep, the live fold, and the fallback door.
267/// Returns `Ok(Some(v2_id))` on a completed flip, `Ok(None)` when nothing was actionable
268/// (no pointer, already flipped, or `m` unopenable — the straggler CTA case).
269pub async fn drive_migration<T: Transport + ?Sized>(
270    transport: &T,
271    community: &Community,
272) -> Result<Option<String>, String> {
273    let session = SessionGuard::capture();
274    let cid = community.id.to_hex();
275
276    // Claim the in-flight slot or bail — a concurrent drive (boot maintenance vs the live
277    // carrier fold, or the owner's wizard vs their own fold) is already handling this cid.
278    // Without this, two channel-less v2 saves can interleave a prune after the other's
279    // re-parent. The claim is released on ANY exit (RAII).
280    let Some(_claim) = DriveClaim::take(&cid) else {
281        return Ok(None);
282    };
283
284    // Already flipped? Nothing to do (idempotent double-trigger).
285    if crate::db::community::get_migrated_to(&cid).ok().flatten().is_some() {
286        return Ok(None);
287    }
288    let Some(raw) = crate::db::community::get_migration_pointer(&cid)? else {
289        return Ok(None); // no pointer → not a migration
290    };
291    let Some(payload) = parse_migration_payload(&raw) else {
292        // A stored-but-unparseable pointer is inert; mark checked so the sweep converges.
293        let _ = crate::db::community::set_migration_checked(&cid);
294        return Ok(None);
295    };
296
297    // Triple-bind check 2 — OWNER CONTINUITY: the v2 owner the signpost claims MUST equal this
298    // v1 community's proven owner (the pointer is already owner-signed at the bound coordinate,
299    // check 1). A migration that changes the owner identity is NOT eligible for consent-free
300    // join — identity continuity is the whole basis for skipping consent. Fail-closed: no
301    // proven owner ⇒ no continuity ⇒ no auto-join. (check 3 — the v2 self-cert recompute — runs
302    // inside accept_bundle.)
303    let Some(owner) = super::service::proven_owner_hex(community) else { return Ok(None) };
304    if payload.signpost.owner_xonly != owner {
305        return Ok(None); // owner discontinuity → not a consent-free migration
306    }
307    // Bind the v2 self-cert id to the signpost's own owner/salt before the network join.
308    if !super::v2::derive::verify_community_id(
309        &CommunityId(crate::simd::hex::hex_to_bytes_32(&payload.signpost.v2_community_id)),
310        &crate::simd::hex::hex_to_bytes_32(&payload.signpost.owner_xonly),
311        &crate::simd::hex::hex_to_bytes_32(&payload.signpost.owner_salt),
312    ) {
313        return Ok(None); // the v2 id is not a commitment to this owner+salt
314    }
315
316    let Some(m_b64) = payload.m.as_deref() else {
317        return Ok(None); // signpost-only pointer → straggler CTA, no keys to open
318    };
319
320    // Open `m` under any held root; if none opens and we're stale vs the publish epoch,
321    // walk the base root forward (no-erase: the `removed` signal is ignored — the community
322    // is terminal either way) and retry. The exemption above lets this walk run despite the
323    // seal.
324    let mut plain = open_m(&held_roots(&cid), m_b64);
325    if plain.is_none() && community.server_root_epoch.0 < payload.signpost.root_epoch {
326        let _ = super::service::catch_up_server_root(transport, community).await;
327        if !session.is_valid() {
328            return Err("account changed during migration catch-up".to_string());
329        }
330        plain = open_m(&held_roots(&cid), m_b64);
331    }
332    let Some(plain) = plain else {
333        return Ok(None); // unopenable (read-cut or lost-DB) → straggler CTA
334    };
335
336    // Verify the JoinMaterial's owner matches the pointer's owner continuity claim before
337    // trusting it (the self-cert id recompute is the fail-closed gate inside accept_bundle).
338    let jm: super::v2::list::JoinMaterial =
339        serde_json::from_slice(&plain).map_err(|e| format!("migration join material parse: {e}"))?;
340    if jm.community_id != payload.signpost.v2_community_id || jm.owner != payload.signpost.owner_xonly {
341        return Err("migration payload keys disagree with the signpost".to_string());
342    }
343
344    // held-v2 dedup: if this account ALREADY holds the v2 twin, do NOT network-join
345    // it again — flip only. Covers the idempotent double-trigger, a multi-device peer that
346    // synced the twin via the 13302 list first, and the OWNER's own client (the wizard
347    // created the twin, so the owner holds it — accept_bundle must never try to "join" it).
348    let v2_id = CommunityId(crate::simd::hex::hex_to_bytes_32(&payload.signpost.v2_community_id));
349    let v2_hex = payload.signpost.v2_community_id.clone();
350    if crate::db::community::load_community_v2(&v2_id)?.is_none() {
351        // Join the v2 twin (ban-gated, owner-root-verified). A refusal (banned / forged
352        // root) leaves the community sealed — never a half-flip.
353        let v2 = super::v2::service::accept_migration_material(transport, &jm).await?;
354        if crate::simd::hex::bytes_to_hex_32(&v2.identity.community_id.0) != v2_hex {
355            return Err("joined community id disagrees with the migration pointer".to_string());
356        }
357        if !session.is_valid() {
358            return Err("account changed during migration join".to_string());
359        }
360    }
361
362    // The flip: re-parent the stitched channel rows + stamp the fence (one txn). The v2
363    // community ROW already exists (accept saved it, or this account already held it); NO
364    // save_community_v2 here — the v2 view is channel-less (its channel ids were v1-owned →
365    // skipped by the hijack guard), so a re-save would PRUNE the just-re-parented rows.
366    // Public channels fold from the control plane; the re-parented rows carry the history.
367    // Under the twin's follow lock: the follow worker's whole-row save deletes channel rows
368    // absent from a pre-flip-loaded (channel-less) struct, so the flip must not straddle it.
369    // Guard IMMEDIATELY before the most destructive write in the feature — the held-v2
370    // path above skips the join branch (and its check), so this is the one that counts.
371    let flock = super::v2::realtime::follow_lock(&v2_id);
372    let _fguard = flock.lock().await;
373    if !session.is_valid() {
374        return Err("account changed during migration flip".to_string());
375    }
376    crate::db::community::reparent_channels_and_fence(&cid, &v2_hex)?;
377    Ok(Some(v2_hex))
378}
379
380// ── Owner flow: the migration wizard ─────────────────────────────────────────────────────
381
382/// Ledger phases (persisted in `community_migrations.phase`). Each is idempotent + resumable.
383/// TWIN_MINTED lands IMMEDIATELY after the twin's genesis returns, BEFORE the sibling-channel
384/// and banlist tail — so a crash anywhere in that multi-await tail resumes onto the SAME twin
385/// instead of re-minting a fresh identity (which would orphan the first genesis on the relays).
386/// Residual window: a crash INSIDE create_migration_twin (after its local save, before return
387/// — spanning its genesis + guestbook publishes, so seconds over a slow transport) still
388/// re-mints on the next run and leaves a phantom v2 row — bounded: no carrier ever references
389/// it, so no member is ever stranded; it is a dead genesis plus one stale local row.
390pub const PHASE_TWIN_MINTED: i64 = 1;
391pub const PHASE_TWIN_BUILT: i64 = 2;
392/// Birth refound 0→1 + Guestbook snapshot of the full v1 roster landed. AFTER this the twin
393/// is at epoch 1, so `m` (sealed in the next phase) carries the epoch-1 root — the whole
394/// reason for the refound (genesis has no snapshot authority).
395pub const PHASE_TWIN_REFOUNDED: i64 = 3;
396pub const PHASE_CARRIER_PUBLISHED: i64 = 4;
397pub const PHASE_FLIPPED: i64 = 5;
398
399/// The full v1 memberlist to seed into the twin's epoch-1 Guestbook. `community_member_activity`
400/// IS v1's single source of truth for "who is a member": it already unions observed authors +
401/// the owner + every roster grant-holder, subtracts the banlist, and applies the leave filter
402/// — so the seed is exactly that set (fetched UNCAPPED, so a large community seeds every
403/// member instead of the top 500-by-recency). Using it verbatim means the v2 seed can NEVER
404/// diverge from what v1 itself shows as members.
405///
406/// note: a v1 admin who LEFT but was never stripped of their grant is re-asserted as a
407/// member by that function (v1's rule: a leave must not lock a sitting admin out) — so they
408/// ARE seeded. That is v1-faithful (v1 shows them as a member), a deliberate divergence from
409/// the design's "− left" line for the admin case; a NON-admin who left is dropped by the leave
410/// filter. `owner_hex` is unused now (the DB seeds the owner) but kept for call-site clarity.
411fn v1_snapshot_members(v1_cid: &str, _owner_hex: &str) -> Vec<nostr_sdk::prelude::PublicKey> {
412    crate::db::community::community_member_activity_capped(v1_cid, false)
413        .unwrap_or_default()
414        .iter()
415        .filter_map(|(npub, _)| nostr_sdk::prelude::PublicKey::parse(npub).ok())
416        .collect()
417}
418
419/// Whether the owner wizard is unlocked (the timelock is a coordination gate, re-checked at
420/// the command entry, not just in the UI). `now_secs` is passed in (the core has no clock).
421pub fn wizard_unlocked(now_secs: u64) -> bool {
422    now_secs >= MIGRATION_UNLOCK_AT
423}
424
425/// The post-timelock door for FRESH v1 joins, probe-first. Pre-unlock, or a community we
426/// already hold (re-accept / cross-device rehydrate), passes locally. Post-unlock a fresh
427/// join passes ONLY when the rotation-stable dissolved coordinate carries the proven
428/// owner's migration pointer — that join is the permanent on-ramp (save → carrier fold
429/// seals → drive lands the joiner in the v2 twin). A live v1 community, an unprovable
430/// owner, or a relay miss all refuse: fail-closed, a retry beats onboarding a fresh user
431/// onto the legacy protocol. Every v1 join door (Tauri direct + public accepts, facade
432/// direct + public accepts) must call this before persisting anything.
433pub async fn gate_fresh_v1_join<T: Transport + ?Sized>(
434    transport: &T,
435    community: &Community,
436    now_secs: u64,
437) -> Result<(), String> {
438    if now_secs < MIGRATION_UNLOCK_AT {
439        return Ok(());
440    }
441    if matches!(crate::db::community::load_community(&community.id), Ok(Some(_))) {
442        return Ok(());
443    }
444    if let Some(owner) = super::service::proven_owner_hex(community) {
445        let records = super::service::dissolved_tombstone_records(transport, community).await;
446        if select_pointer(&records, &owner).is_some() {
447            return Ok(());
448        }
449    }
450    Err("This community still uses the legacy protocol and can no longer be joined. Ask the owner to upgrade it to Concord v2 and share a fresh invite.".to_string())
451}
452
453/// The UI state ladder for a v1 community's migration row, in priority order. Pure so the
454/// ordering is testable: `in_progress` MUST outrank `dissolved`, because the owner's own
455/// carrier self-fold seals v1 while the flip is still pending — exactly the window the
456/// Resume affordance exists for. A ledger row only ever exists on the wizard's own account.
457pub fn migration_state(
458    migrated: bool,
459    ledger_phase: i64,
460    dissolved: bool,
461    is_owner: bool,
462    unlocked: bool,
463) -> &'static str {
464    if migrated {
465        "migrated"
466    } else if ledger_phase > 0 && is_owner {
467        "in_progress"
468    } else if dissolved {
469        "dissolved"
470    } else if !is_owner {
471        "not_owner"
472    } else if unlocked {
473        "ready"
474    } else {
475        "locked"
476    }
477}
478
479/// Whether the wizard may run for this community (the row's action is armed). A sealed
480/// community is eligible ONLY as a resume of its own in-flight migration.
481pub fn migration_eligible(migrated: bool, ledger_phase: i64, dissolved: bool, is_owner: bool) -> bool {
482    is_owner && !migrated && (!dissolved || ledger_phase > 0)
483}
484
485/// Owner-side migration wizard: build the v2 twin (reusing v1 channel ids + cloning the
486/// banlist), seal the twin's JoinMaterial into `m`, publish the carrier dissolution on v1,
487/// then flip the owner's own client to v2. Resumable via the migration-77 ledger — a re-run
488/// after a crash picks up at the recorded phase. Every phase re-checks the `SessionGuard`.
489/// `now_secs` gates the timelock. Returns the v2 community id on completion.
490/// Emit a wizard progress step to the UI (no-op on headless clients via the unregistered
491/// emitter). `pct` is OVERALL progress 0-100 across the whole wizard; `label` is layman-facing.
492/// The frontend renders a determinate ring + this label in an unclosable modal (rekey contract).
493fn emit_migration_progress(label: &str, pct: u8) {
494    crate::emit_event("community_migration_progress", &serde_json::json!({ "label": label, "pct": pct }));
495}
496
497pub async fn migrate_community_to_v2<T: Transport + ?Sized>(
498    transport: &T,
499    v1: &Community,
500    now_secs: u64,
501) -> Result<String, String> {
502    let session = SessionGuard::capture();
503    let v1_cid = v1.id.to_hex();
504    // One wizard/drive at a time per cid: a double-fired command would race the twin mint
505    // pre-ledger (the double-mint orphan window) and its flip against a concurrent drive's.
506    let Some(_claim) = DriveClaim::take(&v1_cid) else {
507        return Err("this community's upgrade is already in progress".to_string());
508    };
509    emit_migration_progress("Preparing the upgrade...", 5);
510
511    // Phase 0 — preflight (owner, unlocked, not already dissolved/migrated).
512    if !wizard_unlocked(now_secs) {
513        return Err("community migration is not unlocked yet".to_string());
514    }
515    if !super::service::is_proven_owner(v1) {
516        return Err("only the community owner can migrate the community".to_string());
517    }
518    // Already migrated? Check FIRST — a migrated community is ALSO dissolved (the flip seals
519    // it), so this must precede the dissolved gate below or a legitimate crash-heal reads as
520    // a plain dissolution.
521    if let Some(v2) = crate::db::community::get_migrated_to(&v1_cid).ok().flatten() {
522        // Crash-heal: the flip LANDED but the FLIPPED ledger write didn't (a crash between
523        // the two). This re-run is a COMPLETED migration — heal the ledger and report
524        // success instead of erroring on our own success.
525        if let Some((ledger_v2, phase, _)) = crate::db::community::get_migration_ledger(&v1_cid).ok().flatten() {
526            if ledger_v2 == v2 && phase < PHASE_FLIPPED {
527                let _ = crate::db::community::set_migration_ledger(&v1_cid, &v2, PHASE_FLIPPED, "");
528                return Ok(v2);
529            }
530        }
531        return Err("this community has already been migrated".to_string());
532    }
533    // Resume ledger read up-front — a ledger row means THIS owner already began THIS
534    // migration, which the dissolved gate below keys off.
535    let ledger = crate::db::community::get_migration_ledger(&v1_cid).ok().flatten();
536    let resume_phase = ledger.as_ref().map(|(_, p, _)| *p).unwrap_or(0);
537
538    // Not already dissolved: a carrier published for a sealed-but-UNMIGRATED
539    // community is undeliverable — members' folds short-circuit on the seal and never see
540    // it, so the owner would flip alone. A plain dissolution and a migration are mutually
541    // exclusive endings. EXEMPT a resume (`resume_phase > 0`) — a `dissolved=1` flag on
542    // a community whose wizard already started is this owner's OWN carrier seal (e.g. a
543    // self-fold sealed it after CARRIER_PUBLISHED, then the flip write flaked), not a foreign
544    // plain dissolution; without the exemption that transient failure reads as false-terminal.
545    if resume_phase == 0 && crate::db::community::get_community_dissolved(&v1_cid).unwrap_or(false) {
546        return Err("this community has been dissolved; it cannot be migrated".to_string());
547    }
548    let Some(owner_hex) = super::service::proven_owner_hex(v1) else {
549        return Err("cannot resolve the community owner".to_string());
550    };
551
552    // Phase 1a — mint (or reload) the v2 twin: primary channel reuses the v1 primary id.
553    emit_migration_progress("Creating the new community...", 15);
554    let twin = if resume_phase >= PHASE_TWIN_MINTED {
555        let (v2_hex, _, _) = ledger.as_ref().unwrap();
556        crate::db::community::load_community_v2(&CommunityId(crate::simd::hex::hex_to_bytes_32(v2_hex)))?
557            .ok_or("migration twin missing on resume")?
558    } else {
559        let primary = v1.channels.first().ok_or("v1 community has no channels")?;
560        let twin = super::v2::service::create_migration_twin(
561            transport,
562            &v1.name,
563            v1.relays.clone(),
564            v1.description.clone(),
565            (primary.id, primary.name.clone()),
566        )
567        .await?;
568        // Ledger the minted identity IMMEDIATELY — before the sibling/banlist tail — so no
569        // crash in that tail can re-mint a second twin (the double-mint orphan window).
570        let v2_hex = crate::simd::hex::bytes_to_hex_32(&twin.identity.community_id.0);
571        if !session.is_valid() {
572            return Err("account changed during twin mint".to_string());
573        }
574        crate::db::community::set_migration_ledger(&v1_cid, &v2_hex, PHASE_TWIN_MINTED, "")?;
575        twin
576    };
577    let v2_hex = crate::simd::hex::bytes_to_hex_32(&twin.identity.community_id.0);
578
579    // Phase 1b — sibling channels + banlist clone. Idempotent, so a resume at TWIN_MINTED
580    // re-runs the whole tail: a re-created channel publishes a vsk-2 chain ADVANCE with the
581    // same content (readers converge either way) and the local save skips v1-owned rows.
582    if resume_phase < PHASE_TWIN_BUILT {
583        emit_migration_progress("Copying channels, roles and bans...", 35);
584        // Additional v1 channels reuse their ids on the twin (public — v1 has no private
585        // channel model in the shipped protocol, so all stitch as public).
586        for ch in v1.channels.iter().skip(1) {
587            super::v2::service::create_public_channel_with_id(transport, &twin, &ch.name, ch.id).await?;
588        }
589        // Clone the v1 banlist so the v2 join-time ban gate catches v1-banned members.
590        let banlist = crate::db::community::get_community_banlist(&v1_cid).unwrap_or_default();
591        super::v2::service::clone_banlist_to_twin(transport, &twin, &banlist).await?;
592        if !session.is_valid() {
593            return Err("account changed during banlist clone".to_string());
594        }
595        // Clone governance: every v1 full admin is re-granted @admin on the twin (owner is
596        // supreme by identity; banned members skipped). Banlist BEFORE governance so a
597        // banned admin never regains authority on v2.
598        let v1_roles = crate::db::community::get_community_roles(&v1_cid).unwrap_or_default();
599        super::v2::service::clone_governance_to_twin(transport, &twin, &v1_roles, &banlist).await?;
600        // The twin persists via save_community_v2 (community row + control plane); its public
601        // channel rows stay v1-owned until the flip re-parents them (the hijack guard).
602        // The ledger needs only the v2 id — a resume reloads the rest from DB + control plane.
603        if !session.is_valid() {
604            return Err("account changed during twin build".to_string());
605        }
606        crate::db::community::set_migration_ledger(&v1_cid, &v2_hex, PHASE_TWIN_BUILT, "")?;
607    }
608
609    // Phase 1c — BIRTH REFOUND 0→1 + seed the full v1 roster. Genesis has no snapshot
610    // authority, so the twin must roll to epoch 1 (owner-only rekey) carrying an owner-signed
611    // Guestbook snapshot of the v1 memberlist. After this the twin is at epoch 1 and `m` (next
612    // phase) carries the epoch-1 root. Members join at epoch 1; not-yet-landed seeds show as
613    // members (holding no keys) and RECEIVE every future rotation's blob, so a late migrator
614    // never misses an epoch. Idempotent: mint_or_reuse re-delivers the same epoch-1 root, the
615    // compaction re-wraps the same heads, the snapshot re-publishes (fresh snap_id each run;
616    // convergence is coalesce commutativity, safe because it precedes the carrier).
617    if resume_phase < PHASE_TWIN_REFOUNDED {
618        emit_migration_progress("Securing member access...", 55);
619        let members = v1_snapshot_members(&v1_cid, &owner_hex);
620        super::v2::service::refound_at_birth(transport, &twin, &members).await?;
621        if !session.is_valid() {
622            return Err("account changed during birth refound".to_string());
623        }
624        crate::db::community::set_migration_ledger(&v1_cid, &v2_hex, PHASE_TWIN_REFOUNDED, "")?;
625    }
626    // Reload the twin at its CURRENT epoch (1 after the refound) so `m` seals the epoch-1
627    // root, not the throwaway genesis root. On a resume ≥ TWIN_REFOUNDED the persisted twin
628    // is already at epoch 1; this reload makes both paths converge.
629    let twin = crate::db::community::load_community_v2(&twin.identity.community_id)?
630        .ok_or("migration twin missing after birth refound")?;
631
632    // Phase 2 — seal `m` + publish the carrier dissolution on v1 (idempotent: a re-run
633    // re-seals fresh key material under the same root and re-publishes; members dedup).
634    if resume_phase < PHASE_CARRIER_PUBLISHED {
635        emit_migration_progress("Publishing the upgrade for all members...", 75);
636        let jm = super::v2::service::twin_join_material(&twin);
637        let m = seal_m(
638            v1.server_root_key.as_bytes(),
639            &serde_json::to_vec(&jm).map_err(|e| e.to_string())?,
640        )?;
641        let signpost = MigrationSignpost {
642            v2_community_id: v2_hex.clone(),
643            owner_xonly: owner_hex.clone(),
644            owner_salt: crate::simd::hex::bytes_to_hex_32(&twin.identity.owner_salt),
645            relays: twin.relays.clone(),
646            name: v1.name.clone(),
647            primary_channel: v1.channels.first().map(|c| c.id.to_hex()).unwrap_or_default(),
648            root_epoch: v1.server_root_epoch.0,
649        };
650        let content = build_migration_content(&signpost, Some(m))?;
651        super::service::publish_migration_carrier(transport, v1, &content).await?;
652        if !session.is_valid() {
653            return Err("account changed during carrier publish".to_string());
654        }
655        crate::db::community::set_migration_ledger(&v1_cid, &v2_hex, PHASE_CARRIER_PUBLISHED, "")?;
656    }
657
658    // Phase 3 — the owner's own local flip: re-parent channel rows + stamp the fence. The
659    // v2 community ROW already exists (create_migration_twin saved it); NO save_community_v2
660    // here — with a channel-less reloaded twin it would PRUNE the just-re-parented rows.
661    // Under the twin's follow lock: a concurrent follow-worker save from a pre-flip
662    // (channel-less) load would prune the rows this txn re-parents.
663    // Straddle the whole wizard's network I/O with the entry guard before the DB write, so
664    // a mid-wizard account swap can't land the flip + ledger row in the wrong account's DB.
665    // `twin` is intentionally not re-saved here (see the fence contract below).
666    emit_migration_progress("Switching you over...", 92);
667    {
668        // Scoped to the flip transaction alone: the follow lock must never be held across
669        // network I/O (the list republish below awaits).
670        let flock = super::v2::realtime::follow_lock(&twin.identity.community_id);
671        let _fguard = flock.lock().await;
672        if !session.is_valid() {
673            return Err("account changed during migration".to_string());
674        }
675        crate::db::community::reparent_channels_and_fence(&v1_cid, &v2_hex)?;
676        crate::db::community::set_migration_ledger(&v1_cid, &v2_hex, PHASE_FLIPPED, "")?;
677    }
678
679    // Record the twin in the cross-device community list, the same step `create_community`
680    // takes for a normal v2 community. Sibling devices usually discover the twin by folding
681    // the carrier themselves, but one that no longer holds the v1 community has no carrier to
682    // fold and the list is its only route. Runs AFTER the flip so the list never advertises a
683    // half-built twin (pre-refound it is epoch 0 with no snapshot). Best-effort.
684    // Durable like every other membership record: a twin whose list entry never lands is
685    // the same stranded-behind-a-tombstone hazard as a failed join.
686    match super::v2::service::republish_community_list(transport, Some(&twin.identity.community_id)).await {
687        Ok(true) => {}
688        _ => super::v2::service::republish_community_list_durable(Some(twin.identity.community_id)),
689    }
690    // Stamp the owner's OWN chats as v2 + notify the UI — the wizard doesn't fold its own
691    // carrier, so without this the owner's client would show the stale v1 row until a
692    // later fold/boot. Same finalize the member path uses (idempotent if a self-fold beat us).
693    spawn_finalize_migration(v1_cid, v2_hex.clone());
694    Ok(v2_hex)
695}
696
697/// Post-flip finalize: stamp the stitched chats as the v2 community (name/metadata,
698/// `proto_version` → 2 monotonic, dissolved=false — the ROOM is alive on v2 even though the
699/// v1 row is sealed) and tell the UI. Spawned (SessionGuard captured BEFORE the spawn, per
700/// the multi-account contract) so no caller's lock context can deadlock the STATE lock.
701pub fn spawn_finalize_migration(v1_cid: String, v2_hex: String) {
702    let session = SessionGuard::capture();
703    tokio::spawn(async move {
704        let v2_id = CommunityId(crate::simd::hex::hex_to_bytes_32(&v2_hex));
705        let Ok(Some(twin)) = crate::db::community::load_community_v2(&v2_id) else { return };
706        if !session.is_valid() {
707            return;
708        }
709        crate::register_v2_chats_inner(&twin, &session).await;
710        // Subscribe to the v2 twin's realtime planes — the flip re-pointed the DB but a
711        // migrating MEMBER was never live-listening on the new community, so the owner's
712        // subsequent messages wouldn't arrive (they can still SEND — that path is stateless).
713        // Idempotent for the owner (already following the twin they created). Mirrors the
714        // normal v2-join tail (enqueue_follow + refresh_subscription).
715        super::v2::realtime::enqueue_follow(&twin.identity.community_id);
716        if let Some(client) = crate::state::nostr_client() {
717            super::v2::realtime::refresh_subscription(&client).await;
718        }
719        crate::emit_event(
720            "community_migrated",
721            &serde_json::json!({ "v1_community_id": v1_cid, "v2_community_id": v2_hex }),
722        );
723    });
724}
725
726/// Boot / account-swap maintenance: (1) re-drive every held pointer whose flip hasn't
727/// landed (crash recovery, stale-root retry, unopenable-`m` retry — `drive_migration` is
728/// idempotent and its held-v2 dedup makes the "joined but never flipped" crash a pure
729/// flip on re-run); (2) probe every sealed pointer-less community for a payload the client
730/// missed (the upgrade-lag sweep). Call at boot and after an account swap.
731pub async fn run_migration_maintenance<T: Transport + ?Sized>(transport: &T) -> Vec<String> {
732    let session = SessionGuard::capture();
733    let mut flipped = Vec::new();
734    for cid in crate::db::community::migration_flip_candidates().unwrap_or_default() {
735        // The candidate list was pre-fetched: after a swap it describes the WRONG account.
736        if !session.is_valid() {
737            return flipped;
738        }
739        let Ok(Some(community)) = crate::db::community::load_community(&CommunityId(
740            crate::simd::hex::hex_to_bytes_32(&cid),
741        )) else {
742            continue;
743        };
744        match drive_migration(transport, &community).await {
745            Ok(Some(v2)) => {
746                spawn_finalize_migration(cid, v2.clone());
747                flipped.push(v2);
748            }
749            Ok(None) => {}
750            Err(e) => crate::log_warn!("migration retry for {cid}: {e}"),
751        }
752    }
753    flipped.extend(sweep_dissolved_for_migration(transport).await);
754    flipped
755}
756
757/// Boot / account-swap sweep: for every SEALED, pointer-less-checked v1 community, re-probe
758/// the rotation-stable dissolved coordinate (relays retain the event; the client kept only
759/// the `dissolved` flag). Extract + persist any migration payload and drive the flip; a
760/// plain `{}` dissolution is marked checked so it is never re-probed. This is the recovery
761/// path for a member who folded the tombstone on a build that predated migration support.
762pub async fn sweep_dissolved_for_migration<T: Transport + ?Sized>(transport: &T) -> Vec<String> {
763    let session = SessionGuard::capture();
764    let mut flipped = Vec::new();
765    let candidates = crate::db::community::migration_sweep_candidates().unwrap_or_default();
766    for cid in candidates {
767        // Pre-fetched candidates + a network probe per iteration: re-check the session both
768        // before each community and again between the probe and any write, so a mid-sweep
769        // swap can't persist pointers/checked markers into the new account's rows.
770        if !session.is_valid() {
771            return flipped;
772        }
773        let Ok(Some(community)) = crate::db::community::load_community(&CommunityId(
774            crate::simd::hex::hex_to_bytes_32(&cid),
775        )) else {
776            continue;
777        };
778        let Some(owner) = super::service::proven_owner_hex(&community) else {
779            let _ = crate::db::community::set_migration_checked(&cid);
780            continue;
781        };
782        let records = super::service::dissolved_tombstone_records(transport, &community).await;
783        if !session.is_valid() {
784            return flipped;
785        }
786        match select_pointer(&records, &owner) {
787            Some((_, raw)) => {
788                let _ = crate::db::community::set_migration_pointer(&cid, &raw);
789                // Re-load so `server_root_epoch` etc. reflect any prior catch-up.
790                if let Ok(Some(fresh)) = crate::db::community::load_community(&community.id) {
791                    if let Ok(Some(v2)) = drive_migration(transport, &fresh).await {
792                        spawn_finalize_migration(cid.clone(), v2.clone());
793                        flipped.push(v2);
794                    }
795                }
796            }
797            None => {
798                // Plain dissolution vs relay-miss vs stranger-only records. Mark checked
799                // (stop re-probing) ONLY when the OWNER's own tombstone is present but carries
800                // no payload — a genuine plain dissolution. A non-owner tombstone is
801                // member-mintable, so a partial-relay probe returning only a stranger's record
802                // must NOT converge the sweep (a real owner carrier could still be unfetched).
803                let owner_sealed = records.iter().any(|d| d.author.to_hex() == owner);
804                if owner_sealed {
805                    let _ = crate::db::community::set_migration_checked(&cid);
806                }
807            }
808        }
809    }
810    flipped
811}
812
813#[cfg(test)]
814mod tests {
815    use super::*;
816    use crate::community::{roster, CommunityId};
817    use nostr_sdk::prelude::*;
818
819    /// `v1_snapshot_members` seeds v1's authoritative memberlist: the owner and a roster
820    /// admin are seeded (the DB re-asserts them), a banned member never is. Uses the DB source
821    /// of truth so the v2 seed can't diverge from what v1 shows.
822    #[test]
823    fn snapshot_member_set_is_v1_memberlist_minus_banned() {
824        let _g = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
825        crate::db::close_database();
826        crate::db::clear_id_caches();
827        let acct = Keys::generate().public_key().to_bech32().unwrap();
828        let tmp = tempfile::tempdir().unwrap();
829        std::fs::create_dir_all(tmp.path().join(&acct)).unwrap();
830        crate::db::set_app_data_dir(tmp.path().to_path_buf());
831        crate::db::set_current_account(acct.clone()).unwrap();
832        crate::db::init_database(&acct).unwrap();
833
834        let owner = Keys::generate();
835        let admin = Keys::generate();
836        let banned = Keys::generate();
837
838        let mut c = crate::community::Community::create("HQ", "general", vec![]);
839        let cid = c.id.to_hex();
840        {
841            c.owner_attestation = Some(crate::community::owner::build_owner_attestation_unsigned(owner.public_key(), &cid)
842                .finalize(&owner).unwrap().as_json());
843        }
844        crate::db::community::save_community(&c).unwrap();
845        crate::db::community::set_community_banlist(&cid, &[banned.public_key().to_hex()], 1).unwrap();
846        use crate::community::roles::{CommunityRoles, MemberGrant, Role};
847        let role = Role::admin("aa".repeat(32));
848        crate::db::community::set_community_roles(&cid, &CommunityRoles {
849            roles: vec![role.clone()],
850            grants: vec![
851                MemberGrant { member: admin.public_key().to_hex(), role_ids: vec![role.role_id.clone()] },
852                // A banned member with a stale grant must still be excluded.
853                MemberGrant { member: banned.public_key().to_hex(), role_ids: vec![role.role_id] },
854            ],
855        }, 1).unwrap();
856
857        let members = v1_snapshot_members(&cid, &owner.public_key().to_hex());
858        let has = |k: &Keys| members.iter().any(|m| *m == k.public_key());
859        assert!(has(&owner), "owner is always seeded");
860        assert!(has(&admin), "a roster admin is seeded (re-asserted by v1's memberlist)");
861        assert!(!has(&banned), "a banned member is never seeded, even with a stale grant");
862
863        crate::db::close_database();
864    }
865
866    /// The drive-in-flight claim is exclusive: a second claim on the same cid is refused
867    /// while the first is held, released on drop so a later drive can proceed, and
868    /// per-cid independent. This claim is what serializes the wizard against the owner's
869    /// own carrier self-fold, and boot maintenance against a live fold.
870    #[test]
871    fn drive_claim_is_exclusive_and_releases_on_drop() {
872        // DRIVE_INFLIGHT is process-global: serialize against every other session/DB test.
873        let _g = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
874        clear_drive_inflight();
875        let cid = "ab".repeat(32);
876        let other = "cd".repeat(32);
877
878        let first = DriveClaim::take(&cid).expect("a free cid claims");
879        assert!(DriveClaim::take(&cid).is_none(), "a second claim on the same cid is refused");
880        let _independent = DriveClaim::take(&other).expect("a different cid claims freely");
881
882        drop(first);
883        let reclaimed = DriveClaim::take(&cid).expect("drop releases the claim for a later drive");
884        assert!(DriveClaim::take(&other).is_none(), "the other cid is still independently held");
885
886        drop(reclaimed);
887        clear_drive_inflight();
888    }
889
890    /// Drop is generation-aware. An account swap clears the set, so a stale drive still
891    /// unwinding must NOT remove the claim the NEW account's drive just inserted for the
892    /// same cid — that would let a second same-generation drive run concurrently and
893    /// re-open the channel-less-save prune race the claim exists to prevent.
894    #[test]
895    fn drive_claim_drop_is_generation_aware() {
896        // Bumps the global session generation — hold the suite guard so no concurrent test
897        // sees its own SessionGuard spuriously invalidated.
898        let _g = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
899        clear_drive_inflight();
900        let cid = "ef".repeat(32);
901
902        let stale = DriveClaim::take(&cid).expect("old account's drive claims");
903        // The swap: generation advances and the set is cleared (production `swap_session`).
904        crate::state::bump_session_generation();
905        clear_drive_inflight();
906        let fresh = DriveClaim::take(&cid).expect("the new account's drive claims the same cid");
907
908        // The old drive finally unwinds. Its Drop must decline to touch the live claim.
909        drop(stale);
910        assert!(
911            DriveClaim::take(&cid).is_none(),
912            "a stale generation's Drop must not release the current account's claim"
913        );
914
915        // The current claim still releases normally.
916        drop(fresh);
917        assert!(DriveClaim::take(&cid).is_some(), "a valid-generation Drop releases");
918        clear_drive_inflight();
919    }
920
921    /// The state ladder, priority-ordered. The load-bearing case is the SELF-SEAL WINDOW:
922    /// the owner's own carrier fold sets dissolved=1 while the ledger still says the flip is
923    /// pending. A dissolved-first ladder hides the row entirely and strands the owner in the
924    /// one state the resumable wizard was built to recover from.
925    #[test]
926    fn migration_state_ladder_is_priority_ordered() {
927        // migrated is terminal and outranks everything, including a stale ledger row.
928        assert_eq!(migration_state(true, 0, false, true, true), "migrated");
929        assert_eq!(migration_state(true, PHASE_CARRIER_PUBLISHED, true, true, true), "migrated");
930
931        // THE SELF-SEAL WINDOW: sealed v1 + pending ledger + owner ⇒ Resume, never "dissolved".
932        assert_eq!(
933            migration_state(false, PHASE_CARRIER_PUBLISHED, true, true, true),
934            "in_progress",
935            "an owner mid-migration must be offered Resume even though their carrier sealed v1"
936        );
937        assert!(
938            migration_eligible(false, PHASE_CARRIER_PUBLISHED, true, true),
939            "the sealed-but-resumable community stays eligible so the command isn't refused"
940        );
941
942        // A plain dissolution (no ledger) is terminal for the row.
943        assert_eq!(migration_state(false, 0, true, true, true), "dissolved");
944        assert!(!migration_eligible(false, 0, true, true), "a plainly dissolved community is not migratable");
945
946        // A MEMBER never sees an in-progress row: ledger rows only exist on the wizard's own
947        // account, and the is_owner bind makes that structural rather than incidental.
948        assert_eq!(migration_state(false, PHASE_TWIN_MINTED, false, false, true), "not_owner");
949        assert!(!migration_eligible(false, PHASE_TWIN_MINTED, false, false));
950
951        // Owner, clean community: the timelock decides.
952        assert_eq!(migration_state(false, 0, false, true, true), "ready");
953        assert_eq!(migration_state(false, 0, false, true, false), "locked");
954        assert!(migration_eligible(false, 0, false, true), "eligibility is the ownership+fence question, not the clock");
955    }
956
957    /// The timelock is a real gate on the wizard, not just a UI hint: the boundary second
958    /// flips it, and every earlier instant is locked.
959    #[test]
960    fn wizard_timelock_boundary() {
961        assert!(!wizard_unlocked(0));
962        assert!(!wizard_unlocked(MIGRATION_UNLOCK_AT - 1));
963        assert!(wizard_unlocked(MIGRATION_UNLOCK_AT), "unlocks exactly at the boundary");
964        assert!(wizard_unlocked(MIGRATION_UNLOCK_AT + 86_400));
965    }
966
967    fn signpost() -> MigrationSignpost {
968        MigrationSignpost {
969            v2_community_id: "aa".repeat(32),
970            owner_xonly: "bb".repeat(32),
971            owner_salt: "cc".repeat(32),
972            relays: vec!["wss://relay.example.com".into()],
973            name: "Team Rocket".into(),
974            primary_channel: "dd".repeat(32),
975            root_epoch: 3,
976        }
977    }
978
979    #[test]
980    fn payload_roundtrip() {
981        let content = build_migration_content(&signpost(), Some("bTEyMw==".into())).unwrap();
982        let p = parse_migration_payload(&content).unwrap();
983        assert_eq!(p.signpost, signpost());
984        assert_eq!(p.m.as_deref(), Some("bTEyMw=="));
985    }
986
987    #[test]
988    fn plain_dissolution_is_no_payload() {
989        assert!(parse_migration_payload("{}").is_none());
990        assert!(parse_migration_payload("").is_none());
991        assert!(parse_migration_payload("not json at all").is_none());
992    }
993
994    #[test]
995    fn bad_hex_rejected() {
996        for field in ["v2_community_id", "owner_xonly", "owner_salt", "primary_channel"] {
997            let mut sp = signpost();
998            match field {
999                "v2_community_id" => sp.v2_community_id = "zz".repeat(32),
1000                "owner_xonly" => sp.owner_xonly = "short".into(),
1001                "owner_salt" => sp.owner_salt = String::new(),
1002                _ => sp.primary_channel = "gg".repeat(32),
1003            }
1004            let content = build_migration_content(&sp, None).unwrap();
1005            assert!(parse_migration_payload(&content).is_none(), "field {field} accepted");
1006        }
1007    }
1008
1009    #[test]
1010    fn bounds_enforced() {
1011        // Oversized m → the whole payload is malformed (fail-safe: plain dissolution).
1012        let content = build_migration_content(&signpost(), Some("A".repeat(MAX_M_B64 + 1))).unwrap();
1013        assert!(parse_migration_payload(&content).is_none());
1014        // Oversized content string → None before any parse.
1015        assert!(parse_migration_payload(&"x".repeat(MAX_PAYLOAD_CONTENT + 1)).is_none());
1016        // Hostile relay list degrades by truncation, never amplifies.
1017        let mut sp = signpost();
1018        sp.relays = (0..40).map(|i| format!("wss://r{i}.example.com")).collect();
1019        sp.name = "n".repeat(500);
1020        let p = parse_migration_payload(&build_migration_content(&sp, None).unwrap()).unwrap();
1021        assert_eq!(p.signpost.relays.len(), crate::community::MAX_COMMUNITY_RELAYS);
1022        assert_eq!(p.signpost.name.chars().count(), MAX_SIGNPOST_NAME);
1023    }
1024
1025    #[test]
1026    fn m_seal_open_multi_root() {
1027        let old_root = [7u8; 32];
1028        let new_root = [8u8; 32];
1029        let sealed = seal_m(&old_root, b"join material").unwrap();
1030        // Newest-first try still finds the older archived root.
1031        let held = vec![(1u64, old_root), (2u64, new_root)];
1032        assert_eq!(open_m(&held, &sealed).unwrap(), b"join material");
1033        // No held root opens it → None (the read-cut member's experience).
1034        assert!(open_m(&[(2u64, new_root)], &sealed).is_none());
1035    }
1036
1037    #[test]
1038    fn seal_errors_past_nip44_cap() {
1039        assert!(seal_m(&[1u8; 32], &vec![0u8; 70_000]).is_err());
1040    }
1041
1042    /// v0.4.0-ACCEPTANCE PIN (the retrofit-certainty condition): an extended tombstone must
1043    /// be accepted as a PLAIN dissolution by the exact shipped code paths — signer extracted
1044    /// at the probe, collected by the fold, content untouched — with a fat payload aboard.
1045    #[test]
1046    fn v040_accepts_extended_tombstone_as_plain_dissolution() {
1047        let owner = Keys::generate();
1048        let cid = CommunityId([0x42u8; 32]);
1049        // ~10 KB of key material — a realistic large community.
1050        let m = Some(base64_simd::STANDARD.encode_to_string(vec![0xabu8; 7_500]));
1051        let content = build_migration_content(&signpost(), m).unwrap();
1052        let inner = roster::build_group_dissolved_edition_with_content(&owner, &cid, 1_753_000_000, &content).unwrap();
1053
1054        // Probe path (dissolved coordinate, id-derived envelope) — v0.4.0's cross-epoch open.
1055        let outer = roster::seal_dissolved_edition(&Keys::generate(), &inner, &cid).unwrap();
1056        let signer = roster::dissolved_tombstone_signer(&outer, &cid).expect("v0.4.0 probe must accept");
1057        assert_eq!(signer, owner.public_key());
1058
1059        // Fold path — dissolved_by (the v0.4.0 seal signal) collects the owner, and the
1060        // v0.4.1 extension carries the content verbatim.
1061        let folded = roster::fold_roster(&[inner.clone()], &cid, &std::collections::HashMap::new());
1062        assert!(folded.dissolved_by.contains(&owner.public_key()));
1063        let rec = folded.dissolved_editions.iter().find(|d| d.author == owner.public_key()).unwrap();
1064        assert_eq!(rec.content, content);
1065
1066        // And the payload-aware probe extracts the same record.
1067        let opened = roster::dissolved_tombstone_open(&outer, &cid).unwrap();
1068        assert_eq!(opened.content, content);
1069        assert_eq!(opened.author, owner.public_key());
1070    }
1071
1072    /// pin: a NEWER payload-less `{}` tombstone seals but never shadows the keys.
1073    #[test]
1074    fn payloadless_never_shadows_the_pointer() {
1075        let owner = Keys::generate();
1076        let stranger = Keys::generate();
1077        let cid = CommunityId([0x24u8; 32]);
1078        let content = build_migration_content(&signpost(), Some("bTEyMw==".into())).unwrap();
1079        let with_payload = roster::build_group_dissolved_edition_with_content(&owner, &cid, 100, &content).unwrap();
1080        let plain_newer = roster::build_group_dissolved_edition(&owner, &cid, 200).unwrap();
1081        let forged = roster::build_group_dissolved_edition_with_content(&stranger, &cid, 300, &content).unwrap();
1082
1083        let folded = roster::fold_roster(&[plain_newer, with_payload, forged], &cid, &std::collections::HashMap::new());
1084        let (p, raw) = select_pointer(&folded.dissolved_editions, &owner.public_key().to_hex()).expect("payload survives");
1085        assert_eq!(p.m.as_deref(), Some("bTEyMw=="));
1086        assert_eq!(parse_migration_payload(&raw).unwrap(), p);
1087        // A stranger's payload alone is never selected.
1088        assert!(select_pointer(&folded.dissolved_editions, &Keys::generate().public_key().to_hex()).is_none());
1089    }
1090
1091    #[test]
1092    fn newest_payload_carrier_wins_with_id_tiebreak() {
1093        let owner = Keys::generate();
1094        let cid = CommunityId([0x33u8; 32]);
1095        let mut sp_old = signpost();
1096        sp_old.name = "old".into();
1097        let mut sp_new = signpost();
1098        sp_new.name = "new".into();
1099        let a = roster::build_group_dissolved_edition_with_content(
1100            &owner, &cid, 100, &build_migration_content(&sp_old, None).unwrap()).unwrap();
1101        let b = roster::build_group_dissolved_edition_with_content(
1102            &owner, &cid, 200, &build_migration_content(&sp_new, None).unwrap()).unwrap();
1103        let folded = roster::fold_roster(&[a, b], &cid, &std::collections::HashMap::new());
1104        let (p, _) = select_pointer(&folded.dissolved_editions, &owner.public_key().to_hex()).unwrap();
1105        assert_eq!(p.signpost.name, "new");
1106    }
1107}