-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
tests.rs
1910 lines (1584 loc) · 72.7 KB
/
tests.rs
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
// Copyright (C) 2019-2023 Aleo Systems Inc.
// This file is part of the snarkVM library.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::{
advance::split_candidate_solutions,
test_helpers::{CurrentLedger, CurrentNetwork},
Ledger,
RecordsFilter,
};
use aleo_std::StorageMode;
use console::{
account::{Address, PrivateKey},
network::prelude::*,
program::{Entry, Identifier, Literal, Plaintext, ProgramID, Value},
};
use ledger_block::{ConfirmedTransaction, Rejected, Transaction};
use ledger_committee::{Committee, MIN_VALIDATOR_STAKE};
use ledger_store::{helpers::memory::ConsensusMemory, ConsensusStore};
use synthesizer::{program::Program, vm::VM, Stack};
use indexmap::IndexMap;
#[test]
fn test_load() {
let rng = &mut TestRng::default();
// Sample the genesis private key.
let private_key = PrivateKey::<CurrentNetwork>::new(rng).unwrap();
// Initialize the store.
let store = ConsensusStore::<_, ConsensusMemory<_>>::open(None).unwrap();
// Create a genesis block.
let genesis = VM::from(store).unwrap().genesis_beacon(&private_key, rng).unwrap();
// Initialize the ledger with the genesis block.
let ledger = CurrentLedger::load(genesis.clone(), StorageMode::Production).unwrap();
assert_eq!(ledger.latest_hash(), genesis.hash());
assert_eq!(ledger.latest_height(), genesis.height());
assert_eq!(ledger.latest_round(), genesis.round());
assert_eq!(ledger.latest_block(), genesis);
}
#[test]
fn test_load_unchecked() {
// Load the genesis block.
let genesis = crate::test_helpers::sample_genesis_block();
// Initialize the ledger without checks.
let ledger = CurrentLedger::load_unchecked(genesis.clone(), StorageMode::Production).unwrap();
assert_eq!(ledger.latest_hash(), genesis.hash());
assert_eq!(ledger.latest_height(), genesis.height());
assert_eq!(ledger.latest_round(), genesis.round());
assert_eq!(ledger.latest_block(), genesis);
// Initialize the ledger with the genesis block.
let ledger = CurrentLedger::load(genesis.clone(), StorageMode::Production).unwrap();
assert_eq!(ledger.latest_hash(), genesis.hash());
assert_eq!(ledger.latest_height(), genesis.height());
assert_eq!(ledger.latest_round(), genesis.round());
assert_eq!(ledger.latest_block(), genesis);
}
#[test]
fn test_state_path() {
let rng = &mut TestRng::default();
// Initialize the ledger.
let ledger = crate::test_helpers::sample_ledger(PrivateKey::<CurrentNetwork>::new(rng).unwrap(), rng);
// Retrieve the genesis block.
let block = ledger.get_block(0).unwrap();
// Construct the state path.
let commitments = block.transactions().commitments().collect::<Vec<_>>();
let commitment = commitments[0];
let _state_path = ledger.get_state_path_for_commitment(commitment).unwrap();
}
#[test]
fn test_insufficient_private_fees() {
let rng = &mut TestRng::default();
// Initialize the test environment.
let crate::test_helpers::TestEnv { ledger, private_key, view_key, address, .. } =
crate::test_helpers::sample_test_env(rng);
// A helper function to find records.
let find_records = || {
let microcredits = Identifier::from_str("microcredits").unwrap();
ledger
.find_records(&view_key, RecordsFilter::SlowUnspent(private_key))
.unwrap()
.filter(|(_, record)| match record.data().get(µcredits) {
Some(Entry::Private(Plaintext::Literal(Literal::U64(amount), _))) => !amount.is_zero(),
_ => false,
})
.collect::<indexmap::IndexMap<_, _>>()
};
// Fetch the unspent records.
let records = find_records();
let record_1 = records[0].clone();
let record_2 = records[1].clone();
// Check fee amount requirements for `split` calls.
{
// Prepare a `split` execution without a fee.
let inputs = [Value::Record(record_1.clone()), Value::from_str("100u64").unwrap()];
let authorization = ledger.vm.authorize(&private_key, "credits.aleo", "split", inputs, rng).unwrap();
let split_transaction_without_fee = ledger.vm.execute_authorization(authorization, None, None, rng).unwrap();
assert!(ledger.check_transaction_basic(&split_transaction_without_fee, None, rng).is_ok());
}
// Check fee amount requirements for executions.
{
// Prepare an execution without a fee.
let inputs = [
Value::Record(record_1),
Value::from_str(&format!("{address}")).unwrap(),
Value::from_str("100u64").unwrap(),
];
let authorization = ledger.vm.authorize(&private_key, "credits.aleo", "transfer_private", inputs, rng).unwrap();
let transaction_without_fee = ledger.vm.execute_authorization(authorization, None, None, rng).unwrap();
let execution = transaction_without_fee.execution().unwrap();
// Check that a transaction with sufficient fee will succeed.
let fee_authorization = ledger
.vm
.authorize_fee_private(
&private_key,
record_2.clone(),
10_000_000,
1_000,
execution.to_execution_id().unwrap(),
rng,
)
.unwrap();
let fee = ledger.vm.execute_fee_authorization(fee_authorization, None, rng).unwrap();
let sufficient_fee_transaction = Transaction::from_execution(execution.clone(), Some(fee)).unwrap();
assert!(ledger.check_transaction_basic(&sufficient_fee_transaction, None, rng).is_ok());
// Check that a transaction with insufficient fee will fail.
let insufficient_fee_authorization = ledger
.vm
.authorize_fee_private(&private_key, record_2.clone(), 1, 0, execution.to_execution_id().unwrap(), rng)
.unwrap();
let insufficient_fee = ledger.vm.execute_fee_authorization(insufficient_fee_authorization, None, rng).unwrap();
let insufficient_fee_transaction =
Transaction::from_execution(execution.clone(), Some(insufficient_fee)).unwrap();
assert!(ledger.check_transaction_basic(&insufficient_fee_transaction, None, rng).is_err());
}
// Check fee amount requirements for deployment.
{
// Deploy a test program to the ledger.
let program = Program::<CurrentNetwork>::from_str(
r"
program dummy.aleo;
function foo:
input r0 as u8.private;
async foo r0 into r1;
output r1 as dummy.aleo/foo.future;
finalize foo:
input r0 as u8.public;
add r0 r0 into r1;",
)
.unwrap();
// Check that a deployment transaction with sufficient fee will succeed.
let transaction = ledger.vm.deploy(&private_key, &program, Some(record_2.clone()), 0, None, rng).unwrap();
assert!(ledger.check_transaction_basic(&transaction, None, rng).is_ok());
// Check that a deployment transaction with insufficient fee will fail.
let deployment = transaction.deployment().unwrap();
let insufficient_fee_authorization = ledger
.vm
.authorize_fee_private(&private_key, record_2, 1, 0, deployment.to_deployment_id().unwrap(), rng)
.unwrap();
let insufficient_fee = ledger.vm.execute_fee_authorization(insufficient_fee_authorization, None, rng).unwrap();
let insufficient_fee_transaction =
Transaction::from_deployment(*transaction.owner().unwrap(), deployment.clone(), insufficient_fee).unwrap();
assert!(ledger.check_transaction_basic(&insufficient_fee_transaction, None, rng).is_err());
}
}
#[test]
fn test_insufficient_public_fees() {
let rng = &mut TestRng::default();
// Initialize the test environment.
let crate::test_helpers::TestEnv { ledger, private_key, .. } = crate::test_helpers::sample_test_env(rng);
// Sample recipient.
let recipient_private_key = PrivateKey::new(rng).unwrap();
let recipient_address = Address::try_from(&recipient_private_key).unwrap();
// Fund the recipient with 1 million credits.
{
let inputs =
[Value::from_str(&format!("{recipient_address}")).unwrap(), Value::from_str("1000000000000u64").unwrap()];
let transaction = ledger
.vm
.execute(&private_key, ("credits.aleo", "transfer_public"), inputs.into_iter(), None, 0, None, rng)
.unwrap();
let block =
ledger.prepare_advance_to_next_beacon_block(&private_key, vec![], vec![], vec![transaction], rng).unwrap();
// Check that the next block is valid.
ledger.check_next_block(&block, rng).unwrap();
// Add the deployment block to the ledger.
ledger.advance_to_next_block(&block).unwrap();
}
println!("-----------");
// Attempt to bond the node with insufficient public fees.
{
let inputs = [
Value::from_str(&format!("{recipient_address}")).unwrap(),
Value::from_str(&format!("{recipient_address}")).unwrap(),
Value::from_str("1000000000000u64").unwrap(),
];
let transaction = ledger
.vm
.execute(&recipient_private_key, ("credits.aleo", "bond_public"), inputs.into_iter(), None, 0, None, rng)
.unwrap();
let block =
ledger.prepare_advance_to_next_beacon_block(&private_key, vec![], vec![], vec![transaction], rng).unwrap();
// Check that the next block is valid.
ledger.check_next_block(&block, rng).unwrap();
// Add the deployment block to the ledger.
ledger.advance_to_next_block(&block).unwrap();
}
}
#[test]
fn test_insufficient_finalize_fees() {
let rng = &mut TestRng::default();
// Initialize the test environment.
let crate::test_helpers::TestEnv { ledger, private_key, view_key, address, .. } =
crate::test_helpers::sample_test_env(rng);
// Deploy a test program to the ledger.
let program = Program::<CurrentNetwork>::from_str(
r"
program dummy.aleo;
function foo:
input r0 as u8.private;
async foo r0 into r1;
output r1 as dummy.aleo/foo.future;
finalize foo:
input r0 as u8.public;
add r0 r0 into r1;",
)
.unwrap();
// A helper function to find records.
let find_records = || {
let microcredits = Identifier::from_str("microcredits").unwrap();
ledger
.find_records(&view_key, RecordsFilter::SlowUnspent(private_key))
.unwrap()
.filter(|(_, record)| match record.data().get(µcredits) {
Some(Entry::Private(Plaintext::Literal(Literal::U64(amount), _))) => !amount.is_zero(),
_ => false,
})
.collect::<indexmap::IndexMap<_, _>>()
};
// Fetch the unspent records.
let records = find_records();
// Prepare the additional fee.
let credits = Some(records.values().next().unwrap().clone());
// Deploy.
let transaction = ledger.vm.deploy(&private_key, &program, credits, 0, None, rng).unwrap();
// Verify.
ledger.vm().check_transaction(&transaction, None, rng).unwrap();
// Construct the next block.
let block =
ledger.prepare_advance_to_next_beacon_block(&private_key, vec![], vec![], vec![transaction], rng).unwrap();
// Advance to the next block.
ledger.advance_to_next_block(&block).unwrap();
assert_eq!(ledger.latest_height(), 1);
assert_eq!(ledger.latest_hash(), block.hash());
// Create a transfer transaction to produce a record with insufficient balance to pay for fees.
let transfer_transaction = ledger.create_transfer(&private_key, address, 100, 0, None, rng).unwrap();
// Construct the next block.
let block = ledger
.prepare_advance_to_next_beacon_block(&private_key, vec![], vec![], vec![transfer_transaction.clone()], rng)
.unwrap();
// Advance to the next block.
ledger.advance_to_next_block(&block).unwrap();
assert_eq!(ledger.latest_height(), 2);
assert_eq!(ledger.latest_hash(), block.hash());
// Execute the test program, without providing enough fees for finalize, and ensure that the ledger deems the transaction invalid.
// Find records from the transfer transaction.
let records = transfer_transaction
.records()
.map(|(_, record)| record.decrypt(&view_key))
.collect::<Result<Vec<_>, _>>()
.unwrap();
// Prepare the inputs.
let inputs = [Value::<CurrentNetwork>::from_str("1u8").unwrap()].into_iter();
// Check that the record has the correct balance.
let insufficient_record = records[0].clone();
if let Some(Entry::Private(Plaintext::Literal(Literal::U64(amount), _))) =
&insufficient_record.data().get(&Identifier::from_str("microcredits").unwrap())
{
assert_eq!(**amount, 100)
}
// Ensure that we can't produce a transaction with a record that has insufficient balance to pay for fees.
assert!(
ledger
.vm
.execute(&private_key, ("dummy.aleo", "foo"), inputs.clone(), Some(insufficient_record), 0, None, rng)
.is_err()
);
let sufficient_record = records[1].clone();
// Execute with enough fees.
let transaction =
ledger.vm.execute(&private_key, ("dummy.aleo", "foo"), inputs, Some(sufficient_record), 0, None, rng).unwrap();
// Verify.
ledger.vm.check_transaction(&transaction, None, rng).unwrap();
// Ensure that the ledger deems the transaction valid.
assert!(ledger.check_transaction_basic(&transaction, None, rng).is_ok());
}
#[test]
fn test_rejected_execution() {
let rng = &mut TestRng::default();
// Initialize the test environment.
let crate::test_helpers::TestEnv { ledger, private_key, view_key, .. } = crate::test_helpers::sample_test_env(rng);
// Deploy a test program to the ledger.
let program_id = "test_rejected_execute.aleo";
let program = Program::<CurrentNetwork>::from_str(&format!(
"
program {program_id};
function failed_assert:
async failed_assert into r0;
output r0 as {program_id}/failed_assert.future;
finalize failed_assert:
assert.eq false true;"
))
.unwrap();
// A helper function to find records.
let find_records = || {
let microcredits = Identifier::from_str("microcredits").unwrap();
ledger
.find_records(&view_key, RecordsFilter::SlowUnspent(private_key))
.unwrap()
.filter(|(_, record)| match record.data().get(µcredits) {
Some(Entry::Private(Plaintext::Literal(Literal::U64(amount), _))) => !amount.is_zero(),
_ => false,
})
.collect::<indexmap::IndexMap<_, _>>()
};
// Fetch the unspent records.
let records = find_records();
let record_1 = records[0].clone();
let record_2 = records[1].clone();
// Deploy the program.
let deployment_transaction = ledger.vm().deploy(&private_key, &program, Some(record_1), 0, None, rng).unwrap();
// Construct the deployment block.
let deployment_block = ledger
.prepare_advance_to_next_beacon_block(&private_key, vec![], vec![], vec![deployment_transaction], rng)
.unwrap();
// Check that the next block is valid.
ledger.check_next_block(&deployment_block, rng).unwrap();
// Add the deployment block to the ledger.
ledger.advance_to_next_block(&deployment_block).unwrap();
// Construct a transaction that will cause error from an assert call in `finalize`.
let failed_assert_transaction = ledger
.vm()
.execute(
&private_key,
(program_id, "failed_assert"),
Vec::<Value<_>>::new().into_iter(),
Some(record_2),
0,
None,
rng,
)
.unwrap();
let failed_assert_transaction_id = failed_assert_transaction.id();
// Construct the next block containing the new transaction.
let next_block = ledger
.prepare_advance_to_next_beacon_block(
&private_key,
vec![],
vec![],
vec![failed_assert_transaction.clone()],
rng,
)
.unwrap();
// Check that the block contains 1 rejected execution.
assert_eq!(next_block.transactions().len(), 1);
let confirmed_transaction = next_block.transactions().iter().next().unwrap();
assert!(confirmed_transaction.is_rejected());
if let Transaction::Execute(_, execution, fee) = failed_assert_transaction {
let fee_transaction = Transaction::from_fee(fee.unwrap()).unwrap();
let expected_confirmed_transaction =
ConfirmedTransaction::RejectedExecute(0, fee_transaction, Rejected::new_execution(execution), vec![]);
assert_eq!(confirmed_transaction, &expected_confirmed_transaction);
}
// Check that the unconfirmed transaction ID of the rejected execution is correct.
assert_eq!(confirmed_transaction.to_unconfirmed_transaction_id().unwrap(), failed_assert_transaction_id);
// Check that the next block is valid.
ledger.check_next_block(&next_block, rng).unwrap();
// Add the block with the rejected transaction to the ledger.
ledger.advance_to_next_block(&next_block).unwrap();
}
#[test]
fn test_deploy_with_public_fees() {
let rng = &mut TestRng::default();
// Initialize the test environment.
let crate::test_helpers::TestEnv { ledger, private_key, .. } = crate::test_helpers::sample_test_env(rng);
// Deploy a test program to the ledger.
let program_id = ProgramID::<CurrentNetwork>::from_str("dummy_program.aleo").unwrap();
let program = Program::<CurrentNetwork>::from_str(&format!(
"
program {program_id};
function foo:
input r0 as u8.private;
async foo r0 into r1;
output r1 as {program_id}/foo.future;
finalize foo:
input r0 as u8.public;
add r0 r0 into r1;",
))
.unwrap();
// Deploy.
let transaction = ledger.vm.deploy(&private_key, &program, None, 0, None, rng).unwrap();
// Verify.
ledger.vm().check_transaction(&transaction, None, rng).unwrap();
// Construct the next block.
let block =
ledger.prepare_advance_to_next_beacon_block(&private_key, vec![], vec![], vec![transaction], rng).unwrap();
// Advance to the next block.
ledger.advance_to_next_block(&block).unwrap();
assert_eq!(ledger.latest_height(), 1);
assert_eq!(ledger.latest_hash(), block.hash());
assert_eq!(program, ledger.get_program(program_id).unwrap())
}
#[test]
fn test_bond_and_unbond_validator() {
let rng = &mut TestRng::default();
// Initialize the test environment.
let crate::test_helpers::TestEnv { ledger, private_key, .. } = crate::test_helpers::sample_test_env(rng);
// Sample new account for the new committee member.
let new_member_private_key = PrivateKey::<CurrentNetwork>::new(rng).unwrap();
let new_member_address = Address::try_from(&new_member_private_key).unwrap();
// Fund the new committee member.
let inputs = [
Value::from_str(&format!("{new_member_address}")).unwrap(),
Value::from_str("20000000000000u64").unwrap(), // 20 million credits.
];
let transfer_transaction = ledger
.vm
.execute(&private_key, ("credits.aleo", "transfer_public"), inputs.iter(), None, 0, None, rng)
.unwrap();
// Construct the next block.
let transfer_block = ledger
.prepare_advance_to_next_beacon_block(&private_key, vec![], vec![], vec![transfer_transaction], rng)
.unwrap();
// Check that the next block is valid.
ledger.check_next_block(&transfer_block, rng).unwrap();
// Add the deployment block to the ledger.
ledger.advance_to_next_block(&transfer_block).unwrap();
// Construct the bond public
let bond_amount = MIN_VALIDATOR_STAKE;
let inputs = [
Value::from_str(&format!("{new_member_address}")).unwrap(),
Value::from_str(&format!("{new_member_address}")).unwrap(),
Value::from_str(&format!("{bond_amount}u64")).unwrap(),
];
let bond_public_transaction = ledger
.vm
.execute(&new_member_private_key, ("credits.aleo", "bond_public"), inputs.iter(), None, 0, None, rng)
.unwrap();
// Construct the next block.
let bond_public_block = ledger
.prepare_advance_to_next_beacon_block(&private_key, vec![], vec![], vec![bond_public_transaction], rng)
.unwrap();
// Check that the committee does not include the new member.
let committee = ledger.latest_committee().unwrap();
assert!(!committee.is_committee_member(new_member_address));
// Check that the next block is valid.
ledger.check_next_block(&bond_public_block, rng).unwrap();
// Add the bond public block to the ledger.
ledger.advance_to_next_block(&bond_public_block).unwrap();
// Check that the committee is updated with the new member.
let committee = ledger.latest_committee().unwrap();
assert!(committee.is_committee_member(new_member_address));
// Check that number of validators in the `metadata` mapping in `credtis.aleo` is updated.
let program_id = ProgramID::<CurrentNetwork>::from_str("credits.aleo").unwrap();
let metadata_mapping_name = Identifier::from_str("metadata").unwrap();
let key = Plaintext::<CurrentNetwork>::from_str("aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc")
.unwrap();
let num_validators = match ledger
.vm()
.finalize_store()
.get_value_confirmed(program_id, metadata_mapping_name, &key)
.unwrap()
.unwrap()
{
Value::Plaintext(Plaintext::Literal(Literal::U32(num_validators), _)) => *num_validators as usize,
_ => panic!("Unexpected value type"),
};
assert_eq!(num_validators, committee.num_members());
// Construct the bond public
let unbond_amount = committee.get_stake(new_member_address);
let inputs = [Value::from_str(&format!("{unbond_amount}u64")).unwrap()];
let unbond_public_transaction = ledger
.vm
.execute(&new_member_private_key, ("credits.aleo", "unbond_public"), inputs.iter(), None, 0, None, rng)
.unwrap();
// Construct the next block.
let unbond_public_block = ledger
.prepare_advance_to_next_beacon_block(&private_key, vec![], vec![], vec![unbond_public_transaction], rng)
.unwrap();
// Check that the next block is valid.
ledger.check_next_block(&unbond_public_block, rng).unwrap();
// Add the bond public block to the ledger.
ledger.advance_to_next_block(&unbond_public_block).unwrap();
// Check that the committee does not include the new member.
let committee = ledger.latest_committee().unwrap();
assert!(!committee.is_committee_member(new_member_address));
// Check that number of validators in the `metadata` mapping in `credtis.aleo` is updated.
let program_id = ProgramID::<CurrentNetwork>::from_str("credits.aleo").unwrap();
let metadata_mapping_name = Identifier::from_str("metadata").unwrap();
let key = Plaintext::<CurrentNetwork>::from_str("aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc")
.unwrap();
let num_validators = match ledger
.vm()
.finalize_store()
.get_value_confirmed(program_id, metadata_mapping_name, &key)
.unwrap()
.unwrap()
{
Value::Plaintext(Plaintext::Literal(Literal::U32(num_validators), _)) => *num_validators as usize,
_ => panic!("Unexpected value type"),
};
assert_eq!(num_validators, committee.num_members());
}
#[test]
fn test_aborted_transaction_indexing() {
let rng = &mut TestRng::default();
// Initialize the test environment.
let crate::test_helpers::TestEnv { ledger, private_key, .. } = crate::test_helpers::sample_test_env(rng);
// Sample a recipient account.
let recipient_private_key = PrivateKey::<CurrentNetwork>::new(rng).unwrap();
let recipient_address = Address::try_from(&recipient_private_key).unwrap();
// Sample another recipient account.
let recipient_private_key_2 = PrivateKey::<CurrentNetwork>::new(rng).unwrap();
let recipient_address_2 = Address::try_from(&recipient_private_key_2).unwrap();
// Fund a new address.
let inputs = [Value::from_str(&format!("{recipient_address}")).unwrap(), Value::from_str("185000u64").unwrap()];
let transfer_transaction = ledger
.vm
.execute(&private_key, ("credits.aleo", "transfer_public"), inputs.iter(), None, 0, None, rng)
.unwrap();
// Construct the next block.
let transfer_block = ledger
.prepare_advance_to_next_beacon_block(&private_key, vec![], vec![], vec![transfer_transaction], rng)
.unwrap();
// Check that the next block is valid.
ledger.check_next_block(&transfer_block, rng).unwrap();
// Add the deployment block to the ledger.
ledger.advance_to_next_block(&transfer_block).unwrap();
// Send a transaction that will be aborted due to insufficient fee.
let inputs = [Value::from_str(&format!("{recipient_address_2}")).unwrap(), Value::from_str("1u64").unwrap()];
let transfer_transaction = ledger
.vm
.execute(&recipient_private_key_2, ("credits.aleo", "transfer_public"), inputs.iter(), None, 0, None, rng)
.unwrap();
let aborted_transaction_id = transfer_transaction.id();
// Create another arbitrary transaction.
let inputs = [Value::from_str(&format!("{recipient_address_2}")).unwrap(), Value::from_str("1u64").unwrap()];
let transfer_transaction_2 = ledger
.vm
.execute(&private_key, ("credits.aleo", "transfer_public"), inputs.iter(), None, 0, None, rng)
.unwrap();
// Create a block.
let block = ledger
.prepare_advance_to_next_beacon_block(
&private_key,
vec![],
vec![],
vec![transfer_transaction, transfer_transaction_2],
rng,
)
.unwrap();
// Check that the block contains the aborted transaction.
assert_eq!(block.aborted_transaction_ids(), &[aborted_transaction_id]);
// Check that the next block is valid.
ledger.check_next_block(&block, rng).unwrap();
// Add the deployment block to the ledger.
ledger.advance_to_next_block(&block).unwrap();
}
#[test]
fn test_aborted_solution_ids() {
let rng = &mut TestRng::default();
// Initialize the test environment.
let crate::test_helpers::TestEnv { ledger, private_key, address, .. } = crate::test_helpers::sample_test_env(rng);
// Retrieve the puzzle parameters.
let puzzle = ledger.puzzle();
let latest_epoch_hash = ledger.latest_epoch_hash().unwrap();
let minimum_proof_target = ledger.latest_proof_target();
// Create a solution that is less than the minimum proof target.
let mut invalid_solution = puzzle.prove(latest_epoch_hash, address, rng.gen(), None).unwrap();
while puzzle.get_proof_target(&invalid_solution).unwrap() >= minimum_proof_target {
invalid_solution = puzzle.prove(latest_epoch_hash, address, rng.gen(), None).unwrap();
}
// Create a valid transaction for the block.
let inputs = [Value::from_str(&format!("{address}")).unwrap(), Value::from_str("10u64").unwrap()];
let transfer_transaction = ledger
.vm
.execute(&private_key, ("credits.aleo", "transfer_public"), inputs.iter(), None, 0, None, rng)
.unwrap();
// Create a block.
let block = ledger
.prepare_advance_to_next_beacon_block(
&private_key,
vec![],
vec![invalid_solution],
vec![transfer_transaction],
rng,
)
.unwrap();
// Check that the next block is valid.
ledger.check_next_block(&block, rng).unwrap();
// Add the deployment block to the ledger.
ledger.advance_to_next_block(&block).unwrap();
// Enforce that the block solution was aborted properly.
assert!(block.solutions().is_empty());
assert_eq!(block.aborted_solution_ids(), &vec![invalid_solution.id()]);
}
#[test]
fn test_execute_duplicate_input_ids() {
let rng = &mut TestRng::default();
// Initialize the test environment.
let crate::test_helpers::TestEnv { ledger, private_key, view_key, address, .. } =
crate::test_helpers::sample_test_env(rng);
// A helper function to find records.
let find_records = || {
let microcredits = Identifier::from_str("microcredits").unwrap();
ledger
.find_records(&view_key, RecordsFilter::SlowUnspent(private_key))
.unwrap()
.filter(|(_, record)| match record.data().get(µcredits) {
Some(Entry::Private(Plaintext::Literal(Literal::U64(amount), _))) => !amount.is_zero(),
_ => false,
})
.collect::<indexmap::IndexMap<_, _>>()
};
// Fetch the unspent records.
let records = find_records();
let record_1 = records[0].clone();
// Prepare a transfer that spends the record.
let inputs = [
Value::Record(record_1.clone()),
Value::from_str(&format!("{address}")).unwrap(),
Value::from_str("100u64").unwrap(),
];
let transfer_1 = ledger
.vm
.execute(&private_key, ("credits.aleo", "transfer_private"), inputs.into_iter(), None, 0, None, rng)
.unwrap();
let transfer_1_id = transfer_1.id();
// Prepare a transfer that attempts to spend the same record.
let inputs = [
Value::Record(record_1.clone()),
Value::from_str(&format!("{address}")).unwrap(),
Value::from_str("1000u64").unwrap(),
];
let transfer_2 = ledger
.vm
.execute(&private_key, ("credits.aleo", "transfer_private"), inputs.into_iter(), None, 0, None, rng)
.unwrap();
let transfer_2_id = transfer_2.id();
// Prepare a transfer that attempts to spend the same record in the fee.
let inputs = [Value::from_str(&format!("{address}")).unwrap(), Value::from_str("100u64").unwrap()];
let transfer_3 = ledger
.vm
.execute(
&private_key,
("credits.aleo", "transfer_public"),
inputs.into_iter(),
Some(record_1.clone()),
0,
None,
rng,
)
.unwrap();
let transfer_3_id = transfer_3.id();
// Prepare a transfer that attempts to spend the same record for the subsequent block.
let inputs =
[Value::Record(record_1), Value::from_str(&format!("{address}")).unwrap(), Value::from_str("1000u64").unwrap()];
let transfer_4 = ledger
.vm
.execute(&private_key, ("credits.aleo", "transfer_private"), inputs.into_iter(), None, 0, None, rng)
.unwrap();
let transfer_4_id = transfer_4.id();
// Create a block.
let block = ledger
.prepare_advance_to_next_beacon_block(
&private_key,
vec![],
vec![],
vec![transfer_1, transfer_2, transfer_3],
rng,
)
.unwrap();
// Check that the next block is valid.
ledger.check_next_block(&block, rng).unwrap();
// Add the block to the ledger.
ledger.advance_to_next_block(&block).unwrap();
// Enforce that the block transactions were correct.
assert_eq!(block.transactions().num_accepted(), 1);
assert_eq!(block.transactions().transaction_ids().collect::<Vec<_>>(), vec![&transfer_1_id]);
assert_eq!(block.aborted_transaction_ids(), &vec![transfer_2_id, transfer_3_id]);
// Prepare a transfer that will succeed for the subsequent block.
let inputs = [Value::from_str(&format!("{address}")).unwrap(), Value::from_str("1000u64").unwrap()];
let transfer_5 = ledger
.vm
.execute(&private_key, ("credits.aleo", "transfer_public"), inputs.into_iter(), None, 0, None, rng)
.unwrap();
let transfer_5_id = transfer_5.id();
// Create a block.
let block = ledger
.prepare_advance_to_next_beacon_block(&private_key, vec![], vec![], vec![transfer_4, transfer_5], rng)
.unwrap();
// Check that the next block is valid.
ledger.check_next_block(&block, rng).unwrap();
// Add the block to the ledger.
ledger.advance_to_next_block(&block).unwrap();
// Enforce that the block transactions were correct.
assert_eq!(block.transactions().num_accepted(), 1);
assert_eq!(block.transactions().transaction_ids().collect::<Vec<_>>(), vec![&transfer_5_id]);
assert_eq!(block.aborted_transaction_ids(), &vec![transfer_4_id]);
}
#[test]
fn test_execute_duplicate_output_ids() {
let rng = &mut TestRng::default();
// Initialize the test environment.
let crate::test_helpers::TestEnv { ledger, private_key, address, .. } = crate::test_helpers::sample_test_env(rng);
// Deploy a test program to the ledger.
let program = Program::<CurrentNetwork>::from_str(
"
program dummy_program.aleo;
record dummy_program:
owner as address.private;
rand_var as u64.private;
function create_duplicate_record:
input r0 as u64.private;
cast self.caller 1u64 into r1 as dummy_program.record;
output r1 as dummy_program.record;",
)
.unwrap();
// Deploy.
let deployment_transaction = ledger.vm.deploy(&private_key, &program, None, 0, None, rng).unwrap();
// Verify.
ledger.vm().check_transaction(&deployment_transaction, None, rng).unwrap();
// Construct the next block.
let block = ledger
.prepare_advance_to_next_beacon_block(&private_key, vec![], vec![], vec![deployment_transaction], rng)
.unwrap();
// Check that the next block is valid.
ledger.check_next_block(&block, rng).unwrap();
// Add the block to the ledger.
ledger.advance_to_next_block(&block).unwrap();
// Create a transaction with different transition ids, but with a fixed output record (output ID).
let mut create_transaction_with_duplicate_output_id = |x: u64| -> Transaction<CurrentNetwork> {
// Use a fixed seed RNG.
let fixed_rng = &mut TestRng::from_seed(1);
// Create a transaction with a fixed rng.
let inputs = [Value::from_str(&format!("{x}u64")).unwrap()];
let transaction = ledger
.vm
.execute(
&private_key,
("dummy_program.aleo", "create_duplicate_record"),
inputs.into_iter(),
None,
0,
None,
fixed_rng,
)
.unwrap();
// Extract the execution.
let execution = transaction.execution().unwrap().clone();
// Create a new fee for the execution.
let fee_authorization = ledger
.vm
.authorize_fee_public(
&private_key,
*transaction.fee_amount().unwrap(),
0,
execution.to_execution_id().unwrap(),
rng,
)
.unwrap();
let fee = ledger.vm.execute_fee_authorization(fee_authorization, None, rng).unwrap();
Transaction::from_execution(execution, Some(fee)).unwrap()
};
// Create the first transfer.
let transfer_1 = create_transaction_with_duplicate_output_id(1);
let transfer_1_id = transfer_1.id();
// Create a second transfer with the same output id.
let transfer_2 = create_transaction_with_duplicate_output_id(2);
let transfer_2_id = transfer_2.id();
// Create a third transfer with the same output id.
let transfer_3 = create_transaction_with_duplicate_output_id(3);
let transfer_3_id = transfer_3.id();
// Ensure that each transaction has a duplicate output id.
let tx_1_output_id = transfer_1.output_ids().next().unwrap();
let tx_2_output_id = transfer_2.output_ids().next().unwrap();
let tx_3_output_id = transfer_3.output_ids().next().unwrap();
assert_eq!(tx_1_output_id, tx_2_output_id);
assert_eq!(tx_1_output_id, tx_3_output_id);
// Create a block.
let block = ledger
.prepare_advance_to_next_beacon_block(&private_key, vec![], vec![], vec![transfer_1, transfer_2], rng)
.unwrap();
// Check that the next block is valid.
ledger.check_next_block(&block, rng).unwrap();
// Add the block to the ledger.
ledger.advance_to_next_block(&block).unwrap();
// Enforce that the block transactions were correct.
assert_eq!(block.transactions().num_accepted(), 1);
assert_eq!(block.transactions().transaction_ids().collect::<Vec<_>>(), vec![&transfer_1_id]);
assert_eq!(block.aborted_transaction_ids(), &vec![transfer_2_id]);
// Prepare a transfer that will succeed for the subsequent block.
let inputs = [Value::from_str(&format!("{address}")).unwrap(), Value::from_str("1000u64").unwrap()];
let transfer_4 = ledger
.vm
.execute(&private_key, ("credits.aleo", "transfer_public"), inputs.into_iter(), None, 0, None, rng)
.unwrap();
let transfer_4_id = transfer_4.id();
// Create a block.
let block = ledger
.prepare_advance_to_next_beacon_block(&private_key, vec![], vec![], vec![transfer_3, transfer_4], rng)
.unwrap();
// Check that the next block is valid.
ledger.check_next_block(&block, rng).unwrap();
// Add the block to the ledger.
ledger.advance_to_next_block(&block).unwrap();
// Enforce that the block transactions were correct.
assert_eq!(block.transactions().num_accepted(), 1);
assert_eq!(block.transactions().transaction_ids().collect::<Vec<_>>(), vec![&transfer_4_id]);
assert_eq!(block.aborted_transaction_ids(), &vec![transfer_3_id]);
}
#[test]
fn test_execute_duplicate_transition_ids() {
let rng = &mut TestRng::default();
// Initialize the test environment.
let crate::test_helpers::TestEnv { ledger, private_key, address, .. } = crate::test_helpers::sample_test_env(rng);
// Deploy a test program to the ledger.
let program = Program::<CurrentNetwork>::from_str(
"
program dummy_program.aleo;
function empty_function:
",
)