Skip to main content

miden_node_store/allowlist/
mod.rs

1//! Stores account registrations and invitation codes for the sequencer.
2//!
3//! The registry contains unused invitation codes, accounts registered with an invitation code, and accounts added directly.
4//! Registry membership does not depend on account deployment or transaction admission policy.
5
6use std::path::Path;
7
8use miden_node_db::sqlite::{DbReader, DbWriter, WriteTx};
9use miden_node_tracing::miden_instrument;
10use miden_protocol::account::AccountId;
11use thiserror::Error;
12
13use crate::{COMPONENT, DatabaseError};
14
15mod invitation;
16mod migrations;
17mod queries;
18
19pub use invitation::{InvalidInvitationCode, InvitationCode};
20
21#[cfg(test)]
22mod tests;
23
24/// An invitation code to import, with an optional account registration.
25#[derive(Clone, Debug)]
26pub struct InvitationEntry {
27    pub invitation_code: InvitationCode,
28    pub account_id: Option<AccountId>,
29}
30
31/// Changes made by an invitation import.
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub struct InvitationImportOutcome {
34    pub invitation_added: bool,
35    /// The account registered by this import. Identical retries return `None`.
36    pub registered_account: Option<AccountId>,
37}
38
39/// The registration state of an invitation code.
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub enum InvitationStatus {
42    Unknown,
43    Unused,
44    Registered(AccountId),
45}
46
47/// An invitation's registration and allowlist entry timestamp in UTC Unix seconds.
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub struct InvitationInfo {
50    pub account_id: Option<AccountId>,
51    pub allowlisted_at: i64,
52}
53
54/// The result of a successful registration request.
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56pub enum RegistrationOutcome {
57    Registered,
58    /// The same invitation code was already registered to the same account.
59    AlreadyRegistered,
60}
61
62/// A registry operation failed.
63#[derive(Debug, Error)]
64pub enum AllowlistError {
65    #[error("invitation code does not exist")]
66    InvitationNotFound,
67    #[error("invitation code is already registered to another account")]
68    InvitationAlreadyUsed,
69    #[error("account {0} is already registered")]
70    AccountAlreadyRegistered(AccountId),
71    #[error("account registry database operation failed")]
72    Database(#[source] DatabaseError),
73}
74
75/// Read-only access to the account registry.
76#[derive(Clone)]
77pub struct AccountAllowlistReader {
78    db: DbReader,
79}
80
81impl AccountAllowlistReader {
82    /// Returns when the account's allowlist entry was added, if it exists.
83    #[miden_instrument(
84        target = COMPONENT,
85        name = "store.allowlist.allowlisted_at",
86        fields(account.id = account_id),
87        err,
88    )]
89    pub async fn allowlisted_at(
90        &self,
91        account_id: AccountId,
92    ) -> Result<Option<i64>, DatabaseError> {
93        self.db
94            .read("allowlist.allowlisted_at", move |tx| queries::allowlisted_at(tx, account_id))
95            .await
96            .map_err(DatabaseError::DatabaseError)
97    }
98
99    /// Returns the invitation's registration and allowlist entry timestamp, if it exists.
100    #[miden_instrument(target = COMPONENT, name = "store.allowlist.invitation_info", err)]
101    pub async fn invitation_info(
102        &self,
103        invitation_code: InvitationCode,
104    ) -> Result<Option<InvitationInfo>, DatabaseError> {
105        self.db
106            .read("allowlist.invitation_info", move |tx| {
107                queries::invitation_info(tx, &invitation_code)
108            })
109            .await
110            .map_err(DatabaseError::DatabaseError)
111    }
112
113    /// Returns whether the registry contains the account.
114    #[miden_instrument(
115        target = COMPONENT,
116        name = "store.allowlist.contains_account",
117        fields(account.id = account_id),
118        err,
119    )]
120    pub async fn contains_account(&self, account_id: AccountId) -> Result<bool, DatabaseError> {
121        self.db
122            .read("allowlist.contains_account", move |tx| {
123                queries::contains_account(tx, account_id)
124            })
125            .await
126            .map_err(DatabaseError::DatabaseError)
127    }
128
129    /// Returns the registration state of the invitation code.
130    #[miden_instrument(target = COMPONENT, name = "store.allowlist.invitation_status", err)]
131    pub async fn invitation_status(
132        &self,
133        invitation_code: InvitationCode,
134    ) -> Result<InvitationStatus, DatabaseError> {
135        self.db
136            .read("allowlist.invitation_status", move |tx| {
137                queries::invitation_status(tx, &invitation_code)
138            })
139            .await
140            .map_err(DatabaseError::DatabaseError)
141    }
142}
143
144/// Persistent account registry in a separate SQLite database.
145///
146/// The registry has separate reader and writer pools. Its writes do not wait for block database writes.
147/// Each entry records when it was added to the allowlist in UTC Unix seconds. Registration and retries preserve this time.
148/// Write transactions acquire the write lock before they read registrations.
149/// Each write operation commits all its changes together. Failed operations leave no changes.
150pub struct AccountAllowlist {
151    writer: DbWriter,
152    reader: AccountAllowlistReader,
153}
154
155impl std::ops::Deref for AccountAllowlist {
156    type Target = AccountAllowlistReader;
157
158    fn deref(&self) -> &Self::Target {
159        &self.reader
160    }
161}
162
163impl AccountAllowlist {
164    /// Creates the registry database and applies all migrations.
165    ///
166    /// The database file must not exist.
167    pub fn bootstrap(database_filepath: impl AsRef<Path>) -> Result<(), DatabaseError> {
168        let migrator = migrations::migrator()
169            .map_err(miden_node_db::DatabaseError::migration)
170            .map_err(DatabaseError::DatabaseError)?;
171        migrator
172            .create_database(database_filepath)
173            .and_then(|mut database| database.migrate_to(migrator.latest_version()))
174            .map_err(miden_node_db::DatabaseError::migration)
175            .map_err(DatabaseError::DatabaseError)
176    }
177
178    /// Opens the registry database after verifying its schema.
179    ///
180    /// The database must exist and have the latest schema. This method does not apply migrations.
181    pub fn load(database_filepath: impl AsRef<Path>) -> Result<Self, DatabaseError> {
182        let database_filepath = database_filepath.as_ref();
183        let migrator = migrations::migrator()
184            .map_err(miden_node_db::DatabaseError::migration)
185            .map_err(DatabaseError::DatabaseError)?;
186        migrator
187            .verify_latest_schema(database_filepath)
188            .map_err(miden_node_db::DatabaseError::migration)
189            .map_err(DatabaseError::DatabaseError)?;
190        let (writer, reader) =
191            miden_node_db::sqlite::open(database_filepath).map_err(DatabaseError::DatabaseError)?;
192        Ok(Self {
193            writer,
194            reader: AccountAllowlistReader { db: reader },
195        })
196    }
197
198    /// Applies pending migrations to an existing registry database.
199    pub fn migrate(database_filepath: impl AsRef<Path>) -> Result<(), DatabaseError> {
200        let migrator = migrations::migrator()
201            .map_err(miden_node_db::DatabaseError::migration)
202            .map_err(DatabaseError::DatabaseError)?;
203        migrator
204            .open_database(database_filepath)
205            .and_then(|mut database| database.migrate_to(migrator.latest_version()))
206            .map_err(miden_node_db::DatabaseError::migration)
207            .map_err(DatabaseError::DatabaseError)
208    }
209
210    /// Returns a read-only handle that shares the reader pool.
211    pub fn reader(&self) -> AccountAllowlistReader {
212        self.reader.clone()
213    }
214
215    /// Imports an invitation code with an optional account registration.
216    /// Returns whether the invitation is new and which account the import registered.
217    ///
218    /// An entry without an account preserves any existing registration for its invitation code.
219    /// An entry with an account can register an unused invitation code. An identical registration has no effect.
220    /// A conflicting registration leaves the registry unchanged.
221    #[miden_instrument(
222        target = COMPONENT,
223        name = "store.allowlist.import_invitation",
224        fields(account.id = entry.account_id),
225        err,
226    )]
227    pub async fn import_invitation(
228        &self,
229        entry: InvitationEntry,
230    ) -> Result<InvitationImportOutcome, AllowlistError> {
231        self.transact("allowlist.import_invitation", move |tx| {
232            queries::import_invitation(tx, &entry)
233        })
234        .await
235    }
236
237    /// Adds an account without an invitation code. Returns true if the registration is new.
238    ///
239    /// An existing account keeps its invitation code registration, if any.
240    #[miden_instrument(
241        target = COMPONENT,
242        name = "store.allowlist.add_account",
243        fields(account.id = account_id),
244        err,
245    )]
246    pub async fn add_account(&self, account_id: AccountId) -> Result<bool, DatabaseError> {
247        self.writer
248            .write("allowlist.add_account", move |tx| queries::add_account(tx, account_id))
249            .await
250            .map_err(DatabaseError::DatabaseError)
251    }
252
253    /// Registers an unused invitation code to an account in one transaction.
254    ///
255    /// A retry with the same invitation code and account succeeds without changes.
256    /// An account already registered by another method cannot consume an unused invitation code.
257    #[miden_instrument(
258        target = COMPONENT,
259        name = "store.allowlist.register_account",
260        fields(account.id = account_id),
261        err,
262    )]
263    pub async fn register_account(
264        &self,
265        invitation_code: InvitationCode,
266        account_id: AccountId,
267    ) -> Result<RegistrationOutcome, AllowlistError> {
268        self.transact("allowlist.register_account", move |tx| {
269            queries::register_account(tx, &invitation_code, account_id)
270        })
271        .await
272    }
273
274    async fn transact<T: Send + 'static>(
275        &self,
276        name: &'static str,
277        query: impl FnOnce(&WriteTx<'_>) -> Result<T, AllowlistError> + Send + 'static,
278    ) -> Result<T, AllowlistError> {
279        let tx = self
280            .writer
281            .begin_write()
282            .await
283            .map_err(DatabaseError::DatabaseError)
284            .map_err(AllowlistError::Database)?;
285        let result = tx
286            .run(name, move |tx| Ok::<_, miden_node_db::DatabaseError>(query(tx)))
287            .await
288            .map_err(DatabaseError::DatabaseError)
289            .map_err(AllowlistError::Database)
290            .and_then(std::convert::identity);
291
292        match result {
293            Ok(value) => {
294                tx.commit()
295                    .await
296                    .map_err(DatabaseError::DatabaseError)
297                    .map_err(AllowlistError::Database)?;
298                Ok(value)
299            },
300            Err(error) => {
301                tx.rollback()
302                    .await
303                    .map_err(DatabaseError::DatabaseError)
304                    .map_err(AllowlistError::Database)?;
305                Err(error)
306            },
307        }
308    }
309}