use std::collections::HashSet;
use chia_bls::Signature;
use crate::wallet::reservation::{select_and_reserve, CoinReservations, HeldCoins, ReservationId};
use crate::wallet::transfer::MAX_RESERVATION_ATTEMPTS;
use chia_protocol::{Bytes32, Coin, CoinSpend, SpendBundle};
use chia_wallet_sdk::driver::{SpendContext, StandardLayer};
use chia_wallet_sdk::prelude::MAINNET_CONSTANTS;
use chia_wallet_sdk::signer::{AggSigConstants, RequiredSignature};
use chia_wallet_sdk::types::Conditions;
use dig_chainsource_interface::{ChainSource, CoinRecord};
use dig_did::types::Owner;
use crate::chain_confirm::{confirm_spendable_by_name, UnconfirmedInput};
use crate::id::ProfileIx;
use crate::keys::wallet_key::WalletKey;
use crate::mint::chain::{PushOutcome, SpendPublisher};
use crate::mint::error::{MintError, MintResult};
use crate::mint::evidence::{MintedDid, PendingMint};
use crate::mint::status::MintStatus;
use crate::profile_mint::ProfileMinter;
const SINGLETON_AMOUNT: u64 = 1;
pub const MAX_MINT_FEE_MOJOS: u64 = 10_000_000_000;
#[derive(Debug, Clone)]
pub struct MintNetwork {
constants: AggSigConstants,
}
impl MintNetwork {
pub fn mainnet() -> Self {
Self {
constants: AggSigConstants::from(&*MAINNET_CONSTANTS),
}
}
pub fn from_constants(constants: AggSigConstants) -> Self {
Self { constants }
}
pub(crate) fn constants(&self) -> &AggSigConstants {
&self.constants
}
}
#[derive(Debug, Clone, Default)]
pub struct MintOptions {
pub fee: u64,
}
impl MintOptions {
pub fn with_fee(fee: u64) -> Self {
Self { fee }
}
fn required_coin_amount(&self) -> u64 {
SINGLETON_AMOUNT.saturating_add(self.fee)
}
fn check_fee_ceiling(&self) -> MintResult<()> {
if self.fee > MAX_MINT_FEE_MOJOS {
return Err(MintError::FeeAboveCeiling {
fee: self.fee,
ceiling: MAX_MINT_FEE_MOJOS,
});
}
Ok(())
}
}
impl ProfileMinter {
pub fn begin_did_mint<'r, C, P>(
&self,
ix: ProfileIx,
chain: &C,
publisher: &P,
network: &MintNetwork,
options: &MintOptions,
reservations: &'r CoinReservations<'r>,
) -> MintResult<(PendingMint, ReservationId)>
where
C: ChainSource + ?Sized,
P: SpendPublisher + ?Sized,
{
let (bundle, pending, held) =
self.prepare_did_mint(ix, chain, network, options, reservations)?;
match push(publisher, &bundle) {
Ok(()) => Ok((pending, held.commit())),
Err(rejected @ MintError::Rejected(_)) => Err(rejected),
Err(unknown) => {
let _ = held.commit();
Err(unknown)
}
}
}
pub(super) fn prepare_did_mint<'r, C>(
&self,
ix: ProfileIx,
chain: &C,
network: &MintNetwork,
options: &MintOptions,
reservations: &'r CoinReservations<'r>,
) -> MintResult<(SpendBundle, PendingMint, HeldCoins<'r>)>
where
C: ChainSource + ?Sized,
{
let wallet = self.live_wallet_key(ix)?;
options.check_fee_ceiling()?;
let (source, held) = select_and_reserve(
reservations,
MAX_RESERVATION_ATTEMPTS,
|excluded| {
let coin = select_funding_coin(chain, wallet.puzzle_hash(), options, excluded)?;
Ok((coin, vec![coin.coin_id()]))
},
|e| MintError::ReservationUnusable(e.to_string()),
)?;
let pushed_at_height = peak_height(chain)?;
let (coin_spends, pending) = build_mint_spends(&wallet, source, options, pushed_at_height)?;
self.ensure_live()?;
let signature = sign_mint_spends(&wallet, &coin_spends, network)?;
Ok((SpendBundle::new(coin_spends, signature), pending, held))
}
pub fn mint_status<C>(&self, pending: &PendingMint, chain: &C) -> MintResult<MintStatus>
where
C: ChainSource + ?Sized,
{
let peak = peak_height(chain)?;
let did_record = chain
.coin_record(pending.did_coin_id())
.map_err(|e| MintError::ChainUnreachable(e.to_string()))?;
if let Some(minted) = did_record
.as_ref()
.and_then(|record| MintedDid::from_confirmed(pending, record, peak))
{
return Ok(MintStatus::Confirmed(minted));
}
let source = chain
.coin_record(pending.source_coin_id())
.map_err(|e| MintError::ChainUnreachable(e.to_string()))?;
if did_record.is_none() && source.as_ref().is_some_and(CoinRecord::is_spent) {
return Ok(MintStatus::Failed {
reason: "the funding coin was spent by a different spend; this mint can never \
confirm"
.into(),
});
}
Ok(MintStatus::Awaiting {
blocks_since_push: peak.saturating_sub(pending.pushed_at_height()),
})
}
pub(super) fn live_wallet_key(&self, ix: ProfileIx) -> MintResult<WalletKey> {
Ok(WalletKey::from_seed_at(&self.live_master_seed()?[..], ix))
}
}
pub(super) fn push<P>(publisher: &P, bundle: &SpendBundle) -> MintResult<()>
where
P: SpendPublisher + ?Sized,
{
match publisher
.push(bundle)
.map_err(|e| MintError::ChainUnreachable(e.to_string()))?
{
PushOutcome::Accepted | PushOutcome::AlreadyInMempool => Ok(()),
PushOutcome::Rejected { reason } => Err(MintError::Rejected(reason)),
}
}
pub(super) fn peak_height<C>(chain: &C) -> MintResult<u32>
where
C: ChainSource + ?Sized,
{
chain
.peak_height()
.map_err(|e| MintError::ChainUnreachable(e.to_string()))?
.ok_or_else(|| {
MintError::ChainUnreachable(
"the chain source reports no peak height, so a confirmation height cannot be \
checked"
.into(),
)
})
}
pub(super) fn select_funding_coin<C>(
chain: &C,
puzzle_hash: Bytes32,
options: &MintOptions,
reserved: &HashSet<Bytes32>,
) -> MintResult<Coin>
where
C: ChainSource + ?Sized,
{
let records = chain
.coin_records_by_puzzle_hash(puzzle_hash, false)
.map_err(|e| MintError::ChainUnreachable(e.to_string()))?;
let spendable = records.iter().filter(|record: &&CoinRecord| {
record.coin.puzzle_hash == puzzle_hash
&& record.confirmed_height.is_some()
&& !record.is_spent()
});
let required = options.required_coin_amount();
let mut best: Option<Coin> = None;
let mut available = 0u64;
let mut owns_a_covering_coin = false;
for record in spendable {
available = available.max(record.coin.amount);
if record.coin.amount < required {
continue;
}
owns_a_covering_coin = true;
if reserved.contains(&record.coin.coin_id()) {
continue;
}
if best.map_or(true, |current| record.coin.amount < current.amount) {
best = Some(record.coin);
}
}
let chosen = match best {
Some(coin) => coin,
None if owns_a_covering_coin => {
return Err(MintError::CoinsReserved {
required,
available,
})
}
None => {
return Err(MintError::InsufficientFunds {
required,
available,
})
}
};
confirm_spendable_by_name(chain, chosen).map_err(unknown_state)?;
Ok(chosen)
}
fn unknown_state(unconfirmed: UnconfirmedInput) -> MintError {
MintError::ChainUnreachable(unconfirmed.to_string())
}
fn build_mint_spends(
wallet: &WalletKey,
source: Coin,
options: &MintOptions,
pushed_at_height: u32,
) -> MintResult<(Vec<CoinSpend>, PendingMint)> {
let mut ctx = SpendContext::new();
let puzzle_hash = wallet.puzzle_hash();
let memos = ctx
.hint(puzzle_hash)
.map_err(|e| MintError::Build(format!("hint: {e}")))?;
let (change, fee) = split_change_and_fee(source.amount, options.fee);
let mut conditions = Conditions::new().create_coin(puzzle_hash, SINGLETON_AMOUNT, memos);
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(&mut ctx, source, conditions)
.map_err(|e| MintError::Build(format!("funding split: {e}")))?;
let funding_coin = Coin::new(source.coin_id(), puzzle_hash, SINGLETON_AMOUNT);
let did_spend =
dig_did::create_simple_did(&mut ctx, funding_coin, Owner::Standard(wallet.public_key()))
.map_err(|e| MintError::Build(format!("DID create: {e}")))?;
let did = did_spend
.child
.ok_or_else(|| MintError::Build("DID create returned no child DID".into()))?;
Ok((
did_spend.coin_spends,
PendingMint::new(
did.info.launcher_id,
did.coin.coin_id(),
source.coin_id(),
pushed_at_height,
),
))
}
fn split_change_and_fee(source_amount: u64, requested_fee: u64) -> (u64, u64) {
let change = source_amount
.saturating_sub(SINGLETON_AMOUNT)
.saturating_sub(requested_fee);
if change == SINGLETON_AMOUNT {
(0, requested_fee.saturating_add(change))
} else {
(change, requested_fee)
}
}
fn sign_mint_spends(
wallet: &WalletKey,
coin_spends: &[CoinSpend],
network: &MintNetwork,
) -> MintResult<Signature> {
let required = dig_did::sign::required_signatures(coin_spends, network.constants())
.map_err(|e| MintError::Build(format!("required signatures: {e}")))?;
gate(wallet, coin_spends, &required, network)?;
let mut aggregate = Signature::default();
for requirement in &required {
let RequiredSignature::Bls(bls) = requirement else {
return Err(MintError::Refused(
"non-BLS signature requirement in a DID mint".into(),
));
};
aggregate += &chia_bls::sign(wallet.secret_key(), bls.message());
}
Ok(aggregate)
}
fn gate(
wallet: &WalletKey,
coin_spends: &[CoinSpend],
required: &[RequiredSignature],
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 mint never signs an unbound message)"
.into(),
));
}
}
RequiredSignature::Secp(_) => {
return Err(MintError::Refused(
"a secp signature requirement, which a DID mint 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();
match roots.as_slice() {
[only] if only.coin.puzzle_hash == wallet.puzzle_hash() => Ok(()),
[_] => Err(MintError::Refused(
"the bundle spends a pre-existing coin that is not this wallet's".into(),
)),
_ => Err(MintError::Refused(format!(
"the bundle spends {} pre-existing coins; a mint spends exactly one",
roots.len()
))),
}
}
#[cfg(test)]
mod tests {
use super::*;
use chia_wallet_sdk::prelude::TESTNET11_CONSTANTS;
use chia_wallet_sdk::signer::{RequiredBlsSignature, RequiredSecpSignature, SecpPublicKey};
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_mint() -> (WalletKey, Vec<CoinSpend>) {
let wallet = WalletKey::from_seed_at(&SEED, ProfileIx::ROOT);
let source = Coin::new(Bytes32::new([3; 32]), wallet.puzzle_hash(), 1_000_000);
let (coin_spends, _) =
build_mint_spends(&wallet, source, &MintOptions::default(), 1).expect("builds");
(wallet, coin_spends)
}
fn required_for(coin_spends: &[CoinSpend]) -> Vec<RequiredSignature> {
dig_did::sign::required_signatures(coin_spends, network().constants()).expect("extracts")
}
#[test]
fn the_mints_own_bundle_passes_the_gate() {
let (wallet, coin_spends) = honest_mint();
gate(
&wallet,
&coin_spends,
&required_for(&coin_spends),
&network(),
)
.expect("the mint's own bundle is exactly what the gate permits");
}
#[test]
fn a_bundle_that_spends_a_second_pre_existing_coin_is_refused() {
let (wallet, mut coin_spends) = honest_mint();
let victim = Coin::new(Bytes32::new([9; 32]), wallet.puzzle_hash(), 500_000);
let first = coin_spends[0].clone();
coin_spends.push(CoinSpend::new(
victim,
first.puzzle_reveal.clone(),
first.solution.clone(),
));
let required = required_for(&coin_spends);
let error = gate(&wallet, &coin_spends, &required, &network())
.expect_err("a mint spends exactly one pre-existing coin");
assert!(
error.to_string().contains("2 pre-existing coins"),
"{error}"
);
}
#[test]
fn a_bundle_rooted_in_a_coin_this_wallet_does_not_own_is_refused() {
let wallet = WalletKey::from_seed_at(&SEED, ProfileIx::ROOT);
let stranger = WalletKey::from_seed_at(&OTHER_SEED, ProfileIx::ROOT);
let foreign_coin = Coin::new(Bytes32::new([3; 32]), stranger.puzzle_hash(), 1_000_000);
let (coin_spends, _) =
build_mint_spends(&wallet, foreign_coin, &MintOptions::default(), 1).expect("builds");
let error = gate(&wallet, &coin_spends, &[], &network())
.expect_err("the funding coin must be this wallet's own");
assert!(error.to_string().contains("not this wallet's"), "{error}");
}
#[test]
fn a_signature_under_another_key_is_refused() {
let (wallet, coin_spends) = honest_mint();
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(&wallet, &coin_spends, &required, &network())
.expect_err("only this profile's wallet key signs");
assert!(
error.to_string().contains("not this profile's wallet key"),
"{error}"
);
}
#[test]
fn an_unsafe_unbound_signature_requirement_is_refused() {
let (wallet, coin_spends) = honest_mint();
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(&wallet, &coin_spends, &required, &network())
.expect_err("a mint never signs an unbound message");
assert!(error.to_string().contains("AGG_SIG_ME"), "{error}");
}
#[test]
fn selection_prefers_the_smallest_sufficient_coin() {
let wallet = WalletKey::from_seed_at(&SEED, ProfileIx::ROOT);
let amounts = [5_000_u64, 900, 50, 20];
let chain = FixedChain::new(
amounts
.iter()
.map(|amount| Coin::new(Bytes32::new([1; 32]), wallet.puzzle_hash(), *amount))
.collect(),
);
let chosen = select_funding_coin(
&chain,
wallet.puzzle_hash(),
&MintOptions::with_fee(100),
&HashSet::new(),
)
.expect("two coins cover the fee");
assert_eq!(
chosen.amount, 900,
"50 and 20 are too small; 5_000 is larger"
);
}
#[test]
fn a_reserved_coin_is_not_chosen_to_fund_a_mint() {
let wallet = WalletKey::from_seed_at(&SEED, ProfileIx::ROOT);
let coin =
|tag: u8, amount| Coin::new(Bytes32::new([tag; 32]), wallet.puzzle_hash(), amount);
let preferred = coin(1, 900);
let spare = coin(2, 5_000);
let chain = FixedChain::new(vec![preferred, spare]);
let control = select_funding_coin(
&chain,
wallet.puzzle_hash(),
&MintOptions::with_fee(100),
&HashSet::new(),
)
.expect("the control: unreserved, the smallest sufficient coin wins");
assert_eq!(control.coin_id(), preferred.coin_id());
let reserved: HashSet<Bytes32> = [preferred.coin_id()].into_iter().collect();
let chosen = select_funding_coin(
&chain,
wallet.puzzle_hash(),
&MintOptions::with_fee(100),
&reserved,
)
.expect("the mint falls back to the coin that is free");
assert_eq!(
chosen.coin_id(),
spare.coin_id(),
"a coin committed to another spend must not fund a mint too"
);
}
#[test]
fn a_mint_blocked_by_a_reservation_is_not_reported_as_a_shortfall() {
let wallet = WalletKey::from_seed_at(&SEED, ProfileIx::ROOT);
let only = Coin::new(Bytes32::new([1; 32]), wallet.puzzle_hash(), 5_000);
let chain = FixedChain::new(vec![only]);
let reserved: HashSet<Bytes32> = [only.coin_id()].into_iter().collect();
let error = select_funding_coin(
&chain,
wallet.puzzle_hash(),
&MintOptions::with_fee(100),
&reserved,
)
.expect_err("the only coin is committed elsewhere");
assert!(
matches!(
error,
MintError::CoinsReserved {
available: 5_000,
..
}
),
"a busy coin is not a shortfall, and the balance must still count it: {error}"
);
}
#[test]
fn unconfirmed_and_spent_coins_are_not_spendable() {
let wallet = WalletKey::from_seed_at(&SEED, ProfileIx::ROOT);
let coin = |amount| Coin::new(Bytes32::new([1; 32]), wallet.puzzle_hash(), amount);
let chain = FixedChain {
records: vec![
CoinRecord {
coin: coin(10_000),
confirmed_height: None,
spent_height: None,
timestamp: None,
coinbase: false,
},
CoinRecord {
coin: coin(20_000),
confirmed_height: Some(1),
spent_height: Some(2),
timestamp: None,
coinbase: false,
},
],
};
let error = select_funding_coin(
&chain,
wallet.puzzle_hash(),
&MintOptions::default(),
&HashSet::new(),
)
.expect_err("neither coin is spendable");
assert!(
matches!(error, MintError::InsufficientFunds { available: 0, .. }),
"{error}"
);
}
#[test]
fn a_foreign_puzzle_hash_coin_is_never_selected_and_never_bricks_the_mint() {
let wallet = WalletKey::from_seed_at(&SEED, ProfileIx::ROOT);
let parent = Bytes32::new([1; 32]);
let chain = HintedChain::returning(vec![
Coin::new(parent, CAT_PUZZLE_HASH, 200),
Coin::new(parent, wallet.puzzle_hash(), 900),
]);
let chosen = select_funding_coin(
&chain,
wallet.puzzle_hash(),
&MintOptions::with_fee(100),
&HashSet::new(),
)
.expect("the wallet's own coin covers the mint, so a foreign record is not fatal");
assert_eq!(
chosen.puzzle_hash,
wallet.puzzle_hash(),
"the mint may only fund itself from a coin its own standard layer can unlock"
);
assert_eq!(chosen.amount, 900);
}
#[test]
fn a_foreign_puzzle_hash_coin_is_not_counted_as_available_balance() {
let wallet = WalletKey::from_seed_at(&SEED, ProfileIx::ROOT);
let parent = Bytes32::new([1; 32]);
let chain = HintedChain::returning(vec![
Coin::new(parent, CAT_PUZZLE_HASH, 50_000),
Coin::new(parent, wallet.puzzle_hash(), 50),
]);
let error = select_funding_coin(
&chain,
wallet.puzzle_hash(),
&MintOptions::with_fee(100),
&HashSet::new(),
)
.expect_err("50 mojos cannot cover a 101-mojo mint");
assert!(
matches!(error, MintError::InsufficientFunds { available: 50, .. }),
"{error}"
);
}
#[test]
fn a_coin_the_listing_calls_spendable_and_the_by_name_read_calls_spent_is_refused() {
let wallet = WalletKey::from_seed_at(&SEED, ProfileIx::ROOT);
let coin = Coin::new(Bytes32::new([1; 32]), wallet.puzzle_hash(), 900);
let chain = DisagreeingChain::listing_says_spendable(coin, ByNameAnswer::Spent);
let error = select_funding_coin(
&chain,
wallet.puzzle_hash(),
&MintOptions::with_fee(100),
&HashSet::new(),
)
.expect_err("a coin the chain also calls spent must never fund a spend");
assert!(
matches!(error, MintError::ChainUnreachable(_)),
"the two reads disagree, so the coin's state is UNKNOWN, never a refusal or a shortfall: {error}"
);
assert!(
error.to_string().contains(&coin.coin_id().to_string()),
"the refusal must name the coin an operator has to go look at: {error}"
);
}
#[test]
fn a_coin_the_listing_calls_spendable_and_the_chain_cannot_find_by_name_is_refused() {
let wallet = WalletKey::from_seed_at(&SEED, ProfileIx::ROOT);
let coin = Coin::new(Bytes32::new([1; 32]), wallet.puzzle_hash(), 900);
let chain = DisagreeingChain::listing_says_spendable(coin, ByNameAnswer::Absent);
let error = select_funding_coin(
&chain,
wallet.puzzle_hash(),
&MintOptions::with_fee(100),
&HashSet::new(),
)
.expect_err("a coin the chain does not know by name must never fund a spend");
assert!(matches!(error, MintError::ChainUnreachable(_)), "{error}");
}
#[test]
fn a_coin_both_reads_call_spendable_still_funds_the_mint() {
let wallet = WalletKey::from_seed_at(&SEED, ProfileIx::ROOT);
let coin = Coin::new(Bytes32::new([1; 32]), wallet.puzzle_hash(), 900);
let chain = DisagreeingChain::listing_says_spendable(coin, ByNameAnswer::Spendable);
let chosen = select_funding_coin(
&chain,
wallet.puzzle_hash(),
&MintOptions::with_fee(100),
&HashSet::new(),
)
.expect("two agreeing reads are the ordinary case");
assert_eq!(chosen, coin);
}
#[test]
fn mainnet_signs_under_chia_mainnets_own_agg_sig_me_data() {
assert_eq!(
MintNetwork::mainnet().constants().me(),
MAINNET_CONSTANTS.agg_sig_me_additional_data,
"MintNetwork::mainnet() must sign under Chia mainnet's AGG_SIG_ME domain"
);
}
#[test]
fn mainnet_and_testnet_domains_differ() {
assert_ne!(
MintNetwork::mainnet().constants().me(),
network().constants().me()
);
}
fn derived_secret_bytes() -> [u8; 32] {
use sha2::{Digest, Sha256};
Sha256::digest(b"dig-account secp gate fixture").into()
}
#[test]
fn a_secp_signature_requirement_is_refused() {
let (wallet, coin_spends) = honest_mint();
let mut required = required_for(&coin_spends);
let secret = chia_secp::K1SecretKey::from_bytes(&derived_secret_bytes())
.expect("a hashed seed is a valid k1 scalar");
required.push(RequiredSignature::Secp(RequiredSecpSignature {
public_key: SecpPublicKey::K1(secret.public_key()),
message_hash: [7; 32],
placeholder_ptr: clvmr::NodePtr::NIL,
}));
let error = gate(&wallet, &coin_spends, &required, &network())
.expect_err("a DID mint never produces a secp requirement");
assert!(error.to_string().contains("secp"), "{error}");
}
#[test]
fn a_one_mojo_change_is_folded_into_the_fee_rather_than_duplicating_the_funding_coin() {
let wallet = WalletKey::from_seed_at(&SEED, ProfileIx::ROOT);
let fee = 100;
let source = Coin::new(Bytes32::new([3; 32]), wallet.puzzle_hash(), fee + 2);
assert_eq!(
split_change_and_fee(source.amount, fee),
(0, fee + 1),
"the mojo that would collide becomes fee, not a second coin"
);
let (coin_spends, pending) =
build_mint_spends(&wallet, source, &MintOptions::with_fee(fee), 1).expect("builds");
let ids: HashSet<Bytes32> = coin_spends
.iter()
.map(|spend| spend.coin.coin_id())
.collect();
assert_eq!(
ids.len(),
coin_spends.len(),
"no coin is spent twice in the bundle"
);
assert_eq!(pending.source_coin_id(), source.coin_id());
}
#[test]
fn change_is_untouched_when_it_cannot_collide() {
assert_eq!(split_change_and_fee(1_000, 100), (899, 100));
assert_eq!(
split_change_and_fee(103, 100),
(2, 100),
"a 2-mojo change is fine"
);
assert_eq!(split_change_and_fee(101, 100), (0, 100), "no change at all");
}
#[test]
fn max_mint_fee_mojos_is_pinned_as_a_security_bound() {
assert_eq!(
MAX_MINT_FEE_MOJOS, 10_000_000_000,
"MAX_MINT_FEE_MOJOS is a security bound pinned at 10 billion mojos (0.01 XCH); \
mutating it changes the spending ceiling for DID mints"
);
const MOJOS_PER_XCH: u64 = 1_000_000_000_000;
assert_eq!(
MAX_MINT_FEE_MOJOS * 100,
MOJOS_PER_XCH,
"MAX_MINT_FEE_MOJOS must equal exactly 0.01 XCH (10_000_000_000 mojos); \
this value is not a knob to tune, it is a deliberate security bound"
);
}
const CAT_PUZZLE_HASH: Bytes32 = Bytes32::new([0xCA; 32]);
struct FixedChain {
records: Vec<CoinRecord>,
}
impl FixedChain {
fn new(coins: Vec<Coin>) -> Self {
Self {
records: coins
.into_iter()
.map(|coin| CoinRecord {
coin,
confirmed_height: Some(1),
spent_height: None,
timestamp: None,
coinbase: false,
})
.collect(),
}
}
}
impl ChainSource for FixedChain {
type Error = String;
fn coin_record(&self, coin_id: Bytes32) -> Result<Option<CoinRecord>, Self::Error> {
Ok(self
.records
.iter()
.find(|record| record.coin.coin_id() == coin_id)
.cloned())
}
fn coin_records_by_puzzle_hash(
&self,
puzzle_hash: Bytes32,
_include_spent: bool,
) -> Result<Vec<CoinRecord>, Self::Error> {
Ok(self
.records
.iter()
.filter(|record| record.coin.puzzle_hash == puzzle_hash)
.cloned()
.collect())
}
fn coin_records_by_parent(&self, _parent: Bytes32) -> Result<Vec<CoinRecord>, Self::Error> {
Ok(Vec::new())
}
fn coin_spend(&self, _coin_id: Bytes32) -> Result<Option<CoinSpend>, Self::Error> {
Ok(None)
}
fn resolve_singleton_lineage(
&self,
_launcher_id: Bytes32,
) -> Result<Option<dig_chainsource_interface::SingletonLineage>, Self::Error> {
Err("not supported by this test double".to_string())
}
fn peak_height(&self) -> Result<Option<u32>, Self::Error> {
Ok(Some(1))
}
fn block_timestamp(&self, _height: u32) -> Result<Option<u64>, Self::Error> {
Ok(None)
}
}
#[derive(Clone, Copy)]
enum ByNameAnswer {
Spendable,
Spent,
Absent,
}
struct DisagreeingChain {
listed: Coin,
by_name: ByNameAnswer,
}
impl DisagreeingChain {
fn listing_says_spendable(coin: Coin, by_name: ByNameAnswer) -> Self {
Self {
listed: coin,
by_name,
}
}
fn record(&self, spent_height: Option<u32>) -> CoinRecord {
CoinRecord {
coin: self.listed,
confirmed_height: Some(1),
spent_height,
timestamp: None,
coinbase: false,
}
}
}
impl ChainSource for DisagreeingChain {
type Error = String;
fn coin_record(&self, coin_id: Bytes32) -> Result<Option<CoinRecord>, Self::Error> {
if coin_id != self.listed.coin_id() {
return Ok(None);
}
Ok(match self.by_name {
ByNameAnswer::Spendable => Some(self.record(None)),
ByNameAnswer::Spent => Some(self.record(Some(2))),
ByNameAnswer::Absent => None,
})
}
fn coin_records_by_puzzle_hash(
&self,
_puzzle_hash: Bytes32,
_include_spent: bool,
) -> Result<Vec<CoinRecord>, Self::Error> {
Ok(vec![self.record(None)])
}
fn coin_records_by_parent(&self, _parent: Bytes32) -> Result<Vec<CoinRecord>, Self::Error> {
Ok(Vec::new())
}
fn coin_spend(&self, _coin_id: Bytes32) -> Result<Option<CoinSpend>, Self::Error> {
Ok(None)
}
fn resolve_singleton_lineage(
&self,
_launcher_id: Bytes32,
) -> Result<Option<dig_chainsource_interface::SingletonLineage>, Self::Error> {
Err("not supported by this test double".to_string())
}
fn peak_height(&self) -> Result<Option<u32>, Self::Error> {
Ok(Some(1))
}
fn block_timestamp(&self, _height: u32) -> Result<Option<u64>, Self::Error> {
Ok(None)
}
}
struct HintedChain {
inner: FixedChain,
}
impl HintedChain {
fn returning(coins: Vec<Coin>) -> Self {
Self {
inner: FixedChain::new(coins),
}
}
}
impl ChainSource for HintedChain {
type Error = String;
fn coin_record(&self, coin_id: Bytes32) -> Result<Option<CoinRecord>, Self::Error> {
self.inner.coin_record(coin_id)
}
fn coin_records_by_puzzle_hash(
&self,
_puzzle_hash: Bytes32,
_include_spent: bool,
) -> Result<Vec<CoinRecord>, Self::Error> {
Ok(self.inner.records.clone())
}
fn coin_records_by_parent(&self, parent: Bytes32) -> Result<Vec<CoinRecord>, Self::Error> {
self.inner.coin_records_by_parent(parent)
}
fn coin_spend(&self, coin_id: Bytes32) -> Result<Option<CoinSpend>, Self::Error> {
self.inner.coin_spend(coin_id)
}
fn resolve_singleton_lineage(
&self,
launcher_id: Bytes32,
) -> Result<Option<dig_chainsource_interface::SingletonLineage>, Self::Error> {
self.inner.resolve_singleton_lineage(launcher_id)
}
fn peak_height(&self) -> Result<Option<u32>, Self::Error> {
self.inner.peak_height()
}
fn block_timestamp(&self, height: u32) -> Result<Option<u64>, Self::Error> {
self.inner.block_timestamp(height)
}
}
}