Skip to main content

keep_core/
wallet.rs

1// SPDX-FileCopyrightText: (C) 2026 PrivKey LLC
2// SPDX-License-Identifier: MIT
3
4#![forbid(unsafe_code)]
5
6use serde::{Deserialize, Serialize};
7use zeroize::Zeroizing;
8
9/// Health status of a key share from a liveness check.
10#[derive(Clone, Debug, Serialize, Deserialize)]
11pub struct KeyHealthStatus {
12    /// The FROST group public key.
13    pub group_pubkey: [u8; 32],
14    /// The share index that was checked.
15    pub share_index: u16,
16    /// Unix timestamp of the last health check.
17    pub last_check_timestamp: u64,
18    /// Whether the share was responsive.
19    pub responsive: bool,
20    /// Unix timestamp when this record was first created (None for legacy records).
21    #[serde(default, skip_serializing_if = "Option::is_none")]
22    pub created_at: Option<u64>,
23}
24
25/// 24 hours - key not checked in this period is considered stale.
26pub const KEY_HEALTH_STALE_THRESHOLD_SECS: u64 = 86400;
27/// 7 days - key not checked in this period is critically stale.
28pub const KEY_HEALTH_CRITICAL_THRESHOLD_SECS: u64 = 604800;
29
30impl KeyHealthStatus {
31    /// Returns true if the last check is older than the stale threshold (24h).
32    pub fn is_stale(&self, now: u64) -> bool {
33        now.saturating_sub(self.last_check_timestamp) >= KEY_HEALTH_STALE_THRESHOLD_SECS
34    }
35
36    /// Returns true if the last check is older than the critical threshold (7d).
37    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/// Record of a hardware signer that has registered this wallet via NIP-46.
43#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
44pub struct DeviceRegistration {
45    /// The NIP-46 signer pubkey (x-only, 32 bytes).
46    pub signer_pubkey: [u8; 32],
47    /// The wallet name sent to the device at registration time.
48    pub wallet_name: String,
49    /// Opaque registration token returned by the device, if any.
50    ///
51    /// This value is **not** cryptographically verified by keep-core; it is
52    /// an arbitrary byte string the device returned at registration time and
53    /// must not be treated as an authenticator unless a verification protocol
54    /// is added. The inner `Vec<u8>` is wrapped in `Zeroizing` so in-memory
55    /// copies are wiped on drop even when the enclosing descriptor is cloned.
56    #[serde(
57        default,
58        skip_serializing_if = "Option::is_none",
59        with = "zeroizing_vec_opt"
60    )]
61    pub hmac: Option<Zeroizing<Vec<u8>>>,
62    /// Unix timestamp of the successful registration.
63    pub registered_at: u64,
64    /// Device kind reported by the signer (e.g. "Coldcard", "Ledger"), if any.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub device_kind: Option<String>,
67    /// BIP32 master key fingerprint reported by the signer, if any.
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub fingerprint: Option<[u8; 4]>,
70    /// Firmware version string reported by the signer, if any.
71    #[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/// A finalized wallet descriptor associated with a FROST group.
118#[derive(Clone, Debug, Serialize, Deserialize)]
119pub struct WalletDescriptor {
120    /// The FROST group public key this descriptor belongs to.
121    pub group_pubkey: [u8; 32],
122    /// The external (receive) descriptor string.
123    pub external_descriptor: String,
124    /// The internal (change) descriptor string.
125    pub internal_descriptor: String,
126    /// The Bitcoin network (e.g. "bitcoin", "testnet", "signet", "regtest").
127    pub network: String,
128    /// Unix timestamp when the descriptor was created.
129    pub created_at: u64,
130    /// Hardware signers that have registered this wallet.
131    #[serde(default, skip_serializing_if = "Vec::is_empty")]
132    pub device_registrations: Vec<DeviceRegistration>,
133    /// Hash of the wallet policy that produced this descriptor. Required for
134    /// canonical descriptor hashing (matches the on-wire `descriptor_hash`
135    /// computed as length-framed
136    /// `sha256(len(ext) || ext || len(int) || int || policy_hash)`).
137    #[serde(default)]
138    pub policy_hash: [u8; 32],
139    /// Monotonic version of the descriptor for this group. Starts at 1 for the
140    /// initial descriptor and increments on each migration. Records persisted
141    /// before versioning materialize as `1` via `#[serde(default)]` +
142    /// [`default_descriptor_version`].
143    #[serde(
144        default = "default_descriptor_version",
145        deserialize_with = "deserialize_nonzero_version"
146    )]
147    pub version: u32,
148    /// Canonical hash of the descriptor this one supersedes, when this is a
149    /// migration. `None` for the initial descriptor.
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub previous_descriptor_hash: Option<[u8; 32]>,
152    /// The wallet policy that produced this descriptor, persisted as an opaque
153    /// JSON value so `keep-core` does not depend on `keep-frost-net`. Callers
154    /// reconstruct `WalletPolicy` via `serde_json::from_value`. Older records
155    /// without this field deserialize with `None`.
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    pub policy: Option<serde_json::Value>,
158}
159
160/// The version assigned to the initial wallet descriptor for a group.
161/// Subsequent migrations increment this monotonically.
162pub const INITIAL_DESCRIPTOR_VERSION: u32 = 1;
163
164/// Default value for [`WalletDescriptor::version`] when deserializing legacy
165/// records that predate the versioning field.
166pub 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
184/// Domain-separated version suffix folded into the canonical descriptor hash
185/// for v2+ descriptors. v1 hashes intentionally omit this suffix to remain
186/// bit-identical to records written before descriptor versioning existed.
187///
188/// Centralizing the fold keeps every site that recomputes the descriptor hash
189/// (initiator, ack verifier, migrate verifier, persisted hash) in lockstep.
190/// TODO: drop the conditional in vN+1 once all v1 records are migrated.
191pub 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
199/// Compute the canonical descriptor hash from its constituent parts.
200/// Centralizing this avoids drift between sites that recompute the hash
201/// (initiator, ack verifier, migrate verifier, persisted descriptor, mobile
202/// completion handler). Must match [`WalletDescriptor::canonical_hash`] and the
203/// on-wire `descriptor_hash` used by the FROST PSBT coordination protocol.
204///
205/// Returns an error if `version == 0`, which is invalid by construction
206/// (descriptor versions start at 1 and increment monotonically). A
207/// zero-version hash cannot match any other code path's computation since the
208/// v2+ fold and v1 omission diverge, so producing one would silently corrupt
209/// lineage.
210pub 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/// Error produced when [`canonical_descriptor_hash`] is given invalid inputs.
231#[derive(Debug, Clone, Copy, PartialEq, Eq)]
232pub enum CanonicalHashError {
233    /// `version == 0` was supplied (versions start at 1).
234    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    /// Return the registration record for a signer pubkey, if any.
251    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    /// Insert or update the registration for a signer pubkey.
258    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    /// Canonical descriptor hash with length framing to avoid collisions
271    /// when the split between external/internal shifts:
272    /// `sha256(u64_le(ext.len) || ext || u64_le(int.len) || int || policy_hash
273    ///   [|| "keep/descriptor/version" || u32_le(version) when version > 1])`.
274    ///
275    /// The version suffix is only folded in for v2+ so v1 hashes remain
276    /// bit-identical to records written before descriptor versioning existed
277    /// (mirroring the conditional fold in `hash_policy`).
278    /// TODO: drop the conditional suffix in vN+1 once all v1 records are
279    /// migrated.
280    ///
281    /// Must match the on-wire `descriptor_hash` used by the FROST PSBT
282    /// coordination protocol.
283    pub fn canonical_hash(&self) -> [u8; 32] {
284        // `WalletDescriptor::version` is enforced non-zero by
285        // `deserialize_nonzero_version` and by every in-process constructor, so
286        // this unwrap is unreachable. `try_canonical_hash` is the fallible
287        // entry point for callers that handle raw byte buffers directly.
288        self.try_canonical_hash()
289            .expect("WalletDescriptor::canonical_hash: version invariant (>= 1) violated")
290    }
291
292    /// Fallible variant of [`canonical_hash`] that returns an error rather
293    /// than panicking when `version == 0`. Prefer this in code paths that
294    /// hash freshly-deserialized inputs without re-validating the version
295    /// invariant.
296    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        // Existing on-disk shape, no device_kind/fingerprint/firmware_version
370        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(&reg).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(&reg).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        // Regression: a descriptor with the default version (1) and no
444        // previous_descriptor_hash must produce the same canonical_hash as
445        // before descriptor versioning was introduced. The expected hash is
446        // pinned here so any change to the v1 hashing path is caught.
447        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        // Pinned bytes computed against the legacy formula:
460        // sha256(le_u64(len(ext)) || ext || le_u64(len(int)) || int || policy_hash)
461        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}