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 AuthMultisig,
219 AuthMultisigConfig,
220 AuthSingleSig,
221 NoAuth,
222 };
223 pub use miden_tx::auth::{BasicAuthenticator, SigningInputs, TransactionAuthenticator};
224
225 pub use crate::account::component::AuthScheme;
226
227 pub const RPO_FALCON_SCHEME_ID: AuthSchemeId = AuthSchemeId::Falcon512Poseidon2;
228 pub const ECDSA_K256_KECCAK_SCHEME_ID: AuthSchemeId = AuthSchemeId::EcdsaK256Keccak;
229}
230
231/// Provides types for working with blocks within the Miden network.
232pub mod block {
233 pub use miden_protocol::block::{BlockHeader, BlockNumber, FeeParameters, ValidatorKeys};
234}
235
236/// Provides cryptographic types and utilities used within the Miden rollup
237/// network. It re-exports commonly used types and random number generators like `FeltRng` from
238/// the `miden_standards` crate.
239pub mod crypto {
240 pub mod ecdsa_k256_keccak {
241 pub use miden_protocol::crypto::dsa::ecdsa_k256_keccak::{
242 PublicKey,
243 Signature,
244 SigningKey,
245 };
246 }
247 pub mod eddsa_25519_sha512 {
248 pub use miden_protocol::crypto::dsa::eddsa_25519_sha512::{KeyExchangeKey, PublicKey};
249 }
250 pub mod rpo_falcon512 {
251 pub use miden_protocol::crypto::dsa::falcon512_poseidon2::{
252 PublicKey,
253 SecretKey,
254 Signature,
255 };
256 }
257 pub use miden_protocol::crypto::hash::blake::Blake3Digest;
258 pub use miden_protocol::crypto::hash::poseidon2::Poseidon2;
259 pub use miden_protocol::crypto::hash::rpo::Rpo256;
260 pub use miden_protocol::crypto::merkle::mmr::{
261 Forest,
262 InOrderIndex,
263 MmrDelta,
264 MmrPeaks,
265 MmrProof,
266 PartialMmr,
267 };
268 // Forest backend types are re-exported for downstream stores.
269 pub use miden_protocol::crypto::merkle::smt::{
270 Backend,
271 BackendReader,
272 ForestInMemoryBackend,
273 LeafIndex,
274 SMT_DEPTH,
275 Smt,
276 SmtForest,
277 SmtLeaf,
278 SmtProof,
279 VersionId,
280 };
281 pub use miden_protocol::crypto::merkle::store::MerkleStore;
282 pub use miden_protocol::crypto::merkle::{
283 EmptySubtreeRoots,
284 MerkleError,
285 MerklePath,
286 MerkleTree,
287 NodeIndex,
288 SparseMerklePath,
289 };
290 pub use miden_protocol::crypto::rand::{FeltRng, RandomCoin};
291}
292
293/// Provides types for working with addresses within the Miden network.
294pub mod address {
295 pub use miden_protocol::address::{
296 Address,
297 AddressId,
298 AddressInterface,
299 CustomNetworkId,
300 NetworkId,
301 RoutingParameters,
302 };
303}
304
305/// Provides types for working with the virtual machine within the Miden network.
306pub mod vm {
307 pub use miden_protocol::vm::{
308 AdviceInputs,
309 AdviceMap,
310 AttributeSet,
311 MIN_STACK_DEPTH,
312 Package,
313 PackageExport,
314 PackageManifest,
315 ProcedureExport,
316 Program,
317 QualifiedProcedureName,
318 Section,
319 SectionId,
320 TargetType,
321 };
322}
323
324pub use async_trait::async_trait;
325pub use errors::*;
326use miden_protocol::assembly::SourceManagerSync;
327pub use miden_protocol::{
328 EMPTY_WORD,
329 Felt,
330 MAX_TX_EXECUTION_CYCLES,
331 MIN_TX_EXECUTION_CYCLES,
332 ONE,
333 PrettyPrint,
334 WORD_SIZE,
335 Word,
336 ZERO,
337};
338pub use miden_tx::ExecutionOptions;
339#[cfg(feature = "tonic")]
340pub use remote_prover::RemoteTransactionProver;
341
342/// Provides test utilities for working with accounts and account IDs
343/// within the Miden network. This module is only available when the `testing` feature is
344/// enabled.
345#[cfg(feature = "testing")]
346pub mod testing {
347 pub use miden_protocol::testing::account_id;
348 /// Raw access to `miden-standards` testing modules for items not curated by
349 /// `miden-client`.
350 pub use miden_standards::testing as standards;
351 pub use miden_standards::testing::note::NoteBuilder;
352 pub use miden_testing::*;
353 /// The data store the executor reads from, along with the trait whose methods it serves.
354 /// Exposed here so that tests can exercise it on its own, without going through a
355 /// transaction or a note screening pass.
356 pub use miden_tx::DataStore;
357
358 pub use crate::store::data_store::ClientDataStore;
359 pub use crate::test_utils::*;
360}
361
362use alloc::sync::Arc;
363use alloc::vec::Vec;
364use core::convert::Infallible;
365
366use miden_protocol::block::BlockNumber;
367use miden_protocol::crypto::merkle::mmr::PartialMmr;
368use miden_protocol::crypto::rand::FeltRng;
369use miden_tx::auth::TransactionAuthenticator;
370use rand::{TryCryptoRng, TryRng};
371use rpc::NodeRpcClient;
372use store::Store;
373
374use crate::note_transport::NoteTransportClient;
375use crate::transaction::TransactionProver;
376
377// MIDEN CLIENT
378// ================================================================================================
379
380/// A light client for connecting to the Miden network.
381///
382/// Miden client is responsible for managing a set of accounts. Specifically, the client:
383/// - Keeps track of the current and historical states of a set of accounts and related objects such
384/// as notes and transactions.
385/// - Connects to a Miden node to periodically sync with the current state of the network.
386/// - Executes, proves, and submits transactions to the network as directed by the user.
387pub struct Client<AUTH> {
388 /// The client's store, which provides a way to write and read entities to provide persistence.
389 store: Arc<dyn Store>,
390 /// An instance of [`FeltRng`] which provides randomness tools for generating new keys,
391 /// serial numbers, etc.
392 rng: ClientRng,
393 /// An instance of [`NodeRpcClient`] which provides a way for the client to connect to the
394 /// Miden node.
395 rpc_api: Arc<dyn NodeRpcClient>,
396 /// An instance of a [`TransactionProver`] which will be the default prover for the
397 /// client.
398 tx_prover: Arc<dyn TransactionProver + Send + Sync>,
399 /// An instance of a [`TransactionAuthenticator`] which will be used by the transaction
400 /// executor whenever a signature is requested from within the VM.
401 authenticator: Option<Arc<AUTH>>,
402 /// Shared source manager used to retain MASM source information for assembled programs.
403 source_manager: Arc<dyn SourceManagerSync>,
404 /// Options that control the transaction executor's runtime behaviour (e.g. cycle limits).
405 exec_options: ExecutionOptions,
406 /// Number of blocks after which pending transactions are considered stale and discarded.
407 tx_discard_delta: Option<u32>,
408 /// Number of synced blocks between automatic irrelevant-block pruning runs.
409 irrelevant_block_prune_interval: Option<u32>,
410 /// Sync height at which the last automatic irrelevant-block prune completed.
411 last_irrelevant_block_prune_sync_height: Option<BlockNumber>,
412 /// Maximum number of blocks the client can be behind the network for transactions and account
413 /// proofs to be considered valid.
414 max_block_number_delta: Option<u32>,
415 /// An instance of [`NoteTransportClient`] which provides a way for the client to connect to
416 /// the Miden Note Transport network.
417 note_transport_api: Option<Arc<dyn NoteTransportClient>>,
418 /// Whether the client should cache the current Partial MMR in memory.
419 cache_partial_mmr_in_memory: bool,
420 /// Cached [`PartialMmr`] for the chain's MMR. Lazily built from the store and kept in sync
421 /// across sync/prune operations. `None` forces a rebuild on next access.
422 partial_mmr: Option<CachedPartialMmr>,
423 /// Observers fired by `apply_transaction`. See
424 /// [`Client::with_transaction_observer`].
425 transaction_observers: Vec<Arc<dyn transaction::TransactionObserver>>,
426}
427
428/// Cached [`PartialMmr`] with a two-part freshness fingerprint:
429///
430/// - `store_peaks_hash`: peaks at the current sync height - guards against chain/height drift.
431/// - `tracked_blocks_hash`: hash of the store's tracked block numbers - guards against drift
432/// between store-tracked and cache-tracked blocks. Required because a same-height update can mark
433/// an existing block relevant without changing peaks; pruning the cached MMR while it's missing
434/// such a block would over-delete auth nodes that the store still needs.
435///
436/// The cached MMR includes the sync-height block as a tracked leaf; the store persists the
437/// peaks committed by that block's header, i.e. the peaks over the chain *before* that block
438/// was added, so the two states are offset by one leaf.
439pub(crate) struct CachedPartialMmr {
440 pub(crate) store_peaks_hash: Word,
441 pub(crate) tracked_blocks_hash: Word,
442 pub(crate) mmr: PartialMmr,
443}
444
445/// Constructors.
446impl<AUTH> Client<AUTH>
447where
448 AUTH: builder::BuilderAuthenticator,
449{
450 /// Returns a new [`ClientBuilder`](builder::ClientBuilder) for constructing a client.
451 ///
452 /// This is a convenience method equivalent to calling `ClientBuilder::new()`.
453 ///
454 /// # Example
455 ///
456 /// ```ignore
457 /// let client = Client::builder()
458 /// .rpc(rpc_client)
459 /// .store(store)
460 /// .authenticator(Arc::new(keystore))
461 /// .build()
462 /// .await?;
463 /// ```
464 pub fn builder() -> builder::ClientBuilder<AUTH> {
465 builder::ClientBuilder::new()
466 }
467}
468
469/// Access methods.
470impl<AUTH> Client<AUTH>
471where
472 AUTH: TransactionAuthenticator,
473{
474 /// Returns an instance of the `CodeBuilder`
475 pub fn code_builder(&self) -> assembly::CodeBuilder {
476 assembly::CodeBuilder::with_source_manager(self.source_manager.clone())
477 }
478
479 /// Returns an instance of [`note::NoteScreener`] configured for this client.
480 pub fn note_screener(&self) -> note::NoteScreener {
481 note::NoteScreener::new(self.store.clone(), self.rpc_api.clone())
482 }
483
484 /// Returns a reference to the client's random number generator. This can be used to generate
485 /// randomness for various purposes such as serial numbers, keys, etc.
486 pub fn rng(&mut self) -> &mut ClientRng {
487 &mut self.rng
488 }
489
490 pub fn prover(&self) -> Arc<dyn TransactionProver + Send + Sync> {
491 self.tx_prover.clone()
492 }
493
494 pub fn authenticator(&self) -> Option<&Arc<AUTH>> {
495 self.authenticator.as_ref()
496 }
497
498 /// Returns the shared source manager used to retain MASM source information for assembled
499 /// programs.
500 pub fn source_manager(&self) -> Arc<dyn SourceManagerSync> {
501 self.source_manager.clone()
502 }
503}
504
505impl<AUTH> Client<AUTH> {
506 /// Returns the identifier of the underlying store (e.g. `IndexedDB` database name, `SQLite`
507 /// file path).
508 pub fn store_identifier(&self) -> &str {
509 self.store.identifier()
510 }
511
512 /// Registers a [`transaction::TransactionObserver`]. Per-observer failures are logged.
513 pub fn with_transaction_observer(
514 &mut self,
515 observer: Arc<dyn transaction::TransactionObserver>,
516 ) {
517 self.transaction_observers.push(observer);
518 }
519
520 /// Returns the network ID of the node the client is connected to.
521 pub async fn network_id(&self) -> Result<address::NetworkId, ClientError> {
522 Ok(self.rpc_api.get_network_id().await?)
523 }
524
525 // TEST HELPERS
526 // --------------------------------------------------------------------------------------------
527
528 #[cfg(any(test, feature = "testing"))]
529 pub fn test_rpc_api(&mut self) -> &mut Arc<dyn NodeRpcClient> {
530 &mut self.rpc_api
531 }
532
533 #[cfg(any(test, feature = "testing"))]
534 pub fn test_store(&mut self) -> &mut Arc<dyn Store> {
535 &mut self.store
536 }
537
538 #[cfg(any(test, feature = "testing"))]
539 pub fn test_has_cached_partial_mmr(&self) -> bool {
540 self.partial_mmr.is_some()
541 }
542}
543
544// CLIENT RNG
545// ================================================================================================
546
547// NOTE: The idea of having `ClientRng` is to enforce `Send` and `Sync` over `FeltRng`.
548// This allows `Client`` to be `Send` and `Sync`. There may be users that would want to use clients
549// with !Send/!Sync RNGs. For this we have two options:
550//
551// - We can make client generic over R (adds verbosity but is more flexible and maybe even correct)
552// - We can optionally (e.g., based on features/target) change `ClientRng` definition to not enforce
553// these bounds. (similar to TransactionAuthenticator)
554
555/// Marker trait for RNGs that can be shared across threads and used by the client.
556pub trait ClientFeltRng: FeltRng + Send + Sync {}
557impl<T> ClientFeltRng for T where T: FeltRng + Send + Sync {}
558
559/// Boxed RNG trait object used by the client.
560pub type ClientRngBox = Box<dyn ClientFeltRng>;
561
562/// A wrapper around a [`FeltRng`] that implements the [`TryRng`] trait.
563/// This allows the user to pass their own generic RNG so that it's used by the client.
564pub struct ClientRng(ClientRngBox);
565
566impl ClientRng {
567 pub fn new(rng: ClientRngBox) -> Self {
568 Self(rng)
569 }
570
571 pub fn inner_mut(&mut self) -> &mut ClientRngBox {
572 &mut self.0
573 }
574}
575
576impl TryRng for ClientRng {
577 type Error = Infallible;
578
579 fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
580 Ok(self.0.next_u32())
581 }
582
583 fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
584 Ok(self.0.next_u64())
585 }
586
587 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Self::Error> {
588 self.0.fill_bytes(dest);
589 Ok(())
590 }
591}
592
593// The client's RNG already backs key and serial-number generation, so callers are required to
594// supply cryptographically secure randomness. Asserting it here lets the RNG drive primitives that
595// demand a `CryptoRng`, such as sealing transaction inputs.
596impl TryCryptoRng for ClientRng {}
597
598impl FeltRng for ClientRng {
599 fn draw_element(&mut self) -> Felt {
600 self.0.draw_element()
601 }
602
603 fn draw_word(&mut self) -> Word {
604 self.0.draw_word()
605 }
606}
607
608#[cfg(test)]
609mod tests {
610 use super::Client;
611
612 fn assert_send_sync<T: Send + Sync>() {}
613
614 #[test]
615 fn client_is_send_sync() {
616 assert_send_sync::<Client<()>>();
617 }
618}