miden_client/
lib.rs

1//! A no_std-compatible client library for interacting with the Miden network.
2//!
3//! This crate provides a lightweight client that handles connections to the Miden node, manages
4//! accounts and their state, and facilitates executing, proving, and submitting transactions.
5//!
6//! For a protocol-level overview and guides for getting started, please visit the official
7//! [Miden docs](https://0xMiden.github.io/miden-docs/).
8//!
9//! ## Overview
10//!
11//! The library is organized into several key modules:
12//!
13//! - **Accounts:** Provides types for managing accounts. Once accounts are tracked by the client,
14//!   their state is updated with every transaction and validated during each sync.
15//!
16//! - **Notes:** Contains types and utilities for working with notes in the Miden client.
17//!
18//! - **RPC:** Facilitates communication with Miden node, exposing RPC methods for syncing state,
19//!   fetching block headers, and submitting transactions.
20//!
21//! - **Store:** Defines and implements the persistence layer for accounts, transactions, notes, and
22//!   other entities.
23//!
24//! - **Sync:** Provides functionality to synchronize the local state with the current state on the
25//!   Miden network.
26//!
27//! - **Transactions:** Offers capabilities to build, execute, prove, and submit transactions.
28//!
29//! Additionally, the crate re-exports several utility modules:
30//!
31//! - **Assembly:** Types for working with Miden Assembly.
32//! - **Assets:** Types and utilities for working with assets.
33//! - **Auth:** Authentication-related types and functionalities.
34//! - **Blocks:** Types for handling block headers.
35//! - **Crypto:** Cryptographic types and utilities, including random number generators.
36//! - **Utils:** Miscellaneous utilities for serialization and common operations.
37//!
38//! The library is designed to work in both `no_std` and `std` environments and is
39//! configurable via Cargo features.
40//!
41//! ## Usage
42//!
43//! To use the Miden client library in your project, add it as a dependency in your `Cargo.toml`:
44//!
45//! ```toml
46//! [dependencies]
47//! miden-client = "0.10"
48//! ```
49//!
50//! ## Example
51//!
52//! Below is a brief example illustrating how to instantiate the client:
53//!
54//! ```rust
55//! use std::sync::Arc;
56//!
57//! use miden_client::crypto::RpoRandomCoin;
58//! use miden_client::keystore::FilesystemKeyStore;
59//! use miden_client::note_transport::NOTE_TRANSPORT_DEFAULT_ENDPOINT;
60//! use miden_client::note_transport::grpc::GrpcNoteTransportClient;
61//! use miden_client::rpc::{Endpoint, GrpcClient};
62//! use miden_client::store::Store;
63//! use miden_client::{Client, ExecutionOptions, Felt};
64//! use miden_client_sqlite_store::SqliteStore;
65//! use miden_objects::crypto::rand::FeltRng;
66//! use miden_objects::{MAX_TX_EXECUTION_CYCLES, MIN_TX_EXECUTION_CYCLES};
67//! use rand::Rng;
68//! use rand::rngs::StdRng;
69//!
70//! # pub async fn create_test_client() -> Result<(), Box<dyn std::error::Error>> {
71//! // Create the SQLite store from the client configuration.
72//! let sqlite_store = SqliteStore::new("path/to/store".try_into()?).await?;
73//! let store = Arc::new(sqlite_store);
74//!
75//! // Generate a random seed for the RpoRandomCoin.
76//! let mut rng = rand::rng();
77//! let coin_seed: [u64; 4] = rng.random();
78//!
79//! // Initialize the random coin using the generated seed.
80//! let rng = RpoRandomCoin::new(coin_seed.map(Felt::new).into());
81//! let keystore = FilesystemKeyStore::new("path/to/keys/directory".try_into()?)?;
82//!
83//! // Determine the number of blocks to consider a transaction stale.
84//! // 20 is simply an example value.
85//! let tx_graceful_blocks = Some(20);
86//! // Determine the maximum number of blocks that the client can be behind from the network.
87//! // 256 is simply an example value.
88//! let max_block_number_delta = Some(256);
89//!
90//! // Optionally, connect to the note transport network to exchange private notes.
91//! let note_transport_api =
92//!     GrpcNoteTransportClient::connect(NOTE_TRANSPORT_DEFAULT_ENDPOINT.to_string(), 10_000)
93//!         .await?;
94//!
95//! // Instantiate the client using a gRPC client
96//! let endpoint = Endpoint::new("https".into(), "localhost".into(), Some(57291));
97//! let client: Client<FilesystemKeyStore<StdRng>> = Client::new(
98//!     Arc::new(GrpcClient::new(&endpoint, 10_000)),
99//!     Box::new(rng),
100//!     store,
101//!     Some(Arc::new(keystore)), // or None if no authenticator is needed
102//!     ExecutionOptions::new(
103//!         Some(MAX_TX_EXECUTION_CYCLES),
104//!         MIN_TX_EXECUTION_CYCLES,
105//!         false,
106//!         false, // Set to true for debug mode, if needed.
107//!     )
108//!     .unwrap(),
109//!     tx_graceful_blocks,
110//!     max_block_number_delta,
111//!     Some(Arc::new(note_transport_api)),
112//!     None, // or Some(Arc::new(prover)) for a custom prover
113//! )
114//! .await
115//! .unwrap();
116//!
117//! # Ok(())
118//! # }
119//! ```
120//!
121//! For additional usage details, configuration options, and examples, consult the documentation for
122//! each module.
123
124#![no_std]
125
126#[macro_use]
127extern crate alloc;
128use alloc::boxed::Box;
129
130#[cfg(feature = "std")]
131extern crate std;
132
133pub mod account;
134pub mod keystore;
135pub mod note;
136pub mod note_transport;
137pub mod rpc;
138pub mod settings;
139pub mod store;
140pub mod sync;
141pub mod transaction;
142pub mod utils;
143
144#[cfg(feature = "std")]
145pub mod builder;
146
147#[cfg(feature = "testing")]
148mod test_utils;
149
150pub mod errors;
151
152// RE-EXPORTS
153// ================================================================================================
154
155pub mod notes {
156    pub use miden_objects::note::NoteFile;
157}
158
159/// Provides types and utilities for working with Miden Assembly.
160pub mod assembly {
161    pub use miden_objects::assembly::debuginfo::SourceManagerSync;
162    pub use miden_objects::assembly::diagnostics::Report;
163    pub use miden_objects::assembly::diagnostics::reporting::PrintDiagnostic;
164    pub use miden_objects::assembly::{
165        Assembler,
166        DefaultSourceManager,
167        Library,
168        LibraryPath,
169        Module,
170        ModuleKind,
171    };
172}
173
174/// Provides types and utilities for working with assets within the Miden network.
175pub mod asset {
176    pub use miden_objects::AssetError;
177    pub use miden_objects::account::delta::{
178        AccountStorageDelta,
179        AccountVaultDelta,
180        FungibleAssetDelta,
181        NonFungibleAssetDelta,
182        NonFungibleDeltaAction,
183    };
184    pub use miden_objects::asset::{
185        Asset,
186        AssetVault,
187        AssetWitness,
188        FungibleAsset,
189        NonFungibleAsset,
190        NonFungibleAssetDetails,
191        TokenSymbol,
192    };
193}
194
195/// Provides authentication-related types and functionalities for the Miden
196/// network.
197pub mod auth {
198    pub use miden_lib::AuthScheme;
199    pub use miden_lib::account::auth::{AuthRpoFalcon512, NoAuth};
200    pub use miden_objects::account::auth::{AuthSecretKey, PublicKeyCommitment, Signature};
201    pub use miden_tx::auth::{BasicAuthenticator, SigningInputs, TransactionAuthenticator};
202}
203
204/// Provides types for working with blocks within the Miden network.
205pub mod block {
206    pub use miden_objects::block::BlockHeader;
207}
208
209/// Provides cryptographic types and utilities used within the Miden rollup
210/// network. It re-exports commonly used types and random number generators like `FeltRng` from
211/// the `miden_objects` crate.
212pub mod crypto {
213    pub mod rpo_falcon512 {
214        pub use miden_objects::crypto::dsa::rpo_falcon512::{PublicKey, SecretKey, Signature};
215    }
216
217    pub use miden_objects::crypto::hash::blake::{Blake3_160, Blake3Digest};
218    pub use miden_objects::crypto::hash::rpo::Rpo256;
219    pub use miden_objects::crypto::merkle::{
220        Forest,
221        InOrderIndex,
222        LeafIndex,
223        MerklePath,
224        MerkleStore,
225        MerkleTree,
226        MmrDelta,
227        MmrPeaks,
228        MmrProof,
229        NodeIndex,
230        SMT_DEPTH,
231        SmtLeaf,
232        SmtProof,
233    };
234    pub use miden_objects::crypto::rand::{FeltRng, RpoRandomCoin};
235}
236
237/// Provides types for working with addresses within the Miden network.
238pub mod address {
239    pub use miden_objects::address::{
240        Address,
241        AddressId,
242        AddressInterface,
243        NetworkId,
244        RoutingParameters,
245    };
246}
247
248/// Provides types for working with the virtual machine within the Miden network.
249pub mod vm {
250    pub use miden_objects::vm::{
251        AdviceInputs,
252        AdviceMap,
253        AttributeSet,
254        MastArtifact,
255        Package,
256        PackageExport,
257        PackageManifest,
258        QualifiedProcedureName,
259        Section,
260        SectionId,
261    };
262}
263
264pub use async_trait::async_trait;
265pub use errors::*;
266use miden_objects::assembly::{DefaultSourceManager, SourceManagerSync};
267pub use miden_objects::{
268    EMPTY_WORD,
269    Felt,
270    MAX_TX_EXECUTION_CYCLES,
271    MIN_TX_EXECUTION_CYCLES,
272    ONE,
273    PrettyPrint,
274    StarkField,
275    Word,
276    ZERO,
277};
278pub use miden_remote_prover_client::remote_prover::tx_prover::RemoteTransactionProver;
279pub use miden_tx::ExecutionOptions;
280
281/// Provides test utilities for working with accounts and account IDs
282/// within the Miden network. This module is only available when the `testing` feature is
283/// enabled.
284#[cfg(feature = "testing")]
285pub mod testing {
286    pub use miden_lib::testing::note::NoteBuilder;
287    pub use miden_objects::testing::*;
288    pub use miden_testing::*;
289
290    pub use crate::test_utils::*;
291}
292
293use alloc::sync::Arc;
294
295pub use miden_lib::utils::{Deserializable, ScriptBuilder, Serializable, SliceReader};
296pub use miden_objects::block::BlockNumber;
297use miden_objects::crypto::rand::FeltRng;
298use miden_tx::LocalTransactionProver;
299use miden_tx::auth::TransactionAuthenticator;
300use rand::RngCore;
301use rpc::NodeRpcClient;
302use store::Store;
303
304use crate::note_transport::{NoteTransportClient, init_note_transport_cursor};
305use crate::transaction::TransactionProver;
306
307// MIDEN CLIENT
308// ================================================================================================
309
310/// A light client for connecting to the Miden network.
311///
312/// Miden client is responsible for managing a set of accounts. Specifically, the client:
313/// - Keeps track of the current and historical states of a set of accounts and related objects such
314///   as notes and transactions.
315/// - Connects to a Miden node to periodically sync with the current state of the network.
316/// - Executes, proves, and submits transactions to the network as directed by the user.
317pub struct Client<AUTH> {
318    /// The client's store, which provides a way to write and read entities to provide persistence.
319    store: Arc<dyn Store>,
320    /// An instance of [`FeltRng`] which provides randomness tools for generating new keys,
321    /// serial numbers, etc.
322    rng: ClientRng,
323    /// An instance of [`NodeRpcClient`] which provides a way for the client to connect to the
324    /// Miden node.
325    rpc_api: Arc<dyn NodeRpcClient>,
326    /// An instance of a [`TransactionProver`] which will be the default prover for the
327    /// client.
328    tx_prover: Arc<dyn TransactionProver + Send + Sync>,
329    /// An instance of a [`TransactionAuthenticator`] which will be used by the transaction
330    /// executor whenever a signature is requested from within the VM.
331    authenticator: Option<Arc<AUTH>>,
332    /// Shared source manager used to retain MASM source information for assembled programs.
333    source_manager: Arc<dyn SourceManagerSync>,
334    /// Options that control the transaction executor’s runtime behaviour (e.g. debug mode).
335    exec_options: ExecutionOptions,
336    /// The number of blocks that are considered old enough to discard pending transactions.
337    tx_graceful_blocks: Option<u32>,
338    /// Maximum number of blocks the client can be behind the network for transactions and account
339    /// proofs to be considered valid.
340    max_block_number_delta: Option<u32>,
341    /// An instance of [`NoteTransportClient`] which provides a way for the client to connect to
342    /// the Miden Note Transport network.
343    note_transport_api: Option<Arc<dyn NoteTransportClient>>,
344}
345
346/// Construction and access methods.
347impl<AUTH> Client<AUTH>
348where
349    AUTH: TransactionAuthenticator,
350{
351    // CONSTRUCTOR
352    // --------------------------------------------------------------------------------------------
353
354    /// Returns a new instance of [`Client`].
355    ///
356    /// ## Arguments
357    ///
358    /// - `rpc_api`: An instance of [`NodeRpcClient`] which provides a way for the client to connect
359    ///   to the Miden node.
360    /// - `rng`: An instance of [`FeltRng`] which provides randomness tools for generating new keys,
361    ///   serial numbers, etc. This can be any RNG that implements the [`FeltRng`] trait.
362    /// - `store`: An instance of [`Store`], which provides a way to write and read entities to
363    ///   provide persistence.
364    /// - `authenticator`: Defines the transaction authenticator that will be used by the
365    ///   transaction executor whenever a signature is requested from within the VM.
366    /// - `exec_options`: Options that control the transaction executor’s runtime behaviour (e.g.
367    ///   debug mode).
368    /// - `tx_graceful_blocks`: The number of blocks that are considered old enough to discard
369    ///   pending transactions.
370    /// - `max_block_number_delta`: Determines the maximum number of blocks that the client can be
371    ///   behind the network for transactions and account proofs to be considered valid.
372    /// - `note_transport_api`: An instance of [`NoteTransportClient`] which provides a way for the
373    ///   client to connect to the Miden Note Transport network.
374    /// - `tx_prover`: An optional instance of [`TransactionProver`] which will be used as the
375    ///   default prover for the client. If not provided, a default local prover will be created.
376    ///
377    /// # Errors
378    ///
379    /// Returns an error if the client couldn't be instantiated.
380    #[allow(clippy::too_many_arguments)]
381    pub async fn new(
382        rpc_api: Arc<dyn NodeRpcClient>,
383        rng: Box<dyn FeltRng>,
384        store: Arc<dyn Store>,
385        authenticator: Option<Arc<AUTH>>,
386        exec_options: ExecutionOptions,
387        tx_graceful_blocks: Option<u32>,
388        max_block_number_delta: Option<u32>,
389        note_transport_api: Option<Arc<dyn NoteTransportClient>>,
390        tx_prover: Option<Arc<dyn TransactionProver + Send + Sync>>,
391    ) -> Result<Self, ClientError> {
392        let tx_prover: Arc<dyn TransactionProver + Send + Sync> =
393            tx_prover.unwrap_or_else(|| Arc::new(LocalTransactionProver::default()));
394
395        if let Some((genesis, _)) = store.get_block_header_by_num(BlockNumber::GENESIS).await? {
396            // Set the genesis commitment in the RPC API client for future requests.
397            rpc_api.set_genesis_commitment(genesis.commitment()).await?;
398        }
399
400        if note_transport_api.is_some() {
401            // Initialize the note transport cursor
402            init_note_transport_cursor(store.clone()).await?;
403        }
404
405        let source_manager: Arc<dyn SourceManagerSync> = Arc::new(DefaultSourceManager::default());
406
407        Ok(Self {
408            store,
409            rng: ClientRng::new(rng),
410            rpc_api,
411            tx_prover,
412            authenticator,
413            source_manager,
414            exec_options,
415            tx_graceful_blocks,
416            max_block_number_delta,
417            note_transport_api,
418        })
419    }
420
421    /// Returns true if the client is in debug mode.
422    pub fn in_debug_mode(&self) -> bool {
423        self.exec_options.enable_debugging()
424    }
425
426    /// Returns an instance of the `ScriptBuilder`
427    pub fn script_builder(&self) -> ScriptBuilder {
428        ScriptBuilder::with_source_manager(self.source_manager.clone())
429    }
430
431    /// Returns a reference to the client's random number generator. This can be used to generate
432    /// randomness for various purposes such as serial numbers, keys, etc.
433    pub fn rng(&mut self) -> &mut ClientRng {
434        &mut self.rng
435    }
436
437    pub fn prover(&self) -> Arc<dyn TransactionProver + Send + Sync> {
438        self.tx_prover.clone()
439    }
440
441    // TEST HELPERS
442    // --------------------------------------------------------------------------------------------
443
444    #[cfg(any(test, feature = "testing"))]
445    pub fn test_rpc_api(&mut self) -> &mut Arc<dyn NodeRpcClient> {
446        &mut self.rpc_api
447    }
448
449    #[cfg(any(test, feature = "testing"))]
450    pub fn test_store(&mut self) -> &mut Arc<dyn Store> {
451        &mut self.store
452    }
453}
454
455// CLIENT RNG
456// ================================================================================================
457
458/// A wrapper around a [`FeltRng`] that implements the [`RngCore`] trait.
459/// This allows the user to pass their own generic RNG so that it's used by the client.
460pub struct ClientRng(Box<dyn FeltRng>);
461
462impl ClientRng {
463    pub fn new(rng: Box<dyn FeltRng>) -> Self {
464        Self(rng)
465    }
466
467    pub fn inner_mut(&mut self) -> &mut Box<dyn FeltRng> {
468        &mut self.0
469    }
470}
471
472impl RngCore for ClientRng {
473    fn next_u32(&mut self) -> u32 {
474        self.0.next_u32()
475    }
476
477    fn next_u64(&mut self) -> u64 {
478        self.0.next_u64()
479    }
480
481    fn fill_bytes(&mut self, dest: &mut [u8]) {
482        self.0.fill_bytes(dest);
483    }
484}
485
486impl FeltRng for ClientRng {
487    fn draw_element(&mut self) -> Felt {
488        self.0.draw_element()
489    }
490
491    fn draw_word(&mut self) -> Word {
492        self.0.draw_word()
493    }
494}
495
496/// Indicates whether the client is operating in debug mode.
497#[derive(Debug, Clone, Copy)]
498pub enum DebugMode {
499    Enabled,
500    Disabled,
501}
502
503impl From<DebugMode> for bool {
504    fn from(debug_mode: DebugMode) -> Self {
505        match debug_mode {
506            DebugMode::Enabled => true,
507            DebugMode::Disabled => false,
508        }
509    }
510}
511
512impl From<bool> for DebugMode {
513    fn from(debug_mode: bool) -> DebugMode {
514        if debug_mode {
515            DebugMode::Enabled
516        } else {
517            DebugMode::Disabled
518        }
519    }
520}