Skip to main content

xmtp_mls/client/
identity.rs

1//! Client identity reads: inbox lookups, states and update counts, credential
2//! validation, reachability and handles.
3
4use super::*;
5
6impl<Context> Client<Context>
7where
8    Context: XmtpSharedContext,
9{
10    /// The inbox that holds `identifier`, or `None`. The backend's answer
11    /// counts only when the newest state the client derives for the answered
12    /// inbox holds the identifier.
13    pub async fn find_inbox_id_from_identifier(
14        &self,
15        identifier: Identifier,
16    ) -> Result<Option<String>, ClientError> {
17        Ok(
18            resolve_verified_in(&self.context, &[IdentityTarget::Account(identifier)])
19                .await?
20                .pop()
21                .flatten(),
22        )
23    }
24
25    /// Get the highest `sequence_id` from the local database for the client's `inbox_id`.
26    /// This may not be consistent with the latest state on the backend.
27    pub fn inbox_sequence_id(
28        &self,
29        conn: &DbConnection<<Context::Db as XmtpDb>::Connection>,
30    ) -> Result<i64, StorageError> {
31        self.context
32            .identity()
33            .sequence_id(conn)
34            .map_err(Into::into)
35    }
36
37    /// Get the [`AssociationState`] for the client's `inbox_id`
38    pub async fn inbox_state(
39        &self,
40        refresh_from_network: bool,
41    ) -> Result<AssociationState, ClientError> {
42        let conn = self.context.db();
43        let inbox_id = self.inbox_id();
44        if refresh_from_network {
45            load_identity_updates_for_client(&self.context, &conn, &[inbox_id]).await?;
46        }
47        let identity_service = IdentityUpdates::new(&self.context);
48        let state = identity_service
49            .get_association_state(&conn, inbox_id, None)
50            .await?;
51        Ok(state)
52    }
53
54    /// Get the [`AssociationState`] for each `inbox_id`
55    pub async fn inbox_addresses(
56        &self,
57        refresh_from_network: bool,
58        inbox_ids: Vec<InboxIdRef<'_>>,
59    ) -> Result<Vec<AssociationState>, ClientError> {
60        let conn = self.context.db();
61        if refresh_from_network {
62            load_identity_updates_for_client(&self.context, &conn, &inbox_ids).await?;
63        }
64        let identity_service = IdentityUpdates::new(&self.context);
65        let state = identity_service
66            .batch_get_association_state(
67                &conn,
68                &inbox_ids.into_iter().map(|i| (i, None)).collect::<Vec<_>>(),
69            )
70            .await?;
71        Ok(state)
72    }
73
74    /// Get the total number of inbox updates for `inbox_ids`. `refresh_from_network` will force
75    /// a network refresh. May still access network if an inbox_id does not yet exist in the local
76    /// cache.
77    pub async fn fetch_inbox_updates_count(
78        &self,
79        refresh_from_network: bool,
80        inbox_ids: Vec<InboxIdRef<'_>>,
81    ) -> Result<HashMap<InboxId, u32>, ClientError> {
82        let conn = self.context.db();
83        if refresh_from_network {
84            load_identity_updates_for_client(&self.context, &conn, &inbox_ids).await?;
85        }
86        let inbox_id_strs = inbox_ids.to_vec();
87        let counts = conn.count_inbox_updates(&inbox_id_strs)?;
88        Ok(counts.into_iter().map(|(k, v)| (k, v as u32)).collect())
89    }
90
91    /// Get the total number of inbox updates for the client's inbox_id.
92    /// Setting `refresh_from_network` forces a network refresh, otherwise
93    /// this operation is offline.
94    pub async fn fetch_own_inbox_updates_count(
95        &self,
96        refresh_from_network: bool,
97    ) -> Result<u32, ClientError> {
98        let inbox_id = self.inbox_id();
99        Ok(self
100            .fetch_inbox_updates_count(refresh_from_network, vec![inbox_id])
101            .await?
102            .get(inbox_id)
103            .copied()
104            .unwrap_or(0))
105    }
106
107    /// Get the signature kind used to create an inbox.
108    ///
109    /// # Arguments
110    /// * `inbox_id` - The inbox ID to check
111    /// * `refresh_from_network` - Whether to fetch updates from the network first
112    ///
113    /// # Returns
114    /// * `Some(SignatureKind)` - The signature kind used to create the inbox
115    /// * `None` - Inbox doesn't exist or creation info is unavailable
116    pub async fn inbox_creation_signature_kind(
117        &self,
118        inbox_id: InboxIdRef<'_>,
119        refresh_from_network: bool,
120    ) -> Result<Option<xmtp_id::associations::SignatureKind>, ClientError> {
121        let conn = self.context.db();
122
123        // Load the first identity update (creation update) for this inbox if requested
124        if refresh_from_network {
125            load_identity_updates_for_client(&self.context, &conn, &[inbox_id]).await?;
126        }
127
128        let verifier = self.context.scw_verifier();
129
130        let signature_kind = get_creation_signature_kind(&conn, verifier, inbox_id).await?;
131
132        Ok(signature_kind)
133    }
134
135    /**
136     * Validates a credential against the given installation public key
137     *
138     * This will go to the network and get the latest association state for the inbox.
139     * It ensures that the installation_pub_key is in that association state
140     */
141    pub async fn validate_credential_against_network(
142        &self,
143        conn: &DbConnection<<Context::Db as XmtpDb>::Connection>,
144        credential: &[u8],
145        installation_pub_key: Vec<u8>,
146    ) -> Result<InboxId, ClientError> {
147        let inbox_id = parse_credential(credential)?;
148        let association_state = IdentityUpdates::new(&self.context)
149            .get_latest_association_state(conn, &inbox_id)
150            .await?;
151        let ident = MemberIdentifier::installation(installation_pub_key);
152
153        match association_state.get(&ident) {
154            Some(_) => Ok(inbox_id),
155            None => Err(IdentityError::InstallationIdNotFound(inbox_id).into()),
156        }
157    }
158
159    /// Reports whether the backend names an inbox for each identifier.
160    /// This is an unverified availability hint. The client does not independently
161    /// verify the lookup against current association state or check
162    /// key packages. This is not a delivery guarantee.
163    ///
164    /// Arguments:
165    /// - account_identifier: a list of account identifiers to check
166    ///
167    /// Returns:
168    /// A map from each identifier to its availability hint.
169    pub async fn can_message(
170        &self,
171        account_identifiers: &[Identifier],
172    ) -> Result<HashMap<Identifier, bool>, ClientError> {
173        // A client with a blocked connection issues no request. The blocked connection
174        // alone, not `ensure_identity_ready`, because this answers before the
175        // caller has registered an identity.
176        self.context.server_configuration().check()?;
177        let requests = account_identifiers.iter().map(Into::into).collect();
178
179        let results = self.context.api().get_inbox_ids(requests).await?;
180        Ok(account_identifiers
181            .iter()
182            .cloned()
183            .zip(results.into_iter().map(|inbox_id| inbox_id.is_some()))
184            .collect())
185    }
186}
187
188impl<Context: XmtpSharedContext> Client<Context> {
189    /// The inbox that holds each handle, in order, or `None`. An answer from
190    /// the backend counts only when the newest state the client derives for
191    /// the answered inbox holds the handle. An old handle of an inbox still
192    /// resolves to it.
193    pub async fn resolve_handles(
194        &self,
195        handles: &[Handle],
196    ) -> Result<Vec<Option<InboxId>>, ClientError> {
197        Ok(inbox_handles::resolve_verified_in(
198            &self.context,
199            &inbox_handles::handle_targets(handles),
200        )
201        .await?)
202    }
203
204    /// Whether the backend names an inbox for each handle, in order. This
205    /// checks no association state: use it only where a wrong answer costs a
206    /// candidate, never to reach an inbox.
207    pub async fn handles_have_owner(&self, handles: &[Handle]) -> Result<Vec<bool>, ClientError> {
208        Ok(inbox_handles::handles_have_owner(&self.context, handles).await?)
209    }
210
211    /// The handles for `input` that no inbox holds. `input` is a handle as a
212    /// user typed it; its ASCII capitals become lowercase. Input with a code
213    /// checks only that handle. A name without a code checks the name and
214    /// [`HANDLE_SEARCH_CODES`](inbox_handles::HANDLE_SEARCH_CODES) distinct random codes in one lookup, and the
215    /// name comes first in the result. Text outside the handle grammar fails
216    /// before any request. No policy applies here, so a returned handle can
217    /// still be refused when it is claimed.
218    pub async fn available_handles(&self, input: &str) -> Result<Vec<Handle>, ClientError> {
219        Ok(inbox_handles::available_handles(&self.context, input).await?)
220    }
221
222    /// Claim `handle` for this client's inbox, signed by this installation's
223    /// key. A claim of a handle the inbox already holds makes it the display
224    /// handle again. The backend refuses a taken, reserved, short, or too
225    /// frequent claim with `ApiError::HandleRejected`. After the publish, the
226    /// client has stored the inbox's new identity update.
227    pub async fn claim_handle(&self, handle: &Handle) -> Result<(), ClientError> {
228        self.ensure_identity_ready::<ClientError>()?;
229        Ok(inbox_handles::claim_handle(&self.context, handle).await?)
230    }
231
232    /// The inbox of each target, in order, from one call. Fails when any
233    /// target has no inbox: an account as `find_or_create_dm_by_identity`
234    /// does, and a handle with [`HandleError::NotFound`].
235    pub async fn resolve_targets(
236        &self,
237        targets: &[IdentityTarget],
238    ) -> Result<Vec<InboxId>, ClientError> {
239        Ok(inbox_handles::resolve_targets(&self.context, targets).await?)
240    }
241}