-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprepare_pqc_tx_load_accounts.rs
More file actions
1033 lines (975 loc) · 34.2 KB
/
prepare_pqc_tx_load_accounts.rs
File metadata and controls
1033 lines (975 loc) · 34.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// Prepare sender accounts for PQC (ML-DSA-44) load testing.
///
/// Identical to `prepare_tx_load_accounts` but every sender uses ML-DSA-44
/// for auth keys and transaction signatures — exercising the full post-quantum
/// attestation path end-to-end.
use std::fs;
use std::path::{Path, PathBuf};
use std::thread;
use std::time::{Duration, Instant};
use ace_engine::executor::TransactionOp;
use ace_mempool::pool::MempoolConfig;
use ace_model::account::AccountId;
use ace_runtime::crypto::attestation::{
auth_public_key_from_ml_dsa_44_seed, auth_public_key_from_seed,
make_credential_for_algorithm,
};
use ace_runtime::crypto::{idcom_xid, SignatureAlgorithm, TaggedPubkey};
use ace_runtime::types::attestation::Domain;
use reqwest::blocking::Client;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::json;
use sha2::{Digest, Sha256};
type DynError = Box<dyn std::error::Error + Send + Sync>;
const DEFAULT_CHAIN_ID: u32 = 656_565;
const DEFAULT_SENDER_COUNT: usize = 1_024;
const DEFAULT_FUND_AMOUNT: u64 = 10_000_000_000;
const DEFAULT_PREP_WAIT: Duration = Duration::from_secs(600);
const POLL_INTERVAL: Duration = Duration::from_millis(500);
const PROGRESS_LOG_INTERVAL: Duration = Duration::from_secs(5);
const DEFAULT_FUNDING_WINDOW_CAP: usize = 8;
#[derive(Debug, Clone)]
struct Config {
rpc_url: String,
chain_id: u32,
sender_count: usize,
fund_amount: u64,
prep_wait: Duration,
funding_window_cap: usize,
output: PathBuf,
algo: SignatureAlgorithm,
}
#[derive(Debug, Clone)]
struct SenderMaterial {
index: usize,
xid: [u8; 32],
idcom: [u8; 32],
auth_seed: [u8; 32],
/// ML-DSA-44 public key (1312 bytes).
auth_pubkey: Vec<u8>,
}
#[derive(Debug, Serialize, Deserialize)]
struct SenderRecord {
index: usize,
xid_hex: String,
idcom_hex: String,
auth_seed_hex: String,
auth_pubkey_hex: String,
/// Always "ml-dsa-44" in this variant.
algorithm: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct SenderCatalog {
chain_id: u32,
algorithm: String,
senders: Vec<SenderRecord>,
}
#[derive(Debug, Deserialize)]
struct RpcEnvelope<T> {
result: Option<T>,
error: Option<RpcErrorObject>,
}
#[derive(Debug, Deserialize)]
struct RpcErrorObject {
code: i64,
message: String,
}
#[derive(Debug, Deserialize)]
struct RpcAccount {
balance: u64,
nonce: u64,
}
#[derive(Debug, Deserialize)]
struct RpcNetworkStatus {
current_slot: u64,
latest_block_slot: u64,
}
#[derive(Debug, Deserialize)]
struct RpcTransactionReceipt {
block_slot: u64,
status: bool,
error: Option<String>,
}
struct RpcClient {
url: String,
http: Client,
next_id: u64,
}
impl RpcClient {
fn new(url: String) -> Result<Self, DynError> {
let http = Client::builder().timeout(Duration::from_secs(10)).build()?;
Ok(Self {
url,
http,
next_id: 1,
})
}
fn call<T: DeserializeOwned>(
&mut self,
method: &str,
params: serde_json::Value,
) -> Result<T, DynError> {
let id = self.next_id;
self.next_id += 1;
let response = self
.http
.post(&self.url)
.json(&json!({
"jsonrpc": "2.0",
"method": method,
"params": params,
"id": id,
}))
.send()?;
let status = response.status();
let body = response.text()?;
if !status.is_success() {
return Err(format!("rpc {method} failed with HTTP {status}: {body}").into());
}
let envelope: RpcEnvelope<T> = serde_json::from_str(&body)?;
match (envelope.result, envelope.error) {
(Some(result), None) => Ok(result),
(_, Some(error)) => Err(format!(
"rpc {method} failed with code {}: {}",
error.code, error.message
)
.into()),
_ => Err(format!("rpc {method} returned neither result nor error").into()),
}
}
fn get_slot(&mut self) -> Result<u64, DynError> {
self.call("ace_getSlot", json!([]))
}
fn get_network_status(&mut self) -> Result<RpcNetworkStatus, DynError> {
self.call("ace_getNetworkStatus", json!([]))
}
fn get_account(&mut self, idcom_hex: &str) -> Result<Option<RpcAccount>, DynError> {
let id = self.next_id;
self.next_id += 1;
let response = self
.http
.post(&self.url)
.json(&json!({
"jsonrpc": "2.0",
"method": "ace_getAccount",
"params": [idcom_hex],
"id": id,
}))
.send()?;
let status = response.status();
let body = response.text()?;
if !status.is_success() {
return Err(format!("rpc ace_getAccount failed with HTTP {status}: {body}").into());
}
let envelope: RpcEnvelope<RpcAccount> = serde_json::from_str(&body)?;
match (envelope.result, envelope.error) {
(Some(result), None) => Ok(Some(result)),
(_, Some(error))
if error.code == -32001
|| error.message.contains("account not found")
|| error.message.contains("Account not found") =>
{
Ok(None)
}
(_, Some(error)) => Err(format!(
"rpc ace_getAccount failed with code {}: {}",
error.code, error.message
)
.into()),
_ => Ok(None),
}
}
fn get_transaction_receipt(
&mut self,
tx_hash_hex: &str,
) -> Result<Option<RpcTransactionReceipt>, DynError> {
let id = self.next_id;
self.next_id += 1;
let response = self
.http
.post(&self.url)
.json(&json!({
"jsonrpc": "2.0",
"method": "ace_getTransactionReceipt",
"params": [tx_hash_hex],
"id": id,
}))
.send()?;
let status = response.status();
let body = response.text()?;
if !status.is_success() {
return Err(
format!("rpc ace_getTransactionReceipt failed with HTTP {status}: {body}").into(),
);
}
let envelope: RpcEnvelope<RpcTransactionReceipt> = serde_json::from_str(&body)?;
match (envelope.result, envelope.error) {
(Some(result), None) => Ok(Some(result)),
(None, None) => Ok(None),
(_, Some(error)) => Err(format!(
"rpc ace_getTransactionReceipt failed with code {}: {}",
error.code, error.message
)
.into()),
}
}
fn submit_signed_transfer(
&mut self,
sender_idcom_hex: &str,
payload_hex: &str,
credential_hex: &str,
pubkey_hex: &str,
chain_id: u32,
domain_slot: u32,
) -> Result<String, DynError> {
self.call(
"ace_submitSignedTransfer",
json!([
sender_idcom_hex,
payload_hex,
credential_hex,
pubkey_hex,
chain_id,
domain_slot,
null
]),
)
}
fn submit_signed_payload(
&mut self,
sender_idcom_hex: &str,
payload_hex: &str,
credential_hex: &str,
pubkey_hex: &str,
chain_id: u32,
domain_slot: u32,
) -> Result<String, DynError> {
self.call(
"ace_submitSignedPayload",
json!([
sender_idcom_hex,
payload_hex,
credential_hex,
pubkey_hex,
chain_id,
domain_slot,
null
]),
)
}
}
fn main() -> Result<(), DynError> {
let config = parse_args()?;
if let Some(parent) = config.output.parent() {
fs::create_dir_all(parent)?;
}
let algo = config.algo;
let algo_str = match algo {
SignatureAlgorithm::Ed25519 => "ed25519",
SignatureAlgorithm::MlDsa44 => "ml-dsa-44",
other => panic!("unsupported algorithm: {:?}", other),
};
let senders = build_senders(config.sender_count, algo);
let catalog = SenderCatalog {
chain_id: config.chain_id,
algorithm: algo_str.to_string(),
senders: senders
.iter()
.map(|sender| SenderRecord {
index: sender.index,
xid_hex: hex::encode(sender.xid),
idcom_hex: hex::encode(sender.idcom),
auth_seed_hex: hex::encode(sender.auth_seed),
auth_pubkey_hex: hex::encode(&sender.auth_pubkey),
algorithm: algo_str.to_string(),
})
.collect(),
};
println!(
"[pqc-tx-load] Preparing {} {:?} sender lanes via {}",
senders.len(),
algo,
config.rpc_url
);
let mut rpc = RpcClient::new(config.rpc_url.clone())?;
wait_for_network_ready(&mut rpc, config.prep_wait)?;
let faucet_idcom = faucet_idcom();
let faucet_seed = derive_devnet_auth_seed(&faucet_idcom);
// The faucet's genesis auth key is always ML-DSA-44 (derived by
// derive_devnet_auth_pubkey in genesis.rs). We use it for all funding
// operations regardless of the load-test algo.
let faucet_algo = SignatureAlgorithm::MlDsa44;
let faucet_pubkey = auth_public_key_from_ml_dsa_44_seed(&faucet_seed);
let faucet_pubkey_hex = hex::encode(&faucet_pubkey.bytes);
let faucet_idcom_hex = hex::encode(faucet_idcom);
if algo == SignatureAlgorithm::MlDsa44 {
// Phase 0: Install ML-DSA-44 auth key on the faucet via AddAuthKey (0x04).
// The faucet's genesis key is Ed25519; we add ML-DSA-44 as an additional key.
println!("[pqc-tx-load] Installing ML-DSA-44 auth key on faucet...");
let add_key_result = submit_with_retry_result(
&mut rpc,
"faucet AddAuthKey",
config.prep_wait,
|rpc, domain_slot| {
let faucet_account = rpc
.get_account(&faucet_idcom_hex)?
.ok_or("faucet account missing during AddAuthKey")?;
let add_key_payload = TransactionOp::AddAuthKey {
nonce: faucet_account.nonce,
auth_pubkey: TaggedPubkey::ml_dsa_44(faucet_pubkey.bytes.clone()),
}
.encode();
let signature = sign_payload(
&add_key_payload,
&faucet_idcom,
&faucet_seed,
SignatureAlgorithm::MlDsa44,
config.chain_id,
domain_slot,
);
rpc.submit_signed_payload(
&faucet_idcom_hex,
&hex::encode(&add_key_payload),
&signature,
&faucet_pubkey_hex,
config.chain_id,
domain_slot,
)
},
);
match add_key_result {
Ok(tx_hash) => {
println!("[pqc-tx-load] Waiting for faucet AddAuthKey to commit...");
let receipt = wait_for_transaction_receipt(
&mut rpc,
"faucet AddAuthKey",
&tx_hash,
config.prep_wait,
)?;
if receipt.status {
println!(
"[pqc-tx-load] Faucet ML-DSA-44 auth key installed in block {}",
receipt.block_slot
);
} else if receipt
.error
.as_deref()
.map(|error| {
error.contains("already exists")
|| error.contains("already has")
|| error.contains("already uses")
})
.unwrap_or(false)
{
println!("[pqc-tx-load] Faucet already has ML-DSA-44 auth key, skipping");
} else {
return Err(format!(
"faucet AddAuthKey failed on chain: {}",
receipt
.error
.unwrap_or_else(|| "unknown execution error".to_string())
)
.into());
}
}
Err(e) => {
if e.contains("already") || e.contains("duplicate") {
println!("[pqc-tx-load] Faucet already has ML-DSA-44 auth key, skipping");
} else {
return Err(e.into());
}
}
}
} else {
println!("[pqc-tx-load] Faucet uses genesis ML-DSA-44 auth key for funding");
}
let mut faucet_nonce = rpc
.get_account(&faucet_idcom_hex)?
.ok_or("devnet faucet account is missing on chain")?
.nonce;
let funding_window = usize::try_from(MempoolConfig::default().max_future_nonce_gap)
.unwrap_or(32)
.saturating_add(1)
.min(config.funding_window_cap.max(1));
let funding_chunks = senders.len().div_ceil(funding_window);
for (chunk_index, chunk) in senders.chunks(funding_window).enumerate() {
let chunk_start = chunk_index * funding_window;
let chunk_end = chunk_start + chunk.len();
println!(
"[pqc-tx-load] Funding senders {}-{} of {} (window {}/{})",
chunk_start + 1,
chunk_end,
senders.len(),
chunk_index + 1,
funding_chunks
);
for sender in chunk {
let sender_id = AccountId::from_bytes(sender.idcom);
let payload = TransactionOp::Transfer {
nonce: faucet_nonce,
to: sender_id,
amount: config.fund_amount,
}
.encode();
submit_with_retry(
&mut rpc,
"fund sender",
config.prep_wait,
|rpc, domain_slot| {
let signature = sign_payload(
&payload,
&faucet_idcom,
&faucet_seed,
faucet_algo,
config.chain_id,
domain_slot,
);
rpc.submit_signed_transfer(
&faucet_idcom_hex,
&hex::encode(&payload),
&signature,
&faucet_pubkey_hex,
config.chain_id,
domain_slot,
)
},
sender.index,
)?;
faucet_nonce = faucet_nonce.saturating_add(1);
}
wait_for(
"funding window commits",
&mut rpc,
config.prep_wait,
vec![faucet_idcom_hex.clone()],
|account| account.nonce >= faucet_nonce,
)?;
}
println!("[pqc-tx-load] Waiting for funded sender balances to settle...");
wait_for(
"funding commits",
&mut rpc,
config.prep_wait,
senders
.iter()
.map(|sender| hex::encode(sender.idcom))
.collect(),
|account| account.balance >= config.fund_amount,
)?;
// Phase 2: Add auth key for each sender.
// These load-test senders are auto-created by faucet funding; adding
// the auth key enables subsequent signed transfers.
println!("[pqc-tx-load] Installing {:?} auth keys for prepared senders...", algo);
for (index, sender) in senders.iter().enumerate() {
if index % 8 == 0 || index + 1 == senders.len() {
println!(
"[pqc-tx-load] Add auth key progress: {}/{}",
index + 1,
senders.len()
);
}
let sender_idcom_hex = hex::encode(sender.idcom);
submit_with_retry(
&mut rpc,
"set sender auth key",
config.prep_wait,
|rpc, domain_slot| {
let account = rpc
.get_account(&sender_idcom_hex)?
.ok_or("sender account disappeared during auth-key setup")?;
let new_key = pubkey_from_seed(&sender.auth_seed, algo);
let payload = TransactionOp::AddAuthKey {
nonce: account.nonce,
auth_pubkey: new_key,
}
.encode();
// Auto-created accounts have ZERO auth_pubkey, so
// has_provisioned_auth_key() == false. The RPC verification
// for AddAuthKey on un-provisioned accounts uses the NEW
// auth_pubkey from the payload itself as the verify key.
// Therefore we must sign with the NEW key (sender.auth_seed).
let new_pubkey = pubkey_from_seed(&sender.auth_seed, algo);
let new_pubkey_hex = hex::encode(&new_pubkey.bytes);
let signature = sign_payload(
&payload,
&sender.idcom,
&sender.auth_seed,
algo,
config.chain_id,
domain_slot,
);
rpc.submit_signed_payload(
&sender_idcom_hex,
&hex::encode(&payload),
&signature,
&new_pubkey_hex,
config.chain_id,
domain_slot,
)
},
index,
)?;
}
// Phase 3: Probe each sender with a signed self-transfer to confirm the
// auth key is committed and accepted.
println!("[pqc-tx-load] Probing prepared senders with {:?} signed self-transfers...", algo);
let mut probe_targets = Vec::with_capacity(senders.len());
for (index, sender) in senders.iter().enumerate() {
if index % 8 == 0 || index + 1 == senders.len() {
println!(
"[pqc-tx-load] Probe progress: {}/{}",
index + 1,
senders.len()
);
}
let sender_idcom_hex = hex::encode(sender.idcom);
let sender_pubkey_hex = hex::encode(&sender.auth_pubkey);
let mut last_probe_retry_log = Instant::now()
.checked_sub(PROGRESS_LOG_INTERVAL)
.unwrap_or_else(Instant::now);
loop {
let account = rpc
.get_account(&sender_idcom_hex)?
.ok_or("sender account disappeared during probe")?;
let payload = TransactionOp::Transfer {
nonce: account.nonce,
to: AccountId::from_bytes(sender.idcom),
amount: 0,
}
.encode();
let result = submit_with_retry_result(
&mut rpc,
"probe sender auth",
config.prep_wait,
|rpc, domain_slot| {
let signature = sign_payload(
&payload,
&sender.idcom,
&sender.auth_seed,
algo,
config.chain_id,
domain_slot,
);
rpc.submit_signed_transfer(
&sender_idcom_hex,
&hex::encode(&payload),
&signature,
&sender_pubkey_hex,
config.chain_id,
domain_slot,
)
},
);
match result {
Ok(_) => {
probe_targets.push(account.nonce.saturating_add(1));
break;
}
Err(error)
if error.contains("sender already has a pending transaction")
|| error.contains("stale nonce")
|| error.contains("duplicate transaction") =>
{
probe_targets.push(account.nonce.saturating_add(1));
break;
}
Err(error)
if error.contains("Invalid attestation signature")
|| error.contains("unknown sender")
|| error.contains("account not found") =>
{
if last_probe_retry_log.elapsed() >= PROGRESS_LOG_INTERVAL {
println!(
"[pqc-tx-load] Waiting for sender auth key to commit before probe: sender={} error={}",
sender_idcom_hex,
error
);
last_probe_retry_log = Instant::now();
}
thread::sleep(POLL_INTERVAL);
}
Err(error) => return Err(error.into()),
}
}
}
println!("[pqc-tx-load] Waiting for probe commits...");
let deadline = Instant::now() + config.prep_wait;
let mut last_progress_log = Instant::now()
.checked_sub(PROGRESS_LOG_INTERVAL)
.unwrap_or_else(Instant::now);
while Instant::now() < deadline {
let mut done = true;
let mut committed = 0usize;
let mut next_pending = None;
for (sender, target_nonce) in senders.iter().zip(probe_targets.iter()) {
let account = rpc
.get_account(&hex::encode(sender.idcom))?
.ok_or("sender account missing while waiting for probe commit")?;
if account.nonce < *target_nonce {
done = false;
next_pending = Some(format!(
"{} nonce={}/{}",
hex::encode(sender.idcom),
account.nonce,
target_nonce
));
break;
}
committed += 1;
}
if done {
write_catalog_atomically(&config.output, &catalog)?;
println!(
"[pqc-tx-load] Prepared {} ML-DSA-44 load senders at {}",
senders.len(),
config.output.display()
);
return Ok(());
}
if last_progress_log.elapsed() >= PROGRESS_LOG_INTERVAL {
println!(
"[pqc-tx-load] Waiting for probe commits: {}/{} committed{}",
committed,
senders.len(),
next_pending
.map(|detail| format!(" next={detail}"))
.unwrap_or_default()
);
last_progress_log = Instant::now();
}
thread::sleep(POLL_INTERVAL);
}
Err(format!(
"timed out waiting for probe commits after {:?}",
config.prep_wait
)
.into())
}
fn write_catalog_atomically(path: &Path, catalog: &SenderCatalog) -> Result<(), DynError> {
let tmp_path = path.with_extension("tmp");
fs::write(&tmp_path, serde_json::to_vec_pretty(catalog)?)?;
fs::rename(&tmp_path, path)?;
Ok(())
}
fn parse_args() -> Result<Config, DynError> {
let mut rpc_url = "http://127.0.0.1:18545".to_string();
let mut chain_id = DEFAULT_CHAIN_ID;
let mut sender_count = DEFAULT_SENDER_COUNT;
let mut fund_amount = DEFAULT_FUND_AMOUNT;
let mut prep_wait = DEFAULT_PREP_WAIT;
let mut funding_window_cap = DEFAULT_FUNDING_WINDOW_CAP;
let mut output = PathBuf::from("data_n_docs/devnet/generated/pqc-jmeter-senders.json");
let mut algo = SignatureAlgorithm::MlDsa44;
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--rpc-url" => rpc_url = args.next().ok_or("missing value for --rpc-url")?,
"--chain-id" => {
chain_id = args.next().ok_or("missing value for --chain-id")?.parse()?
}
"--senders" => {
sender_count = args.next().ok_or("missing value for --senders")?.parse()?
}
"--fund-amount" => {
fund_amount = args
.next()
.ok_or("missing value for --fund-amount")?
.parse()?
}
"--prep-wait-sec" => {
let seconds: u64 = args
.next()
.ok_or("missing value for --prep-wait-sec")?
.parse()?;
prep_wait = Duration::from_secs(seconds.max(1));
}
"--funding-window" => {
funding_window_cap = args
.next()
.ok_or("missing value for --funding-window")?
.parse::<usize>()?
.max(1);
}
"--output" => output = PathBuf::from(args.next().ok_or("missing value for --output")?),
"--algo" => {
let val = args.next().ok_or("missing value for --algo")?;
algo = match val.to_lowercase().as_str() {
"ed25519" => SignatureAlgorithm::Ed25519,
"ml-dsa-44" | "mldsa44" | "pqc" => SignatureAlgorithm::MlDsa44,
other => return Err(format!("unknown algo: {other} (use ed25519 or ml-dsa-44)").into()),
};
}
"--help" | "-h" => {
println!(
"Usage: cargo run -p ace-rpc --example prepare_pqc_tx_load_accounts --features devnet -- \\
[--rpc-url http://127.0.0.1:18545] [--chain-id 656565] [--senders 1024] \\
[--fund-amount 10000000000] [--prep-wait-sec 600] [--funding-window 8] \\
[--algo ml-dsa-44|ed25519] \\
[--output data_n_docs/devnet/generated/pqc-jmeter-senders.json]"
);
std::process::exit(0);
}
other => return Err(format!("unknown argument: {other}").into()),
}
}
Ok(Config {
rpc_url,
chain_id,
sender_count,
fund_amount,
prep_wait,
funding_window_cap,
output,
algo,
})
}
fn pubkey_from_seed(seed: &[u8; 32], algo: SignatureAlgorithm) -> TaggedPubkey {
match algo {
SignatureAlgorithm::Ed25519 => auth_public_key_from_seed(seed),
SignatureAlgorithm::MlDsa44 => auth_public_key_from_ml_dsa_44_seed(seed),
other => panic!("unsupported algorithm for load testing: {:?}", other),
}
}
fn build_senders(count: usize, algo: SignatureAlgorithm) -> Vec<SenderMaterial> {
(0..count)
.map(|index| {
let xid = derive_sender_xid(index as u64);
let idcom = idcom_xid(&xid);
let auth_seed = derive_sender_seed(index as u64);
let auth_pubkey = pubkey_from_seed(&auth_seed, algo);
SenderMaterial {
index,
xid,
idcom,
auth_seed,
auth_pubkey: auth_pubkey.bytes,
}
})
.collect()
}
fn derive_sender_xid(index: u64) -> [u8; 32] {
// Use a different label so PQC senders have distinct identities from Ed25519 senders.
derive_labeled_hash(b"ace-pqc-load-xid", index)
}
fn derive_sender_seed(index: u64) -> [u8; 32] {
derive_labeled_hash(b"ace-pqc-load-auth", index)
}
fn derive_labeled_hash(label: &[u8], index: u64) -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.update(label);
hasher.update(index.to_le_bytes());
let mut out = [0u8; 32];
out.copy_from_slice(&hasher.finalize());
out
}
fn faucet_idcom() -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.update(b"ace-devnet-faucet");
let mut out = [0u8; 32];
out.copy_from_slice(&hasher.finalize());
out
}
fn derive_devnet_auth_seed(idcom: &[u8; 32]) -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.update(b"ACE-DEVNET-AUTH-SIGN");
hasher.update(idcom);
let mut out = [0u8; 32];
out.copy_from_slice(&hasher.finalize());
out
}
fn sign_payload(
payload: &[u8],
signer_idcom: &[u8; 32],
signer_seed: &[u8; 32],
algorithm: SignatureAlgorithm,
chain_id: u32,
domain_slot: u32,
) -> String {
let mut hasher = Sha256::new();
hasher.update(payload);
let mut obj_hash = [0u8; 32];
obj_hash.copy_from_slice(&hasher.finalize());
let credential = make_credential_for_algorithm(
signer_seed,
&obj_hash,
signer_idcom,
&Domain::new(chain_id, domain_slot),
&[0u8; 16],
algorithm,
);
hex::encode(credential.bytes)
}
fn submit_with_retry<F>(
rpc: &mut RpcClient,
label: &str,
prep_wait: Duration,
submit: F,
index: usize,
) -> Result<String, DynError>
where
F: Fn(&mut RpcClient, u32) -> Result<String, DynError>,
{
submit_with_retry_result(rpc, label, prep_wait, submit)
.map_err(|error| format!("{label} #{index} failed permanently: {error}").into())
}
fn submit_with_retry_result<F>(
rpc: &mut RpcClient,
label: &str,
prep_wait: Duration,
submit: F,
) -> Result<String, String>
where
F: Fn(&mut RpcClient, u32) -> Result<String, DynError>,
{
let deadline = Instant::now() + prep_wait;
let mut delay = Duration::from_millis(100);
let mut last_progress_log = Instant::now()
.checked_sub(PROGRESS_LOG_INTERVAL)
.unwrap_or_else(Instant::now);
while Instant::now() < deadline {
let slot = match rpc.get_slot() {
Ok(slot) => slot as u32,
Err(error) => return Err(format!("{label}: failed to query slot: {error}")),
};
match submit(rpc, slot) {
Ok(result) => return Ok(result),
Err(error) => {
let message = error.to_string();
if is_retryable(&message) {
if last_progress_log.elapsed() >= PROGRESS_LOG_INTERVAL {
println!(
"[pqc-tx-load] Retrying {label}: {message} (backoff={}ms)",
delay.as_millis()
);
last_progress_log = Instant::now();
}
thread::sleep(delay);
delay = (delay * 2).min(Duration::from_secs(2));
continue;
}
return Err(format!("{label}: {message}"));
}
}
}
Err(format!("{label}: timed out after {:?}", prep_wait))
}
fn is_retryable(message: &str) -> bool {
message.contains("overloaded:")
|| message.contains("mempool is full")
|| message.contains("future nonce too far ahead")
|| message.contains("future queue full")
}
fn wait_for_network_ready(rpc: &mut RpcClient, prep_wait: Duration) -> Result<(), DynError> {
println!("[pqc-tx-load] Waiting for devnet to start producing blocks...");
let deadline = Instant::now() + prep_wait;
let mut last_progress_log = Instant::now()
.checked_sub(PROGRESS_LOG_INTERVAL)
.unwrap_or_else(Instant::now);
while Instant::now() < deadline {
let status = rpc.get_network_status()?;
if status.latest_block_slot >= 1 {
println!(
"[pqc-tx-load] Devnet ready at slot {} (latest block {})",
status.current_slot, status.latest_block_slot
);
return Ok(());
}
if last_progress_log.elapsed() >= PROGRESS_LOG_INTERVAL {
println!(
"[pqc-tx-load] Waiting for first non-genesis block: current_slot={} latest_block_slot={}",
status.current_slot, status.latest_block_slot
);
last_progress_log = Instant::now();
}
thread::sleep(POLL_INTERVAL);
}
Err(format!(
"devnet did not start producing blocks within {:?}",
prep_wait
)
.into())
}
fn wait_for_transaction_receipt(
rpc: &mut RpcClient,
label: &str,
tx_hash: &str,
prep_wait: Duration,
) -> Result<RpcTransactionReceipt, DynError> {
let deadline = Instant::now() + prep_wait;
let mut last_progress_log = Instant::now()
.checked_sub(PROGRESS_LOG_INTERVAL)
.unwrap_or_else(Instant::now);
while Instant::now() < deadline {
if let Some(receipt) = rpc.get_transaction_receipt(tx_hash)? {
return Ok(receipt);
}
if last_progress_log.elapsed() >= PROGRESS_LOG_INTERVAL {
let status = rpc.get_network_status()?;
println!(
"[pqc-tx-load] Waiting for {label} receipt: current_slot={} latest_block_slot={} tx_hash={}",
status.current_slot,
status.latest_block_slot,
tx_hash
);
last_progress_log = Instant::now();
}
thread::sleep(POLL_INTERVAL);
}
Err(format!(
"{label}: timed out waiting for receipt after {:?}",
prep_wait
)
.into())
}
fn wait_for<F>(
label: &str,
rpc: &mut RpcClient,
prep_wait: Duration,
ids: Vec<String>,
predicate: F,
) -> Result<(), DynError>
where
F: Fn(&RpcAccount) -> bool,
{
let deadline = Instant::now() + prep_wait;
let mut last_progress_log = Instant::now()
.checked_sub(PROGRESS_LOG_INTERVAL)
.unwrap_or_else(Instant::now);
while Instant::now() < deadline {
let mut done = true;
let mut satisfied = 0usize;
let mut next_pending = None;
for id in &ids {