keep-core 0.7.5

Core library for Keep - sovereign key management for Nostr and Bitcoin
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
// SPDX-FileCopyrightText: © 2026 PrivKey LLC
// SPDX-License-Identifier: MIT

//! Error types for keep-core operations.
use thiserror::Error;

/// Machine-readable error codes for programmatic handling.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum ErrorCode {
    E1001,
    E1002,
    E1003,
    E1004,
    E1005,
    E1006,
    E1007,
    E1008,
    E1009,
    E1010,
    E2001,
    E2002,
    E2003,
    E2004,
    E2005,
    E2006,
    E3001,
    E3002,
    E3003,
    E3004,
    E3005,
    E3006,
    E3007,
    E3008,
    E3009,
    E4001,
    E4002,
    E4003,
    E4004,
    E4005,
    E4006,
    E4007,
    E4008,
    E4009,
}

impl std::fmt::Display for ErrorCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{self:?}")
    }
}

/// Storage operation errors.
#[derive(Error, Debug)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum StorageError {
    #[error("[{code}] File not found")]
    FileNotFound { code: ErrorCode, path: String },
    #[error("[{code}] File already exists")]
    FileAlreadyExists { code: ErrorCode, path: String },
    #[error("[{code}] Permission denied")]
    PermissionDenied { code: ErrorCode, path: String },
    #[error("[{code}] Invalid file format: {reason}")]
    InvalidFormat { code: ErrorCode, reason: String },
    #[error("[{code}] Database error: {message}")]
    Database { code: ErrorCode, message: String },
    #[error("[{code}] IO error: {message}")]
    Io { code: ErrorCode, message: String },
    #[error("[{code}] Home directory not found")]
    HomeNotFound { code: ErrorCode },
    #[error("[{code}] Migration failed: {message}")]
    Migration { code: ErrorCode, message: String },
    #[error("[{code}] Serialization failed: {message}")]
    Serialization { code: ErrorCode, message: String },
    #[error("[{code}] Hidden volume full")]
    HiddenVolumeFull { code: ErrorCode },
}

#[allow(missing_docs)]
impl StorageError {
    pub fn file_not_found(path: impl Into<String>) -> Self {
        Self::FileNotFound {
            code: ErrorCode::E1001,
            path: path.into(),
        }
    }

    pub fn file_already_exists(path: impl Into<String>) -> Self {
        Self::FileAlreadyExists {
            code: ErrorCode::E1002,
            path: path.into(),
        }
    }

    pub fn permission_denied(path: impl Into<String>) -> Self {
        Self::PermissionDenied {
            code: ErrorCode::E1003,
            path: path.into(),
        }
    }

    pub fn invalid_format(reason: impl Into<String>) -> Self {
        Self::InvalidFormat {
            code: ErrorCode::E1004,
            reason: reason.into(),
        }
    }

    pub fn corrupted(message: impl Into<String>) -> Self {
        Self::invalid_format(message)
    }

    pub fn database(message: impl Into<String>) -> Self {
        Self::Database {
            code: ErrorCode::E1005,
            message: message.into(),
        }
    }

    pub fn io(message: impl Into<String>) -> Self {
        Self::Io {
            code: ErrorCode::E1006,
            message: message.into(),
        }
    }

    pub fn home_not_found() -> Self {
        Self::HomeNotFound {
            code: ErrorCode::E1007,
        }
    }

    pub fn migration(message: impl Into<String>) -> Self {
        Self::Migration {
            code: ErrorCode::E1008,
            message: message.into(),
        }
    }

    pub fn serialization(message: impl Into<String>) -> Self {
        Self::Serialization {
            code: ErrorCode::E1009,
            message: message.into(),
        }
    }

    pub fn hidden_volume_full() -> Self {
        Self::HiddenVolumeFull {
            code: ErrorCode::E1010,
        }
    }

    pub fn code(&self) -> ErrorCode {
        match self {
            Self::FileNotFound { code, .. }
            | Self::FileAlreadyExists { code, .. }
            | Self::PermissionDenied { code, .. }
            | Self::InvalidFormat { code, .. }
            | Self::Database { code, .. }
            | Self::Io { code, .. }
            | Self::HomeNotFound { code }
            | Self::Migration { code, .. }
            | Self::Serialization { code, .. }
            | Self::HiddenVolumeFull { code } => *code,
        }
    }

    pub fn path(&self) -> Option<&str> {
        match self {
            Self::FileNotFound { path, .. }
            | Self::FileAlreadyExists { path, .. }
            | Self::PermissionDenied { path, .. } => Some(path.as_str()),
            _ => None,
        }
    }
}

