dig-account 0.26.2

The DIG Network user Account: the fat, strictly-logical crate for everything an account does — the Account+Profile object model, unlock policy + keystore crypto, the in-process identity+money signer, per-profile key/DEK derivation, DID+dig-store mint/sign, and all wallet ops. Headless (no UI). Consumed by dig-app.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
//! The PROFILE mint: the two-bundle ceremony that turns an unlocked account into an identity.
//!
//! # A DID is never minted alone
//!
//! A profile is a DID singleton **plus** a dig-store launched from that DID's coin **plus** a seeded
//! SMT, bound together as one [`ProfileAnchor`](crate::ProfileAnchor). Those are two bundles and two
//! confirmations, with a real minutes-wide window between them **in which the DID is already paid
//! for**. Every function here exists to make that window survivable.
//!
//! # Three calls, and why not one
//!
//! - [`begin_profile_mint`](ProfileMinter::begin_profile_mint) journals the reservation, then
//!   builds, signs and pushes the DID bundle.
//! - [`advance_profile_mint`](ProfileMinter::advance_profile_mint) drives the ceremony from whatever
//!   the chain NOW says. A host calls it on a timer.
//! - [`profile_mint_status`](ProfileMinter::profile_mint_status) reports where it stands, and does
//!   nothing else: no spend, no push, no journal write.
//!
//! A single blocking call that returned a finished profile would have to either block for minutes or
//! invent a confirmation, and inventing one is the specific lie [`ProfileAnchor`] exists to make
//! unrepresentable.
//!
//! # Every transition is driven by a chain READ
//!
//! A push being accepted is one node's opinion, so no stage advances on one. `advance_profile_mint`
//! reads the chain FIRST and pushes only where the evidence says the previous half is done and the
//! next has not been pushed — which is what makes calling it on a timer safe. Each half is pushed
//! **at most once**, because its journal entry moves to the pushed stage BEFORE the bundle is
//! broadcast: a lost answer leaves a stage that re-reads chain, never one that re-spends.
//!
//! # The minter does NOT record the profile
//!
//! [`ProfileMintStatus::Confirmed`] carries both evidence halves, and the HOST calls
//! [`ProfileRegistry::record_minted`] with them. That is a deliberate split: the minter owns the
//! JOURNAL, the host owns the ENTRIES — it picks the label and decides whether to activate. Since
//! `record_minted` clears the journal entry, the handoff is what closes the cycle. A minter that
//! recorded internally *and* returned the evidence would make a host following the obvious path fail
//! with `ProfileAlreadyRegistered` on its own success value.
//!
//! [`ProfileAnchor`]: crate::ProfileAnchor
//! [`ProfileRegistry::record_minted`]: crate::ProfileRegistry::record_minted

use chia_protocol::Bytes32;
use dig_chainsource_interface::{ChainSource, CoinRecord};

use crate::id::ProfileIx;
use crate::mint::chain::SpendPublisher;
use crate::mint::did::{peak_height, push, select_funding_coin, MintNetwork, MintOptions};
use crate::mint::error::{MintError, MintResult};
use crate::mint::evidence::{MintedDid, PendingMint};
use crate::mint::seed::ProfileSeed;
use crate::mint::store_evidence::{ConfirmedStore, PendingStoreLaunch};
use crate::mint::store_launch::build_and_sign_store_launch;
use crate::profile_mint::ProfileMinter;
use crate::registry::journal::{
    MintStage, MintedDidRecord, PendingMintRecord, PendingStoreLaunchRecord,
};
use crate::registry::ProfileRegistry;
use crate::wallet::reservation::{select_and_reserve, CoinReservations};
use crate::wallet::transfer::MAX_RESERVATION_ATTEMPTS;

