miden_client/lib.rs
1#![cfg_attr(docsrs, feature(doc_cfg))]
2
3//! A no_std-compatible client library for interacting with the Miden network.
4//!
5//! This crate provides a lightweight client that handles connections to the Miden node, manages
6//! accounts and their state, and facilitates executing, proving, and submitting transactions.
7//!
8//! For a protocol-level overview and guides for getting started, please visit the official
9//! [Miden docs](https://docs.miden.xyz/).
10//!
11//! ## Overview
12//!
13//! The library is organized into several key modules:
14//!
15//! - **Accounts:** Provides types for managing accounts. Once accounts are tracked by the client,
16//! their state is updated with every transaction and validated during each sync.
17//!
18//! - **Notes:** Contains types and utilities for working with notes in the Miden client.
19//!
20//! - **RPC:** Facilitates communication with Miden node, exposing RPC methods for syncing state,
21//! fetching block headers, and submitting transactions.
22//!
23//! - **Store:** Defines and implements the persistence layer for accounts, transactions, notes, and
24//! other entities.
25//!
26//! - **Sync:** Provides functionality to synchronize the local state with the current state on the
27//! Miden network.
28//!
29//! - **Transactions:** Offers capabilities to build, execute, prove, and submit transactions.
30//!
31//! Additionally, the crate re-exports several utility modules:
32//!
33//! - **Assembly:** Types for working with Miden Assembly.
34//! - **Assets:** Types and utilities for working with assets.
35//! - **Auth:** Authentication-related types and functionalities.
36//! - **Blocks:** Types for handling block headers.
37//! - **Crypto:** Cryptographic types and utilities, including random number generators.
38//! - **Utils:** Miscellaneous utilities for serialization and common operations.
39//! - **`AggLayer`:** Bridge account components, note constructors, and Ethereum-compatible helper
40//! types from the Miden `AggLayer` protocol crate.
41//!
42//! The library is designed to work in both `no_std` and `std` environments and is
43//! configurable via Cargo features.
44//!
45//! ## Usage
46//!
47//! To use the Miden client library in your project, add it as a dependency in your `Cargo.toml`:
48//!
49//! ```toml
50//! [dependencies]
51//! miden-client = "0.10"
52//! ```
53//!
54//! ## Example
55//!
56//! Below is a brief example illustrating how to instantiate the client using `ClientBuilder`:
57//!
58//! ```rust,ignore
59//! use std::sync::Arc;
60//!
61//! use miden_client::builder::ClientBuilder;
62//! use miden_client::keystore::FilesystemKeyStore;
63//! use miden_client::rpc::{Endpoint, GrpcClient, VerifyingRpcClient};
64//! use miden_client_sqlite_store::SqliteStore;
65//!
66//! # pub async fn create_test_client() -> Result<(), Box<dyn std::error::Error>> {
67//! // Create the SQLite store.
68//! let sqlite_store = SqliteStore::new("path/to/store".try_into()?).await?;
69//! let store = Arc::new(sqlite_store);
70//!
71//! // Create the keystore for transaction signing.
72//! let keystore = FilesystemKeyStore::new("path/to/keys/directory".try_into()?)?;
73//!
74//! // Create the RPC client.
75//! let endpoint = Endpoint::new("https".into(), "localhost".into(), Some(57291));
76//!
77//! // Instantiate the client using the builder.
78//! let client = ClientBuilder::new()
79//! .rpc(Arc::new(VerifyingRpcClient::new(GrpcClient::new(&endpoint, 10_000))))
80//! .store(store)
81//! .authenticator(Arc::new(keystore))
82//! .build()
83//! .await?;
84//!
85//! # Ok(())
86//! # }
87//! ```
88//!
89//! For network-specific defaults, use the convenience constructors:
90//!
91//! ```ignore
92//! // For testnet (includes remote prover and note transport)
93//! let client = ClientBuilder::for_testnet()
94//! .store(store)
95//! .authenticator(Arc::new(keystore))
96//! .build()
97//! .await?;
98//!
99//! // For local development
100//! let client = ClientBuilder::for_localhost()
101//! .store(store)
102//! .authenticator(Arc::new(keystore))
103//! .build()
104//! .await?;
105//! ```
106//!
107//! For additional usage details, configuration options, and examples, consult the documentation for
108//! each module.
109
110#![no_std]
111
112#[macro_use]
113extern crate alloc;
114use alloc::boxed::Box;
115
116#[cfg(feature = "std")]
117extern crate std;
118
119pub mod account;
120pub mod grpc_support;
121pub mod keystore;
122pub mod note;
123pub mod note_transport;
124pub mod pswap;
125#[cfg(feature = "tonic")]
126pub mod remote_prover;
127pub mod rpc;
128pub mod settings;
129pub mod store;
130pub mod sync;
131pub mod transaction;
132pub mod utils;
133
134pub mod builder;
135
136#[cfg(feature = "testing")]
137mod test_utils;
138
139pub mod errors;
140
141pub use miden_protocol::utils::serde::{Deserializable, Serializable, SliceReader};
142
143// RE-EXPORTS
144// ================================================================================================
145
146pub mod notes {
147 pub use miden_standards::note::NoteFile;
148}
149
150/// Provides `AggLayer` bridge components, note constructors, and helper types.
151pub mod agglayer {
152 pub use miden_agglayer::*;
153 pub use miden_standards::interop::eth::{
154 AddressConversionError,
155 EthAddress,
156 EthAmount,
157 EthAmountError,
158 EthEmbeddedAccountId,
159 };
160}
161
162/// Provides types and utilities for working with Miden Assembly.
163pub mod assembly {
164 pub use miden_protocol::MastForest;
165 pub use miden_protocol::assembly::debuginfo::SourceManagerSync;
166 #[cfg(feature = "std")]
167 pub use miden_protocol::assembly::debuginfo::{SourceManagerExt, Uri};
168 pub use miden_protocol::assembly::diagnostics::Report;
169 pub use miden_protocol::assembly::diagnostics::reporting::PrintDiagnostic;
170 pub use miden_protocol::assembly::mast::MastNodeExt;
171 pub use miden_protocol::assembly::{Assembler, DefaultSourceManager, Module, ModuleKind, Path};
172 pub use miden_standards::code_builder::CodeBuilder;
173}
174
175/// Provides types and utilities for working with assets within the Miden network.
176pub mod asset {
177 pub use miden_protocol::account::delta::{
178 AccountVaultDelta,
179 FungibleAssetDelta,
180 NonFungibleAssetDelta,
181 NonFungibleDeltaAction,
182 };
183 pub use miden_protocol::account::{
184 AccountStorageHeader,
185 AssetCallbackFlag,
186 StorageMapWitness,
187 StorageSlotContent,
188 StorageSlotHeader,
189 };
190 pub use miden_protocol::asset::{
191 Asset,
192 AssetAmount,
193 AssetCallbacks,
194 AssetComposition,
195 AssetId,
196 AssetVault,
197 AssetWitness,
198 FungibleAsset,
199 NonFungibleAsset,
200 NonFungibleAssetDetails,
201 PartialVault,
202 TokenSymbol,
203 };
204}
205
206/// Provides authentication-related types and functionalities for the Miden
207/// network.
208pub mod auth {
209 pub use miden_protocol::account::auth::{
210 AuthScheme as AuthSchemeId,
211 AuthSecretKey,
212 PublicKey,
213 PublicKeyCommitment,
214 Signature,
215 };
216 pub use miden_standards::account::auth::{
217 Approver,
218 ApproverSet,
219 AuthGuardedMultisig,
220 AuthGuardedMultisigConfig,
221 AuthMultisig,
222 AuthMultisigConfig,
223 AuthMultisigSmart,
224 AuthMultisigSmartConfig,
225 AuthSingleSig,
226 GuardianConfig,
227 NoAuth,
228 };
229 pub use miden_tx::auth::{BasicAuthenticator, SigningInputs, TransactionAuthenticator};
230
231 pub use crate::account::component::AuthScheme;
232
233 pub const RPO_FALCON_SCHEME_ID: AuthSchemeId = AuthSchemeId::Falcon512Poseidon2;
234 pub const ECDSA_K256_KECCAK_SCHEME_ID: AuthSchemeId = AuthSchemeId::EcdsaK256Keccak;
235}
236
237/// Provides types for working with blocks within the Miden network.
238pub mod block {
239 pub use miden_protocol::block::{BlockHeader, BlockNumber, FeeParameters, ValidatorKeys};
240}
241
242/// Provides cryptographic types and utilities used within the Miden rollup
243/// network. It re-exports commonly used types and random number generators like `FeltRng` from
244/// the `miden_standards` crate.
245pub mod crypto {
246 pub mod ecdsa_k256_keccak {
247 pub use miden_protocol::crypto::dsa::ecdsa_k256_keccak::{
248 PublicKey,
249 Signature,
250 SigningKey,
251 };
252 }
253 pub mod eddsa_25519_sha512 {
254 pub use miden_protocol::crypto::dsa::eddsa_25519_sha512::{KeyExchangeKey, PublicKey};
255 }
256 pub mod rpo_falcon512 {
257 pub use miden_protocol::crypto::dsa::falcon512_poseidon2::{
258 PublicKey,
259 SecretKey,
260 Signature,
261 };
262 }
263 pub use miden_protocol::crypto::hash::blake::Blake3Digest;
264 pub use miden_protocol::crypto::hash::poseidon2::Poseidon2;
265 pub use miden_protocol::crypto::hash::rpo::Rpo256;
266 pub use miden_protocol::crypto::merkle::mmr::{
267 Forest,
268 InOrderIndex,
269 MmrDelta,
270 MmrPeaks,
271 MmrProof,
272 PartialMmr,
273 };
274 // Forest backend types are re-exported for downstream stores.
275 pub use miden_protocol::crypto::merkle::smt::{
276 Backend,
277 BackendReader,
278 ForestInMemoryBackend,
279 LeafIndex,
280 SMT_DEPTH,
281 Smt,
282 SmtForest,
283 SmtLeaf,
284 SmtProof,
285 VersionId,
286 };
287 pub use miden_protocol::crypto::merkle::store::MerkleStore;
288 pub use miden_protocol::crypto::merkle::{
289 EmptySubtreeRoots,
290 MerkleError,
291 MerklePath,
292 MerkleTree,
293 NodeIndex,
294 SparseMerklePath,
295 };
296 pub use miden_protocol::crypto::rand::{FeltRng, RandomCoin};
297}
298
299/// Provides types for working with addresses within the Miden network.
300pub mod address {
301 pub use miden_protocol::address::{
302 Address,
303 AddressId,
304 AddressInterface,
305 CustomNetworkId,
306 NetworkId,
307 RoutingParameters,
308 };
309}
310
311/// Provides types for working with the virtual machine within the Miden network.
312pub mod vm {
313 pub use miden_protocol::vm::{
314 AdviceInputs,
315 AdviceMap,
316 AttributeSet,
317 MIN_STACK_DEPTH,
318 Package,
319 PackageExport,
320 PackageManifest,
321 ProcedureExport,
322 Program,
323 QualifiedProcedureName,
324 Section,
325 SectionId,
326 TargetType,
327 };
328}
329
330pub use async_trait::async_trait;
331pub use errors::*;
332use miden_protocol::assembly::SourceManagerSync;
333pub use miden_protocol::{
334 EMPTY_WORD,
335 Felt,
336 MAX_TX_EXECUTION_CYCLES,
337 MIN_TX_EXECUTION_CYCLES,
338 ONE,
339 PrettyPrint,
340 WORD_SIZE,
341 Word,
342 ZERO,
343};
344pub use miden_tx::ExecutionOptions;
345#[cfg(feature = "tonic")]
346pub use remote_prover::RemoteTransactionProver;
347
348/// Provides test utilities for working with accounts and account IDs
349/// within the Miden network. This module is only available when the `testing` feature is
350/// enabled.
351#[cfg(feature = "testing")]
352pub mod testing {
353 pub use miden_protocol::testing::account_id;
354 /// Raw access to `miden-standards` testing modules for items not curated by
355 /// `miden-client`.
356 pub use miden_standards::testing as standards;
357 pub use miden_standards::testing::note::NoteBuilder;
358 pub use miden_testing::*;
359 /// The data store the executor reads from, along with the trait whose methods it serves.
360 /// Exposed here so that tests can exercise it on its own, without going through a
361 /// transaction or a note screening pass.
362 pub use miden_tx::DataStore;
363
364 pub use crate::store::data_store::ClientDataStore;
365 pub use crate::test_utils::*;
366}
367
368use alloc::sync::Arc;
369use alloc::vec::Vec;
370use core::convert::Infallible;
371
372use miden_protocol::block::BlockNumber;
373use miden_protocol::crypto::merkle::mmr::PartialMmr;
374use miden_protocol::crypto::rand::FeltRng;
375use miden_tx::auth::TransactionAuthenticator;
376use rand::{TryCryptoRng, TryRng};
377use rpc::NodeRpcClient;
378use store::Store;
379
380use crate::note_transport::NoteTransportClient;
381use crate::transaction::TransactionProver;
382
383// MIDEN CLIENT
384// ================================================================================================
385
386/// A light client for connecting to the Miden network.
387///
388/// Miden client is responsible for managing a set of accounts. Specifically, the client:
389/// - Keeps track of the current and historical states of a set of accounts and related objects such
390/// as notes and transactions.
391/// - Connects to a Miden node to periodically sync with the current state of the network.
392/// - Executes, proves, and submits transactions to the network as directed by the user.
393pub struct Client<AUTH> {
394 /// The client's store, which provides a way to write and read entities to provide persistence.
395 store: Arc<dyn Store>,
396 /// An instance of [`FeltRng`] which provides randomness tools for generating new keys,
397 /// serial numbers, etc.
398 rng: ClientRng,
399 /// An instance of [`NodeRpcClient`] which provides a way for the client to connect to the
400 /// Miden node.
401 rpc_api: Arc<dyn NodeRpcClient>,
402 /// An instance of a [`TransactionProver`] which will be the default prover for the
403 /// client.
404 tx_prover: Arc<dyn TransactionProver + Send + Sync>,
405 /// An instance of a [`TransactionAuthenticator`] which will be used by the transaction
406 /// executor whenever a signature is requested from within the VM.
407 authenticator: Option<Arc<AUTH>>,
408 /// Shared source manager used to retain MASM source information for assembled programs.
409 source_manager: Arc<dyn SourceManagerSync>,
410 /// Options that control the transaction executor's runtime behaviour (e.g. cycle limits).
411 exec_options: ExecutionOptions,
412 /// Number of blocks after which pending transactions are considered stale and discarded.
413 tx_discard_delta: Option<u32>,
414 /// Number of synced blocks between automatic irrelevant-block pruning runs.
415 irrelevant_block_prune_interval: Option<u32>,
416 /// Sync height at which the last automatic irrelevant-block prune completed.
417 last_irrelevant_block_prune_sync_height: Option<BlockNumber>,
418 /// Maximum number of blocks the client can be behind the network for transactions and account
419 /// proofs to be considered valid.
420 max_block_number_delta: Option<u32>,
421 /// An instance of [`NoteTransportClient`] which provides a way for the client to connect to
422 /// the Miden Note Transport network.
423 note_transport_api: Option<Arc<dyn NoteTransportClient>>,
424 /// Whether the client should cache the current Partial MMR in memory.
425 cache_partial_mmr_in_memory: bool,
426 /// Cached [`PartialMmr`] for the chain's MMR. Lazily built from the store and kept in sync
427 /// across sync/prune operations. `None` forces a rebuild on next access.
428 partial_mmr: Option<CachedPartialMmr>,
429 /// Observers fired by `apply_transaction`. See
430 /// [`Client::with_transaction_observer`].
431 transaction_observers: Vec<Arc<dyn transaction::TransactionObserver>>,
432}
433
434/// Cached [`PartialMmr`] with a two-part freshness fingerprint:
435///
436/// - `store_peaks_hash`: peaks at the current sync height - guards against chain/height drift.
437/// - `tracked_blocks_hash`: hash of the store's tracked block numbers - guards against drift
438/// between store-tracked and cache-tracked blocks. Required because a same-height update can mark
439/// an existing block relevant without changing peaks; pruning the cached MMR while it's missing
440/// such a block would over-delete auth nodes that the store still needs.
441///
442/// The cached MMR includes the sync-height block as a tracked leaf; the store persists the
443/// peaks committed by that block's header, i.e. the peaks over the chain *before* that block
444/// was added, so the two states are offset by one leaf.
445pub(crate) struct CachedPartialMmr {
446 pub(crate) store_peaks_hash: Word,
447 pub(crate) tracked_blocks_hash: Word,
448 pub(crate) mmr: PartialMmr,
449}
450
451/// Constructors.
452impl<AUTH> Client<AUTH>
453where
454 AUTH: builder::BuilderAuthenticator,
455{
456 /// Returns a new [`ClientBuilder`](builder::ClientBuilder) for constructing a client.
457 ///
458 /// This is a convenience method equivalent to calling `ClientBuilder::new()`.
459 ///
460 /// # Example
461 ///
462 /// ```ignore
463 /// let client = Client::builder()
464 /// .rpc(rpc_client)
465 /// .store(store)
466 /// .authenticator(Arc::new(keystore))
467 /// .build()
468 /// .await?;
469 /// ```
470 pub fn builder() -> builder::ClientBuilder<AUTH> {
471 builder::ClientBuilder::new()
472 }
473}
474
475/// Access methods.
476impl<AUTH> Client<AUTH>
477where
478 AUTH: TransactionAuthenticator,
479{
480 /// Returns an instance of the `CodeBuilder`
481 pub fn code_builder(&self) -> assembly::CodeBuilder {
482 assembly::CodeBuilder::with_source_manager(self.source_manager.clone())
483 }
484
485 /// Returns an instance of [`note::NoteScreener`] configured for this client.
486 pub fn note_screener(&self) -> note::NoteScreener {
487 note::NoteScreener::new(self.store.clone(), self.rpc_api.clone())
488 }
489
490 /// Returns a reference to the client's random number generator. This can be used to generate
491 /// randomness for various purposes such as serial numbers, keys, etc.
492 pub fn rng(&mut self) -> &mut ClientRng {
493 &mut self.rng
494 }
495
496 pub fn prover(&self) -> Arc<dyn TransactionProver + Send + Sync> {
497 self.tx_prover.clone()
498 }
499
500 pub fn authenticator(&self) -> Option<&Arc<AUTH>> {
501 self.authenticator.as_ref()
502 }
503
504 /// Returns the shared source manager used to retain MASM source information for assembled
505 /// programs.
506 pub fn source_manager(&self) -> Arc<dyn SourceManagerSync> {
507 self.source_manager.clone()
508 }
509}
510
511impl<AUTH> Client<AUTH> {
512 /// Returns the identifier of the underlying store (e.g. `IndexedDB` database name, `SQLite`
513 /// file path).
514 pub fn store_identifier(&self) -> &str {
515 self.store.identifier()
516 }
517
518 /// Registers a [`transaction::TransactionObserver`]. Per-observer failures are logged.
519 pub fn with_transaction_observer(
520 &mut self,
521 observer: Arc<dyn transaction::TransactionObserver>,
522 ) {
523 self.transaction_observers.push(observer);
524 }
525
526 /// Returns the network ID of the node the client is connected to.
527 pub async fn network_id(&self) -> Result<address::NetworkId, ClientError> {
528 Ok(self.rpc_api.get_network_id().await?)
529 }
530
531 // TEST HELPERS
532 // --------------------------------------------------------------------------------------------
533
534 #[cfg(any(test, feature = "testing"))]
535 pub fn test_rpc_api(&mut self) -> &mut Arc<dyn NodeRpcClient> {
536 &mut self.rpc_api
537 }
538
539 #[cfg(any(test, feature = "testing"))]
540 pub fn test_store(&mut self) -> &mut Arc<dyn Store> {
541 &mut self.store
542 }
543
544 #[cfg(any(test, feature = "testing"))]
545 pub fn test_has_cached_partial_mmr(&self) -> bool {
546 self.partial_mmr.is_some()
547 }
548}
549
550// CLIENT RNG
551// ================================================================================================
552
553// NOTE: The idea of having `ClientRng` is to enforce `Send` and `Sync` over `FeltRng`.
554// This allows `Client`` to be `Send` and `Sync`. There may be users that would want to use clients
555// with !Send/!Sync RNGs. For this we have two options:
556//
557// - We can make client generic over R (adds verbosity but is more flexible and maybe even correct)
558// - We can optionally (e.g., based on features/target) change `ClientRng` definition to not enforce
559// these bounds. (similar to TransactionAuthenticator)
560
561/// Marker trait for RNGs that can be shared across threads and used by the client.
562pub trait ClientFeltRng: FeltRng + Send + Sync {}
563impl<T> ClientFeltRng for T where T: FeltRng + Send + Sync {}
564
565/// Boxed RNG trait object used by the client.
566pub type ClientRngBox = Box<dyn ClientFeltRng>;
567
568/// A wrapper around a [`FeltRng`] that implements the [`TryRng`] trait.
569/// This allows the user to pass their own generic RNG so that it's used by the client.
570pub struct ClientRng(ClientRngBox);
571
572impl ClientRng {
573 pub fn new(rng: ClientRngBox) -> Self {
574 Self(rng)
575 }
576
577 pub fn inner_mut(&mut self) -> &mut ClientRngBox {
578 &mut self.0
579 }
580}
581
582impl TryRng for ClientRng {
583 type Error = Infallible;
584
585 fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
586 Ok(self.0.next_u32())
587 }
588
589 fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
590 Ok(self.0.next_u64())
591 }
592
593 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Self::Error> {
594 self.0.fill_bytes(dest);
595 Ok(())
596 }
597}
598
599// The client's RNG already backs key and serial-number generation, so callers are required to
600// supply cryptographically secure randomness. Asserting it here lets the RNG drive primitives that
601// demand a `CryptoRng`, such as sealing transaction inputs.
602impl TryCryptoRng for ClientRng {}
603
604impl FeltRng for ClientRng {
605 fn draw_element(&mut self) -> Felt {
606 self.0.draw_element()
607 }
608
609 fn draw_word(&mut self) -> Word {
610 self.0.draw_word()
611 }
612}
613
614#[cfg(test)]
615mod tests {
616 use super::Client;
617
618 fn assert_send_sync<T: Send + Sync>() {}
619
620 #[test]
621 fn client_is_send_sync() {
622 assert_send_sync::<Client<()>>();
623 }
624}