use std::sync::Arc;
use chia_bls::Signature;
use chia_protocol::{Bytes32, Coin, CoinSpend, SpendBundle};
use chia_wallet_sdk::driver::SpendContext;
use dig_chainsource_interface::ChainSource;
use dig_did::DidTip;
use dig_merkle::{required_signatures, Owner, RequiredSignature};
use crate::chain_confirm::{confirm_spendable_by_name, UnconfirmedInput};
use crate::edit::{gate_store_identity, resolve_store_tip, EditError};
use crate::id::ProfileIx;
use crate::keys::wallet_key::WalletKey;
use crate::mint::chain::{PushOutcome, SpendPublisher};
use crate::mint::did::MintNetwork;
use crate::registry::ProfileAnchor;
use crate::session_residency::Residency;
use dig_session::UnlockedMasterSeed;
use super::error::{MeltError, MeltResult};
use super::preview::DeletionPreview;
use super::status::MeltStatus;
pub struct ProfileMelter {
seed: Arc<UnlockedMasterSeed>,
residency: Arc<Residency>,
}
impl ProfileMelter {
pub(crate) fn new(seed: Arc<UnlockedMasterSeed>, residency: Arc<Residency>) -> Self {
Self { seed, residency }
}
pub fn melt_profile<C, P>(
&self,
ix: ProfileIx,
anchor: &ProfileAnchor,
chain: &C,
publisher: &P,
network: &MintNetwork,
) -> MeltResult<MeltStatus>
where
C: ChainSource,
P: SpendPublisher + ?Sized,
{
let wallet = self.live_wallet_key(ix)?;
let (bundle, did_coin_id, store_coin_id) =
self.build_and_sign_melt(anchor, &wallet, chain, network)?;
match publisher
.push(&bundle)
.map_err(|e| MeltError::ChainUnreachable(e.to_string()))?
{
PushOutcome::Accepted | PushOutcome::AlreadyInMempool => Ok(MeltStatus::Pushed {
did_coin_id,
store_coin_id,
}),
PushOutcome::Rejected { reason } => Err(MeltError::Rejected(reason)),
}
}
pub fn melt_status<C>(
&self,
did_coin_id: Bytes32,
store_coin_id: Bytes32,
chain: &C,
) -> MeltResult<MeltStatus>
where
C: ChainSource + ?Sized,
{
let did_spent = spent_height_of(did_coin_id, chain)?;
let store_spent = spent_height_of(store_coin_id, chain)?;
match (did_spent, store_spent) {
(Some(did_height), Some(store_height)) => Ok(MeltStatus::Confirmed {
at_height: did_height.max(store_height),
}),
_ => Ok(MeltStatus::Pushed {
did_coin_id,
store_coin_id,
}),
}
}
pub fn preview_deletion<C>(
&self,
ix: ProfileIx,
anchor: &ProfileAnchor,
chain: &C,
) -> MeltResult<DeletionPreview>
where
C: ChainSource,
{
let wallet = self.live_wallet_key(ix)?;
Ok(self.plan_melt(anchor, &wallet, chain)?.preview(anchor))
}
fn plan_melt<C>(
&self,
anchor: &ProfileAnchor,
wallet: &WalletKey,
chain: &C,
) -> MeltResult<MeltPlan>
where
C: ChainSource,
{
let did_owner = dig_did::Owner::Standard(wallet.public_key());
let store_owner = Owner::Standard(wallet.public_key());
let tip = dig_did::walk_did_lineage_to_tip(chain, anchor.launcher_id())
.map_err(|e| MeltError::ChainUnreachable(format!("DID lineage: {e}")))?
.ok_or(MeltError::NoDid)?;
pin_did_tip_to_anchor(&tip, anchor, chain)?;
let did_coin = tip.coin;
require_still_alive(did_coin, chain, MeltError::NoDid)?;
let mut ctx = SpendContext::new();
let did_melt = dig_did::melt(&mut ctx, tip.did(), did_owner)
.map_err(|e| MeltError::Build(format!("DID melt: {e}")))?;
let store = resolve_store_tip(anchor, chain).map_err(map_store_read_error)?;
gate_store_identity(wallet, anchor.store_launcher_id(), &store)
.map_err(|e| MeltError::Refused(e.to_string()))?;
let store_coin = store.coin;
require_still_alive(store_coin, chain, MeltError::NoStore)?;
let store_melt = dig_merkle::melt(&store, store_owner)
.map_err(|e| MeltError::Build(format!("store melt: {e}")))?;
let mut coin_spends = did_melt.coin_spends;
coin_spends.extend(store_melt.coin_spends);
Ok(MeltPlan {
coin_spends,
did_coin,
store_coin,
})
}
fn build_and_sign_melt<C>(
&self,
anchor: &ProfileAnchor,
wallet: &WalletKey,
chain: &C,
network: &MintNetwork,
) -> MeltResult<(SpendBundle, Bytes32, Bytes32)>
where
C: ChainSource,
{
let plan = self.plan_melt(anchor, wallet, chain)?;
let did_coin_id = plan.did_coin.coin_id();
let store_coin_id = plan.store_coin.coin_id();
let required = required_signatures(&plan.coin_spends, network.constants())
.map_err(|e| MeltError::Build(format!("required signatures: {e}")))?;
gate_profile_melt(
wallet,
did_coin_id,
store_coin_id,
&plan.coin_spends,
&required,
network,
)?;
let mut signature = Signature::default();
for requirement in &required {
let RequiredSignature::Bls(bls) = requirement else {
return Err(MeltError::Refused(
"non-BLS signature requirement in a profile deletion".into(),
));
};
signature += &chia_bls::sign(wallet.secret_key(), bls.message());
}
Ok((
SpendBundle::new(plan.coin_spends, signature),
did_coin_id,
store_coin_id,
))
}
fn live_wallet_key(&self, ix: ProfileIx) -> MeltResult<WalletKey> {
if !self.residency.is_live() {
return Err(MeltError::Locked);
}
Ok(WalletKey::from_seed_at(
self.seed.master_seed().as_ref(),
ix,
))
}
}
struct MeltPlan {
coin_spends: Vec<CoinSpend>,
did_coin: Coin,
store_coin: Coin,
}
impl MeltPlan {
fn preview(&self, anchor: &ProfileAnchor) -> DeletionPreview {
DeletionPreview::new(
anchor.did().to_owned(),
anchor.launcher_id(),
anchor.store_launcher_id(),
self.did_coin.coin_id(),
self.store_coin.coin_id(),
self.did_coin.amount + self.store_coin.amount,
)
}
}
fn require_still_alive<C>(coin: Coin, chain: &C, gone: MeltError) -> MeltResult<()>
where
C: ChainSource + ?Sized,
{
match confirm_spendable_by_name(chain, coin) {
Ok(()) => Ok(()),
Err(UnconfirmedInput::Contradicted {
spent_height: Some(_),
..
}) => Err(gone),
Err(other) => Err(MeltError::ChainUnreachable(other.to_string())),
}
}
fn pin_did_tip_to_anchor<C>(tip: &DidTip, anchor: &ProfileAnchor, chain: &C) -> MeltResult<()>
where
C: ChainSource,
{
let proof =
dig_did::prove_lineage(tip.coin.coin_id(), &tip.did(), chain).map_err(
|error| match error {
dig_did::DidError::Chain(reason) => {
MeltError::ChainUnreachable(format!("DID lineage proof: {reason}"))
}
other => MeltError::Refused(format!(
"the chain resolves this profile's DID to tip coin {}, which does not authenticate \
as a genuine state of any singleton ({other})",
tip.coin.coin_id()
)),
},
)?;
if proof.authenticated_launcher() != anchor.launcher_id() {
return Err(MeltError::Refused(format!(
"the chain resolves this profile's DID lineage to tip coin {}, which descends from \
launcher {}, but this profile's anchor names launcher {}; a deletion melts only the \
singleton the anchor names",
tip.coin.coin_id(),
proof.authenticated_launcher(),
anchor.launcher_id()
)));
}
Ok(())
}
fn map_store_read_error(error: EditError) -> MeltError {
match error {
EditError::NoStore => MeltError::NoStore,
EditError::ChainUnreachable(reason) => MeltError::ChainUnreachable(reason),
other => MeltError::Format(format!("store tip: {other}")),
}
}
fn spent_height_of<C>(coin_id: Bytes32, chain: &C) -> MeltResult<Option<u32>>
where
C: ChainSource + ?Sized,
{
let record = chain
.coin_record(coin_id)
.map_err(|e| MeltError::ChainUnreachable(e.to_string()))?
.ok_or_else(|| {
MeltError::ChainUnreachable(format!(
"the chain has no record of coin {coin_id}, which this deletion spent — its state \
is unknown, not unspent"
))
})?;
if record.coin.coin_id() != coin_id {
return Err(MeltError::ChainUnreachable(format!(
"the chain source answered a request for coin {coin_id} with a record for {}, so this \
deletion's state is unknown",
record.coin.coin_id()
)));
}
Ok(record.spent_height)
}
fn gate_profile_melt(
wallet: &WalletKey,
did_coin_id: Bytes32,
store_coin_id: Bytes32,
coin_spends: &[CoinSpend],
required: &[RequiredSignature],
network: &MintNetwork,
) -> MeltResult<()> {
if coin_spends.len() != 2 {
return Err(MeltError::Refused(format!(
"the deletion's bundle spends {} coins; deleting a profile ends exactly its two \
singletons",
coin_spends.len()
)));
}
let mut spent: Vec<Bytes32> = coin_spends.iter().map(|s| s.coin.coin_id()).collect();
spent.sort();
let mut expected = vec![did_coin_id, store_coin_id];
expected.sort();
if spent != expected {
return Err(MeltError::Refused(
"the deletion spends a coin that is not one of the two singletons this profile's \
anchor resolved to"
.into(),
));
}
for requirement in required {
let RequiredSignature::Bls(bls) = requirement else {
return Err(MeltError::Refused(
"a deletion signs only BLS AGG_SIG_ME requirements".into(),
));
};
if bls.public_key != wallet.public_key() {
return Err(MeltError::Refused(
"the deletion asks for a signature under a key this profile does not hold".into(),
));
}
if bls.domain_string != Some(network.constants().me()) {
return Err(MeltError::Refused(
"a signature that is not AGG_SIG_ME (a deletion never signs an unbound message)"
.into(),
));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use chia_protocol::{Coin, Program};
use chia_wallet_sdk::prelude::TESTNET11_CONSTANTS;
use chia_wallet_sdk::signer::{AggSigConstants, RequiredBlsSignature};
const SEED: [u8; 32] = [0x5A; 32];
const OTHER_SEED: [u8; 32] = [0xA5; 32];
fn network() -> MintNetwork {
MintNetwork::from_constants(AggSigConstants::from(&*TESTNET11_CONSTANTS))
}
fn wallet() -> WalletKey {
WalletKey::from_seed_at(&SEED, ProfileIx::ROOT)
}
fn spend_of(coin: Coin) -> CoinSpend {
CoinSpend::new(coin, Program::default(), Program::default())
}
fn did_coin() -> Coin {
Coin::new(Bytes32::new([0xD1; 32]), Bytes32::new([0x11; 32]), 1)
}
fn store_coin() -> Coin {
Coin::new(Bytes32::new([0x57; 32]), Bytes32::new([0x22; 32]), 1)
}
fn stranger_coin() -> Coin {
Coin::new(
Bytes32::new([0xEE; 32]),
Bytes32::new([0x33; 32]),
1_000_000,
)
}
fn agg_sig_me(public_key: chia_bls::PublicKey) -> RequiredSignature {
RequiredSignature::Bls(RequiredBlsSignature {
public_key,
raw_message: vec![1, 2, 3].into(),
appended_info: Vec::new(),
domain_string: Some(network().constants().me()),
})
}
#[test]
fn an_honest_two_singleton_deletion_is_admitted() {
let wallet = wallet();
let spends = vec![spend_of(did_coin()), spend_of(store_coin())];
gate_profile_melt(
&wallet,
did_coin().coin_id(),
store_coin().coin_id(),
&spends,
&[agg_sig_me(wallet.public_key())],
&network(),
)
.expect(
"a deletion of this profile's own two singletons is what this seam exists to build",
);
}
#[test]
fn the_two_halves_may_be_assembled_in_either_order() {
let wallet = wallet();
let spends = vec![spend_of(store_coin()), spend_of(did_coin())];
gate_profile_melt(
&wallet,
did_coin().coin_id(),
store_coin().coin_id(),
&spends,
&[agg_sig_me(wallet.public_key())],
&network(),
)
.expect("the gate compares a set of coin ids, not a sequence");
}
#[test]
fn a_deletion_carrying_a_third_smuggled_spend_is_refused() {
let wallet = wallet();
let spends = vec![
spend_of(did_coin()),
spend_of(store_coin()),
spend_of(stranger_coin()),
];
let error = gate_profile_melt(
&wallet,
did_coin().coin_id(),
store_coin().coin_id(),
&spends,
&[agg_sig_me(wallet.public_key())],
&network(),
)
.expect_err("a deletion ends two singletons and funds nothing");
assert!(
error.to_string().contains("spends 3 coins"),
"the refusal must name the count it saw: {error}"
);
}
#[test]
fn a_two_coin_bundle_substituting_a_stranger_coin_is_refused() {
let wallet = wallet();
let spends = vec![spend_of(did_coin()), spend_of(stranger_coin())];
let error = gate_profile_melt(
&wallet,
did_coin().coin_id(),
store_coin().coin_id(),
&spends,
&[agg_sig_me(wallet.public_key())],
&network(),
)
.expect_err("a coin the anchor never named is not part of this profile");
assert!(
error.to_string().contains("not one of the two singletons"),
"the refusal must name what was wrong: {error}"
);
}
#[test]
fn the_same_singleton_spent_twice_is_refused() {
let wallet = wallet();
let spends = vec![spend_of(did_coin()), spend_of(did_coin())];
let error = gate_profile_melt(
&wallet,
did_coin().coin_id(),
store_coin().coin_id(),
&spends,
&[agg_sig_me(wallet.public_key())],
&network(),
)
.expect_err("a bundle that melts the DID twice has not melted the store");
assert!(error.to_string().contains("not one of the two singletons"));
}
#[test]
fn a_signature_under_a_foreign_key_is_refused() {
let wallet = wallet();
let stranger = WalletKey::from_seed_at(&OTHER_SEED, ProfileIx::ROOT);
let spends = vec![spend_of(did_coin()), spend_of(store_coin())];
let error = gate_profile_melt(
&wallet,
did_coin().coin_id(),
store_coin().coin_id(),
&spends,
&[agg_sig_me(stranger.public_key())],
&network(),
)
.expect_err("this account does not authorize a stranger's spend");
assert!(error.to_string().contains("does not hold"));
}
#[test]
fn an_unbound_signature_requirement_is_refused() {
let wallet = wallet();
let spends = vec![spend_of(did_coin()), spend_of(store_coin())];
let unbound = RequiredSignature::Bls(RequiredBlsSignature {
public_key: wallet.public_key(),
raw_message: vec![1, 2, 3].into(),
appended_info: Vec::new(),
domain_string: None,
});
let error = gate_profile_melt(
&wallet,
did_coin().coin_id(),
store_coin().coin_id(),
&spends,
&[unbound],
&network(),
)
.expect_err("a deletion never signs an unbound message");
assert!(error.to_string().contains("AGG_SIG_ME"));
}
#[test]
fn a_one_coin_bundle_is_refused() {
let wallet = wallet();
let spends = vec![spend_of(did_coin())];
let error = gate_profile_melt(
&wallet,
did_coin().coin_id(),
store_coin().coin_id(),
&spends,
&[agg_sig_me(wallet.public_key())],
&network(),
)
.expect_err("a profile is two singletons");
assert!(error.to_string().contains("spends 1 coins"));
}
#[test]
fn a_pushed_deletion_proves_no_end_height() {
let status = MeltStatus::Pushed {
did_coin_id: did_coin().coin_id(),
store_coin_id: store_coin().coin_id(),
};
assert_eq!(
status.end_height(),
None,
"a push has destroyed nothing yet, so it cannot end a profile"
);
}
}