/// Where a profile mint stands. Every variant names exactly what has been PROVEN on chain.
///
/// Non-exhaustive: the ceremony may grow a stage, and a host must not be broken by one.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ProfileMintStatus {
    /// The DID bundle is in flight. **Nothing is proven** — a push is an acceptance by one node.
    DidPending {
        /// The coin whose confirmation will be the DID's evidence.
        did_coin_id: Bytes32,
    },

    /// Funds committed, an identity EXISTS, and there is NO profile.
    ///
    /// **This is the state that costs money to get wrong.** Resume from here by launching the store
    /// from the existing DID coin; **never** by re-minting the DID, which spends again and orphans
    /// the identity the user already owns (dig_ecosystem#2377).
    DidConfirmedStoreNotLaunched(MintedDid),

    /// The store bundle has been broadcast against a confirmed DID and no block carries it yet.
    ///
    /// "Broadcast", not "in flight": a node's acceptance is one node's opinion, and this is also the
    /// state after a push whose answer never arrived. It is NOT the state after a REJECTED push —
    /// that rewinds to [`DidConfirmedStoreNotLaunched`](Self::DidConfirmedStoreNotLaunched), so this
    /// variant never names a bundle the network has refused.
    StorePending {
        /// The DID that already exists.
        did: MintedDid,
        /// The store singleton's launcher id, once it confirms.
        store_launcher_id: Bytes32,
    },

    /// Both halves are confirmed on chain.
    ///
    /// The host completes the mint by passing both to
    /// [`ProfileRegistry::record_minted`](crate::ProfileRegistry::record_minted), which CONSUMES a
    /// [`ConfirmedStore`]. There is no public producer of one at all: this variant is the only place
    /// a host can obtain store evidence, and it is reached only from a chain read. A host cannot
    /// fabricate the value, and cannot record a profile without it.
    Confirmed {
        /// The DID half.
        did: MintedDid,
        /// The store half, launched from that DID's coin.
        store: ConfirmedStore,
    },
}

