use std::collections::HashSet;
use chia_protocol::{Bytes32, Coin, CoinSpend, SpendBundle};
use chia_wallet_sdk::driver::{IntermediateLauncher, SpendContext, StandardLayer};
use chia_wallet_sdk::prelude::Conditions;
use chia_wallet_sdk::signer::RequiredSignature;
use dig_did::{Did, Owner};
use dig_merkle::{mint_datastore_launch_with_kind, StoreKind};
use crate::keys::wallet_key::WalletKey;
use crate::mint::did::MintNetwork;
use crate::mint::error::{MintError, MintResult};
use crate::mint::store_evidence::PendingStoreLaunch;
const LAUNCHER_AMOUNT: u64 = 1;
const INTERMEDIATE_AMOUNT: u64 = 0;
const INTERMEDIATE_MINT_NUMBER: usize = 0;
const INTERMEDIATE_MINT_TOTAL: usize = 1;
pub(super) struct StoreLaunchBundle {
pub(super) bundle: SpendBundle,
pub(super) pending: PendingStoreLaunch,
}
fn store_metadata(did_string: &str) -> (Option<String>, Option<String>) {
(
Some("DIG profile".to_string()),
Some(format!("The DIG profile store for {did_string}")),
)
}
#[allow(
clippy::too_many_arguments,
reason = "building and signing must not be split apart"
)]
pub(super) fn build_and_sign_store_launch(
wallet: &WalletKey,
did: Did,
did_coin_id: Bytes32,
funding: Coin,
seed_root: [u8; 32],
did_string: &str,
fee: u64,
pushed_at_height: u32,
network: &MintNetwork,
) -> MintResult<StoreLaunchBundle> {
if did.coin.coin_id() != did_coin_id {
return Err(MintError::Refused(format!(
"the DID coin to spend is {}, but this mint recorded {}; a launch is built only \
against the coin the mint itself named",
did.coin.coin_id(),
did_coin_id
)));
}
let mut ctx = SpendContext::new();
let owner_puzzle_hash = wallet.puzzle_hash();
let intermediate = IntermediateLauncher::new(
did_coin_id,
INTERMEDIATE_MINT_NUMBER,
INTERMEDIATE_MINT_TOTAL,
);
let intermediate_coin = intermediate.intermediate_coin();
let launcher = intermediate
.create(&mut ctx)
.map_err(|e| MintError::Build(format!("intermediate launcher: {e}")))?;
let (label, description) = store_metadata(did_string);
let launch = mint_datastore_launch_with_kind(
&mut ctx,
StoreKind::DidProfile,
launcher,
Bytes32::new(seed_root),
label,
description,
None,
None,
None,
owner_puzzle_hash,
Vec::new(),
)
.map_err(|e| MintError::Build(format!("store launch: {e}")))?;
let store_coin = launch.datastore.coin;
let store_launcher_id = launch.datastore.info.launcher_id;
let _successor = dig_did::spend_did_with_conditions(
&mut ctx,
did,
Owner::Standard(wallet.public_key()),
launch.parent_conditions,
)
.map_err(|e| MintError::Build(format!("DID spend: {e}")))?;
spend_funding_coin(&mut ctx, wallet, funding, fee)?;
let coin_spends = ctx.take();
if intermediate_coin.amount != INTERMEDIATE_AMOUNT {
return Err(MintError::Build(
"the intermediate coin is not the even amount that makes this launch legal".into(),
));
}
let launcher_spend = coin_spends
.iter()
.find(|spend| spend.coin.coin_id() == store_launcher_id)
.ok_or_else(|| MintError::Build("the launch spends no launcher coin".into()))?;
if launcher_spend.coin.parent_coin_info != intermediate_coin.coin_id() {
return Err(MintError::Build(
"the launcher is not parented on the even-amount intermediate coin".into(),
));
}
let required = dig_merkle::required_signatures(&coin_spends, network.constants())
.map_err(|e| MintError::Build(format!("required signatures: {e}")))?;
gate_store_launch(wallet, &coin_spends, &required, did_coin_id, network)?;
let mut signature = chia_bls::Signature::default();
for requirement in &required {
let RequiredSignature::Bls(bls) = requirement else {
return Err(MintError::Refused(
"non-BLS signature requirement in a store launch".into(),
));
};
signature += &chia_bls::sign(wallet.secret_key(), bls.message());
}
Ok(StoreLaunchBundle {
bundle: SpendBundle::new(coin_spends, signature),
pending: PendingStoreLaunch::new(
store_launcher_id,
store_coin.coin_id(),
did_coin_id,
seed_root,
pushed_at_height,
),
})
}
fn spend_funding_coin(
ctx: &mut SpendContext,
wallet: &WalletKey,
funding: Coin,
fee: u64,
) -> MintResult<()> {
let puzzle_hash = wallet.puzzle_hash();
let memos = ctx
.hint(puzzle_hash)
.map_err(|e| MintError::Build(format!("hint: {e}")))?;
let change = funding
.amount
.checked_sub(LAUNCHER_AMOUNT)
.and_then(|left| left.checked_sub(fee))
.ok_or(MintError::InsufficientFunds {
required: LAUNCHER_AMOUNT.saturating_add(fee),
available: funding.amount,
})?;
let mut conditions = Conditions::new();
if change > 0 {
conditions = conditions.create_coin(puzzle_hash, change, memos);
}
if fee > 0 {
conditions = conditions.reserve_fee(fee);
}
StandardLayer::new(wallet.public_key())
.spend(ctx, funding, conditions)
.map_err(|e| MintError::Build(format!("funding spend: {e}")))
}
fn gate_store_launch(
wallet: &WalletKey,
coin_spends: &[CoinSpend],
required: &[RequiredSignature],
did_coin_id: Bytes32,
network: &MintNetwork,
) -> MintResult<()> {
for requirement in required {
match requirement {
RequiredSignature::Bls(bls) => {
if bls.public_key != wallet.public_key() {
return Err(MintError::Refused(
"a signature under a key that is not this profile's wallet key".into(),
));
}
if bls.domain_string != Some(network.constants().me()) {
return Err(MintError::Refused(
"a signature that is not AGG_SIG_ME (a launch never signs an unbound \
message)"
.into(),
));
}
}
RequiredSignature::Secp(_) => {
return Err(MintError::Refused(
"a secp signature requirement, which a store launch never produces".into(),
))
}
}
}
let spent: HashSet<Bytes32> = coin_spends
.iter()
.map(|spend| spend.coin.coin_id())
.collect();
let roots: Vec<&CoinSpend> = coin_spends
.iter()
.filter(|spend| !spent.contains(&spend.coin.parent_coin_info))
.collect();
let [first, second] = roots.as_slice() else {
return Err(MintError::Refused(format!(
"the bundle spends {} pre-existing coins; a store launch spends exactly two",
roots.len()
)));
};
let (did_spend, wallet_spend) = if first.coin.coin_id() == did_coin_id {
(first, second)
} else if second.coin.coin_id() == did_coin_id {
(second, first)
} else {
return Err(MintError::Refused(
"the bundle does not spend this profile's DID coin".into(),
));
};
if wallet_spend.coin.puzzle_hash != wallet.puzzle_hash() {
return Err(MintError::Refused(
"the bundle's funding coin is not this wallet's".into(),
));
}
let _ = did_spend;
Ok(())
}
#[cfg(test)]
pub(super) fn intermediate_coin_for(did_coin_id: Bytes32) -> Coin {
IntermediateLauncher::new(
did_coin_id,
INTERMEDIATE_MINT_NUMBER,
INTERMEDIATE_MINT_TOTAL,
)
.intermediate_coin()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_intermediate_amount_is_even() {
assert_eq!(INTERMEDIATE_AMOUNT % 2, 0);
assert_eq!(
intermediate_coin_for(Bytes32::new([9; 32])).amount,
INTERMEDIATE_AMOUNT
);
}
#[test]
fn the_launcher_amount_is_odd() {
assert_eq!(LAUNCHER_AMOUNT % 2, 1);
}
#[test]
fn the_store_description_names_the_did() {
let (label, description) = store_metadata("did:chia:1abc");
assert_eq!(label.as_deref(), Some("DIG profile"));
assert!(description.unwrap().contains("did:chia:1abc"));
}
}
#[cfg(test)]
mod gate_tests {
use super::*;
use crate::id::ProfileIx;
use chia_sdk_test::Simulator;
use chia_wallet_sdk::driver::Launcher;
use chia_wallet_sdk::prelude::TESTNET11_CONSTANTS;
use chia_wallet_sdk::signer::{AggSigConstants, RequiredBlsSignature, RequiredSecpSignature};
const SEED: [u8; 32] = [0x5A; 32];
const OTHER_SEED: [u8; 32] = [0xA5; 32];
fn network() -> MintNetwork {
MintNetwork::from_constants(AggSigConstants::from(&*TESTNET11_CONSTANTS))
}
fn honest_launch() -> (WalletKey, Vec<CoinSpend>, Bytes32) {
let wallet = WalletKey::from_seed_at(&SEED, ProfileIx::ROOT);
let mut sim = Simulator::new();
let alice = sim.bls(1_000_000);
let alice_p2 = StandardLayer::new(alice.pk);
let ctx = &mut SpendContext::new();
let (create_did, did) = Launcher::new(alice.coin.coin_id(), 1)
.create_simple_did(ctx, &alice_p2)
.expect("the simulator mints a DID");
alice_p2
.spend(ctx, alice.coin, create_did)
.expect("alice funds the DID");
sim.spend_coins(ctx.take(), std::slice::from_ref(&alice.sk))
.expect("the DID mint validates");
let did_coin_id = did.coin.coin_id();
let funding = Coin::new(Bytes32::new([7; 32]), wallet.puzzle_hash(), 1_000_000);
let launch = build_and_sign_store_launch(
&wallet,
did,
did_coin_id,
funding,
[0x6d; 32],
"did:chia:1test",
0,
1,
&network(),
)
.expect("the launch builds, gates and signs");
(wallet, launch.bundle.coin_spends, did_coin_id)
}
fn required_for(coin_spends: &[CoinSpend]) -> Vec<RequiredSignature> {
dig_merkle::required_signatures(coin_spends, network().constants()).expect("extracts")
}
#[test]
fn the_launchs_own_bundle_passes_the_gate() {
let (wallet, coin_spends, did_coin_id) = honest_launch();
gate_store_launch(
&wallet,
&coin_spends,
&required_for(&coin_spends),
did_coin_id,
&network(),
)
.expect("the launch's own bundle is exactly what the gate permits");
}
#[test]
fn a_signature_under_a_foreign_key_is_refused() {
let (wallet, coin_spends, did_coin_id) = honest_launch();
let stranger = WalletKey::from_seed_at(&OTHER_SEED, ProfileIx::ROOT);
let mut required = required_for(&coin_spends);
required.push(RequiredSignature::Bls(RequiredBlsSignature {
public_key: stranger.public_key(),
raw_message: vec![1, 2, 3].into(),
appended_info: Vec::new(),
domain_string: Some(network().constants().me()),
}));
let error = gate_store_launch(&wallet, &coin_spends, &required, did_coin_id, &network())
.expect_err("only this profile's wallet key signs");
assert!(error.to_string().contains("not this profile's wallet key"));
}
#[test]
fn an_unbound_signature_is_refused() {
let (wallet, coin_spends, did_coin_id) = honest_launch();
let mut required = required_for(&coin_spends);
required.push(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_store_launch(&wallet, &coin_spends, &required, did_coin_id, &network())
.expect_err("a launch never signs an unbound message");
assert!(error.to_string().contains("AGG_SIG_ME"));
}
#[test]
fn a_secp_signature_requirement_is_refused() {
use chia_wallet_sdk::signer::SecpPublicKey;
use sha2::{Digest, Sha256};
let (wallet, coin_spends, did_coin_id) = honest_launch();
let seed: [u8; 32] =
Sha256::digest(b"dig-account store-launch secp refusal fixture").into();
let secret =
chia_secp::K1SecretKey::from_bytes(&seed).expect("a hashed seed is a valid k1 scalar");
let mut required = required_for(&coin_spends);
required.push(RequiredSignature::Secp(RequiredSecpSignature {
public_key: SecpPublicKey::K1(secret.public_key()),
message_hash: [7; 32],
placeholder_ptr: clvmr::NodePtr::NIL,
}));
let error = gate_store_launch(&wallet, &coin_spends, &required, did_coin_id, &network())
.expect_err("a store launch never produces a secp requirement");
assert!(error.to_string().contains("secp"));
}
#[test]
fn a_bundle_that_spends_a_different_singleton_is_refused() {
let (wallet, coin_spends, _) = honest_launch();
let error = gate_store_launch(
&wallet,
&coin_spends,
&required_for(&coin_spends),
Bytes32::new([0xEE; 32]),
&network(),
)
.expect_err("the DID coin is identified by id");
assert!(error
.to_string()
.contains("does not spend this profile's DID coin"));
}
#[test]
fn a_did_that_is_not_the_recorded_coin_is_refused_before_building() {
let wallet = WalletKey::from_seed_at(&SEED, ProfileIx::ROOT);
let mut sim = Simulator::new();
let alice = sim.bls(1_000_000);
let alice_p2 = StandardLayer::new(alice.pk);
let ctx = &mut SpendContext::new();
let (create_did, did) = Launcher::new(alice.coin.coin_id(), 1)
.create_simple_did(ctx, &alice_p2)
.expect("the simulator mints a DID");
alice_p2
.spend(ctx, alice.coin, create_did)
.expect("alice funds the DID");
sim.spend_coins(ctx.take(), std::slice::from_ref(&alice.sk))
.expect("the DID mint validates");
let funding = Coin::new(Bytes32::new([7; 32]), wallet.puzzle_hash(), 1_000_000);
let Err(error) = build_and_sign_store_launch(
&wallet,
did,
Bytes32::new([0xEE; 32]),
funding,
[0x6d; 32],
"did:chia:1test",
0,
1,
&network(),
) else {
panic!("the DID coin must be the one the mint recorded, and nothing may be signed");
};
assert!(matches!(error, MintError::Refused(_)), "{error:?}");
assert!(error.to_string().contains("this mint recorded"));
}
#[test]
fn a_bundle_spending_a_third_pre_existing_coin_is_refused() {
let (wallet, mut coin_spends, did_coin_id) = honest_launch();
let stray = Coin::new(Bytes32::new([0xAB; 32]), wallet.puzzle_hash(), 500);
let template = coin_spends[0].clone();
coin_spends.push(CoinSpend::new(
stray,
template.puzzle_reveal,
template.solution,
));
let error = gate_store_launch(
&wallet,
&coin_spends,
&required_for(&coin_spends),
did_coin_id,
&network(),
)
.expect_err("a launch spends exactly two pre-existing coins");
assert!(error.to_string().contains("exactly two"));
}
}