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;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ProfileMintStatus {
DidPending {
did_coin_id: Bytes32,
},
DidConfirmedStoreNotLaunched(MintedDid),
StorePending {
did: MintedDid,
store_launcher_id: Bytes32,
},
Confirmed {
did: MintedDid,
store: ConfirmedStore,
},
}
impl ProfileMinter {
#[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,
{
let seed_root = seed.root()?;
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) {
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 })
}
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)? {
pending @ ProfileMintStatus::DidPending { .. } => Ok(pending),
ProfileMintStatus::DidConfirmedStoreNotLaunched(did) => {
self.launch_store(registry, ix, &did, chain, publisher, network, reservations)
}
settled => Ok(settled),
}
}
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(),
}),
}
}
}
}
#[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(),
)
})?;
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()
)));
}
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)?;
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();
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) {
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,
})
}
}
fn rewind_to_an_unlaunched_store_on_a_definitive_no(
registry: &mut ProfileRegistry,
ix: ProfileIx,
did: &MintedDid,
error: &MintError,
) {
if matches!(error, MintError::Rejected(_)) {
let _ = registry.advance_mint(
ix,
MintStage::DidConfirmedStoreNotLaunched {
did: MintedDidRecord::from(did),
},
);
}
}
fn release_index_on_a_definitive_no(
registry: &mut ProfileRegistry,
ix: ProfileIx,
error: &MintError,
) {
if matches!(error, MintError::Rejected(_)) {
let _ = registry.abandon_mint(ix);
}
}
fn pending_mint_from(record: &PendingMintRecord) -> PendingMint {
PendingMint::new(
record.launcher_id,
record.did_coin_id,
record.source_coin_id,
record.pushed_at_height,
)
}
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,
)
}
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)))
}
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)))
}
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
))
})
}
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
}
#[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"
);
}
#[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
)
);
}
#[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
)
);
}
}