1#![allow(unused_assignments)]
5
6use crate::address::AddressDerivation;
7use crate::descriptor::DescriptorExport;
8use crate::error::{BitcoinError, Result};
9use crate::psbt::{PsbtAnalysis, PsbtSigner};
10use bitcoin::psbt::Psbt;
11use bitcoin::Network;
12
13pub struct BitcoinSigner {
14 network: Network,
15 address_derivation: AddressDerivation,
16 psbt_signer: PsbtSigner,
17 policy: Option<SigningPolicy>,
18}
19
20#[derive(Clone, Debug, Default)]
21pub struct SigningPolicy {
22 pub max_amount_sats: Option<u64>,
23 pub address_allowlist: Option<Vec<String>>,
24 pub address_blocklist: Option<Vec<String>>,
25 pub require_change_output: bool,
26}
27
28impl BitcoinSigner {
29 pub fn new(secret: &mut [u8; 32], network: Network) -> Result<Self> {
30 let address_derivation = AddressDerivation::new(secret, network)?;
31 let psbt_signer = PsbtSigner::new(secret, network)?;
32
33 Ok(Self {
34 network,
35 address_derivation,
36 psbt_signer,
37 policy: None,
38 })
39 }
40
41 pub fn with_policy(mut self, policy: SigningPolicy) -> Self {
42 self.policy = Some(policy);
43 self
44 }
45
46 pub fn set_policy(&mut self, policy: SigningPolicy) {
47 self.policy = Some(policy);
48 }
49
50 pub fn network(&self) -> Network {
51 self.network
52 }
53
54 pub fn get_receive_address(&self, index: u32) -> Result<String> {
55 let derived = self.address_derivation.get_receive_address(index)?;
56 Ok(derived.address.to_string())
57 }
58
59 pub fn get_change_address(&self, index: u32) -> Result<String> {
60 let derived = self.address_derivation.get_change_address(index)?;
61 Ok(derived.address.to_string())
62 }
63
64 pub fn get_addresses(&self, count: u32) -> Result<Vec<String>> {
65 let addresses = self.address_derivation.get_receive_addresses(count)?;
66 Ok(addresses
67 .into_iter()
68 .map(|a| a.address.to_string())
69 .collect())
70 }
71
72 pub fn export_descriptor(&self, account: u32) -> Result<DescriptorExport> {
73 DescriptorExport::from_derivation(&self.address_derivation, account)
74 }
75
76 pub fn analyze_psbt(&self, psbt: &Psbt) -> Result<PsbtAnalysis> {
77 self.psbt_signer.analyze(psbt)
78 }
79
80 pub fn check_policy(&self, analysis: &PsbtAnalysis) -> Result<()> {
81 let policy = match &self.policy {
82 Some(p) => p,
83 None => return Ok(()),
84 };
85
86 let spend_amount: u64 = analysis
87 .outputs
88 .iter()
89 .filter(|o| !o.is_change)
90 .map(|o| o.amount_sats)
91 .sum();
92
93 if let Some(max) = policy.max_amount_sats {
94 if spend_amount > max {
95 return Err(BitcoinError::AmountExceeded {
96 amount: spend_amount,
97 limit: max,
98 });
99 }
100 }
101
102 if let Some(allowlist) = &policy.address_allowlist {
103 for output in &analysis.outputs {
104 if output.is_change {
105 continue;
106 }
107 if let Some(addr) = &output.address {
108 if !allowlist.contains(addr) {
109 return Err(BitcoinError::AddressNotAllowed(addr.clone()));
110 }
111 }
112 }
113 }
114
115 if let Some(blocklist) = &policy.address_blocklist {
116 for output in &analysis.outputs {
117 if let Some(addr) = &output.address {
118 if blocklist.contains(addr) {
119 return Err(BitcoinError::PolicyDenied(format!(
120 "Address {addr} is blocked"
121 )));
122 }
123 }
124 }
125 }
126
127 if policy.require_change_output {
128 let has_change = analysis.outputs.iter().any(|o| o.is_change);
129 if !has_change {
130 return Err(BitcoinError::PolicyDenied(
131 "Transaction must have change output".into(),
132 ));
133 }
134 }
135
136 Ok(())
137 }
138
139 pub fn sign_psbt(&self, psbt: &mut Psbt) -> Result<usize> {
140 let analysis = self.analyze_psbt(psbt)?;
141 self.check_policy(&analysis)?;
142 self.psbt_signer.sign(psbt)
143 }
144
145 pub fn x_only_public_key(&self) -> [u8; 32] {
146 self.psbt_signer.x_only_public_key().serialize()
147 }
148
149 pub fn fingerprint(&self) -> Result<String> {
150 Ok(self.address_derivation.master_fingerprint()?.to_string())
151 }
152}
153
154#[cfg(test)]
155mod tests {
156 use super::*;
157
158 #[test]
159 fn test_bitcoin_signer() {
160 let mut secret = [1u8; 32];
161 let signer = BitcoinSigner::new(&mut secret, Network::Testnet).unwrap();
162
163 let addr = signer.get_receive_address(0).unwrap();
164 assert!(addr.starts_with("tb1p"));
165 }
166
167 #[test]
168 fn test_signer_with_policy() {
169 let mut secret = [2u8; 32];
170 let policy = SigningPolicy {
171 max_amount_sats: Some(100_000),
172 address_allowlist: None,
173 address_blocklist: None,
174 require_change_output: false,
175 };
176
177 let signer = BitcoinSigner::new(&mut secret, Network::Testnet)
178 .unwrap()
179 .with_policy(policy);
180
181 assert!(signer.policy.is_some());
182 }
183
184 #[test]
185 fn test_export_descriptor() {
186 let mut secret = [3u8; 32];
187 let signer = BitcoinSigner::new(&mut secret, Network::Testnet).unwrap();
188
189 let export = signer.export_descriptor(0).unwrap();
190 assert!(export.descriptor.contains("tr("));
191 }
192
193 #[test]
194 fn test_multiple_addresses() {
195 let mut secret = [4u8; 32];
196 let signer = BitcoinSigner::new(&mut secret, Network::Testnet).unwrap();
197
198 let addresses = signer.get_addresses(5).unwrap();
199 assert_eq!(addresses.len(), 5);
200
201 let unique: std::collections::HashSet<_> = addresses.iter().collect();
202 assert_eq!(unique.len(), 5);
203 }
204}