impl ProfileMinter {
    /// Start a profile mint at `ix`: reserve the index, then push the DID bundle.
    ///
    /// The returned status is always [`ProfileMintStatus::DidPending`] — a pushed bundle is not a
    /// DID. Drive it to completion by calling
    /// [`advance_profile_mint`](Self::advance_profile_mint) until it reports
    /// [`Confirmed`](ProfileMintStatus::Confirmed).
    ///
    /// # Ordering
    ///
    /// The journal entry is written BEFORE the push, so a lost answer leaves a resumable mint rather
    /// than a DID nothing names. A DEFINITIVE rejection — the network answered "no" — releases the
    /// index again; an unreachable chain does not, because then the outcome is unknown and the
    /// bundle may yet be included.
    ///
    /// # Errors
    ///
    /// [`MintError::Journal`] if the registry refuses the reservation (`ix` is already a profile, or
    /// already has a mint in progress). Everything else is [`begin_did_mint`](Self::begin_did_mint)'s
    /// taxonomy: [`InsufficientFunds`](MintError::InsufficientFunds),
    /// [`Rejected`](MintError::Rejected), [`ChainUnreachable`](MintError::ChainUnreachable),
    /// [`Locked`](MintError::Locked), [`Refused`](MintError::Refused).
    ///
    /// # Money
    ///
    /// On [`MintNetwork::mainnet`] this spends real XCH, and `options.fee` is disclosed PER BUNDLE:
    /// the same figure is journalled as the store half's ceiling, so a resumed phase B can never
    /// quietly spend more than the user was shown.
    //
    // Eight arguments, and every one of them is a distinct authority this call needs: the journal to
    // reserve, the index, the content, the chain to read, the network to push to, the signing domain,
    // and the fee. Bundling them into a config struct would hide the two that MOVE MONEY (`publisher`
    // and `options.fee`) among the five that do not, which is exactly the wrong thing to make less
    // visible at a call site.
    #[allow(
        clippy::too_many_arguments,
        reason = "each argument is a distinct authority"
    )]
    pub fn begin_profile_mint<'r, C, P>(
        &self,
        registry: &mut ProfileRegistry,
        ix: ProfileIx,
        seed: &ProfileSeed,
        chain: &C,
        publisher: &P,
        network: &MintNetwork,
        options: &MintOptions,
        reservations: &'r CoinReservations<'r>,
    ) -> MintResult<ProfileMintStatus>
    where
        C: ChainSource,
        P: SpendPublisher + ?Sized,
    {
        // Computed before anything is built, so a seed that cannot be committed costs nothing.
        let seed_root = seed.root()?;
        // The coin guard is carried, never discarded. A profile mint is a two-phase ceremony and
        // phase B re-selects its own funding coin, so the caller has no use for the handle after
        // this call returns — but between here and the push there is a journal write that can fail,
        // and dropping the guard there is exactly what must happen. Letting the TTL cover that case
        // instead would strand the coin over a mint that was never journalled and never pushed, and
        // a caller retrying would strand a different one each time.
        let (bundle, pending, held) =
            self.prepare_did_mint(ix, chain, network, options, reservations)?;
        let did_coin_id = pending.did_coin_id();

        registry
            .begin_seeded_mint(
                ix,
                MintStage::DidPushed {
                    pending: PendingMintRecord::from(&pending),
                },
                seed_root,
                options.fee,
            )
            .map_err(|e| MintError::Journal(e.to_string()))?;

        if let Err(error) = push(publisher, &bundle) {
            // The coins follow the SAME rule as the HD index beside them, and for the same reason: a
            // definitive no means the bundle is dead and the hold guards nothing, while any other
            // error leaves the outcome unknown and the hold must stand until the TTL rather than let
            // a second bundle spend an input the first may already have consumed.
            release_index_on_a_definitive_no(registry, ix, &error);
            if !matches!(error, MintError::Rejected(_)) {
                let _ = held.commit();
            }
            return Err(error);
        }

        let _ = held.commit();
        Ok(ProfileMintStatus::DidPending { did_coin_id })
    }

    /// Drive the mint at `ix` forward from whatever the chain now says.
    ///
    /// Safe to call on a timer: it reads chain FIRST and pushes only on evidence, so repeated calls
    /// against a chain that has not moved push nothing at all.
    ///
    /// # Errors
    ///
    /// [`MintError::Journal`] if no mint is journalled at `ix`, or the entry is a DID-only mint with
    /// no profile seed (see [`ProfileMintInProgress::seed_root`](crate::registry::ProfileMintInProgress::seed_root)).
    /// [`MintError::ChainUnreachable`] leaves the mint exactly where it was — the outcome is unknown,
    /// never a failure to restart from.
    pub fn advance_profile_mint<'r, C, P>(
        &self,
        registry: &mut ProfileRegistry,
        ix: ProfileIx,
        chain: &C,
        publisher: &P,
        network: &MintNetwork,
        reservations: &'r CoinReservations<'r>,
    ) -> MintResult<ProfileMintStatus>
    where
        C: ChainSource,
        P: SpendPublisher + ?Sized,
    {
        match self.profile_mint_status(registry, ix, chain)? {
            // Nothing is proven yet: the DID bundle is still in flight, so there is nothing to do
            // but wait. Deliberately NOT a push.
            pending @ ProfileMintStatus::DidPending { .. } => Ok(pending),

            // The DID exists and the store does not. This is the ONE transition that spends.
            ProfileMintStatus::DidConfirmedStoreNotLaunched(did) => {
                self.launch_store(registry, ix, &did, chain, publisher, network, reservations)
            }

            settled => Ok(settled),
        }
    }

    /// Report where the mint at `ix` stands, WITHOUT spending, pushing, or writing the journal.
    ///
    /// This is the read a UI renders on every frame. It is deliberately `&self` over a `&`-registry:
    /// there is no argument that makes it move money.
    ///
    /// A [`DidConfirmedStoreNotLaunched`](ProfileMintStatus::DidConfirmedStoreNotLaunched) here means
    /// the chain has confirmed the DID and this host has not yet launched the store — the state
    /// [`advance_profile_mint`](Self::advance_profile_mint) resolves.
    ///
    /// # Errors
    ///
    /// [`MintError::Journal`] if no mint is journalled at `ix`, and
    /// [`MintError::ChainUnreachable`] when the chain could not answer. An unreadable chain is never
    /// reported as an absence of progress.
    pub fn profile_mint_status<C>(
        &self,
        registry: &ProfileRegistry,
        ix: ProfileIx,
        chain: &C,
    ) -> MintResult<ProfileMintStatus>
    where
        C: ChainSource,
    {
        let mint = registry
            .in_progress()
            .iter()
            .find(|mint| mint.ix() == ix)
            .ok_or_else(|| MintError::Journal(format!("no mint is journalled at profile {ix}")))?;

        let peak = peak_height(chain)?;

        match mint.stage() {
            MintStage::DidPushed { pending } => {
                let pending = pending_mint_from(pending);
                match confirmed_did(chain, &pending, peak)? {
                    Some(did) => Ok(ProfileMintStatus::DidConfirmedStoreNotLaunched(did)),
                    None => Ok(ProfileMintStatus::DidPending {
                        did_coin_id: pending.did_coin_id(),
                    }),
                }
            }

            MintStage::DidConfirmedStoreNotLaunched { did } => Ok(
                ProfileMintStatus::DidConfirmedStoreNotLaunched(reverified_did(chain, did, peak)?),
            ),

            MintStage::StorePushed { did, pending_store } => {
                let did = reverified_did(chain, did, peak)?;
                let pending = pending_store_from(pending_store);
                match confirmed_store(chain, &pending, peak)? {
                    Some(store) => Ok(ProfileMintStatus::Confirmed { did, store }),
                    None => Ok(ProfileMintStatus::StorePending {
                        did,
                        store_launcher_id: pending.launcher_id(),
                    }),
                }
            }
        }
    }

    /// Build, journal, sign and push the store half against an ALREADY CONFIRMED DID.
    ///
    /// The DID's PUZZLE MATERIAL is re-derived from chain by walking its singleton lineage to the
    /// tip — never read from the journal, which holds none and could not vouch for it if it did.
    /// Its IDENTITY is the opposite: the tip must be the exact coin id this mint recorded, or the
    /// launch is refused. Chain answers what the coin looks like; the journal decides which coin.
    // Seven authorities plus the reservation set. Bundling them into a config struct would hide
    // `publisher` and the journalled fee - the two that MOVE MONEY - among the ones that do not,
    // which is the wrong thing to make less visible at a call site.
    #[allow(
        clippy::too_many_arguments,
        reason = "each argument is a distinct authority"
    )]
    fn launch_store<'r, C, P>(
        &self,
        registry: &mut ProfileRegistry,
        ix: ProfileIx,
        did: &MintedDid,
        chain: &C,
        publisher: &P,
        network: &MintNetwork,
        reservations: &'r CoinReservations<'r>,
    ) -> MintResult<ProfileMintStatus>
    where
        C: ChainSource,
        P: SpendPublisher + ?Sized,
    {
        let mint = registry
            .in_progress()
            .iter()
            .find(|mint| mint.ix() == ix)
            .ok_or_else(|| MintError::Journal(format!("no mint is journalled at profile {ix}")))?;
        let seed_root = mint.seed_root().ok_or_else(|| {
            MintError::Journal(format!(
                "the mint journalled at profile {ix} carries no profile seed, so it is a DID-only \
                 mint rather than a profile mint; its store half cannot be resumed without \
                 committing to bytes the user never chose"
            ))
        })?;
        let fee = mint.store_fee();

        let wallet = self.live_wallet_key(ix)?;
        let tip = dig_did::walk_did_lineage_to_tip(chain, did.launcher_id())
            .map_err(|e| MintError::ChainUnreachable(format!("DID lineage: {e}")))?
            .ok_or_else(|| {
                MintError::ChainUnreachable(
                    "the chain no longer resolves this DID's singleton lineage".into(),
                )
            })?;

        // The walk verifies that the coins the SOURCE returned are internally consistent; it does
        // not verify that they are THIS profile's. So the tip is pinned to the coin id this mint
        // recorded — a value computed from the bundle this crate built, never learned from a chain
        // source. Without this, a source that answered with someone else's DID would have its
        // lineage silently adopted, and the launch's own gate would compare that lineage to itself.
        //
        // It also catches the honest case with no attacker at all: a DID singleton spent between
        // confirmation and this call has a different tip coin, and launching from it would produce
        // a store whose evidence can never match the DID half (dig_ecosystem#2377).
        if tip.coin.coin_id() != did.coin_id() {
            return Err(MintError::Refused(format!(
                "the chain resolves this DID's lineage to tip coin {}, but this mint recorded its \
                 DID coin as {}; the store is launched only from the coin the mint itself named",
                tip.coin.coin_id(),
                did.coin_id()
            )));
        }

        // Held, not discarded. Four fallible steps follow, one of them a peak READ answered by a
        // peer this crate does not trust; discarding the guard here strands the launch funding coin
        // for the full TTL every time one of them fails, on a different coin each retry.
        let (funding, held) = select_and_reserve(
            reservations,
            MAX_RESERVATION_ATTEMPTS,
            |excluded| {
                let coin = select_funding_coin(
                    chain,
                    wallet.puzzle_hash(),
                    &MintOptions::with_fee(fee),
                    excluded,
                )?;
                Ok((coin, vec![coin.coin_id()]))
            },
            |e| MintError::ReservationUnusable(e.to_string()),
        )?;
        let pushed_at_height = peak_height(chain)?;

        // As on the DID half: the lineage walk and the coin selection above are network round
        // trips, so the unlock is re-read immediately before the store launch is signed
        // (dig-account#31).
        self.ensure_live()?;
        let launch = build_and_sign_store_launch(
            &wallet,
            tip.did(),
            did.coin_id(),
            funding,
            seed_root,
            did.did(),
            fee,
            pushed_at_height,
            network,
        )?;
        let store_launcher_id = launch.pending.launcher_id();

        // Journalled BEFORE the push, so a lost answer can never become a second launch.
        registry
            .advance_mint(
                ix,
                MintStage::StorePushed {
                    did: MintedDidRecord::from(did),
                    pending_store: PendingStoreLaunchRecord::from(&launch.pending),
                },
            )
            .map_err(|e| MintError::Journal(e.to_string()))?;

        if let Err(error) = push(publisher, &launch.bundle) {
            // Same rule as the stage rewind beside it: a definitive no means the bundle is dead and
            // the coins guard nothing, so the guard drops and releases; any other error leaves the
            // outcome unknown, so the hold stands until the TTL rather than let a second launch
            // spend an input the first may already have consumed.
            rewind_to_an_unlaunched_store_on_a_definitive_no(registry, ix, did, &error);
            if !matches!(error, MintError::Rejected(_)) {
                let _ = held.commit();
            }
            return Err(error);
        }

        let _ = held.commit();
        Ok(ProfileMintStatus::StorePending {
            did: did.clone(),
            store_launcher_id,
        })
    }
}

