Skip to main content

xmtp_mls/client/
registration.rs

1//! Client registration: registering the identity, waiting for it to be visible, and
2//! key package rotation.
3
4use super::*;
5
6const REGISTRATION_INITIAL_BACKOFF: std::time::Duration = std::time::Duration::from_millis(50);
7const REGISTRATION_MAX_BACKOFF: std::time::Duration = std::time::Duration::from_secs(1);
8
9impl<Context> Client<Context>
10where
11    Context: XmtpSharedContext,
12{
13    /// Register this installation with an inbox owner and wait until it is visible.
14    pub async fn register_with_owner(&self, owner: &impl InboxOwner) -> Result<(), ClientError> {
15        if self.identity().is_ready() {
16            return self.ensure_registration_visible().await;
17        }
18
19        let mut signature_request = self
20            .context
21            .signature_request()
22            .ok_or(SignatureRequestError::MissingSigner)?;
23        let signature = owner
24            .sign(&signature_request.signature_text())
25            .map_err(SignatureError::from)?;
26        signature_request
27            .add_signature(signature, self.scw_verifier())
28            .await?;
29        self.register_identity(signature_request).await
30    }
31
32    /// Upload the key package before the identity update exposes this installation.
33    /// Record its receipt for key retirement and retain the registration cursor.
34    /// Return success only after the backend can read the registration receipt.
35    #[xmtp_common::mls_span]
36    pub async fn register_identity(
37        &self,
38        signature_request: SignatureRequest,
39    ) -> Result<(), ClientError> {
40        tracing::info!("registering identity");
41        // Registration is a network call like any other.
42        self.context.server_configuration().check()?;
43
44        // Resume visibility confirmation after a stored registration.
45        let stored_identity: Option<StoredIdentity> = self.context.db().fetch(&())?;
46        if stored_identity.is_some() {
47            tracing::info!("Resuming stored identity registration");
48            self.identity().set_ready();
49            return self.ensure_registration_visible().await;
50        }
51
52        // Step 1: Generate key package and store locally (not uploaded yet)
53        let (kp_bytes, history_id) = crate::identity_lifecycle::generate_and_store_key_package(
54            self.identity(),
55            self.context.mls_storage(),
56            CREATE_PQ_KEY_PACKAGE_EXTENSION,
57        )?;
58
59        // Step 2: Validate signatures (fails here if invalid - no network pollution)
60        let identity_update = signature_request
61            .build_identity_update()
62            .map_err(IdentityUpdateError::from)?;
63        identity_update
64            .to_verified(&self.context.scw_verifier())
65            .await?;
66
67        // Step 3: Upload key package first (prevents race condition)
68        let key_package_meta = self.context.api().upload_key_package(kp_bytes).await?;
69        let key_package_cursor = key_package_meta
70            .cursor
71            .filter(|cursor| cursor.sequence_id > 0)
72            .ok_or(xmtp_api::ApiError::InvalidResponse(
73                "key package publish cursor",
74            ))?;
75
76        // Own-installation changes are compared from before publication. A
77        // conflict retry can load another installation's update into this
78        // database before the final reload, and those changes are reported too.
79        let inbox_id = self.inbox_id().to_string();
80        let registration_cursor = self
81            .identity_updates()
82            .with_own_installation_events(
83                &self.context.db(),
84                Box::pin(async {
85                    // Step 4: Publish identity update (makes installation visible)
86                    let registration_cursor = crate::identity_updates::publish_with_conflict_retry(
87                        self.context.api(),
88                        &self.context.db(),
89                        identity_update,
90                        &self.context.scw_verifier(),
91                    )
92                    .await
93                    .map_err(|error| IdentityUpdateError::Publish(Box::new(error)))?;
94                    // Step 5: Fetch and store in local DB (needed for group operations)
95                    retry_async!(
96                        Retry::default(),
97                        (async {
98                            load_identity_updates(
99                                self.context.api(),
100                                &self.context.db(),
101                                &[inbox_id.as_str()],
102                            )
103                            .await
104                        })
105                    )?;
106                    Ok(registration_cursor)
107                }),
108            )
109            .await?;
110
111        // Backend publication order can differ from local generation order.
112        crate::state_tx::state_write(self.context.mls_storage(), |tx| {
113            let storage = tx.storage();
114            storage.db().record_key_package_publication(
115                history_id,
116                xmtp_proto::types::Cursor(key_package_cursor.sequence_id),
117            )?;
118            storage
119                .db()
120                .reset_key_package_rotation_queue(KEY_PACKAGE_ROTATION_INTERVAL_NS)?;
121            Ok::<_, StorageError>(Continue(()))
122        })
123        .map(TransactionOutcome::into_continued)?;
124
125        // Mark identity as ready
126        let mut stored_identity = StoredIdentity::try_from(self.identity())?;
127        stored_identity.registration_cursor_sequence_id = Some(registration_cursor.0 as i64);
128        stored_identity.store(&self.context.db())?;
129        self.context
130            .registration_event_pending()
131            .store(true, Ordering::Release);
132        self.identity().set_ready();
133        self.ensure_registration_visible().await
134    }
135
136    /// Whether registration has completed its visibility confirmation.
137    /// A stored identity with a pending receipt is not yet registered.
138    pub fn is_registration_visible(&self) -> Result<bool, ClientError> {
139        let stored: Option<StoredIdentity> = self.context.db().fetch(&())?;
140        Ok(self.identity().is_ready()
141            && stored.is_some_and(|identity| identity.registration_cursor_sequence_id.is_none()))
142    }
143
144    /// Confirm a stored registration before reporting success.
145    pub async fn ensure_registration_visible(&self) -> Result<(), ClientError> {
146        let stored: Option<StoredIdentity> = self.context.db().fetch(&())?;
147        if stored.is_some_and(|identity| identity.registration_cursor_sequence_id.is_some()) {
148            self.wait_for_registration_visible(VisibilityConfirmationOptions::default())
149                .await?;
150        }
151        Ok(())
152    }
153
154    /// Wait until the serving database exposes the registration identity-topic head.
155    /// A missing or older head is polled. The timeout also bounds each request.
156    pub async fn wait_for_registration_visible(
157        &self,
158        options: VisibilityConfirmationOptions,
159    ) -> Result<(), ClientError> {
160        use xmtp_common::time::{Duration, sleep, timeout};
161        if !self.identity().is_ready() {
162            return Err(ClientError::RegistrationNotVisible);
163        }
164        let stored: Option<StoredIdentity> = self.context.db().fetch(&())?;
165        let stored = stored.ok_or(ClientError::RegistrationNotVisible)?;
166        let Some(receipt) = stored.registration_cursor_sequence_id else {
167            return Ok(());
168        };
169        self.context.server_configuration().check()?;
170        let sequence_id = u64::try_from(receipt)
171            .ok()
172            .filter(|sequence_id| *sequence_id != 0)
173            .ok_or(ClientError::RegistrationNotVisible)?;
174        timeout(Duration::from_millis(options.timeout_ms), async {
175            let mut delay = REGISTRATION_INITIAL_BACKOFF;
176            let inbox = hex::decode(self.inbox_id())
177                .map_err(|_| xmtp_api::ApiError::InvalidRequest("registration inbox id"))?;
178            let topic = xmtp_proto::types::Topic::new_identity_update(inbox);
179            xmtp_proto::types::Topic::parse(&topic)?;
180            loop {
181                let heads = self
182                    .context
183                    .api()
184                    .newest_topic_cursors(vec![topic.clone()])
185                    .await?;
186                let head = heads
187                    .get(&topic)
188                    .ok_or(xmtp_api::ApiError::InvalidResponse(
189                        "registration identity head",
190                    ))?;
191                // implements: IDENT-072
192                if head.0 >= sequence_id {
193                    return Ok::<(), ClientError>(());
194                }
195                sleep(delay).await;
196                delay = (delay * 2).min(REGISTRATION_MAX_BACKOFF);
197            }
198        })
199        .await
200        .map_err(|_| ClientError::RegistrationNotVisible)??;
201        if self
202            .context
203            .registration_event_pending()
204            .swap(false, Ordering::AcqRel)
205        {
206            xmtp_events::EventWriter::emit(
207                self.context.events(),
208                Some(xmtp_events::ClientEvent::IdentityRegistered(
209                    xmtp_events::IdentityRegistered {
210                        inbox_id: self.inbox_id().to_string(),
211                        installation_key: self.installation_id.to_vec(),
212                    },
213                )),
214                None,
215            );
216        }
217        self.context.db().clear_registration_cursor(receipt)?;
218        Ok(())
219    }
220
221    /// If no key rotation is scheduled, queue it to occur in the next 5 seconds.
222    pub fn queue_key_rotation(&self) -> Result<(), ClientError> {
223        crate::worker::key_package_maintenance::queue_key_rotation(&self.context)?;
224        Ok(())
225    }
226
227    /// Upload a new key package to the network replacing an existing key package.
228    pub async fn rotate_and_upload_key_package(&self) -> Result<(), ClientError> {
229        // A client with a blocked connection publishes nothing. This one
230        // reaches `Identity` directly instead of going through a group or the
231        // publish path, so it carries its own gate.
232        self.ensure_identity_ready::<ClientError>()?;
233        crate::identity_lifecycle::rotate_and_upload_key_package(
234            self.identity(),
235            self.context.api(),
236            self.context.mls_storage(),
237            CREATE_PQ_KEY_PACKAGE_EXTENSION,
238        )
239        .await?;
240        // The rotation marked superseded KPs delete_at=now+grace; without this
241        // the parked KpDeletion task would sweep them up to ~30d late.
242        crate::worker::key_package_maintenance::nudge_deletion(&self.context)?;
243
244        Ok(())
245    }
246
247    /// Fetches the current key package from the network for each of the `installation_id`s specified
248    #[tracing::instrument(skip_all)]
249    pub async fn get_key_packages_for_installation_ids(
250        &self,
251        installation_ids: Vec<Vec<u8>>,
252    ) -> Result<KeyPackageResultsByInstallation, ClientError> {
253        MlsStore::new(self.context.clone())
254            .get_key_packages_for_installation_ids(installation_ids)
255            .await
256            .map_err(Into::into)
257    }
258}