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 [Miden
9//! 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 configurable via
43//! 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 protocol_config;
125pub mod pswap;
126#[cfg(feature = "tonic")]
127pub mod remote_prover;
128pub mod rpc;
129pub mod settings;
130pub mod store;
131pub mod sync;
132pub mod transaction;
133pub mod utils;
134
135pub mod builder;
136
137#[cfg(feature = "testing")]
138mod test_utils;
139
140pub mod errors;
141
142pub use miden_protocol::utils::serde::{Deserializable, Serializable, SliceReader};
143
144// RE-EXPORTS
145// ================================================================================================
146
147pub mod notes {
148 pub use miden_standards::note::NoteFile;
149}
150
151/// Provides `AggLayer` bridge components, note constructors, and helper types.
152pub mod agglayer {
153 pub use miden_agglayer::*;
154 pub use miden_standards::interop::eth::{
155 AddressConversionError,
156 EthAddress,
157 EthAmount,
158 EthAmountError,
159 EthEmbeddedAccountId,
160 };
161}
162
163/// Provides types and utilities for working with Miden Assembly.
164pub mod assembly {
165 pub use miden_protocol::MastForest;
166 pub use miden_protocol::assembly::debuginfo::SourceManagerSync;
167 #[cfg(feature = "std")]
168 pub use miden_protocol::assembly::debuginfo::{SourceManagerExt, Uri};
169 pub use miden_protocol::assembly::diagnostics::Report;
170 pub use miden_protocol::assembly::diagnostics::reporting::PrintDiagnostic;
171 pub use miden_protocol::assembly::mast::MastNodeExt;
172 pub use miden_protocol::assembly::{Assembler, DefaultSourceManager, Module, ModuleKind, Path};
173 pub use miden_standards::code_builder::CodeBuilder;
174}
175
176/// Provides types and utilities for working with assets within the Miden network.
177pub mod asset {
178 pub use miden_protocol::account::delta::AccountVaultDelta;
179 pub use miden_protocol::account::{
180 AccountStorageHeader,
181 AssetCallbackFlag,
182 StorageMapWitness,
183 StorageSlotContent,
184 StorageSlotHeader,
185 };
186 pub use miden_protocol::asset::{
187 Asset,
188 AssetAmount,
189 AssetCallbacks,
190 AssetComposition,
191 AssetId,
192 AssetVault,
193 AssetWitness,
194 FungibleAsset,
195 NonFungibleAsset,
196 NonFungibleAssetDetails,
197 PartialVault,
198 TokenSymbol,
199 };
200}
201
202/// Provides authentication-related types and functionalities for the Miden network.
203pub mod auth {
204 pub use miden_protocol::account::auth::{
205 AuthScheme as AuthSchemeId,
206 AuthSecretKey,
207 PublicKey,
208 PublicKeyCommitment,
209 Signature,
210 };
211 pub use miden_standards::account::auth::{
212 Approver,
213 ApproverSet,
214 AuthGuardedMultisig,
215 AuthGuardedMultisigConfig,
216 AuthMultisig,
217 AuthMultisigConfig,
218 AuthMultisigSmart,
219 AuthMultisigSmartConfig,
220 AuthSingleSig,
221 GuardianConfig,
222 NoAuth,
223 };
224 pub use miden_tx::auth::{BasicAuthenticator, SigningInputs, TransactionAuthenticator};
225
226 pub use crate::account::component::AuthScheme;
227
228 pub const RPO_FALCON_SCHEME_ID: AuthSchemeId = AuthSchemeId::Falcon512Poseidon2;
229 pub const ECDSA_K256_KECCAK_SCHEME_ID: AuthSchemeId = AuthSchemeId::EcdsaK256Keccak;
230}
231
232/// Provides types for working with blocks within the Miden network.
233pub mod block {
234 pub use miden_protocol::block::{BlockHeader, BlockNumber, FeeParameters, ValidatorConfig};
235}
236
237/// Provides cryptographic types and utilities used within the Miden rollup network. It re-exports
238/// commonly used types and random number generators like `FeltRng` from the `miden_standards`
239/// crate.
240pub mod crypto {
241 pub mod ecdsa_k256_keccak {
242 pub use miden_protocol::crypto::dsa::ecdsa_k256_keccak::{
243 PublicKey,
244 Signature,
245 SigningKey,
246 };
247 }
248 pub mod eddsa_25519_sha512 {
249 pub use miden_protocol::crypto::dsa::eddsa_25519_sha512::{KeyExchangeKey, PublicKey};
250 }
251 pub mod rpo_falcon512 {
252 pub use miden_protocol::crypto::dsa::falcon512_poseidon2::{
253 PublicKey,
254 SecretKey,
255 Signature,
256 };
257 }
258 pub use miden_protocol::crypto::hash::blake::Blake3Digest;
259 pub use miden_protocol::crypto::hash::poseidon2::Poseidon2;
260 pub use miden_protocol::crypto::hash::rpo::Rpo256;
261 pub use miden_protocol::crypto::merkle::mmr::{
262 Forest,
263 InOrderIndex,
264 MmrDelta,
265 MmrPeaks,
266 MmrProof,
267 PartialMmr,
268 };
269 // Forest backend types are re-exported for downstream stores.
270 pub use miden_protocol::crypto::merkle::smt::{
271 Backend,
272 BackendReader,
273 ForestInMemoryBackend,
274 LeafIndex,
275 SMT_DEPTH,
276 Smt,
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_assembly_syntax::ast::types::signatures as typed;
308 pub use miden_processor::ExecutionError;
309 pub use miden_processor::mast::error_code_from_msg;
310 pub use miden_processor::operation::OperationError;
311 pub use miden_protocol::vm::{
312 AdviceInputs,
313 AdviceMap,
314 AttributeSet,
315 MIN_STACK_DEPTH,
316 Package,
317 PackageExport,
318 PackageManifest,
319 ProcedureExport,
320 Program,
321 QualifiedProcedureName,
322 Section,
323 SectionId,
324 TargetType,
325 };
326}
327
328pub use async_trait::async_trait;
329pub use errors::*;
330use miden_protocol::assembly::SourceManagerSync;
331pub use miden_protocol::{
332 EMPTY_WORD,
333 Felt,
334 MAX_TX_EXECUTION_CYCLES,
335 MIN_TX_EXECUTION_CYCLES,
336 ONE,
337 PrettyPrint,
338 WORD_SIZE,
339 Word,
340 ZERO,
341};
342pub use miden_tx::{ExecutionOptions, NetworkNotePricer, NotePricingError};
343#[cfg(feature = "tonic")]
344pub use remote_prover::RemoteTransactionProver;
345
346/// Provides test utilities for working with accounts and account IDs within the Miden network. This
347/// module is only available when the `testing` feature is enabled.
348#[cfg(feature = "testing")]
349pub mod testing {
350 pub use miden_protocol::testing::account_id;
351 /// Raw access to `miden-standards` testing modules for items not curated by `miden-client`.
352 pub use miden_standards::testing as standards;
353 pub use miden_standards::testing::note::NoteBuilder;
354 pub use miden_testing::*;
355 /// The data store the executor reads from, the MAST forest store trait it also serves, and the
356 /// MAST store that [`ClientDataStore::mast_store`] returns. Exposed here so that tests can
357 /// exercise them on their own, without going through a transaction or a note screening pass.
358 pub use miden_tx::{DataStore, MastForestStore, TransactionMastStore};
359
360 pub use crate::store::data_store::ClientDataStore;
361 pub use crate::test_utils::*;
362}
363
364use alloc::sync::Arc;
365use alloc::vec::Vec;
366use core::convert::Infallible;
367
368use miden_protocol::block::BlockNumber;
369use miden_protocol::crypto::merkle::mmr::PartialMmr;
370use miden_protocol::crypto::rand::FeltRng;
371use miden_tx::auth::TransactionAuthenticator;
372use rand::{TryCryptoRng, TryRng};
373use rpc::NodeRpcClient;
374use store::Store;
375
376use crate::note_transport::NoteTransportClient;
377use crate::transaction::TransactionProver;
378
379// MIDEN CLIENT
380// ================================================================================================
381
382/// A light client for connecting to the Miden network.
383///
384/// Miden client is responsible for managing a set of accounts. Specifically, the client:
385/// - Keeps track of the current and historical states of a set of accounts and related objects such
386/// as notes and transactions.
387/// - Connects to a Miden node to periodically sync with the current state of the network.
388/// - Executes, proves, and submits transactions to the network as directed by the user.
389pub struct Client<AUTH> {
390 /// The client's store, which provides a way to write and read entities to provide persistence.
391 store: Arc<dyn Store>,
392 /// An instance of [`FeltRng`] which provides randomness tools for generating new keys, serial
393 /// numbers, etc.
394 rng: ClientRng,
395 /// An instance of [`NodeRpcClient`] which provides a way for the client to connect to the Miden
396 /// node.
397 rpc_api: Arc<dyn NodeRpcClient>,
398 /// An instance of a [`TransactionProver`] which will be the default prover for the client.
399 tx_prover: Arc<dyn TransactionProver + Send + Sync>,
400 /// An instance of a [`TransactionAuthenticator`] which will be used by the transaction executor
401 /// whenever a signature is requested from within the VM.
402 authenticator: Option<Arc<AUTH>>,
403 /// Shared source manager used to retain MASM source information for assembled programs.
404 source_manager: Arc<dyn SourceManagerSync>,
405 /// Options that control the transaction executor's runtime behaviour (e.g. cycle limits).
406 exec_options: ExecutionOptions,
407 /// Number of blocks after which pending transactions are considered stale and discarded.
408 tx_discard_delta: Option<u32>,
409 /// Number of synced blocks between automatic irrelevant-block pruning runs.
410 irrelevant_block_prune_interval: Option<u32>,
411 /// Sync height at which the last automatic irrelevant-block prune completed.
412 last_irrelevant_block_prune_sync_height: Option<BlockNumber>,
413 /// Maximum number of blocks the client can be behind the network for transactions and account
414 /// proofs to be considered valid.
415 max_block_number_delta: Option<u32>,
416 /// An instance of [`NoteTransportClient`] which provides a way for the client to connect to the
417 /// Miden Note Transport network.
418 note_transport_api: Option<Arc<dyn NoteTransportClient>>,
419 /// Whether the client should cache the current Partial MMR in memory.
420 cache_partial_mmr_in_memory: bool,
421 /// Cached [`PartialMmr`] for the chain's MMR. Lazily built from the store and kept in sync
422 /// across sync/prune operations. `None` forces a rebuild on next access.
423 partial_mmr: Option<CachedPartialMmr>,
424 /// Observers fired by `apply_transaction`. See [`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 peaks
437/// committed by that block's header, i.e. the peaks over the chain *before* that block was added,
438/// 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`. This allows
548// `Client`` to be `Send` and `Sync`. There may be users that would want to use clients with
549// !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. This allows the user to
563/// 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}