1#![doc = "Private wallet service composition without browser-engine policy."]
2#![forbid(unsafe_code)]
3
4mod native_read_bootstrap;
5mod native_read_profile;
6mod native_value_runtime;
7
8use std::collections::{BTreeMap, BTreeSet, VecDeque};
9
10use hns_wallet_ffi::{
11 APPROVAL_SCHEMA_VERSION, AccountSummary, ApprovalPrompt, ApprovalSummary, HnsNameDisclosure,
12 HostAuthorityFacts, HostFrame, MAX_HNS_NAME_BYTES, MAX_HNS_NAME_DISCLOSURES,
13 MAX_PROVIDER_RESULT_BYTES, MAX_PUBLIC_STRING_BYTES, ModuleApprovalAction,
14 PROVIDER_SCHEMA_VERSION, ProviderBinding, ProviderCapabilitySnapshot, ProviderEventEnvelope,
15 ProviderEventPayload, ProviderNamespace, ServiceCapability, ServiceErrorCode, ServiceFailure,
16 ServiceFrame, ServiceHello, ServiceLimits, ServiceRequest, ServiceResponse, SessionEnvelope,
17 WALLET_ABI_VERSION, WalletAuthorityContextRequest, WalletHandshakeNetwork,
18 WalletHnsAuthorityContext, WalletRequest, WalletResponse, WalletRuntimeStatus,
19 encode_service_frame,
20};
21use hns_wallet_hns::{
22 HnsAccountReadRuntime, HnsAccountReadSnapshot, HnsBackend, HnsClock,
23 HnsExistingAccountSelector, HnsNetwork, HnsNodeRpcBackend, HnsNodeRpcConfig,
24 HnsPersistedRecoveryReadOnlyRuntime, HnsRuntimeConfig, HnsWalletError, KnownName,
25 MAX_HISTORY_RESULTS, NameOwnershipStatus, NameResourceStatus, SystemClock as HnsSystemClock,
26};
27use hns_wallet_provider::{
28 ApprovedCall, HostAuthorityRegistration, Origin, PROVIDER_API_VERSION, PendingApproval,
29 PermissionSnapshot, ProviderAction, ProviderCore, ProviderError, ProviderMethod,
30 ProviderStateStore, SelectedNamespace,
31};
32use hns_wallet_store::{SharedWalletStore, StoreError};
33use hns_wallet_types::{
34 Amount, ApprovalId, ApprovalKind, HostAuthorityHandleId, HostSessionId, LocalTransactionStatus,
35 ModuleId, PermissionCapability, ProviderApprovalId, ProviderRequestId, ReceiveTarget,
36 TransactionSummary, WalletAsset, WalletServiceSessionId, WalletSessionId,
37};
38use serde_json::{Value, json};
39use thiserror::Error;
40
41pub use native_read_bootstrap::{
42 NativeHnsReadBootstrapError, NativeHnsReadBootstrapPassphrase, NativeHnsReadProfileFence,
43 ProfileBackedNativeHnsReadRuntime, RecoveryProfileBackedNativeHnsReadRuntime,
44};
45pub use native_read_profile::{
46 LoadedNativeHnsReadProfile, NATIVE_HNS_READ_PROFILE_ID, NATIVE_HNS_READ_PROFILE_SCHEMA_VERSION,
47 NativeHnsReadProfile, NativeHnsReadProfileError, NativeHnsReadProfileMetadata,
48 NativeHnsReadProfileState, StoredNativeHnsReadProfile, load_native_hns_read_profile,
49 provision_native_hns_read_profile, revoke_native_hns_read_profile,
50};
51pub use native_value_runtime::{
52 NATIVE_HNS_SEND_PRE_BROADCAST_RETRY_MESSAGE, NativeHnsFinalizeNotice,
53 NativeHnsFinalizeNoticePhase, NativeHnsValueSnapshot, PersistentHnsValueConfig,
54 PersistentHnsValueRuntime, PersistentShakedexConfig, PersistentShakescapeTransport,
55 TRUSTED_NATIVE_HNS_VALUE_ORIGIN, TrustedNativeHnsValueAction,
56};
57
58pub const MAX_SEEN_REQUEST_IDS: usize = 4_096;
59pub const MAX_SERVICE_PENDING_APPROVALS: usize = 128;
60pub const MAX_PROVIDER_HNS_READ_ITEMS: usize = 128;
61pub const MAX_JAVASCRIPT_SAFE_INTEGER: u64 = 9_007_199_254_740_991;
62
63#[derive(Clone, Debug, Eq, PartialEq)]
68pub struct NativeHnsNameSummary {
69 pub name: String,
70 pub name_hash: String,
71 pub proof_height: u64,
72 pub resource_status: NativeHnsNameResourceStatus,
73 pub ownership_status: NativeHnsNameOwnershipStatus,
74 pub registered: Option<bool>,
75 pub expired: Option<bool>,
76 pub canonical_state: Option<NativeHnsNameStateSummary>,
77 pub raw_resource: Option<Vec<u8>>,
78}
79
80#[derive(Clone, Debug, Eq, PartialEq)]
81pub struct NativeHnsNameStateSummary {
82 pub value: u64,
83 pub highest: u64,
84 pub start_height: u32,
85 pub renewal_height: u32,
86 pub transfer_height: u32,
87 pub revoked_height: u32,
88 pub claimed_height: u32,
89 pub renewals: u32,
90 pub weak: bool,
91}
92
93#[derive(Clone, Copy, Debug, Eq, PartialEq)]
94pub enum NativeHnsNameResourceStatus {
95 UnavailableCanonicalBinding,
96 NoCurrentState,
97 Empty,
98 CanonicalDecoded,
99 CanonicalOpaque,
100}
101
102#[derive(Clone, Copy, Debug, Eq, PartialEq)]
103pub enum NativeHnsNameOwnershipStatus {
104 WatchOnlyCanonicalStateDecoderUnavailable,
105 WatchOnlyOwnerTransactionUnavailable,
106 WalletContextUnavailable,
107 NoCurrentOwner,
108 NotWalletOwned,
109 WalletOwned,
110 IncomingTransfer,
111 OutgoingTransfer,
112}
113
114type HnsReadPermissionExtension = (
115 BTreeSet<PermissionCapability>,
116 BTreeSet<hns_wallet_types::AccountId>,
117 BTreeSet<[u8; 32]>,
118 Option<u64>,
119);
120
121pub trait ServiceRuntime {
125 fn capabilities(&self) -> BTreeSet<ServiceCapability>;
126
127 fn admit_service_request(&self, _: &ServiceRequest) -> Result<(), ServiceFailure> {
133 Ok(())
134 }
135
136 fn supports_provider_method(&self, method: ProviderMethod) -> bool;
137
138 fn prepare_approval(
139 &mut self,
140 approval: &PendingApproval,
141 ) -> Result<ApprovalSummary, ServiceFailure>;
142
143 fn prepare_trusted_hns_value_approval(
148 &mut self,
149 _: ApprovalId,
150 _: ApprovalKind,
151 _: &ApprovedCall,
152 _: u64,
153 ) -> Result<ApprovalSummary, ServiceFailure> {
154 Err(ServiceFailure::unsupported(
155 ServiceCapability::HnsValueOperationsV1,
156 ))
157 }
158
159 fn prepare_hns_account_grant(
163 &mut self,
164 _: &ApprovedCall,
165 ) -> Result<AccountSummary, ServiceFailure> {
166 Err(ServiceFailure::unsupported(
167 ServiceCapability::ProviderDispatch,
168 ))
169 }
170
171 fn selected_hns_account(&self) -> Result<AccountSummary, ServiceFailure> {
175 Err(ServiceFailure::unsupported(
176 ServiceCapability::ProviderDispatch,
177 ))
178 }
179
180 fn current_hns_names(&mut self) -> Result<Vec<KnownName>, ServiceFailure> {
184 Err(ServiceFailure::unsupported(
185 ServiceCapability::ProviderDispatch,
186 ))
187 }
188
189 fn execute_hns_name_read(
193 &mut self,
194 _: ApprovedCall,
195 _: &BTreeSet<[u8; 32]>,
196 ) -> Result<Value, ServiceFailure> {
197 Err(ServiceFailure::unsupported(
198 ServiceCapability::ProviderDispatch,
199 ))
200 }
201
202 fn execute_provider(&mut self, call: ApprovedCall) -> Result<Value, ServiceFailure>;
203
204 fn execute_approved_provider(
210 &mut self,
211 call: ApprovedCall,
212 _: ApprovalId,
213 _: u64,
214 ) -> Result<Value, ServiceFailure> {
215 self.execute_provider(call)
216 }
217
218 fn lock_wallet(&mut self) -> Result<(), ServiceFailure>;
219
220 fn execute_wallet(&mut self, request: WalletRequest) -> Result<WalletResponse, ServiceFailure>;
221
222 fn execute_wallet_authority_context(
226 &mut self,
227 _: WalletAuthorityContextRequest,
228 ) -> Result<WalletHnsAuthorityContext, ServiceFailure> {
229 Err(ServiceFailure::unsupported(
230 ServiceCapability::HnsWalletAuthorityContextV1,
231 ))
232 }
233}
234
235#[derive(Default)]
236pub struct UnavailableRuntime;
237
238impl ServiceRuntime for UnavailableRuntime {
239 fn capabilities(&self) -> BTreeSet<ServiceCapability> {
240 BTreeSet::new()
241 }
242
243 fn supports_provider_method(&self, _: ProviderMethod) -> bool {
244 false
245 }
246
247 fn prepare_approval(&mut self, _: &PendingApproval) -> Result<ApprovalSummary, ServiceFailure> {
248 Err(ServiceFailure::unsupported(
249 ServiceCapability::ProviderDispatch,
250 ))
251 }
252
253 fn execute_provider(&mut self, _: ApprovedCall) -> Result<Value, ServiceFailure> {
254 Err(ServiceFailure::unsupported(
255 ServiceCapability::ProviderDispatch,
256 ))
257 }
258
259 fn lock_wallet(&mut self) -> Result<(), ServiceFailure> {
260 Err(ServiceFailure::unsupported(
261 ServiceCapability::WalletOperations,
262 ))
263 }
264
265 fn execute_wallet(&mut self, _: WalletRequest) -> Result<WalletResponse, ServiceFailure> {
266 Err(ServiceFailure::unsupported(
267 ServiceCapability::WalletOperations,
268 ))
269 }
270}
271
272pub struct PersistentControlRuntime {
277 store: SharedWalletStore,
278}
279
280impl PersistentControlRuntime {
281 fn new(store: SharedWalletStore) -> Self {
282 Self { store }
283 }
284
285 fn status(&self) -> Result<WalletRuntimeStatus, ServiceFailure> {
286 Ok(WalletRuntimeStatus {
287 locked: self.store.is_locked().map_err(persistent_store_failure)?,
288 active_wallet: None,
289 enabled_modules: BTreeSet::new(),
290 mainnet_settlement_enabled: false,
291 })
292 }
293}
294
295impl ServiceRuntime for PersistentControlRuntime {
296 fn capabilities(&self) -> BTreeSet<ServiceCapability> {
297 BTreeSet::from([
298 ServiceCapability::WalletOperations,
299 ServiceCapability::ProviderDispatch,
300 ])
301 }
302
303 fn supports_provider_method(&self, method: ProviderMethod) -> bool {
304 method == ProviderMethod::WalletGetStatus
305 }
306
307 fn prepare_approval(&mut self, _: &PendingApproval) -> Result<ApprovalSummary, ServiceFailure> {
308 Err(ServiceFailure::unsupported(
309 ServiceCapability::ProviderDispatch,
310 ))
311 }
312
313 fn execute_provider(&mut self, call: ApprovedCall) -> Result<Value, ServiceFailure> {
314 if call.method != ProviderMethod::WalletGetStatus {
315 return Err(ServiceFailure::unsupported(
316 ServiceCapability::ProviderDispatch,
317 ));
318 }
319 validate_empty_params(&call.params)?;
320 serde_json::to_value(self.status()?)
321 .map_err(|_| invalid_request("wallet status encoding failed"))
322 }
323
324 fn lock_wallet(&mut self) -> Result<(), ServiceFailure> {
325 self.store.lock().map_err(persistent_store_failure)
326 }
327
328 fn execute_wallet(&mut self, request: WalletRequest) -> Result<WalletResponse, ServiceFailure> {
329 match request {
330 WalletRequest::Status => Ok(WalletResponse::Status {
331 status: self.status()?,
332 }),
333 WalletRequest::Unlock { passphrase } => {
334 self.store
335 .unlock(passphrase.expose_secret())
336 .map_err(persistent_store_failure)?;
337 Ok(WalletResponse::Unlocked)
338 }
339 WalletRequest::Lock => {
340 self.lock_wallet()?;
341 Ok(WalletResponse::Locked)
342 }
343 WalletRequest::CreateWallet { .. }
344 | WalletRequest::RestoreWallet { .. }
345 | WalletRequest::ListAccounts
346 | WalletRequest::Balance { .. }
347 | WalletRequest::ReceiveTarget { .. }
348 | WalletRequest::TransactionHistory { .. }
349 | WalletRequest::ModuleStatus { .. }
350 | WalletRequest::WorkflowStatus { .. } => Err(ServiceFailure::unsupported(
351 ServiceCapability::WalletOperations,
352 )),
353 }
354 }
355}
356
357pub struct PersistentHnsAccountConfig {
362 pub selector: HnsExistingAccountSelector,
363 pub account_label: String,
364}
365
366pub struct PersistentHnsAccountRuntime {
371 store: SharedWalletStore,
372 selector: HnsExistingAccountSelector,
373 account_label: String,
374}
375
376impl PersistentHnsAccountRuntime {
377 fn new(store: SharedWalletStore, config: PersistentHnsAccountConfig) -> Self {
378 Self {
379 store,
380 selector: config.selector,
381 account_label: config.account_label,
382 }
383 }
384
385 fn status(&self) -> Result<WalletRuntimeStatus, ServiceFailure> {
386 let locked = self.store.is_locked().map_err(persistent_store_failure)?;
387 let active_wallet = if locked {
388 None
389 } else {
390 Some(
391 self.selector
392 .selected_account()
393 .map_err(hns_runtime_failure)?
394 .config
395 .wallet_id,
396 )
397 };
398 Ok(WalletRuntimeStatus {
399 locked,
400 active_wallet,
401 enabled_modules: BTreeSet::new(),
402 mainnet_settlement_enabled: false,
403 })
404 }
405
406 fn exact_account(&self) -> Result<AccountSummary, ServiceFailure> {
407 if self.store.is_locked().map_err(persistent_store_failure)? {
408 return Err(wallet_locked());
409 }
410 let selected = self
411 .selector
412 .selected_account()
413 .map_err(hns_runtime_failure)?;
414 let account = AccountSummary {
415 account_id: selected.config.account_id,
416 module: ModuleId::Handshake,
417 label: self.account_label.clone(),
418 receive_display: None,
419 };
420 validate_hns_account_summary(&account)
421 .map_err(|_| hns_runtime_failure(HnsWalletError::InvalidEvidence))?;
422 Ok(account)
423 }
424
425 fn unlock(&self, passphrase: &str) -> Result<(), ServiceFailure> {
426 self.store
427 .unlock(passphrase)
428 .map_err(persistent_store_failure)?;
429 if let Err(error) = self.exact_account() {
430 self.store.lock().map_err(persistent_store_failure)?;
431 return Err(error);
432 }
433 Ok(())
434 }
435}
436
437impl ServiceRuntime for PersistentHnsAccountRuntime {
438 fn capabilities(&self) -> BTreeSet<ServiceCapability> {
439 BTreeSet::from([
440 ServiceCapability::WalletOperations,
441 ServiceCapability::ProviderDispatch,
442 ])
443 }
444
445 fn supports_provider_method(&self, method: ProviderMethod) -> bool {
446 matches!(
447 method,
448 ProviderMethod::WalletGetStatus | ProviderMethod::HnsRequestAccounts
449 )
450 }
451
452 fn prepare_approval(&mut self, _: &PendingApproval) -> Result<ApprovalSummary, ServiceFailure> {
453 Err(ServiceFailure::unsupported(
454 ServiceCapability::ProviderDispatch,
455 ))
456 }
457
458 fn prepare_hns_account_grant(
459 &mut self,
460 _: &ApprovedCall,
461 ) -> Result<AccountSummary, ServiceFailure> {
462 self.exact_account()
463 }
464
465 fn selected_hns_account(&self) -> Result<AccountSummary, ServiceFailure> {
466 self.exact_account()
467 }
468
469 fn execute_provider(&mut self, call: ApprovedCall) -> Result<Value, ServiceFailure> {
470 if call.method != ProviderMethod::WalletGetStatus {
471 return Err(ServiceFailure::unsupported(
472 ServiceCapability::ProviderDispatch,
473 ));
474 }
475 validate_empty_params(&call.params)?;
476 serde_json::to_value(self.status()?)
477 .map_err(|_| invalid_request("wallet status encoding failed"))
478 }
479
480 fn lock_wallet(&mut self) -> Result<(), ServiceFailure> {
481 self.store.lock().map_err(persistent_store_failure)
482 }
483
484 fn execute_wallet(&mut self, request: WalletRequest) -> Result<WalletResponse, ServiceFailure> {
485 match request {
486 WalletRequest::Status => Ok(WalletResponse::Status {
487 status: self.status()?,
488 }),
489 WalletRequest::Unlock { passphrase } => {
490 self.unlock(passphrase.expose_secret())?;
491 Ok(WalletResponse::Unlocked)
492 }
493 WalletRequest::Lock => {
494 self.lock_wallet()?;
495 Ok(WalletResponse::Locked)
496 }
497 WalletRequest::ListAccounts => Ok(WalletResponse::Accounts {
498 accounts: vec![self.exact_account()?],
499 }),
500 WalletRequest::CreateWallet { .. }
501 | WalletRequest::RestoreWallet { .. }
502 | WalletRequest::Balance { .. }
503 | WalletRequest::ReceiveTarget { .. }
504 | WalletRequest::TransactionHistory { .. }
505 | WalletRequest::ModuleStatus { .. }
506 | WalletRequest::WorkflowStatus { .. } => Err(ServiceFailure::unsupported(
507 ServiceCapability::WalletOperations,
508 )),
509 }
510 }
511}
512
513pub struct PersistentHnsReadConfig<B, C> {
517 pub runtime: HnsAccountReadRuntime<B, C>,
518 pub account_label: String,
519}
520
521pub struct PersistentNativeHnsReadConfig {
530 pub account: HnsRuntimeConfig,
531 pub node_rpc: HnsNodeRpcConfig,
532 pub account_label: String,
533}
534
535pub type PersistentNativeHnsReadRuntime =
539 PersistentHnsReadRuntime<HnsNodeRpcBackend, HnsSystemClock>;
540
541type PersistentNativeRecoveryReadOnlyRuntime =
542 PersistentRecoveryReadOnlyHnsRuntime<HnsNodeRpcBackend, HnsSystemClock>;
543
544pub struct PersistentHnsReadRuntime<B, C> {
549 store: SharedWalletStore,
550 runtime: HnsAccountReadRuntime<B, C>,
551 account_label: String,
552}
553
554impl<B: HnsBackend, C: HnsClock> PersistentHnsReadRuntime<B, C> {
555 fn new(store: SharedWalletStore, config: PersistentHnsReadConfig<B, C>) -> Self {
556 Self {
557 store,
558 runtime: config.runtime,
559 account_label: config.account_label,
560 }
561 }
562
563 fn status(&self) -> Result<WalletRuntimeStatus, ServiceFailure> {
564 let locked = self.store.is_locked().map_err(persistent_store_failure)?;
565 let active_wallet = if locked {
566 None
567 } else {
568 Some(
569 self.runtime
570 .selected_account()
571 .map_err(hns_read_failure)?
572 .config
573 .wallet_id,
574 )
575 };
576 Ok(WalletRuntimeStatus {
577 locked,
578 active_wallet,
579 enabled_modules: BTreeSet::from([ModuleId::Handshake]),
580 mainnet_settlement_enabled: false,
581 })
582 }
583
584 fn exact_account(&self) -> Result<AccountSummary, ServiceFailure> {
585 if self.store.is_locked().map_err(persistent_store_failure)? {
586 return Err(wallet_locked());
587 }
588 let selected = self.runtime.selected_account().map_err(hns_read_failure)?;
589 let account = AccountSummary {
590 account_id: selected.config.account_id,
591 module: ModuleId::Handshake,
592 label: self.account_label.clone(),
593 receive_display: None,
594 };
595 validate_hns_account_summary(&account)?;
596 Ok(account)
597 }
598
599 fn synchronize(&self) -> Result<HnsAccountReadSnapshot, ServiceFailure> {
600 let selected = self.exact_account()?;
601 let snapshot = self.runtime.synchronize().map_err(hns_read_failure)?;
602 if snapshot.account_id != selected.account_id {
603 return Err(hns_read_failure(HnsWalletError::StaleAccountRead));
604 }
605 Ok(snapshot)
606 }
607
608 fn import_name_exact_text(&self, name: &str) -> Result<NativeHnsNameSummary, ServiceFailure> {
609 let imported = self
610 .runtime
611 .import_name_exact_text_bounded(name, MAX_HISTORY_RESULTS)
612 .map_err(hns_native_name_import_failure)?;
613 native_hns_name_summary(&imported)
614 }
615
616 fn import_names_exact_text(
617 &self,
618 names: &[&str],
619 ) -> Result<Vec<NativeHnsNameSummary>, ServiceFailure> {
620 self.runtime
621 .import_names_exact_text_bounded(names, MAX_HISTORY_RESULTS)
622 .map_err(hns_native_name_import_failure)?
623 .iter()
624 .map(native_hns_name_summary)
625 .collect()
626 }
627
628 fn unlock(&self, passphrase: &str) -> Result<(), ServiceFailure> {
629 self.store
630 .unlock(passphrase)
631 .map_err(persistent_store_failure)?;
632 if let Err(error) = self.exact_account() {
633 self.store.lock().map_err(persistent_store_failure)?;
634 return Err(error);
635 }
636 Ok(())
637 }
638
639 fn authority_network(&self) -> Option<WalletHandshakeNetwork> {
640 match self.runtime.configured_network() {
641 HnsNetwork::Mainnet => Some(WalletHandshakeNetwork::Mainnet),
642 HnsNetwork::Testnet => Some(WalletHandshakeNetwork::Testnet),
643 HnsNetwork::Regtest => Some(WalletHandshakeNetwork::Regtest),
644 HnsNetwork::Simnet => None,
645 }
646 }
647
648 fn wallet_hns_authority_context(
649 &self,
650 request: WalletAuthorityContextRequest,
651 wallet_authority_revision: u64,
652 ) -> Result<WalletHnsAuthorityContext, ServiceFailure> {
653 let WalletAuthorityContextRequest::CurrentHnsContext {
654 network,
655 network_magic,
656 namespace_id,
657 namespace_lease_generation,
658 module,
659 } = request;
660 if self.authority_network() != Some(network)
661 || network_magic != network.magic()
662 || namespace_id.iter().all(|byte| *byte == 0)
663 || namespace_lease_generation == 0
664 || module != ModuleId::Handshake
665 || wallet_authority_revision == 0
666 || self.store.is_locked().map_err(persistent_store_failure)?
667 {
668 return Err(invalid_request(
669 "wallet HNS authority claim does not match the active profile",
670 ));
671 }
672 let selected = self
673 .runtime
674 .selected_account_with_revision()
675 .map_err(hns_read_failure)?;
676 Ok(WalletHnsAuthorityContext {
677 network,
678 network_magic,
679 namespace_id,
680 namespace_lease_generation,
681 active_wallet: selected.account.config.wallet_id,
682 account: selected.account.config.account_id,
683 wallet_authority_revision,
684 account_authority_revision: selected.revision,
685 locked: false,
686 module: ModuleId::Handshake,
687 persistent_wallet_confirmed: true,
688 recovery_pending: false,
689 retirement_pending: false,
690 hns_reads_ready: true,
691 })
692 }
693}
694
695impl<B: HnsBackend, C: HnsClock> ServiceRuntime for PersistentHnsReadRuntime<B, C> {
696 fn capabilities(&self) -> BTreeSet<ServiceCapability> {
697 BTreeSet::from([
698 ServiceCapability::WalletOperations,
699 ServiceCapability::HnsReadOperationsV1,
700 ServiceCapability::ProviderDispatch,
701 ])
702 }
703
704 fn supports_provider_method(&self, method: ProviderMethod) -> bool {
705 matches!(
706 method,
707 ProviderMethod::WalletGetStatus
708 | ProviderMethod::HnsRequestAccounts
709 | ProviderMethod::HnsGetBalance
710 | ProviderMethod::HnsGetTransactions
711 | ProviderMethod::HnsGetReceiveAddress
712 | ProviderMethod::HnsGetNames
713 | ProviderMethod::HnsGetName
714 )
715 }
716
717 fn prepare_approval(&mut self, _: &PendingApproval) -> Result<ApprovalSummary, ServiceFailure> {
718 Err(ServiceFailure::unsupported(
719 ServiceCapability::ProviderDispatch,
720 ))
721 }
722
723 fn prepare_hns_account_grant(
724 &mut self,
725 _: &ApprovedCall,
726 ) -> Result<AccountSummary, ServiceFailure> {
727 self.exact_account()
728 }
729
730 fn selected_hns_account(&self) -> Result<AccountSummary, ServiceFailure> {
731 self.exact_account()
732 }
733
734 fn current_hns_names(&mut self) -> Result<Vec<KnownName>, ServiceFailure> {
735 Ok(self.synchronize()?.known_names)
736 }
737
738 fn execute_hns_name_read(
739 &mut self,
740 call: ApprovedCall,
741 approved_names: &BTreeSet<[u8; 32]>,
742 ) -> Result<Value, ServiceFailure> {
743 if approved_names.len() > MAX_PROVIDER_HNS_READ_ITEMS {
744 return Err(provider_failure(ProviderError::Persistence));
745 }
746 let snapshot = self.synchronize()?;
747 public_hns_name_read(&call, approved_names, &snapshot.known_names)
748 }
749
750 fn execute_provider(&mut self, call: ApprovedCall) -> Result<Value, ServiceFailure> {
751 match call.method {
752 ProviderMethod::WalletGetStatus => {
753 validate_empty_params(&call.params)?;
754 serde_json::to_value(self.status()?)
755 .map_err(|_| invalid_request("wallet status encoding failed"))
756 }
757 ProviderMethod::HnsGetBalance
758 | ProviderMethod::HnsGetTransactions
759 | ProviderMethod::HnsGetReceiveAddress => {
760 let snapshot = self.synchronize()?;
761 public_hns_non_name_read(&call, &snapshot)
762 }
763 ProviderMethod::HnsGetNames | ProviderMethod::HnsGetName => Err(
764 ServiceFailure::unsupported(ServiceCapability::ProviderDispatch),
765 ),
766 _ => Err(ServiceFailure::unsupported(
767 ServiceCapability::ProviderDispatch,
768 )),
769 }
770 }
771
772 fn lock_wallet(&mut self) -> Result<(), ServiceFailure> {
773 self.store.lock().map_err(persistent_store_failure)
774 }
775
776 fn execute_wallet(&mut self, request: WalletRequest) -> Result<WalletResponse, ServiceFailure> {
777 match request {
778 WalletRequest::Status => Ok(WalletResponse::Status {
779 status: self.status()?,
780 }),
781 WalletRequest::Unlock { passphrase } => {
782 self.unlock(passphrase.expose_secret())?;
783 Ok(WalletResponse::Unlocked)
784 }
785 WalletRequest::Lock => {
786 self.lock_wallet()?;
787 Ok(WalletResponse::Locked)
788 }
789 WalletRequest::ListAccounts => Ok(WalletResponse::Accounts {
790 accounts: vec![self.exact_account()?],
791 }),
792 WalletRequest::Balance { module, account } => {
793 let snapshot = self.synchronize()?;
794 validate_hns_wallet_read_scope(module, account, snapshot.account_id)?;
795 Ok(WalletResponse::Balance {
796 amount: snapshot.balance,
797 })
798 }
799 WalletRequest::ReceiveTarget { module, account } => {
800 let snapshot = self.synchronize()?;
801 validate_hns_wallet_read_scope(module, account, snapshot.account_id)?;
802 Ok(WalletResponse::ReceiveTarget {
803 target: snapshot.receive_target,
804 })
805 }
806 WalletRequest::TransactionHistory { module, account } => {
807 let snapshot = self.synchronize()?;
808 validate_hns_wallet_read_scope(module, account, snapshot.account_id)?;
809 if snapshot.transactions.len() > MAX_PROVIDER_HNS_READ_ITEMS {
810 return Err(hns_read_result_bound());
811 }
812 Ok(WalletResponse::TransactionHistory {
813 transactions: snapshot.transactions,
814 })
815 }
816 WalletRequest::ModuleStatus {
817 module: ModuleId::Handshake,
818 } => {
819 let snapshot = self.synchronize()?;
820 Ok(WalletResponse::ModuleStatus {
821 status: hns_wallet_types::SyncStatus {
822 phase: hns_wallet_types::SyncPhase::Ready,
823 validated_height: snapshot.binding.chain.tip.height,
824 scanned_height: snapshot.binding.chain.tip.height,
825 target_height: Some(snapshot.binding.chain.tip.height),
826 last_error: None,
827 },
828 })
829 }
830 WalletRequest::CreateWallet { .. }
831 | WalletRequest::RestoreWallet { .. }
832 | WalletRequest::ModuleStatus { .. }
833 | WalletRequest::WorkflowStatus { .. } => Err(ServiceFailure::unsupported(
834 ServiceCapability::WalletOperations,
835 )),
836 }
837 }
838}
839
840struct PersistentRecoveryReadOnlyHnsRuntime<B, C> {
845 store: SharedWalletStore,
846 runtime: HnsPersistedRecoveryReadOnlyRuntime<B, C>,
847 account_label: String,
848}
849
850impl<B: HnsBackend, C: HnsClock> PersistentRecoveryReadOnlyHnsRuntime<B, C> {
851 fn new(
852 store: SharedWalletStore,
853 runtime: HnsPersistedRecoveryReadOnlyRuntime<B, C>,
854 account_label: String,
855 ) -> Self {
856 Self {
857 store,
858 runtime,
859 account_label,
860 }
861 }
862
863 #[cfg(test)]
864 fn shares_store_authority(&self, store: &SharedWalletStore) -> bool {
865 self.store.is_same_authority(store) && self.runtime.shares_store_authority(store)
866 }
867
868 fn status(&self) -> Result<WalletRuntimeStatus, ServiceFailure> {
869 let locked = self.store.is_locked().map_err(persistent_store_failure)?;
870 let active_wallet = if locked {
871 None
872 } else {
873 Some(
874 self.runtime
875 .selected_account()
876 .map_err(hns_read_failure)?
877 .config
878 .wallet_id,
879 )
880 };
881 Ok(WalletRuntimeStatus {
882 locked,
883 active_wallet,
884 enabled_modules: BTreeSet::from([ModuleId::Handshake]),
885 mainnet_settlement_enabled: false,
886 })
887 }
888
889 fn exact_account(&self) -> Result<AccountSummary, ServiceFailure> {
890 if self.store.is_locked().map_err(persistent_store_failure)? {
891 return Err(wallet_locked());
892 }
893 let selected = self.runtime.selected_account().map_err(hns_read_failure)?;
894 let account = AccountSummary {
895 account_id: selected.config.account_id,
896 module: ModuleId::Handshake,
897 label: self.account_label.clone(),
898 receive_display: None,
899 };
900 validate_hns_account_summary(&account)?;
901 Ok(account)
902 }
903
904 fn synchronize(&self) -> Result<HnsAccountReadSnapshot, ServiceFailure> {
905 let selected = self.exact_account()?;
906 let snapshot = self.runtime.synchronize().map_err(hns_read_failure)?;
907 if snapshot.account_id != selected.account_id {
908 return Err(hns_read_failure(HnsWalletError::StaleAccountRead));
909 }
910 Ok(snapshot)
911 }
912
913 fn unlock(&self, passphrase: &str) -> Result<(), ServiceFailure> {
914 self.store
915 .unlock(passphrase)
916 .map_err(persistent_store_failure)?;
917 if let Err(error) = self.exact_account() {
918 self.store.lock().map_err(persistent_store_failure)?;
919 return Err(error);
920 }
921 Ok(())
922 }
923
924 fn admits_wallet_request(request: &WalletRequest) -> bool {
925 matches!(
926 request,
927 WalletRequest::Status
928 | WalletRequest::ListAccounts
929 | WalletRequest::Balance {
930 module: ModuleId::Handshake,
931 ..
932 }
933 | WalletRequest::ReceiveTarget {
934 module: ModuleId::Handshake,
935 ..
936 }
937 | WalletRequest::TransactionHistory {
938 module: ModuleId::Handshake,
939 ..
940 }
941 | WalletRequest::ModuleStatus {
942 module: ModuleId::Handshake,
943 }
944 )
945 }
946}
947
948impl<B: HnsBackend, C: HnsClock> ServiceRuntime for PersistentRecoveryReadOnlyHnsRuntime<B, C> {
949 fn capabilities(&self) -> BTreeSet<ServiceCapability> {
950 BTreeSet::from([
951 ServiceCapability::WalletOperations,
952 ServiceCapability::HnsReadOperationsV1,
953 ])
954 }
955
956 fn admit_service_request(&self, request: &ServiceRequest) -> Result<(), ServiceFailure> {
957 match request {
958 ServiceRequest::Wallet { request } if Self::admits_wallet_request(request) => Ok(()),
959 ServiceRequest::Wallet { .. } => Err(ServiceFailure::unsupported(
960 ServiceCapability::WalletOperations,
961 )),
962 _ => Err(ServiceFailure::unsupported(
963 ServiceCapability::ProviderDispatch,
964 )),
965 }
966 }
967
968 fn supports_provider_method(&self, _: ProviderMethod) -> bool {
969 false
970 }
971
972 fn prepare_approval(&mut self, _: &PendingApproval) -> Result<ApprovalSummary, ServiceFailure> {
973 Err(ServiceFailure::unsupported(
974 ServiceCapability::ProviderDispatch,
975 ))
976 }
977
978 fn execute_provider(&mut self, _: ApprovedCall) -> Result<Value, ServiceFailure> {
979 Err(ServiceFailure::unsupported(
980 ServiceCapability::ProviderDispatch,
981 ))
982 }
983
984 fn lock_wallet(&mut self) -> Result<(), ServiceFailure> {
985 self.store.lock().map_err(persistent_store_failure)
986 }
987
988 fn execute_wallet(&mut self, request: WalletRequest) -> Result<WalletResponse, ServiceFailure> {
989 if !Self::admits_wallet_request(&request) {
990 return Err(ServiceFailure::unsupported(
991 ServiceCapability::WalletOperations,
992 ));
993 }
994 match request {
995 WalletRequest::Status => Ok(WalletResponse::Status {
996 status: self.status()?,
997 }),
998 WalletRequest::ListAccounts => Ok(WalletResponse::Accounts {
999 accounts: vec![self.exact_account()?],
1000 }),
1001 WalletRequest::Balance { module, account } => {
1002 let snapshot = self.synchronize()?;
1003 validate_hns_wallet_read_scope(module, account, snapshot.account_id)?;
1004 Ok(WalletResponse::Balance {
1005 amount: snapshot.balance,
1006 })
1007 }
1008 WalletRequest::ReceiveTarget { module, account } => {
1009 let snapshot = self.synchronize()?;
1010 validate_hns_wallet_read_scope(module, account, snapshot.account_id)?;
1011 Ok(WalletResponse::ReceiveTarget {
1012 target: snapshot.receive_target,
1013 })
1014 }
1015 WalletRequest::TransactionHistory { module, account } => {
1016 let snapshot = self.synchronize()?;
1017 validate_hns_wallet_read_scope(module, account, snapshot.account_id)?;
1018 if snapshot.transactions.len() > MAX_PROVIDER_HNS_READ_ITEMS {
1019 return Err(hns_read_result_bound());
1020 }
1021 Ok(WalletResponse::TransactionHistory {
1022 transactions: snapshot.transactions,
1023 })
1024 }
1025 WalletRequest::ModuleStatus {
1026 module: ModuleId::Handshake,
1027 } => {
1028 let snapshot = self.synchronize()?;
1029 Ok(WalletResponse::ModuleStatus {
1030 status: hns_wallet_types::SyncStatus {
1031 phase: hns_wallet_types::SyncPhase::Ready,
1032 validated_height: snapshot.binding.chain.tip.height,
1033 scanned_height: snapshot.binding.chain.tip.height,
1034 target_height: Some(snapshot.binding.chain.tip.height),
1035 last_error: None,
1036 },
1037 })
1038 }
1039 _ => Err(ServiceFailure::unsupported(
1040 ServiceCapability::WalletOperations,
1041 )),
1042 }
1043 }
1044}
1045
1046#[derive(Clone, Copy)]
1047struct SessionState {
1048 host_session_id: HostSessionId,
1049 restart_generation: u64,
1050 next_host_sequence: u64,
1051 next_service_sequence: u64,
1052}
1053
1054#[derive(Clone)]
1055struct PendingState {
1056 approval_id: ApprovalId,
1057 binding: ProviderBinding,
1058 kind: ApprovalKind,
1059 expires_at_unix: u64,
1060 hns_permission_scope: Option<PendingHnsPermissionScope>,
1061}
1062
1063#[derive(Clone)]
1064struct PendingHnsPermissionScope {
1065 account: AccountSummary,
1066 names: Option<PendingHnsNameScope>,
1067}
1068
1069#[derive(Clone, Eq, PartialEq)]
1070struct PendingHnsNameScope {
1071 disclosures: Vec<HnsNameDisclosure>,
1072 hashes: BTreeSet<[u8; 32]>,
1073}
1074
1075pub struct WalletService<S, R> {
1081 provider: ProviderCore<S>,
1082 runtime: R,
1083 service_session_id: WalletServiceSessionId,
1084 wallet_session_id: WalletSessionId,
1085 capabilities: BTreeSet<ServiceCapability>,
1086 session: Option<SessionState>,
1087 seen_request_ids: BTreeSet<ProviderRequestId>,
1088 request_order: VecDeque<ProviderRequestId>,
1089 pending: BTreeMap<ProviderApprovalId, PendingState>,
1090 event_sequences: BTreeMap<(HostAuthorityHandleId, u64), u64>,
1091}
1092
1093impl<S: ProviderStateStore, R: ServiceRuntime> WalletService<S, R> {
1094 pub fn new_ephemeral(state: S, runtime: R) -> Result<Self, ServiceError> {
1095 Self::new(state, runtime, false)
1096 }
1097
1098 fn new(state: S, runtime: R, persistent_permissions: bool) -> Result<Self, ServiceError> {
1099 let service_session_id = random_service_session()?;
1100 let wallet_session_id = random_wallet_session()?;
1101 let mut capabilities = BTreeSet::from([
1102 ServiceCapability::CanonicalFraming,
1103 ServiceCapability::RestartIsolation,
1104 ServiceCapability::OpaqueAuthorityRegistry,
1105 ServiceCapability::StructuredApprovals,
1106 ServiceCapability::TypedEvents,
1107 ]);
1108 if persistent_permissions {
1109 capabilities.insert(ServiceCapability::PersistentPermissions);
1110 }
1111 capabilities.extend(runtime.capabilities());
1112 capabilities.remove(&ServiceCapability::BrowserIntegration);
1113 if !persistent_permissions {
1114 capabilities.remove(&ServiceCapability::PersistentPermissions);
1115 }
1116 if !capabilities.contains(&ServiceCapability::ProviderDispatch) {
1117 capabilities.remove(&ServiceCapability::ValueMovement);
1118 capabilities.remove(&ServiceCapability::HnsValueOperationsV1);
1119 capabilities.remove(&ServiceCapability::ShakescapeShakedexV1);
1120 }
1121 if !capabilities.contains(&ServiceCapability::WalletOperations) {
1122 capabilities.remove(&ServiceCapability::HnsReadOperationsV1);
1123 }
1124 if !capabilities.contains(&ServiceCapability::WalletOperations)
1125 || !capabilities.contains(&ServiceCapability::HnsReadOperationsV1)
1126 {
1127 capabilities.remove(&ServiceCapability::HnsWalletAuthorityContextV1);
1128 capabilities.remove(&ServiceCapability::HnsValueOperationsV1);
1129 capabilities.remove(&ServiceCapability::ShakescapeShakedexV1);
1130 }
1131 if !capabilities.contains(&ServiceCapability::HnsValueOperationsV1) {
1132 capabilities.remove(&ServiceCapability::ShakescapeShakedexV1);
1133 }
1134 Ok(Self {
1135 provider: ProviderCore::new(state, wallet_session_id, true),
1136 runtime,
1137 service_session_id,
1138 wallet_session_id,
1139 capabilities,
1140 session: None,
1141 seen_request_ids: BTreeSet::new(),
1142 request_order: VecDeque::new(),
1143 pending: BTreeMap::new(),
1144 event_sequences: BTreeMap::new(),
1145 })
1146 }
1147
1148 pub fn process_frame(
1149 &mut self,
1150 encoded: &[u8],
1151 now_unix_ms: u64,
1152 ) -> Result<Vec<u8>, ServiceError> {
1153 let frame = hns_wallet_ffi::decode_host_frame(encoded)?;
1154 match frame {
1155 HostFrame::Hello { hello } => self.negotiate(hello),
1156 HostFrame::Request { envelope } => self.process_request(envelope, now_unix_ms),
1157 }
1158 }
1159
1160 pub fn rotate_wallet_session(&mut self, locked: bool) -> Result<(), ServiceError> {
1161 self.pending.clear();
1162 self.event_sequences.clear();
1163 match random_wallet_session() {
1164 Ok(wallet_session_id) => {
1165 self.wallet_session_id = wallet_session_id;
1166 self.provider.set_wallet_state(wallet_session_id, locked);
1167 Ok(())
1168 }
1169 Err(error) => {
1170 self.provider.set_wallet_state(self.wallet_session_id, true);
1171 Err(error)
1172 }
1173 }
1174 }
1175
1176 pub fn emit_event(
1177 &mut self,
1178 authority_handle: HostAuthorityHandleId,
1179 authority_revision: u64,
1180 payload: ProviderEventPayload,
1181 now_unix_ms: u64,
1182 ) -> Result<Vec<u8>, ServiceError> {
1183 let permission = match self.provider.permission_snapshot(
1184 authority_handle,
1185 authority_revision,
1186 now_unix_ms,
1187 ) {
1188 Ok(permission) => permission,
1189 Err(error) => {
1190 self.event_sequences.clear();
1191 return Err(ServiceError::from(error));
1192 }
1193 };
1194 if permission.record.is_none()
1195 && !matches!(&payload, ProviderEventPayload::Disconnect { .. })
1196 {
1197 self.event_sequences.clear();
1198 return Err(ServiceError::Provider(ProviderError::Unauthorized));
1199 }
1200 let retire_after_emit = permission.record.is_none();
1201 let event_sequence = self
1202 .event_sequences
1203 .entry((authority_handle, authority_revision))
1204 .or_insert(0);
1205 *event_sequence = event_sequence
1206 .checked_add(1)
1207 .ok_or(ServiceError::SequenceExhausted)?;
1208 let event_sequence = *event_sequence;
1209 let (session, channel_sequence) = self.next_service_sequence()?;
1210 let encoded = encode_service_frame(&ServiceFrame::Event {
1211 event: ProviderEventEnvelope {
1212 protocol_version: WALLET_ABI_VERSION,
1213 host_session_id: session.host_session_id,
1214 service_session_id: self.service_session_id,
1215 restart_generation: session.restart_generation,
1216 channel_sequence,
1217 binding: ProviderBinding {
1218 authority_handle,
1219 authority_revision,
1220 wallet_session_id: self.provider.wallet_session_id(),
1221 permission_generation: permission.generation,
1222 },
1223 event_sequence,
1224 payload,
1225 },
1226 })
1227 .map_err(ServiceError::from);
1228 if retire_after_emit {
1229 self.event_sequences
1230 .remove(&(authority_handle, authority_revision));
1231 }
1232 encoded
1233 }
1234
1235 fn negotiate(&mut self, hello: hns_wallet_ffi::HostHello) -> Result<Vec<u8>, ServiceError> {
1236 if self.session.is_some() {
1237 return Err(ServiceError::AlreadyNegotiated);
1238 }
1239 self.session = Some(SessionState {
1240 host_session_id: hello.host_session_id,
1241 restart_generation: hello.restart_generation,
1242 next_host_sequence: 1,
1243 next_service_sequence: 1,
1244 });
1245 encode_service_frame(&ServiceFrame::Hello {
1246 hello: ServiceHello {
1247 protocol_version: WALLET_ABI_VERSION,
1248 platform: hello.platform,
1249 host_session_id: hello.host_session_id,
1250 service_session_id: self.service_session_id,
1251 restart_generation: hello.restart_generation,
1252 capabilities: self.capabilities.clone(),
1253 limits: ServiceLimits::default(),
1254 },
1255 })
1256 .map_err(ServiceError::from)
1257 }
1258
1259 fn process_request(
1260 &mut self,
1261 envelope: SessionEnvelope<ServiceRequest>,
1262 now_unix_ms: u64,
1263 ) -> Result<Vec<u8>, ServiceError> {
1264 self.accept_request_header(&envelope)?;
1265 self.prune_pending(now_unix_ms / 1_000);
1266 let request_id = envelope.request_id;
1267 let response = self
1268 .dispatch(envelope.body, now_unix_ms)
1269 .unwrap_or_else(|failure| ServiceResponse::Failure { failure });
1270 let (session, channel_sequence) = self.next_service_sequence()?;
1271 encode_service_frame(&ServiceFrame::Response {
1272 envelope: SessionEnvelope {
1273 protocol_version: WALLET_ABI_VERSION,
1274 host_session_id: session.host_session_id,
1275 service_session_id: self.service_session_id,
1276 restart_generation: session.restart_generation,
1277 channel_sequence,
1278 request_id,
1279 body: response,
1280 },
1281 })
1282 .map_err(ServiceError::from)
1283 }
1284
1285 fn accept_request_header<T>(
1286 &mut self,
1287 envelope: &SessionEnvelope<T>,
1288 ) -> Result<(), ServiceError> {
1289 let session = self
1290 .session
1291 .as_mut()
1292 .ok_or(ServiceError::HandshakeRequired)?;
1293 if envelope.host_session_id != session.host_session_id
1294 || envelope.service_session_id != self.service_session_id
1295 || envelope.restart_generation != session.restart_generation
1296 {
1297 return Err(ServiceError::SessionMismatch);
1298 }
1299 if envelope.channel_sequence != session.next_host_sequence {
1300 return Err(ServiceError::SequenceMismatch {
1301 expected: session.next_host_sequence,
1302 received: envelope.channel_sequence,
1303 });
1304 }
1305 if self.seen_request_ids.contains(&envelope.request_id) {
1306 return Err(ServiceError::DuplicateRequest);
1307 }
1308 session.next_host_sequence = session
1309 .next_host_sequence
1310 .checked_add(1)
1311 .ok_or(ServiceError::SequenceExhausted)?;
1312 self.seen_request_ids.insert(envelope.request_id);
1313 self.request_order.push_back(envelope.request_id);
1314 if self.request_order.len() > MAX_SEEN_REQUEST_IDS
1315 && let Some(expired) = self.request_order.pop_front()
1316 {
1317 self.seen_request_ids.remove(&expired);
1318 }
1319 Ok(())
1320 }
1321
1322 fn next_service_sequence(&mut self) -> Result<(SessionState, u64), ServiceError> {
1323 let session = self
1324 .session
1325 .as_mut()
1326 .ok_or(ServiceError::HandshakeRequired)?;
1327 let sequence = session.next_service_sequence;
1328 session.next_service_sequence = sequence
1329 .checked_add(1)
1330 .ok_or(ServiceError::SequenceExhausted)?;
1331 Ok((*session, sequence))
1332 }
1333
1334 fn dispatch(
1335 &mut self,
1336 request: ServiceRequest,
1337 now_unix_ms: u64,
1338 ) -> Result<ServiceResponse, ServiceFailure> {
1339 self.runtime.admit_service_request(&request)?;
1340 match request {
1341 ServiceRequest::RegisterAuthority {
1342 authority_handle,
1343 authority,
1344 } => {
1345 let revision = self
1346 .provider
1347 .register_authority(
1348 authority_handle,
1349 provider_authority(authority)?,
1350 now_unix_ms,
1351 )
1352 .map_err(provider_failure)?;
1353 Ok(ServiceResponse::AuthorityRegistered {
1354 authority_handle,
1355 authority_revision: revision,
1356 })
1357 }
1358 ServiceRequest::ReplaceAuthority {
1359 authority_handle,
1360 expected_authority_revision,
1361 authority,
1362 } => {
1363 let revision = self
1364 .provider
1365 .replace_authority(
1366 authority_handle,
1367 expected_authority_revision,
1368 provider_authority(authority)?,
1369 now_unix_ms,
1370 )
1371 .map_err(provider_failure)?;
1372 self.pending
1373 .retain(|_, pending| pending.binding.authority_handle != authority_handle);
1374 self.event_sequences
1375 .retain(|(handle, _), _| *handle != authority_handle);
1376 Ok(ServiceResponse::AuthorityReplaced {
1377 authority_handle,
1378 authority_revision: revision,
1379 })
1380 }
1381 ServiceRequest::RevokeAuthority {
1382 authority_handle,
1383 expected_authority_revision,
1384 } => {
1385 self.provider
1386 .revoke_authority(authority_handle, expected_authority_revision)
1387 .map_err(provider_failure)?;
1388 self.pending
1389 .retain(|_, pending| pending.binding.authority_handle != authority_handle);
1390 self.event_sequences
1391 .retain(|(handle, _), _| *handle != authority_handle);
1392 Ok(ServiceResponse::AuthorityRevoked { authority_handle })
1393 }
1394 ServiceRequest::ProviderCapabilities {
1395 authority_handle,
1396 authority_revision,
1397 } => self.provider_capabilities(authority_handle, authority_revision, now_unix_ms),
1398 ServiceRequest::ProviderRequest {
1399 authority_handle,
1400 authority_revision,
1401 request_nonce,
1402 method,
1403 params,
1404 } => self.provider_request(
1405 authority_handle,
1406 authority_revision,
1407 request_nonce,
1408 method,
1409 params,
1410 now_unix_ms,
1411 ),
1412 ServiceRequest::ApprovalDecision {
1413 authority_handle,
1414 authority_revision,
1415 approval_id,
1416 decision,
1417 } => self.approval_decision(
1418 authority_handle,
1419 authority_revision,
1420 approval_id,
1421 decision,
1422 now_unix_ms,
1423 ),
1424 ServiceRequest::Wallet { request } => {
1425 if !self
1426 .capabilities
1427 .contains(&ServiceCapability::WalletOperations)
1428 {
1429 return Err(ServiceFailure::unsupported(
1430 ServiceCapability::WalletOperations,
1431 ));
1432 }
1433 let response = self.runtime.execute_wallet(request)?;
1434 match &response {
1435 WalletResponse::Locked => self
1436 .rotate_wallet_session(true)
1437 .map_err(ServiceFailure::from)?,
1438 WalletResponse::Unlocked
1439 | WalletResponse::WalletCreated { .. }
1440 | WalletResponse::WalletRestored { .. } => {
1441 if let Err(error) = self.rotate_wallet_session(false) {
1442 self.runtime.lock_wallet()?;
1449 return Err(ServiceFailure::from(error));
1450 }
1451 }
1452 _ => {}
1453 }
1454 Ok(ServiceResponse::Wallet { response })
1455 }
1456 ServiceRequest::WalletAuthority { request } => {
1457 if !self
1458 .capabilities
1459 .contains(&ServiceCapability::HnsWalletAuthorityContextV1)
1460 {
1461 return Err(ServiceFailure::unsupported(
1462 ServiceCapability::HnsWalletAuthorityContextV1,
1463 ));
1464 }
1465 let context = self.runtime.execute_wallet_authority_context(request)?;
1466 Ok(ServiceResponse::WalletAuthority { context })
1467 }
1468 }
1469 }
1470
1471 fn provider_capabilities(
1472 &mut self,
1473 authority_handle: HostAuthorityHandleId,
1474 authority_revision: u64,
1475 now_unix_ms: u64,
1476 ) -> Result<ServiceResponse, ServiceFailure> {
1477 let binding = self.provider_binding(authority_handle, authority_revision, now_unix_ms)?;
1478 let capabilities = ProviderCapabilitySnapshot {
1479 provider_schema_version: PROVIDER_SCHEMA_VERSION,
1480 approval_schema_version: APPROVAL_SCHEMA_VERSION,
1481 wallet_session_id: binding.wallet_session_id,
1482 permission_generation: binding.permission_generation,
1483 methods: self.supported_provider_method_names(),
1484 };
1485 Ok(ServiceResponse::ProviderCapabilities {
1486 binding,
1487 capabilities,
1488 })
1489 }
1490
1491 fn provider_request(
1492 &mut self,
1493 authority_handle: HostAuthorityHandleId,
1494 authority_revision: u64,
1495 request_nonce: u64,
1496 method_name: String,
1497 params: Value,
1498 now_unix_ms: u64,
1499 ) -> Result<ServiceResponse, ServiceFailure> {
1500 if !self
1501 .capabilities
1502 .contains(&ServiceCapability::ProviderDispatch)
1503 {
1504 return Err(ServiceFailure::unsupported(
1505 ServiceCapability::ProviderDispatch,
1506 ));
1507 }
1508 let method = ProviderMethod::parse(&method_name).map_err(provider_failure)?;
1509 if method == ProviderMethod::WalletLock
1510 && !self
1511 .capabilities
1512 .contains(&ServiceCapability::WalletOperations)
1513 {
1514 return Err(ServiceFailure::unsupported(
1515 ServiceCapability::WalletOperations,
1516 ));
1517 }
1518 if method.approval().is_some_and(value_movement_approval)
1519 && !self
1520 .capabilities
1521 .contains(&ServiceCapability::ValueMovement)
1522 {
1523 return Err(ServiceFailure::unsupported(
1524 ServiceCapability::ValueMovement,
1525 ));
1526 }
1527 if matches!(
1528 method,
1529 ProviderMethod::HnsRequestAccounts | ProviderMethod::HnsAccounts
1530 ) && !self
1531 .runtime
1532 .supports_provider_method(ProviderMethod::HnsRequestAccounts)
1533 {
1534 return Err(ServiceFailure::unsupported(
1535 ServiceCapability::ProviderDispatch,
1536 ));
1537 }
1538 if !service_owned_method(method) && !self.runtime.supports_provider_method(method) {
1539 return Err(ServiceFailure::unsupported(
1540 ServiceCapability::ProviderDispatch,
1541 ));
1542 }
1543 if matches!(
1550 method,
1551 ProviderMethod::HnsRequestAccounts
1552 | ProviderMethod::HnsAccounts
1553 | ProviderMethod::HnsGetBalance
1554 | ProviderMethod::HnsGetTransactions
1555 | ProviderMethod::HnsGetReceiveAddress
1556 | ProviderMethod::HnsGetNames
1557 ) {
1558 validate_empty_params(¶ms)?;
1559 }
1560 if method == ProviderMethod::HnsGetName {
1561 hns_name_hash_param(¶ms)?;
1562 }
1563 if matches!(
1564 method,
1565 ProviderMethod::WalletGetCapabilities
1566 | ProviderMethod::WalletGetPermissions
1567 | ProviderMethod::WalletGetStatus
1568 | ProviderMethod::WalletRevokePermissions
1569 | ProviderMethod::WalletLock
1570 ) {
1571 validate_empty_params(¶ms)?;
1572 }
1573 if method == ProviderMethod::WalletRequestPermissions {
1574 let requested = requested_capabilities_from_params(¶ms)?;
1575 if !requested.is_subset(&self.grantable_permission_capabilities()) {
1576 return Err(ServiceFailure::unsupported(
1577 ServiceCapability::ProviderDispatch,
1578 ));
1579 }
1580 }
1581 let encoded_request = serde_json::to_vec(&json!({
1582 "method": method_name.clone(),
1583 "params": params,
1584 }))
1585 .map_err(|_| invalid_request("provider request encoding failed"))?;
1586 let action = match self.provider.request(
1587 authority_handle,
1588 authority_revision,
1589 request_nonce,
1590 now_unix_ms,
1591 &encoded_request,
1592 ) {
1593 Ok(action) => action,
1594 Err(error) => {
1595 if matches!(
1596 &error,
1597 ProviderError::Unauthorized | ProviderError::ClockRollback
1598 ) {
1599 self.event_sequences.clear();
1600 }
1601 if matches!(&error, ProviderError::ClockRollback) {
1602 self.pending.clear();
1603 }
1604 return Err(provider_failure(error));
1605 }
1606 };
1607 match action {
1608 ProviderAction::Execute(call) => {
1609 let lock_permission_generation = if call.method == ProviderMethod::WalletLock {
1610 Some(
1611 self.provider_binding(authority_handle, authority_revision, now_unix_ms)?
1612 .permission_generation,
1613 )
1614 } else {
1615 None
1616 };
1617 let value = self.execute_call(
1618 authority_handle,
1619 authority_revision,
1620 call,
1621 None,
1622 now_unix_ms,
1623 )?;
1624 let binding = match lock_permission_generation {
1625 Some(permission_generation) => ProviderBinding {
1626 authority_handle,
1627 authority_revision,
1628 wallet_session_id: self.provider.wallet_session_id(),
1629 permission_generation,
1630 },
1631 None => {
1632 self.provider_binding(authority_handle, authority_revision, now_unix_ms)?
1633 }
1634 };
1635 Ok(ServiceResponse::ProviderResult { binding, value })
1636 }
1637 ProviderAction::ApprovalRequired(approval) => {
1638 if self.pending.len() >= MAX_SERVICE_PENDING_APPROVALS {
1639 self.provider
1640 .reject(
1641 authority_handle,
1642 authority_revision,
1643 approval.id,
1644 now_unix_ms,
1645 )
1646 .map_err(provider_failure)?;
1647 return Err(invalid_request("too many pending approvals"));
1648 }
1649 let (summary, hns_permission_scope) =
1650 match self.approval_summary(&approval, now_unix_ms) {
1651 Ok(prepared) => prepared,
1652 Err(failure) => {
1653 let _ = self.provider.reject(
1654 authority_handle,
1655 authority_revision,
1656 approval.id,
1657 now_unix_ms,
1658 );
1659 return Err(failure);
1660 }
1661 };
1662 let wire_id = match wire_approval_id(approval.id) {
1663 Ok(wire_id) => wire_id,
1664 Err(failure) => {
1665 let _ = self.provider.reject(
1666 authority_handle,
1667 authority_revision,
1668 approval.id,
1669 now_unix_ms,
1670 );
1671 return Err(failure);
1672 }
1673 };
1674 let expires_at_unix_ms = match approval.expires_at_unix.checked_mul(1_000) {
1675 Some(expiry) => expiry,
1676 None => {
1677 let _ = self.provider.reject(
1678 authority_handle,
1679 authority_revision,
1680 approval.id,
1681 now_unix_ms,
1682 );
1683 return Err(invalid_request("approval expiry overflow"));
1684 }
1685 };
1686 let prompt = ApprovalPrompt {
1687 approval_id: wire_id,
1688 binding: ProviderBinding {
1689 authority_handle,
1690 authority_revision,
1691 wallet_session_id: approval.wallet_session,
1692 permission_generation: approval.permission_generation,
1693 },
1694 origin: approval.call.origin.as_str().to_owned(),
1695 method: method_name,
1696 expires_at_unix_ms,
1697 summary,
1698 };
1699 if let Err(error) = prompt.validate(approval.kind, now_unix_ms) {
1700 let _ = self.provider.reject(
1701 authority_handle,
1702 authority_revision,
1703 approval.id,
1704 now_unix_ms,
1705 );
1706 return Err(ServiceFailure {
1707 code: ServiceErrorCode::InvalidRequest,
1708 message: error.to_string(),
1709 unsupported_capability: None,
1710 });
1711 }
1712 self.pending.insert(
1713 wire_id,
1714 PendingState {
1715 approval_id: approval.id,
1716 binding: prompt.binding,
1717 kind: approval.kind,
1718 expires_at_unix: approval.expires_at_unix,
1719 hns_permission_scope,
1720 },
1721 );
1722 Ok(ServiceResponse::ApprovalRequired { approval: prompt })
1723 }
1724 }
1725 }
1726
1727 fn approval_decision(
1728 &mut self,
1729 authority_handle: HostAuthorityHandleId,
1730 authority_revision: u64,
1731 approval_id: ProviderApprovalId,
1732 decision: hns_wallet_ffi::ApprovalDecision,
1733 now_unix_ms: u64,
1734 ) -> Result<ServiceResponse, ServiceFailure> {
1735 let pending = self
1736 .pending
1737 .get(&approval_id)
1738 .cloned()
1739 .ok_or_else(stale_approval)?;
1740 if pending.binding.authority_handle != authority_handle
1741 || pending.binding.authority_revision != authority_revision
1742 || pending.expires_at_unix <= now_unix_ms / 1_000
1743 {
1744 return Err(stale_approval());
1745 }
1746 let binding = self.provider_binding(authority_handle, authority_revision, now_unix_ms)?;
1747 if pending.binding != binding {
1748 return Err(stale_approval());
1749 }
1750 let internal_id = ApprovalId::new(approval_id.into_bytes());
1751 match decision {
1752 hns_wallet_ffi::ApprovalDecision::Reject => {
1753 self.provider
1754 .reject(
1755 authority_handle,
1756 authority_revision,
1757 internal_id,
1758 now_unix_ms,
1759 )
1760 .map_err(provider_failure)?;
1761 self.pending.remove(&approval_id);
1762 Ok(ServiceResponse::ApprovalRejected { approval_id })
1763 }
1764 hns_wallet_ffi::ApprovalDecision::Approve => {
1765 if let Err(failure) = self.verify_pending_hns_permission_scope(
1766 authority_handle,
1767 authority_revision,
1768 &pending,
1769 now_unix_ms,
1770 ) {
1771 let _ = self.provider.reject(
1772 authority_handle,
1773 authority_revision,
1774 internal_id,
1775 now_unix_ms,
1776 );
1777 self.pending.remove(&approval_id);
1778 return Err(failure);
1779 }
1780 let call = self
1781 .provider
1782 .approve(
1783 authority_handle,
1784 authority_revision,
1785 internal_id,
1786 now_unix_ms,
1787 )
1788 .map_err(provider_failure)?;
1789 if call.method.approval() != Some(pending.kind) {
1790 self.pending.remove(&approval_id);
1791 return Err(stale_approval());
1792 }
1793 self.pending.remove(&approval_id);
1794 let value = self.execute_call(
1795 authority_handle,
1796 authority_revision,
1797 call,
1798 Some(&pending),
1799 now_unix_ms,
1800 )?;
1801 let binding =
1802 self.provider_binding(authority_handle, authority_revision, now_unix_ms)?;
1803 Ok(ServiceResponse::ProviderResult { binding, value })
1804 }
1805 }
1806 }
1807
1808 fn approval_summary(
1809 &mut self,
1810 approval: &PendingApproval,
1811 now_unix_ms: u64,
1812 ) -> Result<(ApprovalSummary, Option<PendingHnsPermissionScope>), ServiceFailure> {
1813 let mut hns_permission_scope = None;
1814 let summary = match approval.call.method {
1815 ProviderMethod::WalletRequestPermissions => {
1816 let capabilities = requested_capabilities(&approval.call)?;
1817 hns_permission_scope =
1818 self.prepare_hns_permission_scope(approval, &capabilities, now_unix_ms)?;
1819 let hns_names = hns_permission_scope
1820 .as_ref()
1821 .and_then(|scope| scope.names.as_ref())
1822 .map(|scope| scope.disclosures.clone())
1823 .unwrap_or_default();
1824 Ok(ApprovalSummary::Permissions {
1825 capabilities,
1826 hns_names,
1827 })
1828 }
1829 ProviderMethod::HnsRequestAccounts => Ok(ApprovalSummary::Permissions {
1830 capabilities: requested_capabilities(&approval.call)?,
1831 hns_names: Vec::new(),
1832 }),
1833 ProviderMethod::WalletEnableModule | ProviderMethod::WalletDisableModule => {
1834 let module = requested_module(&approval.call.params)?;
1835 let action = if approval.call.method == ProviderMethod::WalletEnableModule {
1836 ModuleApprovalAction::Enable
1837 } else {
1838 ModuleApprovalAction::Disable
1839 };
1840 Ok(ApprovalSummary::ModuleEnablement { module, action })
1841 }
1842 _ => self.runtime.prepare_approval(approval),
1843 }?;
1844 validate_approval_summary(&approval.call, &summary)?;
1845 Ok((summary, hns_permission_scope))
1846 }
1847
1848 fn hns_permission_request_is_account_scoped(
1849 &self,
1850 requested: &BTreeSet<PermissionCapability>,
1851 ) -> bool {
1852 ProviderMethod::ALL.into_iter().any(|method| {
1853 hns_account_read_method(method)
1854 && self.runtime.supports_provider_method(method)
1855 && method
1856 .permission()
1857 .is_some_and(|capability| requested.contains(&capability))
1858 })
1859 }
1860
1861 fn prepare_hns_permission_scope(
1862 &mut self,
1863 approval: &PendingApproval,
1864 requested: &BTreeSet<PermissionCapability>,
1865 now_unix_ms: u64,
1866 ) -> Result<Option<PendingHnsPermissionScope>, ServiceFailure> {
1867 if !self.hns_permission_request_is_account_scoped(requested) {
1868 return Ok(None);
1869 }
1870 if approval.call.namespace != SelectedNamespace::Hns {
1871 return Err(provider_failure(ProviderError::Unauthorized));
1872 }
1873 let permission = self
1874 .provider
1875 .permission_snapshot(
1876 approval.authority_handle,
1877 approval.authority_revision,
1878 now_unix_ms,
1879 )
1880 .map_err(provider_failure)?;
1881 if permission.generation != approval.permission_generation {
1882 return Err(stale_approval());
1883 }
1884 let record = permission
1885 .record
1886 .ok_or_else(|| provider_failure(ProviderError::Unauthorized))?;
1887 let selected = self.runtime.selected_hns_account()?;
1888 validate_hns_account_summary(&selected)?;
1889 if !record
1890 .capabilities
1891 .contains(&PermissionCapability::Accounts)
1892 || record.approved_accounts != BTreeSet::from([selected.account_id])
1893 {
1894 return Err(provider_failure(ProviderError::Unauthorized));
1895 }
1896 let names = if requested.contains(&PermissionCapability::Names) {
1897 Some(hns_name_approval_scope(self.runtime.current_hns_names()?)?)
1898 } else {
1899 None
1900 };
1901 Ok(Some(PendingHnsPermissionScope {
1902 account: selected,
1903 names,
1904 }))
1905 }
1906
1907 fn verify_pending_hns_permission_scope(
1908 &mut self,
1909 authority_handle: HostAuthorityHandleId,
1910 authority_revision: u64,
1911 pending: &PendingState,
1912 now_unix_ms: u64,
1913 ) -> Result<(), ServiceFailure> {
1914 let Some(expected) = pending.hns_permission_scope.as_ref() else {
1915 return Ok(());
1916 };
1917 let permission = self
1918 .provider
1919 .permission_snapshot(authority_handle, authority_revision, now_unix_ms)
1920 .map_err(provider_failure)?;
1921 let Some(record) = permission.record else {
1922 return Err(stale_approval());
1923 };
1924 if permission.generation != pending.binding.permission_generation
1925 || !record
1926 .capabilities
1927 .contains(&PermissionCapability::Accounts)
1928 || record.approved_accounts != BTreeSet::from([expected.account.account_id])
1929 {
1930 return Err(stale_approval());
1931 }
1932 let selected = self.runtime.selected_hns_account()?;
1933 validate_hns_account_summary(&selected)?;
1934 if selected != expected.account {
1935 return Err(stale_approval());
1936 }
1937 if let Some(expected_names) = expected.names.as_ref() {
1938 let current_names = self.runtime.current_hns_names()?;
1939 let current = hns_name_approval_scope(current_names).map_err(|_| stale_approval())?;
1940 if ¤t != expected_names {
1941 return Err(stale_approval());
1942 }
1943 }
1944 Ok(())
1945 }
1946
1947 fn execute_call(
1948 &mut self,
1949 authority_handle: HostAuthorityHandleId,
1950 authority_revision: u64,
1951 call: ApprovedCall,
1952 approved_pending: Option<&PendingState>,
1953 now_unix_ms: u64,
1954 ) -> Result<Value, ServiceFailure> {
1955 match call.method {
1956 ProviderMethod::WalletGetCapabilities => Ok(json!({
1957 "providerApiVersion": PROVIDER_API_VERSION,
1958 "methods": self.supported_provider_method_names(),
1959 })),
1960 ProviderMethod::WalletGetPermissions => {
1961 let permission = self
1962 .provider
1963 .permission_snapshot(authority_handle, authority_revision, now_unix_ms)
1964 .map_err(provider_failure)?;
1965 if permission.record.is_none() {
1966 self.event_sequences.clear();
1967 }
1968 permission_value(permission)
1969 }
1970 ProviderMethod::WalletRevokePermissions => {
1971 let generation = self
1972 .provider
1973 .revoke_permissions(authority_handle, authority_revision, now_unix_ms)
1974 .map_err(provider_failure)?;
1975 self.pending.clear();
1976 self.event_sequences.clear();
1977 Ok(json!({
1978 "permissionGeneration": generation,
1979 "capabilities": [],
1980 "accounts": []
1981 }))
1982 }
1983 ProviderMethod::WalletRequestPermissions => {
1984 let requested = requested_capabilities(&call)?;
1985 if !requested.is_subset(&self.grantable_permission_capabilities()) {
1986 return Err(ServiceFailure::unsupported(
1987 ServiceCapability::ProviderDispatch,
1988 ));
1989 }
1990 let approved_pending = approved_pending.ok_or_else(stale_approval)?;
1991 let expected_generation = approved_pending.binding.permission_generation;
1992 let (capabilities, approved_accounts, approved_names, expires_at_unix) = self
1993 .hns_read_permission_extension(
1994 authority_handle,
1995 authority_revision,
1996 &call,
1997 expected_generation,
1998 requested,
1999 approved_pending.hns_permission_scope.as_ref(),
2000 now_unix_ms,
2001 )?;
2002 let permission = self
2003 .provider
2004 .grant_scoped_permissions_at_generation(
2005 authority_handle,
2006 authority_revision,
2007 expected_generation,
2008 capabilities,
2009 approved_accounts,
2010 approved_names,
2011 now_unix_ms,
2012 expires_at_unix,
2013 )
2014 .map_err(provider_failure)?;
2015 self.pending.clear();
2016 self.event_sequences.clear();
2017 permission_value(PermissionSnapshot {
2018 generation: permission.generation,
2019 record: Some(permission),
2020 })
2021 }
2022 ProviderMethod::HnsRequestAccounts => self.approve_hns_account_grant(
2023 authority_handle,
2024 authority_revision,
2025 &call,
2026 approved_pending
2027 .map(|pending| pending.binding.permission_generation)
2028 .ok_or_else(stale_approval)?,
2029 now_unix_ms,
2030 ),
2031 ProviderMethod::HnsAccounts => {
2032 self.approved_hns_accounts(authority_handle, authority_revision, &call, now_unix_ms)
2033 }
2034 ProviderMethod::WalletLock => {
2035 self.runtime.lock_wallet()?;
2036 self.rotate_wallet_session(true)
2037 .map_err(ServiceFailure::from)?;
2038 Ok(json!({ "locked": true }))
2039 }
2040 _ if hns_account_read_method(call.method) => {
2041 let approved_names = self.authorize_hns_account_read(
2042 authority_handle,
2043 authority_revision,
2044 &call,
2045 now_unix_ms,
2046 )?;
2047 if matches!(
2048 call.method,
2049 ProviderMethod::HnsGetNames | ProviderMethod::HnsGetName
2050 ) {
2051 self.runtime.execute_hns_name_read(call, &approved_names)
2052 } else {
2053 self.runtime.execute_provider(call)
2054 }
2055 }
2056 _ => match approved_pending {
2057 Some(pending) => self.runtime.execute_approved_provider(
2058 call,
2059 pending.approval_id,
2060 now_unix_ms / 1_000,
2061 ),
2062 None => self.runtime.execute_provider(call),
2063 },
2064 }
2065 }
2066
2067 #[allow(clippy::too_many_arguments)]
2068 fn hns_read_permission_extension(
2069 &mut self,
2070 authority_handle: HostAuthorityHandleId,
2071 authority_revision: u64,
2072 call: &ApprovedCall,
2073 expected_generation: u64,
2074 requested: BTreeSet<PermissionCapability>,
2075 pending_scope: Option<&PendingHnsPermissionScope>,
2076 now_unix_ms: u64,
2077 ) -> Result<HnsReadPermissionExtension, ServiceFailure> {
2078 let account_scoped = self.hns_permission_request_is_account_scoped(&requested);
2079 if !account_scoped {
2080 if pending_scope.is_some() {
2081 return Err(stale_approval());
2082 }
2083 return Ok((requested, BTreeSet::new(), BTreeSet::new(), None));
2084 }
2085 if call.namespace != SelectedNamespace::Hns {
2086 return Err(provider_failure(ProviderError::Unauthorized));
2087 }
2088 let snapshot = self
2089 .provider
2090 .permission_snapshot(authority_handle, authority_revision, now_unix_ms)
2091 .map_err(provider_failure)?;
2092 if snapshot.generation != expected_generation {
2093 return Err(stale_approval());
2094 }
2095 let record = snapshot
2096 .record
2097 .ok_or_else(|| provider_failure(ProviderError::Unauthorized))?;
2098 let selected = self.runtime.selected_hns_account()?;
2099 validate_hns_account_summary(&selected)?;
2100 let approved_accounts = BTreeSet::from([selected.account_id]);
2101 if !record
2102 .capabilities
2103 .contains(&PermissionCapability::Accounts)
2104 || record.approved_accounts != approved_accounts
2105 {
2106 return Err(provider_failure(ProviderError::Unauthorized));
2107 }
2108 let pending_scope = pending_scope.ok_or_else(stale_approval)?;
2109 if pending_scope.account != selected {
2110 return Err(stale_approval());
2111 }
2112 let refresh_name_scope = requested.contains(&PermissionCapability::Names);
2113 let approved_names = if refresh_name_scope {
2114 pending_scope
2115 .names
2116 .as_ref()
2117 .ok_or_else(stale_approval)?
2118 .hashes
2119 .clone()
2120 } else {
2121 if pending_scope.names.is_some() {
2122 return Err(stale_approval());
2123 }
2124 record.approved_names
2125 };
2126 if approved_names.len() > MAX_PROVIDER_HNS_READ_ITEMS {
2127 return Err(hns_read_result_bound());
2128 }
2129 let mut capabilities = record.capabilities;
2130 capabilities.extend(requested);
2131 Ok((
2132 capabilities,
2133 approved_accounts,
2134 approved_names,
2135 record.expires_at_unix,
2136 ))
2137 }
2138
2139 fn authorize_hns_account_read(
2140 &mut self,
2141 authority_handle: HostAuthorityHandleId,
2142 authority_revision: u64,
2143 call: &ApprovedCall,
2144 now_unix_ms: u64,
2145 ) -> Result<BTreeSet<[u8; 32]>, ServiceFailure> {
2146 if call.namespace != SelectedNamespace::Hns {
2147 return Err(provider_failure(ProviderError::Unauthorized));
2148 }
2149 let required = call
2150 .method
2151 .permission()
2152 .ok_or_else(|| invalid_request("HNS read has no permission capability"))?;
2153 let record = self
2154 .provider
2155 .permission_snapshot(authority_handle, authority_revision, now_unix_ms)
2156 .map_err(provider_failure)?
2157 .record
2158 .ok_or_else(|| provider_failure(ProviderError::Unauthorized))?;
2159 let selected = self.runtime.selected_hns_account()?;
2160 validate_hns_account_summary(&selected)?;
2161 if !record
2162 .capabilities
2163 .contains(&PermissionCapability::Accounts)
2164 || !record.capabilities.contains(&required)
2165 || record.approved_accounts != BTreeSet::from([selected.account_id])
2166 {
2167 return Err(provider_failure(ProviderError::Unauthorized));
2168 }
2169 if record.approved_names.len() > MAX_PROVIDER_HNS_READ_ITEMS {
2170 return Err(provider_failure(ProviderError::Persistence));
2171 }
2172 if call.method == ProviderMethod::HnsGetName {
2173 let requested = hns_name_hash_param(&call.params)?;
2174 if !record.approved_names.contains(&requested) {
2175 return Err(provider_failure(ProviderError::Unauthorized));
2176 }
2177 }
2178 Ok(record.approved_names)
2179 }
2180
2181 fn provider_binding(
2182 &mut self,
2183 authority_handle: HostAuthorityHandleId,
2184 authority_revision: u64,
2185 now_unix_ms: u64,
2186 ) -> Result<ProviderBinding, ServiceFailure> {
2187 let permission = self
2188 .provider
2189 .permission_snapshot(authority_handle, authority_revision, now_unix_ms)
2190 .map_err(provider_failure)?;
2191 Ok(ProviderBinding {
2192 authority_handle,
2193 authority_revision,
2194 wallet_session_id: self.provider.wallet_session_id(),
2195 permission_generation: permission.generation,
2196 })
2197 }
2198
2199 fn supported_provider_methods(&self) -> BTreeSet<ProviderMethod> {
2200 if !self
2201 .capabilities
2202 .contains(&ServiceCapability::ProviderDispatch)
2203 {
2204 return BTreeSet::new();
2205 }
2206 ProviderMethod::ALL
2207 .into_iter()
2208 .filter(|method| {
2209 if *method == ProviderMethod::WalletRequestPermissions {
2210 return !self.grantable_permission_capabilities().is_empty();
2211 }
2212 if matches!(
2213 method,
2214 ProviderMethod::HnsRequestAccounts | ProviderMethod::HnsAccounts
2215 ) {
2216 return self
2217 .runtime
2218 .supports_provider_method(ProviderMethod::HnsRequestAccounts);
2219 }
2220 if *method == ProviderMethod::WalletLock
2221 && !self
2222 .capabilities
2223 .contains(&ServiceCapability::WalletOperations)
2224 {
2225 return false;
2226 }
2227 if method.approval().is_some_and(value_movement_approval)
2228 && !self
2229 .capabilities
2230 .contains(&ServiceCapability::ValueMovement)
2231 {
2232 return false;
2233 }
2234 service_owned_method(*method) || self.runtime.supports_provider_method(*method)
2235 })
2236 .collect()
2237 }
2238
2239 fn grantable_permission_capabilities(&self) -> BTreeSet<PermissionCapability> {
2240 ProviderMethod::ALL
2241 .into_iter()
2242 .filter(|method| {
2243 !matches!(
2244 method,
2245 ProviderMethod::HnsRequestAccounts | ProviderMethod::HnsAccounts
2246 ) && self.runtime.supports_provider_method(*method)
2247 && (!method.approval().is_some_and(value_movement_approval)
2248 || self
2249 .capabilities
2250 .contains(&ServiceCapability::ValueMovement))
2251 })
2252 .filter_map(ProviderMethod::permission)
2253 .filter(|capability| *capability != PermissionCapability::Accounts)
2254 .collect()
2255 }
2256
2257 fn supported_provider_method_names(&self) -> BTreeSet<String> {
2258 self.supported_provider_methods()
2259 .into_iter()
2260 .map(|method| method.wire_name().to_owned())
2261 .collect()
2262 }
2263
2264 fn prune_pending(&mut self, now_unix: u64) {
2265 self.pending
2266 .retain(|_, pending| pending.expires_at_unix > now_unix);
2267 }
2268
2269 fn approve_hns_account_grant(
2270 &mut self,
2271 authority_handle: HostAuthorityHandleId,
2272 authority_revision: u64,
2273 call: &ApprovedCall,
2274 expected_permission_generation: u64,
2275 now_unix_ms: u64,
2276 ) -> Result<Value, ServiceFailure> {
2277 validate_empty_params(&call.params)?;
2278 if call.namespace != SelectedNamespace::Hns {
2279 return Err(invalid_request(
2280 "Handshake accounts require the HNS namespace",
2281 ));
2282 }
2283 if !self
2284 .runtime
2285 .supports_provider_method(ProviderMethod::HnsRequestAccounts)
2286 {
2287 return Err(ServiceFailure::unsupported(
2288 ServiceCapability::ProviderDispatch,
2289 ));
2290 }
2291 let account = self.runtime.prepare_hns_account_grant(call)?;
2292 validate_hns_account_summary(&account)?;
2293 let account_id = account.account_id;
2294 let value = json!([account_id.to_string()]);
2295 if serde_json::to_vec(&value)
2296 .map_err(|_| invalid_request("account result encoding failed"))?
2297 .len()
2298 > MAX_PROVIDER_RESULT_BYTES
2299 {
2300 return Err(invalid_request("account result exceeds the provider bound"));
2301 }
2302 let permission = self
2303 .provider
2304 .grant_scoped_permissions_at_generation(
2305 authority_handle,
2306 authority_revision,
2307 expected_permission_generation,
2308 BTreeSet::from([PermissionCapability::Accounts]),
2309 BTreeSet::from([account_id]),
2310 BTreeSet::new(),
2311 now_unix_ms,
2312 None,
2313 )
2314 .map_err(provider_failure)?;
2315 if permission.approved_accounts != BTreeSet::from([account_id]) {
2316 return Err(provider_failure(ProviderError::Persistence));
2317 }
2318 self.pending.clear();
2319 self.event_sequences.clear();
2320 Ok(value)
2321 }
2322
2323 fn approved_hns_accounts(
2324 &mut self,
2325 authority_handle: HostAuthorityHandleId,
2326 authority_revision: u64,
2327 call: &ApprovedCall,
2328 now_unix_ms: u64,
2329 ) -> Result<Value, ServiceFailure> {
2330 validate_empty_params(&call.params)?;
2331 if call.namespace != SelectedNamespace::Hns {
2332 return Err(invalid_request(
2333 "Handshake accounts require the HNS namespace",
2334 ));
2335 }
2336 let permission = self
2337 .provider
2338 .permission_snapshot(authority_handle, authority_revision, now_unix_ms)
2339 .map_err(provider_failure)?;
2340 let record = permission
2341 .record
2342 .ok_or_else(|| provider_failure(ProviderError::Unauthorized))?;
2343 let selected = self.runtime.selected_hns_account()?;
2344 validate_hns_account_summary(&selected)?;
2345 let selected_accounts = BTreeSet::from([selected.account_id]);
2346 if !record
2347 .capabilities
2348 .contains(&PermissionCapability::Accounts)
2349 || record.approved_accounts != selected_accounts
2350 {
2351 return Err(provider_failure(ProviderError::Unauthorized));
2352 }
2353 Ok(json!([selected.account_id.to_string()]))
2354 }
2355}
2356
2357impl WalletService<SharedWalletStore, PersistentControlRuntime> {
2358 pub fn new_persistent_control(store: SharedWalletStore) -> Result<Self, ServiceError> {
2362 if !store.is_locked()? {
2363 return Err(ServiceError::PersistentStoreMustStartLocked);
2364 }
2365 let runtime = PersistentControlRuntime::new(store.clone());
2366 Self::new(store, runtime, true)
2367 }
2368}
2369
2370impl WalletService<SharedWalletStore, PersistentHnsAccountRuntime> {
2371 pub fn new_persistent_hns_accounts(
2375 store: SharedWalletStore,
2376 config: PersistentHnsAccountConfig,
2377 ) -> Result<Self, ServiceError> {
2378 if !store.is_locked()? {
2379 return Err(ServiceError::PersistentStoreMustStartLocked);
2380 }
2381 if !config.selector.shares_store_authority(&store) {
2382 return Err(ServiceError::PersistentStoreAuthorityMismatch);
2383 }
2384 if config.account_label.is_empty()
2385 || config.account_label.len() > MAX_PUBLIC_STRING_BYTES
2386 || !is_printable_ascii(&config.account_label)
2387 {
2388 return Err(ServiceError::InvalidPersistentHnsAccount);
2389 }
2390 let runtime = PersistentHnsAccountRuntime::new(store.clone(), config);
2391 Self::new(store, runtime, true)
2392 }
2393}
2394
2395impl<B: HnsBackend, C: HnsClock> WalletService<SharedWalletStore, PersistentHnsReadRuntime<B, C>> {
2396 pub fn new_persistent_hns_reads(
2400 store: SharedWalletStore,
2401 config: PersistentHnsReadConfig<B, C>,
2402 ) -> Result<Self, ServiceError> {
2403 if !store.is_locked()? {
2404 return Err(ServiceError::PersistentStoreMustStartLocked);
2405 }
2406 if !config.runtime.shares_store_authority(&store) {
2407 return Err(ServiceError::PersistentStoreAuthorityMismatch);
2408 }
2409 if config.account_label.is_empty()
2410 || config.account_label.len() > MAX_PUBLIC_STRING_BYTES
2411 || !is_printable_ascii(&config.account_label)
2412 {
2413 return Err(ServiceError::InvalidPersistentHnsAccount);
2414 }
2415 let runtime = PersistentHnsReadRuntime::new(store.clone(), config);
2416 Self::new(store, runtime, true)
2417 }
2418
2419 pub fn synchronize_trusted_native_hns_reads(
2428 &self,
2429 ) -> Result<HnsAccountReadSnapshot, ServiceFailure> {
2430 let snapshot = self.runtime.synchronize()?;
2431 if snapshot.transactions.len() > MAX_PROVIDER_HNS_READ_ITEMS {
2432 return Err(hns_read_result_bound());
2433 }
2434 Ok(snapshot)
2435 }
2436
2437 pub fn local_trusted_native_hns_receive_target(&self) -> Result<ReceiveTarget, ServiceFailure> {
2442 let selected = self.runtime.exact_account()?;
2443 let target = self
2444 .runtime
2445 .runtime
2446 .local_receive_target()
2447 .map_err(hns_read_failure)?;
2448 if target.module != ModuleId::Handshake
2449 || target.account != selected.account_id
2450 || target.validate().is_err()
2451 {
2452 return Err(hns_read_failure(HnsWalletError::InvalidEvidence));
2453 }
2454 Ok(target)
2455 }
2456
2457 pub fn import_trusted_native_hns_name_exact_text(
2463 &self,
2464 name: &str,
2465 ) -> Result<NativeHnsNameSummary, ServiceFailure> {
2466 self.runtime.import_name_exact_text(name)
2467 }
2468
2469 pub fn import_trusted_native_hns_names_exact_text(
2472 &self,
2473 names: &[&str],
2474 ) -> Result<Vec<NativeHnsNameSummary>, ServiceFailure> {
2475 self.runtime.import_names_exact_text(names)
2476 }
2477}
2478
2479impl WalletService<SharedWalletStore, PersistentNativeHnsReadRuntime> {
2480 pub fn new_persistent_native_hns_reads(
2492 store: SharedWalletStore,
2493 config: PersistentNativeHnsReadConfig,
2494 ) -> Result<Self, ServiceError> {
2495 if !store.is_locked()? {
2496 return Err(ServiceError::PersistentStoreMustStartLocked);
2497 }
2498 let PersistentNativeHnsReadConfig {
2499 account,
2500 node_rpc,
2501 account_label,
2502 } = config;
2503 let selector = HnsExistingAccountSelector::new(store.clone(), account)
2504 .map_err(|_| ServiceError::InvalidPersistentHnsAccount)?;
2505 let backend = HnsNodeRpcBackend::new(node_rpc)
2506 .map_err(|_| ServiceError::InvalidPersistentHnsAccount)?;
2507 let runtime = HnsAccountReadRuntime::new(backend, HnsSystemClock, store.clone(), selector)
2508 .map_err(|_| ServiceError::PersistentStoreAuthorityMismatch)?;
2509 Self::new_persistent_hns_reads(
2510 store,
2511 PersistentHnsReadConfig {
2512 runtime,
2513 account_label,
2514 },
2515 )
2516 }
2517}
2518
2519impl WalletService<SharedWalletStore, PersistentNativeRecoveryReadOnlyRuntime> {
2520 pub(crate) fn new_persisted_recovery_read_only_native_hns_reads(
2524 store: SharedWalletStore,
2525 config: PersistentNativeHnsReadConfig,
2526 ) -> Result<Self, ServiceError> {
2527 if !store.is_locked()? {
2528 return Err(ServiceError::PersistentStoreMustStartLocked);
2529 }
2530 let PersistentNativeHnsReadConfig {
2531 account,
2532 node_rpc,
2533 account_label,
2534 } = config;
2535 if account_label.is_empty()
2536 || account_label.len() > MAX_PUBLIC_STRING_BYTES
2537 || !is_printable_ascii(&account_label)
2538 {
2539 return Err(ServiceError::InvalidPersistentHnsAccount);
2540 }
2541 let backend = HnsNodeRpcBackend::new(node_rpc)
2542 .map_err(|_| ServiceError::InvalidPersistentHnsAccount)?;
2543 let runtime = HnsPersistedRecoveryReadOnlyRuntime::new(
2544 backend,
2545 HnsSystemClock,
2546 store.clone(),
2547 account,
2548 )
2549 .map_err(|_| ServiceError::InvalidPersistentHnsAccount)?;
2550 if !runtime.shares_store_authority(&store) {
2551 return Err(ServiceError::PersistentStoreAuthorityMismatch);
2552 }
2553 Self::new(
2554 store.clone(),
2555 PersistentRecoveryReadOnlyHnsRuntime::new(store, runtime, account_label),
2556 false,
2557 )
2558 }
2559}
2560
2561fn provider_authority(
2562 authority: HostAuthorityFacts,
2563) -> Result<HostAuthorityRegistration, ServiceFailure> {
2564 Ok(HostAuthorityRegistration {
2565 origin: Origin::parse(&authority.origin).map_err(provider_failure)?,
2566 namespace: match authority.namespace {
2567 ProviderNamespace::Hns => SelectedNamespace::Hns,
2568 ProviderNamespace::Icann => SelectedNamespace::Icann,
2569 },
2570 runtime_session: authority.runtime_session_id,
2571 runtime_generation: authority.runtime_generation,
2572 policy_generation: authority.policy_generation,
2573 navigation_generation: authority.navigation_generation,
2574 decision_fingerprint: authority.decision_fingerprint,
2575 valid_until_unix_ms: authority.valid_until_unix_ms,
2576 })
2577}
2578
2579fn service_owned_method(method: ProviderMethod) -> bool {
2580 matches!(
2581 method,
2582 ProviderMethod::WalletGetCapabilities
2583 | ProviderMethod::WalletRequestPermissions
2584 | ProviderMethod::WalletGetPermissions
2585 | ProviderMethod::WalletRevokePermissions
2586 | ProviderMethod::HnsAccounts
2587 | ProviderMethod::WalletLock
2588 )
2589}
2590
2591fn hns_account_read_method(method: ProviderMethod) -> bool {
2592 matches!(
2593 method,
2594 ProviderMethod::HnsGetBalance
2595 | ProviderMethod::HnsGetTransactions
2596 | ProviderMethod::HnsGetReceiveAddress
2597 | ProviderMethod::HnsGetNames
2598 | ProviderMethod::HnsGetName
2599 )
2600}
2601
2602fn value_movement_approval(kind: ApprovalKind) -> bool {
2603 matches!(
2604 kind,
2605 ApprovalKind::Send
2606 | ApprovalKind::NameTransfer
2607 | ApprovalKind::NameFinalize
2608 | ApprovalKind::NameMarketOffer
2609 | ApprovalKind::NameMarketPurchase
2610 | ApprovalKind::DirectOffer
2611 | ApprovalKind::DirectOfferAcceptance
2612 | ApprovalKind::SwapRedeem
2613 | ApprovalKind::SwapRefund
2614 )
2615}
2616
2617fn requested_capabilities(
2618 call: &ApprovedCall,
2619) -> Result<BTreeSet<PermissionCapability>, ServiceFailure> {
2620 if call.method == ProviderMethod::HnsRequestAccounts {
2621 return Ok(BTreeSet::from([PermissionCapability::Accounts]));
2622 }
2623 requested_capabilities_from_params(&call.params)
2624}
2625
2626fn requested_capabilities_from_params(
2627 params: &Value,
2628) -> Result<BTreeSet<PermissionCapability>, ServiceFailure> {
2629 let value = params
2630 .get("capabilities")
2631 .or_else(|| params.get("scopes"))
2632 .cloned()
2633 .ok_or_else(|| invalid_request("permission capabilities are required"))?;
2634 let capabilities: BTreeSet<PermissionCapability> = serde_json::from_value(value)
2635 .map_err(|_| invalid_request("permission capabilities are invalid"))?;
2636 if capabilities.is_empty() {
2637 return Err(invalid_request("permission capabilities are empty"));
2638 }
2639 if capabilities.contains(&PermissionCapability::Accounts) {
2640 return Err(invalid_request(
2641 "Accounts permission requires hns_requestAccounts",
2642 ));
2643 }
2644 Ok(capabilities)
2645}
2646
2647fn validate_empty_params(params: &Value) -> Result<(), ServiceFailure> {
2648 if params.is_null() || params.as_object().is_some_and(|object| object.is_empty()) {
2649 Ok(())
2650 } else {
2651 Err(invalid_request("method does not accept parameters"))
2652 }
2653}
2654
2655fn bounded_provider_value(value: Value) -> Result<Value, ServiceFailure> {
2656 if serde_json::to_vec(&value)
2657 .map_err(|_| invalid_request("provider result encoding failed"))?
2658 .len()
2659 > MAX_PROVIDER_RESULT_BYTES
2660 {
2661 return Err(invalid_request(
2662 "provider result exceeds the provider bound",
2663 ));
2664 }
2665 Ok(value)
2666}
2667
2668fn hns_name_hash_param(params: &Value) -> Result<[u8; 32], ServiceFailure> {
2669 let object = params
2670 .as_object()
2671 .filter(|object| object.len() == 1)
2672 .ok_or_else(|| invalid_request("hns_getName requires only nameHash"))?;
2673 let encoded = object
2674 .get("nameHash")
2675 .and_then(Value::as_str)
2676 .filter(|encoded| encoded.len() == 64)
2677 .ok_or_else(|| invalid_request("nameHash must be 32-byte lowercase hexadecimal"))?;
2678 let mut output = [0_u8; 32];
2679 for (index, pair) in encoded.as_bytes().chunks_exact(2).enumerate() {
2680 let decode = |byte| match byte {
2681 b'0'..=b'9' => Some(byte - b'0'),
2682 b'a'..=b'f' => Some(byte - b'a' + 10),
2683 _ => None,
2684 };
2685 let high = decode(pair[0])
2686 .ok_or_else(|| invalid_request("nameHash must be canonical lowercase hexadecimal"))?;
2687 let low = decode(pair[1])
2688 .ok_or_else(|| invalid_request("nameHash must be canonical lowercase hexadecimal"))?;
2689 output[index] = (high << 4) | low;
2690 }
2691 Ok(output)
2692}
2693
2694fn public_hns_non_name_read(
2695 call: &ApprovedCall,
2696 snapshot: &HnsAccountReadSnapshot,
2697) -> Result<Value, ServiceFailure> {
2698 validate_empty_params(&call.params)?;
2699 match call.method {
2700 ProviderMethod::HnsGetBalance => bounded_provider_value(json!({
2701 "amount": public_hns_amount(snapshot.balance)?,
2702 })),
2703 ProviderMethod::HnsGetTransactions => {
2704 if snapshot.transactions.len() > MAX_PROVIDER_HNS_READ_ITEMS {
2705 return Err(hns_read_result_bound());
2706 }
2707 let transactions = snapshot
2708 .transactions
2709 .iter()
2710 .map(public_hns_transaction_summary)
2711 .collect::<Result<Vec<_>, _>>()?;
2712 bounded_provider_value(json!({ "transactions": transactions }))
2713 }
2714 ProviderMethod::HnsGetReceiveAddress => bounded_provider_value(json!({
2715 "target": public_hns_receive_target(&snapshot.receive_target, snapshot.account_id)?,
2716 })),
2717 _ => Err(ServiceFailure::unsupported(
2718 ServiceCapability::ProviderDispatch,
2719 )),
2720 }
2721}
2722
2723fn hns_name_approval_scope(
2724 known_names: Vec<KnownName>,
2725) -> Result<PendingHnsNameScope, ServiceFailure> {
2726 if known_names.len() > MAX_HNS_NAME_DISCLOSURES {
2727 return Err(hns_read_result_bound());
2728 }
2729 let mut hashes = BTreeSet::new();
2730 let mut canonical_names = BTreeSet::new();
2731 let mut disclosures = Vec::with_capacity(known_names.len());
2732 for known_name in &known_names {
2733 let disclosure = hns_name_disclosure(known_name)?;
2734 if !hashes.insert(known_name.name_hash) || !canonical_names.insert(disclosure.name.clone())
2735 {
2736 return Err(hns_read_failure(HnsWalletError::InvalidEvidence));
2737 }
2738 disclosures.push(disclosure);
2739 }
2740 disclosures.sort();
2741 Ok(PendingHnsNameScope {
2742 disclosures,
2743 hashes,
2744 })
2745}
2746
2747fn hns_name_disclosure(name: &KnownName) -> Result<HnsNameDisclosure, ServiceFailure> {
2748 let disclosure = HnsNameDisclosure {
2749 name: canonical_hns_name(name)?.to_owned(),
2750 name_hash: lowercase_hex(&name.name_hash),
2751 };
2752 disclosure
2753 .validate()
2754 .map_err(|_| hns_read_failure(HnsWalletError::InvalidEvidence))?;
2755 Ok(disclosure)
2756}
2757
2758fn native_hns_name_summary(name: &KnownName) -> Result<NativeHnsNameSummary, ServiceFailure> {
2759 if name.proof_height > MAX_JAVASCRIPT_SAFE_INTEGER {
2760 return Err(invalid_request(
2761 "known HNS name proof height exceeds JavaScript integer precision",
2762 ));
2763 }
2764 let disclosure = hns_name_disclosure(name)?;
2765 let resource_status = match name.resource_status {
2766 NameResourceStatus::UnavailableCanonicalBinding => {
2767 NativeHnsNameResourceStatus::UnavailableCanonicalBinding
2768 }
2769 NameResourceStatus::NoCurrentState => NativeHnsNameResourceStatus::NoCurrentState,
2770 NameResourceStatus::Empty => NativeHnsNameResourceStatus::Empty,
2771 NameResourceStatus::CanonicalDecoded => NativeHnsNameResourceStatus::CanonicalDecoded,
2772 NameResourceStatus::CanonicalOpaque => NativeHnsNameResourceStatus::CanonicalOpaque,
2773 };
2774 let ownership_status = match &name.ownership_status {
2775 NameOwnershipStatus::WatchOnlyCanonicalStateDecoderUnavailable => {
2776 NativeHnsNameOwnershipStatus::WatchOnlyCanonicalStateDecoderUnavailable
2777 }
2778 NameOwnershipStatus::WatchOnlyOwnerTransactionUnavailable => {
2779 NativeHnsNameOwnershipStatus::WatchOnlyOwnerTransactionUnavailable
2780 }
2781 NameOwnershipStatus::WalletContextUnavailable => {
2782 NativeHnsNameOwnershipStatus::WalletContextUnavailable
2783 }
2784 NameOwnershipStatus::NoCurrentOwner => NativeHnsNameOwnershipStatus::NoCurrentOwner,
2785 NameOwnershipStatus::NotWalletOwned => NativeHnsNameOwnershipStatus::NotWalletOwned,
2786 NameOwnershipStatus::WalletOwned { .. } => NativeHnsNameOwnershipStatus::WalletOwned,
2787 NameOwnershipStatus::IncomingTransfer { .. } => {
2788 NativeHnsNameOwnershipStatus::IncomingTransfer
2789 }
2790 NameOwnershipStatus::OutgoingTransfer { .. } => {
2791 NativeHnsNameOwnershipStatus::OutgoingTransfer
2792 }
2793 };
2794 let (registered, expired) = name
2795 .canonical_current_state
2796 .as_ref()
2797 .map_or((None, None), |state| {
2798 (Some(state.registered), Some(state.expired))
2799 });
2800 let canonical_state =
2801 name.canonical_current_state
2802 .as_ref()
2803 .map(|state| NativeHnsNameStateSummary {
2804 value: state.value,
2805 highest: state.highest,
2806 start_height: state.start_height,
2807 renewal_height: state.renewal_height,
2808 transfer_height: state.transfer_height,
2809 revoked_height: state.revoked_height,
2810 claimed_height: state.claimed_height,
2811 renewals: state.renewals,
2812 weak: state.weak,
2813 });
2814 Ok(NativeHnsNameSummary {
2815 name: disclosure.name,
2816 name_hash: disclosure.name_hash,
2817 proof_height: name.proof_height,
2818 resource_status,
2819 ownership_status,
2820 registered,
2821 expired,
2822 canonical_state,
2823 raw_resource: name.current_raw_resource.clone(),
2824 })
2825}
2826
2827fn canonical_hns_name(name: &KnownName) -> Result<&str, ServiceFailure> {
2828 std::str::from_utf8(&name.name)
2829 .ok()
2830 .filter(|display| {
2831 !display.is_empty()
2832 && display.len() <= MAX_HNS_NAME_BYTES
2833 && is_printable_ascii(display)
2834 })
2835 .ok_or_else(|| invalid_request("known HNS name is not canonical public text"))
2836}
2837
2838fn public_hns_name_read(
2839 call: &ApprovedCall,
2840 approved_names: &BTreeSet<[u8; 32]>,
2841 known_names: &[KnownName],
2842) -> Result<Value, ServiceFailure> {
2843 if approved_names.len() > MAX_PROVIDER_HNS_READ_ITEMS {
2844 return Err(hns_read_result_bound());
2845 }
2846 let current_names = known_names
2847 .iter()
2848 .map(|name| (name.name_hash, name))
2849 .collect::<BTreeMap<_, _>>();
2850 if current_names.len() != known_names.len()
2851 || !approved_names
2852 .iter()
2853 .all(|name_hash| current_names.contains_key(name_hash))
2854 {
2855 return Err(provider_failure(ProviderError::Unauthorized));
2856 }
2857 match call.method {
2858 ProviderMethod::HnsGetNames => {
2859 validate_empty_params(&call.params)?;
2860 let names = approved_names
2861 .iter()
2862 .map(|name_hash| {
2863 current_names
2864 .get(name_hash)
2865 .ok_or_else(|| provider_failure(ProviderError::Unauthorized))
2866 .and_then(|name| public_hns_name_summary(name))
2867 })
2868 .collect::<Result<Vec<_>, _>>()?;
2869 bounded_provider_value(json!({ "names": names }))
2870 }
2871 ProviderMethod::HnsGetName => {
2872 let name_hash = hns_name_hash_param(&call.params)?;
2873 if !approved_names.contains(&name_hash) {
2874 return Err(provider_failure(ProviderError::Unauthorized));
2875 }
2876 let name = current_names
2877 .get(&name_hash)
2878 .ok_or_else(|| provider_failure(ProviderError::Unauthorized))?;
2879 bounded_provider_value(json!({ "name": public_hns_name_summary(name)? }))
2880 }
2881 _ => Err(ServiceFailure::unsupported(
2882 ServiceCapability::ProviderDispatch,
2883 )),
2884 }
2885}
2886
2887fn public_hns_amount(amount: Amount) -> Result<Value, ServiceFailure> {
2888 if amount.asset != WalletAsset::Hns {
2889 return Err(invalid_request("HNS balance contains a non-HNS asset"));
2890 }
2891 Ok(json!({
2892 "asset": "HNS",
2893 "baseUnits": amount.base_units.get().to_string(),
2894 }))
2895}
2896
2897fn public_hns_receive_target(
2898 target: &ReceiveTarget,
2899 expected_account: hns_wallet_types::AccountId,
2900) -> Result<Value, ServiceFailure> {
2901 if target.module != ModuleId::Handshake || target.account != expected_account {
2902 return Err(invalid_request(
2903 "HNS receive target does not match the synchronized account",
2904 ));
2905 }
2906 target
2907 .validate()
2908 .map_err(|_| invalid_request("HNS receive target is invalid"))?;
2909 if !is_printable_ascii(&target.display) {
2910 return Err(invalid_request(
2911 "HNS receive target is not canonical public text",
2912 ));
2913 }
2914 Ok(json!({
2915 "module": "handshake",
2916 "account": lowercase_hex(target.account.as_bytes()),
2917 "display": &target.display,
2918 "derivationIndex": target.derivation_index,
2919 }))
2920}
2921
2922fn public_hns_transaction_summary(
2923 transaction: &TransactionSummary,
2924) -> Result<Value, ServiceFailure> {
2925 if transaction.module != ModuleId::Handshake {
2926 return Err(invalid_request(
2927 "HNS transaction history contains a non-HNS transaction",
2928 ));
2929 }
2930 if transaction
2931 .block_height
2932 .is_some_and(|height| height > MAX_JAVASCRIPT_SAFE_INTEGER)
2933 || transaction
2934 .first_seen_unix
2935 .is_some_and(|time| time > MAX_JAVASCRIPT_SAFE_INTEGER)
2936 {
2937 return Err(invalid_request(
2938 "HNS transaction history exceeds JavaScript integer precision",
2939 ));
2940 }
2941 let status = match transaction.status {
2942 LocalTransactionStatus::Prepared => "prepared",
2943 LocalTransactionStatus::Authorized => "authorized",
2944 LocalTransactionStatus::Broadcast => "broadcast",
2945 LocalTransactionStatus::Mempool => "mempool",
2946 LocalTransactionStatus::Confirmed => "confirmed",
2947 LocalTransactionStatus::Replaced => "replaced",
2948 LocalTransactionStatus::Conflicted => "conflicted",
2949 LocalTransactionStatus::Reorged => "reorged",
2950 LocalTransactionStatus::Dropped => "dropped",
2951 LocalTransactionStatus::Failed => "failed",
2952 };
2953 Ok(json!({
2954 "module": "handshake",
2955 "txid": lowercase_hex(transaction.txid.as_bytes()),
2956 "status": status,
2957 "netAmount": {
2958 "negative": transaction.net_amount.negative,
2959 "magnitude": transaction.net_amount.magnitude.get().to_string(),
2960 },
2961 "fee": transaction.fee.map(|fee| fee.get().to_string()),
2962 "blockHeight": transaction.block_height,
2963 "firstSeenUnix": transaction.first_seen_unix,
2964 "confirmationCount": transaction.confirmation_count,
2965 }))
2966}
2967
2968fn public_hns_name_summary(name: &KnownName) -> Result<Value, ServiceFailure> {
2969 if name.proof_height > MAX_JAVASCRIPT_SAFE_INTEGER {
2970 return Err(invalid_request(
2971 "known HNS name proof height exceeds JavaScript integer precision",
2972 ));
2973 }
2974 let disclosure = hns_name_disclosure(name)?;
2975 let resource_status = match &name.resource_status {
2976 NameResourceStatus::UnavailableCanonicalBinding => "unavailableCanonicalBinding",
2977 NameResourceStatus::NoCurrentState => "noCurrentState",
2978 NameResourceStatus::Empty => "empty",
2979 NameResourceStatus::CanonicalDecoded => "canonicalDecoded",
2980 NameResourceStatus::CanonicalOpaque => "canonicalOpaque",
2981 };
2982 let ownership_status = match &name.ownership_status {
2983 NameOwnershipStatus::WatchOnlyCanonicalStateDecoderUnavailable => {
2984 "watchOnlyCanonicalStateDecoderUnavailable"
2985 }
2986 NameOwnershipStatus::WatchOnlyOwnerTransactionUnavailable => {
2987 "watchOnlyOwnerTransactionUnavailable"
2988 }
2989 NameOwnershipStatus::WalletContextUnavailable => "walletContextUnavailable",
2990 NameOwnershipStatus::NoCurrentOwner => "noCurrentOwner",
2991 NameOwnershipStatus::NotWalletOwned => "notWalletOwned",
2992 NameOwnershipStatus::WalletOwned { .. } => "walletOwned",
2993 NameOwnershipStatus::IncomingTransfer { .. } => "incomingTransfer",
2994 NameOwnershipStatus::OutgoingTransfer { .. } => "outgoingTransfer",
2995 };
2996 let (registered, expired) = name
2997 .canonical_current_state
2998 .as_ref()
2999 .map_or((None, None), |state| {
3000 (Some(state.registered), Some(state.expired))
3001 });
3002 Ok(json!({
3003 "name": disclosure.name,
3004 "nameHash": disclosure.name_hash,
3005 "proofHeight": name.proof_height,
3006 "resourceStatus": resource_status,
3007 "ownershipStatus": ownership_status,
3008 "registered": registered,
3009 "expired": expired,
3010 }))
3011}
3012
3013fn lowercase_hex(bytes: &[u8]) -> String {
3014 const HEX: &[u8; 16] = b"0123456789abcdef";
3015 let mut encoded = String::with_capacity(bytes.len() * 2);
3016 for byte in bytes {
3017 encoded.push(HEX[(byte >> 4) as usize] as char);
3018 encoded.push(HEX[(byte & 0x0f) as usize] as char);
3019 }
3020 encoded
3021}
3022
3023fn is_printable_ascii(value: &str) -> bool {
3024 value.bytes().all(|byte| (0x20..=0x7e).contains(&byte))
3025}
3026
3027fn hns_read_result_bound() -> ServiceFailure {
3028 ServiceFailure {
3029 code: ServiceErrorCode::RuntimeFailure,
3030 message: "synchronized Handshake read exceeds its public result bound".to_owned(),
3031 unsupported_capability: None,
3032 }
3033}
3034
3035fn validate_hns_wallet_read_scope(
3036 module: ModuleId,
3037 requested: hns_wallet_types::AccountId,
3038 selected: hns_wallet_types::AccountId,
3039) -> Result<(), ServiceFailure> {
3040 if module != ModuleId::Handshake || requested != selected {
3041 return Err(invalid_request(
3042 "wallet read does not match the selected HNS account",
3043 ));
3044 }
3045 Ok(())
3046}
3047
3048fn validate_hns_account_summary(account: &AccountSummary) -> Result<(), ServiceFailure> {
3049 let valid_receive = account.receive_display.as_ref().is_none_or(|value| {
3050 !value.is_empty() && value.len() <= MAX_PUBLIC_STRING_BYTES && is_printable_ascii(value)
3051 });
3052 if account.module != ModuleId::Handshake
3053 || account.account_id.as_bytes().iter().all(|byte| *byte == 0)
3054 || account.label.is_empty()
3055 || account.label.len() > MAX_PUBLIC_STRING_BYTES
3056 || !is_printable_ascii(&account.label)
3057 || !valid_receive
3058 {
3059 return Err(invalid_request("runtime returned an invalid HNS account"));
3060 }
3061 Ok(())
3062}
3063
3064fn requested_module(params: &Value) -> Result<ModuleId, ServiceFailure> {
3065 serde_json::from_value(
3066 params
3067 .get("module")
3068 .cloned()
3069 .ok_or_else(|| invalid_request("module is required"))?,
3070 )
3071 .map_err(|_| invalid_request("module is invalid"))
3072}
3073
3074fn validate_approval_summary(
3075 call: &ApprovedCall,
3076 summary: &ApprovalSummary,
3077) -> Result<(), ServiceFailure> {
3078 let ApprovalSummary::Send {
3079 amount,
3080 maximum_fee,
3081 chain,
3082 ..
3083 } = summary
3084 else {
3085 if matches!(
3086 call.method,
3087 ProviderMethod::HnsSend | ProviderMethod::AssetSend
3088 ) {
3089 return Err(invalid_request("send approval summary is mismatched"));
3090 }
3091 return Ok(());
3092 };
3093
3094 let expected_chain = match call.method {
3095 ProviderMethod::HnsSend => ModuleId::Handshake,
3096 ProviderMethod::AssetSend => {
3097 let module = requested_module(&call.params)?;
3098 if !matches!(module, ModuleId::Bitcoin | ModuleId::Ethereum) {
3099 return Err(invalid_request("external send module is invalid"));
3100 }
3101 module
3102 }
3103 _ => return Ok(()),
3104 };
3105 if *chain != expected_chain
3106 || amount.asset != expected_chain.asset()
3107 || maximum_fee.asset != expected_chain.asset()
3108 {
3109 return Err(invalid_request(
3110 "send approval asset or chain is mismatched",
3111 ));
3112 }
3113 Ok(())
3114}
3115
3116fn permission_value(permission: PermissionSnapshot) -> Result<Value, ServiceFailure> {
3117 let Some(record) = permission.record else {
3118 return Ok(json!({
3119 "permissionGeneration": permission.generation,
3120 "capabilities": [],
3121 "accounts": []
3122 }));
3123 };
3124 let origin = record.origin.as_str().to_owned();
3125 let capabilities = record.capabilities;
3126 let accounts = record
3127 .approved_accounts
3128 .iter()
3129 .map(ToString::to_string)
3130 .collect::<Vec<_>>();
3131 Ok(json!({
3132 "origin": origin,
3133 "permissionGeneration": permission.generation,
3134 "capabilities": capabilities,
3135 "accounts": accounts,
3136 "expiresAtUnix": record.expires_at_unix,
3137 }))
3138}
3139
3140fn wire_approval_id(id: ApprovalId) -> Result<ProviderApprovalId, ServiceFailure> {
3141 ProviderApprovalId::from_bytes(id.into_bytes())
3142 .map_err(|_| invalid_request("approval identifier is invalid"))
3143}
3144
3145fn random_service_session() -> Result<WalletServiceSessionId, ServiceError> {
3146 loop {
3147 let mut bytes = [0_u8; 32];
3148 getrandom::fill(&mut bytes).map_err(|_| ServiceError::Randomness)?;
3149 if let Ok(id) = WalletServiceSessionId::from_bytes(bytes) {
3150 return Ok(id);
3151 }
3152 }
3153}
3154
3155fn random_wallet_session() -> Result<WalletSessionId, ServiceError> {
3156 loop {
3157 let mut bytes = [0_u8; 32];
3158 getrandom::fill(&mut bytes).map_err(|_| ServiceError::Randomness)?;
3159 if let Ok(id) = WalletSessionId::from_bytes(bytes) {
3160 return Ok(id);
3161 }
3162 }
3163}
3164
3165fn invalid_request(message: &str) -> ServiceFailure {
3166 ServiceFailure {
3167 code: ServiceErrorCode::InvalidRequest,
3168 message: message.to_owned(),
3169 unsupported_capability: None,
3170 }
3171}
3172
3173fn wallet_locked() -> ServiceFailure {
3174 ServiceFailure {
3175 code: ServiceErrorCode::WalletLocked,
3176 message: "wallet is locked".to_owned(),
3177 unsupported_capability: None,
3178 }
3179}
3180
3181fn hns_runtime_failure(error: HnsWalletError) -> ServiceFailure {
3182 let (code, message) = match error {
3183 HnsWalletError::StoreLocked => (ServiceErrorCode::WalletLocked, "wallet is locked"),
3184 HnsWalletError::Store
3185 | HnsWalletError::AccountConfigurationMismatch
3186 | HnsWalletError::DuplicateAccountDerivation
3187 | HnsWalletError::InvalidEvidence => (
3188 ServiceErrorCode::PersistenceFailure,
3189 "exact Handshake account selection failed",
3190 ),
3191 _ => (
3192 ServiceErrorCode::RuntimeFailure,
3193 "Handshake account selector failed",
3194 ),
3195 };
3196 ServiceFailure {
3197 code,
3198 message: message.to_owned(),
3199 unsupported_capability: None,
3200 }
3201}
3202
3203fn hns_name_preparation_failure(error: HnsWalletError) -> ServiceFailure {
3209 let detail = error.to_string();
3210 let mut failure = hns_runtime_failure(error);
3211 failure.message = format!("Handshake name action preparation failed: {detail}");
3212 failure
3213}
3214
3215fn hns_read_failure(error: HnsWalletError) -> ServiceFailure {
3216 let (code, message) = match error {
3217 HnsWalletError::StoreLocked => (ServiceErrorCode::WalletLocked, "wallet is locked"),
3218 HnsWalletError::StaleNodeSnapshot | HnsWalletError::StaleAccountRead => (
3219 ServiceErrorCode::RuntimeFailure,
3220 "Handshake read snapshot changed during synchronization",
3221 ),
3222 HnsWalletError::Store
3223 | HnsWalletError::StoreAuthorityMismatch
3224 | HnsWalletError::AccountConfigurationMismatch
3225 | HnsWalletError::DuplicateAccountDerivation
3226 | HnsWalletError::InvalidEvidence => (
3227 ServiceErrorCode::PersistenceFailure,
3228 "synchronized Handshake account state failed authentication",
3229 ),
3230 HnsWalletError::ScanCapacityExhausted | HnsWalletError::HistoryLimit => (
3231 ServiceErrorCode::RuntimeFailure,
3232 "synchronized Handshake read exceeds its configured bound",
3233 ),
3234 _ => (
3235 ServiceErrorCode::RuntimeFailure,
3236 "Handshake account synchronization failed",
3237 ),
3238 };
3239 ServiceFailure {
3240 code,
3241 message: message.to_owned(),
3242 unsupported_capability: None,
3243 }
3244}
3245
3246fn hns_native_name_import_failure(error: HnsWalletError) -> ServiceFailure {
3247 match error {
3248 HnsWalletError::InvalidName => invalid_request(
3249 "HNS name must be exact canonical text without trimming or normalization",
3250 ),
3251 error => hns_read_failure(error),
3252 }
3253}
3254
3255fn stale_approval() -> ServiceFailure {
3256 ServiceFailure {
3257 code: ServiceErrorCode::ApprovalStale,
3258 message: "approval is stale, expired, or belongs to another authority".to_owned(),
3259 unsupported_capability: None,
3260 }
3261}
3262
3263fn provider_failure(error: ProviderError) -> ServiceFailure {
3264 let code = match error {
3265 ProviderError::AuthorityNotFound => ServiceErrorCode::AuthorityUnknown,
3266 ProviderError::DuplicateAuthority
3267 | ProviderError::AuthorityCapacity
3268 | ProviderError::StaleContext
3269 | ProviderError::ClockRollback => ServiceErrorCode::AuthorityStale,
3270 ProviderError::Unauthorized => ServiceErrorCode::PermissionDenied,
3271 ProviderError::WalletLocked => ServiceErrorCode::WalletLocked,
3272 ProviderError::RateLimited => ServiceErrorCode::RateLimited,
3273 ProviderError::Replay => ServiceErrorCode::Replay,
3274 ProviderError::StaleApproval => ServiceErrorCode::ApprovalStale,
3275 ProviderError::Persistence => ServiceErrorCode::PersistenceFailure,
3276 _ => ServiceErrorCode::InvalidRequest,
3277 };
3278 ServiceFailure {
3279 code,
3280 message: error.to_string(),
3281 unsupported_capability: None,
3282 }
3283}
3284
3285fn persistent_store_failure(error: StoreError) -> ServiceFailure {
3286 let code = match &error {
3287 StoreError::Locked => ServiceErrorCode::WalletLocked,
3288 StoreError::InvalidPassphrase => ServiceErrorCode::PermissionDenied,
3289 _ => ServiceErrorCode::PersistenceFailure,
3290 };
3291 ServiceFailure {
3292 code,
3293 message: error.to_string(),
3294 unsupported_capability: None,
3295 }
3296}
3297
3298impl From<ServiceError> for ServiceFailure {
3299 fn from(error: ServiceError) -> Self {
3300 Self {
3301 code: ServiceErrorCode::RuntimeFailure,
3302 message: error.to_string(),
3303 unsupported_capability: None,
3304 }
3305 }
3306}
3307
3308#[derive(Debug, Error)]
3309pub enum ServiceError {
3310 #[error("operating-system randomness is unavailable")]
3311 Randomness,
3312 #[error("wallet service ABI rejected a frame: {0}")]
3313 Abi(#[from] hns_wallet_ffi::AbiError),
3314 #[error("provider authority or state rejected an operation: {0}")]
3315 Provider(#[from] ProviderError),
3316 #[error("wallet persistence failed: {0}")]
3317 Store(#[from] StoreError),
3318 #[error("persistent wallet service must start with a locked store")]
3319 PersistentStoreMustStartLocked,
3320 #[error("persistent HNS selector must share the identical store authority")]
3321 PersistentStoreAuthorityMismatch,
3322 #[error("persistent HNS account configuration is invalid")]
3323 InvalidPersistentHnsAccount,
3324 #[error("host must negotiate a private service session first")]
3325 HandshakeRequired,
3326 #[error("wallet service session was already negotiated")]
3327 AlreadyNegotiated,
3328 #[error("host, service, or restart session does not match")]
3329 SessionMismatch,
3330 #[error("host channel sequence mismatch: expected {expected}, received {received}")]
3331 SequenceMismatch { expected: u64, received: u64 },
3332 #[error("request identifier was already consumed")]
3333 DuplicateRequest,
3334 #[error("channel or event sequence is exhausted")]
3335 SequenceExhausted,
3336}
3337
3338#[cfg(test)]
3339mod tests {
3340 use super::*;
3341 use hns_wallet_ffi::{HostHello, decode_service_frame, encode_host_frame};
3342 use hns_wallet_hns::{
3343 CanonicalNameStateSummary, ChainTip, HnsAccountReadBinding, HnsAccountRecord, HnsNetwork,
3344 HnsRuntimeConfig, MempoolSnapshotBinding, SnapshotBinding,
3345 };
3346 use hns_wallet_provider::MemoryProviderState;
3347 use hns_wallet_store::WalletStore;
3348 use hns_wallet_types::{
3349 AccountId, BaseUnits, BrowserRuntimeSessionId, HnsNameReceiveTarget,
3350 ProviderAuthorityFingerprint, SignedBaseUnits, TransactionHash, WalletId,
3351 };
3352
3353 const NOW_MS: u64 = 100_000;
3354
3355 #[derive(Default)]
3356 struct ProviderRuntime;
3357
3358 impl ServiceRuntime for ProviderRuntime {
3359 fn capabilities(&self) -> BTreeSet<ServiceCapability> {
3360 BTreeSet::from([ServiceCapability::ProviderDispatch])
3361 }
3362
3363 fn supports_provider_method(&self, _: ProviderMethod) -> bool {
3364 false
3365 }
3366
3367 fn prepare_approval(
3368 &mut self,
3369 _: &PendingApproval,
3370 ) -> Result<ApprovalSummary, ServiceFailure> {
3371 Err(ServiceFailure::unsupported(
3372 ServiceCapability::ProviderDispatch,
3373 ))
3374 }
3375
3376 fn execute_provider(&mut self, _: ApprovedCall) -> Result<Value, ServiceFailure> {
3377 Err(ServiceFailure::unsupported(
3378 ServiceCapability::ProviderDispatch,
3379 ))
3380 }
3381
3382 fn lock_wallet(&mut self) -> Result<(), ServiceFailure> {
3383 Err(ServiceFailure::unsupported(
3384 ServiceCapability::WalletOperations,
3385 ))
3386 }
3387
3388 fn execute_wallet(&mut self, _: WalletRequest) -> Result<WalletResponse, ServiceFailure> {
3389 Err(ServiceFailure::unsupported(
3390 ServiceCapability::WalletOperations,
3391 ))
3392 }
3393 }
3394
3395 struct HnsReadMarkerOnlyRuntime;
3396
3397 impl ServiceRuntime for HnsReadMarkerOnlyRuntime {
3398 fn capabilities(&self) -> BTreeSet<ServiceCapability> {
3399 BTreeSet::from([ServiceCapability::HnsReadOperationsV1])
3400 }
3401
3402 fn supports_provider_method(&self, _: ProviderMethod) -> bool {
3403 false
3404 }
3405
3406 fn prepare_approval(
3407 &mut self,
3408 _: &PendingApproval,
3409 ) -> Result<ApprovalSummary, ServiceFailure> {
3410 Err(ServiceFailure::unsupported(
3411 ServiceCapability::ProviderDispatch,
3412 ))
3413 }
3414
3415 fn execute_provider(&mut self, _: ApprovedCall) -> Result<Value, ServiceFailure> {
3416 Err(ServiceFailure::unsupported(
3417 ServiceCapability::ProviderDispatch,
3418 ))
3419 }
3420
3421 fn lock_wallet(&mut self) -> Result<(), ServiceFailure> {
3422 Err(ServiceFailure::unsupported(
3423 ServiceCapability::WalletOperations,
3424 ))
3425 }
3426
3427 fn execute_wallet(&mut self, _: WalletRequest) -> Result<WalletResponse, ServiceFailure> {
3428 Err(ServiceFailure::unsupported(
3429 ServiceCapability::WalletOperations,
3430 ))
3431 }
3432 }
3433
3434 struct AccountRuntime {
3435 account: AccountSummary,
3436 account_join_available: bool,
3437 }
3438
3439 impl ServiceRuntime for AccountRuntime {
3440 fn capabilities(&self) -> BTreeSet<ServiceCapability> {
3441 BTreeSet::from([ServiceCapability::ProviderDispatch])
3442 }
3443
3444 fn supports_provider_method(&self, method: ProviderMethod) -> bool {
3445 self.account_join_available && method == ProviderMethod::HnsRequestAccounts
3446 }
3447
3448 fn prepare_approval(
3449 &mut self,
3450 _: &PendingApproval,
3451 ) -> Result<ApprovalSummary, ServiceFailure> {
3452 Err(ServiceFailure::unsupported(
3453 ServiceCapability::ProviderDispatch,
3454 ))
3455 }
3456
3457 fn prepare_hns_account_grant(
3458 &mut self,
3459 _: &ApprovedCall,
3460 ) -> Result<AccountSummary, ServiceFailure> {
3461 Ok(self.account.clone())
3462 }
3463
3464 fn selected_hns_account(&self) -> Result<AccountSummary, ServiceFailure> {
3465 if self.account_join_available {
3466 Ok(self.account.clone())
3467 } else {
3468 Err(ServiceFailure::unsupported(
3469 ServiceCapability::ProviderDispatch,
3470 ))
3471 }
3472 }
3473
3474 fn execute_provider(&mut self, _: ApprovedCall) -> Result<Value, ServiceFailure> {
3475 Err(ServiceFailure::unsupported(
3476 ServiceCapability::ProviderDispatch,
3477 ))
3478 }
3479
3480 fn lock_wallet(&mut self) -> Result<(), ServiceFailure> {
3481 Err(ServiceFailure::unsupported(
3482 ServiceCapability::WalletOperations,
3483 ))
3484 }
3485
3486 fn execute_wallet(&mut self, _: WalletRequest) -> Result<WalletResponse, ServiceFailure> {
3487 Err(ServiceFailure::unsupported(
3488 ServiceCapability::WalletOperations,
3489 ))
3490 }
3491 }
3492
3493 struct ProductionFollowupProjectionRuntime {
3494 account: AccountSummary,
3495 snapshot: HnsAccountReadSnapshot,
3496 }
3497
3498 impl ServiceRuntime for ProductionFollowupProjectionRuntime {
3499 fn capabilities(&self) -> BTreeSet<ServiceCapability> {
3500 BTreeSet::from([ServiceCapability::ProviderDispatch])
3501 }
3502
3503 fn supports_provider_method(&self, method: ProviderMethod) -> bool {
3504 matches!(
3505 method,
3506 ProviderMethod::HnsRequestAccounts
3507 | ProviderMethod::HnsGetBalance
3508 | ProviderMethod::HnsGetTransactions
3509 | ProviderMethod::HnsGetReceiveAddress
3510 | ProviderMethod::HnsGetNames
3511 | ProviderMethod::HnsGetName
3512 )
3513 }
3514
3515 fn prepare_approval(
3516 &mut self,
3517 _: &PendingApproval,
3518 ) -> Result<ApprovalSummary, ServiceFailure> {
3519 Err(ServiceFailure::unsupported(
3520 ServiceCapability::ProviderDispatch,
3521 ))
3522 }
3523
3524 fn prepare_hns_account_grant(
3525 &mut self,
3526 _: &ApprovedCall,
3527 ) -> Result<AccountSummary, ServiceFailure> {
3528 Ok(self.account.clone())
3529 }
3530
3531 fn selected_hns_account(&self) -> Result<AccountSummary, ServiceFailure> {
3532 Ok(self.account.clone())
3533 }
3534
3535 fn current_hns_names(&mut self) -> Result<Vec<KnownName>, ServiceFailure> {
3536 Ok(self.snapshot.known_names.clone())
3537 }
3538
3539 fn execute_hns_name_read(
3540 &mut self,
3541 call: ApprovedCall,
3542 approved_names: &BTreeSet<[u8; 32]>,
3543 ) -> Result<Value, ServiceFailure> {
3544 public_hns_name_read(&call, approved_names, &self.snapshot.known_names)
3545 }
3546
3547 fn execute_provider(&mut self, call: ApprovedCall) -> Result<Value, ServiceFailure> {
3548 public_hns_non_name_read(&call, &self.snapshot)
3549 }
3550
3551 fn lock_wallet(&mut self) -> Result<(), ServiceFailure> {
3552 Err(ServiceFailure::unsupported(
3553 ServiceCapability::WalletOperations,
3554 ))
3555 }
3556
3557 fn execute_wallet(&mut self, _: WalletRequest) -> Result<WalletResponse, ServiceFailure> {
3558 Err(ServiceFailure::unsupported(
3559 ServiceCapability::WalletOperations,
3560 ))
3561 }
3562 }
3563
3564 fn production_followup_alpha_hash() -> [u8; 32] {
3565 [
3566 0x27, 0x18, 0x78, 0xf8, 0xa9, 0x27, 0xb4, 0x56, 0x6a, 0xc9, 0x51, 0xfc, 0x81, 0x5b,
3567 0x18, 0xdf, 0xad, 0x8d, 0x03, 0x02, 0xd6, 0x1d, 0x11, 0xd8, 0x0c, 0xbe, 0x15, 0xb7,
3568 0xa3, 0xa0, 0x56, 0xaf,
3569 ]
3570 }
3571
3572 fn production_followup_beta_hash() -> [u8; 32] {
3573 [
3574 0xf0, 0x27, 0x7d, 0x92, 0x06, 0x2b, 0xd9, 0xa4, 0x1d, 0xd2, 0x6c, 0xdd, 0xba, 0xf2,
3575 0xc4, 0x1d, 0x57, 0x6c, 0xf7, 0xb0, 0x17, 0x3c, 0xbe, 0x96, 0xc2, 0x3d, 0x5f, 0x5a,
3576 0x4f, 0x92, 0xcc, 0x8f,
3577 ]
3578 }
3579
3580 fn production_followup_known_name() -> KnownName {
3581 KnownName {
3582 name: b"alpha".to_vec(),
3583 name_hash: production_followup_alpha_hash(),
3584 proof_height: 99,
3585 unbound_proof_owner_outpoint: None,
3586 unbound_current_owner_outpoint: None,
3587 proof_state: Some(vec![1, 2, 3]),
3588 current_state: Some(vec![4, 5, 6]),
3589 canonical_proof_state: None,
3590 canonical_current_state: Some(CanonicalNameStateSummary {
3591 owner_outpoint: None,
3592 value: 1,
3593 highest: 2,
3594 start_height: 3,
3595 renewal_height: 4,
3596 transfer_height: 0,
3597 revoked_height: 0,
3598 claimed_height: 0,
3599 renewals: 1,
3600 registered: true,
3601 expired: false,
3602 weak: false,
3603 }),
3604 current_raw_resource: Some(vec![7, 8, 9]),
3605 resource_status: NameResourceStatus::CanonicalDecoded,
3606 ownership_status: NameOwnershipStatus::WalletContextUnavailable,
3607 }
3608 }
3609
3610 fn production_followup_projection_service()
3611 -> WalletService<MemoryProviderState, ProductionFollowupProjectionRuntime> {
3612 let account_id = AccountId::new([9; 16]);
3613 let runtime = ProductionFollowupProjectionRuntime {
3614 account: AccountSummary {
3615 account_id,
3616 module: ModuleId::Handshake,
3617 label: "Handshake".to_owned(),
3618 receive_display: None,
3619 },
3620 snapshot: HnsAccountReadSnapshot {
3621 account_id,
3622 binding: HnsAccountReadBinding {
3623 chain: SnapshotBinding {
3624 tip: ChainTip {
3625 height: 99,
3626 block_hash: [12; 32],
3627 tree_root: [13; 32],
3628 median_time_past: 1_700_000_000,
3629 },
3630 chain_epoch: 3,
3631 },
3632 mempool: MempoolSnapshotBinding {
3633 instance_nonce: [14; 32],
3634 generation: 4,
3635 },
3636 },
3637 balance: Amount::new(WalletAsset::Hns, 42),
3638 transactions: vec![TransactionSummary {
3639 module: ModuleId::Handshake,
3640 txid: TransactionHash::new([0xab; 32]),
3641 status: LocalTransactionStatus::Confirmed,
3642 net_amount: SignedBaseUnits {
3643 negative: false,
3644 magnitude: BaseUnits::new(17),
3645 },
3646 fee: Some(BaseUnits::new(2)),
3647 block_height: Some(99),
3648 first_seen_unix: Some(1_700_000_000),
3649 confirmation_count: 3,
3650 }],
3651 receive_target: ReceiveTarget {
3652 module: ModuleId::Handshake,
3653 account: account_id,
3654 display: "rs1qproductionfollowup".to_owned(),
3655 derivation_index: 7,
3656 },
3657 name_receive_target: HnsNameReceiveTarget {
3658 module: ModuleId::Handshake,
3659 account: account_id,
3660 display: "rs1qproductionfollowupname".to_owned(),
3661 derivation_index: 11,
3662 },
3663 known_names: vec![production_followup_known_name()],
3664 },
3665 };
3666 let mut service = WalletService::new_ephemeral(MemoryProviderState::default(), runtime)
3667 .expect("projection service");
3668 service
3669 .provider
3670 .register_authority(handle(), registration(), NOW_MS)
3671 .expect("projection HNS authority");
3672 service
3673 .provider
3674 .set_wallet_state(service.wallet_session_id, false);
3675 service
3676 }
3677
3678 fn host_session() -> HostSessionId {
3679 HostSessionId::from_bytes([1_u8; 32]).expect("host session")
3680 }
3681
3682 fn handle() -> HostAuthorityHandleId {
3683 HostAuthorityHandleId::from_bytes([2_u8; 32]).expect("handle")
3684 }
3685
3686 fn restart_handle() -> HostAuthorityHandleId {
3687 HostAuthorityHandleId::from_bytes([6_u8; 32]).expect("restart handle")
3688 }
3689
3690 fn registration() -> HostAuthorityRegistration {
3691 HostAuthorityRegistration {
3692 origin: Origin::parse("https://wallet.example").expect("origin"),
3693 namespace: SelectedNamespace::Hns,
3694 runtime_session: BrowserRuntimeSessionId::from_bytes([3_u8; 16])
3695 .expect("runtime session"),
3696 runtime_generation: 1,
3697 policy_generation: 1,
3698 navigation_generation: 1,
3699 decision_fingerprint: ProviderAuthorityFingerprint::from_bytes([4_u8; 32])
3700 .expect("fingerprint"),
3701 valid_until_unix_ms: NOW_MS + 60_000,
3702 }
3703 }
3704
3705 fn provider_service() -> WalletService<MemoryProviderState, ProviderRuntime> {
3706 let mut service =
3707 WalletService::new_ephemeral(MemoryProviderState::default(), ProviderRuntime)
3708 .expect("service");
3709 service
3710 .provider
3711 .register_authority(handle(), registration(), NOW_MS)
3712 .expect("authority");
3713 service
3714 }
3715
3716 fn account_service() -> WalletService<MemoryProviderState, AccountRuntime> {
3717 let mut service = WalletService::new_ephemeral(
3718 MemoryProviderState::default(),
3719 AccountRuntime {
3720 account: AccountSummary {
3721 account_id: AccountId::new([9_u8; 16]),
3722 module: ModuleId::Handshake,
3723 label: "Handshake".to_owned(),
3724 receive_display: None,
3725 },
3726 account_join_available: true,
3727 },
3728 )
3729 .expect("service");
3730 service
3731 .provider
3732 .register_authority(handle(), registration(), NOW_MS)
3733 .expect("authority");
3734 service
3735 .provider
3736 .set_wallet_state(service.wallet_session_id, false);
3737 service
3738 }
3739
3740 #[cfg(target_os = "linux")]
3741 fn production_hns_config(account_byte: u8, derivation_index: u32) -> HnsRuntimeConfig {
3742 HnsRuntimeConfig {
3743 wallet_id: WalletId::new([8_u8; 16]),
3744 account_id: AccountId::new([account_byte; 16]),
3745 account_derivation_index: derivation_index,
3746 network: HnsNetwork::Regtest,
3747 birthday_height: 0,
3748 restore_lookahead: 1,
3749 minimum_confirmations: 1,
3750 dust_threshold: BaseUnits::new(1),
3751 value_operations_enabled: false,
3752 settlement_enabled: false,
3753 }
3754 }
3755
3756 #[cfg(target_os = "linux")]
3757 fn native_hns_read_tempdir() -> tempfile::TempDir {
3758 use std::os::unix::fs::PermissionsExt as _;
3759
3760 let root = std::env::var_os("HNS_WALLET_STORE_TEST_TMPDIR")
3761 .map(std::path::PathBuf::from)
3762 .unwrap_or_else(std::env::temp_dir);
3763 let directory = tempfile::Builder::new()
3764 .prefix("hns-wallet-native-read-")
3765 .tempdir_in(root)
3766 .expect("private native HNS read directory");
3767 std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700))
3768 .expect("private native HNS read directory mode");
3769 directory
3770 }
3771
3772 #[cfg(target_os = "linux")]
3773 fn production_hns_account(config: HnsRuntimeConfig) -> HnsAccountRecord {
3774 HnsAccountRecord {
3775 config,
3776 next_receive_index: 0,
3777 next_change_index: 0,
3778 next_shakedex_index: 0,
3779 external_scan_end: 0,
3780 internal_scan_end: 0,
3781 shakedex_scan_end: 0,
3782 shakedex_scan_complete: false,
3783 shakedex_scan_in_progress: false,
3784 last_used_external: None,
3785 last_used_internal: None,
3786 last_used_shakedex: None,
3787 }
3788 }
3789
3790 #[cfg(target_os = "linux")]
3791 fn production_hns_record_id(config: &HnsRuntimeConfig) -> [u8; 32] {
3792 let mut record_id = [0_u8; 32];
3793 record_id[..16].copy_from_slice(config.wallet_id.as_bytes());
3794 record_id[16..].copy_from_slice(config.account_id.as_bytes());
3795 record_id
3796 }
3797
3798 #[cfg(target_os = "linux")]
3799 fn production_hns_store(
3800 database_path: &std::path::Path,
3801 configs: &[HnsRuntimeConfig],
3802 ) -> SharedWalletStore {
3803 const PASSPHRASE: &str = "correct horse battery staple";
3804 let store = SharedWalletStore::new(
3805 WalletStore::create(database_path, PASSPHRASE).expect("create HNS account store"),
3806 );
3807 for (index, config) in configs.iter().cloned().enumerate() {
3808 let record_id = production_hns_record_id(&config);
3809 let account = production_hns_account(config);
3810 store
3811 .with_store_mut(|wallet| {
3812 wallet
3813 .save_wallet_account(&record_id, 0, &account, 10 + index as u64)
3814 .map(|_| ())
3815 })
3816 .expect("persist exact HNS account");
3817 }
3818 store.lock().expect("lock HNS account store");
3819 store
3820 }
3821
3822 #[cfg(target_os = "linux")]
3823 fn native_hns_profile_store(
3824 database_path: &std::path::Path,
3825 config: &HnsRuntimeConfig,
3826 ) -> SharedWalletStore {
3827 const PASSPHRASE: &str = "correct horse battery staple";
3828 let mut store = WalletStore::create(database_path, PASSPHRASE)
3829 .expect("create native HNS profile store");
3830 store
3831 .initialize_recovery_seed_and_wallet_account(
3832 config.wallet_id.as_bytes(),
3833 &[0x51_u8; 64],
3834 &production_hns_record_id(config),
3835 &production_hns_account(config.clone()),
3836 1,
3837 )
3838 .expect("initialize complete native HNS profile bootstrap");
3839 SharedWalletStore::new(store)
3840 }
3841
3842 #[cfg(target_os = "linux")]
3843 fn native_hns_profile(
3844 config: HnsRuntimeConfig,
3845 endpoint: &str,
3846 authorization: &str,
3847 label: &str,
3848 ) -> NativeHnsReadProfile {
3849 NativeHnsReadProfile::new(
3850 config,
3851 endpoint.parse().expect("profile loopback endpoint"),
3852 hns_wallet_ffi::SecretString::new(authorization.to_owned()),
3853 label.to_owned(),
3854 )
3855 .expect("valid native HNS read profile")
3856 }
3857
3858 #[cfg(target_os = "linux")]
3859 fn persist_existing_flagged_native_hns_read_profile(
3860 store: &SharedWalletStore,
3861 config: &HnsRuntimeConfig,
3862 updated_at_unix: u64,
3863 ) {
3864 assert!(config.value_operations_enabled || config.settlement_enabled);
3865 let record = json!({
3866 "state": "active",
3867 "schemaVersion": NATIVE_HNS_READ_PROFILE_SCHEMA_VERSION,
3868 "account": config,
3869 "nodeEndpoint": "127.0.0.1:24191",
3870 "nodeAuthorization": "Bearer historical-recovery-profile",
3871 "accountLabel": "Handshake Recovery",
3872 });
3873 store
3874 .with_store_mut(|wallet| {
3875 wallet
3876 .save_native_hns_read_profile(
3877 NATIVE_HNS_READ_PROFILE_ID,
3878 0,
3879 &record,
3880 updated_at_unix,
3881 )
3882 .map(|_| ())
3883 })
3884 .expect("persist simulated existing flagged native HNS profile");
3885 }
3886
3887 #[cfg(target_os = "linux")]
3888 fn native_hns_bootstrap_passphrase(value: &str) -> NativeHnsReadBootstrapPassphrase {
3889 NativeHnsReadBootstrapPassphrase::new(zeroize::Zeroizing::new(value.to_owned()))
3890 }
3891
3892 #[cfg(target_os = "linux")]
3893 fn production_hns_service(
3894 store: SharedWalletStore,
3895 config: HnsRuntimeConfig,
3896 ) -> WalletService<SharedWalletStore, PersistentHnsAccountRuntime> {
3897 let selector =
3898 HnsExistingAccountSelector::new(store.clone(), config).expect("exact account selector");
3899 WalletService::new_persistent_hns_accounts(
3900 store,
3901 PersistentHnsAccountConfig {
3902 selector,
3903 account_label: "Handshake".to_owned(),
3904 },
3905 )
3906 .expect("persistent HNS account service")
3907 }
3908
3909 #[cfg(target_os = "linux")]
3910 fn unlock_production_hns(
3911 service: &mut WalletService<SharedWalletStore, PersistentHnsAccountRuntime>,
3912 now_unix_ms: u64,
3913 ) {
3914 const PASSPHRASE: &str = "correct horse battery staple";
3915 let ServiceResponse::Wallet {
3916 response: WalletResponse::Unlocked,
3917 } = service
3918 .dispatch(
3919 ServiceRequest::Wallet {
3920 request: WalletRequest::Unlock {
3921 passphrase: hns_wallet_ffi::SecretString::new(PASSPHRASE.to_owned()),
3922 },
3923 },
3924 now_unix_ms,
3925 )
3926 .expect("unlock production HNS account service")
3927 else {
3928 panic!("unlock response")
3929 };
3930 }
3931
3932 fn hello() -> zeroize::Zeroizing<Vec<u8>> {
3933 encode_host_frame(&HostFrame::Hello {
3934 hello: HostHello {
3935 protocol_version: WALLET_ABI_VERSION,
3936 platform: hns_wallet_ffi::HostPlatform::ChromiumNativeHost,
3937 host_session_id: host_session(),
3938 restart_generation: 1,
3939 },
3940 })
3941 .expect("hello")
3942 }
3943
3944 #[test]
3945 fn production_followup_account_grant_extends_to_minimized_hns_read_results() {
3946 let mut service = production_followup_projection_service();
3947 let methods = service.supported_provider_method_names();
3948 for method in [
3949 "hns_requestAccounts",
3950 "hns_accounts",
3951 "hns_getBalance",
3952 "hns_getTransactions",
3953 "hns_getReceiveAddress",
3954 "hns_getNames",
3955 "hns_getName",
3956 "wallet_requestPermissions",
3957 ] {
3958 assert!(methods.contains(method), "missing {method}");
3959 }
3960 for method in [
3961 "hns_send",
3962 "hns_importKnownName",
3963 "hns_transferName",
3964 "hns_finalizeName",
3965 "hns_signTypedMessage",
3966 "wallet_enableModule",
3967 "wallet_disableModule",
3968 ] {
3969 assert!(!methods.contains(method), "unexpected {method}");
3970 }
3971
3972 let ServiceResponse::ApprovalRequired { approval } = service
3973 .provider_request(
3974 handle(),
3975 1,
3976 1,
3977 ProviderMethod::HnsRequestAccounts.wire_name().to_owned(),
3978 Value::Null,
3979 NOW_MS + 1,
3980 )
3981 .expect("account approval")
3982 else {
3983 panic!("account approval response")
3984 };
3985 let ServiceResponse::ProviderResult { value, .. } = service
3986 .approval_decision(
3987 handle(),
3988 1,
3989 approval.approval_id,
3990 hns_wallet_ffi::ApprovalDecision::Approve,
3991 NOW_MS + 2,
3992 )
3993 .expect("account grant")
3994 else {
3995 panic!("account grant result")
3996 };
3997 assert_eq!(value, json!([AccountId::new([9; 16]).to_string()]));
3998
3999 assert!(matches!(
4000 service.provider_request(
4001 handle(),
4002 1,
4003 2,
4004 ProviderMethod::HnsGetBalance.wire_name().to_owned(),
4005 Value::Null,
4006 NOW_MS + 3,
4007 ),
4008 Err(ServiceFailure {
4009 code: ServiceErrorCode::PermissionDenied,
4010 ..
4011 })
4012 ));
4013
4014 let ServiceResponse::ApprovalRequired { approval } = service
4015 .provider_request(
4016 handle(),
4017 1,
4018 3,
4019 ProviderMethod::WalletRequestPermissions
4020 .wire_name()
4021 .to_owned(),
4022 json!({
4023 "capabilities": ["balance", "transactions", "receive_target", "names"],
4024 }),
4025 NOW_MS + 4,
4026 )
4027 .expect("read permission approval")
4028 else {
4029 panic!("read permission approval response")
4030 };
4031 assert_eq!(
4032 approval.summary,
4033 ApprovalSummary::Permissions {
4034 capabilities: BTreeSet::from([
4035 PermissionCapability::Balance,
4036 PermissionCapability::Transactions,
4037 PermissionCapability::ReceiveTarget,
4038 PermissionCapability::Names,
4039 ]),
4040 hns_names: vec![HnsNameDisclosure {
4041 name: "alpha".to_owned(),
4042 name_hash: "271878f8a927b4566ac951fc815b18dfad8d0302d61d11d80cbe15b7a3a056af"
4043 .to_owned(),
4044 }],
4045 }
4046 );
4047 service
4048 .approval_decision(
4049 handle(),
4050 1,
4051 approval.approval_id,
4052 hns_wallet_ffi::ApprovalDecision::Approve,
4053 NOW_MS + 5,
4054 )
4055 .expect("read permission grant");
4056 let permission = service
4057 .provider
4058 .permission(handle(), 1, NOW_MS + 5)
4059 .expect("permission")
4060 .expect("read permission record");
4061 assert_eq!(
4062 permission.capabilities,
4063 BTreeSet::from([
4064 PermissionCapability::Accounts,
4065 PermissionCapability::Balance,
4066 PermissionCapability::Transactions,
4067 PermissionCapability::ReceiveTarget,
4068 PermissionCapability::Names,
4069 ])
4070 );
4071 assert_eq!(
4072 permission.approved_accounts,
4073 BTreeSet::from([AccountId::new([9; 16])])
4074 );
4075 assert_eq!(
4076 permission.approved_names,
4077 BTreeSet::from([production_followup_alpha_hash()])
4078 );
4079
4080 let ServiceResponse::ProviderResult { value, .. } = service
4081 .provider_request(
4082 handle(),
4083 1,
4084 4,
4085 ProviderMethod::HnsGetBalance.wire_name().to_owned(),
4086 Value::Null,
4087 NOW_MS + 6,
4088 )
4089 .expect("balance read")
4090 else {
4091 panic!("balance result")
4092 };
4093 assert_eq!(
4094 value,
4095 json!({ "amount": { "asset": "HNS", "baseUnits": "42" } })
4096 );
4097
4098 let ServiceResponse::ProviderResult { value, .. } = service
4099 .provider_request(
4100 handle(),
4101 1,
4102 5,
4103 ProviderMethod::HnsGetTransactions.wire_name().to_owned(),
4104 Value::Null,
4105 NOW_MS + 7,
4106 )
4107 .expect("history read")
4108 else {
4109 panic!("history result")
4110 };
4111 assert_eq!(
4112 value,
4113 json!({
4114 "transactions": [{
4115 "module": "handshake",
4116 "txid": "abababababababababababababababababababababababababababababababab",
4117 "status": "confirmed",
4118 "netAmount": { "negative": false, "magnitude": "17" },
4119 "fee": "2",
4120 "blockHeight": 99,
4121 "firstSeenUnix": 1_700_000_000_u64,
4122 "confirmationCount": 3,
4123 }],
4124 })
4125 );
4126
4127 let ServiceResponse::ProviderResult { value, .. } = service
4128 .provider_request(
4129 handle(),
4130 1,
4131 6,
4132 ProviderMethod::HnsGetReceiveAddress.wire_name().to_owned(),
4133 Value::Null,
4134 NOW_MS + 8,
4135 )
4136 .expect("receive read")
4137 else {
4138 panic!("receive result")
4139 };
4140 assert_eq!(
4141 value,
4142 json!({
4143 "target": {
4144 "module": "handshake",
4145 "account": AccountId::new([9; 16]).to_string(),
4146 "display": "rs1qproductionfollowup",
4147 "derivationIndex": 7,
4148 },
4149 })
4150 );
4151 let encoded = serde_json::to_string(&value).expect("encode public receive target");
4152 assert!(!encoded.contains("productionfollowupname"));
4153 assert!(!encoded.contains("nameReceiveTarget"));
4154
4155 let ServiceResponse::ProviderResult { value, .. } = service
4156 .provider_request(
4157 handle(),
4158 1,
4159 7,
4160 ProviderMethod::HnsGetNames.wire_name().to_owned(),
4161 Value::Null,
4162 NOW_MS + 9,
4163 )
4164 .expect("name list read")
4165 else {
4166 panic!("name list result")
4167 };
4168 let expected_name = json!({
4169 "name": "alpha",
4170 "nameHash": "271878f8a927b4566ac951fc815b18dfad8d0302d61d11d80cbe15b7a3a056af",
4171 "proofHeight": 99,
4172 "resourceStatus": "canonicalDecoded",
4173 "ownershipStatus": "walletContextUnavailable",
4174 "registered": true,
4175 "expired": false,
4176 });
4177 assert_eq!(value, json!({ "names": [expected_name.clone()] }));
4178 let encoded = serde_json::to_string(&value).expect("encode minimized name");
4179 for private_field in [
4180 "proof_state",
4181 "proofState",
4182 "current_state",
4183 "currentState",
4184 "current_raw_resource",
4185 "currentRawResource",
4186 "ownerOutpoint",
4187 "derivation",
4188 "chainEpoch",
4189 "mempool",
4190 ] {
4191 assert!(!encoded.contains(private_field), "leaked {private_field}");
4192 }
4193
4194 let ServiceResponse::ProviderResult { value, .. } = service
4195 .provider_request(
4196 handle(),
4197 1,
4198 8,
4199 ProviderMethod::HnsGetName.wire_name().to_owned(),
4200 json!({
4201 "nameHash": "271878f8a927b4566ac951fc815b18dfad8d0302d61d11d80cbe15b7a3a056af",
4202 }),
4203 NOW_MS + 10,
4204 )
4205 .expect("one approved name")
4206 else {
4207 panic!("one name result")
4208 };
4209 assert_eq!(value, json!({ "name": expected_name }));
4210
4211 assert!(matches!(
4212 service.provider_request(
4213 handle(),
4214 1,
4215 9,
4216 ProviderMethod::HnsGetName.wire_name().to_owned(),
4217 json!({
4218 "nameHash": "1212121212121212121212121212121212121212121212121212121212121212",
4219 }),
4220 NOW_MS + 11,
4221 ),
4222 Err(ServiceFailure {
4223 code: ServiceErrorCode::PermissionDenied,
4224 ..
4225 })
4226 ));
4227 service.runtime.snapshot.known_names.clear();
4228 assert!(matches!(
4229 service.provider_request(
4230 handle(),
4231 1,
4232 10,
4233 ProviderMethod::HnsGetNames.wire_name().to_owned(),
4234 Value::Null,
4235 NOW_MS + 12,
4236 ),
4237 Err(ServiceFailure {
4238 code: ServiceErrorCode::PermissionDenied,
4239 ..
4240 })
4241 ));
4242 }
4243
4244 #[test]
4245 fn production_followup_name_permission_rejects_post_prompt_scope_or_account_change() {
4246 let mut service = production_followup_projection_service();
4247 let ServiceResponse::ApprovalRequired { approval } = service
4248 .provider_request(
4249 handle(),
4250 1,
4251 1,
4252 ProviderMethod::HnsRequestAccounts.wire_name().to_owned(),
4253 Value::Null,
4254 NOW_MS + 1,
4255 )
4256 .expect("account approval")
4257 else {
4258 panic!("account approval response")
4259 };
4260 service
4261 .approval_decision(
4262 handle(),
4263 1,
4264 approval.approval_id,
4265 hns_wallet_ffi::ApprovalDecision::Approve,
4266 NOW_MS + 2,
4267 )
4268 .expect("account grant");
4269
4270 let ServiceResponse::ApprovalRequired { approval } = service
4271 .provider_request(
4272 handle(),
4273 1,
4274 2,
4275 ProviderMethod::WalletRequestPermissions
4276 .wire_name()
4277 .to_owned(),
4278 json!({ "capabilities": ["names"] }),
4279 NOW_MS + 3,
4280 )
4281 .expect("exact name disclosure")
4282 else {
4283 panic!("name approval response")
4284 };
4285 let mut beta = production_followup_known_name();
4286 beta.name = b"beta".to_vec();
4287 beta.name_hash = production_followup_beta_hash();
4288 service.runtime.snapshot.known_names.push(beta);
4289 assert!(matches!(
4290 service.approval_decision(
4291 handle(),
4292 1,
4293 approval.approval_id,
4294 hns_wallet_ffi::ApprovalDecision::Approve,
4295 NOW_MS + 4,
4296 ),
4297 Err(ServiceFailure {
4298 code: ServiceErrorCode::ApprovalStale,
4299 ..
4300 })
4301 ));
4302 let permission = service
4303 .provider
4304 .permission(handle(), 1, NOW_MS + 4)
4305 .expect("permission")
4306 .expect("account permission");
4307 assert_eq!(
4308 permission.capabilities,
4309 BTreeSet::from([PermissionCapability::Accounts])
4310 );
4311 assert!(permission.approved_names.is_empty());
4312
4313 service.runtime.snapshot.known_names = vec![production_followup_known_name()];
4314 let ServiceResponse::ApprovalRequired { approval } = service
4315 .provider_request(
4316 handle(),
4317 1,
4318 3,
4319 ProviderMethod::WalletRequestPermissions
4320 .wire_name()
4321 .to_owned(),
4322 json!({ "capabilities": ["names"] }),
4323 NOW_MS + 5,
4324 )
4325 .expect("second exact name disclosure")
4326 else {
4327 panic!("second name approval response")
4328 };
4329 service.runtime.account.account_id = AccountId::new([10; 16]);
4330 assert!(matches!(
4331 service.approval_decision(
4332 handle(),
4333 1,
4334 approval.approval_id,
4335 hns_wallet_ffi::ApprovalDecision::Approve,
4336 NOW_MS + 6,
4337 ),
4338 Err(ServiceFailure {
4339 code: ServiceErrorCode::ApprovalStale,
4340 ..
4341 })
4342 ));
4343 }
4344
4345 #[test]
4346 fn production_followup_hns_reads_reject_namespace_malformed_bounds_and_value_surfaces() {
4347 let mut service = production_followup_projection_service();
4348 let mut icann = registration();
4349 icann.namespace = SelectedNamespace::Icann;
4350 service
4351 .provider
4352 .register_authority(restart_handle(), icann, NOW_MS)
4353 .expect("ICANN authority");
4354 assert!(matches!(
4355 service.provider_request(
4356 restart_handle(),
4357 1,
4358 1,
4359 ProviderMethod::HnsGetBalance.wire_name().to_owned(),
4360 Value::Null,
4361 NOW_MS + 1,
4362 ),
4363 Err(ServiceFailure {
4364 code: ServiceErrorCode::PermissionDenied,
4365 ..
4366 })
4367 ));
4368 assert!(matches!(
4369 service.provider_request(
4370 handle(),
4371 1,
4372 1,
4373 ProviderMethod::HnsGetName.wire_name().to_owned(),
4374 json!({ "nameHash": "AA", "extra": true }),
4375 NOW_MS + 2,
4376 ),
4377 Err(ServiceFailure {
4378 code: ServiceErrorCode::InvalidRequest,
4379 ..
4380 })
4381 ));
4382 for (nonce, method) in [
4383 ProviderMethod::HnsSend,
4384 ProviderMethod::HnsImportKnownName,
4385 ProviderMethod::HnsTransferName,
4386 ProviderMethod::HnsFinalizeName,
4387 ProviderMethod::HnsSignTypedMessage,
4388 ProviderMethod::WalletEnableModule,
4389 ProviderMethod::WalletDisableModule,
4390 ]
4391 .into_iter()
4392 .enumerate()
4393 {
4394 assert!(matches!(
4395 service.provider_request(
4396 handle(),
4397 1,
4398 nonce as u64 + 2,
4399 method.wire_name().to_owned(),
4400 Value::Null,
4401 NOW_MS + nonce as u64 + 3,
4402 ),
4403 Err(ServiceFailure {
4404 code: ServiceErrorCode::UnsupportedCapability,
4405 ..
4406 })
4407 ));
4408 }
4409
4410 let mut oversized = service.runtime.snapshot.clone();
4411 oversized.transactions = vec![oversized.transactions[0].clone(); 129];
4412 let call = ApprovedCall {
4413 origin: Origin::parse("https://wallet.example").expect("origin"),
4414 namespace: SelectedNamespace::Hns,
4415 method: ProviderMethod::HnsGetTransactions,
4416 params: Value::Null,
4417 request_nonce: 99,
4418 };
4419 assert!(matches!(
4420 public_hns_non_name_read(&call, &oversized),
4421 Err(ServiceFailure {
4422 code: ServiceErrorCode::RuntimeFailure,
4423 ..
4424 })
4425 ));
4426 oversized.transactions.truncate(1);
4427 oversized.transactions[0].block_height = Some(MAX_JAVASCRIPT_SAFE_INTEGER + 1);
4428 assert!(matches!(
4429 public_hns_non_name_read(&call, &oversized),
4430 Err(ServiceFailure {
4431 code: ServiceErrorCode::InvalidRequest,
4432 ..
4433 })
4434 ));
4435 let invalid_account = AccountSummary {
4436 account_id: AccountId::new([9; 16]),
4437 module: ModuleId::Handshake,
4438 label: "Handshake\nWallet".to_owned(),
4439 receive_display: None,
4440 };
4441 assert!(validate_hns_account_summary(&invalid_account).is_err());
4442 let mut unsafe_name = production_followup_known_name();
4443 unsafe_name.proof_height = MAX_JAVASCRIPT_SAFE_INTEGER + 1;
4444 assert!(public_hns_name_summary(&unsafe_name).is_err());
4445 }
4446
4447 #[test]
4448 fn trusted_native_name_import_output_is_minimized_and_errors_are_typed() {
4449 let name = production_followup_known_name();
4450 let summary = native_hns_name_summary(&name).expect("minimized native name");
4451 assert_eq!(summary.name, "alpha");
4452 assert_eq!(summary.name_hash, lowercase_hex(&name.name_hash));
4453 assert_eq!(summary.proof_height, 99);
4454 assert_eq!(
4455 summary.resource_status,
4456 NativeHnsNameResourceStatus::CanonicalDecoded
4457 );
4458 assert_eq!(
4459 summary.ownership_status,
4460 NativeHnsNameOwnershipStatus::WalletContextUnavailable
4461 );
4462 assert_eq!(summary.registered, Some(true));
4463 assert_eq!(summary.expired, Some(false));
4464 assert_eq!(summary.raw_resource.as_deref(), Some(&[7, 8, 9][..]));
4465 let debug = format!("{summary:?}");
4466 for forbidden in [
4467 "proof_state",
4468 "current_state",
4469 "owner_outpoint",
4470 "derivation",
4471 ] {
4472 assert!(!debug.contains(forbidden));
4473 }
4474
4475 assert_eq!(
4476 hns_native_name_import_failure(HnsWalletError::InvalidName).code,
4477 ServiceErrorCode::InvalidRequest
4478 );
4479 assert_eq!(
4480 hns_native_name_import_failure(HnsWalletError::HistoryLimit).code,
4481 ServiceErrorCode::RuntimeFailure
4482 );
4483 assert_eq!(
4484 hns_native_name_import_failure(HnsWalletError::InvalidEvidence).code,
4485 ServiceErrorCode::PersistenceFailure
4486 );
4487 }
4488
4489 #[test]
4490 fn default_subprocess_never_claims_provider_value_or_browser_availability() {
4491 let mut service =
4492 WalletService::new_ephemeral(MemoryProviderState::default(), UnavailableRuntime)
4493 .expect("service");
4494 let response = service.process_frame(&hello(), 1).expect("hello response");
4495 let ServiceFrame::Hello { hello } = decode_service_frame(&response).expect("decode") else {
4496 panic!("expected hello")
4497 };
4498 assert!(
4499 !hello
4500 .capabilities
4501 .contains(&ServiceCapability::ProviderDispatch)
4502 );
4503 assert!(
4504 !hello
4505 .capabilities
4506 .contains(&ServiceCapability::ValueMovement)
4507 );
4508 assert!(
4509 !hello
4510 .capabilities
4511 .contains(&ServiceCapability::BrowserIntegration)
4512 );
4513 assert!(
4514 !hello
4515 .capabilities
4516 .contains(&ServiceCapability::HnsReadOperationsV1)
4517 );
4518 service
4519 .provider
4520 .register_authority(handle(), registration(), NOW_MS)
4521 .expect("authority");
4522 let ServiceResponse::ProviderCapabilities { capabilities, .. } = service
4523 .provider_capabilities(handle(), 1, NOW_MS)
4524 .expect("private capability snapshot")
4525 else {
4526 panic!("private capabilities")
4527 };
4528 assert!(capabilities.methods.is_empty());
4529 }
4530
4531 #[test]
4532 fn hns_read_marker_is_removed_without_coarse_wallet_operations() {
4533 let mut service =
4534 WalletService::new_ephemeral(MemoryProviderState::default(), HnsReadMarkerOnlyRuntime)
4535 .expect("service");
4536 assert!(
4537 !service
4538 .capabilities
4539 .contains(&ServiceCapability::HnsReadOperationsV1)
4540 );
4541 let response = service.process_frame(&hello(), 1).expect("hello response");
4542 let ServiceFrame::Hello { hello } = decode_service_frame(&response).expect("decode") else {
4543 panic!("expected hello")
4544 };
4545 assert!(
4546 !hello
4547 .capabilities
4548 .contains(&ServiceCapability::HnsReadOperationsV1)
4549 );
4550 }
4551
4552 #[test]
4553 fn a_new_service_process_rotates_sessions_and_drops_ephemeral_state() {
4554 let first =
4555 WalletService::new_ephemeral(MemoryProviderState::default(), UnavailableRuntime)
4556 .expect("first");
4557 let second =
4558 WalletService::new_ephemeral(MemoryProviderState::default(), UnavailableRuntime)
4559 .expect("second");
4560 assert_ne!(first.service_session_id, second.service_session_id);
4561 assert!(second.pending.is_empty());
4562 assert!(second.event_sequences.is_empty());
4563 assert!(second.seen_request_ids.is_empty());
4564 }
4565
4566 #[cfg(target_os = "linux")]
4567 #[test]
4568 fn production_tranche_persistent_control_reopens_locked_and_preserves_only_permission_authority()
4569 {
4570 use std::os::unix::fs::PermissionsExt as _;
4571
4572 const PASSPHRASE: &str = "correct horse battery staple";
4573 let directory = tempfile::tempdir().expect("temporary wallet directory");
4574 std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700))
4575 .expect("private wallet directory permissions");
4576 let database_path = directory.path().join("wallet.sqlite3");
4577 let first_store = SharedWalletStore::new(
4578 WalletStore::create(&database_path, PASSPHRASE).expect("create store"),
4579 );
4580 assert!(matches!(
4581 WalletService::new_persistent_control(first_store.clone()),
4582 Err(ServiceError::PersistentStoreMustStartLocked)
4583 ));
4584 first_store.lock().expect("lock created store");
4585 let mut first = WalletService::new_persistent_control(first_store.clone())
4586 .expect("first persistent service");
4587 assert!(first_store.is_locked().expect("first lock state"));
4588 assert!(
4589 first
4590 .capabilities
4591 .contains(&ServiceCapability::PersistentPermissions)
4592 );
4593 assert!(
4594 !first
4595 .capabilities
4596 .contains(&ServiceCapability::ValueMovement)
4597 );
4598 assert!(
4599 !first
4600 .capabilities
4601 .contains(&ServiceCapability::BrowserIntegration)
4602 );
4603 assert!(
4604 !first
4605 .capabilities
4606 .contains(&ServiceCapability::HnsReadOperationsV1)
4607 );
4608 first
4609 .provider
4610 .register_authority(handle(), registration(), NOW_MS)
4611 .expect("first authority");
4612 assert!(matches!(
4613 first.provider_capabilities(handle(), 1, NOW_MS),
4614 Err(ServiceFailure {
4615 code: ServiceErrorCode::WalletLocked,
4616 ..
4617 })
4618 ));
4619
4620 let ServiceResponse::Wallet {
4621 response: WalletResponse::Unlocked,
4622 } = first
4623 .dispatch(
4624 ServiceRequest::Wallet {
4625 request: WalletRequest::Unlock {
4626 passphrase: hns_wallet_ffi::SecretString::new(PASSPHRASE.to_owned()),
4627 },
4628 },
4629 NOW_MS,
4630 )
4631 .expect("unlock first service")
4632 else {
4633 panic!("unlock response")
4634 };
4635 assert!(!first_store.is_locked().expect("unlocked first store"));
4636 let ServiceResponse::ProviderCapabilities { capabilities, .. } = first
4637 .provider_capabilities(handle(), 1, NOW_MS + 1)
4638 .expect("first capabilities")
4639 else {
4640 panic!("first capabilities response")
4641 };
4642 assert_eq!(
4643 capabilities.methods,
4644 BTreeSet::from([
4645 "wallet_getCapabilities".to_owned(),
4646 "wallet_getPermissions".to_owned(),
4647 "wallet_getStatus".to_owned(),
4648 "wallet_lock".to_owned(),
4649 "wallet_revokePermissions".to_owned(),
4650 ])
4651 );
4652 assert!(!capabilities.methods.contains("wallet_requestPermissions"));
4653 assert!(matches!(
4654 first.provider_request(
4655 handle(),
4656 1,
4657 1,
4658 ProviderMethod::WalletRequestPermissions
4659 .wire_name()
4660 .to_owned(),
4661 json!({ "capabilities": ["balance"] }),
4662 NOW_MS + 2,
4663 ),
4664 Err(ServiceFailure {
4665 code: ServiceErrorCode::UnsupportedCapability,
4666 ..
4667 })
4668 ));
4669
4670 first
4671 .provider
4672 .grant_permissions(
4673 handle(),
4674 1,
4675 BTreeSet::from([PermissionCapability::Balance]),
4676 BTreeSet::new(),
4677 NOW_MS + 3,
4678 None,
4679 )
4680 .expect("seed persisted permission");
4681 let ServiceResponse::ProviderResult { binding, value } = first
4682 .provider_request(
4683 handle(),
4684 1,
4685 2,
4686 ProviderMethod::WalletRevokePermissions
4687 .wire_name()
4688 .to_owned(),
4689 Value::Null,
4690 NOW_MS + 4,
4691 )
4692 .expect("persist tombstone")
4693 else {
4694 panic!("tombstone response")
4695 };
4696 assert_eq!(binding.permission_generation, 2);
4697 assert_eq!(value["permissionGeneration"], json!(2));
4698
4699 let first_service_session = first.service_session_id;
4700 let first_wallet_session = first.wallet_session_id;
4701 let ServiceResponse::Wallet {
4702 response: WalletResponse::Locked,
4703 } = first
4704 .dispatch(
4705 ServiceRequest::Wallet {
4706 request: WalletRequest::Lock,
4707 },
4708 NOW_MS + 5,
4709 )
4710 .expect("lock first service")
4711 else {
4712 panic!("lock response")
4713 };
4714 assert!(first_store.is_locked().expect("locked first store"));
4715 drop(first);
4716 drop(first_store);
4717
4718 let second_store =
4719 SharedWalletStore::new(WalletStore::open(&database_path).expect("reopen locked store"));
4720 let mut second = WalletService::new_persistent_control(second_store.clone())
4721 .expect("second persistent service");
4722 assert!(second_store.is_locked().expect("restart lock state"));
4723 assert_ne!(second.service_session_id, first_service_session);
4724 assert_ne!(second.wallet_session_id, first_wallet_session);
4725 assert!(second.pending.is_empty());
4726 assert!(second.event_sequences.is_empty());
4727 assert!(second.seen_request_ids.is_empty());
4728 assert!(second.request_order.is_empty());
4729 assert!(matches!(
4730 second.provider_capabilities(handle(), 1, NOW_MS + 6),
4731 Err(ServiceFailure {
4732 code: ServiceErrorCode::AuthorityUnknown,
4733 ..
4734 })
4735 ));
4736 second
4737 .provider
4738 .register_authority(restart_handle(), registration(), NOW_MS + 6)
4739 .expect("fresh restart authority");
4740 assert!(matches!(
4741 second.provider_capabilities(restart_handle(), 1, NOW_MS + 6),
4742 Err(ServiceFailure {
4743 code: ServiceErrorCode::WalletLocked,
4744 ..
4745 })
4746 ));
4747
4748 let ServiceResponse::Wallet {
4749 response: WalletResponse::Unlocked,
4750 } = second
4751 .dispatch(
4752 ServiceRequest::Wallet {
4753 request: WalletRequest::Unlock {
4754 passphrase: hns_wallet_ffi::SecretString::new(PASSPHRASE.to_owned()),
4755 },
4756 },
4757 NOW_MS + 7,
4758 )
4759 .expect("unlock restarted service")
4760 else {
4761 panic!("restart unlock response")
4762 };
4763 let ServiceResponse::ProviderCapabilities {
4764 binding,
4765 capabilities,
4766 } = second
4767 .provider_capabilities(restart_handle(), 1, NOW_MS + 8)
4768 .expect("restart capabilities")
4769 else {
4770 panic!("restart capabilities response")
4771 };
4772 assert_eq!(binding.permission_generation, 2);
4773 assert_eq!(capabilities.permission_generation, 2);
4774 assert!(!capabilities.methods.contains("wallet_requestPermissions"));
4775 let permission = second
4776 .provider
4777 .permission_snapshot(restart_handle(), 1, NOW_MS + 8)
4778 .expect("restart permission snapshot");
4779 assert_eq!(permission.generation, 2);
4780 assert!(permission.record.is_none());
4781 }
4782
4783 #[test]
4784 fn native_hns_read_inputs_require_authenticated_loopback_rpc() {
4785 assert!(
4786 HnsNodeRpcConfig::new(
4787 "192.0.2.1:14038".parse().expect("non-loopback socket"),
4788 "Bearer node-authority",
4789 )
4790 .is_err()
4791 );
4792 assert!(
4793 HnsNodeRpcConfig::new("127.0.0.1:14038".parse().expect("loopback socket"), "",)
4794 .is_err()
4795 );
4796 assert!(
4797 HnsNodeRpcConfig::new(
4798 "[::1]:14038".parse().expect("IPv6 loopback socket"),
4799 "Bearer node-authority",
4800 )
4801 .is_ok()
4802 );
4803 }
4804
4805 #[cfg(target_os = "linux")]
4806 #[test]
4807 fn native_hns_read_profile_rejects_ambient_or_value_authority() {
4808 let account = production_hns_config(9, 0);
4809 for endpoint in ["192.0.2.1:14038", "127.0.0.1:0"] {
4810 assert!(matches!(
4811 NativeHnsReadProfile::new(
4812 account.clone(),
4813 endpoint.parse().expect("socket address"),
4814 hns_wallet_ffi::SecretString::new("Bearer node-authority".to_owned()),
4815 "Handshake".to_owned(),
4816 ),
4817 Err(NativeHnsReadProfileError::InvalidConfiguration)
4818 ));
4819 }
4820 for authorization in [
4821 String::new(),
4822 "Bearer\nnode-authority".to_owned(),
4823 "Bearer quoted-\"authority\"".to_owned(),
4824 "Bearer escaped\\authority".to_owned(),
4825 "x".repeat(4_097),
4826 ] {
4827 assert!(matches!(
4828 NativeHnsReadProfile::new(
4829 account.clone(),
4830 "127.0.0.1:14038".parse().expect("loopback socket"),
4831 hns_wallet_ffi::SecretString::new(authorization),
4832 "Handshake".to_owned(),
4833 ),
4834 Err(NativeHnsReadProfileError::InvalidConfiguration)
4835 ));
4836 }
4837 assert!(matches!(
4838 NativeHnsReadProfile::new(
4839 account.clone(),
4840 "127.0.0.1:14038".parse().expect("loopback socket"),
4841 hns_wallet_ffi::SecretString::new("Bearer node-authority".to_owned()),
4842 "Handshake\nWallet".to_owned(),
4843 ),
4844 Err(NativeHnsReadProfileError::InvalidConfiguration)
4845 ));
4846
4847 let mut value_account = account;
4848 value_account.value_operations_enabled = true;
4849 assert!(matches!(
4850 NativeHnsReadProfile::new(
4851 value_account,
4852 "127.0.0.1:14038".parse().expect("loopback socket"),
4853 hns_wallet_ffi::SecretString::new("Bearer node-authority".to_owned()),
4854 "Handshake".to_owned(),
4855 ),
4856 Err(NativeHnsReadProfileError::InvalidConfiguration)
4857 ));
4858 }
4859
4860 #[cfg(target_os = "linux")]
4861 #[test]
4862 fn native_hns_read_profile_is_encrypted_rotatable_and_restart_durable() {
4863 const PASSPHRASE: &str = "correct horse battery staple";
4864 const FIRST_AUTHORIZATION: &str = "Bearer native-profile-secret-one-63e9";
4865 const SECOND_AUTHORIZATION: &str = "Bearer native-profile-secret-two-a1d4";
4866 const ACCOUNT_LABEL: &str = "Native Profile HNS 63e9";
4867 let directory = native_hns_read_tempdir();
4868 let database_path = directory.path().join("wallet.sqlite3");
4869 let account = production_hns_config(9, 0);
4870 let store = native_hns_profile_store(&database_path, &account);
4871
4872 assert!(matches!(
4873 load_native_hns_read_profile(&store).expect("empty unlocked profile namespace"),
4874 LoadedNativeHnsReadProfile::Absent
4875 ));
4876 store.lock().expect("lock before denial checks");
4877 assert!(matches!(
4878 load_native_hns_read_profile(&store),
4879 Err(NativeHnsReadProfileError::Store(StoreError::Locked))
4880 ));
4881 assert!(matches!(
4882 store.unlock("wrong passphrase"),
4883 Err(StoreError::InvalidPassphrase)
4884 ));
4885 assert!(store.is_locked().expect("failed first unlock stays locked"));
4886 store.unlock(PASSPHRASE).expect("unlock profile store");
4887
4888 let first = native_hns_profile(
4889 account.clone(),
4890 "127.0.0.1:24191",
4891 FIRST_AUTHORIZATION,
4892 ACCOUNT_LABEL,
4893 );
4894 let debug = format!("{first:?}");
4895 assert!(debug.contains("[REDACTED]"));
4896 assert!(!debug.contains(FIRST_AUTHORIZATION));
4897 assert_eq!(
4898 provision_native_hns_read_profile(&store, 0, &first, 100).expect("provision profile"),
4899 1
4900 );
4901
4902 for entry in std::fs::read_dir(directory.path()).expect("profile store files") {
4903 let path = entry.expect("profile store entry").path();
4904 if !path.is_file() {
4905 continue;
4906 }
4907 let contents = std::fs::read(&path).expect("profile store bytes");
4908 for needle in [
4909 FIRST_AUTHORIZATION.as_bytes(),
4910 b"127.0.0.1:24191".as_slice(),
4911 ACCOUNT_LABEL.as_bytes(),
4912 ] {
4913 assert!(
4914 !contents
4915 .windows(needle.len())
4916 .any(|window| window == needle),
4917 "{} exposed encrypted profile cleartext",
4918 path.display()
4919 );
4920 }
4921 }
4922
4923 let LoadedNativeHnsReadProfile::Active(loaded) =
4924 load_native_hns_read_profile(&store).expect("load profile")
4925 else {
4926 panic!("stored active profile")
4927 };
4928 assert_eq!(loaded.revision, 1);
4929 assert_eq!(loaded.updated_at_unix, 100);
4930 assert_eq!(loaded.profile.account(), &account);
4931 assert_eq!(loaded.profile.schema_version(), 1);
4932 let config = loaded
4933 .profile
4934 .into_service_config()
4935 .expect("consume profile into service config");
4936 assert_eq!(config.account, account);
4937 assert_eq!(config.node_rpc.endpoint().to_string(), "127.0.0.1:24191");
4938 assert_eq!(config.account_label, ACCOUNT_LABEL);
4939 assert!(!format!("{:?}", config.node_rpc).contains(FIRST_AUTHORIZATION));
4940
4941 let second = native_hns_profile(
4942 account.clone(),
4943 "[::1]:24192",
4944 SECOND_AUTHORIZATION,
4945 "Rotated Native Profile",
4946 );
4947 assert!(matches!(
4948 provision_native_hns_read_profile(&store, 1, &second, 99),
4949 Err(NativeHnsReadProfileError::TimestampRollback)
4950 ));
4951 assert_eq!(
4952 provision_native_hns_read_profile(&store, 1, &second, 101).expect("CAS rotate profile"),
4953 2
4954 );
4955 assert!(matches!(
4956 provision_native_hns_read_profile(&store, 1, &first, 102),
4957 Err(NativeHnsReadProfileError::Store(
4958 StoreError::StaleRevision {
4959 expected: 1,
4960 actual: 2
4961 }
4962 ))
4963 ));
4964
4965 store.lock().expect("lock before restart");
4966 drop(store);
4967 let restarted = SharedWalletStore::new(
4968 WalletStore::open(&database_path).expect("reopen native HNS profile store"),
4969 );
4970 restarted
4971 .unlock(PASSPHRASE)
4972 .expect("unlock restarted store");
4973 let LoadedNativeHnsReadProfile::Active(loaded) =
4974 load_native_hns_read_profile(&restarted).expect("load restarted profile")
4975 else {
4976 panic!("latest active profile revision")
4977 };
4978 assert_eq!(loaded.revision, 2);
4979 assert_eq!(loaded.profile.node_endpoint().to_string(), "[::1]:24192");
4980 assert_eq!(loaded.profile.account_label(), "Rotated Native Profile");
4981 assert!(matches!(
4982 revoke_native_hns_read_profile(&restarted, 2, 100),
4983 Err(NativeHnsReadProfileError::TimestampRollback)
4984 ));
4985 assert_eq!(
4986 revoke_native_hns_read_profile(&restarted, 2, 102).expect("CAS revoke profile"),
4987 3
4988 );
4989 let LoadedNativeHnsReadProfile::Revoked(revoked) =
4990 load_native_hns_read_profile(&restarted).expect("load revoked profile")
4991 else {
4992 panic!("revoked profile tombstone")
4993 };
4994 assert_eq!(
4995 revoked,
4996 NativeHnsReadProfileMetadata {
4997 revision: 3,
4998 state: NativeHnsReadProfileState::Revoked,
4999 updated_at_unix: 102,
5000 }
5001 );
5002 assert!(matches!(
5003 restarted.with_store_mut(
5004 |wallet| wallet.delete_native_hns_read_profile(NATIVE_HNS_READ_PROFILE_ID, 3,)
5005 ),
5006 Err(StoreError::ProtectedEntity)
5007 ));
5008 assert!(matches!(
5009 revoke_native_hns_read_profile(&restarted, 2, 103),
5010 Err(NativeHnsReadProfileError::Store(
5011 StoreError::StaleRevision {
5012 expected: 2,
5013 actual: 3
5014 }
5015 ))
5016 ));
5017 assert!(matches!(
5018 provision_native_hns_read_profile(&restarted, 0, &first, 103),
5019 Err(NativeHnsReadProfileError::Store(
5020 StoreError::StaleRevision {
5021 expected: 0,
5022 actual: 3
5023 }
5024 ))
5025 ));
5026 assert!(matches!(
5027 provision_native_hns_read_profile(&restarted, 3, &first, 101),
5028 Err(NativeHnsReadProfileError::TimestampRollback)
5029 ));
5030 assert_eq!(
5031 provision_native_hns_read_profile(&restarted, 3, &first, 103)
5032 .expect("re-provision from tombstone"),
5033 4
5034 );
5035 let LoadedNativeHnsReadProfile::Active(reprovisioned) =
5036 load_native_hns_read_profile(&restarted).expect("load re-provisioned profile")
5037 else {
5038 panic!("re-provisioned active profile")
5039 };
5040 assert_eq!(reprovisioned.revision, 4);
5041 assert_eq!(reprovisioned.updated_at_unix, 103);
5042 assert_eq!(
5043 revoke_native_hns_read_profile(&restarted, 4, 104)
5044 .expect("revoke re-provisioned profile"),
5045 5
5046 );
5047 assert_eq!(
5048 revoke_native_hns_read_profile(&restarted, 5, 105)
5049 .expect("advance an already-revoked tombstone"),
5050 6
5051 );
5052 }
5053
5054 #[cfg(target_os = "linux")]
5055 #[test]
5056 fn native_hns_read_profile_cas_has_one_concurrent_winner() {
5057 let directory = native_hns_read_tempdir();
5058 let account = production_hns_config(9, 0);
5059 let store = native_hns_profile_store(&directory.path().join("wallet.sqlite3"), &account);
5060 let initial = native_hns_profile(
5061 account.clone(),
5062 "127.0.0.1:24191",
5063 "Bearer initial-profile",
5064 "Handshake",
5065 );
5066 assert_eq!(
5067 provision_native_hns_read_profile(&store, 0, &initial, 1).expect("initial profile"),
5068 1
5069 );
5070
5071 let barrier = std::sync::Arc::new(std::sync::Barrier::new(3));
5072 let mut workers = Vec::new();
5073 for (port, timestamp) in [(24192_u16, 2_u64), (24193, 3)] {
5074 let worker_store = store.clone();
5075 let worker_barrier = barrier.clone();
5076 let worker_account = account.clone();
5077 workers.push(std::thread::spawn(move || {
5078 let profile = native_hns_profile(
5079 worker_account,
5080 &format!("127.0.0.1:{port}"),
5081 &format!("Bearer concurrent-{port}"),
5082 "Handshake",
5083 );
5084 worker_barrier.wait();
5085 provision_native_hns_read_profile(&worker_store, 1, &profile, timestamp)
5086 }));
5087 }
5088 barrier.wait();
5089 let results: Vec<_> = workers
5090 .into_iter()
5091 .map(|worker| worker.join().expect("profile worker"))
5092 .collect();
5093 assert_eq!(
5094 results
5095 .iter()
5096 .filter(|result| matches!(result, Ok(2)))
5097 .count(),
5098 1
5099 );
5100 assert_eq!(
5101 results
5102 .iter()
5103 .filter(|result| {
5104 matches!(
5105 result,
5106 Err(NativeHnsReadProfileError::Store(
5107 StoreError::StaleRevision {
5108 expected: 1,
5109 actual: 2
5110 }
5111 ))
5112 )
5113 })
5114 .count(),
5115 1
5116 );
5117 let LoadedNativeHnsReadProfile::Active(winner) =
5118 load_native_hns_read_profile(&store).expect("load winning profile")
5119 else {
5120 panic!("winning active profile")
5121 };
5122 assert_eq!(winner.revision, 2);
5123 }
5124
5125 #[cfg(target_os = "linux")]
5126 #[test]
5127 fn native_hns_read_profile_rejects_ambiguous_or_partial_wallet_state() {
5128 const PASSPHRASE: &str = "correct horse battery staple";
5129 let directory = native_hns_read_tempdir();
5130 let account = production_hns_config(9, 0);
5131 let partial = production_hns_store(
5132 &directory.path().join("partial.sqlite3"),
5133 std::slice::from_ref(&account),
5134 );
5135 partial.unlock(PASSPHRASE).expect("unlock partial store");
5136 let profile = native_hns_profile(
5137 account.clone(),
5138 "127.0.0.1:24191",
5139 "Bearer partial-profile",
5140 "Handshake",
5141 );
5142 assert!(matches!(
5143 provision_native_hns_read_profile(&partial, 0, &profile, 1),
5144 Err(NativeHnsReadProfileError::AccountMismatch)
5145 ));
5146
5147 let complete =
5148 native_hns_profile_store(&directory.path().join("ambiguous.sqlite3"), &account);
5149 let second = production_hns_config(10, 1);
5150 complete
5151 .with_store_mut(|wallet| {
5152 wallet
5153 .save_wallet_account(
5154 &production_hns_record_id(&second),
5155 0,
5156 &production_hns_account(second),
5157 2,
5158 )
5159 .map(|_| ())
5160 })
5161 .expect("persist ambiguous second account");
5162 assert!(matches!(
5163 provision_native_hns_read_profile(&complete, 0, &profile, 2),
5164 Err(NativeHnsReadProfileError::AccountMismatch)
5165 ));
5166 }
5167
5168 #[cfg(target_os = "linux")]
5169 #[test]
5170 fn native_hns_read_profile_rejects_unknown_schema_and_wrong_record_id() {
5171 let directory = native_hns_read_tempdir();
5172 let account = production_hns_config(9, 0);
5173 let store = native_hns_profile_store(&directory.path().join("wallet.sqlite3"), &account);
5174 let valid_record = json!({
5175 "state": "active",
5176 "schemaVersion": 1,
5177 "account": account,
5178 "nodeEndpoint": "127.0.0.1:24191",
5179 "nodeAuthorization": "Bearer schema-profile",
5180 "accountLabel": "Handshake",
5181 });
5182 let mut unknown_account_field = valid_record.clone();
5183 unknown_account_field["account"]["future_authority"] = json!(true);
5184 store
5185 .with_store_mut(|wallet| {
5186 wallet
5187 .save_native_hns_read_profile(b"wrong-profile-id", 0, &valid_record, 1)
5188 .map(|_| ())
5189 })
5190 .expect("persist wrong profile ID");
5191 assert!(matches!(
5192 load_native_hns_read_profile(&store),
5193 Err(NativeHnsReadProfileError::SingletonConflict)
5194 ));
5195
5196 let unknown_store = native_hns_profile_store(
5197 &directory.path().join("unknown-schema.sqlite3"),
5198 &production_hns_config(9, 0),
5199 );
5200 let mut unknown = valid_record;
5201 unknown["schemaVersion"] = json!(2);
5202 unknown_store
5203 .with_store_mut(|wallet| {
5204 wallet
5205 .save_native_hns_read_profile(NATIVE_HNS_READ_PROFILE_ID, 0, &unknown, 2)
5206 .map(|_| ())
5207 })
5208 .expect("persist unknown profile schema");
5209 assert!(matches!(
5210 load_native_hns_read_profile(&unknown_store),
5211 Err(NativeHnsReadProfileError::UnsupportedSchema)
5212 ));
5213 assert_eq!(
5214 revoke_native_hns_read_profile(&unknown_store, 1, 3)
5215 .expect("revoke unknown profile schema without decoding its secret"),
5216 2
5217 );
5218
5219 let nested_unknown_store = native_hns_profile_store(
5220 &directory.path().join("unknown-account-field.sqlite3"),
5221 &production_hns_config(9, 0),
5222 );
5223 nested_unknown_store
5224 .with_store_mut(|wallet| {
5225 wallet
5226 .save_native_hns_read_profile(
5227 NATIVE_HNS_READ_PROFILE_ID,
5228 0,
5229 &unknown_account_field,
5230 2,
5231 )
5232 .map(|_| ())
5233 })
5234 .expect("persist unknown nested account field");
5235 assert!(matches!(
5236 load_native_hns_read_profile(&nested_unknown_store),
5237 Err(NativeHnsReadProfileError::Store(StoreError::Json(_)))
5238 ));
5239 }
5240
5241 #[cfg(target_os = "linux")]
5242 #[test]
5243 fn profile_backed_native_hns_bootstrap_returns_unlocked_exact_six_read_service() {
5244 const PASSPHRASE: &str = "correct horse battery staple";
5245 const AUTHORIZATION: &str = "Bearer profile-bootstrap-authority-67c2";
5246 let directory = native_hns_read_tempdir();
5247 let account = production_hns_config(9, 0);
5248 let store = native_hns_profile_store(&directory.path().join("wallet.sqlite3"), &account);
5249 let profile = native_hns_profile(
5250 account.clone(),
5251 "127.0.0.1:24191",
5252 AUTHORIZATION,
5253 "Handshake",
5254 );
5255 assert_eq!(
5256 provision_native_hns_read_profile(&store, 0, &profile, 100)
5257 .expect("provision bootstrap profile"),
5258 1
5259 );
5260 store.lock().expect("lock before bootstrap");
5261
5262 let passphrase = native_hns_bootstrap_passphrase(PASSPHRASE);
5263 let passphrase_debug = format!("{passphrase:?}");
5264 assert!(passphrase_debug.contains("[REDACTED]"));
5265 assert!(!passphrase_debug.contains(PASSPHRASE));
5266 let mut service = WalletService::new_profile_backed_native_hns_reads(
5267 store.clone(),
5268 passphrase,
5269 NativeHnsReadProfileFence::new(1, 100),
5270 )
5271 .expect("profile-backed native HNS reads");
5272
5273 assert!(!store.is_locked().expect("bootstrap leaves store unlocked"));
5274 assert!(service.runtime.shares_store_authority(&store));
5275 assert_eq!(
5276 service.runtime.capabilities(),
5277 BTreeSet::from([
5278 ServiceCapability::WalletOperations,
5279 ServiceCapability::HnsReadOperationsV1,
5280 ServiceCapability::HnsWalletAuthorityContextV1,
5281 ])
5282 );
5283 assert!(
5284 service
5285 .capabilities
5286 .contains(&ServiceCapability::HnsReadOperationsV1)
5287 );
5288 assert!(
5289 service
5290 .capabilities
5291 .contains(&ServiceCapability::HnsWalletAuthorityContextV1)
5292 );
5293 for capability in [
5294 ServiceCapability::ProviderDispatch,
5295 ServiceCapability::ValueMovement,
5296 ServiceCapability::BrowserIntegration,
5297 ] {
5298 assert!(!service.capabilities.contains(&capability));
5299 }
5300
5301 let allowed = [
5302 WalletRequest::Status,
5303 WalletRequest::ListAccounts,
5304 WalletRequest::Balance {
5305 module: ModuleId::Handshake,
5306 account: account.account_id,
5307 },
5308 WalletRequest::ReceiveTarget {
5309 module: ModuleId::Handshake,
5310 account: account.account_id,
5311 },
5312 WalletRequest::TransactionHistory {
5313 module: ModuleId::Handshake,
5314 account: account.account_id,
5315 },
5316 WalletRequest::ModuleStatus {
5317 module: ModuleId::Handshake,
5318 },
5319 ];
5320 assert_eq!(allowed.len(), 6);
5321 assert!(
5322 allowed
5323 .iter()
5324 .all(ProfileBackedNativeHnsReadRuntime::admits_wallet_request)
5325 );
5326
5327 let ServiceResponse::Wallet {
5328 response: WalletResponse::Status { status },
5329 } = service
5330 .dispatch(
5331 ServiceRequest::Wallet {
5332 request: WalletRequest::Status,
5333 },
5334 NOW_MS,
5335 )
5336 .expect("already-unlocked status")
5337 else {
5338 panic!("status response")
5339 };
5340 assert!(!status.locked);
5341 assert_eq!(status.active_wallet, Some(account.wallet_id));
5342 let ServiceResponse::Wallet {
5343 response: WalletResponse::Accounts { accounts },
5344 } = service
5345 .dispatch(
5346 ServiceRequest::Wallet {
5347 request: WalletRequest::ListAccounts,
5348 },
5349 NOW_MS + 1,
5350 )
5351 .expect("already-unlocked account list")
5352 else {
5353 panic!("accounts response")
5354 };
5355 assert_eq!(accounts.len(), 1);
5356 assert_eq!(accounts[0].account_id, account.account_id);
5357
5358 let namespace_id = [41_u8; 16];
5359 let authority_request = WalletAuthorityContextRequest::CurrentHnsContext {
5360 network: WalletHandshakeNetwork::Regtest,
5361 network_magic: WalletHandshakeNetwork::Regtest.magic(),
5362 namespace_id,
5363 namespace_lease_generation: 7,
5364 module: ModuleId::Handshake,
5365 };
5366 let expected_account_revision = service
5367 .runtime
5368 .selected_account_revision()
5369 .expect("selected account revision");
5370 let ServiceResponse::WalletAuthority { context } = service
5371 .dispatch(
5372 ServiceRequest::WalletAuthority {
5373 request: authority_request,
5374 },
5375 NOW_MS + 2,
5376 )
5377 .expect("profile-backed HNS authority context")
5378 else {
5379 panic!("wallet authority response")
5380 };
5381 assert_eq!(
5382 context,
5383 WalletHnsAuthorityContext {
5384 network: WalletHandshakeNetwork::Regtest,
5385 network_magic: WalletHandshakeNetwork::Regtest.magic(),
5386 namespace_id,
5387 namespace_lease_generation: 7,
5388 active_wallet: account.wallet_id,
5389 account: account.account_id,
5390 wallet_authority_revision: 1,
5391 account_authority_revision: expected_account_revision,
5392 locked: false,
5393 module: ModuleId::Handshake,
5394 persistent_wallet_confirmed: true,
5395 recovery_pending: false,
5396 retirement_pending: false,
5397 hns_reads_ready: true,
5398 }
5399 );
5400 assert!(matches!(
5401 service.dispatch(
5402 ServiceRequest::WalletAuthority {
5403 request: WalletAuthorityContextRequest::CurrentHnsContext {
5404 network: WalletHandshakeNetwork::Testnet,
5405 network_magic: WalletHandshakeNetwork::Testnet.magic(),
5406 namespace_id,
5407 namespace_lease_generation: 7,
5408 module: ModuleId::Handshake,
5409 },
5410 },
5411 NOW_MS + 3,
5412 ),
5413 Err(ServiceFailure {
5414 code: ServiceErrorCode::InvalidRequest,
5415 ..
5416 })
5417 ));
5418 assert!(
5419 !store
5420 .is_locked()
5421 .expect("claim mismatch leaves service live")
5422 );
5423
5424 let account_record_id = production_hns_record_id(&account);
5425 let next_account_revision = store
5426 .with_store_mut(|wallet| {
5427 let stored = wallet
5428 .wallet_account::<HnsAccountRecord>(&account_record_id)?
5429 .expect("selected account row");
5430 let mut advanced = stored.value;
5431 advanced.next_receive_index = 1;
5432 wallet.save_wallet_account(&account_record_id, stored.revision, &advanced, 101)
5433 })
5434 .expect("advance authenticated account revision");
5435 assert!(next_account_revision > context.account_authority_revision);
5436 let ServiceResponse::WalletAuthority {
5437 context: advanced_context,
5438 } = service
5439 .dispatch(
5440 ServiceRequest::WalletAuthority {
5441 request: authority_request,
5442 },
5443 NOW_MS + 4,
5444 )
5445 .expect("re-read advanced HNS authority context")
5446 else {
5447 panic!("advanced wallet authority response")
5448 };
5449 assert_eq!(
5450 advanced_context.account_authority_revision,
5451 next_account_revision
5452 );
5453 assert_eq!(
5454 advanced_context.wallet_authority_revision,
5455 context.wallet_authority_revision
5456 );
5457 assert_ne!(advanced_context, context);
5458
5459 let rejected = [
5460 WalletRequest::Unlock {
5461 passphrase: hns_wallet_ffi::SecretString::new(PASSPHRASE.to_owned()),
5462 },
5463 WalletRequest::Lock,
5464 WalletRequest::CreateWallet {
5465 passphrase: hns_wallet_ffi::SecretString::new("create secret".to_owned()),
5466 },
5467 WalletRequest::RestoreWallet {
5468 passphrase: hns_wallet_ffi::SecretString::new("restore secret".to_owned()),
5469 recovery_phrase: hns_wallet_ffi::SecretString::new(
5470 "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
5471 .to_owned(),
5472 ),
5473 },
5474 WalletRequest::WorkflowStatus {
5475 workflow_id: hns_wallet_types::WorkflowId::new([7_u8; 16]),
5476 },
5477 WalletRequest::Balance {
5478 module: ModuleId::Bitcoin,
5479 account: account.account_id,
5480 },
5481 WalletRequest::ReceiveTarget {
5482 module: ModuleId::Ethereum,
5483 account: account.account_id,
5484 },
5485 WalletRequest::TransactionHistory {
5486 module: ModuleId::Bitcoin,
5487 account: account.account_id,
5488 },
5489 WalletRequest::ModuleStatus {
5490 module: ModuleId::Ethereum,
5491 },
5492 ];
5493 for (index, request) in rejected.into_iter().enumerate() {
5494 assert!(!ProfileBackedNativeHnsReadRuntime::admits_wallet_request(
5495 &request
5496 ));
5497 assert!(matches!(
5498 service.dispatch(
5499 ServiceRequest::Wallet { request },
5500 NOW_MS + 5 + u64::try_from(index).expect("bounded request index"),
5501 ),
5502 Err(ServiceFailure {
5503 code: ServiceErrorCode::UnsupportedCapability,
5504 unsupported_capability: Some(ServiceCapability::WalletOperations),
5505 ..
5506 })
5507 ));
5508 assert!(!store.is_locked().expect("rejection does not run ABI lock"));
5509 }
5510
5511 let authority = HostAuthorityFacts {
5512 origin: "https://wallet.example".to_owned(),
5513 namespace: ProviderNamespace::Hns,
5514 runtime_session_id: BrowserRuntimeSessionId::from_bytes([31_u8; 16])
5515 .expect("runtime session"),
5516 runtime_generation: 1,
5517 policy_generation: 1,
5518 navigation_generation: 1,
5519 decision_fingerprint: ProviderAuthorityFingerprint::from_bytes([32_u8; 32])
5520 .expect("authority fingerprint"),
5521 valid_until_unix_ms: NOW_MS + 60_000,
5522 };
5523 let provider_requests = vec![
5524 ServiceRequest::RegisterAuthority {
5525 authority_handle: handle(),
5526 authority: authority.clone(),
5527 },
5528 ServiceRequest::ReplaceAuthority {
5529 authority_handle: handle(),
5530 expected_authority_revision: 1,
5531 authority,
5532 },
5533 ServiceRequest::RevokeAuthority {
5534 authority_handle: handle(),
5535 expected_authority_revision: 1,
5536 },
5537 ServiceRequest::ProviderCapabilities {
5538 authority_handle: handle(),
5539 authority_revision: 1,
5540 },
5541 ServiceRequest::ProviderRequest {
5542 authority_handle: handle(),
5543 authority_revision: 1,
5544 request_nonce: 1,
5545 method: ProviderMethod::WalletGetStatus.wire_name().to_owned(),
5546 params: Value::Null,
5547 },
5548 ServiceRequest::ApprovalDecision {
5549 authority_handle: handle(),
5550 authority_revision: 1,
5551 approval_id: ProviderApprovalId::from_bytes([33_u8; 16])
5552 .expect("provider approval ID"),
5553 decision: hns_wallet_ffi::ApprovalDecision::Reject,
5554 },
5555 ];
5556 for (index, request) in provider_requests.into_iter().enumerate() {
5557 assert!(matches!(
5558 service.dispatch(
5559 request,
5560 NOW_MS + 20 + u64::try_from(index).expect("bounded provider request index"),
5561 ),
5562 Err(ServiceFailure {
5563 code: ServiceErrorCode::UnsupportedCapability,
5564 unsupported_capability: Some(ServiceCapability::ProviderDispatch),
5565 ..
5566 })
5567 ));
5568 assert!(
5569 !store
5570 .is_locked()
5571 .expect("provider rejection leaves active read service unlocked")
5572 );
5573 }
5574
5575 drop(service);
5576 assert!(
5577 store
5578 .is_locked()
5579 .expect("service drop relocks shared store")
5580 );
5581 }
5582
5583 #[cfg(target_os = "linux")]
5584 #[test]
5585 fn profile_backed_simnet_reads_never_advertise_browser_authority_context() {
5586 const PASSPHRASE: &str = "correct horse battery staple";
5587 let directory = native_hns_read_tempdir();
5588 let mut account = production_hns_config(9, 0);
5589 account.network = HnsNetwork::Simnet;
5590 let store = native_hns_profile_store(&directory.path().join("simnet.sqlite3"), &account);
5591 let profile = native_hns_profile(
5592 account,
5593 "127.0.0.1:24191",
5594 "Bearer simnet-profile",
5595 "Handshake Simnet",
5596 );
5597 assert_eq!(
5598 provision_native_hns_read_profile(&store, 0, &profile, 100)
5599 .expect("provision simnet profile"),
5600 1
5601 );
5602 store.lock().expect("lock simnet profile before bootstrap");
5603 let mut service = WalletService::new_profile_backed_native_hns_reads(
5604 store.clone(),
5605 native_hns_bootstrap_passphrase(PASSPHRASE),
5606 NativeHnsReadProfileFence::new(1, 100),
5607 )
5608 .expect("profile-backed simnet reads");
5609
5610 assert!(
5611 !service
5612 .runtime
5613 .capabilities()
5614 .contains(&ServiceCapability::HnsWalletAuthorityContextV1)
5615 );
5616 assert!(
5617 !service
5618 .capabilities
5619 .contains(&ServiceCapability::HnsWalletAuthorityContextV1)
5620 );
5621 assert!(matches!(
5622 service.dispatch(
5623 ServiceRequest::WalletAuthority {
5624 request: WalletAuthorityContextRequest::CurrentHnsContext {
5625 network: WalletHandshakeNetwork::Regtest,
5626 network_magic: WalletHandshakeNetwork::Regtest.magic(),
5627 namespace_id: [45_u8; 16],
5628 namespace_lease_generation: 1,
5629 module: ModuleId::Handshake,
5630 },
5631 },
5632 NOW_MS,
5633 ),
5634 Err(ServiceFailure {
5635 code: ServiceErrorCode::UnsupportedCapability,
5636 unsupported_capability: Some(ServiceCapability::HnsWalletAuthorityContextV1),
5637 ..
5638 })
5639 ));
5640 assert!(
5641 !store
5642 .is_locked()
5643 .expect("rejection leaves simnet reads live")
5644 );
5645 drop(service);
5646 assert!(store.is_locked().expect("simnet service drop relocks"));
5647 }
5648
5649 #[cfg(target_os = "linux")]
5650 #[test]
5651 fn profile_backed_native_hns_bootstrap_rejects_wrong_secret_absence_and_revocation_locked() {
5652 const PASSPHRASE: &str = "correct horse battery staple";
5653 let directory = native_hns_read_tempdir();
5654 let account = production_hns_config(9, 0);
5655
5656 let wrong_secret_store =
5657 native_hns_profile_store(&directory.path().join("wrong-secret.sqlite3"), &account);
5658 let profile = native_hns_profile(
5659 account.clone(),
5660 "127.0.0.1:24191",
5661 "Bearer wrong-secret-fixture",
5662 "Handshake",
5663 );
5664 provision_native_hns_read_profile(&wrong_secret_store, 0, &profile, 100)
5665 .expect("provision wrong-secret fixture");
5666 wrong_secret_store
5667 .lock()
5668 .expect("lock wrong-secret fixture");
5669 assert!(matches!(
5670 WalletService::new_profile_backed_native_hns_reads(
5671 wrong_secret_store.clone(),
5672 native_hns_bootstrap_passphrase("incorrect passphrase"),
5673 NativeHnsReadProfileFence::new(1, 100),
5674 ),
5675 Err(NativeHnsReadBootstrapError::Store(
5676 StoreError::InvalidPassphrase
5677 ))
5678 ));
5679 assert!(
5680 wrong_secret_store
5681 .is_locked()
5682 .expect("wrong secret relocks")
5683 );
5684
5685 let absent_store =
5686 native_hns_profile_store(&directory.path().join("absent.sqlite3"), &account);
5687 absent_store.lock().expect("lock absent fixture");
5688 assert!(matches!(
5689 WalletService::new_profile_backed_native_hns_reads(
5690 absent_store.clone(),
5691 native_hns_bootstrap_passphrase(PASSPHRASE),
5692 NativeHnsReadProfileFence::new(1, 100),
5693 ),
5694 Err(NativeHnsReadBootstrapError::ProfileAbsent)
5695 ));
5696 assert!(absent_store.is_locked().expect("absence relocks"));
5697
5698 let revoked_store =
5699 native_hns_profile_store(&directory.path().join("revoked.sqlite3"), &account);
5700 provision_native_hns_read_profile(&revoked_store, 0, &profile, 100)
5701 .expect("provision revoked fixture");
5702 assert_eq!(
5703 revoke_native_hns_read_profile(&revoked_store, 1, 101)
5704 .expect("revoke bootstrap profile"),
5705 2
5706 );
5707 revoked_store.lock().expect("lock revoked fixture");
5708 assert!(matches!(
5709 WalletService::new_profile_backed_native_hns_reads(
5710 revoked_store.clone(),
5711 native_hns_bootstrap_passphrase(PASSPHRASE),
5712 NativeHnsReadProfileFence::new(2, 101),
5713 ),
5714 Err(NativeHnsReadBootstrapError::ProfileRevoked {
5715 revision: 2,
5716 updated_at_unix: 101,
5717 })
5718 ));
5719 assert!(revoked_store.is_locked().expect("revocation relocks"));
5720 }
5721
5722 #[cfg(target_os = "linux")]
5723 #[test]
5724 fn profile_backed_native_hns_bootstrap_rejects_stale_fence_and_value_profile_locked() {
5725 const PASSPHRASE: &str = "correct horse battery staple";
5726 let directory = native_hns_read_tempdir();
5727 let account = production_hns_config(9, 0);
5728 let stale_store =
5729 native_hns_profile_store(&directory.path().join("stale.sqlite3"), &account);
5730 let profile = native_hns_profile(
5731 account.clone(),
5732 "127.0.0.1:24191",
5733 "Bearer stale-fence-fixture",
5734 "Handshake",
5735 );
5736 provision_native_hns_read_profile(&stale_store, 0, &profile, 100)
5737 .expect("provision stale fixture");
5738 stale_store.lock().expect("lock stale fixture");
5739 assert!(matches!(
5740 WalletService::new_profile_backed_native_hns_reads(
5741 stale_store.clone(),
5742 native_hns_bootstrap_passphrase(PASSPHRASE),
5743 NativeHnsReadProfileFence::new(1, 99),
5744 ),
5745 Err(NativeHnsReadBootstrapError::ProfileFenceMismatch {
5746 expected_revision: 1,
5747 expected_updated_at_unix: 99,
5748 actual_revision: 1,
5749 actual_updated_at_unix: 100,
5750 })
5751 ));
5752 assert!(stale_store.is_locked().expect("stale fence relocks"));
5753
5754 for (index, field) in ["value_operations_enabled", "settlement_enabled"]
5755 .into_iter()
5756 .enumerate()
5757 {
5758 let value_store = native_hns_profile_store(
5759 &directory.path().join(format!("value-{index}.sqlite3")),
5760 &account,
5761 );
5762 let mut persisted_account =
5763 serde_json::to_value(&account).expect("encode invalid profile account");
5764 persisted_account[field] = json!(true);
5765 let record = json!({
5766 "state": "active",
5767 "schemaVersion": 1,
5768 "account": persisted_account,
5769 "nodeEndpoint": "127.0.0.1:24191",
5770 "nodeAuthorization": "Bearer invalid-value-fixture",
5771 "accountLabel": "Handshake",
5772 });
5773 value_store
5774 .with_store_mut(|wallet| {
5775 wallet
5776 .save_native_hns_read_profile(NATIVE_HNS_READ_PROFILE_ID, 0, &record, 100)
5777 .map(|_| ())
5778 })
5779 .expect("persist invalid value profile fixture");
5780 value_store.lock().expect("lock invalid value fixture");
5781 assert!(matches!(
5782 WalletService::new_profile_backed_native_hns_reads(
5783 value_store.clone(),
5784 native_hns_bootstrap_passphrase(PASSPHRASE),
5785 NativeHnsReadProfileFence::new(1, 100),
5786 ),
5787 Err(NativeHnsReadBootstrapError::Profile(
5788 NativeHnsReadProfileError::InvalidConfiguration
5789 ))
5790 ));
5791 assert!(value_store.is_locked().expect("invalid value relocks"));
5792 }
5793 }
5794
5795 #[cfg(target_os = "linux")]
5796 #[test]
5797 fn flagged_profiles_open_only_as_exact_six_read_recovery_services() {
5798 const PASSPHRASE: &str = "correct horse battery staple";
5799 let directory = native_hns_read_tempdir();
5800
5801 for (index, network, value_operations_enabled, settlement_enabled) in [
5802 (0, HnsNetwork::Mainnet, true, false),
5803 (1, HnsNetwork::Mainnet, false, true),
5804 (2, HnsNetwork::Testnet, true, false),
5805 (3, HnsNetwork::Testnet, false, true),
5806 (4, HnsNetwork::Testnet, true, true),
5807 ] {
5808 let mut account = production_hns_config(9, 0);
5809 account.network = network;
5810 account.value_operations_enabled = value_operations_enabled;
5811 account.settlement_enabled = settlement_enabled;
5812 let store = native_hns_profile_store(
5813 &directory.path().join(format!("recovery-{index}.sqlite3")),
5814 &account,
5815 );
5816 persist_existing_flagged_native_hns_read_profile(&store, &account, 100);
5817
5818 assert!(matches!(
5819 load_native_hns_read_profile(&store),
5820 Err(NativeHnsReadProfileError::InvalidConfiguration)
5821 ));
5822 store.lock().expect("lock flagged profile before bootstrap");
5823 assert!(matches!(
5824 WalletService::new_profile_backed_native_hns_reads(
5825 store.clone(),
5826 native_hns_bootstrap_passphrase(PASSPHRASE),
5827 NativeHnsReadProfileFence::new(1, 100),
5828 ),
5829 Err(NativeHnsReadBootstrapError::Profile(
5830 NativeHnsReadProfileError::InvalidConfiguration
5831 ))
5832 ));
5833 assert!(store.is_locked().expect("ordinary failure relocks"));
5834
5835 let mut service: WalletService<
5836 SharedWalletStore,
5837 RecoveryProfileBackedNativeHnsReadRuntime,
5838 > = WalletService::new_recovery_read_only_profile_backed_native_hns_reads(
5839 store.clone(),
5840 native_hns_bootstrap_passphrase(PASSPHRASE),
5841 NativeHnsReadProfileFence::new(1, 100),
5842 )
5843 .expect("exact flagged recovery service");
5844 assert!(!store.is_locked().expect("recovery service is active"));
5845 assert!(service.runtime.shares_store_authority(&store));
5846 assert_eq!(
5847 service.runtime.capabilities(),
5848 BTreeSet::from([
5849 ServiceCapability::WalletOperations,
5850 ServiceCapability::HnsReadOperationsV1,
5851 ])
5852 );
5853 assert_eq!(
5854 service.capabilities,
5855 BTreeSet::from([
5856 ServiceCapability::CanonicalFraming,
5857 ServiceCapability::RestartIsolation,
5858 ServiceCapability::OpaqueAuthorityRegistry,
5859 ServiceCapability::StructuredApprovals,
5860 ServiceCapability::TypedEvents,
5861 ServiceCapability::WalletOperations,
5862 ServiceCapability::HnsReadOperationsV1,
5863 ])
5864 );
5865 for capability in [
5866 ServiceCapability::HnsWalletAuthorityContextV1,
5867 ServiceCapability::ProviderDispatch,
5868 ServiceCapability::PersistentPermissions,
5869 ServiceCapability::ValueMovement,
5870 ServiceCapability::BrowserIntegration,
5871 ] {
5872 assert!(!service.capabilities.contains(&capability));
5873 }
5874 for method in ProviderMethod::ALL {
5875 assert!(!service.runtime.supports_provider_method(method));
5876 }
5877 assert!(matches!(
5878 service.runtime.selected_hns_account(),
5879 Err(ServiceFailure {
5880 code: ServiceErrorCode::UnsupportedCapability,
5881 unsupported_capability: Some(ServiceCapability::ProviderDispatch),
5882 ..
5883 })
5884 ));
5885 assert!(matches!(
5886 service.runtime.current_hns_names(),
5887 Err(ServiceFailure {
5888 code: ServiceErrorCode::UnsupportedCapability,
5889 unsupported_capability: Some(ServiceCapability::ProviderDispatch),
5890 ..
5891 })
5892 ));
5893
5894 let allowed = [
5895 WalletRequest::Status,
5896 WalletRequest::ListAccounts,
5897 WalletRequest::Balance {
5898 module: ModuleId::Handshake,
5899 account: account.account_id,
5900 },
5901 WalletRequest::ReceiveTarget {
5902 module: ModuleId::Handshake,
5903 account: account.account_id,
5904 },
5905 WalletRequest::TransactionHistory {
5906 module: ModuleId::Handshake,
5907 account: account.account_id,
5908 },
5909 WalletRequest::ModuleStatus {
5910 module: ModuleId::Handshake,
5911 },
5912 ];
5913 assert_eq!(allowed.len(), 6);
5914 assert!(
5915 allowed
5916 .iter()
5917 .all(RecoveryProfileBackedNativeHnsReadRuntime::admits_wallet_request)
5918 );
5919
5920 let ServiceResponse::Wallet {
5921 response: WalletResponse::Status { status },
5922 } = service
5923 .dispatch(
5924 ServiceRequest::Wallet {
5925 request: WalletRequest::Status,
5926 },
5927 NOW_MS,
5928 )
5929 .expect("recovery status")
5930 else {
5931 panic!("status response")
5932 };
5933 assert!(!status.locked);
5934 assert_eq!(status.active_wallet, Some(account.wallet_id));
5935 assert!(!status.mainnet_settlement_enabled);
5936 let ServiceResponse::Wallet {
5937 response: WalletResponse::Accounts { accounts },
5938 } = service
5939 .dispatch(
5940 ServiceRequest::Wallet {
5941 request: WalletRequest::ListAccounts,
5942 },
5943 NOW_MS + 1,
5944 )
5945 .expect("recovery exact account")
5946 else {
5947 panic!("accounts response")
5948 };
5949 assert_eq!(accounts.len(), 1);
5950 assert_eq!(accounts[0].account_id, account.account_id);
5951
5952 assert!(matches!(
5953 service.dispatch(
5954 ServiceRequest::Wallet {
5955 request: WalletRequest::Lock,
5956 },
5957 NOW_MS + 2,
5958 ),
5959 Err(ServiceFailure {
5960 code: ServiceErrorCode::UnsupportedCapability,
5961 unsupported_capability: Some(ServiceCapability::WalletOperations),
5962 ..
5963 })
5964 ));
5965 assert!(matches!(
5966 service.dispatch(
5967 ServiceRequest::WalletAuthority {
5968 request: WalletAuthorityContextRequest::CurrentHnsContext {
5969 network: WalletHandshakeNetwork::Testnet,
5970 network_magic: WalletHandshakeNetwork::Testnet.magic(),
5971 namespace_id: [44_u8; 16],
5972 namespace_lease_generation: 1,
5973 module: ModuleId::Handshake,
5974 },
5975 },
5976 NOW_MS + 3,
5977 ),
5978 Err(ServiceFailure {
5979 code: ServiceErrorCode::UnsupportedCapability,
5980 unsupported_capability: Some(ServiceCapability::HnsWalletAuthorityContextV1),
5981 ..
5982 })
5983 ));
5984 assert!(matches!(
5985 service.dispatch(
5986 ServiceRequest::ProviderCapabilities {
5987 authority_handle: handle(),
5988 authority_revision: 1,
5989 },
5990 NOW_MS + 4,
5991 ),
5992 Err(ServiceFailure {
5993 code: ServiceErrorCode::UnsupportedCapability,
5994 unsupported_capability: Some(ServiceCapability::ProviderDispatch),
5995 ..
5996 })
5997 ));
5998 assert!(!store.is_locked().expect("rejections do not invoke lock"));
5999
6000 drop(service);
6001 assert!(store.is_locked().expect("recovery drop relocks"));
6002 let restarted: WalletService<
6003 SharedWalletStore,
6004 RecoveryProfileBackedNativeHnsReadRuntime,
6005 > = WalletService::new_recovery_read_only_profile_backed_native_hns_reads(
6006 store.clone(),
6007 native_hns_bootstrap_passphrase(PASSPHRASE),
6008 NativeHnsReadProfileFence::new(1, 100),
6009 )
6010 .expect("restart exact flagged recovery service");
6011 drop(restarted);
6012 assert!(store.is_locked().expect("restarted recovery drop relocks"));
6013 }
6014 }
6015
6016 #[cfg(target_os = "linux")]
6017 #[test]
6018 fn flagged_profile_recovery_rejects_absent_nonflagged_mismatch_and_stale_fences() {
6019 const PASSPHRASE: &str = "correct horse battery staple";
6020 let directory = native_hns_read_tempdir();
6021 let mut flagged = production_hns_config(9, 0);
6022 flagged.network = HnsNetwork::Testnet;
6023 flagged.value_operations_enabled = true;
6024
6025 let absent = native_hns_profile_store(&directory.path().join("absent.sqlite3"), &flagged);
6026 absent.lock().expect("lock absent recovery profile");
6027 assert!(matches!(
6028 WalletService::new_recovery_read_only_profile_backed_native_hns_reads(
6029 absent.clone(),
6030 native_hns_bootstrap_passphrase(PASSPHRASE),
6031 NativeHnsReadProfileFence::new(1, 100),
6032 ),
6033 Err(NativeHnsReadBootstrapError::ProfileAbsent)
6034 ));
6035 assert!(absent.is_locked().expect("absent recovery relocks"));
6036
6037 let nonflagged = production_hns_config(9, 0);
6038 let nonflagged_store =
6039 native_hns_profile_store(&directory.path().join("nonflagged.sqlite3"), &nonflagged);
6040 let nonflagged_profile = native_hns_profile(
6041 nonflagged,
6042 "127.0.0.1:24191",
6043 "Bearer nonflagged-recovery-fixture",
6044 "Handshake",
6045 );
6046 provision_native_hns_read_profile(&nonflagged_store, 0, &nonflagged_profile, 100)
6047 .expect("provision nonflagged profile");
6048 nonflagged_store
6049 .lock()
6050 .expect("lock nonflagged recovery profile");
6051 assert!(matches!(
6052 WalletService::new_recovery_read_only_profile_backed_native_hns_reads(
6053 nonflagged_store.clone(),
6054 native_hns_bootstrap_passphrase(PASSPHRASE),
6055 NativeHnsReadProfileFence::new(1, 100),
6056 ),
6057 Err(NativeHnsReadBootstrapError::Profile(
6058 NativeHnsReadProfileError::InvalidConfiguration
6059 ))
6060 ));
6061 assert!(
6062 nonflagged_store
6063 .is_locked()
6064 .expect("nonflagged recovery relocks")
6065 );
6066
6067 let stale = native_hns_profile_store(&directory.path().join("stale.sqlite3"), &flagged);
6068 persist_existing_flagged_native_hns_read_profile(&stale, &flagged, 100);
6069 stale.lock().expect("lock stale recovery profile");
6070 assert!(matches!(
6071 WalletService::new_recovery_read_only_profile_backed_native_hns_reads(
6072 stale.clone(),
6073 native_hns_bootstrap_passphrase(PASSPHRASE),
6074 NativeHnsReadProfileFence::new(1, 99),
6075 ),
6076 Err(NativeHnsReadBootstrapError::ProfileFenceMismatch {
6077 expected_revision: 1,
6078 expected_updated_at_unix: 99,
6079 actual_revision: 1,
6080 actual_updated_at_unix: 100,
6081 })
6082 ));
6083 assert!(stale.is_locked().expect("stale recovery relocks"));
6084
6085 let mismatch =
6086 native_hns_profile_store(&directory.path().join("account-mismatch.sqlite3"), &flagged);
6087 let mut other_flags = flagged.clone();
6088 other_flags.value_operations_enabled = false;
6089 other_flags.settlement_enabled = true;
6090 persist_existing_flagged_native_hns_read_profile(&mismatch, &other_flags, 100);
6091 mismatch.lock().expect("lock mismatch recovery profile");
6092 assert!(matches!(
6093 WalletService::new_recovery_read_only_profile_backed_native_hns_reads(
6094 mismatch.clone(),
6095 native_hns_bootstrap_passphrase(PASSPHRASE),
6096 NativeHnsReadProfileFence::new(1, 100),
6097 ),
6098 Err(NativeHnsReadBootstrapError::Profile(
6099 NativeHnsReadProfileError::AccountMismatch
6100 ))
6101 ));
6102 assert!(mismatch.is_locked().expect("mismatch recovery relocks"));
6103 }
6104
6105 #[cfg(target_os = "linux")]
6106 #[test]
6107 fn flagged_profile_recovery_locks_on_live_revocation() {
6108 const PASSPHRASE: &str = "correct horse battery staple";
6109 let directory = native_hns_read_tempdir();
6110 let mut flagged = production_hns_config(9, 0);
6111 flagged.network = HnsNetwork::Testnet;
6112 flagged.settlement_enabled = true;
6113 let store = native_hns_profile_store(&directory.path().join("revoked.sqlite3"), &flagged);
6114 persist_existing_flagged_native_hns_read_profile(&store, &flagged, 100);
6115 store
6116 .lock()
6117 .expect("lock recovery profile before bootstrap");
6118 let mut service: WalletService<
6119 SharedWalletStore,
6120 RecoveryProfileBackedNativeHnsReadRuntime,
6121 > = WalletService::new_recovery_read_only_profile_backed_native_hns_reads(
6122 store.clone(),
6123 native_hns_bootstrap_passphrase(PASSPHRASE),
6124 NativeHnsReadProfileFence::new(1, 100),
6125 )
6126 .expect("active recovery profile");
6127
6128 assert_eq!(
6129 revoke_native_hns_read_profile(&store, 1, 101).expect("revoke active recovery profile"),
6130 2
6131 );
6132 assert!(matches!(
6133 service.dispatch(
6134 ServiceRequest::Wallet {
6135 request: WalletRequest::Status,
6136 },
6137 NOW_MS,
6138 ),
6139 Err(ServiceFailure {
6140 code: ServiceErrorCode::PersistenceFailure,
6141 ..
6142 })
6143 ));
6144 assert!(store.is_locked().expect("revoked recovery service locks"));
6145 }
6146
6147 #[cfg(target_os = "linux")]
6148 #[test]
6149 fn profile_backed_native_hns_reads_lock_on_live_profile_rotation_or_revocation() {
6150 const PASSPHRASE: &str = "correct horse battery staple";
6151 let directory = native_hns_read_tempdir();
6152 let account = production_hns_config(9, 0);
6153
6154 for (index, revoke) in [false, true].into_iter().enumerate() {
6155 let store = native_hns_profile_store(
6156 &directory
6157 .path()
6158 .join(format!("live-profile-{index}.sqlite3")),
6159 &account,
6160 );
6161 let first = native_hns_profile(
6162 account.clone(),
6163 "127.0.0.1:24191",
6164 "Bearer live-profile-first",
6165 "Handshake",
6166 );
6167 provision_native_hns_read_profile(&store, 0, &first, 100)
6168 .expect("provision live profile");
6169 store.lock().expect("lock live profile before bootstrap");
6170 let mut service = WalletService::new_profile_backed_native_hns_reads(
6171 store.clone(),
6172 native_hns_bootstrap_passphrase(PASSPHRASE),
6173 NativeHnsReadProfileFence::new(1, 100),
6174 )
6175 .expect("bootstrap live profile");
6176
6177 if revoke {
6178 assert_eq!(
6179 revoke_native_hns_read_profile(&store, 1, 101)
6180 .expect("revoke active service profile"),
6181 2
6182 );
6183 } else {
6184 let rotated = native_hns_profile(
6185 account.clone(),
6186 "127.0.0.1:24192",
6187 "Bearer live-profile-rotated",
6188 "Rotated Handshake",
6189 );
6190 assert_eq!(
6191 provision_native_hns_read_profile(&store, 1, &rotated, 101)
6192 .expect("rotate active service profile"),
6193 2
6194 );
6195 }
6196
6197 assert!(matches!(
6198 service.dispatch(
6199 ServiceRequest::Wallet {
6200 request: WalletRequest::Status,
6201 },
6202 NOW_MS,
6203 ),
6204 Err(ServiceFailure {
6205 code: ServiceErrorCode::PersistenceFailure,
6206 unsupported_capability: None,
6207 ..
6208 })
6209 ));
6210 assert!(store.is_locked().expect("profile change locks service"));
6211 }
6212 }
6213
6214 #[cfg(target_os = "linux")]
6215 #[test]
6216 fn native_hns_read_constructor_wires_exact_store_and_non_value_surface() {
6217 let directory = native_hns_read_tempdir();
6218 let account = production_hns_config(9, 0);
6219 let store = production_hns_store(
6220 &directory.path().join("wallet.sqlite3"),
6221 std::slice::from_ref(&account),
6222 );
6223 let node_rpc = HnsNodeRpcConfig::new(
6224 "127.0.0.1:14038".parse().expect("loopback socket"),
6225 "Bearer test-only-node-authority",
6226 )
6227 .expect("authenticated loopback configuration");
6228 let mut service = WalletService::new_persistent_native_hns_reads(
6229 store.clone(),
6230 PersistentNativeHnsReadConfig {
6231 account: account.clone(),
6232 node_rpc,
6233 account_label: "Handshake".to_owned(),
6234 },
6235 )
6236 .expect("native HNS read service");
6237
6238 assert!(service.runtime.store.is_same_authority(&store));
6239 assert!(service.runtime.runtime.shares_store_authority(&store));
6240 assert!(store.is_locked().expect("locked startup"));
6241 assert!(
6242 service
6243 .capabilities
6244 .contains(&ServiceCapability::PersistentPermissions)
6245 );
6246 assert!(
6247 service
6248 .capabilities
6249 .contains(&ServiceCapability::ProviderDispatch)
6250 );
6251 assert!(
6252 service
6253 .capabilities
6254 .contains(&ServiceCapability::HnsReadOperationsV1)
6255 );
6256 assert!(
6257 !service
6258 .capabilities
6259 .contains(&ServiceCapability::HnsWalletAuthorityContextV1)
6260 );
6261 assert!(
6262 !service
6263 .capabilities
6264 .contains(&ServiceCapability::ValueMovement)
6265 );
6266 assert!(
6267 !service
6268 .capabilities
6269 .contains(&ServiceCapability::BrowserIntegration)
6270 );
6271
6272 service
6273 .provider
6274 .register_authority(handle(), registration(), NOW_MS)
6275 .expect("native browser authority");
6276 let ServiceResponse::Wallet {
6277 response: WalletResponse::Unlocked,
6278 } = service
6279 .dispatch(
6280 ServiceRequest::Wallet {
6281 request: WalletRequest::Unlock {
6282 passphrase: hns_wallet_ffi::SecretString::new(
6283 "correct horse battery staple".to_owned(),
6284 ),
6285 },
6286 },
6287 NOW_MS + 1,
6288 )
6289 .expect("unlock native HNS read service")
6290 else {
6291 panic!("unlock response")
6292 };
6293
6294 let ServiceResponse::Wallet {
6295 response: WalletResponse::Status { status },
6296 } = service
6297 .dispatch(
6298 ServiceRequest::Wallet {
6299 request: WalletRequest::Status,
6300 },
6301 NOW_MS + 2,
6302 )
6303 .expect("native status read")
6304 else {
6305 panic!("status response")
6306 };
6307 assert!(!status.locked);
6308 assert_eq!(status.active_wallet, Some(account.wallet_id));
6309 assert_eq!(
6310 status.enabled_modules,
6311 BTreeSet::from([ModuleId::Handshake])
6312 );
6313 assert!(!status.mainnet_settlement_enabled);
6314
6315 let ServiceResponse::Wallet {
6316 response: WalletResponse::Accounts { accounts },
6317 } = service
6318 .dispatch(
6319 ServiceRequest::Wallet {
6320 request: WalletRequest::ListAccounts,
6321 },
6322 NOW_MS + 3,
6323 )
6324 .expect("native account read")
6325 else {
6326 panic!("account response")
6327 };
6328 assert_eq!(accounts.len(), 1);
6329 assert_eq!(accounts[0].account_id, account.account_id);
6330
6331 let ServiceResponse::ProviderCapabilities { capabilities, .. } = service
6332 .provider_capabilities(handle(), 1, NOW_MS + 4)
6333 .expect("native read capabilities")
6334 else {
6335 panic!("provider capabilities response")
6336 };
6337 assert_eq!(
6338 capabilities.methods,
6339 BTreeSet::from([
6340 "hns_accounts".to_owned(),
6341 "hns_getBalance".to_owned(),
6342 "hns_getName".to_owned(),
6343 "hns_getNames".to_owned(),
6344 "hns_getReceiveAddress".to_owned(),
6345 "hns_getTransactions".to_owned(),
6346 "hns_requestAccounts".to_owned(),
6347 "wallet_getCapabilities".to_owned(),
6348 "wallet_getPermissions".to_owned(),
6349 "wallet_getStatus".to_owned(),
6350 "wallet_lock".to_owned(),
6351 "wallet_requestPermissions".to_owned(),
6352 "wallet_revokePermissions".to_owned(),
6353 ])
6354 );
6355
6356 for (index, method) in [
6357 ProviderMethod::HnsSend,
6358 ProviderMethod::HnsImportKnownName,
6359 ProviderMethod::HnsTransferName,
6360 ProviderMethod::HnsFinalizeName,
6361 ProviderMethod::HnsSignTypedMessage,
6362 ProviderMethod::NameMarketCreateFixedPriceOffer,
6363 ProviderMethod::NameMarketFinalizePurchase,
6364 ProviderMethod::AssetSend,
6365 ProviderMethod::WalletEnableModule,
6366 ]
6367 .into_iter()
6368 .enumerate()
6369 {
6370 assert!(matches!(
6371 service.provider_request(
6372 handle(),
6373 1,
6374 u64::try_from(index).expect("bounded request index") + 1,
6375 method.wire_name().to_owned(),
6376 Value::Null,
6377 NOW_MS + 5 + u64::try_from(index).expect("bounded request index"),
6378 ),
6379 Err(ServiceFailure {
6380 code: ServiceErrorCode::UnsupportedCapability,
6381 ..
6382 })
6383 ));
6384 }
6385 }
6386
6387 #[cfg(target_os = "linux")]
6388 #[test]
6389 fn native_hns_read_constructor_rejects_exact_persisted_flagged_account_config() {
6390 let directory = native_hns_read_tempdir();
6391 for (index, network, value_operations_enabled, settlement_enabled) in [
6392 (0, HnsNetwork::Mainnet, true, false),
6393 (1, HnsNetwork::Mainnet, false, true),
6394 (2, HnsNetwork::Testnet, true, false),
6395 (3, HnsNetwork::Testnet, false, true),
6396 ] {
6397 let mut persisted = production_hns_config(9, 0);
6398 persisted.network = network;
6399 persisted.value_operations_enabled = value_operations_enabled;
6400 persisted.settlement_enabled = settlement_enabled;
6401 let store = production_hns_store(
6402 &directory.path().join(format!("wallet-{index}.sqlite3")),
6403 std::slice::from_ref(&persisted),
6404 );
6405 let node_rpc = HnsNodeRpcConfig::new(
6406 "127.0.0.1:14038".parse().expect("loopback socket"),
6407 "Bearer test-only-node-authority",
6408 )
6409 .expect("authenticated loopback configuration");
6410
6411 assert!(matches!(
6412 WalletService::new_persistent_native_hns_reads(
6413 store,
6414 PersistentNativeHnsReadConfig {
6415 account: persisted,
6416 node_rpc,
6417 account_label: "Handshake".to_owned(),
6418 },
6419 ),
6420 Err(ServiceError::InvalidPersistentHnsAccount)
6421 ));
6422 }
6423 }
6424
6425 #[cfg(target_os = "linux")]
6426 #[test]
6427 fn production_next_advertises_only_exact_account_and_control_surface() {
6428 use std::os::unix::fs::PermissionsExt as _;
6429
6430 let first_directory = tempfile::tempdir().expect("first private directory");
6431 std::fs::set_permissions(
6432 first_directory.path(),
6433 std::fs::Permissions::from_mode(0o700),
6434 )
6435 .expect("first private permissions");
6436 let config = production_hns_config(9, 0);
6437 let first_store = production_hns_store(
6438 &first_directory.path().join("wallet.sqlite3"),
6439 std::slice::from_ref(&config),
6440 );
6441 let first_selector = HnsExistingAccountSelector::new(first_store.clone(), config.clone())
6442 .expect("first selector");
6443
6444 let second_directory = tempfile::tempdir().expect("second private directory");
6445 std::fs::set_permissions(
6446 second_directory.path(),
6447 std::fs::Permissions::from_mode(0o700),
6448 )
6449 .expect("second private permissions");
6450 let second_store = production_hns_store(
6451 &second_directory.path().join("wallet.sqlite3"),
6452 std::slice::from_ref(&config),
6453 );
6454 assert!(matches!(
6455 WalletService::new_persistent_hns_accounts(
6456 second_store.clone(),
6457 PersistentHnsAccountConfig {
6458 selector: first_selector.clone(),
6459 account_label: "Handshake".to_owned(),
6460 },
6461 ),
6462 Err(ServiceError::PersistentStoreAuthorityMismatch)
6463 ));
6464
6465 let missing_selector =
6466 HnsExistingAccountSelector::new(second_store.clone(), production_hns_config(10, 1))
6467 .expect("missing-account selector configuration");
6468 let mut missing_account_service = WalletService::new_persistent_hns_accounts(
6469 second_store.clone(),
6470 PersistentHnsAccountConfig {
6471 selector: missing_selector,
6472 account_label: "Handshake".to_owned(),
6473 },
6474 )
6475 .expect("locked missing-account composition");
6476 assert!(matches!(
6477 missing_account_service.dispatch(
6478 ServiceRequest::Wallet {
6479 request: WalletRequest::Unlock {
6480 passphrase: hns_wallet_ffi::SecretString::new(
6481 "correct horse battery staple".to_owned(),
6482 ),
6483 },
6484 },
6485 NOW_MS,
6486 ),
6487 Err(ServiceFailure {
6488 code: ServiceErrorCode::PersistenceFailure,
6489 ..
6490 })
6491 ));
6492 assert!(
6493 second_store
6494 .is_locked()
6495 .expect("failed unlock relocks store")
6496 );
6497
6498 let mut service = WalletService::new_persistent_hns_accounts(
6499 first_store,
6500 PersistentHnsAccountConfig {
6501 selector: first_selector,
6502 account_label: "Handshake".to_owned(),
6503 },
6504 )
6505 .expect("same-authority composition");
6506 assert!(
6507 !service
6508 .capabilities
6509 .contains(&ServiceCapability::ValueMovement)
6510 );
6511 assert!(
6512 !service
6513 .capabilities
6514 .contains(&ServiceCapability::BrowserIntegration)
6515 );
6516 assert!(
6517 !service
6518 .capabilities
6519 .contains(&ServiceCapability::HnsReadOperationsV1)
6520 );
6521 service
6522 .provider
6523 .register_authority(handle(), registration(), NOW_MS)
6524 .expect("authority");
6525 unlock_production_hns(&mut service, NOW_MS + 1);
6526 let ServiceResponse::ProviderCapabilities { capabilities, .. } = service
6527 .provider_capabilities(handle(), 1, NOW_MS + 2)
6528 .expect("capabilities")
6529 else {
6530 panic!("capabilities response")
6531 };
6532 assert_eq!(
6533 capabilities.methods,
6534 BTreeSet::from([
6535 "hns_accounts".to_owned(),
6536 "hns_requestAccounts".to_owned(),
6537 "wallet_getCapabilities".to_owned(),
6538 "wallet_getPermissions".to_owned(),
6539 "wallet_getStatus".to_owned(),
6540 "wallet_lock".to_owned(),
6541 "wallet_revokePermissions".to_owned(),
6542 ])
6543 );
6544 assert!(!capabilities.methods.contains("wallet_requestPermissions"));
6545 assert!(!capabilities.methods.contains("hns_getBalance"));
6546 assert!(!capabilities.methods.contains("hns_send"));
6547 }
6548
6549 #[cfg(target_os = "linux")]
6550 #[test]
6551 fn production_next_rejects_authenticated_zero_account_rows_without_exposure() {
6552 use std::os::unix::fs::PermissionsExt as _;
6553
6554 let zero_directory = tempfile::tempdir().expect("zero-account private directory");
6555 std::fs::set_permissions(
6556 zero_directory.path(),
6557 std::fs::Permissions::from_mode(0o700),
6558 )
6559 .expect("zero-account private permissions");
6560 let zero_config = production_hns_config(0, 0);
6561 let zero_store = production_hns_store(
6562 &zero_directory.path().join("wallet.sqlite3"),
6563 std::slice::from_ref(&zero_config),
6564 );
6565 assert!(matches!(
6566 HnsExistingAccountSelector::new(zero_store.clone(), zero_config),
6567 Err(HnsWalletError::InvalidRuntimeConfiguration)
6568 ));
6569 assert!(
6570 zero_store
6571 .is_locked()
6572 .expect("zero-account store remains locked")
6573 );
6574
6575 let malformed_directory = tempfile::tempdir().expect("malformed private directory");
6576 std::fs::set_permissions(
6577 malformed_directory.path(),
6578 std::fs::Permissions::from_mode(0o700),
6579 )
6580 .expect("malformed private permissions");
6581 let expected = production_hns_config(9, 0);
6582 let malformed = production_hns_account(production_hns_config(0, 0));
6583 let malformed_store = SharedWalletStore::new(
6584 WalletStore::create(
6585 malformed_directory.path().join("wallet.sqlite3"),
6586 "correct horse battery staple",
6587 )
6588 .expect("create malformed account store"),
6589 );
6590 malformed_store
6591 .with_store_mut(|wallet| {
6592 wallet
6593 .save_wallet_account(&production_hns_record_id(&expected), 0, &malformed, 10)
6594 .map(|_| ())
6595 })
6596 .expect("persist authenticated malformed row");
6597 malformed_store
6598 .lock()
6599 .expect("lock malformed account store");
6600 let selector = HnsExistingAccountSelector::new(malformed_store.clone(), expected)
6601 .expect("valid expected selector");
6602 let mut service = WalletService::new_persistent_hns_accounts(
6603 malformed_store.clone(),
6604 PersistentHnsAccountConfig {
6605 selector,
6606 account_label: "Handshake".to_owned(),
6607 },
6608 )
6609 .expect("locked malformed-row composition");
6610 assert!(matches!(
6611 service.dispatch(
6612 ServiceRequest::Wallet {
6613 request: WalletRequest::Unlock {
6614 passphrase: hns_wallet_ffi::SecretString::new(
6615 "correct horse battery staple".to_owned(),
6616 ),
6617 },
6618 },
6619 NOW_MS,
6620 ),
6621 Err(ServiceFailure {
6622 code: ServiceErrorCode::PersistenceFailure,
6623 ..
6624 })
6625 ));
6626 assert!(
6627 malformed_store
6628 .is_locked()
6629 .expect("malformed unlock relocks")
6630 );
6631 assert!(matches!(
6632 service.dispatch(
6633 ServiceRequest::Wallet {
6634 request: WalletRequest::ListAccounts,
6635 },
6636 NOW_MS + 1,
6637 ),
6638 Err(ServiceFailure {
6639 code: ServiceErrorCode::WalletLocked,
6640 ..
6641 })
6642 ));
6643 }
6644
6645 #[cfg(target_os = "linux")]
6646 #[test]
6647 fn production_next_minimizes_and_rechecks_the_runtime_selected_singleton_account() {
6648 use std::os::unix::fs::PermissionsExt as _;
6649
6650 let directory = tempfile::tempdir().expect("private directory");
6651 std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700))
6652 .expect("private permissions");
6653 let config = production_hns_config(9, 0);
6654 let alternate_config = production_hns_config(10, 1);
6655 let store = production_hns_store(
6656 &directory.path().join("wallet.sqlite3"),
6657 &[config.clone(), alternate_config.clone()],
6658 );
6659 let mut service = production_hns_service(store.clone(), config.clone());
6660 service
6661 .provider
6662 .register_authority(handle(), registration(), NOW_MS)
6663 .expect("HNS authority");
6664 let mut icann = registration();
6665 icann.namespace = SelectedNamespace::Icann;
6666 service
6667 .provider
6668 .register_authority(restart_handle(), icann, NOW_MS)
6669 .expect("ICANN authority");
6670 unlock_production_hns(&mut service, NOW_MS + 1);
6671
6672 assert!(matches!(
6673 service.provider_request(
6674 restart_handle(),
6675 1,
6676 1,
6677 ProviderMethod::HnsRequestAccounts.wire_name().to_owned(),
6678 Value::Null,
6679 NOW_MS + 2,
6680 ),
6681 Err(ServiceFailure {
6682 code: ServiceErrorCode::PermissionDenied,
6683 ..
6684 })
6685 ));
6686
6687 let ServiceResponse::ApprovalRequired { approval } = service
6688 .provider_request(
6689 handle(),
6690 1,
6691 1,
6692 ProviderMethod::HnsRequestAccounts.wire_name().to_owned(),
6693 Value::Null,
6694 NOW_MS + 3,
6695 )
6696 .expect("account approval")
6697 else {
6698 panic!("account approval response")
6699 };
6700 let ServiceResponse::ProviderResult { value, .. } = service
6701 .approval_decision(
6702 handle(),
6703 1,
6704 approval.approval_id,
6705 hns_wallet_ffi::ApprovalDecision::Approve,
6706 NOW_MS + 4,
6707 )
6708 .expect("account approval decision")
6709 else {
6710 panic!("account result")
6711 };
6712 assert_eq!(value, json!([config.account_id.to_string()]));
6713 let permission = service
6714 .provider
6715 .permission(handle(), 1, NOW_MS + 4)
6716 .expect("permission read")
6717 .expect("account permission");
6718 assert_eq!(
6719 permission.approved_accounts,
6720 BTreeSet::from([config.account_id])
6721 );
6722 assert_eq!(
6723 permission.capabilities,
6724 BTreeSet::from([PermissionCapability::Accounts])
6725 );
6726
6727 let ServiceResponse::ProviderResult { value, .. } = service
6728 .provider_request(
6729 handle(),
6730 1,
6731 2,
6732 ProviderMethod::HnsAccounts.wire_name().to_owned(),
6733 Value::Object(serde_json::Map::new()),
6734 NOW_MS + 5,
6735 )
6736 .expect("minimized account projection")
6737 else {
6738 panic!("account projection")
6739 };
6740 assert_eq!(value, json!([config.account_id.to_string()]));
6741 assert!(matches!(
6742 service.provider_request(
6743 handle(),
6744 1,
6745 3,
6746 ProviderMethod::HnsAccounts.wire_name().to_owned(),
6747 json!({ "account": config.account_id }),
6748 NOW_MS + 6,
6749 ),
6750 Err(ServiceFailure {
6751 code: ServiceErrorCode::InvalidRequest,
6752 ..
6753 })
6754 ));
6755
6756 let ServiceResponse::Wallet {
6757 response: WalletResponse::Locked,
6758 } = service
6759 .dispatch(
6760 ServiceRequest::Wallet {
6761 request: WalletRequest::Lock,
6762 },
6763 NOW_MS + 7,
6764 )
6765 .expect("lock before alternate selection restart")
6766 else {
6767 panic!("lock response")
6768 };
6769 drop(service);
6770
6771 let mut restarted = production_hns_service(store, alternate_config);
6772 restarted
6773 .provider
6774 .register_authority(handle(), registration(), NOW_MS + 8)
6775 .expect("restarted authority");
6776 unlock_production_hns(&mut restarted, NOW_MS + 9);
6777 assert!(matches!(
6778 restarted.provider_request(
6779 handle(),
6780 1,
6781 1,
6782 ProviderMethod::HnsAccounts.wire_name().to_owned(),
6783 Value::Null,
6784 NOW_MS + 10,
6785 ),
6786 Err(ServiceFailure {
6787 code: ServiceErrorCode::PermissionDenied,
6788 ..
6789 })
6790 ));
6791 }
6792
6793 #[cfg(target_os = "linux")]
6794 #[test]
6795 fn production_next_restarts_locked_preserves_tombstone_and_returns_provider_lock() {
6796 use std::os::unix::fs::PermissionsExt as _;
6797
6798 let directory = tempfile::tempdir().expect("private directory");
6799 std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700))
6800 .expect("private permissions");
6801 let database_path = directory.path().join("wallet.sqlite3");
6802 let config = production_hns_config(9, 0);
6803 let first_store = production_hns_store(&database_path, std::slice::from_ref(&config));
6804 let mut first = production_hns_service(first_store.clone(), config.clone());
6805 first
6806 .provider
6807 .register_authority(handle(), registration(), NOW_MS)
6808 .expect("first authority");
6809 assert!(matches!(
6810 first.provider_request(
6811 handle(),
6812 1,
6813 1,
6814 ProviderMethod::HnsRequestAccounts.wire_name().to_owned(),
6815 Value::Null,
6816 NOW_MS,
6817 ),
6818 Err(ServiceFailure {
6819 code: ServiceErrorCode::WalletLocked,
6820 ..
6821 })
6822 ));
6823 unlock_production_hns(&mut first, NOW_MS + 1);
6824 let ServiceResponse::ApprovalRequired { approval } = first
6825 .provider_request(
6826 handle(),
6827 1,
6828 2,
6829 ProviderMethod::HnsRequestAccounts.wire_name().to_owned(),
6830 Value::Null,
6831 NOW_MS + 2,
6832 )
6833 .expect("account approval")
6834 else {
6835 panic!("approval")
6836 };
6837 first
6838 .approval_decision(
6839 handle(),
6840 1,
6841 approval.approval_id,
6842 hns_wallet_ffi::ApprovalDecision::Approve,
6843 NOW_MS + 3,
6844 )
6845 .expect("grant account");
6846 let ServiceResponse::ProviderResult { binding, .. } = first
6847 .provider_request(
6848 handle(),
6849 1,
6850 3,
6851 ProviderMethod::WalletRevokePermissions
6852 .wire_name()
6853 .to_owned(),
6854 Value::Null,
6855 NOW_MS + 4,
6856 )
6857 .expect("revoke permission")
6858 else {
6859 panic!("revoke result")
6860 };
6861 assert_eq!(binding.permission_generation, 2);
6862 let old_wallet_session = first.wallet_session_id;
6863 let old_service_session = first.service_session_id;
6864 let ServiceResponse::ProviderResult { binding, value } = first
6865 .provider_request(
6866 handle(),
6867 1,
6868 4,
6869 ProviderMethod::WalletLock.wire_name().to_owned(),
6870 Value::Null,
6871 NOW_MS + 5,
6872 )
6873 .expect("provider lock result")
6874 else {
6875 panic!("provider lock")
6876 };
6877 assert_eq!(binding.permission_generation, 2);
6878 assert_ne!(binding.wallet_session_id, old_wallet_session);
6879 assert_eq!(value, json!({ "locked": true }));
6880 assert!(first_store.is_locked().expect("locked shared store"));
6881 drop(first);
6882 drop(first_store);
6883
6884 let reopened_store =
6885 SharedWalletStore::new(WalletStore::open(&database_path).expect("reopen wallet store"));
6886 let mut restarted = production_hns_service(reopened_store.clone(), config);
6887 assert!(reopened_store.is_locked().expect("restart locked"));
6888 assert_ne!(restarted.wallet_session_id, old_wallet_session);
6889 assert_ne!(restarted.service_session_id, old_service_session);
6890 assert!(restarted.pending.is_empty());
6891 assert!(restarted.seen_request_ids.is_empty());
6892 assert!(restarted.event_sequences.is_empty());
6893 restarted
6894 .provider
6895 .register_authority(restart_handle(), registration(), NOW_MS + 6)
6896 .expect("restart authority");
6897 unlock_production_hns(&mut restarted, NOW_MS + 7);
6898 let ServiceResponse::ProviderCapabilities {
6899 binding,
6900 capabilities,
6901 } = restarted
6902 .provider_capabilities(restart_handle(), 1, NOW_MS + 8)
6903 .expect("restart capabilities")
6904 else {
6905 panic!("restart capabilities")
6906 };
6907 assert_eq!(binding.permission_generation, 2);
6908 assert_eq!(capabilities.permission_generation, 2);
6909 let tombstone = restarted
6910 .provider
6911 .permission_snapshot(restart_handle(), 1, NOW_MS + 8)
6912 .expect("restart tombstone");
6913 assert_eq!(tombstone.generation, 2);
6914 assert!(tombstone.record.is_none());
6915 }
6916
6917 #[cfg(target_os = "linux")]
6918 #[test]
6919 fn production_next_rejects_all_value_module_and_unspecified_chain_reads() {
6920 use std::os::unix::fs::PermissionsExt as _;
6921
6922 let directory = tempfile::tempdir().expect("private directory");
6923 std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700))
6924 .expect("private permissions");
6925 let config = production_hns_config(9, 0);
6926 let store = production_hns_store(
6927 &directory.path().join("wallet.sqlite3"),
6928 std::slice::from_ref(&config),
6929 );
6930 let mut service = production_hns_service(store, config);
6931 service
6932 .provider
6933 .register_authority(handle(), registration(), NOW_MS)
6934 .expect("authority");
6935 unlock_production_hns(&mut service, NOW_MS + 1);
6936 let unsupported = [
6937 ProviderMethod::HnsGetBalance,
6938 ProviderMethod::HnsGetTransactions,
6939 ProviderMethod::HnsGetReceiveAddress,
6940 ProviderMethod::HnsGetNames,
6941 ProviderMethod::HnsGetName,
6942 ProviderMethod::HnsImportKnownName,
6943 ProviderMethod::HnsSend,
6944 ProviderMethod::HnsTransferName,
6945 ProviderMethod::HnsFinalizeName,
6946 ProviderMethod::HnsSignTypedMessage,
6947 ProviderMethod::WalletEnableModule,
6948 ProviderMethod::WalletDisableModule,
6949 ];
6950 for (index, method) in unsupported.into_iter().enumerate() {
6951 assert!(matches!(
6952 service.provider_request(
6953 handle(),
6954 1,
6955 u64::try_from(index).expect("bounded index") + 1,
6956 method.wire_name().to_owned(),
6957 Value::Null,
6958 NOW_MS + 2 + u64::try_from(index).expect("bounded index"),
6959 ),
6960 Err(ServiceFailure {
6961 code: ServiceErrorCode::UnsupportedCapability,
6962 ..
6963 })
6964 ));
6965 }
6966 assert!(matches!(
6967 service.provider_request(
6968 handle(),
6969 1,
6970 100,
6971 ProviderMethod::WalletRequestPermissions
6972 .wire_name()
6973 .to_owned(),
6974 json!({ "capabilities": ["balance"] }),
6975 NOW_MS + 100,
6976 ),
6977 Err(ServiceFailure {
6978 code: ServiceErrorCode::UnsupportedCapability,
6979 ..
6980 })
6981 ));
6982 assert!(
6983 !service
6984 .capabilities
6985 .contains(&ServiceCapability::ValueMovement)
6986 );
6987 assert!(
6988 !service
6989 .capabilities
6990 .contains(&ServiceCapability::BrowserIntegration)
6991 );
6992 }
6993
6994 #[test]
6995 fn private_provider_capabilities_are_typed_exact_and_bound() {
6996 let mut service = provider_service();
6997 let response = service
6998 .provider_capabilities(handle(), 1, NOW_MS)
6999 .expect("capabilities");
7000 let ServiceResponse::ProviderCapabilities {
7001 binding,
7002 capabilities: snapshot,
7003 } = response
7004 else {
7005 panic!("private capabilities")
7006 };
7007 assert_eq!(binding.wallet_session_id, service.wallet_session_id);
7008 assert_eq!(binding.permission_generation, 0);
7009 assert_eq!(snapshot.provider_schema_version, 1);
7010 assert_eq!(snapshot.approval_schema_version, 3);
7011 assert_eq!(snapshot.permission_generation, 0);
7012 assert!(!snapshot.methods.contains("hns_requestAccounts"));
7013 assert_eq!(
7014 snapshot.methods,
7015 BTreeSet::from([
7016 "wallet_getCapabilities".to_owned(),
7017 "wallet_getPermissions".to_owned(),
7018 "wallet_revokePermissions".to_owned(),
7019 ])
7020 );
7021 }
7022
7023 #[test]
7024 fn canonical_provider_account_join_persists_and_projects_only_the_approved_account() {
7025 let mut service = account_service();
7026 let ServiceResponse::ProviderCapabilities { capabilities, .. } = service
7027 .provider_capabilities(handle(), 1, NOW_MS)
7028 .expect("capabilities")
7029 else {
7030 panic!("private capabilities")
7031 };
7032 assert!(capabilities.methods.contains("hns_requestAccounts"));
7033 assert!(capabilities.methods.contains("hns_accounts"));
7034
7035 let ServiceResponse::ApprovalRequired { approval } = service
7036 .provider_request(
7037 handle(),
7038 1,
7039 1,
7040 ProviderMethod::HnsRequestAccounts.wire_name().to_owned(),
7041 Value::Null,
7042 NOW_MS,
7043 )
7044 .expect("account request")
7045 else {
7046 panic!("approval")
7047 };
7048 assert_eq!(
7049 approval.summary,
7050 ApprovalSummary::Permissions {
7051 capabilities: BTreeSet::from([PermissionCapability::Accounts]),
7052 hns_names: Vec::new(),
7053 }
7054 );
7055
7056 let ServiceResponse::ProviderResult { binding, value } = service
7057 .approval_decision(
7058 handle(),
7059 1,
7060 approval.approval_id,
7061 hns_wallet_ffi::ApprovalDecision::Approve,
7062 NOW_MS + 1,
7063 )
7064 .expect("approved account join")
7065 else {
7066 panic!("account result")
7067 };
7068 let account = AccountId::new([9_u8; 16]);
7069 assert_eq!(binding.permission_generation, 1);
7070 assert_eq!(value, json!([account.to_string()]));
7071 let permission = service
7072 .provider
7073 .permission(handle(), 1, NOW_MS + 1)
7074 .expect("permission")
7075 .expect("grant");
7076 assert_eq!(permission.approved_accounts, BTreeSet::from([account]));
7077
7078 let ServiceResponse::ProviderResult { binding, value } = service
7079 .provider_request(
7080 handle(),
7081 1,
7082 2,
7083 ProviderMethod::HnsAccounts.wire_name().to_owned(),
7084 Value::Object(serde_json::Map::new()),
7085 NOW_MS + 2,
7086 )
7087 .expect("account projection")
7088 else {
7089 panic!("account projection")
7090 };
7091 assert_eq!(binding.permission_generation, 1);
7092 assert_eq!(value, json!([account.to_string()]));
7093
7094 service.runtime.account_join_available = false;
7095 let failure = service.provider_request(
7096 handle(),
7097 1,
7098 3,
7099 ProviderMethod::HnsAccounts.wire_name().to_owned(),
7100 Value::Null,
7101 NOW_MS + 3,
7102 );
7103 assert!(matches!(
7104 failure,
7105 Err(ServiceFailure {
7106 code: ServiceErrorCode::UnsupportedCapability,
7107 ..
7108 })
7109 ));
7110
7111 let failure = service.provider_request(
7112 handle(),
7113 1,
7114 4,
7115 ProviderMethod::WalletRequestPermissions
7116 .wire_name()
7117 .to_owned(),
7118 json!({ "capabilities": ["accounts"] }),
7119 NOW_MS + 4,
7120 );
7121 assert!(matches!(
7122 failure,
7123 Err(ServiceFailure {
7124 code: ServiceErrorCode::InvalidRequest,
7125 ..
7126 })
7127 ));
7128 }
7129
7130 #[test]
7131 fn canonical_provider_account_join_rechecks_runtime_when_approval_executes() {
7132 let mut service = account_service();
7133 let ServiceResponse::ApprovalRequired { approval } = service
7134 .provider_request(
7135 handle(),
7136 1,
7137 1,
7138 ProviderMethod::HnsRequestAccounts.wire_name().to_owned(),
7139 Value::Null,
7140 NOW_MS,
7141 )
7142 .expect("account request")
7143 else {
7144 panic!("approval")
7145 };
7146 service.runtime.account_join_available = false;
7147 assert!(matches!(
7148 service.approval_decision(
7149 handle(),
7150 1,
7151 approval.approval_id,
7152 hns_wallet_ffi::ApprovalDecision::Approve,
7153 NOW_MS + 1,
7154 ),
7155 Err(ServiceFailure {
7156 code: ServiceErrorCode::UnsupportedCapability,
7157 ..
7158 })
7159 ));
7160 let permission = service
7161 .provider
7162 .permission_snapshot(handle(), 1, NOW_MS + 1)
7163 .expect("permission snapshot");
7164 assert_eq!(permission.generation, 0);
7165 assert!(permission.record.is_none());
7166 }
7167
7168 #[test]
7169 fn website_capabilities_expose_only_public_api_version_and_methods() {
7170 let mut service = provider_service();
7171 let response = service
7172 .provider_request(
7173 handle(),
7174 1,
7175 1,
7176 ProviderMethod::WalletGetCapabilities.wire_name().to_owned(),
7177 Value::Null,
7178 NOW_MS,
7179 )
7180 .expect("website capabilities");
7181 let ServiceResponse::ProviderResult { binding, value } = response else {
7182 panic!("provider result")
7183 };
7184 assert_eq!(binding.permission_generation, 0);
7185 assert_eq!(
7186 value
7187 .as_object()
7188 .expect("object")
7189 .keys()
7190 .cloned()
7191 .collect::<BTreeSet<_>>(),
7192 BTreeSet::from(["methods".to_owned(), "providerApiVersion".to_owned()])
7193 );
7194 assert_eq!(value["providerApiVersion"], json!(1));
7195 }
7196
7197 #[test]
7198 fn get_permissions_returns_the_revocation_tombstone_generation() {
7199 let mut service = provider_service();
7200 service
7201 .provider
7202 .set_wallet_state(service.wallet_session_id, false);
7203 service
7204 .provider
7205 .grant_permissions(
7206 handle(),
7207 1,
7208 BTreeSet::from([PermissionCapability::Send]),
7209 BTreeSet::new(),
7210 NOW_MS,
7211 None,
7212 )
7213 .expect("grant");
7214 assert_eq!(
7215 service
7216 .provider
7217 .revoke_permissions(handle(), 1, NOW_MS)
7218 .expect("revoke"),
7219 2
7220 );
7221 let response = service
7222 .provider_request(
7223 handle(),
7224 1,
7225 1,
7226 ProviderMethod::WalletGetPermissions.wire_name().to_owned(),
7227 Value::Null,
7228 NOW_MS,
7229 )
7230 .expect("permissions");
7231 let ServiceResponse::ProviderResult { binding, value } = response else {
7232 panic!("provider result")
7233 };
7234 assert_eq!(binding.permission_generation, 2);
7235 assert_eq!(value["permissionGeneration"], json!(2));
7236 assert_eq!(value["capabilities"], json!([]));
7237 }
7238}