-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy patherror.rs
More file actions
497 lines (448 loc) · 21.1 KB
/
Copy patherror.rs
File metadata and controls
497 lines (448 loc) · 21.1 KB
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
//! Typed errors for `platform-wallet-storage`.
//!
//! Variants carry the upstream error via `#[source]`/`#[from]`, never a
//! stringified copy; the `#[error("...")]` attribute provides `Display`.
//!
//! At the `PlatformWalletPersistence` boundary this converts into
//! `PersistenceError`: `LockPoisoned` keeps its dedicated variant, and
//! everything else flows through `Backend { kind, source }` where `kind`
//! comes from [`WalletStorageError::persistence_kind`] and `source`
//! preserves the typed error for `Error::source()` walking.
use std::path::PathBuf;
use platform_wallet::changeset::{PersistenceError, PersistenceErrorKind};
use crate::sqlite::util::safe_cast::SafeCastTarget;
/// Which automatic-backup operation was attempted when the
/// configured backup directory was missing or otherwise unwritable.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum AutoBackupOperation {
#[error("open (pending migration)")]
OpenMigration,
#[error("delete_wallet")]
DeleteWallet,
#[error("restore_from")]
Restore,
}
/// Errors produced by the wallet-storage SQLite backend.
#[derive(Debug, thiserror::Error)]
pub enum WalletStorageError {
/// File-system I/O error reaching the database or backup files.
#[error("io error")]
Io(#[from] std::io::Error),
/// Error from rusqlite — covers SQL errors, busy timeouts, and
/// schema-level failures alike. The inner `rusqlite::Error`
/// already discriminates between them.
#[error("sqlite error")]
Sqlite(#[from] rusqlite::Error),
/// Refinery migration runner failure.
#[error("migration error")]
Migration(#[from] refinery::Error),
/// `PRAGMA integrity_check` ran successfully but reported a
/// non-`ok` result. `report` carries SQLite's own diagnostic
/// text — not a user-facing message, not a stringified source.
/// May be multi-line (`\n`-joined): SQLite returns one row per
/// detected problem and the helper preserves every line.
#[error("integrity check failed: {report}")]
IntegrityCheckFailed { report: String },
/// Failed to even run the integrity-check pragma.
#[error("integrity check could not run")]
IntegrityCheckRunFailed {
#[source]
source: rusqlite::Error,
},
/// Cannot open the candidate source database file (most likely
/// not a SQLite database at all, or bytes are torn).
#[error("cannot open candidate source database")]
SourceOpenFailed {
#[source]
source: rusqlite::Error,
},
/// Source backup file lacks the `refinery_schema_history` table —
/// it isn't a wallet-storage database.
#[error("source backup is missing schema_history (not a platform-wallet-storage database)")]
SchemaHistoryMissing,
/// Source backup carries a schema version beyond what this build
/// can apply.
#[error(
"source backup schema version {found} is beyond the supported maximum {max_supported}"
)]
SchemaVersionUnsupported { found: i64, max_supported: i64 },
/// A destructive operation needed an automatic backup but the
/// configuration disabled them.
#[error("auto-backup is disabled for operation: {operation}")]
AutoBackupDisabled { operation: AutoBackupOperation },
/// The configured auto-backup directory could not be created or
/// written to.
#[error("auto-backup directory {} could not be prepared", dir.display())]
AutoBackupDirUnwritable {
dir: PathBuf,
#[source]
source: std::io::Error,
},
/// `delete_wallet` (or another wallet-id-keyed operation) was
/// called with an id that has no matching `wallets` row.
#[error("wallet not found: {}", hex::encode(wallet_id))]
WalletNotFound { wallet_id: [u8; 32] },
/// A changeset entry named a `wallet_id` different from the wallet
/// the flush is scoped to — writing it would mis-file the row under
/// the wrong parent.
#[error(
"wallet id mismatch: entry names {} but flush is scoped to {}",
hex::encode(found),
hex::encode(expected)
)]
WalletIdMismatch { expected: [u8; 32], found: [u8; 32] },
/// A previous holder of an internal mutex panicked. Maps to the
/// trait-level [`PersistenceError::LockPoisoned`] so callers can
/// still pattern-match the boundary variant cleanly.
#[error("persister lock poisoned")]
LockPoisoned,
/// `restore_from` tried to take a SQLite-native `BEGIN EXCLUSIVE`
/// on the destination and a peer (another `SqlitePersister`, a
/// bare `rusqlite::Connection`, the CLI) is holding it busy
/// beyond `busy_timeout`.
#[error("restore destination is locked or in use")]
RestoreDestinationLocked,
/// A wallet-id hex string couldn't be parsed.
#[error("invalid wallet id: bad hex")]
InvalidWalletIdHex {
#[source]
source: hex::FromHexError,
},
/// A wallet-id hex string had the wrong length (must be 64 chars
/// for a 32-byte id).
#[error("invalid wallet id length: expected 64 hex chars, got {actual}")]
InvalidWalletIdLength { actual: usize },
/// A `SqlitePersisterConfig` field carries an unsupported value
/// (e.g. `synchronous = Off`). The `reason` is a compile-time
/// `&'static str` constant naming the rejected setting.
#[error("invalid configuration: {reason}")]
ConfigInvalid { reason: &'static str },
/// bincode-serde refused to encode a value (typically because
/// the value's serde representation needs `deserialize_any`-style
/// dispatch — see dpp's `IdentityPublicKey` workaround).
#[error("bincode encode error")]
BincodeEncode {
#[source]
source: bincode::error::EncodeError,
},
/// bincode-serde refused to decode a payload.
#[error("bincode decode error")]
BincodeDecode {
#[source]
source: bincode::error::DecodeError,
},
/// A typed-column decode failed (e.g. outpoint had the wrong
/// length, or a column held a value the schema doesn't recognise).
#[error("blob/column decode failed: {reason}")]
BlobDecode { reason: &'static str },
/// A typed-column decode failed because an underlying
/// `dashcore::hashes` deserialisation rejected the bytes.
#[error("hash decode failed")]
HashDecode {
#[source]
source: dashcore::hashes::Error,
},
/// A `dashcore` consensus encode/decode failed.
#[error("dashcore consensus encoding failed")]
ConsensusCodec {
#[source]
source: dashcore::consensus::encode::Error,
},
/// The CLI's `backup` subcommand refuses to overwrite an existing
/// destination file.
#[error("backup destination already exists: {}", path.display())]
BackupDestinationExists { path: PathBuf },
/// An `identity_keys` upsert entry's `(identity_id, key_id,
/// wallet_id)` fields disagreed with the map key / flush scope the
/// typed columns are bound from — persisting it would leave the
/// typed columns and the serialized blob describing different rows.
#[error("identity key entry fields disagree with its map key / wallet scope")]
IdentityKeyEntryMismatch,
/// An `identities` upsert entry's `id` disagreed with the map key the
/// `identity_id` column is bound from — persisting it would leave the
/// typed id column and the serialized blob naming different
/// identities.
#[error("identity entry id disagrees with its map key")]
IdentityEntryIdMismatch,
/// An `asset_locks` row's typed-column `(outpoint, account_index)`
/// disagreed with the lifecycle blob's. Rejected at decode time rather
/// than mis-bucketing the lock under the wrong account.
#[error(
"asset_lock entry fields disagree with typed columns \
(typed outpoint={typed_outpoint}, blob outpoint={blob_outpoint}, \
typed account_index={typed_account_index}, blob account_index={blob_account_index})"
)]
AssetLockEntryMismatch {
typed_outpoint: String,
blob_outpoint: String,
typed_account_index: u32,
blob_account_index: u32,
},
/// A blob exceeded the decode allocation cap (default 16 MiB).
/// Separate from [`Self::BlobDecode`] so operators can distinguish an
/// oversize blob from a structural decode failure.
#[error("blob exceeded decode size limit ({len_bytes} bytes > {limit_bytes} byte cap)")]
BlobTooLarge {
len_bytes: usize,
limit_bytes: usize,
},
/// An unspent UTXO named an address absent from
/// `core_derived_addresses`, so its account index can't be resolved.
/// Retained as a fatal-classified typed marker; the apply path no
/// longer raises it — it skips such a UTXO (logged) so one
/// unresolvable row never aborts a whole flush, and the balance
/// re-warms when the address later derives.
#[error("unspent utxo address {address} is not in core_derived_addresses")]
UtxoAddressNotDerived { address: String },
/// A live `addresses_derived` entry arrived without its address in the
/// wallet's `account_address_pools` manifest. The emitter must attach a
/// full pool snapshot in-band with every derivation, so a derived
/// address absent from the manifest means the emitter contract is
/// broken — a logic regression, not a benign SPV gap. Failing loud at
/// the storage trust boundary surfaces it instead of persisting a row
/// the manifest can't vouch for.
#[error(
"emitter contract violated: derived address {address} is absent from the \
account_address_pools manifest (pool snapshot not emitted in-band)"
)]
DerivedIndexInvariantViolated { address: String },
/// `PRAGMA foreign_keys = ON` was issued on open but the read-back
/// reported the constraint enforcement is still off — the linked
/// SQLite build silently ignores the pragma (no FK support compiled
/// in). Hard-error at open rather than letting orphan rows accrue.
#[error("SQLite foreign-key enforcement could not be enabled on this connection")]
ForeignKeysNotEnforced,
/// The requested `journal_mode` read back as a different mode —
/// SQLite silently fell back (e.g. WAL→DELETE on some FUSE mounts).
/// With `synchronous=NORMAL` that risks corruption on power loss, so
/// open hard-errors instead of running downgraded.
#[error("journal_mode {requested} could not be applied (SQLite reports {actual})")]
JournalModeNotApplied {
requested: &'static str,
actual: String,
},
/// A pre-existing / restored DB passed `integrity_check` but its
/// `refinery_schema_history` carries a malformed row (non-RFC3339
/// `applied_on` or non-numeric `checksum`). Probed BEFORE refinery
/// runs so a foreign or corrupted-but-integrity-valid input returns
/// a typed error instead of refinery panicking on the parse.
#[error("refinery_schema_history is malformed: {reason}")]
SchemaHistoryMalformed { reason: &'static str },
/// A restore source / opened DB carries a `refinery_schema_history`
/// (so it is refinery-versioned) but its `application_id` header does
/// not match the wallet-storage magic — it is a foreign SQLite DB,
/// not a wallet database. Rejected before it can be persisted over
/// the live wallet DB or migrated in place.
#[error(
"not a platform-wallet-storage database: application_id {found:#010x} != expected {expected:#010x}"
)]
NotAWalletDb { expected: i32, found: i32 },
/// A second [`SqlitePersister`](crate::SqlitePersister) `open()` on a
/// path already open in THIS process. Each handle has its own
/// `Mutex<Connection>` and write buffer, so buffered writes on one are
/// invisible to the other — silent state divergence. Refused until the
/// first persister drops.
#[error("a SqlitePersister is already open on {} in this process", path.display())]
AlreadyOpen { path: PathBuf },
/// A value couldn't be cast to the database's native i64
/// representation without losing magnitude.
#[error("integer overflow casting `{field}` (value={value}) to {target}")]
IntegerOverflow {
field: &'static str,
value: u64,
target: SafeCastTarget,
},
/// Flush failed transiently (e.g. `SQLITE_BUSY` / `SQLITE_LOCKED`) for
/// `wallet_id`. The buffered changeset is restored, so the next
/// `flush(wallet_id)` retries it merged with anything stored in
/// between. Use **exponential backoff** — tight-looping turns lock
/// contention into a CPU spin that starves the lock holder.
#[error(
"FlushRetryable: flush failed transiently for wallet {}; buffer preserved for retry",
hex::encode(wallet_id)
)]
FlushRetryable {
wallet_id: [u8; 32],
#[source]
source: rusqlite::Error,
},
}
impl From<WalletStorageError> for PersistenceError {
fn from(err: WalletStorageError) -> Self {
match err {
WalletStorageError::LockPoisoned => PersistenceError::LockPoisoned,
other => {
let kind = other.persistence_kind();
PersistenceError::backend_with_kind(kind, other)
}
}
}
}
impl WalletStorageError {
/// Construct a `BlobDecode` error from a static reason. Used by schema
/// modules on a structural decode error (wrong-length id, trailing
/// bytes).
pub(crate) fn blob_decode(reason: &'static str) -> Self {
Self::BlobDecode { reason }
}
/// `true` when the failure is safe to retry — the caller should
/// preserve in-flight state and call again. Transient codes are the
/// recoverable environmental ones: `DatabaseBusy`/`DatabaseLocked`
/// (contention), `DiskFull`, `SystemIoFailure`, `OutOfMemory`.
///
/// The OUTER match is intentionally wildcard-free so a future variant
/// forces explicit classification here; the INNER `ErrorCode` match
/// needs a wildcard because that enum is upstream `#[non_exhaustive]`.
pub fn is_transient(&self) -> bool {
use rusqlite::ErrorCode;
match self {
Self::Sqlite(rusqlite::Error::SqliteFailure(e, _)) => matches!(
e.code,
ErrorCode::DatabaseBusy
| ErrorCode::DatabaseLocked
| ErrorCode::DiskFull
| ErrorCode::SystemIoFailure
| ErrorCode::OutOfMemory
),
Self::FlushRetryable { .. } => true,
// Every other rusqlite variant — non-`SqliteFailure` (e.g.
// `ToSqlConversionFailure`, `InvalidColumnIndex`) — is a
// logic bug, not a contention failure.
Self::Sqlite(_) => false,
Self::Io(_)
| Self::Migration(_)
| Self::IntegrityCheckFailed { .. }
| Self::IntegrityCheckRunFailed { .. }
| Self::SourceOpenFailed { .. }
| Self::SchemaHistoryMissing
| Self::SchemaVersionUnsupported { .. }
| Self::AutoBackupDisabled { .. }
| Self::AutoBackupDirUnwritable { .. }
| Self::WalletNotFound { .. }
| Self::WalletIdMismatch { .. }
// TODO(qa): `LockPoisoned` fatal classification has no e2e
// mutex-poison test; verified manually via
// `tests/sqlite_error_classification`. Re-check
// `handle_flush_error`'s fatal branch if you change it.
| Self::LockPoisoned
| Self::RestoreDestinationLocked
| Self::InvalidWalletIdHex { .. }
| Self::InvalidWalletIdLength { .. }
| Self::ConfigInvalid { .. }
| Self::BincodeEncode { .. }
| Self::BincodeDecode { .. }
| Self::BlobDecode { .. }
| Self::HashDecode { .. }
| Self::ConsensusCodec { .. }
| Self::BackupDestinationExists { .. }
| Self::ForeignKeysNotEnforced
| Self::JournalModeNotApplied { .. }
| Self::SchemaHistoryMalformed { .. }
| Self::NotAWalletDb { .. }
| Self::AlreadyOpen { .. }
| Self::IdentityKeyEntryMismatch
| Self::IdentityEntryIdMismatch
| Self::AssetLockEntryMismatch { .. }
| Self::BlobTooLarge { .. }
| Self::UtxoAddressNotDerived { .. }
| Self::DerivedIndexInvariantViolated { .. }
| Self::IntegerOverflow { .. } => false,
}
}
/// Trait-boundary classification for [`PersistenceError::Backend`]:
///
/// - [`PersistenceErrorKind::Transient`] — [`Self::is_transient`] true; caller MAY retry.
/// - [`PersistenceErrorKind::Constraint`] — SQL constraint/FK/CHECK violation; caller bug.
/// - [`PersistenceErrorKind::Fatal`] — everything else.
///
/// [`Self::LockPoisoned`] never reaches here; the `From` impl maps it
/// straight to [`PersistenceError::LockPoisoned`].
pub fn persistence_kind(&self) -> PersistenceErrorKind {
use rusqlite::ErrorCode;
if self.is_transient() {
return PersistenceErrorKind::Transient;
}
match self {
Self::Sqlite(rusqlite::Error::SqliteFailure(e, _))
if matches!(e.code, ErrorCode::ConstraintViolation) =>
{
PersistenceErrorKind::Constraint
}
// A migration failure (`Self::Migration`) isn't a caller bug,
// so it stays `Fatal` rather than `Constraint`.
_ => PersistenceErrorKind::Fatal,
}
}
/// Short, lowercase, snake-case tag for tracing fields. One tag
/// per variant family — readers grep for these in production
/// logs.
pub fn error_kind_str(&self) -> &'static str {
use rusqlite::ErrorCode;
match self {
Self::Sqlite(rusqlite::Error::SqliteFailure(e, _)) => match e.code {
ErrorCode::DatabaseBusy => "sqlite_busy",
ErrorCode::DatabaseLocked => "sqlite_locked",
ErrorCode::DiskFull => "sqlite_disk_full",
ErrorCode::SystemIoFailure => "sqlite_io_failure",
ErrorCode::OutOfMemory => "sqlite_out_of_memory",
_ => "sqlite_other",
},
Self::Sqlite(_) => "sqlite_other",
Self::FlushRetryable { .. } => "flush_retryable",
Self::Io(_) => "io",
Self::Migration(_) => "migration",
Self::IntegrityCheckFailed { .. } => "integrity_check_failed",
Self::IntegrityCheckRunFailed { .. } => "integrity_check_run_failed",
Self::SourceOpenFailed { .. } => "source_open_failed",
Self::SchemaHistoryMissing => "schema_history_missing",
Self::SchemaVersionUnsupported { .. } => "schema_version_unsupported",
Self::AutoBackupDisabled { .. } => "auto_backup_disabled",
Self::AutoBackupDirUnwritable { .. } => "auto_backup_dir_unwritable",
Self::WalletNotFound { .. } => "wallet_not_found",
Self::WalletIdMismatch { .. } => "wallet_id_mismatch",
Self::LockPoisoned => "lock_poisoned",
Self::RestoreDestinationLocked => "restore_destination_locked",
Self::InvalidWalletIdHex { .. } => "invalid_wallet_id_hex",
Self::InvalidWalletIdLength { .. } => "invalid_wallet_id_length",
Self::ConfigInvalid { .. } => "config_invalid",
Self::BincodeEncode { .. } => "bincode_encode",
Self::BincodeDecode { .. } => "bincode_decode",
Self::BlobDecode { .. } => "blob_decode",
Self::HashDecode { .. } => "hash_decode",
Self::ConsensusCodec { .. } => "consensus_codec",
Self::BackupDestinationExists { .. } => "backup_destination_exists",
Self::ForeignKeysNotEnforced => "foreign_keys_not_enforced",
Self::JournalModeNotApplied { .. } => "journal_mode_not_applied",
Self::SchemaHistoryMalformed { .. } => "schema_history_malformed",
Self::NotAWalletDb { .. } => "not_a_wallet_db",
Self::AlreadyOpen { .. } => "already_open",
Self::IdentityKeyEntryMismatch => "identity_key_entry_mismatch",
Self::IdentityEntryIdMismatch => "identity_entry_id_mismatch",
Self::AssetLockEntryMismatch { .. } => "asset_lock_entry_mismatch",
Self::BlobTooLarge { .. } => "blob_too_large",
Self::UtxoAddressNotDerived { .. } => "utxo_address_not_derived",
Self::DerivedIndexInvariantViolated { .. } => "derived_index_invariant_violated",
Self::IntegerOverflow { .. } => "integer_overflow",
}
}
}
impl From<bincode::error::EncodeError> for WalletStorageError {
fn from(source: bincode::error::EncodeError) -> Self {
Self::BincodeEncode { source }
}
}
impl From<bincode::error::DecodeError> for WalletStorageError {
fn from(source: bincode::error::DecodeError) -> Self {
Self::BincodeDecode { source }
}
}
impl From<dashcore::hashes::Error> for WalletStorageError {
fn from(source: dashcore::hashes::Error) -> Self {
Self::HashDecode { source }
}
}
impl From<dashcore::consensus::encode::Error> for WalletStorageError {
fn from(source: dashcore::consensus::encode::Error) -> Self {
Self::ConsensusCodec { source }
}
}