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::wallet::money_signer::LocalMoneySigner;
use crate::wallet::policy::CustodyPolicy;
use crate::wallet::summary::SpendSummary;
pub trait SpendAuthorizer: Send + Sync {
fn authorize(&self, summary: &SpendSummary) -> Result<()>;
}
pub struct WalletOps {
seed: Arc<UnlockedMasterSeed>,
profile_ix: ProfileIx,
}
impl WalletOps {
pub(crate) fn new(seed: Arc<UnlockedMasterSeed>, profile_ix: ProfileIx) -> Self {
Self { seed, profile_ix }
}
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) -> Result<LocalMoneySigner> {
LocalMoneySigner::new_canonical(
self.seed.master_seed().to_vec(),
self.profile_ix.0,
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, SEED_LEN};
const SEED: [u8; SEED_LEN] = [0x33; SEED_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(),
)
}
#[test]
fn wallet_key_matches_the_canonical_derivation_at_the_profile_index() {
let s = seed();
let ops = WalletOps::new(s.clone(), ProfileIx(5));
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));
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).wallet_key();
let k1 = WalletOps::new(s, ProfileIx(1)).wallet_key();
assert_ne!(k0.secret_key(), k1.secret_key());
}
struct AllowIf(bool);
impl SpendAuthorizer for AllowIf {
fn authorize(&self, _summary: &SpendSummary) -> Result<()> {
if self.0 {
Ok(())
} else {
Err(crate::error::AccountError::Auth("refused".into()))
}
}
}
fn sample_summary() -> SpendSummary {
use crate::wallet::summary::{SpendRecipient, SpendTier};
SpendSummary::new(
SpendTier::Confirm,
vec![SpendRecipient {
address: "xch1abc".into(),
amount_mojos: 1,
asset_id: None,
}],
0,
)
}
#[test]
fn spend_authorizer_seam_permits_and_refuses() {
assert!(AllowIf(true).authorize(&sample_summary()).is_ok());
assert!(AllowIf(false).authorize(&sample_summary()).is_err());
}
#[test]
fn wallet_ops_money_signer_signs_a_real_send() {
use crate::wallet::money_signer::MoneySigner;
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);
let synthetic_pk = ops.public_key();
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(synthetic_pk)
.spend(&mut ctx, coin, conditions)
.unwrap();
let signer = ops.money_signer(Network::Mainnet).unwrap();
assert!(signer.sign_coin_spends(&ctx.take()).is_ok());
}
}