use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
use chia_protocol::{Bytes32, CoinSpend};
use chia_wallet_sdk::utils::Address;
use crate::error::{AccountError, Result};
use crate::id::ProfileIx;
use crate::wallet::approval::{PendingApproval, SpendApproval, SpendRuling};
use crate::wallet::autosend::{AutoSendPolicy, SpendOpClass, MAX_LEDGER_ENTRIES};
use crate::wallet::clock::Clock;
use crate::wallet::policy::{CustodyPolicy, CustodyScope};
use crate::wallet::summary::{DerivedSpend, SpendDestination, SpendSummary, SpendTier};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct AutoSendRecord {
at_unix: u64,
mojos: u64,
}
#[derive(Debug)]
pub struct PolicyAuthorizer {
custody: CustodyPolicy,
auto_send: AutoSendPolicy,
hot_wallet_puzzle_hash: Bytes32,
scope: CustodyScope,
clock: Arc<dyn Clock>,
recent: Mutex<VecDeque<AutoSendRecord>>,
prompts: Mutex<VecDeque<u64>>,
}
impl PolicyAuthorizer {
pub fn new(
profile: ProfileIx,
custody: CustodyPolicy,
auto_send: AutoSendPolicy,
hot_wallet_address: &str,
clock: Arc<dyn Clock>,
) -> Result<Self> {
let hot_wallet = Address::decode(hot_wallet_address).map_err(|e| {
AccountError::PolicyIndeterminate(format!(
"hot-wallet address {hot_wallet_address:?} is not a valid address: {e}"
))
})?;
Ok(Self {
scope: CustodyScope::new(profile, &custody, hot_wallet.puzzle_hash),
custody,
auto_send,
hot_wallet_puzzle_hash: hot_wallet.puzzle_hash,
clock,
recent: Mutex::new(VecDeque::new()),
prompts: Mutex::new(VecDeque::new()),
})
}
pub fn authorize_op(
&self,
coin_spends: &[CoinSpend],
op_class: SpendOpClass,
) -> Result<SpendRuling> {
let derived = DerivedSpend::derive(coin_spends, &self.custody)?;
match derived.summary.tier {
SpendTier::Vault => {
self.reject_vault_outflow_to_anyone_but_the_hot_wallet(&derived.summary)?;
self.escalate(coin_spends, derived)
}
SpendTier::Confirm => self.escalate(coin_spends, derived),
SpendTier::AutoSend => self.rule_on_auto_send(coin_spends, derived, op_class),
}
}
fn reject_vault_outflow_to_anyone_but_the_hot_wallet(
&self,
summary: &SpendSummary,
) -> Result<()> {
for recipient in &summary.recipients {
if recipient.destination == SpendDestination::ProtocolStructure {
return Err(AccountError::PolicyDenied(format!(
"a vault spend may only pay this profile's own hot wallet, but this one commits \
value to {}; move the funds vault -> hot wallet through the 24h clawback \
window first",
recipient.address
)));
}
let address = Address::decode(&recipient.address).map_err(|e| {
AccountError::PolicyIndeterminate(format!(
"a vault spend pays {:?}, which is not a decodable address ({e}), so it cannot \
be proven to be the hot wallet",
recipient.address
))
})?;
if address.puzzle_hash != self.hot_wallet_puzzle_hash {
return Err(AccountError::PolicyDenied(format!(
"a vault spend may only pay this profile's own hot wallet, but this one pays \
{}; move the funds vault -> hot wallet through the 24h clawback window first",
recipient.address
)));
}
}
Ok(())
}
fn rule_on_auto_send(
&self,
coin_spends: &[CoinSpend],
derived: DerivedSpend,
op_class: SpendOpClass,
) -> Result<SpendRuling> {
if !self.auto_send.enabled {
return self.escalate(coin_spends, derived);
}
let Some(limits) = self.auto_send.configured_limits(op_class) else {
return self.escalate(coin_spends, derived);
};
if !limits.enabled {
return self.escalate(coin_spends, derived);
}
self.reject_amounts_no_mojo_limit_can_bound(&derived.summary)?;
if derived.native_total_mojos > limits.per_tx_limit_mojos {
return self.escalate(coin_spends, derived);
}
match self.charge_the_rolling_period_cap(derived.native_total_mojos)? {
CapVerdict::Charged => Ok(SpendRuling::Approved(SpendApproval::new(
coin_spends.to_vec(),
derived.summary,
self.scope,
))),
CapVerdict::OverCap => self.escalate(coin_spends, derived),
}
}
fn reject_amounts_no_mojo_limit_can_bound(&self, summary: &SpendSummary) -> Result<()> {
let unbounded: Vec<&str> = summary
.recipients
.iter()
.filter_map(|recipient| recipient.asset_id.as_deref())
.collect();
if unbounded.is_empty() {
return Ok(());
}
Err(AccountError::PolicyIndeterminate(format!(
"this spend moves non-native assets ({}) whose amounts no mojo-denominated auto-send \
limit can bound",
unbounded.join(", ")
)))
}
fn charge_the_rolling_period_cap(&self, total: u64) -> Result<CapVerdict> {
if self.auto_send.period_seconds == 0 {
return Err(AccountError::PolicyIndeterminate(
"the auto-send period is zero seconds long, so no window exists to measure the cap \
over; the cap cannot be evaluated"
.to_string(),
));
}
let now = self.clock.now_unix()?;
let mut recent = self.recent.lock().map_err(|_| {
AccountError::PolicyIndeterminate(
"the auto-send ledger is poisoned, so the rolling period cap cannot be evaluated"
.to_string(),
)
})?;
recent.retain(|record| record.at_unix.saturating_add(self.auto_send.period_seconds) > now);
let projected = recent
.iter()
.try_fold(total, |sum, record| sum.checked_add(record.mojos))
.ok_or_else(|| {
AccountError::PolicyIndeterminate(
"this spend plus the rolling period total overflows u64, so the cap cannot be \
evaluated"
.to_string(),
)
})?;
if projected > self.auto_send.period_cap_mojos {
return Ok(CapVerdict::OverCap);
}
if recent.len() >= MAX_LEDGER_ENTRIES {
return Err(AccountError::PolicyIndeterminate(format!(
"the rolling auto-send ledger already holds {MAX_LEDGER_ENTRIES} approvals in this window, so the cap cannot be measured over any further spend"
)));
}
if total > 0 {
recent.push_back(AutoSendRecord {
at_unix: now,
mojos: total,
});
}
Ok(CapVerdict::Charged)
}
fn escalate(&self, coin_spends: &[CoinSpend], derived: DerivedSpend) -> Result<SpendRuling> {
self.charge_a_confirmation_prompt()?;
Ok(SpendRuling::RequiresConfirmation(PendingApproval::new(
coin_spends.to_vec(),
derived.summary,
self.scope,
)))
}
fn charge_a_confirmation_prompt(&self) -> Result<()> {
if self.auto_send.period_seconds == 0 {
return Err(AccountError::PolicyIndeterminate(
"the auto-send period is zero seconds long, so no window exists to measure the \
confirmation ceiling over"
.to_string(),
));
}
let now = self.clock.now_unix()?;
let mut prompts = self.prompts.lock().map_err(|_| {
AccountError::PolicyIndeterminate(
"the confirmation ledger is poisoned, so the prompt ceiling cannot be evaluated"
.to_string(),
)
})?;
prompts.retain(|at| at.saturating_add(self.auto_send.period_seconds) > now);
if prompts.len() as u64 >= u64::from(self.auto_send.max_confirmations_per_period) {
return Err(AccountError::PolicyIndeterminate(format!(
"{} confirmation ceremonies have already been raised in the last {}s, reaching the \
configured ceiling; no further spend can be put to the user until the window rolls \
forward",
prompts.len(),
self.auto_send.period_seconds
)));
}
prompts.push_back(now);
Ok(())
}
}
enum CapVerdict {
Charged,
OverCap,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::keys::wallet_key::WalletKey;
use crate::wallet::autosend::{OpClassLimits, DEFAULT_PERIOD_SECONDS};
use crate::wallet::clock::{FixedClock, UnreadableClock};
use crate::wallet::policy::{HotWallet, Vault};
use crate::wallet::summary::{SpendDestination, SpendRecipient};
use chia_protocol::Coin;
use chia_puzzle_types::Memos;
use chia_wallet_sdk::driver::{SpendContext, StandardLayer};
use chia_wallet_sdk::types::Conditions;
const NOW: u64 = 1_800_000_000;
const GATE_PROFILE: ProfileIx = ProfileIx::ROOT;
const CUSTODY_AUTO_SEND_CEILING: u64 = 1_000_000;
const SPENDER_SEED: [u8; 32] = [0x5C; 32];
fn spender() -> WalletKey {
WalletKey::from_seed_at(&SPENDER_SEED, ProfileIx::ROOT)
}
fn hot_wallet() -> WalletKey {
WalletKey::from_seed_at(&[0xA1; 32], ProfileIx::ROOT)
}
fn third_party() -> WalletKey {
WalletKey::from_seed_at(&[0xB2; 32], ProfileIx::ROOT)
}
fn spend_paying(payments: &[(Bytes32, u64)], fee: u64) -> Vec<CoinSpend> {
let total = payments
.iter()
.try_fold(fee, |sum, (_, amount)| sum.checked_add(*amount))
.expect("fixture totals must be representable; use `two_coin_spend_totalling` if not");
let mut ctx = SpendContext::new();
let mut conditions = Conditions::new();
for (puzzle_hash, amount) in payments {
let hint = ctx.hint(*puzzle_hash).unwrap();
conditions = conditions.create_coin(*puzzle_hash, *amount, hint);
}
if fee > 0 {
conditions = conditions.reserve_fee(fee);
}
StandardLayer::new(spender().public_key())
.spend(
&mut ctx,
Coin::new(Bytes32::new([1u8; 32]), spender().puzzle_hash(), total),
conditions,
)
.unwrap();
ctx.take()
}
fn two_coin_spend(first: u64, second: u64) -> Vec<CoinSpend> {
let recipient = third_party().puzzle_hash();
let mut ctx = SpendContext::new();
for (parent, amount) in [([1u8; 32], first), ([2u8; 32], second)] {
let hint = ctx.hint(recipient).unwrap();
StandardLayer::new(spender().public_key())
.spend(
&mut ctx,
Coin::new(Bytes32::new(parent), spender().puzzle_hash(), amount),
Conditions::new().create_coin(recipient, amount, hint),
)
.unwrap();
}
ctx.take()
}
fn pays_third_party(amount: u64) -> Vec<CoinSpend> {
spend_paying(&[(third_party().puzzle_hash(), amount)], 0)
}
fn cat_spend_paying(amount: u64, fee: u64) -> Vec<CoinSpend> {
use chia_wallet_sdk::driver::{Cat, CatSpend, SpendWithConditions};
let wallet_ph = spender().puzzle_hash();
let cat = {
let mut issue_ctx = SpendContext::new();
let genesis = Coin::new(Bytes32::new([9u8; 32]), wallet_ph, amount);
let hint = issue_ctx.hint(wallet_ph).unwrap();
let issue = Conditions::new().create_coin(wallet_ph, amount, hint);
let (_, cats) =
Cat::single_issuance(&mut issue_ctx, genesis.coin_id(), None, amount, issue)
.unwrap();
cats[0]
};
let mut ctx = SpendContext::new();
let recipient = third_party().puzzle_hash();
let cat_hint = ctx.hint(recipient).unwrap();
let inner = StandardLayer::new(spender().public_key())
.spend_with_conditions(
&mut ctx,
Conditions::new().create_coin(recipient, amount, cat_hint),
)
.unwrap();
Cat::spend_all(&mut ctx, &[CatSpend::new(cat, inner)]).unwrap();
if fee > 0 {
StandardLayer::new(spender().public_key())
.spend(
&mut ctx,
Coin::new(Bytes32::new([8u8; 32]), wallet_ph, fee),
Conditions::new().reserve_fee(fee),
)
.unwrap();
}
ctx.take()
}
fn permissive_auto_send() -> AutoSendPolicy {
AutoSendPolicy {
enabled: true,
rebalance: OpClassLimits::enabled_up_to(u64::MAX),
tip: OpClassLimits::enabled_up_to(u64::MAX),
small_send: OpClassLimits::enabled_up_to(u64::MAX),
period_seconds: DEFAULT_PERIOD_SECONDS,
period_cap_mojos: u64::MAX,
max_confirmations_per_period: u32::MAX,
}
}
fn vault_custody() -> CustodyPolicy {
CustodyPolicy::Vault(Vault::default())
}
fn hot_custody() -> CustodyPolicy {
CustodyPolicy::Hot(HotWallet {
auto_send_limit: CUSTODY_AUTO_SEND_CEILING,
})
}
fn gate_with(custody: CustodyPolicy, auto_send: AutoSendPolicy) -> PolicyAuthorizer {
gate_at(custody, auto_send).0
}
fn gate_at(
custody: CustodyPolicy,
auto_send: AutoSendPolicy,
) -> (PolicyAuthorizer, Arc<FixedClock>) {
let clock = Arc::new(FixedClock::new(NOW));
let gate = PolicyAuthorizer::new(
GATE_PROFILE,
custody,
auto_send,
&hot_wallet().address().unwrap(),
clock.clone(),
)
.unwrap();
(gate, clock)
}
fn approval(result: Result<SpendRuling>) -> SpendApproval {
match result {
Ok(SpendRuling::Approved(approval)) => approval,
Ok(SpendRuling::RequiresConfirmation(_)) => {
panic!("expected an auto-approval, got an escalation to the human")
}
Err(e) => panic!("expected an auto-approval, got a refusal: {e}"),
}
}
fn pending(result: Result<SpendRuling>) -> PendingApproval {
match result {
Ok(SpendRuling::RequiresConfirmation(pending)) => pending,
Ok(SpendRuling::Approved(_)) => {
panic!("expected an escalation to the human, got an auto-approval")
}
Err(e) => panic!("expected an escalation to the human, got a refusal: {e}"),
}
}
fn refusal(result: Result<SpendRuling>) -> AccountError {
match result {
Ok(SpendRuling::Approved(_)) => panic!("expected a refusal, got an auto-approval"),
Ok(SpendRuling::RequiresConfirmation(_)) => {
panic!("expected a refusal, got an escalation to the human")
}
Err(e) => e,
}
}
async fn confirmed(
pending: PendingApproval,
decision: crate::auth::provider::SpendDecision,
) -> Result<SpendApproval> {
use crate::auth::factors::AuthFactors;
use crate::auth::provider::{AuthProvider, SpendConfirmRequest, UnlockRequest};
use crate::id::AccountId;
use crate::auth::provider::SpendDecision;
struct Fixed(SpendDecision);
#[async_trait::async_trait]
impl AuthProvider for Fixed {
async fn collect_factors(&self, _: UnlockRequest) -> Result<AuthFactors> {
unreachable!("a spend ceremony never collects unlock factors")
}
async fn confirm_spend(&self, _: SpendConfirmRequest) -> Result<SpendDecision> {
Ok(self.0.clone())
}
}
pending
.confirm_with(
&Fixed(decision),
AccountId::new("ceremony-fixture"),
ProfileIx::ROOT,
)
.await
}
fn denial(result: Result<SpendApproval>) -> AccountError {
match result {
Ok(_) => panic!("expected a denial, got a signable approval"),
Err(e) => e,
}
}
fn is_approved(result: &Result<SpendRuling>) -> bool {
matches!(result, Ok(SpendRuling::Approved(_)))
}
fn ledger_total(gate: &PolicyAuthorizer) -> u64 {
gate.recent.lock().unwrap().iter().map(|r| r.mojos).sum()
}
#[test]
fn an_nft_transfer_never_auto_approves_under_a_maximally_permissive_policy() {
use crate::wallet::nft_fixture::{nft_transfer_to, RECIPIENT_PUZZLE_HASH};
let gate = gate_with(hot_custody(), permissive_auto_send());
let coin_spends = nft_transfer_to(spender().public_key(), RECIPIENT_PUZZLE_HASH, 0x44);
for op_class in [
SpendOpClass::SmallSend,
SpendOpClass::Tip,
SpendOpClass::Rebalance,
] {
let escalated = pending(gate.authorize_op(&coin_spends, op_class));
assert_eq!(
escalated.summary().tier,
SpendTier::Confirm,
"an NFT transfer declared as {op_class:?} must reach a human"
);
assert!(
!escalated.summary().nft_operations.is_empty(),
"the escalated summary must NAME the act, or the human is shown dust"
);
}
}
#[test]
fn an_ordinary_send_of_the_same_value_under_the_same_policy_auto_approves() {
let gate = gate_with(hot_custody(), permissive_auto_send());
let coin_spends = spend_paying(&[(third_party().puzzle_hash(), 4)], 0);
let _signable = approval(gate.authorize_op(&coin_spends, SpendOpClass::SmallSend));
}
#[test]
fn a_vault_spend_never_auto_approves_at_any_amount_even_under_a_maximally_permissive_policy() {
let gate = gate_with(vault_custody(), permissive_auto_send());
for amount in [0, 1, 42, CUSTODY_AUTO_SEND_CEILING, u64::MAX - 1] {
let coin_spends = spend_paying(&[(hot_wallet().puzzle_hash(), amount)], 0);
let escalated = pending(gate.authorize_op(&coin_spends, SpendOpClass::SmallSend));
assert_eq!(
escalated.summary().tier,
SpendTier::Vault,
"{amount} mojos must be tiered Vault"
);
}
}
#[test]
fn a_vault_spend_to_a_third_party_is_forbidden_outright_while_one_to_the_hot_wallet_escalates()
{
let gate = gate_with(vault_custody(), permissive_auto_send());
pending(gate.authorize_op(
&spend_paying(&[(hot_wallet().puzzle_hash(), 500)], 0),
SpendOpClass::SmallSend,
));
let denied = refusal(gate.authorize_op(&pays_third_party(500), SpendOpClass::SmallSend));
assert!(
matches!(denied, AccountError::PolicyDenied(_)),
"vault to a third party must be forbidden outright, got: {denied}"
);
}
#[test]
fn a_vault_spend_paying_the_hot_wallet_and_a_third_party_is_forbidden() {
let gate = gate_with(vault_custody(), permissive_auto_send());
let coin_spends = spend_paying(
&[
(hot_wallet().puzzle_hash(), 500),
(third_party().puzzle_hash(), 1),
],
0,
);
let err = refusal(gate.authorize_op(&coin_spends, SpendOpClass::Tip));
assert!(matches!(err, AccountError::PolicyDenied(_)), "{err}");
}
#[test]
fn a_vault_spend_committing_value_to_a_protocol_structure_is_denied() {
let gate = gate_with(vault_custody(), permissive_auto_send());
let summary = SpendSummary::new(
SpendTier::Vault,
vec![SpendRecipient {
address: "the singleton launcher".to_string(),
amount_mojos: 500,
asset_id: None,
destination: SpendDestination::ProtocolStructure,
}],
0,
);
let err = gate
.reject_vault_outflow_to_anyone_but_the_hot_wallet(&summary)
.unwrap_err();
assert!(
matches!(err, AccountError::PolicyDenied(ref message) if message.contains("the singleton launcher")),
"a structural commitment is a destination the gate understands and forbids: {err}"
);
let permitted = SpendSummary::new(
SpendTier::Vault,
vec![SpendRecipient {
address: hot_wallet().address().unwrap(),
amount_mojos: 500,
asset_id: None,
destination: SpendDestination::Address,
}],
0,
);
gate.reject_vault_outflow_to_anyone_but_the_hot_wallet(&permitted)
.expect("the profile's own hot wallet is the one permitted destination");
}
#[test]
fn a_vault_recipient_with_an_undecodable_address_is_indeterminate() {
let gate = gate_with(vault_custody(), permissive_auto_send());
let hot = hot_wallet().address().unwrap();
for address in ["", "not-an-address", "xch1", &hot[..20]] {
let summary = SpendSummary::new(
SpendTier::Vault,
vec![SpendRecipient {
address: address.to_string(),
amount_mojos: 500,
asset_id: None,
destination: SpendDestination::Address,
}],
0,
);
let err = gate
.reject_vault_outflow_to_anyone_but_the_hot_wallet(&summary)
.unwrap_err();
assert!(
matches!(err, AccountError::PolicyIndeterminate(_)),
"address {address:?}: {err}"
);
}
let ok = SpendSummary::new(
SpendTier::Vault,
vec![SpendRecipient {
address: hot,
amount_mojos: 500,
asset_id: None,
destination: SpendDestination::Address,
}],
0,
);
gate.reject_vault_outflow_to_anyone_but_the_hot_wallet(&ok)
.expect("the profile's own hot wallet is the one permitted destination");
}
#[test]
fn an_auto_send_within_every_bound_is_approved_and_charges_the_cap_its_real_value() {
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1_000),
period_cap_mojos: 5_000,
..AutoSendPolicy::default()
},
);
let coin_spends = spend_paying(&[(third_party().puzzle_hash(), 990)], 10);
let approved = approval(gate.authorize_op(&coin_spends, SpendOpClass::Tip));
assert_eq!(approved.summary().tier, SpendTier::AutoSend);
assert_eq!(approved.summary().fee, 10);
assert_eq!(approved.summary().recipients[0].amount_mojos, 990);
assert_eq!(
approved.coin_spends(),
coin_spends.as_slice(),
"the approval must own the very spends that were judged"
);
assert_eq!(
ledger_total(&gate),
1_000,
"the cap must be charged the spend's real value, fee included"
);
}
#[test]
fn the_rolling_cap_is_charged_the_spends_own_value_so_a_small_description_cannot_understate_it()
{
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1_000_000),
period_cap_mojos: 1_000_000,
..AutoSendPolicy::default()
},
);
approval(gate.authorize_op(&pays_third_party(900_000), SpendOpClass::Tip));
assert_eq!(
ledger_total(&gate),
900_000,
"the ledger must stand at the spend's real value, not at a nominal 1"
);
pending(gate.authorize_op(&pays_third_party(200_000), SpendOpClass::Tip));
assert_eq!(
ledger_total(&gate),
900_000,
"and the escalated spend must not have been charged"
);
}
#[test]
fn an_auto_send_over_the_per_transaction_limit_escalates() {
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1_000),
period_cap_mojos: u64::MAX,
..AutoSendPolicy::default()
},
);
approval(gate.authorize_op(&pays_third_party(1_000), SpendOpClass::Tip));
let escalated = pending(gate.authorize_op(&pays_third_party(1_001), SpendOpClass::Tip));
assert_eq!(
escalated.summary().tier,
SpendTier::AutoSend,
"the custody tier is untouched — it is the auto-send limit that bound"
);
}
#[test]
fn the_fee_counts_toward_the_per_transaction_limit() {
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1_000),
period_cap_mojos: u64::MAX,
..AutoSendPolicy::default()
},
);
let coin_spends = spend_paying(&[(third_party().puzzle_hash(), 1_000)], 1);
pending(gate.authorize_op(&coin_spends, SpendOpClass::Tip));
}
#[test]
fn an_auto_send_over_the_rolling_period_cap_escalates() {
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1_000),
period_cap_mojos: 1_500,
..AutoSendPolicy::default()
},
);
approval(gate.authorize_op(&pays_third_party(900), SpendOpClass::Tip));
pending(gate.authorize_op(&pays_third_party(900), SpendOpClass::Tip));
}
#[test]
fn the_rolling_period_cap_is_shared_across_op_classes() {
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
rebalance: OpClassLimits::enabled_up_to(1_000),
tip: OpClassLimits::enabled_up_to(1_000),
period_cap_mojos: 1_500,
..AutoSendPolicy::default()
},
);
approval(gate.authorize_op(&pays_third_party(900), SpendOpClass::Rebalance));
pending(gate.authorize_op(&pays_third_party(900), SpendOpClass::Tip));
}
#[test]
fn the_rolling_period_cap_renews_exactly_one_period_after_a_spend_not_a_second_earlier() {
let period = 86_400;
let (gate, clock) = gate_at(
hot_custody(),
AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1_000),
period_seconds: period,
period_cap_mojos: 1_500,
..AutoSendPolicy::default()
},
);
approval(gate.authorize_op(&pays_third_party(900), SpendOpClass::Tip));
clock.set(NOW + period - 1);
assert!(
!is_approved(&gate.authorize_op(&pays_third_party(900), SpendOpClass::Tip)),
"one second before the window closes the earlier spend must still count"
);
clock.set(NOW + period);
approval(gate.authorize_op(&pays_third_party(900), SpendOpClass::Tip));
}
#[test]
fn an_escalated_spend_does_not_consume_the_period_allowance() {
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1_000),
period_cap_mojos: 1_000,
..AutoSendPolicy::default()
},
);
approval(gate.authorize_op(&pays_third_party(600), SpendOpClass::Tip));
assert_eq!(ledger_total(&gate), 600);
pending(gate.authorize_op(&pays_third_party(600), SpendOpClass::Tip));
assert_eq!(ledger_total(&gate), 600, "the escalation must cost nothing");
approval(gate.authorize_op(&pays_third_party(400), SpendOpClass::Tip));
}
#[test]
fn a_spend_escalated_before_the_ledger_is_reached_does_not_consume_the_period_allowance() {
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1_000),
rebalance: OpClassLimits::default(),
period_cap_mojos: 1_000,
..AutoSendPolicy::default()
},
);
pending(gate.authorize_op(&pays_third_party(1_000), SpendOpClass::Rebalance));
pending(gate.authorize_op(&pays_third_party(1_000), SpendOpClass::Undeclared));
pending(gate.authorize_op(&pays_third_party(1_001), SpendOpClass::Tip));
assert_eq!(ledger_total(&gate), 0);
approval(gate.authorize_op(&pays_third_party(1_000), SpendOpClass::Tip));
}
#[test]
fn a_disabled_op_class_escalates_while_its_enabled_sibling_is_approved() {
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1_000),
rebalance: OpClassLimits {
enabled: false,
per_tx_limit_mojos: 1_000,
},
period_cap_mojos: u64::MAX,
..AutoSendPolicy::default()
},
);
approval(gate.authorize_op(&pays_third_party(100), SpendOpClass::Tip));
pending(gate.authorize_op(&pays_third_party(100), SpendOpClass::Rebalance));
}
#[test]
fn an_enabled_op_class_with_a_zero_limit_permits_no_value() {
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
tip: OpClassLimits {
enabled: true,
per_tx_limit_mojos: 0,
},
period_cap_mojos: u64::MAX,
..AutoSendPolicy::default()
},
);
pending(gate.authorize_op(&pays_third_party(1), SpendOpClass::Tip));
}
#[test]
fn the_global_off_switch_escalates_even_a_spend_within_every_other_bound() {
let coin_spends = pays_third_party(100);
let permissive = AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1_000),
period_cap_mojos: u64::MAX,
..AutoSendPolicy::default()
};
approval(
gate_with(hot_custody(), permissive).authorize_op(&coin_spends, SpendOpClass::Tip),
);
let switched_off = AutoSendPolicy {
enabled: false,
..permissive
};
pending(
gate_with(hot_custody(), switched_off).authorize_op(&coin_spends, SpendOpClass::Tip),
);
}
#[test]
fn the_default_policy_auto_approves_no_op_class() {
let gate = gate_with(hot_custody(), AutoSendPolicy::default());
let coin_spends = pays_third_party(1);
for op_class in [
SpendOpClass::Rebalance,
SpendOpClass::Tip,
SpendOpClass::SmallSend,
SpendOpClass::Undeclared,
] {
assert!(
!is_approved(&gate.authorize_op(&coin_spends, op_class)),
"{op_class:?} must not auto-approve under the default policy"
);
}
}
#[test]
fn an_undeclared_intent_escalates_to_the_human_rather_than_dead_ending() {
let coin_spends = pays_third_party(100);
let on = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1_000),
small_send: OpClassLimits::enabled_up_to(1_000),
rebalance: OpClassLimits::enabled_up_to(1_000),
period_cap_mojos: u64::MAX,
..AutoSendPolicy::default()
},
);
approval(on.authorize_op(&coin_spends, SpendOpClass::Tip));
let escalated = pending(on.authorize_op(&coin_spends, SpendOpClass::Undeclared));
assert_eq!(escalated.summary().recipients[0].amount_mojos, 100);
assert_eq!(
ledger_total(&on),
100,
"only the declared, auto-approved spend was charged"
);
let off = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: false,
..permissive_auto_send()
},
);
pending(off.authorize_op(&coin_spends, SpendOpClass::Undeclared));
}
#[tokio::test]
async fn a_confirm_tier_spend_reaches_the_ceremony_and_a_confirmation_makes_it_signable() {
let gate = gate_with(hot_custody(), permissive_auto_send());
let coin_spends = pays_third_party(CUSTODY_AUTO_SEND_CEILING + 1);
let escalated = pending(gate.authorize_op(&coin_spends, SpendOpClass::Tip));
assert_eq!(escalated.summary().tier, SpendTier::Confirm);
assert_eq!(
escalated.summary().recipients[0].amount_mojos,
CUSTODY_AUTO_SEND_CEILING + 1,
"the user must be shown the spend's real value"
);
let approved = confirmed(escalated, crate::auth::provider::SpendDecision::Approve)
.await
.expect("a confirmed spend becomes signable");
assert_eq!(
approved.coin_spends(),
coin_spends.as_slice(),
"and it is the very spend that was confirmed"
);
assert_eq!(
ledger_total(&gate),
0,
"a human-confirmed spend does not consume the unattended allowance"
);
}
#[tokio::test]
async fn a_declined_ceremony_yields_no_approval_and_charges_nothing() {
let gate = gate_with(hot_custody(), permissive_auto_send());
let escalated = pending(gate.authorize_op(
&pays_third_party(CUSTODY_AUTO_SEND_CEILING + 1),
SpendOpClass::Tip,
));
let err = denial(
confirmed(
escalated,
crate::auth::provider::SpendDecision::Decline(None),
)
.await,
);
assert!(matches!(err, AccountError::UserDeclined(_)), "{err}");
assert_eq!(ledger_total(&gate), 0);
}
fn hides_value_behind_a_wrapper_layer(
hidden_mojos: u64,
fee: u64,
) -> (Vec<CoinSpend>, Bytes32) {
use chia_wallet_sdk::driver::{Cat, CatSpend, SpendWithConditions};
let wallet_ph = spender().puzzle_hash();
const CAT_UNITS: u64 = 1_000;
let cat = {
let mut issue_ctx = SpendContext::new();
let genesis = Coin::new(Bytes32::new([9u8; 32]), wallet_ph, CAT_UNITS);
let hint = issue_ctx.hint(wallet_ph).unwrap();
let issue = Conditions::new().create_coin(wallet_ph, CAT_UNITS, hint);
let (_, cats) =
Cat::single_issuance(&mut issue_ctx, genesis.coin_id(), None, CAT_UNITS, issue)
.unwrap();
cats[0]
};
let wrapper_hash = cat.coin.puzzle_hash;
let mut ctx = SpendContext::new();
let inner = StandardLayer::new(spender().public_key())
.spend_with_conditions(
&mut ctx,
Conditions::new().create_coin(wallet_ph, CAT_UNITS, Memos::None),
)
.unwrap();
Cat::spend_all(&mut ctx, &[CatSpend::new(cat, inner)]).unwrap();
let hint = ctx.hint(wrapper_hash).unwrap();
let mut conditions = Conditions::new().create_coin(wrapper_hash, hidden_mojos, hint);
if fee > 0 {
conditions = conditions.reserve_fee(fee);
}
StandardLayer::new(spender().public_key())
.spend(
&mut ctx,
Coin::new(Bytes32::new([3u8; 32]), wallet_ph, hidden_mojos + fee),
conditions,
)
.unwrap();
(ctx.take(), wrapper_hash)
}
#[test]
fn value_hidden_behind_a_wrapper_layer_hash_is_counted_not_excused_as_change() {
let (coin_spends, wrapper_hash) = hides_value_behind_a_wrapper_layer(999_999, 1);
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(10),
period_cap_mojos: 10,
..AutoSendPolicy::default()
},
);
let escalated = pending(gate.authorize_op(&coin_spends, SpendOpClass::Tip));
assert_eq!(
escalated.summary().checked_native_total_mojos().unwrap(),
1_000_000,
"the 999_999 hidden output plus the 1 mojo fee must be what the gate weighed"
);
assert_eq!(
ledger_total(&gate),
0,
"an escalated spend charges nothing — and it must never have been charged 1"
);
let shown = escalated.summary().to_string();
assert!(
shown.contains("999999"),
"the confirm line must state the hidden amount: {shown}"
);
assert!(
escalated
.summary()
.recipients
.iter()
.any(|r| r.amount_mojos == 999_999),
"the output must appear as a destination, not be filtered away"
);
let denied = refusal(
gate_with(vault_custody(), permissive_auto_send())
.authorize_op(&coin_spends, SpendOpClass::Tip),
);
assert!(
matches!(&denied, AccountError::PolicyDenied(m) if m.contains("vault")),
"a vault outflow to a wrapper hash must be forbidden outright, not escalated: {denied}"
);
assert!(
coin_spends
.iter()
.any(|spend| spend.coin.puzzle_hash == wrapper_hash),
"the fixture must pay a hash the spend is spending from, or it proves nothing"
);
}
#[test]
fn only_a_proven_p2_destination_of_this_spend_counts_as_returning_to_the_spender() {
let wallet_ph = spender().puzzle_hash();
let plain = spend_paying(&[(third_party().puzzle_hash(), 10)], 0);
assert!(
crate::wallet::summary::p2_destinations(&plain).contains(&wallet_ph),
"a bare p2 puzzle whose curry reproduces its own coin hash is a payable destination"
);
let (wrapped, wrapper_hash) = hides_value_behind_a_wrapper_layer(999, 1);
let proven = crate::wallet::summary::p2_destinations(&wrapped);
assert!(
!proven.contains(&wrapper_hash),
"a wrapper layer's hash is not a payable destination"
);
assert!(
proven.contains(&wallet_ph),
"the same bundle's plain p2 coin must still qualify, so (a) is the WRAPPER being \
excluded and not the whole bundle being distrusted"
);
let mut opaque = plain.clone();
opaque[0].puzzle_reveal = chia_protocol::Program::from(vec![0xFFu8, 0xFE, 0xFD]);
assert!(
!crate::wallet::summary::p2_destinations(&opaque).contains(&wallet_ph),
"a reveal that cannot be decoded cannot prove a destination"
);
let mut borrowed = plain.clone();
borrowed[0].coin.puzzle_hash = Bytes32::new([0xAB; 32]);
assert!(
crate::wallet::summary::p2_destinations(&borrowed).is_empty(),
"a p2 reveal that does not hash to its own coin proves no destination"
);
}
#[test]
fn the_confirmation_prompt_ceiling_is_pinned_at_the_bound_and_one_more_is_refused() {
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: false,
max_confirmations_per_period: 4,
..permissive_auto_send()
},
);
let coin_spends = pays_third_party(100);
for raised in 1..=4 {
pending(gate.authorize_op(&coin_spends, SpendOpClass::Tip));
assert_eq!(gate.prompts.lock().unwrap().len(), raised);
}
let err = refusal(gate.authorize_op(&coin_spends, SpendOpClass::Tip));
assert!(
matches!(&err, AccountError::PolicyIndeterminate(m) if m.contains("ceiling")),
"past the ceiling the gate cannot obtain a decision, and must say so: {err}"
);
}
#[test]
fn the_rolling_ledger_refuses_rather_than_growing_past_its_entry_ceiling() {
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1),
period_cap_mojos: u64::MAX,
..AutoSendPolicy::default()
},
);
let one_mojo = pays_third_party(1);
for _ in 0..MAX_LEDGER_ENTRIES {
approval(gate.authorize_op(&one_mojo, SpendOpClass::Tip));
}
assert_eq!(
gate.recent.lock().unwrap().len(),
MAX_LEDGER_ENTRIES,
"the ledger must have filled to exactly its ceiling"
);
let err = refusal(gate.authorize_op(&one_mojo, SpendOpClass::Tip));
assert!(
matches!(&err, AccountError::PolicyIndeterminate(m) if m.contains("ledger")),
"at the ceiling the cap cannot be measured over a further spend: {err}"
);
assert_eq!(
gate.recent.lock().unwrap().len(),
MAX_LEDGER_ENTRIES,
"and the refusal must not have evicted an entry to make room"
);
}
#[test]
fn a_spend_paying_a_non_native_asset_escalates_to_an_informed_human_and_never_auto_approves() {
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1_000),
period_cap_mojos: u64::MAX,
..AutoSendPolicy::default()
},
);
let coin_spends = cat_spend_paying(1_000_000_000, 1);
let summary = SpendSummary::classified(&coin_spends, &hot_custody()).unwrap();
assert_eq!(
summary.native_total_mojos(),
1,
"the CAT amount is invisible to a mojo total: {summary:?}"
);
assert_eq!(
summary.tier,
SpendTier::Confirm,
"a spend moving a non-native asset is Confirm by rule, not by accident of where a filter sits: {summary:?}"
);
let pending = match gate.authorize_op(&coin_spends, SpendOpClass::Tip) {
Ok(SpendRuling::RequiresConfirmation(pending)) => pending,
Ok(SpendRuling::Approved(_)) => {
panic!("a spend no mojo limit can bound must never auto-approve")
}
Err(e) => panic!("it must reach the ceremony rather than dead-ending: {e}"),
};
let paid = pending
.summary()
.recipients
.iter()
.find(|recipient| recipient.asset_id.is_some())
.expect("the ceremony must show the human WHICH asset is leaving");
assert_eq!(
paid.amount_mojos, 1_000_000_000,
"and HOW MUCH of it — an escalation to an uninformed prompt would be worse than a refusal: {:?}",
pending.summary()
);
}
#[test]
fn an_unreadable_clock_refuses_rather_than_assuming_an_empty_window() {
let gate = PolicyAuthorizer::new(
GATE_PROFILE,
hot_custody(),
permissive_auto_send(),
&hot_wallet().address().unwrap(),
Arc::new(UnreadableClock),
)
.unwrap();
let err = refusal(gate.authorize_op(&pays_third_party(1), SpendOpClass::Tip));
assert!(matches!(err, AccountError::PolicyIndeterminate(_)), "{err}");
}
#[test]
fn an_unaccountable_spend_is_refused_at_the_gate_before_any_approval_exists() {
use chia_wallet_sdk::driver::Spend;
let mut ctx = SpendContext::new();
let malleable = ctx.alloc(&1).unwrap();
let echoed = Conditions::new().create_coin(spender().puzzle_hash(), 1_000, Memos::None);
let solution = ctx.alloc(&echoed).unwrap();
let spend = StandardLayer::new(spender().public_key())
.delegated_inner_spend(
&mut ctx,
Spend {
puzzle: malleable,
solution,
},
)
.unwrap();
ctx.spend(
Coin::new(Bytes32::new([1u8; 32]), spender().puzzle_hash(), 1_000),
spend,
)
.unwrap();
let coin_spends = ctx.take();
let gate = gate_with(hot_custody(), permissive_auto_send());
let err = refusal(gate.authorize_op(&coin_spends, SpendOpClass::Tip));
assert!(
matches!(err, AccountError::Spend(_)),
"the gate itself must refuse an unaccountable spend: {err}"
);
}
#[test]
fn every_spend_tier_that_exists_has_an_explicit_enforced_decision() {
let gate = gate_with(hot_custody(), permissive_auto_send());
let vault_gate = gate_with(vault_custody(), permissive_auto_send());
for tier in [SpendTier::AutoSend, SpendTier::Confirm, SpendTier::Vault] {
match tier {
SpendTier::AutoSend => {
let approved =
approval(gate.authorize_op(&pays_third_party(100), SpendOpClass::Tip));
assert_eq!(approved.summary().tier, SpendTier::AutoSend);
}
SpendTier::Confirm => {
let escalated = pending(gate.authorize_op(
&pays_third_party(CUSTODY_AUTO_SEND_CEILING + 1),
SpendOpClass::Tip,
));
assert_eq!(escalated.summary().tier, SpendTier::Confirm);
}
SpendTier::Vault => {
let err =
refusal(vault_gate.authorize_op(&pays_third_party(100), SpendOpClass::Tip));
assert!(matches!(err, AccountError::PolicyDenied(_)), "{err}");
}
}
}
}
#[test]
fn a_gate_cannot_be_built_on_an_undecodable_hot_wallet_address() {
for address in ["", "nonsense", "xch1zzzz"] {
let err = PolicyAuthorizer::new(
GATE_PROFILE,
hot_custody(),
permissive_auto_send(),
address,
Arc::new(FixedClock::new(NOW)),
)
.unwrap_err();
assert!(
matches!(err, AccountError::PolicyIndeterminate(_)),
"address {address:?}: {err}"
);
}
}
#[test]
fn only_the_vault_arm_applies_the_destination_rule() {
let over_the_hot_ceiling = pays_third_party(CUSTODY_AUTO_SEND_CEILING + 1);
let denied = refusal(
gate_with(vault_custody(), permissive_auto_send())
.authorize_op(&over_the_hot_ceiling, SpendOpClass::Tip),
);
assert!(
matches!(&denied, AccountError::PolicyDenied(m) if m.contains("vault")),
"a vault outflow to a third party is denied, and says why: {denied}"
);
let escalated = pending(
gate_with(hot_custody(), permissive_auto_send())
.authorize_op(&over_the_hot_ceiling, SpendOpClass::Tip),
);
assert_eq!(
escalated.summary().tier,
SpendTier::Confirm,
"the same spend under a hot policy is confirmable, not forbidden"
);
}
#[test]
fn a_spend_that_brings_the_rolling_total_exactly_to_the_cap_is_approved_and_one_more_is_not() {
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1_000),
period_cap_mojos: 1_000,
..AutoSendPolicy::default()
},
);
approval(gate.authorize_op(&pays_third_party(600), SpendOpClass::Tip));
approval(gate.authorize_op(&pays_third_party(400), SpendOpClass::Tip));
assert_eq!(ledger_total(&gate), 1_000, "exactly the cap, and within it");
pending(gate.authorize_op(&pays_third_party(1), SpendOpClass::Tip));
}
#[test]
fn a_zero_length_rolling_period_cannot_be_evaluated_and_is_refused() {
let policy = AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1_000),
period_seconds: 0,
period_cap_mojos: 1_000,
..AutoSendPolicy::default()
};
let coin_spends = pays_third_party(100);
let err =
refusal(gate_with(hot_custody(), policy).authorize_op(&coin_spends, SpendOpClass::Tip));
assert!(matches!(err, AccountError::PolicyIndeterminate(_)), "{err}");
approval(
gate_with(
hot_custody(),
AutoSendPolicy {
period_seconds: 1,
..policy
},
)
.authorize_op(&coin_spends, SpendOpClass::Tip),
);
}
#[test]
fn repeated_zero_value_approvals_neither_accumulate_nor_consume_the_allowance() {
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1_000),
period_cap_mojos: 1_000,
..AutoSendPolicy::default()
},
);
let nothing = pays_third_party(0);
for _ in 0..1_000 {
approval(gate.authorize_op(¬hing, SpendOpClass::Tip));
}
assert_eq!(
gate.recent.lock().unwrap().len(),
0,
"a zero charge must leave no record behind"
);
approval(gate.authorize_op(&pays_third_party(1_000), SpendOpClass::Tip));
}
#[test]
fn an_unhinted_output_to_an_owned_derivation_is_counted_not_hidden() {
let attacker_owned = WalletKey::from_seed_at(&SPENDER_SEED, ProfileIx(1)).puzzle_hash();
assert_ne!(
attacker_owned,
spender().puzzle_hash(),
"the fixture must pay a DIFFERENT derivation, or it is testing genuine change"
);
let mut ctx = SpendContext::new();
StandardLayer::new(spender().public_key())
.spend(
&mut ctx,
Coin::new(Bytes32::new([1u8; 32]), spender().puzzle_hash(), 1_000),
Conditions::new()
.create_coin(attacker_owned, 999, Memos::None)
.reserve_fee(1),
)
.unwrap();
let coin_spends = ctx.take();
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
rebalance: OpClassLimits::enabled_up_to(10),
period_cap_mojos: 10,
..AutoSendPolicy::default()
},
);
let escalated = pending(gate.authorize_op(&coin_spends, SpendOpClass::Rebalance));
let summary = escalated.summary();
assert_eq!(
summary.recipients.len(),
1,
"the un-hinted output must appear in the line the human confirms: {summary}"
);
assert_eq!(summary.recipients[0].amount_mojos, 999);
assert_eq!(
summary.native_total_mojos(),
1_000,
"the whole coin leaves, so the whole coin is what is weighed"
);
assert_eq!(
ledger_total(&gate),
0,
"nothing was auto-approved, so nothing was charged"
);
}
#[test]
fn change_returning_to_the_spent_coins_own_puzzle_hash_is_not_counted() {
let mut ctx = SpendContext::new();
StandardLayer::new(spender().public_key())
.spend(
&mut ctx,
Coin::new(Bytes32::new([1u8; 32]), spender().puzzle_hash(), 1_000),
Conditions::new()
.create_coin(spender().puzzle_hash(), 999, Memos::None)
.reserve_fee(1),
)
.unwrap();
let coin_spends = ctx.take();
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
rebalance: OpClassLimits::enabled_up_to(10),
period_cap_mojos: 10,
..AutoSendPolicy::default()
},
);
let approved = approval(gate.authorize_op(&coin_spends, SpendOpClass::Rebalance));
assert!(
approved.summary().recipients.is_empty(),
"returning change to the coin's own puzzle hash moves no value"
);
assert_eq!(approved.summary().fee, 1);
assert_eq!(ledger_total(&gate), 1, "only the fee is charged");
}
#[test]
fn change_to_a_fresh_derivation_is_deliberately_overcounted_and_escalates() {
let fresh_change = WalletKey::from_seed_at(&SPENDER_SEED, ProfileIx(9)).puzzle_hash();
let mut ctx = SpendContext::new();
let recipient = third_party().puzzle_hash();
let hint = ctx.hint(recipient).unwrap();
StandardLayer::new(spender().public_key())
.spend(
&mut ctx,
Coin::new(Bytes32::new([1u8; 32]), spender().puzzle_hash(), 1_000),
Conditions::new()
.create_coin(recipient, 5, hint)
.create_coin(fresh_change, 994, Memos::None)
.reserve_fee(1),
)
.unwrap();
let coin_spends = ctx.take();
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
rebalance: OpClassLimits::enabled_up_to(10),
period_cap_mojos: 1_000,
..AutoSendPolicy::default()
},
);
let escalated = pending(gate.authorize_op(&coin_spends, SpendOpClass::Rebalance));
assert_eq!(
escalated.summary().native_total_mojos(),
1_000,
"the fresh-derivation change is counted, by design"
);
}
#[test]
fn an_unhinted_vault_outflow_to_a_third_party_is_refused_exactly_like_a_hinted_one() {
let stranger = third_party().puzzle_hash();
assert_ne!(
stranger,
hot_wallet().puzzle_hash(),
"the fixture must pay someone other than the hot wallet, or nothing is being tested"
);
let mut ctx = SpendContext::new();
StandardLayer::new(spender().public_key())
.spend(
&mut ctx,
Coin::new(Bytes32::new([1u8; 32]), spender().puzzle_hash(), 1_000),
Conditions::new()
.create_coin(stranger, 999, Memos::None)
.reserve_fee(1),
)
.unwrap();
let gate = gate_with(vault_custody(), permissive_auto_send());
let denied = refusal(gate.authorize_op(&ctx.take(), SpendOpClass::SmallSend));
assert!(
matches!(denied, AccountError::PolicyDenied(_)),
"an un-hinted vault outflow must be forbidden outright, exactly as the hinted one is — \
an escalation here would mean the clawback window can be skipped by omitting a memo, \
got: {denied}"
);
}
#[test]
fn a_spend_whose_input_amounts_do_not_sum_in_a_u64_is_refused_rather_than_wrapped() {
let gate = gate_with(hot_custody(), permissive_auto_send());
let err =
refusal(gate.authorize_op(&two_coin_spend(u64::MAX, u64::MAX), SpendOpClass::Tip));
assert!(
matches!(&err, AccountError::PolicyIndeterminate(m) if m.contains("sum in a u64")),
"an unsummable input total must be indeterminate, and say so: {err}"
);
let judged = gate.authorize_op(&two_coin_spend(1_000, 2_000), SpendOpClass::Tip);
assert!(
!matches!(&judged, Err(AccountError::PolicyIndeterminate(_))),
"the same two-coin shape must be judgeable when its total is representable"
);
}
#[test]
fn a_charge_that_would_overflow_the_rolling_total_is_indeterminate_not_wrapped() {
let gate = gate_with(
CustodyPolicy::Hot(HotWallet {
auto_send_limit: u64::MAX,
}),
permissive_auto_send(),
);
approval(gate.authorize_op(&pays_third_party(u64::MAX), SpendOpClass::Tip));
assert_eq!(ledger_total(&gate), u64::MAX);
let err = refusal(gate.authorize_op(&pays_third_party(1), SpendOpClass::Tip));
assert!(
matches!(&err, AccountError::PolicyIndeterminate(m) if m.contains("overflows u64")),
"the projection must refuse rather than wrap to 0: {err}"
);
}
fn spend_creating(coin_amount: u64, outputs: &[(Bytes32, u64)]) -> Vec<CoinSpend> {
let mut ctx = SpendContext::new();
let mut conditions = Conditions::new();
for (puzzle_hash, amount) in outputs {
let hint = ctx.hint(*puzzle_hash).unwrap();
conditions = conditions.create_coin(*puzzle_hash, *amount, hint);
}
StandardLayer::new(spender().public_key())
.spend(
&mut ctx,
Coin::new(
Bytes32::new([9u8; 32]),
spender().puzzle_hash(),
coin_amount,
),
conditions,
)
.unwrap();
ctx.take()
}
#[test]
fn a_spend_whose_output_amounts_overflow_is_never_approved() {
let gate = gate_with(hot_custody(), permissive_auto_send());
let overflowing = spend_creating(
1_000,
&[
(third_party().puzzle_hash(), u64::MAX),
(third_party().puzzle_hash(), 1_001),
],
);
let err = refusal(gate.authorize_op(&overflowing, SpendOpClass::Tip));
assert!(
matches!(&err, AccountError::Spend(_)),
"an unaccountable spend must be refused at the derivation, before any approval or signature exists: {err}"
);
}
#[test]
fn a_spend_whose_output_amounts_sum_to_exactly_u64_max_is_still_accountable() {
let gate = gate_with(hot_custody(), permissive_auto_send());
let at_the_bound = spend_creating(
u64::MAX,
&[
(third_party().puzzle_hash(), u64::MAX - 1),
(third_party().puzzle_hash(), 1),
],
);
let ruling = gate.authorize_op(&at_the_bound, SpendOpClass::Tip);
assert!(
!matches!(&ruling, Err(AccountError::Spend(_))),
"a spend whose outputs sum to exactly u64::MAX is accountable and must not be refused as though it overflowed"
);
let _ = pending(ruling);
}
#[tokio::test]
async fn a_user_refusal_and_a_structural_refusal_are_distinguishable_outcomes() {
let vault = gate_with(vault_custody(), permissive_auto_send());
let structural = refusal(vault.authorize_op(&pays_third_party(1_000), SpendOpClass::Tip));
let escalated = pending(vault.authorize_op(
&spend_paying(&[(hot_wallet().puzzle_hash(), 1_000)], 0),
SpendOpClass::Tip,
));
let human = denial(
confirmed(
escalated,
crate::auth::provider::SpendDecision::Decline(None),
)
.await,
);
assert!(
matches!(structural, AccountError::PolicyDenied(_)),
"a structural refusal must map to SPEND_NOT_AUTHORIZED -33052: {structural}"
);
assert!(
matches!(human, AccountError::UserDeclined(_)),
"a user's refusal must map to SPEND_DENIED -33053: {human}"
);
assert_ne!(
std::mem::discriminant(&structural),
std::mem::discriminant(&human),
"the wire mapping is a function only if these are different values; collapsing them leaves a host unable to tell 'you said no' from 'the rules say no'"
);
}
}