use chia_protocol::{Bytes32, Coin};
use chia_wallet_sdk::driver::{ClawbackV2, SpendContext, SpendWithConditions};
use chia_wallet_sdk::prelude::ToTreeHash;
use chia_wallet_sdk::types::Conditions;
use crate::error::{AccountError, Result};
use crate::wallet::clock::Clock;
use crate::wallet::policy::Vault;
pub const MIN_CLAWBACK_SECONDS: u64 = 24 * 60 * 60;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VaultMove {
clawback: ClawbackV2,
}
impl VaultMove {
pub fn to_hot_wallet(
vault: &Vault,
vault_puzzle_hash: Bytes32,
hot_wallet_puzzle_hash: Bytes32,
amount_mojos: u64,
clock: &dyn Clock,
) -> Result<Self> {
if amount_mojos == 0 {
return Err(AccountError::PolicyDenied(
"a vault move must move a non-zero amount".to_string(),
));
}
if hot_wallet_puzzle_hash == vault_puzzle_hash {
return Err(AccountError::PolicyDenied(
"the hot wallet must be a different puzzle hash from the vault, or the cancel and \
settle paths would be controlled by the same key"
.to_string(),
));
}
if vault.clawback_seconds < MIN_CLAWBACK_SECONDS {
return Err(AccountError::PolicyDenied(format!(
"a vault move needs at least a {MIN_CLAWBACK_SECONDS}s clawback window for the user \
to notice and cancel it, but this one is {}s",
vault.clawback_seconds
)));
}
let now_unix = clock.now_unix()?;
let settles_at_unix = now_unix
.checked_add(vault.clawback_seconds)
.ok_or_else(|| {
AccountError::PolicyIndeterminate(
"the clawback window overflows the absolute on-chain timestamp".to_string(),
)
})?;
Ok(Self {
clawback: ClawbackV2::new(
vault_puzzle_hash,
hot_wallet_puzzle_hash,
settles_at_unix,
amount_mojos,
true,
),
})
}
pub fn puzzle_hash(&self) -> Bytes32 {
Bytes32::new(self.clawback.tree_hash().to_bytes())
}
pub fn settles_at_unix(&self) -> u64 {
self.clawback.seconds
}
pub fn amount_mojos(&self) -> u64 {
self.clawback.amount
}
pub fn vault_puzzle_hash(&self) -> Bytes32 {
self.clawback.sender_puzzle_hash
}
pub fn hot_wallet_puzzle_hash(&self) -> Bytes32 {
self.clawback.receiver_puzzle_hash
}
pub fn funding_conditions(&self, ctx: &mut SpendContext) -> Result<Conditions> {
let memos = ctx
.memos(&(
self.clawback.receiver_puzzle_hash,
(self.clawback.memo(), ()),
))
.map_err(|e| {
AccountError::Spend(format!("cannot allocate the vault-move memo: {e:?}"))
})?;
Ok(Conditions::new().create_coin(self.puzzle_hash(), self.amount_mojos(), memos))
}
pub fn coin(&self, funding_coin_id: Bytes32) -> Coin {
Coin::new(funding_coin_id, self.puzzle_hash(), self.amount_mojos())
}
pub fn cancel<I>(
&self,
ctx: &mut SpendContext,
coin: Coin,
vault_layer: &I,
extra: Conditions,
) -> Result<()>
where
I: SpendWithConditions,
{
self.clawback
.recover_coin_spend(ctx, coin, vault_layer, extra)
.map_err(|e| AccountError::Spend(format!("cannot build the vault-move cancel: {e:?}")))
}
pub fn settle<I>(
&self,
ctx: &mut SpendContext,
coin: Coin,
hot_wallet_layer: &I,
extra: Conditions,
) -> Result<()>
where
I: SpendWithConditions,
{
self.clawback
.finish_coin_spend(ctx, coin, hot_wallet_layer, extra)
.map_err(|e| {
AccountError::Spend(format!("cannot build the vault-move settlement: {e:?}"))
})
}
pub fn parse_pending(
allocator: &clvmr::Allocator,
memo: clvmr::NodePtr,
coin: Coin,
hot_wallet_puzzle_hash: Bytes32,
) -> Option<Self> {
ClawbackV2::from_memo(
allocator,
memo,
hot_wallet_puzzle_hash,
coin.amount,
true,
coin.puzzle_hash,
)
.map(|clawback| Self { clawback })
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::wallet::clock::{FixedClock, UnreadableClock};
use chia_wallet_sdk::driver::StandardLayer;
use chia_wallet_sdk::prelude::ToClvm;
use chia_wallet_sdk::test::{expect_spend, Simulator};
use clvmr::Allocator;
use std::slice;
const VAULT_PH: Bytes32 = Bytes32::new([0x11; 32]);
const HOT_PH: Bytes32 = Bytes32::new([0x22; 32]);
const NOW: u64 = 1_800_000_000;
fn at_now() -> FixedClock {
FixedClock::new(NOW)
}
fn move_of(amount: u64) -> VaultMove {
VaultMove::to_hot_wallet(&Vault::default(), VAULT_PH, HOT_PH, amount, &at_now()).unwrap()
}
fn window(clawback_seconds: u64) -> Vault {
Vault { clawback_seconds }
}
#[test]
fn a_default_vault_move_settles_exactly_24_hours_after_it_is_planned() {
let planned = move_of(1_000);
assert_eq!(planned.settles_at_unix(), NOW + 24 * 60 * 60);
assert_eq!(planned.amount_mojos(), 1_000);
assert_eq!(planned.vault_puzzle_hash(), VAULT_PH);
assert_eq!(planned.hot_wallet_puzzle_hash(), HOT_PH);
}
#[test]
fn the_time_locked_coin_puzzle_hash_is_a_pinned_golden() {
assert_eq!(
hex::encode(move_of(1_000).puzzle_hash()),
"1667a84d17199928961692f271826c5c7c28d559f0380e4ad0a91a2d4069de65"
);
}
#[test]
fn a_different_window_amount_or_destination_yields_a_different_locked_coin() {
let base = move_of(1_000).puzzle_hash();
assert_ne!(base, move_of(1_001).puzzle_hash());
assert_ne!(
base,
VaultMove::to_hot_wallet(
&Vault::default(),
VAULT_PH,
HOT_PH,
1_000,
&FixedClock::new(NOW + 1)
)
.unwrap()
.puzzle_hash()
);
assert_ne!(
base,
VaultMove::to_hot_wallet(
&window(MIN_CLAWBACK_SECONDS + 1),
VAULT_PH,
HOT_PH,
1_000,
&at_now()
)
.unwrap()
.puzzle_hash()
);
assert_ne!(
base,
VaultMove::to_hot_wallet(
&Vault::default(),
VAULT_PH,
Bytes32::new([0x33; 32]),
1_000,
&at_now()
)
.unwrap()
.puzzle_hash()
);
}
#[test]
fn every_window_shorter_than_the_floor_is_refused_and_exactly_the_floor_is_not() {
for too_short in [0, 1, 60, MIN_CLAWBACK_SECONDS - 1] {
let err =
VaultMove::to_hot_wallet(&window(too_short), VAULT_PH, HOT_PH, 1_000, &at_now())
.unwrap_err();
assert!(
matches!(err, AccountError::PolicyDenied(_)),
"a {too_short}s window must be refused: {err}"
);
}
let planned = VaultMove::to_hot_wallet(
&window(MIN_CLAWBACK_SECONDS),
VAULT_PH,
HOT_PH,
1_000,
&at_now(),
)
.expect("exactly the floor is a valid window");
assert_eq!(planned.settles_at_unix(), NOW + MIN_CLAWBACK_SECONDS);
}
#[test]
fn the_floor_is_24_hours_and_the_default_vault_uses_it() {
assert_eq!(MIN_CLAWBACK_SECONDS, 24 * 60 * 60);
assert_eq!(Vault::default().clawback_seconds, MIN_CLAWBACK_SECONDS);
}
#[test]
fn a_planned_move_always_settles_after_the_clock_it_was_planned_against() {
for now in [0, 1, NOW, u64::MAX - MIN_CLAWBACK_SECONDS] {
let planned = VaultMove::to_hot_wallet(
&Vault::default(),
VAULT_PH,
HOT_PH,
1_000,
&FixedClock::new(now),
)
.unwrap();
assert!(
planned.settles_at_unix() > now,
"a move planned at {now} settles at {}",
planned.settles_at_unix()
);
assert_eq!(planned.settles_at_unix(), now + 24 * 60 * 60);
}
}
#[test]
fn a_move_cannot_be_planned_against_an_unreadable_clock() {
let err =
VaultMove::to_hot_wallet(&Vault::default(), VAULT_PH, HOT_PH, 1_000, &UnreadableClock)
.unwrap_err();
assert!(matches!(err, AccountError::PolicyIndeterminate(_)), "{err}");
}
#[test]
fn a_zero_amount_move_is_refused() {
let err = VaultMove::to_hot_wallet(&Vault::default(), VAULT_PH, HOT_PH, 0, &at_now())
.unwrap_err();
assert!(matches!(err, AccountError::PolicyDenied(_)), "{err}");
}
#[test]
fn a_hot_wallet_at_the_vaults_own_puzzle_hash_is_refused() {
let err = VaultMove::to_hot_wallet(&Vault::default(), VAULT_PH, VAULT_PH, 1_000, &at_now())
.unwrap_err();
assert!(matches!(err, AccountError::PolicyDenied(_)), "{err}");
}
#[test]
fn a_window_that_overflows_the_absolute_timestamp_is_indeterminate() {
let err = VaultMove::to_hot_wallet(
&Vault::default(),
VAULT_PH,
HOT_PH,
1_000,
&FixedClock::new(u64::MAX - 5),
)
.unwrap_err();
assert!(matches!(err, AccountError::PolicyIndeterminate(_)), "{err}");
}
#[test]
fn the_funding_spend_pays_the_time_locked_coin_and_not_the_hot_wallet() {
let planned = move_of(1_000);
let mut ctx = SpendContext::new();
let conditions = planned.funding_conditions(&mut ctx).unwrap();
let created: Vec<_> = conditions
.into_iter()
.filter_map(|condition| condition.into_create_coin())
.collect();
assert_eq!(created.len(), 1);
assert_eq!(created[0].puzzle_hash, planned.puzzle_hash());
assert_eq!(created[0].amount, 1_000);
assert_ne!(
created[0].puzzle_hash, HOT_PH,
"the funds must land in the time lock, never straight in the hot wallet"
);
}
#[test]
fn a_pending_move_parses_from_its_memo_only_when_it_matches_the_coins_puzzle_hash() {
let planned = move_of(1_000);
let coin = planned.coin(Bytes32::new([0x99; 32]));
let mut allocator = Allocator::new();
let honest = planned.clawback.memo().to_clvm(&mut allocator).unwrap();
assert_eq!(
VaultMove::parse_pending(&allocator, honest, coin, HOT_PH),
Some(planned)
);
let lying = ClawbackV2::new(
VAULT_PH,
HOT_PH,
NOW + MIN_CLAWBACK_SECONDS + 1,
1_000,
true,
)
.memo()
.to_clvm(&mut allocator)
.unwrap();
assert_eq!(
VaultMove::parse_pending(&allocator, lying, coin, HOT_PH),
None,
"a memo that does not reconstruct the coin's puzzle hash proves nothing"
);
}
fn simulated_chain_genesis_clock() -> FixedClock {
FixedClock::new(0)
}
#[test]
fn the_vault_can_cancel_before_the_window_elapses_and_not_after() {
for elapsed in [false, true] {
let mut sim = Simulator::new();
let mut ctx = SpendContext::new();
let window_ends_at = MIN_CLAWBACK_SECONDS;
if elapsed {
sim.set_next_timestamp(window_ends_at).unwrap();
}
let vault = sim.bls(1);
let vault_layer = StandardLayer::new(vault.pk);
let hot = sim.bls(0);
let planned = VaultMove::to_hot_wallet(
&window(window_ends_at),
vault.puzzle_hash,
hot.puzzle_hash,
1,
&simulated_chain_genesis_clock(),
)
.unwrap();
assert_eq!(planned.settles_at_unix(), window_ends_at);
let funding = planned.funding_conditions(&mut ctx).unwrap();
vault_layer.spend(&mut ctx, vault.coin, funding).unwrap();
let locked = planned.coin(vault.coin.coin_id());
sim.spend_coins(ctx.take(), slice::from_ref(&vault.sk))
.unwrap();
planned
.cancel(&mut ctx, locked, &vault_layer, Conditions::new())
.unwrap();
expect_spend(sim.spend_coins(ctx.take(), &[vault.sk]), !elapsed);
if !elapsed {
let returned = Coin::new(locked.coin_id(), vault.puzzle_hash, 1);
assert!(
sim.coin_state(returned.coin_id()).is_some(),
"cancelling must return the funds to the vault"
);
}
}
}
#[test]
fn the_hot_wallet_can_settle_after_the_window_elapses_and_not_before() {
for elapsed in [false, true] {
let mut sim = Simulator::new();
let mut ctx = SpendContext::new();
let window_ends_at = MIN_CLAWBACK_SECONDS;
let vault = sim.bls(1);
let vault_layer = StandardLayer::new(vault.pk);
let hot = sim.bls(0);
let hot_layer = StandardLayer::new(hot.pk);
let planned = VaultMove::to_hot_wallet(
&window(window_ends_at),
vault.puzzle_hash,
hot.puzzle_hash,
1,
&simulated_chain_genesis_clock(),
)
.unwrap();
let funding = planned.funding_conditions(&mut ctx).unwrap();
vault_layer.spend(&mut ctx, vault.coin, funding).unwrap();
let locked = planned.coin(vault.coin.coin_id());
sim.spend_coins(ctx.take(), slice::from_ref(&vault.sk))
.unwrap();
if elapsed {
sim.set_next_timestamp(window_ends_at).unwrap();
}
planned
.settle(&mut ctx, locked, &hot_layer, Conditions::new())
.unwrap();
expect_spend(sim.spend_coins(ctx.take(), &[hot.sk]), elapsed);
if elapsed {
let delivered = Coin::new(locked.coin_id(), hot.puzzle_hash, 1);
assert!(
sim.coin_state(delivered.coin_id()).is_some(),
"settling must deliver the funds to the hot wallet"
);
}
}
}
}