/// Put the mint at `ix` back to "the DID exists, the store does not" when the network answered a
/// definitive NO to the store launch.
///
/// The store half is journalled as `StorePushed` BEFORE it is broadcast, so a LOST answer leaves a
/// stage that re-reads chain rather than one that re-spends. A rejection is the other case entirely:
/// the bundle reached a node and was refused, so it sits in no mempool and no block will ever carry
/// it. Left at `StorePushed`, every later advance would report `StorePending` — "in flight" — for a
/// bundle nothing is carrying, and would push nothing, forever, stranding a DID the user has already
/// paid for.
///
/// This is the phase-B twin of [`release_index_on_a_definitive_no`], and it stops SHORT of that
/// function's remedy on purpose: the index is NOT released, because unlike a rejected DID mint there
/// IS an identity on chain here. `DidConfirmedStoreNotLaunched` is precisely that state, so the next
/// advance rebuilds and retries the launch.
///
/// An UNREACHABLE chain is excluded for the same reason it is excluded there, and the stakes are
/// higher: the launch may yet be included, and rewinding would let the next advance broadcast a
/// SECOND launch — the double-spend the pre-push journalling exists to prevent.
fn rewind_to_an_unlaunched_store_on_a_definitive_no(
    registry: &mut ProfileRegistry,
    ix: ProfileIx,
    did: &MintedDid,
    error: &MintError,
) {
    if matches!(error, MintError::Rejected(_)) {
        // This same call journalled the entry moments ago, so it exists; if it somehow did not,
        // there is no stage to rewind.
        let _ = registry.advance_mint(
            ix,
            MintStage::DidConfirmedStoreNotLaunched {
                did: MintedDidRecord::from(did),
            },
        );
    }
}

