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
33pub 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
61pub 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
96const 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
117fn to_elements(poly: Polynomial<Felt>) -> Vec<Felt> {
127 poly.coefficients.to_vec()
128}
129
130pub 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 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 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 let polynomials: Vec<u64> = polynomials.iter().map(|&e| e.into()).collect();
155 advice_stack.extend_from_slice(&polynomials);
156
157 advice_stack
158}
159
160pub 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
185pub 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 .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
219pub 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
252pub 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
338pub 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>, ) -> 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
401pub 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
469pub 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 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
503pub 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
529pub 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}