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