-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathe2e_test_env.rs
More file actions
3440 lines (3284 loc) · 134 KB
/
e2e_test_env.rs
File metadata and controls
3440 lines (3284 loc) · 134 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
// Flow:
// init indexer
// init first keypair
// init crank
// vec of public Merkle tree NF queue pairs
// vec of public address Mt and queue pairs
// for i in rounds
// randomly add new keypair
// for every keypair randomly select whether it does an action
// Architecture:
// - bundle trees, indexer etc in a E2ETestEnv struct
// - methods:
// // bundles all general actions
// - activate general actions
// // bundles all keypair actions
// - activate keypair actions
// // calls general and keypair actions
// - execute round
// // every action takes a probability as input
// // if you want to execute the action on purpose pass 1
// - method for every action
// - add action activation config with default configs
// - all enabled
// - only spl, only sol, etc
// Forester struct
// - payer keypair, authority keypair
// -methods
// - empty nullifier queue
// - empty address queue
// - rollover Merkle tree
// - rollover address Merkle tree
// keypair actions:
// safeguard every action in case of no balance
// 1. compress sol
// 2. decompress sol
// 2. transfer sol
// 3. compress spl
// 4. decompress spl
// 5. mint spl
// 6. transfer spl
// general actions:
// add keypair
// create new state Mt
// create new address Mt
// extension:
// keypair actions:
// - create pda
// - escrow tokens
// - delegate, revoke, delegated transaction
// general actions:
// - create new program owned state Merkle tree and queue
// - create new program owned address Merkle tree and queue
// minimal start
// struct with env and test-indexer
// only spl transactions
// second pr
// refactor sol tests to functions that can be reused
use std::collections::HashMap;
use account_compression::{
utils::constants::{STATE_MERKLE_TREE_CANOPY_DEPTH, STATE_MERKLE_TREE_HEIGHT},
AddressMerkleTreeConfig, AddressQueueConfig, NullifierQueueConfig, StateMerkleTreeConfig,
SAFETY_MARGIN,
};
use anchor_lang::{prelude::AccountMeta, AnchorSerialize, Discriminator};
use create_address_test_program::create_invoke_cpi_instruction;
use forester_utils::{
account_zero_copy::AccountZeroCopy,
address_merkle_tree_config::{address_tree_ready_for_rollover, state_tree_ready_for_rollover},
forester_epoch::{Epoch, Forester, TreeAccounts},
utils::airdrop_lamports,
};
use light_batched_merkle_tree::{
batch::BatchState,
constants::{DEFAULT_BATCH_ADDRESS_TREE_HEIGHT, TEST_DEFAULT_BATCH_SIZE},
merkle_tree::{BatchedMerkleTreeAccount, InstructionDataBatchNullifyInputs},
queue::BatchedQueueAccount,
};
use light_client::{
fee::{FeeConfig, TransactionParams},
indexer::{
AddressMerkleTreeAccounts, AddressWithTree, Indexer, QueueElementsV2Options,
StateMerkleTreeAccounts,
},
rpc::{errors::RpcError, merkle_tree::MerkleTreeExt, Rpc},
};
// TODO: implement traits for context object and indexer that we can implement with an rpc as well
// context trait: send_transaction -> return transaction result, get_account_info -> return account info
// indexer trait: get_compressed_accounts_by_owner -> return compressed accounts,
// refactor all tests to work with that so that we can run all tests with a test validator and concurrency
use light_compressed_account::{
address::{
derive_address,
// pack_new_address_params, pack_read_only_accounts,
// pack_read_only_address_params,
},
compressed_account::{
// pack_compressed_accounts, pack_output_compressed_accounts,
CompressedAccount,
CompressedAccountData,
CompressedAccountWithMerkleContext,
ReadOnlyCompressedAccount,
},
instruction_data::{
compressed_proof::CompressedProof,
cpi_context::CompressedCpiContext,
data::{NewAddressParams, ReadOnlyAddress},
invoke_cpi::InstructionDataInvokeCpi,
with_readonly::InstructionDataInvokeCpiWithReadOnly,
},
TreeType,
};
use light_compressed_token::process_transfer::transfer_sdk::to_account_metas;
use light_hasher::{bigint::bigint_to_be_bytes_array, Poseidon};
use light_indexed_merkle_tree::{
array::IndexedArray, reference::IndexedMerkleTree, HIGHEST_ADDRESS_PLUS_ONE,
};
use light_program_test::{
accounts::{
state_tree::create_state_merkle_tree_and_queue_account, test_accounts::TestAccounts,
},
indexer::{
address_tree::AddressMerkleTreeBundle, state_tree::StateMerkleTreeBundle, TestIndexer,
TestIndexerExtensions,
},
program_test::{LightProgramTest, TestRpc},
utils::register_test_forester::register_test_forester,
ForesterConfig,
};
use light_prover_client::{
constants::{PROVE_PATH, SERVER_ADDRESS},
proof::{compress_proof, deserialize_gnark_proof_json, proof_from_json_struct},
proof_types::batch_address_append::{get_batch_address_append_circuit_inputs, to_json},
};
use light_registry::{
account_compression_cpi::sdk::create_batch_update_address_tree_instruction,
protocol_config::state::{ProtocolConfig, ProtocolConfigPda},
sdk::create_finalize_registration_instruction,
utils::get_protocol_config_pda_address,
};
use light_sdk::{
address::NewAddressParamsAssignedPacked,
constants::{ADDRESS_MERKLE_TREE_ROOTS, CPI_AUTHORITY_PDA_SEED, STATE_MERKLE_TREE_ROOTS},
};
use light_sparse_merkle_tree::{
changelog::ChangelogEntry, indexed_changelog::IndexedChangelogEntry, SparseMerkleTree,
};
use light_token::compat::{AccountState, TokenDataWithMerkleContext};
use log::info;
use num_bigint::{BigUint, RandBigInt};
use num_traits::Num;
use rand::{
distributions::uniform::{SampleRange, SampleUniform},
prelude::SliceRandom,
rngs::{StdRng, ThreadRng},
Rng, RngCore, SeedableRng,
};
use reqwest::Client;
use solana_sdk::{
pubkey::Pubkey,
signature::{Keypair, Signature},
signer::{SeedDerivable, Signer},
};
use spl_token::solana_program::native_token::LAMPORTS_PER_SOL;
use crate::{
address_tree_rollover::{
assert_rolled_over_address_merkle_tree_and_queue,
perform_address_merkle_tree_roll_over_forester,
perform_state_merkle_tree_roll_over_forester,
},
assert_epoch::{
assert_finalized_epoch_registration, assert_report_work, fetch_epoch_and_forester_pdas,
},
create_address_merkle_tree_and_queue_account_with_assert,
pack::*,
spl::{
approve_test, burn_test, compress_test, compressed_transfer_test, create_mint_helper,
create_token_account, decompress_test, freeze_test, mint_tokens_helper, revoke_test,
thaw_test,
},
state_tree_rollover::assert_rolled_over_pair,
system_program::{
compress_sol_test, create_addresses_test, decompress_sol_test, transfer_compressed_sol_test,
},
test_batch_forester::{perform_batch_append, perform_batch_nullify},
test_forester::{empty_address_queue_test, nullify_compressed_accounts},
};
pub struct User {
pub keypair: Keypair,
// Vector of (mint, token account)
pub token_accounts: Vec<(Pubkey, Pubkey)>,
}
#[derive(Debug, Default)]
pub struct Stats {
pub spl_transfers: u64,
pub mints: u64,
pub spl_decompress: u64,
pub spl_compress: u64,
pub sol_transfers: u64,
pub sol_decompress: u64,
pub sol_compress: u64,
pub create_address: u64,
pub create_pda: u64,
pub create_state_mt: u64,
pub create_address_mt: u64,
pub rolledover_state_trees: u64,
pub rolledover_address_trees: u64,
pub spl_approved: u64,
pub spl_revoked: u64,
pub spl_burned: u64,
pub spl_frozen: u64,
pub spl_thawed: u64,
pub registered_foresters: u64,
pub created_foresters: u64,
pub work_reported: u64,
pub finalized_registrations: u64,
}
impl Stats {
pub fn print(&self, users: u64) {
println!("Stats:");
println!("Users {}", users);
println!("Mints {}", self.mints);
println!("Spl transfers {}", self.spl_transfers);
println!("Spl decompress {}", self.spl_decompress);
println!("Spl compress {}", self.spl_compress);
println!("Sol transfers {}", self.sol_transfers);
println!("Sol decompress {}", self.sol_decompress);
println!("Sol compress {}", self.sol_compress);
println!("Create address {}", self.create_address);
println!("Create pda {}", self.create_pda);
println!("Create state mt {}", self.create_state_mt);
println!("Create address mt {}", self.create_address_mt);
println!("Rolled over state trees {}", self.rolledover_state_trees);
println!(
"Rolled over address trees {}",
self.rolledover_address_trees
);
println!("Spl approved {}", self.spl_approved);
println!("Spl revoked {}", self.spl_revoked);
println!("Spl burned {}", self.spl_burned);
println!("Spl frozen {}", self.spl_frozen);
println!("Spl thawed {}", self.spl_thawed);
println!("Registered foresters {}", self.registered_foresters);
println!("Created foresters {}", self.created_foresters);
println!("Work reported {}", self.work_reported);
println!("Finalized registrations {}", self.finalized_registrations);
}
}
pub async fn init_program_test_env<R: Rpc + MerkleTreeExt + Indexer + TestRpc>(
rpc: R,
test_accounts: &TestAccounts,
batch_size: usize,
) -> E2ETestEnv<R, TestIndexer> {
let indexer: TestIndexer = TestIndexer::init_from_acounts(
&test_accounts.protocol.forester.insecure_clone(),
test_accounts,
batch_size,
)
.await;
E2ETestEnv::<R, TestIndexer>::new(
rpc,
indexer,
test_accounts,
KeypairActionConfig::all_default(),
GeneralActionConfig::default(),
10,
None,
)
.await
}
pub async fn init_program_test_env_forester(
rpc: LightProgramTest,
test_accounts: &TestAccounts,
batch_size: usize,
) -> E2ETestEnv<LightProgramTest, TestIndexer> {
let indexer = TestIndexer::init_from_acounts(
&test_accounts.protocol.forester.insecure_clone(),
test_accounts,
batch_size,
)
.await;
E2ETestEnv::<LightProgramTest, TestIndexer>::new(
rpc,
indexer,
test_accounts,
KeypairActionConfig::all_default(),
GeneralActionConfig::default(),
10,
None,
)
.await
}
#[derive(Debug, PartialEq)]
pub struct TestForester {
keypair: Keypair,
forester: Forester,
is_registered: Option<u64>,
}
pub struct E2ETestEnv<R: Rpc + TestRpc + Indexer, I: Indexer + Clone + TestIndexerExtensions> {
pub payer: Keypair,
pub governance_keypair: Keypair,
pub indexer: I,
pub users: Vec<User>,
pub mints: Vec<Pubkey>,
pub foresters: Vec<TestForester>,
pub rpc: R,
pub keypair_action_config: KeypairActionConfig,
pub general_action_config: GeneralActionConfig,
pub round: u64,
pub rounds: u64,
pub rng: StdRng,
pub stats: Stats,
pub epoch: u64,
pub slot: u64,
/// Forester struct is reused but not used for foresting here
/// Epoch config keeps track of the ongong epochs.
pub epoch_config: Forester,
pub protocol_config: ProtocolConfig,
pub registration_epoch: u64,
}
impl<R: Rpc + TestRpc + Indexer, I: Indexer + Clone + TestIndexerExtensions> E2ETestEnv<R, I>
where
R: Rpc,
I: Indexer,
{
pub async fn new(
mut rpc: R,
mut indexer: I,
test_accounts: &TestAccounts,
keypair_action_config: KeypairActionConfig,
general_action_config: GeneralActionConfig,
rounds: u64,
seed: Option<u64>,
) -> Self {
let payer = rpc.get_payer().insecure_clone();
airdrop_lamports(&mut rpc, &payer.pubkey(), 1_000_000_000_000)
.await
.unwrap();
airdrop_lamports(
&mut rpc,
&test_accounts.protocol.forester.pubkey(),
1_000_000_000_000,
)
.await
.unwrap();
let mut thread_rng = ThreadRng::default();
let random_seed = thread_rng.next_u64();
let seed: u64 = seed.unwrap_or(random_seed);
// Keep this print so that in case the test fails
// we can use the seed to reproduce the error.
println!("\n\ne2e test seed {}\n\n", seed);
let mut rng = StdRng::seed_from_u64(seed);
let user = Self::create_user(&mut rng, &mut rpc).await;
let mint = create_mint_helper(&mut rpc, &payer).await;
mint_tokens_helper(
&mut rpc,
&mut indexer,
&test_accounts.v1_state_trees[0].merkle_tree,
&payer,
&mint,
vec![100_000_000; 1],
vec![user.keypair.pubkey()],
)
.await;
let protocol_config_pda_address = get_protocol_config_pda_address().0;
println!("here");
let protocol_config = rpc
.get_anchor_account::<ProtocolConfigPda>(&protocol_config_pda_address)
.await
.unwrap()
.unwrap()
.config;
// TODO: add clear test env enum
// register foresters is only compatible with ProgramTest environment
// Default forester setup - tests that need forester functionality should call
// setup_forester_and_advance_to_epoch explicitly and manage their own forester state
let (foresters, epoch_config) = (Vec::<TestForester>::new(), Forester::default());
Self {
payer,
indexer,
users: vec![user],
rpc,
keypair_action_config,
general_action_config,
round: 0,
rounds,
rng,
mints: vec![],
stats: Stats::default(),
foresters,
registration_epoch: 0,
epoch: 0,
slot: 0,
epoch_config,
protocol_config,
governance_keypair: test_accounts.protocol.governance_authority.insecure_clone(),
}
}
/// Creates a new user with a random keypair and 100 sol
pub async fn create_user(rng: &mut StdRng, rpc: &mut R) -> User {
let keypair: Keypair = Keypair::from_seed(&[rng.gen_range(0..255); 32]).unwrap();
rpc.airdrop_lamports(&keypair.pubkey(), LAMPORTS_PER_SOL * 5000)
.await
.unwrap();
User {
keypair,
token_accounts: vec![],
}
}
pub async fn get_balance(&self, pubkey: &Pubkey) -> u64 {
self.rpc.get_balance(pubkey).await.unwrap()
}
pub async fn execute_rounds(&mut self) {
for _ in 0..=self.rounds {
self.execute_round().await;
}
}
pub async fn execute_round(&mut self) {
println!("\n------------------------------------------------------\n");
println!("Round: {}", self.round);
self.stats.print(self.users.len() as u64);
// TODO: check at the beginning of the round that the Merkle trees are in sync
let len = self.users.len();
for i in 0..len {
self.activate_keypair_actions(&self.users[i].keypair.pubkey())
.await;
}
self.activate_general_actions().await;
self.round += 1;
}
/// 1. Add a new keypair
/// 2. Create a new state Merkle tree
pub async fn activate_general_actions(&mut self) {
// If we want to test rollovers we set the threshold to 0 for all newly created trees
let rollover_threshold = if self.general_action_config.rollover.is_some() {
Some(0)
} else {
None
};
if self
.rng
.gen_bool(self.general_action_config.add_keypair.unwrap_or_default())
{
let user = Self::create_user(&mut self.rng, &mut self.rpc).await;
self.users.push(user);
}
if self.rng.gen_bool(
self.general_action_config
.create_state_mt
.unwrap_or_default(),
) {
println!("\n------------------------------------------------------\n");
println!("Creating new state Merkle tree");
self.create_state_tree(rollover_threshold).await;
self.stats.create_state_mt += 1;
}
if self.rng.gen_bool(
self.general_action_config
.create_address_mt
.unwrap_or_default(),
) {
println!("\n------------------------------------------------------\n");
println!("Creating new address Merkle tree");
self.create_address_tree(rollover_threshold).await;
self.stats.create_address_mt += 1;
}
if self.rng.gen_bool(
self.general_action_config
.nullify_compressed_accounts
.unwrap_or_default(),
) {
for state_tree_bundle in self.indexer.get_state_merkle_trees_mut().iter_mut() {
println!("state tree bundle version {}", state_tree_bundle.tree_type);
match state_tree_bundle.tree_type {
TreeType::StateV1 => {
println!("\n --------------------------------------------------\n\t\t NULLIFYING LEAVES v1\n --------------------------------------------------");
// find forester which is eligible this slot for this tree
if let Some(payer) = Self::get_eligible_forester_for_queue(
&state_tree_bundle.accounts.nullifier_queue,
&self.foresters,
self.slot,
) {
// TODO: add newly addeded trees to foresters
nullify_compressed_accounts(
&mut self.rpc,
&payer,
state_tree_bundle,
self.epoch,
false,
)
.await
.unwrap();
} else {
println!("No forester found for nullifier queue");
};
}
TreeType::StateV2 => {
let merkle_tree_pubkey = state_tree_bundle.accounts.merkle_tree;
let queue_pubkey = state_tree_bundle.accounts.nullifier_queue;
// Check input queue
if let Some(payer) = Self::get_eligible_forester_for_queue(
&state_tree_bundle.accounts.merkle_tree,
&self.foresters,
self.slot,
) {
let mut merkle_tree_account_data = self
.rpc
.get_account(merkle_tree_pubkey)
.await
.unwrap()
.unwrap()
.data;
let merkle_tree = BatchedMerkleTreeAccount::state_from_bytes(
merkle_tree_account_data.as_mut_slice(),
&merkle_tree_pubkey.into(),
)
.unwrap();
let pending_batch_index = merkle_tree.queue_batches.pending_batch_index;
let batch = merkle_tree
.queue_batches
.batches
.get(pending_batch_index as usize)
.unwrap();
let batch_state = batch.get_state();
println!(
"output batch_state {:?}, {}, batch index {}",
batch_state,
batch.get_num_inserted_zkp_batch()
+ batch.get_current_zkp_batch_index() * batch.zkp_batch_size,
pending_batch_index
);
println!("input batch_state {:?}", batch_state);
if batch_state == BatchState::Full {
println!("\n --------------------------------------------------\n\t\t NULLIFYING LEAVES batched (v2)\n --------------------------------------------------");
for _ in 0..TEST_DEFAULT_BATCH_SIZE {
perform_batch_nullify(
&mut self.rpc,
state_tree_bundle,
&payer,
self.epoch,
false,
None,
)
.await
.unwrap();
}
}
}
// Check output queue
if let Some(payer) = Self::get_eligible_forester_for_queue(
&state_tree_bundle.accounts.merkle_tree,
&self.foresters,
self.slot,
) {
println!("\n --------------------------------------------------\n\t\t Appending LEAVES batched (v2)\n --------------------------------------------------");
let mut queue_account_data = self
.rpc
.get_account(queue_pubkey)
.await
.unwrap()
.unwrap()
.data;
let output_queue = BatchedQueueAccount::output_from_bytes(
queue_account_data.as_mut_slice(),
)
.unwrap();
let pending_batch_index =
output_queue.batch_metadata.pending_batch_index;
let batch = output_queue
.batch_metadata
.batches
.get(pending_batch_index as usize)
.unwrap();
let batch_state = batch.get_state();
println!(
"output batch_state {:?}, {}, batch index {}",
batch_state,
batch.get_num_inserted_zkp_batch()
+ batch.get_current_zkp_batch_index() * batch.zkp_batch_size,
pending_batch_index
);
if batch_state == BatchState::Full {
for _ in 0..output_queue.batch_metadata.get_num_zkp_batches() {
perform_batch_append(
&mut self.rpc,
state_tree_bundle,
&payer,
self.epoch,
false,
None,
)
.await
.unwrap();
}
}
}
}
_ => {
println!("Version skipped {}", state_tree_bundle.tree_type);
}
}
}
}
if self.rng.gen_bool(
self.general_action_config
.empty_address_queue
.unwrap_or_default(),
) {
for address_merkle_tree_bundle in self
.indexer
.get_address_merkle_trees_mut()
.iter_mut()
.filter(|x| x.accounts.merkle_tree != x.accounts.queue)
.collect::<Vec<_>>()
.iter_mut()
{
// find forester which is eligible this slot for this tree
if let Some(payer) = Self::get_eligible_forester_for_queue(
&address_merkle_tree_bundle.accounts.queue,
&self.foresters,
self.slot,
) {
println!("\n --------------------------------------------------\n\t\t Empty v1 Address Queue\n --------------------------------------------------");
println!("epoch {}", self.epoch);
println!("forester {}", payer.pubkey());
if address_merkle_tree_bundle.accounts.queue
!= address_merkle_tree_bundle.accounts.merkle_tree
{
// TODO: add newly addeded trees to foresters
empty_address_queue_test(
&payer,
&mut self.rpc,
address_merkle_tree_bundle,
false,
self.epoch,
false,
)
.await
.unwrap();
}
}
}
let pubkeys = self
.indexer
.get_address_merkle_trees_mut()
.iter_mut()
.filter(|x| x.accounts.merkle_tree == x.accounts.queue)
.map(|x| x.accounts.merkle_tree)
.collect::<Vec<_>>();
for merkle_tree_pubkey in pubkeys {
// find forester which is eligible this slot for this tree
if let Some(payer) = Self::get_eligible_forester_for_queue(
&merkle_tree_pubkey,
&self.foresters,
self.slot,
) {
println!("\n --------------------------------------------------\n\t\t Empty Address Queue\n --------------------------------------------------");
println!("epoch {}", self.epoch);
println!("forester {}", payer.pubkey());
let mut merkle_tree_account_data = self
.rpc
.get_account(merkle_tree_pubkey)
.await
.unwrap()
.unwrap()
.data;
let merkle_tree = BatchedMerkleTreeAccount::address_from_bytes(
merkle_tree_account_data.as_mut_slice(),
&merkle_tree_pubkey.into(),
)
.unwrap();
let pending_batch_index = merkle_tree.queue_batches.pending_batch_index;
let batch = merkle_tree
.queue_batches
.batches
.get(pending_batch_index as usize)
.unwrap();
let batch_state = batch.get_state();
println!(
"output batch_state {:?}, {}, batch index {}",
batch_state,
batch.get_num_inserted_zkp_batch()
+ batch.get_current_zkp_batch_index() * batch.zkp_batch_size,
pending_batch_index
);
println!("input batch_state {:?}", batch_state);
if batch_state == BatchState::Full {
println!("\n --------------------------------------------------\n\t\t Empty Address Queue (v2)\n --------------------------------------------------");
let mut merkle_tree_account = self
.rpc
.get_account(merkle_tree_pubkey)
.await
.unwrap()
.unwrap();
let merkle_tree = BatchedMerkleTreeAccount::address_from_bytes(
merkle_tree_account.data.as_mut_slice(),
&merkle_tree_pubkey.into(),
)
.unwrap();
for _ in 0..merkle_tree.queue_batches.get_num_zkp_batches() {
let instruction_data = {
let full_batch_index =
merkle_tree.queue_batches.pending_batch_index;
let batch =
&merkle_tree.queue_batches.batches[full_batch_index as usize];
let zkp_batch_index = batch.get_num_inserted_zkps();
let leaves_hash_chain = merkle_tree.hash_chain_stores
[full_batch_index as usize]
[zkp_batch_index as usize];
let options = QueueElementsV2Options::default()
.with_address_queue(None, Some(batch.batch_size as u16));
let result = self
.indexer
.get_queue_elements(merkle_tree_pubkey.to_bytes(), options, None)
.await
.unwrap();
let addresses = result
.value
.address_queue
.map(|aq| aq.addresses)
.unwrap_or_default();
// // local_leaves_hash_chain is only used for a test assertion.
// let local_nullifier_hash_chain = create_hash_chain_from_array(&addresses);
// assert_eq!(leaves_hash_chain, local_nullifier_hash_chain);
let start_index = merkle_tree.next_index as usize;
assert!(
start_index >= 2,
"start index should be greater than 2 else tree is not inited"
);
let current_root = *merkle_tree.root_history.last().unwrap();
let mut low_element_values = Vec::new();
let mut low_element_indices = Vec::new();
let mut low_element_next_indices = Vec::new();
let mut low_element_next_values = Vec::new();
let mut low_element_proofs: Vec<Vec<[u8; 32]>> = Vec::new();
let non_inclusion_proofs = self
.indexer
.get_multiple_new_address_proofs(
merkle_tree_pubkey.to_bytes(),
addresses.clone(),
None,
)
.await
.unwrap();
for non_inclusion_proof in &non_inclusion_proofs.value.items {
low_element_values.push(non_inclusion_proof.low_address_value);
low_element_indices
.push(non_inclusion_proof.low_address_index as usize);
low_element_next_indices
.push(non_inclusion_proof.low_address_next_index as usize);
low_element_next_values
.push(non_inclusion_proof.low_address_next_value);
low_element_proofs
.push(non_inclusion_proof.low_address_proof.to_vec());
}
let subtrees = self.indexer
.get_subtrees(merkle_tree_pubkey.to_bytes(), None)
.await
.unwrap();
let mut sparse_merkle_tree = SparseMerkleTree::<Poseidon, { DEFAULT_BATCH_ADDRESS_TREE_HEIGHT as usize }>::new(<[[u8; 32]; DEFAULT_BATCH_ADDRESS_TREE_HEIGHT as usize]>::try_from(subtrees.value.items).unwrap(), start_index);
let mut changelog: Vec<ChangelogEntry<{ DEFAULT_BATCH_ADDRESS_TREE_HEIGHT as usize }>> = Vec::new();
let mut indexed_changelog: Vec<IndexedChangelogEntry<usize, { DEFAULT_BATCH_ADDRESS_TREE_HEIGHT as usize }>> = Vec::new();
let inputs = get_batch_address_append_circuit_inputs::<
{ DEFAULT_BATCH_ADDRESS_TREE_HEIGHT as usize },
>(
start_index,
current_root,
low_element_values,
low_element_next_values,
low_element_indices,
low_element_next_indices,
low_element_proofs,
addresses,
&mut sparse_merkle_tree,
leaves_hash_chain,
batch.zkp_batch_size as usize,
&mut changelog,
&mut indexed_changelog,
)
.unwrap();
let client = Client::new();
let circuit_inputs_new_root =
bigint_to_be_bytes_array::<32>(&inputs.new_root).unwrap();
let inputs = to_json(&inputs);
let response_result = client
.post(format!("{}{}", SERVER_ADDRESS, PROVE_PATH))
.header("Content-Type", "text/plain; charset=utf-8")
.body(inputs)
.send()
.await
.expect("Failed to execute request.");
if response_result.status().is_success() {
let body = response_result.text().await.unwrap();
let proof_json = deserialize_gnark_proof_json(&body).unwrap();
let (proof_a, proof_b, proof_c) = proof_from_json_struct(proof_json);
let (proof_a, proof_b, proof_c) = compress_proof(&proof_a, &proof_b, &proof_c);
let instruction_data = InstructionDataBatchNullifyInputs {
new_root: circuit_inputs_new_root,
compressed_proof: CompressedProof {
a: proof_a,
b: proof_b,
c: proof_c,
},
};
Ok(instruction_data)
} else {
Err(RpcError::CustomError(
"Prover failed to generate proof".to_string(),
))
}
}
.unwrap();
let instruction = create_batch_update_address_tree_instruction(
payer.pubkey(),
payer.pubkey(),
merkle_tree_pubkey,
self.epoch,
instruction_data.try_to_vec().unwrap(),
);
self.rpc
.create_and_send_transaction(
&[instruction],
&payer.pubkey(),
&[&payer],
)
.await
.unwrap();
}
let mut account = self
.rpc
.get_account(merkle_tree_pubkey)
.await
.unwrap()
.unwrap();
self.indexer
.finalize_batched_address_tree_update(
merkle_tree_pubkey,
account.data.as_mut_slice(),
)
.await;
}
} else {
println!("No forester found for address queue");
};
}
}
for index in 0..self.indexer.get_state_merkle_trees().len() {
let is_read_for_rollover = state_tree_ready_for_rollover(
&mut self.rpc,
self.indexer.get_state_merkle_trees()[index]
.accounts
.merkle_tree,
)
.await
.unwrap();
if self
.rng
.gen_bool(self.general_action_config.rollover.unwrap_or_default())
&& is_read_for_rollover
{
println!("\n --------------------------------------------------\n\t\t Rollover State Merkle Tree\n --------------------------------------------------");
// find forester which is eligible this slot for this tree
if let Some(payer) = Self::get_eligible_forester_for_queue(
&self.indexer.get_state_merkle_trees()[index]
.accounts
.nullifier_queue,
&self.foresters,
self.slot,
) {
self.rollover_state_merkle_tree_and_queue(index, &payer, self.epoch)
.await
.unwrap();
self.stats.rolledover_state_trees += 1;
}
}
}
for index in 0..self
.indexer
.get_address_merkle_trees()
.iter()
.filter(|x| x.accounts.merkle_tree != x.accounts.queue)
.collect::<Vec<_>>()
.len()
{
let is_read_for_rollover = address_tree_ready_for_rollover(
&mut self.rpc,
self.indexer
.get_address_merkle_trees()
.iter()
.filter(|x| x.accounts.merkle_tree != x.accounts.queue)
.collect::<Vec<_>>()[index]
.accounts
.merkle_tree,
)
.await
.unwrap();
if self
.rng
.gen_bool(self.general_action_config.rollover.unwrap_or_default())
&& is_read_for_rollover
{
// find forester which is eligible this slot for this tree
if let Some(payer) = Self::get_eligible_forester_for_queue(
&self
.indexer
.get_address_merkle_trees()
.iter()
.filter(|x| x.accounts.merkle_tree != x.accounts.queue)
.collect::<Vec<_>>()[index]
.accounts
.queue,
&self.foresters,
self.slot,
) {
println!("\n --------------------------------------------------\n\t\t Rollover Address Merkle Tree\n --------------------------------------------------");
self.rollover_address_merkle_tree_and_queue(index, &payer, self.epoch)
.await
.unwrap();
self.stats.rolledover_address_trees += 1;
}
}
}
if self
.rng
.gen_bool(self.general_action_config.add_forester.unwrap_or_default())
{
println!("\n --------------------------------------------------\n\t\t Add Forester\n --------------------------------------------------");
let forester = TestForester {
keypair: Keypair::new(),
forester: Forester::default(),
is_registered: None,
};
let forester_config = ForesterConfig {
fee: self.rng.gen_range(0..=100),
};
register_test_forester(
&mut self.rpc,
&self.governance_keypair,
&forester.keypair.pubkey(),
forester_config,
)
.await
.unwrap();
self.foresters.push(forester);
self.stats.created_foresters += 1;
}
// advance to next light slot and perform forester epoch actions
if !self.general_action_config.disable_epochs {
println!("\n --------------------------------------------------\n\t\t Start Epoch Actions \n --------------------------------------------------");
let current_solana_slot = self.rpc.get_slot().await.unwrap();
let current_light_slot = self