/// Cryptographic operation errors.
#[derive(Error, Debug)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum CryptoError {
    #[error("[{code}] Encryption failed: {message}")]
    Encryption { code: ErrorCode, message: String },
    #[error("[{code}] Decryption failed: {message}")]
    Decryption { code: ErrorCode, message: String },
    #[error("[{code}] Invalid key: {message}")]
    InvalidKey { code: ErrorCode, message: String },
    #[error("[{code}] Key derivation failed: {message}")]
    KeyDerivation { code: ErrorCode, message: String },
    #[error("[{code}] Signature verification failed: {message}")]
    SignatureVerification { code: ErrorCode, message: String },
    #[error("[{code}] Invalid signature: {message}")]
    InvalidSignature { code: ErrorCode, message: String },
}

#[allow(missing_docs)]
impl CryptoError {
    pub fn encryption(message: impl Into<String>) -> Self {
        Self::Encryption {
            code: ErrorCode::E2001,
            message: message.into(),
        }
    }

    pub fn decryption(message: impl Into<String>) -> Self {
        Self::Decryption {
            code: ErrorCode::E2002,
            message: message.into(),
        }
    }

    pub fn invalid_key(message: impl Into<String>) -> Self {
        Self::InvalidKey {
            code: ErrorCode::E2003,
            message: message.into(),
        }
    }

    pub fn key_derivation(message: impl Into<String>) -> Self {
        Self::KeyDerivation {
            code: ErrorCode::E2004,
            message: message.into(),
        }
    }

    pub fn kdf(message: impl Into<String>) -> Self {
        Self::key_derivation(message)
    }

    pub fn signature_verification(message: impl Into<String>) -> Self {
        Self::SignatureVerification {
            code: ErrorCode::E2005,
            message: message.into(),
        }
    }

    pub fn invalid_signature(message: impl Into<String>) -> Self {
        Self::InvalidSignature {
            code: ErrorCode::E2006,
            message: message.into(),
        }
    }

    pub fn code(&self) -> ErrorCode {
        match self {
            Self::Encryption { code, .. }
            | Self::Decryption { code, .. }
            | Self::InvalidKey { code, .. }
            | Self::KeyDerivation { code, .. }
            | Self::SignatureVerification { code, .. }
            | Self::InvalidSignature { code, .. } => *code,
        }
    }
}

/// FROST protocol errors.
#[derive(Error, Debug)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum FrostError {
    #[error("[{code}] Threshold not met: need {needed}, have {available}")]
    ThresholdNotMet {
        code: ErrorCode,
        needed: u16,
        available: u16,
    },
    #[error("[{code}] Invalid share: {message}")]
    InvalidShare { code: ErrorCode, message: String },
    #[error("[{code}] Session error: {message}")]
    Session { code: ErrorCode, message: String },
    #[error("[{code}] Commitment error: {message}")]
    Commitment { code: ErrorCode, message: String },
    #[error("[{code}] Signature aggregation failed: {message}")]
    Aggregation { code: ErrorCode, message: String },
    #[error("[{code}] Invalid configuration: {message}")]
    InvalidConfig { code: ErrorCode, message: String },
    #[error("[{code}] DKG failed: {message}")]
    Dkg { code: ErrorCode, message: String },
    #[error("[{code}] Duplicate participant: {identifier}")]
    DuplicateParticipant { code: ErrorCode, identifier: u16 },
    #[error("[{code}] Unknown participant: {identifier}")]
    UnknownParticipant { code: ErrorCode, identifier: u16 },
}

#[allow(missing_docs)]
impl FrostError {
    pub fn threshold_not_met(needed: u16, available: u16) -> Self {
        Self::ThresholdNotMet {
            code: ErrorCode::E3001,
            needed,
            available,
        }
    }

    pub fn invalid_share(message: impl Into<String>) -> Self {
        Self::InvalidShare {
            code: ErrorCode::E3002,
            message: message.into(),
        }
    }

    pub fn session(message: impl Into<String>) -> Self {
        Self::Session {
            code: ErrorCode::E3003,
            message: message.into(),
        }
    }

    pub fn commitment(message: impl Into<String>) -> Self {
        Self::Commitment {
            code: ErrorCode::E3004,
            message: message.into(),
        }
    }

    pub fn aggregation(message: impl Into<String>) -> Self {
        Self::Aggregation {
            code: ErrorCode::E3005,
            message: message.into(),
        }
    }

    pub fn invalid_config(message: impl Into<String>) -> Self {
        Self::InvalidConfig {
            code: ErrorCode::E3006,
            message: message.into(),
        }
    }

