use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
use chia_protocol::Bytes32;
use chia_wallet_sdk::utils::Address;
use crate::error::{AccountError, Result};
use crate::wallet::authorizer::SpendAuthorizer;
use crate::wallet::autosend::{AutoSendPolicy, SpendOpClass};
use crate::wallet::clock::Clock;
use crate::wallet::policy::CustodyPolicy;
use crate::wallet::summary::{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,
clock: Arc<dyn Clock>,
recent: Mutex<VecDeque<AutoSendRecord>>,
}
impl PolicyAuthorizer {
pub fn new(
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 {
custody,
auto_send,
hot_wallet_puzzle_hash: hot_wallet.puzzle_hash,
clock,
recent: Mutex::new(VecDeque::new()),
})
}
pub fn authorize_op(&self, summary: &SpendSummary, op_class: SpendOpClass) -> Result<()> {
let (tier, native_total_mojos) = self.reclassify(summary)?;
match tier {
SpendTier::Vault => {
self.reject_vault_outflow_to_anyone_but_the_hot_wallet(summary)?;
Err(AccountError::RequireAuth(
"a vault spend always requires the full authorization ceremony, at any amount"
.to_string(),
))
}
SpendTier::Confirm => Err(AccountError::RequireAuth(
"a spend over this profile's auto-send allowance requires explicit confirmation"
.to_string(),
)),
SpendTier::AutoSend => self.check_auto_send(summary, op_class, native_total_mojos),
}
}
fn reclassify(&self, summary: &SpendSummary) -> Result<(SpendTier, u64)> {
let native_total_mojos = summary.checked_native_total_mojos()?;
let derived = SpendTier::classify(&self.custody, native_total_mojos);
if derived != summary.tier {
return Err(AccountError::PolicyIndeterminate(format!(
"the summary declares the {:?} tier but this profile's custody policy classifies \
this spend as {derived:?}",
summary.tier
)));
}
Ok((derived, native_total_mojos))
}
fn reject_vault_outflow_to_anyone_but_the_hot_wallet(
&self,
summary: &SpendSummary,
) -> Result<()> {
for recipient in &summary.recipients {
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 check_auto_send(
&self,
summary: &SpendSummary,
op_class: SpendOpClass,
native_total_mojos: u64,
) -> Result<()> {
if !self.auto_send.enabled {
return Err(AccountError::RequireAuth(
"auto-send is switched off for this account".to_string(),
));
}
let limits = self.auto_send.limits_for(op_class)?;
if !limits.enabled {
return Err(AccountError::RequireAuth(format!(
"auto-send is not enabled for {op_class:?} spends"
)));
}
self.reject_amounts_no_mojo_limit_can_bound(summary)?;
if native_total_mojos > limits.per_tx_limit_mojos {
return Err(AccountError::RequireAuth(format!(
"{native_total_mojos} mojos exceeds the {} mojo per-transaction auto-send limit for \
{op_class:?}",
limits.per_tx_limit_mojos
)));
}
self.charge_the_rolling_period_cap(native_total_mojos)
}
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<()> {
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 already: u64 = recent.iter().try_fold(0u64, |sum, record| {
sum.checked_add(record.mojos).ok_or_else(|| {
AccountError::PolicyIndeterminate(
"the auto-send ledger total overflows u64".to_string(),
)
})
})?;
let projected = already.checked_add(total).ok_or_else(|| {
AccountError::PolicyIndeterminate(
"this spend plus the period total overflows u64".to_string(),
)
})?;
if projected > self.auto_send.period_cap_mojos {
return Err(AccountError::RequireAuth(format!(
"this {total} mojo spend would bring the rolling {}s auto-send total to {projected} \
mojos, over the {} mojo cap",
self.auto_send.period_seconds, self.auto_send.period_cap_mojos
)));
}
if total > 0 {
recent.push_back(AutoSendRecord {
at_unix: now,
mojos: total,
});
}
Ok(())
}
}
impl SpendAuthorizer for PolicyAuthorizer {
fn authorize(&self, summary: &SpendSummary) -> Result<()> {
self.authorize_op(summary, SpendOpClass::Undeclared)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::id::ProfileIx;
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::SpendRecipient;
const NOW: u64 = 1_800_000_000;
const CUSTODY_AUTO_SEND_CEILING: u64 = 1_000_000;
fn hot_wallet_address() -> String {
WalletKey::from_seed_at(&[0xA1; 32], ProfileIx::ROOT)
.address()
.unwrap()
}
fn third_party_address() -> String {
WalletKey::from_seed_at(&[0xB2; 32], ProfileIx::ROOT)
.address()
.unwrap()
}
fn xch(address: &str, amount_mojos: u64) -> SpendRecipient {
SpendRecipient {
address: address.to_string(),
amount_mojos,
asset_id: None,
}
}
fn cat(address: &str, amount: u64, asset_id: &str) -> SpendRecipient {
SpendRecipient {
address: address.to_string(),
amount_mojos: amount,
asset_id: Some(asset_id.to_string()),
}
}
fn summary_under(
custody: &CustodyPolicy,
recipients: Vec<SpendRecipient>,
fee: u64,
) -> SpendSummary {
let mut summary = SpendSummary::new(SpendTier::Confirm, recipients, fee);
summary.tier = SpendTier::classify(custody, summary.native_total_mojos());
summary
}
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,
}
}
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(custody, auto_send, &hot_wallet_address(), clock.clone())
.unwrap();
(gate, clock)
}
#[test]
fn a_vault_spend_is_refused_at_every_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 summary = summary_under(
&vault_custody(),
vec![xch(&hot_wallet_address(), amount)],
0,
);
assert_eq!(summary.tier, SpendTier::Vault);
let err = gate
.authorize_op(&summary, SpendOpClass::SmallSend)
.unwrap_err();
assert!(
matches!(err, AccountError::RequireAuth(_)),
"{amount} mojos: {err}"
);
}
}
#[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());
let to_hot = summary_under(&vault_custody(), vec![xch(&hot_wallet_address(), 500)], 0);
let escalated = gate
.authorize_op(&to_hot, SpendOpClass::SmallSend)
.unwrap_err();
assert!(
matches!(escalated, AccountError::RequireAuth(_)),
"vault to hot must escalate, got: {escalated}"
);
let to_stranger =
summary_under(&vault_custody(), vec![xch(&third_party_address(), 500)], 0);
let denied = gate
.authorize_op(&to_stranger, SpendOpClass::SmallSend)
.unwrap_err();
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 summary = summary_under(
&vault_custody(),
vec![
xch(&hot_wallet_address(), 500),
xch(&third_party_address(), 1),
],
0,
);
let err = gate.authorize_op(&summary, SpendOpClass::Tip).unwrap_err();
assert!(matches!(err, AccountError::PolicyDenied(_)), "{err}");
}
#[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();
for address in ["", "not-an-address", "xch1", &hot[..20]] {
let summary = summary_under(&vault_custody(), vec![xch(address, 500)], 0);
let err = gate.authorize_op(&summary, SpendOpClass::Tip).unwrap_err();
assert!(
matches!(err, AccountError::PolicyIndeterminate(_)),
"address {address:?}: {err}"
);
}
}
#[test]
fn an_auto_send_within_the_op_class_the_per_tx_limit_and_the_period_cap_is_permitted() {
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1_000),
period_cap_mojos: 5_000,
..AutoSendPolicy::default()
},
);
let summary = summary_under(&hot_custody(), vec![xch(&third_party_address(), 990)], 10);
assert_eq!(summary.tier, SpendTier::AutoSend);
gate.authorize_op(&summary, SpendOpClass::Tip).unwrap();
}
#[test]
fn an_auto_send_over_the_per_transaction_limit_requires_auth() {
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1_000),
period_cap_mojos: u64::MAX,
..AutoSendPolicy::default()
},
);
let at_limit = summary_under(&hot_custody(), vec![xch(&third_party_address(), 1_000)], 0);
gate.authorize_op(&at_limit, SpendOpClass::Tip)
.expect("a spend exactly at the limit is within it");
let one_over = summary_under(&hot_custody(), vec![xch(&third_party_address(), 1_001)], 0);
assert_eq!(one_over.tier, SpendTier::AutoSend);
let err = gate.authorize_op(&one_over, SpendOpClass::Tip).unwrap_err();
assert!(matches!(err, AccountError::RequireAuth(_)), "{err}");
}
#[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 summary = summary_under(&hot_custody(), vec![xch(&third_party_address(), 1_000)], 1);
let err = gate.authorize_op(&summary, SpendOpClass::Tip).unwrap_err();
assert!(matches!(err, AccountError::RequireAuth(_)), "{err}");
}
#[test]
fn an_auto_send_over_the_rolling_period_cap_requires_auth() {
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1_000),
period_cap_mojos: 1_500,
..AutoSendPolicy::default()
},
);
let spend = summary_under(&hot_custody(), vec![xch(&third_party_address(), 900)], 0);
gate.authorize_op(&spend, SpendOpClass::Tip).unwrap();
let err = gate.authorize_op(&spend, SpendOpClass::Tip).unwrap_err();
assert!(matches!(err, AccountError::RequireAuth(_)), "{err}");
}
#[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()
},
);
let spend = summary_under(&hot_custody(), vec![xch(&third_party_address(), 900)], 0);
gate.authorize_op(&spend, SpendOpClass::Rebalance).unwrap();
let err = gate.authorize_op(&spend, SpendOpClass::Tip).unwrap_err();
assert!(matches!(err, AccountError::RequireAuth(_)), "{err}");
}
#[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()
},
);
let spend = summary_under(&hot_custody(), vec![xch(&third_party_address(), 900)], 0);
gate.authorize_op(&spend, SpendOpClass::Tip).unwrap();
clock.set(NOW + period - 1);
let err = gate.authorize_op(&spend, SpendOpClass::Tip).unwrap_err();
assert!(
matches!(err, AccountError::RequireAuth(_)),
"one second before the window closes the earlier spend must still count: {err}"
);
clock.set(NOW + period);
gate.authorize_op(&spend, SpendOpClass::Tip)
.expect("exactly one period later the allowance has renewed");
}
#[test]
fn a_refused_spend_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()
},
);
let six_hundred = summary_under(&hot_custody(), vec![xch(&third_party_address(), 600)], 0);
let four_hundred = summary_under(&hot_custody(), vec![xch(&third_party_address(), 400)], 0);
gate.authorize_op(&six_hundred, SpendOpClass::Tip)
.expect("600 of the 1000 allowance");
let err = gate
.authorize_op(&six_hundred, SpendOpClass::Tip)
.unwrap_err();
assert!(matches!(err, AccountError::RequireAuth(_)), "{err}");
gate.authorize_op(&four_hundred, SpendOpClass::Tip)
.expect("a refusal must not have consumed the remaining allowance");
}
#[test]
fn a_spend_refused_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()
},
);
let spend = summary_under(&hot_custody(), vec![xch(&third_party_address(), 1_000)], 0);
assert!(gate.authorize_op(&spend, SpendOpClass::Rebalance).is_err());
assert!(gate.authorize_op(&spend, SpendOpClass::Undeclared).is_err());
let over = summary_under(&hot_custody(), vec![xch(&third_party_address(), 1_001)], 0);
assert!(gate.authorize_op(&over, SpendOpClass::Tip).is_err());
gate.authorize_op(&spend, SpendOpClass::Tip)
.expect("the full allowance must still be available");
}
#[test]
fn a_disabled_op_class_is_refused_while_its_enabled_sibling_is_permitted() {
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()
},
);
let summary = summary_under(&hot_custody(), vec![xch(&third_party_address(), 100)], 0);
gate.authorize_op(&summary, SpendOpClass::Tip)
.expect("the enabled class must still pass");
let err = gate
.authorize_op(&summary, SpendOpClass::Rebalance)
.unwrap_err();
assert!(matches!(err, AccountError::RequireAuth(_)), "{err}");
}
#[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()
},
);
let summary = summary_under(&hot_custody(), vec![xch(&third_party_address(), 1)], 0);
let err = gate.authorize_op(&summary, SpendOpClass::Tip).unwrap_err();
assert!(matches!(err, AccountError::RequireAuth(_)), "{err}");
}
#[test]
fn the_global_off_switch_refuses_even_a_spend_that_is_within_every_other_bound() {
let within_everything =
summary_under(&hot_custody(), vec![xch(&third_party_address(), 100)], 0);
let permissive = AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1_000),
period_cap_mojos: u64::MAX,
..AutoSendPolicy::default()
};
gate_with(hot_custody(), permissive)
.authorize_op(&within_everything, SpendOpClass::Tip)
.expect("control: this spend is within every bound while the switch is on");
let switched_off = AutoSendPolicy {
enabled: false,
..permissive
};
let err = gate_with(hot_custody(), switched_off)
.authorize_op(&within_everything, SpendOpClass::Tip)
.unwrap_err();
assert!(matches!(err, AccountError::RequireAuth(_)), "{err}");
}
#[test]
fn the_default_policy_refuses_every_op_class() {
let gate = gate_with(hot_custody(), AutoSendPolicy::default());
let summary = summary_under(&hot_custody(), vec![xch(&third_party_address(), 1)], 0);
for op_class in [
SpendOpClass::Rebalance,
SpendOpClass::Tip,
SpendOpClass::SmallSend,
SpendOpClass::Undeclared,
] {
assert!(
gate.authorize_op(&summary, op_class).is_err(),
"{op_class:?} must be refused under the default policy"
);
}
}
#[test]
fn the_untyped_trait_seam_cannot_auto_approve_even_an_otherwise_approvable_spend() {
let gate = gate_with(hot_custody(), permissive_auto_send());
let summary = summary_under(&hot_custody(), vec![xch(&third_party_address(), 100)], 0);
gate.authorize_op(&summary, SpendOpClass::Tip)
.expect("control: declared intent, within every bound");
let err = SpendAuthorizer::authorize(&gate, &summary).unwrap_err();
assert!(
matches!(err, AccountError::PolicyIndeterminate(_)),
"an undeclared intent is unknown, not merely denied: {err}"
);
}
#[test]
fn a_summary_whose_declared_tier_disagrees_with_the_custody_policy_is_indeterminate() {
let gate = gate_with(hot_custody(), permissive_auto_send());
let mislabelled = SpendSummary::new(
SpendTier::AutoSend,
vec![xch(&third_party_address(), CUSTODY_AUTO_SEND_CEILING + 1)],
0,
);
let err = gate
.authorize_op(&mislabelled, SpendOpClass::Tip)
.unwrap_err();
assert!(matches!(err, AccountError::PolicyIndeterminate(_)), "{err}");
let vault_gate = gate_with(vault_custody(), permissive_auto_send());
let laundered =
SpendSummary::new(SpendTier::AutoSend, vec![xch(&third_party_address(), 1)], 0);
let err = vault_gate
.authorize_op(&laundered, SpendOpClass::Tip)
.unwrap_err();
assert!(
matches!(err, AccountError::PolicyIndeterminate(_)),
"a vault-policy spend must not pass as an auto-send by claiming the tier: {err}"
);
}
#[test]
fn a_spend_paying_a_non_native_asset_is_indeterminate_however_small_its_mojo_total() {
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1_000),
period_cap_mojos: u64::MAX,
..AutoSendPolicy::default()
},
);
let summary = summary_under(
&hot_custody(),
vec![cat(&third_party_address(), 1_000_000_000, "deadbeef")],
1,
);
assert_eq!(
summary.native_total_mojos(),
1,
"the CAT amount is invisible"
);
assert_eq!(summary.tier, SpendTier::AutoSend);
let err = gate.authorize_op(&summary, SpendOpClass::Tip).unwrap_err();
assert!(matches!(err, AccountError::PolicyIndeterminate(_)), "{err}");
}
#[test]
fn a_mixed_native_and_non_native_spend_is_indeterminate() {
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1_000),
period_cap_mojos: u64::MAX,
..AutoSendPolicy::default()
},
);
let summary = summary_under(
&hot_custody(),
vec![
xch(&third_party_address(), 10),
cat(&third_party_address(), u64::MAX, "cafe"),
],
0,
);
let err = gate.authorize_op(&summary, SpendOpClass::Tip).unwrap_err();
assert!(matches!(err, AccountError::PolicyIndeterminate(_)), "{err}");
}
#[test]
fn an_unreadable_clock_refuses_rather_than_assuming_an_empty_window() {
let gate = PolicyAuthorizer::new(
hot_custody(),
permissive_auto_send(),
&hot_wallet_address(),
Arc::new(UnreadableClock),
)
.unwrap();
let summary = summary_under(&hot_custody(), vec![xch(&third_party_address(), 1)], 0);
let err = gate.authorize_op(&summary, SpendOpClass::Tip).unwrap_err();
assert!(matches!(err, AccountError::PolicyIndeterminate(_)), "{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());
let recipients = vec![xch(&third_party_address(), 100)];
for tier in [SpendTier::AutoSend, SpendTier::Confirm, SpendTier::Vault] {
match tier {
SpendTier::AutoSend => {
let summary = summary_under(&hot_custody(), recipients.clone(), 0);
assert_eq!(summary.tier, SpendTier::AutoSend);
gate.authorize_op(&summary, SpendOpClass::Tip).unwrap();
}
SpendTier::Confirm => {
let summary = summary_under(
&hot_custody(),
vec![xch(&third_party_address(), CUSTODY_AUTO_SEND_CEILING + 1)],
0,
);
assert_eq!(summary.tier, SpendTier::Confirm);
let err = gate.authorize_op(&summary, SpendOpClass::Tip).unwrap_err();
assert!(matches!(err, AccountError::RequireAuth(_)), "{err}");
}
SpendTier::Vault => {
let summary = summary_under(&vault_custody(), recipients.clone(), 0);
assert_eq!(summary.tier, SpendTier::Vault);
let err = vault_gate
.authorize_op(&summary, SpendOpClass::Tip)
.unwrap_err();
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(
hot_custody(),
permissive_auto_send(),
address,
Arc::new(FixedClock::new(NOW)),
)
.unwrap_err();
assert!(
matches!(err, AccountError::PolicyIndeterminate(_)),
"address {address:?}: {err}"
);
}
}
#[test]
fn a_vault_refusal_names_the_vault_and_is_not_the_generic_over_allowance_refusal() {
let vault_gate = gate_with(vault_custody(), permissive_auto_send());
let hot_gate = gate_with(hot_custody(), permissive_auto_send());
let vault_spend = summary_under(&vault_custody(), vec![xch(&hot_wallet_address(), 1)], 0);
let over_allowance = summary_under(
&hot_custody(),
vec![xch(&third_party_address(), CUSTODY_AUTO_SEND_CEILING + 1)],
0,
);
let vault_refusal = vault_gate
.authorize_op(&vault_spend, SpendOpClass::Tip)
.unwrap_err()
.to_string();
let confirm_refusal = hot_gate
.authorize_op(&over_allowance, SpendOpClass::Tip)
.unwrap_err()
.to_string();
assert!(
vault_refusal.contains("vault"),
"the vault refusal must say so: {vault_refusal}"
);
assert!(
!confirm_refusal.contains("vault"),
"the over-allowance refusal is not a vault refusal: {confirm_refusal}"
);
assert_ne!(vault_refusal, confirm_refusal);
}
#[test]
fn a_spend_that_brings_the_rolling_total_exactly_to_the_cap_is_permitted_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()
},
);
let six_hundred = summary_under(&hot_custody(), vec![xch(&third_party_address(), 600)], 0);
let four_hundred = summary_under(&hot_custody(), vec![xch(&third_party_address(), 400)], 0);
let one = summary_under(&hot_custody(), vec![xch(&third_party_address(), 1)], 0);
gate.authorize_op(&six_hundred, SpendOpClass::Tip).unwrap();
gate.authorize_op(&four_hundred, SpendOpClass::Tip)
.expect("600 + 400 is exactly the 1000 cap, which is within it");
let err = gate.authorize_op(&one, SpendOpClass::Tip).unwrap_err();
assert!(matches!(err, AccountError::RequireAuth(_)), "{err}");
}
#[test]
fn a_native_total_that_overflows_u64_is_refused_and_never_reported_as_its_wrapped_value() {
let gate = gate_with(
hot_custody(),
AutoSendPolicy {
enabled: true,
tip: OpClassLimits::enabled_up_to(1_000),
period_cap_mojos: 1_000,
..AutoSendPolicy::default()
},
);
let overflowing = SpendSummary::new(
SpendTier::AutoSend,
vec![
xch(&third_party_address(), u64::MAX - 100),
xch(&third_party_address(), 1_000),
],
0,
);
assert!(
overflowing.checked_native_total_mojos().is_err(),
"the total is not representable"
);
assert_ne!(
overflowing.native_total_mojos(),
899,
"the wrapped total would pass every limit"
);
assert_eq!(
overflowing.native_total_mojos(),
u64::MAX,
"saturating biases the unchecked accessor toward refusal"
);
let err = gate
.authorize_op(&overflowing, SpendOpClass::Tip)
.unwrap_err();
assert!(matches!(err, AccountError::PolicyIndeterminate(_)), "{err}");
assert!(
err.to_string().contains("overflow"),
"the refusal must name the overflow, not a tier disagreement: {err}"
);
}
#[test]
fn an_unsummable_total_is_indeterminate_and_not_merely_escalated_to_a_confirmation() {
let gate = gate_with(hot_custody(), permissive_auto_send());
let overflowing = SpendSummary::new(
SpendTier::Confirm,
vec![
xch(&third_party_address(), u64::MAX - 100),
xch(&third_party_address(), 1_000),
],
0,
);
assert_eq!(
SpendTier::classify(&hot_custody(), overflowing.native_total_mojos()),
SpendTier::Confirm,
);
let err = gate
.authorize_op(&overflowing, SpendOpClass::Tip)
.unwrap_err();
assert!(
matches!(err, AccountError::PolicyIndeterminate(_)),
"an uncomputable total must be indeterminate, not escalated: {err}"
);
assert!(err.to_string().contains("overflow"), "{err}");
}
#[test]
fn a_fee_that_overflows_the_native_total_is_refused() {
let gate = gate_with(hot_custody(), permissive_auto_send());
let overflowing = SpendSummary::new(
SpendTier::AutoSend,
vec![xch(&third_party_address(), u64::MAX)],
1,
);
assert!(overflowing.checked_native_total_mojos().is_err());
let err = gate
.authorize_op(&overflowing, SpendOpClass::Tip)
.unwrap_err();
assert!(matches!(err, AccountError::PolicyIndeterminate(_)), "{err}");
assert!(err.to_string().contains("overflow"), "{err}");
}
#[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 summary = summary_under(&hot_custody(), vec![xch(&third_party_address(), 100)], 0);
let err = gate_with(hot_custody(), policy)
.authorize_op(&summary, SpendOpClass::Tip)
.unwrap_err();
assert!(matches!(err, AccountError::PolicyIndeterminate(_)), "{err}");
gate_with(
hot_custody(),
AutoSendPolicy {
period_seconds: 1,
..policy
},
)
.authorize_op(&summary, SpendOpClass::Tip)
.expect("control: the same spend passes once the window has a length");
}
#[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 = summary_under(&hot_custody(), vec![xch(&third_party_address(), 0)], 0);
assert_eq!(nothing.native_total_mojos(), 0);
for _ in 0..1_000 {
gate.authorize_op(¬hing, SpendOpClass::Tip).unwrap();
}
assert_eq!(
gate.recent.lock().unwrap().len(),
0,
"a zero charge must leave no record behind"
);
let full_allowance =
summary_under(&hot_custody(), vec![xch(&third_party_address(), 1_000)], 0);
gate.authorize_op(&full_allowance, SpendOpClass::Tip)
.expect("the whole allowance must still be available");
}
#[test]
fn refuses_to_sign_unhinted_value_leaving_the_wallet_even_when_the_policy_approves() {
use crate::wallet::money_signer::{LocalMoneySigner, MoneySigner};
use chia_protocol::Coin;
use chia_puzzle_types::Memos;
use chia_wallet_sdk::driver::{SpendContext, StandardLayer};
use chia_wallet_sdk::types::Conditions;
use dig_wallet_backend::types::Network;
let seed = [0x5Cu8; 32];
let wallet = WalletKey::from_seed_at(&seed, ProfileIx::ROOT);
let stranger = WalletKey::from_seed_at(&[0xB2; 32], ProfileIx::ROOT).puzzle_hash();
let mut ctx = SpendContext::new();
let coin = Coin::new(Bytes32::new([1u8; 32]), wallet.puzzle_hash(), 1_000);
StandardLayer::new(wallet.public_key())
.spend(
&mut ctx,
coin,
Conditions::new()
.create_coin(stranger, 999, Memos::None)
.reserve_fee(1),
)
.unwrap();
let coin_spends = ctx.take();
let custody = hot_custody();
let summary = SpendSummary::classified(&coin_spends, &custody).unwrap();
assert!(
summary.recipients.is_empty(),
"an un-hinted output is invisible to the summary: {summary:?}"
);
assert_eq!(summary.native_total_mojos(), 1, "only the fee is visible");
let gate = gate_with(
custody,
AutoSendPolicy {
enabled: true,
rebalance: OpClassLimits::enabled_up_to(10),
period_cap_mojos: 10,
..AutoSendPolicy::default()
},
);
gate.authorize_op(&summary, SpendOpClass::Rebalance)
.expect("the policy gate can only bound what the summary shows");
let signer =
LocalMoneySigner::new_canonical(seed.to_vec(), ProfileIx::ROOT.0, Network::Mainnet)
.unwrap();
let err = signer.sign_coin_spends(&coin_spends).unwrap_err();
assert!(
matches!(err, AccountError::Spend(_)),
"the signer must refuse un-hinted value leaving the wallet: {err}"
);
}
}