1use std::str::FromStr;
4
5use bitcoin::bip32::{ChildNumber, DerivationPath, Xpriv, Xpub};
6use bitcoin::hashes::{sha256, Hash, HashEngine};
7use bitcoin::psbt::Psbt;
8use bitcoin::secp256k1::{Keypair, Message, Secp256k1};
9use bitcoin::sighash::{Prevouts, SighashCache, TapSighashType};
10use bitcoin::taproot::Signature as TaprootSignature;
11use bitcoin::{
12 absolute::LockTime, transaction::Version, Address, Amount, Network, OutPoint, ScriptBuf,
13 Sequence, Transaction, TxIn, TxOut, Txid, Witness, XOnlyPublicKey,
14};
15use zeroize::Zeroizing;
16
17use crate::error::{BitcoinError, Result};
18
19const PROOF_DOMAIN: &[u8] = b"keep-key-proof/v1";
20const INPUT_SATS: u64 = 1000;
21const OUTPUT_SATS: u64 = 546;
22
23fn derive_proof_txid(session_id: &[u8; 32], share_index: u16) -> Txid {
27 let mut engine = sha256::HashEngine::default();
28 engine.input(PROOF_DOMAIN);
29 engine.input(session_id);
30 engine.input(&share_index.to_le_bytes());
31 let hash = sha256::Hash::from_engine(engine);
32 let bytes = hash.to_byte_array();
33 Txid::from_raw_hash(bitcoin::hashes::sha256d::Hash::from_byte_array(bytes))
34}
35
36fn derive_child_xonly(
37 secp: &Secp256k1<bitcoin::secp256k1::All>,
38 account_xpub: &str,
39) -> Result<XOnlyPublicKey> {
40 let xpub = Xpub::from_str(account_xpub)
41 .map_err(|e| BitcoinError::InvalidPsbt(format!("invalid xpub: {e}")))?;
42 let child = xpub
43 .derive_pub(
44 secp,
45 &[
46 ChildNumber::Normal { index: 0 },
47 ChildNumber::Normal { index: 0 },
48 ],
49 )
50 .map_err(|e| BitcoinError::InvalidPsbt(format!("xpub derivation: {e}")))?;
51 Ok(child.to_x_only_pub())
52}
53
54fn compute_sighash(psbt: &Psbt) -> Result<Message> {
55 let witness_utxo = psbt.inputs[0]
56 .witness_utxo
57 .clone()
58 .ok_or(BitcoinError::MissingWitnessUtxo(0))?;
59 let prevouts = [witness_utxo];
60 let mut sighash_cache = SighashCache::new(&psbt.unsigned_tx);
61 let sighash = sighash_cache
62 .taproot_key_spend_signature_hash(0, &Prevouts::All(&prevouts), TapSighashType::Default)
63 .map_err(|e| BitcoinError::Sighash(e.to_string()))?;
64 Message::from_digest_slice(sighash.as_ref()).map_err(|e| BitcoinError::Signing(e.to_string()))
65}
66
67pub fn build_key_proof_psbt(
68 session_id: &[u8; 32],
69 share_index: u16,
70 account_xpub: &str,
71 network: Network,
72) -> Result<Psbt> {
73 let secp = Secp256k1::new();
74 let x_only = derive_child_xonly(&secp, account_xpub)?;
75 let txid = derive_proof_txid(session_id, share_index);
76 let address = Address::p2tr(&secp, x_only, None, network);
77 let script_pubkey = address.script_pubkey();
78
79 let tx = Transaction {
80 version: Version(2),
81 lock_time: LockTime::ZERO,
82 input: vec![TxIn {
83 previous_output: OutPoint { txid, vout: 0 },
84 script_sig: ScriptBuf::new(),
85 sequence: Sequence::ZERO,
86 witness: Witness::default(),
87 }],
88 output: vec![TxOut {
89 value: Amount::from_sat(OUTPUT_SATS),
90 script_pubkey: script_pubkey.clone(),
91 }],
92 };
93
94 let mut psbt =
95 Psbt::from_unsigned_tx(tx).map_err(|e| BitcoinError::InvalidPsbt(e.to_string()))?;
96
97 psbt.inputs[0].witness_utxo = Some(TxOut {
98 value: Amount::from_sat(INPUT_SATS),
99 script_pubkey,
100 });
101 psbt.inputs[0].tap_internal_key = Some(x_only);
102
103 Ok(psbt)
104}
105
106pub fn sign_key_proof(
107 psbt: &mut Psbt,
108 signing_secret: &[u8; 32],
109 network: Network,
110) -> Result<Vec<u8>> {
111 let secp = Secp256k1::new();
112 let coin_type = if network == Network::Bitcoin { 0 } else { 1 };
113 let path = DerivationPath::from_str(&format!("m/86'/{coin_type}'/0'/0/0"))
114 .map_err(|e| BitcoinError::Signing(format!("derivation path: {e}")))?;
115
116 let child_bytes = Zeroizing::new({
117 let master = Xpriv::new_master(network, signing_secret)
118 .map_err(|e| BitcoinError::Signing(format!("master key: {e}")))?;
119 let child = master
120 .derive_priv(&secp, &path)
121 .map_err(|e| BitcoinError::Signing(format!("child derivation: {e}")))?;
122 child.private_key.secret_bytes()
123 });
124 let keypair = Keypair::from_seckey_slice(&secp, child_bytes.as_ref())
125 .map_err(|e| BitcoinError::Signing(e.to_string()))?;
126
127 let msg = compute_sighash(psbt)?;
128 let aux_rand = crate::aux_rand()?;
129 let sig = secp.sign_schnorr_with_aux_rand(&msg, &keypair, &aux_rand);
130
131 psbt.inputs[0].tap_key_sig = Some(TaprootSignature {
132 signature: sig,
133 sighash_type: TapSighashType::Default,
134 });
135
136 Ok(psbt.serialize())
137}
138
139pub fn verify_key_proof(
140 session_id: &[u8; 32],
141 share_index: u16,
142 account_xpub: &str,
143 signed_psbt_bytes: &[u8],
144 network: Network,
145) -> Result<()> {
146 let expected_psbt = build_key_proof_psbt(session_id, share_index, account_xpub, network)?;
147
148 let signed_psbt = Psbt::deserialize(signed_psbt_bytes)
149 .map_err(|e| BitcoinError::InvalidPsbt(format!("key proof PSBT: {e}")))?;
150
151 if signed_psbt.unsigned_tx != expected_psbt.unsigned_tx {
152 return Err(BitcoinError::InvalidPsbt(
153 "key proof transaction mismatch".into(),
154 ));
155 }
156
157 let tap_sig = signed_psbt.inputs[0]
158 .tap_key_sig
159 .ok_or_else(|| BitcoinError::InvalidPsbt("key proof missing signature".into()))?;
160
161 if tap_sig.sighash_type != TapSighashType::Default {
162 return Err(BitcoinError::InvalidPsbt(format!(
163 "key proof sighash type must be Default, got {:?}",
164 tap_sig.sighash_type
165 )));
166 }
167
168 let x_only = expected_psbt.inputs[0]
169 .tap_internal_key
170 .ok_or_else(|| BitcoinError::InvalidPsbt("missing tap internal key".into()))?;
171 let msg = compute_sighash(&expected_psbt)?;
172
173 Secp256k1::verification_only()
174 .verify_schnorr(&tap_sig.signature, &msg, &x_only)
175 .map_err(|_| BitcoinError::InvalidPsbt("key proof signature verification failed".into()))
176}
177
178#[cfg(test)]
179mod tests {
180 use super::*;
181
182 fn test_xpub(secret: &[u8; 32], network: Network) -> (String, [u8; 32]) {
183 let secp = Secp256k1::new();
184 let master = Xpriv::new_master(network, secret).unwrap();
185 let coin_type = if network == Network::Bitcoin { 0 } else { 1 };
186 let path = DerivationPath::from_str(&format!("m/86'/{coin_type}'/0'")).unwrap();
187 let account = master.derive_priv(&secp, &path).unwrap();
188 let xpub = Xpub::from_priv(&secp, &account);
189 (xpub.to_string(), *secret)
190 }
191
192 #[test]
193 fn test_deterministic() {
194 let session_id = [1u8; 32];
195 let secret = [42u8; 32];
196 let (xpub, _) = test_xpub(&secret, Network::Testnet);
197
198 let psbt1 = build_key_proof_psbt(&session_id, 1, &xpub, Network::Testnet).unwrap();
199 let psbt2 = build_key_proof_psbt(&session_id, 1, &xpub, Network::Testnet).unwrap();
200
201 assert_eq!(psbt1.serialize(), psbt2.serialize());
202 }
203
204 #[test]
205 fn test_different_session_id() {
206 let secret = [42u8; 32];
207 let (xpub, _) = test_xpub(&secret, Network::Testnet);
208
209 let psbt1 = build_key_proof_psbt(&[1u8; 32], 1, &xpub, Network::Testnet).unwrap();
210 let psbt2 = build_key_proof_psbt(&[2u8; 32], 1, &xpub, Network::Testnet).unwrap();
211
212 assert_ne!(
213 psbt1.unsigned_tx.input[0].previous_output.txid,
214 psbt2.unsigned_tx.input[0].previous_output.txid
215 );
216 }
217
218 #[test]
219 fn test_different_share_index() {
220 let session_id = [1u8; 32];
221 let secret = [42u8; 32];
222 let (xpub, _) = test_xpub(&secret, Network::Testnet);
223
224 let psbt1 = build_key_proof_psbt(&session_id, 1, &xpub, Network::Testnet).unwrap();
225 let psbt2 = build_key_proof_psbt(&session_id, 2, &xpub, Network::Testnet).unwrap();
226
227 assert_ne!(
228 psbt1.unsigned_tx.input[0].previous_output.txid,
229 psbt2.unsigned_tx.input[0].previous_output.txid
230 );
231 }
232
233 #[test]
234 fn test_sign_and_verify_roundtrip() {
235 let session_id = [7u8; 32];
236 let secret = [42u8; 32];
237 let share_index = 3;
238 let (xpub, _) = test_xpub(&secret, Network::Testnet);
239
240 let mut psbt =
241 build_key_proof_psbt(&session_id, share_index, &xpub, Network::Testnet).unwrap();
242 let signed_bytes = sign_key_proof(&mut psbt, &secret, Network::Testnet).unwrap();
243
244 assert!(
246 signed_bytes.len() <= 512,
247 "key proof PSBT {} bytes exceeds protocol max 512",
248 signed_bytes.len(),
249 );
250
251 verify_key_proof(
252 &session_id,
253 share_index,
254 &xpub,
255 &signed_bytes,
256 Network::Testnet,
257 )
258 .unwrap();
259 }
260
261 #[test]
262 fn test_verify_wrong_session_id() {
263 let secret = [42u8; 32];
264 let (xpub, _) = test_xpub(&secret, Network::Testnet);
265
266 let mut psbt = build_key_proof_psbt(&[1u8; 32], 1, &xpub, Network::Testnet).unwrap();
267 let signed_bytes = sign_key_proof(&mut psbt, &secret, Network::Testnet).unwrap();
268
269 let result = verify_key_proof(&[2u8; 32], 1, &xpub, &signed_bytes, Network::Testnet);
270 assert!(result.is_err());
271 }
272
273 #[test]
274 fn test_verify_wrong_xpub() {
275 let session_id = [1u8; 32];
276 let secret1 = [42u8; 32];
277 let secret2 = [43u8; 32];
278 let (xpub1, _) = test_xpub(&secret1, Network::Testnet);
279 let (xpub2, _) = test_xpub(&secret2, Network::Testnet);
280
281 let mut psbt = build_key_proof_psbt(&session_id, 1, &xpub1, Network::Testnet).unwrap();
282 let signed_bytes = sign_key_proof(&mut psbt, &secret1, Network::Testnet).unwrap();
283
284 let result = verify_key_proof(&session_id, 1, &xpub2, &signed_bytes, Network::Testnet);
285 assert!(result.is_err());
286 }
287
288 #[test]
289 fn test_verify_tampered_signature() {
290 let session_id = [1u8; 32];
291 let secret = [42u8; 32];
292 let (xpub, _) = test_xpub(&secret, Network::Testnet);
293
294 let mut psbt = build_key_proof_psbt(&session_id, 1, &xpub, Network::Testnet).unwrap();
295 let mut signed_bytes = sign_key_proof(&mut psbt, &secret, Network::Testnet).unwrap();
296
297 let last = signed_bytes.len() - 1;
298 signed_bytes[last] ^= 0xFF;
299
300 let result = verify_key_proof(&session_id, 1, &xpub, &signed_bytes, Network::Testnet);
301 assert!(result.is_err());
302 }
303
304 #[test]
305 fn test_mainnet() {
306 let session_id = [5u8; 32];
307 let secret = [42u8; 32];
308 let (xpub, _) = test_xpub(&secret, Network::Bitcoin);
309
310 let mut psbt = build_key_proof_psbt(&session_id, 1, &xpub, Network::Bitcoin).unwrap();
311 let signed_bytes = sign_key_proof(&mut psbt, &secret, Network::Bitcoin).unwrap();
312
313 verify_key_proof(&session_id, 1, &xpub, &signed_bytes, Network::Bitcoin).unwrap();
314 }
315}