1#![forbid(unsafe_code)]
5
6use serde::{Deserialize, Serialize};
7use zeroize::Zeroizing;
8
9#[derive(Clone, Debug, Serialize, Deserialize)]
11pub struct KeyHealthStatus {
12 pub group_pubkey: [u8; 32],
14 pub share_index: u16,
16 pub last_check_timestamp: u64,
18 pub responsive: bool,
20 #[serde(default, skip_serializing_if = "Option::is_none")]
22 pub created_at: Option<u64>,
23}
24
25pub const KEY_HEALTH_STALE_THRESHOLD_SECS: u64 = 86400;
27pub const KEY_HEALTH_CRITICAL_THRESHOLD_SECS: u64 = 604800;
29
30impl KeyHealthStatus {
31 pub fn is_stale(&self, now: u64) -> bool {
33 now.saturating_sub(self.last_check_timestamp) >= KEY_HEALTH_STALE_THRESHOLD_SECS
34 }
35
36 pub fn is_critical(&self, now: u64) -> bool {
38 now.saturating_sub(self.last_check_timestamp) >= KEY_HEALTH_CRITICAL_THRESHOLD_SECS
39 }
40}
41
42#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
44pub struct DeviceRegistration {
45 pub signer_pubkey: [u8; 32],
47 pub wallet_name: String,
49 #[serde(
57 default,
58 skip_serializing_if = "Option::is_none",
59 with = "zeroizing_vec_opt"
60 )]
61 pub hmac: Option<Zeroizing<Vec<u8>>>,
62 pub registered_at: u64,
64 #[serde(default, skip_serializing_if = "Option::is_none")]
66 pub device_kind: Option<String>,
67 #[serde(default, skip_serializing_if = "Option::is_none")]
69 pub fingerprint: Option<[u8; 4]>,
70 #[serde(default, skip_serializing_if = "Option::is_none")]
72 pub firmware_version: Option<String>,
73}
74
75mod zeroizing_vec_opt {
76 use super::*;
77 use serde::{Deserializer, Serializer};
78
79 pub fn serialize<S: Serializer>(
80 value: &Option<Zeroizing<Vec<u8>>>,
81 serializer: S,
82 ) -> std::result::Result<S::Ok, S::Error> {
83 match value {
84 Some(v) => serializer.serialize_some(&v[..]),
85 None => serializer.serialize_none(),
86 }
87 }
88
89 pub fn deserialize<'de, D: Deserializer<'de>>(
90 deserializer: D,
91 ) -> std::result::Result<Option<Zeroizing<Vec<u8>>>, D::Error> {
92 let opt: Option<Vec<u8>> = Option::deserialize(deserializer)?;
93 Ok(opt.map(Zeroizing::new))
94 }
95}
96
97impl std::fmt::Debug for DeviceRegistration {
98 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99 f.debug_struct("DeviceRegistration")
100 .field("signer_pubkey", &self.signer_pubkey)
101 .field("wallet_name", &self.wallet_name)
102 .field(
103 "hmac",
104 &self
105 .hmac
106 .as_ref()
107 .map(|h| format!("<redacted; {} bytes>", h.len())),
108 )
109 .field("registered_at", &self.registered_at)
110 .field("device_kind", &self.device_kind)
111 .field("fingerprint", &self.fingerprint.map(hex::encode))
112 .field("firmware_version", &self.firmware_version)
113 .finish()
114 }
115}
116
117#[derive(Clone, Debug, Serialize, Deserialize)]
119pub struct WalletDescriptor {
120 pub group_pubkey: [u8; 32],
122 pub external_descriptor: String,
124 pub internal_descriptor: String,
126 pub network: String,
128 pub created_at: u64,
130 #[serde(default, skip_serializing_if = "Vec::is_empty")]
132 pub device_registrations: Vec<DeviceRegistration>,
133 #[serde(default)]
138 pub policy_hash: [u8; 32],
139 #[serde(
144 default = "default_descriptor_version",
145 deserialize_with = "deserialize_nonzero_version"
146 )]
147 pub version: u32,
148 #[serde(default, skip_serializing_if = "Option::is_none")]
151 pub previous_descriptor_hash: Option<[u8; 32]>,
152 #[serde(default, skip_serializing_if = "Option::is_none")]
157 pub policy: Option<serde_json::Value>,
158}
159
160pub const INITIAL_DESCRIPTOR_VERSION: u32 = 1;
163
164pub fn default_descriptor_version() -> u32 {
167 INITIAL_DESCRIPTOR_VERSION
168}
169
170fn deserialize_nonzero_version<'de, D>(deserializer: D) -> Result<u32, D::Error>
171where
172 D: serde::Deserializer<'de>,
173{
174 use serde::Deserialize;
175 let v = u32::deserialize(deserializer)?;
176 if v == 0 {
177 return Err(serde::de::Error::custom(
178 "descriptor version must be >= 1 (versions start at INITIAL_DESCRIPTOR_VERSION)",
179 ));
180 }
181 Ok(v)
182}
183
184pub fn fold_descriptor_version_suffix(hasher: &mut sha2::Sha256, version: u32) {
192 use sha2::Digest;
193 if version > INITIAL_DESCRIPTOR_VERSION {
194 hasher.update(b"keep/descriptor/version");
195 hasher.update(version.to_le_bytes());
196 }
197}
198
199pub fn canonical_descriptor_hash(
211 external_descriptor: &str,
212 internal_descriptor: &str,
213 policy_hash: &[u8; 32],
214 version: u32,
215) -> std::result::Result<[u8; 32], CanonicalHashError> {
216 use sha2::{Digest, Sha256};
217 if version == 0 {
218 return Err(CanonicalHashError::ZeroVersion);
219 }
220 let mut h = Sha256::new();
221 h.update((external_descriptor.len() as u64).to_le_bytes());
222 h.update(external_descriptor.as_bytes());
223 h.update((internal_descriptor.len() as u64).to_le_bytes());
224 h.update(internal_descriptor.as_bytes());
225 h.update(policy_hash);
226 fold_descriptor_version_suffix(&mut h, version);
227 Ok(h.finalize().into())
228}
229
230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
232pub enum CanonicalHashError {
233 ZeroVersion,
235}
236
237impl std::fmt::Display for CanonicalHashError {
238 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
239 match self {
240 CanonicalHashError::ZeroVersion => f.write_str(
241 "canonical descriptor hash requested for version 0 (versions start at 1)",
242 ),
243 }
244 }
245}
246
247impl std::error::Error for CanonicalHashError {}
248
249impl WalletDescriptor {
250 pub fn device_registration(&self, signer_pubkey: &[u8; 32]) -> Option<&DeviceRegistration> {
252 self.device_registrations
253 .iter()
254 .find(|r| &r.signer_pubkey == signer_pubkey)
255 }
256
257 pub fn upsert_device_registration(&mut self, reg: DeviceRegistration) {
259 if let Some(slot) = self
260 .device_registrations
261 .iter_mut()
262 .find(|r| r.signer_pubkey == reg.signer_pubkey)
263 {
264 *slot = reg;
265 } else {
266 self.device_registrations.push(reg);
267 }
268 }
269
270 pub fn canonical_hash(&self) -> [u8; 32] {
284 self.try_canonical_hash()
289 .expect("WalletDescriptor::canonical_hash: version invariant (>= 1) violated")
290 }
291
292 pub fn try_canonical_hash(&self) -> std::result::Result<[u8; 32], CanonicalHashError> {
297 canonical_descriptor_hash(
298 &self.external_descriptor,
299 &self.internal_descriptor,
300 &self.policy_hash,
301 self.version,
302 )
303 }
304}
305
306#[cfg(test)]
307mod tests {
308 use super::*;
309
310 #[test]
311 fn test_descriptor_back_compat_deserializes_without_registrations() {
312 let json = r#"{
313 "group_pubkey": [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
314 "external_descriptor": "tr(xpub.../0/*)#abc",
315 "internal_descriptor": "tr(xpub.../1/*)#def",
316 "network": "testnet",
317 "created_at": 1700000000
318 }"#;
319 let desc: WalletDescriptor = serde_json::from_str(json).expect("back-compat deserialize");
320 assert!(desc.device_registrations.is_empty());
321 assert_eq!(desc.version, 1);
322 assert!(desc.previous_descriptor_hash.is_none());
323 }
324
325 #[test]
326 fn test_upsert_device_registration_inserts_then_replaces() {
327 let mut desc = WalletDescriptor {
328 group_pubkey: [0u8; 32],
329 external_descriptor: String::new(),
330 internal_descriptor: String::new(),
331 network: "testnet".into(),
332 created_at: 0,
333 device_registrations: Vec::new(),
334 policy_hash: [0u8; 32],
335 version: 1,
336 previous_descriptor_hash: None,
337 policy: None,
338 };
339 let signer = [7u8; 32];
340 desc.upsert_device_registration(DeviceRegistration {
341 signer_pubkey: signer,
342 wallet_name: "first".into(),
343 hmac: Some(Zeroizing::new(vec![1, 2, 3])),
344 registered_at: 1,
345 device_kind: None,
346 fingerprint: None,
347 firmware_version: None,
348 });
349 desc.upsert_device_registration(DeviceRegistration {
350 signer_pubkey: signer,
351 wallet_name: "second".into(),
352 hmac: Some(Zeroizing::new(vec![9, 9, 9])),
353 registered_at: 2,
354 device_kind: None,
355 fingerprint: None,
356 firmware_version: None,
357 });
358 assert_eq!(desc.device_registrations.len(), 1);
359 let reg = desc.device_registration(&signer).unwrap();
360 assert_eq!(reg.wallet_name, "second");
361 assert_eq!(
362 reg.hmac.as_ref().map(|v| v.as_slice()),
363 Some(&[9, 9, 9][..])
364 );
365 }
366
367 #[test]
368 fn test_device_registration_back_compat_without_metadata_fields() {
369 let json = r#"{
371 "signer_pubkey": [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
372 "wallet_name": "legacy",
373 "registered_at": 1700000000
374 }"#;
375 let reg: DeviceRegistration =
376 serde_json::from_str(json).expect("legacy DeviceRegistration deserializes");
377 assert!(reg.device_kind.is_none());
378 assert!(reg.fingerprint.is_none());
379 assert!(reg.firmware_version.is_none());
380 assert!(reg.hmac.is_none());
381 let json_out = serde_json::to_string(®).unwrap();
382 assert!(!json_out.contains("device_kind"));
383 assert!(!json_out.contains("fingerprint"));
384 assert!(!json_out.contains("firmware_version"));
385 assert!(!json_out.contains("hmac"));
386 }
387
388 #[test]
389 fn test_device_registration_roundtrip_with_metadata_fields() {
390 let reg = DeviceRegistration {
391 signer_pubkey: [1u8; 32],
392 wallet_name: "treasury".into(),
393 hmac: None,
394 registered_at: 42,
395 device_kind: Some("Coldcard".into()),
396 fingerprint: Some([0xde, 0xad, 0xbe, 0xef]),
397 firmware_version: Some("1.2.3".into()),
398 };
399 let json = serde_json::to_string(®).unwrap();
400 let back: DeviceRegistration = serde_json::from_str(&json).unwrap();
401 assert_eq!(back.device_kind.as_deref(), Some("Coldcard"));
402 assert_eq!(back.fingerprint, Some([0xde, 0xad, 0xbe, 0xef]));
403 assert_eq!(back.firmware_version.as_deref(), Some("1.2.3"));
404 }
405
406 #[test]
407 fn test_wallet_descriptor_roundtrip_preserves_device_registrations() {
408 let reg = DeviceRegistration {
409 signer_pubkey: [7u8; 32],
410 wallet_name: "primary".into(),
411 hmac: Some(Zeroizing::new(vec![0xaa; 32])),
412 registered_at: 1234,
413 device_kind: Some("Ledger".into()),
414 fingerprint: Some([0x01, 0x02, 0x03, 0x04]),
415 firmware_version: Some("2.1.0".into()),
416 };
417 let desc = WalletDescriptor {
418 group_pubkey: [9u8; 32],
419 external_descriptor: "tr(xpub.../0/*)".into(),
420 internal_descriptor: "tr(xpub.../1/*)".into(),
421 network: "bitcoin".into(),
422 created_at: 1700000000,
423 device_registrations: vec![reg],
424 policy_hash: [0u8; 32],
425 version: 1,
426 previous_descriptor_hash: None,
427 policy: None,
428 };
429 let json = serde_json::to_string(&desc).unwrap();
430 let back: WalletDescriptor = serde_json::from_str(&json).unwrap();
431 assert_eq!(back.device_registrations.len(), 1);
432 let r = &back.device_registrations[0];
433 assert_eq!(r.signer_pubkey, [7u8; 32]);
434 assert_eq!(r.wallet_name, "primary");
435 assert_eq!(r.device_kind.as_deref(), Some("Ledger"));
436 assert_eq!(r.fingerprint, Some([0x01, 0x02, 0x03, 0x04]));
437 assert_eq!(r.firmware_version.as_deref(), Some("2.1.0"));
438 assert_eq!(r.hmac.as_deref().map(|h| h.to_vec()), Some(vec![0xaa; 32]));
439 }
440
441 #[test]
442 fn test_canonical_hash_v1_matches_legacy_pre_upgrade_bytes() {
443 let desc = WalletDescriptor {
448 group_pubkey: [0u8; 32],
449 external_descriptor: "tr(xpub.../0/*)#abc".into(),
450 internal_descriptor: "tr(xpub.../1/*)#def".into(),
451 network: "testnet".into(),
452 created_at: 0,
453 device_registrations: Vec::new(),
454 policy_hash: [0xAAu8; 32],
455 version: 1,
456 previous_descriptor_hash: None,
457 policy: None,
458 };
459 let expected = {
462 use sha2::{Digest, Sha256};
463 let mut h = Sha256::new();
464 h.update((desc.external_descriptor.len() as u64).to_le_bytes());
465 h.update(desc.external_descriptor.as_bytes());
466 h.update((desc.internal_descriptor.len() as u64).to_le_bytes());
467 h.update(desc.internal_descriptor.as_bytes());
468 h.update(desc.policy_hash);
469 let out: [u8; 32] = h.finalize().into();
470 out
471 };
472 assert_eq!(desc.canonical_hash(), expected);
473 }
474
475 #[test]
476 fn test_canonical_hash_differs_for_v2() {
477 let mut v1 = WalletDescriptor {
478 group_pubkey: [0u8; 32],
479 external_descriptor: "ext".into(),
480 internal_descriptor: "int".into(),
481 network: "testnet".into(),
482 created_at: 0,
483 device_registrations: Vec::new(),
484 policy_hash: [0u8; 32],
485 version: 1,
486 previous_descriptor_hash: None,
487 policy: None,
488 };
489 let h1 = v1.canonical_hash();
490 v1.version = 2;
491 let h2 = v1.canonical_hash();
492 assert_ne!(h1, h2);
493 }
494
495 #[test]
496 fn test_empty_registrations_roundtrip_omits_field() {
497 let desc = WalletDescriptor {
498 group_pubkey: [0u8; 32],
499 external_descriptor: "a".into(),
500 internal_descriptor: "b".into(),
501 network: "testnet".into(),
502 created_at: 1,
503 device_registrations: Vec::new(),
504 policy_hash: [0u8; 32],
505 version: 1,
506 previous_descriptor_hash: None,
507 policy: None,
508 };
509 let json = serde_json::to_string(&desc).unwrap();
510 assert!(!json.contains("device_registrations"));
511 assert!(!json.contains("\"policy\""));
512 }
513
514 #[test]
515 fn test_descriptor_back_compat_deserializes_without_policy() {
516 let json = r#"{
517 "group_pubkey": [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
518 "external_descriptor": "tr(xpub.../0/*)#abc",
519 "internal_descriptor": "tr(xpub.../1/*)#def",
520 "network": "testnet",
521 "created_at": 1700000000
522 }"#;
523 let desc: WalletDescriptor = serde_json::from_str(json).expect("back-compat deserialize");
524 assert!(desc.policy.is_none());
525 }
526
527 #[test]
528 fn test_descriptor_policy_roundtrips() {
529 let policy = serde_json::json!({
530 "recovery_tiers": [{
531 "threshold": 2,
532 "timelock_months": 6,
533 "key_slots": [
534 {"type": "participant", "share_index": 1},
535 {"type": "external", "xpub": "xpub6...", "fingerprint": "abcdef01"}
536 ]
537 }]
538 });
539 let desc = WalletDescriptor {
540 group_pubkey: [0u8; 32],
541 external_descriptor: "a".into(),
542 internal_descriptor: "b".into(),
543 network: "testnet".into(),
544 created_at: 1,
545 device_registrations: Vec::new(),
546 policy_hash: [0u8; 32],
547 version: 1,
548 previous_descriptor_hash: None,
549 policy: Some(policy.clone()),
550 };
551 let json = serde_json::to_string(&desc).unwrap();
552 let parsed: WalletDescriptor = serde_json::from_str(&json).unwrap();
553 assert_eq!(parsed.policy.as_ref(), Some(&policy));
554 }
555}