use std::sync::Arc;
use chia_protocol::CoinSpend;
use dig_session::UnlockedMasterSeed;
use dig_wallet_backend::types::Network;
use crate::error::Result;
use crate::id::ProfileIx;
use crate::keys::wallet_key::WalletKey;
use crate::session_residency::Residency;
use crate::wallet::money_signer::LocalMoneySigner;
use crate::wallet::policy::CustodyPolicy;
use crate::wallet::summary::SpendSummary;
pub struct WalletOps {
seed: Arc<UnlockedMasterSeed>,
profile_ix: ProfileIx,
residency: Arc<Residency>,
}
impl WalletOps {
pub(crate) fn new(
seed: Arc<UnlockedMasterSeed>,
profile_ix: ProfileIx,
residency: Arc<Residency>,
) -> Self {
Self {
seed,
profile_ix,
residency,
}
}
pub(crate) fn wallet_key(&self) -> WalletKey {
let seed = self.seed.master_seed();
WalletKey::from_seed_at(&seed[..], self.profile_ix)
}
pub fn public_key(&self) -> chia_bls::PublicKey {
self.wallet_key().public_key()
}
pub fn puzzle_hash(&self) -> chia_protocol::Bytes32 {
self.wallet_key().puzzle_hash()
}
pub fn address(&self) -> Result<String> {
self.wallet_key().address()
}
pub fn money_signer(&self, network: Network) -> LocalMoneySigner {
LocalMoneySigner::new_canonical(
self.seed.clone(),
self.residency.clone(),
self.profile_ix,
network,
)
}
pub fn summarize(
&self,
coin_spends: &[CoinSpend],
policy: &CustodyPolicy,
) -> Result<SpendSummary> {
SpendSummary::classified(coin_spends, policy)
}
}
#[cfg(test)]
mod tests {
use super::*;
use dig_keystore::{BackendKey, MemoryBackend};
use dig_session::{Password, Session, ENTROPY_LEN};
const SEED: [u8; ENTROPY_LEN] = [0x33; ENTROPY_LEN];
fn seed() -> Arc<UnlockedMasterSeed> {
Arc::new(
Session::enroll_master_seed(
Arc::new(MemoryBackend::new()),
BackendKey::new("k".to_string()),
Password::new("pw"),
&SEED,
)
.unwrap(),
)
}
fn live() -> Arc<Residency> {
Arc::new(Residency::new())
}
#[test]
fn wallet_key_matches_the_canonical_derivation_at_the_profile_index() {
let s = seed();
let ops = WalletOps::new(s.clone(), ProfileIx(5), live());
let expected = WalletKey::from_seed_at(&s.master_seed()[..], ProfileIx(5));
assert_eq!(ops.wallet_key().secret_key(), expected.secret_key());
}
#[test]
fn public_passthroughs_match_the_wallet_key_without_exposing_it() {
let s = seed();
let ops = WalletOps::new(s, ProfileIx(2), live());
assert_eq!(ops.public_key(), ops.wallet_key().public_key());
assert_eq!(ops.puzzle_hash(), ops.wallet_key().puzzle_hash());
assert!(ops.address().unwrap().starts_with("xch1"));
}
#[test]
fn distinct_profiles_derive_distinct_wallet_keys() {
let s = seed();
let k0 = WalletOps::new(s.clone(), ProfileIx::ROOT, live()).wallet_key();
let k1 = WalletOps::new(s, ProfileIx(1), live()).wallet_key();
assert_ne!(k0.secret_key(), k1.secret_key());
}
#[test]
fn wallet_ops_signs_a_real_send_only_by_way_of_the_custody_gate() {
use crate::wallet::approval::SpendRuling;
use crate::wallet::autosend::{AutoSendPolicy, OpClassLimits, SpendOpClass};
use crate::wallet::clock::FixedClock;
use crate::wallet::enforcer::PolicyAuthorizer;
use crate::wallet::money_signer::MoneySigner;
use crate::wallet::policy::HotWallet;
use chia_puzzle_types::Memos;
use chia_wallet_sdk::driver::{SpendContext, StandardLayer};
use chia_wallet_sdk::types::Conditions;
let ops = WalletOps::new(seed(), ProfileIx::ROOT, live());
let wallet_ph = ops.puzzle_hash();
let mut ctx = SpendContext::new();
let coin =
chia_protocol::Coin::new(chia_protocol::Bytes32::new([1u8; 32]), wallet_ph, 1_000);
let recipient = chia_protocol::Bytes32::new([7u8; 32]);
let hint = ctx.hint(recipient).unwrap();
let conditions = Conditions::new()
.create_coin(recipient, 600, hint)
.create_coin(wallet_ph, 390, Memos::None)
.reserve_fee(10);
StandardLayer::new(ops.public_key())
.spend(&mut ctx, coin, conditions)
.unwrap();
let coin_spends = ctx.take();
let gate = PolicyAuthorizer::new(
ProfileIx::ROOT,
CustodyPolicy::Hot(HotWallet {
auto_send_limit: 10_000,
}),
AutoSendPolicy {
enabled: true,
small_send: OpClassLimits::enabled_up_to(1_000),
period_cap_mojos: 1_000,
..AutoSendPolicy::default()
},
&ops.address().unwrap(),
Arc::new(FixedClock::new(1_800_000_000)),
)
.unwrap();
let approval = match gate.authorize_op(&coin_spends, SpendOpClass::SmallSend) {
Ok(SpendRuling::Approved(approval)) => approval,
Ok(SpendRuling::RequiresConfirmation(_)) => panic!("a 610 mojo send is within bounds"),
Err(e) => panic!("the gate refused a legitimate send: {e}"),
};
let bundle = ops
.money_signer(Network::Mainnet)
.sign_approved(approval)
.expect("an approved, wallet-owned send must sign");
assert_eq!(
bundle.coin_spends, coin_spends,
"the signature is paired with the very spends the gate approved"
);
}
fn send_from_profile(ix: ProfileIx, recipient: chia_protocol::Bytes32) -> Vec<CoinSpend> {
use chia_puzzle_types::Memos;
use chia_wallet_sdk::driver::{SpendContext, StandardLayer};
use chia_wallet_sdk::types::Conditions;
let key = WalletKey::from_seed_at(&seed().master_seed()[..], ix);
let mut ctx = SpendContext::new();
let hint = ctx.hint(recipient).unwrap();
StandardLayer::new(key.public_key())
.spend(
&mut ctx,
chia_protocol::Coin::new(
chia_protocol::Bytes32::new([1u8; 32]),
key.puzzle_hash(),
1_000,
),
Conditions::new()
.create_coin(recipient, 600, hint)
.create_coin(key.puzzle_hash(), 390, Memos::None)
.reserve_fee(10),
)
.unwrap();
ctx.take()
}
fn hot_gate_for(profile: ProfileIx) -> crate::wallet::enforcer::PolicyAuthorizer {
use crate::wallet::autosend::{AutoSendPolicy, OpClassLimits};
use crate::wallet::clock::FixedClock;
use crate::wallet::enforcer::PolicyAuthorizer;
use crate::wallet::policy::HotWallet;
let wallet = WalletKey::from_seed_at(&seed().master_seed()[..], profile);
PolicyAuthorizer::new(
profile,
CustodyPolicy::Hot(HotWallet {
auto_send_limit: 10_000,
}),
AutoSendPolicy {
enabled: true,
small_send: OpClassLimits::enabled_up_to(1_000),
period_cap_mojos: 1_000,
..AutoSendPolicy::default()
},
&wallet.address().unwrap(),
Arc::new(FixedClock::new(1_800_000_000)),
)
.unwrap()
}
fn auto_approved(
gate: &crate::wallet::enforcer::PolicyAuthorizer,
coin_spends: &[CoinSpend],
) -> crate::wallet::approval::SpendApproval {
use crate::wallet::approval::SpendRuling;
use crate::wallet::autosend::SpendOpClass;
match gate.authorize_op(coin_spends, SpendOpClass::SmallSend) {
Ok(SpendRuling::Approved(approval)) => approval,
Ok(SpendRuling::RequiresConfirmation(_)) => panic!("a 610 mojo send is within bounds"),
Err(e) => panic!("the gate refused a legitimate send: {e}"),
}
}
#[test]
fn an_approval_minted_for_one_profile_is_refused_by_another_profiles_signer() {
use crate::wallet::money_signer::MoneySigner;
let coin_spends = send_from_profile(ProfileIx(1), chia_protocol::Bytes32::new([7u8; 32]));
let approval = auto_approved(&hot_gate_for(ProfileIx::ROOT), &coin_spends);
let vault_profile_signer =
WalletOps::new(seed(), ProfileIx(1), live()).money_signer(Network::Mainnet);
let err = vault_profile_signer
.sign_approved(approval)
.expect_err("a signer must refuse an approval another profile's gate minted");
assert!(
matches!(&err, crate::error::AccountError::PolicyDenied(m)
if m.contains("profile")),
"the refusal must name the mismatch, not a key failure: {err:?}"
);
}
#[test]
fn a_gate_and_signer_for_the_same_profile_still_sign() {
use crate::wallet::money_signer::MoneySigner;
let coin_spends = send_from_profile(ProfileIx(1), chia_protocol::Bytes32::new([7u8; 32]));
let approval = auto_approved(&hot_gate_for(ProfileIx(1)), &coin_spends);
let bundle = WalletOps::new(seed(), ProfileIx(1), live())
.money_signer(Network::Mainnet)
.sign_approved(approval)
.expect("a correctly-scoped approval must still sign");
assert_eq!(bundle.coin_spends, coin_spends);
}
#[test]
fn a_signer_built_before_the_lock_refuses_after_it() {
use crate::wallet::money_signer::MoneySigner;
let coin_spends = send_from_profile(ProfileIx(1), chia_protocol::Bytes32::new([7u8; 32]));
let approval = auto_approved(&hot_gate_for(ProfileIx(1)), &coin_spends);
let residency = live();
let signer =
WalletOps::new(seed(), ProfileIx(1), residency.clone()).money_signer(Network::Mainnet);
residency.revoke();
let err = signer
.sign_approved(approval)
.expect_err("a signer must not outlive the unlock that produced it");
assert!(
matches!(err, crate::error::AccountError::Locked),
"a locked session is a named outcome, not a generic spend failure: {err:?}"
);
}
}