    pub fn dkg(message: impl Into<String>) -> Self {
        Self::Dkg {
            code: ErrorCode::E3007,
            message: message.into(),
        }
    }

    pub fn duplicate_participant(identifier: u16) -> Self {
        Self::DuplicateParticipant {
            code: ErrorCode::E3008,
            identifier,
        }
    }

    pub fn unknown_participant(identifier: u16) -> Self {
        Self::UnknownParticipant {
            code: ErrorCode::E3009,
            identifier,
        }
    }

    pub fn code(&self) -> ErrorCode {
        match self {
            Self::ThresholdNotMet { code, .. }
            | Self::InvalidShare { code, .. }
            | Self::Session { code, .. }
            | Self::Commitment { code, .. }
            | Self::Aggregation { code, .. }
            | Self::InvalidConfig { code, .. }
            | Self::Dkg { code, .. }
            | Self::DuplicateParticipant { code, .. }
            | Self::UnknownParticipant { code, .. } => *code,
        }
    }
}

/// Network operation errors.
#[derive(Error, Debug)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum NetworkError {
    #[error("[{code}] Connection failed: {message}")]
    Connection { code: ErrorCode, message: String },
    #[error("[{code}] Relay error: {message}")]
    Relay { code: ErrorCode, message: String },
    #[error("[{code}] Request failed: {message}")]
    Request { code: ErrorCode, message: String },
    #[error("[{code}] Response error: {message}")]
    Response { code: ErrorCode, message: String },
    #[error("[{code}] Timeout: {message}")]
    Timeout { code: ErrorCode, message: String },
    #[error("[{code}] Attestation failed: {message}")]
    Attestation { code: ErrorCode, message: String },
    #[error("[{code}] Subscribe failed: {message}")]
    Subscribe { code: ErrorCode, message: String },
    #[error("[{code}] Publish failed: {message}")]
    Publish { code: ErrorCode, message: String },
    #[error("[{code}] Warden error: {message}")]
    Warden { code: ErrorCode, message: String },
}

#[allow(missing_docs)]
impl NetworkError {
    pub fn connection(message: impl Into<String>) -> Self {
        Self::Connection {
            code: ErrorCode::E4001,
            message: message.into(),
        }
    }

    pub fn relay(message: impl Into<String>) -> Self {
        Self::Relay {
            code: ErrorCode::E4002,
            message: message.into(),
        }
    }

    pub fn request(message: impl Into<String>) -> Self {
        Self::Request {
            code: ErrorCode::E4003,
            message: message.into(),
        }
    }

    pub fn response(message: impl Into<String>) -> Self {
        Self::Response {
            code: ErrorCode::E4004,
            message: message.into(),
        }
    }

    pub fn timeout(message: impl Into<String>) -> Self {
        Self::Timeout {
            code: ErrorCode::E4005,
            message: message.into(),
        }
    }

    pub fn attestation(message: impl Into<String>) -> Self {
        Self::Attestation {
            code: ErrorCode::E4006,
            message: message.into(),
        }
    }

    pub fn subscribe(message: impl Into<String>) -> Self {
        Self::Subscribe {
            code: ErrorCode::E4007,
            message: message.into(),
        }
    }

    pub fn publish(message: impl Into<String>) -> Self {
        Self::Publish {
            code: ErrorCode::E4008,
            message: message.into(),
        }
    }

    pub fn warden(message: impl Into<String>) -> Self {
        Self::Warden {
            code: ErrorCode::E4009,
            message: message.into(),
        }
    }

    pub fn code(&self) -> ErrorCode {
        match self {
            Self::Connection { code, .. }
            | Self::Relay { code, .. }
            | Self::Request { code, .. }
            | Self::Response { code, .. }
            | Self::Timeout { code, .. }
            | Self::Attestation { code, .. }
            | Self::Subscribe { code, .. }
            | Self::Publish { code, .. }
            | Self::Warden { code, .. } => *code,
        }
    }
}