/// Forget the reservation at `ix` when the network answered a definitive NO.
///
/// A rejection means the bundle is not in any mempool, so holding the index would strand it forever.
/// An UNREACHABLE chain is deliberately excluded: the outcome is unknown there, the bundle may yet
/// be included, and releasing the index would invite a second DID mint for the same profile.
fn release_index_on_a_definitive_no(
    registry: &mut ProfileRegistry,
    ix: ProfileIx,
    error: &MintError,
) {
    if matches!(error, MintError::Rejected(_)) {
        // The reservation was inserted moments ago on this same path; nothing else can have removed
        // it, and if it somehow had, there is nothing to release.
        let _ = registry.abandon_mint(ix);
    }
}

/// Rebuild what a journalled DID mint told this host to LOOK FOR.
///
/// A [`PendingMint`] is not evidence and this is not the forbidden record-to-evidence conversion
/// (`registry::journal`): it names a coin id, and only a fresh chain read of that coin can produce a
/// [`MintedDid`].
fn pending_mint_from(record: &PendingMintRecord) -> PendingMint {
    PendingMint::new(
        record.launcher_id,
        record.did_coin_id,
        record.source_coin_id,
        record.pushed_at_height,
    )
}

/// The same, for a journalled store launch.
fn pending_store_from(record: &PendingStoreLaunchRecord) -> PendingStoreLaunch {
    PendingStoreLaunch::new(
        record.launcher_id,
        record.store_coin_id,
        record.did_coin_id,
        record.committed_root,
        record.pushed_at_height,
    )
}

