miden_client_tools/
lib.rs

1use miden_assembly::{
2    Assembler, DefaultSourceManager, LibraryPath,
3    ast::{Module, ModuleKind},
4};
5use miden_crypto::dsa::rpo_falcon512::Polynomial;
6use rand::{RngCore, rngs::StdRng};
7use std::sync::Arc;
8use tokio::time::{Duration, sleep};
9
10use miden_client::{
11    Client, ClientError, Felt, Word,
12    account::{
13        Account, AccountBuilder, AccountId, AccountStorageMode, AccountType,
14        component::{BasicFungibleFaucet, BasicWallet, RpoFalcon512},
15    },
16    asset::{Asset, FungibleAsset, TokenSymbol},
17    auth::AuthSecretKey,
18    builder::ClientBuilder,
19    crypto::{FeltRng, SecretKey},
20    keystore::FilesystemKeyStore,
21    note::{
22        Note, NoteAssets, NoteExecutionHint, NoteExecutionMode, NoteInputs, NoteMetadata,
23        NoteRecipient, NoteScript, NoteTag, NoteType,
24    },
25    rpc::{Endpoint, TonicRpcClient},
26    store::NoteFilter,
27    transaction::{OutputNote, TransactionKernel, TransactionRequestBuilder, TransactionScript},
28};
29use miden_lib::note::utils;
30use miden_objects::{Hasher, NoteError, assembly::Library};
31use serde::de::value::Error;
32
33/// Helper to instantiate a `Client` for interacting with Miden.
34///
35/// # Arguments
36///
37/// * `endpoint` - The endpoint of the RPC server to connect to.
38/// * `store_path` - An optional path to the SQLite store.
39///
40/// # Returns
41///
42/// Returns a `Result` containing the `Client` if successful, or a `ClientError` if an error occurs.
43pub async fn instantiate_client(
44    endpoint: Endpoint,
45    store_path: Option<&str>,
46) -> Result<Client, ClientError> {
47    let timeout_ms = 10_000;
48    let rpc_api = Arc::new(TonicRpcClient::new(&endpoint, timeout_ms));
49
50    let client = ClientBuilder::new()
51        .rpc(rpc_api.clone())
52        .filesystem_keystore("./keystore")
53        .sqlite_store(store_path.unwrap_or("./store.sqlite3"))
54        .in_debug_mode(true)
55        .build()
56        .await?;
57
58    Ok(client)
59}
60
61/// Deletes the keystore and store files.
62///
63/// # Arguments
64///
65/// * `store_path` - An optional path to the SQLite store that should be deleted. Defaults to `./store.sqlite3` if not provided.
66///
67/// This function removes all files from the keystore and deletes the SQLite store file, if they exist.
68pub async fn delete_keystore_and_store(store_path: Option<&str>) {
69    let store_path = store_path.unwrap_or("./store.sqlite3");
70    if tokio::fs::metadata(store_path).await.is_ok() {
71        if let Err(e) = tokio::fs::remove_file(store_path).await {
72            eprintln!("failed to remove {}: {}", store_path, e);
73        } else {
74            println!("cleared sqlite store: {}", store_path);
75        }
76    } else {
77        println!("store not found: {}", store_path);
78    }
79
80    let keystore_dir = "./keystore";
81    match tokio::fs::read_dir(keystore_dir).await {
82        Ok(mut dir) => {
83            while let Ok(Some(entry)) = dir.next_entry().await {
84                let file_path = entry.path();
85                if let Err(e) = tokio::fs::remove_file(&file_path).await {
86                    eprintln!("failed to remove {}: {}", file_path.display(), e);
87                } else {
88                    println!("removed file: {}", file_path.display());
89                }
90            }
91        }
92        Err(e) => eprintln!("failed to read directory {}: {}", keystore_dir, e),
93    }
94}
95
96/// Multiplies two polynomials modulo `p` and returns the result.
97///
98/// # Arguments
99///
100/// * `a` - The first polynomial.
101/// * `b` - The second polynomial.
102///
103/// # Returns
104///
105/// Returns the resulting polynomial of the multiplication.
106const N: usize = 512;
107fn mul_modulo_p(a: Polynomial<Felt>, b: Polynomial<Felt>) -> [u64; 1024] {
108    let mut c = [0; 2 * N];
109    for i in 0..N {
110        for j in 0..N {
111            c[i + j] += a.coefficients[i].as_int() * b.coefficients[j].as_int();
112        }
113    }
114    c
115}
116
117/// Converts a polynomial into a vector of `Felt` elements.
118///
119/// # Arguments
120///
121/// * `poly` - The polynomial to convert.
122///
123/// # Returns
124///
125/// A vector of `Felt` elements corresponding to the polynomial's coefficients.
126fn to_elements(poly: Polynomial<Felt>) -> Vec<Felt> {
127    poly.coefficients.to_vec()
128}
129
130/// Generates an advice stack from a signature using two polynomials `h` and `s2`.
131///
132/// # Arguments
133///
134/// * `h` - The first polynomial representing part of the signature.
135/// * `s2` - The second polynomial representing part of the signature.
136///
137/// # Returns
138///
139/// Returns a vector representing the advice stack.
140pub fn generate_advice_stack_from_signature(h: Polynomial<Felt>, s2: Polynomial<Felt>) -> Vec<u64> {
141    let pi = mul_modulo_p(h.clone(), s2.clone());
142
143    // lay the polynomials in order h then s2 then pi = h * s2
144    let mut polynomials = to_elements(h.clone());
145    polynomials.extend(to_elements(s2.clone()));
146    polynomials.extend(pi.iter().map(|a| Felt::new(*a)));
147
148    // get the challenge point and push it to the advice stack
149    let digest_polynomials = Hasher::hash_elements(&polynomials);
150    let challenge = (digest_polynomials[0], digest_polynomials[1]);
151    let mut advice_stack = vec![challenge.0.as_int(), challenge.1.as_int()];
152
153    // push the polynomials to the advice stack
154    let polynomials: Vec<u64> = polynomials.iter().map(|&e| e.into()).collect();
155    advice_stack.extend_from_slice(&polynomials);
156
157    advice_stack
158}
159
160/// Creates a Miden library from the provided account code and library path.
161///
162/// # Arguments
163///
164/// * `account_code` - The account code in MASM format.
165/// * `library_path` - The path where the library is located.
166///
167/// # Returns
168///
169/// Returns the resulting `Library` if successful, or an error if the library cannot be created.
170pub fn create_library(
171    account_code: String,
172    library_path: &str,
173) -> Result<miden_assembly::Library, Box<dyn std::error::Error>> {
174    let assembler: Assembler = TransactionKernel::assembler().with_debug_mode(true);
175    let source_manager = Arc::new(DefaultSourceManager::default());
176    let module = Module::parser(ModuleKind::Library).parse_str(
177        LibraryPath::new(library_path)?,
178        account_code,
179        &source_manager,
180    )?;
181    let library = assembler.clone().assemble_library([module])?;
182    Ok(library)
183}
184
185/// Creates a basic account with a random key and adds it to the client.
186///
187/// # Arguments
188///
189/// * `client` - The Miden client to interact with.
190/// * `keystore` - The keystore to store the account's secret key.
191///
192/// # Returns
193///
194/// Returns a tuple containing the created `Account` and the associated `SecretKey`.
195pub async fn create_basic_account(
196    client: &mut Client,
197    keystore: FilesystemKeyStore<StdRng>,
198) -> Result<(miden_client::account::Account, SecretKey), ClientError> {
199    let mut init_seed = [0_u8; 32];
200    client.rng().fill_bytes(&mut init_seed);
201
202    let key_pair = SecretKey::with_rng(client.rng());
203    let builder = AccountBuilder::new(init_seed)
204        // .anchor((&anchor_block).try_into().unwrap())
205        .account_type(AccountType::RegularAccountUpdatableCode)
206        .storage_mode(AccountStorageMode::Public)
207        .with_auth_component(RpoFalcon512::new(key_pair.public_key().clone()))
208        .with_component(BasicWallet);
209
210    let (account, seed) = builder.build().unwrap();
211    client.add_account(&account, Some(seed), false).await?;
212    keystore
213        .add_key(&AuthSecretKey::RpoFalcon512(key_pair.clone()))
214        .unwrap();
215
216    Ok((account, key_pair))
217}
218
219/// Creates a basic faucet account with a fungible asset.
220///
221/// # Arguments
222///
223/// * `client` - The Miden client to interact with.
224/// * `keystore` - The keystore to store the faucet's secret key.
225///
226/// # Returns
227///
228/// Returns the created faucet `Account`.
229pub async fn create_basic_faucet(
230    client: &mut Client,
231    keystore: FilesystemKeyStore<StdRng>,
232) -> Result<miden_client::account::Account, ClientError> {
233    let mut init_seed = [0u8; 32];
234    client.rng().fill_bytes(&mut init_seed);
235    let key_pair = SecretKey::with_rng(client.rng());
236    let symbol = TokenSymbol::new("MID").unwrap();
237    let decimals = 8;
238    let max_supply = Felt::new(1_000_000);
239    let builder = AccountBuilder::new(init_seed)
240        .account_type(AccountType::FungibleFaucet)
241        .storage_mode(AccountStorageMode::Public)
242        .with_auth_component(RpoFalcon512::new(key_pair.public_key()))
243        .with_component(BasicFungibleFaucet::new(symbol, decimals, max_supply).unwrap());
244    let (account, seed) = builder.build().unwrap();
245    client.add_account(&account, Some(seed), false).await?;
246    keystore
247        .add_key(&AuthSecretKey::RpoFalcon512(key_pair))
248        .unwrap();
249    Ok(account)
250}
251
252/// Sets up a specified number of accounts and faucets, and mints tokens for each account.
253///
254/// This function creates a set of basic accounts and faucets, and mints tokens from each faucet to the accounts
255/// based on the given balance matrix.
256///
257/// # Arguments
258///
259/// * `client` - The Miden client used to interact with the blockchain.
260/// * `keystore` - The keystore used to securely store account keys.
261/// * `num_accounts` - The number of accounts to create.
262/// * `num_faucets` - The number of faucets to create.
263/// * `balances` - A matrix where each entry represents the number of tokens to mint from a faucet to an account.
264///
265/// # Returns
266///
267/// Returns a tuple containing the created accounts and faucets as vectors.
268pub async fn setup_accounts_and_faucets(
269    client: &mut Client,
270    keystore: FilesystemKeyStore<StdRng>,
271    num_accounts: usize,
272    num_faucets: usize,
273    balances: Vec<Vec<u64>>,
274) -> Result<(Vec<Account>, Vec<Account>), ClientError> {
275    let mut accounts = Vec::with_capacity(num_accounts);
276    for i in 0..num_accounts {
277        let (account, _) = create_basic_account(client, keystore.clone()).await?;
278        println!("Created Account #{i} => ID: {:?}", account.id());
279        accounts.push(account);
280    }
281
282    let mut faucets = Vec::with_capacity(num_faucets);
283    for j in 0..num_faucets {
284        let faucet = create_basic_faucet(client, keystore.clone()).await?;
285        println!("Created Faucet #{j} => ID: {:?}", faucet.id());
286        faucets.push(faucet);
287    }
288
289    client.sync_state().await?;
290
291    for (acct_index, account) in accounts.iter().enumerate() {
292        for (faucet_index, faucet) in faucets.iter().enumerate() {
293            let amount_to_mint = balances[acct_index][faucet_index];
294            if amount_to_mint == 0 {
295                continue;
296            }
297
298            println!(
299                "Minting {amount_to_mint} tokens from Faucet #{faucet_index} to Account #{acct_index}"
300            );
301
302            let fungible_asset = FungibleAsset::new(faucet.id(), amount_to_mint).unwrap();
303            let tx_req = TransactionRequestBuilder::new()
304                .build_mint_fungible_asset(
305                    fungible_asset,
306                    account.id(),
307                    NoteType::Public,
308                    client.rng(),
309                )
310                .unwrap();
311
312            let tx_exec = client.new_transaction(faucet.id(), tx_req).await?;
313            client.submit_transaction(tx_exec.clone()).await?;
314
315            let minted_note = if let OutputNote::Full(note) = tx_exec.created_notes().get_note(0) {
316                note.clone()
317            } else {
318                panic!("Expected OutputNote::Full, but got something else");
319            };
320
321            wait_for_note(client, &minted_note).await?;
322            client.sync_state().await?;
323
324            let consume_req = TransactionRequestBuilder::new()
325                .authenticated_input_notes([(minted_note.id(), None)])
326                .build()
327                .unwrap();
328
329            let tx_exec = client.new_transaction(account.id(), consume_req).await?;
330            client.submit_transaction(tx_exec).await?;
331            client.sync_state().await?;
332        }
333    }
334
335    Ok((accounts, faucets))
336}
337
338/// Mints tokens from a faucet to an account.
339///
340/// This function mints a specified amount of tokens from a faucet to an account, and waits for the transaction
341/// to be confirmed. It optionally executes a custom transaction script if provided.
342///
343/// # Arguments
344///
345/// * `client` - The Miden client used to interact with the blockchain.
346/// * `account` - The account that will receive the tokens.
347/// * `faucet` - The faucet to mint tokens from.
348/// * `amount` - The number of tokens to mint.
349/// * `tx_script` - An optional custom transaction script to execute after the minting transaction. If `None`, no script is executed.
350///
351/// # Returns
352///
353/// Returns a `Result` indicating whether the minting process was successful or not. If the transaction script is provided, it will also be executed
354/// after the minting process, otherwise, only the minting transaction is processed.
355pub async fn mint_from_faucet_for_account(
356    client: &mut Client,
357    account: &Account,
358    faucet: &Account,
359    amount: u64,
360    tx_script: Option<TransactionScript>, // Make tx_script optional
361) -> Result<(), ClientError> {
362    if amount == 0 {
363        return Ok(());
364    }
365
366    let asset = FungibleAsset::new(faucet.id(), amount).unwrap();
367    let mint_req = TransactionRequestBuilder::new()
368        .build_mint_fungible_asset(asset, account.id(), NoteType::Public, client.rng())
369        .unwrap();
370
371    let mint_exec = client.new_transaction(faucet.id(), mint_req).await?;
372    client.submit_transaction(mint_exec.clone()).await?;
373
374    let minted_note = match mint_exec.created_notes().get_note(0) {
375        OutputNote::Full(note) => note.clone(),
376        _ => panic!("Expected full minted note"),
377    };
378
379    let consume_req = if let Some(script) = tx_script {
380        TransactionRequestBuilder::new()
381            .unauthenticated_input_notes([(minted_note, None)])
382            .custom_script(script)
383            .build()?
384    } else {
385        TransactionRequestBuilder::new()
386            .unauthenticated_input_notes([(minted_note, None)])
387            .build()?
388    };
389
390    let consume_exec = client
391        .new_transaction(account.id(), consume_req)
392        .await
393        .unwrap();
394
395    client.submit_transaction(consume_exec.clone()).await?;
396    client.sync_state().await?;
397
398    Ok(())
399}
400
401/// Creates a public note in the blockchain.
402///
403/// This function creates a public note using the provided note code, account library (if any), and other
404/// related parameters.
405///
406/// # Arguments
407///
408/// * `client` - The Miden client used to interact with the blockchain.
409/// * `note_code` - The code for the note, typically written in MASM.
410/// * `account_library` - An optional library that might be used during note creation.
411/// * `creator_account` - The account creating the note.
412/// * `assets` - The assets associated with the note (optional).
413/// * `note_inputs` - The inputs associated with the note (optional).
414///
415/// # Returns
416///
417/// Returns a `Result` containing the created `Note` or an error.
418pub async fn create_public_note(
419    client: &mut Client,
420    note_code: String,
421    account_library: Option<Library>,
422    creator_account: Account,
423    assets: Option<NoteAssets>,
424    note_inputs: Option<NoteInputs>,
425) -> Result<Note, ClientError> {
426    let assembler = if let Some(library) = account_library {
427        TransactionKernel::assembler()
428            .with_library(&library)
429            .unwrap()
430    } else {
431        TransactionKernel::assembler()
432    }
433    .with_debug_mode(true);
434
435    let rng = client.rng();
436    let serial_num = rng.draw_word();
437    let note_script = NoteScript::compile(note_code, assembler.clone()).unwrap();
438
439    let note_inputs = note_inputs.unwrap_or_else(|| NoteInputs::new([].to_vec()).unwrap());
440    let assets = assets.unwrap_or_else(|| NoteAssets::new(vec![]).unwrap());
441
442    let recipient = NoteRecipient::new(serial_num, note_script, note_inputs.clone());
443    let tag = NoteTag::for_public_use_case(0, 0, NoteExecutionMode::Local).unwrap();
444    let metadata = NoteMetadata::new(
445        creator_account.id(),
446        NoteType::Public,
447        tag,
448        NoteExecutionHint::always(),
449        Felt::new(0),
450    )
451    .unwrap();
452
453    let note = Note::new(assets, metadata, recipient);
454
455    let note_req = TransactionRequestBuilder::new()
456        .own_output_notes(vec![OutputNote::Full(note.clone())])
457        .build()
458        .unwrap();
459    let tx_result = client
460        .new_transaction(creator_account.id(), note_req)
461        .await?;
462
463    client.submit_transaction(tx_result).await?;
464    client.sync_state().await?;
465
466    Ok(note)
467}
468
469/// Waits for the exact note to be available and committed.
470///
471/// This function will block until the specified note is found in the output notes and is committed.
472///
473/// # Arguments
474///
475/// * `client` - The Miden client used to interact with the blockchain.
476/// * `expected` - The note to wait for.
477///
478/// # Returns
479///
480/// Returns a `Result` indicating whether the note was found and committed.
481pub async fn wait_for_note(client: &mut Client, expected: &Note) -> Result<(), ClientError> {
482    loop {
483        client.sync_state().await?;
484
485        let notes = client.get_output_notes(NoteFilter::All).await?;
486
487        // Check if the expected note is in the output notes and is committed
488        let found = notes
489            .iter()
490            .any(|output_note| output_note.id() == expected.id() && output_note.is_committed());
491
492        if found {
493            println!("✅ note found and committed {}", expected.id().to_hex());
494            break;
495        }
496
497        println!("Note {} not found. Waiting...", expected.id().to_hex());
498        sleep(Duration::from_secs(3)).await;
499    }
500    Ok(())
501}
502
503/// Creates a transaction script based on the provided code and optional library.
504///
505/// # Arguments
506///
507/// * `script_code` - The code for the transaction script, typically written in MASM.
508/// * `library` - An optional library to use with the script.
509///
510/// # Returns
511///
512/// Returns a `TransactionScript` if successfully created, or an error.
513pub fn create_tx_script(
514    script_code: String,
515    library: Option<Library>,
516) -> Result<TransactionScript, Error> {
517    let assembler = TransactionKernel::assembler();
518
519    let assembler = match library {
520        Some(lib) => assembler.with_library(lib),
521        None => Ok(assembler.with_debug_mode(true)),
522    }
523    .unwrap();
524    let tx_script = TransactionScript::compile(script_code, assembler).unwrap();
525
526    Ok(tx_script)
527}
528
529/// Creates a public-to-ID (p2id) note for a specified sender and target account.
530///
531/// # Arguments
532///
533/// * `sender` - The account ID of the sender.
534/// * `target` - The account ID of the target.
535/// * `assets` - The assets associated with the note.
536/// * `note_type` - The type of the note (e.g., public).
537/// * `aux` - Auxiliary data for the note.
538/// * `serial_num` - The serial number of the note.
539///
540/// # Returns
541///
542/// Returns the created `Note`.
543pub fn create_exact_p2id_note(
544    sender: AccountId,
545    target: AccountId,
546    assets: Vec<Asset>,
547    note_type: NoteType,
548    aux: Felt,
549    serial_num: Word,
550) -> Result<Note, NoteError> {
551    let recipient = utils::build_p2id_recipient(target, serial_num)?;
552    let tag = NoteTag::from_account_id(target);
553
554    let metadata = NoteMetadata::new(sender, note_type, tag, NoteExecutionHint::always(), aux)?;
555    let vault = NoteAssets::new(assets)?;
556
557    Ok(Note::new(vault, metadata, recipient))
558}