use chia_protocol::{Bytes32, CoinSpend, SpendBundle};
use chia_wallet_sdk::signer::{AggSigConstants, RequiredSignature as SdkRequiredSignature};
use dig_wallet_backend::client::{LocalSigner, MasterKey};
use dig_wallet_backend::types::{
IdentityRef, Network, RequiredSignature, SignedBundle, UnsignedSpend, WalletId,
};
use std::sync::Arc;
use dig_session::UnlockedMasterSeed;
use crate::error::{AccountError, Result};
use crate::id::ProfileIx;
use crate::keys::wallet_key::WalletKey;
use crate::session_residency::Residency;
use crate::wallet::approval::SpendApproval;
pub trait MoneySigner: Send + Sync {
fn sign_approved(&self, approval: SpendApproval) -> Result<SpendBundle>;
}
pub struct LocalMoneySigner {
seed: Arc<UnlockedMasterSeed>,
residency: Arc<Residency>,
profile_ix: ProfileIx,
network: Network,
}
impl LocalMoneySigner {
pub(crate) fn new_canonical(
seed: Arc<UnlockedMasterSeed>,
residency: Arc<Residency>,
profile_ix: ProfileIx,
network: Network,
) -> Self {
Self {
seed,
residency,
profile_ix,
network,
}
}
fn live_signer(&self) -> Result<LocalSigner> {
if !self.residency.is_live() {
return Err(AccountError::Locked);
}
let identity = IdentityRef::new(WalletId(0)).with_profile(self.profile_ix.0);
let master = MasterKey::from_seed_bytes(self.seed.master_seed().to_vec());
LocalSigner::new_canonical(identity, master, self.network)
.map_err(|e| AccountError::Spend(format!("cannot build money signer: {e}")))
}
fn wallet_puzzle_hash(&self) -> Bytes32 {
WalletKey::from_seed_at(&self.seed.master_seed()[..], self.profile_ix).puzzle_hash()
}
pub(crate) fn sign_unsigned(
&self,
signer: &LocalSigner,
unsigned: &UnsignedSpend,
) -> Result<SignedBundle> {
signer
.sign_unsigned(unsigned)
.map_err(|e| AccountError::Spend(format!("spend signing refused: {e}")))
}
fn required_signatures(
signer: &LocalSigner,
coin_spends: &[CoinSpend],
) -> Result<Vec<RequiredSignature>> {
let mut allocator = clvmr::Allocator::new();
let constants = AggSigConstants::new(Bytes32::new(signer.agg_sig_me_extra_data()));
let extracted =
SdkRequiredSignature::from_coin_spends(&mut allocator, coin_spends, &constants)
.map_err(|e| {
AccountError::Spend(format!("required-signature extraction failed: {e:?}"))
})?;
let mut required = Vec::with_capacity(extracted.len());
for item in extracted {
match item {
SdkRequiredSignature::Bls(bls) => required.push(RequiredSignature {
public_key: bls.public_key,
message: bls.message(),
}),
SdkRequiredSignature::Secp(_) => {
return Err(AccountError::Spend(
"unexpected secp signature requirement in a wallet spend".into(),
))
}
}
}
Ok(required)
}
}
impl MoneySigner for LocalMoneySigner {
fn sign_approved(&self, approval: SpendApproval) -> Result<SpendBundle> {
let signer = self.live_signer()?;
approval
.scope()
.assert_signable_by(self.profile_ix, self.wallet_puzzle_hash())?;
let unsigned = UnsignedSpend {
coin_spends: approval.coin_spends().to_vec(),
required_signatures: Self::required_signatures(&signer, approval.coin_spends())?,
summary: signer
.reviewable_summary(approval.coin_spends())
.map_err(|e| {
AccountError::Spend(format!("cannot render this spend for signing: {e}"))
})?,
};
Ok(self.sign_unsigned(&signer, &unsigned)?.bundle)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::id::ProfileIx;
use crate::keys::wallet_key::WalletKey;
use crate::wallet::summary::{SpendSummary, SpendTier};
use chia_bls::{aggregate_verify, PublicKey};
use chia_protocol::{Bytes, Coin};
use chia_puzzle_types::Memos;
use chia_wallet_sdk::driver::{Spend, SpendContext, StandardLayer};
use chia_wallet_sdk::types::conditions::AggSigUnsafe;
use chia_wallet_sdk::types::{Condition, Conditions};
use dig_session::{UnlockedMasterSeed, MASTER_SEED_LEN};
use dig_wallet_backend::client::derive_summary;
const ENTROPY: [u8; 32] = [0x42; 32];
const PROFILE: u32 = 0;
fn master_root() -> [u8; MASTER_SEED_LEN] {
bip39::Mnemonic::from_entropy_in(bip39::Language::English, &ENTROPY)
.expect("32 bytes is valid 24-word BIP-39 entropy")
.to_seed("")
}
fn money_key() -> WalletKey {
WalletKey::from_seed_at(&master_root()[..], ProfileIx(PROFILE))
}
fn unlocked_seed() -> Arc<UnlockedMasterSeed> {
use dig_keystore::{BackendKey, MemoryBackend};
use dig_session::{Password, Session};
Arc::new(
Session::enroll_master_seed(
Arc::new(MemoryBackend::new()),
BackendKey::new("money-signer-tests".to_string()),
Password::new("pw"),
&ENTROPY,
)
.expect("the fixture seed must enrol"),
)
}
fn signer() -> LocalMoneySigner {
signer_for(Arc::new(Residency::new()))
}
fn signer_for(residency: Arc<Residency>) -> LocalMoneySigner {
LocalMoneySigner::new_canonical(
unlocked_seed(),
residency,
ProfileIx(PROFILE),
Network::Mainnet,
)
}
fn live_core() -> LocalSigner {
signer().live_signer().expect("a live session must derive")
}
fn gate_derivation(coin_spends: &[CoinSpend]) -> Result<SpendSummary> {
SpendSummary::from_coin_spends(coin_spends, SpendTier::AutoSend)
}
fn approval_over(coin_spends: &[CoinSpend]) -> SpendApproval {
let summary = SpendSummary::from_coin_spends(coin_spends, SpendTier::AutoSend)
.expect("fixture must be summarizable");
let scope = crate::wallet::policy::CustodyScope::new(
ProfileIx(PROFILE),
&crate::wallet::policy::CustodyPolicy::Hot(Default::default()),
money_key().puzzle_hash(),
);
SpendApproval::new(coin_spends.to_vec(), summary, scope)
}
fn sign(coin_spends: &[CoinSpend]) -> Result<chia_bls::Signature> {
signer()
.sign_approved(approval_over(coin_spends))
.map(|bundle| bundle.aggregated_signature)
}
fn wallet_coin(amount: u64, parent_seed: u8) -> Coin {
Coin::new(
Bytes32::new([parent_seed; 32]),
money_key().puzzle_hash(),
amount,
)
}
fn recipient_ph() -> Bytes32 {
Bytes32::new([7u8; 32])
}
fn legit_xch_send(send: u64, fee: u64, coin_amount: u64) -> Vec<CoinSpend> {
let mut ctx = SpendContext::new();
let recipient = recipient_ph();
let hint = ctx.hint(recipient).unwrap();
let change = coin_amount - send - fee;
let mut conditions = Conditions::new().create_coin(recipient, send, hint);
if change > 0 {
conditions = conditions.create_coin(money_key().puzzle_hash(), change, Memos::None);
}
if fee > 0 {
conditions = conditions.reserve_fee(fee);
}
StandardLayer::new(money_key().public_key())
.spend(&mut ctx, wallet_coin(coin_amount, 1), conditions)
.unwrap();
ctx.take()
}
#[test]
fn legit_standard_send_signs_and_verifies() {
let coin_spends = legit_xch_send(600, 10, 1_000);
let signature = sign(&coin_spends).unwrap();
let mut allocator = clvmr::Allocator::new();
let constants = AggSigConstants::new(Bytes32::new(live_core().agg_sig_me_extra_data()));
let pairs: Vec<(PublicKey, Vec<u8>)> =
SdkRequiredSignature::from_coin_spends(&mut allocator, &coin_spends, &constants)
.unwrap()
.into_iter()
.map(|item| match item {
SdkRequiredSignature::Bls(bls) => (bls.public_key, bls.message()),
SdkRequiredSignature::Secp(_) => panic!("unexpected secp"),
})
.collect();
assert!(!pairs.is_empty(), "a real send requires a signature");
assert!(aggregate_verify(
&signature,
pairs.iter().map(|(pk, m)| (pk, m.as_slice())),
));
assert!(pairs.iter().any(|(pk, _)| *pk == money_key().public_key()));
}
#[test]
fn legit_cat_send_signs() {
use chia_wallet_sdk::driver::{Cat, CatSpend, SpendWithConditions};
let wallet_ph = money_key().puzzle_hash();
let cat = {
let mut issue_ctx = SpendContext::new();
let genesis = wallet_coin(1_000, 9);
let issue_hint = issue_ctx.hint(wallet_ph).unwrap();
let issue = Conditions::new().create_coin(wallet_ph, 1_000, issue_hint);
let (_, cats) =
Cat::single_issuance(&mut issue_ctx, genesis.coin_id(), None, 1_000, issue)
.unwrap();
cats[0]
};
let mut ctx = SpendContext::new();
let recipient = recipient_ph();
let send_hint = ctx.hint(recipient).unwrap();
let inner = StandardLayer::new(money_key().public_key())
.spend_with_conditions(
&mut ctx,
Conditions::new()
.create_coin(recipient, 600, send_hint)
.create_coin(wallet_ph, 400, Memos::None),
)
.unwrap();
Cat::spend_all(&mut ctx, &[CatSpend::new(cat, inner)]).unwrap();
let coin_spends = ctx.take();
let result = sign(&coin_spends);
assert!(
result.is_ok(),
"a conserving CAT send from the wallet's own key must sign: {result:?}"
);
}
#[test]
fn engine_supplied_required_signatures_are_not_an_oracle() {
let coin_spends = legit_xch_send(600, 10, 1_000);
let summary = derive_summary(&coin_spends).unwrap();
let core = live_core();
let honest = LocalMoneySigner::required_signatures(&core, &coin_spends).unwrap();
let mut tampered = honest.clone();
tampered.push(RequiredSignature {
public_key: money_key().public_key(),
message: b"attacker-chosen-blank-check".to_vec(),
});
let unsigned = UnsignedSpend {
coin_spends,
required_signatures: tampered,
summary,
};
let err = signer().sign_unsigned(&core, &unsigned).unwrap_err();
assert!(matches!(err, AccountError::Spend(_)), "{err:?}");
}
#[test]
fn agg_sig_unsafe_requirement_is_refused() {
let mut ctx = SpendContext::new();
let recipient = recipient_ph();
let hint = ctx.hint(recipient).unwrap();
let conditions = Conditions::new()
.create_coin(recipient, 600, hint)
.create_coin(money_key().puzzle_hash(), 390, Memos::None)
.reserve_fee(10)
.with(Condition::AggSigUnsafe(AggSigUnsafe::new(
money_key().public_key(),
Bytes::from(b"raw-unbound-drain".to_vec()),
)));
StandardLayer::new(money_key().public_key())
.spend(&mut ctx, wallet_coin(1_000, 1), conditions)
.unwrap();
let refused = gate_derivation(&ctx.take()).unwrap_err();
assert!(
refused.to_string().contains("AGG_SIG_ME"),
"the gate's derivation must refuse a non-AGG_SIG_ME requirement by name: {refused}"
);
}
#[test]
fn solution_malleable_delegated_puzzle_is_refused() {
let mut ctx = SpendContext::new();
let malleable_puzzle = ctx.alloc(&1).unwrap();
let conditions =
Conditions::new().create_coin(money_key().puzzle_hash(), 1_000, Memos::None);
let solution = ctx.alloc(&conditions).unwrap();
let inner = Spend {
puzzle: malleable_puzzle,
solution,
};
let spend = StandardLayer::new(money_key().public_key())
.delegated_inner_spend(&mut ctx, inner)
.unwrap();
ctx.spend(wallet_coin(1_000, 1), spend).unwrap();
let refused = gate_derivation(&ctx.take()).unwrap_err();
assert!(
refused.to_string().contains("quote-form"),
"the gate's derivation must refuse a solution-malleable puzzle by name: {refused}"
);
}
#[test]
fn empty_coin_spends_are_refused_before_an_approval_can_be_minted() {
assert!(
gate_derivation(&[]).is_err(),
"no approval can be minted over an empty spend set"
);
}
#[test]
fn signs_the_pinned_golden_money_key() {
const GOLDEN_SYNTHETIC_PK: [u8; 48] = [
0xad, 0xff, 0xff, 0x01, 0x8d, 0xd7, 0xe4, 0x5e, 0x51, 0x71, 0x79, 0x6d, 0x8c, 0xa0,
0x04, 0xd7, 0xc7, 0xca, 0xdd, 0x10, 0x02, 0x58, 0xfb, 0xdb, 0x5f, 0x65, 0xa2, 0xda,
0x40, 0x48, 0x42, 0x4a, 0x32, 0x41, 0xf5, 0x47, 0x63, 0x72, 0xf7, 0xc4, 0x26, 0xf3,
0xc7, 0xc0, 0xa4, 0xef, 0x3a, 0x58,
];
assert_eq!(money_key().public_key().to_bytes(), GOLDEN_SYNTHETIC_PK);
let coin_spends = legit_xch_send(600, 10, 1_000);
let signature = sign(&coin_spends).unwrap();
let mut allocator = clvmr::Allocator::new();
let constants = AggSigConstants::new(Bytes32::new(live_core().agg_sig_me_extra_data()));
let golden_pk = PublicKey::from_bytes(&GOLDEN_SYNTHETIC_PK).unwrap();
let message =
SdkRequiredSignature::from_coin_spends(&mut allocator, &coin_spends, &constants)
.unwrap()
.into_iter()
.find_map(|item| match item {
SdkRequiredSignature::Bls(bls) if bls.public_key == golden_pk => {
Some(bls.message())
}
_ => None,
})
.expect("the spend must require the golden money key's signature");
assert!(chia_bls::verify(&signature, &golden_pk, &message));
}
#[test]
fn a_melt_of_a_singleton_this_wallet_owns_signs_and_verifies() {
let coin_spends =
crate::wallet::melt_fixture::store_melt_owned_by(money_key().public_key(), 0x11);
let signature = sign(&coin_spends)
.expect("a melt of a singleton this wallet owns must be signable end to end");
let mut allocator = clvmr::Allocator::new();
let constants = AggSigConstants::new(Bytes32::new(live_core().agg_sig_me_extra_data()));
let pairs: Vec<(PublicKey, Vec<u8>)> =
SdkRequiredSignature::from_coin_spends(&mut allocator, &coin_spends, &constants)
.unwrap()
.into_iter()
.map(|item| match item {
SdkRequiredSignature::Bls(bls) => (bls.public_key, bls.message()),
SdkRequiredSignature::Secp(_) => panic!("unexpected secp"),
})
.collect();
assert!(!pairs.is_empty(), "a melt requires a signature");
assert!(
aggregate_verify(&signature, pairs.iter().map(|(pk, m)| (pk, m.as_slice()))),
"the aggregate must verify over the melt's own required signatures"
);
assert!(
pairs.iter().any(|(pk, _)| *pk == money_key().public_key()),
"the destroyed singleton must be owned by the wallet's canonical money key"
);
}
#[test]
fn signing_refuses_a_melt_whose_reviewed_summary_omits_the_destroyed_singleton() {
use dig_wallet_backend::types::UnsignedSpend;
let melt = crate::wallet::melt_fixture::store_melt_owned_by(money_key().public_key(), 0x11);
let signer = signer();
let core = live_core();
let mut claim = core
.reviewable_summary(&melt)
.expect("the melt's own summary renders");
assert!(
!claim.melted_singletons.is_empty(),
"the melt's honest summary must name a destroyed singleton, or removing one is a no-op \
and this test cannot fail"
);
claim.melted_singletons.clear();
let unsigned = UnsignedSpend {
coin_spends: melt.clone(),
required_signatures: LocalMoneySigner::required_signatures(&core, &melt)
.expect("the melt's required signatures extract"),
summary: claim,
};
let refusal = signer
.sign_unsigned(&core, &unsigned)
.expect_err("a melt the reviewed summary never named must not be signed");
assert!(
refusal.to_string().contains("destroyed singletons"),
"the refusal must name the destruction it could not find in the claim: {refusal}"
);
}
#[test]
fn signing_refuses_an_nft_transfer_whose_reviewed_summary_omits_the_operation() {
use crate::wallet::nft_fixture::{nft_transfer_to, RECIPIENT_PUZZLE_HASH};
use dig_wallet_backend::types::UnsignedSpend;
let transfer = nft_transfer_to(money_key().public_key(), RECIPIENT_PUZZLE_HASH, 0x44);
let signer = signer();
let core = live_core();
let mut claim = core
.reviewable_summary(&transfer)
.expect("the transfer's own summary renders");
assert!(
!claim.nft_operations.is_empty(),
"the transfer's honest summary must name an NFT act, or removing one is a no-op and \
this test cannot fail"
);
claim.nft_operations.clear();
let unsigned = UnsignedSpend {
coin_spends: transfer.clone(),
required_signatures: LocalMoneySigner::required_signatures(&core, &transfer)
.expect("the transfer's required signatures extract"),
summary: claim,
};
let refusal = signer
.sign_unsigned(&core, &unsigned)
.expect_err("an NFT act the reviewed summary never named must not be signed");
assert!(
refusal.to_string().contains("NFT operations"),
"the refusal must name the act it could not find in the claim: {refusal}"
);
}
#[test]
fn the_same_nft_transfer_with_its_honest_summary_signs() {
use dig_wallet_backend::types::UnsignedSpend;
use crate::wallet::nft_fixture::{nft_transfer_to, RECIPIENT_PUZZLE_HASH};
let transfer = nft_transfer_to(money_key().public_key(), RECIPIENT_PUZZLE_HASH, 0x44);
let signer = signer();
let core = live_core();
let unsigned = UnsignedSpend {
coin_spends: transfer.clone(),
required_signatures: LocalMoneySigner::required_signatures(&core, &transfer)
.expect("the transfer's required signatures extract"),
summary: core
.reviewable_summary(&transfer)
.expect("the transfer's own summary renders"),
};
let signed = signer
.sign_unsigned(&core, &unsigned)
.expect("an NFT transfer whose summary names it must sign");
assert_eq!(
signed.bundle.coin_spends, transfer,
"the signed bundle must be the very bytes reviewed"
);
}
#[test]
fn an_nft_mint_signs_when_named_and_is_refused_when_not() {
use crate::wallet::nft_fixture::{nft_mint_to, RECIPIENT_PUZZLE_HASH};
use dig_wallet_backend::types::UnsignedSpend;
let mint = nft_mint_to(money_key().public_key(), RECIPIENT_PUZZLE_HASH, 0x55);
let signer = signer();
let core = live_core();
let honest = core
.reviewable_summary(&mint)
.expect("the mint's own summary renders");
assert!(
honest
.nft_operations
.iter()
.any(|op| op.starts_with("mint ")),
"the mint's honest summary must name the mint: {:?}",
honest.nft_operations
);
let unsigned = |summary| UnsignedSpend {
coin_spends: mint.clone(),
required_signatures: LocalMoneySigner::required_signatures(&core, &mint)
.expect("the mint's required signatures extract"),
summary,
};
signer
.sign_unsigned(&core, &unsigned(honest.clone()))
.expect("an NFT mint whose summary names it must sign");
let mut omitted = honest;
omitted.nft_operations.clear();
let refusal = signer
.sign_unsigned(&core, &unsigned(omitted))
.expect_err("a mint the reviewed summary never named must not be signed");
assert!(
refusal.to_string().contains("NFT operations"),
"the refusal must name the act it could not find: {refusal}"
);
}
}