/// Look up `pending`'s DID coin and turn a sufficiently-buried confirmation into evidence.
fn confirmed_did<C>(chain: &C, pending: &PendingMint, peak: u32) -> MintResult<Option<MintedDid>>
where
    C: ChainSource,
{
    Ok(coin_record(chain, pending.did_coin_id())?
        .and_then(|record| MintedDid::from_confirmed(pending, &record, peak)))
}

/// Look up `pending`'s store coin and turn a sufficiently-buried confirmation into evidence.
fn confirmed_store<C>(
    chain: &C,
    pending: &PendingStoreLaunch,
    peak: u32,
) -> MintResult<Option<ConfirmedStore>>
where
    C: ChainSource,
{
    Ok(coin_record(chain, pending.store_coin_id())?
        .and_then(|record| ConfirmedStore::from_confirmed(pending, &record, peak)))
}

/// Re-prove a journalled DID against a FRESH chain read.
///
/// A DID the chain no longer shows — reorged away, or now too shallow — must not be spent from just
/// because a file remembers it, so this fails rather than trusting the record.
fn reverified_did<C>(chain: &C, record: &MintedDidRecord, peak: u32) -> MintResult<MintedDid>
where
    C: ChainSource,
{
    coin_record(chain, record.coin_id)?
        .and_then(|coin| {
            MintedDid::reverified(
                record.launcher_id,
                record.coin_id,
                record.confirmed_height,
                &coin,
                peak,
            )
        })
        .ok_or_else(|| {
            MintError::ChainUnreachable(format!(
                "the chain no longer confirms the DID coin {} this mint recorded",
                record.coin_id
            ))
        })
}