/// Keep operation errors.
#[derive(Error, Debug)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum KeepError {
    #[error("Invalid password")]
    InvalidPassword,
    #[error("Rate limited after repeated unlock failures; try again in {0}s. Exponential backoff is active (1s, 2s, 4s, ..., capped at 300s).")]
    RateLimited(u64),
    #[error("Decryption failed - wrong password or corrupted data")]
    DecryptionFailed,
    #[error("Key not found: {0}")]
    KeyNotFound(String),
    #[error("Key already exists: {0}")]
    KeyAlreadyExists(String),
    #[error("Invalid mnemonic: {0}")]
    InvalidMnemonic(String),
    #[error("Invalid nsec format")]
    InvalidNsec,
    #[error("Invalid npub: {0}")]
    InvalidNpub(String),
    #[error("Keyring full (max {0} keys)")]
    KeyringFull(usize),
    #[error("Keep is locked")]
    Locked,
    #[error("Keep already exists at {0}")]
    AlreadyExists(String),
    #[error("Keep not found at {0}")]
    NotFound(String),
    #[error("Invalid network: {0}")]
    InvalidNetwork(String),
    #[error("Rotation failed: {0}")]
    RotationFailed(String),
    /// Audit-log write failed for a security-critical event. Distinct from
    /// best-effort audit failures (those are only warn-logged): operations
    /// that return this variant performed their side effect (e.g. password /
    /// data-key rotation) but the audit entry could not be persisted, so the
    /// operation is observable only via this error.
    #[error("Audit write failed: {0}")]
    AuditWriteFailed(String),
    #[error("Encryption error: {0}")]
    Encryption(String),
    #[error("Database error: {0}")]
    Database(String),
    /// The vault's redb file is already opened (exclusive lock) by another
    /// process, typically a running `keep serve` daemon. Distinct from `Database`
    /// so read-only CLI commands can detect it and route through the daemon's
    /// inspect socket instead of failing (#533). The payload is a
    /// ready-to-display hint.
    #[error("{0}")]
    VaultAlreadyOpen(String),
    #[error("Migration error: {0}")]
    Migration(String),
    #[error("Home directory not found")]
    HomeNotFound,
    #[error("Permission denied: {0}")]
    PermissionDenied(String),
    #[error("User rejected operation")]
    UserRejected,
    #[error("Invalid input: {0}")]
    InvalidInput(String),
    #[error("Not implemented: {0}")]
    NotImplemented(String),
    #[error("Runtime error: {0}")]
    Runtime(String),
    #[error("Configuration error: {0}")]
    Config(String),
    #[error("FROST error: {0}")]
    Frost(String),
    #[error(transparent)]
    StorageErr(#[from] StorageError),
    #[error(transparent)]
    CryptoErr(#[from] CryptoError),
    #[error(transparent)]
    FrostErr(#[from] FrostError),
    #[error(transparent)]
    NetworkErr(#[from] NetworkError),
    #[error("Serialization error: {0}")]
    Serialization(#[from] bincode::Error),
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    #[error("Capacity exceeded: {0}")]
    CapacityExceeded(String),
    #[error("{0}")]
    Other(String),
}

impl From<crate::entropy::EntropyHealthError> for KeepError {
    fn from(e: crate::entropy::EntropyHealthError) -> Self {
        KeepError::Encryption(e.to_string())
    }
}

#[allow(missing_docs)]
impl KeepError {
    pub fn code(&self) -> Option<ErrorCode> {
        match self {
            Self::StorageErr(e) => Some(e.code()),
            Self::CryptoErr(e) => Some(e.code()),
            Self::FrostErr(e) => Some(e.code()),
            Self::NetworkErr(e) => Some(e.code()),
            _ => None,
        }
    }

    pub fn permission_denied(msg: impl Into<String>) -> Self {
        Self::PermissionDenied(msg.into())
    }

    pub fn invalid_input(msg: impl Into<String>) -> Self {
        Self::InvalidInput(msg.into())
    }

    pub fn not_implemented(msg: impl Into<String>) -> Self {
        Self::NotImplemented(msg.into())
    }

    pub fn runtime(msg: impl Into<String>) -> Self {
        Self::Runtime(msg.into())
    }

    pub fn config(msg: impl Into<String>) -> Self {
        Self::Config(msg.into())
    }
}

impl From<redb::DatabaseError> for KeepError {
    fn from(e: redb::DatabaseError) -> Self {
        KeepError::Database(e.to_string())
    }
}

impl From<redb::TransactionError> for KeepError {
    fn from(e: redb::TransactionError) -> Self {
        KeepError::Database(e.to_string())
    }
}

impl From<redb::TableError> for KeepError {
    fn from(e: redb::TableError) -> Self {
        KeepError::Database(e.to_string())
    }
}

impl From<redb::StorageError> for KeepError {
    fn from(e: redb::StorageError) -> Self {
        KeepError::Database(e.to_string())
    }
}

impl From<redb::CommitError> for KeepError {
    fn from(e: redb::CommitError) -> Self {
        KeepError::Database(e.to_string())
    }
}

/// Result type alias for Keep operations.
pub type Result<T> = std::result::Result<T, KeepError>;