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, NoteRelevance, NoteScript, NoteTag, NoteType,
24 },
25 rpc::{Endpoint, TonicRpcClient},
26 store::InputNoteRecord,
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 .with_rpc(rpc_api.clone())
52 .with_filesystem_keystore("./keystore")
53 .with_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 anchor_block = client.get_latest_epoch_block().await.unwrap();
204 let builder = AccountBuilder::new(init_seed)
205 .anchor((&anchor_block).try_into().unwrap())
206 .account_type(AccountType::RegularAccountUpdatableCode)
207 .storage_mode(AccountStorageMode::Public)
208 .with_component(RpoFalcon512::new(key_pair.public_key().clone()))
209 .with_component(BasicWallet);
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 anchor_block = client.get_latest_epoch_block().await.unwrap();
237 let symbol = TokenSymbol::new("MID").unwrap();
238 let decimals = 8;
239 let max_supply = Felt::new(1_000_000);
240 let builder = AccountBuilder::new(init_seed)
241 .anchor((&anchor_block).try_into().unwrap())
242 .account_type(AccountType::FungibleFaucet)
243 .storage_mode(AccountStorageMode::Public)
244 .with_component(RpoFalcon512::new(key_pair.public_key()))
245 .with_component(BasicFungibleFaucet::new(symbol, decimals, max_supply).unwrap());
246 let (account, seed) = builder.build().unwrap();
247 client.add_account(&account, Some(seed), false).await?;
248 keystore
249 .add_key(&AuthSecretKey::RpoFalcon512(key_pair))
250 .unwrap();
251 Ok(account)
252}
253
254pub async fn setup_accounts_and_faucets(
271 client: &mut Client,
272 keystore: FilesystemKeyStore<StdRng>,
273 num_accounts: usize,
274 num_faucets: usize,
275 balances: Vec<Vec<u64>>,
276) -> Result<(Vec<Account>, Vec<Account>), ClientError> {
277 let mut accounts = Vec::with_capacity(num_accounts);
278 for i in 0..num_accounts {
279 let (account, _) = create_basic_account(client, keystore.clone()).await?;
280 println!("Created Account #{i} => ID: {:?}", account.id());
281 accounts.push(account);
282 }
283
284 let mut faucets = Vec::with_capacity(num_faucets);
285 for j in 0..num_faucets {
286 let faucet = create_basic_faucet(client, keystore.clone()).await?;
287 println!("Created Faucet #{j} => ID: {:?}", faucet.id());
288 faucets.push(faucet);
289 }
290
291 client.sync_state().await?;
292
293 for (acct_index, account) in accounts.iter().enumerate() {
294 for (faucet_index, faucet) in faucets.iter().enumerate() {
295 let amount_to_mint = balances[acct_index][faucet_index];
296 if amount_to_mint == 0 {
297 continue;
298 }
299
300 println!(
301 "Minting {amount_to_mint} tokens from Faucet #{faucet_index} to Account #{acct_index}"
302 );
303
304 let fungible_asset = FungibleAsset::new(faucet.id(), amount_to_mint).unwrap();
305 let tx_req = TransactionRequestBuilder::new()
306 .build_mint_fungible_asset(
307 fungible_asset,
308 account.id(),
309 NoteType::Public,
310 client.rng(),
311 )
312 .unwrap();
313
314 let tx_exec = client.new_transaction(faucet.id(), tx_req).await?;
315 client.submit_transaction(tx_exec.clone()).await?;
316
317 let minted_note = if let OutputNote::Full(note) = tx_exec.created_notes().get_note(0) {
318 note.clone()
319 } else {
320 panic!("Expected OutputNote::Full, but got something else");
321 };
322
323 wait_for_notes(client, account, 1).await?;
324 client.sync_state().await?;
325
326 let consume_req = TransactionRequestBuilder::new()
327 .with_authenticated_input_notes([(minted_note.id(), None)])
328 .build()
329 .unwrap();
330
331 let tx_exec = client.new_transaction(account.id(), consume_req).await?;
332 client.submit_transaction(tx_exec).await?;
333 client.sync_state().await?;
334 }
335 }
336
337 Ok((accounts, faucets))
338}
339
340pub async fn mint_from_faucet_for_account(
358 client: &mut Client,
359 account: &Account,
360 faucet: &Account,
361 amount: u64,
362 tx_script: Option<TransactionScript>, ) -> Result<(), ClientError> {
364 if amount == 0 {
365 return Ok(());
366 }
367
368 let asset = FungibleAsset::new(faucet.id(), amount).unwrap();
369 let mint_req = TransactionRequestBuilder::new()
370 .build_mint_fungible_asset(asset, account.id(), NoteType::Public, client.rng())
371 .unwrap();
372
373 let mint_exec = client.new_transaction(faucet.id(), mint_req).await?;
374 client.submit_transaction(mint_exec.clone()).await?;
375
376 let minted_note = match mint_exec.created_notes().get_note(0) {
377 OutputNote::Full(note) => note.clone(),
378 _ => panic!("Expected full minted note"),
379 };
380
381 wait_for_notes(client, account, 1).await?;
382 client.sync_state().await?;
383
384 let consume_req = if let Some(script) = tx_script {
385 TransactionRequestBuilder::new()
386 .with_authenticated_input_notes([(minted_note.id(), None)])
387 .with_custom_script(script)
388 .build()?
389 } else {
390 TransactionRequestBuilder::new()
391 .with_authenticated_input_notes([(minted_note.id(), None)])
392 .build()?
393 };
394
395 let consume_exec = client.new_transaction(account.id(), consume_req).await?;
396 client.submit_transaction(consume_exec.clone()).await?;
397 client.sync_state().await?;
398
399 Ok(())
400}
401
402pub async fn create_public_note(
420 client: &mut Client,
421 note_code: String,
422 account_library: Option<Library>,
423 creator_account: Account,
424 assets: Option<NoteAssets>,
425 note_inputs: Option<NoteInputs>,
426) -> Result<Note, Error> {
427 let assembler = if let Some(library) = account_library {
428 TransactionKernel::assembler()
429 .with_library(&library)
430 .unwrap()
431 } else {
432 TransactionKernel::assembler()
433 }
434 .with_debug_mode(true);
435
436 let rng = client.rng();
437 let serial_num = rng.draw_word();
438 let note_script = NoteScript::compile(note_code, assembler.clone()).unwrap();
439
440 let note_inputs = note_inputs.unwrap_or_else(|| NoteInputs::new([].to_vec()).unwrap());
441 let assets = assets.unwrap_or_else(|| NoteAssets::new(vec![]).unwrap());
442
443 let recipient = NoteRecipient::new(serial_num, note_script, note_inputs.clone());
444 let tag = NoteTag::for_public_use_case(0, 0, NoteExecutionMode::Local).unwrap();
445 let metadata = NoteMetadata::new(
446 creator_account.id(),
447 NoteType::Public,
448 tag,
449 NoteExecutionHint::always(),
450 Felt::new(0),
451 )
452 .unwrap();
453
454 let note = Note::new(assets, metadata, recipient);
455
456 let note_req = TransactionRequestBuilder::new()
457 .with_own_output_notes(vec![OutputNote::Full(note.clone())])
458 .build()
459 .unwrap();
460 let tx_result = client
461 .new_transaction(creator_account.id(), note_req)
462 .await
463 .unwrap();
464
465 let _ = client.submit_transaction(tx_result).await;
466 client.sync_state().await.unwrap();
467
468 Ok(note)
469}
470
471pub async fn wait_for_note(
485 client: &mut Client,
486 account_id: &Account,
487 expected: &Note,
488) -> Result<(), ClientError> {
489 loop {
490 client.sync_state().await?;
491
492 let notes: Vec<(InputNoteRecord, Vec<(AccountId, NoteRelevance)>)> =
493 client.get_consumable_notes(Some(account_id.id())).await?;
494
495 let found = notes.iter().any(|(rec, _)| rec.id() == expected.id());
496
497 if found {
498 println!("✅ note found {}", expected.id().to_hex());
499 break;
500 }
501
502 println!("Note {} not found. Waiting...", expected.id().to_hex());
503 sleep(Duration::from_secs(3)).await;
504 }
505 Ok(())
506}
507
508pub async fn wait_for_notes(
522 client: &mut Client,
523 account_id: &miden_client::account::Account,
524 expected: usize,
525) -> Result<(), ClientError> {
526 loop {
527 client.sync_state().await?;
528 let notes = client.get_consumable_notes(Some(account_id.id())).await?;
529 if notes.len() >= expected {
530 break;
531 }
532 println!(
533 "{} consumable notes found for account {}. Waiting...",
534 notes.len(),
535 account_id.id().to_hex()
536 );
537 sleep(Duration::from_secs(3)).await;
538 }
539 Ok(())
540}
541
542pub fn create_tx_script(
553 script_code: String,
554 library: Option<Library>,
555) -> Result<TransactionScript, Error> {
556 let assembler = TransactionKernel::assembler();
557
558 let assembler = match library {
559 Some(lib) => assembler.with_library(lib),
560 None => Ok(assembler.with_debug_mode(true)),
561 }
562 .unwrap();
563 let tx_script = TransactionScript::compile(script_code, [], assembler).unwrap();
564
565 Ok(tx_script)
566}
567
568pub fn create_exact_p2id_note(
583 sender: AccountId,
584 target: AccountId,
585 assets: Vec<Asset>,
586 note_type: NoteType,
587 aux: Felt,
588 serial_num: Word,
589) -> Result<Note, NoteError> {
590 let recipient = utils::build_p2id_recipient(target, serial_num)?;
591 let tag = NoteTag::from_account_id(target, NoteExecutionMode::Local)?;
592
593 let metadata = NoteMetadata::new(sender, note_type, tag, NoteExecutionHint::always(), aux)?;
594 let vault = NoteAssets::new(assets)?;
595
596 Ok(Note::new(vault, metadata, recipient))
597}