/// Read one coin record, turning a source failure into "unknown" rather than "absent".
fn coin_record<C>(chain: &C, coin_id: Bytes32) -> MintResult<Option<CoinRecord>>
where
    C: ChainSource,
{
    chain
        .coin_record(coin_id)
        .map_err(|e| MintError::ChainUnreachable(e.to_string()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::registry::journal::PendingMintRecord;

    fn a_did_only_journal() -> ProfileRegistry {
        let mut registry = ProfileRegistry::empty();
        registry
            .begin_mint(
                ProfileIx::ROOT,
                MintStage::DidPushed {
                    pending: PendingMintRecord {
                        launcher_id: Bytes32::new([1; 32]),
                        did_coin_id: Bytes32::new([2; 32]),
                        source_coin_id: Bytes32::new([3; 32]),
                        pushed_at_height: 100,
                    },
                },
                0,
            )
            .expect("a fresh registry accepts a reservation");
        registry
    }

    /// **A definitive rejection releases the index; an unknown outcome does NOT.**
    ///
    /// The asymmetry is the whole point, so both directions are asserted from one fixture: a shared
    /// helper that released on every error would satisfy either assertion alone.
    #[test]
    fn only_a_definitive_rejection_releases_the_reserved_index() {
        let mut registry = a_did_only_journal();
        release_index_on_a_definitive_no(
            &mut registry,
            ProfileIx::ROOT,
            &MintError::ChainUnreachable("timeout".into()),
        );
        assert_eq!(
            registry.in_progress().len(),
            1,
            "an unknown outcome keeps the index reserved: the DID may exist and be paid for"
        );

        release_index_on_a_definitive_no(
            &mut registry,
            ProfileIx::ROOT,
            &MintError::Rejected("DOUBLE_SPEND".into()),
        );
        assert!(
            registry.in_progress().is_empty(),
            "a bundle the network refused holds no index"
        );
    }

    /// A `PendingMintRecord` rebuilds the coin ids to LOOK FOR, field for field. A transposition
    /// here would send the resume path hunting the wrong coin and report the mint as never
    /// confirming — each fixture field carries its own byte pattern so that is visible.
    #[test]
    fn a_journalled_pending_mint_rebuilds_field_for_field() {
        let record = PendingMintRecord {
            launcher_id: Bytes32::new([1; 32]),
            did_coin_id: Bytes32::new([2; 32]),
            source_coin_id: Bytes32::new([3; 32]),
            pushed_at_height: 100,
        };
        let pending = pending_mint_from(&record);
        assert_eq!(
            (
                pending.launcher_id(),
                pending.did_coin_id(),
                pending.source_coin_id(),
                pending.pushed_at_height()
            ),
            (
                record.launcher_id,
                record.did_coin_id,
                record.source_coin_id,
                record.pushed_at_height
            )
        );
    }

    /// The same, for a journalled store launch.
    #[test]
    fn a_journalled_store_launch_rebuilds_field_for_field() {
        let record = PendingStoreLaunchRecord {
            launcher_id: Bytes32::new([4; 32]),
            store_coin_id: Bytes32::new([5; 32]),
            did_coin_id: Bytes32::new([6; 32]),
            committed_root: [7; 32],
            pushed_at_height: 88,
        };
        let pending = pending_store_from(&record);
        assert_eq!(
            (
                pending.launcher_id(),
                pending.store_coin_id(),
                pending.did_coin_id(),
                pending.committed_root(),
                pending.pushed_at_height()
            ),
            (
                record.launcher_id,
                record.store_coin_id,
                record.did_coin_id,
                record.committed_root,
                record.pushed_at_height
            )
        );
    }
}