use std::collections::HashSet;
use chia_protocol::{Bytes32, Coin, CoinSpend};
use chia_puzzle_types::cat::CatArgs;
use chia_puzzle_types::Memos;
use chia_wallet_sdk::driver::{
Cat, CatSpend, Puzzle, SpendContext, SpendWithConditions, StandardLayer,
};
use chia_wallet_sdk::prelude::TreeHash;
use chia_wallet_sdk::types::Conditions;
use clvmr::serde::node_from_bytes;
use clvmr::Allocator;
use dig_chainsource_interface::ChainSource;
use dig_constants::DIG_ASSET_ID;
use crate::chain_confirm::{confirm_all_spendable_by_name, UnconfirmedInput};
use crate::keys::wallet_key::WalletKey;
use crate::wallet::authorizer::WalletOps;
use crate::wallet::policy::CustodyPolicy;
use crate::wallet::reservation::{select_and_reserve, CoinReservations, ReservationId};
use crate::wallet::transfer::{
PayableDestination, MAX_RESERVATION_ATTEMPTS, MAX_TRANSFER_INPUT_COINS,
};
pub const DIG_BASE_UNITS_PER_TOKEN: u64 = 1_000;
pub const MAX_CAT_TRANSFER_INPUT_COINS: usize = MAX_TRANSFER_INPUT_COINS;
const FEE_BINDING_MESSAGE: &[u8] = b"dig-account:cat-transfer";
pub type CatTransferResult<T> = std::result::Result<T, CatTransferError>;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum CatTransferError {
#[error(
"insufficient $DIG: the transfer needs {required} base units, the wallet holds {available}"
)]
InsufficientDig {
required: u64,
available: u64,
},
#[error("every coin that could fund this send is reserved by an in-flight spend: it needs {required}, the wallet holds {available} but only {selectable} is free right now")]
CoinsReserved {
required: u64,
available: u64,
selectable: u64,
},
#[error("{0}")]
ReservationUnusable(String),
#[error(
"this transfer would need {needed} $DIG coins, above the {cap}-coin limit; consolidate \
some coins first"
)]
TooManyInputCoins {
needed: usize,
cap: usize,
},
#[error(
"this wallet holds $DIG but only {available} mojos of XCH, and a {required}-mojo fee is \
paid in XCH, not in $DIG; add a little XCH, or send with a zero fee and wait longer for \
it to confirm"
)]
NoXchForFee {
required: u64,
available: u64,
},
#[error(
"the recipient is this wallet's own address; a self-payment moves nothing and costs a fee"
)]
SelfPayment,
#[error("a transfer must move a positive number of $DIG base units")]
ZeroAmount,
#[error(
"this profile's funds are in the vault tier, which cannot send directly; move funds vault \
-> hot wallet through the clawback window first, then send from the hot wallet"
)]
VaultTransferUnsupported,
#[error("the wallet's $DIG coins total more than u64 can represent, so the balance cannot be judged")]
BalanceUnjudgeable,
#[error(
"the lineage of $DIG coin {coin_id} could not be established from its parent spend ({reason}), \
so it cannot be proven to be a genuine $DIG coin"
)]
LineageUnavailable {
coin_id: Bytes32,
reason: String,
},
#[error("chain unreachable: {0}")]
ChainUnreachable(String),
#[error("could not build the $DIG transfer spend: {0}")]
Build(String),
}
impl From<UnconfirmedInput> for CatTransferError {
fn from(error: UnconfirmedInput) -> Self {
CatTransferError::ChainUnreachable(error.to_string())
}
}
#[derive(Debug, Clone, Copy)]
pub struct CatTransferRequest {
recipient: PayableDestination,
amount_base_units: u64,
fee_mojos: u64,
}
impl CatTransferRequest {
pub fn new(recipient: PayableDestination, amount_base_units: u64) -> Self {
Self {
recipient,
amount_base_units,
fee_mojos: 0,
}
}
pub fn with_fee_mojos(mut self, fee_mojos: u64) -> Self {
self.fee_mojos = fee_mojos;
self
}
pub fn recipient(&self) -> Bytes32 {
self.recipient.puzzle_hash()
}
pub fn amount_base_units(&self) -> u64 {
self.amount_base_units
}
pub fn fee_mojos(&self) -> u64 {
self.fee_mojos
}
}
#[derive(Debug, Clone)]
pub struct CatTransferPlan {
coin_spends: Vec<CoinSpend>,
dig_source_coin_ids: Vec<Bytes32>,
xch_source_coin_ids: Vec<Bytes32>,
recipient: Bytes32,
amount_base_units: u64,
fee_mojos: u64,
change_base_units: u64,
reservation: Option<ReservationId>,
}
impl CatTransferPlan {
pub fn reservation(&self) -> Option<ReservationId> {
self.reservation
}
pub fn coin_spends(&self) -> &[CoinSpend] {
&self.coin_spends
}
pub fn dig_source_coin_ids(&self) -> &[Bytes32] {
&self.dig_source_coin_ids
}
pub fn xch_source_coin_ids(&self) -> &[Bytes32] {
&self.xch_source_coin_ids
}
pub fn recipient(&self) -> Bytes32 {
self.recipient
}
pub fn amount_base_units(&self) -> u64 {
self.amount_base_units
}
pub fn fee_mojos(&self) -> u64 {
self.fee_mojos
}
pub fn change_base_units(&self) -> u64 {
self.change_base_units
}
}
pub fn cat_curried_puzzle_hash(asset_id: Bytes32, p2_puzzle_hash: Bytes32) -> Bytes32 {
CatArgs::curry_tree_hash(asset_id, TreeHash::new(p2_puzzle_hash.into())).into()
}
pub fn dig_curried_puzzle_hash(p2_puzzle_hash: Bytes32) -> Bytes32 {
cat_curried_puzzle_hash(DIG_ASSET_ID, p2_puzzle_hash)
}
pub fn amount_in_dig(base_units: u64) -> (u64, u64) {
(
base_units / DIG_BASE_UNITS_PER_TOKEN,
base_units % DIG_BASE_UNITS_PER_TOKEN,
)
}
impl WalletOps {
pub fn build_dig_transfer<C>(
&self,
chain: &C,
custody: &CustodyPolicy,
request: &CatTransferRequest,
reservations: &CoinReservations<'_>,
) -> CatTransferResult<CatTransferPlan>
where
C: ChainSource + ?Sized,
{
self.build_cat_transfer(chain, custody, DIG_ASSET_ID, request, reservations)
}
pub fn build_cat_transfer<C>(
&self,
chain: &C,
custody: &CustodyPolicy,
asset_id: Bytes32,
request: &CatTransferRequest,
reservations: &CoinReservations<'_>,
) -> CatTransferResult<CatTransferPlan>
where
C: ChainSource + ?Sized,
{
if let CustodyPolicy::Vault(_) = custody {
return Err(CatTransferError::VaultTransferUnsupported);
}
if request.amount_base_units == 0 {
return Err(CatTransferError::ZeroAmount);
}
let wallet = self.wallet_key();
if request.recipient() == wallet.puzzle_hash() {
return Err(CatTransferError::SelfPayment);
}
let ((cat_coins, fee_coins), held) = select_and_reserve(
reservations,
MAX_RESERVATION_ATTEMPTS,
|excluded| {
let cat_coins = select_cat_coins(
chain,
asset_id,
wallet.puzzle_hash(),
request.amount_base_units,
excluded,
)?;
let fee_coins =
select_fee_coins(chain, wallet.puzzle_hash(), request.fee_mojos, excluded)?;
let ids = cat_coins
.iter()
.chain(fee_coins.iter())
.map(Coin::coin_id)
.collect();
Ok(((cat_coins, fee_coins), ids))
},
|e| CatTransferError::ReservationUnusable(e.to_string()),
)?;
let cats = resolve_lineage(chain, asset_id, &cat_coins)?;
let mut plan = build_dig_transfer_spends(&wallet, &cats, &fee_coins, request, None)?;
plan.reservation = Some(held.commit());
Ok(plan)
}
}
fn select_cat_coins<C>(
chain: &C,
asset_id: Bytes32,
p2_puzzle_hash: Bytes32,
required: u64,
reserved: &HashSet<Bytes32>,
) -> CatTransferResult<Vec<Coin>>
where
C: ChainSource + ?Sized,
{
let cat_puzzle_hash = cat_curried_puzzle_hash(asset_id, p2_puzzle_hash);
let records = chain
.coin_records_by_puzzle_hash(cat_puzzle_hash, false)
.map_err(|e| CatTransferError::ChainUnreachable(e.to_string()))?;
let mut seen: HashSet<Bytes32> = HashSet::with_capacity(records.len());
let mut spendable: Vec<Coin> = Vec::with_capacity(records.len());
for record in &records {
if record.is_spent() || record.confirmed_height.is_none() {
continue;
}
if record.coin.puzzle_hash != cat_puzzle_hash {
continue;
}
if !seen.insert(record.coin.coin_id()) {
continue;
}
spendable.push(record.coin);
}
spendable.sort_by_cached_key(|coin| (coin.amount, coin.coin_id()));
let available = spendable
.iter()
.try_fold(0u64, |sum, coin| sum.checked_add(coin.amount))
.ok_or(CatTransferError::BalanceUnjudgeable)?;
if available < required {
return Err(CatTransferError::InsufficientDig {
required,
available,
});
}
spendable.retain(|coin| !reserved.contains(&coin.coin_id()));
let selectable = spendable
.iter()
.try_fold(0u64, |sum, coin| sum.checked_add(coin.amount))
.ok_or(CatTransferError::BalanceUnjudgeable)?;
if selectable < required {
return Err(CatTransferError::CoinsReserved {
required,
available,
selectable,
});
}
let selected = if let Some(single) = spendable.iter().find(|coin| coin.amount >= required) {
vec![*single]
} else {
let mut selected = Vec::new();
let mut total = 0u64;
for coin in spendable.iter().rev() {
total = total.saturating_add(coin.amount);
selected.push(*coin);
if total >= required {
break;
}
}
if selected.len() > MAX_CAT_TRANSFER_INPUT_COINS {
return Err(CatTransferError::TooManyInputCoins {
needed: selected.len(),
cap: MAX_CAT_TRANSFER_INPUT_COINS,
});
}
selected
};
confirm_all_spendable_by_name(chain, &selected)?;
Ok(selected)
}
fn select_fee_coins<C>(
chain: &C,
p2_puzzle_hash: Bytes32,
fee_mojos: u64,
reserved: &HashSet<Bytes32>,
) -> CatTransferResult<Vec<Coin>>
where
C: ChainSource + ?Sized,
{
if fee_mojos == 0 {
return Ok(Vec::new());
}
let records = chain
.coin_records_by_puzzle_hash(p2_puzzle_hash, false)
.map_err(|e| CatTransferError::ChainUnreachable(e.to_string()))?;
let mut seen: HashSet<Bytes32> = HashSet::with_capacity(records.len());
let mut spendable: Vec<Coin> = Vec::new();
for record in &records {
if record.is_spent()
|| record.confirmed_height.is_none()
|| record.coin.puzzle_hash != p2_puzzle_hash
|| !seen.insert(record.coin.coin_id())
{
continue;
}
spendable.push(record.coin);
}
let available = spendable
.iter()
.try_fold(0u64, |sum, coin| sum.checked_add(coin.amount))
.ok_or(CatTransferError::BalanceUnjudgeable)?;
spendable.sort_by_cached_key(|coin| (coin.amount, coin.coin_id()));
let owns_a_covering_coin = spendable.iter().any(|coin| coin.amount >= fee_mojos);
spendable.retain(|coin| !reserved.contains(&coin.coin_id()));
let selectable = spendable
.iter()
.try_fold(0u64, |sum, coin| sum.checked_add(coin.amount))
.ok_or(CatTransferError::BalanceUnjudgeable)?;
let chosen = match spendable
.iter()
.find(|coin| coin.amount >= fee_mojos)
.copied()
{
Some(coin) => coin,
None if owns_a_covering_coin => {
return Err(CatTransferError::CoinsReserved {
required: fee_mojos,
available,
selectable,
})
}
None => {
return Err(CatTransferError::NoXchForFee {
required: fee_mojos,
available,
})
}
};
confirm_all_spendable_by_name(chain, std::slice::from_ref(&chosen))?;
Ok(vec![chosen])
}
fn resolve_lineage<C>(chain: &C, asset_id: Bytes32, coins: &[Coin]) -> CatTransferResult<Vec<Cat>>
where
C: ChainSource + ?Sized,
{
let mut allocator = Allocator::new();
let mut cats = Vec::with_capacity(coins.len());
for coin in coins {
let coin_id = coin.coin_id();
let unprovable = |reason: String| CatTransferError::LineageUnavailable { coin_id, reason };
let parent = chain
.parent_spend(coin_id)
.map_err(|e| CatTransferError::ChainUnreachable(e.to_string()))?
.ok_or_else(|| unprovable("its parent spend is unknown to this source".into()))?;
let puzzle_ptr = node_from_bytes(&mut allocator, &parent.puzzle_reveal)
.map_err(|e| unprovable(format!("the parent puzzle reveal does not decode: {e}")))?;
let solution_ptr = node_from_bytes(&mut allocator, &parent.solution)
.map_err(|e| unprovable(format!("the parent solution does not decode: {e}")))?;
let puzzle = Puzzle::parse(&allocator, puzzle_ptr);
let children = Cat::parse_children(&mut allocator, parent.coin, puzzle, solution_ptr)
.map_err(|e| unprovable(format!("the parent spend could not be parsed: {e}")))?
.ok_or_else(|| unprovable("the parent coin is not a CAT".into()))?;
let cat = children
.into_iter()
.find(|child| child.coin.coin_id() == coin_id)
.ok_or_else(|| {
unprovable("the parent spend does not create this coin as a CAT child".into())
})?;
if cat.info.asset_id != asset_id {
return Err(unprovable(format!(
"it is a CAT of asset {} rather than the {} being spent",
hex::encode(cat.info.asset_id),
hex::encode(asset_id)
)));
}
cats.push(cat);
}
Ok(cats)
}
fn build_dig_transfer_spends(
wallet: &WalletKey,
cats: &[Cat],
fee_coins: &[Coin],
request: &CatTransferRequest,
reservation: Option<ReservationId>,
) -> CatTransferResult<CatTransferPlan> {
if cats.is_empty() {
return Err(CatTransferError::Build(
"no $DIG coins were selected".into(),
));
}
let total = cats
.iter()
.try_fold(0u64, |sum, cat| sum.checked_add(cat.coin.amount))
.ok_or_else(|| CatTransferError::Build("the selected $DIG coins overflow u64".into()))?;
let change = total
.checked_sub(request.amount_base_units)
.ok_or_else(|| {
CatTransferError::Build("the selected $DIG coins do not cover the transfer".into())
})?;
let mut ctx = SpendContext::new();
let layer = StandardLayer::new(wallet.public_key());
let recipient_hint = ctx
.hint(request.recipient())
.map_err(|e| CatTransferError::Build(format!("recipient hint: {e}")))?;
let change_hint = ctx
.hint(wallet.puzzle_hash())
.map_err(|e| CatTransferError::Build(format!("change hint: {e}")))?;
let mut lead_conditions = Conditions::new().create_coin(
request.recipient(),
request.amount_base_units,
recipient_hint,
);
if change > 0 {
lead_conditions = lead_conditions.create_coin(wallet.puzzle_hash(), change, change_hint);
}
if !fee_coins.is_empty() {
lead_conditions =
lead_conditions.create_coin_announcement(FEE_BINDING_MESSAGE.to_vec().into());
}
let mut cat_spends = Vec::with_capacity(cats.len());
for (index, cat) in cats.iter().enumerate() {
let is_lead = index == cats.len() - 1;
let conditions = if is_lead {
lead_conditions.clone()
} else {
Conditions::new()
};
let spend = layer
.spend_with_conditions(&mut ctx, conditions)
.map_err(|e| CatTransferError::Build(format!("$DIG input {index}: {e}")))?;
cat_spends.push(CatSpend::new(*cat, spend));
}
Cat::spend_all(&mut ctx, &cat_spends)
.map_err(|e| CatTransferError::Build(format!("the $DIG ring: {e}")))?;
let lead_coin_id = cats[cats.len() - 1].coin.coin_id();
let binding = chia_wallet_sdk::types::announcement_id(lead_coin_id, FEE_BINDING_MESSAGE);
let fee_total = fee_coins
.iter()
.try_fold(0u64, |sum, coin| sum.checked_add(coin.amount))
.ok_or_else(|| CatTransferError::Build("the fee coins overflow u64".into()))?;
if !fee_coins.is_empty() {
let fee_change = fee_total
.checked_sub(request.fee_mojos)
.ok_or_else(|| CatTransferError::Build("the fee coins do not cover the fee".into()))?;
for (index, coin) in fee_coins.iter().enumerate() {
let mut conditions = Conditions::new().assert_coin_announcement(binding);
if index == 0 {
if request.fee_mojos > 0 {
conditions = conditions.reserve_fee(request.fee_mojos);
}
if fee_change > 0 {
conditions =
conditions.create_coin(wallet.puzzle_hash(), fee_change, Memos::None);
}
}
layer
.spend(&mut ctx, *coin, conditions)
.map_err(|e| CatTransferError::Build(format!("fee input {index}: {e}")))?;
}
}
Ok(CatTransferPlan {
coin_spends: ctx.take(),
dig_source_coin_ids: cats.iter().map(|cat| cat.coin.coin_id()).collect(),
xch_source_coin_ids: fee_coins.iter().map(Coin::coin_id).collect(),
recipient: request.recipient(),
amount_base_units: request.amount_base_units,
fee_mojos: request.fee_mojos,
change_base_units: change,
reservation,
})
}
#[cfg(test)]
mod tests {
use super::*;
use dig_chainsource_interface::CoinRecord;
#[derive(Debug)]
struct FixedChain {
records: Vec<CoinRecord>,
}
impl ChainSource for FixedChain {
type Error = String;
fn coin_record(&self, coin_id: Bytes32) -> std::result::Result<Option<CoinRecord>, String> {
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,
) -> std::result::Result<Vec<CoinRecord>, String> {
Ok(self
.records
.iter()
.filter(|record| record.coin.puzzle_hash == puzzle_hash)
.cloned()
.collect())
}
fn coin_records_by_parent(
&self,
_parent: Bytes32,
) -> std::result::Result<Vec<CoinRecord>, String> {
Ok(Vec::new())
}
fn coin_spend(&self, _coin_id: Bytes32) -> std::result::Result<Option<CoinSpend>, String> {
Ok(None)
}
fn resolve_singleton_lineage(
&self,
_launcher_id: Bytes32,
) -> std::result::Result<Option<dig_chainsource_interface::SingletonLineage>, String>
{
Err("not supported by this test double".to_string())
}
fn peak_height(&self) -> std::result::Result<Option<u32>, String> {
Ok(Some(4_200_000))
}
fn block_timestamp(&self, _height: u32) -> std::result::Result<Option<u64>, String> {
Ok(None)
}
}
fn confirmed(coin: Coin) -> CoinRecord {
CoinRecord {
coin,
confirmed_height: Some(4_100_000),
spent_height: None,
timestamp: None,
coinbase: false,
}
}
const P2: Bytes32 = Bytes32::new([0x11; 32]);
fn xch(tag: u8, amount: u64) -> Coin {
Coin::new(Bytes32::new([tag; 32]), P2, amount)
}
#[test]
fn the_fee_leg_will_not_take_an_xch_coin_an_ordinary_transfer_reserved() {
let taken = xch(1, 1_000);
let spare = xch(2, 2_000);
let chain = FixedChain {
records: vec![confirmed(taken), confirmed(spare)],
};
let control = select_fee_coins(&chain, P2, 500, &HashSet::new())
.expect("the control: unreserved, the smallest sufficient coin pays the fee");
assert_eq!(control[0].coin_id(), taken.coin_id());
let reserved: HashSet<Bytes32> = [taken.coin_id()].into_iter().collect();
let chosen = select_fee_coins(&chain, P2, 500, &reserved)
.expect("a $DIG send can still pay its fee from the coin that is free");
assert_eq!(
chosen[0].coin_id(),
spare.coin_id(),
"an XCH coin an in-flight transfer holds must not also pay a CAT fee"
);
}
#[test]
fn a_reserved_fee_coin_is_not_reported_as_missing_xch() {
let only = xch(1, 1_000);
let chain = FixedChain {
records: vec![confirmed(only)],
};
let reserved: HashSet<Bytes32> = [only.coin_id()].into_iter().collect();
let error = select_fee_coins(&chain, P2, 500, &reserved)
.expect_err("the only XCH coin is committed elsewhere");
match error {
CatTransferError::CoinsReserved {
available,
selectable,
..
} => {
assert_eq!(available, 1_000, "the XCH is still the user's money");
assert_eq!(selectable, 0);
}
other => panic!("a busy fee coin is not missing XCH: {other:?}"),
}
}
#[test]
fn a_zero_fee_selects_and_reserves_no_xch_at_all() {
let chain = FixedChain {
records: vec![confirmed(xch(1, 1_000))],
};
assert!(select_fee_coins(&chain, P2, 0, &HashSet::new())
.expect("a zero fee needs no XCH")
.is_empty());
}
}