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::instrument;
10use miden_protocol::account::AccountId;
11use thiserror::Error;
12
13use crate::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    #[instrument(
84        name = "allowlisted_at",
85        fields(account.id = account_id),
86        err(level = "debug"),
87    )]
88    pub async fn allowlisted_at(
89        &self,
90        account_id: AccountId,
91    ) -> Result<Option<i64>, DatabaseError> {
92        self.db
93            .read("allowlist.allowlisted_at", move |tx| queries::allowlisted_at(tx, account_id))
94            .await
95            .map_err(DatabaseError::DatabaseError)
96    }
97
98    /// Returns the invitation's registration and allowlist entry timestamp, if it exists.
99    #[instrument(name = "invitation_info", err(level = "debug"))]
100    pub async fn invitation_info(
101        &self,
102        invitation_code: InvitationCode,
103    ) -> Result<Option<InvitationInfo>, DatabaseError> {
104        self.db
105            .read("allowlist.invitation_info", move |tx| {
106                queries::invitation_info(tx, &invitation_code)
107            })
108            .await
109            .map_err(DatabaseError::DatabaseError)
110    }
111
112    /// Returns whether the registry contains the account.
113    #[instrument(
114        name = "contains_account",
115        fields(account.id = account_id),
116        err(level = "debug"),
117    )]
118    pub async fn contains_account(&self, account_id: AccountId) -> Result<bool, DatabaseError> {
119        self.db
120            .read("allowlist.contains_account", move |tx| {
121                queries::contains_account(tx, account_id)
122            })
123            .await
124            .map_err(DatabaseError::DatabaseError)
125    }
126
127    /// Returns the registration state of the invitation code.
128    #[instrument(name = "invitation_status", err(level = "debug"))]
129    pub async fn invitation_status(
130        &self,
131        invitation_code: InvitationCode,
132    ) -> Result<InvitationStatus, DatabaseError> {
133        self.db
134            .read("allowlist.invitation_status", move |tx| {
135                queries::invitation_status(tx, &invitation_code)
136            })
137            .await
138            .map_err(DatabaseError::DatabaseError)
139    }
140}
141
142/// Persistent account registry in a separate SQLite database.
143///
144/// The registry has separate reader and writer pools. Its writes do not wait for block database writes.
145/// Each entry records when it was added to the allowlist in UTC Unix seconds. Registration and retries preserve this time.
146/// Write transactions acquire the write lock before they read registrations.
147/// Each write operation commits all its changes together. Failed operations leave no changes.
148pub struct AccountAllowlist {
149    writer: DbWriter,
150    reader: AccountAllowlistReader,
151}
152
153impl std::ops::Deref for AccountAllowlist {
154    type Target = AccountAllowlistReader;
155
156    fn deref(&self) -> &Self::Target {
157        &self.reader
158    }
159}
160
161impl AccountAllowlist {
162    /// Creates the registry database and applies all migrations.
163    ///
164    /// The database file must not exist.
165    pub fn bootstrap(database_filepath: impl AsRef<Path>) -> Result<(), DatabaseError> {
166        let migrator = migrations::migrator()
167            .map_err(miden_node_db::DatabaseError::migration)
168            .map_err(DatabaseError::DatabaseError)?;
169        migrator
170            .create_database(database_filepath)
171            .and_then(|mut database| database.migrate_to(migrator.latest_version()))
172            .map_err(miden_node_db::DatabaseError::migration)
173            .map_err(DatabaseError::DatabaseError)
174    }
175
176    /// Opens the registry database after verifying its schema.
177    ///
178    /// The database must exist and have the latest schema. This method does not apply migrations.
179    pub fn load(database_filepath: impl AsRef<Path>) -> Result<Self, DatabaseError> {
180        let database_filepath = database_filepath.as_ref();
181        let migrator = migrations::migrator()
182            .map_err(miden_node_db::DatabaseError::migration)
183            .map_err(DatabaseError::DatabaseError)?;
184        migrator
185            .verify_latest_schema(database_filepath)
186            .map_err(miden_node_db::DatabaseError::migration)
187            .map_err(DatabaseError::DatabaseError)?;
188        let (writer, reader) =
189            miden_node_db::sqlite::open(database_filepath).map_err(DatabaseError::DatabaseError)?;
190        Ok(Self {
191            writer,
192            reader: AccountAllowlistReader { db: reader },
193        })
194    }
195
196    /// Applies pending migrations to an existing registry database.
197    pub fn migrate(database_filepath: impl AsRef<Path>) -> Result<(), DatabaseError> {
198        let migrator = migrations::migrator()
199            .map_err(miden_node_db::DatabaseError::migration)
200            .map_err(DatabaseError::DatabaseError)?;
201        migrator
202            .open_database(database_filepath)
203            .and_then(|mut database| database.migrate_to(migrator.latest_version()))
204            .map_err(miden_node_db::DatabaseError::migration)
205            .map_err(DatabaseError::DatabaseError)
206    }
207
208    /// Returns a read-only handle that shares the reader pool.
209    pub fn reader(&self) -> AccountAllowlistReader {
210        self.reader.clone()
211    }
212
213    /// Imports an invitation code with an optional account registration.
214    /// Returns whether the invitation is new and which account the import registered.
215    ///
216    /// An entry without an account preserves any existing registration for its invitation code.
217    /// An entry with an account can register an unused invitation code. An identical registration has no effect.
218    /// A conflicting registration leaves the registry unchanged.
219    #[instrument(
220        name = "import_invitation",
221        fields(account.id = entry.account_id),
222        err,
223    )]
224    pub async fn import_invitation(
225        &self,
226        entry: InvitationEntry,
227    ) -> Result<InvitationImportOutcome, AllowlistError> {
228        self.transact("allowlist.import_invitation", move |tx| {
229            queries::import_invitation(tx, &entry)
230        })
231        .await
232    }
233
234    /// Adds an account without an invitation code. Returns true if the registration is new.
235    ///
236    /// An existing account keeps its invitation code registration, if any.
237    #[instrument(
238        name = "add_account",
239        fields(account.id = account_id),
240        err,
241    )]
242    pub async fn add_account(&self, account_id: AccountId) -> Result<bool, DatabaseError> {
243        self.writer
244            .write("allowlist.add_account", move |tx| queries::add_account(tx, account_id))
245            .await
246            .map_err(DatabaseError::DatabaseError)
247    }
248
249    /// Registers an unused invitation code to an account in one transaction.
250    ///
251    /// A retry with the same invitation code and account succeeds without changes.
252    /// An account already registered by another method cannot consume an unused invitation code.
253    #[instrument(
254        name = "register_account",
255        fields(account.id = account_id),
256        err,
257    )]
258    pub async fn register_account(
259        &self,
260        invitation_code: InvitationCode,
261        account_id: AccountId,
262    ) -> Result<RegistrationOutcome, AllowlistError> {
263        self.transact("allowlist.register_account", move |tx| {
264            queries::register_account(tx, &invitation_code, account_id)
265        })
266        .await
267    }
268
269    async fn transact<T: Send + 'static>(
270        &self,
271        name: &'static str,
272        query: impl FnOnce(&WriteTx<'_>) -> Result<T, AllowlistError> + Send + 'static,
273    ) -> Result<T, AllowlistError> {
274        let tx = self
275            .writer
276            .begin_write()
277            .await
278            .map_err(DatabaseError::DatabaseError)
279            .map_err(AllowlistError::Database)?;
280        let result = tx
281            .run(name, move |tx| Ok::<_, miden_node_db::DatabaseError>(query(tx)))
282            .await
283            .map_err(DatabaseError::DatabaseError)
284            .map_err(AllowlistError::Database)
285            .and_then(std::convert::identity);
286
287        match result {
288            Ok(value) => {
289                tx.commit()
290                    .await
291                    .map_err(DatabaseError::DatabaseError)
292                    .map_err(AllowlistError::Database)?;
293                Ok(value)
294            },
295            Err(error) => {
296                tx.rollback()
297                    .await
298                    .map_err(DatabaseError::DatabaseError)
299                    .map_err(AllowlistError::Database)?;
300                Err(error)
301            },
302        }
303    }
304}