Skip to main content

hns_wallet_ffi/
lib.rs

1#![doc = "Versioned, framed, secret-minimizing private wallet service ABI."]
2#![forbid(unsafe_code)]
3
4use std::collections::BTreeSet;
5
6use hns_covenants::{hash_name, validate_name};
7use hns_wallet_types::{
8    AccountId, Amount, ApprovalKind, BaseUnits, BrowserRuntimeSessionId, FinalityModel,
9    HostAuthorityHandleId, HostSessionId, ModuleId, PROVIDER_METHOD_WIRE_NAMES,
10    PermissionCapability, ProviderApprovalId, ProviderAuthorityFingerprint, ProviderRequestId,
11    ReceiveTarget, SyncStatus, TransactionSummary, WalletAsset, WalletId, WalletServiceSessionId,
12    WalletSessionId, WorkflowId,
13};
14use serde::{Deserialize, Serialize};
15use serde_json::Value;
16use thiserror::Error;
17use zeroize::Zeroizing;
18
19pub const WALLET_ABI_VERSION: u16 = 2;
20pub const LENGTH_PREFIX_BYTES: usize = 4;
21pub const MAX_ABI_FRAME_BYTES: usize = 1_048_576;
22pub const MAX_PROVIDER_REQUEST_BYTES: usize = 65_536;
23pub const MAX_PROVIDER_RESULT_BYTES: usize = 262_144;
24pub const MAX_PROVIDER_EVENT_BYTES: usize = 65_536;
25pub const MAX_APPROVAL_FRAME_BYTES: usize = 16_384;
26pub const MAX_APPROVAL_LIFETIME_MS: u64 = 90_000;
27pub const MAX_PASSPHRASE_BYTES: usize = 1_024;
28pub const MAX_RECOVERY_PHRASE_BYTES: usize = 1_024;
29pub const MAX_METHOD_BYTES: usize = 96;
30pub const MAX_ORIGIN_BYTES: usize = 512;
31pub const MAX_PUBLIC_STRING_BYTES: usize = 4_096;
32pub const MAX_PUBLIC_ITEMS: usize = 128;
33pub const MAX_HNS_NAME_DISCLOSURES: usize = 64;
34pub const MAX_HNS_NAME_BYTES: usize = 63;
35pub const MAX_FAILURE_MESSAGE_BYTES: usize = 1_024;
36pub const PROVIDER_SCHEMA_VERSION: u16 = 1;
37pub const APPROVAL_SCHEMA_VERSION: u16 = 3;
38pub const MAX_PROVIDER_METHODS: usize = PROVIDER_METHOD_WIRE_NAMES.len();
39
40#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
41#[serde(rename_all = "camelCase")]
42pub enum HostPlatform {
43    Android,
44    Ios,
45    ChromiumNativeHost,
46}
47
48#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
49#[serde(rename_all = "camelCase")]
50pub enum ServiceCapability {
51    CanonicalFraming,
52    RestartIsolation,
53    OpaqueAuthorityRegistry,
54    PersistentPermissions,
55    StructuredApprovals,
56    TypedEvents,
57    WalletOperations,
58    HnsReadOperationsV1,
59    HnsWalletAuthorityContextV1,
60    /// Exact native/provider HNS send plus TRANSFER/FINALIZE protocol.
61    HnsValueOperationsV1,
62    /// Exact Shakescape V1 fixed-price board and Shakedex value protocol.
63    ShakescapeShakedexV1,
64    ProviderDispatch,
65    ValueMovement,
66    BrowserIntegration,
67}
68
69/// Canonical Handshake network identity used by the native-only wallet
70/// authority-context operation. Simnet is intentionally absent because the
71/// browser authority broker admits only production, public test, and local
72/// regression networks.
73#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
74#[serde(rename_all = "lowercase")]
75pub enum WalletHandshakeNetwork {
76    Mainnet,
77    Testnet,
78    Regtest,
79}
80
81impl WalletHandshakeNetwork {
82    /// Return the canonical Handshake wire magic for this network.
83    pub const fn magic(self) -> u32 {
84        match self {
85            Self::Mainnet => 0x5b6e_f2d3,
86            Self::Testnet => 0xb152_0dd2,
87            Self::Regtest => 0xae38_95cf,
88        }
89    }
90}
91
92#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
93#[serde(rename_all = "camelCase")]
94pub enum ProviderNamespace {
95    Hns,
96    Icann,
97}
98
99#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
100#[serde(deny_unknown_fields, rename_all = "camelCase")]
101pub struct ServiceLimits {
102    pub outer_frame_bytes: u32,
103    pub provider_request_bytes: u32,
104    pub provider_result_bytes: u32,
105    pub provider_event_bytes: u32,
106    pub approval_frame_bytes: u32,
107    pub approval_lifetime_ms: u64,
108}
109
110impl Default for ServiceLimits {
111    fn default() -> Self {
112        Self {
113            outer_frame_bytes: MAX_ABI_FRAME_BYTES as u32,
114            provider_request_bytes: MAX_PROVIDER_REQUEST_BYTES as u32,
115            provider_result_bytes: MAX_PROVIDER_RESULT_BYTES as u32,
116            provider_event_bytes: MAX_PROVIDER_EVENT_BYTES as u32,
117            approval_frame_bytes: MAX_APPROVAL_FRAME_BYTES as u32,
118            approval_lifetime_ms: MAX_APPROVAL_LIFETIME_MS,
119        }
120    }
121}
122
123#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
124#[serde(deny_unknown_fields, rename_all = "camelCase")]
125pub struct HostHello {
126    pub protocol_version: u16,
127    pub platform: HostPlatform,
128    pub host_session_id: HostSessionId,
129    pub restart_generation: u64,
130}
131
132#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
133#[serde(deny_unknown_fields, rename_all = "camelCase")]
134pub struct ServiceHello {
135    pub protocol_version: u16,
136    pub platform: HostPlatform,
137    pub host_session_id: HostSessionId,
138    pub service_session_id: WalletServiceSessionId,
139    pub restart_generation: u64,
140    pub capabilities: BTreeSet<ServiceCapability>,
141    pub limits: ServiceLimits,
142}
143
144#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
145#[serde(deny_unknown_fields, rename_all = "camelCase")]
146pub struct SessionEnvelope<T> {
147    pub protocol_version: u16,
148    pub host_session_id: HostSessionId,
149    pub service_session_id: WalletServiceSessionId,
150    pub restart_generation: u64,
151    pub channel_sequence: u64,
152    pub request_id: ProviderRequestId,
153    pub body: T,
154}
155
156#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
157#[serde(deny_unknown_fields, rename_all = "camelCase")]
158pub struct HostAuthorityFacts {
159    pub origin: String,
160    pub namespace: ProviderNamespace,
161    pub runtime_session_id: BrowserRuntimeSessionId,
162    pub runtime_generation: u64,
163    pub policy_generation: u64,
164    pub navigation_generation: u64,
165    pub decision_fingerprint: ProviderAuthorityFingerprint,
166    pub valid_until_unix_ms: u64,
167}
168
169#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
170#[serde(rename_all = "camelCase")]
171pub enum ApprovalDecision {
172    Approve,
173    Reject,
174}
175
176#[derive(Debug, PartialEq, Serialize, Deserialize)]
177#[serde(
178    tag = "operation",
179    rename_all = "camelCase",
180    rename_all_fields = "camelCase",
181    deny_unknown_fields
182)]
183pub enum ServiceRequest {
184    RegisterAuthority {
185        authority_handle: HostAuthorityHandleId,
186        authority: HostAuthorityFacts,
187    },
188    ReplaceAuthority {
189        authority_handle: HostAuthorityHandleId,
190        expected_authority_revision: u64,
191        authority: HostAuthorityFacts,
192    },
193    RevokeAuthority {
194        authority_handle: HostAuthorityHandleId,
195        expected_authority_revision: u64,
196    },
197    ProviderCapabilities {
198        authority_handle: HostAuthorityHandleId,
199        authority_revision: u64,
200    },
201    ProviderRequest {
202        authority_handle: HostAuthorityHandleId,
203        authority_revision: u64,
204        request_nonce: u64,
205        method: String,
206        #[serde(default)]
207        params: Value,
208    },
209    ApprovalDecision {
210        authority_handle: HostAuthorityHandleId,
211        authority_revision: u64,
212        approval_id: ProviderApprovalId,
213        decision: ApprovalDecision,
214    },
215    Wallet {
216        request: WalletRequest,
217    },
218    WalletAuthority {
219        request: WalletAuthorityContextRequest,
220    },
221}
222
223/// Additive native-only request kept outside [`WalletRequest`] so the exact
224/// six-operation `hnsReadOperationsV1` subset remains unchanged.
225#[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
226#[serde(
227    tag = "operation",
228    rename_all = "camelCase",
229    rename_all_fields = "camelCase",
230    deny_unknown_fields
231)]
232pub enum WalletAuthorityContextRequest {
233    CurrentHnsContext {
234        network: WalletHandshakeNetwork,
235        network_magic: u32,
236        namespace_id: [u8; 16],
237        namespace_lease_generation: u64,
238        module: ModuleId,
239    },
240}
241
242impl std::fmt::Debug for WalletAuthorityContextRequest {
243    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
244        match self {
245            Self::CurrentHnsContext { module, .. } => formatter
246                .debug_struct("CurrentHnsContext")
247                .field("network", &"<bound>")
248                .field("network_magic", &"<bound>")
249                .field("namespace_id", &"<opaque>")
250                .field("namespace_lease_generation", &"<bound>")
251                .field("module", module)
252                .finish(),
253        }
254    }
255}
256
257/// An owned ABI secret that zeroizes its allocation on drop and never prints
258/// its plaintext. It deliberately does not implement `Clone`.
259pub struct SecretString(Zeroizing<String>);
260
261impl SecretString {
262    pub fn new(value: String) -> Self {
263        Self(Zeroizing::new(value))
264    }
265
266    pub fn expose_secret(&self) -> &str {
267        self.0.as_str()
268    }
269}
270
271impl std::fmt::Debug for SecretString {
272    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
273        formatter.write_str("SecretString([REDACTED])")
274    }
275}
276
277impl PartialEq for SecretString {
278    fn eq(&self, other: &Self) -> bool {
279        self.expose_secret() == other.expose_secret()
280    }
281}
282
283impl Eq for SecretString {}
284
285impl Serialize for SecretString {
286    fn serialize<Serializer>(
287        &self,
288        serializer: Serializer,
289    ) -> Result<Serializer::Ok, Serializer::Error>
290    where
291        Serializer: serde::Serializer,
292    {
293        serializer.serialize_str(self.expose_secret())
294    }
295}
296
297impl<'de> Deserialize<'de> for SecretString {
298    fn deserialize<Deserializer>(deserializer: Deserializer) -> Result<Self, Deserializer::Error>
299    where
300        Deserializer: serde::Deserializer<'de>,
301    {
302        String::deserialize(deserializer).map(Self::new)
303    }
304}
305
306#[derive(Debug, Eq, PartialEq, Serialize, Deserialize)]
307#[serde(
308    tag = "operation",
309    rename_all = "camelCase",
310    rename_all_fields = "camelCase",
311    deny_unknown_fields
312)]
313pub enum WalletRequest {
314    Status,
315    CreateWallet {
316        passphrase: SecretString,
317    },
318    RestoreWallet {
319        passphrase: SecretString,
320        recovery_phrase: SecretString,
321    },
322    Unlock {
323        passphrase: SecretString,
324    },
325    Lock,
326    ListAccounts,
327    Balance {
328        module: ModuleId,
329        account: AccountId,
330    },
331    ReceiveTarget {
332        module: ModuleId,
333        account: AccountId,
334    },
335    TransactionHistory {
336        module: ModuleId,
337        account: AccountId,
338    },
339    ModuleStatus {
340        module: ModuleId,
341    },
342    WorkflowStatus {
343        workflow_id: WorkflowId,
344    },
345}
346
347// Keep the payload inline: boxing would change this public Rust ABI wrapper,
348// while serde already bounds and validates the frame at the transport edge.
349#[allow(clippy::large_enum_variant)]
350#[derive(Debug, PartialEq, Serialize, Deserialize)]
351#[serde(
352    tag = "frameType",
353    rename_all = "camelCase",
354    rename_all_fields = "camelCase",
355    deny_unknown_fields
356)]
357pub enum HostFrame {
358    Hello {
359        hello: HostHello,
360    },
361    Request {
362        envelope: SessionEnvelope<ServiceRequest>,
363    },
364}
365
366// Keep the payload inline to preserve the public frame representation.
367#[allow(clippy::large_enum_variant)]
368#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
369#[serde(
370    tag = "frameType",
371    rename_all = "camelCase",
372    rename_all_fields = "camelCase",
373    deny_unknown_fields
374)]
375pub enum ServiceFrame {
376    Hello {
377        hello: ServiceHello,
378    },
379    Response {
380        envelope: SessionEnvelope<ServiceResponse>,
381    },
382    Event {
383        event: ProviderEventEnvelope,
384    },
385}
386
387/// Wallet-owned provider authority binding carried by every private provider
388/// output. Generation zero is valid only while the authority has never had a
389/// permission grant or revocation tombstone.
390#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
391#[serde(deny_unknown_fields, rename_all = "camelCase")]
392pub struct ProviderBinding {
393    pub authority_handle: HostAuthorityHandleId,
394    pub authority_revision: u64,
395    pub wallet_session_id: WalletSessionId,
396    pub permission_generation: u64,
397}
398
399impl ProviderBinding {
400    fn validate(&self) -> Result<(), AbiError> {
401        if self.authority_revision == 0 {
402            return Err(AbiError::InvalidEnvelope);
403        }
404        Ok(())
405    }
406}
407
408#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
409#[serde(deny_unknown_fields, rename_all = "camelCase")]
410pub struct ProviderCapabilitySnapshot {
411    pub provider_schema_version: u16,
412    pub approval_schema_version: u16,
413    pub wallet_session_id: WalletSessionId,
414    pub permission_generation: u64,
415    pub methods: BTreeSet<String>,
416}
417
418impl ProviderCapabilitySnapshot {
419    fn validate(&self, binding: &ProviderBinding) -> Result<(), AbiError> {
420        if self.provider_schema_version != PROVIDER_SCHEMA_VERSION
421            || self.approval_schema_version != APPROVAL_SCHEMA_VERSION
422            || self.wallet_session_id != binding.wallet_session_id
423            || self.permission_generation != binding.permission_generation
424            || self.methods.len() > MAX_PROVIDER_METHODS
425        {
426            return Err(AbiError::InvalidEnvelope);
427        }
428        for method in &self.methods {
429            if method.is_empty()
430                || method.len() > MAX_METHOD_BYTES
431                || !method.is_ascii()
432                || !PROVIDER_METHOD_WIRE_NAMES.contains(&method.as_str())
433            {
434                return Err(AbiError::InvalidEnvelope);
435            }
436        }
437        Ok(())
438    }
439}
440
441// Response variants mirror the stable wire schema and remain inline so callers
442// do not inherit an allocation solely to equalize enum variant sizes.
443#[allow(clippy::large_enum_variant)]
444#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
445#[serde(
446    tag = "result",
447    rename_all = "camelCase",
448    rename_all_fields = "camelCase",
449    deny_unknown_fields
450)]
451pub enum ServiceResponse {
452    AuthorityRegistered {
453        authority_handle: HostAuthorityHandleId,
454        authority_revision: u64,
455    },
456    AuthorityReplaced {
457        authority_handle: HostAuthorityHandleId,
458        authority_revision: u64,
459    },
460    AuthorityRevoked {
461        authority_handle: HostAuthorityHandleId,
462    },
463    ProviderCapabilities {
464        binding: ProviderBinding,
465        capabilities: ProviderCapabilitySnapshot,
466    },
467    ProviderResult {
468        binding: ProviderBinding,
469        value: Value,
470    },
471    ApprovalRequired {
472        approval: ApprovalPrompt,
473    },
474    ApprovalRejected {
475        approval_id: ProviderApprovalId,
476    },
477    Wallet {
478        response: WalletResponse,
479    },
480    WalletAuthority {
481        context: WalletHnsAuthorityContext,
482    },
483    Failure {
484        failure: ServiceFailure,
485    },
486}
487
488/// Wallet-service evidence joined to a trusted native broker lease by the
489/// browser host. This value is not independently an authority and is never a
490/// website/provider projection.
491#[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
492#[serde(deny_unknown_fields, rename_all = "camelCase")]
493pub struct WalletHnsAuthorityContext {
494    pub network: WalletHandshakeNetwork,
495    pub network_magic: u32,
496    pub namespace_id: [u8; 16],
497    pub namespace_lease_generation: u64,
498    pub active_wallet: WalletId,
499    pub account: AccountId,
500    pub wallet_authority_revision: u64,
501    pub account_authority_revision: u64,
502    pub locked: bool,
503    pub module: ModuleId,
504    pub persistent_wallet_confirmed: bool,
505    pub recovery_pending: bool,
506    pub retirement_pending: bool,
507    pub hns_reads_ready: bool,
508}
509
510impl std::fmt::Debug for WalletHnsAuthorityContext {
511    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
512        formatter
513            .debug_struct("WalletHnsAuthorityContext")
514            .field("network", &"<bound>")
515            .field("network_magic", &"<bound>")
516            .field("namespace_id", &"<opaque>")
517            .field("namespace_lease_generation", &"<bound>")
518            .field("active_wallet", &"<opaque>")
519            .field("account", &"<opaque>")
520            .field("wallet_authority_revision", &"<bound>")
521            .field("account_authority_revision", &"<bound>")
522            .field("lifecycle", &"<positive evidence>")
523            .finish()
524    }
525}
526
527#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
528#[serde(
529    tag = "result",
530    rename_all = "camelCase",
531    rename_all_fields = "camelCase",
532    deny_unknown_fields
533)]
534pub enum WalletResponse {
535    Status {
536        status: WalletRuntimeStatus,
537    },
538    WalletCreated {
539        wallet_id: WalletId,
540    },
541    WalletRestored {
542        wallet_id: WalletId,
543    },
544    Locked,
545    Unlocked,
546    Accounts {
547        accounts: Vec<AccountSummary>,
548    },
549    Balance {
550        amount: Amount,
551    },
552    ReceiveTarget {
553        target: ReceiveTarget,
554    },
555    TransactionHistory {
556        transactions: Vec<TransactionSummary>,
557    },
558    ModuleStatus {
559        status: SyncStatus,
560    },
561    Workflow {
562        summary: WorkflowSummary,
563    },
564}
565
566#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
567#[serde(deny_unknown_fields, rename_all = "camelCase")]
568pub struct WalletRuntimeStatus {
569    pub locked: bool,
570    pub active_wallet: Option<WalletId>,
571    pub enabled_modules: BTreeSet<ModuleId>,
572    pub mainnet_settlement_enabled: bool,
573}
574
575#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
576#[serde(deny_unknown_fields, rename_all = "camelCase")]
577pub struct AccountSummary {
578    pub account_id: AccountId,
579    pub module: ModuleId,
580    pub label: String,
581    pub receive_display: Option<String>,
582}
583
584#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
585#[serde(deny_unknown_fields, rename_all = "camelCase")]
586pub struct WorkflowSummary {
587    pub workflow_id: WorkflowId,
588    pub state: String,
589    pub next_action: Option<String>,
590    pub terminal: bool,
591}
592
593#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
594#[serde(rename_all = "camelCase")]
595pub enum ModuleApprovalAction {
596    Enable,
597    Disable,
598}
599
600#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
601#[serde(rename_all = "camelCase")]
602pub enum NameMarketApprovalAction {
603    Create,
604    Cancel,
605    Recover,
606}
607
608#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
609#[serde(rename_all = "camelCase")]
610pub enum DirectOfferApprovalAction {
611    Publish,
612    Cancel,
613}
614
615#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
616#[serde(rename_all = "camelCase")]
617pub enum ApprovalWarning {
618    FeeEstimateMayChange,
619    NameTransferIsIrreversible,
620    RefundRequiresManualAction,
621    SettlementCanBeDelayed,
622}
623
624/// One canonical Handshake name disclosed by a permission prompt. The hash is
625/// lowercase hexadecimal so a trusted UI can render and compare the exact
626/// authority being granted without receiving private wallet/name state.
627#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
628#[serde(deny_unknown_fields, rename_all = "camelCase")]
629pub struct HnsNameDisclosure {
630    pub name: String,
631    pub name_hash: String,
632}
633
634impl HnsNameDisclosure {
635    pub fn validate(&self) -> Result<(), AbiError> {
636        if validate_name(self.name.as_bytes()) && hns_name_hash_matches(&self.name, &self.name_hash)
637        {
638            Ok(())
639        } else {
640            Err(AbiError::InvalidApproval)
641        }
642    }
643}
644
645#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
646#[serde(
647    tag = "kind",
648    rename_all = "camelCase",
649    rename_all_fields = "camelCase",
650    deny_unknown_fields
651)]
652pub enum ApprovalSummary {
653    Permissions {
654        capabilities: BTreeSet<PermissionCapability>,
655        #[serde(rename = "hnsNames")]
656        hns_names: Vec<HnsNameDisclosure>,
657    },
658    ModuleEnablement {
659        module: ModuleId,
660        action: ModuleApprovalAction,
661    },
662    Send {
663        amount: Amount,
664        recipient: String,
665        maximum_fee: Amount,
666        chain: ModuleId,
667        finality: FinalityModel,
668        warnings: BTreeSet<ApprovalWarning>,
669    },
670    NameTransfer {
671        name: String,
672        recipient: String,
673        maximum_fee: Amount,
674        warnings: BTreeSet<ApprovalWarning>,
675    },
676    NameFinalize {
677        name: String,
678        recipient: String,
679        maximum_fee: Amount,
680        warnings: BTreeSet<ApprovalWarning>,
681    },
682    NameUpdate {
683        name: String,
684        resource_hex: String,
685        resource_bytes: u16,
686        record_count: u16,
687        maximum_fee: Amount,
688        warnings: BTreeSet<ApprovalWarning>,
689    },
690    TypedSignature {
691        message_type: String,
692        message_digest: String,
693    },
694    NameMarketOffer {
695        action: NameMarketApprovalAction,
696        name: String,
697        listing_id: Option<String>,
698        price: Amount,
699        maximum_fee: Amount,
700        warnings: BTreeSet<ApprovalWarning>,
701    },
702    NameMarketPurchase {
703        name: String,
704        listing_id: String,
705        payment: Amount,
706        recipient: String,
707        maximum_fee: Amount,
708        /// Present only when the approval also grants a bounded unattended
709        /// fee for the recipient-fixed FINALIZE after the consensus lockup.
710        automatic_finalize_maximum_fee: Option<Amount>,
711        warnings: BTreeSet<ApprovalWarning>,
712    },
713    DirectOffer {
714        action: DirectOfferApprovalAction,
715        direct_offer_id: Option<String>,
716        offered: Amount,
717        received: Amount,
718        maximum_fee: Amount,
719        warnings: BTreeSet<ApprovalWarning>,
720    },
721    DirectOfferAcceptance {
722        direct_offer_id: String,
723        swap_session_id: String,
724        offered: Amount,
725        received: Amount,
726        refund_timeout_unix_ms: u64,
727        maximum_fee: Amount,
728        warnings: BTreeSet<ApprovalWarning>,
729    },
730    SwapRedeem {
731        swap_session_id: String,
732        amount: Amount,
733        recipient: String,
734        maximum_fee: Amount,
735        finality: FinalityModel,
736        warnings: BTreeSet<ApprovalWarning>,
737    },
738    SwapRefund {
739        swap_session_id: String,
740        amount: Amount,
741        recipient: String,
742        maximum_fee: Amount,
743        refund_available_at_unix_ms: u64,
744        warnings: BTreeSet<ApprovalWarning>,
745    },
746}
747
748impl ApprovalSummary {
749    pub const fn approval_kind(&self) -> ApprovalKind {
750        match self {
751            Self::Permissions { .. } => ApprovalKind::Permission,
752            Self::ModuleEnablement { .. } => ApprovalKind::ModuleEnablement,
753            Self::Send { .. } => ApprovalKind::Send,
754            Self::NameTransfer { .. } => ApprovalKind::NameTransfer,
755            Self::NameFinalize { .. } => ApprovalKind::NameFinalize,
756            Self::NameUpdate { .. } => ApprovalKind::NameUpdate,
757            Self::TypedSignature { .. } => ApprovalKind::TypedSignature,
758            Self::NameMarketOffer { .. } => ApprovalKind::NameMarketOffer,
759            Self::NameMarketPurchase { .. } => ApprovalKind::NameMarketPurchase,
760            Self::DirectOffer { .. } => ApprovalKind::DirectOffer,
761            Self::DirectOfferAcceptance { .. } => ApprovalKind::DirectOfferAcceptance,
762            Self::SwapRedeem { .. } => ApprovalKind::SwapRedeem,
763            Self::SwapRefund { .. } => ApprovalKind::SwapRefund,
764        }
765    }
766
767    /// Validate one structured approval summary independently of a browser
768    /// prompt envelope. Trusted native products use the same canonical summary
769    /// checks before displaying a locally prepared value action.
770    pub fn validate(&self) -> Result<(), AbiError> {
771        match self {
772            Self::Permissions {
773                capabilities,
774                hns_names,
775            } => {
776                if capabilities.is_empty() || capabilities.len() > MAX_PUBLIC_ITEMS {
777                    return Err(AbiError::InvalidApproval);
778                }
779                if !capabilities.contains(&PermissionCapability::Names) && !hns_names.is_empty() {
780                    return Err(AbiError::InvalidApproval);
781                }
782                validate_hns_name_disclosures(hns_names)?;
783            }
784            Self::ModuleEnablement { .. } => {}
785            Self::Send {
786                amount,
787                recipient,
788                maximum_fee,
789                chain,
790                warnings,
791                ..
792            } => {
793                if amount.asset != chain.asset() {
794                    return Err(AbiError::InvalidApproval);
795                }
796                validate_value_movement(*amount, recipient, *maximum_fee, warnings)?;
797            }
798            Self::NameTransfer {
799                name,
800                recipient,
801                maximum_fee,
802                warnings,
803            }
804            | Self::NameFinalize {
805                name,
806                recipient,
807                maximum_fee,
808                warnings,
809            } => {
810                if maximum_fee.asset != WalletAsset::Hns {
811                    return Err(AbiError::InvalidApproval);
812                }
813                validate_public_string(name)?;
814                validate_value_movement(
815                    Amount::new(WalletAsset::Hns, 1),
816                    recipient,
817                    *maximum_fee,
818                    warnings,
819                )?;
820            }
821            Self::NameUpdate {
822                name,
823                resource_hex,
824                resource_bytes,
825                maximum_fee,
826                warnings,
827                ..
828            } => {
829                if maximum_fee.asset != WalletAsset::Hns
830                    || usize::from(*resource_bytes) > 512
831                    || resource_hex.len() != usize::from(*resource_bytes) * 2
832                    || !resource_hex
833                        .bytes()
834                        .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
835                {
836                    return Err(AbiError::InvalidApproval);
837                }
838                validate_public_string(name)?;
839                validate_amount(*maximum_fee, false)?;
840                validate_warnings(warnings)?;
841            }
842            Self::TypedSignature {
843                message_type,
844                message_digest,
845            } => {
846                validate_public_string(message_type)?;
847                validate_public_string(message_digest)?;
848            }
849            Self::NameMarketOffer {
850                name,
851                listing_id,
852                price,
853                maximum_fee,
854                warnings,
855                ..
856            } => {
857                if price.asset != WalletAsset::Hns || maximum_fee.asset != WalletAsset::Hns {
858                    return Err(AbiError::InvalidApproval);
859                }
860                validate_public_string(name)?;
861                validate_optional_public_string(listing_id)?;
862                validate_amount(*price, false)?;
863                validate_amount(*maximum_fee, true)?;
864                validate_warnings(warnings)?;
865            }
866            Self::NameMarketPurchase {
867                name,
868                listing_id,
869                payment,
870                recipient,
871                maximum_fee,
872                automatic_finalize_maximum_fee,
873                warnings,
874            } => {
875                if payment.asset != WalletAsset::Hns || maximum_fee.asset != WalletAsset::Hns {
876                    return Err(AbiError::InvalidApproval);
877                }
878                validate_public_string(name)?;
879                validate_public_string(listing_id)?;
880                validate_value_movement(*payment, recipient, *maximum_fee, warnings)?;
881                if let Some(automatic) = automatic_finalize_maximum_fee
882                    && (automatic.asset != WalletAsset::Hns || automatic.base_units.is_zero())
883                {
884                    return Err(AbiError::InvalidApproval);
885                }
886            }
887            Self::DirectOffer {
888                direct_offer_id,
889                offered,
890                received,
891                maximum_fee,
892                warnings,
893                ..
894            } => {
895                if offered.asset == received.asset || maximum_fee.asset != offered.asset {
896                    return Err(AbiError::InvalidApproval);
897                }
898                validate_optional_public_string(direct_offer_id)?;
899                validate_amount(*offered, false)?;
900                validate_amount(*received, false)?;
901                validate_amount(*maximum_fee, true)?;
902                validate_warnings(warnings)?;
903            }
904            Self::DirectOfferAcceptance {
905                direct_offer_id,
906                swap_session_id,
907                offered,
908                received,
909                refund_timeout_unix_ms,
910                maximum_fee,
911                warnings,
912            } => {
913                if offered.asset == received.asset || maximum_fee.asset != offered.asset {
914                    return Err(AbiError::InvalidApproval);
915                }
916                validate_public_string(direct_offer_id)?;
917                validate_public_string(swap_session_id)?;
918                validate_amount(*offered, false)?;
919                validate_amount(*received, false)?;
920                validate_amount(*maximum_fee, true)?;
921                validate_warnings(warnings)?;
922                if *refund_timeout_unix_ms == 0 {
923                    return Err(AbiError::InvalidApproval);
924                }
925            }
926            Self::SwapRedeem {
927                swap_session_id,
928                amount,
929                recipient,
930                maximum_fee,
931                warnings,
932                ..
933            } => {
934                validate_public_string(swap_session_id)?;
935                validate_value_movement(*amount, recipient, *maximum_fee, warnings)?;
936            }
937            Self::SwapRefund {
938                swap_session_id,
939                amount,
940                recipient,
941                maximum_fee,
942                refund_available_at_unix_ms,
943                warnings,
944            } => {
945                validate_public_string(swap_session_id)?;
946                validate_value_movement(*amount, recipient, *maximum_fee, warnings)?;
947                if *refund_available_at_unix_ms == 0 {
948                    return Err(AbiError::InvalidApproval);
949                }
950            }
951        }
952        Ok(())
953    }
954
955    fn validate_method(&self, method: &str) -> Result<(), AbiError> {
956        let matches = match self {
957            Self::Permissions {
958                capabilities,
959                hns_names,
960            } => match method {
961                "hns_requestAccounts" => {
962                    capabilities.len() == 1
963                        && capabilities.contains(&PermissionCapability::Accounts)
964                        && hns_names.is_empty()
965                }
966                "wallet_requestPermissions" => {
967                    !capabilities.contains(&PermissionCapability::Accounts)
968                }
969                _ => false,
970            },
971            Self::ModuleEnablement { action, .. } => matches!(
972                (method, *action),
973                ("wallet_enableModule", ModuleApprovalAction::Enable)
974                    | ("wallet_disableModule", ModuleApprovalAction::Disable)
975            ),
976            Self::Send { .. } => matches!(method, "hns_send" | "asset_send"),
977            Self::NameTransfer { .. } => method == "hns_transferName",
978            Self::NameFinalize { .. } => method == "hns_finalizeName",
979            Self::NameUpdate { .. } => method == "hns_updateName",
980            Self::TypedSignature { .. } => method == "hns_signTypedMessage",
981            Self::NameMarketOffer { action, .. } => matches!(
982                (method, *action),
983                (
984                    "nameMarket_createFixedPriceOffer",
985                    NameMarketApprovalAction::Create
986                ) | ("nameMarket_cancelOffer", NameMarketApprovalAction::Cancel)
987                    | ("nameMarket_recoverName", NameMarketApprovalAction::Recover)
988            ),
989            Self::NameMarketPurchase { .. } => matches!(
990                method,
991                "nameMarket_acceptOffer" | "nameMarket_finalizePurchase"
992            ),
993            Self::DirectOffer { action, .. } => matches!(
994                (method, *action),
995                (
996                    "swap_publishDirectOffer",
997                    DirectOfferApprovalAction::Publish
998                ) | ("swap_cancelDirectOffer", DirectOfferApprovalAction::Cancel)
999            ),
1000            Self::DirectOfferAcceptance { .. } => method == "swap_acceptDirectOffer",
1001            Self::SwapRedeem { .. } => method == "swap_redeem",
1002            Self::SwapRefund { .. } => method == "swap_refund",
1003        };
1004        if matches {
1005            Ok(())
1006        } else {
1007            Err(AbiError::InvalidApproval)
1008        }
1009    }
1010}
1011
1012#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
1013#[serde(deny_unknown_fields, rename_all = "camelCase")]
1014pub struct ApprovalPrompt {
1015    pub approval_id: ProviderApprovalId,
1016    pub binding: ProviderBinding,
1017    pub origin: String,
1018    pub method: String,
1019    pub expires_at_unix_ms: u64,
1020    pub summary: ApprovalSummary,
1021}
1022
1023impl ApprovalPrompt {
1024    pub fn validate(&self, expected_kind: ApprovalKind, now_unix_ms: u64) -> Result<(), AbiError> {
1025        self.binding
1026            .validate()
1027            .map_err(|_| AbiError::InvalidApproval)?;
1028        if self.expires_at_unix_ms <= now_unix_ms
1029            || self.expires_at_unix_ms > now_unix_ms.saturating_add(MAX_APPROVAL_LIFETIME_MS)
1030            || self.origin.is_empty()
1031            || self.origin.len() > MAX_ORIGIN_BYTES
1032            || !self.origin.is_ascii()
1033            || self.method.is_empty()
1034            || self.method.len() > MAX_METHOD_BYTES
1035            || !self.method.is_ascii()
1036            || self.summary.approval_kind() != expected_kind
1037        {
1038            return Err(AbiError::InvalidApproval);
1039        }
1040        self.summary.validate()?;
1041        self.summary.validate_method(&self.method)?;
1042        if serde_json::to_vec(self)
1043            .map_err(|_| AbiError::Encoding)?
1044            .len()
1045            > MAX_APPROVAL_FRAME_BYTES
1046        {
1047            return Err(AbiError::ApprovalTooLarge);
1048        }
1049        Ok(())
1050    }
1051}
1052
1053#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
1054#[serde(rename_all = "camelCase")]
1055pub enum DisconnectReason {
1056    AuthorityRevoked,
1057    AuthorityExpired,
1058    NavigationChanged,
1059    PolicyChanged,
1060    WalletSessionChanged,
1061    ServiceRestarted,
1062}
1063
1064#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
1065#[serde(
1066    tag = "event",
1067    rename_all = "camelCase",
1068    rename_all_fields = "camelCase",
1069    deny_unknown_fields
1070)]
1071pub enum ProviderEventPayload {
1072    Connect {
1073        permission_generation: u64,
1074    },
1075    Disconnect {
1076        reason: DisconnectReason,
1077    },
1078    PermissionsChanged {
1079        permission_generation: u64,
1080        capabilities: BTreeSet<PermissionCapability>,
1081    },
1082    ModulesChanged {
1083        modules: BTreeSet<ModuleId>,
1084    },
1085    AccountsChanged {
1086        modules: BTreeSet<ModuleId>,
1087    },
1088    BalancesChanged {
1089        modules: BTreeSet<ModuleId>,
1090    },
1091    TransactionsChanged {
1092        modules: BTreeSet<ModuleId>,
1093    },
1094    NamesChanged {
1095        names: Vec<String>,
1096    },
1097    NameMarketChanged {
1098        listing_ids: Vec<String>,
1099    },
1100    DirectOfferChanged {
1101        direct_offer_ids: Vec<String>,
1102    },
1103    SwapSessionChanged {
1104        swap_session_ids: Vec<String>,
1105    },
1106    WalletLocked,
1107}
1108
1109impl ProviderEventPayload {
1110    fn validate(&self) -> Result<(), AbiError> {
1111        match self {
1112            Self::Connect {
1113                permission_generation,
1114            }
1115            | Self::PermissionsChanged {
1116                permission_generation,
1117                ..
1118            } if *permission_generation == 0 => return Err(AbiError::InvalidEvent),
1119            Self::PermissionsChanged { capabilities, .. } => {
1120                if capabilities.len() > MAX_PUBLIC_ITEMS {
1121                    return Err(AbiError::InvalidEvent);
1122                }
1123            }
1124            Self::ModulesChanged { modules }
1125            | Self::AccountsChanged { modules }
1126            | Self::BalancesChanged { modules }
1127            | Self::TransactionsChanged { modules } => {
1128                if modules.len() > MAX_PUBLIC_ITEMS {
1129                    return Err(AbiError::InvalidEvent);
1130                }
1131            }
1132            Self::NamesChanged { names } => validate_public_strings(names)?,
1133            Self::NameMarketChanged { listing_ids } => validate_public_strings(listing_ids)?,
1134            Self::DirectOfferChanged { direct_offer_ids } => {
1135                validate_public_strings(direct_offer_ids)?;
1136            }
1137            Self::SwapSessionChanged { swap_session_ids } => {
1138                validate_public_strings(swap_session_ids)?;
1139            }
1140            _ => {}
1141        }
1142        Ok(())
1143    }
1144}
1145
1146#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
1147#[serde(deny_unknown_fields, rename_all = "camelCase")]
1148pub struct ProviderEventEnvelope {
1149    pub protocol_version: u16,
1150    pub host_session_id: HostSessionId,
1151    pub service_session_id: WalletServiceSessionId,
1152    pub restart_generation: u64,
1153    pub channel_sequence: u64,
1154    pub binding: ProviderBinding,
1155    pub event_sequence: u64,
1156    pub payload: ProviderEventPayload,
1157}
1158
1159#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
1160#[serde(rename_all = "camelCase")]
1161pub enum ServiceErrorCode {
1162    InvalidFrame,
1163    VersionMismatch,
1164    SessionMismatch,
1165    SequenceMismatch,
1166    AuthorityUnknown,
1167    AuthorityStale,
1168    PermissionDenied,
1169    ApprovalStale,
1170    WalletLocked,
1171    RateLimited,
1172    Replay,
1173    UnsupportedCapability,
1174    InvalidRequest,
1175    PersistenceFailure,
1176    RuntimeFailure,
1177}
1178
1179#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
1180#[serde(deny_unknown_fields, rename_all = "camelCase")]
1181pub struct ServiceFailure {
1182    pub code: ServiceErrorCode,
1183    pub message: String,
1184    pub unsupported_capability: Option<ServiceCapability>,
1185}
1186
1187impl ServiceFailure {
1188    pub fn unsupported(capability: ServiceCapability) -> Self {
1189        Self {
1190            code: ServiceErrorCode::UnsupportedCapability,
1191            message: "requested wallet capability is not available".to_owned(),
1192            unsupported_capability: Some(capability),
1193        }
1194    }
1195
1196    fn validate(&self) -> Result<(), AbiError> {
1197        if self.message.is_empty()
1198            || self.message.len() > MAX_FAILURE_MESSAGE_BYTES
1199            || !self.message.is_ascii()
1200            || (self.code == ServiceErrorCode::UnsupportedCapability)
1201                != self.unsupported_capability.is_some()
1202        {
1203            return Err(AbiError::InvalidFailure);
1204        }
1205        Ok(())
1206    }
1207}
1208
1209pub fn declared_payload_len(prefix: [u8; LENGTH_PREFIX_BYTES]) -> Result<usize, AbiError> {
1210    let length = u32::from_be_bytes(prefix) as usize;
1211    if length == 0 || length > MAX_ABI_FRAME_BYTES {
1212        return Err(AbiError::FrameSize);
1213    }
1214    Ok(length)
1215}
1216
1217pub fn decode_host_frame(frame: &[u8]) -> Result<HostFrame, AbiError> {
1218    let payload = decode_payload(frame)?;
1219    let decoded: HostFrame =
1220        serde_json::from_slice(payload).map_err(|_| AbiError::InvalidEnvelope)?;
1221    validate_host_frame(&decoded)?;
1222    Ok(decoded)
1223}
1224
1225/// Encode a host frame into an owned buffer that clears its allocation on
1226/// drop. Host requests can contain wallet passphrases or restore phrases, so
1227/// callers must retain this owner through the transport write instead of
1228/// copying the bytes into an ordinary `Vec<u8>`.
1229pub fn encode_host_frame(frame: &HostFrame) -> Result<Zeroizing<Vec<u8>>, AbiError> {
1230    validate_host_frame(frame)?;
1231    encode_zeroizing_frame(frame)
1232}
1233
1234pub fn decode_service_frame(frame: &[u8]) -> Result<ServiceFrame, AbiError> {
1235    let payload = decode_payload(frame)?;
1236    let decoded: ServiceFrame =
1237        serde_json::from_slice(payload).map_err(|_| AbiError::InvalidEnvelope)?;
1238    validate_service_frame(&decoded)?;
1239    Ok(decoded)
1240}
1241
1242pub fn encode_service_frame(frame: &ServiceFrame) -> Result<Vec<u8>, AbiError> {
1243    validate_service_frame(frame)?;
1244    encode_frame(frame)
1245}
1246
1247fn decode_payload(frame: &[u8]) -> Result<&[u8], AbiError> {
1248    if frame.len() < LENGTH_PREFIX_BYTES {
1249        return Err(AbiError::TruncatedFrame);
1250    }
1251    let prefix: [u8; LENGTH_PREFIX_BYTES] = frame[..LENGTH_PREFIX_BYTES]
1252        .try_into()
1253        .map_err(|_| AbiError::TruncatedFrame)?;
1254    let length = declared_payload_len(prefix)?;
1255    if frame.len() != LENGTH_PREFIX_BYTES + length {
1256        return Err(AbiError::TruncatedFrame);
1257    }
1258    Ok(&frame[LENGTH_PREFIX_BYTES..])
1259}
1260
1261fn encode_frame<T: Serialize>(value: &T) -> Result<Vec<u8>, AbiError> {
1262    let payload = Zeroizing::new(serde_json::to_vec(value).map_err(|_| AbiError::Encoding)?);
1263    if payload.is_empty() || payload.len() > MAX_ABI_FRAME_BYTES {
1264        return Err(AbiError::FrameSize);
1265    }
1266    let length = u32::try_from(payload.len()).map_err(|_| AbiError::FrameSize)?;
1267    let mut framed = Vec::with_capacity(LENGTH_PREFIX_BYTES + payload.len());
1268    framed.extend_from_slice(&length.to_be_bytes());
1269    framed.extend_from_slice(&payload);
1270    Ok(framed)
1271}
1272
1273fn encode_zeroizing_frame<T: Serialize>(value: &T) -> Result<Zeroizing<Vec<u8>>, AbiError> {
1274    let payload = Zeroizing::new(serde_json::to_vec(value).map_err(|_| AbiError::Encoding)?);
1275    if payload.is_empty() || payload.len() > MAX_ABI_FRAME_BYTES {
1276        return Err(AbiError::FrameSize);
1277    }
1278    let length = u32::try_from(payload.len()).map_err(|_| AbiError::FrameSize)?;
1279    let mut framed = Zeroizing::new(Vec::with_capacity(LENGTH_PREFIX_BYTES + payload.len()));
1280    framed.extend_from_slice(&length.to_be_bytes());
1281    framed.extend_from_slice(&payload);
1282    Ok(framed)
1283}
1284
1285fn validate_host_frame(frame: &HostFrame) -> Result<(), AbiError> {
1286    match frame {
1287        HostFrame::Hello { hello } => {
1288            if hello.protocol_version != WALLET_ABI_VERSION || hello.restart_generation == 0 {
1289                return Err(AbiError::VersionMismatch);
1290            }
1291        }
1292        HostFrame::Request { envelope } => {
1293            validate_session_envelope(envelope)?;
1294            validate_service_request(&envelope.body)?;
1295        }
1296    }
1297    Ok(())
1298}
1299
1300fn validate_session_envelope<T>(envelope: &SessionEnvelope<T>) -> Result<(), AbiError> {
1301    if envelope.protocol_version != WALLET_ABI_VERSION {
1302        return Err(AbiError::VersionMismatch);
1303    }
1304    if envelope.restart_generation == 0 || envelope.channel_sequence == 0 {
1305        return Err(AbiError::InvalidEnvelope);
1306    }
1307    Ok(())
1308}
1309
1310fn validate_service_request(request: &ServiceRequest) -> Result<(), AbiError> {
1311    match request {
1312        ServiceRequest::RegisterAuthority { authority, .. } => validate_authority(authority),
1313        ServiceRequest::ReplaceAuthority {
1314            expected_authority_revision,
1315            authority,
1316            ..
1317        } => {
1318            if *expected_authority_revision == 0 {
1319                return Err(AbiError::InvalidAuthority);
1320            }
1321            validate_authority(authority)
1322        }
1323        ServiceRequest::RevokeAuthority {
1324            expected_authority_revision,
1325            ..
1326        } => {
1327            if *expected_authority_revision == 0 {
1328                return Err(AbiError::InvalidAuthority);
1329            }
1330            Ok(())
1331        }
1332        ServiceRequest::ProviderCapabilities {
1333            authority_revision, ..
1334        } => {
1335            if *authority_revision == 0 {
1336                return Err(AbiError::InvalidAuthority);
1337            }
1338            Ok(())
1339        }
1340        ServiceRequest::ProviderRequest {
1341            authority_revision,
1342            request_nonce,
1343            method,
1344            params,
1345            ..
1346        } => {
1347            if *authority_revision == 0
1348                || *request_nonce == 0
1349                || method.is_empty()
1350                || method.len() > MAX_METHOD_BYTES
1351                || !method.is_ascii()
1352            {
1353                return Err(AbiError::InvalidProviderRequest);
1354            }
1355            let provider = serde_json::json!({ "method": method, "params": params });
1356            if serde_json::to_vec(&provider)
1357                .map_err(|_| AbiError::Encoding)?
1358                .len()
1359                > MAX_PROVIDER_REQUEST_BYTES
1360            {
1361                return Err(AbiError::ProviderRequestTooLarge);
1362            }
1363            Ok(())
1364        }
1365        ServiceRequest::ApprovalDecision {
1366            authority_revision, ..
1367        } => {
1368            if *authority_revision == 0 {
1369                return Err(AbiError::InvalidApproval);
1370            }
1371            Ok(())
1372        }
1373        ServiceRequest::Wallet { request } => validate_wallet_request(request),
1374        ServiceRequest::WalletAuthority { request } => {
1375            validate_wallet_authority_context_request(request)
1376        }
1377    }
1378}
1379
1380fn validate_authority(authority: &HostAuthorityFacts) -> Result<(), AbiError> {
1381    if authority.origin.is_empty()
1382        || authority.origin.len() > MAX_ORIGIN_BYTES
1383        || !authority.origin.is_ascii()
1384        || authority.runtime_generation == 0
1385        || authority.policy_generation == 0
1386        || authority.navigation_generation == 0
1387        || authority.valid_until_unix_ms == 0
1388    {
1389        return Err(AbiError::InvalidAuthority);
1390    }
1391    Ok(())
1392}
1393
1394fn validate_wallet_request(request: &WalletRequest) -> Result<(), AbiError> {
1395    match request {
1396        WalletRequest::CreateWallet { passphrase } | WalletRequest::Unlock { passphrase } => {
1397            validate_secret(passphrase.expose_secret(), MAX_PASSPHRASE_BYTES)
1398        }
1399        WalletRequest::RestoreWallet {
1400            passphrase,
1401            recovery_phrase,
1402        } => {
1403            validate_secret(passphrase.expose_secret(), MAX_PASSPHRASE_BYTES)?;
1404            validate_secret(recovery_phrase.expose_secret(), MAX_RECOVERY_PHRASE_BYTES)
1405        }
1406        _ => Ok(()),
1407    }
1408}
1409
1410fn validate_wallet_authority_context_request(
1411    request: &WalletAuthorityContextRequest,
1412) -> Result<(), AbiError> {
1413    match request {
1414        WalletAuthorityContextRequest::CurrentHnsContext {
1415            network,
1416            network_magic,
1417            namespace_id,
1418            namespace_lease_generation,
1419            module,
1420        } if *network_magic == network.magic()
1421            && namespace_id.iter().any(|byte| *byte != 0)
1422            && *namespace_lease_generation != 0
1423            && *module == ModuleId::Handshake =>
1424        {
1425            Ok(())
1426        }
1427        WalletAuthorityContextRequest::CurrentHnsContext { .. } => Err(AbiError::InvalidAuthority),
1428    }
1429}
1430
1431fn validate_service_frame(frame: &ServiceFrame) -> Result<(), AbiError> {
1432    match frame {
1433        ServiceFrame::Hello { hello } => {
1434            if hello.protocol_version != WALLET_ABI_VERSION
1435                || hello.restart_generation == 0
1436                || hello.limits != ServiceLimits::default()
1437                || hello.capabilities.len() > MAX_PUBLIC_ITEMS
1438                || (hello
1439                    .capabilities
1440                    .contains(&ServiceCapability::HnsReadOperationsV1)
1441                    && !hello
1442                        .capabilities
1443                        .contains(&ServiceCapability::WalletOperations))
1444                || (hello
1445                    .capabilities
1446                    .contains(&ServiceCapability::HnsWalletAuthorityContextV1)
1447                    && (!hello
1448                        .capabilities
1449                        .contains(&ServiceCapability::WalletOperations)
1450                        || !hello
1451                            .capabilities
1452                            .contains(&ServiceCapability::HnsReadOperationsV1)))
1453            {
1454                return Err(AbiError::InvalidEnvelope);
1455            }
1456        }
1457        ServiceFrame::Response { envelope } => {
1458            validate_session_envelope(envelope)?;
1459            validate_service_response(&envelope.body)?;
1460        }
1461        ServiceFrame::Event { event } => {
1462            if event.protocol_version != WALLET_ABI_VERSION
1463                || event.restart_generation == 0
1464                || event.channel_sequence == 0
1465                || event.event_sequence == 0
1466            {
1467                return Err(AbiError::InvalidEvent);
1468            }
1469            event
1470                .binding
1471                .validate()
1472                .map_err(|_| AbiError::InvalidEvent)?;
1473            event.payload.validate()?;
1474            match &event.payload {
1475                ProviderEventPayload::Connect {
1476                    permission_generation,
1477                }
1478                | ProviderEventPayload::PermissionsChanged {
1479                    permission_generation,
1480                    ..
1481                } if *permission_generation != event.binding.permission_generation => {
1482                    return Err(AbiError::InvalidEvent);
1483                }
1484                ProviderEventPayload::Disconnect { .. } => {}
1485                _ if event.binding.permission_generation == 0 => {
1486                    return Err(AbiError::InvalidEvent);
1487                }
1488                _ => {}
1489            }
1490            if serde_json::to_vec(event)
1491                .map_err(|_| AbiError::Encoding)?
1492                .len()
1493                > MAX_PROVIDER_EVENT_BYTES
1494            {
1495                return Err(AbiError::EventTooLarge);
1496            }
1497        }
1498    }
1499    Ok(())
1500}
1501
1502fn validate_service_response(response: &ServiceResponse) -> Result<(), AbiError> {
1503    match response {
1504        ServiceResponse::AuthorityRegistered {
1505            authority_revision, ..
1506        }
1507        | ServiceResponse::AuthorityReplaced {
1508            authority_revision, ..
1509        } if *authority_revision == 0 => Err(AbiError::InvalidEnvelope),
1510        ServiceResponse::ProviderResult { binding, value } => {
1511            binding.validate()?;
1512            if serde_json::to_vec(value)
1513                .map_err(|_| AbiError::Encoding)?
1514                .len()
1515                > MAX_PROVIDER_RESULT_BYTES
1516            {
1517                return Err(AbiError::ProviderResultTooLarge);
1518            }
1519            Ok(())
1520        }
1521        ServiceResponse::ProviderCapabilities {
1522            binding,
1523            capabilities,
1524        } => {
1525            binding.validate()?;
1526            capabilities.validate(binding)
1527        }
1528        ServiceResponse::ApprovalRequired { approval } => {
1529            approval
1530                .binding
1531                .validate()
1532                .map_err(|_| AbiError::InvalidApproval)?;
1533            if approval.origin.is_empty()
1534                || approval.method.is_empty()
1535                || approval.expires_at_unix_ms == 0
1536            {
1537                return Err(AbiError::InvalidApproval);
1538            }
1539            approval.summary.validate()?;
1540            approval.summary.validate_method(&approval.method)?;
1541            if serde_json::to_vec(approval)
1542                .map_err(|_| AbiError::Encoding)?
1543                .len()
1544                > MAX_APPROVAL_FRAME_BYTES
1545            {
1546                return Err(AbiError::ApprovalTooLarge);
1547            }
1548            Ok(())
1549        }
1550        ServiceResponse::Wallet { response } => validate_wallet_response(response),
1551        ServiceResponse::WalletAuthority { context } => {
1552            validate_wallet_hns_authority_context(context)
1553        }
1554        ServiceResponse::Failure { failure } => failure.validate(),
1555        _ => Ok(()),
1556    }
1557}
1558
1559fn validate_wallet_hns_authority_context(
1560    context: &WalletHnsAuthorityContext,
1561) -> Result<(), AbiError> {
1562    if context.network_magic != context.network.magic()
1563        || context.namespace_id.iter().all(|byte| *byte == 0)
1564        || context.namespace_lease_generation == 0
1565        || context
1566            .active_wallet
1567            .as_bytes()
1568            .iter()
1569            .all(|byte| *byte == 0)
1570        || context.account.as_bytes().iter().all(|byte| *byte == 0)
1571        || context.wallet_authority_revision == 0
1572        || context.account_authority_revision == 0
1573        || context.locked
1574        || context.module != ModuleId::Handshake
1575        || !context.persistent_wallet_confirmed
1576        || context.recovery_pending
1577        || context.retirement_pending
1578        || !context.hns_reads_ready
1579    {
1580        return Err(AbiError::InvalidAuthority);
1581    }
1582    Ok(())
1583}
1584
1585fn validate_wallet_response(response: &WalletResponse) -> Result<(), AbiError> {
1586    match response {
1587        WalletResponse::Accounts { accounts } if accounts.len() > MAX_PUBLIC_ITEMS => {
1588            Err(AbiError::ProviderResultTooLarge)
1589        }
1590        WalletResponse::TransactionHistory { transactions }
1591            if transactions.len() > MAX_PUBLIC_ITEMS =>
1592        {
1593            Err(AbiError::ProviderResultTooLarge)
1594        }
1595        WalletResponse::Accounts { accounts } => {
1596            for account in accounts {
1597                validate_public_string(&account.label)?;
1598                validate_optional_public_string(&account.receive_display)?;
1599            }
1600            Ok(())
1601        }
1602        WalletResponse::Workflow { summary } => {
1603            validate_public_string(&summary.state)?;
1604            validate_optional_public_string(&summary.next_action)
1605        }
1606        _ => Ok(()),
1607    }
1608}
1609
1610fn validate_secret(value: &str, maximum: usize) -> Result<(), AbiError> {
1611    if value.is_empty() || value.len() > maximum {
1612        return Err(AbiError::InvalidSecretInput);
1613    }
1614    Ok(())
1615}
1616
1617fn validate_value_movement(
1618    amount: Amount,
1619    recipient: &str,
1620    maximum_fee: Amount,
1621    warnings: &BTreeSet<ApprovalWarning>,
1622) -> Result<(), AbiError> {
1623    if amount.asset != maximum_fee.asset {
1624        return Err(AbiError::InvalidApproval);
1625    }
1626    validate_amount(amount, false)?;
1627    validate_public_string(recipient)?;
1628    validate_amount(maximum_fee, true)?;
1629    validate_warnings(warnings)
1630}
1631
1632fn validate_amount(amount: Amount, allow_zero: bool) -> Result<(), AbiError> {
1633    if !allow_zero && amount.base_units == BaseUnits::ZERO {
1634        return Err(AbiError::InvalidApproval);
1635    }
1636    Ok(())
1637}
1638
1639fn validate_warnings(warnings: &BTreeSet<ApprovalWarning>) -> Result<(), AbiError> {
1640    if warnings.len() > MAX_PUBLIC_ITEMS {
1641        return Err(AbiError::InvalidApproval);
1642    }
1643    Ok(())
1644}
1645
1646fn validate_hns_name_disclosures(names: &[HnsNameDisclosure]) -> Result<(), AbiError> {
1647    if names.len() > MAX_HNS_NAME_DISCLOSURES || names.windows(2).any(|pair| pair[0] >= pair[1]) {
1648        return Err(AbiError::InvalidApproval);
1649    }
1650    let mut canonical_names = BTreeSet::new();
1651    let mut canonical_hashes = BTreeSet::new();
1652    for disclosure in names {
1653        disclosure.validate()?;
1654        if !canonical_names.insert(disclosure.name.as_str())
1655            || !canonical_hashes.insert(disclosure.name_hash.as_str())
1656        {
1657            return Err(AbiError::InvalidApproval);
1658        }
1659    }
1660    Ok(())
1661}
1662
1663fn hns_name_hash_matches(name: &str, encoded: &str) -> bool {
1664    if encoded.len() != 64 {
1665        return false;
1666    }
1667    let mut decoded = [0_u8; 32];
1668    for (index, pair) in encoded.as_bytes().chunks_exact(2).enumerate() {
1669        let nibble = |byte| match byte {
1670            b'0'..=b'9' => Some(byte - b'0'),
1671            b'a'..=b'f' => Some(byte - b'a' + 10),
1672            _ => None,
1673        };
1674        let Some(high) = nibble(pair[0]) else {
1675            return false;
1676        };
1677        let Some(low) = nibble(pair[1]) else {
1678            return false;
1679        };
1680        decoded[index] = (high << 4) | low;
1681    }
1682    hash_name(name.as_bytes()).is_ok_and(|expected| decoded == expected.into_bytes())
1683}
1684
1685fn validate_public_string(value: &str) -> Result<(), AbiError> {
1686    if value.is_empty() || value.len() > MAX_PUBLIC_STRING_BYTES || !value.is_ascii() {
1687        return Err(AbiError::InvalidPublicValue);
1688    }
1689    Ok(())
1690}
1691
1692fn validate_optional_public_string(value: &Option<String>) -> Result<(), AbiError> {
1693    if let Some(value) = value {
1694        validate_public_string(value)?;
1695    }
1696    Ok(())
1697}
1698
1699fn validate_public_strings(values: &[String]) -> Result<(), AbiError> {
1700    if values.len() > MAX_PUBLIC_ITEMS {
1701        return Err(AbiError::InvalidEvent);
1702    }
1703    for value in values {
1704        validate_public_string(value)?;
1705    }
1706    Ok(())
1707}
1708
1709#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
1710pub enum AbiError {
1711    #[error("frame is empty or exceeds the bounded outer maximum")]
1712    FrameSize,
1713    #[error("length-prefixed frame is truncated or has trailing bytes")]
1714    TruncatedFrame,
1715    #[error("wallet service protocol version mismatch")]
1716    VersionMismatch,
1717    #[error("invalid wallet service envelope")]
1718    InvalidEnvelope,
1719    #[error("invalid or stale host authority registration")]
1720    InvalidAuthority,
1721    #[error("provider request is invalid")]
1722    InvalidProviderRequest,
1723    #[error("provider request exceeds 64 KiB")]
1724    ProviderRequestTooLarge,
1725    #[error("provider result exceeds 256 KiB")]
1726    ProviderResultTooLarge,
1727    #[error("provider event exceeds 64 KiB")]
1728    EventTooLarge,
1729    #[error("approval prompt exceeds 16 KiB")]
1730    ApprovalTooLarge,
1731    #[error("approval prompt is incomplete, stale, or mismatched")]
1732    InvalidApproval,
1733    #[error("provider event is invalid")]
1734    InvalidEvent,
1735    #[error("secret input is empty or exceeds its bounded maximum")]
1736    InvalidSecretInput,
1737    #[error("public response value is empty, non-ASCII, or unbounded")]
1738    InvalidPublicValue,
1739    #[error("failure response is invalid or unbounded")]
1740    InvalidFailure,
1741    #[error("frame JSON encoding failed")]
1742    Encoding,
1743}
1744
1745#[cfg(test)]
1746mod tests {
1747    use super::*;
1748    use serde::de::DeserializeOwned;
1749
1750    fn host_session() -> HostSessionId {
1751        HostSessionId::from_bytes([1_u8; 32]).expect("host session")
1752    }
1753
1754    fn service_session() -> WalletServiceSessionId {
1755        WalletServiceSessionId::from_bytes([2_u8; 32]).expect("service session")
1756    }
1757
1758    fn wallet_session() -> WalletSessionId {
1759        WalletSessionId::from_bytes([5_u8; 32]).expect("wallet session")
1760    }
1761
1762    fn request_id() -> ProviderRequestId {
1763        ProviderRequestId::from_bytes([3_u8; 16]).expect("request id")
1764    }
1765
1766    fn handle() -> HostAuthorityHandleId {
1767        HostAuthorityHandleId::from_bytes([4_u8; 32]).expect("handle")
1768    }
1769
1770    fn approval_id() -> ProviderApprovalId {
1771        ProviderApprovalId::from_bytes([6_u8; 16]).expect("approval id")
1772    }
1773
1774    fn wallet_id() -> WalletId {
1775        WalletId::new([8_u8; 16])
1776    }
1777
1778    fn assert_json_round_trip<T>(value: &T, expected: Value)
1779    where
1780        T: DeserializeOwned + std::fmt::Debug + PartialEq + Serialize,
1781    {
1782        let encoded = serde_json::to_value(value).expect("serialize schema-shaped value");
1783        assert_eq!(encoded, expected);
1784        let bytes = serde_json::to_vec(&encoded).expect("encode schema-shaped JSON");
1785        let decoded: T = serde_json::from_slice(&bytes).expect("deserialize schema-shaped value");
1786        assert_eq!(&decoded, value);
1787    }
1788
1789    fn request(body: ServiceRequest) -> HostFrame {
1790        HostFrame::Request {
1791            envelope: SessionEnvelope {
1792                protocol_version: WALLET_ABI_VERSION,
1793                host_session_id: host_session(),
1794                service_session_id: service_session(),
1795                restart_generation: 7,
1796                channel_sequence: 1,
1797                request_id: request_id(),
1798                body,
1799            },
1800        }
1801    }
1802
1803    #[test]
1804    fn golden_hello_is_length_prefixed_v2_with_canonical_ids() {
1805        let encoded = encode_host_frame(&HostFrame::Hello {
1806            hello: HostHello {
1807                protocol_version: WALLET_ABI_VERSION,
1808                platform: HostPlatform::ChromiumNativeHost,
1809                host_session_id: host_session(),
1810                restart_generation: 7,
1811            },
1812        })
1813        .expect("encode");
1814        let declared = u32::from_be_bytes(encoded[..4].try_into().expect("prefix")) as usize;
1815        assert_eq!(declared, encoded.len() - 4);
1816        assert!(
1817            std::str::from_utf8(&encoded[4..])
1818                .expect("json")
1819                .contains("AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE")
1820        );
1821        assert_eq!(
1822            decode_host_frame(&encoded).expect("decode"),
1823            decode_host_frame(&encoded).expect("decode twice")
1824        );
1825    }
1826
1827    #[test]
1828    fn hns_read_operations_v1_is_exact_and_requires_wallet_operations() {
1829        assert_json_round_trip(
1830            &ServiceCapability::HnsReadOperationsV1,
1831            serde_json::json!("hnsReadOperationsV1"),
1832        );
1833        assert!(
1834            serde_json::from_value::<ServiceCapability>(serde_json::json!("hnsReadOperationsV2"))
1835                .is_err()
1836        );
1837
1838        let service_hello = |capabilities| ServiceFrame::Hello {
1839            hello: ServiceHello {
1840                protocol_version: WALLET_ABI_VERSION,
1841                platform: HostPlatform::ChromiumNativeHost,
1842                host_session_id: host_session(),
1843                service_session_id: service_session(),
1844                restart_generation: 7,
1845                capabilities,
1846                limits: ServiceLimits::default(),
1847            },
1848        };
1849        assert_eq!(
1850            encode_service_frame(&service_hello(BTreeSet::from([
1851                ServiceCapability::HnsReadOperationsV1,
1852            ]))),
1853            Err(AbiError::InvalidEnvelope)
1854        );
1855
1856        let framed = encode_service_frame(&service_hello(BTreeSet::from([
1857            ServiceCapability::WalletOperations,
1858            ServiceCapability::HnsReadOperationsV1,
1859        ])))
1860        .expect("exact HNS read hello");
1861        assert_eq!(
1862            decode_service_frame(&framed).expect("decode exact HNS read hello"),
1863            service_hello(BTreeSet::from([
1864                ServiceCapability::WalletOperations,
1865                ServiceCapability::HnsReadOperationsV1,
1866            ]))
1867        );
1868    }
1869
1870    #[test]
1871    fn hns_wallet_authority_context_v1_is_additive_exact_and_positive_only() {
1872        assert_json_round_trip(
1873            &ServiceCapability::HnsWalletAuthorityContextV1,
1874            serde_json::json!("hnsWalletAuthorityContextV1"),
1875        );
1876        let namespace_id = [7_u8; 16];
1877        let authority_request = WalletAuthorityContextRequest::CurrentHnsContext {
1878            network: WalletHandshakeNetwork::Regtest,
1879            network_magic: 0xae38_95cf,
1880            namespace_id,
1881            namespace_lease_generation: 9_007_199_254_740_997,
1882            module: ModuleId::Handshake,
1883        };
1884        let request_debug = format!("{authority_request:?}");
1885        assert!(!request_debug.contains("9007199254740997"));
1886        assert!(!request_debug.contains("[7, 7"));
1887        assert_json_round_trip(
1888            &ServiceRequest::WalletAuthority {
1889                request: authority_request,
1890            },
1891            serde_json::json!({
1892                "operation": "walletAuthority",
1893                "request": {
1894                    "operation": "currentHnsContext",
1895                    "network": "regtest",
1896                    "networkMagic": 2_922_943_951_u32,
1897                    "namespaceId": namespace_id,
1898                    "namespaceLeaseGeneration": 9_007_199_254_740_997_u64,
1899                    "module": "handshake",
1900                },
1901            }),
1902        );
1903
1904        let context = WalletHnsAuthorityContext {
1905            network: WalletHandshakeNetwork::Regtest,
1906            network_magic: 0xae38_95cf,
1907            namespace_id,
1908            namespace_lease_generation: 9_007_199_254_740_997,
1909            active_wallet: wallet_id(),
1910            account: AccountId::new([9_u8; 16]),
1911            wallet_authority_revision: 9_007_199_254_740_993,
1912            account_authority_revision: 9_007_199_254_740_995,
1913            locked: false,
1914            module: ModuleId::Handshake,
1915            persistent_wallet_confirmed: true,
1916            recovery_pending: false,
1917            retirement_pending: false,
1918            hns_reads_ready: true,
1919        };
1920        let context_debug = format!("{context:?}");
1921        for private_value in [
1922            "9007199254740993",
1923            "9007199254740995",
1924            "9007199254740997",
1925            "[7, 7",
1926            "[8, 8",
1927            "[9, 9",
1928        ] {
1929            assert!(!context_debug.contains(private_value));
1930        }
1931        assert_json_round_trip(
1932            &ServiceResponse::WalletAuthority { context },
1933            serde_json::json!({
1934                "result": "walletAuthority",
1935                "context": {
1936                    "network": "regtest",
1937                    "networkMagic": 2_922_943_951_u32,
1938                    "namespaceId": namespace_id,
1939                    "namespaceLeaseGeneration": 9_007_199_254_740_997_u64,
1940                    "activeWallet": [8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8],
1941                    "account": [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9],
1942                    "walletAuthorityRevision": 9_007_199_254_740_993_u64,
1943                    "accountAuthorityRevision": 9_007_199_254_740_995_u64,
1944                    "locked": false,
1945                    "module": "handshake",
1946                    "persistentWalletConfirmed": true,
1947                    "recoveryPending": false,
1948                    "retirementPending": false,
1949                    "hnsReadsReady": true,
1950                },
1951            }),
1952        );
1953
1954        for invalid in [
1955            WalletAuthorityContextRequest::CurrentHnsContext {
1956                network: WalletHandshakeNetwork::Regtest,
1957                network_magic: 1,
1958                namespace_id,
1959                namespace_lease_generation: 1,
1960                module: ModuleId::Handshake,
1961            },
1962            WalletAuthorityContextRequest::CurrentHnsContext {
1963                network: WalletHandshakeNetwork::Regtest,
1964                network_magic: 0xae38_95cf,
1965                namespace_id: [0_u8; 16],
1966                namespace_lease_generation: 1,
1967                module: ModuleId::Handshake,
1968            },
1969            WalletAuthorityContextRequest::CurrentHnsContext {
1970                network: WalletHandshakeNetwork::Regtest,
1971                network_magic: 0xae38_95cf,
1972                namespace_id,
1973                namespace_lease_generation: 0,
1974                module: ModuleId::Handshake,
1975            },
1976            WalletAuthorityContextRequest::CurrentHnsContext {
1977                network: WalletHandshakeNetwork::Regtest,
1978                network_magic: 0xae38_95cf,
1979                namespace_id,
1980                namespace_lease_generation: 1,
1981                module: ModuleId::Bitcoin,
1982            },
1983        ] {
1984            assert_eq!(
1985                encode_host_frame(&request(ServiceRequest::WalletAuthority {
1986                    request: invalid,
1987                })),
1988                Err(AbiError::InvalidAuthority)
1989            );
1990        }
1991
1992        let service_hello = |capabilities| ServiceFrame::Hello {
1993            hello: ServiceHello {
1994                protocol_version: WALLET_ABI_VERSION,
1995                platform: HostPlatform::ChromiumNativeHost,
1996                host_session_id: host_session(),
1997                service_session_id: service_session(),
1998                restart_generation: 7,
1999                capabilities,
2000                limits: ServiceLimits::default(),
2001            },
2002        };
2003        for capabilities in [
2004            BTreeSet::from([ServiceCapability::HnsWalletAuthorityContextV1]),
2005            BTreeSet::from([
2006                ServiceCapability::WalletOperations,
2007                ServiceCapability::HnsWalletAuthorityContextV1,
2008            ]),
2009            BTreeSet::from([
2010                ServiceCapability::HnsReadOperationsV1,
2011                ServiceCapability::HnsWalletAuthorityContextV1,
2012            ]),
2013        ] {
2014            assert_eq!(
2015                encode_service_frame(&service_hello(capabilities)),
2016                Err(AbiError::InvalidEnvelope)
2017            );
2018        }
2019        encode_service_frame(&service_hello(BTreeSet::from([
2020            ServiceCapability::WalletOperations,
2021            ServiceCapability::HnsReadOperationsV1,
2022            ServiceCapability::HnsWalletAuthorityContextV1,
2023        ])))
2024        .expect("complete HNS authority capability prerequisites");
2025
2026        let invalid_context = WalletHnsAuthorityContext {
2027            locked: true,
2028            ..context
2029        };
2030        let invalid_response = ServiceFrame::Response {
2031            envelope: SessionEnvelope {
2032                protocol_version: WALLET_ABI_VERSION,
2033                host_session_id: host_session(),
2034                service_session_id: service_session(),
2035                restart_generation: 7,
2036                channel_sequence: 1,
2037                request_id: request_id(),
2038                body: ServiceResponse::WalletAuthority {
2039                    context: invalid_context,
2040                },
2041            },
2042        };
2043        assert_eq!(
2044            encode_service_frame(&invalid_response),
2045            Err(AbiError::InvalidAuthority)
2046        );
2047    }
2048
2049    #[test]
2050    fn v1_unframed_json_and_unknown_fields_are_rejected() {
2051        assert!(decode_host_frame(br#"{"abi_version":1}"#).is_err());
2052        let payload = br#"{"frameType":"hello","hello":{"protocolVersion":2,"platform":"chromiumNativeHost","hostSessionId":"AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE","restartGeneration":1,"trusted":true}}"#;
2053        let mut frame = (payload.len() as u32).to_be_bytes().to_vec();
2054        frame.extend_from_slice(payload);
2055        assert_eq!(decode_host_frame(&frame), Err(AbiError::InvalidEnvelope));
2056    }
2057
2058    #[test]
2059    fn provider_context_is_only_an_opaque_handle_and_revision() {
2060        let frame = request(ServiceRequest::ProviderRequest {
2061            authority_handle: handle(),
2062            authority_revision: 1,
2063            request_nonce: 9,
2064            method: "wallet_getStatus".to_owned(),
2065            params: Value::Null,
2066        });
2067        let encoded = encode_host_frame(&frame).expect("frame");
2068        let json: Value = serde_json::from_slice(&encoded[LENGTH_PREFIX_BYTES..]).expect("json");
2069        assert_eq!(
2070            json["envelope"]["body"],
2071            serde_json::json!({
2072                "operation": "providerRequest",
2073                "authorityHandle": serde_json::to_value(handle()).expect("handle"),
2074                "authorityRevision": 1,
2075                "requestNonce": 9,
2076                "method": "wallet_getStatus",
2077                "params": null,
2078            })
2079        );
2080        assert_eq!(decode_host_frame(&encoded), Ok(frame));
2081    }
2082
2083    #[test]
2084    fn every_tagged_enum_uses_schema_shaped_camel_case_fields() {
2085        assert_json_round_trip(
2086            &ServiceFrame::Response {
2087                envelope: SessionEnvelope {
2088                    protocol_version: WALLET_ABI_VERSION,
2089                    host_session_id: host_session(),
2090                    service_session_id: service_session(),
2091                    restart_generation: 7,
2092                    channel_sequence: 1,
2093                    request_id: request_id(),
2094                    body: ServiceResponse::AuthorityRegistered {
2095                        authority_handle: handle(),
2096                        authority_revision: 2,
2097                    },
2098                },
2099            },
2100            serde_json::json!({
2101                "frameType": "response",
2102                "envelope": {
2103                    "protocolVersion": WALLET_ABI_VERSION,
2104                    "hostSessionId": serde_json::to_value(host_session()).expect("host session"),
2105                    "serviceSessionId": serde_json::to_value(service_session()).expect("service session"),
2106                    "restartGeneration": 7,
2107                    "channelSequence": 1,
2108                    "requestId": serde_json::to_value(request_id()).expect("request id"),
2109                    "body": {
2110                        "result": "authorityRegistered",
2111                        "authorityHandle": serde_json::to_value(handle()).expect("handle"),
2112                        "authorityRevision": 2,
2113                    },
2114                },
2115            }),
2116        );
2117        assert_json_round_trip(
2118            &WalletRequest::RestoreWallet {
2119                passphrase: SecretString::new("correct horse battery staple".to_owned()),
2120                recovery_phrase: SecretString::new(
2121                    "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
2122                        .to_owned(),
2123                ),
2124            },
2125            serde_json::json!({
2126                "operation": "restoreWallet",
2127                "passphrase": "correct horse battery staple",
2128                "recoveryPhrase": "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",
2129            }),
2130        );
2131        assert_json_round_trip(
2132            &ServiceResponse::AuthorityRegistered {
2133                authority_handle: handle(),
2134                authority_revision: 2,
2135            },
2136            serde_json::json!({
2137                "result": "authorityRegistered",
2138                "authorityHandle": serde_json::to_value(handle()).expect("handle"),
2139                "authorityRevision": 2,
2140            }),
2141        );
2142        assert_json_round_trip(
2143            &WalletResponse::WalletCreated {
2144                wallet_id: wallet_id(),
2145            },
2146            serde_json::json!({
2147                "result": "walletCreated",
2148                "walletId": serde_json::to_value(wallet_id()).expect("wallet id"),
2149            }),
2150        );
2151        assert_json_round_trip(
2152            &ApprovalSummary::TypedSignature {
2153                message_type: "hns-name-auth".to_owned(),
2154                message_digest: "00".repeat(32),
2155            },
2156            serde_json::json!({
2157                "kind": "typedSignature",
2158                "messageType": "hns-name-auth",
2159                "messageDigest": "00".repeat(32),
2160            }),
2161        );
2162        assert_json_round_trip(
2163            &ProviderEventPayload::DirectOfferChanged {
2164                direct_offer_ids: vec!["offer-1".to_owned()],
2165            },
2166            serde_json::json!({
2167                "event": "directOfferChanged",
2168                "directOfferIds": ["offer-1"],
2169            }),
2170        );
2171    }
2172
2173    #[test]
2174    fn provider_outputs_carry_the_private_authority_binding() {
2175        let response = ServiceResponse::ProviderResult {
2176            binding: ProviderBinding {
2177                authority_handle: handle(),
2178                authority_revision: 3,
2179                wallet_session_id: wallet_session(),
2180                permission_generation: 0,
2181            },
2182            value: Value::Null,
2183        };
2184        validate_service_response(&response).expect("fresh generation is valid");
2185        let json = serde_json::to_string(&response).expect("json");
2186        assert!(json.contains("walletSessionId"));
2187        assert!(json.contains("permissionGeneration"));
2188
2189        let prompt = ApprovalPrompt {
2190            approval_id: approval_id(),
2191            binding: ProviderBinding {
2192                authority_handle: handle(),
2193                authority_revision: 3,
2194                wallet_session_id: wallet_session(),
2195                permission_generation: 0,
2196            },
2197            origin: "https://wallet.example".to_owned(),
2198            method: "wallet_requestPermissions".to_owned(),
2199            expires_at_unix_ms: 10_000,
2200            summary: ApprovalSummary::Permissions {
2201                capabilities: BTreeSet::from([PermissionCapability::Balance]),
2202                hns_names: Vec::new(),
2203            },
2204        };
2205        prompt
2206            .validate(ApprovalKind::Permission, 1_000)
2207            .expect("bound prompt");
2208    }
2209
2210    #[test]
2211    fn canonical_provider_account_join_private_capability_snapshot_is_exact_and_bound() {
2212        assert_eq!(
2213            validate_service_request(&ServiceRequest::ProviderCapabilities {
2214                authority_handle: handle(),
2215                authority_revision: 0,
2216            }),
2217            Err(AbiError::InvalidAuthority)
2218        );
2219        let binding = ProviderBinding {
2220            authority_handle: handle(),
2221            authority_revision: 1,
2222            wallet_session_id: wallet_session(),
2223            permission_generation: 0,
2224        };
2225        let capabilities = ProviderCapabilitySnapshot {
2226            provider_schema_version: PROVIDER_SCHEMA_VERSION,
2227            approval_schema_version: APPROVAL_SCHEMA_VERSION,
2228            wallet_session_id: wallet_session(),
2229            permission_generation: 0,
2230            methods: BTreeSet::from(["wallet_getCapabilities".to_owned()]),
2231        };
2232        validate_service_response(&ServiceResponse::ProviderCapabilities {
2233            binding,
2234            capabilities: capabilities.clone(),
2235        })
2236        .expect("matching snapshot");
2237
2238        let mut mismatched = capabilities.clone();
2239        mismatched.permission_generation = 1;
2240        assert_eq!(
2241            validate_service_response(&ServiceResponse::ProviderCapabilities {
2242                binding,
2243                capabilities: mismatched,
2244            }),
2245            Err(AbiError::InvalidEnvelope)
2246        );
2247        let mut mismatched_session = capabilities.clone();
2248        mismatched_session.wallet_session_id =
2249            WalletSessionId::from_bytes([7_u8; 32]).expect("other wallet session");
2250        assert_eq!(
2251            validate_service_response(&ServiceResponse::ProviderCapabilities {
2252                binding,
2253                capabilities: mismatched_session,
2254            }),
2255            Err(AbiError::InvalidEnvelope)
2256        );
2257        let mut invalid_schema = capabilities.clone();
2258        invalid_schema.provider_schema_version += 1;
2259        assert_eq!(
2260            validate_service_response(&ServiceResponse::ProviderCapabilities {
2261                binding,
2262                capabilities: invalid_schema,
2263            }),
2264            Err(AbiError::InvalidEnvelope)
2265        );
2266        let mut unknown_method = capabilities.clone();
2267        unknown_method.methods = BTreeSet::from(["wallet_unknown".to_owned()]);
2268        assert_eq!(
2269            validate_service_response(&ServiceResponse::ProviderCapabilities {
2270                binding,
2271                capabilities: unknown_method,
2272            }),
2273            Err(AbiError::InvalidEnvelope)
2274        );
2275        let mut account_join = capabilities.clone();
2276        account_join.methods = BTreeSet::from(["hns_requestAccounts".to_owned()]);
2277        validate_service_response(&ServiceResponse::ProviderCapabilities {
2278            binding,
2279            capabilities: account_join,
2280        })
2281        .expect("canonical account join method");
2282
2283        let account_prompt = ApprovalPrompt {
2284            approval_id: approval_id(),
2285            binding,
2286            origin: "https://wallet.example".to_owned(),
2287            method: "hns_requestAccounts".to_owned(),
2288            expires_at_unix_ms: 10_000,
2289            summary: ApprovalSummary::Permissions {
2290                capabilities: BTreeSet::from([PermissionCapability::Accounts]),
2291                hns_names: Vec::new(),
2292            },
2293        };
2294        account_prompt
2295            .validate(ApprovalKind::Permission, 1_000)
2296            .expect("exact account permission prompt");
2297        let mut wrong_account_prompt = account_prompt.clone();
2298        wrong_account_prompt.summary = ApprovalSummary::Permissions {
2299            capabilities: BTreeSet::from([PermissionCapability::Balance]),
2300            hns_names: Vec::new(),
2301        };
2302        assert_eq!(
2303            wrong_account_prompt.validate(ApprovalKind::Permission, 1_000),
2304            Err(AbiError::InvalidApproval)
2305        );
2306        let mut generic_accounts = account_prompt;
2307        generic_accounts.method = "wallet_requestPermissions".to_owned();
2308        assert_eq!(
2309            generic_accounts.validate(ApprovalKind::Permission, 1_000),
2310            Err(AbiError::InvalidApproval)
2311        );
2312        let mut oversized_method = capabilities;
2313        oversized_method.methods = BTreeSet::from(["m".repeat(MAX_METHOD_BYTES + 1)]);
2314        assert_eq!(
2315            validate_service_response(&ServiceResponse::ProviderCapabilities {
2316                binding,
2317                capabilities: oversized_method,
2318            }),
2319            Err(AbiError::InvalidEnvelope)
2320        );
2321    }
2322
2323    #[test]
2324    fn production_followup_permission_name_disclosures_are_exact_sorted_and_bounded() {
2325        let alpha = HnsNameDisclosure {
2326            name: "alpha".to_owned(),
2327            name_hash: "271878f8a927b4566ac951fc815b18dfad8d0302d61d11d80cbe15b7a3a056af"
2328                .to_owned(),
2329        };
2330        let beta = HnsNameDisclosure {
2331            name: "beta".to_owned(),
2332            name_hash: "f0277d92062bd9a41dd26cddbaf2c41d576cf7b0173cbe96c23d5f5a4f92cc8f"
2333                .to_owned(),
2334        };
2335        let mut prompt = ApprovalPrompt {
2336            approval_id: approval_id(),
2337            binding: ProviderBinding {
2338                authority_handle: handle(),
2339                authority_revision: 3,
2340                wallet_session_id: wallet_session(),
2341                permission_generation: 1,
2342            },
2343            origin: "https://wallet.example".to_owned(),
2344            method: "wallet_requestPermissions".to_owned(),
2345            expires_at_unix_ms: 10_000,
2346            summary: ApprovalSummary::Permissions {
2347                capabilities: BTreeSet::from([PermissionCapability::Names]),
2348                hns_names: vec![alpha.clone(), beta.clone()],
2349            },
2350        };
2351        prompt
2352            .validate(ApprovalKind::Permission, 1_000)
2353            .expect("sorted exact name disclosure");
2354        let encoded = serde_json::to_value(&prompt).expect("name prompt JSON");
2355        assert_eq!(
2356            encoded["summary"]["hnsNames"],
2357            serde_json::json!([
2358                { "name": "alpha", "nameHash": "271878f8a927b4566ac951fc815b18dfad8d0302d61d11d80cbe15b7a3a056af" },
2359                { "name": "beta", "nameHash": "f0277d92062bd9a41dd26cddbaf2c41d576cf7b0173cbe96c23d5f5a4f92cc8f" },
2360            ])
2361        );
2362
2363        let ApprovalSummary::Permissions { hns_names, .. } = &mut prompt.summary else {
2364            panic!("permission summary")
2365        };
2366        hns_names.swap(0, 1);
2367        assert_eq!(
2368            prompt.validate(ApprovalKind::Permission, 1_000),
2369            Err(AbiError::InvalidApproval)
2370        );
2371
2372        let oversized = (0..=MAX_HNS_NAME_DISCLOSURES)
2373            .map(|index| HnsNameDisclosure {
2374                name: format!("name-{index:03}"),
2375                name_hash: format!("{index:064x}"),
2376            })
2377            .collect();
2378        prompt.summary = ApprovalSummary::Permissions {
2379            capabilities: BTreeSet::from([PermissionCapability::Names]),
2380            hns_names: oversized,
2381        };
2382        assert_eq!(
2383            prompt.validate(ApprovalKind::Permission, 1_000),
2384            Err(AbiError::InvalidApproval)
2385        );
2386
2387        prompt.summary = ApprovalSummary::Permissions {
2388            capabilities: BTreeSet::from([PermissionCapability::Names]),
2389            hns_names: vec![HnsNameDisclosure {
2390                name: "alpha".to_owned(),
2391                name_hash: "f0277d92062bd9a41dd26cddbaf2c41d576cf7b0173cbe96c23d5f5a4f92cc8f"
2392                    .to_owned(),
2393            }],
2394        };
2395        assert_eq!(
2396            prompt.validate(ApprovalKind::Permission, 1_000),
2397            Err(AbiError::InvalidApproval)
2398        );
2399
2400        prompt.summary = ApprovalSummary::Permissions {
2401            capabilities: BTreeSet::from([PermissionCapability::Names]),
2402            hns_names: vec![alpha.clone(), alpha.clone()],
2403        };
2404        assert_eq!(
2405            prompt.validate(ApprovalKind::Permission, 1_000),
2406            Err(AbiError::InvalidApproval)
2407        );
2408
2409        prompt.summary = ApprovalSummary::Permissions {
2410            capabilities: BTreeSet::from([PermissionCapability::Balance]),
2411            hns_names: vec![alpha],
2412        };
2413        assert_eq!(
2414            prompt.validate(ApprovalKind::Permission, 1_000),
2415            Err(AbiError::InvalidApproval)
2416        );
2417        assert!(
2418            serde_json::from_value::<ApprovalSummary>(serde_json::json!({
2419                "kind": "permissions",
2420                "capabilities": ["balance"],
2421            }))
2422            .is_err()
2423        );
2424    }
2425
2426    #[test]
2427    fn event_generation_must_match_its_authority_binding() {
2428        let mut event = ProviderEventEnvelope {
2429            protocol_version: WALLET_ABI_VERSION,
2430            host_session_id: host_session(),
2431            service_session_id: service_session(),
2432            restart_generation: 1,
2433            channel_sequence: 1,
2434            binding: ProviderBinding {
2435                authority_handle: handle(),
2436                authority_revision: 1,
2437                wallet_session_id: wallet_session(),
2438                permission_generation: 6,
2439            },
2440            event_sequence: 1,
2441            payload: ProviderEventPayload::Connect {
2442                permission_generation: 7,
2443            },
2444        };
2445        assert_eq!(
2446            validate_service_frame(&ServiceFrame::Event {
2447                event: event.clone()
2448            }),
2449            Err(AbiError::InvalidEvent)
2450        );
2451        event.binding.permission_generation = 7;
2452        validate_service_frame(&ServiceFrame::Event { event }).expect("matching generation");
2453    }
2454
2455    #[test]
2456    fn oversized_declared_payload_fails_before_payload_allocation() {
2457        assert_eq!(
2458            declared_payload_len(((MAX_ABI_FRAME_BYTES as u32) + 1).to_be_bytes()),
2459            Err(AbiError::FrameSize)
2460        );
2461    }
2462
2463    #[test]
2464    fn every_provider_approval_kind_has_a_typed_wire_variant() {
2465        let kinds = [
2466            ApprovalKind::Permission,
2467            ApprovalKind::ModuleEnablement,
2468            ApprovalKind::Send,
2469            ApprovalKind::NameTransfer,
2470            ApprovalKind::NameFinalize,
2471            ApprovalKind::TypedSignature,
2472            ApprovalKind::NameMarketOffer,
2473            ApprovalKind::NameMarketPurchase,
2474            ApprovalKind::DirectOffer,
2475            ApprovalKind::DirectOfferAcceptance,
2476            ApprovalKind::SwapRedeem,
2477            ApprovalKind::SwapRefund,
2478        ];
2479        assert_eq!(kinds.len(), 12);
2480        assert!(!kinds.contains(&ApprovalKind::RecoveryPhraseDisplay));
2481    }
2482}