Skip to main content

hns_wallet_mobile/
lib.rs

1#![doc = "Platform-neutral native wallet control for Android and iOS applications."]
2#![forbid(unsafe_code)]
3
4mod bitcoin;
5mod market;
6
7use std::collections::BTreeSet;
8use std::net::SocketAddr;
9use std::ops::{Deref, DerefMut};
10use std::path::Path;
11
12pub use bitcoin::{
13    MobileBitcoinBroadcastReceipt, MobileBitcoinDirectConfig, MobileBitcoinHtlcFundingApproval,
14    MobileBitcoinHtlcFundingReceipt, MobileBitcoinHtlcSettlementApproval,
15    MobileBitcoinHtlcSettlementReceipt, MobileBitcoinSendApproval, MobileBitcoinShutdownHandle,
16    MobileBitcoinSnapshot, MobileBitcoinSyncProgress, MobileBitcoinSyncProgressHandle,
17    MobileBitcoinValueController, MobileShakescapeUnfundedBitcoinProof,
18    ReconciledShakescapeBitcoinFunding,
19};
20pub use hns_wallet_bitcoin_kyoto::{
21    BitcoinBroadcastRecoverySummary, VerifiedBitcoinHtlcSpendObservation, VerifiedBitcoinLock,
22};
23pub use market::{
24    MINIMUM_BITCOIN_FEE_RESERVE_SATS, MobileAutomaticSettlementPermission,
25    MobileBtcForHnsOfferApproval, MobileBtcForHnsOfferSummary, MobileDirectOfferAcceptanceApproval,
26    MobileDirectOfferAcceptanceSummary, MobileDirectOfferCandidateSummary,
27    MobileDirectOfferSummary, MobileHnsForBtcOfferApproval, MobileShakescapeBitcoinAbsencePermit,
28    MobileShakescapeBitcoinFundingPermit, MobileShakescapeBitcoinSettlementPermit,
29    MobileShakescapeBitcoinWatchPermit, MobileShakescapeDirectAdmission,
30    MobileShakescapeDirectInventoryReport, MobileShakescapeDirectMessageKind,
31    MobileShakescapeDirectTransportReport, MobileShakescapeExecutionSummary,
32    MobileShakescapeFirstFundingObservation, MobileShakescapeHnsFundingPermit,
33    MobileShakescapeHnsSettlementPermit, MobileShakescapeHnsVerificationPermit,
34    MobileShakescapeHnsWatchPermit, MobileShakescapeSessionController,
35    MobileShakescapeSettlementAction, MobileShakescapeUnfundedHnsProof,
36};
37
38use hns_wallet_chain_api::{PreparedArtifact, PreparedSettlementLock};
39use hns_wallet_ffi::{
40    AbiError, AccountSummary, ApprovalSummary, HnsNameDisclosure, HostFrame, HostPlatform,
41    MAX_HNS_NAME_DISCLOSURES, SecretString, ServiceCapability, ServiceErrorCode, ServiceFailure,
42    ServiceResponse, WalletRequest, WalletResponse, WalletRuntimeStatus, decode_service_frame,
43    encode_host_frame,
44};
45/// Backend composition types exposed for downstream native shells. The RPC
46/// adapter remains available for explicitly configured local deployments; a
47/// host can instead open the wallet-owned direct peer coordinator below and
48/// compose its [`EmbeddedHnsBackend`] without endpoint credentials.
49pub use hns_wallet_hns::{
50    ConnectedHnsPeer, EmbeddedHnsBackend, HnsBackend, HnsBlockScanProgress, HnsBootstrapPolicy,
51    HnsClock, HnsDirectPeerConfig, HnsDirectPeerCoordinator, HnsDirectPeerError,
52    HnsDirectShakescapeListener, HnsDirectShakescapeMessage, HnsDirectShakescapePeer,
53    HnsHeaderRoundProgress, HnsInboundMobilePeer, HnsInboundNetworkPeer, HnsLightFloor, HnsNetwork,
54    HnsNodeRpcBackend, HnsNodeRpcConfig, HnsPublicPeerSessions, HnsShakescapeDirectFailure,
55    HnsShakescapeDiscoveryStatus, SystemClock as HnsReadSystemClock,
56};
57use hns_wallet_hns::{
58    HnsAccountReadRuntime, HnsAccountRecord, HnsExistingAccountSelector, HnsRuntimeConfig,
59    HnsWalletBootstrap, HnsWalletError, HnsWalletRuntime, KnownName, NameOwnershipStatus,
60    NameResourceStatus, RecoveryPhrase, open_wallet_direct_hns_peer_coordinator_with_floor,
61    open_wallet_direct_hns_peer_coordinator_with_floor_and_checkpoint_bootstrap,
62    open_wallet_direct_hns_peer_coordinator_with_floor_and_genesis_bootstrap,
63    open_wallet_direct_hns_peer_coordinator_with_floor_and_public_peer_sessions,
64    open_wallet_direct_hns_peer_coordinator_with_floor_checkpoint_and_public_peer_sessions,
65};
66use hns_wallet_host::{
67    Clock, ClockError, HostError, HostOutput, SystemClock, SystemEntropy, WalletHost,
68};
69use hns_wallet_market::{ShakescapeDirectOfferBoardPolicy, ShakescapeDirectSwapPolicy};
70use hns_wallet_provider::{
71    APPROVAL_LIFETIME_SECONDS, ApprovedCall, Origin, ProviderMethod, SelectedNamespace,
72};
73use hns_wallet_service::{
74    MAX_JAVASCRIPT_SAFE_INTEGER, NATIVE_HNS_SEND_PRE_BROADCAST_RETRY_MESSAGE,
75    NativeHnsFinalizeNoticePhase, NativeHnsNameOwnershipStatus, NativeHnsNameResourceStatus,
76    NativeHnsNameSummary, NativeHnsValueSnapshot, PersistentHnsAccountConfig,
77    PersistentHnsAccountRuntime, PersistentHnsReadConfig, PersistentHnsReadRuntime,
78    PersistentHnsValueConfig, PersistentHnsValueRuntime, PersistentShakedexConfig,
79    PersistentShakescapeTransport, ServiceError, ServiceRuntime, TRUSTED_NATIVE_HNS_VALUE_ORIGIN,
80    TrustedNativeHnsValueAction, WalletService,
81};
82use hns_wallet_shakedex::{DirectShakescapeBoardSyncReport, ShakedexSellerPolicy};
83use hns_wallet_store::{SharedWalletStore, StoreError, WalletStore};
84use hns_wallet_types::{
85    AccountId, Amount, ApprovalId, ApprovalKind, BaseUnits, HnsNameReceiveTarget, ModuleId,
86    ObjectHash, ReceiveTarget, SyncPhase, SyncStatus, TransactionSummary, WalletAsset,
87};
88use serde::{Deserialize, Serialize};
89use serde_json::{Value, json};
90use thiserror::Error;
91use zeroize::Zeroizing;
92
93pub const MOBILE_DATABASE_KEY_BYTES: usize = 32;
94pub const MAX_MOBILE_RECOVERY_PHRASE_BYTES: usize = 256;
95pub const MOBILE_ACCOUNT_LABEL: &str = "Handshake";
96pub const MAX_MOBILE_HNS_NAME_PAGE: usize = MAX_HNS_NAME_DISCLOSURES;
97const STORE_PASSPHRASE_DOMAIN: &str = "hns-wallet-mobile/store-passphrase/v1:";
98const RESTART_GENERATION: u64 = 1;
99const MAX_MOBILE_WALLET_ACCOUNTS: usize = 2;
100const MOBILE_ACTION_TOKEN_BYTES: usize = 32;
101const HEX: &[u8; 16] = b"0123456789abcdef";
102
103#[derive(Clone, Copy, Debug, Eq, PartialEq)]
104pub enum MobilePlatform {
105    Android,
106    Ios,
107}
108
109impl From<MobilePlatform> for HostPlatform {
110    fn from(platform: MobilePlatform) -> Self {
111        match platform {
112            MobilePlatform::Android => Self::Android,
113            MobilePlatform::Ios => Self::Ios,
114        }
115    }
116}
117
118/// A platform-unwrapped database key. It deliberately implements neither
119/// `Clone` nor `Debug`, and it is zeroized when dropped.
120pub struct MobileDatabaseKey(Zeroizing<[u8; MOBILE_DATABASE_KEY_BYTES]>);
121
122impl MobileDatabaseKey {
123    pub fn new(bytes: [u8; MOBILE_DATABASE_KEY_BYTES]) -> Result<Self, MobileWalletError> {
124        if bytes.iter().all(|byte| *byte == 0) {
125            return Err(MobileWalletError::InvalidDatabaseKey);
126        }
127        Ok(Self(Zeroizing::new(bytes)))
128    }
129
130    pub fn from_slice(bytes: &[u8]) -> Result<Self, MobileWalletError> {
131        let bytes = <[u8; MOBILE_DATABASE_KEY_BYTES]>::try_from(bytes)
132            .map_err(|_| MobileWalletError::InvalidDatabaseKey)?;
133        Self::new(bytes)
134    }
135
136    fn store_passphrase(&self) -> Zeroizing<String> {
137        let mut passphrase = Zeroizing::new(String::with_capacity(
138            STORE_PASSPHRASE_DOMAIN.len() + MOBILE_DATABASE_KEY_BYTES * 2,
139        ));
140        passphrase.push_str(STORE_PASSPHRASE_DOMAIN);
141        for byte in self.0.iter() {
142            passphrase.push(HEX[usize::from(byte >> 4)] as char);
143            passphrase.push(HEX[usize::from(byte & 0x0f)] as char);
144        }
145        passphrase
146    }
147}
148
149/// A caller-owned recovery phrase accepted only by the native restore path.
150/// It deliberately implements neither `Clone` nor `Debug` and zeroizes its
151/// allocation on drop.
152pub struct MobileRecoveryPhrase(Zeroizing<String>);
153
154impl MobileRecoveryPhrase {
155    pub fn new(value: String) -> Result<Self, MobileWalletError> {
156        if value.is_empty() || value.len() > MAX_MOBILE_RECOVERY_PHRASE_BYTES {
157            return Err(MobileWalletError::InvalidRecoveryPhrase);
158        }
159        Ok(Self(Zeroizing::new(value)))
160    }
161
162    fn expose_secret(&self) -> &str {
163        self.0.as_str()
164    }
165}
166
167type MobileHost = WalletHost<SystemClock, SystemEntropy>;
168
169struct MobileControllerSession<R> {
170    store: SharedWalletStore,
171    host: MobileHost,
172    service: WalletService<SharedWalletStore, R>,
173    failed: bool,
174}
175
176/// One process-local native controller. No raw ABI frame, provider authority,
177/// decrypted record key, or recovery phrase is exposed through this type.
178pub struct MobileWalletController {
179    session: MobileControllerSession<PersistentHnsAccountRuntime>,
180    account_config: HnsRuntimeConfig,
181    platform: MobilePlatform,
182}
183
184/// One minimized, serializable known-name projection for trusted native UI.
185/// Raw proofs, name-state bytes, owner outpoints, resource bytes, and key
186/// derivations never cross this boundary.
187#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
188#[serde(deny_unknown_fields, rename_all = "camelCase")]
189pub struct MobileHnsNameSummary {
190    pub name: String,
191    pub name_hash: String,
192    pub proof_height: u64,
193    pub resource_status: MobileHnsNameResourceStatus,
194    pub ownership_status: MobileHnsNameOwnershipStatus,
195    pub registered: Option<bool>,
196    pub expired: Option<bool>,
197    pub canonical_state: Option<MobileHnsNameStateSummary>,
198    pub raw_resource_hex: Option<String>,
199    pub resource_record_count: Option<u32>,
200}
201
202#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
203#[serde(deny_unknown_fields, rename_all = "camelCase")]
204pub struct MobileHnsNameStateSummary {
205    /// Locked name value in HNS base units. A decimal string preserves u64.
206    pub value_base_units: String,
207    /// Highest auction bid in HNS base units. A decimal string preserves u64.
208    pub highest_base_units: String,
209    pub start_height: u32,
210    pub renewal_height: u32,
211    pub transfer_height: u32,
212    pub revoked_height: u32,
213    pub claimed_height: u32,
214    pub renewals: u32,
215    pub weak: bool,
216}
217
218#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
219#[serde(rename_all = "camelCase")]
220pub enum MobileHnsNameResourceStatus {
221    UnavailableCanonicalBinding,
222    NoCurrentState,
223    Empty,
224    CanonicalDecoded,
225    CanonicalOpaque,
226}
227
228#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
229#[serde(rename_all = "camelCase")]
230pub enum MobileHnsNameOwnershipStatus {
231    WatchOnlyCanonicalStateDecoderUnavailable,
232    WatchOnlyOwnerTransactionUnavailable,
233    WalletContextUnavailable,
234    NoCurrentOwner,
235    NotWalletOwned,
236    WalletOwned,
237    IncomingTransfer,
238    OutgoingTransfer,
239}
240
241/// One exact synchronized read-only HNS projection. Every field comes from the
242/// same chain-tip/epoch and mempool instance/generation binding, which remains
243/// internal to the controller.
244#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
245#[serde(deny_unknown_fields, rename_all = "camelCase")]
246pub struct MobileHnsReadSnapshot {
247    pub balance: Amount,
248    pub receive_target: ReceiveTarget,
249    pub name_receive_target: HnsNameReceiveTarget,
250    pub transaction_history: Vec<TransactionSummary>,
251    /// First page only. Additional pages are obtained from the controller's
252    /// last authenticated synchronization without repeating reconciliation.
253    pub known_names: Vec<MobileHnsNameSummary>,
254    pub known_name_count: u32,
255    pub known_names_complete: bool,
256    /// Durable TRANSFER-to-FINALIZE lifecycle notices. These are present only
257    /// on the full value controller; the read-only controller returns none.
258    pub finalize_notices: Vec<MobileHnsFinalizeNotice>,
259    pub module_status: SyncStatus,
260}
261
262#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
263#[serde(deny_unknown_fields, rename_all = "camelCase")]
264pub struct MobileHnsFinalizeNotice {
265    pub name: String,
266    pub transaction_id: String,
267    pub phase: MobileHnsFinalizeNoticePhase,
268    pub current_height: u64,
269    pub finalize_eligible_height: Option<u64>,
270}
271
272#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
273#[serde(rename_all = "camelCase")]
274pub enum MobileHnsFinalizeNoticePhase {
275    TransferPending,
276    FinalizeWaiting,
277    FinalizeAvailable,
278    FinalizePending,
279}
280
281/// One deterministic page from the last authenticated known-name projection.
282#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
283#[serde(deny_unknown_fields, rename_all = "camelCase")]
284pub struct MobileHnsNamePage {
285    pub offset: u32,
286    pub total: u32,
287    pub names: Vec<MobileHnsNameSummary>,
288    pub has_more: bool,
289}
290
291/// Backend-injected native HNS read controller. It composes the exact same
292/// `SharedWalletStore` authority through account selection, synchronized HNS
293/// reconciliation, provider-state persistence, and private ABI lifecycle
294/// control. It authenticates a script-free epoch/tip and selected-network
295/// genesis before deriving or querying watch scripts. Backend transport remains
296/// a product-owned trust boundary. This controller exposes no browser/provider
297/// entry point or value operation.
298pub struct MobileHnsReadController<B, C = HnsReadSystemClock> {
299    session: MobileControllerSession<PersistentHnsReadRuntime<B, C>>,
300    account_config: HnsRuntimeConfig,
301    known_names: Vec<MobileHnsNameSummary>,
302}
303
304/// Full same-store native HNS controller. It retains the signing runtime and
305/// the private service behind an installed-product boundary, exposes no raw
306/// provider frames, and permits at most one exact process-local value approval
307/// at a time.
308pub struct MobileHnsValueController<B: HnsBackend, C: HnsClock = HnsReadSystemClock> {
309    session: MobileControllerSession<PersistentHnsValueRuntime<B, C>>,
310    account_config: HnsRuntimeConfig,
311    pending: Option<PendingMobileHnsValueAction>,
312    pending_shakescape_hns_funding: Option<PendingMobileShakescapeHnsFunding>,
313    pending_shakescape_hns_settlement: Option<PendingMobileShakescapeHnsSettlement>,
314    known_names: Vec<MobileHnsNameSummary>,
315}
316
317/// Full native HNS value controller composed with the wallet-owned direct
318/// standard-peer coordinator.
319///
320/// The inner [`MobileHnsValueController`] and the coordinator share one
321/// `EmbeddedHnsBackend`, encrypted light index, header authority, store/key
322/// authority, and direct broadcast pool. Keeping them in one value preserves
323/// the direct synchronization authority alongside the value runtime rather
324/// than requiring an endpoint-backed fallback after activation.
325pub struct MobileDirectHnsValueController<C: HnsClock = HnsReadSystemClock> {
326    value: MobileHnsValueController<EmbeddedHnsBackend, C>,
327    coordinator: HnsDirectPeerCoordinator,
328}
329
330impl<C: HnsClock> Deref for MobileDirectHnsValueController<C> {
331    type Target = MobileHnsValueController<EmbeddedHnsBackend, C>;
332
333    fn deref(&self) -> &Self::Target {
334        &self.value
335    }
336}
337
338impl<C: HnsClock> DerefMut for MobileDirectHnsValueController<C> {
339    fn deref_mut(&mut self) -> &mut Self::Target {
340        &mut self.value
341    }
342}
343
344/// A direct Shakescape listener created by one [`MobileDirectHnsValueController`].
345///
346/// The underlying listener stays private so accepting a peer has to cross the
347/// same controller that owns the value runtime's trusted clock.  It is still
348/// an ordinary socket resource: the embedding application must drop it when
349/// its native I/O worker stops, including when the wallet is locked.
350pub struct MobileDirectShakescapeListener {
351    listener: HnsDirectShakescapeListener,
352}
353
354impl MobileDirectShakescapeListener {
355    /// Return the concrete local socket locator, including a kernel-selected
356    /// port when the listener was bound with port zero.
357    pub fn local_addr(&self) -> Result<SocketAddr, MobileWalletError> {
358        self.listener.local_addr().map_err(Into::into)
359    }
360}
361
362/// One active mobile ShakeScape discovery/listening lifecycle.
363///
364/// The platform supplies an endpoint only after it has independently verified
365/// that the bound TCP listener is reachable there (public IPv6 or a temporary
366/// router mapping). The endpoint is never inferred from STUN because stock HSD
367/// `ADDR` describes a TCP Handshake peer, not a UDP candidate.
368pub struct MobileShakescapeNetworking {
369    listener: MobileDirectShakescapeListener,
370    verified_public_endpoint: SocketAddr,
371}
372
373impl MobileShakescapeNetworking {
374    /// Local bound listener, including its kernel-selected internal port.
375    pub fn local_addr(&self) -> Result<SocketAddr, MobileWalletError> {
376        self.listener.local_addr()
377    }
378
379    /// Host-verified public TCP endpoint currently eligible for advertisement.
380    #[must_use]
381    pub const fn verified_public_endpoint(&self) -> SocketAddr {
382        self.verified_public_endpoint
383    }
384}
385
386struct PendingMobileHnsValueAction {
387    action_token: [u8; MOBILE_ACTION_TOKEN_BYTES],
388    action: TrustedNativeHnsValueAction,
389}
390
391fn hns_second_funding_broadcast_guard(
392    guard: hns_wallet_market::SecondFundingBroadcastGuard,
393) -> Result<hns_wallet_hns::HnsSettlementBroadcastGuard, MobileWalletError> {
394    let workflow = guard.workflow_assertion();
395    let authorization = guard.authorization_assertion();
396    hns_wallet_hns::HnsSettlementBroadcastGuard::new_second_funding(
397        guard.session_id(),
398        workflow.id,
399        workflow.expected_revision,
400        authorization.id,
401        authorization.expected_revision,
402        guard.authorization_id(),
403        guard.module(),
404        guard.expires_at_unix(),
405    )
406    .map_err(MobileWalletError::from)
407}
408
409/// Closed native value vocabulary. The selected account and native origin are
410/// inserted by Rust and can never be supplied or replaced by Kotlin, Swift, a
411/// WebView, or website content.
412#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
413#[serde(
414    tag = "action",
415    rename_all = "camelCase",
416    rename_all_fields = "camelCase",
417    deny_unknown_fields
418)]
419pub enum MobileHnsValueIntent {
420    Send {
421        recipient: String,
422        amount: BaseUnits,
423        maximum_fee: BaseUnits,
424    },
425    TransferName {
426        name: String,
427        recipient: String,
428        maximum_fee: BaseUnits,
429    },
430    FinalizeName {
431        name: String,
432        expected_recipient: Option<String>,
433        maximum_fee: BaseUnits,
434    },
435    SetNameRecords {
436        name: String,
437        /// Human-readable records, or `hex:` followed by exact HSD resource bytes.
438        records: String,
439        maximum_fee: BaseUnits,
440    },
441    CreateFixedPriceOffer {
442        name: String,
443        price: BaseUnits,
444        maximum_fee: BaseUnits,
445        listing_lifetime_seconds: u64,
446    },
447    CancelOffer {
448        seller_session_id: String,
449    },
450    AcceptOffer {
451        listing_id: String,
452        maximum_fee: BaseUnits,
453        automatic_finalize_maximum_fee: Option<BaseUnits>,
454    },
455    FinalizePurchase {
456        session_id: String,
457        maximum_fee: BaseUnits,
458    },
459    RecoverName {
460        seller_session_id: String,
461        maximum_fee: BaseUnits,
462    },
463}
464
465/// Closed non-signing Shakedex query vocabulary for the installed native UI.
466#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
467#[serde(
468    tag = "query",
469    rename_all = "camelCase",
470    rename_all_fields = "camelCase",
471    deny_unknown_fields
472)]
473pub enum MobileShakedexQuery {
474    ListOffers {
475        cursor: Option<String>,
476        limit: Option<u16>,
477    },
478    ListMyOffers {
479        cursor: Option<String>,
480        limit: Option<u16>,
481    },
482    GetOffer {
483        listing_id: String,
484    },
485    GetSession {
486        session_id: String,
487    },
488}
489
490/// Exact summary displayed by native UI before one value action can execute.
491/// The opaque action token is process-local, random, single-use, and carries no
492/// signing authority after this controller is locked or dropped.
493#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
494#[serde(deny_unknown_fields, rename_all = "camelCase")]
495pub struct MobileHnsValueApproval {
496    pub action_token: String,
497    pub expires_at_unix: u64,
498    pub summary: ApprovalSummary,
499}
500
501struct PendingMobileShakescapeHnsFunding {
502    action_token: [u8; 32],
503    session_id: hns_wallet_types::SessionId,
504    side: hns_marketplace_protocol::SwapAssetSide,
505    prepared: PreparedSettlementLock,
506    maximum_fee: BaseUnits,
507}
508
509struct PendingMobileShakescapeHnsSettlement {
510    action_token: [u8; 32],
511    session_id: hns_wallet_types::SessionId,
512    action: MobileShakescapeSettlementAction,
513    prepared: PreparedArtifact,
514    maximum_fee: BaseUnits,
515}
516
517#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
518#[serde(deny_unknown_fields, rename_all = "camelCase")]
519pub struct MobileShakescapeHnsFundingApproval {
520    pub action_token: String,
521    pub session_id: String,
522    pub transaction_id: String,
523    pub amount_dollarydoos: u64,
524    pub fee_dollarydoos: u64,
525    pub maximum_fee_dollarydoos: u64,
526    pub refund_at_unix: u64,
527    pub expires_at_unix: u64,
528}
529
530#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
531#[serde(deny_unknown_fields, rename_all = "camelCase")]
532pub struct MobileShakescapeHnsFundingReceipt {
533    pub session_id: String,
534    pub transaction_id: String,
535    pub output_index: u32,
536    pub accepted_at_unix: u64,
537}
538
539#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
540#[serde(deny_unknown_fields, rename_all = "camelCase")]
541pub struct MobileShakescapeHnsSettlementApproval {
542    pub action_token: String,
543    pub session_id: String,
544    pub action: MobileShakescapeSettlementAction,
545    pub transaction_id: String,
546    pub input_amount_dollarydoos: u64,
547    pub output_amount_dollarydoos: u64,
548    pub fee_dollarydoos: u64,
549    pub maximum_fee_dollarydoos: u64,
550    pub expires_at_unix: u64,
551}
552
553#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
554#[serde(deny_unknown_fields, rename_all = "camelCase")]
555pub struct MobileShakescapeHnsSettlementReceipt {
556    pub session_id: String,
557    pub action: MobileShakescapeSettlementAction,
558    pub transaction_id: String,
559    pub accepted_at_unix: u64,
560}
561
562/// A newly created controller and its one-time dedicated recovery display.
563/// The phrase is not exposed as an ordinary public field or through `Debug`.
564pub struct MobileWalletCreation {
565    controller: MobileWalletController,
566    recovery_phrase: RecoveryPhrase,
567}
568
569impl MobileWalletCreation {
570    pub fn into_parts(self) -> (MobileWalletController, RecoveryPhrase) {
571        (self.controller, self.recovery_phrase)
572    }
573}
574
575impl<R: ServiceRuntime> MobileControllerSession<R> {
576    fn new(
577        store: SharedWalletStore,
578        host: MobileHost,
579        service: WalletService<SharedWalletStore, R>,
580    ) -> Self {
581        Self {
582            store,
583            host,
584            service,
585            failed: false,
586        }
587    }
588
589    fn negotiate_non_value(&mut self) -> Result<(), MobileWalletError> {
590        let hello = self.host.hello_frame()?;
591        match self.exchange(hello)? {
592            HostOutput::Negotiated(session)
593                if !session
594                    .capabilities
595                    .contains(&ServiceCapability::ValueMovement)
596                    && !session
597                        .capabilities
598                        .contains(&ServiceCapability::BrowserIntegration) =>
599            {
600                Ok(())
601            }
602            _ => Err(MobileWalletError::UnexpectedResponse),
603        }
604    }
605
606    fn negotiate_value(&mut self, require_shakedex: bool) -> Result<(), MobileWalletError> {
607        let hello = self.host.hello_frame()?;
608        match self.exchange(hello)? {
609            HostOutput::Negotiated(session)
610                if session
611                    .capabilities
612                    .contains(&ServiceCapability::WalletOperations)
613                    && session
614                        .capabilities
615                        .contains(&ServiceCapability::HnsReadOperationsV1)
616                    && session
617                        .capabilities
618                        .contains(&ServiceCapability::HnsValueOperationsV1)
619                    && session
620                        .capabilities
621                        .contains(&ServiceCapability::ProviderDispatch)
622                    && session
623                        .capabilities
624                        .contains(&ServiceCapability::ValueMovement)
625                    && (!require_shakedex
626                        || session
627                            .capabilities
628                            .contains(&ServiceCapability::ShakescapeShakedexV1))
629                    && !session
630                        .capabilities
631                        .contains(&ServiceCapability::BrowserIntegration) =>
632            {
633                Ok(())
634            }
635            _ => Err(MobileWalletError::UnexpectedResponse),
636        }
637    }
638
639    fn wallet_request(
640        &mut self,
641        request: WalletRequest,
642    ) -> Result<WalletResponse, MobileWalletError> {
643        let result = self.wallet_request_inner(request);
644        if result.is_err() {
645            self.lock_after_request_error();
646        }
647        result
648    }
649
650    fn wallet_request_inner(
651        &mut self,
652        request: WalletRequest,
653    ) -> Result<WalletResponse, MobileWalletError> {
654        if self.failed {
655            return Err(MobileWalletError::ControllerFailed);
656        }
657        let frame = self.host.wallet_request(request)?;
658        match self.exchange(frame)? {
659            HostOutput::Response(accepted) => match accepted.response {
660                ServiceResponse::Wallet { response } => Ok(response),
661                ServiceResponse::Failure { failure } => Err(mobile_service_failure(failure)),
662                _ => Err(MobileWalletError::UnexpectedResponse),
663            },
664            _ => Err(MobileWalletError::UnexpectedResponse),
665        }
666    }
667
668    fn lock_after_request_error(&mut self) {
669        if self.failed {
670            let _ = self.store.lock();
671            return;
672        }
673        let locked = matches!(
674            self.wallet_request_inner(WalletRequest::Lock),
675            Ok(WalletResponse::Locked)
676        );
677        if !locked {
678            self.failed = true;
679            let _ = self.store.lock();
680        }
681    }
682
683    fn exchange(&mut self, frame: HostFrame) -> Result<HostOutput, MobileWalletError> {
684        let result = (|| {
685            let encoded = encode_host_frame(&frame)?;
686            let response = self
687                .service
688                .process_frame(encoded.as_slice(), SystemClock.now_unix_ms()?)?;
689            let response = decode_service_frame(&response)?;
690            self.host
691                .accept_service_frame(response)
692                .map_err(MobileWalletError::from)
693        })();
694        if result.is_err() {
695            self.failed = true;
696            let _ = self.store.lock();
697        }
698        result
699    }
700}
701
702impl<R> Drop for MobileControllerSession<R> {
703    fn drop(&mut self) {
704        let _ = self.store.lock();
705    }
706}
707
708impl MobileWalletController {
709    /// Creates one new non-value HNS account. The cleanup guard remains armed
710    /// until the account, controller, private ABI session, and recovery-display
711    /// object all exist, so a fallible post-bootstrap step cannot strand an
712    /// undisclosed mnemonic behind a durable database.
713    pub fn create(
714        path: impl AsRef<Path>,
715        database_key: &MobileDatabaseKey,
716        platform: MobilePlatform,
717        policy: HnsBootstrapPolicy,
718    ) -> Result<MobileWalletCreation, MobileWalletError> {
719        let bootstrap = HnsWalletBootstrap::generate(policy)?;
720        let account_config = bootstrap.account_record().config.clone();
721        let host = WalletHost::new_system(platform.into(), RESTART_GENERATION)?;
722        let passphrase = database_key.store_passphrase();
723        let now_unix = SystemClock.now_unix_ms()? / 1_000;
724        WalletStore::create_with_owned_initializer(
725            path,
726            passphrase.as_str(),
727            move |mut store| -> Result<MobileWalletCreation, MobileWalletError> {
728                bootstrap.persist(&mut store, now_unix)?;
729                bitcoin::persist_mobile_bitcoin_wallet_origin(
730                    &mut store,
731                    account_config.account_id.as_bytes(),
732                    bitcoin::MobileBitcoinWalletOrigin::Generated,
733                    now_unix,
734                )?;
735                let controller = Self::from_unlocked_store(store, account_config, platform, host)?;
736                Ok(MobileWalletCreation {
737                    controller,
738                    recovery_phrase: bootstrap.into_recovery_phrase(),
739                })
740            },
741        )
742    }
743
744    /// Restores one new non-value HNS account from an owned, zeroizing 24-word
745    /// phrase input. It never opens or fills a pre-existing partial database.
746    pub fn restore(
747        path: impl AsRef<Path>,
748        database_key: &MobileDatabaseKey,
749        platform: MobilePlatform,
750        policy: HnsBootstrapPolicy,
751        recovery_phrase: MobileRecoveryPhrase,
752    ) -> Result<Self, MobileWalletError> {
753        let bootstrap = HnsWalletBootstrap::restore(recovery_phrase.expose_secret(), policy)?;
754        Self::restore_bootstrap(path, database_key, platform, bootstrap, recovery_phrase)
755    }
756
757    fn restore_bootstrap(
758        path: impl AsRef<Path>,
759        database_key: &MobileDatabaseKey,
760        platform: MobilePlatform,
761        bootstrap: HnsWalletBootstrap,
762        recovery_phrase: MobileRecoveryPhrase,
763    ) -> Result<Self, MobileWalletError> {
764        drop(recovery_phrase);
765        let account_config = bootstrap.account_record().config.clone();
766        let host = WalletHost::new_system(platform.into(), RESTART_GENERATION)?;
767        let passphrase = database_key.store_passphrase();
768        let now_unix = SystemClock.now_unix_ms()? / 1_000;
769        WalletStore::create_with_owned_initializer(
770            path,
771            passphrase.as_str(),
772            move |mut store| -> Result<Self, MobileWalletError> {
773                bootstrap.persist(&mut store, now_unix)?;
774                bitcoin::persist_mobile_bitcoin_wallet_origin(
775                    &mut store,
776                    account_config.account_id.as_bytes(),
777                    bitcoin::MobileBitcoinWalletOrigin::Restored,
778                    now_unix,
779                )?;
780                Self::from_unlocked_store(store, account_config, platform, host)
781            },
782        )
783    }
784
785    /// Open exactly one existing structurally valid HNS account and start
786    /// locked. Persisted value flags remain authenticated identity facts but do
787    /// not become authority in this lifecycle-only controller. The database key
788    /// is used only for discovery and is not retained.
789    pub fn open(
790        path: impl AsRef<Path>,
791        database_key: &MobileDatabaseKey,
792        platform: MobilePlatform,
793    ) -> Result<Self, MobileWalletError> {
794        let host = WalletHost::new_system(platform.into(), RESTART_GENERATION)?;
795        let mut store = WalletStore::open(path)?;
796        let passphrase = database_key.store_passphrase();
797        store.unlock(passphrase.as_str())?;
798        let mut accounts = store.wallet_accounts::<HnsAccountRecord>(MAX_MOBILE_WALLET_ACCOUNTS)?;
799        if accounts.len() != 1 {
800            store.lock();
801            return Err(MobileWalletError::InvalidAccountSet);
802        }
803        let account_config = accounts
804            .pop()
805            .ok_or(MobileWalletError::InvalidAccountSet)?
806            .value
807            .config;
808        store.validate_single_recovery_seed(account_config.wallet_id.as_bytes())?;
809        Self::from_unlocked_store(store, account_config, platform, host)
810    }
811
812    fn from_unlocked_store(
813        store: WalletStore,
814        account_config: HnsRuntimeConfig,
815        platform: MobilePlatform,
816        host: MobileHost,
817    ) -> Result<Self, MobileWalletError> {
818        let store = SharedWalletStore::new(store);
819        let selector =
820            HnsExistingAccountSelector::new_lifecycle(store.clone(), account_config.clone());
821        let selector = match selector {
822            Ok(selector) => selector,
823            Err(error) => {
824                let _ = store.lock();
825                return Err(error.into());
826            }
827        };
828        let selection = selector.selected_account();
829        let lock = store.lock();
830        selection?;
831        lock?;
832
833        let service = WalletService::new_persistent_hns_accounts(
834            store.clone(),
835            PersistentHnsAccountConfig {
836                selector,
837                account_label: MOBILE_ACCOUNT_LABEL.to_owned(),
838            },
839        )?;
840        let mut controller = Self {
841            session: MobileControllerSession::new(store, host, service),
842            account_config,
843            platform,
844        };
845        controller.session.negotiate_non_value()?;
846        Ok(controller)
847    }
848
849    pub const fn account_config(&self) -> &HnsRuntimeConfig {
850        &self.account_config
851    }
852
853    /// Open the wallet-owned direct HNS peer coordinator for this exact
854    /// encrypted account. This consumes no endpoint, RPC credential, relay,
855    /// or third-party index configuration: the coordinator derives its watch
856    /// set from the locally encrypted account and uses ordinary HNS peers.
857    ///
858    /// The controller returns locked. A host retains the coordinator while it
859    /// later consumes this lifecycle controller into the read or value runtime;
860    /// synchronization then runs only while that same wallet store is unlocked.
861    pub fn open_direct_hns_peer_coordinator(
862        &mut self,
863        database_key: &MobileDatabaseKey,
864        peer_config: HnsDirectPeerConfig,
865    ) -> Result<HnsDirectPeerCoordinator, MobileWalletError> {
866        self.open_direct_hns_peer_coordinator_with_floor(
867            database_key,
868            peer_config,
869            HnsLightFloor::default(),
870        )
871    }
872
873    /// Open the direct HNS coordinator with the platform-held monotonic
874    /// rollback floor. An installed shell persists this floor outside the
875    /// encrypted wallet database after header synchronization and provides it
876    /// again on reopen, preventing an older database backup from silently
877    /// becoming the wallet's chain authority.
878    pub fn open_direct_hns_peer_coordinator_with_floor(
879        &mut self,
880        database_key: &MobileDatabaseKey,
881        peer_config: HnsDirectPeerConfig,
882        rollback_floor: HnsLightFloor,
883    ) -> Result<HnsDirectPeerCoordinator, MobileWalletError> {
884        self.lock()?;
885        let store = self.session.store.clone();
886        let account_config = self.account_config.clone();
887        let passphrase = database_key.store_passphrase();
888        store.unlock(passphrase.as_str())?;
889        let now_unix = HnsReadSystemClock.now_unix()?;
890        let opened = open_wallet_direct_hns_peer_coordinator_with_floor(
891            store.clone(),
892            &account_config,
893            peer_config,
894            rollback_floor,
895            now_unix,
896        );
897        let relocked = store.lock();
898        match (opened, relocked) {
899            (Ok(coordinator), Ok(())) => Ok(coordinator),
900            (Err(error), _) => Err(error.into()),
901            (Ok(_), Err(error)) => Err(error.into()),
902        }
903    }
904
905    /// Reopen this exact wallet authority around transport sessions that a
906    /// prior controller sanitized before retirement. Platform code must scope
907    /// the handle to the same wallet database; the native type itself contains
908    /// no wallet identity or private state.
909    pub fn open_direct_hns_peer_coordinator_with_floor_and_public_peer_sessions(
910        &mut self,
911        database_key: &MobileDatabaseKey,
912        peer_config: HnsDirectPeerConfig,
913        rollback_floor: HnsLightFloor,
914        public_peer_sessions: HnsPublicPeerSessions,
915    ) -> Result<HnsDirectPeerCoordinator, MobileWalletError> {
916        self.lock()?;
917        let store = self.session.store.clone();
918        let account_config = self.account_config.clone();
919        let passphrase = database_key.store_passphrase();
920        store.unlock(passphrase.as_str())?;
921        let now_unix = HnsReadSystemClock.now_unix()?;
922        let opened = open_wallet_direct_hns_peer_coordinator_with_floor_and_public_peer_sessions(
923            store.clone(),
924            &account_config,
925            peer_config,
926            rollback_floor,
927            public_peer_sessions,
928            now_unix,
929        );
930        let relocked = store.lock();
931        match (opened, relocked) {
932            (Ok(coordinator), Ok(())) => Ok(coordinator),
933            (Err(error), _) => Err(error.into()),
934            (Ok(_), Err(error)) => Err(error.into()),
935        }
936    }
937
938    /// Open the direct coordinator from the compiled Mainnet checkpoint and
939    /// the canonical header segment after block 300,000 through the wallet's
940    /// exact birthday.
941    pub fn open_direct_hns_peer_coordinator_with_floor_and_checkpoint_bootstrap<I>(
942        &mut self,
943        database_key: &MobileDatabaseKey,
944        peer_config: HnsDirectPeerConfig,
945        rollback_floor: HnsLightFloor,
946        expected_height: u32,
947        expected_hash: [u8; 32],
948        headers_after_checkpoint: I,
949    ) -> Result<HnsDirectPeerCoordinator, MobileWalletError>
950    where
951        I: IntoIterator<Item = hns_header_consensus::Header>,
952    {
953        self.lock()?;
954        let store = self.session.store.clone();
955        let account_config = self.account_config.clone();
956        let passphrase = database_key.store_passphrase();
957        store.unlock(passphrase.as_str())?;
958        let now_unix = HnsReadSystemClock.now_unix()?;
959        let opened = open_wallet_direct_hns_peer_coordinator_with_floor_and_checkpoint_bootstrap(
960            store.clone(),
961            &account_config,
962            peer_config,
963            rollback_floor,
964            expected_height,
965            expected_hash,
966            headers_after_checkpoint,
967            now_unix,
968        );
969        let relocked = store.lock();
970        match (opened, relocked) {
971            (Ok(coordinator), Ok(())) => Ok(coordinator),
972            (Err(error), _) => Err(error.into()),
973            (Ok(_), Err(error)) => Err(error.into()),
974        }
975    }
976
977    /// Checkpoint-accelerated reopen using sanitized standard HSD sessions
978    /// retained by the same platform wallet scope.
979    #[allow(clippy::too_many_arguments)]
980    pub fn open_direct_hns_peer_coordinator_with_floor_checkpoint_and_public_peer_sessions<I>(
981        &mut self,
982        database_key: &MobileDatabaseKey,
983        peer_config: HnsDirectPeerConfig,
984        rollback_floor: HnsLightFloor,
985        expected_height: u32,
986        expected_hash: [u8; 32],
987        headers_after_checkpoint: I,
988        public_peer_sessions: HnsPublicPeerSessions,
989    ) -> Result<HnsDirectPeerCoordinator, MobileWalletError>
990    where
991        I: IntoIterator<Item = hns_header_consensus::Header>,
992    {
993        self.lock()?;
994        let store = self.session.store.clone();
995        let account_config = self.account_config.clone();
996        let passphrase = database_key.store_passphrase();
997        store.unlock(passphrase.as_str())?;
998        let now_unix = HnsReadSystemClock.now_unix()?;
999        let opened =
1000            open_wallet_direct_hns_peer_coordinator_with_floor_checkpoint_and_public_peer_sessions(
1001                store.clone(),
1002                &account_config,
1003                peer_config,
1004                rollback_floor,
1005                expected_height,
1006                expected_hash,
1007                headers_after_checkpoint,
1008                public_peer_sessions,
1009                now_unix,
1010            );
1011        let relocked = store.lock();
1012        match (opened, relocked) {
1013            (Ok(coordinator), Ok(())) => Ok(coordinator),
1014            (Err(error), _) => Err(error.into()),
1015            (Ok(_), Err(error)) => Err(error.into()),
1016        }
1017    }
1018
1019    /// Open the direct coordinator from a locally verified, product-pinned
1020    /// genesis header acceleration stream. This is only valid for the
1021    /// pristine new-wallet birthday represented by `expected_height`; restored
1022    /// wallets must retain their actual discovery birthday.
1023    pub fn open_direct_hns_peer_coordinator_with_floor_and_genesis_bootstrap<I>(
1024        &mut self,
1025        database_key: &MobileDatabaseKey,
1026        peer_config: HnsDirectPeerConfig,
1027        rollback_floor: HnsLightFloor,
1028        expected_height: u32,
1029        expected_hash: [u8; 32],
1030        headers: I,
1031    ) -> Result<HnsDirectPeerCoordinator, MobileWalletError>
1032    where
1033        I: IntoIterator<Item = hns_header_consensus::Header>,
1034    {
1035        self.lock()?;
1036        let store = self.session.store.clone();
1037        let account_config = self.account_config.clone();
1038        let passphrase = database_key.store_passphrase();
1039        store.unlock(passphrase.as_str())?;
1040        let now_unix = HnsReadSystemClock.now_unix()?;
1041        let opened = open_wallet_direct_hns_peer_coordinator_with_floor_and_genesis_bootstrap(
1042            store.clone(),
1043            &account_config,
1044            peer_config,
1045            rollback_floor,
1046            expected_height,
1047            expected_hash,
1048            headers,
1049            now_unix,
1050        );
1051        let relocked = store.lock();
1052        match (opened, relocked) {
1053            (Ok(coordinator), Ok(())) => Ok(coordinator),
1054            (Err(error), _) => Err(error.into()),
1055            (Ok(_), Err(error)) => Err(error.into()),
1056        }
1057    }
1058
1059    /// Consume this lifecycle-only controller and install a synchronized HNS
1060    /// read backend around the literal same process-local store/key authority.
1061    /// The controller is locked before its private session is replaced.
1062    pub fn into_hns_reads<B: HnsBackend>(
1063        self,
1064        backend: B,
1065    ) -> Result<MobileHnsReadController<B>, MobileWalletError> {
1066        self.into_hns_reads_with_clock(backend, HnsReadSystemClock)
1067    }
1068
1069    /// Clock-injectable form of [`Self::into_hns_reads`] for deterministic
1070    /// products and tests.
1071    pub fn into_hns_reads_with_clock<B: HnsBackend, C: HnsClock>(
1072        mut self,
1073        backend: B,
1074        clock: C,
1075    ) -> Result<MobileHnsReadController<B, C>, MobileWalletError> {
1076        self.lock()?;
1077        let store = self.session.store.clone();
1078        let account_config = self.account_config.clone();
1079        let platform = self.platform;
1080        drop(self);
1081        MobileHnsReadController::from_locked_store(
1082            store,
1083            account_config,
1084            WalletHost::new_system(platform.into(), RESTART_GENERATION)?,
1085            backend,
1086            clock,
1087        )
1088    }
1089
1090    /// Consume this lifecycle controller and activate the full same-store HNS
1091    /// value runtime. The database is unlocked only while the full runtime
1092    /// authenticates and persists its exact account policy, then it is relocked
1093    /// before the private value service is constructed.
1094    pub fn into_hns_value<B: HnsBackend>(
1095        self,
1096        database_key: &MobileDatabaseKey,
1097        backend: B,
1098        shakedex: Option<PersistentShakedexConfig>,
1099    ) -> Result<MobileHnsValueController<B>, MobileWalletError> {
1100        self.into_hns_value_with_clock(database_key, backend, HnsReadSystemClock, shakedex)
1101    }
1102
1103    /// Consume this lifecycle controller into the full HNS value composition
1104    /// backed only by its already-opened wallet-owned direct peer coordinator.
1105    ///
1106    /// This path accepts no RPC URL, node credential, relay, or indexer. The
1107    /// coordinator must have been opened from this exact controller before it
1108    /// is consumed; the account check rejects a generic coordinator or one for
1109    /// another wallet even when its network happens to match. The returned
1110    /// wrapper retains that coordinator for the complete value-controller
1111    /// lifetime, so the embedded backend's header, filtered-block, mempool,
1112    /// fee, and broadcast boundaries cannot outlive their direct transport.
1113    pub fn into_wallet_owned_direct_hns_value(
1114        self,
1115        database_key: &MobileDatabaseKey,
1116        coordinator: HnsDirectPeerCoordinator,
1117        shakedex: Option<PersistentShakedexConfig>,
1118    ) -> Result<MobileDirectHnsValueController, MobileWalletError> {
1119        self.into_wallet_owned_direct_hns_value_with_clock(
1120            database_key,
1121            coordinator,
1122            HnsReadSystemClock,
1123            shakedex,
1124        )
1125    }
1126
1127    /// Clock-injectable form of
1128    /// [`Self::into_wallet_owned_direct_hns_value`] for deterministic
1129    /// qualification fixtures.
1130    pub fn into_wallet_owned_direct_hns_value_with_clock<C: HnsClock>(
1131        self,
1132        database_key: &MobileDatabaseKey,
1133        coordinator: HnsDirectPeerCoordinator,
1134        clock: C,
1135        shakedex: Option<PersistentShakedexConfig>,
1136    ) -> Result<MobileDirectHnsValueController<C>, MobileWalletError> {
1137        coordinator.require_wallet_account_config(&self.account_config)?;
1138        let backend = coordinator.embedded_backend();
1139        let value = self.into_hns_value_with_clock(database_key, backend, clock, shakedex)?;
1140        Ok(MobileDirectHnsValueController { value, coordinator })
1141    }
1142
1143    /// Consume this lifecycle controller into native HNS value and Shakedex
1144    /// runtimes that both use wallet-owned direct peers.
1145    ///
1146    /// This fixes the marketplace policy to no marketplace fee and wallet-peer
1147    /// board transport, while retaining the same direct HNS coordinator for
1148    /// chain evidence, fee evidence, broadcasts, and later direct synchronization.
1149    pub fn into_wallet_owned_direct_hns_value_with_wallet_owned_direct_shakedex(
1150        self,
1151        database_key: &MobileDatabaseKey,
1152        coordinator: HnsDirectPeerCoordinator,
1153    ) -> Result<MobileDirectHnsValueController, MobileWalletError> {
1154        self.into_wallet_owned_direct_hns_value_with_wallet_owned_direct_shakedex_with_clock(
1155            database_key,
1156            coordinator,
1157            HnsReadSystemClock,
1158        )
1159    }
1160
1161    /// Clock-injectable form of
1162    /// [`Self::into_wallet_owned_direct_hns_value_with_wallet_owned_direct_shakedex`]
1163    /// for deterministic qualification fixtures.
1164    pub fn into_wallet_owned_direct_hns_value_with_wallet_owned_direct_shakedex_with_clock<
1165        C: HnsClock,
1166    >(
1167        self,
1168        database_key: &MobileDatabaseKey,
1169        coordinator: HnsDirectPeerCoordinator,
1170        clock: C,
1171    ) -> Result<MobileDirectHnsValueController<C>, MobileWalletError> {
1172        self.into_wallet_owned_direct_hns_value_with_clock(
1173            database_key,
1174            coordinator,
1175            clock,
1176            Some(wallet_owned_direct_shakedex_config()),
1177        )
1178    }
1179
1180    /// Clock-injectable value activation for deterministic installed products
1181    /// and qualification fixtures.
1182    pub fn into_hns_value_with_clock<B: HnsBackend, C: HnsClock>(
1183        mut self,
1184        database_key: &MobileDatabaseKey,
1185        backend: B,
1186        clock: C,
1187        shakedex: Option<PersistentShakedexConfig>,
1188    ) -> Result<MobileHnsValueController<B, C>, MobileWalletError> {
1189        self.lock()?;
1190        let store = self.session.store.clone();
1191        let platform = self.platform;
1192        let mut account_config = self.account_config.clone();
1193        account_config.value_operations_enabled = true;
1194        if shakedex.is_some() {
1195            account_config.settlement_enabled = true;
1196        }
1197        let require_shakedex = shakedex.is_some();
1198        drop(self);
1199
1200        let passphrase = database_key.store_passphrase();
1201        store.unlock(passphrase.as_str())?;
1202        let opened =
1203            HnsWalletRuntime::open_shared(backend, store.clone(), account_config.clone(), clock);
1204        // Construction of the service and all subsequent lifecycle always
1205        // begin locked, including every full-runtime activation failure.
1206        store.lock()?;
1207        let runtime = opened?;
1208        let service = WalletService::new_persistent_hns_value(
1209            store.clone(),
1210            PersistentHnsValueConfig {
1211                runtime,
1212                account_label: MOBILE_ACCOUNT_LABEL.to_owned(),
1213                shakedex,
1214            },
1215        )?;
1216        let mut controller = MobileHnsValueController {
1217            session: MobileControllerSession::new(
1218                store,
1219                WalletHost::new_system(platform.into(), RESTART_GENERATION)?,
1220                service,
1221            ),
1222            account_config,
1223            pending: None,
1224            pending_shakescape_hns_funding: None,
1225            pending_shakescape_hns_settlement: None,
1226            known_names: Vec::new(),
1227        };
1228        controller.session.negotiate_value(require_shakedex)?;
1229        Ok(controller)
1230    }
1231
1232    pub fn status(&mut self) -> Result<WalletRuntimeStatus, MobileWalletError> {
1233        match self.session.wallet_request(WalletRequest::Status)? {
1234            WalletResponse::Status { status } => Ok(status),
1235            _ => Err(MobileWalletError::UnexpectedResponse),
1236        }
1237    }
1238
1239    pub fn unlock(&mut self, database_key: &MobileDatabaseKey) -> Result<(), MobileWalletError> {
1240        // Rotate the private wallet session into a coherent locked posture
1241        // before testing a replacement key. WalletStore intentionally retains
1242        // its current key when a re-unlock fails, so skipping this step would
1243        // leave an already unlocked controller unlocked after a bad attempt.
1244        self.lock()?;
1245        let mut passphrase = database_key.store_passphrase();
1246        let passphrase = SecretString::new(std::mem::take(&mut *passphrase));
1247        match self
1248            .session
1249            .wallet_request(WalletRequest::Unlock { passphrase })?
1250        {
1251            WalletResponse::Unlocked => Ok(()),
1252            _ => Err(MobileWalletError::UnexpectedResponse),
1253        }
1254    }
1255
1256    pub fn lock(&mut self) -> Result<(), MobileWalletError> {
1257        match self.session.wallet_request(WalletRequest::Lock)? {
1258            WalletResponse::Locked => Ok(()),
1259            _ => Err(MobileWalletError::UnexpectedResponse),
1260        }
1261    }
1262
1263    pub fn accounts(&mut self) -> Result<Vec<AccountSummary>, MobileWalletError> {
1264        match self.session.wallet_request(WalletRequest::ListAccounts)? {
1265            WalletResponse::Accounts { accounts } => Ok(accounts),
1266            _ => Err(MobileWalletError::UnexpectedResponse),
1267        }
1268    }
1269}
1270
1271impl<B: HnsBackend> MobileHnsReadController<B, HnsReadSystemClock> {
1272    /// Open one existing native wallet around an injected HNS read backend and
1273    /// the production wall clock. Startup remains locked.
1274    pub fn open(
1275        path: impl AsRef<Path>,
1276        database_key: &MobileDatabaseKey,
1277        platform: MobilePlatform,
1278        backend: B,
1279    ) -> Result<Self, MobileWalletError> {
1280        Self::open_with_clock(path, database_key, platform, backend, HnsReadSystemClock)
1281    }
1282}
1283
1284impl<B: HnsBackend, C: HnsClock> MobileHnsReadController<B, C> {
1285    /// Clock-injectable open path for deterministic products and tests. The
1286    /// database key authenticates discovery only and is not retained.
1287    pub fn open_with_clock(
1288        path: impl AsRef<Path>,
1289        database_key: &MobileDatabaseKey,
1290        platform: MobilePlatform,
1291        backend: B,
1292        clock: C,
1293    ) -> Result<Self, MobileWalletError> {
1294        let host = WalletHost::new_system(platform.into(), RESTART_GENERATION)?;
1295        let mut store = WalletStore::open(path)?;
1296        let passphrase = database_key.store_passphrase();
1297        store.unlock(passphrase.as_str())?;
1298        let mut accounts = store.wallet_accounts::<HnsAccountRecord>(MAX_MOBILE_WALLET_ACCOUNTS)?;
1299        if accounts.len() != 1 {
1300            store.lock();
1301            return Err(MobileWalletError::InvalidAccountSet);
1302        }
1303        let account_config = accounts
1304            .pop()
1305            .ok_or(MobileWalletError::InvalidAccountSet)?
1306            .value
1307            .config;
1308        store.validate_single_recovery_seed(account_config.wallet_id.as_bytes())?;
1309        let store = SharedWalletStore::new(store);
1310        store.lock()?;
1311        Self::from_locked_store(store, account_config, host, backend, clock)
1312    }
1313
1314    fn from_locked_store(
1315        store: SharedWalletStore,
1316        account_config: HnsRuntimeConfig,
1317        host: MobileHost,
1318        backend: B,
1319        clock: C,
1320    ) -> Result<Self, MobileWalletError> {
1321        let selector = HnsExistingAccountSelector::new(store.clone(), account_config.clone())?;
1322        let runtime = HnsAccountReadRuntime::new(backend, clock, store.clone(), selector)?;
1323        let service = WalletService::new_persistent_hns_reads(
1324            store.clone(),
1325            PersistentHnsReadConfig {
1326                runtime,
1327                account_label: MOBILE_ACCOUNT_LABEL.to_owned(),
1328            },
1329        )?;
1330        let mut controller = Self {
1331            session: MobileControllerSession::new(store, host, service),
1332            account_config,
1333            known_names: Vec::new(),
1334        };
1335        controller.session.negotiate_non_value()?;
1336        Ok(controller)
1337    }
1338
1339    pub const fn account_config(&self) -> &HnsRuntimeConfig {
1340        &self.account_config
1341    }
1342
1343    pub fn status(&mut self) -> Result<WalletRuntimeStatus, MobileWalletError> {
1344        match self.session.wallet_request(WalletRequest::Status)? {
1345            WalletResponse::Status { status } => Ok(status),
1346            _ => Err(MobileWalletError::UnexpectedResponse),
1347        }
1348    }
1349
1350    pub fn unlock(&mut self, database_key: &MobileDatabaseKey) -> Result<(), MobileWalletError> {
1351        self.lock()?;
1352        let mut passphrase = database_key.store_passphrase();
1353        let passphrase = SecretString::new(std::mem::take(&mut *passphrase));
1354        match self
1355            .session
1356            .wallet_request(WalletRequest::Unlock { passphrase })?
1357        {
1358            WalletResponse::Unlocked => Ok(()),
1359            _ => Err(MobileWalletError::UnexpectedResponse),
1360        }
1361    }
1362
1363    pub fn lock(&mut self) -> Result<(), MobileWalletError> {
1364        self.known_names.clear();
1365        match self.session.wallet_request(WalletRequest::Lock)? {
1366            WalletResponse::Locked => Ok(()),
1367            _ => Err(MobileWalletError::UnexpectedResponse),
1368        }
1369    }
1370
1371    pub fn accounts(&mut self) -> Result<Vec<AccountSummary>, MobileWalletError> {
1372        match self.session.wallet_request(WalletRequest::ListAccounts)? {
1373            WalletResponse::Accounts { accounts } => Ok(accounts),
1374            _ => Err(MobileWalletError::UnexpectedResponse),
1375        }
1376    }
1377
1378    /// Perform one fresh bounded reconciliation and return only the minimized
1379    /// native read projection. The chain/mempool binding remains internal.
1380    ///
1381    /// A rejected read does not create a signing artifact, alter wallet value,
1382    /// or expose a partial projection. It therefore leaves the already
1383    /// unlocked session intact so the host can retry a transient direct-peer
1384    /// or snapshot-availability failure.
1385    pub fn synchronize(&mut self) -> Result<MobileHnsReadSnapshot, MobileWalletError> {
1386        self.synchronize_inner()
1387    }
1388
1389    /// Return balance from one new bounded synchronization.
1390    pub fn balance(&mut self) -> Result<Amount, MobileWalletError> {
1391        Ok(self.synchronize()?.balance)
1392    }
1393
1394    /// Return the receive target from one new bounded synchronization.
1395    pub fn receive_target(&mut self) -> Result<ReceiveTarget, MobileWalletError> {
1396        Ok(self.synchronize()?.receive_target)
1397    }
1398
1399    /// Return the ordinary HNS payment receive target deterministically
1400    /// derived from the unlocked local wallet. This deliberately does not
1401    /// synchronize a node or peer and therefore must not be used as balance,
1402    /// history, name, or spend evidence.
1403    pub fn local_receive_target(&mut self) -> Result<ReceiveTarget, MobileWalletError> {
1404        let result = (|| {
1405            if self.session.failed {
1406                return Err(MobileWalletError::ControllerFailed);
1407            }
1408            let target = self
1409                .session
1410                .service
1411                .local_trusted_native_hns_receive_target()
1412                .map_err(mobile_service_failure)?;
1413            validate_mobile_hns_payment_receive_target(self.account_config.account_id, &target)?;
1414            Ok(target)
1415        })();
1416        if result.is_err() {
1417            self.session.lock_after_request_error();
1418        }
1419        result
1420    }
1421
1422    /// Return the name-transfer view of the canonical account-zero external
1423    /// receive target from one new bounded synchronization.
1424    pub fn name_receive_target(&mut self) -> Result<HnsNameReceiveTarget, MobileWalletError> {
1425        Ok(self.synchronize()?.name_receive_target)
1426    }
1427
1428    /// Return transaction history from one new bounded synchronization.
1429    pub fn transaction_history(&mut self) -> Result<Vec<TransactionSummary>, MobileWalletError> {
1430        Ok(self.synchronize()?.transaction_history)
1431    }
1432
1433    /// Return minimized known-name summaries from one new bounded
1434    /// synchronization. No proof, resource, owner, or derivation material is
1435    /// returned.
1436    pub fn known_names(&mut self) -> Result<Vec<MobileHnsNameSummary>, MobileWalletError> {
1437        Ok(self.synchronize()?.known_names)
1438    }
1439
1440    /// Return one page from the last successful authenticated synchronization
1441    /// without performing another node reconciliation.
1442    pub fn known_name_page(
1443        &self,
1444        offset: usize,
1445        limit: usize,
1446    ) -> Result<MobileHnsNamePage, MobileWalletError> {
1447        mobile_hns_name_page(&self.known_names, offset, limit)
1448    }
1449
1450    /// Import one exact canonical Handshake name through the trusted native
1451    /// service boundary. The text is passed through byte-for-byte: this method
1452    /// never trims, lowercases, applies IDNA, normalizes Unicode, or removes a
1453    /// trailing dot. Only the minimized name summary is returned.
1454    pub fn import_name_exact_text(
1455        &mut self,
1456        name: &str,
1457    ) -> Result<MobileHnsNameSummary, MobileWalletError> {
1458        if self.session.failed {
1459            return Err(MobileWalletError::ControllerFailed);
1460        }
1461        match self
1462            .session
1463            .service
1464            .import_trusted_native_hns_name_exact_text(name)
1465        {
1466            Ok(summary) => mobile_native_hns_name_summary(summary),
1467            Err(failure) => {
1468                if failure.code != ServiceErrorCode::InvalidRequest {
1469                    self.session.lock_after_request_error();
1470                }
1471                Err(mobile_service_failure(failure))
1472            }
1473        }
1474    }
1475
1476    /// Atomically import exact names and authenticate every proof before any
1477    /// row is committed. Synchronization is intentionally caller-controlled.
1478    pub fn import_names_exact_text(&mut self, names: &[&str]) -> Result<usize, MobileWalletError> {
1479        if self.session.failed {
1480            return Err(MobileWalletError::ControllerFailed);
1481        }
1482        match self
1483            .session
1484            .service
1485            .import_trusted_native_hns_names_exact_text(names)
1486        {
1487            Ok(imported) => Ok(imported.len()),
1488            Err(failure) => {
1489                if failure.code != ServiceErrorCode::InvalidRequest {
1490                    self.session.lock_after_request_error();
1491                }
1492                Err(mobile_service_failure(failure))
1493            }
1494        }
1495    }
1496
1497    /// Return module status from one new bounded synchronization.
1498    pub fn module_status(&mut self) -> Result<SyncStatus, MobileWalletError> {
1499        Ok(self.synchronize()?.module_status)
1500    }
1501
1502    fn synchronize_inner(&mut self) -> Result<MobileHnsReadSnapshot, MobileWalletError> {
1503        if self.session.failed {
1504            return Err(MobileWalletError::ControllerFailed);
1505        }
1506        let snapshot = self
1507            .session
1508            .service
1509            .synchronize_trusted_native_hns_reads()
1510            .map_err(mobile_service_failure)?;
1511        if snapshot.account_id != self.account_config.account_id
1512            || snapshot.balance.asset != WalletAsset::Hns
1513            || snapshot
1514                .transactions
1515                .iter()
1516                .any(|transaction| transaction.module != ModuleId::Handshake)
1517        {
1518            return Err(MobileWalletError::Hns(HnsWalletError::InvalidEvidence));
1519        }
1520        validate_mobile_hns_receive_targets(
1521            snapshot.account_id,
1522            &snapshot.receive_target,
1523            &snapshot.name_receive_target,
1524        )?;
1525        let mut known_names = snapshot
1526            .known_names
1527            .iter()
1528            .map(mobile_hns_name_summary)
1529            .collect::<Result<Vec<_>, _>>()?;
1530        let mut unique_names = BTreeSet::new();
1531        let mut unique_hashes = BTreeSet::new();
1532        if !known_names.iter().all(|name| {
1533            unique_names.insert(name.name.clone()) && unique_hashes.insert(name.name_hash.clone())
1534        }) {
1535            return Err(MobileWalletError::Hns(HnsWalletError::InvalidEvidence));
1536        }
1537        known_names.sort_by(|left, right| {
1538            left.name
1539                .cmp(&right.name)
1540                .then_with(|| left.name_hash.cmp(&right.name_hash))
1541        });
1542        let known_name_count = u32::try_from(known_names.len())
1543            .map_err(|_| MobileWalletError::Hns(HnsWalletError::HistoryLimit))?;
1544        self.known_names.clone_from(&known_names);
1545        known_names.truncate(MAX_MOBILE_HNS_NAME_PAGE);
1546        let known_names_complete = known_names.len() == self.known_names.len();
1547        let height = snapshot.binding.chain.tip.height;
1548        Ok(MobileHnsReadSnapshot {
1549            balance: snapshot.balance,
1550            receive_target: snapshot.receive_target,
1551            name_receive_target: snapshot.name_receive_target,
1552            transaction_history: snapshot.transactions,
1553            known_names,
1554            known_name_count,
1555            known_names_complete,
1556            finalize_notices: Vec::new(),
1557            module_status: SyncStatus {
1558                phase: SyncPhase::Ready,
1559                validated_height: height,
1560                scanned_height: height,
1561                target_height: Some(height),
1562                last_error: None,
1563            },
1564        })
1565    }
1566}
1567
1568impl<B: HnsBackend> MobileHnsValueController<B, HnsReadSystemClock> {
1569    /// Open one existing installed wallet directly into its full HNS value
1570    /// composition. Startup remains locked and no pending approval survives a
1571    /// process restart.
1572    pub fn open(
1573        path: impl AsRef<Path>,
1574        database_key: &MobileDatabaseKey,
1575        platform: MobilePlatform,
1576        backend: B,
1577        shakedex: Option<PersistentShakedexConfig>,
1578    ) -> Result<Self, MobileWalletError> {
1579        Self::open_with_clock(
1580            path,
1581            database_key,
1582            platform,
1583            backend,
1584            HnsReadSystemClock,
1585            shakedex,
1586        )
1587    }
1588}
1589
1590impl<B: HnsBackend, C: HnsClock> MobileHnsValueController<B, C> {
1591    /// Clock-injectable full-value open path. Exact account discovery first
1592    /// runs through the structural lifecycle controller, which grants no node
1593    /// or signing authority by itself.
1594    pub fn open_with_clock(
1595        path: impl AsRef<Path>,
1596        database_key: &MobileDatabaseKey,
1597        platform: MobilePlatform,
1598        backend: B,
1599        clock: C,
1600        shakedex: Option<PersistentShakedexConfig>,
1601    ) -> Result<Self, MobileWalletError> {
1602        MobileWalletController::open(path, database_key, platform)?.into_hns_value_with_clock(
1603            database_key,
1604            backend,
1605            clock,
1606            shakedex,
1607        )
1608    }
1609
1610    pub const fn account_config(&self) -> &HnsRuntimeConfig {
1611        &self.account_config
1612    }
1613
1614    /// Construct the Bitcoin half of the installed direct wallet. The
1615    /// returned controller uses this exact encrypted store and recovery seed;
1616    /// it does not create a second mnemonic, node credential, or relay path.
1617    /// The caller activates it only after this HNS controller unlocks the
1618    /// shared store.
1619    pub fn direct_bitcoin_value_controller(
1620        &self,
1621        config: MobileBitcoinDirectConfig,
1622    ) -> Result<MobileBitcoinValueController, MobileWalletError> {
1623        MobileBitcoinValueController::new(
1624            self.session.store.clone(),
1625            self.account_config.clone(),
1626            config,
1627        )
1628    }
1629
1630    /// Construct the adjacent direct HNS/BTC Shakescape controller from this
1631    /// exact value runtime's encrypted store and selected HNS network. No
1632    /// peer, relay, indexer, price reporter, or caller-supplied policy enters
1633    /// this construction.
1634    pub fn direct_shakescape_session_controller(
1635        &self,
1636    ) -> Result<MobileShakescapeSessionController, MobileWalletError> {
1637        let hns_network =
1638            hns_wallet_hns::direct_shakescape_network_binding(self.account_config.network)?;
1639        let (counterchain_network, counterchain_genesis) =
1640            MobileBitcoinDirectConfig::direct_shakescape_counterchain(self.account_config.network);
1641        let network = hns_marketplace_protocol::NetworkBinding {
1642            hns_magic: hns_network.magic,
1643            hns_genesis: hns_network.genesis,
1644            counterchain: hns_marketplace_protocol::ChainId::BITCOIN,
1645            counterchain_network,
1646            counterchain_genesis,
1647        };
1648        let board_policy = ShakescapeDirectOfferBoardPolicy::new(network)?;
1649        let swap_policy = ShakescapeDirectSwapPolicy::new(board_policy)?;
1650        Ok(MobileShakescapeSessionController::new(
1651            self.session.store.clone(),
1652            swap_policy,
1653            self.account_config.wallet_id,
1654        )
1655        .with_recovery_account(self.account_config.clone()))
1656    }
1657
1658    pub fn status(&mut self) -> Result<WalletRuntimeStatus, MobileWalletError> {
1659        match self.session.wallet_request(WalletRequest::Status)? {
1660            WalletResponse::Status { status } => Ok(status),
1661            _ => Err(MobileWalletError::UnexpectedResponse),
1662        }
1663    }
1664
1665    pub fn unlock(&mut self, database_key: &MobileDatabaseKey) -> Result<(), MobileWalletError> {
1666        self.lock()?;
1667        let mut passphrase = database_key.store_passphrase();
1668        let passphrase = SecretString::new(std::mem::take(&mut *passphrase));
1669        match self
1670            .session
1671            .wallet_request(WalletRequest::Unlock { passphrase })?
1672        {
1673            WalletResponse::Unlocked => Ok(()),
1674            _ => Err(MobileWalletError::UnexpectedResponse),
1675        }
1676    }
1677
1678    pub fn lock(&mut self) -> Result<(), MobileWalletError> {
1679        self.known_names.clear();
1680        let discard = self.discard_pending_action();
1681        let discard_shakescape = self.discard_pending_shakescape_hns_funding();
1682        let discard_settlement = self.discard_pending_shakescape_hns_settlement();
1683        let lock = match self.session.wallet_request(WalletRequest::Lock) {
1684            Ok(WalletResponse::Locked) => Ok(()),
1685            Ok(_) => Err(MobileWalletError::UnexpectedResponse),
1686            Err(error) => Err(error),
1687        };
1688        discard?;
1689        discard_shakescape?;
1690        discard_settlement?;
1691        lock
1692    }
1693
1694    pub fn accounts(&mut self) -> Result<Vec<AccountSummary>, MobileWalletError> {
1695        match self.session.wallet_request(WalletRequest::ListAccounts)? {
1696            WalletResponse::Accounts { accounts } => Ok(accounts),
1697            _ => Err(MobileWalletError::UnexpectedResponse),
1698        }
1699    }
1700
1701    /// Perform one full reconciliation and return only the same minimized
1702    /// native projection used by the read controller.
1703    ///
1704    /// Reconciliation is a read-only operation. A failed synchronization does
1705    /// not grant a balance or authorization, and must not invalidate an
1706    /// otherwise valid unlocked session that may later prepare an explicit
1707    /// user-approved send.
1708    pub fn synchronize(&mut self) -> Result<MobileHnsReadSnapshot, MobileWalletError> {
1709        if self.pending.is_some() {
1710            return Err(MobileWalletError::ValueActionPending);
1711        }
1712        self.synchronize_inner()
1713    }
1714
1715    /// Re-submit exact, already approved HNS sends that the most recent
1716    /// authenticated snapshot classified as dropped. This never accepts raw
1717    /// transaction bytes or creates a replacement payment.
1718    pub fn rebroadcast_dropped_hns_sends(&mut self) -> Result<usize, MobileWalletError> {
1719        if self.pending.is_some() {
1720            return Err(MobileWalletError::ValueActionPending);
1721        }
1722        if self.session.failed {
1723            return Err(MobileWalletError::ControllerFailed);
1724        }
1725        self.session
1726            .service
1727            .rebroadcast_trusted_native_dropped_hns_sends()
1728            .map_err(mobile_service_failure)
1729    }
1730
1731    /// Recover seller publications only after this controller has completed a
1732    /// verified HNS reconciliation. Embeddings deliberately call this after
1733    /// accepting the wallet snapshot and handle a marketplace-only failure
1734    /// separately, so offer recovery can never suppress valid wallet reads.
1735    pub fn recover_shakedex_after_reconcile(&mut self) -> Result<(), MobileWalletError> {
1736        if self.pending.is_some() {
1737            return Err(MobileWalletError::ValueActionPending);
1738        }
1739        if self.session.failed {
1740            return Err(MobileWalletError::ControllerFailed);
1741        }
1742        self.session
1743            .service
1744            .recover_trusted_native_shakedex_after_reconcile()
1745            .map_err(mobile_service_failure)
1746    }
1747
1748    /// Return the ordinary HNS payment receive target deterministically
1749    /// derived from the unlocked local wallet. No HNS, Bitcoin, Shakescape, or
1750    /// clock operation occurs here; fund state and value operations still
1751    /// require a separately completed reconciliation.
1752    pub fn local_receive_target(&mut self) -> Result<ReceiveTarget, MobileWalletError> {
1753        if self.pending.is_some() {
1754            return Err(MobileWalletError::ValueActionPending);
1755        }
1756        let result = (|| {
1757            if self.session.failed {
1758                return Err(MobileWalletError::ControllerFailed);
1759            }
1760            let target = self
1761                .session
1762                .service
1763                .local_trusted_native_hns_value_receive_target()
1764                .map_err(mobile_service_failure)?;
1765            validate_mobile_hns_payment_receive_target(self.account_config.account_id, &target)?;
1766            Ok(target)
1767        })();
1768        if result.is_err() {
1769            self.session.lock_after_request_error();
1770        }
1771        result
1772    }
1773
1774    fn synchronize_inner(&mut self) -> Result<MobileHnsReadSnapshot, MobileWalletError> {
1775        if self.session.failed {
1776            return Err(MobileWalletError::ControllerFailed);
1777        }
1778        let snapshot = self
1779            .session
1780            .service
1781            .synchronize_trusted_native_hns_value()
1782            .map_err(mobile_service_failure)?;
1783        let (snapshot, known_names) =
1784            mobile_hns_value_snapshot(self.account_config.account_id, snapshot)?;
1785        self.known_names = known_names;
1786        Ok(snapshot)
1787    }
1788
1789    /// Return the exact clock authority used by the native HNS runtime after
1790    /// confirming that the same persisted account remains unlocked. Direct
1791    /// Shakescape handshakes carry a timestamp, but an embedding application must
1792    /// never get to substitute its own clock for the value runtime's clock.
1793    fn trusted_wallet_peer_now_unix(&mut self) -> Result<u64, MobileWalletError> {
1794        if self.session.failed {
1795            return Err(MobileWalletError::ControllerFailed);
1796        }
1797        let result = (|| {
1798            if self.session.store.is_locked()? {
1799                return Err(MobileWalletError::Store(StoreError::Locked));
1800            }
1801            // This exact-account lookup also detects a separately changed
1802            // persisted account configuration before a peer sees a direct
1803            // Shakescape handshake for the value controller.
1804            self.session
1805                .service
1806                .local_trusted_native_hns_value_receive_target()
1807                .map_err(mobile_service_failure)?;
1808            self.session
1809                .service
1810                .trusted_native_hns_value_now_unix()
1811                .map_err(mobile_service_failure)
1812        })();
1813        if result.is_err() {
1814            self.session.lock_after_request_error();
1815        }
1816        result
1817    }
1818
1819    /// Query the synchronized Shakescape/Shakedex board or one local trade session
1820    /// without exposing generic provider JSON as an input surface.
1821    pub fn query_shakedex(
1822        &mut self,
1823        query: MobileShakedexQuery,
1824    ) -> Result<Value, MobileWalletError> {
1825        if self.session.failed {
1826            return Err(MobileWalletError::ControllerFailed);
1827        }
1828        if self.pending.is_some() {
1829            return Err(MobileWalletError::ValueActionPending);
1830        }
1831        let request_nonce = random_nonzero_request_nonce()?;
1832        let origin = Origin::parse(TRUSTED_NATIVE_HNS_VALUE_ORIGIN)
1833            .map_err(|_| MobileWalletError::InvalidValueAction)?;
1834        let (method, params) = query.into_provider_parts(self.account_config.account_id);
1835        let result = self
1836            .session
1837            .service
1838            .query_trusted_native_shakedex(ApprovedCall {
1839                origin,
1840                namespace: SelectedNamespace::Hns,
1841                method,
1842                params,
1843                request_nonce,
1844            })
1845            .map_err(mobile_service_failure);
1846        if result.is_err() {
1847            self.session.lock_after_request_error();
1848        }
1849        result
1850    }
1851
1852    /// Start one explicit wallet-owned direct board exchange. No hidden
1853    /// relay/network request occurs: the caller supplies the already
1854    /// negotiated direct peer and controls the socket lifetime.
1855    pub fn begin_wallet_owned_direct_shakedex(
1856        &mut self,
1857        peer: &mut HnsDirectShakescapePeer,
1858    ) -> Result<DirectShakescapeBoardSyncReport, MobileWalletError> {
1859        // A direct peer is untrusted transport. A malformed packet, a closed
1860        // socket, or a timeout must discard that peer at the caller boundary,
1861        // never lock the wallet that independently owns chain and board state.
1862        self.session
1863            .service
1864            .begin_wallet_owned_direct_shakedex(peer)
1865            .map_err(mobile_service_failure)
1866    }
1867
1868    /// Process an explicitly bounded number of messages from a wallet-owned
1869    /// direct board peer. The caller must schedule subsequent calls itself.
1870    pub fn synchronize_wallet_owned_direct_shakedex(
1871        &mut self,
1872        peer: &mut HnsDirectShakescapePeer,
1873        message_limit: usize,
1874    ) -> Result<DirectShakescapeBoardSyncReport, MobileWalletError> {
1875        self.session
1876            .service
1877            .synchronize_wallet_owned_direct_shakedex(peer, message_limit)
1878            .map_err(mobile_service_failure)
1879    }
1880
1881    /// Service one name-market message classified by the direct peer
1882    /// multiplexer. This leaves cross-chain HNS/BTC envelopes for the separate
1883    /// durable direct-session controller.
1884    pub fn service_wallet_owned_direct_shakedex_message(
1885        &mut self,
1886        peer: &mut HnsDirectShakescapePeer,
1887        request_id: u64,
1888        message: hns_marketplace_protocol::NameMarketMessage,
1889    ) -> Result<DirectShakescapeBoardSyncReport, MobileWalletError> {
1890        self.session
1891            .service
1892            .service_wallet_owned_direct_shakedex_message(peer, request_id, message)
1893            .map_err(mobile_service_failure)
1894    }
1895
1896    /// Write one due local board publication to a negotiated wallet peer and
1897    /// record the resulting local transport observation.
1898    pub fn announce_wallet_owned_direct_shakedex(
1899        &mut self,
1900        peer: &mut HnsDirectShakescapePeer,
1901    ) -> Result<Option<ObjectHash>, MobileWalletError> {
1902        self.session
1903            .service
1904            .announce_wallet_owned_direct_shakedex(peer)
1905            .map_err(mobile_service_failure)
1906    }
1907
1908    /// Import one exact canonical Handshake name while retaining the full
1909    /// value composition. The input is never normalized or rewritten.
1910    pub fn import_name_exact_text(
1911        &mut self,
1912        name: &str,
1913    ) -> Result<MobileHnsNameSummary, MobileWalletError> {
1914        if self.session.failed {
1915            return Err(MobileWalletError::ControllerFailed);
1916        }
1917        if self.pending.is_some() {
1918            return Err(MobileWalletError::ValueActionPending);
1919        }
1920        match self
1921            .session
1922            .service
1923            .import_trusted_native_hns_value_name_exact_text(name)
1924        {
1925            Ok(summary) => mobile_native_hns_name_summary(summary),
1926            Err(failure) => {
1927                if failure.code != ServiceErrorCode::InvalidRequest {
1928                    self.session.lock_after_request_error();
1929                }
1930                Err(mobile_service_failure(failure))
1931            }
1932        }
1933    }
1934
1935    /// Atomically import exact names against the last synchronized value
1936    /// snapshot and defer the caller's one desired post-import refresh.
1937    pub fn import_names_exact_text(&mut self, names: &[&str]) -> Result<usize, MobileWalletError> {
1938        if self.session.failed {
1939            return Err(MobileWalletError::ControllerFailed);
1940        }
1941        if self.pending.is_some() {
1942            return Err(MobileWalletError::ValueActionPending);
1943        }
1944        match self
1945            .session
1946            .service
1947            .import_trusted_native_hns_value_names_exact_text(names)
1948        {
1949            Ok(imported) => Ok(imported.len()),
1950            Err(failure) => {
1951                if failure.code != ServiceErrorCode::InvalidRequest {
1952                    self.session.lock_after_request_error();
1953                }
1954                Err(mobile_service_failure(failure))
1955            }
1956        }
1957    }
1958
1959    /// Return one page from the last successful authenticated synchronization
1960    /// without reconciling or loading the full name set into the host UI.
1961    pub fn known_name_page(
1962        &self,
1963        offset: usize,
1964        limit: usize,
1965    ) -> Result<MobileHnsNamePage, MobileWalletError> {
1966        mobile_hns_name_page(&self.known_names, offset, limit)
1967    }
1968
1969    /// Prepare one exact value action and return the only summary the installed
1970    /// UI may approve. A second action is rejected until the first is approved,
1971    /// rejected, expired, or the controller is locked.
1972    pub fn prepare_value_action(
1973        &mut self,
1974        intent: MobileHnsValueIntent,
1975    ) -> Result<MobileHnsValueApproval, MobileWalletError> {
1976        if self.session.failed {
1977            return Err(MobileWalletError::ControllerFailed);
1978        }
1979        if self.pending.is_some() {
1980            return Err(MobileWalletError::ValueActionPending);
1981        }
1982        let now_unix = self
1983            .session
1984            .service
1985            .trusted_native_hns_value_now_unix()
1986            .map_err(mobile_service_failure)?;
1987        let expires_at_unix = now_unix
1988            .checked_add(APPROVAL_LIFETIME_SECONDS)
1989            .ok_or(MobileWalletError::InvalidValueAction)?;
1990        let action_token = random_nonzero_bytes()?;
1991        let approval_id = ApprovalId::new(random_nonzero_bytes()?);
1992        let request_nonce = random_nonzero_request_nonce()?;
1993        let origin = Origin::parse(TRUSTED_NATIVE_HNS_VALUE_ORIGIN)
1994            .map_err(|_| MobileWalletError::InvalidValueAction)?;
1995        let (kind, method, params) = intent.into_provider_parts(self.account_config.account_id)?;
1996        let call = ApprovedCall {
1997            origin,
1998            namespace: SelectedNamespace::Hns,
1999            method,
2000            params,
2001            request_nonce,
2002        };
2003        let action = self
2004            .session
2005            .service
2006            .prepare_trusted_native_hns_value_action(approval_id, kind, call, expires_at_unix)
2007            .map_err(mobile_service_failure)?;
2008        let summary = action.summary().clone();
2009        let expires_at_unix = action.expires_at_unix();
2010        self.pending = Some(PendingMobileHnsValueAction {
2011            action_token,
2012            action,
2013        });
2014        Ok(MobileHnsValueApproval {
2015            action_token: lowercase_hex(&action_token),
2016            expires_at_unix,
2017            summary,
2018        })
2019    }
2020
2021    /// Prepare the next mature pre-upgrade Shakedex purchase without taking a
2022    /// host-supplied session identifier. New purchases carrying an explicit
2023    /// automatic-finalize grant never reach this path.
2024    pub fn prepare_next_shakedex_finalize(
2025        &mut self,
2026    ) -> Result<Option<MobileHnsValueApproval>, MobileWalletError> {
2027        if self.session.failed {
2028            return Err(MobileWalletError::ControllerFailed);
2029        }
2030        if self.pending.is_some() {
2031            return Err(MobileWalletError::ValueActionPending);
2032        }
2033        let Some((session_id, maximum_fee)) = self
2034            .session
2035            .service
2036            .next_trusted_native_shakedex_finalize()
2037            .map_err(mobile_service_failure)?
2038        else {
2039            return Ok(None);
2040        };
2041        self.prepare_value_action(MobileHnsValueIntent::FinalizePurchase {
2042            session_id: lowercase_hex(session_id.as_bytes()),
2043            maximum_fee,
2044        })
2045        .map(Some)
2046    }
2047
2048    /// Consume the process-local token exactly once, then re-prepare and
2049    /// execute the approval-bound action through the HNS runtime.
2050    pub fn approve_value_action(&mut self, action_token: &str) -> Result<Value, MobileWalletError> {
2051        self.require_pending_token(action_token)?;
2052        let pending = self
2053            .pending
2054            .take()
2055            .ok_or(MobileWalletError::NoPendingValueAction)?;
2056        let result = self
2057            .session
2058            .service
2059            .execute_trusted_native_hns_value_action(pending.action)
2060            .map_err(mobile_service_failure);
2061        if result
2062            .as_ref()
2063            .err()
2064            .is_some_and(|error| !hns_send_pre_broadcast_retry_required(error))
2065        {
2066            self.session.lock_after_request_error();
2067        }
2068        result
2069    }
2070
2071    /// Reject one pending action and remove its encrypted runtime approval.
2072    pub fn reject_value_action(&mut self, action_token: &str) -> Result<(), MobileWalletError> {
2073        self.require_pending_token(action_token)?;
2074        let result = self.discard_pending_action();
2075        if result.is_err() {
2076            self.session.lock_after_request_error();
2077        }
2078        result
2079    }
2080
2081    pub fn prepare_shakescape_hns_funding(
2082        &mut self,
2083        permit: MobileShakescapeHnsFundingPermit,
2084        maximum_fee_dollarydoos: u64,
2085    ) -> Result<MobileShakescapeHnsFundingApproval, MobileWalletError> {
2086        if self.pending.is_some()
2087            || self.pending_shakescape_hns_funding.is_some()
2088            || self.pending_shakescape_hns_settlement.is_some()
2089        {
2090            return Err(MobileWalletError::ValueActionPending);
2091        }
2092        if maximum_fee_dollarydoos == 0
2093            || maximum_fee_dollarydoos > permit.hns_fee_reserve_dollarydoos()
2094        {
2095            return Err(MobileWalletError::InvalidValueAction);
2096        }
2097        let now_unix = self
2098            .session
2099            .service
2100            .trusted_native_hns_value_now_unix()
2101            .map_err(mobile_service_failure)?;
2102        let hello = permit.hello();
2103        let side = permit.side();
2104        let session_id = hns_wallet_types::SessionId::new(hello.swap_session_id);
2105        if !permit.authorizes_pending_funding(
2106            session_id,
2107            side,
2108            u128::from(maximum_fee_dollarydoos),
2109            now_unix,
2110        ) {
2111            return Err(MobileWalletError::InvalidValueAction);
2112        }
2113        let binding = hello
2114            .build_hns_htlc(
2115                side,
2116                match side {
2117                    hns_marketplace_protocol::SwapAssetSide::Offered => {
2118                        hello.taker_settlement_public_key
2119                    }
2120                    hns_marketplace_protocol::SwapAssetSide::Received => {
2121                        hello.maker_settlement_public_key
2122                    }
2123                },
2124                match side {
2125                    hns_marketplace_protocol::SwapAssetSide::Offered => {
2126                        hello.maker_settlement_public_key
2127                    }
2128                    hns_marketplace_protocol::SwapAssetSide::Received => {
2129                        hello.taker_settlement_public_key
2130                    }
2131                },
2132            )
2133            .map_err(|_| MobileWalletError::InvalidValueAction)?;
2134        let (amount, refund_at, commitment) = match side {
2135            hns_marketplace_protocol::SwapAssetSide::Offered => (
2136                hello.offered_amount,
2137                hello.offered_refund_deadline.value,
2138                hello.offered_lock_commitment,
2139            ),
2140            hns_marketplace_protocol::SwapAssetSide::Received => (
2141                hello.received_amount,
2142                hello.received_refund_deadline.value,
2143                hello.received_lock_commitment,
2144            ),
2145        };
2146        if binding.descriptor_hash != commitment
2147            || binding.descriptor.refund_public_key != permit.settlement_key().public_key()
2148        {
2149            return Err(MobileWalletError::InvalidValueAction);
2150        }
2151        let publication =
2152            hns_wallet_chain_api::SwapRecoveryPublication::new(hello, side, hello.header.network)
2153                .map_err(|_| MobileWalletError::InvalidValueAction)?;
2154        let second_funding_guard = permit.into_second_funding_broadcast_guard(now_unix)?;
2155        let maximum_fee = BaseUnits::new(u128::from(maximum_fee_dollarydoos));
2156        let mut prepared = self
2157            .session
2158            .service
2159            .prepare_trusted_native_hns_recoverable_htlc_lock(
2160                session_id,
2161                binding.descriptor,
2162                maximum_fee,
2163                publication,
2164            )
2165            .map_err(mobile_service_failure)?;
2166        if let Some(guard) = second_funding_guard {
2167            prepared = self
2168                .session
2169                .service
2170                .bind_trusted_native_hns_htlc_lock_broadcast_guard(
2171                    &prepared,
2172                    hns_second_funding_broadcast_guard(guard)?,
2173                )
2174                .map_err(mobile_service_failure)?;
2175        }
2176        let transaction_id = self
2177            .session
2178            .service
2179            .trusted_native_hns_settlement_transaction_id(&prepared.0)
2180            .map_err(mobile_service_failure)?;
2181        let amount_dollarydoos =
2182            u64::try_from(amount.get()).map_err(|_| MobileWalletError::InvalidValueAction)?;
2183        let fee_dollarydoos = u64::try_from(prepared.0.fee.get())
2184            .map_err(|_| MobileWalletError::InvalidValueAction)?;
2185        let action_token = random_nonzero_bytes()?;
2186        let approval = MobileShakescapeHnsFundingApproval {
2187            action_token: lowercase_hex(&action_token),
2188            session_id: lowercase_hex(session_id.as_bytes()),
2189            transaction_id: lowercase_hex(transaction_id.as_bytes()),
2190            amount_dollarydoos,
2191            fee_dollarydoos,
2192            maximum_fee_dollarydoos,
2193            refund_at_unix: refund_at,
2194            expires_at_unix: prepared.0.expires_at_unix,
2195        };
2196        self.pending_shakescape_hns_funding = Some(PendingMobileShakescapeHnsFunding {
2197            action_token,
2198            session_id,
2199            side,
2200            prepared,
2201            maximum_fee,
2202        });
2203        Ok(approval)
2204    }
2205
2206    /// Consume one prepared HNS lock only with a freshly minted Rust-only
2207    /// funding capability for the same session, side, and fee authorization.
2208    /// This prevents a displayed approval from surviving first-chain evidence
2209    /// revocation between preparation and broadcast.
2210    pub fn approve_shakescape_hns_funding(
2211        &mut self,
2212        action_token: &str,
2213        reauthorization: MobileShakescapeHnsFundingPermit,
2214    ) -> Result<MobileShakescapeHnsFundingReceipt, MobileWalletError> {
2215        let now_unix = self
2216            .session
2217            .service
2218            .trusted_native_hns_value_now_unix()
2219            .map_err(mobile_service_failure)?;
2220        let pending = self
2221            .pending_shakescape_hns_funding
2222            .as_ref()
2223            .ok_or(MobileWalletError::NoPendingValueAction)?;
2224        if !reauthorization.authorizes_pending_funding(
2225            pending.session_id,
2226            pending.side,
2227            pending.maximum_fee.get(),
2228            now_unix,
2229        ) {
2230            return Err(MobileWalletError::InvalidValueAction);
2231        }
2232        let mut pending = self
2233            .pending_shakescape_hns_funding
2234            .take()
2235            .ok_or(MobileWalletError::NoPendingValueAction)?;
2236        if !mobile_action_token_matches(&pending.action_token, action_token) {
2237            self.pending_shakescape_hns_funding = Some(pending);
2238            return Err(MobileWalletError::InvalidActionToken);
2239        }
2240        if pending.prepared.0.fee > pending.maximum_fee {
2241            return Err(MobileWalletError::InvalidValueAction);
2242        }
2243        let funding_authorization_expires_at_unix = reauthorization.authorization_expires_at_unix();
2244        if let Some(guard) = reauthorization.into_second_funding_broadcast_guard(now_unix)? {
2245            pending.prepared = self
2246                .session
2247                .service
2248                .bind_trusted_native_hns_htlc_lock_broadcast_guard(
2249                    &pending.prepared,
2250                    hns_second_funding_broadcast_guard(guard)?,
2251                )
2252                .map_err(mobile_service_failure)?;
2253        }
2254        let receipt = self
2255            .session
2256            .service
2257            .broadcast_trusted_native_hns_settlement_before(
2258                &pending.prepared.0,
2259                funding_authorization_expires_at_unix,
2260            )
2261            .map_err(mobile_service_failure)?;
2262        Ok(MobileShakescapeHnsFundingReceipt {
2263            session_id: lowercase_hex(pending.session_id.as_bytes()),
2264            transaction_id: lowercase_hex(receipt.txid.as_bytes()),
2265            // Native HNS payment construction always places the requested
2266            // destination before an optional change output.
2267            output_index: 0,
2268            accepted_at_unix: receipt.accepted_at_unix,
2269        })
2270    }
2271
2272    pub fn pending_shakescape_hns_funding_session_id(&self) -> Option<hns_wallet_types::SessionId> {
2273        self.pending_shakescape_hns_funding
2274            .as_ref()
2275            .map(|pending| pending.session_id)
2276    }
2277
2278    pub fn reject_shakescape_hns_funding(
2279        &mut self,
2280        action_token: &str,
2281    ) -> Result<(), MobileWalletError> {
2282        let pending = self
2283            .pending_shakescape_hns_funding
2284            .take()
2285            .ok_or(MobileWalletError::NoPendingValueAction)?;
2286        if !mobile_action_token_matches(&pending.action_token, action_token) {
2287            self.pending_shakescape_hns_funding = Some(pending);
2288            return Err(MobileWalletError::InvalidActionToken);
2289        }
2290        self.session
2291            .service
2292            .cancel_trusted_native_hns_settlement(&pending.prepared.0)
2293            .map_err(mobile_service_failure)
2294    }
2295
2296    pub fn prepare_shakescape_hns_settlement(
2297        &mut self,
2298        mut permit: MobileShakescapeHnsSettlementPermit,
2299        maximum_fee_dollarydoos: u64,
2300    ) -> Result<MobileShakescapeHnsSettlementApproval, MobileWalletError> {
2301        if self.pending.is_some()
2302            || self.pending_shakescape_hns_funding.is_some()
2303            || self.pending_shakescape_hns_settlement.is_some()
2304        {
2305            return Err(MobileWalletError::ValueActionPending);
2306        }
2307        if maximum_fee_dollarydoos == 0 || maximum_fee_dollarydoos > permit.fee_reserve() {
2308            return Err(MobileWalletError::InvalidValueAction);
2309        }
2310        let terms = permit.terms().clone();
2311        let side = permit.side();
2312        let hns_broadcast_guard = permit.take_hns_broadcast_guard();
2313        let descriptor = hns_wallet_hns::build_recovered_hns_htlc(&terms, side)?;
2314        let parameters = terms.htlc(side);
2315        let amount = hns_marketplace_protocol::AssetAmount::new(u128::from(parameters.amount));
2316        let confirmations = parameters.minimum_confirmations;
2317        let expected_key = match permit.action() {
2318            MobileShakescapeSettlementAction::Redeem => descriptor.receiver_public_key,
2319            MobileShakescapeSettlementAction::Refund => descriptor.refund_public_key,
2320        };
2321        if expected_key != permit.settlement_key().public_key() {
2322            return Err(MobileWalletError::InvalidValueAction);
2323        }
2324        let session_id = hns_wallet_types::SessionId::new(terms.session_id);
2325        let lock = match permit.funding_transaction() {
2326            Some(transaction) => self.session.service.verify_trusted_native_hns_htlc_lock(
2327                session_id,
2328                descriptor,
2329                transaction,
2330                confirmations,
2331            ),
2332            None => self
2333                .session
2334                .service
2335                .verify_trusted_native_persisted_hns_htlc_lock(
2336                    session_id,
2337                    descriptor,
2338                    confirmations,
2339                ),
2340        }
2341        .map_err(mobile_service_failure)?
2342        .ok_or(MobileWalletError::InvalidValueAction)?;
2343        let maximum_fee = BaseUnits::new(u128::from(maximum_fee_dollarydoos));
2344        let action = permit.action();
2345        let prepared = match (action, hns_broadcast_guard) {
2346            (MobileShakescapeSettlementAction::Redeem, Some(guard)) => self
2347                .session
2348                .service
2349                .prepare_trusted_native_hns_htlc_redeem_with_broadcast_guard(
2350                    session_id,
2351                    descriptor,
2352                    lock,
2353                    permit
2354                        .take_preimage()
2355                        .ok_or(MobileWalletError::InvalidValueAction)?,
2356                    maximum_fee,
2357                    permit.settlement_key(),
2358                    guard,
2359                )
2360                .map(|prepared| prepared.0),
2361            (MobileShakescapeSettlementAction::Redeem, None) => self
2362                .session
2363                .service
2364                .prepare_trusted_native_hns_htlc_redeem(
2365                    session_id,
2366                    descriptor,
2367                    lock,
2368                    permit
2369                        .take_preimage()
2370                        .ok_or(MobileWalletError::InvalidValueAction)?,
2371                    maximum_fee,
2372                    permit.settlement_key(),
2373                )
2374                .map(|prepared| prepared.0),
2375            (MobileShakescapeSettlementAction::Refund, None) => self
2376                .session
2377                .service
2378                .prepare_trusted_native_hns_htlc_refund(
2379                    session_id,
2380                    descriptor,
2381                    lock,
2382                    maximum_fee,
2383                    permit.settlement_key(),
2384                )
2385                .map(|prepared| prepared.0),
2386            (MobileShakescapeSettlementAction::Refund, Some(_)) => {
2387                return Err(MobileWalletError::InvalidValueAction);
2388            }
2389        }
2390        .map_err(mobile_service_failure)?;
2391        let transaction_id = self
2392            .session
2393            .service
2394            .trusted_native_hns_settlement_transaction_id(&prepared)
2395            .map_err(mobile_service_failure)?;
2396        let value_summary = self
2397            .session
2398            .service
2399            .trusted_native_hns_settlement_value_summary(&prepared)
2400            .map_err(mobile_service_failure)?;
2401        if value_summary.settlement_input != BaseUnits::new(amount.get())
2402            || value_summary
2403                .settlement_input
2404                .checked_add(value_summary.wallet_sponsor_input)
2405                .map_err(|_| MobileWalletError::InvalidValueAction)?
2406                != value_summary.total_input
2407        {
2408            return Err(MobileWalletError::InvalidValueAction);
2409        }
2410        let input_amount_dollarydoos = u64::try_from(value_summary.total_input.get())
2411            .map_err(|_| MobileWalletError::InvalidValueAction)?;
2412        let fee_dollarydoos =
2413            u64::try_from(prepared.fee.get()).map_err(|_| MobileWalletError::InvalidValueAction)?;
2414        let output_amount_dollarydoos = u64::try_from(value_summary.total_output.get())
2415            .map_err(|_| MobileWalletError::InvalidValueAction)?;
2416        if input_amount_dollarydoos
2417            .checked_sub(fee_dollarydoos)
2418            .ok_or(MobileWalletError::InvalidValueAction)?
2419            != output_amount_dollarydoos
2420        {
2421            return Err(MobileWalletError::InvalidValueAction);
2422        }
2423        let action_token = random_nonzero_bytes()?;
2424        let approval = MobileShakescapeHnsSettlementApproval {
2425            action_token: lowercase_hex(&action_token),
2426            session_id: lowercase_hex(session_id.as_bytes()),
2427            action,
2428            transaction_id: lowercase_hex(transaction_id.as_bytes()),
2429            input_amount_dollarydoos,
2430            output_amount_dollarydoos,
2431            fee_dollarydoos,
2432            maximum_fee_dollarydoos,
2433            expires_at_unix: prepared.expires_at_unix,
2434        };
2435        self.pending_shakescape_hns_settlement = Some(PendingMobileShakescapeHnsSettlement {
2436            action_token,
2437            session_id,
2438            action,
2439            prepared,
2440            maximum_fee,
2441        });
2442        Ok(approval)
2443    }
2444
2445    pub fn approve_shakescape_hns_settlement(
2446        &mut self,
2447        action_token: &str,
2448    ) -> Result<MobileShakescapeHnsSettlementReceipt, MobileWalletError> {
2449        let pending = self
2450            .pending_shakescape_hns_settlement
2451            .take()
2452            .ok_or(MobileWalletError::NoPendingValueAction)?;
2453        if !mobile_action_token_matches(&pending.action_token, action_token) {
2454            self.pending_shakescape_hns_settlement = Some(pending);
2455            return Err(MobileWalletError::InvalidActionToken);
2456        }
2457        if pending.prepared.fee > pending.maximum_fee {
2458            return Err(MobileWalletError::InvalidValueAction);
2459        }
2460        let receipt = self
2461            .session
2462            .service
2463            .broadcast_trusted_native_hns_settlement(&pending.prepared)
2464            .map_err(mobile_service_failure);
2465        let receipt = match receipt {
2466            Ok(receipt) => receipt,
2467            Err(error) => {
2468                self.pending_shakescape_hns_settlement = Some(pending);
2469                return Err(error);
2470            }
2471        };
2472        Ok(MobileShakescapeHnsSettlementReceipt {
2473            session_id: lowercase_hex(pending.session_id.as_bytes()),
2474            action: pending.action,
2475            transaction_id: lowercase_hex(receipt.txid.as_bytes()),
2476            accepted_at_unix: receipt.accepted_at_unix,
2477        })
2478    }
2479
2480    pub fn reject_shakescape_hns_settlement(
2481        &mut self,
2482        action_token: &str,
2483    ) -> Result<(), MobileWalletError> {
2484        let pending = self
2485            .pending_shakescape_hns_settlement
2486            .take()
2487            .ok_or(MobileWalletError::NoPendingValueAction)?;
2488        if !mobile_action_token_matches(&pending.action_token, action_token) {
2489            self.pending_shakescape_hns_settlement = Some(pending);
2490            return Err(MobileWalletError::InvalidActionToken);
2491        }
2492        self.session
2493            .service
2494            .cancel_trusted_native_hns_settlement(&pending.prepared)
2495            .map_err(mobile_service_failure)
2496    }
2497
2498    pub fn resume_approved_shakescape_hns_settlements(&self) -> Result<usize, MobileWalletError> {
2499        self.session
2500            .service
2501            .rebroadcast_trusted_native_hns_settlements()
2502            .map_err(mobile_service_failure)
2503    }
2504
2505    /// Prove that this wallet never crossed the irreversible HNS lock
2506    /// broadcast gate for the exact signed swap descriptor. A prepared action
2507    /// without that durable gate remains safe to abandon after its deadline.
2508    pub fn prove_shakescape_hns_htlc_unfunded(
2509        &self,
2510        permit: &MobileShakescapeHnsVerificationPermit,
2511    ) -> Result<Option<MobileShakescapeUnfundedHnsProof>, MobileWalletError> {
2512        let session_id = permit.session_id();
2513        if permit.funding_transaction().is_some()
2514            || self.pending_shakescape_hns_funding_session_id() == Some(session_id)
2515        {
2516            return Ok(None);
2517        }
2518        let descriptor = hns_wallet_hns::build_recovered_hns_htlc(permit.terms(), permit.side())?;
2519        let submitted = self
2520            .session
2521            .service
2522            .submitted_trusted_native_hns_htlc_lock_transaction_id(session_id, descriptor)
2523            .map_err(mobile_service_failure)?;
2524        Ok(submitted
2525            .is_none()
2526            .then_some(MobileShakescapeUnfundedHnsProof { session_id }))
2527    }
2528
2529    pub fn verified_shakescape_hns_funding(
2530        &self,
2531        permit: MobileShakescapeHnsVerificationPermit,
2532    ) -> Result<Option<hns_wallet_chain_api::VerifiedLock>, MobileWalletError> {
2533        let terms = permit.terms();
2534        let side = permit.side();
2535        let descriptor = hns_wallet_hns::build_recovered_hns_htlc(terms, side)?;
2536        let confirmations = terms.htlc(side).minimum_confirmations;
2537        let session_id = hns_wallet_types::SessionId::new(terms.session_id);
2538        match permit.funding_transaction() {
2539            Some(transaction) => self.session.service.verify_trusted_native_hns_htlc_lock(
2540                session_id,
2541                descriptor,
2542                transaction,
2543                confirmations,
2544            ),
2545            None => self
2546                .session
2547                .service
2548                .verify_trusted_native_persisted_hns_htlc_lock(
2549                    session_id,
2550                    descriptor,
2551                    confirmations,
2552                ),
2553        }
2554        .map_err(mobile_service_failure)
2555    }
2556
2557    pub fn verified_shakescape_hns_spend(
2558        &self,
2559        permit: MobileShakescapeHnsVerificationPermit,
2560    ) -> Result<Option<hns_wallet_hns::VerifiedNativeHtlcSpend>, MobileWalletError> {
2561        let terms = permit.terms();
2562        let side = permit.side();
2563        let descriptor = hns_wallet_hns::build_recovered_hns_htlc(terms, side)?;
2564        let confirmations = terms.htlc(side).minimum_confirmations;
2565        let session_id = hns_wallet_types::SessionId::new(terms.session_id);
2566        let verified = match permit.funding_transaction() {
2567            Some(transaction) => self.session.service.verify_trusted_native_hns_htlc_lock(
2568                session_id,
2569                descriptor,
2570                transaction,
2571                confirmations,
2572            ),
2573            None => self
2574                .session
2575                .service
2576                .verify_trusted_native_persisted_hns_htlc_lock(
2577                    session_id,
2578                    descriptor,
2579                    confirmations,
2580                ),
2581        };
2582        let Some(lock) = verified.map_err(mobile_service_failure)? else {
2583            return Ok(None);
2584        };
2585        self.session
2586            .service
2587            .verify_trusted_native_hns_htlc_spend(session_id, descriptor, lock)
2588            .map_err(mobile_service_failure)
2589    }
2590
2591    fn require_pending_token(&self, action_token: &str) -> Result<(), MobileWalletError> {
2592        let pending = self
2593            .pending
2594            .as_ref()
2595            .ok_or(MobileWalletError::NoPendingValueAction)?;
2596        if !mobile_action_token_matches(&pending.action_token, action_token) {
2597            return Err(MobileWalletError::InvalidActionToken);
2598        }
2599        Ok(())
2600    }
2601
2602    fn discard_pending_action(&mut self) -> Result<(), MobileWalletError> {
2603        let Some(pending) = self.pending.take() else {
2604            return Ok(());
2605        };
2606        self.session
2607            .service
2608            .discard_trusted_native_hns_value_action(pending.action)
2609            .map_err(mobile_service_failure)
2610    }
2611
2612    fn discard_pending_shakescape_hns_funding(&mut self) -> Result<(), MobileWalletError> {
2613        let Some(pending) = self.pending_shakescape_hns_funding.take() else {
2614            return Ok(());
2615        };
2616        self.session
2617            .service
2618            .cancel_trusted_native_hns_settlement(&pending.prepared.0)
2619            .map_err(mobile_service_failure)
2620    }
2621
2622    fn discard_pending_shakescape_hns_settlement(&mut self) -> Result<(), MobileWalletError> {
2623        let Some(pending) = self.pending_shakescape_hns_settlement.take() else {
2624            return Ok(());
2625        };
2626        self.session
2627            .service
2628            .cancel_trusted_native_hns_settlement(&pending.prepared)
2629            .map_err(mobile_service_failure)
2630    }
2631}
2632
2633impl<C: HnsClock> MobileDirectHnsValueController<C> {
2634    /// The retained direct-peer coordinator. Callers schedule its bounded
2635    /// connection, header, filtered-block, proof, and mempool operations only
2636    /// while the adjacent value controller is unlocked.
2637    #[must_use]
2638    pub const fn coordinator(&self) -> &HnsDirectPeerCoordinator {
2639        &self.coordinator
2640    }
2641
2642    /// Resolve configured peers and establish as many bounded direct HNS
2643    /// connections as are presently available. The peer handshakes use the
2644    /// value runtime's trusted clock; caller code retains control over when to
2645    /// retry after a temporary network failure.
2646    pub fn connect_wallet_owned_direct_hns_peers(
2647        &mut self,
2648    ) -> Result<Vec<ConnectedHnsPeer>, MobileWalletError> {
2649        let now_unix = self.value.trusted_wallet_peer_now_unix()?;
2650        self.coordinator
2651            .connect_available(now_unix)
2652            .map_err(Into::into)
2653    }
2654
2655    /// Run one bounded, multi-peer direct HNS header round with the exact
2656    /// runtime clock. A pending/underfilled result is retained by the
2657    /// coordinator for the caller's next scheduled tick; it never becomes a
2658    /// wallet value authorization.
2659    pub fn synchronize_wallet_owned_direct_hns_headers(
2660        &mut self,
2661    ) -> Result<HnsHeaderRoundProgress, MobileWalletError> {
2662        let now_unix = self.value.trusted_wallet_peer_now_unix()?;
2663        self.coordinator
2664            .synchronize_headers_once(now_unix)
2665            .map_err(Into::into)
2666    }
2667
2668    /// Scan at most `max_blocks` authenticated direct-peer block heights with
2669    /// the wallet's current encrypted watch set. The host cannot substitute a
2670    /// timestamp, script set, or block evidence through this façade.
2671    pub fn scan_wallet_owned_direct_hns_blocks(
2672        &mut self,
2673        max_blocks: u32,
2674    ) -> Result<HnsBlockScanProgress, MobileWalletError> {
2675        let now_unix = self.value.trusted_wallet_peer_now_unix()?;
2676        self.coordinator
2677            .scan_wallet_blocks(max_blocks, now_unix)
2678            .map_err(Into::into)
2679    }
2680
2681    /// Refresh the bounded relevant-mempool view from the direct-peer quorum
2682    /// using the value runtime's clock. The return value counts only locally
2683    /// admitted transactions; it is not a confirmation or broadcast receipt.
2684    pub fn refresh_wallet_owned_direct_hns_mempool(&mut self) -> Result<usize, MobileWalletError> {
2685        let now_unix = self.value.trusted_wallet_peer_now_unix()?;
2686        self.coordinator
2687            .refresh_mempool(now_unix)
2688            .map_err(Into::into)
2689    }
2690
2691    /// Extend the authenticated direct restore watch set by one bounded
2692    /// frontier. The active account configuration and time are both obtained
2693    /// from the exact unlocked value runtime rather than caller input.
2694    pub fn extend_wallet_owned_direct_hns_restore_watch_set(
2695        &mut self,
2696    ) -> Result<bool, MobileWalletError> {
2697        let now_unix = self.value.trusted_wallet_peer_now_unix()?;
2698        self.coordinator
2699            .extend_wallet_restore_watch_set(now_unix)
2700            .map_err(Into::into)
2701    }
2702
2703    /// Bind one wallet-owned direct Shakescape listener with the same network,
2704    /// address policy, socket deadlines, and explicit peer configuration as
2705    /// the embedded HNS backend.  Binding the socket does not unlock the
2706    /// wallet or service a board exchange.
2707    pub fn bind_wallet_owned_direct_shakescape_listener(
2708        &self,
2709        address: SocketAddr,
2710    ) -> Result<MobileDirectShakescapeListener, MobileWalletError> {
2711        self.coordinator
2712            .bind_shakescape_listener(address)
2713            .map(|listener| MobileDirectShakescapeListener { listener })
2714            .map_err(Into::into)
2715    }
2716
2717    /// Start the complete stock-HSD-backed ShakeScape TCP discovery lifecycle.
2718    ///
2719    /// `verified_public_endpoint` must be the public IPv6 socket or temporary
2720    /// PCP/NAT-PMP/UPnP TCP mapping that reaches `bind_address`. The Rust wallet
2721    /// never substitutes a STUN UDP mapping. Startup remains successful before
2722    /// ordinary HSD peers connect; a later tick performs the first publication.
2723    pub fn start_wallet_owned_shakescape_networking(
2724        &mut self,
2725        bind_address: SocketAddr,
2726        verified_public_endpoint: SocketAddr,
2727    ) -> Result<MobileShakescapeNetworking, MobileWalletError> {
2728        let listener = self.bind_wallet_owned_direct_shakescape_listener(bind_address)?;
2729        let now_unix = self.value.trusted_wallet_peer_now_unix()?;
2730        match self
2731            .coordinator
2732            .advertise_shakescape_endpoint(verified_public_endpoint, now_unix)
2733        {
2734            Ok(_) | Err(HnsDirectPeerError::NoReadyPeers) => {}
2735            Err(error) => return Err(error.into()),
2736        }
2737        Ok(MobileShakescapeNetworking {
2738            listener,
2739            verified_public_endpoint,
2740        })
2741    }
2742
2743    /// Refresh bounded self-advertisement and `GETADDR`, then try at most one
2744    /// due direct candidate. A returned peer has already passed Handshake and
2745    /// exact ShakeScape registry/network/genesis negotiation.
2746    pub fn tick_wallet_owned_shakescape_networking(
2747        &mut self,
2748        networking: &MobileShakescapeNetworking,
2749        local_height: u32,
2750    ) -> Result<Option<HnsDirectShakescapePeer>, MobileWalletError> {
2751        let now_unix = self.value.trusted_wallet_peer_now_unix()?;
2752        match self
2753            .coordinator
2754            .advertise_shakescape_endpoint(networking.verified_public_endpoint, now_unix)
2755        {
2756            Ok(_) | Err(HnsDirectPeerError::NoReadyPeers) => {}
2757            Err(error) => return Err(error.into()),
2758        }
2759        match self.coordinator.refresh_shakescape_discovery(now_unix) {
2760            Ok(_) | Err(HnsDirectPeerError::NoReadyPeers) => {}
2761            Err(error) => return Err(error.into()),
2762        }
2763        self.coordinator
2764            .connect_next_discovered_shakescape_peer(local_height, now_unix)
2765            .map_err(Into::into)
2766    }
2767
2768    /// Replace the host-verified public TCP mapping after an IPv6, interface,
2769    /// or router-mapping transition. The previous gossiped record cannot be
2770    /// withdrawn and therefore expires by its original timestamp.
2771    pub fn update_wallet_owned_shakescape_public_endpoint(
2772        &mut self,
2773        networking: &mut MobileShakescapeNetworking,
2774        verified_public_endpoint: SocketAddr,
2775    ) -> Result<(), MobileWalletError> {
2776        let now_unix = self.value.trusted_wallet_peer_now_unix()?;
2777        match self
2778            .coordinator
2779            .advertise_shakescape_endpoint(verified_public_endpoint, now_unix)
2780        {
2781            Ok(_) | Err(HnsDirectPeerError::NoReadyPeers) => {
2782                networking.verified_public_endpoint = verified_public_endpoint;
2783                Ok(())
2784            }
2785            Err(error) => Err(error.into()),
2786        }
2787    }
2788
2789    /// Accept at most one registry-negotiated inbound peer from the active
2790    /// networking lifecycle. Signed board validation remains a separate gate.
2791    pub fn accept_wallet_owned_shakescape_networking_peer(
2792        &mut self,
2793        networking: &MobileShakescapeNetworking,
2794        local_height: u32,
2795    ) -> Result<Option<HnsDirectShakescapePeer>, MobileWalletError> {
2796        self.accept_wallet_owned_direct_shakescape_peer(&networking.listener, local_height)
2797    }
2798
2799    /// Return the small non-sensitive mobile networking status surface. Raw
2800    /// candidate IPs, ports, and observation histories are not exposed here.
2801    pub fn wallet_owned_shakescape_networking_status(
2802        &mut self,
2803    ) -> Result<HnsShakescapeDiscoveryStatus, MobileWalletError> {
2804        let now_unix = self.value.trusted_wallet_peer_now_unix()?;
2805        self.coordinator
2806            .shakescape_discovery_status(now_unix)
2807            .map_err(Into::into)
2808    }
2809
2810    /// Stop discovery advertisement and consume the listener lifecycle. HSD
2811    /// has no withdrawal message; the last gossiped endpoint expires normally.
2812    pub fn stop_wallet_owned_shakescape_networking(
2813        &mut self,
2814        networking: MobileShakescapeNetworking,
2815    ) -> Result<bool, MobileWalletError> {
2816        let retired = self
2817            .coordinator
2818            .retire_shakescape_advertisement()
2819            .map_err(MobileWalletError::from)?;
2820        drop(networking);
2821        Ok(retired)
2822    }
2823
2824    /// Establish a direct Shakescape peer using the exact policy retained by this
2825    /// controller and the trusted clock of its unlocked value runtime.
2826    ///
2827    /// `local_height` is only the standard peer-handshake height hint. It is
2828    /// not chain evidence and cannot authorize a wallet action; all value
2829    /// operations continue to require a later synchronized runtime view.
2830    pub fn connect_wallet_owned_direct_shakescape_peer(
2831        &mut self,
2832        address: SocketAddr,
2833        local_height: u32,
2834    ) -> Result<HnsDirectShakescapePeer, MobileWalletError> {
2835        let now_unix = self.value.trusted_wallet_peer_now_unix()?;
2836        self.coordinator
2837            .connect_shakescape_peer(address, local_height, now_unix)
2838            .map_err(Into::into)
2839    }
2840
2841    /// Accept at most one Shakescape peer from a listener created by this direct
2842    /// controller.  A return value of `Ok(None)` means no TCP connection is
2843    /// pending.  Handshake time comes from the value runtime rather than a
2844    /// caller-provided wall clock.
2845    pub fn accept_wallet_owned_direct_shakescape_peer(
2846        &mut self,
2847        listener: &MobileDirectShakescapeListener,
2848        local_height: u32,
2849    ) -> Result<Option<HnsDirectShakescapePeer>, MobileWalletError> {
2850        let now_unix = self.value.trusted_wallet_peer_now_unix()?;
2851        listener
2852            .listener
2853            .accept_next(local_height, now_unix)
2854            .map_err(Into::into)
2855    }
2856
2857    /// Start one explicitly scheduled wallet-peer Shakedex board exchange.
2858    /// The supplied peer must have been obtained through this controller's
2859    /// connect/accept path; the board remains independently authenticated and
2860    /// no relay or provider transport is involved.
2861    pub fn begin_wallet_owned_direct_shakedex(
2862        &mut self,
2863        peer: &mut HnsDirectShakescapePeer,
2864    ) -> Result<DirectShakescapeBoardSyncReport, MobileWalletError> {
2865        self.value.begin_wallet_owned_direct_shakedex(peer)
2866    }
2867
2868    /// Process one bounded batch from an already negotiated wallet peer.
2869    pub fn synchronize_wallet_owned_direct_shakedex(
2870        &mut self,
2871        peer: &mut HnsDirectShakescapePeer,
2872        message_limit: usize,
2873    ) -> Result<DirectShakescapeBoardSyncReport, MobileWalletError> {
2874        self.value
2875            .synchronize_wallet_owned_direct_shakedex(peer, message_limit)
2876    }
2877
2878    /// Service one already classified name-market message from a negotiated
2879    /// wallet peer. Cross-chain direct-session messages remain owned by the
2880    /// adjacent direct HNS/BTC session controller.
2881    pub fn service_wallet_owned_direct_shakedex_message(
2882        &mut self,
2883        peer: &mut HnsDirectShakescapePeer,
2884        request_id: u64,
2885        message: hns_marketplace_protocol::NameMarketMessage,
2886    ) -> Result<DirectShakescapeBoardSyncReport, MobileWalletError> {
2887        self.value
2888            .service_wallet_owned_direct_shakedex_message(peer, request_id, message)
2889    }
2890
2891    /// Write one due local board publication to an already negotiated wallet
2892    /// peer and persist its local transport observation.
2893    pub fn announce_wallet_owned_direct_shakedex(
2894        &mut self,
2895        peer: &mut HnsDirectShakescapePeer,
2896    ) -> Result<Option<ObjectHash>, MobileWalletError> {
2897        self.value.announce_wallet_owned_direct_shakedex(peer)
2898    }
2899
2900    /// The native value controller sharing the coordinator's exact embedded
2901    /// backend. It retains the existing closed approval and value-action
2902    /// vocabulary; no raw key, seed, or generic provider interface is added.
2903    pub fn value_controller(&mut self) -> &mut MobileHnsValueController<EmbeddedHnsBackend, C> {
2904        &mut self.value
2905    }
2906}
2907
2908const MAX_MOBILE_NAME_RESOURCE_EDITOR_BYTES: usize = 4 * 1024;
2909
2910fn parse_mobile_name_resource(input: &str) -> Result<Vec<u8>, MobileWalletError> {
2911    if input.len() > MAX_MOBILE_NAME_RESOURCE_EDITOR_BYTES {
2912        return Err(MobileWalletError::InvalidValueAction);
2913    }
2914    let trimmed = input.trim();
2915    if let Some(exact) = trimmed.strip_prefix("hex:") {
2916        let compact = exact
2917            .bytes()
2918            .filter(|byte| !byte.is_ascii_whitespace())
2919            .collect::<Vec<_>>();
2920        if compact.len() % 2 != 0 || compact.len() > hns_covenants::MAX_RESOURCE_SIZE * 2 {
2921            return Err(MobileWalletError::InvalidValueAction);
2922        }
2923        let mut raw = Vec::with_capacity(compact.len() / 2);
2924        for pair in compact.chunks_exact(2) {
2925            let nibble = |byte| match byte {
2926                b'0'..=b'9' => Some(byte - b'0'),
2927                b'a'..=b'f' => Some(byte - b'a' + 10),
2928                b'A'..=b'F' => Some(byte - b'A' + 10),
2929                _ => None,
2930            };
2931            let high = nibble(pair[0]).ok_or(MobileWalletError::InvalidValueAction)?;
2932            let low = nibble(pair[1]).ok_or(MobileWalletError::InvalidValueAction)?;
2933            raw.push((high << 4) | low);
2934        }
2935        if !raw.is_empty() && hns_covenants::Resource::decode(&raw).is_err() {
2936            return Err(MobileWalletError::InvalidValueAction);
2937        }
2938        return Ok(raw);
2939    }
2940
2941    let lines = trimmed
2942        .lines()
2943        .map(str::trim)
2944        .filter(|line| !line.is_empty() && !line.starts_with('#'))
2945        .collect::<Vec<_>>();
2946    if lines.is_empty() {
2947        return Ok(Vec::new());
2948    }
2949    let mut raw = vec![0_u8];
2950    for line in lines {
2951        let split = line.find(char::is_whitespace);
2952        let (kind, arguments) =
2953            split.map_or((line, ""), |index| (&line[..index], line[index..].trim()));
2954        match kind.to_ascii_uppercase().as_str() {
2955            "NS" => {
2956                raw.push(1);
2957                encode_mobile_resource_name(arguments, &mut raw)?;
2958            }
2959            "GLUE4" => {
2960                let (name, address) = two_resource_arguments(arguments)?;
2961                raw.push(2);
2962                encode_mobile_resource_name(name, &mut raw)?;
2963                raw.extend_from_slice(
2964                    &address
2965                        .parse::<std::net::Ipv4Addr>()
2966                        .map_err(|_| MobileWalletError::InvalidValueAction)?
2967                        .octets(),
2968                );
2969            }
2970            "GLUE6" => {
2971                let (name, address) = two_resource_arguments(arguments)?;
2972                raw.push(3);
2973                encode_mobile_resource_name(name, &mut raw)?;
2974                raw.extend_from_slice(
2975                    &address
2976                        .parse::<std::net::Ipv6Addr>()
2977                        .map_err(|_| MobileWalletError::InvalidValueAction)?
2978                        .octets(),
2979                );
2980            }
2981            "SYNTH4" => {
2982                raw.push(4);
2983                raw.extend_from_slice(
2984                    &arguments
2985                        .parse::<std::net::Ipv4Addr>()
2986                        .map_err(|_| MobileWalletError::InvalidValueAction)?
2987                        .octets(),
2988                );
2989            }
2990            "SYNTH6" => {
2991                raw.push(5);
2992                raw.extend_from_slice(
2993                    &arguments
2994                        .parse::<std::net::Ipv6Addr>()
2995                        .map_err(|_| MobileWalletError::InvalidValueAction)?
2996                        .octets(),
2997                );
2998            }
2999            "TXT" => {
3000                let text = if arguments.starts_with('"') {
3001                    serde_json::from_str::<String>(arguments)
3002                        .map_err(|_| MobileWalletError::InvalidValueAction)?
3003                } else {
3004                    arguments.to_owned()
3005                };
3006                let bytes = text.as_bytes();
3007                if bytes.is_empty() || bytes.len() > u8::MAX as usize {
3008                    return Err(MobileWalletError::InvalidValueAction);
3009                }
3010                raw.extend_from_slice(&[6, 1, bytes.len() as u8]);
3011                raw.extend_from_slice(bytes);
3012            }
3013            "DS" => {
3014                let fields = arguments.split_whitespace().collect::<Vec<_>>();
3015                if fields.len() != 4 {
3016                    return Err(MobileWalletError::InvalidValueAction);
3017                }
3018                let key_tag = fields[0]
3019                    .parse::<u16>()
3020                    .map_err(|_| MobileWalletError::InvalidValueAction)?;
3021                let algorithm = fields[1]
3022                    .parse::<u8>()
3023                    .map_err(|_| MobileWalletError::InvalidValueAction)?;
3024                let digest_type = fields[2]
3025                    .parse::<u8>()
3026                    .map_err(|_| MobileWalletError::InvalidValueAction)?;
3027                let digest = parse_mobile_resource_digest(fields[3])?;
3028                raw.push(0);
3029                raw.extend_from_slice(&key_tag.to_be_bytes());
3030                raw.extend_from_slice(&[algorithm, digest_type, digest.len() as u8]);
3031                raw.extend_from_slice(&digest);
3032            }
3033            _ => return Err(MobileWalletError::InvalidValueAction),
3034        }
3035        if raw.len() > hns_covenants::MAX_RESOURCE_SIZE {
3036            return Err(MobileWalletError::InvalidValueAction);
3037        }
3038    }
3039    hns_covenants::Resource::decode(&raw).map_err(|_| MobileWalletError::InvalidValueAction)?;
3040    Ok(raw)
3041}
3042
3043fn two_resource_arguments(arguments: &str) -> Result<(&str, &str), MobileWalletError> {
3044    let mut fields = arguments.split_whitespace();
3045    let first = fields.next().ok_or(MobileWalletError::InvalidValueAction)?;
3046    let second = fields.next().ok_or(MobileWalletError::InvalidValueAction)?;
3047    if fields.next().is_some() {
3048        return Err(MobileWalletError::InvalidValueAction);
3049    }
3050    Ok((first, second))
3051}
3052
3053fn encode_mobile_resource_name(input: &str, output: &mut Vec<u8>) -> Result<(), MobileWalletError> {
3054    if input.is_empty() || input == "." {
3055        if input == "." {
3056            output.push(0);
3057            return Ok(());
3058        }
3059        return Err(MobileWalletError::InvalidValueAction);
3060    }
3061    let without_root = input.strip_suffix('.').unwrap_or(input);
3062    let labels = without_root.split('.').collect::<Vec<_>>();
3063    let encoded_size = labels.iter().try_fold(1_usize, |size, label| {
3064        if label.is_empty()
3065            || label.len() > 63
3066            || !label
3067                .bytes()
3068                .all(|byte| (0x21..=0x7e).contains(&byte) && byte != b'.')
3069        {
3070            return Err(MobileWalletError::InvalidValueAction);
3071        }
3072        size.checked_add(label.len() + 1)
3073            .ok_or(MobileWalletError::InvalidValueAction)
3074    })?;
3075    if encoded_size > 255 {
3076        return Err(MobileWalletError::InvalidValueAction);
3077    }
3078    for label in labels {
3079        output.push(label.len() as u8);
3080        output.extend(label.bytes().map(|byte| byte.to_ascii_lowercase()));
3081    }
3082    output.push(0);
3083    Ok(())
3084}
3085
3086fn parse_mobile_resource_digest(input: &str) -> Result<Vec<u8>, MobileWalletError> {
3087    if input.is_empty() || input.len() % 2 != 0 || input.len() > u8::MAX as usize * 2 {
3088        return Err(MobileWalletError::InvalidValueAction);
3089    }
3090    input
3091        .as_bytes()
3092        .chunks_exact(2)
3093        .map(|pair| {
3094            let nibble = |byte| match byte {
3095                b'0'..=b'9' => Some(byte - b'0'),
3096                b'a'..=b'f' => Some(byte - b'a' + 10),
3097                b'A'..=b'F' => Some(byte - b'A' + 10),
3098                _ => None,
3099            };
3100            Ok(
3101                (nibble(pair[0]).ok_or(MobileWalletError::InvalidValueAction)? << 4)
3102                    | nibble(pair[1]).ok_or(MobileWalletError::InvalidValueAction)?,
3103            )
3104        })
3105        .collect()
3106}
3107
3108impl MobileHnsValueIntent {
3109    fn into_provider_parts(
3110        self,
3111        account: AccountId,
3112    ) -> Result<(ApprovalKind, ProviderMethod, Value), MobileWalletError> {
3113        let market_account = lowercase_hex(account.as_bytes());
3114        Ok(match self {
3115            Self::Send {
3116                recipient,
3117                amount,
3118                maximum_fee,
3119            } => (
3120                ApprovalKind::Send,
3121                ProviderMethod::HnsSend,
3122                json!({
3123                    "account": account,
3124                    "recipient": recipient,
3125                    "amount": amount,
3126                    "maximumFee": maximum_fee,
3127                }),
3128            ),
3129            Self::TransferName {
3130                name,
3131                recipient,
3132                maximum_fee,
3133            } => (
3134                ApprovalKind::NameTransfer,
3135                ProviderMethod::HnsTransferName,
3136                json!({
3137                    "account": account,
3138                    "name": name,
3139                    "recipient": recipient,
3140                    "maximumFee": maximum_fee,
3141                }),
3142            ),
3143            Self::FinalizeName {
3144                name,
3145                expected_recipient,
3146                maximum_fee,
3147            } => (
3148                ApprovalKind::NameFinalize,
3149                ProviderMethod::HnsFinalizeName,
3150                json!({
3151                    "account": account,
3152                    "name": name,
3153                    "expectedRecipient": expected_recipient,
3154                    "maximumFee": maximum_fee,
3155                }),
3156            ),
3157            Self::SetNameRecords {
3158                name,
3159                records,
3160                maximum_fee,
3161            } => {
3162                let resource = parse_mobile_name_resource(&records)?;
3163                (
3164                    ApprovalKind::NameUpdate,
3165                    ProviderMethod::HnsUpdateName,
3166                    json!({
3167                        "account": account,
3168                        "name": name,
3169                        "rawResource": lowercase_hex(&resource),
3170                        "maximumFee": maximum_fee,
3171                    }),
3172                )
3173            }
3174            Self::CreateFixedPriceOffer {
3175                name,
3176                price,
3177                maximum_fee,
3178                listing_lifetime_seconds,
3179            } => (
3180                ApprovalKind::NameMarketOffer,
3181                ProviderMethod::NameMarketCreateFixedPriceOffer,
3182                json!({
3183                    "account": market_account,
3184                    "name": name,
3185                    "price": price,
3186                    "maximumFee": maximum_fee,
3187                    "listingLifetimeSeconds": listing_lifetime_seconds,
3188                }),
3189            ),
3190            Self::CancelOffer { seller_session_id } => (
3191                ApprovalKind::NameMarketOffer,
3192                ProviderMethod::NameMarketCancelOffer,
3193                json!({
3194                    "account": market_account,
3195                    "sellerSessionId": seller_session_id,
3196                }),
3197            ),
3198            Self::AcceptOffer {
3199                listing_id,
3200                maximum_fee,
3201                automatic_finalize_maximum_fee,
3202            } => (
3203                ApprovalKind::NameMarketPurchase,
3204                ProviderMethod::NameMarketAcceptOffer,
3205                json!({
3206                    "account": market_account,
3207                    "listingId": listing_id,
3208                    "maximumFee": maximum_fee,
3209                    "automaticFinalizeMaximumFee": automatic_finalize_maximum_fee,
3210                }),
3211            ),
3212            Self::FinalizePurchase {
3213                session_id,
3214                maximum_fee,
3215            } => (
3216                ApprovalKind::NameMarketPurchase,
3217                ProviderMethod::NameMarketFinalizePurchase,
3218                json!({
3219                    "account": market_account,
3220                    "sessionId": session_id,
3221                    "maximumFee": maximum_fee,
3222                }),
3223            ),
3224            Self::RecoverName {
3225                seller_session_id,
3226                maximum_fee,
3227            } => (
3228                ApprovalKind::NameMarketOffer,
3229                ProviderMethod::NameMarketRecoverName,
3230                json!({
3231                    "account": market_account,
3232                    "sellerSessionId": seller_session_id,
3233                    "maximumFee": maximum_fee,
3234                }),
3235            ),
3236        })
3237    }
3238}
3239
3240impl MobileShakedexQuery {
3241    fn into_provider_parts(self, account: AccountId) -> (ProviderMethod, Value) {
3242        match self {
3243            Self::ListOffers { cursor, limit } => (
3244                ProviderMethod::NameMarketListOffers,
3245                json!({
3246                    "cursor": cursor,
3247                    "limit": limit,
3248                }),
3249            ),
3250            Self::GetSession { session_id } => (
3251                ProviderMethod::NameMarketGetSession,
3252                json!({
3253                    "account": lowercase_hex(account.as_bytes()),
3254                    "sessionId": session_id,
3255                }),
3256            ),
3257            Self::ListMyOffers { cursor, limit } => (
3258                ProviderMethod::NameMarketListMyOffers,
3259                json!({
3260                    "account": lowercase_hex(account.as_bytes()),
3261                    "cursor": cursor,
3262                    "limit": limit,
3263                }),
3264            ),
3265            Self::GetOffer { listing_id } => (
3266                ProviderMethod::NameMarketGetOffer,
3267                json!({
3268                    "listingId": listing_id,
3269                }),
3270            ),
3271        }
3272    }
3273}
3274
3275fn mobile_hns_value_snapshot(
3276    expected_account: AccountId,
3277    snapshot: NativeHnsValueSnapshot,
3278) -> Result<(MobileHnsReadSnapshot, Vec<MobileHnsNameSummary>), MobileWalletError> {
3279    if snapshot.account_id != expected_account
3280        || snapshot.balance.asset != WalletAsset::Hns
3281        || snapshot
3282            .transactions
3283            .iter()
3284            .any(|transaction| transaction.module != ModuleId::Handshake)
3285        || snapshot.module_status.phase != SyncPhase::Ready
3286        || snapshot.module_status.validated_height != snapshot.module_status.scanned_height
3287        || snapshot.module_status.target_height != Some(snapshot.module_status.validated_height)
3288        || snapshot.module_status.last_error.is_some()
3289    {
3290        return Err(MobileWalletError::Hns(HnsWalletError::InvalidEvidence));
3291    }
3292    validate_mobile_hns_receive_targets(
3293        expected_account,
3294        &snapshot.receive_target,
3295        &snapshot.name_receive_target,
3296    )?;
3297    let mut known_names = snapshot
3298        .known_names
3299        .into_iter()
3300        .map(mobile_native_hns_name_summary)
3301        .collect::<Result<Vec<_>, _>>()?;
3302    let mut unique_names = BTreeSet::new();
3303    let mut unique_hashes = BTreeSet::new();
3304    if !known_names.iter().all(|name| {
3305        unique_names.insert(name.name.clone()) && unique_hashes.insert(name.name_hash.clone())
3306    }) {
3307        return Err(MobileWalletError::Hns(HnsWalletError::InvalidEvidence));
3308    }
3309    known_names.sort_by(|left, right| {
3310        left.name
3311            .cmp(&right.name)
3312            .then_with(|| left.name_hash.cmp(&right.name_hash))
3313    });
3314    let known_name_count = u32::try_from(known_names.len())
3315        .map_err(|_| MobileWalletError::Hns(HnsWalletError::HistoryLimit))?;
3316    let mut first_page = known_names.clone();
3317    first_page.truncate(MAX_MOBILE_HNS_NAME_PAGE);
3318    let known_names_complete = first_page.len() == known_names.len();
3319    let finalize_notices = snapshot
3320        .finalize_notices
3321        .into_iter()
3322        .map(|notice| MobileHnsFinalizeNotice {
3323            name: notice.name,
3324            transaction_id: notice.transaction_id,
3325            phase: match notice.phase {
3326                NativeHnsFinalizeNoticePhase::TransferPending => {
3327                    MobileHnsFinalizeNoticePhase::TransferPending
3328                }
3329                NativeHnsFinalizeNoticePhase::FinalizeWaiting => {
3330                    MobileHnsFinalizeNoticePhase::FinalizeWaiting
3331                }
3332                NativeHnsFinalizeNoticePhase::FinalizeAvailable => {
3333                    MobileHnsFinalizeNoticePhase::FinalizeAvailable
3334                }
3335                NativeHnsFinalizeNoticePhase::FinalizePending => {
3336                    MobileHnsFinalizeNoticePhase::FinalizePending
3337                }
3338            },
3339            current_height: notice.current_height,
3340            finalize_eligible_height: notice.finalize_eligible_height,
3341        })
3342        .collect();
3343    Ok((
3344        MobileHnsReadSnapshot {
3345            balance: snapshot.balance,
3346            receive_target: snapshot.receive_target,
3347            name_receive_target: snapshot.name_receive_target,
3348            transaction_history: snapshot.transactions,
3349            known_names: first_page,
3350            known_name_count,
3351            known_names_complete,
3352            finalize_notices,
3353            module_status: snapshot.module_status,
3354        },
3355        known_names,
3356    ))
3357}
3358
3359fn mobile_hns_name_page(
3360    names: &[MobileHnsNameSummary],
3361    offset: usize,
3362    limit: usize,
3363) -> Result<MobileHnsNamePage, MobileWalletError> {
3364    if limit == 0 || limit > MAX_MOBILE_HNS_NAME_PAGE || offset > names.len() {
3365        return Err(MobileWalletError::Hns(HnsWalletError::HistoryLimit));
3366    }
3367    let end = offset.saturating_add(limit).min(names.len());
3368    Ok(MobileHnsNamePage {
3369        offset: u32::try_from(offset)
3370            .map_err(|_| MobileWalletError::Hns(HnsWalletError::HistoryLimit))?,
3371        total: u32::try_from(names.len())
3372            .map_err(|_| MobileWalletError::Hns(HnsWalletError::HistoryLimit))?,
3373        names: names[offset..end].to_vec(),
3374        has_more: end < names.len(),
3375    })
3376}
3377
3378fn random_nonzero_bytes<const N: usize>() -> Result<[u8; N], MobileWalletError> {
3379    for _ in 0..8 {
3380        let mut bytes = [0_u8; N];
3381        getrandom::fill(&mut bytes).map_err(|_| MobileWalletError::Randomness)?;
3382        if bytes.iter().any(|byte| *byte != 0) {
3383            return Ok(bytes);
3384        }
3385    }
3386    Err(MobileWalletError::Randomness)
3387}
3388
3389fn random_nonzero_request_nonce() -> Result<u64, MobileWalletError> {
3390    Ok(u64::from_be_bytes(random_nonzero_bytes()?))
3391}
3392
3393fn mobile_action_token_matches(
3394    expected: &[u8; MOBILE_ACTION_TOKEN_BYTES],
3395    candidate: &str,
3396) -> bool {
3397    if candidate.len() != MOBILE_ACTION_TOKEN_BYTES * 2 {
3398        return false;
3399    }
3400    let mut difference = 0_u8;
3401    for (index, pair) in candidate.as_bytes().chunks_exact(2).enumerate() {
3402        let decode = |byte| match byte {
3403            b'0'..=b'9' => Some(byte - b'0'),
3404            b'a'..=b'f' => Some(byte - b'a' + 10),
3405            _ => None,
3406        };
3407        let Some(high) = decode(pair[0]) else {
3408            return false;
3409        };
3410        let Some(low) = decode(pair[1]) else {
3411            return false;
3412        };
3413        difference |= expected[index] ^ ((high << 4) | low);
3414    }
3415    difference == 0
3416}
3417
3418fn validate_mobile_hns_receive_targets(
3419    expected_account: AccountId,
3420    receive_target: &ReceiveTarget,
3421    name_receive_target: &HnsNameReceiveTarget,
3422) -> Result<(), MobileWalletError> {
3423    validate_mobile_hns_payment_receive_target(expected_account, receive_target)?;
3424    if name_receive_target.module != ModuleId::Handshake
3425        || name_receive_target.account != expected_account
3426        || name_receive_target.validate().is_err()
3427        || name_receive_target.display != receive_target.display
3428        || name_receive_target.derivation_index != receive_target.derivation_index
3429        || !name_receive_target
3430            .display
3431            .bytes()
3432            .all(|byte| (0x20..=0x7e).contains(&byte))
3433    {
3434        return Err(MobileWalletError::Hns(HnsWalletError::InvalidEvidence));
3435    }
3436    Ok(())
3437}
3438
3439fn validate_mobile_hns_payment_receive_target(
3440    expected_account: AccountId,
3441    receive_target: &ReceiveTarget,
3442) -> Result<(), MobileWalletError> {
3443    if receive_target.module != ModuleId::Handshake
3444        || receive_target.account != expected_account
3445        || receive_target.validate().is_err()
3446        || !receive_target
3447            .display
3448            .bytes()
3449            .all(|byte| (0x20..=0x7e).contains(&byte))
3450    {
3451        return Err(MobileWalletError::Hns(HnsWalletError::InvalidEvidence));
3452    }
3453    Ok(())
3454}
3455
3456fn mobile_hns_name_summary(name: &KnownName) -> Result<MobileHnsNameSummary, MobileWalletError> {
3457    if name.proof_height > MAX_JAVASCRIPT_SAFE_INTEGER {
3458        return Err(MobileWalletError::Hns(HnsWalletError::InvalidEvidence));
3459    }
3460    let display = String::from_utf8(name.name.clone())
3461        .map_err(|_| MobileWalletError::Hns(HnsWalletError::InvalidEvidence))?;
3462    let name_hash = lowercase_hex(&name.name_hash);
3463    HnsNameDisclosure {
3464        name: display.clone(),
3465        name_hash: name_hash.clone(),
3466    }
3467    .validate()?;
3468    let resource_status = match name.resource_status {
3469        NameResourceStatus::UnavailableCanonicalBinding => {
3470            MobileHnsNameResourceStatus::UnavailableCanonicalBinding
3471        }
3472        NameResourceStatus::NoCurrentState => MobileHnsNameResourceStatus::NoCurrentState,
3473        NameResourceStatus::Empty => MobileHnsNameResourceStatus::Empty,
3474        NameResourceStatus::CanonicalDecoded => MobileHnsNameResourceStatus::CanonicalDecoded,
3475        NameResourceStatus::CanonicalOpaque => MobileHnsNameResourceStatus::CanonicalOpaque,
3476    };
3477    let ownership_status = match &name.ownership_status {
3478        NameOwnershipStatus::WatchOnlyCanonicalStateDecoderUnavailable => {
3479            MobileHnsNameOwnershipStatus::WatchOnlyCanonicalStateDecoderUnavailable
3480        }
3481        NameOwnershipStatus::WatchOnlyOwnerTransactionUnavailable => {
3482            MobileHnsNameOwnershipStatus::WatchOnlyOwnerTransactionUnavailable
3483        }
3484        NameOwnershipStatus::WalletContextUnavailable => {
3485            MobileHnsNameOwnershipStatus::WalletContextUnavailable
3486        }
3487        NameOwnershipStatus::NoCurrentOwner => MobileHnsNameOwnershipStatus::NoCurrentOwner,
3488        NameOwnershipStatus::NotWalletOwned => MobileHnsNameOwnershipStatus::NotWalletOwned,
3489        NameOwnershipStatus::WalletOwned { .. } => MobileHnsNameOwnershipStatus::WalletOwned,
3490        NameOwnershipStatus::IncomingTransfer { .. } => {
3491            MobileHnsNameOwnershipStatus::IncomingTransfer
3492        }
3493        NameOwnershipStatus::OutgoingTransfer { .. } => {
3494            MobileHnsNameOwnershipStatus::OutgoingTransfer
3495        }
3496    };
3497    let (registered, expired) = name
3498        .canonical_current_state
3499        .as_ref()
3500        .map_or((None, None), |state| {
3501            (Some(state.registered), Some(state.expired))
3502        });
3503    let canonical_state =
3504        name.canonical_current_state
3505            .as_ref()
3506            .map(|state| MobileHnsNameStateSummary {
3507                value_base_units: state.value.to_string(),
3508                highest_base_units: state.highest.to_string(),
3509                start_height: state.start_height,
3510                renewal_height: state.renewal_height,
3511                transfer_height: state.transfer_height,
3512                revoked_height: state.revoked_height,
3513                claimed_height: state.claimed_height,
3514                renewals: state.renewals,
3515                weak: state.weak,
3516            });
3517    let raw_resource_hex = name.current_raw_resource.as_deref().map(lowercase_hex);
3518    let resource_record_count = name.current_raw_resource.as_deref().and_then(|raw| {
3519        if raw.is_empty() {
3520            Some(0)
3521        } else {
3522            hns_covenants::Resource::decode(raw)
3523                .ok()
3524                .and_then(|resource| u32::try_from(resource.records().len()).ok())
3525        }
3526    });
3527    Ok(MobileHnsNameSummary {
3528        name: display,
3529        name_hash,
3530        proof_height: name.proof_height,
3531        resource_status,
3532        ownership_status,
3533        registered,
3534        expired,
3535        canonical_state,
3536        raw_resource_hex,
3537        resource_record_count,
3538    })
3539}
3540
3541fn mobile_native_hns_name_summary(
3542    name: NativeHnsNameSummary,
3543) -> Result<MobileHnsNameSummary, MobileWalletError> {
3544    let resource_status = match name.resource_status {
3545        NativeHnsNameResourceStatus::UnavailableCanonicalBinding => {
3546            MobileHnsNameResourceStatus::UnavailableCanonicalBinding
3547        }
3548        NativeHnsNameResourceStatus::NoCurrentState => MobileHnsNameResourceStatus::NoCurrentState,
3549        NativeHnsNameResourceStatus::Empty => MobileHnsNameResourceStatus::Empty,
3550        NativeHnsNameResourceStatus::CanonicalDecoded => {
3551            MobileHnsNameResourceStatus::CanonicalDecoded
3552        }
3553        NativeHnsNameResourceStatus::CanonicalOpaque => {
3554            MobileHnsNameResourceStatus::CanonicalOpaque
3555        }
3556    };
3557    let ownership_status = match name.ownership_status {
3558        NativeHnsNameOwnershipStatus::WatchOnlyCanonicalStateDecoderUnavailable => {
3559            MobileHnsNameOwnershipStatus::WatchOnlyCanonicalStateDecoderUnavailable
3560        }
3561        NativeHnsNameOwnershipStatus::WatchOnlyOwnerTransactionUnavailable => {
3562            MobileHnsNameOwnershipStatus::WatchOnlyOwnerTransactionUnavailable
3563        }
3564        NativeHnsNameOwnershipStatus::WalletContextUnavailable => {
3565            MobileHnsNameOwnershipStatus::WalletContextUnavailable
3566        }
3567        NativeHnsNameOwnershipStatus::NoCurrentOwner => {
3568            MobileHnsNameOwnershipStatus::NoCurrentOwner
3569        }
3570        NativeHnsNameOwnershipStatus::NotWalletOwned => {
3571            MobileHnsNameOwnershipStatus::NotWalletOwned
3572        }
3573        NativeHnsNameOwnershipStatus::WalletOwned => MobileHnsNameOwnershipStatus::WalletOwned,
3574        NativeHnsNameOwnershipStatus::IncomingTransfer => {
3575            MobileHnsNameOwnershipStatus::IncomingTransfer
3576        }
3577        NativeHnsNameOwnershipStatus::OutgoingTransfer => {
3578            MobileHnsNameOwnershipStatus::OutgoingTransfer
3579        }
3580    };
3581    let canonical_state = name.canonical_state.map(|state| MobileHnsNameStateSummary {
3582        value_base_units: state.value.to_string(),
3583        highest_base_units: state.highest.to_string(),
3584        start_height: state.start_height,
3585        renewal_height: state.renewal_height,
3586        transfer_height: state.transfer_height,
3587        revoked_height: state.revoked_height,
3588        claimed_height: state.claimed_height,
3589        renewals: state.renewals,
3590        weak: state.weak,
3591    });
3592    let raw_resource_hex = name.raw_resource.as_deref().map(lowercase_hex);
3593    let resource_record_count = name.raw_resource.as_deref().and_then(|raw| {
3594        if raw.is_empty() {
3595            Some(0)
3596        } else {
3597            hns_covenants::Resource::decode(raw)
3598                .ok()
3599                .and_then(|resource| u32::try_from(resource.records().len()).ok())
3600        }
3601    });
3602    let summary = MobileHnsNameSummary {
3603        name: name.name,
3604        name_hash: name.name_hash,
3605        proof_height: name.proof_height,
3606        resource_status,
3607        ownership_status,
3608        registered: name.registered,
3609        expired: name.expired,
3610        canonical_state,
3611        raw_resource_hex,
3612        resource_record_count,
3613    };
3614    if summary.proof_height > MAX_JAVASCRIPT_SAFE_INTEGER {
3615        return Err(MobileWalletError::Hns(HnsWalletError::InvalidEvidence));
3616    }
3617    HnsNameDisclosure {
3618        name: summary.name.clone(),
3619        name_hash: summary.name_hash.clone(),
3620    }
3621    .validate()?;
3622    Ok(summary)
3623}
3624
3625fn wallet_owned_direct_shakedex_config() -> PersistentShakedexConfig {
3626    PersistentShakedexConfig {
3627        seller_policy: ShakedexSellerPolicy::no_marketplace_fee(),
3628        transport: PersistentShakescapeTransport::WalletPeers,
3629    }
3630}
3631
3632fn lowercase_hex(bytes: &[u8]) -> String {
3633    let mut encoded = String::with_capacity(bytes.len() * 2);
3634    for byte in bytes {
3635        encoded.push(HEX[usize::from(byte >> 4)] as char);
3636        encoded.push(HEX[usize::from(byte & 0x0f)] as char);
3637    }
3638    encoded
3639}
3640
3641fn mobile_service_failure(failure: ServiceFailure) -> MobileWalletError {
3642    MobileWalletError::ServiceFailure {
3643        code: failure.code,
3644        message: failure.message,
3645    }
3646}
3647
3648/// The service emits this exact error only from the final re-preparation step
3649/// of an HNS send, before signing or broadcasting begins. The pending approval
3650/// has already been discarded, so keeping the session unlocked cannot retain
3651/// executable authority. A fresh sync and review are still mandatory.
3652fn hns_send_pre_broadcast_retry_required(error: &MobileWalletError) -> bool {
3653    matches!(
3654        error,
3655        MobileWalletError::ServiceFailure {
3656            code: ServiceErrorCode::RuntimeFailure,
3657            message,
3658        } if message == NATIVE_HNS_SEND_PRE_BROADCAST_RETRY_MESSAGE
3659    )
3660}
3661
3662#[derive(Debug, Error)]
3663pub enum MobileWalletError {
3664    #[error("wallet database key must be exactly 32 nonzero bytes")]
3665    InvalidDatabaseKey,
3666    #[error("mobile wallet database must contain exactly one valid HNS account")]
3667    InvalidAccountSet,
3668    #[error("mobile recovery phrase is empty or exceeds its native input bound")]
3669    InvalidRecoveryPhrase,
3670    #[error("the system clock is unavailable for Bitcoin wallet state")]
3671    BitcoinClockUnavailable,
3672    #[error("the direct Bitcoin runtime is inactive")]
3673    BitcoinRuntimeInactive,
3674    #[error("the direct Bitcoin runtime could not be created")]
3675    BitcoinRuntimeUnavailable,
3676    #[error("a direct Bitcoin send approval is already pending")]
3677    BitcoinActionPending,
3678    #[error("there is no pending direct Bitcoin send approval")]
3679    NoPendingBitcoinAction,
3680    #[error("the direct Bitcoin send approval token is invalid")]
3681    InvalidBitcoinActionToken,
3682    #[error("the direct Bitcoin send approval has expired")]
3683    BitcoinActionExpired,
3684    #[error("the direct Bitcoin send request is invalid")]
3685    InvalidBitcoinAction,
3686    #[error("the direct Shakescape HNS/Bitcoin session message is invalid")]
3687    InvalidShakescapeSessionMessage,
3688    #[error("a direct BTC-for-HNS offer approval is already pending")]
3689    DirectOfferActionPending,
3690    #[error("there is no pending direct BTC-for-HNS offer approval")]
3691    NoPendingDirectOfferAction,
3692    #[error("the direct BTC-for-HNS offer approval token is invalid")]
3693    InvalidDirectOfferActionToken,
3694    #[error("the direct BTC-for-HNS offer approval has expired")]
3695    DirectOfferActionExpired,
3696    #[error("the direct BTC-for-HNS offer request is invalid")]
3697    InvalidDirectOfferAction,
3698    #[error("confirmed Bitcoin does not cover active offers, this offer, and its fee reserve")]
3699    InsufficientBitcoinForDirectOffer,
3700    #[error("insufficient confirmed HNS for direct offer")]
3701    InsufficientHnsForDirectOffer,
3702    #[error("private wallet host/service response was unexpected")]
3703    UnexpectedResponse,
3704    #[error("private mobile wallet controller failed closed and must be reopened")]
3705    ControllerFailed,
3706    #[error("a native HNS value action is already pending")]
3707    ValueActionPending,
3708    #[error("there is no pending native HNS value action")]
3709    NoPendingValueAction,
3710    #[error("native HNS value action token is invalid")]
3711    InvalidActionToken,
3712    #[error("native HNS value action is invalid")]
3713    InvalidValueAction,
3714    #[error("secure native randomness is unavailable")]
3715    Randomness,
3716    #[error("wallet service rejected the request ({code:?}): {message}")]
3717    ServiceFailure {
3718        code: ServiceErrorCode,
3719        message: String,
3720    },
3721    #[error(transparent)]
3722    Store(#[from] StoreError),
3723    #[error(transparent)]
3724    Hns(#[from] HnsWalletError),
3725    #[error(transparent)]
3726    DirectHns(#[from] HnsDirectPeerError),
3727    #[error(transparent)]
3728    Bitcoin(#[from] hns_wallet_bitcoin_kyoto::BitcoinWalletError),
3729    #[error(transparent)]
3730    Market(#[from] hns_wallet_market::MarketError),
3731    #[error(transparent)]
3732    Host(#[from] HostError),
3733    #[error(transparent)]
3734    Clock(#[from] ClockError),
3735    #[error(transparent)]
3736    Service(#[from] ServiceError),
3737    #[error(transparent)]
3738    Abi(#[from] AbiError),
3739}
3740
3741impl MobileWalletError {
3742    /// Whether a failed direct ShakeScape envelope proves that the underlying
3743    /// authenticated peer can no longer be serviced safely.
3744    ///
3745    /// Durable board/session admission is deliberately independent from the
3746    /// transport lifetime. A stale, duplicate, conflicting, or locally
3747    /// unserviceable signed object can be rejected while later inventory and
3748    /// offer messages on the same ordered connection remain useful. Only an
3749    /// actual peer I/O failure or a non-canonical cross-chain envelope makes
3750    /// the connection itself unusable.
3751    pub const fn invalidates_direct_shakescape_transport(&self) -> bool {
3752        matches!(
3753            self,
3754            Self::DirectHns(_) | Self::InvalidShakescapeSessionMessage
3755        )
3756    }
3757}
3758
3759#[cfg(test)]
3760mod tests {
3761    use super::*;
3762    use std::sync::Arc;
3763    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
3764
3765    use hns_transaction::Coin;
3766    use hns_wallet_hns::{
3767        BlockHashEvidence, CanonicalNameStateSummary, ChainTip, ConfirmedWalletPage,
3768        ConfirmedWalletPageRequest, HnsNameAction, HnsOutpoint, HnsTransactionFeeQuote,
3769        IncomingTransfersPage, IncomingTransfersPageRequest, MempoolSnapshotBinding,
3770        MempoolWalletPage, MempoolWalletPageRequest, NameActionContextEvidence, NameEvidence,
3771        OutpointSpendEvidence, SnapshotBinding, TransactionEvidence,
3772    };
3773    use hns_wallet_store::EntityKind;
3774    use hns_wallet_types::{BaseUnits, TransactionHash};
3775
3776    const MOCK_READ_HEIGHT: u64 = 7;
3777
3778    #[test]
3779    fn only_the_exact_pre_broadcast_send_retry_keeps_the_session_unlocked() {
3780        let safe_retry = MobileWalletError::ServiceFailure {
3781            code: ServiceErrorCode::RuntimeFailure,
3782            message: NATIVE_HNS_SEND_PRE_BROADCAST_RETRY_MESSAGE.to_owned(),
3783        };
3784        assert!(hns_send_pre_broadcast_retry_required(&safe_retry));
3785
3786        for error in [
3787            MobileWalletError::ServiceFailure {
3788                code: ServiceErrorCode::RuntimeFailure,
3789                message: "HNS value runtime failed".to_owned(),
3790            },
3791            MobileWalletError::ServiceFailure {
3792                code: ServiceErrorCode::InvalidRequest,
3793                message: NATIVE_HNS_SEND_PRE_BROADCAST_RETRY_MESSAGE.to_owned(),
3794            },
3795            MobileWalletError::InvalidActionToken,
3796        ] {
3797            assert!(!hns_send_pre_broadcast_retry_required(&error));
3798        }
3799    }
3800
3801    #[test]
3802    fn durable_swap_rejection_does_not_invalidate_authenticated_transport() {
3803        let conflict =
3804            MobileWalletError::Market(hns_wallet_market::MarketError::ShakescapeDirectSwapConflict);
3805        assert!(!conflict.invalidates_direct_shakescape_transport());
3806
3807        let invalid_envelope = MobileWalletError::InvalidShakescapeSessionMessage;
3808        assert!(invalid_envelope.invalidates_direct_shakescape_transport());
3809    }
3810
3811    #[derive(Default)]
3812    struct MockReadProbe {
3813        fail_synchronization: AtomicBool,
3814        snapshot_calls: AtomicUsize,
3815        tip_calls: AtomicUsize,
3816        confirmed_calls: AtomicUsize,
3817        incoming_calls: AtomicUsize,
3818        mempool_calls: AtomicUsize,
3819        evidence_calls: AtomicUsize,
3820        forbidden_calls: AtomicUsize,
3821    }
3822
3823    struct MockReadBackend {
3824        probe: Arc<MockReadProbe>,
3825    }
3826
3827    impl MockReadBackend {
3828        fn new(probe: Arc<MockReadProbe>) -> Self {
3829            Self { probe }
3830        }
3831
3832        fn tip() -> ChainTip {
3833            ChainTip {
3834                height: MOCK_READ_HEIGHT,
3835                block_hash: [0x31; 32],
3836                tree_root: [0x32; 32],
3837                median_time_past: 1_800_000_000,
3838            }
3839        }
3840
3841        fn binding() -> SnapshotBinding {
3842            SnapshotBinding {
3843                tip: Self::tip(),
3844                chain_epoch: 3,
3845            }
3846        }
3847
3848        fn mempool() -> MempoolSnapshotBinding {
3849            MempoolSnapshotBinding {
3850                instance_nonce: [0x33; 32],
3851                generation: 4,
3852            }
3853        }
3854
3855        fn regtest_genesis() -> [u8; 32] {
3856            [
3857                0xae, 0x38, 0x95, 0xcf, 0x59, 0x7e, 0xff, 0x05, 0xb1, 0x9e, 0x02, 0xa7, 0x0c, 0xee,
3858                0xee, 0xcb, 0x9d, 0xc7, 0x2d, 0xbf, 0xe6, 0x50, 0x4a, 0x50, 0xe9, 0x34, 0x3a, 0x72,
3859                0xf0, 0x6a, 0x87, 0xc5,
3860            ]
3861        }
3862
3863        fn unavailable_evidence(&self, method: &str) -> HnsWalletError {
3864            self.probe.evidence_calls.fetch_add(1, Ordering::SeqCst);
3865            HnsWalletError::Backend(format!(
3866                "unexpected evidence call for empty mobile read fixture: {method}"
3867            ))
3868        }
3869
3870        fn forbidden(&self, method: &str) -> HnsWalletError {
3871            self.probe.forbidden_calls.fetch_add(1, Ordering::SeqCst);
3872            HnsWalletError::Backend(format!(
3873                "unexpected value-capable backend call from mobile reads: {method}"
3874            ))
3875        }
3876    }
3877
3878    impl HnsBackend for MockReadBackend {
3879        fn get_chain_snapshot(&self) -> Result<SnapshotBinding, HnsWalletError> {
3880            self.probe.snapshot_calls.fetch_add(1, Ordering::SeqCst);
3881            if self.probe.fail_synchronization.load(Ordering::SeqCst) {
3882                return Err(HnsWalletError::Backend(
3883                    "injected mobile read failure".to_owned(),
3884                ));
3885            }
3886            Ok(Self::binding())
3887        }
3888
3889        fn get_chain_tip(&self) -> Result<ChainTip, HnsWalletError> {
3890            self.probe.tip_calls.fetch_add(1, Ordering::SeqCst);
3891            Ok(Self::tip())
3892        }
3893
3894        fn get_block_hash(
3895            &self,
3896            height: u64,
3897            binding: SnapshotBinding,
3898        ) -> Result<BlockHashEvidence, HnsWalletError> {
3899            Ok(BlockHashEvidence {
3900                binding,
3901                height,
3902                block_hash: Some(if height == 0 {
3903                    Self::regtest_genesis()
3904                } else if height == binding.tip.height {
3905                    binding.tip.block_hash
3906                } else {
3907                    [0x35; 32]
3908                }),
3909            })
3910        }
3911
3912        fn get_confirmed_wallet_page(
3913            &self,
3914            request: ConfirmedWalletPageRequest<'_>,
3915        ) -> Result<ConfirmedWalletPage, HnsWalletError> {
3916            self.probe.confirmed_calls.fetch_add(1, Ordering::SeqCst);
3917            if request.expected_tip != Self::tip()
3918                || request
3919                    .expected_epoch
3920                    .is_some_and(|epoch| epoch != Self::binding().chain_epoch)
3921            {
3922                return Err(HnsWalletError::StaleNodeSnapshot);
3923            }
3924            Ok(ConfirmedWalletPage {
3925                binding: Self::binding(),
3926                next_cursor: None,
3927                history: Vec::new(),
3928                utxos: Vec::new(),
3929            })
3930        }
3931
3932        fn get_mempool_wallet_page(
3933            &self,
3934            request: MempoolWalletPageRequest<'_>,
3935        ) -> Result<MempoolWalletPage, HnsWalletError> {
3936            self.probe.mempool_calls.fetch_add(1, Ordering::SeqCst);
3937            if request.binding != Self::binding()
3938                || request
3939                    .expected_mempool
3940                    .is_some_and(|mempool| mempool != Self::mempool())
3941            {
3942                return Err(HnsWalletError::StaleNodeSnapshot);
3943            }
3944            Ok(MempoolWalletPage {
3945                binding: Self::binding(),
3946                mempool: Self::mempool(),
3947                next_cursor: None,
3948                history: Vec::new(),
3949            })
3950        }
3951
3952        fn get_incoming_transfers_page(
3953            &self,
3954            request: IncomingTransfersPageRequest<'_>,
3955        ) -> Result<IncomingTransfersPage, HnsWalletError> {
3956            self.probe.incoming_calls.fetch_add(1, Ordering::SeqCst);
3957            if request.binding != Self::binding()
3958                || request.scripts.is_empty()
3959                || request.cursor.is_some()
3960                || request.limit == 0
3961            {
3962                return Err(HnsWalletError::StaleNodeSnapshot);
3963            }
3964            Ok(IncomingTransfersPage {
3965                projection_version: 1,
3966                binding: Self::binding(),
3967                entries: Vec::new(),
3968                script_examinations: request.scripts.len(),
3969                next_cursor: None,
3970            })
3971        }
3972
3973        fn get_transaction_evidence(
3974            &self,
3975            _: TransactionHash,
3976            _: SnapshotBinding,
3977            _: Option<MempoolSnapshotBinding>,
3978        ) -> Result<TransactionEvidence, HnsWalletError> {
3979            Err(self.unavailable_evidence("get_transaction_evidence"))
3980        }
3981
3982        fn get_outpoint_spend_evidence(
3983            &self,
3984            _: &[HnsOutpoint],
3985            _: SnapshotBinding,
3986        ) -> Result<OutpointSpendEvidence, HnsWalletError> {
3987            Err(self.unavailable_evidence("get_outpoint_spend_evidence"))
3988        }
3989
3990        fn broadcast_transaction(&self, _: &[u8]) -> Result<TransactionHash, HnsWalletError> {
3991            Err(self.forbidden("broadcast_transaction"))
3992        }
3993
3994        fn quote_transaction_fee(
3995            &self,
3996            _: &[u8],
3997            _: &[Coin],
3998            _: u16,
3999            _: SnapshotBinding,
4000            _: MempoolSnapshotBinding,
4001        ) -> Result<HnsTransactionFeeQuote, HnsWalletError> {
4002            Err(self.forbidden("quote_transaction_fee"))
4003        }
4004
4005        fn estimate_fee_rate(&self, _: u16) -> Result<BaseUnits, HnsWalletError> {
4006            Err(self.forbidden("estimate_fee_rate"))
4007        }
4008
4009        fn get_name_evidence(
4010            &self,
4011            _: [u8; 32],
4012            _: SnapshotBinding,
4013        ) -> Result<NameEvidence, HnsWalletError> {
4014            Err(self.unavailable_evidence("get_name_evidence"))
4015        }
4016
4017        fn get_name_action_context(
4018            &self,
4019            _: HnsNameAction,
4020            _: [u8; 32],
4021            _: SnapshotBinding,
4022            _: MempoolSnapshotBinding,
4023        ) -> Result<NameActionContextEvidence, HnsWalletError> {
4024            Err(self.forbidden("get_name_action_context"))
4025        }
4026    }
4027
4028    #[derive(Clone, Copy)]
4029    struct MockReadClock;
4030
4031    impl HnsClock for MockReadClock {
4032        fn now_unix(&self) -> Result<u64, HnsWalletError> {
4033            Ok(1_800_000_000)
4034        }
4035    }
4036
4037    fn private_tempdir() -> tempfile::TempDir {
4038        let root = std::env::var_os("HNS_WALLET_STORE_TEST_TMPDIR")
4039            .map(std::path::PathBuf::from)
4040            .unwrap_or_else(std::env::temp_dir);
4041        let directory = tempfile::Builder::new()
4042            .prefix("hns-wallet-mobile-")
4043            .tempdir_in(root)
4044            .expect("private mobile-wallet test directory");
4045        #[cfg(unix)]
4046        {
4047            use std::os::unix::fs::PermissionsExt as _;
4048
4049            std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700))
4050                .expect("private mobile-wallet test directory mode");
4051        }
4052        directory
4053    }
4054
4055    #[test]
4056    fn database_key_is_exact_nonzero_and_domain_separated() {
4057        assert!(matches!(
4058            MobileDatabaseKey::from_slice(&[7_u8; MOBILE_DATABASE_KEY_BYTES - 1]),
4059            Err(MobileWalletError::InvalidDatabaseKey)
4060        ));
4061        assert!(matches!(
4062            MobileDatabaseKey::new([0_u8; MOBILE_DATABASE_KEY_BYTES]),
4063            Err(MobileWalletError::InvalidDatabaseKey)
4064        ));
4065
4066        let key = MobileDatabaseKey::new([0xab; MOBILE_DATABASE_KEY_BYTES]).expect("key");
4067        let passphrase = key.store_passphrase();
4068        assert!(passphrase.starts_with(STORE_PASSPHRASE_DOMAIN));
4069        assert_eq!(
4070            passphrase.len(),
4071            STORE_PASSPHRASE_DOMAIN.len() + MOBILE_DATABASE_KEY_BYTES * 2
4072        );
4073        assert!(!passphrase.contains("[171"));
4074    }
4075
4076    #[test]
4077    fn recovery_phrase_input_is_owned_and_bounded() {
4078        assert!(matches!(
4079            MobileRecoveryPhrase::new(String::new()),
4080            Err(MobileWalletError::InvalidRecoveryPhrase)
4081        ));
4082        assert!(matches!(
4083            MobileRecoveryPhrase::new("a".repeat(MAX_MOBILE_RECOVERY_PHRASE_BYTES + 1)),
4084            Err(MobileWalletError::InvalidRecoveryPhrase)
4085        ));
4086    }
4087
4088    #[test]
4089    fn android_create_and_ios_open_restore_keep_the_first_slice_fail_closed() {
4090        let directory = private_tempdir();
4091        let created_path = directory.path().join("created.sqlite3");
4092        let restored_path = directory.path().join("restored.sqlite3");
4093        let key = MobileDatabaseKey::new([0xab; MOBILE_DATABASE_KEY_BYTES]).expect("database key");
4094        let policy = HnsBootstrapPolicy::new(HnsNetwork::Regtest, 123);
4095
4096        let creation =
4097            MobileWalletController::create(&created_path, &key, MobilePlatform::Android, policy)
4098                .expect("create Android controller");
4099        let (mut controller, recovery_phrase) = creation.into_parts();
4100        let created_config = controller.account_config().clone();
4101        assert_eq!(created_config.network, HnsNetwork::Regtest);
4102        assert_eq!(created_config.birthday_height, 123);
4103        assert_eq!(created_config.account_derivation_index, 0);
4104        assert!(!created_config.value_operations_enabled);
4105        assert!(!created_config.settlement_enabled);
4106
4107        let phrase = recovery_phrase.expose_for_dedicated_display();
4108        assert_eq!(phrase.split_whitespace().count(), 24);
4109
4110        let status = controller.status().expect("created status");
4111        assert!(status.locked);
4112        assert_eq!(status.active_wallet, None);
4113        assert!(status.enabled_modules.is_empty());
4114        assert!(!status.mainnet_settlement_enabled);
4115
4116        controller.unlock(&key).expect("unlock created wallet");
4117        let status = controller.status().expect("unlocked created status");
4118        assert!(!status.locked);
4119        assert_eq!(status.active_wallet, Some(created_config.wallet_id));
4120        assert!(status.enabled_modules.is_empty());
4121        let accounts = controller.accounts().expect("created accounts");
4122        assert_eq!(accounts.len(), 1);
4123        assert_eq!(accounts[0].account_id, created_config.account_id);
4124        assert_eq!(accounts[0].label, MOBILE_ACCOUNT_LABEL);
4125        assert_eq!(accounts[0].receive_display, None);
4126
4127        let wrong_key =
4128            MobileDatabaseKey::new([0xcd; MOBILE_DATABASE_KEY_BYTES]).expect("wrong database key");
4129        assert!(controller.unlock(&wrong_key).is_err());
4130        assert!(controller.status().expect("status after bad key").locked);
4131        controller.unlock(&key).expect("unlock after bad key");
4132        controller.lock().expect("lock created wallet");
4133        drop(controller);
4134
4135        let mut reopened = MobileWalletController::open(&created_path, &key, MobilePlatform::Ios)
4136            .expect("open created wallet on iOS boundary");
4137        assert!(reopened.status().expect("reopened status").locked);
4138        reopened.unlock(&key).expect("unlock reopened wallet");
4139        assert_eq!(
4140            reopened
4141                .status()
4142                .expect("reopened unlocked status")
4143                .active_wallet,
4144            Some(created_config.wallet_id)
4145        );
4146        reopened.lock().expect("lock reopened wallet");
4147        drop(reopened);
4148
4149        let recovery_phrase = MobileRecoveryPhrase::new(phrase).expect("owned recovery phrase");
4150        let mut restored = MobileWalletController::restore(
4151            &restored_path,
4152            &key,
4153            MobilePlatform::Ios,
4154            policy,
4155            recovery_phrase,
4156        )
4157        .expect("restore iOS controller");
4158        let restored_config = restored.account_config().clone();
4159        assert_eq!(restored_config.network, HnsNetwork::Regtest);
4160        assert_eq!(restored_config.birthday_height, 123);
4161        assert_eq!(restored_config.account_derivation_index, 0);
4162        assert!(!restored_config.value_operations_enabled);
4163        assert!(!restored_config.settlement_enabled);
4164        assert!(restored.status().expect("restored status").locked);
4165        restored.unlock(&key).expect("unlock restored wallet");
4166        let accounts = restored.accounts().expect("restored accounts");
4167        assert_eq!(accounts.len(), 1);
4168        assert_eq!(accounts[0].account_id, restored_config.account_id);
4169        restored.lock().expect("lock restored wallet");
4170    }
4171
4172    #[test]
4173    fn lifecycle_opens_a_wallet_owned_direct_peer_coordinator_without_rpc_credentials() {
4174        let directory = private_tempdir();
4175        let path = directory.path().join("direct-peer-wallet.sqlite3");
4176        let key = MobileDatabaseKey::new([0x7a; MOBILE_DATABASE_KEY_BYTES]).expect("database key");
4177        let creation = MobileWalletController::create(
4178            &path,
4179            &key,
4180            MobilePlatform::Android,
4181            HnsBootstrapPolicy::new(HnsNetwork::Regtest, 0),
4182        )
4183        .expect("create direct-peer wallet");
4184        let (mut controller, _recovery) = creation.into_parts();
4185        let coordinator = controller
4186            .open_direct_hns_peer_coordinator(
4187                &key,
4188                HnsDirectPeerConfig::for_network(HnsNetwork::Regtest),
4189            )
4190            .expect("open direct coordinator without an endpoint or credential");
4191        let scan = coordinator
4192            .backend()
4193            .light_scan_status()
4194            .expect("wallet-owned direct index");
4195        assert_eq!(
4196            scan.watched_scripts,
4197            controller.account_config().restore_lookahead as usize * 3
4198        );
4199        assert_eq!(scan.watched_names, 0);
4200        assert!(controller.status().expect("controller relocked").locked);
4201    }
4202
4203    #[test]
4204    fn direct_value_composition_retains_the_coordinator_and_refreshes_its_account_policy() {
4205        let directory = private_tempdir();
4206        let path = directory.path().join("direct-value-wallet.sqlite3");
4207        let key = MobileDatabaseKey::new([0x7b; MOBILE_DATABASE_KEY_BYTES]).expect("database key");
4208        let creation = MobileWalletController::create(
4209            &path,
4210            &key,
4211            MobilePlatform::Android,
4212            HnsBootstrapPolicy::new(HnsNetwork::Regtest, 0),
4213        )
4214        .expect("create direct value wallet");
4215        let (mut controller, _recovery) = creation.into_parts();
4216        let coordinator = controller
4217            .open_direct_hns_peer_coordinator(
4218                &key,
4219                HnsDirectPeerConfig::for_network(HnsNetwork::Regtest),
4220            )
4221            .expect("open wallet-owned coordinator");
4222
4223        let mut direct = controller
4224            .into_wallet_owned_direct_hns_value_with_clock(&key, coordinator, MockReadClock, None)
4225            .expect("compose direct value controller");
4226        assert!(
4227            direct
4228                .value_controller()
4229                .account_config()
4230                .value_operations_enabled
4231        );
4232        assert!(
4233            !direct
4234                .value_controller()
4235                .account_config()
4236                .settlement_enabled
4237        );
4238
4239        direct
4240            .value_controller()
4241            .unlock(&key)
4242            .expect("unlock direct value controller");
4243        // Value activation updates the persisted policy record. A coordinator
4244        // that retained the original non-value configuration would now reject
4245        // its own account instead of growing the direct restore frontier.
4246        assert!(
4247            direct
4248                .extend_wallet_owned_direct_hns_restore_watch_set()
4249                .expect("extend direct restore watch set with the value runtime clock")
4250        );
4251        direct
4252            .value_controller()
4253            .lock()
4254            .expect("relock direct value controller");
4255    }
4256
4257    #[test]
4258    fn direct_value_and_shakedex_composition_enables_wallet_peer_settlement() {
4259        let directory = private_tempdir();
4260        let path = directory
4261            .path()
4262            .join("direct-value-shakedex-wallet.sqlite3");
4263        let key = MobileDatabaseKey::new([0x7c; MOBILE_DATABASE_KEY_BYTES]).expect("database key");
4264        let creation = MobileWalletController::create(
4265            &path,
4266            &key,
4267            MobilePlatform::Android,
4268            HnsBootstrapPolicy::new(HnsNetwork::Regtest, 0),
4269        )
4270        .expect("create direct Shakedex wallet");
4271        let (mut controller, _recovery) = creation.into_parts();
4272        let coordinator = controller
4273            .open_direct_hns_peer_coordinator(
4274                &key,
4275                HnsDirectPeerConfig::for_network(HnsNetwork::Regtest),
4276            )
4277            .expect("open wallet-owned coordinator");
4278
4279        let mut direct = controller
4280            .into_wallet_owned_direct_hns_value_with_wallet_owned_direct_shakedex_with_clock(
4281                &key,
4282                coordinator,
4283                MockReadClock,
4284            )
4285            .expect("compose direct value and Shakedex controller");
4286        assert!(
4287            direct
4288                .value_controller()
4289                .account_config()
4290                .value_operations_enabled
4291        );
4292        assert!(
4293            direct
4294                .value_controller()
4295                .account_config()
4296                .settlement_enabled
4297        );
4298        let listener = direct
4299            .bind_wallet_owned_direct_shakescape_listener((std::net::Ipv4Addr::LOCALHOST, 0).into())
4300            .expect("bind Shakescape listener from the direct value controller");
4301        assert!(
4302            listener
4303                .local_addr()
4304                .expect("direct Shakescape listener address")
4305                .port()
4306                != 0
4307        );
4308        assert!(matches!(
4309            direct.connect_wallet_owned_direct_shakescape_peer(
4310                (std::net::Ipv4Addr::LOCALHOST, 1).into(),
4311                0,
4312            ),
4313            Err(MobileWalletError::Store(StoreError::Locked))
4314        ));
4315        direct
4316            .value_controller()
4317            .unlock(&key)
4318            .expect("unlock direct value and Shakedex controller");
4319        assert!(
4320            direct
4321                .accept_wallet_owned_direct_shakescape_peer(&listener, 0)
4322                .expect("poll direct Shakescape listener with the value runtime clock")
4323                .is_none()
4324        );
4325        direct
4326            .value_controller()
4327            .lock()
4328            .expect("relock direct value and Shakedex controller");
4329    }
4330
4331    #[test]
4332    fn value_unlock_defers_wallet_peer_market_recovery_until_explicit_sync() {
4333        let directory = private_tempdir();
4334        let path = directory.path().join("value-unlock-deferred-sync.sqlite3");
4335        let key = MobileDatabaseKey::new([0x8b; MOBILE_DATABASE_KEY_BYTES]).expect("database key");
4336        let creation = MobileWalletController::create(
4337            &path,
4338            &key,
4339            MobilePlatform::Android,
4340            HnsBootstrapPolicy::new(HnsNetwork::Regtest, 0),
4341        )
4342        .expect("create direct value wallet");
4343        let (controller, _recovery) = creation.into_parts();
4344        let probe = Arc::new(MockReadProbe::default());
4345        let mut value = controller
4346            .into_hns_value_with_clock(
4347                &key,
4348                MockReadBackend::new(probe.clone()),
4349                MockReadClock,
4350                Some(PersistentShakedexConfig {
4351                    seller_policy: ShakedexSellerPolicy::no_marketplace_fee(),
4352                    transport: PersistentShakescapeTransport::WalletPeers,
4353                }),
4354            )
4355            .expect("compose direct value wallet");
4356
4357        value.unlock(&key).expect("unlock must not synchronize");
4358        let receive = value
4359            .local_receive_target()
4360            .expect("local value receive target after unlock");
4361        assert_eq!(receive.module, ModuleId::Handshake);
4362        assert_eq!(receive.account, value.account_config().account_id);
4363        assert!(receive.display.starts_with("rs1"));
4364        assert_eq!(probe.snapshot_calls.load(Ordering::SeqCst), 0);
4365        assert_eq!(probe.tip_calls.load(Ordering::SeqCst), 0);
4366        assert_eq!(probe.confirmed_calls.load(Ordering::SeqCst), 0);
4367        assert_eq!(probe.mempool_calls.load(Ordering::SeqCst), 0);
4368
4369        probe.fail_synchronization.store(true, Ordering::SeqCst);
4370        assert!(matches!(
4371            value.synchronize(),
4372            Err(MobileWalletError::ServiceFailure {
4373                code: ServiceErrorCode::RuntimeFailure,
4374                ..
4375            })
4376        ));
4377        assert!(
4378            !value
4379                .status()
4380                .expect("status after a rejected value read")
4381                .locked
4382        );
4383
4384        probe.fail_synchronization.store(false, Ordering::SeqCst);
4385        let snapshot = value.synchronize().expect("explicit sync");
4386        assert_eq!(snapshot.balance, Amount::new(WalletAsset::Hns, 0));
4387        assert!(probe.snapshot_calls.load(Ordering::SeqCst) > 1);
4388        assert!(probe.confirmed_calls.load(Ordering::SeqCst) > 0);
4389        assert!(probe.mempool_calls.load(Ordering::SeqCst) > 0);
4390        let synchronized_backend_calls = (
4391            probe.snapshot_calls.load(Ordering::SeqCst),
4392            probe.tip_calls.load(Ordering::SeqCst),
4393            probe.confirmed_calls.load(Ordering::SeqCst),
4394            probe.mempool_calls.load(Ordering::SeqCst),
4395        );
4396        value
4397            .recover_shakedex_after_reconcile()
4398            .expect("market recovery after explicit verified sync");
4399        assert_eq!(
4400            (
4401                probe.snapshot_calls.load(Ordering::SeqCst),
4402                probe.tip_calls.load(Ordering::SeqCst),
4403                probe.confirmed_calls.load(Ordering::SeqCst),
4404                probe.mempool_calls.load(Ordering::SeqCst),
4405            ),
4406            (
4407                synchronized_backend_calls.0 + 1,
4408                synchronized_backend_calls.1,
4409                synchronized_backend_calls.2,
4410                synchronized_backend_calls.3,
4411            ),
4412            "marketplace recovery refreshes its funding scope without another chain sync",
4413        );
4414    }
4415
4416    #[test]
4417    fn value_send_preparation_uses_the_staged_verified_snapshot() {
4418        let directory = private_tempdir();
4419        let path = directory.path().join("value-send-staged-snapshot.sqlite3");
4420        let key = MobileDatabaseKey::new([0x8c; MOBILE_DATABASE_KEY_BYTES]).expect("database key");
4421        let creation = MobileWalletController::create(
4422            &path,
4423            &key,
4424            MobilePlatform::Android,
4425            HnsBootstrapPolicy::new(HnsNetwork::Regtest, 0),
4426        )
4427        .expect("create value wallet");
4428        let (controller, _recovery) = creation.into_parts();
4429        let probe = Arc::new(MockReadProbe::default());
4430        let mut value = controller
4431            .into_hns_value_with_clock(
4432                &key,
4433                MockReadBackend::new(probe.clone()),
4434                MockReadClock,
4435                None,
4436            )
4437            .expect("compose value wallet");
4438        value.unlock(&key).expect("unlock value wallet");
4439        let recipient = value
4440            .local_receive_target()
4441            .expect("derive exact local payment target")
4442            .display;
4443
4444        // This empty fixture cannot fund a transaction, but preparation must
4445        // first complete the staged verified read.  The old legacy
4446        // reconciliation queried `get_chain_tip`; that path can self-deadlock
4447        // when the backend is the wallet-owned embedded light index.
4448        assert!(
4449            value
4450                .prepare_value_action(MobileHnsValueIntent::Send {
4451                    recipient,
4452                    amount: BaseUnits::new(1),
4453                    maximum_fee: BaseUnits::new(1),
4454                })
4455                .is_err()
4456        );
4457        assert!(probe.snapshot_calls.load(Ordering::SeqCst) > 0);
4458        assert_eq!(probe.tip_calls.load(Ordering::SeqCst), 0);
4459        assert!(probe.confirmed_calls.load(Ordering::SeqCst) > 0);
4460        assert!(probe.mempool_calls.load(Ordering::SeqCst) > 0);
4461    }
4462
4463    #[test]
4464    fn flagged_value_account_reopens_for_lifecycle_uses_value_composition() {
4465        let directory = private_tempdir();
4466        let path = directory.path().join("flagged-lifecycle.sqlite3");
4467        let key = MobileDatabaseKey::new([0x8a; MOBILE_DATABASE_KEY_BYTES]).expect("database key");
4468        let creation = MobileWalletController::create(
4469            &path,
4470            &key,
4471            MobilePlatform::Android,
4472            HnsBootstrapPolicy::new(HnsNetwork::Regtest, 0),
4473        )
4474        .expect("create lifecycle controller");
4475        let (controller, _recovery_phrase) = creation.into_parts();
4476        drop(controller);
4477
4478        let mut store = WalletStore::open(&path).expect("open store for release-policy fixture");
4479        let passphrase = key.store_passphrase();
4480        store
4481            .unlock(passphrase.as_str())
4482            .expect("unlock release-policy fixture");
4483        let mut accounts = store
4484            .wallet_accounts::<HnsAccountRecord>(MAX_MOBILE_WALLET_ACCOUNTS)
4485            .expect("load exact account");
4486        assert_eq!(accounts.len(), 1);
4487        let mut stored = accounts.pop().expect("one account");
4488        stored.value.config.value_operations_enabled = true;
4489        stored.value.config.settlement_enabled = true;
4490        store
4491            .save_wallet_account(&stored.id, stored.revision, &stored.value, 1_800_000_001)
4492            .expect("persist qualified-policy-shaped fixture");
4493        store.lock();
4494        drop(store);
4495
4496        let lifecycle = MobileWalletController::open(&path, &key, MobilePlatform::Android)
4497            .expect("flagged account remains lifecycle-reopenable");
4498        assert!(lifecycle.account_config().value_operations_enabled);
4499        assert!(lifecycle.account_config().settlement_enabled);
4500        let probe = Arc::new(MockReadProbe::default());
4501        assert!(matches!(
4502            lifecycle.into_hns_reads_with_clock(MockReadBackend::new(probe), MockReadClock),
4503            Err(MobileWalletError::Hns(
4504                HnsWalletError::RuntimeIntegrationUnavailable
4505            ))
4506        ));
4507
4508        let lifecycle = MobileWalletController::open(&path, &key, MobilePlatform::Ios)
4509            .expect("reopen after rejected ordinary-read composition");
4510        let probe = Arc::new(MockReadProbe::default());
4511        let mut value = lifecycle
4512            .into_hns_value_with_clock(&key, MockReadBackend::new(probe), MockReadClock, None)
4513            .expect("qualified value composition accepts the persisted value flags");
4514        value.lock().expect("relock qualified value controller");
4515
4516        let mut reopened = MobileWalletController::open(&path, &key, MobilePlatform::Android)
4517            .expect("qualified value activation leaves wallet safely reopenable");
4518        assert!(reopened.status().expect("locked lifecycle status").locked);
4519    }
4520
4521    #[test]
4522    fn native_value_intents_insert_the_exact_account_and_tokens_are_canonical() {
4523        let account = AccountId::new([0x42; 16]);
4524        let (kind, method, params) = MobileHnsValueIntent::Send {
4525            recipient: "rs1qexample".to_owned(),
4526            amount: BaseUnits::new(12_345),
4527            maximum_fee: BaseUnits::new(678),
4528        }
4529        .into_provider_parts(account)
4530        .expect("valid send intent");
4531        assert_eq!(kind, ApprovalKind::Send);
4532        assert_eq!(method, ProviderMethod::HnsSend);
4533        assert_eq!(params["account"], json!(account));
4534        assert_eq!(params["recipient"], "rs1qexample");
4535        assert_eq!(params["amount"], json!(BaseUnits::new(12_345)));
4536        assert_eq!(params["maximumFee"], json!(BaseUnits::new(678)));
4537        assert!(params.get("origin").is_none());
4538
4539        let token = [0xab; MOBILE_ACTION_TOKEN_BYTES];
4540        let encoded = lowercase_hex(&token);
4541        assert!(mobile_action_token_matches(&token, &encoded));
4542        assert!(!mobile_action_token_matches(
4543            &token,
4544            &encoded.to_uppercase()
4545        ));
4546        assert!(!mobile_action_token_matches(
4547            &token,
4548            &encoded[..encoded.len() - 2]
4549        ));
4550        let mut changed = encoded.into_bytes();
4551        changed[17] = b'0';
4552        assert!(!mobile_action_token_matches(
4553            &token,
4554            std::str::from_utf8(&changed).expect("ASCII token")
4555        ));
4556    }
4557
4558    #[test]
4559    fn mobile_name_resource_editor_encodes_supported_records() {
4560        let raw = parse_mobile_name_resource(
4561            r#"
4562                # Delegation and service records
4563                NS NS1.Example.
4564                GLUE4 ns1.example. 192.0.2.1
4565                GLUE6 ns1.example. 2001:db8::1
4566                SYNTH4 198.51.100.2
4567                SYNTH6 2001:db8::2
4568                DS 12345 8 2 a1b2c3d4
4569                TXT "wallet record with spaces"
4570            "#,
4571        )
4572        .expect("supported presentation forms");
4573        let decoded = hns_covenants::Resource::decode(&raw).expect("valid HSD resource");
4574        assert_eq!(decoded.records().len(), 7);
4575        assert_eq!(decoded.as_bytes(), raw);
4576        assert!(raw.windows(b"ns1".len()).any(|window| window == b"ns1"));
4577        assert!(!raw.windows(b"NS1".len()).any(|window| window == b"NS1"));
4578    }
4579
4580    #[test]
4581    fn mobile_name_resource_editor_supports_clear_and_exact_hex() {
4582        assert_eq!(
4583            parse_mobile_name_resource("  # clear all records\n")
4584                .expect("empty editor clears the resource"),
4585            Vec::<u8>::new()
4586        );
4587        assert_eq!(
4588            parse_mobile_name_resource("hex: 00 04 c0 00 02 01")
4589                .expect("valid exact encoded resource"),
4590            vec![0, 4, 192, 0, 2, 1]
4591        );
4592        assert!(parse_mobile_name_resource("hex: ff").is_err());
4593        assert!(parse_mobile_name_resource("TXT \"unterminated").is_err());
4594        assert!(parse_mobile_name_resource("UNKNOWN value").is_err());
4595    }
4596
4597    #[test]
4598    fn native_value_and_query_wire_vocabulary_is_closed_camel_case() {
4599        let transfer = MobileHnsValueIntent::TransferName {
4600            name: "example".to_owned(),
4601            recipient: "rs1qrecipient".to_owned(),
4602            maximum_fee: BaseUnits::new(123),
4603        };
4604        let encoded = serde_json::to_value(&transfer).expect("serialize native transfer");
4605        assert_eq!(encoded["action"], "transferName");
4606        assert_eq!(encoded["maximumFee"], "123");
4607        assert!(encoded.get("maximum_fee").is_none());
4608        assert_eq!(
4609            serde_json::from_value::<MobileHnsValueIntent>(encoded)
4610                .expect("deserialize native transfer"),
4611            transfer
4612        );
4613
4614        let acceptance = MobileHnsValueIntent::AcceptOffer {
4615            listing_id: "22".repeat(32),
4616            maximum_fee: BaseUnits::new(100_000),
4617            automatic_finalize_maximum_fee: Some(BaseUnits::new(100_000)),
4618        };
4619        let encoded = serde_json::to_value(&acceptance).expect("serialize native acceptance");
4620        assert_eq!(encoded["action"], "acceptOffer");
4621        assert_eq!(encoded["maximumFee"], "100000");
4622        assert_eq!(encoded["automaticFinalizeMaximumFee"], "100000");
4623        assert_eq!(
4624            serde_json::from_value::<MobileHnsValueIntent>(encoded)
4625                .expect("deserialize native acceptance"),
4626            acceptance
4627        );
4628
4629        let query = MobileShakedexQuery::GetSession {
4630            session_id: "11".repeat(32),
4631        };
4632        let encoded = serde_json::to_value(&query).expect("serialize native query");
4633        assert_eq!(encoded["query"], "getSession");
4634        assert_eq!(encoded["sessionId"], "11".repeat(32));
4635        assert!(encoded.get("session_id").is_none());
4636        assert!(
4637            serde_json::from_value::<MobileShakedexQuery>(json!({
4638                "query": "getSession",
4639                "sessionId": "11".repeat(32),
4640                "account": "caller-controlled"
4641            }))
4642            .is_err()
4643        );
4644        let my_offers = MobileShakedexQuery::ListMyOffers {
4645            cursor: None,
4646            limit: Some(16),
4647        };
4648        let encoded = serde_json::to_value(&my_offers).expect("serialize seller query");
4649        assert_eq!(encoded["query"], "listMyOffers");
4650        assert_eq!(encoded["limit"], 16);
4651        assert!(encoded.get("account").is_none());
4652        assert!(
4653            serde_json::from_value::<MobileShakedexQuery>(json!({
4654                "query": "listMyOffers",
4655                "cursor": null,
4656                "limit": 16,
4657                "account": "caller-controlled"
4658            }))
4659            .is_err()
4660        );
4661        let get_offer = MobileShakedexQuery::GetOffer {
4662            listing_id: "22".repeat(32),
4663        };
4664        let encoded = serde_json::to_value(&get_offer).expect("serialize offer lookup");
4665        assert_eq!(encoded["query"], "getOffer");
4666        assert_eq!(encoded["listingId"], "22".repeat(32));
4667        assert!(encoded.get("account").is_none());
4668    }
4669
4670    #[test]
4671    fn injected_hns_reads_are_coherent_serializable_and_fresh() {
4672        let directory = private_tempdir();
4673        let path = directory.path().join("read-controller.sqlite3");
4674        let key = MobileDatabaseKey::new([0x91; MOBILE_DATABASE_KEY_BYTES]).expect("database key");
4675        let policy = HnsBootstrapPolicy::new(HnsNetwork::Regtest, 0);
4676        let creation = MobileWalletController::create(&path, &key, MobilePlatform::Android, policy)
4677            .expect("create lifecycle controller");
4678        let (controller, _recovery_phrase) = creation.into_parts();
4679        let expected_account = controller.account_config().account_id;
4680        let probe = Arc::new(MockReadProbe::default());
4681        let mut reads = controller
4682            .into_hns_reads_with_clock(MockReadBackend::new(probe.clone()), MockReadClock)
4683            .expect("compose synchronized HNS reads");
4684
4685        let status = reads.status().expect("locked read status");
4686        assert!(status.locked);
4687        assert_eq!(status.active_wallet, None);
4688        assert_eq!(
4689            status.enabled_modules,
4690            BTreeSet::from([ModuleId::Handshake])
4691        );
4692        assert!(!status.mainnet_settlement_enabled);
4693
4694        reads.unlock(&key).expect("unlock read controller");
4695        assert!(!reads.account_config().value_operations_enabled);
4696        assert!(!reads.account_config().settlement_enabled);
4697        let accounts = reads.accounts().expect("read account");
4698        assert_eq!(accounts.len(), 1);
4699        assert_eq!(accounts[0].account_id, expected_account);
4700        assert_eq!(accounts[0].receive_display, None);
4701
4702        let local_receive = reads
4703            .local_receive_target()
4704            .expect("local payment receive target after unlock");
4705        assert_eq!(local_receive.module, ModuleId::Handshake);
4706        assert_eq!(local_receive.account, expected_account);
4707        assert!(local_receive.display.starts_with("rs1"));
4708        assert_eq!(probe.snapshot_calls.load(Ordering::SeqCst), 0);
4709        assert_eq!(probe.tip_calls.load(Ordering::SeqCst), 0);
4710        assert_eq!(probe.confirmed_calls.load(Ordering::SeqCst), 0);
4711        assert_eq!(probe.mempool_calls.load(Ordering::SeqCst), 0);
4712
4713        let before = probe.snapshot_calls.load(Ordering::SeqCst);
4714        let snapshot = reads.synchronize().expect("synchronized mobile snapshot");
4715        assert_eq!(probe.snapshot_calls.load(Ordering::SeqCst), before + 1);
4716        assert_eq!(snapshot.balance, Amount::new(WalletAsset::Hns, 0));
4717        assert_eq!(snapshot.receive_target.module, ModuleId::Handshake);
4718        assert_eq!(snapshot.receive_target.account, expected_account);
4719        assert!(snapshot.receive_target.display.starts_with("rs1"));
4720        assert_eq!(snapshot.name_receive_target.module, ModuleId::Handshake);
4721        assert_eq!(snapshot.name_receive_target.account, expected_account);
4722        assert!(snapshot.name_receive_target.display.starts_with("rs1"));
4723        assert_eq!(
4724            snapshot.name_receive_target.display,
4725            snapshot.receive_target.display
4726        );
4727        assert!(snapshot.transaction_history.is_empty());
4728        assert!(snapshot.known_names.is_empty());
4729        assert!(snapshot.finalize_notices.is_empty());
4730        assert_eq!(snapshot.known_name_count, 0);
4731        assert!(snapshot.known_names_complete);
4732        assert_eq!(
4733            reads
4734                .known_name_page(0, MAX_MOBILE_HNS_NAME_PAGE)
4735                .expect("empty authenticated name page"),
4736            MobileHnsNamePage {
4737                offset: 0,
4738                total: 0,
4739                names: Vec::new(),
4740                has_more: false,
4741            }
4742        );
4743        assert_eq!(
4744            snapshot.module_status,
4745            SyncStatus {
4746                phase: SyncPhase::Ready,
4747                validated_height: MOCK_READ_HEIGHT,
4748                scanned_height: MOCK_READ_HEIGHT,
4749                target_height: Some(MOCK_READ_HEIGHT),
4750                last_error: None,
4751            }
4752        );
4753
4754        let encoded = serde_json::to_value(&snapshot).expect("serialize mobile HNS snapshot");
4755        let fields = encoded
4756            .as_object()
4757            .expect("snapshot object")
4758            .keys()
4759            .map(String::as_str)
4760            .collect::<BTreeSet<_>>();
4761        assert_eq!(
4762            fields,
4763            BTreeSet::from([
4764                "balance",
4765                "finalizeNotices",
4766                "knownNameCount",
4767                "knownNames",
4768                "knownNamesComplete",
4769                "moduleStatus",
4770                "nameReceiveTarget",
4771                "receiveTarget",
4772                "transactionHistory",
4773            ])
4774        );
4775        let name_target_fields = encoded["nameReceiveTarget"]
4776            .as_object()
4777            .expect("name receive target object")
4778            .keys()
4779            .map(String::as_str)
4780            .collect::<BTreeSet<_>>();
4781        assert_eq!(
4782            name_target_fields,
4783            BTreeSet::from(["account", "derivation_index", "display", "module"])
4784        );
4785        assert_eq!(
4786            serde_json::from_value::<MobileHnsReadSnapshot>(encoded.clone())
4787                .expect("deserialize mobile HNS snapshot"),
4788            snapshot
4789        );
4790        let mut legacy_shape = encoded;
4791        legacy_shape
4792            .as_object_mut()
4793            .expect("legacy snapshot object")
4794            .remove("nameReceiveTarget");
4795        assert!(serde_json::from_value::<MobileHnsReadSnapshot>(legacy_shape).is_err());
4796
4797        let before = probe.snapshot_calls.load(Ordering::SeqCst);
4798        assert_eq!(
4799            reads.balance().expect("fresh balance"),
4800            Amount::new(WalletAsset::Hns, 0)
4801        );
4802        assert_eq!(probe.snapshot_calls.load(Ordering::SeqCst), before + 1);
4803        assert_eq!(
4804            reads
4805                .receive_target()
4806                .expect("fresh receive target")
4807                .account,
4808            expected_account
4809        );
4810        let fresh_name_target = reads
4811            .name_receive_target()
4812            .expect("fresh name receive target");
4813        assert_eq!(fresh_name_target, snapshot.name_receive_target);
4814        assert_eq!(fresh_name_target.display, snapshot.receive_target.display);
4815        assert!(
4816            reads
4817                .transaction_history()
4818                .expect("fresh transaction history")
4819                .is_empty()
4820        );
4821        assert!(reads.known_names().expect("fresh known names").is_empty());
4822        assert_eq!(
4823            reads.module_status().expect("fresh module status").phase,
4824            SyncPhase::Ready
4825        );
4826        assert_eq!(probe.snapshot_calls.load(Ordering::SeqCst), before + 6);
4827        assert_eq!(probe.tip_calls.load(Ordering::SeqCst), 0);
4828        assert!(probe.confirmed_calls.load(Ordering::SeqCst) > 0);
4829        assert!(probe.incoming_calls.load(Ordering::SeqCst) > 0);
4830        assert!(probe.mempool_calls.load(Ordering::SeqCst) > 0);
4831        assert_eq!(probe.evidence_calls.load(Ordering::SeqCst), 0);
4832        assert_eq!(probe.forbidden_calls.load(Ordering::SeqCst), 0);
4833        reads.lock().expect("lock read controller");
4834
4835        drop(reads);
4836        let reopen_probe = Arc::new(MockReadProbe::default());
4837        let mut reopened = MobileHnsReadController::open_with_clock(
4838            &path,
4839            &key,
4840            MobilePlatform::Ios,
4841            MockReadBackend::new(reopen_probe.clone()),
4842            MockReadClock,
4843        )
4844        .expect("reopen read controller");
4845        reopened.unlock(&key).expect("unlock reopened reads");
4846        assert_eq!(
4847            reopened
4848                .synchronize()
4849                .expect("reopened synchronized snapshot")
4850                .name_receive_target
4851                .account,
4852            expected_account
4853        );
4854        assert_eq!(reopen_probe.evidence_calls.load(Ordering::SeqCst), 0);
4855        assert_eq!(reopen_probe.forbidden_calls.load(Ordering::SeqCst), 0);
4856    }
4857
4858    #[test]
4859    fn synchronized_read_error_remains_unlocked_for_a_retry() {
4860        let directory = private_tempdir();
4861        let path = directory.path().join("read-failure.sqlite3");
4862        let key = MobileDatabaseKey::new([0x92; MOBILE_DATABASE_KEY_BYTES]).expect("database key");
4863        let creation = MobileWalletController::create(
4864            &path,
4865            &key,
4866            MobilePlatform::Ios,
4867            HnsBootstrapPolicy::new(HnsNetwork::Regtest, 0),
4868        )
4869        .expect("create lifecycle controller");
4870        let (controller, _recovery_phrase) = creation.into_parts();
4871        let probe = Arc::new(MockReadProbe::default());
4872        let mut reads = controller
4873            .into_hns_reads_with_clock(MockReadBackend::new(probe.clone()), MockReadClock)
4874            .expect("compose synchronized reads");
4875        reads.unlock(&key).expect("unlock reads");
4876
4877        probe.fail_synchronization.store(true, Ordering::SeqCst);
4878        assert!(matches!(
4879            reads.balance(),
4880            Err(MobileWalletError::ServiceFailure {
4881                code: ServiceErrorCode::RuntimeFailure,
4882                ..
4883            })
4884        ));
4885        assert!(!reads.status().expect("status after read error").locked);
4886        assert_eq!(probe.evidence_calls.load(Ordering::SeqCst), 0);
4887        assert_eq!(probe.forbidden_calls.load(Ordering::SeqCst), 0);
4888
4889        probe.fail_synchronization.store(false, Ordering::SeqCst);
4890        assert_eq!(
4891            reads.balance().expect("balance after backend recovery"),
4892            Amount::new(WalletAsset::Hns, 0)
4893        );
4894        assert!(probe.incoming_calls.load(Ordering::SeqCst) > 0);
4895    }
4896
4897    #[test]
4898    fn exact_text_name_import_rejects_input_without_poisoning_and_locks_on_runtime_fault() {
4899        let directory = private_tempdir();
4900        let path = directory.path().join("name-import-errors.sqlite3");
4901        let key = MobileDatabaseKey::new([0x93; MOBILE_DATABASE_KEY_BYTES]).expect("database key");
4902        let creation = MobileWalletController::create(
4903            &path,
4904            &key,
4905            MobilePlatform::Android,
4906            HnsBootstrapPolicy::new(HnsNetwork::Regtest, 0),
4907        )
4908        .expect("create lifecycle controller");
4909        let (controller, _recovery_phrase) = creation.into_parts();
4910        let probe = Arc::new(MockReadProbe::default());
4911        let mut reads = controller
4912            .into_hns_reads_with_clock(MockReadBackend::new(probe.clone()), MockReadClock)
4913            .expect("compose name import controller");
4914        reads.unlock(&key).expect("unlock name import controller");
4915
4916        assert!(matches!(
4917            reads.import_name_exact_text(" Alpha"),
4918            Err(MobileWalletError::ServiceFailure {
4919                code: ServiceErrorCode::InvalidRequest,
4920                ..
4921            })
4922        ));
4923        assert!(!reads.status().expect("status after invalid input").locked);
4924        assert_eq!(probe.snapshot_calls.load(Ordering::SeqCst), 0);
4925        assert_eq!(probe.evidence_calls.load(Ordering::SeqCst), 0);
4926
4927        assert!(matches!(
4928            reads.import_name_exact_text("alpha"),
4929            Err(MobileWalletError::ServiceFailure {
4930                code: ServiceErrorCode::RuntimeFailure,
4931                ..
4932            })
4933        ));
4934        assert!(reads.status().expect("status after backend fault").locked);
4935        assert_eq!(probe.snapshot_calls.load(Ordering::SeqCst), 1);
4936        assert_eq!(probe.evidence_calls.load(Ordering::SeqCst), 1);
4937        assert_eq!(probe.forbidden_calls.load(Ordering::SeqCst), 0);
4938    }
4939
4940    #[test]
4941    fn native_import_summary_projection_is_bounded_and_exact() {
4942        let summary = mobile_native_hns_name_summary(NativeHnsNameSummary {
4943            name: "alpha".to_owned(),
4944            name_hash: "271878f8a927b4566ac951fc815b18dfad8d0302d61d11d80cbe15b7a3a056af"
4945                .to_owned(),
4946            proof_height: 99,
4947            resource_status: NativeHnsNameResourceStatus::CanonicalDecoded,
4948            ownership_status: NativeHnsNameOwnershipStatus::IncomingTransfer,
4949            registered: Some(true),
4950            expired: Some(false),
4951            canonical_state: None,
4952            raw_resource: None,
4953        })
4954        .expect("mobile native name summary");
4955        assert_eq!(summary.name, "alpha");
4956        assert_eq!(
4957            summary.ownership_status,
4958            MobileHnsNameOwnershipStatus::IncomingTransfer
4959        );
4960        let encoded = serde_json::to_value(summary).expect("serialize minimized import result");
4961        assert_eq!(
4962            encoded
4963                .as_object()
4964                .expect("summary object")
4965                .keys()
4966                .map(String::as_str)
4967                .collect::<BTreeSet<_>>(),
4968            BTreeSet::from([
4969                "expired",
4970                "canonicalState",
4971                "name",
4972                "nameHash",
4973                "ownershipStatus",
4974                "proofHeight",
4975                "rawResourceHex",
4976                "registered",
4977                "resourceRecordCount",
4978                "resourceStatus",
4979            ])
4980        );
4981    }
4982
4983    #[test]
4984    fn known_name_projection_is_bounded_typed_and_serializable() {
4985        let known_name = KnownName {
4986            name: b"alpha".to_vec(),
4987            name_hash: [
4988                0x27, 0x18, 0x78, 0xf8, 0xa9, 0x27, 0xb4, 0x56, 0x6a, 0xc9, 0x51, 0xfc, 0x81, 0x5b,
4989                0x18, 0xdf, 0xad, 0x8d, 0x03, 0x02, 0xd6, 0x1d, 0x11, 0xd8, 0x0c, 0xbe, 0x15, 0xb7,
4990                0xa3, 0xa0, 0x56, 0xaf,
4991            ],
4992            proof_height: 99,
4993            unbound_proof_owner_outpoint: None,
4994            unbound_current_owner_outpoint: None,
4995            proof_state: Some(vec![1, 2, 3]),
4996            current_state: Some(vec![4, 5, 6]),
4997            canonical_proof_state: None,
4998            canonical_current_state: Some(CanonicalNameStateSummary {
4999                owner_outpoint: None,
5000                value: 1,
5001                highest: 2,
5002                start_height: 3,
5003                renewal_height: 4,
5004                transfer_height: 0,
5005                revoked_height: 0,
5006                claimed_height: 0,
5007                renewals: 1,
5008                registered: true,
5009                expired: false,
5010                weak: false,
5011            }),
5012            current_raw_resource: Some(vec![7, 8, 9]),
5013            resource_status: NameResourceStatus::CanonicalDecoded,
5014            ownership_status: NameOwnershipStatus::WalletContextUnavailable,
5015        };
5016        let summary = mobile_hns_name_summary(&known_name).expect("minimized name summary");
5017        assert_eq!(summary.name, "alpha");
5018        assert_eq!(summary.name_hash.len(), 64);
5019        assert_eq!(
5020            summary.resource_status,
5021            MobileHnsNameResourceStatus::CanonicalDecoded
5022        );
5023        assert_eq!(
5024            summary.ownership_status,
5025            MobileHnsNameOwnershipStatus::WalletContextUnavailable
5026        );
5027        assert_eq!(summary.registered, Some(true));
5028        assert_eq!(summary.expired, Some(false));
5029        assert_eq!(summary.raw_resource_hex.as_deref(), Some("070809"));
5030        assert_eq!(summary.resource_record_count, None);
5031        assert_eq!(
5032            summary.canonical_state.as_ref().map(|state| state.renewals),
5033            Some(1)
5034        );
5035
5036        let encoded = serde_json::to_string(&summary).expect("serialize name summary");
5037        for forbidden in ["proofState", "currentState", "ownerOutpoint", "derivation"] {
5038            assert!(!encoded.contains(forbidden));
5039        }
5040        assert_eq!(
5041            serde_json::from_str::<MobileHnsNameSummary>(&encoded)
5042                .expect("deserialize name summary"),
5043            summary
5044        );
5045
5046        let mut malformed = known_name.clone();
5047        malformed.name = vec![0xff];
5048        assert!(mobile_hns_name_summary(&malformed).is_err());
5049        let mut oversized_height = known_name;
5050        oversized_height.proof_height = MAX_JAVASCRIPT_SAFE_INTEGER + 1;
5051        assert!(mobile_hns_name_summary(&oversized_height).is_err());
5052    }
5053
5054    #[test]
5055    fn known_name_pages_are_bounded_ordered_and_complete_without_resync() {
5056        let names = (0..130)
5057            .map(|index| MobileHnsNameSummary {
5058                name: format!("name{index:04}"),
5059                name_hash: format!("{index:064x}"),
5060                proof_height: 500,
5061                resource_status: MobileHnsNameResourceStatus::Empty,
5062                ownership_status: MobileHnsNameOwnershipStatus::WalletOwned,
5063                registered: Some(true),
5064                expired: Some(false),
5065                canonical_state: None,
5066                raw_resource_hex: None,
5067                resource_record_count: None,
5068            })
5069            .collect::<Vec<_>>();
5070        let first = mobile_hns_name_page(&names, 0, 64).expect("first page");
5071        let second = mobile_hns_name_page(&names, 64, 64).expect("second page");
5072        let final_page = mobile_hns_name_page(&names, 128, 64).expect("final page");
5073        assert_eq!((first.offset, first.total, first.names.len()), (0, 130, 64));
5074        assert!(first.has_more);
5075        assert_eq!((second.offset, second.names.len()), (64, 64));
5076        assert!(second.has_more);
5077        assert_eq!((final_page.offset, final_page.names.len()), (128, 2));
5078        assert!(!final_page.has_more);
5079        assert!(mobile_hns_name_page(&names, 0, 65).is_err());
5080        assert!(mobile_hns_name_page(&names, 131, 1).is_err());
5081    }
5082
5083    #[test]
5084    fn trusted_mobile_name_receive_alias_revalidates_the_canonical_target() {
5085        let account = AccountId::new([0x31; 16]);
5086        let receive = ReceiveTarget {
5087            module: ModuleId::Handshake,
5088            account,
5089            display: "rs1qcoin".to_owned(),
5090            derivation_index: 2,
5091        };
5092        let name = HnsNameReceiveTarget {
5093            module: ModuleId::Handshake,
5094            account,
5095            display: receive.display.clone(),
5096            derivation_index: receive.derivation_index,
5097        };
5098        validate_mobile_hns_receive_targets(account, &receive, &name)
5099            .expect("valid trusted native targets");
5100
5101        for invalid in [
5102            HnsNameReceiveTarget {
5103                module: ModuleId::Bitcoin,
5104                ..name.clone()
5105            },
5106            HnsNameReceiveTarget {
5107                account: AccountId::new([0x32; 16]),
5108                ..name.clone()
5109            },
5110            HnsNameReceiveTarget {
5111                display: String::new(),
5112                ..name.clone()
5113            },
5114            HnsNameReceiveTarget {
5115                display: "rs1qname\n".to_owned(),
5116                ..name.clone()
5117            },
5118            HnsNameReceiveTarget {
5119                display: "rs1qn\u{e9}me".to_owned(),
5120                ..name.clone()
5121            },
5122            HnsNameReceiveTarget {
5123                derivation_index: receive.derivation_index + 1,
5124                ..name.clone()
5125            },
5126        ] {
5127            assert!(validate_mobile_hns_receive_targets(account, &receive, &invalid).is_err());
5128        }
5129        for invalid_receive in [
5130            ReceiveTarget {
5131                module: ModuleId::Bitcoin,
5132                ..receive.clone()
5133            },
5134            ReceiveTarget {
5135                account: AccountId::new([0x32; 16]),
5136                ..receive
5137            },
5138        ] {
5139            assert!(validate_mobile_hns_receive_targets(account, &invalid_receive, &name).is_err());
5140        }
5141    }
5142
5143    #[test]
5144    fn open_rejects_an_account_only_partial_bootstrap() {
5145        let directory = private_tempdir();
5146        let path = directory.path().join("partial.sqlite3");
5147        let key = MobileDatabaseKey::new([0xef; MOBILE_DATABASE_KEY_BYTES]).expect("database key");
5148        let policy = HnsBootstrapPolicy::new(HnsNetwork::Regtest, 456);
5149        let bootstrap = HnsWalletBootstrap::generate(policy).expect("bootstrap");
5150        let account = bootstrap.account_record().clone();
5151        let mut account_id = [0_u8; 32];
5152        account_id[..16].copy_from_slice(account.config.wallet_id.as_bytes());
5153        account_id[16..].copy_from_slice(account.config.account_id.as_bytes());
5154
5155        let passphrase = key.store_passphrase();
5156        let mut store = WalletStore::create(&path, passphrase.as_str()).expect("create partial DB");
5157        store
5158            .save_entity(EntityKind::WalletAccount, &account_id, 0, &account, 1)
5159            .expect("save account without recovery seed");
5160        store.lock();
5161        drop(store);
5162
5163        let error = match MobileWalletController::open(&path, &key, MobilePlatform::Android) {
5164            Ok(_) => panic!("account-only bootstrap must be rejected"),
5165            Err(error) => error,
5166        };
5167        assert!(matches!(
5168            error,
5169            MobileWalletError::Store(StoreError::BootstrapConflict)
5170        ));
5171    }
5172}