use std::collections::HashSet;
use chia_protocol::{Bytes32, Coin, CoinSpend};
use chia_puzzle_types::Memos;
use chia_wallet_sdk::driver::{SpendContext, StandardLayer};
use chia_wallet_sdk::types::Conditions;
use chia_wallet_sdk::utils::Address;
use dig_chainsource_interface::{ChainSource, CoinRecord};
use crate::chain_confirm::{confirm_all_spendable_by_name, UnconfirmedInput};
use crate::keys::wallet_key::WalletKey;
use crate::mint::MIN_CONFIRMATION_DEPTH;
use crate::wallet::authorizer::WalletOps;
use crate::wallet::policy::CustodyPolicy;
use crate::wallet::reservation::{select_and_reserve, CoinReservations, ReservationId};
pub const MAX_TRANSFER_INPUT_COINS: usize = 12;
pub(crate) const MAX_RESERVATION_ATTEMPTS: usize = 16;
pub use crate::constants::MAINNET_ADDRESS_PREFIX;
const INPUT_BINDING_MESSAGE: &[u8] = b"dig-account:transfer";
pub type TransferResult<T> = std::result::Result<T, TransferError>;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum TransferError {
#[error("insufficient funds: the transfer needs {required} mojos, the wallet holds {available} spendable")]
InsufficientFunds {
required: u64,
available: u64,
},
#[error("every coin that could fund this transfer is reserved by an in-flight spend: it needs {required} mojos, 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} input coins, above the {cap}-coin limit; consolidate \
some coins first"
)]
TooManyInputCoins {
needed: usize,
cap: usize,
},
#[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 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 mojos")]
ZeroAmount,
#[error("the wallet's spendable coins total more than u64 can represent, so the balance cannot be judged")]
BalanceUnjudgeable,
#[error("the amount ({amount}) plus the fee ({fee}) overflows u64")]
AmountOverflow {
amount: u64,
fee: u64,
},
#[error("recipient address {address:?} is not a valid address: {reason}")]
InvalidRecipient {
address: String,
reason: String,
},
#[error(
"input coin {coin_id} of the transfer being replaced is no longer confirmed and unspent"
)]
SourcesNoLongerSpendable {
coin_id: Bytes32,
},
#[error(
"this transfer cannot be sped up: its own input coins total {reused_total} mojos, which \
cannot cover the {required} a fee this high would need. Wait for it to confirm or fail on \
its own — a second payment to the same recipient risks paying them twice"
)]
ReplacementInputsInsufficient {
required: u64,
reused_total: u64,
},
#[error(
"a replacement must outbid the transfer it replaces: the current fee is {current} mojos \
and the proposed fee is {proposed}"
)]
ReplacementFeeNotHigher {
current: u64,
proposed: u64,
},
#[error(
"coin {coin_id} has no confirmation height from this chain source, so its spendability is \
unknown and the balance cannot be judged"
)]
SpendabilityUnknown {
coin_id: Bytes32,
},
#[error(
"coin {coin_id} is locked by puzzle hash {puzzle_hash}, not this wallet's; a transfer spends \
only native XCH coins at the wallet's own puzzle hash"
)]
UnexpectedCoinPuzzleHash {
coin_id: Bytes32,
puzzle_hash: Bytes32,
},
#[error("chain unreachable: {0}")]
ChainUnreachable(String),
#[error("could not build the transfer spend: {0}")]
Build(String),
}
impl From<UnconfirmedInput> for TransferError {
fn from(error: UnconfirmedInput) -> Self {
TransferError::ChainUnreachable(error.to_string())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PayableDestination(Bytes32);
impl PayableDestination {
pub fn from_address(address: &str) -> TransferResult<Self> {
let decoded = Address::decode(address).map_err(|e| TransferError::InvalidRecipient {
address: address.to_string(),
reason: e.to_string(),
})?;
if decoded.prefix != MAINNET_ADDRESS_PREFIX {
return Err(TransferError::InvalidRecipient {
address: address.to_string(),
reason: format!(
"it is a {:?} address, not an {MAINNET_ADDRESS_PREFIX} payment address; paying \
the puzzle hash inside one would burn the funds",
decoded.prefix
),
});
}
Ok(Self(decoded.puzzle_hash))
}
pub fn from_derived(puzzle_hash: Bytes32) -> Self {
Self(puzzle_hash)
}
pub fn puzzle_hash(&self) -> Bytes32 {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TransferRequest {
recipient: PayableDestination,
amount_mojos: u64,
fee_mojos: u64,
}
impl TransferRequest {
pub fn new(recipient: PayableDestination, amount_mojos: u64) -> Self {
Self {
recipient,
amount_mojos,
fee_mojos: 0,
}
}
pub fn to_address(address: &str, amount_mojos: u64) -> TransferResult<Self> {
Ok(Self::new(
PayableDestination::from_address(address)?,
amount_mojos,
))
}
pub fn with_fee(mut self, fee_mojos: u64) -> Self {
self.fee_mojos = fee_mojos;
self
}
pub fn recipient(&self) -> Bytes32 {
self.recipient.puzzle_hash()
}
pub fn destination(&self) -> PayableDestination {
self.recipient
}
pub fn amount_mojos(&self) -> u64 {
self.amount_mojos
}
pub fn fee_mojos(&self) -> u64 {
self.fee_mojos
}
fn required_total(&self) -> TransferResult<u64> {
self.amount_mojos
.checked_add(self.fee_mojos)
.ok_or(TransferError::AmountOverflow {
amount: self.amount_mojos,
fee: self.fee_mojos,
})
}
}
#[derive(Debug, Clone)]
pub struct TransferPlan {
coin_spends: Vec<CoinSpend>,
payment_coin_id: Bytes32,
source_coin_ids: Vec<Bytes32>,
recipient: Bytes32,
amount_mojos: u64,
fee_mojos: u64,
change_mojos: u64,
reservation: Option<ReservationId>,
}
impl TransferPlan {
pub fn coin_spends(&self) -> &[CoinSpend] {
&self.coin_spends
}
pub fn into_coin_spends(self) -> Vec<CoinSpend> {
self.coin_spends
}
pub fn source_coin_ids(&self) -> &[Bytes32] {
&self.source_coin_ids
}
pub fn reservation(&self) -> Option<ReservationId> {
self.reservation
}
pub fn payment_coin_id(&self) -> Bytes32 {
self.payment_coin_id
}
pub fn recipient(&self) -> Bytes32 {
self.recipient
}
pub fn amount_mojos(&self) -> u64 {
self.amount_mojos
}
pub fn fee_mojos(&self) -> u64 {
self.fee_mojos
}
pub fn change_mojos(&self) -> u64 {
self.change_mojos
}
pub fn pushed_now<C>(&self, chain: &C) -> TransferResult<PendingTransfer>
where
C: ChainSource + ?Sized,
{
Ok(self.pushed_at(peak_height(chain)?))
}
pub fn pushed_at(&self, pre_push_peak: u32) -> PendingTransfer {
PendingTransfer {
payment_coin_id: self.payment_coin_id,
source_coin_ids: self.source_coin_ids.clone(),
recipient: self.recipient,
amount_mojos: self.amount_mojos,
fee_mojos: self.fee_mojos,
change_mojos: self.change_mojos,
input_total_mojos: self.amount_mojos + self.fee_mojos + self.change_mojos,
pushed_at_height: pre_push_peak,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PendingTransfer {
payment_coin_id: Bytes32,
source_coin_ids: Vec<Bytes32>,
recipient: Bytes32,
amount_mojos: u64,
fee_mojos: u64,
change_mojos: u64,
input_total_mojos: u64,
pushed_at_height: u32,
}
impl PendingTransfer {
pub fn payment_coin_id(&self) -> Bytes32 {
self.payment_coin_id
}
pub fn source_coin_ids(&self) -> &[Bytes32] {
&self.source_coin_ids
}
pub fn recipient(&self) -> Bytes32 {
self.recipient
}
pub fn amount_mojos(&self) -> u64 {
self.amount_mojos
}
pub fn fee_mojos(&self) -> u64 {
self.fee_mojos
}
pub fn change_mojos(&self) -> u64 {
self.change_mojos
}
pub fn input_total_mojos(&self) -> u64 {
self.input_total_mojos
}
pub fn max_replacement_fee_mojos(&self) -> u64 {
self.fee_mojos + self.change_mojos
}
pub fn pushed_at_height(&self) -> u32 {
self.pushed_at_height
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfirmedTransfer {
payment_coin_id: Bytes32,
recipient: Bytes32,
amount_mojos: u64,
confirmed_height: u32,
}
impl ConfirmedTransfer {
fn from_confirmed(
pending: &PendingTransfer,
record: &CoinRecord,
peak_height: u32,
) -> Option<Self> {
if record.coin.coin_id() != pending.payment_coin_id {
return None;
}
let confirmed_height = record.confirmed_height?;
if confirmed_height == 0 || confirmed_height < pending.pushed_at_height {
return None;
}
if peak_height
.saturating_sub(confirmed_height)
.saturating_add(1)
< MIN_CONFIRMATION_DEPTH
{
return None;
}
Some(Self {
payment_coin_id: pending.payment_coin_id,
recipient: pending.recipient,
amount_mojos: pending.amount_mojos,
confirmed_height,
})
}
pub fn payment_coin_id(&self) -> Bytes32 {
self.payment_coin_id
}
pub fn recipient(&self) -> Bytes32 {
self.recipient
}
pub fn amount_mojos(&self) -> u64 {
self.amount_mojos
}
pub fn confirmed_height(&self) -> u32 {
self.confirmed_height
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TransferStatus {
Confirmed(ConfirmedTransfer),
Awaiting {
blocks_since_push: u32,
},
Failed {
reason: String,
},
}
impl TransferStatus {
pub fn confirmed(&self) -> Option<&ConfirmedTransfer> {
match self {
Self::Confirmed(settled) => Some(settled),
Self::Awaiting { .. } | Self::Failed { .. } => None,
}
}
}
impl WalletOps {
pub fn build_transfer<C>(
&self,
chain: &C,
custody: &CustodyPolicy,
request: &TransferRequest,
reservations: &CoinReservations<'_>,
) -> TransferResult<TransferPlan>
where
C: ChainSource + ?Sized,
{
if let CustodyPolicy::Vault(_) = custody {
return Err(TransferError::VaultTransferUnsupported);
}
if request.amount_mojos == 0 {
return Err(TransferError::ZeroAmount);
}
let wallet = self.wallet_key();
if request.recipient() == wallet.puzzle_hash() {
return Err(TransferError::SelfPayment);
}
let required = request.required_total()?;
let (selected, held) = select_and_reserve(
reservations,
MAX_RESERVATION_ATTEMPTS,
|excluded| {
let coins = select_input_coins(chain, wallet.puzzle_hash(), required, excluded)?;
let ids = coins.iter().map(Coin::coin_id).collect();
Ok((coins, ids))
},
|e| TransferError::ReservationUnusable(e.to_string()),
)?;
let mut plan = build_transfer_spends(&wallet, &selected, request, None)?;
plan.reservation = Some(held.commit());
Ok(plan)
}
pub fn build_transfer_replacing<C>(
&self,
chain: &C,
custody: &CustodyPolicy,
pending: &PendingTransfer,
new_fee_mojos: u64,
) -> TransferResult<TransferPlan>
where
C: ChainSource + ?Sized,
{
if let CustodyPolicy::Vault(_) = custody {
return Err(TransferError::VaultTransferUnsupported);
}
if new_fee_mojos <= pending.fee_mojos {
return Err(TransferError::ReplacementFeeNotHigher {
current: pending.fee_mojos,
proposed: new_fee_mojos,
});
}
let wallet = self.wallet_key();
let request = TransferRequest {
recipient: PayableDestination::from_derived(pending.recipient),
amount_mojos: pending.amount_mojos,
fee_mojos: new_fee_mojos,
};
let required = request.required_total()?;
let mut inputs = Vec::with_capacity(pending.source_coin_ids.len());
for coin_id in &pending.source_coin_ids {
inputs.push(reread_spendable_input(chain, &wallet, *coin_id)?);
}
let reused_total = inputs
.iter()
.try_fold(0u64, |sum, coin: &Coin| sum.checked_add(coin.amount))
.ok_or(TransferError::BalanceUnjudgeable)?;
if reused_total < required {
return Err(TransferError::ReplacementInputsInsufficient {
required,
reused_total,
});
}
build_transfer_spends(&wallet, &inputs, &request, None)
}
}
fn reread_spendable_input<C>(
chain: &C,
wallet: &WalletKey,
coin_id: Bytes32,
) -> TransferResult<Coin>
where
C: ChainSource + ?Sized,
{
let record = chain
.coin_record(coin_id)
.map_err(|e| TransferError::ChainUnreachable(e.to_string()))?
.ok_or(TransferError::SourcesNoLongerSpendable { coin_id })?;
if record.coin.coin_id() != coin_id {
return Err(TransferError::ChainUnreachable(format!(
"the chain source answered a request for coin {} with a record for {}",
hex::encode(coin_id),
hex::encode(record.coin.coin_id())
)));
}
if record.confirmed_height.is_none() || record.is_spent() {
return Err(TransferError::SourcesNoLongerSpendable { coin_id });
}
if record.coin.puzzle_hash != wallet.puzzle_hash() {
return Err(TransferError::UnexpectedCoinPuzzleHash {
coin_id,
puzzle_hash: record.coin.puzzle_hash,
});
}
Ok(record.coin)
}
pub fn transfer_status<C>(pending: &PendingTransfer, chain: &C) -> TransferResult<TransferStatus>
where
C: ChainSource + ?Sized,
{
let peak = peak_height(chain)?;
let payment = chain
.coin_record(pending.payment_coin_id)
.map_err(|e| TransferError::ChainUnreachable(e.to_string()))?;
if let Some(settled) = payment
.as_ref()
.and_then(|record| ConfirmedTransfer::from_confirmed(pending, record, peak))
{
return Ok(TransferStatus::Confirmed(settled));
}
if payment.is_none() {
if let Some(reason) = proof_of_death(pending, chain, peak)? {
return Ok(TransferStatus::Failed { reason });
}
}
Ok(TransferStatus::Awaiting {
blocks_since_push: peak.saturating_sub(pending.pushed_at_height),
})
}
fn proof_of_death<C>(
pending: &PendingTransfer,
chain: &C,
peak_height: u32,
) -> TransferResult<Option<String>>
where
C: ChainSource + ?Sized,
{
let read = |coin_id: Bytes32| {
chain
.coin_record(coin_id)
.map_err(|e| TransferError::ChainUnreachable(e.to_string()))
};
for source_id in &pending.source_coin_ids {
let Some(spent_height) = read(*source_id)?.and_then(|record| record.spent_height) else {
continue;
};
if spent_height == 0 {
continue;
}
let spend_depth = peak_height.saturating_sub(spent_height).saturating_add(1);
if spend_depth < MIN_CONFIRMATION_DEPTH {
continue;
}
if read(pending.payment_coin_id)?.is_some() {
return Ok(None);
}
return Ok(Some(format!(
"input coin {} was spent by a different spend at height {spent_height}, now buried \
under {spend_depth} blocks; this transfer can never confirm",
hex::encode(source_id)
)));
}
Ok(None)
}
fn peak_height<C>(chain: &C) -> TransferResult<u32>
where
C: ChainSource + ?Sized,
{
chain
.peak_height()
.map_err(|e| TransferError::ChainUnreachable(e.to_string()))?
.ok_or_else(|| {
TransferError::ChainUnreachable(
"the chain source reports no peak height, so a confirmation height cannot be \
checked"
.into(),
)
})
}
fn select_input_coins<C>(
chain: &C,
puzzle_hash: Bytes32,
required: u64,
reserved: &HashSet<Bytes32>,
) -> TransferResult<Vec<Coin>>
where
C: ChainSource + ?Sized,
{
let records = chain
.coin_records_by_puzzle_hash(puzzle_hash, false)
.map_err(|e| TransferError::ChainUnreachable(e.to_string()))?;
let mut spendable: Vec<Coin> = Vec::with_capacity(records.len());
let mut unjudgeable: Vec<Bytes32> = Vec::new();
let mut seen: HashSet<Bytes32> = HashSet::with_capacity(records.len());
for record in &records {
if record.is_spent() {
continue;
}
if record.coin.puzzle_hash != puzzle_hash {
continue;
}
if record.confirmed_height.is_none() {
unjudgeable.push(record.coin.coin_id());
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(TransferError::BalanceUnjudgeable)?;
if available < required {
if let Some(coin_id) = unjudgeable.first() {
return Err(TransferError::SpendabilityUnknown { coin_id: *coin_id });
}
return Err(TransferError::InsufficientFunds {
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(TransferError::BalanceUnjudgeable)?;
if selectable < required {
return Err(TransferError::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: u64 = 0;
for coin in spendable.iter().rev() {
total = total.saturating_add(coin.amount);
selected.push(*coin);
if total >= required {
break;
}
}
if selected.len() > MAX_TRANSFER_INPUT_COINS {
return Err(TransferError::TooManyInputCoins {
needed: selected.len(),
cap: MAX_TRANSFER_INPUT_COINS,
});
}
selected
};
confirm_all_spendable_by_name(chain, &selected)?;
Ok(selected)
}
fn build_transfer_spends(
wallet: &WalletKey,
selected: &[Coin],
request: &TransferRequest,
reservation: Option<ReservationId>,
) -> TransferResult<TransferPlan> {
let (lead, secondaries) = selected
.split_last()
.ok_or_else(|| TransferError::Build("no input coins were selected".into()))?;
let total = selected
.iter()
.try_fold(0u64, |sum, coin| sum.checked_add(coin.amount))
.ok_or_else(|| TransferError::Build("the selected inputs overflow u64".into()))?;
let change = total
.checked_sub(request.required_total()?)
.ok_or_else(|| {
TransferError::Build("the selected inputs do not cover the transfer".into())
})?;
let mut ctx = SpendContext::new();
let hint = ctx
.hint(request.recipient())
.map_err(|e| TransferError::Build(format!("recipient hint: {e}")))?;
let mut lead_conditions =
Conditions::new().create_coin(request.recipient(), request.amount_mojos, hint);
if change > 0 {
lead_conditions = lead_conditions.create_coin(wallet.puzzle_hash(), change, Memos::None);
}
if request.fee_mojos > 0 {
lead_conditions = lead_conditions.reserve_fee(request.fee_mojos);
}
if !secondaries.is_empty() {
lead_conditions =
lead_conditions.create_coin_announcement(INPUT_BINDING_MESSAGE.to_vec().into());
}
let layer = StandardLayer::new(wallet.public_key());
layer
.spend(&mut ctx, *lead, lead_conditions)
.map_err(|e| TransferError::Build(format!("lead input: {e}")))?;
let binding = chia_wallet_sdk::types::announcement_id(lead.coin_id(), INPUT_BINDING_MESSAGE);
for coin in secondaries {
layer
.spend(
&mut ctx,
*coin,
Conditions::new().assert_coin_announcement(binding),
)
.map_err(|e| TransferError::Build(format!("secondary input: {e}")))?;
}
Ok(TransferPlan {
coin_spends: ctx.take(),
payment_coin_id: Coin::new(lead.coin_id(), request.recipient(), request.amount_mojos)
.coin_id(),
source_coin_ids: selected.iter().map(Coin::coin_id).collect(),
recipient: request.recipient(),
amount_mojos: request.amount_mojos,
fee_mojos: request.fee_mojos,
change_mojos: change,
reservation,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::id::ProfileIx;
use crate::session_residency::Residency;
use crate::wallet::clock::{FixedClock, SystemClock, UnreadableClock};
use crate::wallet::policy::{HotWallet, Vault};
use crate::wallet::reservation::{
CoinReservationStore, LocalReservations, ReservationError, DEFAULT_RESERVATION_TTL_SECS,
};
use chia_wallet_sdk::prelude::FromClvm;
use chia_wallet_sdk::types::{run_puzzle, Condition};
use clvmr::serde::node_from_bytes;
use clvmr::Allocator;
use dig_keystore::{BackendKey, MemoryBackend};
use dig_session::{Password, Session, UnlockedMasterSeed, ENTROPY_LEN};
use std::cell::Cell;
use std::collections::HashSet;
use std::sync::Arc;
const ENTROPY: [u8; ENTROPY_LEN] = [0x37; ENTROPY_LEN];
const RECIPIENT: Bytes32 = Bytes32::new([7u8; 32]);
const PEAK: u32 = 4_200_000;
fn seed() -> Arc<UnlockedMasterSeed> {
Arc::new(
Session::enroll_master_seed(
Arc::new(MemoryBackend::new()),
BackendKey::new("transfer-tests".to_string()),
Password::new("pw"),
&ENTROPY,
)
.expect("the fixture seed must enrol"),
)
}
fn ops() -> WalletOps {
WalletOps::new(seed(), ProfileIx::ROOT, Arc::new(Residency::new()))
}
fn free() -> CoinReservations<'static> {
let store: &'static LocalReservations = Box::leak(Box::new(LocalReservations::new()));
CoinReservations::new(store, &SystemClock)
}
fn hot() -> CustodyPolicy {
CustodyPolicy::Hot(HotWallet {
auto_send_limit: u64::MAX,
})
}
struct FixedChain {
records: Vec<CoinRecord>,
peak: Option<u32>,
offline: bool,
answers_with: Option<CoinRecord>,
answers_puzzle_hash_query_with: Option<Vec<CoinRecord>>,
by_name: Option<Vec<CoinRecord>>,
}
impl FixedChain {
fn holding(puzzle_hash: Bytes32, amounts: &[u64]) -> Self {
Self {
records: amounts
.iter()
.enumerate()
.map(|(ix, amount)| {
confirmed(Coin::new(
Bytes32::new([ix as u8 + 1; 32]),
puzzle_hash,
*amount,
))
})
.collect(),
peak: Some(PEAK),
offline: false,
answers_with: None,
answers_puzzle_hash_query_with: None,
by_name: None,
}
}
fn with_records(records: Vec<CoinRecord>) -> Self {
Self {
records,
peak: Some(PEAK),
offline: false,
answers_with: None,
answers_puzzle_hash_query_with: None,
by_name: None,
}
}
fn at_peak(mut self, peak: u32) -> Self {
self.peak = Some(peak);
self
}
fn offline() -> Self {
Self {
records: Vec::new(),
peak: Some(PEAK),
offline: true,
answers_with: None,
answers_puzzle_hash_query_with: None,
by_name: None,
}
}
fn answering_every_query_with(mut self, record: CoinRecord) -> Self {
self.answers_with = Some(record);
self
}
fn answering_puzzle_hash_query_with(mut self, records: Vec<CoinRecord>) -> Self {
self.answers_puzzle_hash_query_with = Some(records);
self
}
fn answering_by_name_with(mut self, records: Vec<CoinRecord>) -> Self {
self.by_name = Some(records);
self
}
fn without_peak(mut self) -> Self {
self.peak = None;
self
}
fn unavailable<T>(&self) -> std::result::Result<T, String> {
Err("simulated: no node answered".to_string())
}
}
fn record(coin: Coin, confirmed_height: Option<u32>, spent_height: Option<u32>) -> CoinRecord {
CoinRecord {
coin,
confirmed_height,
spent_height,
timestamp: None,
coinbase: false,
}
}
fn confirmed(coin: Coin) -> CoinRecord {
record(coin, Some(PEAK - 100), None)
}
fn unconfirmed(coin: Coin) -> CoinRecord {
record(coin, None, None)
}
fn spent(coin: Coin) -> CoinRecord {
record(coin, Some(PEAK - 100), Some(PEAK - 50))
}
impl ChainSource for FixedChain {
type Error = String;
fn coin_record(&self, coin_id: Bytes32) -> std::result::Result<Option<CoinRecord>, String> {
if self.offline {
return self.unavailable();
}
if let Some(answer) = &self.answers_with {
return Ok(Some(answer.clone()));
}
if let Some(by_name) = &self.by_name {
return Ok(by_name
.iter()
.find(|record| record.coin.coin_id() == coin_id)
.cloned());
}
Ok(self
.records
.iter()
.chain(self.answers_puzzle_hash_query_with.iter().flatten())
.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> {
if self.offline {
return self.unavailable();
}
if let Some(answer) = &self.answers_puzzle_hash_query_with {
return Ok(answer.clone());
}
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> {
if self.offline {
return self.unavailable();
}
Ok(self.peak)
}
fn block_timestamp(&self, _height: u32) -> std::result::Result<Option<u64>, String> {
Ok(None)
}
}
fn created_coins(coin_spends: &[CoinSpend]) -> Vec<Coin> {
conditions_of(coin_spends)
.into_iter()
.filter_map(|(spender, condition)| match condition {
Condition::CreateCoin(create) => {
Some(Coin::new(spender, create.puzzle_hash, create.amount))
}
_ => None,
})
.collect()
}
fn conditions_of(coin_spends: &[CoinSpend]) -> Vec<(Bytes32, Condition)> {
let mut allocator = Allocator::new();
let mut out = Vec::new();
for spend in coin_spends {
let puzzle = node_from_bytes(&mut allocator, &spend.puzzle_reveal).expect("puzzle");
let solution = node_from_bytes(&mut allocator, &spend.solution).expect("solution");
let output = run_puzzle(&mut allocator, puzzle, solution).expect("runs");
for condition in Vec::<Condition>::from_clvm(&allocator, output).expect("conditions") {
out.push((spend.coin.coin_id(), condition));
}
}
out
}
fn inputs_of(plan: &TransferPlan) -> Vec<u64> {
let mut amounts: Vec<u64> = plan
.coin_spends()
.iter()
.map(|spend| spend.coin.amount)
.collect();
amounts.sort_unstable();
amounts
}
#[test]
fn two_builds_in_the_same_window_must_not_select_the_same_coin() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000, 1_100]);
let request = TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 900);
let store = LocalReservations::new();
let reservations = store.reservations();
let first = ops
.build_transfer(&chain, &hot(), &request, &reservations)
.expect("the first build is funded");
let second = ops
.build_transfer(&chain, &hot(), &request, &reservations)
.expect("the second build is funded by the OTHER coin");
assert_ne!(
first.source_coin_ids(),
second.source_coin_ids(),
"two spends built in the same window selected the same coin"
);
}
#[derive(Debug)]
struct UnreadableReservations;
impl CoinReservationStore for UnreadableReservations {
fn held(&self, _now_unix: u64) -> std::result::Result<Vec<Bytes32>, ReservationError> {
Err(ReservationError::Unavailable(
"simulated: the store is gone".into(),
))
}
fn reserve_all(
&self,
_coins: &[Bytes32],
_now_unix: u64,
_expires_at_unix: u64,
) -> std::result::Result<ReservationId, ReservationError> {
Err(ReservationError::Unavailable(
"simulated: the store is gone".into(),
))
}
fn release(&self, _id: ReservationId) -> std::result::Result<(), ReservationError> {
Ok(())
}
}
#[derive(Debug)]
struct UnreadableButWritable(LocalReservations);
impl CoinReservationStore for UnreadableButWritable {
fn held(&self, _now_unix: u64) -> std::result::Result<Vec<Bytes32>, ReservationError> {
Err(ReservationError::Unavailable(
"simulated: the read replica is down".into(),
))
}
fn reserve_all(
&self,
coins: &[Bytes32],
now_unix: u64,
expires_at_unix: u64,
) -> std::result::Result<ReservationId, ReservationError> {
self.0.reserve_all(coins, now_unix, expires_at_unix)
}
fn release(&self, id: ReservationId) -> std::result::Result<(), ReservationError> {
self.0.release(id)
}
}
const NOW: u64 = 1_800_000_000;
#[test]
fn a_reserved_coin_is_still_the_users_money() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let request = TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 900);
let store = LocalReservations::new();
let reservations = store.reservations();
ops.build_transfer(&chain, &hot(), &request, &reservations)
.expect("the first build takes the only coin");
let error = ops
.build_transfer(&chain, &hot(), &request, &reservations)
.expect_err("the only coin is committed to the first build");
match error {
TransferError::CoinsReserved {
required,
available,
selectable,
} => {
assert_eq!(required, 900);
assert_eq!(
available, 1_000,
"a reserved coin is still the money the user holds and must still be counted"
);
assert_eq!(selectable, 0, "and none of it is free to select right now");
}
other => panic!(
"a busy coin must not be reported as a shortfall - that asks a funded user to \
deposit for no reason: {other:?}"
),
}
}
#[test]
fn releasing_a_reservation_frees_its_coin_immediately() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let request = TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 900);
let store = LocalReservations::new();
let clock = FixedClock::new(NOW);
let reservations = CoinReservations::new(&store, &clock);
let first = ops
.build_transfer(&chain, &hot(), &request, &reservations)
.expect("the first build takes the only coin");
let held = first
.reservation()
.expect("an ordinary build reserves what it selected");
assert!(
ops.build_transfer(&chain, &hot(), &request, &reservations)
.is_err(),
"the control: while the reservation is live the coin is unavailable"
);
reservations.release(held).expect("release must succeed");
let after = ops
.build_transfer(&chain, &hot(), &request, &reservations)
.expect("a released coin is selectable again");
assert_eq!(after.source_coin_ids(), first.source_coin_ids());
}
#[test]
fn a_reservation_lapses_after_its_ttl_and_not_before() {
const TTL: u64 = 300;
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let request = TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 900);
let store = LocalReservations::new();
let clock = FixedClock::new(NOW);
let reservations =
CoinReservations::with_ttl_secs(&store, &clock, TTL).expect("a non-zero TTL is fine");
ops.build_transfer(&chain, &hot(), &request, &reservations)
.expect("the first build takes the only coin");
clock.set(NOW + TTL);
assert!(
ops.build_transfer(&chain, &hot(), &request, &reservations)
.is_err(),
"at exactly the TTL the reservation is still holding the coin"
);
clock.set(NOW + TTL + 1);
ops.build_transfer(&chain, &hot(), &request, &reservations)
.expect("one second past the TTL the coin is selectable again");
}
#[test]
fn a_lapsed_reservation_does_not_make_a_spent_coin_selectable() {
let ops = ops();
let ph = ops.puzzle_hash();
let alive = Coin::new(Bytes32::new([2; 32]), ph, 100);
let consumed = Coin::new(Bytes32::new([3; 32]), ph, 5_000);
let chain = FixedChain::with_records(vec![confirmed(alive), spent(consumed)]);
let request = TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 900);
let store = LocalReservations::new();
let clock = FixedClock::new(NOW);
let reservations = CoinReservations::new(&store, &clock);
clock.set(NOW + DEFAULT_RESERVATION_TTL_SECS * 10);
let error = ops
.build_transfer(&chain, &hot(), &request, &reservations)
.expect_err("the only coin big enough is already spent on chain");
assert!(
matches!(
error,
TransferError::InsufficientFunds { available: 100, .. }
),
"a spent coin is not spendable whatever the reservation table says: {error:?}"
);
}
#[test]
fn an_unreadable_reservation_store_refuses_rather_than_proceeds() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000_000]);
let request = TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 900);
let store = UnreadableReservations;
let clock = FixedClock::new(NOW);
let reservations = CoinReservations::new(&store, &clock);
let error = ops
.build_transfer(&chain, &hot(), &request, &reservations)
.expect_err("a guard that cannot be read must stop the build, not be skipped");
assert!(
matches!(error, TransferError::ReservationUnusable(_)),
"and it must say so as itself, not as a shortfall or a chain fault: {error:?}"
);
}
#[test]
fn a_store_that_cannot_be_read_refuses_even_when_it_could_be_written() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000_000]);
let request = TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 900);
let store = UnreadableButWritable(LocalReservations::new());
let clock = FixedClock::new(NOW);
let reservations = CoinReservations::new(&store, &clock);
store
.reserve_all(&[Bytes32::new([0xAB; 32])], NOW, NOW + 300)
.expect("the write path of this double genuinely works");
let error = ops
.build_transfer(&chain, &hot(), &request, &reservations)
.expect_err("what is already reserved is UNKNOWN, so selection cannot be trusted");
assert!(
matches!(error, TransferError::ReservationUnusable(_)),
"{error:?}"
);
}
#[test]
fn an_unreadable_clock_refuses_rather_than_guesses() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000_000]);
let store = LocalReservations::new();
let reservations = CoinReservations::new(&store, &UnreadableClock);
let error = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 900),
&reservations,
)
.expect_err("an unreadable clock cannot judge expiry, so it must stop the build");
assert!(
matches!(error, TransferError::ReservationUnusable(_)),
"{error:?}"
);
}
#[test]
fn a_fee_bump_is_not_blocked_by_its_own_reservation() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let store = LocalReservations::new();
let reservations = store.reservations();
let plan = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 500)
.with_fee(10),
&reservations,
)
.expect("the first build is funded");
assert!(plan.reservation().is_some(), "the control: it did reserve");
let pending = plan.pushed_at(PEAK);
let bumped = ops
.build_transfer_replacing(&chain, &hot(), &pending, 50)
.expect("a fee bump re-spends coins its own transfer already reserved");
assert_eq!(
bumped.source_coin_ids(),
plan.source_coin_ids(),
"a replacement re-spends the SAME inputs, which is what makes it a replacement"
);
assert!(
bumped.reservation().is_none(),
"and it takes no second hold on them"
);
}
#[test]
fn selection_prefers_the_smallest_single_coin_that_covers_the_transfer() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[5_000, 900, 50, 20]);
let plan = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 900),
&free(),
)
.expect("the 900 coin covers it exactly");
assert_eq!(inputs_of(&plan), vec![900]);
assert_eq!(plan.change_mojos(), 0);
}
#[test]
fn a_wallet_dusted_beyond_the_cap_can_still_spend_its_large_coin() {
let ops = ops();
let mut amounts = vec![1u64; MAX_TRANSFER_INPUT_COINS * 10];
amounts.push(1_000_000);
let chain = FixedChain::holding(ops.puzzle_hash(), &amounts);
let plan = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 600_000),
&free(),
)
.expect("one coin covers this transfer, however much dust surrounds it");
assert_eq!(inputs_of(&plan), vec![1_000_000]);
}
#[test]
fn a_transfer_no_single_coin_covers_uses_the_fewest_inputs() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[600, 500, 400, 300]);
let plan = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
&free(),
)
.expect("1_800 mojos cover 1_000");
assert_eq!(inputs_of(&plan), vec![500, 600]);
assert_eq!(plan.change_mojos(), 100);
}
#[test]
fn insufficient_funds_reports_the_whole_spendable_balance() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[100, 200, 300, 400]);
let error = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 5_000),
&free(),
)
.expect_err("1_000 mojos cannot cover 5_000");
assert!(
matches!(
error,
TransferError::InsufficientFunds {
required: 5_000,
available: 1_000
}
),
"{error}"
);
}
#[test]
fn spent_coins_are_neither_selected_nor_counted_as_available() {
let ops = ops();
let ph = ops.puzzle_hash();
let chain = FixedChain::with_records(vec![
spent(Coin::new(Bytes32::new([2; 32]), ph, 20_000)),
confirmed(Coin::new(Bytes32::new([3; 32]), ph, 5)),
]);
let error = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
&free(),
)
.expect_err("only 5 mojos are actually spendable");
assert!(
matches!(
error,
TransferError::InsufficientFunds {
required: 1_000,
available: 5
}
),
"{error}"
);
}
#[test]
fn a_shortfall_caused_by_an_unjudgeable_coin_is_reported_as_unjudgeable() {
let ops = ops();
let ph = ops.puzzle_hash();
let unknown = Coin::new(Bytes32::new([1; 32]), ph, 10_000);
let chain = FixedChain::with_records(vec![unconfirmed(unknown)]);
let error = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
&free(),
)
.expect_err("a source that cannot report a height cannot judge the balance");
assert!(
matches!(
error,
TransferError::SpendabilityUnknown { coin_id } if coin_id == unknown.coin_id()
),
"{error}"
);
}
#[test]
fn the_same_coin_with_a_confirmation_height_funds_the_transfer() {
let ops = ops();
let ph = ops.puzzle_hash();
let chain = FixedChain::with_records(vec![confirmed(Coin::new(
Bytes32::new([1; 32]),
ph,
10_000,
))]);
assert!(ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
&free(),
)
.is_ok());
}
#[test]
fn a_coin_at_a_foreign_puzzle_hash_is_excluded_without_blocking_the_transfer() {
let ops = ops();
let ph = ops.puzzle_hash();
let genuine = Coin::new(Bytes32::new([2; 32]), ph, 5_000);
let foreign = Coin::new(Bytes32::new([1; 32]), Bytes32::new([0xCA; 32]), 10_000);
let chain = FixedChain::with_records(Vec::new())
.answering_puzzle_hash_query_with(vec![confirmed(genuine), confirmed(foreign)]);
let plan = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
&free(),
)
.expect("a foreign coin must not stop a wallet spending the coins it owns");
assert_eq!(
plan.source_coin_ids(),
&[genuine.coin_id()],
"only the wallet's own coin may be spent"
);
assert_eq!(
plan.change_mojos(),
4_000,
"the change proves the spend came from the 5_000 coin, not the 10_000 foreign one"
);
}
#[test]
fn a_foreign_coin_is_not_counted_toward_the_spendable_balance() {
let ops = ops();
let ph = ops.puzzle_hash();
let chain = FixedChain::with_records(Vec::new()).answering_puzzle_hash_query_with(vec![
confirmed(Coin::new(Bytes32::new([2; 32]), ph, 5)),
confirmed(Coin::new(
Bytes32::new([1; 32]),
Bytes32::new([0xCA; 32]),
10_000,
)),
]);
let error = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
&free(),
)
.expect_err("5 spendable mojos cannot cover 1_000");
assert!(
matches!(
error,
TransferError::InsufficientFunds {
required: 1_000,
available: 5
}
),
"available must exclude the foreign coin's 10_000: {error}"
);
}
#[test]
fn a_stranger_cannot_brick_the_wallet_by_dusting_it_with_foreign_coins() {
let ops = ops();
let ph = ops.puzzle_hash();
let mut records = vec![confirmed(Coin::new(Bytes32::new([9; 32]), ph, 1_000_000))];
for seed in 0..32u8 {
records.push(confirmed(Coin::new(
Bytes32::new([seed; 32]),
Bytes32::new([seed ^ 0xFF; 32]),
1,
)));
}
let chain = FixedChain::with_records(Vec::new()).answering_puzzle_hash_query_with(records);
for attempt in 0..3 {
let plan = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
&free(),
)
.unwrap_or_else(|e| {
panic!("attempt {attempt}: dust from a stranger must never block a send: {e}")
});
assert_eq!(plan.source_coin_ids().len(), 1);
}
}
#[test]
fn an_unjudgeable_coin_does_not_block_a_wallet_that_can_afford_the_transfer() {
let ops = ops();
let ph = ops.puzzle_hash();
let genuine = Coin::new(Bytes32::new([2; 32]), ph, 5_000);
let chain = FixedChain::with_records(vec![
confirmed(genuine),
unconfirmed(Coin::new(Bytes32::new([1; 32]), ph, 10_000)),
]);
let plan = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
&free(),
)
.expect("a coin of unknown status must not block an affordable transfer");
assert_eq!(plan.source_coin_ids(), &[genuine.coin_id()]);
}
#[test]
fn a_spent_coin_with_an_unknown_height_is_skipped_rather_than_escalated() {
let ops = ops();
let ph = ops.puzzle_hash();
let chain = FixedChain::with_records(vec![
confirmed(Coin::new(Bytes32::new([2; 32]), ph, 5)),
record(
Coin::new(Bytes32::new([1; 32]), ph, 10_000),
None,
Some(PEAK),
),
]);
let error = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
&free(),
)
.expect_err("5 spendable mojos cannot cover 1_000");
assert!(
matches!(
error,
TransferError::InsufficientFunds {
required: 1_000,
available: 5
}
),
"a spent coin is not spendable whatever its height, so it must not become the story: \
{error}"
);
}
#[test]
fn two_inputs_confirmed_by_name_fund_the_transfer() {
let ops = ops();
let wallet = ops.wallet_key();
let listing = vec![
confirmed(Coin::new(Bytes32::new([1; 32]), wallet.puzzle_hash(), 600)),
confirmed(Coin::new(Bytes32::new([2; 32]), wallet.puzzle_hash(), 600)),
];
let chain = FixedChain::with_records(listing.clone())
.answering_puzzle_hash_query_with(listing.clone())
.answering_by_name_with(listing);
let plan = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
&free(),
)
.expect("both inputs agree, so the transfer must build");
assert_eq!(
inputs_of(&plan),
vec![600, 600],
"both coins must be spent when both indexes call them spendable"
);
}
#[test]
fn one_input_spent_by_name_fails_the_whole_attempt() {
let ops = ops();
let wallet = ops.wallet_key();
let honest = Coin::new(Bytes32::new([1; 32]), wallet.puzzle_hash(), 900);
let stale = Coin::new(Bytes32::new([2; 32]), wallet.puzzle_hash(), 900);
let listing = vec![confirmed(honest), confirmed(stale)];
let chain = FixedChain::with_records(listing.clone())
.answering_puzzle_hash_query_with(listing)
.answering_by_name_with(vec![confirmed(honest), spent(stale)]);
let error = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_500),
&free(),
)
.expect_err("a selected input the network calls spent must abandon the attempt");
assert!(
matches!(error, TransferError::ChainUnreachable(_)),
"a coin whose two answers disagree is UNKNOWN, not a shortfall and not a refusal: \
{error}"
);
}
#[test]
fn an_input_the_by_name_read_cannot_find_fails_the_attempt() {
let ops = ops();
let wallet = ops.wallet_key();
let honest = Coin::new(Bytes32::new([1; 32]), wallet.puzzle_hash(), 900);
let vanished = Coin::new(Bytes32::new([2; 32]), wallet.puzzle_hash(), 900);
let listing = vec![confirmed(honest), confirmed(vanished)];
let chain = FixedChain::with_records(listing.clone())
.answering_puzzle_hash_query_with(listing)
.answering_by_name_with(vec![confirmed(honest)]);
let error = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_500),
&free(),
)
.expect_err("an input the by-name read denies must abandon the attempt");
assert!(
matches!(error, TransferError::ChainUnreachable(_)),
"two answers that cannot both be true make the coin's state unknown: {error}"
);
}
#[test]
fn the_single_covering_coin_is_confirmed_by_name_too() {
let ops = ops();
let wallet = ops.wallet_key();
let only = Coin::new(Bytes32::new([1; 32]), wallet.puzzle_hash(), 5_000);
let listing = vec![confirmed(only)];
let chain = FixedChain::with_records(listing.clone())
.answering_puzzle_hash_query_with(listing)
.answering_by_name_with(vec![spent(only)]);
let error = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
&free(),
)
.expect_err("the single-coin path must confirm its coin by name as well");
assert!(
matches!(error, TransferError::ChainUnreachable(_)),
"a single stale input is the exact shape that produced a mainnet DOUBLE_SPEND: {error}"
);
}
#[test]
fn a_duplicated_coin_is_counted_once_in_the_balance() {
let ops = ops();
let wallet = ops.wallet_key();
let coin = Coin::new(Bytes32::new([1; 32]), wallet.puzzle_hash(), 1_000);
let doubled = vec![confirmed(coin), confirmed(coin)];
let chain = FixedChain::with_records(doubled.clone())
.answering_puzzle_hash_query_with(doubled.clone())
.answering_by_name_with(doubled);
let error = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_500),
&free(),
)
.expect_err("one 1000-mojo coin cannot fund 1500, however many times it is listed");
assert!(
matches!(
error,
TransferError::InsufficientFunds {
required: 1_500,
available: 1_000
}
),
"the duplicate must not inflate the balance the user is shown: {error}"
);
}
#[test]
fn a_duplicated_coin_is_never_selected_twice() {
let ops = ops();
let wallet = ops.wallet_key();
let big = Coin::new(Bytes32::new([1; 32]), wallet.puzzle_hash(), 1_000);
let small = Coin::new(Bytes32::new([2; 32]), wallet.puzzle_hash(), 400);
let listing = vec![confirmed(big), confirmed(big), confirmed(small)];
let chain = FixedChain::with_records(listing.clone())
.answering_puzzle_hash_query_with(listing.clone())
.answering_by_name_with(listing);
let plan = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_200),
&free(),
)
.expect("1000 + 400 covers 1200, so the transfer must build");
let spent_ids: Vec<Bytes32> = plan
.coin_spends()
.iter()
.map(|spend| spend.coin.coin_id())
.collect();
let unique: HashSet<Bytes32> = spent_ids.iter().copied().collect();
assert_eq!(
spent_ids.len(),
unique.len(),
"no coin may appear twice among the bundle's inputs: {spent_ids:?}"
);
assert_eq!(
inputs_of(&plan),
vec![400, 1_000],
"the second copy of the 1000 coin is not a second coin, so the 400 must be reached for"
);
}
#[test]
fn the_recipient_is_paid_exactly_and_the_change_is_exact_and_wallet_owned() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000_000]);
let plan = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 600_000)
.with_fee(1_000),
&free(),
)
.expect("builds");
let created = created_coins(plan.coin_spends());
assert_eq!(created.len(), 2, "a payment and a change coin: {created:?}");
let payment = created
.iter()
.find(|coin| coin.puzzle_hash == RECIPIENT)
.expect("the recipient is paid");
assert_eq!(payment.amount, 600_000);
assert_eq!(payment.coin_id(), plan.payment_coin_id());
let change = created
.iter()
.find(|coin| coin.puzzle_hash == ops.puzzle_hash())
.expect("the change returns to THIS wallet");
assert_eq!(
change.amount,
1_000_000 - 600_000 - 1_000,
"unspent input value silently becomes fee, so an inexact change donates the difference"
);
assert_eq!(plan.change_mojos(), change.amount);
}
#[test]
fn the_payment_coin_is_hinted_to_the_recipient() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000_000]);
let plan = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 600_000)
.with_fee(1_000),
&free(),
)
.expect("builds");
let mut allocator = Allocator::new();
let mut payment_hint: Option<Bytes32> = None;
'outer: for spend in plan.coin_spends() {
let puzzle =
node_from_bytes(&mut allocator, &spend.puzzle_reveal).expect("valid puzzle");
let solution =
node_from_bytes(&mut allocator, &spend.solution).expect("valid solution");
let output = run_puzzle(&mut allocator, puzzle, solution).expect("runs");
for condition in
Vec::<Condition>::from_clvm(&allocator, output).expect("valid conditions")
{
if let Condition::CreateCoin(create) = condition {
if create.puzzle_hash == RECIPIENT {
let Memos::Some(ptr) = create.memos else {
panic!("the payment coin must carry a hint memo");
};
let hints: Vec<Bytes32> =
Vec::from_clvm(&allocator, ptr).expect("hint is a list of Bytes32");
assert_eq!(hints.len(), 1, "exactly one hint expected");
payment_hint = Some(hints[0]);
break 'outer;
}
}
}
}
assert_eq!(
payment_hint.expect("a CREATE_COIN for RECIPIENT must exist"),
RECIPIENT,
"the hint must name the recipient, not the sender or any other puzzle hash"
);
}
#[test]
fn an_exactly_covering_selection_creates_no_change_coin() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[601_000]);
let plan = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 600_000)
.with_fee(1_000),
&free(),
)
.expect("builds");
assert_eq!(plan.change_mojos(), 0);
let created = created_coins(plan.coin_spends());
assert_eq!(created.len(), 1, "only the payment coin: {created:?}");
assert_eq!(created[0].puzzle_hash, RECIPIENT);
}
#[test]
fn a_one_mojo_remainder_is_emitted_as_a_change_coin() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[601_001]);
let plan = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 600_000)
.with_fee(1_000),
&free(),
)
.expect("builds");
assert_eq!(plan.change_mojos(), 1, "plan must report a 1-mojo change");
let created = created_coins(plan.coin_spends());
let change_coin = created
.iter()
.find(|coin| coin.puzzle_hash == ops.puzzle_hash())
.expect("a change coin of 1 mojo must be created");
assert_eq!(
change_coin.amount, 1,
"the change coin must carry the 1-mojo remainder, not lose it as fee"
);
}
#[test]
fn a_payment_to_this_wallets_own_address_is_refused_by_name() {
let ops = ops();
let own = ops.puzzle_hash();
let chain = FixedChain::holding(own, &[1_000]);
let error = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(own), 500),
&free(),
)
.expect_err("a self-payment moves nothing and would duplicate a coin id");
assert!(matches!(error, TransferError::SelfPayment), "{error}");
}
#[test]
fn no_bundle_ever_creates_two_coins_with_the_same_id() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
for amount in [1u64, 2, 499, 500, 501, 999] {
let plan = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), amount),
&free(),
)
.expect("builds");
let created = created_coins(plan.coin_spends());
let ids: HashSet<Bytes32> = created.iter().map(Coin::coin_id).collect();
assert_eq!(
ids.len(),
created.len(),
"amount {amount} produced a duplicate coin id"
);
}
}
#[test]
fn needing_more_coins_than_the_cap_is_its_own_error() {
let ops = ops();
let coins = vec![100u64; MAX_TRANSFER_INPUT_COINS + 1];
let chain = FixedChain::holding(ops.puzzle_hash(), &coins);
let error = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(
PayableDestination::from_derived(RECIPIENT),
100 * coins.len() as u64,
),
&free(),
)
.expect_err("one coin over the cap");
assert!(
matches!(
error,
TransferError::TooManyInputCoins { needed, cap }
if needed == MAX_TRANSFER_INPUT_COINS + 1 && cap == MAX_TRANSFER_INPUT_COINS
),
"{error}"
);
}
#[test]
fn a_transfer_needing_exactly_the_cap_is_still_built() {
let ops = ops();
let coins = vec![100u64; MAX_TRANSFER_INPUT_COINS];
let chain = FixedChain::holding(ops.puzzle_hash(), &coins);
let plan = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(
PayableDestination::from_derived(RECIPIENT),
100 * coins.len() as u64,
),
&free(),
)
.expect("exactly the cap is allowed");
assert_eq!(plan.coin_spends().len(), MAX_TRANSFER_INPUT_COINS);
}
#[test]
fn a_vault_profile_is_refused_with_its_own_error() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000_000]);
let error = ops
.build_transfer(
&chain,
&CustodyPolicy::Vault(Vault::default()),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 600_000),
&free(),
)
.expect_err("a vault outflow may only pay this profile's own hot wallet");
assert!(
matches!(error, TransferError::VaultTransferUnsupported),
"{error}"
);
assert!(
error.to_string().contains("vault"),
"the sentence must name the tier: {error}"
);
}
#[test]
fn the_same_request_under_the_hot_tier_is_built() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000_000]);
assert!(ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 600_000),
&free(),
)
.is_ok());
}
#[test]
fn a_fee_the_inputs_cannot_cover_is_refused() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let error = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000)
.with_fee(1),
&free(),
)
.expect_err("1_000 mojos cannot pay 1_000 plus a fee");
assert!(
matches!(
error,
TransferError::InsufficientFunds {
required: 1_001,
available: 1_000
}
),
"{error}"
);
}
#[test]
fn the_same_amount_with_no_fee_is_built() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
assert!(ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
&free(),
)
.is_ok());
}
#[test]
fn a_zero_amount_transfer_is_refused() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let error = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 0),
&free(),
)
.expect_err("a transfer moves a positive amount");
assert!(matches!(error, TransferError::ZeroAmount), "{error}");
}
#[test]
fn an_amount_plus_fee_that_overflows_is_refused() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let error = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), u64::MAX)
.with_fee(1),
&free(),
)
.expect_err("u64::MAX + 1 is not a spendable total");
assert!(
matches!(error, TransferError::AmountOverflow { .. }),
"{error}"
);
}
#[test]
fn an_unreachable_chain_is_not_reported_as_a_shortfall() {
let ops = ops();
let error = ops
.build_transfer(
&FixedChain::offline(),
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
&free(),
)
.expect_err("an unanswerable chain is not an empty wallet");
assert!(
matches!(error, TransferError::ChainUnreachable(_)),
"{error}"
);
}
#[test]
fn an_undecodable_recipient_address_is_refused() {
let error = TransferRequest::to_address("not-an-address", 1_000)
.expect_err("a malformed address has no destination");
assert!(
matches!(error, TransferError::InvalidRecipient { .. }),
"{error}"
);
}
#[test]
fn a_well_formed_address_with_a_non_xch_prefix_is_refused_by_prefix() {
for prefix in ["nft", "txch", "did:chia", "cat", "totally-bogus"] {
let encoded = Address::new(RECIPIENT, prefix.to_string())
.encode()
.expect("a 32-byte payload encodes under any prefix");
assert_eq!(
Address::decode(&encoded).expect("it decodes").puzzle_hash,
RECIPIENT,
"{prefix} must be a decodable address, or this case proves nothing"
);
let error = TransferRequest::to_address(&encoded, 1_000)
.expect_err("paying the puzzle hash inside a non-payment address burns the funds");
match &error {
TransferError::InvalidRecipient { reason, .. } => assert!(
reason.contains(prefix),
"the refusal must name the prefix the user actually pasted: {reason}"
),
other => panic!("{prefix}: {other}"),
}
}
}
#[test]
fn a_spendable_balance_that_overflows_u64_is_refused_rather_than_clamped() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[u64::MAX, u64::MAX]);
let error = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
&free(),
)
.expect_err("a balance past u64 cannot be judged");
assert!(
matches!(error, TransferError::BalanceUnjudgeable),
"{error}"
);
}
#[test]
fn the_checked_and_vouched_destinations_agree_on_a_real_xch_address() {
let address = Address::new(RECIPIENT, MAINNET_ADDRESS_PREFIX.to_string())
.encode()
.expect("encodes");
let checked = PayableDestination::from_address(&address).expect("an xch address");
let vouched = PayableDestination::from_derived(RECIPIENT);
assert_eq!(checked, vouched);
assert_eq!(checked.puzzle_hash(), RECIPIENT);
}
#[test]
fn a_payable_destination_refuses_every_non_xch_prefix() {
for prefix in ["nft", "txch", "did:chia", "cat", "totally-bogus"] {
let encoded = Address::new(RECIPIENT, prefix.to_string())
.encode()
.expect("a 32-byte payload encodes under any prefix");
assert_eq!(
Address::decode(&encoded).expect("it decodes").puzzle_hash,
RECIPIENT,
"{prefix} must be a decodable address, or this case proves nothing"
);
let error = PayableDestination::from_address(&encoded)
.expect_err("paying the puzzle hash inside a non-payment address burns the funds");
match &error {
TransferError::InvalidRecipient { reason, .. } => assert!(
reason.contains(prefix),
"the refusal must name the prefix the user actually pasted: {reason}"
),
other => panic!("{prefix}: {other}"),
}
assert!(TransferRequest::to_address(&encoded, 1_000).is_err());
}
}
#[test]
fn a_valid_address_decodes_to_its_puzzle_hash() {
let address = Address::new(RECIPIENT, "xch".to_string()).encode().unwrap();
let request = TransferRequest::to_address(&address, 42).expect("a valid address");
assert_eq!(request.recipient(), RECIPIENT);
assert_eq!(request.amount_mojos(), 42);
assert_eq!(request.fee_mojos(), 0);
}
#[test]
fn the_wallets_displayed_address_is_one_the_transfer_builder_will_pay() {
let ops = ops();
let displayed = ops
.wallet_key()
.address()
.expect("the wallet renders its own receive address");
let request = TransferRequest::to_address(&displayed, 42)
.expect("an address this crate displays must be one it will pay");
assert_eq!(
request.recipient(),
ops.puzzle_hash(),
"the payment path must recover the puzzle hash the display path encoded"
);
assert!(
displayed.starts_with(MAINNET_ADDRESS_PREFIX),
"the displayed address must bear the one prefix: {displayed}"
);
}
#[test]
fn pushed_now_anchors_to_the_chains_own_peak() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000]).at_peak(PEAK + 42);
let plan = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 600),
&free(),
)
.expect("builds");
let pending = plan.pushed_now(&chain).expect("the chain reports a peak");
assert_eq!(pending.pushed_at_height(), PEAK + 42);
}
#[test]
fn pushed_now_refuses_when_the_chain_has_no_peak() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let plan = ops
.build_transfer(
&source,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 600),
&free(),
)
.expect("builds");
let error = plan
.pushed_now(&source.without_peak())
.expect_err("no peak, no anchor");
assert!(
matches!(error, TransferError::ChainUnreachable(_)),
"{error}"
);
}
#[test]
fn a_naive_fee_bump_can_select_a_different_lead_and_pay_twice() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000, 1_200]);
let original = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
&free(),
)
.expect("builds");
let naive_retry = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000)
.with_fee(100),
&free(),
)
.expect("builds");
assert_ne!(
original.source_coin_ids(),
naive_retry.source_coin_ids(),
"the fee bump must cross a coin boundary, or this fixture proves nothing"
);
assert_ne!(
original.payment_coin_id(),
naive_retry.payment_coin_id(),
"disjoint inputs mean two payment coins, so BOTH bundles can confirm"
);
}
#[test]
fn a_replacement_reuses_the_exact_inputs_and_keeps_the_payment_coin_id() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_500, 5_000]);
let original = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
&free(),
)
.expect("builds");
let pending = original.pushed_at(PEAK);
let replacement = ops
.build_transfer_replacing(&chain, &hot(), &pending, 100)
.expect("a higher fee over the same inputs");
assert_eq!(
replacement.source_coin_ids(),
original.source_coin_ids(),
"a replacement must re-spend exactly the coins the original spends"
);
assert_eq!(
replacement.payment_coin_id(),
original.payment_coin_id(),
"the same lead yields the same payment coin, so the pending record still applies"
);
assert_eq!(replacement.fee_mojos(), 100);
assert_eq!(replacement.amount_mojos(), original.amount_mojos());
assert_eq!(replacement.recipient(), original.recipient());
assert_eq!(
replacement.change_mojos(),
original.change_mojos() - 100,
"the extra fee comes out of the change, never out of the recipient"
);
}
#[test]
fn a_replacement_the_reused_inputs_cannot_cover_is_refused_by_its_own_name() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000, 1_200]);
let pending = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
&free(),
)
.expect("builds")
.pushed_at(PEAK);
let error = ops
.build_transfer_replacing(&chain, &hot(), &pending, 100)
.expect_err("an exactly-consumed input has no headroom for a bigger fee");
assert!(
matches!(
error,
TransferError::ReplacementInputsInsufficient {
required: 1_100,
reused_total: 1_000
}
),
"{error}"
);
}
#[test]
fn a_wealthy_wallet_is_refused_with_the_reused_total_not_its_balance() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000, 10_000_000]);
let pending = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
&free(),
)
.expect("builds")
.pushed_at(PEAK);
assert_eq!(
pending.source_coin_ids().len(),
1,
"the transfer must rest on the SMALL coin, or the gap this test needs does not exist"
);
let error = ops
.build_transfer_replacing(&chain, &hot(), &pending, 500)
.expect_err("the 1_000 input cannot cover 1_500");
match error {
TransferError::ReplacementInputsInsufficient {
required,
reused_total,
} => {
assert_eq!(required, 1_500);
assert_eq!(
reused_total, 1_000,
"the figure must be the reused inputs' total, never the 10_001_000 balance"
);
}
other => panic!("a replacement shortfall must not borrow the balance variant: {other}"),
}
}
#[test]
fn a_replacement_the_reused_inputs_can_cover_is_built() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_500, 10_000_000]);
let pending = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
&free(),
)
.expect("builds")
.pushed_at(PEAK);
let replacement = ops
.build_transfer_replacing(&chain, &hot(), &pending, 400)
.expect("1_400 fits inside the 1_500 input");
assert_eq!(replacement.fee_mojos(), 400);
assert_eq!(replacement.change_mojos(), 100);
}
#[test]
fn a_replacement_fee_that_does_not_outbid_is_refused_by_name() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[10_000]);
let pending = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000)
.with_fee(50),
&free(),
)
.expect("builds")
.pushed_at(PEAK);
for proposed in [0u64, 49, 50] {
let error = ops
.build_transfer_replacing(&chain, &hot(), &pending, proposed)
.expect_err("a replacement must outbid the transfer it replaces");
assert!(
matches!(
error,
TransferError::ReplacementFeeNotHigher { current: 50, proposed: p } if p == proposed
),
"{error}"
);
}
}
#[test]
fn a_replacement_fee_one_mojo_higher_is_accepted() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[10_000]);
let pending = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000)
.with_fee(50),
&free(),
)
.expect("builds")
.pushed_at(PEAK);
let replacement = ops
.build_transfer_replacing(&chain, &hot(), &pending, 51)
.expect("one mojo more is a higher bid");
assert_eq!(replacement.fee_mojos(), 51);
}
#[test]
fn a_replacement_over_a_spent_input_is_refused_by_name() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[10_000]);
let original = ops
.build_transfer(
&source,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000)
.with_fee(50),
&free(),
)
.expect("builds");
let pending = original.pushed_at(PEAK);
let input = source.records[0].coin;
let consumed = FixedChain::with_records(vec![spent(input)]);
let error = ops
.build_transfer_replacing(&consumed, &hot(), &pending, 100)
.expect_err("a spent input cannot be re-spent");
assert!(
matches!(
error,
TransferError::SourcesNoLongerSpendable { coin_id } if coin_id == input.coin_id()
),
"{error}"
);
let absent = FixedChain::with_records(Vec::new());
let error = ops
.build_transfer_replacing(&absent, &hot(), &pending, 100)
.expect_err("an input the source no longer reports cannot be re-spent");
assert!(
matches!(
error,
TransferError::SourcesNoLongerSpendable { coin_id } if coin_id == input.coin_id()
),
"{error}"
);
}
#[test]
fn a_replacement_over_a_still_spendable_input_builds() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[10_000]);
let pending = ops
.build_transfer(
&source,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000)
.with_fee(50),
&free(),
)
.expect("builds")
.pushed_at(PEAK);
assert!(ops
.build_transfer_replacing(&source, &hot(), &pending, 100)
.is_ok());
}
#[test]
fn a_replacement_refuses_a_record_for_a_different_coin() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[10_000]);
let pending = ops
.build_transfer(
&source,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000)
.with_fee(50),
&free(),
)
.expect("builds")
.pushed_at(PEAK);
let impostor = confirmed(Coin::new(
Bytes32::new([0xAB; 32]),
ops.puzzle_hash(),
10_000,
));
let chain = FixedChain::with_records(Vec::new()).answering_every_query_with(impostor);
let error = ops
.build_transfer_replacing(&chain, &hot(), &pending, 100)
.expect_err("a record about another coin answers nothing about this input");
assert!(
matches!(error, TransferError::ChainUnreachable(_)),
"{error}"
);
}
#[test]
fn a_vault_profile_cannot_build_a_replacement() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[10_000]);
let pending = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000)
.with_fee(50),
&free(),
)
.expect("builds")
.pushed_at(PEAK);
let error = ops
.build_transfer_replacing(
&chain,
&CustodyPolicy::Vault(Vault::default()),
&pending,
100,
)
.expect_err("a vault profile cannot pay a third party by any route");
assert!(
matches!(error, TransferError::VaultTransferUnsupported),
"{error}"
);
}
#[test]
fn no_replacement_refusal_ever_advises_building_another_transfer() {
let ops = ops();
let wallet = FixedChain::holding(ops.puzzle_hash(), &[1_000, 10_000_000]);
let exact = ops
.build_transfer(
&wallet,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000),
&free(),
)
.expect("builds")
.pushed_at(PEAK);
let funded = ops
.build_transfer(
&wallet,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 500)
.with_fee(50),
&free(),
)
.expect("builds")
.pushed_at(PEAK);
let consumed = FixedChain::with_records(vec![spent(wallet.records[0].coin)]);
let refusals = [
ops.build_transfer_replacing(&wallet, &hot(), &exact, 100),
ops.build_transfer_replacing(&wallet, &hot(), &funded, 50),
ops.build_transfer_replacing(&consumed, &hot(), &exact, 100),
ops.build_transfer_replacing(
&wallet,
&CustodyPolicy::Vault(Vault::default()),
&exact,
100,
),
];
for refusal in refusals {
let error = refusal.expect_err("each fixture must actually refuse");
let rendered = error.to_string().to_lowercase();
if let Some(forbidden) = forbidden_advice_in(&rendered) {
panic!(
"{error:?} tells the user to {forbidden:?}, which is the action that pays the \
recipient twice: {rendered}"
);
}
}
}
const REBUILD_INSTRUCTIONS: [&str; 6] = [
"build another transfer",
"build a new transfer",
"send another transfer",
"send it again",
"try again",
"a fresh transfer",
];
fn forbidden_advice_in(rendered: &str) -> Option<&'static str> {
REBUILD_INSTRUCTIONS
.into_iter()
.find(|forbidden| rendered.contains(forbidden))
}
#[test]
fn the_forbidden_advice_check_detects_every_instruction_it_screens_for() {
for instruction in REBUILD_INSTRUCTIONS {
let rendered = format!("this transfer cannot be sped up; {instruction} instead");
assert_eq!(
forbidden_advice_in(&rendered),
Some(instruction),
"the screen must catch {instruction:?}, or the invariant is measuring nothing"
);
}
}
#[test]
fn the_forbidden_advice_check_does_not_fire_on_a_warning() {
let rendered = TransferError::ReplacementInputsInsufficient {
required: 1_100,
reused_total: 1_000,
}
.to_string()
.to_lowercase();
assert_eq!(forbidden_advice_in(&rendered), None, "{rendered}");
assert!(
rendered.contains("wait for it to confirm"),
"the refusal must still give the one always-correct instruction: {rendered}"
);
}
#[test]
fn the_replacement_fee_ceiling_is_the_original_fee_plus_its_change() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_500, 10_000_000]);
let with_change = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_000)
.with_fee(50),
&free(),
)
.expect("builds")
.pushed_at(PEAK);
assert_eq!(with_change.change_mojos(), 450);
assert_eq!(with_change.input_total_mojos(), 1_500);
assert_eq!(with_change.max_replacement_fee_mojos(), 500);
assert!(ops
.build_transfer_replacing(&chain, &hot(), &with_change, 500)
.is_ok());
assert!(matches!(
ops.build_transfer_replacing(&chain, &hot(), &with_change, 501),
Err(TransferError::ReplacementInputsInsufficient { .. })
));
let exact = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 1_500),
&free(),
)
.expect("builds")
.pushed_at(PEAK);
assert_eq!(exact.change_mojos(), 0);
assert_eq!(
exact.max_replacement_fee_mojos(),
exact.fee_mojos(),
"a ceiling equal to the current fee means no bump is possible, and the control must be \
disabled rather than merely capped"
);
}
#[test]
fn every_secondary_input_is_bound_to_the_lead() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[100, 200, 300]);
let plan = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 550),
&free(),
)
.expect("builds");
let conditions = conditions_of(plan.coin_spends());
let lead_id = conditions
.iter()
.find_map(|(coin_id, condition)| {
matches!(condition, Condition::CreateCoinAnnouncement(_)).then_some(*coin_id)
})
.expect("the lead announces");
let expected = chia_wallet_sdk::types::announcement_id(lead_id, INPUT_BINDING_MESSAGE);
let asserting: Vec<Bytes32> = conditions
.iter()
.filter_map(|(coin_id, condition)| match condition {
Condition::AssertCoinAnnouncement(assertion) => {
assert_eq!(assertion.announcement_id, expected);
Some(*coin_id)
}
_ => None,
})
.collect();
assert_eq!(
asserting.len(),
2,
"both secondary inputs must be bound to the lead"
);
assert!(!asserting.contains(&lead_id));
}
#[test]
fn an_orphaned_secondary_input_is_refused_by_consensus_even_when_correctly_signed() {
use chia_bls::Signature;
use chia_consensus::validation_error::ErrorCode;
use chia_sdk_test::{Simulator, SimulatorError};
use chia_wallet_sdk::prelude::TESTNET11_CONSTANTS;
use chia_wallet_sdk::signer::{AggSigConstants, RequiredSignature};
fn sign(wallet: &WalletKey, coin_spends: &[CoinSpend]) -> Signature {
let constants = AggSigConstants::from(&*TESTNET11_CONSTANTS);
let mut allocator = Allocator::new();
let required =
RequiredSignature::from_coin_spends(&mut allocator, coin_spends, &constants)
.expect("required signatures");
let mut aggregate = Signature::default();
for requirement in required {
let RequiredSignature::Bls(bls) = requirement else {
panic!("a standard-layer send never requires a secp signature");
};
aggregate += &chia_bls::sign(wallet.secret_key(), bls.message());
}
aggregate
}
let ops = ops();
let wallet = ops.wallet_key();
let mut sim = Simulator::new();
let coins: Vec<Coin> = (0..4)
.map(|_| sim.new_coin(wallet.puzzle_hash(), 200_000))
.collect();
sim.create_block();
let chain =
FixedChain::with_records(coins.iter().copied().map(confirmed).collect::<Vec<_>>());
let plan = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 700_000)
.with_fee(1_000),
&free(),
)
.expect("builds");
assert!(
plan.coin_spends().len() > 1,
"the fixture must actually exercise secondary inputs"
);
let lead_id = plan
.coin_spends()
.iter()
.find(|spend| {
Coin::new(spend.coin.coin_id(), RECIPIENT, 700_000).coin_id()
== plan.payment_coin_id()
})
.map(|spend| spend.coin.coin_id())
.expect("one spend creates the payment coin");
let orphans: Vec<CoinSpend> = plan
.coin_spends()
.iter()
.filter(|spend| spend.coin.coin_id() != lead_id)
.cloned()
.collect();
assert!(!orphans.is_empty());
let orphan_signature = sign(&wallet, &orphans);
let refused = sim.new_transaction(chia_protocol::SpendBundle::new(
orphans.clone(),
orphan_signature.clone(),
));
match refused {
Err(SimulatorError::Validation(ErrorCode::AssertCoinAnnouncementFailed)) => {}
other => panic!(
"the orphaned subset must be refused for the UNSATISFIED ANNOUNCEMENT specifically, not for some other reason that would hide a missing binding: {other:?}"
),
}
let whole = plan.coin_spends().to_vec();
let signature = sign(&wallet, &whole);
sim.new_transaction(chia_protocol::SpendBundle::new(whole, signature))
.expect(
"the complete bundle is valid, so the refusal above was about the missing lead",
);
}
#[test]
fn a_single_input_transfer_carries_no_binding() {
let ops = ops();
let chain = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let plan = ops
.build_transfer(
&chain,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 500),
&free(),
)
.expect("builds");
assert!(conditions_of(plan.coin_spends())
.iter()
.all(|(_, condition)| !matches!(condition, Condition::CreateCoinAnnouncement(_))));
}
fn pending_and_payment(ops: &WalletOps, source: &FixedChain) -> (PendingTransfer, Coin) {
let plan = ops
.build_transfer(
source,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 600),
&free(),
)
.expect("builds");
let payment = created_coins(plan.coin_spends())
.into_iter()
.find(|coin| coin.puzzle_hash == RECIPIENT)
.expect("the recipient is paid");
assert_eq!(payment.coin_id(), plan.payment_coin_id());
(plan.pushed_at(PEAK), payment)
}
#[test]
fn a_buried_payment_coin_is_confirmed_evidence() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let (pending, payment) = pending_and_payment(&ops, &source);
let chain = FixedChain::with_records(vec![record(payment, Some(PEAK + 1), None)])
.at_peak(PEAK + MIN_CONFIRMATION_DEPTH);
let settled = transfer_status(&pending, &chain)
.expect("readable")
.confirmed()
.cloned()
.expect("a buried payment is settled");
assert_eq!(settled.recipient(), RECIPIENT);
assert_eq!(settled.amount_mojos(), 600);
assert_eq!(settled.confirmed_height(), PEAK + 1);
assert_eq!(settled.payment_coin_id(), payment.coin_id());
}
#[test]
fn a_confirmed_record_for_a_different_coin_is_not_this_transfers_evidence() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let (pending, payment) = pending_and_payment(&ops, &source);
let impostor = Coin::new(
Bytes32::new([0xAB; 32]),
payment.puzzle_hash,
payment.amount,
);
assert_ne!(
impostor.coin_id(),
pending.payment_coin_id(),
"the impostor must be a different coin, or this test proves nothing"
);
let chain = FixedChain::with_records(Vec::new())
.at_peak(PEAK + MIN_CONFIRMATION_DEPTH)
.answering_every_query_with(record(impostor, Some(PEAK + 1), None));
assert_eq!(
transfer_status(&pending, &chain).expect("readable"),
TransferStatus::Awaiting {
blocks_since_push: MIN_CONFIRMATION_DEPTH
},
"a record about some other coin says nothing about this payment"
);
}
#[test]
fn the_same_double_answering_with_the_correct_coin_is_confirmed() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let (pending, payment) = pending_and_payment(&ops, &source);
let chain = FixedChain::with_records(Vec::new())
.at_peak(PEAK + MIN_CONFIRMATION_DEPTH)
.answering_every_query_with(record(payment, Some(PEAK + 1), None));
let settled = transfer_status(&pending, &chain)
.expect("readable")
.confirmed()
.cloned()
.expect("the correct coin, buried, IS the payment");
assert_eq!(settled.payment_coin_id(), pending.payment_coin_id());
assert_eq!(settled.recipient(), RECIPIENT);
assert_eq!(settled.amount_mojos(), 600);
}
#[test]
fn a_shallow_confirmation_is_not_yet_settled() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let (pending, payment) = pending_and_payment(&ops, &source);
let chain =
FixedChain::with_records(vec![record(payment, Some(PEAK + 1), None)]).at_peak(PEAK + 1);
assert!(matches!(
transfer_status(&pending, &chain).expect("readable"),
TransferStatus::Awaiting { .. }
));
}
#[test]
fn a_payment_coin_observed_without_a_confirmed_height_is_not_evidence() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let (pending, payment) = pending_and_payment(&ops, &source);
let chain = FixedChain::with_records(vec![record(payment, None, None)])
.at_peak(PEAK + MIN_CONFIRMATION_DEPTH * 10);
assert!(
matches!(
transfer_status(&pending, &chain).expect("readable"),
TransferStatus::Awaiting { .. }
),
"a mempool observation is not a confirmation, however deep the chain has since gone"
);
}
#[test]
fn a_confirmation_predating_the_push_is_not_evidence() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let (pending, payment) = pending_and_payment(&ops, &source);
let chain = FixedChain::with_records(vec![record(payment, Some(PEAK - 1), None)])
.at_peak(PEAK + MIN_CONFIRMATION_DEPTH);
assert!(matches!(
transfer_status(&pending, &chain).expect("readable"),
TransferStatus::Awaiting { .. }
));
}
#[test]
fn a_payment_coin_confirmed_at_genesis_height_is_not_evidence() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let plan = ops
.build_transfer(
&source,
&hot(),
&TransferRequest::new(PayableDestination::from_derived(RECIPIENT), 600),
&free(),
)
.expect("builds");
let payment = created_coins(plan.coin_spends())
.into_iter()
.find(|coin| coin.puzzle_hash == RECIPIENT)
.expect("recipient is paid");
let pending = plan.pushed_at(0);
let chain = FixedChain::with_records(vec![record(payment, Some(0), None)])
.at_peak(MIN_CONFIRMATION_DEPTH);
assert!(
matches!(
transfer_status(&pending, &chain).expect("readable"),
TransferStatus::Awaiting { .. }
),
"a genesis-height confirmation must not be accepted"
);
let chain_at_one = FixedChain::with_records(vec![record(payment, Some(1), None)])
.at_peak(MIN_CONFIRMATION_DEPTH);
assert!(
matches!(
transfer_status(&pending, &chain_at_one).expect("readable"),
TransferStatus::Confirmed(_)
),
"the same fixture at height 1 must confirm"
);
}
#[test]
fn the_confirmation_depth_bound_holds_from_both_sides() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let (pending, payment) = pending_and_payment(&ops, &source);
let confirmed_at = PEAK + 1;
let at_bound = FixedChain::with_records(vec![record(payment, Some(confirmed_at), None)])
.at_peak(confirmed_at + MIN_CONFIRMATION_DEPTH - 1);
assert!(
transfer_status(&pending, &at_bound)
.expect("readable")
.confirmed()
.is_some(),
"exactly MIN_CONFIRMATION_DEPTH blocks of burial must be enough"
);
let one_under = FixedChain::with_records(vec![record(payment, Some(confirmed_at), None)])
.at_peak(confirmed_at + MIN_CONFIRMATION_DEPTH - 2);
assert!(
matches!(
transfer_status(&pending, &one_under).expect("readable"),
TransferStatus::Awaiting { .. }
),
"one block short of the bound must not be treated as settled"
);
}
#[test]
fn a_confirmation_at_exactly_the_pre_push_peak_is_accepted() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let (pending, payment) = pending_and_payment(&ops, &source);
assert_eq!(
pending.pushed_at_height(),
PEAK,
"the fixture pins the boundary"
);
let chain = FixedChain::with_records(vec![record(payment, Some(PEAK), None)])
.at_peak(PEAK + MIN_CONFIRMATION_DEPTH);
assert!(
transfer_status(&pending, &chain)
.expect("readable")
.confirmed()
.is_some(),
"the first block that can contain the bundle carries the pre-push peak's own height"
);
}
#[test]
fn a_source_coin_spent_elsewhere_is_a_failure_not_a_wait() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let (pending, _) = pending_and_payment(&ops, &source);
let chain = FixedChain::with_records(vec![spent(source.records[0].coin)]);
assert!(
matches!(
transfer_status(&pending, &chain).expect("readable"),
TransferStatus::Failed { .. }
),
"a consumed input can never confirm"
);
}
#[test]
fn a_shallow_competing_spend_is_not_yet_a_proof_of_death() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let (pending, _) = pending_and_payment(&ops, &source);
let input = source.records[0].coin;
let spent_at = PEAK;
let chain = FixedChain::with_records(vec![record(input, Some(PEAK - 100), Some(spent_at))])
.at_peak(spent_at + MIN_CONFIRMATION_DEPTH - 2);
assert!(
matches!(
transfer_status(&pending, &chain).expect("readable"),
TransferStatus::Awaiting { .. }
),
"one block short of the bound must not be reported as dead"
);
}
#[test]
fn a_competing_spend_buried_to_the_bound_is_a_proof_of_death() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let (pending, _) = pending_and_payment(&ops, &source);
let input = source.records[0].coin;
let spent_at = PEAK;
let chain = FixedChain::with_records(vec![record(input, Some(PEAK - 100), Some(spent_at))])
.at_peak(spent_at + MIN_CONFIRMATION_DEPTH - 1);
assert!(
matches!(
transfer_status(&pending, &chain).expect("readable"),
TransferStatus::Failed { .. }
),
"exactly MIN_CONFIRMATION_DEPTH blocks of burial is enough to declare death"
);
}
#[test]
fn a_source_coin_spent_at_genesis_is_not_a_proof_of_death() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let (pending, _) = pending_and_payment(&ops, &source);
let input = source.records[0].coin;
let chain = FixedChain::with_records(vec![record(input, Some(PEAK - 100), Some(0))])
.at_peak(PEAK + MIN_CONFIRMATION_DEPTH);
assert!(
matches!(
transfer_status(&pending, &chain).expect("readable"),
TransferStatus::Awaiting { .. }
),
"a spend the chain could not have recorded must not be the evidence that kills a transfer"
);
}
#[test]
fn a_source_coin_spent_at_the_first_real_height_is_a_proof_of_death() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let (pending, _) = pending_and_payment(&ops, &source);
let input = source.records[0].coin;
let chain = FixedChain::with_records(vec![record(input, Some(PEAK - 100), Some(1))])
.at_peak(PEAK + MIN_CONFIRMATION_DEPTH);
assert!(matches!(
transfer_status(&pending, &chain).expect("readable"),
TransferStatus::Failed { .. }
));
}
#[test]
fn a_payment_coin_absent_on_the_first_read_and_present_on_the_second_is_not_a_failure() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let (pending, payment) = pending_and_payment(&ops, &source);
let chain = FlickeringChain {
payment: record(payment, Some(PEAK + 1), None),
other: vec![spent(source.records[0].coin)],
payment_reads: Cell::new(0),
peak: PEAK + 1,
vanishing: false,
};
let status = transfer_status(&pending, &chain).expect("readable");
assert!(
!matches!(status, TransferStatus::Failed { .. }),
"a payment coin that ANY read reports must not be called never-includable: {status:?}"
);
assert!(
chain.payment_reads.get() >= 2,
"the conclusion must rest on a read taken after the spent-source observation"
);
}
#[test]
fn a_payment_coin_absent_on_every_read_is_still_a_failure() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let (pending, payment) = pending_and_payment(&ops, &source);
let chain = FlickeringChain {
payment: record(payment, Some(PEAK + 1), None),
other: vec![spent(source.records[0].coin)],
payment_reads: Cell::new(usize::MAX),
peak: PEAK + 1,
vanishing: false,
};
assert!(matches!(
transfer_status(&pending, &chain).expect("readable"),
TransferStatus::Failed { .. }
));
}
#[test]
fn a_payment_coin_seen_on_the_first_read_is_never_a_failure() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let (pending, payment) = pending_and_payment(&ops, &source);
let input = source.records[0].coin;
let chain = FlickeringChain {
payment: record(payment, Some(PEAK + 1), None),
other: vec![record(input, Some(PEAK - 100), Some(PEAK - 50))],
payment_reads: Cell::new(0),
peak: PEAK,
vanishing: true,
};
let status = transfer_status(&pending, &chain).expect("readable");
assert!(
!matches!(status, TransferStatus::Failed { .. }),
"a payment coin this source has already reported must not become a death: {status:?}"
);
}
#[test]
fn the_same_fixture_with_the_payment_never_seen_is_a_failure() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let (pending, payment) = pending_and_payment(&ops, &source);
let input = source.records[0].coin;
let chain = FlickeringChain {
payment: record(payment, Some(PEAK + 1), None),
other: vec![record(input, Some(PEAK - 100), Some(PEAK - 50))],
payment_reads: Cell::new(usize::MAX),
peak: PEAK,
vanishing: false,
};
assert!(matches!(
transfer_status(&pending, &chain).expect("readable"),
TransferStatus::Failed { .. }
));
}
struct FlickeringChain {
payment: CoinRecord,
other: Vec<CoinRecord>,
payment_reads: Cell<usize>,
peak: u32,
vanishing: bool,
}
impl ChainSource for FlickeringChain {
type Error = String;
fn coin_record(&self, coin_id: Bytes32) -> std::result::Result<Option<CoinRecord>, String> {
if coin_id == self.payment.coin.coin_id() {
let seen = self.payment_reads.get();
self.payment_reads.set(seen.saturating_add(1));
let present = if self.vanishing {
seen == 0
} else {
seen > 0 && seen != usize::MAX
};
return Ok(present.then(|| self.payment.clone()));
}
Ok(self
.other
.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(Vec::new())
}
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(self.peak))
}
fn block_timestamp(&self, _height: u32) -> std::result::Result<Option<u64>, String> {
Ok(None)
}
}
#[test]
fn an_unreachable_chain_makes_the_status_unknown() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let (pending, _) = pending_and_payment(&ops, &source);
let error = transfer_status(&pending, &FixedChain::offline())
.expect_err("an unanswerable chain yields no status");
assert!(
matches!(error, TransferError::ChainUnreachable(_)),
"{error}"
);
}
#[test]
fn a_source_without_a_peak_fails_closed() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let (pending, _) = pending_and_payment(&ops, &source);
let error =
transfer_status(&pending, &source.without_peak()).expect_err("no peak, no bound");
assert!(
matches!(error, TransferError::ChainUnreachable(_)),
"{error}"
);
}
#[test]
fn a_transfer_still_in_flight_reports_the_blocks_elapsed_since_the_push() {
let ops = ops();
let source = FixedChain::holding(ops.puzzle_hash(), &[1_000]);
let (pending, _) = pending_and_payment(&ops, &source);
let chain =
FixedChain::with_records(vec![confirmed(source.records[0].coin)]).at_peak(PEAK + 9);
assert_eq!(
transfer_status(&pending, &chain).expect("readable"),
TransferStatus::Awaiting {
blocks_since_push: 9
}
);
}
}