Skip to main content

hns_wallet_types/
lib.rs

1#![doc = "Wallet-local semantics which are not canonical chain or wire types."]
2#![forbid(unsafe_code)]
3
4use core::fmt;
5use serde::{Deserialize, Deserializer, Serialize, Serializer};
6use thiserror::Error;
7
8/// The complete canonical website-provider method vocabulary in stable enum
9/// order. Availability is negotiated separately.
10pub const PROVIDER_METHOD_WIRE_NAMES: [&str; 44] = [
11    "wallet_getCapabilities",
12    "wallet_getEnabledModules",
13    "wallet_enableModule",
14    "wallet_disableModule",
15    "wallet_requestPermissions",
16    "wallet_getPermissions",
17    "wallet_revokePermissions",
18    "wallet_lock",
19    "wallet_getStatus",
20    "hns_requestAccounts",
21    "hns_accounts",
22    "hns_getBalance",
23    "hns_getTransactions",
24    "hns_getReceiveAddress",
25    "hns_send",
26    "hns_getNames",
27    "hns_getName",
28    "hns_importKnownName",
29    "hns_transferName",
30    "hns_finalizeName",
31    "hns_signTypedMessage",
32    "asset_getAccount",
33    "asset_getBalance",
34    "asset_getTransactions",
35    "asset_getReceiveTarget",
36    "asset_send",
37    "nameMarket_listOffers",
38    "nameMarket_createFixedPriceOffer",
39    "nameMarket_cancelOffer",
40    "nameMarket_acceptOffer",
41    "nameMarket_getSession",
42    "nameMarket_finalizePurchase",
43    "nameMarket_recoverName",
44    "swap_getSupportedPairs",
45    "swap_listDirectOffers",
46    "swap_publishDirectOffer",
47    "swap_cancelDirectOffer",
48    "swap_acceptDirectOffer",
49    "swap_getSession",
50    "swap_redeem",
51    "swap_refund",
52    "hns_updateName",
53    "nameMarket_listMyOffers",
54    "nameMarket_getOffer",
55];
56
57macro_rules! semantic_id {
58    ($name:ident, $size:expr) => {
59        #[derive(
60            Clone, Copy, Default, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize,
61        )]
62        pub struct $name([u8; $size]);
63
64        impl $name {
65            pub const LENGTH: usize = $size;
66
67            pub const fn new(bytes: [u8; $size]) -> Self {
68                Self(bytes)
69            }
70
71            pub const fn as_bytes(&self) -> &[u8; $size] {
72                &self.0
73            }
74
75            pub const fn into_bytes(self) -> [u8; $size] {
76                self.0
77            }
78        }
79
80        impl fmt::Debug for $name {
81            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
82                write!(formatter, "{}({})", stringify!($name), hex::encode(self.0))
83            }
84        }
85
86        impl fmt::Display for $name {
87            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
88                formatter.write_str(&hex::encode(self.0))
89            }
90        }
91    };
92}
93
94semantic_id!(WalletId, 16);
95semantic_id!(AccountId, 16);
96semantic_id!(ApprovalId, 16);
97semantic_id!(PermissionId, 16);
98semantic_id!(WorkflowId, 16);
99semantic_id!(SessionId, 32);
100semantic_id!(ObjectHash, 32);
101semantic_id!(TransactionHash, 32);
102
103const BASE64URL_ALPHABET: &[u8; 64] =
104    b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
105
106fn encode_wire_id(bytes: &[u8]) -> String {
107    let mut encoded = String::with_capacity((bytes.len() * 4).div_ceil(3));
108    let mut index = 0;
109    while index + 3 <= bytes.len() {
110        let first = bytes[index];
111        let second = bytes[index + 1];
112        let third = bytes[index + 2];
113        encoded.push(BASE64URL_ALPHABET[(first >> 2) as usize] as char);
114        encoded.push(BASE64URL_ALPHABET[(((first & 0x03) << 4) | (second >> 4)) as usize] as char);
115        encoded.push(BASE64URL_ALPHABET[(((second & 0x0f) << 2) | (third >> 6)) as usize] as char);
116        encoded.push(BASE64URL_ALPHABET[(third & 0x3f) as usize] as char);
117        index += 3;
118    }
119    match bytes.len() - index {
120        1 => {
121            let first = bytes[index];
122            encoded.push(BASE64URL_ALPHABET[(first >> 2) as usize] as char);
123            encoded.push(BASE64URL_ALPHABET[((first & 0x03) << 4) as usize] as char);
124        }
125        2 => {
126            let first = bytes[index];
127            let second = bytes[index + 1];
128            encoded.push(BASE64URL_ALPHABET[(first >> 2) as usize] as char);
129            encoded
130                .push(BASE64URL_ALPHABET[(((first & 0x03) << 4) | (second >> 4)) as usize] as char);
131            encoded.push(BASE64URL_ALPHABET[((second & 0x0f) << 2) as usize] as char);
132        }
133        _ => {}
134    }
135    encoded
136}
137
138fn decode_wire_id(encoded: &str, bytes: &mut [u8]) -> Result<(), WireIdError> {
139    fn value(byte: u8) -> Option<u8> {
140        match byte {
141            b'A'..=b'Z' => Some(byte - b'A'),
142            b'a'..=b'z' => Some(byte - b'a' + 26),
143            b'0'..=b'9' => Some(byte - b'0' + 52),
144            b'-' => Some(62),
145            b'_' => Some(63),
146            _ => None,
147        }
148    }
149
150    let input = encoded.as_bytes();
151    let mut input_index = 0;
152    let mut output_index = 0;
153    while input_index + 4 <= input.len() {
154        let first = value(input[input_index]).ok_or(WireIdError::NonCanonical)?;
155        let second = value(input[input_index + 1]).ok_or(WireIdError::NonCanonical)?;
156        let third = value(input[input_index + 2]).ok_or(WireIdError::NonCanonical)?;
157        let fourth = value(input[input_index + 3]).ok_or(WireIdError::NonCanonical)?;
158        if output_index + 3 > bytes.len() {
159            return Err(WireIdError::NonCanonical);
160        }
161        bytes[output_index] = (first << 2) | (second >> 4);
162        bytes[output_index + 1] = (second << 4) | (third >> 2);
163        bytes[output_index + 2] = (third << 6) | fourth;
164        input_index += 4;
165        output_index += 3;
166    }
167    match input.len() - input_index {
168        2 => {
169            let first = value(input[input_index]).ok_or(WireIdError::NonCanonical)?;
170            let second = value(input[input_index + 1]).ok_or(WireIdError::NonCanonical)?;
171            if second & 0x0f != 0 || output_index >= bytes.len() {
172                return Err(WireIdError::NonCanonical);
173            }
174            bytes[output_index] = (first << 2) | (second >> 4);
175            output_index += 1;
176        }
177        3 => {
178            let first = value(input[input_index]).ok_or(WireIdError::NonCanonical)?;
179            let second = value(input[input_index + 1]).ok_or(WireIdError::NonCanonical)?;
180            let third = value(input[input_index + 2]).ok_or(WireIdError::NonCanonical)?;
181            if third & 0x03 != 0 || output_index + 2 > bytes.len() {
182                return Err(WireIdError::NonCanonical);
183            }
184            bytes[output_index] = (first << 2) | (second >> 4);
185            bytes[output_index + 1] = (second << 4) | (third >> 2);
186            output_index += 2;
187        }
188        0 => {}
189        _ => return Err(WireIdError::NonCanonical),
190    }
191    if output_index != bytes.len() {
192        return Err(WireIdError::NonCanonical);
193    }
194    Ok(())
195}
196
197macro_rules! wire_id {
198    ($name:ident, $size:expr) => {
199        /// Canonical non-zero identifier used only by the wallet service wire
200        /// protocol. Its JSON representation is fixed-width unpadded base64url;
201        /// persisted wallet identifiers deliberately retain their existing
202        /// serialization.
203        #[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
204        pub struct $name([u8; $size]);
205
206        impl $name {
207            pub const LENGTH: usize = $size;
208            pub const ENCODED_LENGTH: usize = ($size * 4_usize).div_ceil(3);
209
210            pub fn from_bytes(bytes: [u8; $size]) -> Result<Self, WireIdError> {
211                if bytes == [0_u8; $size] {
212                    return Err(WireIdError::Zero);
213                }
214                Ok(Self(bytes))
215            }
216
217            pub fn parse(encoded: &str) -> Result<Self, WireIdError> {
218                if encoded.len() != Self::ENCODED_LENGTH {
219                    return Err(WireIdError::NonCanonical);
220                }
221                let mut bytes = [0_u8; $size];
222                decode_wire_id(encoded, &mut bytes)?;
223                Self::from_bytes(bytes)
224            }
225
226            pub const fn as_bytes(&self) -> &[u8; $size] {
227                &self.0
228            }
229
230            pub const fn into_bytes(self) -> [u8; $size] {
231                self.0
232            }
233        }
234
235        impl fmt::Debug for $name {
236            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
237                write!(formatter, "{}(<redacted>)", stringify!($name))
238            }
239        }
240
241        impl fmt::Display for $name {
242            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
243                formatter.write_str("<redacted>")
244            }
245        }
246
247        impl Serialize for $name {
248            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
249            where
250                S: Serializer,
251            {
252                serializer.serialize_str(&encode_wire_id(&self.0))
253            }
254        }
255
256        impl<'de> Deserialize<'de> for $name {
257            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
258            where
259                D: Deserializer<'de>,
260            {
261                let encoded = <&str>::deserialize(deserializer)?;
262                Self::parse(encoded).map_err(serde::de::Error::custom)
263            }
264        }
265    };
266}
267
268wire_id!(HostSessionId, 32);
269wire_id!(WalletServiceSessionId, 32);
270wire_id!(WalletSessionId, 32);
271wire_id!(HostAuthorityHandleId, 32);
272wire_id!(BrowserRuntimeSessionId, 16);
273wire_id!(ProviderAuthorityFingerprint, 32);
274wire_id!(ProviderRequestId, 16);
275wire_id!(ProviderApprovalId, 16);
276
277/// A wallet-local module selector. Canonical marketplace wire identifiers live
278/// in `hns-rs`; this enum selects an installed wallet implementation.
279#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
280#[serde(rename_all = "lowercase")]
281pub enum ModuleId {
282    Handshake,
283    Bitcoin,
284    Ethereum,
285}
286
287impl ModuleId {
288    pub const fn asset(self) -> WalletAsset {
289        match self {
290            Self::Handshake => WalletAsset::Hns,
291            Self::Bitcoin => WalletAsset::Btc,
292            Self::Ethereum => WalletAsset::Eth,
293        }
294    }
295}
296
297#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
298#[serde(rename_all = "UPPERCASE")]
299pub enum WalletAsset {
300    Hns,
301    Btc,
302    Eth,
303}
304
305/// Integer base units serialized as a decimal string so JavaScript cannot lose
306/// precision.
307#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
308pub struct BaseUnits(u128);
309
310impl BaseUnits {
311    pub const ZERO: Self = Self(0);
312
313    pub const fn new(value: u128) -> Self {
314        Self(value)
315    }
316
317    pub const fn get(self) -> u128 {
318        self.0
319    }
320
321    pub fn checked_add(self, other: Self) -> Result<Self, AmountError> {
322        self.0
323            .checked_add(other.0)
324            .map(Self)
325            .ok_or(AmountError::Overflow)
326    }
327
328    pub fn checked_sub(self, other: Self) -> Result<Self, AmountError> {
329        self.0
330            .checked_sub(other.0)
331            .map(Self)
332            .ok_or(AmountError::Underflow)
333    }
334
335    pub const fn is_zero(self) -> bool {
336        self.0 == 0
337    }
338}
339
340impl Serialize for BaseUnits {
341    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
342    where
343        S: Serializer,
344    {
345        serializer.serialize_str(&self.0.to_string())
346    }
347}
348
349impl<'de> Deserialize<'de> for BaseUnits {
350    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
351    where
352        D: Deserializer<'de>,
353    {
354        let text = String::deserialize(deserializer)?;
355        text.parse::<u128>()
356            .map(Self)
357            .map_err(serde::de::Error::custom)
358    }
359}
360
361#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
362pub enum AmountError {
363    #[error("amount overflow")]
364    Overflow,
365    #[error("amount underflow")]
366    Underflow,
367    #[error("amount asset mismatch")]
368    AssetMismatch,
369}
370
371#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
372pub struct Amount {
373    pub asset: WalletAsset,
374    pub base_units: BaseUnits,
375}
376
377impl Amount {
378    pub const fn new(asset: WalletAsset, base_units: u128) -> Self {
379        Self {
380            asset,
381            base_units: BaseUnits::new(base_units),
382        }
383    }
384
385    pub fn checked_add(self, other: Self) -> Result<Self, AmountError> {
386        if self.asset != other.asset {
387            return Err(AmountError::AssetMismatch);
388        }
389        Ok(Self {
390            asset: self.asset,
391            base_units: self.base_units.checked_add(other.base_units)?,
392        })
393    }
394}
395
396#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
397#[serde(rename_all = "snake_case")]
398pub enum SyncPhase {
399    Disabled,
400    Starting,
401    Headers,
402    Filters,
403    WalletScan,
404    Ready,
405    Degraded,
406}
407
408#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
409pub struct SyncStatus {
410    pub phase: SyncPhase,
411    pub validated_height: u64,
412    pub scanned_height: u64,
413    pub target_height: Option<u64>,
414    pub last_error: Option<String>,
415}
416
417#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
418#[serde(rename_all = "snake_case")]
419pub enum LocalTransactionStatus {
420    Prepared,
421    Authorized,
422    Broadcast,
423    Mempool,
424    Confirmed,
425    Replaced,
426    Conflicted,
427    Reorged,
428    Dropped,
429    Failed,
430}
431
432#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
433pub struct TransactionSummary {
434    pub module: ModuleId,
435    pub txid: TransactionHash,
436    pub status: LocalTransactionStatus,
437    pub net_amount: SignedBaseUnits,
438    pub fee: Option<BaseUnits>,
439    pub block_height: Option<u64>,
440    pub first_seen_unix: Option<u64>,
441    pub confirmation_count: u32,
442}
443
444#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
445pub struct SignedBaseUnits {
446    pub negative: bool,
447    pub magnitude: BaseUnits,
448}
449
450#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
451pub struct ReceiveTarget {
452    pub module: ModuleId,
453    pub account: AccountId,
454    pub display: String,
455    pub derivation_index: u32,
456}
457
458impl ReceiveTarget {
459    pub fn validate(&self) -> Result<(), TypeError> {
460        if self.display.is_empty() || self.display.len() > 512 {
461            return Err(TypeError::InvalidLength {
462                field: "receive target",
463                maximum: 512,
464            });
465        }
466        Ok(())
467    }
468}
469
470/// Dedicated Handshake name-owner receive target.
471///
472/// This is intentionally a different type from [`ReceiveTarget`]: a name
473/// owner must be derived from the `HnsName` branch and must never be reused as
474/// an ordinary HNS coin receive target. The HNS runtime is responsible for
475/// enforcing that role, account, change-zero, and synchronized-index binding
476/// before constructing this projection.
477#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
478pub struct HnsNameReceiveTarget {
479    pub module: ModuleId,
480    pub account: AccountId,
481    pub display: String,
482    pub derivation_index: u32,
483}
484
485impl HnsNameReceiveTarget {
486    pub fn validate(&self) -> Result<(), TypeError> {
487        if self.module != ModuleId::Handshake {
488            return Err(TypeError::InvalidModule {
489                field: "HNS name receive target",
490                expected: "handshake",
491            });
492        }
493        if self.display.is_empty() || self.display.len() > 512 {
494            return Err(TypeError::InvalidLength {
495                field: "HNS name receive target",
496                maximum: 512,
497            });
498        }
499        Ok(())
500    }
501}
502
503#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
504pub struct DerivationReference {
505    pub role: KeyRole,
506    pub account: u32,
507    pub change: u32,
508    pub index: u32,
509}
510
511#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
512#[serde(rename_all = "snake_case")]
513pub enum KeyRole {
514    HnsCoin,
515    HnsName,
516    HnsShakedex,
517    HnsAtomicSwap,
518    HnsIdentity,
519    HnsDappSession,
520    BitcoinWallet,
521    BitcoinAtomicSwap,
522    EthereumWallet,
523    EthereumAtomicSwap,
524    MetadataEncryption,
525}
526
527#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
528pub struct ChainCapabilities {
529    pub receive: bool,
530    pub send: bool,
531    pub history: bool,
532    pub atomic_settlement: bool,
533    pub hash_algorithm: HashAlgorithm,
534    pub locktime_model: LocktimeModel,
535    pub finality_model: FinalityModel,
536    pub fee_model: FeeModel,
537}
538
539#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
540#[serde(rename_all = "snake_case")]
541pub enum HashAlgorithm {
542    Sha256,
543    Keccak256,
544}
545
546#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
547#[serde(rename_all = "snake_case")]
548pub enum LocktimeModel {
549    None,
550    BlockHeight,
551    UnixTime,
552    SmartContractTimestamp,
553}
554
555#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
556#[serde(rename_all = "snake_case")]
557pub enum FinalityModel {
558    ProofOfWorkConfirmations,
559    EthereumFinalizedCheckpoint,
560}
561
562#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
563#[serde(rename_all = "snake_case")]
564pub enum FeeModel {
565    WeightRate,
566    GasAndPriority,
567}
568
569#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
570#[serde(rename_all = "snake_case")]
571pub enum PermissionCapability {
572    Accounts,
573    Balance,
574    Transactions,
575    ReceiveTarget,
576    Send,
577    Names,
578    NameTransfer,
579    NameFinalize,
580    NameUpdate,
581    TypedIdentitySignature,
582    NameMarket,
583    CrossChainMarket,
584    SwapSettlement,
585}
586
587#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
588#[serde(rename_all = "snake_case")]
589pub enum ApprovalKind {
590    Permission,
591    ModuleEnablement,
592    Send,
593    NameTransfer,
594    NameFinalize,
595    NameUpdate,
596    TypedSignature,
597    NameMarketOffer,
598    NameMarketPurchase,
599    DirectOffer,
600    DirectOfferAcceptance,
601    SwapRedeem,
602    SwapRefund,
603    RecoveryPhraseDisplay,
604}
605
606#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
607#[serde(rename_all = "snake_case")]
608pub enum WorkflowKind {
609    HnsSend,
610    NameTransfer,
611    NameFinalize,
612    NameUpdate,
613    ShakedexSeller,
614    ShakedexBuyer,
615    ShakedexSellerPlan,
616    ShakedexBuyerPlan,
617    ShakedexSellerOffer,
618    ShakedexValue,
619    DirectOffer,
620    DirectOfferAcceptance,
621    AtomicSwap,
622    Refund,
623}
624
625#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
626pub struct PersistedWorkflowReference {
627    pub id: WorkflowId,
628    pub kind: WorkflowKind,
629    pub revision: u64,
630}
631
632#[derive(Clone, Debug, Eq, Error, PartialEq)]
633pub enum TypeError {
634    #[error("{field} is empty or exceeds {maximum} bytes")]
635    InvalidLength { field: &'static str, maximum: usize },
636    #[error("{field} must use the {expected} module")]
637    InvalidModule {
638        field: &'static str,
639        expected: &'static str,
640    },
641}
642
643#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
644pub enum WireIdError {
645    #[error("wire identifier must use fixed-width unpadded base64url")]
646    NonCanonical,
647    #[error("wire identifier cannot be the all-zero sentinel")]
648    Zero,
649}
650
651#[cfg(test)]
652mod tests {
653    use super::*;
654
655    #[test]
656    fn base_units_are_json_strings_and_checked() {
657        let maximum = BaseUnits::new(u128::MAX);
658        assert_eq!(
659            serde_json::to_string(&maximum).expect("serialize"),
660            format!("\"{}\"", u128::MAX)
661        );
662        assert_eq!(
663            serde_json::from_str::<BaseUnits>("\"42\"").expect("deserialize"),
664            BaseUnits::new(42)
665        );
666        assert_eq!(
667            maximum.checked_add(BaseUnits::new(1)),
668            Err(AmountError::Overflow)
669        );
670    }
671
672    #[test]
673    fn module_assets_cannot_be_confused() {
674        assert_eq!(ModuleId::Handshake.asset(), WalletAsset::Hns);
675        assert_eq!(ModuleId::Bitcoin.asset(), WalletAsset::Btc);
676        assert_eq!(ModuleId::Ethereum.asset(), WalletAsset::Eth);
677        assert_eq!(
678            Amount::new(WalletAsset::Hns, 1).checked_add(Amount::new(WalletAsset::Btc, 1)),
679            Err(AmountError::AssetMismatch)
680        );
681    }
682
683    #[test]
684    fn hns_name_receive_target_is_a_bounded_distinct_dto() {
685        let target = HnsNameReceiveTarget {
686            module: ModuleId::Handshake,
687            account: AccountId::new([7; 16]),
688            display: "rs1qnameowner".to_owned(),
689            derivation_index: 9,
690        };
691        target.validate().expect("bounded name receive target");
692        let encoded = serde_json::to_vec(&target).expect("encode name receive target");
693        assert_eq!(
694            serde_json::from_slice::<HnsNameReceiveTarget>(&encoded)
695                .expect("decode name receive target"),
696            target
697        );
698        assert!(
699            HnsNameReceiveTarget {
700                display: String::new(),
701                ..target.clone()
702            }
703            .validate()
704            .is_err()
705        );
706        assert!(
707            HnsNameReceiveTarget {
708                display: "x".repeat(513),
709                ..target.clone()
710            }
711            .validate()
712            .is_err()
713        );
714        HnsNameReceiveTarget {
715            display: "x".repeat(512),
716            ..target
717        }
718        .validate()
719        .expect("maximum-length name receive target");
720        assert!(matches!(
721            HnsNameReceiveTarget {
722                module: ModuleId::Bitcoin,
723                account: AccountId::new([7; 16]),
724                display: "bc1qnotahnsnameowner".to_owned(),
725                derivation_index: 9,
726            }
727            .validate(),
728            Err(TypeError::InvalidModule {
729                field: "HNS name receive target",
730                expected: "handshake",
731            })
732        ));
733    }
734
735    #[test]
736    fn service_wire_ids_have_one_canonical_non_zero_encoding() {
737        let id = ProviderRequestId::from_bytes([1_u8; 16]).expect("non-zero identifier");
738        let encoded = serde_json::to_string(&id).expect("serialize");
739        assert_eq!(encoded, "\"AQEBAQEBAQEBAQEBAQEBAQ\"");
740        assert_eq!(
741            serde_json::from_str::<ProviderRequestId>(&encoded).expect("deserialize"),
742            id
743        );
744        assert!(serde_json::from_str::<ProviderRequestId>("\"AQEBAQEBAQEBAQEBAQEBAg\"").is_ok());
745        assert!(serde_json::from_str::<ProviderRequestId>("\"AQEBAQEBAQEBAQEBAQEBAR\"").is_err());
746        assert!(serde_json::from_str::<ProviderRequestId>("\"AQEBAQEBAQEBAQEBAQEBAQ==\"").is_err());
747        assert!(ProviderRequestId::from_bytes([0_u8; 16]).is_err());
748        assert!(!format!("{id:?}").contains("AQEBA"));
749        assert_eq!(format!("{id}"), "<redacted>");
750    }
751}