1#![doc = "Transactional wallet persistence with per-record authenticated encryption."]
2#![forbid(unsafe_code)]
3
4use std::collections::BTreeSet;
5use std::ops::{Deref, DerefMut};
6#[cfg(unix)]
7use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt};
8use std::path::{Path, PathBuf};
9use std::sync::{Arc, Mutex, MutexGuard};
10
11use argon2::{Algorithm, Argon2, Params, Version};
12use chacha20poly1305::{
13 XChaCha20Poly1305, XNonce,
14 aead::{Aead, KeyInit, Payload},
15};
16use hmac::{Hmac, Mac};
17use hns_wallet_types::{ApprovalId, WorkflowId, WorkflowKind};
18use rusqlite::{Connection, OpenFlags, OptionalExtension, TransactionBehavior, params};
19use serde::{Deserialize, Serialize};
20use sha2::{Digest, Sha256};
21use thiserror::Error;
22use zeroize::{Zeroize, Zeroizing};
23
24pub const SCHEMA_VERSION: u32 = 3;
25pub const MAX_RECORD_ID_BYTES: usize = 128;
26pub const MAX_SECRET_BYTES: usize = 1_048_576;
27pub const MAX_STATE_BYTES: usize = 1_048_576;
28pub const MAX_REPLAY_ROWS_PER_ORIGIN: usize = 4_096;
29pub const MAX_ENTITY_LIST_RESULTS: usize = 10_000;
30pub const MAX_PROVIDER_PERMISSIONS: usize = 4_096;
31pub const MAX_PENDING_APPROVALS: usize = 4_096;
32pub const MAX_REPLAY_ORIGINS: usize = 4_096;
33pub const MAX_REPLAY_ROWS: usize = 65_536;
34pub const MAX_REPLAY_LIFETIME_SECONDS: u64 = 86_400;
35pub const MAX_APPROVAL_LIFETIME_SECONDS: u64 = 3_600;
36pub const MAX_ENTITY_BATCH_OPERATIONS: usize = 16_384;
37pub const MAX_PASSPHRASE_BYTES: usize = 1_024;
38pub const RECOVERY_SEED_BYTES: usize = 64;
40
41const DATABASE_ID_BYTES: usize = 16;
42const SALT_BYTES: usize = 16;
43const NONCE_BYTES: usize = 24;
44const TAG_BYTES: usize = 16;
45const MAX_ENCRYPTED_RECORD_BYTES: usize = MAX_SECRET_BYTES + NONCE_BYTES + TAG_BYTES;
46const KEY_BYTES: usize = 32;
47const SENTINEL: &[u8] = b"hns-wallet-store-key-check-v1";
48const AAD_DOMAIN: &[u8] = b"hns-wallet-store/record/v1";
49const ORIGIN_TOKEN_DOMAIN: &[u8] = b"hns-wallet-store/origin-token/v1";
50const CHECKPOINT_PENDING_KEY: &str = "plaintext_checkpoint_pending";
51
52#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
56pub enum EntityKind {
57 WalletAccount,
58 NativeHnsReadProfile,
59 DerivedAddress,
60 HnsUtxo,
61 HnsTransaction,
62 HnsLightChain,
63 HnsLightWallet,
64 KnownName,
65 NameOwnerOutpoint,
66 NameTransfer,
67 Shakedex,
68 HnsShakedexKeyAllocation,
69 HnsaHnsrPublisherSequence,
70 ShakescapeBoardObject,
71 BitcoinHeader,
72 BitcoinFilterHeader,
73 BitcoinPeer,
74 BitcoinWalletState,
75 BitcoinWalletChangeSet,
76 BitcoinScanState,
77 BitcoinSwapKeyAllocation,
78 BitcoinSwapWatch,
79 CrossChainSwapKeyAllocation,
80 BitcoinUtxo,
81 BitcoinTransaction,
82 EthereumAccount,
83 EthereumTransaction,
84 SwapSession,
85 SwapFundingAuthorization,
86 RefundTransaction,
87 HnsRecoveryState,
88 HnsShakescapeWatch,
89 HnsVerifiedSettlement,
90 PendingApproval,
91 InputReservation,
92}
93
94impl EntityKind {
95 pub const fn label(self) -> &'static str {
96 match self {
97 Self::WalletAccount => "wallet_account",
98 Self::NativeHnsReadProfile => "native_hns_read_profile",
99 Self::DerivedAddress => "derived_address",
100 Self::HnsUtxo => "hns_utxo",
101 Self::HnsTransaction => "hns_transaction",
102 Self::HnsLightChain => "hns_light_chain",
103 Self::HnsLightWallet => "hns_light_wallet",
104 Self::KnownName => "known_name",
105 Self::NameOwnerOutpoint => "name_owner_outpoint",
106 Self::NameTransfer => "name_transfer",
107 Self::Shakedex => "shakedex",
108 Self::HnsShakedexKeyAllocation => "hns_shakedex_key_allocation",
109 Self::HnsaHnsrPublisherSequence => "hnsa_hnsr_publisher_sequence",
110 Self::ShakescapeBoardObject => "shakescape_board_object",
111 Self::BitcoinHeader => "bitcoin_header",
112 Self::BitcoinFilterHeader => "bitcoin_filter_header",
113 Self::BitcoinPeer => "bitcoin_peer",
114 Self::BitcoinWalletState => "bitcoin_wallet_state",
115 Self::BitcoinWalletChangeSet => "bitcoin_wallet_changeset",
116 Self::BitcoinScanState => "bitcoin_scan_state",
117 Self::BitcoinSwapKeyAllocation => "bitcoin_swap_key_allocation",
118 Self::BitcoinSwapWatch => "bitcoin_swap_watch",
119 Self::CrossChainSwapKeyAllocation => "cross_chain_swap_key_allocation",
120 Self::BitcoinUtxo => "bitcoin_utxo",
121 Self::BitcoinTransaction => "bitcoin_transaction",
122 Self::EthereumAccount => "ethereum_account",
123 Self::EthereumTransaction => "ethereum_transaction",
124 Self::SwapSession => "swap_session",
125 Self::SwapFundingAuthorization => "swap_funding_authorization",
126 Self::RefundTransaction => "refund_transaction",
127 Self::HnsRecoveryState => "hns_recovery_state",
128 Self::HnsShakescapeWatch => "hns_shakescape_watch",
129 Self::HnsVerifiedSettlement => "hns_verified_settlement",
130 Self::PendingApproval => "pending_approval",
131 Self::InputReservation => "input_reservation",
132 }
133 }
134
135 const fn deletion_protected(self) -> bool {
136 matches!(
137 self,
138 Self::NativeHnsReadProfile
139 | Self::HnsShakedexKeyAllocation
140 | Self::HnsaHnsrPublisherSequence
141 | Self::BitcoinWalletState
142 | Self::BitcoinSwapKeyAllocation
143 | Self::CrossChainSwapKeyAllocation
144 )
145 }
146}
147
148#[derive(Clone, Debug, Eq, PartialEq)]
149pub struct StoredEntity<T> {
150 pub kind: EntityKind,
151 pub id: Vec<u8>,
152 pub revision: u64,
153 pub value: T,
154 pub updated_at_unix: u64,
155}
156
157#[derive(Clone, Debug, Eq, PartialEq)]
163pub struct StoredEntityMetadata {
164 pub kind: EntityKind,
165 pub id: Vec<u8>,
166 pub revision: u64,
167 pub updated_at_unix: u64,
168}
169
170pub struct EntityReadSnapshot<'snapshot> {
177 connection: &'snapshot Connection,
178 key: &'snapshot [u8; KEY_BYTES],
179 database_id: &'snapshot [u8; DATABASE_ID_BYTES],
180}
181
182pub struct EntityPrefixSetLease {
191 database_id: [u8; DATABASE_ID_BYTES],
192 kind: EntityKind,
193 prefix: Vec<u8>,
194 limit: usize,
195 metadata: Vec<StoredEntityMetadata>,
196 encrypted_value_fingerprints: Vec<[u8; 32]>,
197}
198
199impl EntityPrefixSetLease {
200 pub fn metadata(&self) -> &[StoredEntityMetadata] {
206 &self.metadata
207 }
208}
209
210impl EntityReadSnapshot<'_> {
211 pub fn load_entity<T: for<'de> Deserialize<'de>>(
213 &self,
214 kind: EntityKind,
215 id: &[u8],
216 ) -> Result<Option<StoredEntity<T>>, StoreError> {
217 load_entity_from_connection(self.connection, self.key, self.database_id, kind, id)
218 }
219
220 pub fn list_entities_by_id_prefix<T: for<'de> Deserialize<'de>>(
224 &self,
225 kind: EntityKind,
226 prefix: &[u8],
227 limit: usize,
228 ) -> Result<Vec<StoredEntity<T>>, StoreError> {
229 list_entities_by_id_prefix_from_connection(
230 self.connection,
231 self.key,
232 self.database_id,
233 kind,
234 prefix,
235 limit,
236 )
237 }
238
239 pub fn list_untrusted_entity_metadata_by_id_prefix(
242 &self,
243 kind: EntityKind,
244 prefix: &[u8],
245 limit: usize,
246 ) -> Result<Vec<StoredEntityMetadata>, StoreError> {
247 list_untrusted_entity_metadata_by_id_prefix_from_connection(
248 self.connection,
249 kind,
250 prefix,
251 limit,
252 )
253 }
254
255 pub fn entity_prefix_set_lease(
257 &self,
258 kind: EntityKind,
259 prefix: &[u8],
260 limit: usize,
261 ) -> Result<EntityPrefixSetLease, StoreError> {
262 let (metadata, encrypted_value_fingerprints) =
263 load_entity_prefix_set_lease_projection(self.connection, kind, prefix, limit)?;
264 Ok(EntityPrefixSetLease {
265 database_id: *self.database_id,
266 kind,
267 prefix: prefix.to_vec(),
268 limit,
269 metadata,
270 encrypted_value_fingerprints,
271 })
272 }
273
274 pub fn refresh_entity_prefix_set_lease(
279 &self,
280 lease: EntityPrefixSetLease,
281 ) -> Result<EntityPrefixSetLease, StoreError> {
282 validate_entity_prefix_set_lease_shape(self.database_id, &lease)?;
283 let current = load_entity_prefix_set_lease_projection(
284 self.connection,
285 lease.kind,
286 &lease.prefix,
287 lease.limit,
288 );
289 match current {
290 Ok((metadata, encrypted_value_fingerprints))
291 if metadata == lease.metadata
292 && encrypted_value_fingerprints == lease.encrypted_value_fingerprints =>
293 {
294 Ok(lease)
295 }
296 Ok(_) | Err(StoreError::ListCapacity) => Err(StoreError::StaleEntitySet),
297 Err(error) => Err(error),
298 }
299 }
300}
301
302#[derive(Clone, Debug, Eq, PartialEq)]
303pub struct EntityBatchSave<T> {
304 pub id: Vec<u8>,
305 pub expected_revision: u64,
306 pub value: T,
307 pub updated_at_unix: u64,
308}
309
310#[derive(Clone, Debug, Eq, PartialEq)]
311pub struct EntityBatchDelete {
312 pub id: Vec<u8>,
313 pub expected_revision: u64,
314}
315
316#[derive(Clone, Debug, Eq, PartialEq)]
319pub struct EntityRevisionAssertion {
320 pub id: Vec<u8>,
321 pub expected_revision: u64,
322}
323
324#[derive(Clone, Copy, Debug, Eq, PartialEq)]
328pub struct WorkflowRevisionAssertion {
329 pub id: WorkflowId,
330 pub kind: WorkflowKind,
331 pub expected_revision: u64,
332}
333
334macro_rules! entity_crud_methods {
335 ($(($save:ident, $load:ident, $list:ident, $delete:ident, $kind:ident)),+ $(,)?) => {
336 $(
337 pub fn $save<T: Serialize>(
338 &mut self,
339 id: &[u8],
340 expected_revision: u64,
341 value: &T,
342 updated_at_unix: u64,
343 ) -> Result<u64, StoreError> {
344 self.save_entity(
345 EntityKind::$kind,
346 id,
347 expected_revision,
348 value,
349 updated_at_unix,
350 )
351 }
352
353 pub fn $load<T: for<'de> Deserialize<'de>>(
354 &self,
355 id: &[u8],
356 ) -> Result<Option<StoredEntity<T>>, StoreError> {
357 self.load_entity(EntityKind::$kind, id)
358 }
359
360 pub fn $list<T: for<'de> Deserialize<'de>>(
361 &self,
362 limit: usize,
363 ) -> Result<Vec<StoredEntity<T>>, StoreError> {
364 self.list_entities(EntityKind::$kind, limit)
365 }
366
367 pub fn $delete(
368 &mut self,
369 id: &[u8],
370 expected_revision: u64,
371 ) -> Result<bool, StoreError> {
372 self.delete_entity(EntityKind::$kind, id, expected_revision)
373 }
374 )+
375 };
376}
377
378#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
379pub struct KdfConfig {
380 pub memory_kib: u32,
382 pub iterations: u32,
383 pub lanes: u32,
384}
385
386impl Default for KdfConfig {
387 fn default() -> Self {
388 Self {
389 memory_kib: 65_536,
390 iterations: 3,
391 lanes: 1,
392 }
393 }
394}
395
396impl KdfConfig {
397 fn validate(self) -> Result<(), StoreError> {
398 if self.memory_kib < 19_456 || self.iterations < 2 || self.lanes == 0 || self.lanes > 4 {
399 return Err(StoreError::UnsafeKdfParameters);
400 }
401 Params::new(
402 self.memory_kib,
403 self.iterations,
404 self.lanes,
405 Some(KEY_BYTES),
406 )
407 .map_err(|_| StoreError::UnsafeKdfParameters)?;
408 Ok(())
409 }
410
411 #[cfg(test)]
412 const fn testing() -> Self {
413 Self {
414 memory_kib: 19_456,
415 iterations: 2,
416 lanes: 1,
417 }
418 }
419}
420
421#[derive(Clone, Copy, Debug, Eq, PartialEq)]
422pub enum SecretKind {
423 RecoverySeed,
424 PrivateKey,
425 MetadataKey,
426 HtlcPreimage,
427 ProviderCapability,
428 SessionAuthorization,
429}
430
431impl SecretKind {
432 const fn label(self) -> &'static str {
433 match self {
434 Self::RecoverySeed => "recovery_seed",
435 Self::PrivateKey => "private_key",
436 Self::MetadataKey => "metadata_key",
437 Self::HtlcPreimage => "htlc_preimage",
438 Self::ProviderCapability => "provider_capability",
439 Self::SessionAuthorization => "session_authorization",
440 }
441 }
442}
443
444pub struct WalletStore {
445 connection: Connection,
446 database_id: [u8; DATABASE_ID_BYTES],
447 salt: [u8; SALT_BYTES],
448 kdf: KdfConfig,
449 key: Option<Zeroizing<[u8; KEY_BYTES]>>,
450}
451
452#[derive(Clone)]
461pub struct SharedWalletStore {
462 inner: Arc<Mutex<WalletStore>>,
463}
464
465pub struct SharedWalletStoreGuard<'a> {
476 guard: MutexGuard<'a, WalletStore>,
477}
478
479impl Deref for SharedWalletStoreGuard<'_> {
480 type Target = WalletStore;
481
482 fn deref(&self) -> &Self::Target {
483 &self.guard
484 }
485}
486
487impl DerefMut for SharedWalletStoreGuard<'_> {
488 fn deref_mut(&mut self) -> &mut Self::Target {
489 &mut self.guard
490 }
491}
492
493impl SharedWalletStore {
494 pub fn new(store: WalletStore) -> Self {
495 Self {
496 inner: Arc::new(Mutex::new(store)),
497 }
498 }
499
500 pub fn with_store<T>(
501 &self,
502 operation: impl FnOnce(&WalletStore) -> Result<T, StoreError>,
503 ) -> Result<T, StoreError> {
504 self.try_with_store(operation)
505 }
506
507 pub fn try_with_store<T, E>(
511 &self,
512 operation: impl FnOnce(&WalletStore) -> Result<T, E>,
513 ) -> Result<T, E>
514 where
515 E: From<StoreError>,
516 {
517 let store = match self.inner.lock() {
518 Ok(store) => store,
519 Err(poisoned) => {
520 let mut store = poisoned.into_inner();
521 store.lock();
522 return Err(StoreError::Concurrency.into());
523 }
524 };
525 operation(&store)
526 }
527
528 pub fn is_same_authority(&self, other: &Self) -> bool {
531 Arc::ptr_eq(&self.inner, &other.inner)
532 }
533
534 pub fn runtime_guard(&self) -> Result<SharedWalletStoreGuard<'_>, StoreError> {
540 let guard = match self.inner.lock() {
541 Ok(store) => store,
542 Err(poisoned) => {
543 let mut store = poisoned.into_inner();
544 store.lock();
545 return Err(StoreError::Concurrency);
546 }
547 };
548 Ok(SharedWalletStoreGuard { guard })
549 }
550
551 pub fn with_store_mut<T>(
552 &self,
553 operation: impl FnOnce(&mut WalletStore) -> Result<T, StoreError>,
554 ) -> Result<T, StoreError> {
555 self.try_with_store_mut(operation)
556 }
557
558 pub fn try_with_store_mut<T, E>(
562 &self,
563 operation: impl FnOnce(&mut WalletStore) -> Result<T, E>,
564 ) -> Result<T, E>
565 where
566 E: From<StoreError>,
567 {
568 let mut store = match self.inner.lock() {
569 Ok(store) => store,
570 Err(poisoned) => {
571 let mut store = poisoned.into_inner();
572 store.lock();
573 return Err(StoreError::Concurrency.into());
574 }
575 };
576 operation(&mut store)
577 }
578
579 pub fn unlock(&self, passphrase: &str) -> Result<(), StoreError> {
580 self.with_store_mut(|store| store.unlock(passphrase))
581 }
582
583 pub fn change_passphrase(&self, old: &str, new: &str) -> Result<(), StoreError> {
584 self.with_store_mut(|store| store.change_passphrase(old, new))
585 }
586
587 pub fn lock(&self) -> Result<(), StoreError> {
592 match self.inner.lock() {
593 Ok(mut store) => {
594 store.lock();
595 Ok(())
596 }
597 Err(poisoned) => {
598 let mut store = poisoned.into_inner();
599 store.lock();
600 Err(StoreError::Concurrency)
601 }
602 }
603 }
604
605 pub fn is_locked(&self) -> Result<bool, StoreError> {
606 self.with_store(|store| Ok(store.is_locked()))
607 }
608}
609
610impl WalletStore {
611 pub fn create(path: impl AsRef<Path>, passphrase: &str) -> Result<Self, StoreError> {
612 Self::create_with_kdf(path, passphrase, KdfConfig::default())
613 }
614
615 pub fn create_with_initializer<T>(
624 path: impl AsRef<Path>,
625 passphrase: &str,
626 initializer: impl FnOnce(&mut Self) -> Result<T, StoreError>,
627 ) -> Result<(Self, T), StoreError> {
628 Self::create_with_kdf_and_initializer(
629 path,
630 passphrase,
631 KdfConfig::default(),
632 |_| Ok(()),
633 initializer,
634 )
635 }
636
637 pub fn create_with_owned_initializer<T, E>(
648 path: impl AsRef<Path>,
649 passphrase: &str,
650 initializer: impl FnOnce(Self) -> Result<T, E>,
651 ) -> Result<T, E>
652 where
653 E: From<StoreError>,
654 {
655 Self::create_with_kdf_and_owned_initializer(
656 path,
657 passphrase,
658 KdfConfig::default(),
659 initializer,
660 )
661 }
662
663 fn create_with_kdf(
664 path: impl AsRef<Path>,
665 passphrase: &str,
666 kdf: KdfConfig,
667 ) -> Result<Self, StoreError> {
668 Self::create_with_kdf_after_migration(path, passphrase, kdf, |_| Ok(()))
669 }
670
671 fn create_with_kdf_after_migration(
672 path: impl AsRef<Path>,
673 passphrase: &str,
674 kdf: KdfConfig,
675 after_migration: impl FnOnce(&Connection) -> Result<(), StoreError>,
676 ) -> Result<Self, StoreError> {
677 let (store, ()) =
678 Self::create_with_kdf_and_initializer(path, passphrase, kdf, after_migration, |_| {
679 Ok(())
680 })?;
681 Ok(store)
682 }
683
684 fn create_with_kdf_and_initializer<T>(
685 path: impl AsRef<Path>,
686 passphrase: &str,
687 kdf: KdfConfig,
688 after_migration: impl FnOnce(&Connection) -> Result<(), StoreError>,
689 initializer: impl FnOnce(&mut Self) -> Result<T, StoreError>,
690 ) -> Result<(Self, T), StoreError> {
691 let (mut store, mut created_file, path) =
692 Self::create_pending_with_kdf(path, passphrase, kdf, after_migration)?;
693 let initialized = initializer(&mut store)?;
694 complete_wallet_creation(&mut created_file, &path)?;
695 Ok((store, initialized))
696 }
697
698 fn create_with_kdf_and_owned_initializer<T, E>(
699 path: impl AsRef<Path>,
700 passphrase: &str,
701 kdf: KdfConfig,
702 initializer: impl FnOnce(Self) -> Result<T, E>,
703 ) -> Result<T, E>
704 where
705 E: From<StoreError>,
706 {
707 let (store, mut created_file, path) =
708 Self::create_pending_with_kdf(path, passphrase, kdf, |_| Ok(())).map_err(E::from)?;
709 let initialized = initializer(store)?;
710 if let Err(error) = complete_wallet_creation(&mut created_file, &path) {
711 drop(initialized);
714 return Err(E::from(error));
715 }
716 Ok(initialized)
717 }
718
719 fn create_pending_with_kdf(
720 path: impl AsRef<Path>,
721 passphrase: &str,
722 kdf: KdfConfig,
723 after_migration: impl FnOnce(&Connection) -> Result<(), StoreError>,
724 ) -> Result<(Self, Option<CreatedWalletFile>, PathBuf), StoreError> {
725 validate_passphrase(passphrase)?;
726 kdf.validate()?;
727 let location = validate_wallet_location(path.as_ref(), WalletPathRequirement::Missing)?;
728 let created_file = if is_in_memory(&location.path) {
729 None
730 } else {
731 Some(create_new_wallet_file(&location.path)?)
732 };
733 let connection = open_wallet_connection(&location.path)?;
734 if let Some(created_file) = created_file.as_ref() {
735 let reopened_location =
736 validate_wallet_location(&location.path, WalletPathRequirement::Existing)?;
737 validate_created_wallet_location(created_file, &reopened_location)?;
738 }
739 configure(&connection)?;
740 migrate(&connection)?;
741 after_migration(&connection)?;
742 if meta(&connection, "database_id")?.is_some() {
743 return Err(StoreError::AlreadyInitialized);
744 }
745
746 let mut database_id = [0_u8; DATABASE_ID_BYTES];
747 let mut salt = [0_u8; SALT_BYTES];
748 getrandom::fill(&mut database_id).map_err(|_| StoreError::Randomness)?;
749 getrandom::fill(&mut salt).map_err(|_| StoreError::Randomness)?;
750 let key = derive_key(passphrase, &salt, kdf)?;
751 let sentinel = encrypt_record(
752 &key,
753 &database_id,
754 SecretKind::MetadataKey.label(),
755 b"key_check",
756 SENTINEL,
757 )?;
758 let kdf_json = serde_json::to_vec(&kdf)?;
759
760 let transaction = connection.unchecked_transaction()?;
761 set_meta(&transaction, "database_id", &database_id)?;
762 set_meta(&transaction, "kdf_salt", &salt)?;
763 set_meta(&transaction, "kdf_config", &kdf_json)?;
764 set_meta(&transaction, "key_check", &sentinel)?;
765 transaction.commit()?;
766
767 let store = Self {
768 connection,
769 database_id,
770 salt,
771 kdf,
772 key: Some(key),
773 };
774 Ok((store, created_file, location.path))
775 }
776
777 pub fn open(path: impl AsRef<Path>) -> Result<Self, StoreError> {
778 let location = validate_wallet_location(path.as_ref(), WalletPathRequirement::Existing)?;
779 let recognition_connection = open_wallet_connection_read_only(&location.path)?;
780 let recognized_location =
781 validate_wallet_location(&location.path, WalletPathRequirement::Existing)?;
782 validate_wallet_location_identity(&location, &recognized_location)?;
783 let recognized_metadata = recognize_wallet_database(&recognition_connection)?;
784 drop(recognition_connection);
785
786 let connection = open_wallet_connection(&location.path)?;
787 let reopened_location =
788 validate_wallet_location(&location.path, WalletPathRequirement::Existing)?;
789 validate_wallet_location_identity(&location, &reopened_location)?;
790 if recognize_wallet_database(&connection)? != recognized_metadata {
791 return Err(StoreError::CorruptMetadata);
792 }
793 configure(&connection)?;
794 migrate(&connection)?;
795 let metadata = load_wallet_metadata(&connection)?;
796 if metadata != recognized_metadata {
797 return Err(StoreError::CorruptMetadata);
798 }
799 Ok(Self {
800 connection,
801 database_id: metadata.database_id,
802 salt: metadata.salt,
803 kdf: metadata.kdf,
804 key: None,
805 })
806 }
807
808 pub fn unlock(&mut self, passphrase: &str) -> Result<(), StoreError> {
809 validate_passphrase(passphrase)?;
810 let key = derive_key(passphrase, &self.salt, self.kdf)?;
811 let encrypted = required_meta(&self.connection, "key_check")?;
812 let clear = decrypt_record(
813 &key,
814 &self.database_id,
815 SecretKind::MetadataKey.label(),
816 b"key_check",
817 &encrypted,
818 )
819 .map_err(|_| StoreError::InvalidPassphrase)?;
820 if clear.as_slice() != SENTINEL {
821 return Err(StoreError::InvalidPassphrase);
822 }
823 self.key = Some(key);
824 if let Err(error) = self
825 .encrypt_legacy_rows()
826 .and_then(|()| self.complete_plaintext_checkpoint())
827 {
828 self.key = None;
829 return Err(error);
830 }
831 Ok(())
832 }
833
834 pub fn change_passphrase(&mut self, old: &str, new: &str) -> Result<(), StoreError> {
839 let current_key = self.key.as_ref().ok_or(StoreError::Locked)?;
840 validate_passphrase(new)?;
841 if old == new {
842 return Err(StoreError::InvalidPassphrase);
843 }
844 let old_key = derive_key(old, &self.salt, self.kdf)?;
845 let key_check = required_meta(&self.connection, "key_check")?;
846 let clear = decrypt_record(
847 &old_key,
848 &self.database_id,
849 SecretKind::MetadataKey.label(),
850 b"key_check",
851 &key_check,
852 )
853 .map_err(|_| StoreError::InvalidPassphrase)?;
854 if clear.as_slice() != SENTINEL || current_key.as_ref() != old_key.as_ref() {
855 return Err(StoreError::InvalidPassphrase);
856 }
857 drop(clear);
858
859 let mut salt = [0_u8; SALT_BYTES];
860 getrandom::fill(&mut salt).map_err(|_| StoreError::Randomness)?;
861 let new_key = derive_key(new, &salt, self.kdf)?;
862 let database_id = self.database_id;
863 let transaction = self
864 .connection
865 .transaction_with_behavior(TransactionBehavior::Immediate)?;
866 reject_unmigrated_legacy_entities(&transaction)?;
867
868 rekey_rows(
869 &transaction,
870 "SELECT rowid, id, kind, encrypted_value FROM secrets WHERE ?1 IS NULL OR rowid>?1 ORDER BY rowid LIMIT 128",
871 |row| {
872 Ok((
873 row.get(0)?,
874 (
875 row.get::<_, Vec<u8>>(1)?,
876 row.get::<_, String>(2)?,
877 row.get::<_, Vec<u8>>(3)?,
878 ),
879 ))
880 },
881 |tx, rowid, (id, kind, encrypted)| {
882 let clear = decrypt_record(&old_key, &database_id, &kind, &id, &encrypted)?;
883 let encrypted = encrypt_record(&new_key, &database_id, &kind, &id, &clear)?;
884 tx.execute(
885 "UPDATE secrets SET encrypted_value=?1 WHERE rowid=?2",
886 params![encrypted, rowid],
887 )?;
888 Ok(())
889 },
890 )?;
891 rekey_rows(
892 &transaction,
893 "SELECT rowid, entity_kind, record_id, revision, encrypted_value, updated_at_unix FROM encrypted_entities WHERE ?1 IS NULL OR rowid>?1 ORDER BY rowid LIMIT 128",
894 |row| {
895 Ok((
896 row.get(0)?,
897 (
898 row.get::<_, String>(1)?,
899 row.get::<_, Vec<u8>>(2)?,
900 row.get::<_, u64>(3)?,
901 row.get::<_, Vec<u8>>(4)?,
902 row.get::<_, u64>(5)?,
903 ),
904 ))
905 },
906 |tx, rowid, (kind, id, revision, encrypted, updated_at)| {
907 let aad_id = revisioned_aad_id(&id, revision, updated_at, None)?;
908 let label = format!("entity/{kind}");
909 let clear = decrypt_record(&old_key, &database_id, &label, &aad_id, &encrypted)?;
910 let encrypted = encrypt_record(&new_key, &database_id, &label, &aad_id, &clear)?;
911 tx.execute(
912 "UPDATE encrypted_entities SET encrypted_value=?1 WHERE rowid=?2",
913 params![encrypted, rowid],
914 )?;
915 Ok(())
916 },
917 )?;
918 rekey_rows(
919 &transaction,
920 "SELECT rowid, id, kind, revision, state_json, broadcast_prepared, updated_at_unix, encryption_version FROM workflows WHERE ?1 IS NULL OR rowid>?1 ORDER BY rowid LIMIT 128",
921 |row| {
922 Ok((
923 row.get(0)?,
924 (
925 row.get::<_, Vec<u8>>(1)?,
926 row.get::<_, String>(2)?,
927 row.get::<_, u64>(3)?,
928 row.get::<_, Vec<u8>>(4)?,
929 row.get::<_, bool>(5)?,
930 row.get::<_, u64>(6)?,
931 row.get::<_, u32>(7)?,
932 ),
933 ))
934 },
935 |tx, rowid, (id, kind, revision, encrypted, broadcast, updated_at, version)| {
936 if version != 1 {
937 return Err(StoreError::LegacyEncryptionPending);
938 }
939 let label = workflow_label(parse_workflow_kind(&kind)?);
940 let aad_id = revisioned_aad_id(&id, revision, updated_at, Some(broadcast))?;
941 let clear = decrypt_record(&old_key, &database_id, &label, &aad_id, &encrypted)?;
942 let encrypted = encrypt_record(&new_key, &database_id, &label, &aad_id, &clear)?;
943 tx.execute(
944 "UPDATE workflows SET state_json=?1 WHERE rowid=?2",
945 params![encrypted, rowid],
946 )?;
947 Ok(())
948 },
949 )?;
950 rekey_rows(
951 &transaction,
952 "SELECT rowid, origin_token, generation, encrypted_record, updated_at_unix, revoked FROM private_provider_permissions WHERE ?1 IS NULL OR rowid>?1 ORDER BY rowid LIMIT 128",
953 |row| {
954 Ok((
955 row.get(0)?,
956 (
957 row.get::<_, Vec<u8>>(1)?,
958 row.get::<_, u64>(2)?,
959 row.get::<_, Vec<u8>>(3)?,
960 row.get::<_, u64>(4)?,
961 row.get::<_, bool>(5)?,
962 ),
963 ))
964 },
965 |tx, rowid, (token, generation, encrypted, updated_at, revoked)| {
966 let token = exact_array::<32>(token)?;
967 let aad_id = permission_record_id(&token, generation, revoked, updated_at);
968 let clear = decrypt_record(
969 &old_key,
970 &database_id,
971 "provider_permission",
972 &aad_id,
973 &encrypted,
974 )?;
975 let (origin, _) = decode_origin_payload(&clear)?;
976 if origin_lookup_token(&old_key, &database_id, &origin)? != token {
977 return Err(StoreError::Encryption);
978 }
979 let new_token = origin_lookup_token(&new_key, &database_id, &origin)?;
980 let new_aad_id = permission_record_id(&new_token, generation, revoked, updated_at);
981 let encrypted = encrypt_record(
982 &new_key,
983 &database_id,
984 "provider_permission",
985 &new_aad_id,
986 &clear,
987 )?;
988 tx.execute("UPDATE private_provider_permissions SET origin_token=?1, encrypted_record=?2 WHERE rowid=?3", params![new_token.as_slice(), encrypted, rowid])?;
989 Ok(())
990 },
991 )?;
992 rekey_rows(
993 &transaction,
994 "SELECT rowid, id, origin_token, encrypted_record, expires_at_unix FROM private_pending_approvals WHERE ?1 IS NULL OR rowid>?1 ORDER BY rowid LIMIT 128",
995 |row| {
996 Ok((
997 row.get(0)?,
998 (
999 row.get::<_, Vec<u8>>(1)?,
1000 row.get::<_, Vec<u8>>(2)?,
1001 row.get::<_, Vec<u8>>(3)?,
1002 row.get::<_, u64>(4)?,
1003 ),
1004 ))
1005 },
1006 |tx, rowid, (id, token, encrypted, expires_at)| {
1007 let id = ApprovalId::new(exact_array::<16>(id)?);
1008 let token = exact_array::<32>(token)?;
1009 let aad_id = approval_record_id(&id, &token, expires_at);
1010 let clear = decrypt_record(
1011 &old_key,
1012 &database_id,
1013 "pending_approval",
1014 &aad_id,
1015 &encrypted,
1016 )?;
1017 let (origin, _) = decode_origin_payload(&clear)?;
1018 if origin_lookup_token(&old_key, &database_id, &origin)? != token {
1019 return Err(StoreError::Encryption);
1020 }
1021 let new_token = origin_lookup_token(&new_key, &database_id, &origin)?;
1022 let new_aad_id = approval_record_id(&id, &new_token, expires_at);
1023 let encrypted = encrypt_record(
1024 &new_key,
1025 &database_id,
1026 "pending_approval",
1027 &new_aad_id,
1028 &clear,
1029 )?;
1030 tx.execute("UPDATE private_pending_approvals SET origin_token=?1, encrypted_record=?2 WHERE rowid=?3", params![new_token.as_slice(), encrypted, rowid])?;
1031 Ok(())
1032 },
1033 )?;
1034 rekey_rows(
1035 &transaction,
1036 "SELECT rowid, origin_token, nonce, encrypted_origin, expires_at_unix FROM private_replay_protection WHERE ?1 IS NULL OR rowid>?1 ORDER BY rowid LIMIT 128",
1037 |row| {
1038 Ok((
1039 row.get(0)?,
1040 (
1041 row.get::<_, Vec<u8>>(1)?,
1042 row.get::<_, u64>(2)?,
1043 row.get::<_, Vec<u8>>(3)?,
1044 row.get::<_, u64>(4)?,
1045 ),
1046 ))
1047 },
1048 |tx, rowid, (token, nonce, encrypted, expires_at)| {
1049 let token = exact_array::<32>(token)?;
1050 let aad_id = replay_record_id(&token, nonce, expires_at);
1051 let clear =
1052 decrypt_record(&old_key, &database_id, "replay_origin", &aad_id, &encrypted)?;
1053 let origin = core::str::from_utf8(&clear).map_err(|_| StoreError::Encryption)?;
1054 validate_origin(origin).map_err(|_| StoreError::Encryption)?;
1055 if origin_lookup_token(&old_key, &database_id, origin)? != token {
1056 return Err(StoreError::Encryption);
1057 }
1058 let new_token = origin_lookup_token(&new_key, &database_id, origin)?;
1059 let new_aad_id = replay_record_id(&new_token, nonce, expires_at);
1060 let encrypted =
1061 encrypt_record(&new_key, &database_id, "replay_origin", &new_aad_id, &clear)?;
1062 tx.execute("UPDATE private_replay_protection SET origin_token=?1, encrypted_origin=?2 WHERE rowid=?3", params![new_token.as_slice(), encrypted, rowid])?;
1063 Ok(())
1064 },
1065 )?;
1066
1067 let sentinel = encrypt_record(
1068 &new_key,
1069 &database_id,
1070 SecretKind::MetadataKey.label(),
1071 b"key_check",
1072 SENTINEL,
1073 )?;
1074 if transaction.execute(
1075 "UPDATE wallet_meta SET value=?1 WHERE key='kdf_salt'",
1076 params![salt.as_slice()],
1077 )? != 1
1078 {
1079 return Err(StoreError::CorruptMetadata);
1080 }
1081 if transaction.execute(
1082 "UPDATE wallet_meta SET value=?1 WHERE key='key_check'",
1083 params![sentinel],
1084 )? != 1
1085 {
1086 return Err(StoreError::CorruptMetadata);
1087 }
1088 set_meta(&transaction, CHECKPOINT_PENDING_KEY, b"1")?;
1089 transaction.commit()?;
1090 self.salt = salt;
1091 self.key = Some(new_key);
1092 self.complete_plaintext_checkpoint()
1093 .map_err(|_| StoreError::PassphraseChangedCheckpointPending)?;
1094 Ok(())
1095 }
1096
1097 pub fn lock(&mut self) {
1098 self.key = None;
1099 }
1100
1101 pub const fn is_locked(&self) -> bool {
1102 self.key.is_none()
1103 }
1104
1105 pub const fn schema_version(&self) -> u32 {
1106 SCHEMA_VERSION
1107 }
1108
1109 pub fn put_secret(
1110 &mut self,
1111 id: &[u8],
1112 kind: SecretKind,
1113 cleartext: &[u8],
1114 updated_at_unix: u64,
1115 ) -> Result<(), StoreError> {
1116 validate_id(id)?;
1117 if cleartext.is_empty() || cleartext.len() > MAX_SECRET_BYTES {
1118 return Err(StoreError::RecordTooLarge);
1119 }
1120 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
1121 let transaction = self
1122 .connection
1123 .transaction_with_behavior(TransactionBehavior::Immediate)?;
1124 let current: Option<(String, Vec<u8>)> = transaction
1125 .query_row(
1126 "SELECT kind, encrypted_value FROM secrets WHERE id=?1",
1127 params![id],
1128 |row| Ok((row.get(0)?, row.get(1)?)),
1129 )
1130 .optional()?;
1131 if let Some((current_kind, current_encrypted)) = current {
1132 if current_kind != kind.label() {
1133 return Err(StoreError::KindMismatch);
1134 }
1135 if kind == SecretKind::RecoverySeed {
1136 let current_clear =
1137 decrypt_record(key, &self.database_id, kind.label(), id, ¤t_encrypted)?;
1138 if current_clear.as_slice() == cleartext {
1139 transaction.commit()?;
1140 return Ok(());
1141 }
1142 return Err(StoreError::ProtectedSecret);
1143 }
1144 }
1145 let encrypted = encrypt_record(key, &self.database_id, kind.label(), id, cleartext)?;
1146 transaction.execute(
1147 "INSERT INTO secrets(id, kind, encrypted_value, updated_at_unix) VALUES(?1, ?2, ?3, ?4)
1148 ON CONFLICT(id) DO UPDATE SET encrypted_value=excluded.encrypted_value,
1149 updated_at_unix=excluded.updated_at_unix",
1150 params![id, kind.label(), encrypted, updated_at_unix],
1151 )?;
1152 transaction.commit()?;
1153 Ok(())
1154 }
1155
1156 pub fn initialize_recovery_seed_and_wallet_account<T: Serialize>(
1161 &mut self,
1162 recovery_seed_id: &[u8],
1163 recovery_seed: &[u8],
1164 wallet_account_id: &[u8],
1165 wallet_account: &T,
1166 updated_at_unix: u64,
1167 ) -> Result<u64, StoreError> {
1168 self.initialize_recovery_seed_and_wallet_account_with_hook(
1169 recovery_seed_id,
1170 recovery_seed,
1171 wallet_account_id,
1172 wallet_account,
1173 updated_at_unix,
1174 || Ok(()),
1175 )
1176 }
1177
1178 fn initialize_recovery_seed_and_wallet_account_with_hook<T: Serialize>(
1179 &mut self,
1180 recovery_seed_id: &[u8],
1181 recovery_seed: &[u8],
1182 wallet_account_id: &[u8],
1183 wallet_account: &T,
1184 updated_at_unix: u64,
1185 after_seed_write: impl FnOnce() -> Result<(), StoreError>,
1186 ) -> Result<u64, StoreError> {
1187 validate_id(recovery_seed_id)?;
1188 validate_id(wallet_account_id)?;
1189 if recovery_seed.len() != RECOVERY_SEED_BYTES {
1190 return Err(StoreError::InvalidRecoverySeed);
1191 }
1192 let encoded_account = Zeroizing::new(serde_json::to_vec(wallet_account)?);
1193 if encoded_account.is_empty() || encoded_account.len() > MAX_STATE_BYTES {
1194 return Err(StoreError::RecordTooLarge);
1195 }
1196
1197 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
1198 let transaction = self
1199 .connection
1200 .transaction_with_behavior(TransactionBehavior::Immediate)?;
1201
1202 let current_seed: Option<(String, Vec<u8>)> = transaction
1203 .query_row(
1204 "SELECT kind, encrypted_value FROM secrets WHERE id=?1",
1205 params![recovery_seed_id],
1206 |row| Ok((row.get(0)?, row.get(1)?)),
1207 )
1208 .optional()?;
1209 if let Some((kind, encrypted)) = current_seed {
1210 if kind != SecretKind::RecoverySeed.label() {
1211 return Err(StoreError::KindMismatch);
1212 }
1213 decrypt_record(
1214 key,
1215 &self.database_id,
1216 SecretKind::RecoverySeed.label(),
1217 recovery_seed_id,
1218 &encrypted,
1219 )?;
1220 return Err(StoreError::BootstrapConflict);
1221 }
1222
1223 let recovery_seed_count: u64 = transaction.query_row(
1224 "SELECT COUNT(*) FROM secrets WHERE kind=?1",
1225 params![SecretKind::RecoverySeed.label()],
1226 |row| row.get(0),
1227 )?;
1228 if recovery_seed_count != 0 {
1229 return Err(StoreError::BootstrapConflict);
1230 }
1231
1232 if let Some(actual) = authenticated_entity_revision(
1233 &transaction,
1234 key,
1235 &self.database_id,
1236 EntityKind::WalletAccount,
1237 wallet_account_id,
1238 )? {
1239 return Err(StoreError::StaleRevision {
1240 expected: 0,
1241 actual,
1242 });
1243 }
1244 let wallet_account_count: u64 = transaction.query_row(
1245 "SELECT COUNT(*) FROM encrypted_entities WHERE entity_kind=?1",
1246 params![EntityKind::WalletAccount.label()],
1247 |row| row.get(0),
1248 )?;
1249 if wallet_account_count != 0 {
1250 return Err(StoreError::BootstrapConflict);
1251 }
1252
1253 let account_revision = 1_u64;
1254 let encrypted_seed = encrypt_record(
1255 key,
1256 &self.database_id,
1257 SecretKind::RecoverySeed.label(),
1258 recovery_seed_id,
1259 recovery_seed,
1260 )?;
1261 let encrypted_account = encrypt_record(
1262 key,
1263 &self.database_id,
1264 &entity_label(EntityKind::WalletAccount),
1265 &revisioned_aad_id(wallet_account_id, account_revision, updated_at_unix, None)?,
1266 &encoded_account,
1267 )?;
1268
1269 transaction.execute(
1270 "INSERT INTO secrets(id, kind, encrypted_value, updated_at_unix)
1271 VALUES(?1, ?2, ?3, ?4)",
1272 params![
1273 recovery_seed_id,
1274 SecretKind::RecoverySeed.label(),
1275 encrypted_seed,
1276 updated_at_unix,
1277 ],
1278 )?;
1279 after_seed_write()?;
1280 transaction.execute(
1281 "INSERT INTO encrypted_entities(
1282 entity_kind, record_id, revision, encrypted_value, updated_at_unix
1283 ) VALUES(?1, ?2, ?3, ?4, ?5)",
1284 params![
1285 EntityKind::WalletAccount.label(),
1286 wallet_account_id,
1287 account_revision,
1288 encrypted_account,
1289 updated_at_unix,
1290 ],
1291 )?;
1292 transaction.commit()?;
1293 Ok(account_revision)
1294 }
1295
1296 pub fn validate_single_recovery_seed(
1301 &mut self,
1302 recovery_seed_id: &[u8],
1303 ) -> Result<(), StoreError> {
1304 validate_id(recovery_seed_id)?;
1305 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
1306 let transaction = self
1307 .connection
1308 .transaction_with_behavior(TransactionBehavior::Immediate)?;
1309 let current: Option<(String, Vec<u8>)> = transaction
1310 .query_row(
1311 "SELECT kind, encrypted_value FROM secrets WHERE id=?1",
1312 params![recovery_seed_id],
1313 |row| Ok((row.get(0)?, row.get(1)?)),
1314 )
1315 .optional()?;
1316 let Some((kind, encrypted)) = current else {
1317 return Err(StoreError::BootstrapConflict);
1318 };
1319 if kind != SecretKind::RecoverySeed.label() {
1320 return Err(StoreError::KindMismatch);
1321 }
1322 let seed = decrypt_record(
1323 key,
1324 &self.database_id,
1325 SecretKind::RecoverySeed.label(),
1326 recovery_seed_id,
1327 &encrypted,
1328 )?;
1329 if seed.len() != RECOVERY_SEED_BYTES {
1330 return Err(StoreError::InvalidRecoverySeed);
1331 }
1332 let recovery_seed_count: u64 = transaction.query_row(
1333 "SELECT COUNT(*) FROM secrets WHERE kind=?1",
1334 params![SecretKind::RecoverySeed.label()],
1335 |row| row.get(0),
1336 )?;
1337 if recovery_seed_count != 1 {
1338 return Err(StoreError::BootstrapConflict);
1339 }
1340 transaction.commit()?;
1341 Ok(())
1342 }
1343
1344 pub fn get_secret(
1345 &self,
1346 id: &[u8],
1347 expected_kind: SecretKind,
1348 ) -> Result<Option<Zeroizing<Vec<u8>>>, StoreError> {
1349 validate_id(id)?;
1350 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
1351 let row: Option<(String, Vec<u8>)> = self
1352 .connection
1353 .query_row(
1354 "SELECT kind, encrypted_value FROM secrets WHERE id=?1",
1355 params![id],
1356 |row| Ok((row.get(0)?, row.get(1)?)),
1357 )
1358 .optional()?;
1359 let Some((kind, encrypted)) = row else {
1360 return Ok(None);
1361 };
1362 if kind != expected_kind.label() {
1363 return Err(StoreError::KindMismatch);
1364 }
1365 decrypt_record(
1366 key,
1367 &self.database_id,
1368 expected_kind.label(),
1369 id,
1370 &encrypted,
1371 )
1372 .map(Some)
1373 }
1374
1375 pub fn delete_secret(&mut self, id: &[u8]) -> Result<bool, StoreError> {
1376 validate_id(id)?;
1377 self.key.as_ref().ok_or(StoreError::Locked)?;
1378 let transaction = self
1379 .connection
1380 .transaction_with_behavior(TransactionBehavior::Immediate)?;
1381 let current_kind: Option<String> = transaction
1382 .query_row("SELECT kind FROM secrets WHERE id=?1", params![id], |row| {
1383 row.get(0)
1384 })
1385 .optional()?;
1386 let Some(current_kind) = current_kind else {
1387 return Ok(false);
1388 };
1389 if current_kind == SecretKind::RecoverySeed.label() {
1390 return Err(StoreError::ProtectedSecret);
1391 }
1392 transaction.execute("DELETE FROM secrets WHERE id=?1", params![id])?;
1393 transaction.commit()?;
1394 Ok(true)
1395 }
1396
1397 pub fn try_with_entity_read_snapshot<T, E>(
1405 &self,
1406 operation: impl FnOnce(&EntityReadSnapshot<'_>) -> Result<T, E>,
1407 ) -> Result<T, E>
1408 where
1409 E: From<StoreError>,
1410 {
1411 let key = self
1412 .key
1413 .as_ref()
1414 .ok_or(StoreError::Locked)
1415 .map_err(E::from)?;
1416 let transaction = self
1417 .connection
1418 .unchecked_transaction()
1419 .map_err(StoreError::from)
1420 .map_err(E::from)?;
1421 let result = {
1422 let snapshot = EntityReadSnapshot {
1423 connection: &transaction,
1424 key,
1425 database_id: &self.database_id,
1426 };
1427 operation(&snapshot)
1428 };
1429 let rollback = transaction.rollback().map_err(StoreError::from);
1430 match (result, rollback) {
1431 (Err(error), _) => Err(error),
1432 (Ok(_), Err(error)) => Err(E::from(error)),
1433 (Ok(value), Ok(())) => Ok(value),
1434 }
1435 }
1436
1437 pub fn save_entity<T: Serialize>(
1440 &mut self,
1441 kind: EntityKind,
1442 id: &[u8],
1443 expected_revision: u64,
1444 value: &T,
1445 updated_at_unix: u64,
1446 ) -> Result<u64, StoreError> {
1447 validate_id(id)?;
1448 let encoded = Zeroizing::new(serde_json::to_vec(value)?);
1449 if encoded.is_empty() || encoded.len() > MAX_STATE_BYTES {
1450 return Err(StoreError::RecordTooLarge);
1451 }
1452 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
1453 let label = entity_label(kind);
1454 let transaction = self
1455 .connection
1456 .transaction_with_behavior(TransactionBehavior::Immediate)?;
1457 let current: Option<(u64, Vec<u8>, u64)> = transaction
1458 .query_row(
1459 "SELECT revision, encrypted_value, updated_at_unix
1460 FROM encrypted_entities WHERE entity_kind=?1 AND record_id=?2",
1461 params![kind.label(), id],
1462 |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
1463 )
1464 .optional()?;
1465 let actual = match current {
1466 Some((revision, encrypted, current_updated_at)) => {
1467 decrypt_record(
1468 key,
1469 &self.database_id,
1470 &label,
1471 &revisioned_aad_id(id, revision, current_updated_at, None)?,
1472 &encrypted,
1473 )?;
1474 revision
1475 }
1476 None => 0,
1477 };
1478 if actual != expected_revision {
1479 return Err(StoreError::StaleRevision {
1480 expected: expected_revision,
1481 actual,
1482 });
1483 }
1484 let next = actual.checked_add(1).ok_or(StoreError::RevisionOverflow)?;
1485 let aad_id = revisioned_aad_id(id, next, updated_at_unix, None)?;
1486 let encrypted = encrypt_record(key, &self.database_id, &label, &aad_id, &encoded)?;
1487 transaction.execute(
1488 "INSERT INTO encrypted_entities(
1489 entity_kind, record_id, revision, encrypted_value, updated_at_unix
1490 ) VALUES(?1, ?2, ?3, ?4, ?5)
1491 ON CONFLICT(entity_kind, record_id) DO UPDATE SET
1492 revision=excluded.revision,
1493 encrypted_value=excluded.encrypted_value,
1494 updated_at_unix=excluded.updated_at_unix",
1495 params![kind.label(), id, next, encrypted, updated_at_unix],
1496 )?;
1497 transaction.commit()?;
1498 Ok(next)
1499 }
1500
1501 pub fn load_entity<T: for<'de> Deserialize<'de>>(
1502 &self,
1503 kind: EntityKind,
1504 id: &[u8],
1505 ) -> Result<Option<StoredEntity<T>>, StoreError> {
1506 validate_id(id)?;
1507 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
1508 load_entity_from_connection(&self.connection, key, &self.database_id, kind, id)
1509 }
1510
1511 pub fn list_entities<T: for<'de> Deserialize<'de>>(
1512 &self,
1513 kind: EntityKind,
1514 limit: usize,
1515 ) -> Result<Vec<StoredEntity<T>>, StoreError> {
1516 if limit == 0 || limit > MAX_ENTITY_LIST_RESULTS {
1517 return Err(StoreError::InvalidListLimit);
1518 }
1519 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
1520 let limit = i64::try_from(limit).map_err(|_| StoreError::InvalidListLimit)?;
1521 let mut statement = self.connection.prepare(
1522 "SELECT record_id, revision, encrypted_value, updated_at_unix
1523 FROM encrypted_entities WHERE entity_kind=?1 ORDER BY record_id LIMIT ?2",
1524 )?;
1525 let rows = statement.query_map(params![kind.label(), limit], |row| {
1526 Ok((
1527 row.get::<_, Vec<u8>>(0)?,
1528 row.get::<_, u64>(1)?,
1529 row.get::<_, Vec<u8>>(2)?,
1530 row.get::<_, u64>(3)?,
1531 ))
1532 })?;
1533 let mut entities = Vec::new();
1534 for row in rows {
1535 let (id, revision, encrypted, updated_at_unix) = row?;
1536 validate_id(&id)?;
1537 let clear = decrypt_record(
1538 key,
1539 &self.database_id,
1540 &entity_label(kind),
1541 &revisioned_aad_id(&id, revision, updated_at_unix, None)?,
1542 &encrypted,
1543 )?;
1544 entities.push(StoredEntity {
1545 kind,
1546 id,
1547 revision,
1548 value: serde_json::from_slice(&clear)?,
1549 updated_at_unix,
1550 });
1551 }
1552 Ok(entities)
1553 }
1554
1555 pub fn list_entities_by_id_prefix<T: for<'de> Deserialize<'de>>(
1559 &self,
1560 kind: EntityKind,
1561 prefix: &[u8],
1562 limit: usize,
1563 ) -> Result<Vec<StoredEntity<T>>, StoreError> {
1564 validate_id(prefix)?;
1565 if limit == 0 || limit > MAX_ENTITY_LIST_RESULTS {
1566 return Err(StoreError::InvalidListLimit);
1567 }
1568 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
1569 list_entities_by_id_prefix_from_connection(
1570 &self.connection,
1571 key,
1572 &self.database_id,
1573 kind,
1574 prefix,
1575 limit,
1576 )
1577 }
1578
1579 pub fn list_untrusted_entity_metadata_by_id_prefix(
1587 &self,
1588 kind: EntityKind,
1589 prefix: &[u8],
1590 limit: usize,
1591 ) -> Result<Vec<StoredEntityMetadata>, StoreError> {
1592 validate_id(prefix)?;
1593 if limit == 0 || limit > MAX_ENTITY_LIST_RESULTS {
1594 return Err(StoreError::InvalidListLimit);
1595 }
1596 self.key.as_ref().ok_or(StoreError::Locked)?;
1597 list_untrusted_entity_metadata_by_id_prefix_from_connection(
1598 &self.connection,
1599 kind,
1600 prefix,
1601 limit,
1602 )
1603 }
1604
1605 pub fn delete_entity(
1606 &mut self,
1607 kind: EntityKind,
1608 id: &[u8],
1609 expected_revision: u64,
1610 ) -> Result<bool, StoreError> {
1611 validate_id(id)?;
1612 if kind.deletion_protected() {
1613 return Err(StoreError::ProtectedEntity);
1614 }
1615 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
1616 if expected_revision == 0 {
1617 return Err(StoreError::InvalidRevision);
1618 }
1619 let transaction = self
1620 .connection
1621 .transaction_with_behavior(TransactionBehavior::Immediate)?;
1622 let current: Option<(u64, Vec<u8>, u64)> = transaction
1623 .query_row(
1624 "SELECT revision, encrypted_value, updated_at_unix
1625 FROM encrypted_entities WHERE entity_kind=?1 AND record_id=?2",
1626 params![kind.label(), id],
1627 |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
1628 )
1629 .optional()?;
1630 let Some((actual, encrypted, updated_at_unix)) = current else {
1631 return Ok(false);
1632 };
1633 decrypt_record(
1634 key,
1635 &self.database_id,
1636 &entity_label(kind),
1637 &revisioned_aad_id(id, actual, updated_at_unix, None)?,
1638 &encrypted,
1639 )?;
1640 if actual != expected_revision {
1641 return Err(StoreError::StaleRevision {
1642 expected: expected_revision,
1643 actual,
1644 });
1645 }
1646 transaction.execute(
1647 "DELETE FROM encrypted_entities WHERE entity_kind=?1 AND record_id=?2",
1648 params![kind.label(), id],
1649 )?;
1650 transaction.commit()?;
1651 Ok(true)
1652 }
1653
1654 pub fn delete_entities(
1659 &mut self,
1660 entity_deletes: &[(EntityKind, EntityBatchDelete)],
1661 ) -> Result<(), StoreError> {
1662 if entity_deletes.is_empty() {
1663 return Err(StoreError::InvalidRevision);
1664 }
1665 if entity_deletes.len() > MAX_ENTITY_BATCH_OPERATIONS {
1666 return Err(StoreError::BatchCapacity);
1667 }
1668 let mut identities = BTreeSet::new();
1669 for (entity_kind, delete) in entity_deletes {
1670 validate_id(&delete.id)?;
1671 if entity_kind.deletion_protected() {
1672 return Err(StoreError::ProtectedEntity);
1673 }
1674 if delete.expected_revision == 0 {
1675 return Err(StoreError::InvalidRevision);
1676 }
1677 if !identities.insert((*entity_kind, delete.id.clone())) {
1678 return Err(StoreError::DuplicateBatchEntity);
1679 }
1680 }
1681 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
1682 let transaction = self
1683 .connection
1684 .transaction_with_behavior(TransactionBehavior::Immediate)?;
1685 for (entity_kind, delete) in entity_deletes {
1686 let actual = authenticated_entity_revision(
1687 &transaction,
1688 key,
1689 &self.database_id,
1690 *entity_kind,
1691 &delete.id,
1692 )?
1693 .unwrap_or(0);
1694 if actual != delete.expected_revision {
1695 return Err(StoreError::StaleRevision {
1696 expected: delete.expected_revision,
1697 actual,
1698 });
1699 }
1700 }
1701 for (entity_kind, delete) in entity_deletes {
1702 transaction.execute(
1703 "DELETE FROM encrypted_entities WHERE entity_kind=?1 AND record_id=?2",
1704 params![entity_kind.label(), &delete.id],
1705 )?;
1706 }
1707 transaction.commit()?;
1708 Ok(())
1709 }
1710
1711 entity_crud_methods!(
1712 (
1713 save_wallet_account,
1714 wallet_account,
1715 wallet_accounts,
1716 delete_wallet_account,
1717 WalletAccount
1718 ),
1719 (
1720 save_native_hns_read_profile,
1721 native_hns_read_profile,
1722 native_hns_read_profiles,
1723 delete_native_hns_read_profile,
1724 NativeHnsReadProfile
1725 ),
1726 (
1727 save_derived_address,
1728 derived_address,
1729 derived_addresses,
1730 delete_derived_address,
1731 DerivedAddress
1732 ),
1733 (save_hns_utxo, hns_utxo, hns_utxos, delete_hns_utxo, HnsUtxo),
1734 (
1735 save_hns_transaction,
1736 hns_transaction,
1737 hns_transactions,
1738 delete_hns_transaction,
1739 HnsTransaction
1740 ),
1741 (
1742 save_hns_light_chain,
1743 hns_light_chain,
1744 hns_light_chain_records,
1745 delete_hns_light_chain,
1746 HnsLightChain
1747 ),
1748 (
1749 save_hns_light_wallet,
1750 hns_light_wallet,
1751 hns_light_wallet_records,
1752 delete_hns_light_wallet,
1753 HnsLightWallet
1754 ),
1755 (
1756 save_known_name,
1757 known_name,
1758 known_names,
1759 delete_known_name,
1760 KnownName
1761 ),
1762 (
1763 save_name_owner_outpoint,
1764 name_owner_outpoint,
1765 name_owner_outpoints,
1766 delete_name_owner_outpoint,
1767 NameOwnerOutpoint
1768 ),
1769 (
1770 save_name_transfer,
1771 name_transfer,
1772 name_transfers,
1773 delete_name_transfer,
1774 NameTransfer
1775 ),
1776 (
1777 save_shakedex,
1778 shakedex,
1779 shakedex_records,
1780 delete_shakedex,
1781 Shakedex
1782 ),
1783 (
1784 save_shakescape_board_object,
1785 shakescape_board_object,
1786 shakescape_board_objects,
1787 delete_shakescape_board_object,
1788 ShakescapeBoardObject
1789 ),
1790 (
1791 save_bitcoin_header,
1792 bitcoin_header,
1793 bitcoin_headers,
1794 delete_bitcoin_header,
1795 BitcoinHeader
1796 ),
1797 (
1798 save_bitcoin_filter_header,
1799 bitcoin_filter_header,
1800 bitcoin_filter_headers,
1801 delete_bitcoin_filter_header,
1802 BitcoinFilterHeader
1803 ),
1804 (
1805 save_bitcoin_peer,
1806 bitcoin_peer,
1807 bitcoin_peers,
1808 delete_bitcoin_peer,
1809 BitcoinPeer
1810 ),
1811 (
1812 save_bitcoin_wallet_state,
1813 bitcoin_wallet_state,
1814 bitcoin_wallet_states,
1815 delete_bitcoin_wallet_state,
1816 BitcoinWalletState
1817 ),
1818 (
1819 save_bitcoin_wallet_changeset,
1820 bitcoin_wallet_changeset,
1821 bitcoin_wallet_changesets,
1822 delete_bitcoin_wallet_changeset,
1823 BitcoinWalletChangeSet
1824 ),
1825 (
1826 save_bitcoin_scan_state,
1827 bitcoin_scan_state,
1828 bitcoin_scan_states,
1829 delete_bitcoin_scan_state,
1830 BitcoinScanState
1831 ),
1832 (
1833 save_bitcoin_swap_watch,
1834 bitcoin_swap_watch,
1835 bitcoin_swap_watches,
1836 delete_bitcoin_swap_watch,
1837 BitcoinSwapWatch
1838 ),
1839 (
1840 save_bitcoin_utxo,
1841 bitcoin_utxo,
1842 bitcoin_utxos,
1843 delete_bitcoin_utxo,
1844 BitcoinUtxo
1845 ),
1846 (
1847 save_bitcoin_transaction,
1848 bitcoin_transaction,
1849 bitcoin_transactions,
1850 delete_bitcoin_transaction,
1851 BitcoinTransaction
1852 ),
1853 (
1854 save_ethereum_account,
1855 ethereum_account,
1856 ethereum_accounts,
1857 delete_ethereum_account,
1858 EthereumAccount
1859 ),
1860 (
1861 save_ethereum_transaction,
1862 ethereum_transaction,
1863 ethereum_transactions,
1864 delete_ethereum_transaction,
1865 EthereumTransaction
1866 ),
1867 (
1868 save_swap_session,
1869 swap_session,
1870 swap_sessions,
1871 delete_swap_session,
1872 SwapSession
1873 ),
1874 (
1875 save_refund_transaction,
1876 refund_transaction,
1877 refund_transactions,
1878 delete_refund_transaction,
1879 RefundTransaction
1880 ),
1881 (
1882 save_hns_recovery_state,
1883 hns_recovery_state,
1884 hns_recovery_states,
1885 delete_hns_recovery_state,
1886 HnsRecoveryState
1887 ),
1888 (
1889 save_hns_shakescape_watch,
1890 hns_shakescape_watch,
1891 hns_shakescape_watches,
1892 delete_hns_shakescape_watch,
1893 HnsShakescapeWatch
1894 ),
1895 (
1896 save_hns_verified_settlement,
1897 hns_verified_settlement,
1898 hns_verified_settlements,
1899 delete_hns_verified_settlement,
1900 HnsVerifiedSettlement
1901 ),
1902 (
1903 save_pending_approval_entity,
1904 pending_approval_entity,
1905 pending_approval_entities,
1906 delete_pending_approval_entity,
1907 PendingApproval
1908 ),
1909 (
1910 save_input_reservation,
1911 input_reservation,
1912 input_reservations,
1913 delete_input_reservation,
1914 InputReservation
1915 ),
1916 );
1917
1918 pub fn save_workflow<T: Serialize>(
1922 &mut self,
1923 id: WorkflowId,
1924 kind: WorkflowKind,
1925 expected_revision: u64,
1926 state: &T,
1927 irreversible_broadcast_prepared: bool,
1928 updated_at_unix: u64,
1929 ) -> Result<u64, StoreError> {
1930 let encoded = Zeroizing::new(serde_json::to_vec(state)?);
1931 if encoded.len() > MAX_STATE_BYTES {
1932 return Err(StoreError::RecordTooLarge);
1933 }
1934 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
1935 let label = workflow_label(kind);
1936 let transaction = self
1937 .connection
1938 .transaction_with_behavior(TransactionBehavior::Immediate)?;
1939 let current: Option<(String, u64, Vec<u8>, bool, u64, u32)> = transaction
1940 .query_row(
1941 "SELECT kind, revision, state_json, broadcast_prepared,
1942 updated_at_unix, encryption_version
1943 FROM workflows WHERE id=?1",
1944 params![id.as_bytes().as_slice()],
1945 |row| {
1946 Ok((
1947 row.get(0)?,
1948 row.get(1)?,
1949 row.get(2)?,
1950 row.get(3)?,
1951 row.get(4)?,
1952 row.get(5)?,
1953 ))
1954 },
1955 )
1956 .optional()?;
1957 let actual = match current {
1958 Some((stored_kind, revision, encrypted, broadcast, updated_at, version)) => {
1959 let parsed_kind = parse_workflow_kind(&stored_kind)?;
1960 if parsed_kind != kind {
1961 return Err(StoreError::WorkflowKindMismatch);
1962 }
1963 if version != 1 {
1964 return Err(StoreError::LegacyEncryptionPending);
1965 }
1966 decrypt_record(
1967 key,
1968 &self.database_id,
1969 &workflow_label(parsed_kind),
1970 &revisioned_aad_id(id.as_bytes(), revision, updated_at, Some(broadcast))?,
1971 &encrypted,
1972 )?;
1973 revision
1974 }
1975 None => 0,
1976 };
1977 if actual != expected_revision {
1978 return Err(StoreError::StaleRevision {
1979 expected: expected_revision,
1980 actual,
1981 });
1982 }
1983 let next = actual.checked_add(1).ok_or(StoreError::RevisionOverflow)?;
1984 let aad_id = revisioned_aad_id(
1985 id.as_bytes(),
1986 next,
1987 updated_at_unix,
1988 Some(irreversible_broadcast_prepared),
1989 )?;
1990 let encrypted = encrypt_record(key, &self.database_id, &label, &aad_id, &encoded)?;
1991 transaction.execute(
1992 "INSERT INTO workflows(
1993 id, kind, revision, state_json, broadcast_prepared, updated_at_unix,
1994 encryption_version
1995 ) VALUES(?1, ?2, ?3, ?4, ?5, ?6, 1)
1996 ON CONFLICT(id) DO UPDATE SET revision=excluded.revision,
1997 state_json=excluded.state_json, broadcast_prepared=excluded.broadcast_prepared,
1998 updated_at_unix=excluded.updated_at_unix,
1999 encryption_version=excluded.encryption_version",
2000 params![
2001 id.as_bytes().as_slice(),
2002 workflow_kind(kind),
2003 next,
2004 encrypted,
2005 irreversible_broadcast_prepared,
2006 updated_at_unix,
2007 ],
2008 )?;
2009 transaction.commit()?;
2010 Ok(next)
2011 }
2012
2013 #[allow(clippy::too_many_arguments)]
2017 pub fn save_workflow_with_entity_batch<W: Serialize, E: Serialize>(
2018 &mut self,
2019 id: WorkflowId,
2020 kind: WorkflowKind,
2021 expected_revision: u64,
2022 state: &W,
2023 irreversible_broadcast_prepared: bool,
2024 updated_at_unix: u64,
2025 entity_kind: EntityKind,
2026 saves: &[EntityBatchSave<E>],
2027 deletes: &[EntityBatchDelete],
2028 ) -> Result<u64, StoreError> {
2029 let encoded_workflow = Zeroizing::new(serde_json::to_vec(state)?);
2030 if encoded_workflow.is_empty() || encoded_workflow.len() > MAX_STATE_BYTES {
2031 return Err(StoreError::RecordTooLarge);
2032 }
2033 let prepared_entities = prepare_entity_batch(saves, deletes)?;
2034 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
2035 let transaction = self
2036 .connection
2037 .transaction_with_behavior(TransactionBehavior::Immediate)?;
2038 let actual =
2039 authenticated_workflow_revision(&transaction, key, &self.database_id, id, kind)?;
2040 if actual != expected_revision {
2041 return Err(StoreError::StaleRevision {
2042 expected: expected_revision,
2043 actual,
2044 });
2045 }
2046 apply_entity_batch_in_transaction(
2047 &transaction,
2048 key,
2049 &self.database_id,
2050 entity_kind,
2051 &prepared_entities,
2052 deletes,
2053 )?;
2054 let next = actual.checked_add(1).ok_or(StoreError::RevisionOverflow)?;
2055 let encrypted = encrypt_record(
2056 key,
2057 &self.database_id,
2058 &workflow_label(kind),
2059 &revisioned_aad_id(
2060 id.as_bytes(),
2061 next,
2062 updated_at_unix,
2063 Some(irreversible_broadcast_prepared),
2064 )?,
2065 &encoded_workflow,
2066 )?;
2067 transaction.execute(
2068 "INSERT INTO workflows(
2069 id, kind, revision, state_json, broadcast_prepared, updated_at_unix,
2070 encryption_version
2071 ) VALUES(?1, ?2, ?3, ?4, ?5, ?6, 1)
2072 ON CONFLICT(id) DO UPDATE SET revision=excluded.revision,
2073 state_json=excluded.state_json, broadcast_prepared=excluded.broadcast_prepared,
2074 updated_at_unix=excluded.updated_at_unix,
2075 encryption_version=excluded.encryption_version",
2076 params![
2077 id.as_bytes().as_slice(),
2078 workflow_kind(kind),
2079 next,
2080 encrypted,
2081 irreversible_broadcast_prepared,
2082 updated_at_unix,
2083 ],
2084 )?;
2085 transaction.commit()?;
2086 Ok(next)
2087 }
2088
2089 #[allow(clippy::too_many_arguments)]
2095 pub fn save_workflow_with_entity_batch_and_guards<W: Serialize, E: Serialize>(
2096 &mut self,
2097 id: WorkflowId,
2098 kind: WorkflowKind,
2099 expected_revision: u64,
2100 state: &W,
2101 irreversible_broadcast_prepared: bool,
2102 updated_at_unix: u64,
2103 entity_kind: EntityKind,
2104 saves: &[EntityBatchSave<E>],
2105 deletes: &[EntityBatchDelete],
2106 workflow_guard: WorkflowRevisionAssertion,
2107 entity_guard_kind: EntityKind,
2108 entity_guard: &EntityRevisionAssertion,
2109 consume_entity_guard: bool,
2110 ) -> Result<u64, StoreError> {
2111 if workflow_guard.expected_revision == 0
2112 || entity_guard.expected_revision == 0
2113 || workflow_guard.id == id
2114 {
2115 return Err(StoreError::InvalidRevision);
2116 }
2117 validate_id(&entity_guard.id)?;
2118 if consume_entity_guard && entity_guard_kind.deletion_protected() {
2119 return Err(StoreError::ProtectedEntity);
2120 }
2121 if entity_guard_kind == entity_kind
2122 && (saves.iter().any(|save| save.id == entity_guard.id)
2123 || deletes.iter().any(|delete| delete.id == entity_guard.id))
2124 {
2125 return Err(StoreError::DuplicateBatchEntity);
2126 }
2127 let encoded_workflow = Zeroizing::new(serde_json::to_vec(state)?);
2128 if encoded_workflow.is_empty() || encoded_workflow.len() > MAX_STATE_BYTES {
2129 return Err(StoreError::RecordTooLarge);
2130 }
2131 let prepared_entities = prepare_entity_batch(saves, deletes)?;
2132 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
2133 let transaction = self
2134 .connection
2135 .transaction_with_behavior(TransactionBehavior::Immediate)?;
2136 let actual =
2137 authenticated_workflow_revision(&transaction, key, &self.database_id, id, kind)?;
2138 if actual != expected_revision {
2139 return Err(StoreError::StaleRevision {
2140 expected: expected_revision,
2141 actual,
2142 });
2143 }
2144 let guarded_workflow_revision = authenticated_workflow_revision(
2145 &transaction,
2146 key,
2147 &self.database_id,
2148 workflow_guard.id,
2149 workflow_guard.kind,
2150 )?;
2151 if guarded_workflow_revision != workflow_guard.expected_revision {
2152 return Err(StoreError::StaleRevision {
2153 expected: workflow_guard.expected_revision,
2154 actual: guarded_workflow_revision,
2155 });
2156 }
2157 let guarded_entity_revision = authenticated_entity_revision(
2158 &transaction,
2159 key,
2160 &self.database_id,
2161 entity_guard_kind,
2162 &entity_guard.id,
2163 )?
2164 .unwrap_or(0);
2165 if guarded_entity_revision != entity_guard.expected_revision {
2166 return Err(StoreError::StaleRevision {
2167 expected: entity_guard.expected_revision,
2168 actual: guarded_entity_revision,
2169 });
2170 }
2171 apply_entity_batch_in_transaction(
2172 &transaction,
2173 key,
2174 &self.database_id,
2175 entity_kind,
2176 &prepared_entities,
2177 deletes,
2178 )?;
2179 if consume_entity_guard {
2180 consume_authenticated_entity_revision(
2181 &transaction,
2182 key,
2183 &self.database_id,
2184 entity_guard_kind,
2185 entity_guard,
2186 updated_at_unix,
2187 )?;
2188 }
2189 let next = actual.checked_add(1).ok_or(StoreError::RevisionOverflow)?;
2190 let encrypted = encrypt_record(
2191 key,
2192 &self.database_id,
2193 &workflow_label(kind),
2194 &revisioned_aad_id(
2195 id.as_bytes(),
2196 next,
2197 updated_at_unix,
2198 Some(irreversible_broadcast_prepared),
2199 )?,
2200 &encoded_workflow,
2201 )?;
2202 transaction.execute(
2203 "INSERT INTO workflows(
2204 id, kind, revision, state_json, broadcast_prepared, updated_at_unix,
2205 encryption_version
2206 ) VALUES(?1, ?2, ?3, ?4, ?5, ?6, 1)
2207 ON CONFLICT(id) DO UPDATE SET revision=excluded.revision,
2208 state_json=excluded.state_json, broadcast_prepared=excluded.broadcast_prepared,
2209 updated_at_unix=excluded.updated_at_unix,
2210 encryption_version=excluded.encryption_version",
2211 params![
2212 id.as_bytes().as_slice(),
2213 workflow_kind(kind),
2214 next,
2215 encrypted,
2216 irreversible_broadcast_prepared,
2217 updated_at_unix,
2218 ],
2219 )?;
2220 transaction.commit()?;
2221 Ok(next)
2222 }
2223
2224 #[allow(clippy::too_many_arguments)]
2229 pub fn consume_approval_and_save_workflow_with_entity_batch<W: Serialize, E: Serialize>(
2230 &mut self,
2231 expected_approval: &PendingApproval,
2232 now_unix: u64,
2233 id: WorkflowId,
2234 kind: WorkflowKind,
2235 expected_revision: u64,
2236 state: &W,
2237 irreversible_broadcast_prepared: bool,
2238 entity_kind: EntityKind,
2239 saves: &[EntityBatchSave<E>],
2240 deletes: &[EntityBatchDelete],
2241 ) -> Result<Option<u64>, StoreError> {
2242 let encoded_workflow = Zeroizing::new(serde_json::to_vec(state)?);
2243 if encoded_workflow.is_empty() || encoded_workflow.len() > MAX_STATE_BYTES {
2244 return Err(StoreError::RecordTooLarge);
2245 }
2246 let prepared_entities = prepare_entity_batch(saves, deletes)?;
2247 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
2248 let transaction = self
2249 .connection
2250 .transaction_with_behavior(TransactionBehavior::Immediate)?;
2251 let Some(current_approval) = authenticated_pending_approval(
2252 &transaction,
2253 key,
2254 &self.database_id,
2255 expected_approval.id,
2256 )?
2257 else {
2258 return Ok(None);
2259 };
2260 if current_approval.expires_at_unix <= now_unix {
2261 transaction.execute(
2262 "DELETE FROM private_pending_approvals WHERE id=?1",
2263 params![expected_approval.id.as_bytes().as_slice()],
2264 )?;
2265 transaction.commit()?;
2266 return Ok(None);
2267 }
2268 if current_approval.origin.as_str() != expected_approval.origin.as_str()
2269 || current_approval.expires_at_unix != expected_approval.expires_at_unix
2270 || current_approval.request_json.as_slice() != expected_approval.request_json.as_slice()
2271 {
2272 return Ok(None);
2273 }
2274 let actual =
2275 authenticated_workflow_revision(&transaction, key, &self.database_id, id, kind)?;
2276 if actual != expected_revision {
2277 return Err(StoreError::StaleRevision {
2278 expected: expected_revision,
2279 actual,
2280 });
2281 }
2282 let encrypted_entities = authenticate_entity_batch(
2283 &transaction,
2284 key,
2285 &self.database_id,
2286 entity_kind,
2287 &prepared_entities,
2288 deletes,
2289 )?;
2290 let next = actual.checked_add(1).ok_or(StoreError::RevisionOverflow)?;
2291 let encrypted_workflow = encrypt_record(
2292 key,
2293 &self.database_id,
2294 &workflow_label(kind),
2295 &revisioned_aad_id(
2296 id.as_bytes(),
2297 next,
2298 now_unix,
2299 Some(irreversible_broadcast_prepared),
2300 )?,
2301 &encoded_workflow,
2302 )?;
2303 write_entity_batch_in_transaction(&transaction, entity_kind, &encrypted_entities, deletes)?;
2304 transaction.execute(
2305 "DELETE FROM private_pending_approvals WHERE id=?1",
2306 params![expected_approval.id.as_bytes().as_slice()],
2307 )?;
2308 transaction.execute(
2309 "INSERT INTO workflows(
2310 id, kind, revision, state_json, broadcast_prepared, updated_at_unix,
2311 encryption_version
2312 ) VALUES(?1, ?2, ?3, ?4, ?5, ?6, 1)
2313 ON CONFLICT(id) DO UPDATE SET revision=excluded.revision,
2314 state_json=excluded.state_json, broadcast_prepared=excluded.broadcast_prepared,
2315 updated_at_unix=excluded.updated_at_unix,
2316 encryption_version=excluded.encryption_version",
2317 params![
2318 id.as_bytes().as_slice(),
2319 workflow_kind(kind),
2320 next,
2321 encrypted_workflow,
2322 irreversible_broadcast_prepared,
2323 now_unix,
2324 ],
2325 )?;
2326 transaction.commit()?;
2327 Ok(Some(next))
2328 }
2329
2330 #[allow(clippy::too_many_arguments)]
2335 pub fn save_workflow_with_account_and_entity_batch<W: Serialize, A: Serialize, E: Serialize>(
2336 &mut self,
2337 id: WorkflowId,
2338 kind: WorkflowKind,
2339 expected_revision: u64,
2340 state: &W,
2341 irreversible_broadcast_prepared: bool,
2342 updated_at_unix: u64,
2343 account_save: &EntityBatchSave<A>,
2344 entity_kind: EntityKind,
2345 saves: &[EntityBatchSave<E>],
2346 deletes: &[EntityBatchDelete],
2347 ) -> Result<(u64, u64), StoreError> {
2348 let operation_count = 1_usize
2349 .checked_add(saves.len())
2350 .and_then(|count| count.checked_add(deletes.len()))
2351 .ok_or(StoreError::BatchCapacity)?;
2352 if operation_count > MAX_ENTITY_BATCH_OPERATIONS {
2353 return Err(StoreError::BatchCapacity);
2354 }
2355
2356 let encoded_workflow = Zeroizing::new(serde_json::to_vec(state)?);
2357 if encoded_workflow.is_empty() || encoded_workflow.len() > MAX_STATE_BYTES {
2358 return Err(StoreError::RecordTooLarge);
2359 }
2360 let prepared_account = prepare_entity_batch(std::slice::from_ref(account_save), &[])?;
2361 let prepared_entities = prepare_entity_batch(saves, deletes)?;
2362 let mut operation_ids = BTreeSet::new();
2363 for (record_id, ..) in &prepared_account {
2364 operation_ids.insert((EntityKind::WalletAccount, record_id.clone()));
2365 }
2366 for (record_id, ..) in &prepared_entities {
2367 if !operation_ids.insert((entity_kind, record_id.clone())) {
2368 return Err(StoreError::DuplicateBatchEntity);
2369 }
2370 }
2371 for delete in deletes {
2372 if !operation_ids.insert((entity_kind, delete.id.clone())) {
2373 return Err(StoreError::DuplicateBatchEntity);
2374 }
2375 }
2376
2377 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
2378 let transaction = self
2379 .connection
2380 .transaction_with_behavior(TransactionBehavior::Immediate)?;
2381 let actual =
2382 authenticated_workflow_revision(&transaction, key, &self.database_id, id, kind)?;
2383 if actual != expected_revision {
2384 return Err(StoreError::StaleRevision {
2385 expected: expected_revision,
2386 actual,
2387 });
2388 }
2389 let authenticated_account = authenticate_entity_batch(
2390 &transaction,
2391 key,
2392 &self.database_id,
2393 EntityKind::WalletAccount,
2394 &prepared_account,
2395 &[],
2396 )?;
2397 let authenticated_entities = authenticate_entity_batch(
2398 &transaction,
2399 key,
2400 &self.database_id,
2401 entity_kind,
2402 &prepared_entities,
2403 deletes,
2404 )?;
2405
2406 let next = actual.checked_add(1).ok_or(StoreError::RevisionOverflow)?;
2407 let account_next = authenticated_account
2408 .first()
2409 .map(|(_, revision, _, _)| *revision)
2410 .ok_or(StoreError::CorruptMetadata)?;
2411 let encrypted_workflow = encrypt_record(
2412 key,
2413 &self.database_id,
2414 &workflow_label(kind),
2415 &revisioned_aad_id(
2416 id.as_bytes(),
2417 next,
2418 updated_at_unix,
2419 Some(irreversible_broadcast_prepared),
2420 )?,
2421 &encoded_workflow,
2422 )?;
2423
2424 write_entity_batch_in_transaction(
2425 &transaction,
2426 EntityKind::WalletAccount,
2427 &authenticated_account,
2428 &[],
2429 )?;
2430 write_entity_batch_in_transaction(
2431 &transaction,
2432 entity_kind,
2433 &authenticated_entities,
2434 deletes,
2435 )?;
2436 transaction.execute(
2437 "INSERT INTO workflows(
2438 id, kind, revision, state_json, broadcast_prepared, updated_at_unix,
2439 encryption_version
2440 ) VALUES(?1, ?2, ?3, ?4, ?5, ?6, 1)
2441 ON CONFLICT(id) DO UPDATE SET revision=excluded.revision,
2442 state_json=excluded.state_json, broadcast_prepared=excluded.broadcast_prepared,
2443 updated_at_unix=excluded.updated_at_unix,
2444 encryption_version=excluded.encryption_version",
2445 params![
2446 id.as_bytes().as_slice(),
2447 workflow_kind(kind),
2448 next,
2449 encrypted_workflow,
2450 irreversible_broadcast_prepared,
2451 updated_at_unix,
2452 ],
2453 )?;
2454 transaction.commit()?;
2455 Ok((next, account_next))
2456 }
2457
2458 pub fn apply_account_and_entity_batch<A: Serialize, E: Serialize>(
2462 &mut self,
2463 account_save: &EntityBatchSave<A>,
2464 entity_kind: EntityKind,
2465 saves: &[EntityBatchSave<E>],
2466 deletes: &[EntityBatchDelete],
2467 ) -> Result<u64, StoreError> {
2468 if entity_kind == EntityKind::WalletAccount {
2469 return Err(StoreError::DuplicateBatchEntity);
2470 }
2471 let operation_count = 1_usize
2472 .checked_add(saves.len())
2473 .and_then(|count| count.checked_add(deletes.len()))
2474 .ok_or(StoreError::BatchCapacity)?;
2475 if operation_count > MAX_ENTITY_BATCH_OPERATIONS {
2476 return Err(StoreError::BatchCapacity);
2477 }
2478 let prepared_account = prepare_entity_batch(std::slice::from_ref(account_save), &[])?;
2479 let prepared_entities = prepare_entity_batch(saves, deletes)?;
2480 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
2481 let transaction = self
2482 .connection
2483 .transaction_with_behavior(TransactionBehavior::Immediate)?;
2484 let authenticated_account = authenticate_entity_batch(
2485 &transaction,
2486 key,
2487 &self.database_id,
2488 EntityKind::WalletAccount,
2489 &prepared_account,
2490 &[],
2491 )?;
2492 let authenticated_entities = authenticate_entity_batch(
2493 &transaction,
2494 key,
2495 &self.database_id,
2496 entity_kind,
2497 &prepared_entities,
2498 deletes,
2499 )?;
2500 let account_next = authenticated_account
2501 .first()
2502 .map(|(_, revision, _, _)| *revision)
2503 .ok_or(StoreError::CorruptMetadata)?;
2504 write_entity_batch_in_transaction(
2505 &transaction,
2506 EntityKind::WalletAccount,
2507 &authenticated_account,
2508 &[],
2509 )?;
2510 write_entity_batch_in_transaction(
2511 &transaction,
2512 entity_kind,
2513 &authenticated_entities,
2514 deletes,
2515 )?;
2516 transaction.commit()?;
2517 Ok(account_next)
2518 }
2519
2520 pub fn apply_entity_batch<E: Serialize>(
2521 &mut self,
2522 entity_kind: EntityKind,
2523 saves: &[EntityBatchSave<E>],
2524 deletes: &[EntityBatchDelete],
2525 ) -> Result<(), StoreError> {
2526 let prepared_entities = prepare_entity_batch(saves, deletes)?;
2527 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
2528 let transaction = self
2529 .connection
2530 .transaction_with_behavior(TransactionBehavior::Immediate)?;
2531 apply_entity_batch_in_transaction(
2532 &transaction,
2533 key,
2534 &self.database_id,
2535 entity_kind,
2536 &prepared_entities,
2537 deletes,
2538 )?;
2539 transaction.commit()?;
2540 Ok(())
2541 }
2542
2543 pub fn apply_entity_batch_with_assertions<E: Serialize>(
2550 &mut self,
2551 entity_kind: EntityKind,
2552 saves: &[EntityBatchSave<E>],
2553 deletes: &[EntityBatchDelete],
2554 assertions: &[EntityRevisionAssertion],
2555 ) -> Result<(), StoreError> {
2556 let prepared_entities = prepare_entity_batch(saves, deletes)?;
2557 validate_entity_revision_assertions(saves, deletes, assertions)?;
2558 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
2559 let transaction = self
2560 .connection
2561 .transaction_with_behavior(TransactionBehavior::Immediate)?;
2562 let encrypted_saves = authenticate_entity_batch(
2563 &transaction,
2564 key,
2565 &self.database_id,
2566 entity_kind,
2567 &prepared_entities,
2568 deletes,
2569 )?;
2570 authenticate_entity_revision_assertions(
2571 &transaction,
2572 key,
2573 &self.database_id,
2574 entity_kind,
2575 assertions,
2576 )?;
2577 write_entity_batch_in_transaction(&transaction, entity_kind, &encrypted_saves, deletes)?;
2578 transaction.commit()?;
2579 Ok(())
2580 }
2581
2582 #[allow(clippy::too_many_arguments)]
2588 pub fn apply_entity_batch_with_workflow_guard_and_consumed_entity<E: Serialize>(
2589 &mut self,
2590 entity_kind: EntityKind,
2591 saves: &[EntityBatchSave<E>],
2592 deletes: &[EntityBatchDelete],
2593 workflow_guard: WorkflowRevisionAssertion,
2594 consumed_entity_kind: EntityKind,
2595 consumed_entity: &EntityRevisionAssertion,
2596 consumed_at_unix: u64,
2597 ) -> Result<(), StoreError> {
2598 if workflow_guard.expected_revision == 0
2599 || consumed_entity.expected_revision == 0
2600 || consumed_entity_kind.deletion_protected()
2601 || consumed_at_unix == 0
2602 {
2603 return Err(StoreError::InvalidRevision);
2604 }
2605 validate_id(&consumed_entity.id)?;
2606 if consumed_entity_kind == entity_kind
2607 && (saves.iter().any(|save| save.id == consumed_entity.id)
2608 || deletes.iter().any(|delete| delete.id == consumed_entity.id))
2609 {
2610 return Err(StoreError::DuplicateBatchEntity);
2611 }
2612 let prepared_entities = prepare_entity_batch(saves, deletes)?;
2613 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
2614 let transaction = self
2615 .connection
2616 .transaction_with_behavior(TransactionBehavior::Immediate)?;
2617 let guarded_workflow_revision = authenticated_workflow_revision(
2618 &transaction,
2619 key,
2620 &self.database_id,
2621 workflow_guard.id,
2622 workflow_guard.kind,
2623 )?;
2624 if guarded_workflow_revision != workflow_guard.expected_revision {
2625 return Err(StoreError::StaleRevision {
2626 expected: workflow_guard.expected_revision,
2627 actual: guarded_workflow_revision,
2628 });
2629 }
2630 let consumed_revision = authenticated_entity_revision(
2631 &transaction,
2632 key,
2633 &self.database_id,
2634 consumed_entity_kind,
2635 &consumed_entity.id,
2636 )?
2637 .unwrap_or(0);
2638 if consumed_revision != consumed_entity.expected_revision {
2639 return Err(StoreError::StaleRevision {
2640 expected: consumed_entity.expected_revision,
2641 actual: consumed_revision,
2642 });
2643 }
2644 apply_entity_batch_in_transaction(
2645 &transaction,
2646 key,
2647 &self.database_id,
2648 entity_kind,
2649 &prepared_entities,
2650 deletes,
2651 )?;
2652 consume_authenticated_entity_revision(
2653 &transaction,
2654 key,
2655 &self.database_id,
2656 consumed_entity_kind,
2657 consumed_entity,
2658 consumed_at_unix,
2659 )?;
2660 transaction.commit()?;
2661 Ok(())
2662 }
2663
2664 pub fn apply_entity_batch_with_assertions_and_prefix_lease<E: Serialize>(
2672 &mut self,
2673 entity_kind: EntityKind,
2674 saves: &[EntityBatchSave<E>],
2675 deletes: &[EntityBatchDelete],
2676 assertions: &[EntityRevisionAssertion],
2677 prefix_lease: EntityPrefixSetLease,
2678 ) -> Result<(), StoreError> {
2679 self.apply_entity_batch_with_assertions_and_prefix_lease_guard_inner(
2680 entity_kind,
2681 saves,
2682 deletes,
2683 assertions,
2684 prefix_lease,
2685 None,
2686 )
2687 }
2688
2689 pub fn apply_entity_batch_with_assertions_and_prefix_lease_guard<E: Serialize>(
2697 &mut self,
2698 entity_kind: EntityKind,
2699 saves: &[EntityBatchSave<E>],
2700 deletes: &[EntityBatchDelete],
2701 assertions: &[EntityRevisionAssertion],
2702 prefix_lease: EntityPrefixSetLease,
2703 guard_prefix_lease: EntityPrefixSetLease,
2704 ) -> Result<(), StoreError> {
2705 self.apply_entity_batch_with_assertions_and_prefix_lease_guard_inner(
2706 entity_kind,
2707 saves,
2708 deletes,
2709 assertions,
2710 prefix_lease,
2711 Some(guard_prefix_lease),
2712 )
2713 }
2714
2715 fn apply_entity_batch_with_assertions_and_prefix_lease_guard_inner<E: Serialize>(
2716 &mut self,
2717 entity_kind: EntityKind,
2718 saves: &[EntityBatchSave<E>],
2719 deletes: &[EntityBatchDelete],
2720 assertions: &[EntityRevisionAssertion],
2721 prefix_lease: EntityPrefixSetLease,
2722 guard_prefix_lease: Option<EntityPrefixSetLease>,
2723 ) -> Result<(), StoreError> {
2724 let prepared_entities = prepare_entity_batch(saves, deletes)?;
2725 validate_entity_revision_assertions(saves, deletes, assertions)?;
2726 validate_entity_prefix_set_lease(
2727 &self.database_id,
2728 entity_kind,
2729 saves,
2730 deletes,
2731 assertions,
2732 &prefix_lease,
2733 )?;
2734 if let Some(guard) = &guard_prefix_lease {
2735 validate_entity_prefix_set_lease_shape(&self.database_id, guard)?;
2736 }
2737 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
2738 let transaction = self
2739 .connection
2740 .transaction_with_behavior(TransactionBehavior::Immediate)?;
2741 assert_entity_prefix_set_lease(&transaction, &prefix_lease)?;
2742 if let Some(guard) = &guard_prefix_lease {
2743 assert_entity_prefix_set_lease(&transaction, guard)?;
2744 }
2745 let encrypted_saves = authenticate_entity_batch(
2746 &transaction,
2747 key,
2748 &self.database_id,
2749 entity_kind,
2750 &prepared_entities,
2751 deletes,
2752 )?;
2753 authenticate_entity_revision_assertions(
2754 &transaction,
2755 key,
2756 &self.database_id,
2757 entity_kind,
2758 assertions,
2759 )?;
2760 write_entity_batch_in_transaction(&transaction, entity_kind, &encrypted_saves, deletes)?;
2761 transaction.commit()?;
2762 Ok(())
2763 }
2764
2765 pub fn load_workflow<T: for<'de> Deserialize<'de>>(
2766 &self,
2767 id: WorkflowId,
2768 ) -> Result<Option<StoredWorkflow<T>>, StoreError> {
2769 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
2770 let row: Option<(String, u64, Vec<u8>, bool, u64, u32)> = self
2771 .connection
2772 .query_row(
2773 "SELECT kind, revision, state_json, broadcast_prepared, updated_at_unix,
2774 encryption_version
2775 FROM workflows WHERE id=?1",
2776 params![id.as_bytes().as_slice()],
2777 |row| {
2778 Ok((
2779 row.get(0)?,
2780 row.get(1)?,
2781 row.get(2)?,
2782 row.get(3)?,
2783 row.get(4)?,
2784 row.get(5)?,
2785 ))
2786 },
2787 )
2788 .optional()?;
2789 row.map(
2790 |(kind, revision, state, broadcast_prepared, updated_at_unix, encryption_version)| {
2791 if encryption_version != 1 {
2792 return Err(StoreError::LegacyEncryptionPending);
2793 }
2794 let parsed_kind = parse_workflow_kind(&kind)?;
2795 let clear = decrypt_record(
2796 key,
2797 &self.database_id,
2798 &workflow_label(parsed_kind),
2799 &revisioned_aad_id(
2800 id.as_bytes(),
2801 revision,
2802 updated_at_unix,
2803 Some(broadcast_prepared),
2804 )?,
2805 &state,
2806 )?;
2807 Ok(StoredWorkflow {
2808 id,
2809 kind: parsed_kind,
2810 revision,
2811 state: serde_json::from_slice(&clear)?,
2812 irreversible_broadcast_prepared: broadcast_prepared,
2813 updated_at_unix,
2814 })
2815 },
2816 )
2817 .transpose()
2818 }
2819
2820 pub fn list_workflows<T: for<'de> Deserialize<'de>>(
2821 &self,
2822 kind: WorkflowKind,
2823 limit: usize,
2824 ) -> Result<Vec<StoredWorkflow<T>>, StoreError> {
2825 if limit == 0 || limit > MAX_ENTITY_LIST_RESULTS {
2826 return Err(StoreError::InvalidListLimit);
2827 }
2828 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
2829 let limit = i64::try_from(limit).map_err(|_| StoreError::InvalidListLimit)?;
2830 let mut statement = self.connection.prepare(
2831 "SELECT id, revision, state_json, broadcast_prepared, updated_at_unix,
2832 encryption_version
2833 FROM workflows WHERE kind=?1 ORDER BY id LIMIT ?2",
2834 )?;
2835 let rows = statement.query_map(params![workflow_kind(kind), limit], |row| {
2836 Ok((
2837 row.get::<_, Vec<u8>>(0)?,
2838 row.get::<_, u64>(1)?,
2839 row.get::<_, Vec<u8>>(2)?,
2840 row.get::<_, bool>(3)?,
2841 row.get::<_, u64>(4)?,
2842 row.get::<_, u32>(5)?,
2843 ))
2844 })?;
2845 let mut workflows = Vec::new();
2846 for row in rows {
2847 let (id, revision, state, broadcast_prepared, updated_at_unix, encryption_version) =
2848 row?;
2849 if encryption_version != 1 {
2850 return Err(StoreError::LegacyEncryptionPending);
2851 }
2852 let id = WorkflowId::new(id.try_into().map_err(|_| StoreError::CorruptMetadata)?);
2853 let clear = decrypt_record(
2854 key,
2855 &self.database_id,
2856 &workflow_label(kind),
2857 &revisioned_aad_id(
2858 id.as_bytes(),
2859 revision,
2860 updated_at_unix,
2861 Some(broadcast_prepared),
2862 )?,
2863 &state,
2864 )?;
2865 workflows.push(StoredWorkflow {
2866 id,
2867 kind,
2868 revision,
2869 state: serde_json::from_slice(&clear)?,
2870 irreversible_broadcast_prepared: broadcast_prepared,
2871 updated_at_unix,
2872 });
2873 }
2874 Ok(workflows)
2875 }
2876
2877 pub fn list_workflows_complete<T: for<'de> Deserialize<'de>>(
2880 &self,
2881 kind: WorkflowKind,
2882 limit: usize,
2883 ) -> Result<Vec<StoredWorkflow<T>>, StoreError> {
2884 if limit == 0 || limit > MAX_ENTITY_LIST_RESULTS {
2885 return Err(StoreError::InvalidListLimit);
2886 }
2887 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
2888 let query_limit = limit
2889 .checked_add(1)
2890 .and_then(|value| i64::try_from(value).ok())
2891 .ok_or(StoreError::InvalidListLimit)?;
2892 let mut statement = self.connection.prepare(
2893 "SELECT id, revision, state_json, broadcast_prepared, updated_at_unix,
2894 encryption_version
2895 FROM workflows WHERE kind=?1 ORDER BY id LIMIT ?2",
2896 )?;
2897 let rows = statement.query_map(params![workflow_kind(kind), query_limit], |row| {
2898 Ok((
2899 row.get::<_, Vec<u8>>(0)?,
2900 row.get::<_, u64>(1)?,
2901 row.get::<_, Vec<u8>>(2)?,
2902 row.get::<_, bool>(3)?,
2903 row.get::<_, u64>(4)?,
2904 row.get::<_, u32>(5)?,
2905 ))
2906 })?;
2907 let mut encrypted_workflows = Vec::new();
2908 for row in rows {
2909 encrypted_workflows.push(row?);
2910 }
2911 if encrypted_workflows.len() > limit {
2912 return Err(StoreError::ListCapacity);
2913 }
2914 let mut workflows = Vec::with_capacity(encrypted_workflows.len());
2915 for (id, revision, state, broadcast_prepared, updated_at_unix, encryption_version) in
2916 encrypted_workflows
2917 {
2918 if encryption_version != 1 {
2919 return Err(StoreError::LegacyEncryptionPending);
2920 }
2921 let id = WorkflowId::new(id.try_into().map_err(|_| StoreError::CorruptMetadata)?);
2922 let clear = decrypt_record(
2923 key,
2924 &self.database_id,
2925 &workflow_label(kind),
2926 &revisioned_aad_id(
2927 id.as_bytes(),
2928 revision,
2929 updated_at_unix,
2930 Some(broadcast_prepared),
2931 )?,
2932 &state,
2933 )?;
2934 workflows.push(StoredWorkflow {
2935 id,
2936 kind,
2937 revision,
2938 state: serde_json::from_slice(&clear)?,
2939 irreversible_broadcast_prepared: broadcast_prepared,
2940 updated_at_unix,
2941 });
2942 }
2943 Ok(workflows)
2944 }
2945
2946 pub fn list_workflow_ids_complete(
2951 &self,
2952 kind: WorkflowKind,
2953 limit: usize,
2954 ) -> Result<Vec<WorkflowId>, StoreError> {
2955 if limit == 0 || limit > MAX_ENTITY_LIST_RESULTS {
2956 return Err(StoreError::InvalidListLimit);
2957 }
2958 let _key = self.key.as_ref().ok_or(StoreError::Locked)?;
2959 let query_limit = limit
2960 .checked_add(1)
2961 .and_then(|value| i64::try_from(value).ok())
2962 .ok_or(StoreError::InvalidListLimit)?;
2963 let mut statement = self
2964 .connection
2965 .prepare("SELECT id FROM workflows WHERE kind=?1 ORDER BY id LIMIT ?2")?;
2966 let rows = statement.query_map(params![workflow_kind(kind), query_limit], |row| {
2967 row.get::<_, Vec<u8>>(0)
2968 })?;
2969 let mut ids = Vec::new();
2970 for row in rows {
2971 ids.push(WorkflowId::new(
2972 row?.try_into().map_err(|_| StoreError::CorruptMetadata)?,
2973 ));
2974 }
2975 if ids.len() > limit {
2976 return Err(StoreError::ListCapacity);
2977 }
2978 Ok(ids)
2979 }
2980
2981 pub fn put_provider_permission(
2982 &mut self,
2983 origin: &str,
2984 generation: u64,
2985 permission_json: &[u8],
2986 updated_at_unix: u64,
2987 ) -> Result<(), StoreError> {
2988 validate_origin(origin)?;
2989 if generation == 0 {
2990 return Err(StoreError::InvalidGeneration);
2991 }
2992 if permission_json.is_empty() || permission_json.len() > MAX_STATE_BYTES {
2993 return Err(StoreError::RecordTooLarge);
2994 }
2995 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
2996 let record_id = origin_lookup_token(key, &self.database_id, origin)?;
2997 let clear = encode_origin_payload(origin, permission_json)?;
2998 let transaction = self
2999 .connection
3000 .transaction_with_behavior(TransactionBehavior::Immediate)?;
3001 let current: Option<(u64, Vec<u8>, u64, bool)> = transaction
3002 .query_row(
3003 "SELECT generation, encrypted_record, updated_at_unix, revoked
3004 FROM private_provider_permissions WHERE origin_token=?1",
3005 params![record_id.as_slice()],
3006 |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
3007 )
3008 .optional()?;
3009 let current_generation = match current.as_ref() {
3010 Some((generation, encrypted, current_updated_at, revoked)) => {
3011 let current_clear = decrypt_record(
3012 key,
3013 &self.database_id,
3014 "provider_permission",
3015 &permission_record_id(&record_id, *generation, *revoked, *current_updated_at),
3016 encrypted,
3017 )?;
3018 let (stored_origin, _) = decode_origin_payload(¤t_clear)?;
3019 if stored_origin != origin {
3020 return Err(StoreError::Encryption);
3021 }
3022 *generation
3023 }
3024 None => 0,
3025 };
3026 let expected_generation = if current.is_none() {
3027 generation
3028 } else {
3029 current_generation
3030 .checked_add(1)
3031 .ok_or(StoreError::RevisionOverflow)?
3032 };
3033 if generation != expected_generation {
3034 return Err(StoreError::StaleGeneration {
3035 expected: expected_generation,
3036 actual: generation,
3037 });
3038 }
3039 let encrypted = encrypt_record(
3040 key,
3041 &self.database_id,
3042 "provider_permission",
3043 &permission_record_id(&record_id, generation, false, updated_at_unix),
3044 &clear,
3045 )?;
3046 if current.is_none() {
3047 let count: usize = transaction.query_row(
3048 "SELECT COUNT(*) FROM private_provider_permissions",
3049 [],
3050 |row| row.get(0),
3051 )?;
3052 if count >= MAX_PROVIDER_PERMISSIONS {
3053 return Err(StoreError::ProviderCapacity);
3054 }
3055 }
3056 transaction.execute(
3057 "INSERT INTO private_provider_permissions(
3058 origin_token, generation, encrypted_record, updated_at_unix, revoked
3059 ) VALUES(?1, ?2, ?3, ?4, 0)
3060 ON CONFLICT(origin_token) DO UPDATE SET generation=excluded.generation,
3061 encrypted_record=excluded.encrypted_record,
3062 updated_at_unix=excluded.updated_at_unix, revoked=0",
3063 params![record_id.as_slice(), generation, encrypted, updated_at_unix],
3064 )?;
3065 transaction.commit()?;
3066 Ok(())
3067 }
3068
3069 pub fn provider_permission(&self, origin: &str) -> Result<Option<(u64, Vec<u8>)>, StoreError> {
3070 validate_origin(origin)?;
3071 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
3072 let record_id = origin_lookup_token(key, &self.database_id, origin)?;
3073 let row: Option<(u64, Vec<u8>, u64, bool)> = self
3074 .connection
3075 .query_row(
3076 "SELECT generation, encrypted_record, updated_at_unix, revoked
3077 FROM private_provider_permissions WHERE origin_token=?1",
3078 params![record_id.as_slice()],
3079 |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
3080 )
3081 .optional()
3082 .map_err(StoreError::from)?;
3083 row.map(|(generation, encrypted, updated_at_unix, revoked)| {
3084 let clear = decrypt_record(
3085 key,
3086 &self.database_id,
3087 "provider_permission",
3088 &permission_record_id(&record_id, generation, revoked, updated_at_unix),
3089 &encrypted,
3090 )?;
3091 let (stored_origin, permission_json) = decode_origin_payload(&clear)?;
3092 if stored_origin != origin {
3093 return Err(StoreError::Encryption);
3094 }
3095 if revoked {
3096 Ok(None)
3097 } else {
3098 Ok(Some((generation, permission_json.to_vec())))
3099 }
3100 })
3101 .transpose()
3102 .map(Option::flatten)
3103 }
3104
3105 pub fn provider_permission_generation(&self, origin: &str) -> Result<Option<u64>, StoreError> {
3106 validate_origin(origin)?;
3107 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
3108 let record_id = origin_lookup_token(key, &self.database_id, origin)?;
3109 let row: Option<(u64, Vec<u8>, u64, bool)> = self
3110 .connection
3111 .query_row(
3112 "SELECT generation, encrypted_record, updated_at_unix, revoked
3113 FROM private_provider_permissions WHERE origin_token=?1",
3114 params![record_id.as_slice()],
3115 |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
3116 )
3117 .optional()?;
3118 row.map(|(generation, encrypted, updated_at_unix, revoked)| {
3119 let clear = decrypt_record(
3120 key,
3121 &self.database_id,
3122 "provider_permission",
3123 &permission_record_id(&record_id, generation, revoked, updated_at_unix),
3124 &encrypted,
3125 )?;
3126 let (stored_origin, _) = decode_origin_payload(&clear)?;
3127 if stored_origin != origin {
3128 return Err(StoreError::Encryption);
3129 }
3130 Ok(generation)
3131 })
3132 .transpose()
3133 }
3134
3135 pub fn revoke_provider_permission(
3136 &mut self,
3137 origin: &str,
3138 expected_generation: u64,
3139 next_generation: u64,
3140 updated_at_unix: u64,
3141 ) -> Result<(), StoreError> {
3142 validate_origin(origin)?;
3143 if expected_generation == 0
3144 || next_generation
3145 != expected_generation
3146 .checked_add(1)
3147 .ok_or(StoreError::RevisionOverflow)?
3148 {
3149 return Err(StoreError::InvalidGeneration);
3150 }
3151 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
3152 let record_id = origin_lookup_token(key, &self.database_id, origin)?;
3153 let transaction = self
3154 .connection
3155 .transaction_with_behavior(TransactionBehavior::Immediate)?;
3156 let current: Option<(u64, Vec<u8>, u64, bool)> = transaction
3157 .query_row(
3158 "SELECT generation, encrypted_record, updated_at_unix, revoked
3159 FROM private_provider_permissions WHERE origin_token=?1",
3160 params![record_id.as_slice()],
3161 |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
3162 )
3163 .optional()?;
3164 let Some((generation, encrypted, current_updated_at, current_revoked)) = current else {
3165 return Err(StoreError::StaleGeneration {
3166 expected: expected_generation,
3167 actual: 0,
3168 });
3169 };
3170 if generation != expected_generation || current_revoked {
3171 return Err(StoreError::StaleGeneration {
3172 expected: expected_generation,
3173 actual: generation,
3174 });
3175 }
3176 let clear = decrypt_record(
3177 key,
3178 &self.database_id,
3179 "provider_permission",
3180 &permission_record_id(&record_id, generation, current_revoked, current_updated_at),
3181 &encrypted,
3182 )?;
3183 let (stored_origin, _) = decode_origin_payload(&clear)?;
3184 if stored_origin != origin {
3185 return Err(StoreError::Encryption);
3186 }
3187 let tombstone = encode_origin_payload(origin, b"revoked")?;
3188 let encrypted = encrypt_record(
3189 key,
3190 &self.database_id,
3191 "provider_permission",
3192 &permission_record_id(&record_id, next_generation, true, updated_at_unix),
3193 &tombstone,
3194 )?;
3195 transaction.execute(
3196 "UPDATE private_provider_permissions
3197 SET generation=?1, encrypted_record=?2, updated_at_unix=?3, revoked=1
3198 WHERE origin_token=?4",
3199 params![
3200 next_generation,
3201 encrypted,
3202 updated_at_unix,
3203 record_id.as_slice()
3204 ],
3205 )?;
3206 transaction.commit()?;
3207 Ok(())
3208 }
3209
3210 pub fn put_pending_approval(
3211 &mut self,
3212 id: ApprovalId,
3213 origin: &str,
3214 request_json: &[u8],
3215 now_unix: u64,
3216 expires_at_unix: u64,
3217 ) -> Result<(), StoreError> {
3218 validate_origin(origin)?;
3219 if expires_at_unix <= now_unix || expires_at_unix - now_unix > MAX_APPROVAL_LIFETIME_SECONDS
3220 {
3221 return Err(StoreError::InvalidApprovalWindow);
3222 }
3223 if request_json.is_empty() || request_json.len() > MAX_STATE_BYTES {
3224 return Err(StoreError::RecordTooLarge);
3225 }
3226 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
3227 let origin_token = origin_lookup_token(key, &self.database_id, origin)?;
3228 let clear = encode_origin_payload(origin, request_json)?;
3229 let encrypted = encrypt_record(
3230 key,
3231 &self.database_id,
3232 "pending_approval",
3233 &approval_record_id(&id, &origin_token, expires_at_unix),
3234 &clear,
3235 )?;
3236 let transaction = self
3237 .connection
3238 .transaction_with_behavior(TransactionBehavior::Immediate)?;
3239 prune_expired_approvals(&transaction, key, &self.database_id, now_unix)?;
3240 let count: usize = transaction.query_row(
3241 "SELECT COUNT(*) FROM private_pending_approvals",
3242 [],
3243 |row| row.get(0),
3244 )?;
3245 if count >= MAX_PENDING_APPROVALS {
3246 return Err(StoreError::ApprovalCapacity);
3247 }
3248 transaction.execute(
3249 "INSERT INTO private_pending_approvals(
3250 id, origin_token, encrypted_record, expires_at_unix
3251 ) VALUES(?1, ?2, ?3, ?4)",
3252 params![
3253 id.as_bytes().as_slice(),
3254 origin_token.as_slice(),
3255 encrypted,
3256 expires_at_unix
3257 ],
3258 )?;
3259 transaction.commit()?;
3260 Ok(())
3261 }
3262
3263 pub fn get_pending_approval(
3267 &self,
3268 id: ApprovalId,
3269 now_unix: u64,
3270 ) -> Result<Option<PendingApproval>, StoreError> {
3271 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
3272 Ok(
3273 authenticated_pending_approval(&self.connection, key, &self.database_id, id)?
3274 .filter(|approval| approval.expires_at_unix > now_unix),
3275 )
3276 }
3277
3278 pub fn take_pending_approval(
3281 &mut self,
3282 id: ApprovalId,
3283 now_unix: u64,
3284 ) -> Result<Option<PendingApproval>, StoreError> {
3285 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
3286 let transaction = self
3287 .connection
3288 .transaction_with_behavior(TransactionBehavior::Immediate)?;
3289 let Some(approval) =
3290 authenticated_pending_approval(&transaction, key, &self.database_id, id)?
3291 else {
3292 return Ok(None);
3293 };
3294 if approval.expires_at_unix <= now_unix {
3295 transaction.execute(
3296 "DELETE FROM private_pending_approvals WHERE id=?1",
3297 params![id.as_bytes().as_slice()],
3298 )?;
3299 transaction.commit()?;
3300 return Ok(None);
3301 }
3302 transaction.execute(
3303 "DELETE FROM private_pending_approvals WHERE id=?1",
3304 params![id.as_bytes().as_slice()],
3305 )?;
3306 transaction.commit()?;
3307 Ok(Some(approval))
3308 }
3309
3310 pub fn consume_replay_nonce(
3312 &mut self,
3313 origin: &str,
3314 nonce: u64,
3315 now_unix: u64,
3316 expires_at_unix: u64,
3317 ) -> Result<(), StoreError> {
3318 validate_origin(origin)?;
3319 if nonce == 0
3320 || expires_at_unix <= now_unix
3321 || expires_at_unix - now_unix > MAX_REPLAY_LIFETIME_SECONDS
3322 {
3323 return Err(StoreError::InvalidReplayWindow);
3324 }
3325 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
3326 let origin_token = origin_lookup_token(key, &self.database_id, origin)?;
3327 let record_id = replay_record_id(&origin_token, nonce, expires_at_unix);
3328 let encrypted_origin = encrypt_record(
3329 key,
3330 &self.database_id,
3331 "replay_origin",
3332 &record_id,
3333 origin.as_bytes(),
3334 )?;
3335 let transaction = self
3336 .connection
3337 .transaction_with_behavior(TransactionBehavior::Immediate)?;
3338 prune_expired_replay(&transaction, key, &self.database_id, now_unix)?;
3339 let count: usize = transaction.query_row(
3340 "SELECT COUNT(*) FROM private_replay_protection WHERE origin_token=?1",
3341 params![origin_token.as_slice()],
3342 |row| row.get(0),
3343 )?;
3344 if count >= MAX_REPLAY_ROWS_PER_ORIGIN {
3345 return Err(StoreError::ReplayCapacity);
3346 }
3347 let total: usize = transaction.query_row(
3348 "SELECT COUNT(*) FROM private_replay_protection",
3349 [],
3350 |row| row.get(0),
3351 )?;
3352 if total >= MAX_REPLAY_ROWS {
3353 return Err(StoreError::ReplayGlobalCapacity);
3354 }
3355 if count == 0 {
3356 let origin_count: usize = transaction.query_row(
3357 "SELECT COUNT(DISTINCT origin_token) FROM private_replay_protection",
3358 [],
3359 |row| row.get(0),
3360 )?;
3361 if origin_count >= MAX_REPLAY_ORIGINS {
3362 return Err(StoreError::ReplayOriginCapacity);
3363 }
3364 }
3365 let inserted = transaction.execute(
3366 "INSERT OR IGNORE INTO private_replay_protection(
3367 origin_token, nonce, encrypted_origin, expires_at_unix
3368 ) VALUES(?1, ?2, ?3, ?4)",
3369 params![
3370 origin_token.as_slice(),
3371 nonce,
3372 encrypted_origin,
3373 expires_at_unix
3374 ],
3375 )?;
3376 if inserted != 1 {
3377 return Err(StoreError::Replay);
3378 }
3379 transaction.commit()?;
3380 Ok(())
3381 }
3382
3383 fn encrypt_legacy_rows(&mut self) -> Result<(), StoreError> {
3384 let key = self.key.as_ref().ok_or(StoreError::Locked)?;
3385 let transaction = self
3386 .connection
3387 .transaction_with_behavior(TransactionBehavior::Immediate)?;
3388
3389 reject_unmigrated_legacy_entities(&transaction)?;
3390
3391 let workflows = {
3392 let mut statement = transaction.prepare(
3393 "SELECT id, kind, revision, state_json, broadcast_prepared, updated_at_unix
3394 FROM workflows
3395 WHERE encryption_version=0 ORDER BY id",
3396 )?;
3397 let rows = statement.query_map([], |row| {
3398 Ok((
3399 row.get::<_, Vec<u8>>(0)?,
3400 row.get::<_, String>(1)?,
3401 row.get::<_, u64>(2)?,
3402 row.get::<_, Vec<u8>>(3)?,
3403 row.get::<_, bool>(4)?,
3404 row.get::<_, u64>(5)?,
3405 ))
3406 })?;
3407 rows.collect::<Result<Vec<_>, _>>()?
3408 };
3409 let removed_plaintext = !workflows.is_empty();
3410 for (id, kind, revision, clear, broadcast_prepared, updated_at_unix) in workflows {
3411 let clear = Zeroizing::new(clear);
3412 validate_id(&id)?;
3413 let kind = parse_workflow_kind(&kind)?;
3414 let encrypted = encrypt_record(
3415 key,
3416 &self.database_id,
3417 &workflow_label(kind),
3418 &revisioned_aad_id(&id, revision, updated_at_unix, Some(broadcast_prepared))?,
3419 &clear,
3420 )?;
3421 transaction.execute(
3422 "UPDATE workflows SET state_json=?1, encryption_version=1 WHERE id=?2",
3423 params![encrypted, id],
3424 )?;
3425 }
3426
3427 let permissions = {
3428 let mut statement = transaction.prepare(
3429 "SELECT origin, generation, permission_json, updated_at_unix
3430 FROM provider_permissions ORDER BY origin",
3431 )?;
3432 let rows = statement.query_map([], |row| {
3433 Ok((
3434 row.get::<_, String>(0)?,
3435 row.get::<_, u64>(1)?,
3436 row.get::<_, Vec<u8>>(2)?,
3437 row.get::<_, u64>(3)?,
3438 ))
3439 })?;
3440 rows.collect::<Result<Vec<_>, _>>()?
3441 };
3442 if permissions.len() > MAX_PROVIDER_PERMISSIONS {
3443 return Err(StoreError::ProviderCapacity);
3444 }
3445 let removed_permissions = !permissions.is_empty();
3446 for (origin, generation, permission_json, updated_at_unix) in permissions {
3447 let permission_json = Zeroizing::new(permission_json);
3448 validate_origin(&origin)?;
3449 if generation == 0 {
3450 return Err(StoreError::InvalidGeneration);
3451 }
3452 let origin_token = origin_lookup_token(key, &self.database_id, &origin)?;
3453 let clear = encode_origin_payload(&origin, &permission_json)?;
3454 let encrypted = encrypt_record(
3455 key,
3456 &self.database_id,
3457 "provider_permission",
3458 &permission_record_id(&origin_token, generation, false, updated_at_unix),
3459 &clear,
3460 )?;
3461 transaction.execute(
3462 "INSERT INTO private_provider_permissions(
3463 origin_token, generation, encrypted_record, updated_at_unix, revoked
3464 ) VALUES(?1, ?2, ?3, ?4, 0)",
3465 params![
3466 origin_token.as_slice(),
3467 generation,
3468 encrypted,
3469 updated_at_unix
3470 ],
3471 )?;
3472 }
3473
3474 let removed_approvals: bool = transaction.query_row(
3478 "SELECT EXISTS(SELECT 1 FROM pending_approvals LIMIT 1)",
3479 [],
3480 |row| row.get(0),
3481 )?;
3482
3483 let replay_rows = {
3484 let mut statement = transaction.prepare(
3485 "SELECT origin, nonce, expires_at_unix
3486 FROM replay_protection ORDER BY origin, nonce",
3487 )?;
3488 let rows = statement.query_map([], |row| {
3489 Ok((
3490 row.get::<_, String>(0)?,
3491 row.get::<_, u64>(1)?,
3492 row.get::<_, u64>(2)?,
3493 ))
3494 })?;
3495 rows.collect::<Result<Vec<_>, _>>()?
3496 };
3497 validate_legacy_replay_capacity(&replay_rows)?;
3498 let removed_replay_rows = !replay_rows.is_empty();
3499 for (origin, nonce, expires_at_unix) in replay_rows {
3500 validate_origin(&origin)?;
3501 let origin_token = origin_lookup_token(key, &self.database_id, &origin)?;
3502 let record_id = replay_record_id(&origin_token, nonce, expires_at_unix);
3503 let encrypted_origin = encrypt_record(
3504 key,
3505 &self.database_id,
3506 "replay_origin",
3507 &record_id,
3508 origin.as_bytes(),
3509 )?;
3510 transaction.execute(
3511 "INSERT INTO private_replay_protection(
3512 origin_token, nonce, encrypted_origin, expires_at_unix
3513 ) VALUES(?1, ?2, ?3, ?4)",
3514 params![
3515 origin_token.as_slice(),
3516 nonce,
3517 encrypted_origin,
3518 expires_at_unix
3519 ],
3520 )?;
3521 }
3522
3523 transaction.execute("DELETE FROM provider_permissions", [])?;
3524 transaction.execute("DELETE FROM pending_approvals", [])?;
3525 transaction.execute("DELETE FROM replay_protection", [])?;
3526
3527 let removed_plaintext =
3528 removed_plaintext || removed_permissions || removed_approvals || removed_replay_rows;
3529 if removed_plaintext {
3530 set_meta(&transaction, CHECKPOINT_PENDING_KEY, b"1")?;
3531 }
3532 transaction.commit()?;
3533 Ok(())
3534 }
3535
3536 fn complete_plaintext_checkpoint(&mut self) -> Result<(), StoreError> {
3537 truncate_wal(&self.connection)?;
3541 if meta(&self.connection, CHECKPOINT_PENDING_KEY)?.is_some() {
3542 self.connection.execute(
3543 "DELETE FROM wallet_meta WHERE key=?1",
3544 params![CHECKPOINT_PENDING_KEY],
3545 )?;
3546 truncate_wal(&self.connection)?;
3547 }
3548 Ok(())
3549 }
3550
3551 #[cfg(test)]
3552 fn create_in_memory(passphrase: &str) -> Result<Self, StoreError> {
3553 Self::create_with_kdf(":memory:", passphrase, KdfConfig::testing())
3554 }
3555}
3556
3557fn complete_wallet_creation(
3558 created_file: &mut Option<CreatedWalletFile>,
3559 path: &Path,
3560) -> Result<(), StoreError> {
3561 if let Some(created_file) = created_file.as_mut() {
3562 let completed_location = validate_wallet_location(path, WalletPathRequirement::Existing)?;
3563 validate_created_wallet_location(created_file, &completed_location)?;
3564 created_file.disarm();
3565 }
3566 Ok(())
3567}
3568
3569#[derive(Clone, Debug, Eq, PartialEq)]
3570pub struct StoredWorkflow<T> {
3571 pub id: WorkflowId,
3572 pub kind: WorkflowKind,
3573 pub revision: u64,
3574 pub state: T,
3575 pub irreversible_broadcast_prepared: bool,
3576 pub updated_at_unix: u64,
3577}
3578
3579pub struct PendingApproval {
3580 pub id: ApprovalId,
3581 pub origin: String,
3582 pub request_json: Zeroizing<Vec<u8>>,
3583 pub expires_at_unix: u64,
3584}
3585
3586impl core::fmt::Debug for PendingApproval {
3587 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
3588 formatter
3589 .debug_struct("PendingApproval")
3590 .field("id", &self.id)
3591 .field("origin", &self.origin)
3592 .field("request_json", &"[REDACTED]")
3593 .field("expires_at_unix", &self.expires_at_unix)
3594 .finish()
3595 }
3596}
3597
3598fn load_entity_from_connection<T: for<'de> Deserialize<'de>>(
3599 connection: &Connection,
3600 key: &[u8; KEY_BYTES],
3601 database_id: &[u8; DATABASE_ID_BYTES],
3602 kind: EntityKind,
3603 id: &[u8],
3604) -> Result<Option<StoredEntity<T>>, StoreError> {
3605 validate_id(id)?;
3606 let row: Option<(u64, Vec<u8>, u64)> = connection
3607 .query_row(
3608 "SELECT revision, encrypted_value, updated_at_unix
3609 FROM encrypted_entities WHERE entity_kind=?1 AND record_id=?2",
3610 params![kind.label(), id],
3611 |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
3612 )
3613 .optional()?;
3614 row.map(|(revision, encrypted, updated_at_unix)| {
3615 let clear = decrypt_record(
3616 key,
3617 database_id,
3618 &entity_label(kind),
3619 &revisioned_aad_id(id, revision, updated_at_unix, None)?,
3620 &encrypted,
3621 )?;
3622 Ok(StoredEntity {
3623 kind,
3624 id: id.to_vec(),
3625 revision,
3626 value: serde_json::from_slice(&clear)?,
3627 updated_at_unix,
3628 })
3629 })
3630 .transpose()
3631}
3632
3633fn list_entities_by_id_prefix_from_connection<T: for<'de> Deserialize<'de>>(
3634 connection: &Connection,
3635 key: &[u8; KEY_BYTES],
3636 database_id: &[u8; DATABASE_ID_BYTES],
3637 kind: EntityKind,
3638 prefix: &[u8],
3639 limit: usize,
3640) -> Result<Vec<StoredEntity<T>>, StoreError> {
3641 validate_id(prefix)?;
3642 if limit == 0 || limit > MAX_ENTITY_LIST_RESULTS {
3643 return Err(StoreError::InvalidListLimit);
3644 }
3645 let query_limit = limit
3646 .checked_add(1)
3647 .and_then(|value| i64::try_from(value).ok())
3648 .ok_or(StoreError::InvalidListLimit)?;
3649 let prefix_length = i64::try_from(prefix.len()).map_err(|_| StoreError::InvalidRecordId)?;
3650 let mut statement = connection.prepare(
3651 "SELECT record_id, revision, encrypted_value, updated_at_unix
3652 FROM encrypted_entities
3653 WHERE entity_kind=?1 AND substr(record_id, 1, ?2)=?3
3654 ORDER BY record_id LIMIT ?4",
3655 )?;
3656 let rows = statement.query_map(
3657 params![kind.label(), prefix_length, prefix, query_limit],
3658 |row| {
3659 Ok((
3660 row.get::<_, Vec<u8>>(0)?,
3661 row.get::<_, u64>(1)?,
3662 row.get::<_, Vec<u8>>(2)?,
3663 row.get::<_, u64>(3)?,
3664 ))
3665 },
3666 )?;
3667 let mut encrypted_entities = Vec::new();
3668 for row in rows {
3669 encrypted_entities.push(row?);
3670 }
3671 if encrypted_entities.len() > limit {
3672 return Err(StoreError::ListCapacity);
3673 }
3674 let mut entities = Vec::with_capacity(encrypted_entities.len());
3675 for (id, revision, encrypted, updated_at_unix) in encrypted_entities {
3676 validate_id(&id)?;
3677 let clear = decrypt_record(
3678 key,
3679 database_id,
3680 &entity_label(kind),
3681 &revisioned_aad_id(&id, revision, updated_at_unix, None)?,
3682 &encrypted,
3683 )?;
3684 entities.push(StoredEntity {
3685 kind,
3686 id,
3687 revision,
3688 value: serde_json::from_slice(&clear)?,
3689 updated_at_unix,
3690 });
3691 }
3692 Ok(entities)
3693}
3694
3695fn list_untrusted_entity_metadata_by_id_prefix_from_connection(
3696 connection: &Connection,
3697 kind: EntityKind,
3698 prefix: &[u8],
3699 limit: usize,
3700) -> Result<Vec<StoredEntityMetadata>, StoreError> {
3701 validate_id(prefix)?;
3702 if limit == 0 || limit > MAX_ENTITY_LIST_RESULTS {
3703 return Err(StoreError::InvalidListLimit);
3704 }
3705 let query_limit = limit
3706 .checked_add(1)
3707 .and_then(|value| i64::try_from(value).ok())
3708 .ok_or(StoreError::InvalidListLimit)?;
3709 let prefix_length = i64::try_from(prefix.len()).map_err(|_| StoreError::InvalidRecordId)?;
3710 let mut statement = connection.prepare(
3711 "SELECT record_id, revision, updated_at_unix
3712 FROM encrypted_entities
3713 WHERE entity_kind=?1 AND substr(record_id, 1, ?2)=?3
3714 ORDER BY record_id LIMIT ?4",
3715 )?;
3716 let rows = statement.query_map(
3717 params![kind.label(), prefix_length, prefix, query_limit],
3718 |row| {
3719 Ok((
3720 row.get::<_, Vec<u8>>(0)?,
3721 row.get::<_, u64>(1)?,
3722 row.get::<_, u64>(2)?,
3723 ))
3724 },
3725 )?;
3726 let mut metadata = Vec::new();
3727 for row in rows {
3728 let (id, revision, updated_at_unix) = row?;
3729 if metadata.len() == limit {
3730 return Err(StoreError::ListCapacity);
3731 }
3732 validate_id(&id)?;
3733 metadata.push(StoredEntityMetadata {
3734 kind,
3735 id,
3736 revision,
3737 updated_at_unix,
3738 });
3739 }
3740 Ok(metadata)
3741}
3742
3743fn load_entity_prefix_set_lease_projection(
3744 connection: &Connection,
3745 kind: EntityKind,
3746 prefix: &[u8],
3747 limit: usize,
3748) -> Result<(Vec<StoredEntityMetadata>, Vec<[u8; 32]>), StoreError> {
3749 validate_id(prefix)?;
3750 if limit == 0 || limit > MAX_ENTITY_LIST_RESULTS {
3751 return Err(StoreError::InvalidListLimit);
3752 }
3753 let query_limit = limit
3754 .checked_add(1)
3755 .and_then(|value| i64::try_from(value).ok())
3756 .ok_or(StoreError::InvalidListLimit)?;
3757 let prefix_length = i64::try_from(prefix.len()).map_err(|_| StoreError::InvalidRecordId)?;
3758 let mut statement = connection.prepare(
3759 "SELECT length(record_id), record_id, revision, updated_at_unix,
3760 length(encrypted_value), encrypted_value
3761 FROM encrypted_entities
3762 WHERE entity_kind=?1 AND substr(record_id, 1, ?2)=?3
3763 ORDER BY record_id LIMIT ?4",
3764 )?;
3765 let mut rows = statement.query(params![kind.label(), prefix_length, prefix, query_limit])?;
3766 let mut metadata = Vec::new();
3767 let mut encrypted_value_fingerprints = Vec::new();
3768 while let Some(row) = rows.next()? {
3769 if metadata.len() == limit {
3770 return Err(StoreError::ListCapacity);
3771 }
3772 let id_length =
3773 usize::try_from(row.get::<_, i64>(0)?).map_err(|_| StoreError::InvalidRecordId)?;
3774 if id_length == 0 || id_length > MAX_RECORD_ID_BYTES {
3775 return Err(StoreError::InvalidRecordId);
3776 }
3777 let id = row.get::<_, Vec<u8>>(1)?;
3778 let revision = row.get::<_, u64>(2)?;
3779 let updated_at_unix = row.get::<_, u64>(3)?;
3780 let encrypted_value_length =
3781 usize::try_from(row.get::<_, i64>(4)?).map_err(|_| StoreError::Encryption)?;
3782 validate_encrypted_record_length(encrypted_value_length)?;
3783 let encrypted_value = row.get::<_, Vec<u8>>(5)?;
3784 if encrypted_value.len() != encrypted_value_length {
3785 return Err(StoreError::Encryption);
3786 }
3787 validate_id(&id)?;
3788 metadata.push(StoredEntityMetadata {
3789 kind,
3790 id,
3791 revision,
3792 updated_at_unix,
3793 });
3794 encrypted_value_fingerprints.push(Sha256::digest(encrypted_value).into());
3795 }
3796 Ok((metadata, encrypted_value_fingerprints))
3797}
3798
3799type PreparedEntityBatch = Vec<(Vec<u8>, u64, Zeroizing<Vec<u8>>, u64)>;
3800type AuthenticatedEntityWrites = Vec<(Vec<u8>, u64, Vec<u8>, u64)>;
3801
3802fn prepare_entity_batch<E: Serialize>(
3803 saves: &[EntityBatchSave<E>],
3804 deletes: &[EntityBatchDelete],
3805) -> Result<PreparedEntityBatch, StoreError> {
3806 if saves
3807 .len()
3808 .checked_add(deletes.len())
3809 .is_none_or(|count| count > MAX_ENTITY_BATCH_OPERATIONS)
3810 {
3811 return Err(StoreError::BatchCapacity);
3812 }
3813 let mut ids = BTreeSet::new();
3814 let mut prepared = Vec::with_capacity(saves.len());
3815 for save in saves {
3816 validate_id(&save.id)?;
3817 if !ids.insert(save.id.clone()) {
3818 return Err(StoreError::DuplicateBatchEntity);
3819 }
3820 let encoded = Zeroizing::new(serde_json::to_vec(&save.value)?);
3821 if encoded.is_empty() || encoded.len() > MAX_STATE_BYTES {
3822 return Err(StoreError::RecordTooLarge);
3823 }
3824 prepared.push((
3825 save.id.clone(),
3826 save.expected_revision,
3827 encoded,
3828 save.updated_at_unix,
3829 ));
3830 }
3831 for delete in deletes {
3832 validate_id(&delete.id)?;
3833 if delete.expected_revision == 0 || !ids.insert(delete.id.clone()) {
3834 return Err(StoreError::DuplicateBatchEntity);
3835 }
3836 }
3837 Ok(prepared)
3838}
3839
3840fn validate_entity_revision_assertions<E>(
3841 saves: &[EntityBatchSave<E>],
3842 deletes: &[EntityBatchDelete],
3843 assertions: &[EntityRevisionAssertion],
3844) -> Result<(), StoreError> {
3845 if saves
3846 .len()
3847 .checked_add(deletes.len())
3848 .and_then(|count| count.checked_add(assertions.len()))
3849 .is_none_or(|count| count > MAX_ENTITY_BATCH_OPERATIONS)
3850 {
3851 return Err(StoreError::BatchCapacity);
3852 }
3853 let mut ids = BTreeSet::new();
3854 for save in saves {
3855 validate_id(&save.id)?;
3856 if !ids.insert(save.id.clone()) {
3857 return Err(StoreError::DuplicateBatchEntity);
3858 }
3859 }
3860 for delete in deletes {
3861 validate_id(&delete.id)?;
3862 if !ids.insert(delete.id.clone()) {
3863 return Err(StoreError::DuplicateBatchEntity);
3864 }
3865 }
3866 for assertion in assertions {
3867 validate_id(&assertion.id)?;
3868 if assertion.expected_revision == 0 || !ids.insert(assertion.id.clone()) {
3869 return Err(if assertion.expected_revision == 0 {
3870 StoreError::InvalidRevision
3871 } else {
3872 StoreError::DuplicateBatchEntity
3873 });
3874 }
3875 }
3876 Ok(())
3877}
3878
3879fn validate_entity_prefix_set_lease<E>(
3880 database_id: &[u8; DATABASE_ID_BYTES],
3881 kind: EntityKind,
3882 saves: &[EntityBatchSave<E>],
3883 deletes: &[EntityBatchDelete],
3884 assertions: &[EntityRevisionAssertion],
3885 lease: &EntityPrefixSetLease,
3886) -> Result<(), StoreError> {
3887 validate_entity_prefix_set_lease_shape(database_id, lease)?;
3888 let invalid_scope = lease.kind != kind
3889 || saves
3890 .iter()
3891 .any(|operation| !operation.id.starts_with(&lease.prefix))
3892 || deletes
3893 .iter()
3894 .any(|operation| !operation.id.starts_with(&lease.prefix))
3895 || assertions
3896 .iter()
3897 .any(|operation| !operation.id.starts_with(&lease.prefix));
3898 if invalid_scope {
3899 return Err(StoreError::InvalidEntityPrefixLease);
3900 }
3901 Ok(())
3902}
3903
3904fn validate_entity_prefix_set_lease_shape(
3905 database_id: &[u8; DATABASE_ID_BYTES],
3906 lease: &EntityPrefixSetLease,
3907) -> Result<(), StoreError> {
3908 let invalid_shape = lease.database_id != *database_id
3909 || lease.limit == 0
3910 || lease.limit > MAX_ENTITY_LIST_RESULTS
3911 || lease.metadata.len() > lease.limit
3912 || lease.encrypted_value_fingerprints.len() != lease.metadata.len()
3913 || validate_id(&lease.prefix).is_err()
3914 || lease
3915 .metadata
3916 .iter()
3917 .any(|entry| entry.kind != lease.kind || !entry.id.starts_with(&lease.prefix))
3918 || lease
3919 .metadata
3920 .windows(2)
3921 .any(|entries| entries[0].id >= entries[1].id);
3922 if invalid_shape {
3923 return Err(StoreError::InvalidEntityPrefixLease);
3924 }
3925 Ok(())
3926}
3927
3928fn assert_entity_prefix_set_lease(
3929 transaction: &rusqlite::Transaction<'_>,
3930 lease: &EntityPrefixSetLease,
3931) -> Result<(), StoreError> {
3932 let current = load_entity_prefix_set_lease_projection(
3933 transaction,
3934 lease.kind,
3935 &lease.prefix,
3936 lease.limit,
3937 );
3938 match current {
3939 Ok((metadata, encrypted_value_fingerprints))
3940 if metadata.as_slice() == lease.metadata.as_slice()
3941 && encrypted_value_fingerprints.as_slice()
3942 == lease.encrypted_value_fingerprints.as_slice() =>
3943 {
3944 Ok(())
3945 }
3946 Ok(_) | Err(StoreError::ListCapacity) => Err(StoreError::StaleEntitySet),
3947 Err(error) => Err(error),
3948 }
3949}
3950
3951fn authenticated_pending_approval(
3952 connection: &Connection,
3953 key: &[u8; KEY_BYTES],
3954 database_id: &[u8; DATABASE_ID_BYTES],
3955 id: ApprovalId,
3956) -> Result<Option<PendingApproval>, StoreError> {
3957 let row: Option<(Vec<u8>, Vec<u8>, u64)> = connection
3958 .query_row(
3959 "SELECT origin_token, encrypted_record, expires_at_unix
3960 FROM private_pending_approvals WHERE id=?1",
3961 params![id.as_bytes().as_slice()],
3962 |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
3963 )
3964 .optional()?;
3965 let Some((origin_token, encrypted, expires_at_unix)) = row else {
3966 return Ok(None);
3967 };
3968 let origin_token: [u8; 32] = origin_token
3969 .try_into()
3970 .map_err(|_| StoreError::CorruptMetadata)?;
3971 let clear = decrypt_record(
3972 key,
3973 database_id,
3974 "pending_approval",
3975 &approval_record_id(&id, &origin_token, expires_at_unix),
3976 &encrypted,
3977 )?;
3978 let (origin, request_json) = decode_origin_payload(&clear)?;
3979 let expected_token = origin_lookup_token(key, database_id, &origin)?;
3980 if origin_token != expected_token {
3981 return Err(StoreError::Encryption);
3982 }
3983 Ok(Some(PendingApproval {
3984 id,
3985 origin,
3986 request_json,
3987 expires_at_unix,
3988 }))
3989}
3990
3991fn authenticated_workflow_revision(
3992 transaction: &rusqlite::Transaction<'_>,
3993 key: &[u8; KEY_BYTES],
3994 database_id: &[u8; DATABASE_ID_BYTES],
3995 id: WorkflowId,
3996 expected_kind: WorkflowKind,
3997) -> Result<u64, StoreError> {
3998 let current: Option<(String, u64, Vec<u8>, bool, u64, u32)> = transaction
3999 .query_row(
4000 "SELECT kind, revision, state_json, broadcast_prepared,
4001 updated_at_unix, encryption_version
4002 FROM workflows WHERE id=?1",
4003 params![id.as_bytes().as_slice()],
4004 |row| {
4005 Ok((
4006 row.get(0)?,
4007 row.get(1)?,
4008 row.get(2)?,
4009 row.get(3)?,
4010 row.get(4)?,
4011 row.get(5)?,
4012 ))
4013 },
4014 )
4015 .optional()?;
4016 let Some((kind, revision, encrypted, broadcast, updated_at, version)) = current else {
4017 return Ok(0);
4018 };
4019 let kind = parse_workflow_kind(&kind)?;
4020 if kind != expected_kind {
4021 return Err(StoreError::WorkflowKindMismatch);
4022 }
4023 if version != 1 {
4024 return Err(StoreError::LegacyEncryptionPending);
4025 }
4026 decrypt_record(
4027 key,
4028 database_id,
4029 &workflow_label(kind),
4030 &revisioned_aad_id(id.as_bytes(), revision, updated_at, Some(broadcast))?,
4031 &encrypted,
4032 )?;
4033 Ok(revision)
4034}
4035
4036fn authenticated_entity_revision(
4037 transaction: &rusqlite::Transaction<'_>,
4038 key: &[u8; KEY_BYTES],
4039 database_id: &[u8; DATABASE_ID_BYTES],
4040 kind: EntityKind,
4041 id: &[u8],
4042) -> Result<Option<u64>, StoreError> {
4043 let current: Option<(u64, Vec<u8>, u64)> = transaction
4044 .query_row(
4045 "SELECT revision, encrypted_value, updated_at_unix
4046 FROM encrypted_entities WHERE entity_kind=?1 AND record_id=?2",
4047 params![kind.label(), id],
4048 |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
4049 )
4050 .optional()?;
4051 current
4052 .map(|(revision, encrypted, updated_at)| {
4053 decrypt_record(
4054 key,
4055 database_id,
4056 &entity_label(kind),
4057 &revisioned_aad_id(id, revision, updated_at, None)?,
4058 &encrypted,
4059 )?;
4060 Ok(revision)
4061 })
4062 .transpose()
4063}
4064
4065fn consume_authenticated_entity_revision(
4070 transaction: &rusqlite::Transaction<'_>,
4071 key: &[u8; KEY_BYTES],
4072 database_id: &[u8; DATABASE_ID_BYTES],
4073 kind: EntityKind,
4074 assertion: &EntityRevisionAssertion,
4075 consumed_at_unix: u64,
4076) -> Result<(), StoreError> {
4077 let current: Option<(u64, Vec<u8>, u64)> = transaction
4078 .query_row(
4079 "SELECT revision, encrypted_value, updated_at_unix
4080 FROM encrypted_entities WHERE entity_kind=?1 AND record_id=?2",
4081 params![kind.label(), &assertion.id],
4082 |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
4083 )
4084 .optional()?;
4085 let Some((revision, encrypted, updated_at_unix)) = current else {
4086 return Err(StoreError::StaleRevision {
4087 expected: assertion.expected_revision,
4088 actual: 0,
4089 });
4090 };
4091 if revision != assertion.expected_revision {
4092 return Err(StoreError::StaleRevision {
4093 expected: assertion.expected_revision,
4094 actual: revision,
4095 });
4096 }
4097 let plaintext = Zeroizing::new(decrypt_record(
4098 key,
4099 database_id,
4100 &entity_label(kind),
4101 &revisioned_aad_id(&assertion.id, revision, updated_at_unix, None)?,
4102 &encrypted,
4103 )?);
4104 let next = revision
4105 .checked_add(1)
4106 .ok_or(StoreError::RevisionOverflow)?;
4107 let encrypted = encrypt_record(
4108 key,
4109 database_id,
4110 &entity_label(kind),
4111 &revisioned_aad_id(&assertion.id, next, consumed_at_unix, None)?,
4112 &plaintext,
4113 )?;
4114 transaction.execute(
4115 "UPDATE encrypted_entities
4116 SET revision=?1, encrypted_value=?2, updated_at_unix=?3
4117 WHERE entity_kind=?4 AND record_id=?5",
4118 params![
4119 next,
4120 encrypted,
4121 consumed_at_unix,
4122 kind.label(),
4123 &assertion.id,
4124 ],
4125 )?;
4126 Ok(())
4127}
4128
4129fn apply_entity_batch_in_transaction(
4130 transaction: &rusqlite::Transaction<'_>,
4131 key: &[u8; KEY_BYTES],
4132 database_id: &[u8; DATABASE_ID_BYTES],
4133 kind: EntityKind,
4134 saves: &PreparedEntityBatch,
4135 deletes: &[EntityBatchDelete],
4136) -> Result<(), StoreError> {
4137 let encrypted_saves =
4138 authenticate_entity_batch(transaction, key, database_id, kind, saves, deletes)?;
4139 write_entity_batch_in_transaction(transaction, kind, &encrypted_saves, deletes)
4140}
4141
4142fn authenticate_entity_batch(
4143 transaction: &rusqlite::Transaction<'_>,
4144 key: &[u8; KEY_BYTES],
4145 database_id: &[u8; DATABASE_ID_BYTES],
4146 kind: EntityKind,
4147 saves: &PreparedEntityBatch,
4148 deletes: &[EntityBatchDelete],
4149) -> Result<AuthenticatedEntityWrites, StoreError> {
4150 if kind.deletion_protected() && !deletes.is_empty() {
4151 return Err(StoreError::ProtectedEntity);
4152 }
4153 let mut encrypted_saves = Vec::with_capacity(saves.len());
4154 for (id, expected_revision, encoded, updated_at) in saves {
4155 let actual =
4156 authenticated_entity_revision(transaction, key, database_id, kind, id)?.unwrap_or(0);
4157 if actual != *expected_revision {
4158 return Err(StoreError::StaleRevision {
4159 expected: *expected_revision,
4160 actual,
4161 });
4162 }
4163 let next = actual.checked_add(1).ok_or(StoreError::RevisionOverflow)?;
4164 let encrypted = encrypt_record(
4165 key,
4166 database_id,
4167 &entity_label(kind),
4168 &revisioned_aad_id(id, next, *updated_at, None)?,
4169 encoded,
4170 )?;
4171 encrypted_saves.push((id.clone(), next, encrypted, *updated_at));
4172 }
4173 for delete in deletes {
4174 let actual =
4175 authenticated_entity_revision(transaction, key, database_id, kind, &delete.id)?
4176 .unwrap_or(0);
4177 if actual != delete.expected_revision {
4178 return Err(StoreError::StaleRevision {
4179 expected: delete.expected_revision,
4180 actual,
4181 });
4182 }
4183 }
4184 Ok(encrypted_saves)
4185}
4186
4187fn authenticate_entity_revision_assertions(
4188 transaction: &rusqlite::Transaction<'_>,
4189 key: &[u8; KEY_BYTES],
4190 database_id: &[u8; DATABASE_ID_BYTES],
4191 kind: EntityKind,
4192 assertions: &[EntityRevisionAssertion],
4193) -> Result<(), StoreError> {
4194 for assertion in assertions {
4195 let actual =
4196 authenticated_entity_revision(transaction, key, database_id, kind, &assertion.id)?
4197 .unwrap_or(0);
4198 if actual != assertion.expected_revision {
4199 return Err(StoreError::StaleRevision {
4200 expected: assertion.expected_revision,
4201 actual,
4202 });
4203 }
4204 }
4205 Ok(())
4206}
4207
4208fn write_entity_batch_in_transaction(
4209 transaction: &rusqlite::Transaction<'_>,
4210 kind: EntityKind,
4211 encrypted_saves: &AuthenticatedEntityWrites,
4212 deletes: &[EntityBatchDelete],
4213) -> Result<(), StoreError> {
4214 for (id, revision, encrypted, updated_at) in encrypted_saves {
4215 transaction.execute(
4216 "INSERT INTO encrypted_entities(
4217 entity_kind, record_id, revision, encrypted_value, updated_at_unix
4218 ) VALUES(?1, ?2, ?3, ?4, ?5)
4219 ON CONFLICT(entity_kind, record_id) DO UPDATE SET
4220 revision=excluded.revision,
4221 encrypted_value=excluded.encrypted_value,
4222 updated_at_unix=excluded.updated_at_unix",
4223 params![kind.label(), id, revision, encrypted, updated_at],
4224 )?;
4225 }
4226 for delete in deletes {
4227 transaction.execute(
4228 "DELETE FROM encrypted_entities WHERE entity_kind=?1 AND record_id=?2",
4229 params![kind.label(), &delete.id],
4230 )?;
4231 }
4232 Ok(())
4233}
4234
4235fn is_in_memory(path: &Path) -> bool {
4236 path == Path::new(":memory:")
4237}
4238
4239fn open_wallet_connection(path: &Path) -> Result<Connection, StoreError> {
4240 if is_in_memory(path) {
4241 return Connection::open_in_memory().map_err(StoreError::from);
4242 }
4243 let flags = OpenFlags::SQLITE_OPEN_READ_WRITE
4244 | OpenFlags::SQLITE_OPEN_NO_MUTEX
4245 | OpenFlags::SQLITE_OPEN_NOFOLLOW;
4246 Connection::open_with_flags(path, flags).map_err(StoreError::from)
4247}
4248
4249fn open_wallet_connection_read_only(path: &Path) -> Result<Connection, StoreError> {
4250 let connection = if is_in_memory(path) {
4251 Connection::open_in_memory()?
4252 } else {
4253 let flags = OpenFlags::SQLITE_OPEN_READ_ONLY
4254 | OpenFlags::SQLITE_OPEN_NO_MUTEX
4255 | OpenFlags::SQLITE_OPEN_NOFOLLOW;
4256 Connection::open_with_flags(path, flags)?
4257 };
4258 connection.execute_batch("PRAGMA trusted_schema=OFF; PRAGMA query_only=ON;")?;
4259 Ok(connection)
4260}
4261
4262#[derive(Clone, Copy, Debug, Eq, PartialEq)]
4263enum WalletPathRequirement {
4264 Missing,
4265 Existing,
4266}
4267
4268#[cfg(unix)]
4269#[derive(Clone, Copy, Debug, Eq, PartialEq)]
4270enum UnixBoundaryKind {
4271 Directory,
4272 RegularFile,
4273 Other,
4274}
4275
4276#[cfg(unix)]
4277#[derive(Clone, Copy, Debug, Eq, PartialEq)]
4278struct UnixBoundaryMetadata {
4279 kind: UnixBoundaryKind,
4280 uid: u32,
4281 mode: u32,
4282 dev: u64,
4283 ino: u64,
4284 nlink: u64,
4285}
4286
4287#[cfg(unix)]
4288#[derive(Clone, Copy, Debug, Eq, PartialEq)]
4289enum UnixAncestorPolicy {
4290 Strict,
4291 AndroidSystemUid1000,
4292 IosPlatformPrefix,
4293}
4294
4295#[cfg(unix)]
4296const fn active_unix_ancestor_policy() -> UnixAncestorPolicy {
4297 #[cfg(target_os = "android")]
4298 {
4299 UnixAncestorPolicy::AndroidSystemUid1000
4300 }
4301 #[cfg(target_os = "ios")]
4302 {
4303 UnixAncestorPolicy::IosPlatformPrefix
4304 }
4305 #[cfg(not(any(target_os = "android", target_os = "ios")))]
4306 {
4307 UnixAncestorPolicy::Strict
4308 }
4309}
4310
4311#[cfg(unix)]
4312fn unix_boundary_metadata(metadata: &std::fs::Metadata) -> UnixBoundaryMetadata {
4313 let file_type = metadata.file_type();
4314 let kind = if file_type.is_dir() {
4315 UnixBoundaryKind::Directory
4316 } else if file_type.is_file() {
4317 UnixBoundaryKind::RegularFile
4318 } else {
4319 UnixBoundaryKind::Other
4320 };
4321 UnixBoundaryMetadata {
4322 kind,
4323 uid: metadata.uid(),
4324 mode: metadata.mode() & 0o7777,
4325 dev: metadata.dev(),
4326 ino: metadata.ino(),
4327 nlink: metadata.nlink(),
4328 }
4329}
4330
4331#[cfg(unix)]
4332fn validate_unix_ancestor_chain(
4333 ancestors: &[UnixBoundaryMetadata],
4334 process_uid: u32,
4335 policy: UnixAncestorPolicy,
4336) -> Result<(), StoreError> {
4337 if ancestors.is_empty() {
4338 return Err(StoreError::UnsafeFilesystemBoundary);
4339 }
4340 for ancestor in ancestors {
4341 if ancestor.kind != UnixBoundaryKind::Directory {
4342 return Err(StoreError::UnsafeFilesystemBoundary);
4343 }
4344 }
4345
4346 let trusted_suffix = if policy == UnixAncestorPolicy::IosPlatformPrefix {
4352 ancestors
4353 .iter()
4354 .rposition(|ancestor| ancestor.uid != process_uid)
4355 .map_or(0, |index| index + 1)
4356 } else {
4357 ancestors
4358 .iter()
4359 .position(|ancestor| ancestor.uid == process_uid)
4360 .ok_or(StoreError::UnsafeFilesystemBoundary)?
4361 };
4362 if trusted_suffix == ancestors.len() {
4363 return Err(StoreError::UnsafeFilesystemBoundary);
4364 }
4365 for (index, ancestor) in ancestors[..trusted_suffix].iter().enumerate() {
4366 if ancestor.mode & 0o022 != 0 {
4367 let sticky = ancestor.mode & 0o1000 != 0;
4368 let trusted_child = ancestors.get(index + 1).is_some_and(|child| {
4369 child.uid == 0
4370 || child.uid == process_uid
4371 || (policy == UnixAncestorPolicy::AndroidSystemUid1000
4376 && ancestor.uid == 0
4377 && child.uid == 1_000)
4378 });
4379 let android_platform_group_write = policy == UnixAncestorPolicy::AndroidSystemUid1000
4380 && ancestor.uid == 1_000
4381 && ancestor.mode & 0o020 != 0
4382 && ancestor.mode & 0o002 == 0;
4383 if (!sticky || !trusted_child) && !android_platform_group_write {
4384 return Err(StoreError::UnsafeFilesystemBoundary);
4385 }
4386 }
4387 }
4388 let private_suffix = &ancestors[trusted_suffix..];
4389 let mut owner_only_ancestor = false;
4390 for (offset, ancestor) in private_suffix.iter().enumerate() {
4391 if ancestor.uid != process_uid {
4392 return Err(StoreError::UnsafeFilesystemBoundary);
4393 }
4394 if ancestor.mode & 0o022 != 0 {
4395 let protected_ios_intermediate = policy == UnixAncestorPolicy::IosPlatformPrefix
4401 && owner_only_ancestor
4402 && offset + 1 < private_suffix.len()
4403 && ancestor.mode & 0o002 == 0;
4404 let sticky = ancestor.mode & 0o1000 != 0;
4405 let trusted_child = ancestors
4406 .get(trusted_suffix + offset + 1)
4407 .is_some_and(|child| child.uid == process_uid);
4408 if !protected_ios_intermediate && (!sticky || !trusted_child) {
4409 return Err(StoreError::UnsafeFilesystemBoundary);
4410 }
4411 }
4412 owner_only_ancestor |= ancestor.mode & 0o077 == 0;
4413 }
4414 Ok(())
4415}
4416
4417#[cfg(unix)]
4418fn validate_unix_wallet_directory(
4419 directory: UnixBoundaryMetadata,
4420 process_uid: u32,
4421) -> Result<(), StoreError> {
4422 if directory.kind != UnixBoundaryKind::Directory
4423 || directory.uid != process_uid
4424 || directory.mode != 0o700
4425 {
4426 return Err(StoreError::UnsafeFilesystemBoundary);
4427 }
4428 Ok(())
4429}
4430
4431#[cfg(unix)]
4432fn validate_unix_wallet_file(
4433 file: UnixBoundaryMetadata,
4434 process_uid: u32,
4435) -> Result<(), StoreError> {
4436 if file.kind != UnixBoundaryKind::RegularFile
4437 || file.uid != process_uid
4438 || file.mode != 0o600
4439 || file.nlink != 1
4440 {
4441 return Err(StoreError::UnsafeFilesystemBoundary);
4442 }
4443 Ok(())
4444}
4445
4446#[cfg(unix)]
4447fn validate_unix_file_identity(
4448 expected: UnixBoundaryMetadata,
4449 actual: UnixBoundaryMetadata,
4450) -> Result<(), StoreError> {
4451 if expected.kind != UnixBoundaryKind::RegularFile
4452 || actual.kind != UnixBoundaryKind::RegularFile
4453 || expected.dev != actual.dev
4454 || expected.ino != actual.ino
4455 || expected.nlink != 1
4456 || actual.nlink != 1
4457 {
4458 return Err(StoreError::UnsafeFilesystemBoundary);
4459 }
4460 Ok(())
4461}
4462
4463#[derive(Debug)]
4464struct ValidatedWalletLocation {
4465 path: PathBuf,
4466 #[cfg(unix)]
4467 file: Option<UnixBoundaryMetadata>,
4468}
4469
4470#[cfg(unix)]
4471struct CreatedWalletFile {
4472 file: std::fs::File,
4473 path: PathBuf,
4474 identity: Option<UnixBoundaryMetadata>,
4475 process_uid: u32,
4476 armed: bool,
4477}
4478
4479#[cfg(not(unix))]
4480struct CreatedWalletFile;
4481
4482#[cfg(unix)]
4483impl CreatedWalletFile {
4484 fn disarm(&mut self) {
4485 self.armed = false;
4486 }
4487}
4488
4489#[cfg(not(unix))]
4490impl CreatedWalletFile {
4491 fn disarm(&mut self) {}
4492}
4493
4494#[cfg(unix)]
4495impl Drop for CreatedWalletFile {
4496 fn drop(&mut self) {
4497 if !self.armed {
4498 return;
4499 }
4500 let expected = self.identity.or_else(|| {
4501 self.file
4502 .metadata()
4503 .ok()
4504 .map(|metadata| unix_boundary_metadata(&metadata))
4505 });
4506 let Some(expected) = expected else {
4507 return;
4508 };
4509 if !unix_cleanup_file_is_owned(expected, self.process_uid) {
4510 return;
4511 }
4512 let Ok(actual) = std::fs::symlink_metadata(&self.path) else {
4513 return;
4514 };
4515 let actual = unix_boundary_metadata(&actual);
4516 if !unix_cleanup_file_is_owned(actual, self.process_uid)
4517 || validate_unix_file_identity(expected, actual).is_err()
4518 {
4519 return;
4520 }
4521
4522 for sidecar in sqlite_sidecar_paths(&self.path) {
4526 let Ok(metadata) = std::fs::symlink_metadata(&sidecar) else {
4527 continue;
4528 };
4529 if unix_cleanup_file_is_owned(unix_boundary_metadata(&metadata), self.process_uid) {
4530 let _ = std::fs::remove_file(sidecar);
4531 }
4532 }
4533 let _ = std::fs::remove_file(&self.path);
4534 }
4535}
4536
4537#[cfg(unix)]
4538fn unix_cleanup_file_is_owned(file: UnixBoundaryMetadata, process_uid: u32) -> bool {
4539 file.kind == UnixBoundaryKind::RegularFile && file.uid == process_uid && file.nlink == 1
4540}
4541
4542#[cfg(unix)]
4543fn sqlite_sidecar_paths(path: &Path) -> [PathBuf; 3] {
4544 ["-wal", "-shm", "-journal"].map(|suffix| {
4545 let mut sidecar = path.as_os_str().to_os_string();
4546 sidecar.push(suffix);
4547 PathBuf::from(sidecar)
4548 })
4549}
4550
4551#[cfg(unix)]
4552fn preflight_sqlite_sidecars(path: &Path) -> Result<(), StoreError> {
4553 for sidecar in sqlite_sidecar_paths(path) {
4554 match std::fs::symlink_metadata(sidecar) {
4555 Ok(_) => return Err(StoreError::DatabaseExists),
4556 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
4557 Err(error) => return Err(StoreError::Io(error)),
4558 }
4559 }
4560 Ok(())
4561}
4562
4563#[cfg(unix)]
4564fn validate_wallet_location(
4565 path: &Path,
4566 requirement: WalletPathRequirement,
4567) -> Result<ValidatedWalletLocation, StoreError> {
4568 if is_in_memory(path) {
4569 return Ok(ValidatedWalletLocation {
4570 path: path.to_path_buf(),
4571 file: None,
4572 });
4573 }
4574 let file_name = path
4575 .file_name()
4576 .ok_or(StoreError::UnsafeFilesystemBoundary)?;
4577 let parent = path
4578 .parent()
4579 .filter(|parent| !parent.as_os_str().is_empty())
4580 .unwrap_or_else(|| Path::new("."));
4581 let supplied_parent_metadata = std::fs::symlink_metadata(parent)?;
4582 if supplied_parent_metadata.file_type().is_symlink() {
4583 return Err(StoreError::UnsafeFilesystemBoundary);
4584 }
4585 match std::fs::symlink_metadata(path) {
4586 Ok(metadata) if metadata.file_type().is_symlink() => {
4587 return Err(StoreError::UnsafeFilesystemBoundary);
4588 }
4589 Ok(_) => {}
4590 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
4591 Err(error) => return Err(StoreError::Io(error)),
4592 }
4593
4594 let canonical_parent = std::fs::canonicalize(parent)?;
4599 let canonical_path = canonical_parent.join(file_name);
4600 let process_uid = rustix::process::geteuid().as_raw();
4601
4602 let mut ancestor_paths = canonical_parent.ancestors().collect::<Vec<_>>();
4603 ancestor_paths.reverse();
4604 let ancestor_metadata = ancestor_paths
4605 .into_iter()
4606 .map(std::fs::symlink_metadata)
4607 .collect::<Result<Vec<_>, _>>()?
4608 .iter()
4609 .map(unix_boundary_metadata)
4610 .collect::<Vec<_>>();
4611 validate_unix_ancestor_chain(
4612 &ancestor_metadata,
4613 process_uid,
4614 active_unix_ancestor_policy(),
4615 )?;
4616 validate_unix_wallet_directory(
4617 *ancestor_metadata
4618 .last()
4619 .ok_or(StoreError::UnsafeFilesystemBoundary)?,
4620 process_uid,
4621 )?;
4622
4623 let file_metadata = match std::fs::symlink_metadata(&canonical_path) {
4624 Ok(metadata) => Some(unix_boundary_metadata(&metadata)),
4625 Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
4626 Err(error) => return Err(StoreError::Io(error)),
4627 };
4628 match (requirement, file_metadata) {
4629 (WalletPathRequirement::Missing, None) => Ok(ValidatedWalletLocation {
4630 path: canonical_path,
4631 file: None,
4632 }),
4633 (WalletPathRequirement::Missing, Some(file)) => {
4634 validate_unix_wallet_file(file, process_uid)?;
4635 Err(StoreError::DatabaseExists)
4636 }
4637 (WalletPathRequirement::Existing, Some(file)) => {
4638 validate_unix_wallet_file(file, process_uid)?;
4639 Ok(ValidatedWalletLocation {
4640 path: canonical_path,
4641 file: Some(file),
4642 })
4643 }
4644 (WalletPathRequirement::Existing, None) => Err(StoreError::Io(std::io::Error::new(
4645 std::io::ErrorKind::NotFound,
4646 "wallet database does not exist",
4647 ))),
4648 }
4649}
4650
4651#[cfg(not(unix))]
4652fn validate_wallet_location(
4653 path: &Path,
4654 _: WalletPathRequirement,
4655) -> Result<ValidatedWalletLocation, StoreError> {
4656 if is_in_memory(path) {
4657 Ok(ValidatedWalletLocation {
4658 path: path.to_path_buf(),
4659 })
4660 } else {
4661 Err(StoreError::UnsupportedFilesystemBoundary)
4662 }
4663}
4664
4665#[cfg(unix)]
4666fn create_new_wallet_file(path: &Path) -> Result<CreatedWalletFile, StoreError> {
4667 preflight_sqlite_sidecars(path)?;
4668 let file = std::fs::OpenOptions::new()
4669 .read(true)
4670 .write(true)
4671 .create_new(true)
4672 .mode(0o600)
4673 .open(path)
4674 .map_err(|error| {
4675 if error.kind() == std::io::ErrorKind::AlreadyExists {
4676 StoreError::DatabaseExists
4677 } else {
4678 StoreError::Io(error)
4679 }
4680 })?;
4681 let process_uid = rustix::process::geteuid().as_raw();
4682 let mut created = CreatedWalletFile {
4683 file,
4684 path: path.to_path_buf(),
4685 identity: None,
4686 process_uid,
4687 armed: true,
4688 };
4689 created
4690 .file
4691 .set_permissions(std::fs::Permissions::from_mode(0o600))?;
4692 let identity = unix_boundary_metadata(&created.file.metadata()?);
4693 created.identity = Some(identity);
4694 validate_unix_wallet_file(identity, process_uid)?;
4695 let path_identity = unix_boundary_metadata(&std::fs::symlink_metadata(path)?);
4696 validate_unix_wallet_file(path_identity, process_uid)?;
4697 validate_unix_file_identity(identity, path_identity)?;
4698 Ok(created)
4699}
4700
4701#[cfg(not(unix))]
4702fn create_new_wallet_file(_: &Path) -> Result<CreatedWalletFile, StoreError> {
4703 Err(StoreError::UnsupportedFilesystemBoundary)
4704}
4705
4706fn validate_wallet_location_identity(
4707 expected: &ValidatedWalletLocation,
4708 actual: &ValidatedWalletLocation,
4709) -> Result<(), StoreError> {
4710 if expected.path != actual.path {
4711 return Err(StoreError::UnsafeFilesystemBoundary);
4712 }
4713 #[cfg(unix)]
4714 match (expected.file, actual.file) {
4715 (Some(expected), Some(actual)) => validate_unix_file_identity(expected, actual),
4716 (None, None) if is_in_memory(&expected.path) => Ok(()),
4717 _ => Err(StoreError::UnsafeFilesystemBoundary),
4718 }
4719 #[cfg(not(unix))]
4720 Ok(())
4721}
4722
4723#[cfg(unix)]
4724fn validate_created_wallet_location(
4725 created: &CreatedWalletFile,
4726 actual: &ValidatedWalletLocation,
4727) -> Result<(), StoreError> {
4728 if created.path != actual.path {
4729 return Err(StoreError::UnsafeFilesystemBoundary);
4730 }
4731 let identity = created
4732 .identity
4733 .ok_or(StoreError::UnsafeFilesystemBoundary)?;
4734 let actual = actual.file.ok_or(StoreError::UnsafeFilesystemBoundary)?;
4735 validate_unix_file_identity(identity, actual)
4736}
4737
4738#[cfg(not(unix))]
4739fn validate_created_wallet_location(
4740 _: &CreatedWalletFile,
4741 _: &ValidatedWalletLocation,
4742) -> Result<(), StoreError> {
4743 Err(StoreError::UnsupportedFilesystemBoundary)
4744}
4745
4746#[derive(Debug, Eq, PartialEq)]
4747struct WalletMetadata {
4748 database_id: [u8; DATABASE_ID_BYTES],
4749 salt: [u8; SALT_BYTES],
4750 kdf: KdfConfig,
4751 key_check: Vec<u8>,
4752}
4753
4754fn recognize_wallet_database(connection: &Connection) -> Result<WalletMetadata, StoreError> {
4755 let schema_version: u32 = connection.query_row("PRAGMA user_version", [], |row| row.get(0))?;
4756 if schema_version == 0 {
4757 return Err(StoreError::NotInitialized);
4758 }
4759 let schema_anchors: usize = connection.query_row(
4760 "SELECT COUNT(*) FROM sqlite_schema
4761 WHERE type='table' AND name IN ('wallet_meta', 'secrets', 'workflows')",
4762 [],
4763 |row| row.get(0),
4764 )?;
4765 if schema_anchors != 3 {
4766 return Err(StoreError::NotInitialized);
4767 }
4768 let metadata = load_wallet_metadata(connection)?;
4769 if schema_version > SCHEMA_VERSION {
4770 return Err(StoreError::NewerSchema(schema_version));
4771 }
4772 Ok(metadata)
4773}
4774
4775fn load_wallet_metadata(connection: &Connection) -> Result<WalletMetadata, StoreError> {
4776 let database_id = exact_array::<DATABASE_ID_BYTES>(required_meta(connection, "database_id")?)?;
4777 let salt = exact_array::<SALT_BYTES>(required_meta(connection, "kdf_salt")?)?;
4778 let kdf: KdfConfig = serde_json::from_slice(&required_meta(connection, "kdf_config")?)?;
4779 kdf.validate()?;
4780 let key_check = required_meta(connection, "key_check")?;
4781 if key_check.len() != NONCE_BYTES + SENTINEL.len() + 16 {
4782 return Err(StoreError::CorruptMetadata);
4783 }
4784 Ok(WalletMetadata {
4785 database_id,
4786 salt,
4787 kdf,
4788 key_check,
4789 })
4790}
4791
4792fn configure(connection: &Connection) -> Result<(), StoreError> {
4793 connection.execute_batch(
4794 "PRAGMA foreign_keys=ON;
4795 PRAGMA trusted_schema=OFF;
4796 PRAGMA secure_delete=ON;
4797 PRAGMA synchronous=FULL;
4798 PRAGMA journal_mode=WAL;",
4799 )?;
4800 Ok(())
4801}
4802
4803fn migrate(connection: &Connection) -> Result<(), StoreError> {
4804 let current: u32 = connection.query_row("PRAGMA user_version", [], |row| row.get(0))?;
4805 if current > SCHEMA_VERSION {
4806 return Err(StoreError::NewerSchema(current));
4807 }
4808 if current == 0 {
4809 connection.execute_batch(SCHEMA_V1)?;
4810 }
4811 if current < 2 {
4812 connection.execute_batch(SCHEMA_V2)?;
4813 }
4814 if current < 3 {
4815 connection.execute_batch(SCHEMA_V3)?;
4816 }
4817 Ok(())
4818}
4819
4820const SCHEMA_V1: &str = r#"
4821BEGIN IMMEDIATE;
4822CREATE TABLE wallet_meta(key TEXT PRIMARY KEY, value BLOB NOT NULL) STRICT;
4823CREATE TABLE secrets(
4824 id BLOB PRIMARY KEY, kind TEXT NOT NULL, encrypted_value BLOB NOT NULL,
4825 updated_at_unix INTEGER NOT NULL
4826) STRICT;
4827CREATE TABLE wallet_accounts(id BLOB PRIMARY KEY, module TEXT NOT NULL, state_json BLOB NOT NULL) STRICT;
4828CREATE TABLE derived_addresses(account_id BLOB NOT NULL, derivation_index INTEGER NOT NULL,
4829 address TEXT NOT NULL, used INTEGER NOT NULL, PRIMARY KEY(account_id, derivation_index)) STRICT;
4830CREATE TABLE hns_utxos(outpoint BLOB PRIMARY KEY, account_id BLOB NOT NULL, value INTEGER NOT NULL,
4831 script BLOB NOT NULL, height INTEGER, spent_by BLOB) STRICT;
4832CREATE TABLE hns_transactions(txid BLOB PRIMARY KEY, raw BLOB, status_json BLOB NOT NULL,
4833 first_seen_unix INTEGER NOT NULL) STRICT;
4834CREATE TABLE known_names(name_hash BLOB PRIMARY KEY, name TEXT NOT NULL, state_json BLOB NOT NULL,
4835 checked_height INTEGER NOT NULL) STRICT;
4836CREATE TABLE name_owner_outpoints(name_hash BLOB PRIMARY KEY, outpoint BLOB NOT NULL,
4837 proof_root BLOB NOT NULL, checked_height INTEGER NOT NULL) STRICT;
4838CREATE TABLE name_transfer_state(name_hash BLOB PRIMARY KEY, workflow_id BLOB NOT NULL,
4839 state_json BLOB NOT NULL) STRICT;
4840CREATE TABLE shakedex_state(id BLOB PRIMARY KEY, state_json BLOB NOT NULL,
4841 updated_at_unix INTEGER NOT NULL) STRICT;
4842CREATE TABLE shakescape_board_cache(object_hash BLOB PRIMARY KEY, protocol INTEGER NOT NULL,
4843 expires_at_unix INTEGER NOT NULL, payload BLOB NOT NULL) STRICT;
4844CREATE TABLE bitcoin_headers(height INTEGER PRIMARY KEY, block_hash BLOB NOT NULL,
4845 header BLOB NOT NULL, chainwork BLOB NOT NULL) STRICT;
4846CREATE TABLE bitcoin_filter_headers(height INTEGER PRIMARY KEY, block_hash BLOB NOT NULL,
4847 filter_header BLOB NOT NULL) STRICT;
4848CREATE TABLE bitcoin_peers(peer_id TEXT PRIMARY KEY, state_json BLOB NOT NULL,
4849 updated_at_unix INTEGER NOT NULL) STRICT;
4850CREATE TABLE bitcoin_scan_state(account_id BLOB PRIMARY KEY, birthday_height INTEGER,
4851 scanned_height INTEGER NOT NULL, checkpoint_json BLOB NOT NULL) STRICT;
4852CREATE TABLE bitcoin_utxos(outpoint BLOB PRIMARY KEY, account_id BLOB NOT NULL,
4853 value INTEGER NOT NULL, script BLOB NOT NULL, height INTEGER, spent_by BLOB) STRICT;
4854CREATE TABLE bitcoin_transactions(txid BLOB PRIMARY KEY, raw BLOB, status_json BLOB NOT NULL,
4855 first_seen_unix INTEGER NOT NULL) STRICT;
4856CREATE TABLE ethereum_accounts(id BLOB PRIMARY KEY, address BLOB NOT NULL,
4857 state_json BLOB NOT NULL) STRICT;
4858CREATE TABLE ethereum_transactions(txid BLOB PRIMARY KEY, raw BLOB, status_json BLOB NOT NULL,
4859 first_seen_unix INTEGER NOT NULL) STRICT;
4860CREATE TABLE swap_sessions(id BLOB PRIMARY KEY, state_json BLOB NOT NULL,
4861 updated_at_unix INTEGER NOT NULL) STRICT;
4862CREATE TABLE htlc_secrets(session_id BLOB PRIMARY KEY, encrypted_secret BLOB NOT NULL,
4863 updated_at_unix INTEGER NOT NULL) STRICT;
4864CREATE TABLE refund_transactions(session_id BLOB NOT NULL, module TEXT NOT NULL,
4865 txid BLOB, state_json BLOB NOT NULL, PRIMARY KEY(session_id, module)) STRICT;
4866CREATE TABLE provider_permissions(origin TEXT PRIMARY KEY, generation INTEGER NOT NULL,
4867 permission_json BLOB NOT NULL, updated_at_unix INTEGER NOT NULL) STRICT;
4868CREATE TABLE pending_approvals(id BLOB PRIMARY KEY, origin TEXT NOT NULL,
4869 request_json BLOB NOT NULL, expires_at_unix INTEGER NOT NULL) STRICT;
4870CREATE TABLE replay_protection(origin TEXT NOT NULL, nonce INTEGER NOT NULL,
4871 expires_at_unix INTEGER NOT NULL, PRIMARY KEY(origin, nonce)) STRICT;
4872CREATE INDEX replay_expiry ON replay_protection(expires_at_unix);
4873CREATE TABLE workflows(id BLOB PRIMARY KEY, kind TEXT NOT NULL, revision INTEGER NOT NULL,
4874 state_json BLOB NOT NULL, broadcast_prepared INTEGER NOT NULL,
4875 updated_at_unix INTEGER NOT NULL) STRICT;
4876PRAGMA user_version=1;
4877COMMIT;
4878"#;
4879
4880const SCHEMA_V2: &str = r#"
4881BEGIN IMMEDIATE;
4882ALTER TABLE workflows ADD COLUMN encryption_version INTEGER NOT NULL DEFAULT 0;
4883CREATE TABLE encrypted_entities(
4884 entity_kind TEXT NOT NULL,
4885 record_id BLOB NOT NULL,
4886 revision INTEGER NOT NULL,
4887 encrypted_value BLOB NOT NULL,
4888 updated_at_unix INTEGER NOT NULL,
4889 PRIMARY KEY(entity_kind, record_id)
4890) STRICT;
4891CREATE INDEX encrypted_entities_updated
4892 ON encrypted_entities(entity_kind, updated_at_unix, record_id);
4893CREATE TABLE private_provider_permissions(
4894 origin_token BLOB PRIMARY KEY,
4895 generation INTEGER NOT NULL,
4896 encrypted_record BLOB NOT NULL,
4897 updated_at_unix INTEGER NOT NULL
4898) STRICT;
4899CREATE TABLE private_pending_approvals(
4900 id BLOB PRIMARY KEY,
4901 origin_token BLOB NOT NULL,
4902 encrypted_record BLOB NOT NULL,
4903 expires_at_unix INTEGER NOT NULL
4904) STRICT;
4905CREATE INDEX private_pending_approval_expiry
4906 ON private_pending_approvals(expires_at_unix);
4907CREATE TABLE private_replay_protection(
4908 origin_token BLOB NOT NULL,
4909 nonce INTEGER NOT NULL,
4910 encrypted_origin BLOB NOT NULL,
4911 expires_at_unix INTEGER NOT NULL,
4912 PRIMARY KEY(origin_token, nonce)
4913) STRICT;
4914CREATE INDEX private_replay_expiry
4915 ON private_replay_protection(expires_at_unix);
4916PRAGMA user_version=2;
4917COMMIT;
4918"#;
4919
4920const SCHEMA_V3: &str = r#"
4921BEGIN IMMEDIATE;
4922ALTER TABLE private_provider_permissions
4923 ADD COLUMN revoked INTEGER NOT NULL DEFAULT 0;
4924PRAGMA user_version=3;
4925COMMIT;
4926"#;
4927
4928const LEGACY_ENTITY_TABLES: &[&str] = &[
4929 "wallet_accounts",
4930 "derived_addresses",
4931 "hns_utxos",
4932 "hns_transactions",
4933 "known_names",
4934 "name_owner_outpoints",
4935 "name_transfer_state",
4936 "shakedex_state",
4937 "shakescape_board_cache",
4938 "bitcoin_headers",
4939 "bitcoin_filter_headers",
4940 "bitcoin_peers",
4941 "bitcoin_scan_state",
4942 "bitcoin_utxos",
4943 "bitcoin_transactions",
4944 "ethereum_accounts",
4945 "ethereum_transactions",
4946 "market_intents",
4947 "fill_grants",
4948 "price_rounds",
4949 "swap_sessions",
4950 "htlc_secrets",
4951 "refund_transactions",
4952];
4953
4954fn reject_unmigrated_legacy_entities(
4958 transaction: &rusqlite::Transaction<'_>,
4959) -> Result<(), StoreError> {
4960 for table in LEGACY_ENTITY_TABLES {
4961 let exists: bool = transaction.query_row(
4962 "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1)",
4963 [*table],
4964 |row| row.get(0),
4965 )?;
4966 if !exists {
4967 continue;
4968 }
4969 let query = format!("SELECT EXISTS(SELECT 1 FROM {table} LIMIT 1)");
4970 let populated: bool = transaction.query_row(&query, [], |row| row.get(0))?;
4971 if populated {
4972 return Err(StoreError::LegacyEntityMigrationRequired(
4973 (*table).to_owned(),
4974 ));
4975 }
4976 }
4977 Ok(())
4978}
4979
4980fn validate_legacy_replay_capacity(rows: &[(String, u64, u64)]) -> Result<(), StoreError> {
4981 if rows.len() > MAX_REPLAY_ROWS {
4982 return Err(StoreError::ReplayGlobalCapacity);
4983 }
4984 let mut previous_origin: Option<&str> = None;
4985 let mut origin_count = 0_usize;
4986 let mut rows_for_origin = 0_usize;
4987 for (origin, nonce, _) in rows {
4988 validate_origin(origin)?;
4989 if *nonce == 0 {
4990 return Err(StoreError::InvalidReplayWindow);
4991 }
4992 if previous_origin != Some(origin.as_str()) {
4993 origin_count = origin_count
4994 .checked_add(1)
4995 .ok_or(StoreError::ReplayOriginCapacity)?;
4996 if origin_count > MAX_REPLAY_ORIGINS {
4997 return Err(StoreError::ReplayOriginCapacity);
4998 }
4999 previous_origin = Some(origin);
5000 rows_for_origin = 0;
5001 }
5002 rows_for_origin = rows_for_origin
5003 .checked_add(1)
5004 .ok_or(StoreError::ReplayCapacity)?;
5005 if rows_for_origin > MAX_REPLAY_ROWS_PER_ORIGIN {
5006 return Err(StoreError::ReplayCapacity);
5007 }
5008 }
5009 Ok(())
5010}
5011
5012fn truncate_wal(connection: &Connection) -> Result<(), StoreError> {
5013 let busy: u32 =
5014 connection.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| row.get(0))?;
5015 if busy != 0 {
5016 return Err(StoreError::WalCheckpointBusy);
5017 }
5018 Ok(())
5019}
5020
5021fn encode_origin_payload(origin: &str, payload: &[u8]) -> Result<Zeroizing<Vec<u8>>, StoreError> {
5022 validate_origin(origin)?;
5023 if payload.is_empty() {
5024 return Err(StoreError::RecordTooLarge);
5025 }
5026 let origin_len = u16::try_from(origin.len()).map_err(|_| StoreError::InvalidOrigin)?;
5027 let capacity = 2_usize
5028 .checked_add(origin.len())
5029 .and_then(|length| length.checked_add(payload.len()))
5030 .ok_or(StoreError::RecordTooLarge)?;
5031 if capacity > MAX_SECRET_BYTES {
5032 return Err(StoreError::RecordTooLarge);
5033 }
5034 let mut encoded = Zeroizing::new(Vec::with_capacity(capacity));
5035 encoded.extend_from_slice(&origin_len.to_be_bytes());
5036 encoded.extend_from_slice(origin.as_bytes());
5037 encoded.extend_from_slice(payload);
5038 Ok(encoded)
5039}
5040
5041fn decode_origin_payload(encoded: &[u8]) -> Result<(String, Zeroizing<Vec<u8>>), StoreError> {
5042 if encoded.len() < 3 || encoded.len() > MAX_SECRET_BYTES {
5043 return Err(StoreError::Encryption);
5044 }
5045 let origin_len = usize::from(u16::from_be_bytes([encoded[0], encoded[1]]));
5046 let payload_offset = 2_usize
5047 .checked_add(origin_len)
5048 .ok_or(StoreError::Encryption)?;
5049 if payload_offset >= encoded.len() {
5050 return Err(StoreError::Encryption);
5051 }
5052 let origin = core::str::from_utf8(&encoded[2..payload_offset])
5053 .map_err(|_| StoreError::Encryption)?
5054 .to_owned();
5055 validate_origin(&origin).map_err(|_| StoreError::Encryption)?;
5056 Ok((origin, Zeroizing::new(encoded[payload_offset..].to_vec())))
5057}
5058
5059fn prune_expired_approvals(
5060 transaction: &rusqlite::Transaction<'_>,
5061 key: &[u8; KEY_BYTES],
5062 database_id: &[u8; DATABASE_ID_BYTES],
5063 now_unix: u64,
5064) -> Result<(), StoreError> {
5065 let rows = {
5066 let mut statement = transaction.prepare(
5067 "SELECT id, origin_token, encrypted_record, expires_at_unix
5068 FROM private_pending_approvals ORDER BY id",
5069 )?;
5070 let rows = statement.query_map([], |row| {
5071 Ok((
5072 row.get::<_, Vec<u8>>(0)?,
5073 row.get::<_, Vec<u8>>(1)?,
5074 row.get::<_, Vec<u8>>(2)?,
5075 row.get::<_, u64>(3)?,
5076 ))
5077 })?;
5078 rows.collect::<Result<Vec<_>, _>>()?
5079 };
5080 if rows.len() > MAX_PENDING_APPROVALS {
5081 return Err(StoreError::ApprovalCapacity);
5082 }
5083 for (id, origin_token, encrypted, expires_at_unix) in rows {
5084 let id = ApprovalId::new(id.try_into().map_err(|_| StoreError::CorruptMetadata)?);
5085 let origin_token: [u8; 32] = origin_token
5086 .try_into()
5087 .map_err(|_| StoreError::CorruptMetadata)?;
5088 let clear = decrypt_record(
5089 key,
5090 database_id,
5091 "pending_approval",
5092 &approval_record_id(&id, &origin_token, expires_at_unix),
5093 &encrypted,
5094 )?;
5095 let (origin, _) = decode_origin_payload(&clear)?;
5096 if origin_lookup_token(key, database_id, &origin)? != origin_token {
5097 return Err(StoreError::Encryption);
5098 }
5099 if expires_at_unix <= now_unix {
5100 transaction.execute(
5101 "DELETE FROM private_pending_approvals WHERE id=?1",
5102 params![id.as_bytes().as_slice()],
5103 )?;
5104 }
5105 }
5106 Ok(())
5107}
5108
5109fn prune_expired_replay(
5110 transaction: &rusqlite::Transaction<'_>,
5111 key: &[u8; KEY_BYTES],
5112 database_id: &[u8; DATABASE_ID_BYTES],
5113 now_unix: u64,
5114) -> Result<(), StoreError> {
5115 let rows = {
5116 let mut statement = transaction.prepare(
5117 "SELECT origin_token, nonce, encrypted_origin, expires_at_unix
5118 FROM private_replay_protection ORDER BY origin_token, nonce",
5119 )?;
5120 let rows = statement.query_map([], |row| {
5121 Ok((
5122 row.get::<_, Vec<u8>>(0)?,
5123 row.get::<_, u64>(1)?,
5124 row.get::<_, Vec<u8>>(2)?,
5125 row.get::<_, u64>(3)?,
5126 ))
5127 })?;
5128 rows.collect::<Result<Vec<_>, _>>()?
5129 };
5130 if rows.len() > MAX_REPLAY_ROWS {
5131 return Err(StoreError::ReplayGlobalCapacity);
5132 }
5133 for (origin_token, nonce, encrypted_origin, expires_at_unix) in rows {
5134 let origin_token: [u8; 32] = origin_token
5135 .try_into()
5136 .map_err(|_| StoreError::CorruptMetadata)?;
5137 let clear = decrypt_record(
5138 key,
5139 database_id,
5140 "replay_origin",
5141 &replay_record_id(&origin_token, nonce, expires_at_unix),
5142 &encrypted_origin,
5143 )?;
5144 let origin = core::str::from_utf8(&clear).map_err(|_| StoreError::Encryption)?;
5145 validate_origin(origin).map_err(|_| StoreError::Encryption)?;
5146 if origin_lookup_token(key, database_id, origin)? != origin_token {
5147 return Err(StoreError::Encryption);
5148 }
5149 if expires_at_unix <= now_unix {
5150 transaction.execute(
5151 "DELETE FROM private_replay_protection
5152 WHERE origin_token=?1 AND nonce=?2",
5153 params![origin_token.as_slice(), nonce],
5154 )?;
5155 }
5156 }
5157 Ok(())
5158}
5159
5160fn validate_passphrase(passphrase: &str) -> Result<(), StoreError> {
5161 if passphrase.is_empty() || passphrase.len() > MAX_PASSPHRASE_BYTES {
5162 Err(StoreError::InvalidPassphrase)
5163 } else {
5164 Ok(())
5165 }
5166}
5167
5168fn derive_key(
5169 passphrase: &str,
5170 salt: &[u8; SALT_BYTES],
5171 config: KdfConfig,
5172) -> Result<Zeroizing<[u8; KEY_BYTES]>, StoreError> {
5173 validate_passphrase(passphrase)?;
5174 config.validate()?;
5175 let params = Params::new(
5176 config.memory_kib,
5177 config.iterations,
5178 config.lanes,
5179 Some(KEY_BYTES),
5180 )
5181 .map_err(|_| StoreError::UnsafeKdfParameters)?;
5182 let mut key = Zeroizing::new([0_u8; KEY_BYTES]);
5183 Argon2::new(Algorithm::Argon2id, Version::V0x13, params)
5184 .hash_password_into(passphrase.as_bytes(), salt, key.as_mut())
5185 .map_err(|_| StoreError::KeyDerivation)?;
5186 Ok(key)
5187}
5188
5189fn rekey_rows<T>(
5193 transaction: &rusqlite::Transaction<'_>,
5194 select: &str,
5195 mut decode: impl FnMut(&rusqlite::Row<'_>) -> rusqlite::Result<(i64, T)>,
5196 mut rekey: impl FnMut(&rusqlite::Transaction<'_>, i64, T) -> Result<(), StoreError>,
5197) -> Result<(), StoreError> {
5198 let mut after: Option<i64> = None;
5199 loop {
5200 let rows = {
5201 let mut statement = transaction.prepare(select)?;
5202 let mapped = statement.query_map([after], &mut decode)?;
5203 mapped.collect::<Result<Vec<_>, _>>()?
5204 };
5205 if rows.is_empty() {
5206 return Ok(());
5207 }
5208 for (rowid, value) in rows {
5209 rekey(transaction, rowid, value)?;
5210 after = Some(rowid);
5211 }
5212 }
5213}
5214
5215fn encrypt_record(
5216 key: &[u8; KEY_BYTES],
5217 database_id: &[u8; DATABASE_ID_BYTES],
5218 kind: &str,
5219 id: &[u8],
5220 cleartext: &[u8],
5221) -> Result<Vec<u8>, StoreError> {
5222 if cleartext.is_empty() || cleartext.len() > MAX_SECRET_BYTES {
5223 return Err(StoreError::RecordTooLarge);
5224 }
5225 let mut nonce = [0_u8; NONCE_BYTES];
5226 getrandom::fill(&mut nonce).map_err(|_| StoreError::Randomness)?;
5227 let aad = record_aad(database_id, kind, id)?;
5228 let cipher = XChaCha20Poly1305::new(key.into());
5229 let ciphertext = cipher
5230 .encrypt(
5231 XNonce::from_slice(&nonce),
5232 Payload {
5233 msg: cleartext,
5234 aad: &aad,
5235 },
5236 )
5237 .map_err(|_| StoreError::Encryption)?;
5238 let mut envelope = Vec::with_capacity(NONCE_BYTES + ciphertext.len());
5239 envelope.extend_from_slice(&nonce);
5240 envelope.extend_from_slice(&ciphertext);
5241 nonce.zeroize();
5242 Ok(envelope)
5243}
5244
5245fn decrypt_record(
5246 key: &[u8; KEY_BYTES],
5247 database_id: &[u8; DATABASE_ID_BYTES],
5248 kind: &str,
5249 id: &[u8],
5250 envelope: &[u8],
5251) -> Result<Zeroizing<Vec<u8>>, StoreError> {
5252 validate_encrypted_record_length(envelope.len())?;
5253 let (nonce, ciphertext) = envelope.split_at(NONCE_BYTES);
5254 let aad = record_aad(database_id, kind, id)?;
5255 let cipher = XChaCha20Poly1305::new(key.into());
5256 cipher
5257 .decrypt(
5258 XNonce::from_slice(nonce),
5259 Payload {
5260 msg: ciphertext,
5261 aad: &aad,
5262 },
5263 )
5264 .map(Zeroizing::new)
5265 .map_err(|_| StoreError::Encryption)
5266}
5267
5268fn validate_encrypted_record_length(length: usize) -> Result<(), StoreError> {
5269 if length <= NONCE_BYTES || length > MAX_ENCRYPTED_RECORD_BYTES {
5270 return Err(StoreError::Encryption);
5271 }
5272 Ok(())
5273}
5274
5275fn record_aad(
5276 database_id: &[u8; DATABASE_ID_BYTES],
5277 kind: &str,
5278 id: &[u8],
5279) -> Result<Vec<u8>, StoreError> {
5280 if id.is_empty() || id.len() > MAX_RECORD_ID_BYTES + 64 {
5281 return Err(StoreError::InvalidRecordId);
5282 }
5283 if kind.is_empty() || kind.len() > 64 {
5284 return Err(StoreError::InvalidRecordId);
5285 }
5286 let mut aad = Vec::with_capacity(AAD_DOMAIN.len() + database_id.len() + kind.len() + id.len());
5287 aad.extend_from_slice(AAD_DOMAIN);
5288 aad.extend_from_slice(database_id);
5289 aad.extend_from_slice(kind.as_bytes());
5290 aad.push(0);
5291 aad.extend_from_slice(id);
5292 Ok(aad)
5293}
5294
5295fn entity_label(kind: EntityKind) -> String {
5296 format!("entity/{}", kind.label())
5297}
5298
5299fn workflow_label(kind: WorkflowKind) -> String {
5300 format!("workflow/{}", workflow_kind(kind))
5301}
5302
5303fn origin_lookup_token(
5304 key: &[u8; KEY_BYTES],
5305 database_id: &[u8; DATABASE_ID_BYTES],
5306 origin: &str,
5307) -> Result<[u8; 32], StoreError> {
5308 let mut mac =
5309 <Hmac<Sha256> as Mac>::new_from_slice(key).map_err(|_| StoreError::KeyDerivation)?;
5310 Mac::update(&mut mac, ORIGIN_TOKEN_DOMAIN);
5311 Mac::update(&mut mac, database_id);
5312 Mac::update(&mut mac, origin.as_bytes());
5313 Ok(mac.finalize().into_bytes().into())
5314}
5315
5316fn revisioned_aad_id(
5317 id: &[u8],
5318 revision: u64,
5319 updated_at_unix: u64,
5320 broadcast_prepared: Option<bool>,
5321) -> Result<Vec<u8>, StoreError> {
5322 validate_id(id)?;
5323 let mut aad_id = Vec::with_capacity(id.len() + 17);
5324 aad_id.extend_from_slice(id);
5325 aad_id.extend_from_slice(&revision.to_be_bytes());
5326 aad_id.extend_from_slice(&updated_at_unix.to_be_bytes());
5327 if let Some(prepared) = broadcast_prepared {
5328 aad_id.push(u8::from(prepared));
5329 }
5330 Ok(aad_id)
5331}
5332
5333fn permission_record_id(
5334 origin_token: &[u8; 32],
5335 generation: u64,
5336 revoked: bool,
5337 updated_at_unix: u64,
5338) -> [u8; 49] {
5339 let mut id = [0_u8; 49];
5340 id[..32].copy_from_slice(origin_token);
5341 id[32..40].copy_from_slice(&generation.to_be_bytes());
5342 id[40] = u8::from(revoked);
5343 id[41..].copy_from_slice(&updated_at_unix.to_be_bytes());
5344 id
5345}
5346
5347fn approval_record_id(id: &ApprovalId, origin_token: &[u8; 32], expires_at_unix: u64) -> [u8; 56] {
5348 let mut aad_id = [0_u8; 56];
5349 aad_id[..16].copy_from_slice(id.as_bytes());
5350 aad_id[16..48].copy_from_slice(origin_token);
5351 aad_id[48..].copy_from_slice(&expires_at_unix.to_be_bytes());
5352 aad_id
5353}
5354
5355fn replay_record_id(origin_token: &[u8; 32], nonce: u64, expires_at_unix: u64) -> [u8; 48] {
5356 let mut id = [0_u8; 48];
5357 id[..32].copy_from_slice(origin_token);
5358 id[32..40].copy_from_slice(&nonce.to_be_bytes());
5359 id[40..].copy_from_slice(&expires_at_unix.to_be_bytes());
5360 id
5361}
5362
5363fn validate_id(id: &[u8]) -> Result<(), StoreError> {
5364 if id.is_empty() || id.len() > MAX_RECORD_ID_BYTES {
5365 return Err(StoreError::InvalidRecordId);
5366 }
5367 Ok(())
5368}
5369
5370fn validate_origin(origin: &str) -> Result<(), StoreError> {
5371 if origin.is_empty() || origin.len() > 512 || !origin.is_ascii() {
5372 return Err(StoreError::InvalidOrigin);
5373 }
5374 Ok(())
5375}
5376
5377fn meta(connection: &Connection, key: &str) -> Result<Option<Vec<u8>>, StoreError> {
5378 connection
5379 .query_row(
5380 "SELECT value FROM wallet_meta WHERE key=?1",
5381 params![key],
5382 |row| row.get(0),
5383 )
5384 .optional()
5385 .map_err(StoreError::from)
5386}
5387
5388fn required_meta(connection: &Connection, key: &str) -> Result<Vec<u8>, StoreError> {
5389 meta(connection, key)?.ok_or(StoreError::NotInitialized)
5390}
5391
5392fn set_meta(
5393 transaction: &rusqlite::Transaction<'_>,
5394 key: &str,
5395 value: &[u8],
5396) -> Result<(), StoreError> {
5397 transaction.execute(
5398 "INSERT INTO wallet_meta(key, value) VALUES(?1, ?2)",
5399 params![key, value],
5400 )?;
5401 Ok(())
5402}
5403
5404fn exact_array<const N: usize>(bytes: Vec<u8>) -> Result<[u8; N], StoreError> {
5405 bytes.try_into().map_err(|_| StoreError::CorruptMetadata)
5406}
5407
5408const fn workflow_kind(kind: WorkflowKind) -> &'static str {
5409 match kind {
5410 WorkflowKind::HnsSend => "hns_send",
5411 WorkflowKind::NameTransfer => "name_transfer",
5412 WorkflowKind::NameFinalize => "name_finalize",
5413 WorkflowKind::NameUpdate => "name_update",
5414 WorkflowKind::ShakedexSeller => "shakedex_seller",
5415 WorkflowKind::ShakedexBuyer => "shakedex_buyer",
5416 WorkflowKind::ShakedexSellerPlan => "shakedex_seller_plan",
5417 WorkflowKind::ShakedexBuyerPlan => "shakedex_buyer_plan",
5418 WorkflowKind::ShakedexSellerOffer => "shakedex_seller_offer",
5419 WorkflowKind::ShakedexValue => "shakedex_value",
5420 WorkflowKind::DirectOffer => "direct_offer",
5421 WorkflowKind::DirectOfferAcceptance => "direct_offer_acceptance",
5422 WorkflowKind::AtomicSwap => "atomic_swap",
5423 WorkflowKind::Refund => "refund",
5424 }
5425}
5426
5427fn parse_workflow_kind(value: &str) -> Result<WorkflowKind, StoreError> {
5428 match value {
5429 "hns_send" => Ok(WorkflowKind::HnsSend),
5430 "name_transfer" => Ok(WorkflowKind::NameTransfer),
5431 "name_finalize" => Ok(WorkflowKind::NameFinalize),
5432 "name_update" => Ok(WorkflowKind::NameUpdate),
5433 "shakedex_seller" => Ok(WorkflowKind::ShakedexSeller),
5434 "shakedex_buyer" => Ok(WorkflowKind::ShakedexBuyer),
5435 "shakedex_seller_plan" => Ok(WorkflowKind::ShakedexSellerPlan),
5436 "shakedex_buyer_plan" => Ok(WorkflowKind::ShakedexBuyerPlan),
5437 "shakedex_seller_offer" => Ok(WorkflowKind::ShakedexSellerOffer),
5438 "shakedex_value" => Ok(WorkflowKind::ShakedexValue),
5439 "direct_offer" => Ok(WorkflowKind::DirectOffer),
5440 "direct_offer_acceptance" => Ok(WorkflowKind::DirectOfferAcceptance),
5441 "atomic_swap" => Ok(WorkflowKind::AtomicSwap),
5442 "refund" => Ok(WorkflowKind::Refund),
5443 _ => Err(StoreError::CorruptMetadata),
5444 }
5445}
5446
5447#[derive(Debug, Error)]
5448pub enum StoreError {
5449 #[error(transparent)]
5450 Io(#[from] std::io::Error),
5451 #[error(transparent)]
5452 Sqlite(#[from] rusqlite::Error),
5453 #[error(transparent)]
5454 Json(#[from] serde_json::Error),
5455 #[error("wallet store is already initialized")]
5456 AlreadyInitialized,
5457 #[error("wallet database path already exists")]
5458 DatabaseExists,
5459 #[error("wallet store is not initialized")]
5460 NotInitialized,
5461 #[error("wallet store is locked")]
5462 Locked,
5463 #[error("invalid wallet passphrase")]
5464 InvalidPassphrase,
5465 #[error("wallet passphrase changed, but old ciphertext checkpoint is pending")]
5466 PassphraseChangedCheckpointPending,
5467 #[error("unsafe or unsupported Argon2 parameters")]
5468 UnsafeKdfParameters,
5469 #[error("key derivation failed")]
5470 KeyDerivation,
5471 #[error("operating-system randomness is unavailable")]
5472 Randomness,
5473 #[error("authenticated encryption failed")]
5474 Encryption,
5475 #[error("secret kind does not match the requested kind")]
5476 KindMismatch,
5477 #[error("wallet recovery seed is immutable and cannot be deleted or replaced")]
5478 ProtectedSecret,
5479 #[error("wallet recovery seed must be exactly 64 bytes")]
5480 InvalidRecoverySeed,
5481 #[error("wallet seed/account bootstrap conflicts with existing initialization state")]
5482 BootstrapConflict,
5483 #[error("a workflow identifier cannot change workflow kind")]
5484 WorkflowKindMismatch,
5485 #[error("record identifier is invalid")]
5486 InvalidRecordId,
5487 #[error("origin is invalid")]
5488 InvalidOrigin,
5489 #[error("record exceeds its bounded maximum")]
5490 RecordTooLarge,
5491 #[error("wallet metadata is corrupt")]
5492 CorruptMetadata,
5493 #[error("database schema {0} is newer than this wallet")]
5494 NewerSchema(u32),
5495 #[error("stale workflow revision: expected {expected}, actual {actual}")]
5496 StaleRevision { expected: u64, actual: u64 },
5497 #[error("encrypted entity prefix set changed since its coherent snapshot")]
5498 StaleEntitySet,
5499 #[error("entity prefix-set lease does not match this database, kind, prefix, or batch")]
5500 InvalidEntityPrefixLease,
5501 #[error("workflow revision overflow")]
5502 RevisionOverflow,
5503 #[error("request nonce has already been consumed")]
5504 Replay,
5505 #[error("request replay window is invalid")]
5506 InvalidReplayWindow,
5507 #[error("pending approval lifetime is invalid")]
5508 InvalidApprovalWindow,
5509 #[error("origin replay-protection capacity is exhausted")]
5510 ReplayCapacity,
5511 #[error("global replay-protection capacity is exhausted")]
5512 ReplayGlobalCapacity,
5513 #[error("replay-protection origin capacity is exhausted")]
5514 ReplayOriginCapacity,
5515 #[error("provider permission capacity is exhausted")]
5516 ProviderCapacity,
5517 #[error("pending approval capacity is exhausted")]
5518 ApprovalCapacity,
5519 #[error("provider permission generation must be nonzero")]
5520 InvalidGeneration,
5521 #[error("provider permission generation mismatch: expected {expected}, got {actual}")]
5522 StaleGeneration { expected: u64, actual: u64 },
5523 #[error("entity or workflow list limit is invalid")]
5524 InvalidListLimit,
5525 #[error("complete bounded entity or workflow list exceeds its capacity")]
5526 ListCapacity,
5527 #[error("record revision must be nonzero")]
5528 InvalidRevision,
5529 #[error("managed encrypted entity records cannot be deleted")]
5530 ProtectedEntity,
5531 #[error("entity batch contains duplicate or invalid operations")]
5532 DuplicateBatchEntity,
5533 #[error("entity batch exceeds its bounded operation limit")]
5534 BatchCapacity,
5535 #[error("legacy sensitive rows require an unlocked migration")]
5536 LegacyEncryptionPending,
5537 #[error("legacy entity table `{0}` requires an explicit authenticated import")]
5538 LegacyEntityMigrationRequired(String),
5539 #[error("the plaintext-removal WAL checkpoint could not acquire the database")]
5540 WalCheckpointBusy,
5541 #[error("wallet database or parent ownership/mode is unsafe")]
5542 UnsafeFilesystemBoundary,
5543 #[error("wallet filesystem ownership validation is unsupported on this platform")]
5544 UnsupportedFilesystemBoundary,
5545 #[error("shared wallet store access failed")]
5546 Concurrency,
5547}
5548
5549#[cfg(test)]
5550mod tests {
5551 use super::*;
5552 use serde_json::json;
5553
5554 #[cfg(unix)]
5555 struct OwnedWalletProduct {
5556 store: WalletStore,
5557 account_revision: u64,
5558 }
5559
5560 #[cfg(unix)]
5561 #[derive(Debug, Eq, PartialEq)]
5562 enum OwnedWalletProductError {
5563 Store,
5564 Negotiation,
5565 }
5566
5567 #[cfg(unix)]
5568 impl From<StoreError> for OwnedWalletProductError {
5569 fn from(_: StoreError) -> Self {
5570 Self::Store
5571 }
5572 }
5573
5574 #[cfg(unix)]
5575 fn unix_private_tempdir() -> tempfile::TempDir {
5576 use std::os::unix::fs::PermissionsExt as _;
5577
5578 let root = std::env::var_os("HNS_WALLET_STORE_TEST_TMPDIR")
5579 .map(PathBuf::from)
5580 .unwrap_or_else(std::env::temp_dir);
5581 let directory = tempfile::Builder::new()
5582 .prefix("hns-wallet-store-")
5583 .tempdir_in(root)
5584 .expect("private Unix test directory");
5585 std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700))
5586 .expect("private Unix test directory mode");
5587 directory
5588 }
5589
5590 #[cfg(unix)]
5591 #[test]
5592 fn unix_wallet_boundary_policy_is_exact_and_platform_independent() {
5593 const UID: u32 = 10_123;
5594 let private_directory = UnixBoundaryMetadata {
5595 kind: UnixBoundaryKind::Directory,
5596 uid: UID,
5597 mode: 0o700,
5598 dev: 1,
5599 ino: 2,
5600 nlink: 2,
5601 };
5602 let private_file = UnixBoundaryMetadata {
5603 kind: UnixBoundaryKind::RegularFile,
5604 uid: UID,
5605 mode: 0o600,
5606 dev: 1,
5607 ino: 3,
5608 nlink: 1,
5609 };
5610 assert!(validate_unix_wallet_directory(private_directory, UID).is_ok());
5611 assert!(validate_unix_wallet_file(private_file, UID).is_ok());
5612
5613 for unsafe_parent in [
5614 UnixBoundaryMetadata {
5615 mode: 0o750,
5616 ..private_directory
5617 },
5618 UnixBoundaryMetadata {
5619 uid: UID + 1,
5620 ..private_directory
5621 },
5622 UnixBoundaryMetadata {
5623 kind: UnixBoundaryKind::Other,
5624 ..private_directory
5625 },
5626 ] {
5627 assert!(matches!(
5628 validate_unix_wallet_directory(unsafe_parent, UID),
5629 Err(StoreError::UnsafeFilesystemBoundary)
5630 ));
5631 }
5632 for unsafe_file in [
5633 UnixBoundaryMetadata {
5634 mode: 0o640,
5635 ..private_file
5636 },
5637 UnixBoundaryMetadata {
5638 uid: UID + 1,
5639 ..private_file
5640 },
5641 UnixBoundaryMetadata {
5642 kind: UnixBoundaryKind::Other,
5643 ..private_file
5644 },
5645 UnixBoundaryMetadata {
5646 nlink: 2,
5647 ..private_file
5648 },
5649 ] {
5650 assert!(matches!(
5651 validate_unix_wallet_file(unsafe_file, UID),
5652 Err(StoreError::UnsafeFilesystemBoundary)
5653 ));
5654 }
5655 }
5656
5657 #[cfg(unix)]
5658 #[test]
5659 fn unix_ancestor_policy_rejects_untrusted_rename_boundaries() {
5660 const UID: u32 = 10_123;
5661 const STRICT: UnixAncestorPolicy = UnixAncestorPolicy::Strict;
5662 const ANDROID: UnixAncestorPolicy = UnixAncestorPolicy::AndroidSystemUid1000;
5663 let root = UnixBoundaryMetadata {
5664 kind: UnixBoundaryKind::Directory,
5665 uid: 0,
5666 mode: 0o755,
5667 dev: 1,
5668 ino: 1,
5669 nlink: 2,
5670 };
5671 let sticky_root = UnixBoundaryMetadata {
5672 mode: 0o1777,
5673 ..root
5674 };
5675 let private = UnixBoundaryMetadata {
5676 uid: UID,
5677 mode: 0o700,
5678 ino: 2,
5679 ..root
5680 };
5681 let owned_ancestor = UnixBoundaryMetadata {
5682 uid: UID,
5683 mode: 0o755,
5684 ino: 3,
5685 ..root
5686 };
5687
5688 assert!(validate_unix_ancestor_chain(&[root, private], UID, STRICT).is_ok());
5689 assert!(validate_unix_ancestor_chain(&[sticky_root, private], UID, STRICT).is_ok());
5690 assert!(matches!(
5691 validate_unix_ancestor_chain(
5692 &[
5693 UnixBoundaryMetadata {
5694 mode: 0o777,
5695 ..root
5696 },
5697 private,
5698 ],
5699 UID,
5700 STRICT,
5701 ),
5702 Err(StoreError::UnsafeFilesystemBoundary)
5703 ));
5704 assert!(matches!(
5705 validate_unix_ancestor_chain(
5706 &[
5707 UnixBoundaryMetadata {
5708 mode: 0o775,
5709 ..root
5710 },
5711 private,
5712 ],
5713 UID,
5714 STRICT,
5715 ),
5716 Err(StoreError::UnsafeFilesystemBoundary)
5717 ));
5718
5719 let android_app_data_chain = [
5720 root,
5721 UnixBoundaryMetadata {
5722 uid: 1_000,
5723 mode: 0o771,
5724 ino: 4,
5725 ..root
5726 },
5727 UnixBoundaryMetadata {
5728 uid: 1_000,
5729 mode: 0o511,
5730 ino: 5,
5731 ..root
5732 },
5733 UnixBoundaryMetadata {
5734 uid: 1_000,
5735 mode: 0o771,
5736 ino: 6,
5737 ..root
5738 },
5739 private,
5740 ];
5741 assert!(matches!(
5742 validate_unix_ancestor_chain(&android_app_data_chain, UID, STRICT),
5743 Err(StoreError::UnsafeFilesystemBoundary)
5744 ));
5745 assert!(validate_unix_ancestor_chain(&android_app_data_chain, UID, ANDROID).is_ok());
5746 let android_9_app_data_chain = [
5747 sticky_root,
5748 UnixBoundaryMetadata {
5749 uid: 1_000,
5750 mode: 0o771,
5751 ino: 4,
5752 ..root
5753 },
5754 UnixBoundaryMetadata {
5755 uid: 1_000,
5756 mode: 0o771,
5757 ino: 6,
5758 ..root
5759 },
5760 private,
5761 ];
5762 assert!(matches!(
5763 validate_unix_ancestor_chain(&android_9_app_data_chain, UID, STRICT),
5764 Err(StoreError::UnsafeFilesystemBoundary)
5765 ));
5766 assert!(validate_unix_ancestor_chain(&android_9_app_data_chain, UID, ANDROID).is_ok());
5767 for unsafe_android_prefix in [
5768 UnixBoundaryMetadata {
5769 uid: 1_001,
5770 mode: 0o771,
5771 ino: 7,
5772 ..root
5773 },
5774 UnixBoundaryMetadata {
5775 uid: 1_000,
5776 mode: 0o773,
5777 ino: 8,
5778 ..root
5779 },
5780 ] {
5781 assert!(matches!(
5782 validate_unix_ancestor_chain(&[root, unsafe_android_prefix, private], UID, ANDROID,),
5783 Err(StoreError::UnsafeFilesystemBoundary)
5784 ));
5785 }
5786
5787 assert!(
5788 validate_unix_ancestor_chain(&[root, owned_ancestor, private], UID, STRICT).is_ok()
5789 );
5790 assert!(
5791 validate_unix_ancestor_chain(
5792 &[
5793 root,
5794 UnixBoundaryMetadata {
5795 mode: 0o1777,
5796 ..owned_ancestor
5797 },
5798 private,
5799 ],
5800 UID,
5801 STRICT,
5802 )
5803 .is_ok()
5804 );
5805 assert!(matches!(
5806 validate_unix_ancestor_chain(
5807 &[
5808 root,
5809 UnixBoundaryMetadata {
5810 mode: 0o777,
5811 ..owned_ancestor
5812 },
5813 private,
5814 ],
5815 UID,
5816 STRICT,
5817 ),
5818 Err(StoreError::UnsafeFilesystemBoundary)
5819 ));
5820 assert!(matches!(
5821 validate_unix_ancestor_chain(
5822 &[
5823 root,
5824 owned_ancestor,
5825 UnixBoundaryMetadata {
5826 uid: UID + 1,
5827 mode: 0o555,
5828 ..private
5829 },
5830 ],
5831 UID,
5832 STRICT,
5833 ),
5834 Err(StoreError::UnsafeFilesystemBoundary)
5835 ));
5836 assert!(matches!(
5837 validate_unix_ancestor_chain(
5838 &[
5839 root,
5840 UnixBoundaryMetadata {
5841 uid: UID + 1,
5842 mode: 0o555,
5843 ..private
5844 },
5845 ],
5846 UID,
5847 STRICT,
5848 ),
5849 Err(StoreError::UnsafeFilesystemBoundary)
5850 ));
5851 }
5852
5853 #[cfg(unix)]
5854 #[test]
5855 fn ios_platform_prefix_allows_owner_transition_before_private_suffix() {
5856 const UID: u32 = 10_123;
5857 let root = UnixBoundaryMetadata {
5858 kind: UnixBoundaryKind::Directory,
5859 uid: 0,
5860 mode: 0o755,
5861 dev: 1,
5862 ino: 1,
5863 nlink: 2,
5864 };
5865 let mobile_home = UnixBoundaryMetadata {
5866 uid: UID,
5867 ino: 2,
5868 ..root
5869 };
5870 let system_container = UnixBoundaryMetadata {
5871 uid: 200,
5872 mode: 0o555,
5873 ino: 3,
5874 ..root
5875 };
5876 let app_container = UnixBoundaryMetadata {
5877 uid: UID,
5878 mode: 0o700,
5879 ino: 4,
5880 ..root
5881 };
5882 let private_wallet = UnixBoundaryMetadata {
5883 ino: 5,
5884 ..app_container
5885 };
5886 let chain = [
5887 root,
5888 mobile_home,
5889 system_container,
5890 app_container,
5891 private_wallet,
5892 ];
5893
5894 assert!(matches!(
5895 validate_unix_ancestor_chain(&chain, UID, UnixAncestorPolicy::Strict),
5896 Err(StoreError::UnsafeFilesystemBoundary)
5897 ));
5898 assert!(
5899 validate_unix_ancestor_chain(&chain, UID, UnixAncestorPolicy::IosPlatformPrefix)
5900 .is_ok()
5901 );
5902
5903 for (index, unsafe_ancestor) in [
5904 (
5905 1,
5906 UnixBoundaryMetadata {
5907 mode: 0o775,
5908 ..mobile_home
5909 },
5910 ),
5911 (
5912 2,
5913 UnixBoundaryMetadata {
5914 mode: 0o775,
5915 ..system_container
5916 },
5917 ),
5918 (
5919 3,
5920 UnixBoundaryMetadata {
5921 mode: 0o770,
5922 ..app_container
5923 },
5924 ),
5925 (
5926 4,
5927 UnixBoundaryMetadata {
5928 mode: 0o770,
5929 ..private_wallet
5930 },
5931 ),
5932 ] {
5933 let mut unsafe_chain = chain;
5934 unsafe_chain[index] = unsafe_ancestor;
5935 assert!(matches!(
5936 validate_unix_ancestor_chain(
5937 &unsafe_chain,
5938 UID,
5939 UnixAncestorPolicy::IosPlatformPrefix
5940 ),
5941 Err(StoreError::UnsafeFilesystemBoundary)
5942 ));
5943 }
5944
5945 let mut unowned_wallet = chain;
5946 unowned_wallet[4].uid = 200;
5947 assert!(matches!(
5948 validate_unix_ancestor_chain(
5949 &unowned_wallet,
5950 UID,
5951 UnixAncestorPolicy::IosPlatformPrefix
5952 ),
5953 Err(StoreError::UnsafeFilesystemBoundary)
5954 ));
5955 }
5956
5957 #[cfg(unix)]
5958 #[test]
5959 fn ios_private_ancestor_protects_group_writable_simulator_intermediate() {
5960 const UID: u32 = 10_123;
5961 let root = UnixBoundaryMetadata {
5962 kind: UnixBoundaryKind::Directory,
5963 uid: 0,
5964 mode: 0o755,
5965 dev: 1,
5966 ino: 1,
5967 nlink: 2,
5968 };
5969 let owner_home = UnixBoundaryMetadata {
5970 uid: UID,
5971 ino: 2,
5972 ..root
5973 };
5974 let owner_library = UnixBoundaryMetadata {
5975 mode: 0o700,
5976 ino: 3,
5977 ..owner_home
5978 };
5979 let simulator_data = UnixBoundaryMetadata {
5980 mode: 0o775,
5981 ino: 4,
5982 ..owner_home
5983 };
5984 let wallet_parent = UnixBoundaryMetadata {
5985 mode: 0o700,
5986 ino: 5,
5987 ..owner_home
5988 };
5989 let chain = [
5990 root,
5991 owner_home,
5992 owner_library,
5993 simulator_data,
5994 wallet_parent,
5995 ];
5996
5997 assert!(
5998 validate_unix_ancestor_chain(&chain, UID, UnixAncestorPolicy::IosPlatformPrefix)
5999 .is_ok()
6000 );
6001 assert!(matches!(
6002 validate_unix_ancestor_chain(&chain, UID, UnixAncestorPolicy::Strict),
6003 Err(StoreError::UnsafeFilesystemBoundary)
6004 ));
6005
6006 for (index, mode) in [(1, 0o775), (3, 0o777), (4, 0o770)] {
6007 let mut unsafe_chain = chain;
6008 unsafe_chain[index].mode = mode;
6009 assert!(matches!(
6010 validate_unix_ancestor_chain(
6011 &unsafe_chain,
6012 UID,
6013 UnixAncestorPolicy::IosPlatformPrefix
6014 ),
6015 Err(StoreError::UnsafeFilesystemBoundary)
6016 ));
6017 }
6018 }
6019
6020 #[cfg(unix)]
6021 #[test]
6022 fn unix_file_identity_rejects_inode_changes_and_hard_links() {
6023 let identity = UnixBoundaryMetadata {
6024 kind: UnixBoundaryKind::RegularFile,
6025 uid: 10_123,
6026 mode: 0o600,
6027 dev: 7,
6028 ino: 11,
6029 nlink: 1,
6030 };
6031 assert!(validate_unix_file_identity(identity, identity).is_ok());
6032 for changed in [
6033 UnixBoundaryMetadata { dev: 8, ..identity },
6034 UnixBoundaryMetadata {
6035 ino: 12,
6036 ..identity
6037 },
6038 UnixBoundaryMetadata {
6039 nlink: 2,
6040 ..identity
6041 },
6042 ] {
6043 assert!(matches!(
6044 validate_unix_file_identity(identity, changed),
6045 Err(StoreError::UnsafeFilesystemBoundary)
6046 ));
6047 }
6048 }
6049
6050 #[cfg(unix)]
6051 #[test]
6052 fn unix_wallet_location_canonicalizes_ancestor_aliases_only() {
6053 use std::os::unix::fs::{PermissionsExt as _, symlink};
6054
6055 let directory = unix_private_tempdir();
6056 let physical_root = directory.path().join("physical");
6057 let container = physical_root.join("container");
6058 let private_directory = container.join("wallet-private");
6059 std::fs::create_dir_all(&private_directory).expect("physical private directory");
6060 for owned_ancestor in [&physical_root, &container] {
6061 std::fs::set_permissions(owned_ancestor, std::fs::Permissions::from_mode(0o700))
6062 .expect("private owned ancestor mode");
6063 }
6064 std::fs::set_permissions(&private_directory, std::fs::Permissions::from_mode(0o700))
6065 .expect("private directory mode");
6066 let ancestor_alias = directory.path().join("system-alias");
6067 symlink(&physical_root, &ancestor_alias).expect("system-style ancestor alias");
6068
6069 let supplied_database = ancestor_alias
6070 .join("container")
6071 .join("wallet-private")
6072 .join("wallet.sqlite3");
6073 let physical_database = private_directory.join("wallet.sqlite3");
6074 assert_eq!(
6075 validate_wallet_location(&supplied_database, WalletPathRequirement::Missing)
6076 .expect("missing create target")
6077 .path,
6078 physical_database
6079 );
6080 std::fs::write(&physical_database, []).expect("empty database fixture");
6081 std::fs::set_permissions(&physical_database, std::fs::Permissions::from_mode(0o600))
6082 .expect("private database mode");
6083 assert_eq!(
6084 validate_wallet_location(&supplied_database, WalletPathRequirement::Existing)
6085 .expect("existing database")
6086 .path,
6087 physical_database
6088 );
6089
6090 let database_alias = private_directory.join("wallet-link.sqlite3");
6091 symlink(&physical_database, &database_alias).expect("database alias");
6092 assert!(matches!(
6093 validate_wallet_location(&database_alias, WalletPathRequirement::Existing),
6094 Err(StoreError::UnsafeFilesystemBoundary)
6095 ));
6096
6097 let parent_alias = directory.path().join("wallet-parent-link");
6098 symlink(&private_directory, &parent_alias).expect("parent alias");
6099 assert!(matches!(
6100 validate_wallet_location(
6101 &parent_alias.join("wallet.sqlite3"),
6102 WalletPathRequirement::Existing,
6103 ),
6104 Err(StoreError::UnsafeFilesystemBoundary)
6105 ));
6106
6107 std::fs::set_permissions(&private_directory, std::fs::Permissions::from_mode(0o750))
6108 .expect("unsafe parent mode fixture");
6109 assert!(matches!(
6110 validate_wallet_location(&supplied_database, WalletPathRequirement::Existing),
6111 Err(StoreError::UnsafeFilesystemBoundary)
6112 ));
6113 }
6114
6115 #[cfg(unix)]
6116 #[test]
6117 fn unix_create_rejects_existing_file_without_mutation() {
6118 use std::os::unix::fs::PermissionsExt as _;
6119
6120 let directory = unix_private_tempdir();
6121 std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700))
6122 .expect("private directory mode");
6123 let database = directory.path().join("wallet.sqlite3");
6124 let sentinel = b"existing non-wallet bytes";
6125 std::fs::write(&database, sentinel).expect("existing database fixture");
6126 std::fs::set_permissions(&database, std::fs::Permissions::from_mode(0o600))
6127 .expect("existing database mode");
6128
6129 assert!(matches!(
6130 WalletStore::create_with_kdf(
6131 &database,
6132 "existing-file-passphrase",
6133 KdfConfig::testing(),
6134 ),
6135 Err(StoreError::DatabaseExists)
6136 ));
6137 assert_eq!(
6138 std::fs::read(&database).expect("unchanged existing database"),
6139 sentinel
6140 );
6141 assert!(!directory.path().join("wallet.sqlite3-wal").exists());
6142 assert!(!directory.path().join("wallet.sqlite3-shm").exists());
6143 }
6144
6145 #[cfg(unix)]
6146 #[test]
6147 fn unix_failed_create_cleans_owned_artifacts_and_allows_retry() {
6148 use std::os::unix::fs::{OpenOptionsExt as _, PermissionsExt as _};
6149
6150 let directory = unix_private_tempdir();
6151 let database = directory.path().join("wallet.sqlite3");
6152 let sidecars = sqlite_sidecar_paths(&database);
6153
6154 for sidecar in &sidecars {
6155 std::fs::write(sidecar, b"pre-existing sidecar").expect("sidecar fixture");
6156 std::fs::set_permissions(sidecar, std::fs::Permissions::from_mode(0o600))
6157 .expect("sidecar mode");
6158 assert!(matches!(
6159 WalletStore::create_with_kdf(
6160 &database,
6161 "cleanup-retry-passphrase",
6162 KdfConfig::testing(),
6163 ),
6164 Err(StoreError::DatabaseExists)
6165 ));
6166 assert!(!database.exists());
6167 assert_eq!(
6168 std::fs::read(sidecar).expect("preserved sidecar"),
6169 b"pre-existing sidecar"
6170 );
6171 std::fs::remove_file(sidecar).expect("remove sidecar fixture");
6172 }
6173
6174 assert!(matches!(
6175 WalletStore::create_with_kdf_after_migration(
6176 &database,
6177 "cleanup-retry-passphrase",
6178 KdfConfig::testing(),
6179 |_| {
6180 for sidecar in &sidecars {
6181 if !sidecar.exists() {
6182 std::fs::OpenOptions::new()
6183 .write(true)
6184 .create_new(true)
6185 .mode(0o600)
6186 .open(sidecar)
6187 .expect("invocation-owned sidecar fixture");
6188 }
6189 }
6190 Err(StoreError::CorruptMetadata)
6191 },
6192 ),
6193 Err(StoreError::CorruptMetadata)
6194 ));
6195 assert!(!database.exists());
6196 for sidecar in &sidecars {
6197 assert!(!sidecar.exists());
6198 }
6199
6200 let store = WalletStore::create_with_kdf(
6201 &database,
6202 "cleanup-retry-passphrase",
6203 KdfConfig::testing(),
6204 )
6205 .expect("retry clean creation");
6206 drop(store);
6207 let mut reopened = WalletStore::open(&database).expect("open retried wallet");
6208 reopened
6209 .unlock("cleanup-retry-passphrase")
6210 .expect("unlock retried wallet");
6211 }
6212
6213 #[cfg(unix)]
6214 #[test]
6215 fn unix_failed_product_initializer_keeps_creation_cleanup_armed() {
6216 let directory = unix_private_tempdir();
6217 let database = directory.path().join("wallet.sqlite3");
6218
6219 assert!(matches!(
6220 WalletStore::create_with_kdf_and_initializer(
6221 &database,
6222 "product-initializer-passphrase",
6223 KdfConfig::testing(),
6224 |_| Ok(()),
6225 |store| {
6226 store.initialize_recovery_seed_and_wallet_account(
6227 &[61_u8; 16],
6228 &[62_u8; 64],
6229 &[63_u8; 32],
6230 &json!({"account": 63}),
6231 1,
6232 )?;
6233 Err::<(), _>(StoreError::CorruptMetadata)
6234 },
6235 ),
6236 Err(StoreError::CorruptMetadata)
6237 ));
6238 assert!(!database.exists());
6239 for sidecar in sqlite_sidecar_paths(&database) {
6240 assert!(!sidecar.exists());
6241 }
6242
6243 let (store, revision) = WalletStore::create_with_kdf_and_initializer(
6244 &database,
6245 "product-initializer-passphrase",
6246 KdfConfig::testing(),
6247 |_| Ok(()),
6248 |store| {
6249 store.initialize_recovery_seed_and_wallet_account(
6250 &[61_u8; 16],
6251 &[62_u8; 64],
6252 &[63_u8; 32],
6253 &json!({"account": 63}),
6254 2,
6255 )
6256 },
6257 )
6258 .expect("retry complete product initialization");
6259 assert_eq!(revision, 1);
6260 drop(store);
6261
6262 let mut reopened = WalletStore::open(&database).expect("reopen initialized wallet");
6263 reopened
6264 .unlock("product-initializer-passphrase")
6265 .expect("unlock initialized wallet");
6266 assert!(
6267 reopened
6268 .get_secret(&[61_u8; 16], SecretKind::RecoverySeed)
6269 .expect("read initialized seed")
6270 .is_some()
6271 );
6272 assert!(
6273 reopened
6274 .wallet_account::<serde_json::Value>(&[63_u8; 32])
6275 .expect("read initialized account")
6276 .is_some()
6277 );
6278 }
6279
6280 #[cfg(unix)]
6281 #[test]
6282 fn unix_owned_product_initializer_cleans_failure_and_returns_live_success() {
6283 let directory = unix_private_tempdir();
6284 let database = directory.path().join("wallet.sqlite3");
6285 let passphrase = "owned-product-initializer-passphrase";
6286
6287 let failure: Result<OwnedWalletProduct, OwnedWalletProductError> =
6288 WalletStore::create_with_kdf_and_owned_initializer(
6289 &database,
6290 passphrase,
6291 KdfConfig::testing(),
6292 |mut store| {
6293 let account_revision = store
6294 .initialize_recovery_seed_and_wallet_account(
6295 &[71_u8; 16],
6296 &[72_u8; RECOVERY_SEED_BYTES],
6297 &[73_u8; 32],
6298 &json!({"account": 73}),
6299 1,
6300 )
6301 .map_err(OwnedWalletProductError::from)?;
6302 let _product = OwnedWalletProduct {
6303 store,
6304 account_revision,
6305 };
6306 Err(OwnedWalletProductError::Negotiation)
6307 },
6308 );
6309 assert!(matches!(failure, Err(OwnedWalletProductError::Negotiation)));
6310 assert!(!database.exists());
6311 for sidecar in sqlite_sidecar_paths(&database) {
6312 assert!(!sidecar.exists());
6313 }
6314
6315 let mut product: OwnedWalletProduct = WalletStore::create_with_kdf_and_owned_initializer(
6316 &database,
6317 passphrase,
6318 KdfConfig::testing(),
6319 |mut store| {
6320 let account_revision = store
6321 .initialize_recovery_seed_and_wallet_account(
6322 &[71_u8; 16],
6323 &[72_u8; RECOVERY_SEED_BYTES],
6324 &[73_u8; 32],
6325 &json!({"account": 73}),
6326 2,
6327 )
6328 .map_err(OwnedWalletProductError::from)?;
6329 Ok::<_, OwnedWalletProductError>(OwnedWalletProduct {
6330 store,
6331 account_revision,
6332 })
6333 },
6334 )
6335 .expect("owned product initialization");
6336 assert_eq!(product.account_revision, 1);
6337 assert!(database.exists());
6338 product
6339 .store
6340 .validate_single_recovery_seed(&[71_u8; 16])
6341 .expect("product-owned store remains live");
6342 assert!(
6343 product
6344 .store
6345 .wallet_account::<serde_json::Value>(&[73_u8; 32])
6346 .expect("read product-owned account")
6347 .is_some()
6348 );
6349 drop(product);
6350
6351 let mut reopened = WalletStore::open(&database).expect("reopen owned product wallet");
6352 reopened
6353 .unlock(passphrase)
6354 .expect("unlock owned product wallet");
6355 reopened
6356 .validate_single_recovery_seed(&[71_u8; 16])
6357 .expect("validate reopened product seed");
6358 }
6359
6360 #[cfg(unix)]
6361 #[test]
6362 fn unix_cleanup_guard_preserves_replaced_database_identity() {
6363 use std::os::unix::fs::PermissionsExt as _;
6364
6365 let directory = unix_private_tempdir();
6366 let database = directory.path().join("wallet.sqlite3");
6367 let created = create_new_wallet_file(&database).expect("armed creation guard");
6368 std::fs::remove_file(&database).expect("unlink original database");
6369 std::fs::write(&database, b"replacement database").expect("replacement database");
6370 std::fs::set_permissions(&database, std::fs::Permissions::from_mode(0o600))
6371 .expect("replacement mode");
6372 let sidecar = sqlite_sidecar_paths(&database)[2].clone();
6373 std::fs::write(&sidecar, b"replacement sidecar").expect("replacement sidecar");
6374 std::fs::set_permissions(&sidecar, std::fs::Permissions::from_mode(0o600))
6375 .expect("replacement sidecar mode");
6376
6377 drop(created);
6378 assert_eq!(
6379 std::fs::read(&database).expect("preserved replacement database"),
6380 b"replacement database"
6381 );
6382 assert_eq!(
6383 std::fs::read(&sidecar).expect("preserved replacement sidecar"),
6384 b"replacement sidecar"
6385 );
6386 }
6387
6388 #[cfg(unix)]
6389 #[test]
6390 fn unix_open_rejects_non_wallet_without_mutation() {
6391 use std::os::unix::fs::PermissionsExt as _;
6392
6393 let directory = unix_private_tempdir();
6394 let database = directory.path().join("foreign.sqlite3");
6395 let connection = Connection::open(&database).expect("foreign SQLite database");
6396 connection
6397 .execute_batch(
6398 "CREATE TABLE foreign_records(id INTEGER PRIMARY KEY, value TEXT NOT NULL);
6399 INSERT INTO foreign_records(value) VALUES('unchanged');
6400 PRAGMA user_version=1;",
6401 )
6402 .expect("foreign schema");
6403 drop(connection);
6404 std::fs::set_permissions(&database, std::fs::Permissions::from_mode(0o600))
6405 .expect("foreign database mode");
6406 let before = std::fs::read(&database).expect("foreign bytes before open");
6407
6408 assert!(matches!(
6409 WalletStore::open(&database),
6410 Err(StoreError::NotInitialized)
6411 ));
6412 assert_eq!(
6413 std::fs::read(&database).expect("foreign bytes after open"),
6414 before
6415 );
6416 for sidecar in sqlite_sidecar_paths(&database) {
6417 assert!(!sidecar.exists());
6418 }
6419 let connection = open_wallet_connection_read_only(&database).expect("inspect foreign DB");
6420 assert_eq!(
6421 connection
6422 .query_row::<u32, _, _>("PRAGMA user_version", [], |row| row.get(0))
6423 .expect("foreign schema version"),
6424 1
6425 );
6426 assert_eq!(
6427 connection
6428 .query_row::<String, _, _>("PRAGMA journal_mode", [], |row| row.get(0))
6429 .expect("foreign journal mode"),
6430 "delete"
6431 );
6432 }
6433
6434 #[cfg(unix)]
6435 #[test]
6436 fn unix_open_rejects_partial_v1_wallet_without_mutation() {
6437 use std::os::unix::fs::PermissionsExt as _;
6438
6439 let directory = unix_private_tempdir();
6440 let database = directory.path().join("partial-wallet.sqlite3");
6441 let connection = Connection::open(&database).expect("partial wallet database");
6442 connection.execute_batch(SCHEMA_V1).expect("schema v1");
6443 drop(connection);
6444 std::fs::set_permissions(&database, std::fs::Permissions::from_mode(0o600))
6445 .expect("partial wallet mode");
6446 let before = std::fs::read(&database).expect("partial wallet bytes before open");
6447
6448 assert!(matches!(
6449 WalletStore::open(&database),
6450 Err(StoreError::NotInitialized)
6451 ));
6452 assert_eq!(
6453 std::fs::read(&database).expect("partial wallet bytes after open"),
6454 before
6455 );
6456 for sidecar in sqlite_sidecar_paths(&database) {
6457 assert!(!sidecar.exists());
6458 }
6459 let connection = open_wallet_connection_read_only(&database).expect("inspect partial DB");
6460 assert_eq!(
6461 connection
6462 .query_row::<u32, _, _>("PRAGMA user_version", [], |row| row.get(0))
6463 .expect("partial schema version"),
6464 1
6465 );
6466 let has_v2_table: bool = connection
6467 .query_row(
6468 "SELECT EXISTS(
6469 SELECT 1 FROM sqlite_schema
6470 WHERE type='table' AND name='encrypted_entities'
6471 )",
6472 [],
6473 |row| row.get(0),
6474 )
6475 .expect("partial schema inspection");
6476 assert!(!has_v2_table);
6477 }
6478
6479 #[cfg(unix)]
6480 #[test]
6481 fn unix_open_recognizes_and_migrates_initialized_v1_wallet() {
6482 use std::os::unix::fs::PermissionsExt as _;
6483
6484 const PASSPHRASE: &str = "initialized-v1-passphrase";
6485 let source = WalletStore::create_in_memory(PASSPHRASE).expect("metadata source");
6486 let metadata = ["database_id", "kdf_salt", "kdf_config", "key_check"].map(|key| {
6487 (
6488 key,
6489 required_meta(&source.connection, key).expect("source metadata"),
6490 )
6491 });
6492
6493 let directory = unix_private_tempdir();
6494 let database = directory.path().join("legacy-wallet.sqlite3");
6495 let connection = Connection::open(&database).expect("legacy wallet database");
6496 connection.execute_batch(SCHEMA_V1).expect("schema v1");
6497 let transaction = connection
6498 .unchecked_transaction()
6499 .expect("metadata transaction");
6500 for (key, value) in metadata {
6501 set_meta(&transaction, key, &value).expect("legacy metadata");
6502 }
6503 transaction.commit().expect("commit legacy metadata");
6504 drop(connection);
6505 std::fs::set_permissions(&database, std::fs::Permissions::from_mode(0o600))
6506 .expect("legacy wallet mode");
6507
6508 let mut opened = WalletStore::open(&database).expect("recognized legacy wallet");
6509 assert!(opened.is_locked());
6510 assert_eq!(
6511 opened
6512 .connection
6513 .query_row::<u32, _, _>("PRAGMA user_version", [], |row| row.get(0))
6514 .expect("migrated schema version"),
6515 SCHEMA_VERSION
6516 );
6517 opened.unlock(PASSPHRASE).expect("unlock migrated wallet");
6518 }
6519
6520 #[cfg(unix)]
6521 #[test]
6522 fn unix_open_rejects_malformed_key_check_without_mutation() {
6523 let directory = unix_private_tempdir();
6524 let database = directory.path().join("malformed-key-check.sqlite3");
6525 let store = WalletStore::create_with_kdf(
6526 &database,
6527 "malformed-key-check-passphrase",
6528 KdfConfig::testing(),
6529 )
6530 .expect("create wallet fixture");
6531 let mut malformed = required_meta(&store.connection, "key_check").expect("key check");
6532 malformed.push(0);
6533 store
6534 .connection
6535 .execute(
6536 "UPDATE wallet_meta SET value=?1 WHERE key='key_check'",
6537 params![malformed],
6538 )
6539 .expect("write malformed key check");
6540 store
6541 .connection
6542 .execute_batch("PRAGMA wal_checkpoint(TRUNCATE); PRAGMA journal_mode=DELETE;")
6543 .expect("checkpoint malformed fixture");
6544 drop(store);
6545
6546 let before = std::fs::read(&database).expect("wallet bytes before rejected open");
6547 assert!(matches!(
6548 WalletStore::open(&database),
6549 Err(StoreError::CorruptMetadata)
6550 ));
6551 assert_eq!(
6552 std::fs::read(&database).expect("wallet bytes after rejected open"),
6553 before
6554 );
6555 for sidecar in sqlite_sidecar_paths(&database) {
6556 assert!(!sidecar.exists());
6557 }
6558 }
6559
6560 #[cfg(unix)]
6561 #[test]
6562 fn unix_wallet_database_hard_links_are_rejected() {
6563 use std::os::unix::fs::PermissionsExt as _;
6564
6565 let directory = unix_private_tempdir();
6566 std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700))
6567 .expect("private directory mode");
6568 let source = directory.path().join("source.sqlite3");
6569 let database = directory.path().join("wallet.sqlite3");
6570 std::fs::write(&source, []).expect("hard-link source");
6571 std::fs::set_permissions(&source, std::fs::Permissions::from_mode(0o600))
6572 .expect("hard-link source mode");
6573 std::fs::hard_link(&source, &database).expect("database hard link");
6574
6575 assert!(matches!(
6576 validate_wallet_location(&database, WalletPathRequirement::Existing),
6577 Err(StoreError::UnsafeFilesystemBoundary)
6578 ));
6579 assert!(matches!(
6580 validate_wallet_location(&database, WalletPathRequirement::Missing),
6581 Err(StoreError::UnsafeFilesystemBoundary)
6582 ));
6583 }
6584
6585 #[cfg(unix)]
6586 #[test]
6587 fn unix_create_atomically_sets_mode_and_reopens() {
6588 use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
6589
6590 let directory = unix_private_tempdir();
6591 std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700))
6592 .expect("private directory mode");
6593 let database = directory.path().join("wallet.sqlite3");
6594 let store = WalletStore::create_with_kdf(
6595 &database,
6596 "create-reopen-passphrase",
6597 KdfConfig::testing(),
6598 )
6599 .expect("create wallet database");
6600 let metadata = std::fs::symlink_metadata(&database).expect("created database metadata");
6601 assert!(metadata.file_type().is_file());
6602 assert_eq!(metadata.mode() & 0o7777, 0o600);
6603 assert_eq!(metadata.uid(), rustix::process::geteuid().as_raw());
6604 assert_eq!(metadata.nlink(), 1);
6605 drop(store);
6606
6607 let mut reopened = WalletStore::open(&database).expect("reopen wallet database");
6608 assert!(reopened.is_locked());
6609 reopened
6610 .unlock("create-reopen-passphrase")
6611 .expect("unlock reopened wallet database");
6612 }
6613
6614 #[test]
6615 fn secrets_require_unlock_and_ciphertext_does_not_contain_cleartext() {
6616 let mut store = WalletStore::create_in_memory("correct horse battery staple")
6617 .expect("create encrypted store");
6618 store
6619 .put_secret(
6620 b"seed",
6621 SecretKind::RecoverySeed,
6622 b"never persist me clear",
6623 1,
6624 )
6625 .expect("put secret");
6626 let raw: Vec<u8> = store
6627 .connection
6628 .query_row(
6629 "SELECT encrypted_value FROM secrets WHERE id=?1",
6630 params![b"seed".as_slice()],
6631 |row| row.get(0),
6632 )
6633 .expect("raw envelope");
6634 assert!(
6635 !raw.windows(b"never persist me clear".len())
6636 .any(|window| window == b"never persist me clear")
6637 );
6638 assert_eq!(
6639 store
6640 .get_secret(b"seed", SecretKind::RecoverySeed)
6641 .expect("decrypt")
6642 .expect("present")
6643 .as_slice(),
6644 b"never persist me clear"
6645 );
6646 store.lock();
6647 assert!(matches!(
6648 store.get_secret(b"seed", SecretKind::RecoverySeed),
6649 Err(StoreError::Locked)
6650 ));
6651 }
6652
6653 #[test]
6654 fn seed_and_initial_account_commit_together_or_not_at_all() {
6655 let mut store = WalletStore::create_in_memory("atomic bootstrap passphrase")
6656 .expect("create encrypted store");
6657 let seed_id = [41_u8; 16];
6658 let account_id = [42_u8; 32];
6659 let account = json!({"wallet": 41, "account": 42});
6660
6661 assert!(matches!(
6662 store.initialize_recovery_seed_and_wallet_account_with_hook(
6663 &seed_id,
6664 &[43_u8; 64],
6665 &account_id,
6666 &account,
6667 7,
6668 || Err(StoreError::CorruptMetadata),
6669 ),
6670 Err(StoreError::CorruptMetadata)
6671 ));
6672 assert!(
6673 store
6674 .get_secret(&seed_id, SecretKind::RecoverySeed)
6675 .expect("read rolled-back seed")
6676 .is_none()
6677 );
6678 assert!(
6679 store
6680 .wallet_account::<serde_json::Value>(&account_id)
6681 .expect("read rolled-back account")
6682 .is_none()
6683 );
6684
6685 let revision = store
6686 .initialize_recovery_seed_and_wallet_account(
6687 &seed_id,
6688 &[43_u8; 64],
6689 &account_id,
6690 &account,
6691 8,
6692 )
6693 .expect("atomic bootstrap");
6694 assert_eq!(revision, 1);
6695 assert_eq!(
6696 store
6697 .get_secret(&seed_id, SecretKind::RecoverySeed)
6698 .expect("read seed")
6699 .expect("seed present")
6700 .as_slice(),
6701 &[43_u8; 64]
6702 );
6703 let stored = store
6704 .wallet_account::<serde_json::Value>(&account_id)
6705 .expect("read account")
6706 .expect("account present");
6707 assert_eq!(stored.revision, 1);
6708 assert_eq!(stored.value, account);
6709 store
6710 .validate_single_recovery_seed(&seed_id)
6711 .expect("one exact authenticated recovery seed");
6712
6713 store
6714 .put_secret(&[44_u8; 16], SecretKind::RecoverySeed, &[45_u8; 64], 9)
6715 .expect("second seed fixture");
6716 assert!(matches!(
6717 store.validate_single_recovery_seed(&seed_id),
6718 Err(StoreError::BootstrapConflict)
6719 ));
6720 }
6721
6722 #[test]
6723 fn single_recovery_seed_validation_rejects_malformed_plaintext_length() {
6724 for (case, length) in [63_usize, 65].into_iter().enumerate() {
6725 let mut store = WalletStore::create_in_memory(&format!("seed length case {case}"))
6726 .expect("malformed seed store");
6727 let seed_id = [81_u8 + case as u8; 16];
6728 store
6729 .put_secret(&seed_id, SecretKind::RecoverySeed, &vec![82_u8; length], 1)
6730 .expect("malformed seed fixture");
6731 assert!(matches!(
6732 store.validate_single_recovery_seed(&seed_id),
6733 Err(StoreError::InvalidRecoverySeed)
6734 ));
6735 }
6736
6737 let mut initializer_store =
6738 WalletStore::create_in_memory("malformed initializer seed store")
6739 .expect("initializer store");
6740 assert!(matches!(
6741 initializer_store.initialize_recovery_seed_and_wallet_account(
6742 &[84_u8; 16],
6743 &[85_u8; RECOVERY_SEED_BYTES - 1],
6744 &[86_u8; 32],
6745 &json!({"account": 86}),
6746 1,
6747 ),
6748 Err(StoreError::InvalidRecoverySeed)
6749 ));
6750 assert!(
6751 initializer_store
6752 .get_secret(&[84_u8; 16], SecretKind::RecoverySeed)
6753 .expect("read rejected seed")
6754 .is_none()
6755 );
6756 assert!(
6757 initializer_store
6758 .wallet_account::<serde_json::Value>(&[86_u8; 32])
6759 .expect("read rejected account")
6760 .is_none()
6761 );
6762 }
6763
6764 #[test]
6765 fn seed_and_initial_account_reject_partial_or_duplicate_state() {
6766 let seed_id = [51_u8; 16];
6767 let account_id = [52_u8; 32];
6768 let account = json!({"wallet": 51, "account": 52});
6769
6770 let mut seed_only =
6771 WalletStore::create_in_memory("seed-only passphrase").expect("create seed-only store");
6772 seed_only
6773 .put_secret(&seed_id, SecretKind::RecoverySeed, &[53_u8; 64], 1)
6774 .expect("seed fixture");
6775 assert!(matches!(
6776 seed_only.initialize_recovery_seed_and_wallet_account(
6777 &seed_id,
6778 &[53_u8; 64],
6779 &account_id,
6780 &account,
6781 2,
6782 ),
6783 Err(StoreError::BootstrapConflict)
6784 ));
6785 assert!(
6786 seed_only
6787 .wallet_account::<serde_json::Value>(&account_id)
6788 .expect("read absent account")
6789 .is_none()
6790 );
6791
6792 let mut account_only = WalletStore::create_in_memory("account-only passphrase")
6793 .expect("create account-only store");
6794 account_only
6795 .save_wallet_account(&account_id, 0, &account, 1)
6796 .expect("account fixture");
6797 assert!(matches!(
6798 account_only.initialize_recovery_seed_and_wallet_account(
6799 &seed_id,
6800 &[53_u8; 64],
6801 &account_id,
6802 &account,
6803 2,
6804 ),
6805 Err(StoreError::StaleRevision {
6806 expected: 0,
6807 actual: 1,
6808 })
6809 ));
6810 assert!(
6811 account_only
6812 .get_secret(&seed_id, SecretKind::RecoverySeed)
6813 .expect("read absent seed")
6814 .is_none()
6815 );
6816
6817 let other_seed_id = [54_u8; 16];
6818 let other_account_id = [55_u8; 32];
6819 assert!(matches!(
6820 seed_only.initialize_recovery_seed_and_wallet_account(
6821 &other_seed_id,
6822 &[56_u8; 64],
6823 &other_account_id,
6824 &account,
6825 3,
6826 ),
6827 Err(StoreError::BootstrapConflict)
6828 ));
6829 assert!(
6830 seed_only
6831 .get_secret(&other_seed_id, SecretKind::RecoverySeed)
6832 .expect("read absent second seed")
6833 .is_none()
6834 );
6835 }
6836
6837 #[test]
6838 fn workflow_updates_are_compare_and_swap_and_persist_before_broadcast() {
6839 let mut store = WalletStore::create_in_memory("passphrase").expect("store");
6840 let id = WorkflowId::new([7; 16]);
6841 let revision = store
6842 .save_workflow(
6843 id,
6844 WorkflowKind::AtomicSwap,
6845 0,
6846 &json!({"state":"terms_frozen"}),
6847 true,
6848 5,
6849 )
6850 .expect("first revision");
6851 assert_eq!(revision, 1);
6852 assert!(matches!(
6853 store.save_workflow(id, WorkflowKind::AtomicSwap, 0, &json!({}), true, 6),
6854 Err(StoreError::StaleRevision { .. })
6855 ));
6856 let loaded: StoredWorkflow<serde_json::Value> =
6857 store.load_workflow(id).expect("load").expect("present");
6858 assert!(loaded.irreversible_broadcast_prepared);
6859 assert_eq!(loaded.revision, 1);
6860 let raw: Vec<u8> = store
6861 .connection
6862 .query_row(
6863 "SELECT state_json FROM workflows WHERE id=?1",
6864 params![id.as_bytes().as_slice()],
6865 |row| row.get(0),
6866 )
6867 .expect("encrypted workflow row");
6868 assert!(!raw.windows(12).any(|window| window == b"terms_frozen"));
6869 }
6870
6871 #[test]
6872 fn typed_entities_are_encrypted_revisioned_and_relocation_bound() {
6873 let mut store = WalletStore::create_in_memory("passphrase").expect("store");
6874 let id = [4_u8; 36];
6875 let revision = store
6876 .save_hns_utxo(&id, 0, &json!({"value":"42000000"}), 10)
6877 .expect("save entity");
6878 assert_eq!(revision, 1);
6879 let loaded: StoredEntity<serde_json::Value> =
6880 store.hns_utxo(&id).expect("load entity").expect("present");
6881 assert_eq!(loaded.revision, 1);
6882 assert_eq!(loaded.value["value"], "42000000");
6883 assert!(matches!(
6884 store.save_hns_utxo(&id, 0, &json!({"value":"1"}), 11),
6885 Err(StoreError::StaleRevision { .. })
6886 ));
6887
6888 let envelope: Vec<u8> = store
6889 .connection
6890 .query_row(
6891 "SELECT encrypted_value FROM encrypted_entities
6892 WHERE entity_kind='hns_utxo' AND record_id=?1",
6893 params![id.as_slice()],
6894 |row| row.get(0),
6895 )
6896 .expect("ciphertext");
6897 store
6898 .connection
6899 .execute(
6900 "INSERT INTO encrypted_entities(
6901 entity_kind, record_id, revision, encrypted_value, updated_at_unix
6902 ) VALUES('bitcoin_utxo', ?1, 1, ?2, 10)",
6903 params![[5_u8; 36].as_slice(), envelope],
6904 )
6905 .expect("relocate ciphertext");
6906 assert!(matches!(
6907 store.bitcoin_utxo::<serde_json::Value>(&[5_u8; 36]),
6908 Err(StoreError::Encryption)
6909 ));
6910 }
6911
6912 #[cfg(unix)]
6913 #[test]
6914 fn entity_read_snapshot_remains_coherent_across_another_connection_commit() {
6915 const PASSPHRASE: &str = "coherent entity snapshot";
6916 let directory = unix_private_tempdir();
6917 let database = directory.path().join("coherent-entity-snapshot.sqlite3");
6918 let id = b"snapshot/row".to_vec();
6919 let prefix = b"snapshot/";
6920 let mut writer = WalletStore::create_with_kdf(&database, PASSPHRASE, KdfConfig::testing())
6921 .expect("writer store");
6922 writer
6923 .save_shakescape_board_object(&id, 0, &json!({"generation": 1}), 10)
6924 .expect("initial row");
6925 let mut reader = WalletStore::open(&database).expect("reader store");
6926 reader.unlock(PASSPHRASE).expect("unlock reader");
6927
6928 reader
6929 .try_with_entity_read_snapshot(|snapshot| {
6930 let first: StoredEntity<serde_json::Value> = snapshot
6931 .load_entity(EntityKind::ShakescapeBoardObject, &id)?
6932 .expect("first snapshot row");
6933 assert_eq!(first.revision, 1);
6934 assert_eq!(first.value, json!({"generation": 1}));
6935
6936 writer
6937 .save_shakescape_board_object(&id, 1, &json!({"generation": 2}), 11)
6938 .expect("concurrent committed row");
6939
6940 let second: StoredEntity<serde_json::Value> = snapshot
6941 .load_entity(EntityKind::ShakescapeBoardObject, &id)?
6942 .expect("second snapshot row");
6943 let metadata = snapshot.list_untrusted_entity_metadata_by_id_prefix(
6944 EntityKind::ShakescapeBoardObject,
6945 prefix,
6946 1,
6947 )?;
6948 assert_eq!(second, first);
6949 assert_eq!(metadata.len(), 1);
6950 assert_eq!(metadata[0].revision, 1);
6951 assert_eq!(metadata[0].updated_at_unix, 10);
6952 Ok::<_, StoreError>(())
6953 })
6954 .expect("coherent snapshot");
6955
6956 let current: StoredEntity<serde_json::Value> = reader
6957 .shakescape_board_object(&id)
6958 .expect("current row lookup")
6959 .expect("current row");
6960 assert_eq!(current.revision, 2);
6961 assert_eq!(current.value, json!({"generation": 2}));
6962 }
6963
6964 #[test]
6965 fn entity_prefix_set_lease_allows_one_exact_namespace_batch() {
6966 let prefix = b"lease/success/";
6967 let stable_id = b"lease/success/stable".to_vec();
6968 let saved_id = b"lease/success/saved".to_vec();
6969 let mut store =
6970 WalletStore::create_in_memory("entity prefix lease success").expect("store");
6971 store
6972 .save_shakescape_board_object(&stable_id, 0, &json!({"stable": true}), 20)
6973 .expect("stable row");
6974 let lease = store
6975 .try_with_entity_read_snapshot(|snapshot| {
6976 snapshot.entity_prefix_set_lease(EntityKind::ShakescapeBoardObject, prefix, 2)
6977 })
6978 .expect("prefix lease");
6979 assert_eq!(lease.metadata().len(), 1);
6980
6981 store
6982 .apply_entity_batch_with_assertions_and_prefix_lease(
6983 EntityKind::ShakescapeBoardObject,
6984 &[EntityBatchSave {
6985 id: saved_id.clone(),
6986 expected_revision: 0,
6987 value: json!({"saved": true}),
6988 updated_at_unix: 21,
6989 }],
6990 &[],
6991 &[EntityRevisionAssertion {
6992 id: stable_id.clone(),
6993 expected_revision: 1,
6994 }],
6995 lease,
6996 )
6997 .expect("lease-gated batch");
6998 assert!(
6999 store
7000 .shakescape_board_object::<serde_json::Value>(&saved_id)
7001 .expect("saved lookup")
7002 .is_some()
7003 );
7004 assert_eq!(
7005 store
7006 .shakescape_board_object::<serde_json::Value>(&stable_id)
7007 .expect("stable lookup")
7008 .expect("stable row")
7009 .revision,
7010 1
7011 );
7012 }
7013
7014 #[test]
7015 fn entity_prefix_set_lease_rejects_ciphertext_aba_and_rolls_back_batch() {
7016 let prefix = b"lease/aba/";
7017 let substituted_id = b"lease/aba/substituted".to_vec();
7018 let retained_id = b"lease/aba/retained".to_vec();
7019 let planned_id = b"lease/aba/planned".to_vec();
7020 let mut store = WalletStore::create_in_memory("entity prefix lease aba").expect("store");
7021 store
7022 .save_shakescape_board_object(&substituted_id, 0, &json!({"value": "original"}), 50)
7023 .expect("original row");
7024 store
7025 .save_shakescape_board_object(&retained_id, 0, &json!({"retained": true}), 51)
7026 .expect("retained row");
7027
7028 let lease = store
7029 .try_with_entity_read_snapshot(|snapshot| {
7030 snapshot.entity_prefix_set_lease(EntityKind::ShakescapeBoardObject, prefix, 3)
7031 })
7032 .expect("prefix lease");
7033 let leased_metadata = lease.metadata().to_vec();
7034
7035 assert!(
7036 store
7037 .delete_shakescape_board_object(&substituted_id, 1)
7038 .expect("delete original row")
7039 );
7040 assert_eq!(
7041 store
7042 .save_shakescape_board_object(
7043 &substituted_id,
7044 0,
7045 &json!({"value": "substituted"}),
7046 50,
7047 )
7048 .expect("recreate substituted row"),
7049 1
7050 );
7051 assert_eq!(
7052 store
7053 .list_untrusted_entity_metadata_by_id_prefix(
7054 EntityKind::ShakescapeBoardObject,
7055 prefix,
7056 3,
7057 )
7058 .expect("current metadata"),
7059 leased_metadata,
7060 "the ABA must restore the exact public lease metadata"
7061 );
7062
7063 assert!(matches!(
7064 store.apply_entity_batch_with_assertions_and_prefix_lease(
7065 EntityKind::ShakescapeBoardObject,
7066 &[EntityBatchSave {
7067 id: planned_id.clone(),
7068 expected_revision: 0,
7069 value: json!({"must_not_commit": true}),
7070 updated_at_unix: 52,
7071 }],
7072 &[EntityBatchDelete {
7073 id: retained_id.clone(),
7074 expected_revision: 1,
7075 }],
7076 &[EntityRevisionAssertion {
7077 id: substituted_id.clone(),
7078 expected_revision: 1,
7079 }],
7080 lease,
7081 ),
7082 Err(StoreError::StaleEntitySet)
7083 ));
7084 assert!(
7085 store
7086 .shakescape_board_object::<serde_json::Value>(&planned_id)
7087 .expect("rolled-back save lookup")
7088 .is_none()
7089 );
7090 assert_eq!(
7091 store
7092 .shakescape_board_object::<serde_json::Value>(&retained_id)
7093 .expect("rolled-back delete lookup")
7094 .expect("retained row")
7095 .value,
7096 json!({"retained": true})
7097 );
7098 let substituted: StoredEntity<serde_json::Value> = store
7099 .shakescape_board_object(&substituted_id)
7100 .expect("substituted row lookup")
7101 .expect("substituted row");
7102 assert_eq!(substituted.revision, 1);
7103 assert_eq!(substituted.updated_at_unix, 50);
7104 assert_eq!(substituted.value, json!({"value": "substituted"}));
7105 }
7106
7107 #[test]
7108 fn entity_prefix_set_lease_rejects_oversized_ciphertext_before_fingerprinting() {
7109 let prefix = b"lease/oversized/";
7110 let id = b"lease/oversized/row".to_vec();
7111 let mut store =
7112 WalletStore::create_in_memory("entity prefix lease oversized").expect("store");
7113 store
7114 .save_shakescape_board_object(&id, 0, &json!({"valid": true}), 50)
7115 .expect("valid row");
7116 store
7117 .connection
7118 .execute(
7119 "UPDATE encrypted_entities
7120 SET encrypted_value=zeroblob(?1)
7121 WHERE entity_kind=?2 AND record_id=?3",
7122 params![
7123 i64::try_from(MAX_ENCRYPTED_RECORD_BYTES + 1)
7124 .expect("encrypted record bound fits SQLite"),
7125 EntityKind::ShakescapeBoardObject.label(),
7126 &id,
7127 ],
7128 )
7129 .expect("oversized ciphertext substitution");
7130
7131 assert!(matches!(
7132 store.try_with_entity_read_snapshot(|snapshot| {
7133 snapshot.entity_prefix_set_lease(EntityKind::ShakescapeBoardObject, prefix, 1)
7134 }),
7135 Err(StoreError::Encryption)
7136 ));
7137 }
7138
7139 #[cfg(unix)]
7140 #[test]
7141 fn cross_kind_guard_lease_rejects_account_aba_and_insertions() {
7142 const PASSPHRASE: &str = "cross-kind account guard";
7143 let directory = unix_private_tempdir();
7144 let database = directory.path().join("cross-kind-account-guard.sqlite3");
7145 let account_prefix = b"account/";
7146 let account_id = b"account/selected".to_vec();
7147 let duplicate_id = b"account/duplicate".to_vec();
7148 let board_prefix = b"board/";
7149 let planned_id = b"board/planned".to_vec();
7150 let mut writer = WalletStore::create_with_kdf(&database, PASSPHRASE, KdfConfig::testing())
7151 .expect("writer store");
7152 writer
7153 .save_entity(
7154 EntityKind::WalletAccount,
7155 &account_id,
7156 0,
7157 &json!({"generation": 1}),
7158 70,
7159 )
7160 .expect("initial account");
7161 let mut reader = WalletStore::open(&database).expect("reader store");
7162 reader.unlock(PASSPHRASE).expect("unlock reader");
7163
7164 let (refresh_lease, guard_lease, primary_lease) = reader
7165 .try_with_entity_read_snapshot(|snapshot| {
7166 Ok::<_, StoreError>((
7167 snapshot.entity_prefix_set_lease(
7168 EntityKind::WalletAccount,
7169 account_prefix,
7170 2,
7171 )?,
7172 snapshot.entity_prefix_set_lease(
7173 EntityKind::WalletAccount,
7174 account_prefix,
7175 2,
7176 )?,
7177 snapshot.entity_prefix_set_lease(
7178 EntityKind::ShakescapeBoardObject,
7179 board_prefix,
7180 1,
7181 )?,
7182 ))
7183 })
7184 .expect("coherent guard leases");
7185 assert!(
7186 writer
7187 .delete_entity(EntityKind::WalletAccount, &account_id, 1)
7188 .expect("delete selected account")
7189 );
7190 assert_eq!(
7191 writer
7192 .save_entity(
7193 EntityKind::WalletAccount,
7194 &account_id,
7195 0,
7196 &json!({"generation": 2}),
7197 70,
7198 )
7199 .expect("recreate selected account"),
7200 1
7201 );
7202
7203 assert!(matches!(
7204 reader.try_with_entity_read_snapshot(|snapshot| {
7205 snapshot.refresh_entity_prefix_set_lease(refresh_lease)
7206 }),
7207 Err(StoreError::StaleEntitySet)
7208 ));
7209 assert!(matches!(
7210 reader.apply_entity_batch_with_assertions_and_prefix_lease_guard(
7211 EntityKind::ShakescapeBoardObject,
7212 &[EntityBatchSave {
7213 id: planned_id.clone(),
7214 expected_revision: 0,
7215 value: json!({"must_not_commit": "aba"}),
7216 updated_at_unix: 71,
7217 }],
7218 &[],
7219 &[],
7220 primary_lease,
7221 guard_lease,
7222 ),
7223 Err(StoreError::StaleEntitySet)
7224 ));
7225 assert!(
7226 reader
7227 .shakescape_board_object::<serde_json::Value>(&planned_id)
7228 .expect("ABA rollback lookup")
7229 .is_none()
7230 );
7231
7232 let (guard_lease, primary_lease) = reader
7233 .try_with_entity_read_snapshot(|snapshot| {
7234 Ok::<_, StoreError>((
7235 snapshot.entity_prefix_set_lease(
7236 EntityKind::WalletAccount,
7237 account_prefix,
7238 2,
7239 )?,
7240 snapshot.entity_prefix_set_lease(
7241 EntityKind::ShakescapeBoardObject,
7242 board_prefix,
7243 1,
7244 )?,
7245 ))
7246 })
7247 .expect("insertion guard leases");
7248 writer
7249 .save_entity(
7250 EntityKind::WalletAccount,
7251 &duplicate_id,
7252 0,
7253 &json!({"duplicate": true}),
7254 72,
7255 )
7256 .expect("insert duplicate account");
7257 assert!(matches!(
7258 reader.apply_entity_batch_with_assertions_and_prefix_lease_guard(
7259 EntityKind::ShakescapeBoardObject,
7260 &[EntityBatchSave {
7261 id: planned_id.clone(),
7262 expected_revision: 0,
7263 value: json!({"must_not_commit": "insertion"}),
7264 updated_at_unix: 73,
7265 }],
7266 &[],
7267 &[],
7268 primary_lease,
7269 guard_lease,
7270 ),
7271 Err(StoreError::StaleEntitySet)
7272 ));
7273 assert!(
7274 reader
7275 .shakescape_board_object::<serde_json::Value>(&planned_id)
7276 .expect("insertion rollback lookup")
7277 .is_none()
7278 );
7279 }
7280
7281 #[cfg(unix)]
7282 #[test]
7283 fn entity_prefix_set_lease_rejects_insert_revision_and_capacity_races() {
7284 const PASSPHRASE: &str = "entity prefix lease races";
7285 let directory = unix_private_tempdir();
7286 let database = directory.path().join("entity-prefix-lease-races.sqlite3");
7287 let prefix = b"lease/race/";
7288 let stable_id = b"lease/race/stable".to_vec();
7289 let injected_id = b"lease/race/injected".to_vec();
7290 let overflow_id = b"lease/race/overflow".to_vec();
7291 let planned_id = b"lease/race/planned".to_vec();
7292 let mut store = WalletStore::create_with_kdf(&database, PASSPHRASE, KdfConfig::testing())
7293 .expect("leased store");
7294 store
7295 .save_shakescape_board_object(&stable_id, 0, &json!({"revision": 1}), 30)
7296 .expect("stable row");
7297 let mut concurrent = WalletStore::open(&database).expect("concurrent store");
7298 concurrent.unlock(PASSPHRASE).expect("unlock concurrent");
7299
7300 let insertion_lease = store
7301 .try_with_entity_read_snapshot(|snapshot| {
7302 snapshot.entity_prefix_set_lease(EntityKind::ShakescapeBoardObject, prefix, 4)
7303 })
7304 .expect("insertion lease");
7305 concurrent
7306 .save_shakescape_board_object(&injected_id, 0, &json!({"injected": true}), 31)
7307 .expect("concurrent insertion");
7308 assert!(matches!(
7309 store.apply_entity_batch_with_assertions_and_prefix_lease(
7310 EntityKind::ShakescapeBoardObject,
7311 &[EntityBatchSave {
7312 id: planned_id.clone(),
7313 expected_revision: 0,
7314 value: json!({"must_not_commit": true}),
7315 updated_at_unix: 32,
7316 }],
7317 &[],
7318 &[EntityRevisionAssertion {
7319 id: stable_id.clone(),
7320 expected_revision: 1,
7321 }],
7322 insertion_lease,
7323 ),
7324 Err(StoreError::StaleEntitySet)
7325 ));
7326 assert!(
7327 store
7328 .shakescape_board_object::<serde_json::Value>(&planned_id)
7329 .expect("rolled-back planned lookup")
7330 .is_none()
7331 );
7332
7333 let revision_lease = store
7334 .try_with_entity_read_snapshot(|snapshot| {
7335 snapshot.entity_prefix_set_lease(EntityKind::ShakescapeBoardObject, prefix, 4)
7336 })
7337 .expect("revision lease");
7338 concurrent
7339 .save_shakescape_board_object(&stable_id, 1, &json!({"revision": 2}), 33)
7340 .expect("concurrent revision");
7341 assert!(matches!(
7342 store.apply_entity_batch_with_assertions_and_prefix_lease::<serde_json::Value>(
7343 EntityKind::ShakescapeBoardObject,
7344 &[],
7345 &[],
7346 &[],
7347 revision_lease,
7348 ),
7349 Err(StoreError::StaleEntitySet)
7350 ));
7351
7352 let capacity_lease = store
7353 .try_with_entity_read_snapshot(|snapshot| {
7354 snapshot.entity_prefix_set_lease(EntityKind::ShakescapeBoardObject, prefix, 2)
7355 })
7356 .expect("capacity lease");
7357 concurrent
7358 .save_shakescape_board_object(&overflow_id, 0, &json!({"overflow": true}), 34)
7359 .expect("capacity-crossing insertion");
7360 assert!(matches!(
7361 store.apply_entity_batch_with_assertions_and_prefix_lease::<serde_json::Value>(
7362 EntityKind::ShakescapeBoardObject,
7363 &[],
7364 &[],
7365 &[],
7366 capacity_lease,
7367 ),
7368 Err(StoreError::StaleEntitySet)
7369 ));
7370 }
7371
7372 #[test]
7373 fn entity_prefix_set_lease_rejects_wrong_database_kind_prefix_and_capture_capacity() {
7374 let prefix = b"lease/shape/";
7375 let first_id = b"lease/shape/first".to_vec();
7376 let second_id = b"lease/shape/second".to_vec();
7377 let mut first = WalletStore::create_in_memory("entity prefix lease first").expect("first");
7378 let mut second =
7379 WalletStore::create_in_memory("entity prefix lease second").expect("second");
7380 first
7381 .save_shakescape_board_object(&first_id, 0, &json!({"first": true}), 40)
7382 .expect("first row");
7383 first
7384 .save_shakescape_board_object(&second_id, 0, &json!({"second": true}), 41)
7385 .expect("second row");
7386
7387 assert!(matches!(
7388 first.try_with_entity_read_snapshot(|snapshot| {
7389 snapshot.entity_prefix_set_lease(EntityKind::ShakescapeBoardObject, prefix, 1)
7390 }),
7391 Err(StoreError::ListCapacity)
7392 ));
7393
7394 let wrong_database = first
7395 .try_with_entity_read_snapshot(|snapshot| {
7396 snapshot.entity_prefix_set_lease(EntityKind::ShakescapeBoardObject, prefix, 2)
7397 })
7398 .expect("wrong-database lease");
7399 assert!(matches!(
7400 second.apply_entity_batch_with_assertions_and_prefix_lease::<serde_json::Value>(
7401 EntityKind::ShakescapeBoardObject,
7402 &[],
7403 &[],
7404 &[],
7405 wrong_database,
7406 ),
7407 Err(StoreError::InvalidEntityPrefixLease)
7408 ));
7409
7410 let wrong_kind = first
7411 .try_with_entity_read_snapshot(|snapshot| {
7412 snapshot.entity_prefix_set_lease(EntityKind::ShakescapeBoardObject, prefix, 2)
7413 })
7414 .expect("wrong-kind lease");
7415 assert!(matches!(
7416 first.apply_entity_batch_with_assertions_and_prefix_lease::<serde_json::Value>(
7417 EntityKind::HnsUtxo,
7418 &[],
7419 &[],
7420 &[],
7421 wrong_kind,
7422 ),
7423 Err(StoreError::InvalidEntityPrefixLease)
7424 ));
7425
7426 let wrong_prefix = first
7427 .try_with_entity_read_snapshot(|snapshot| {
7428 snapshot.entity_prefix_set_lease(EntityKind::ShakescapeBoardObject, prefix, 2)
7429 })
7430 .expect("wrong-prefix lease");
7431 assert!(matches!(
7432 first.apply_entity_batch_with_assertions_and_prefix_lease(
7433 EntityKind::ShakescapeBoardObject,
7434 &[EntityBatchSave {
7435 id: b"outside/leased/prefix".to_vec(),
7436 expected_revision: 0,
7437 value: json!({"outside": true}),
7438 updated_at_unix: 42,
7439 }],
7440 &[],
7441 &[],
7442 wrong_prefix,
7443 ),
7444 Err(StoreError::InvalidEntityPrefixLease)
7445 ));
7446 }
7447
7448 #[test]
7449 fn entity_revision_assertion_succeeds_without_mutating_asserted_entity() {
7450 let mut store = WalletStore::create_in_memory("entity assertion success").expect("store");
7451 let asserted_id = b"assertion/unchanged".to_vec();
7452 let deleted_id = b"assertion/deleted".to_vec();
7453 let saved_id = b"assertion/saved".to_vec();
7454 store
7455 .save_shakescape_board_object(&asserted_id, 0, &json!({"stable": true}), 11)
7456 .expect("asserted fixture");
7457 store
7458 .save_shakescape_board_object(&deleted_id, 0, &json!({"delete": true}), 12)
7459 .expect("delete fixture");
7460 let before: StoredEntity<serde_json::Value> = store
7461 .shakescape_board_object(&asserted_id)
7462 .expect("read asserted fixture")
7463 .expect("asserted fixture present");
7464
7465 store
7466 .apply_entity_batch_with_assertions(
7467 EntityKind::ShakescapeBoardObject,
7468 &[EntityBatchSave {
7469 id: saved_id.clone(),
7470 expected_revision: 0,
7471 value: json!({"saved": true}),
7472 updated_at_unix: 13,
7473 }],
7474 &[EntityBatchDelete {
7475 id: deleted_id.clone(),
7476 expected_revision: 1,
7477 }],
7478 &[EntityRevisionAssertion {
7479 id: asserted_id.clone(),
7480 expected_revision: 1,
7481 }],
7482 )
7483 .expect("assertion-gated batch");
7484
7485 let after: StoredEntity<serde_json::Value> = store
7486 .shakescape_board_object(&asserted_id)
7487 .expect("read asserted entity")
7488 .expect("asserted entity present");
7489 assert_eq!(after, before);
7490 assert!(
7491 store
7492 .shakescape_board_object::<serde_json::Value>(&saved_id)
7493 .expect("read saved entity")
7494 .is_some()
7495 );
7496 assert!(
7497 store
7498 .shakescape_board_object::<serde_json::Value>(&deleted_id)
7499 .expect("read deleted entity")
7500 .is_none()
7501 );
7502 }
7503
7504 #[test]
7505 fn entity_revision_assertion_failures_roll_back_every_write_and_delete() {
7506 for case in ["stale", "missing", "tampered"] {
7507 let mut store =
7508 WalletStore::create_in_memory(&format!("entity assertion {case}")).expect("store");
7509 let asserted_id = b"assertion/current".to_vec();
7510 let deleted_id = b"assertion/retained".to_vec();
7511 let saved_id = b"assertion/not-written".to_vec();
7512 store
7513 .save_shakescape_board_object(&asserted_id, 0, &json!({"current": true}), 20)
7514 .expect("asserted fixture");
7515 store
7516 .save_shakescape_board_object(&deleted_id, 0, &json!({"retained": true}), 21)
7517 .expect("delete fixture");
7518
7519 let assertion = match case {
7520 "stale" => EntityRevisionAssertion {
7521 id: asserted_id.clone(),
7522 expected_revision: 2,
7523 },
7524 "missing" => EntityRevisionAssertion {
7525 id: b"assertion/missing".to_vec(),
7526 expected_revision: 1,
7527 },
7528 "tampered" => {
7529 let mut ciphertext: Vec<u8> = store
7530 .connection
7531 .query_row(
7532 "SELECT encrypted_value FROM encrypted_entities
7533 WHERE entity_kind=?1 AND record_id=?2",
7534 params![EntityKind::ShakescapeBoardObject.label(), &asserted_id],
7535 |row| row.get(0),
7536 )
7537 .expect("asserted ciphertext");
7538 ciphertext[0] ^= 0x80;
7539 store
7540 .connection
7541 .execute(
7542 "UPDATE encrypted_entities SET encrypted_value=?1
7543 WHERE entity_kind=?2 AND record_id=?3",
7544 params![
7545 ciphertext,
7546 EntityKind::ShakescapeBoardObject.label(),
7547 &asserted_id
7548 ],
7549 )
7550 .expect("tamper asserted ciphertext");
7551 EntityRevisionAssertion {
7552 id: asserted_id.clone(),
7553 expected_revision: 1,
7554 }
7555 }
7556 _ => unreachable!(),
7557 };
7558 let result = store.apply_entity_batch_with_assertions(
7559 EntityKind::ShakescapeBoardObject,
7560 &[EntityBatchSave {
7561 id: saved_id.clone(),
7562 expected_revision: 0,
7563 value: json!({"must_not_commit": true}),
7564 updated_at_unix: 22,
7565 }],
7566 &[EntityBatchDelete {
7567 id: deleted_id.clone(),
7568 expected_revision: 1,
7569 }],
7570 &[assertion],
7571 );
7572 match case {
7573 "stale" | "missing" => {
7574 assert!(matches!(result, Err(StoreError::StaleRevision { .. })))
7575 }
7576 "tampered" => assert!(matches!(result, Err(StoreError::Encryption))),
7577 _ => unreachable!(),
7578 }
7579 assert!(
7580 store
7581 .shakescape_board_object::<serde_json::Value>(&saved_id)
7582 .expect("read rolled-back save")
7583 .is_none()
7584 );
7585 assert_eq!(
7586 store
7587 .shakescape_board_object::<serde_json::Value>(&deleted_id)
7588 .expect("read rolled-back delete")
7589 .expect("delete rolled back")
7590 .value,
7591 json!({"retained": true})
7592 );
7593 }
7594 }
7595
7596 #[test]
7597 fn entity_revision_assertions_reject_zero_duplicate_and_cross_operation_ids() {
7598 let mut store = WalletStore::create_in_memory("entity assertion shape").expect("store");
7599 let id = b"assertion/overlap".to_vec();
7600 store
7601 .save_shakescape_board_object(&id, 0, &json!({"present": true}), 30)
7602 .expect("fixture");
7603
7604 assert!(matches!(
7605 store.apply_entity_batch_with_assertions::<serde_json::Value>(
7606 EntityKind::ShakescapeBoardObject,
7607 &[],
7608 &[],
7609 &[EntityRevisionAssertion {
7610 id: id.clone(),
7611 expected_revision: 0,
7612 }],
7613 ),
7614 Err(StoreError::InvalidRevision)
7615 ));
7616 assert!(matches!(
7617 store.apply_entity_batch_with_assertions::<serde_json::Value>(
7618 EntityKind::ShakescapeBoardObject,
7619 &[],
7620 &[],
7621 &[
7622 EntityRevisionAssertion {
7623 id: id.clone(),
7624 expected_revision: 1,
7625 },
7626 EntityRevisionAssertion {
7627 id: id.clone(),
7628 expected_revision: 1,
7629 },
7630 ],
7631 ),
7632 Err(StoreError::DuplicateBatchEntity)
7633 ));
7634 assert!(matches!(
7635 store.apply_entity_batch_with_assertions(
7636 EntityKind::ShakescapeBoardObject,
7637 &[EntityBatchSave {
7638 id: id.clone(),
7639 expected_revision: 1,
7640 value: json!({"changed": true}),
7641 updated_at_unix: 31,
7642 }],
7643 &[],
7644 &[EntityRevisionAssertion {
7645 id: id.clone(),
7646 expected_revision: 1,
7647 }],
7648 ),
7649 Err(StoreError::DuplicateBatchEntity)
7650 ));
7651 assert!(matches!(
7652 store.apply_entity_batch_with_assertions(
7653 EntityKind::ShakescapeBoardObject,
7654 &[EntityBatchSave {
7655 id: id.clone(),
7656 expected_revision: 1,
7657 value: json!({"changed": true}),
7658 updated_at_unix: 31,
7659 }],
7660 &[EntityBatchDelete {
7661 id: id.clone(),
7662 expected_revision: 1,
7663 }],
7664 &[],
7665 ),
7666 Err(StoreError::DuplicateBatchEntity)
7667 ));
7668 assert!(matches!(
7669 store.apply_entity_batch_with_assertions::<serde_json::Value>(
7670 EntityKind::ShakescapeBoardObject,
7671 &[],
7672 &[EntityBatchDelete {
7673 id: id.clone(),
7674 expected_revision: 1,
7675 }],
7676 &[EntityRevisionAssertion {
7677 id,
7678 expected_revision: 1,
7679 }],
7680 ),
7681 Err(StoreError::DuplicateBatchEntity)
7682 ));
7683 }
7684
7685 #[test]
7686 fn entity_revision_assertion_capacity_counts_every_operation_class() {
7687 let saves = vec![EntityBatchSave {
7688 id: b"capacity/save".to_vec(),
7689 expected_revision: 0,
7690 value: (),
7691 updated_at_unix: 1,
7692 }];
7693 let deletes = vec![EntityBatchDelete {
7694 id: b"capacity/delete".to_vec(),
7695 expected_revision: 1,
7696 }];
7697 let assertions = (0..MAX_ENTITY_BATCH_OPERATIONS - 2)
7698 .map(|index| {
7699 let mut id = b"capacity/assert/".to_vec();
7700 id.extend_from_slice(&index.to_be_bytes());
7701 EntityRevisionAssertion {
7702 id,
7703 expected_revision: 1,
7704 }
7705 })
7706 .collect::<Vec<_>>();
7707 assert!(validate_entity_revision_assertions(&saves, &deletes, &assertions).is_ok());
7708 let mut over_capacity = assertions;
7709 over_capacity.push(EntityRevisionAssertion {
7710 id: b"capacity/one-too-many".to_vec(),
7711 expected_revision: 1,
7712 });
7713 assert!(matches!(
7714 validate_entity_revision_assertions(&saves, &deletes, &over_capacity),
7715 Err(StoreError::BatchCapacity)
7716 ));
7717 }
7718
7719 #[test]
7720 fn untrusted_prefix_metadata_is_bounded_sorted_locked_and_never_authority() {
7721 let prefix = b"metadata/binary/\0";
7722 let mut store = WalletStore::create_in_memory("metadata projection").expect("store");
7723 let mut ids = [vec![0xff], vec![0x00, 0xff], vec![0x7f]].map(|suffix| {
7724 let mut id = prefix.to_vec();
7725 id.extend_from_slice(&suffix);
7726 id
7727 });
7728 for (updated_at_unix, id) in ids.iter().rev().enumerate() {
7729 store
7730 .save_shakescape_board_object(
7731 id,
7732 0,
7733 &json!({"order": updated_at_unix}),
7734 u64::try_from(updated_at_unix + 1).expect("bounded timestamp"),
7735 )
7736 .expect("metadata fixture");
7737 }
7738 ids.sort();
7739 let metadata = store
7740 .list_untrusted_entity_metadata_by_id_prefix(
7741 EntityKind::ShakescapeBoardObject,
7742 prefix,
7743 ids.len(),
7744 )
7745 .expect("complete metadata");
7746 assert_eq!(
7747 metadata.iter().map(|entry| &entry.id).collect::<Vec<_>>(),
7748 ids.iter().collect::<Vec<_>>()
7749 );
7750 assert!(metadata.iter().all(|entry| entry.revision == 1));
7751 assert!(matches!(
7752 store.list_untrusted_entity_metadata_by_id_prefix(
7753 EntityKind::ShakescapeBoardObject,
7754 prefix,
7755 ids.len() - 1,
7756 ),
7757 Err(StoreError::ListCapacity)
7758 ));
7759 store.lock();
7760 assert!(matches!(
7761 store.list_untrusted_entity_metadata_by_id_prefix(
7762 EntityKind::ShakescapeBoardObject,
7763 prefix,
7764 ids.len(),
7765 ),
7766 Err(StoreError::Locked)
7767 ));
7768
7769 let mut tampered =
7770 WalletStore::create_in_memory("metadata is not authority").expect("store");
7771 let tampered_id = b"metadata/tampered/row".to_vec();
7772 tampered
7773 .save_shakescape_board_object(&tampered_id, 0, &json!({"authentic": true}), 41)
7774 .expect("tamper fixture");
7775 tampered
7776 .connection
7777 .execute(
7778 "UPDATE encrypted_entities
7779 SET revision=0, encrypted_value=?1
7780 WHERE entity_kind=?2 AND record_id=?3",
7781 params![
7782 vec![0x42_u8; NONCE_BYTES + TAG_BYTES + 1],
7783 EntityKind::ShakescapeBoardObject.label(),
7784 &tampered_id
7785 ],
7786 )
7787 .expect("malformed untrusted row");
7788 let projected = tampered
7789 .list_untrusted_entity_metadata_by_id_prefix(
7790 EntityKind::ShakescapeBoardObject,
7791 b"metadata/tampered/",
7792 1,
7793 )
7794 .expect("untrusted metadata remains enumerable");
7795 assert_eq!(projected.len(), 1);
7796 assert_eq!(projected[0].revision, 0);
7797 assert!(matches!(
7798 tampered.shakescape_board_object::<serde_json::Value>(&tampered_id),
7799 Err(StoreError::Encryption)
7800 ));
7801 }
7802
7803 #[test]
7804 fn pending_approval_is_encrypted_single_use_and_expiring() {
7805 let mut store = WalletStore::create_in_memory("passphrase").expect("store");
7806 let id = ApprovalId::new([9; 16]);
7807 store
7808 .put_pending_approval(id, "https://wallet.example", b"approval commitment", 10, 20)
7809 .expect("put approval");
7810 let approval = store
7811 .take_pending_approval(id, 10)
7812 .expect("take approval")
7813 .expect("live approval");
7814 assert_eq!(approval.request_json.as_slice(), b"approval commitment");
7815 assert!(
7816 store
7817 .take_pending_approval(id, 10)
7818 .expect("second take")
7819 .is_none()
7820 );
7821
7822 let expired = ApprovalId::new([8; 16]);
7823 store
7824 .put_pending_approval(expired, "https://wallet.example", b"expired", 20, 30)
7825 .expect("put expired approval");
7826 assert!(
7827 store
7828 .take_pending_approval(expired, 30)
7829 .expect("expire approval")
7830 .is_none()
7831 );
7832 }
7833
7834 #[test]
7835 fn replay_nonces_are_atomic_and_expiring() {
7836 let mut store = WalletStore::create_in_memory("passphrase").expect("store");
7837 store
7838 .consume_replay_nonce("https://example", 1, 10, 20)
7839 .expect("first use");
7840 assert!(matches!(
7841 store.consume_replay_nonce("https://example", 1, 11, 20),
7842 Err(StoreError::Replay)
7843 ));
7844 store
7845 .consume_replay_nonce("https://example", 1, 20, 30)
7846 .expect("expired nonce can be reused in a new bounded session");
7847 }
7848
7849 #[cfg(unix)]
7850 #[test]
7851 fn passphrase_change_rekeys_every_encrypted_namespace_and_survives_reopen() {
7852 let directory = unix_private_tempdir();
7853 let database = directory.path().join("rekey.sqlite3");
7854 let mut store = WalletStore::create_with_kdf(&database, "old secret", KdfConfig::testing())
7855 .expect("create");
7856 store
7857 .put_secret(b"secret", SecretKind::MetadataKey, b"private", 1)
7858 .expect("secret");
7859 store
7860 .save_wallet_account(b"account", 0, &json!({"balance": 7}), 2)
7861 .expect("entity");
7862 for index in 0..129 {
7863 let id = format!("account/{index:03}");
7864 store
7865 .save_wallet_account(id.as_bytes(), 0, &json!({"index": index}), 2)
7866 .expect("entity page fixture");
7867 }
7868 let workflow = WorkflowId::new([42; 16]);
7869 store
7870 .save_workflow(
7871 workflow,
7872 WorkflowKind::AtomicSwap,
7873 0,
7874 &json!({"tx": "signed"}),
7875 true,
7876 3,
7877 )
7878 .expect("workflow");
7879 store
7880 .put_provider_permission("https://example.test", 1, b"permission", 4)
7881 .expect("permission");
7882 let approval = ApprovalId::new([43; 16]);
7883 store
7884 .put_pending_approval(approval, "https://example.test", b"approval", 5, 100)
7885 .expect("approval");
7886 store
7887 .consume_replay_nonce("https://example.test", 8, 5, 100)
7888 .expect("nonce");
7889
7890 assert!(matches!(
7891 store.change_passphrase("incorrect", "new secret"),
7892 Err(StoreError::InvalidPassphrase)
7893 ));
7894 store
7895 .change_passphrase("old secret", "new secret")
7896 .expect("atomic rekey");
7897 store.lock();
7898 drop(store);
7899
7900 let mut store = WalletStore::open(&database).expect("reopen");
7901 assert!(matches!(
7902 store.unlock("old secret"),
7903 Err(StoreError::InvalidPassphrase)
7904 ));
7905 store.unlock("new secret").expect("new passphrase");
7906 assert_eq!(
7907 store
7908 .get_secret(b"secret", SecretKind::MetadataKey)
7909 .expect("secret")
7910 .expect("present")
7911 .as_slice(),
7912 b"private"
7913 );
7914 assert_eq!(
7915 store
7916 .wallet_account::<serde_json::Value>(b"account")
7917 .expect("entity")
7918 .expect("present")
7919 .value,
7920 json!({"balance": 7})
7921 );
7922 assert_eq!(
7923 store
7924 .wallet_account::<serde_json::Value>(b"account/128")
7925 .expect("last entity page")
7926 .expect("present")
7927 .value,
7928 json!({"index": 128})
7929 );
7930 assert_eq!(
7931 store
7932 .load_workflow::<serde_json::Value>(workflow)
7933 .expect("workflow")
7934 .expect("present")
7935 .state,
7936 json!({"tx": "signed"})
7937 );
7938 assert_eq!(
7939 store
7940 .provider_permission("https://example.test")
7941 .expect("permission")
7942 .expect("present")
7943 .1,
7944 b"permission"
7945 );
7946 assert_eq!(
7947 store
7948 .get_pending_approval(approval, 6)
7949 .expect("approval")
7950 .expect("present")
7951 .request_json
7952 .as_slice(),
7953 b"approval"
7954 );
7955 assert!(matches!(
7956 store.consume_replay_nonce("https://example.test", 8, 6, 100),
7957 Err(StoreError::Replay)
7958 ));
7959 assert!(store.change_passphrase("new secret", "new secret").is_err());
7960 }
7961
7962 #[test]
7963 fn passphrase_change_rolls_back_on_late_ciphertext_failure() {
7964 let mut store = WalletStore::create_in_memory("old secret").expect("create");
7965 store
7966 .put_secret(b"secret", SecretKind::MetadataKey, b"private", 1)
7967 .expect("secret");
7968 let workflow = WorkflowId::new([44; 16]);
7969 store
7970 .save_workflow(
7971 workflow,
7972 WorkflowKind::AtomicSwap,
7973 0,
7974 &json!({"tx": "signed"}),
7975 true,
7976 2,
7977 )
7978 .expect("workflow");
7979 store
7980 .connection
7981 .execute(
7982 "UPDATE workflows SET state_json=?1 WHERE id=?2",
7983 params![
7984 vec![0x42_u8; NONCE_BYTES + TAG_BYTES + 1],
7985 workflow.as_bytes().as_slice()
7986 ],
7987 )
7988 .expect("corrupt workflow");
7989 assert!(matches!(
7990 store.change_passphrase("old secret", "new secret"),
7991 Err(StoreError::Encryption)
7992 ));
7993 store.lock();
7994 store
7995 .unlock("old secret")
7996 .expect("old password still valid");
7997 assert_eq!(
7998 store
7999 .get_secret(b"secret", SecretKind::MetadataKey)
8000 .expect("secret")
8001 .expect("present")
8002 .as_slice(),
8003 b"private"
8004 );
8005 store.lock();
8006 assert!(matches!(
8007 store.unlock("new secret"),
8008 Err(StoreError::InvalidPassphrase)
8009 ));
8010 }
8011
8012 #[test]
8013 fn account_workflow_reservation_batch_is_all_or_nothing() {
8014 let mut store = WalletStore::create_in_memory("passphrase").expect("store");
8015 let account_id = vec![1_u8; 32];
8016 store
8017 .save_wallet_account(&account_id, 0, &json!({"next_change": 0}), 1)
8018 .expect("initial account");
8019 let workflow_id = WorkflowId::new([2; 16]);
8020 let account_save = EntityBatchSave {
8021 id: account_id.clone(),
8022 expected_revision: 1,
8023 value: json!({"next_change": 1}),
8024 updated_at_unix: 2,
8025 };
8026 let stale_reservation = EntityBatchSave {
8027 id: vec![3_u8; 36],
8028 expected_revision: 1,
8029 value: json!({"reserved": true}),
8030 updated_at_unix: 2,
8031 };
8032 assert!(matches!(
8033 store.save_workflow_with_account_and_entity_batch(
8034 workflow_id,
8035 WorkflowKind::HnsSend,
8036 0,
8037 &json!({"stage": "prepared"}),
8038 false,
8039 2,
8040 &account_save,
8041 EntityKind::InputReservation,
8042 &[stale_reservation],
8043 &[],
8044 ),
8045 Err(StoreError::StaleRevision { .. })
8046 ));
8047 let account: StoredEntity<serde_json::Value> = store
8048 .wallet_account(&account_id)
8049 .expect("load account")
8050 .expect("account present");
8051 assert_eq!(account.revision, 1);
8052 assert_eq!(account.value["next_change"], 0);
8053 assert!(
8054 store
8055 .load_workflow::<serde_json::Value>(workflow_id)
8056 .expect("load workflow")
8057 .is_none()
8058 );
8059
8060 let reservation = EntityBatchSave {
8061 id: vec![3_u8; 36],
8062 expected_revision: 0,
8063 value: json!({"reserved": true}),
8064 updated_at_unix: 2,
8065 };
8066 let revisions = store
8067 .save_workflow_with_account_and_entity_batch(
8068 workflow_id,
8069 WorkflowKind::HnsSend,
8070 0,
8071 &json!({"stage": "prepared"}),
8072 false,
8073 2,
8074 &account_save,
8075 EntityKind::InputReservation,
8076 &[reservation],
8077 &[],
8078 )
8079 .expect("atomic prepare");
8080 assert_eq!(revisions, (1, 2));
8081 assert_eq!(
8082 store
8083 .wallet_account::<serde_json::Value>(&account_id)
8084 .expect("load account")
8085 .expect("account present")
8086 .value["next_change"],
8087 1
8088 );
8089 assert!(
8090 store
8091 .load_workflow::<serde_json::Value>(workflow_id)
8092 .expect("load workflow")
8093 .is_some()
8094 );
8095 assert!(
8096 store
8097 .input_reservation::<serde_json::Value>(&[3_u8; 36])
8098 .expect("load reservation")
8099 .is_some()
8100 );
8101 }
8102
8103 #[cfg(target_os = "linux")]
8104 #[test]
8105 fn production_tranche_shakedex_terminal_workflow_and_reservation_delete_is_atomic() {
8106 use std::os::unix::fs::PermissionsExt as _;
8107
8108 const PASSPHRASE: &str = "production-tranche-terminal-release";
8109 let directory = unix_private_tempdir();
8110 std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700))
8111 .expect("private wallet directory permissions");
8112 let database = directory.path().join("wallet.sqlite3");
8113 let mut store = WalletStore::create_with_kdf(&database, PASSPHRASE, KdfConfig::testing())
8114 .expect("file-backed encrypted store");
8115 let workflow_id = WorkflowId::new([0x41; 16]);
8116 let source_id = vec![0x42; 36];
8117 let funding_id = vec![0x43; 36];
8118 store
8119 .save_workflow(
8120 workflow_id,
8121 WorkflowKind::ShakedexValue,
8122 0,
8123 &json!({"stage": "confirmed"}),
8124 true,
8125 10,
8126 )
8127 .expect("active workflow");
8128 store
8129 .save_input_reservation(&source_id, 0, &json!({"kind": "source"}), 10)
8130 .expect("source reservation");
8131 store
8132 .save_input_reservation(&funding_id, 0, &json!({"kind": "funding"}), 10)
8133 .expect("funding reservation");
8134
8135 let stale_deletes = [
8136 EntityBatchDelete {
8137 id: source_id.clone(),
8138 expected_revision: 2,
8139 },
8140 EntityBatchDelete {
8141 id: funding_id.clone(),
8142 expected_revision: 1,
8143 },
8144 ];
8145 assert!(matches!(
8146 store.save_workflow_with_entity_batch::<_, serde_json::Value>(
8147 workflow_id,
8148 WorkflowKind::ShakedexValue,
8149 1,
8150 &json!({"stage": "reservations_released"}),
8151 true,
8152 11,
8153 EntityKind::InputReservation,
8154 &[],
8155 &stale_deletes,
8156 ),
8157 Err(StoreError::StaleRevision { .. })
8158 ));
8159 let unchanged: StoredWorkflow<serde_json::Value> = store
8160 .load_workflow(workflow_id)
8161 .expect("load workflow")
8162 .expect("workflow present");
8163 assert_eq!(unchanged.revision, 1);
8164 assert_eq!(unchanged.state["stage"], "confirmed");
8165 assert!(
8166 store
8167 .input_reservation::<serde_json::Value>(&source_id)
8168 .expect("load source")
8169 .is_some()
8170 );
8171 assert!(
8172 store
8173 .input_reservation::<serde_json::Value>(&funding_id)
8174 .expect("load funding")
8175 .is_some()
8176 );
8177
8178 let deletes = [
8179 EntityBatchDelete {
8180 id: source_id.clone(),
8181 expected_revision: 1,
8182 },
8183 EntityBatchDelete {
8184 id: funding_id.clone(),
8185 expected_revision: 1,
8186 },
8187 ];
8188 assert_eq!(
8189 store
8190 .save_workflow_with_entity_batch::<_, serde_json::Value>(
8191 workflow_id,
8192 WorkflowKind::ShakedexValue,
8193 1,
8194 &json!({"stage": "reservations_released"}),
8195 true,
8196 12,
8197 EntityKind::InputReservation,
8198 &[],
8199 &deletes,
8200 )
8201 .expect("atomic terminal release"),
8202 2
8203 );
8204 assert_eq!(
8205 store
8206 .load_workflow::<serde_json::Value>(workflow_id)
8207 .expect("load released workflow")
8208 .expect("released workflow present")
8209 .state["stage"],
8210 "reservations_released"
8211 );
8212 assert!(
8213 store
8214 .input_reservation::<serde_json::Value>(&source_id)
8215 .expect("load released source")
8216 .is_none()
8217 );
8218 assert!(
8219 store
8220 .input_reservation::<serde_json::Value>(&funding_id)
8221 .expect("load released funding")
8222 .is_none()
8223 );
8224
8225 store.lock();
8226 assert!(store.is_locked());
8227 drop(store);
8228
8229 let mut reopened = WalletStore::open(&database).expect("open locked encrypted store");
8230 assert!(reopened.is_locked());
8231 assert!(matches!(
8232 reopened.load_workflow::<serde_json::Value>(workflow_id),
8233 Err(StoreError::Locked)
8234 ));
8235 reopened.unlock(PASSPHRASE).expect("unlock reopened store");
8236 let persisted: StoredWorkflow<serde_json::Value> = reopened
8237 .load_workflow(workflow_id)
8238 .expect("load persisted terminal workflow")
8239 .expect("terminal workflow present after reopen");
8240 assert_eq!(persisted.revision, 2);
8241 assert_eq!(persisted.state["stage"], "reservations_released");
8242 assert!(
8243 reopened
8244 .input_reservation::<serde_json::Value>(&source_id)
8245 .expect("load absent source after reopen")
8246 .is_none()
8247 );
8248 assert!(
8249 reopened
8250 .input_reservation::<serde_json::Value>(&funding_id)
8251 .expect("load absent funding after reopen")
8252 .is_none()
8253 );
8254 }
8255
8256 #[test]
8257 fn guarded_workflow_checkpoint_consumes_authority_once() {
8258 let mut store = WalletStore::create_in_memory("guarded-workflow").expect("store");
8259 let target_id = WorkflowId::new([0x51; 16]);
8260 let execution_id = WorkflowId::new([0x52; 16]);
8261 let authority_id = vec![0x53; 32];
8262 store
8263 .save_workflow(
8264 target_id,
8265 WorkflowKind::Refund,
8266 0,
8267 &json!({"stage": "prepared"}),
8268 false,
8269 10,
8270 )
8271 .expect("target workflow");
8272 store
8273 .save_workflow(
8274 execution_id,
8275 WorkflowKind::AtomicSwap,
8276 0,
8277 &json!({"stage": "authorized"}),
8278 true,
8279 10,
8280 )
8281 .expect("execution workflow");
8282 store
8283 .save_entity(
8284 EntityKind::SwapFundingAuthorization,
8285 &authority_id,
8286 0,
8287 &json!({"authorization": "exact"}),
8288 10,
8289 )
8290 .expect("funding authority");
8291
8292 let empty_saves: [EntityBatchSave<serde_json::Value>; 0] = [];
8293 assert_eq!(
8294 store
8295 .save_workflow_with_entity_batch_and_guards(
8296 target_id,
8297 WorkflowKind::Refund,
8298 1,
8299 &json!({"stage": "requires_rebroadcast"}),
8300 true,
8301 20,
8302 EntityKind::InputReservation,
8303 &empty_saves,
8304 &[],
8305 WorkflowRevisionAssertion {
8306 id: execution_id,
8307 kind: WorkflowKind::AtomicSwap,
8308 expected_revision: 1,
8309 },
8310 EntityKind::SwapFundingAuthorization,
8311 &EntityRevisionAssertion {
8312 id: authority_id.clone(),
8313 expected_revision: 1,
8314 },
8315 true,
8316 )
8317 .expect("guarded checkpoint"),
8318 2
8319 );
8320 let consumed = store
8321 .load_entity::<serde_json::Value>(EntityKind::SwapFundingAuthorization, &authority_id)
8322 .expect("load consumed authority")
8323 .expect("consumed authority retained");
8324 assert_eq!(consumed.revision, 2);
8325 assert_eq!(consumed.value["authorization"], "exact");
8326
8327 assert!(matches!(
8328 store.save_workflow_with_entity_batch_and_guards(
8329 target_id,
8330 WorkflowKind::Refund,
8331 2,
8332 &json!({"stage": "broadcast"}),
8333 true,
8334 21,
8335 EntityKind::InputReservation,
8336 &empty_saves,
8337 &[],
8338 WorkflowRevisionAssertion {
8339 id: execution_id,
8340 kind: WorkflowKind::AtomicSwap,
8341 expected_revision: 1,
8342 },
8343 EntityKind::SwapFundingAuthorization,
8344 &EntityRevisionAssertion {
8345 id: authority_id,
8346 expected_revision: 1,
8347 },
8348 true,
8349 ),
8350 Err(StoreError::StaleRevision {
8351 expected: 1,
8352 actual: 2
8353 })
8354 ));
8355 let target = store
8356 .load_workflow::<serde_json::Value>(target_id)
8357 .expect("load target")
8358 .expect("target retained");
8359 assert_eq!(target.revision, 2);
8360 assert_eq!(target.state["stage"], "requires_rebroadcast");
8361 }
8362
8363 #[test]
8364 fn guarded_entity_batch_rolls_back_when_authority_was_consumed() {
8365 let mut store = WalletStore::create_in_memory("guarded-entity-batch").expect("store");
8366 let execution_id = WorkflowId::new([0x61; 16]);
8367 let authority_id = vec![0x62; 32];
8368 let broadcast_id = vec![0x63; 32];
8369 store
8370 .save_workflow(
8371 execution_id,
8372 WorkflowKind::AtomicSwap,
8373 0,
8374 &json!({"stage": "authorized"}),
8375 true,
8376 10,
8377 )
8378 .expect("execution workflow");
8379 store
8380 .save_entity(
8381 EntityKind::SwapFundingAuthorization,
8382 &authority_id,
8383 0,
8384 &json!({"authorization": "exact"}),
8385 10,
8386 )
8387 .expect("funding authority");
8388 let first_save = [EntityBatchSave {
8389 id: broadcast_id.clone(),
8390 expected_revision: 0,
8391 value: json!({"raw_transaction": "first"}),
8392 updated_at_unix: 20,
8393 }];
8394 let workflow_guard = WorkflowRevisionAssertion {
8395 id: execution_id,
8396 kind: WorkflowKind::AtomicSwap,
8397 expected_revision: 1,
8398 };
8399 let entity_guard = EntityRevisionAssertion {
8400 id: authority_id.clone(),
8401 expected_revision: 1,
8402 };
8403 store
8404 .apply_entity_batch_with_workflow_guard_and_consumed_entity(
8405 EntityKind::BitcoinTransaction,
8406 &first_save,
8407 &[],
8408 workflow_guard,
8409 EntityKind::SwapFundingAuthorization,
8410 &entity_guard,
8411 20,
8412 )
8413 .expect("guarded broadcast persistence");
8414
8415 let replacement = [EntityBatchSave {
8416 id: broadcast_id.clone(),
8417 expected_revision: 1,
8418 value: json!({"raw_transaction": "replacement"}),
8419 updated_at_unix: 21,
8420 }];
8421 assert!(matches!(
8422 store.apply_entity_batch_with_workflow_guard_and_consumed_entity(
8423 EntityKind::BitcoinTransaction,
8424 &replacement,
8425 &[],
8426 workflow_guard,
8427 EntityKind::SwapFundingAuthorization,
8428 &entity_guard,
8429 21,
8430 ),
8431 Err(StoreError::StaleRevision {
8432 expected: 1,
8433 actual: 2
8434 })
8435 ));
8436 let broadcast = store
8437 .load_entity::<serde_json::Value>(EntityKind::BitcoinTransaction, &broadcast_id)
8438 .expect("load broadcast")
8439 .expect("broadcast retained");
8440 assert_eq!(broadcast.revision, 1);
8441 assert_eq!(broadcast.value["raw_transaction"], "first");
8442 assert_eq!(
8443 store
8444 .load_entity::<serde_json::Value>(
8445 EntityKind::SwapFundingAuthorization,
8446 &authority_id,
8447 )
8448 .expect("load authority")
8449 .expect("authority tombstone")
8450 .revision,
8451 2
8452 );
8453 }
8454
8455 #[test]
8456 fn passphrases_are_bounded_at_the_store_boundary() {
8457 assert!(matches!(
8458 WalletStore::create_in_memory(""),
8459 Err(StoreError::InvalidPassphrase)
8460 ));
8461 let oversized = "x".repeat(MAX_PASSPHRASE_BYTES + 1);
8462 assert!(matches!(
8463 WalletStore::create_in_memory(&oversized),
8464 Err(StoreError::InvalidPassphrase)
8465 ));
8466 let mut store = WalletStore::create_in_memory("passphrase").expect("store");
8467 store.lock();
8468 assert!(matches!(
8469 store.unlock(&oversized),
8470 Err(StoreError::InvalidPassphrase)
8471 ));
8472 }
8473}