-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
test_credits.rs
2410 lines (2028 loc) · 105 KB
/
test_credits.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::Process;
use circuit::network::AleoV0;
use console::{
account::{Address, PrivateKey},
network::{prelude::*, MainnetV0},
program::{Identifier, Literal, Plaintext, ProgramID, Value},
types::U64,
};
use ledger_committee::{MIN_DELEGATOR_STAKE, MIN_VALIDATOR_STAKE};
use ledger_query::Query;
use ledger_store::{
atomic_finalize,
helpers::memory::{BlockMemory, FinalizeMemory},
BlockStore,
FinalizeMode,
FinalizeStorage,
FinalizeStore,
};
use synthesizer_program::{FinalizeGlobalState, FinalizeStoreTrait, Program};
use indexmap::IndexMap;
type CurrentNetwork = MainnetV0;
type CurrentAleo = AleoV0;
const NUM_BLOCKS_TO_UNLOCK: u32 = 360;
/// Samples a new finalize store.
macro_rules! sample_finalize_store {
() => {{
#[cfg(feature = "rocks")]
let temp_dir = tempfile::tempdir().expect("Failed to open temporary directory");
#[cfg(not(feature = "rocks"))]
let temp_dir = ();
#[cfg(feature = "rocks")]
let store = FinalizeStore::<CurrentNetwork, ledger_store::helpers::rocksdb::FinalizeDB<_>>::open_testing(
temp_dir.path().to_owned(),
None,
)
.unwrap();
#[cfg(not(feature = "rocks"))]
let store = FinalizeStore::<CurrentNetwork, FinalizeMemory<_>>::open(None).unwrap();
(store, temp_dir)
}};
}
macro_rules! test_atomic_finalize {
($store:ident, $mode:expr, $test:block) => {{
// The test closure.
let mut run = || -> Result<()> { atomic_finalize!($store, $mode, $test) };
// Run the test.
run()
}};
}
/// Samples a new finalize state.
fn sample_finalize_state(block_height: u32) -> FinalizeGlobalState {
FinalizeGlobalState::from(block_height as u64, block_height, [0u8; 32])
}
/// Returns the `value` for the given `key` in the `mapping` for the given `program_id`.
fn get_mapping_value<N: Network, F: FinalizeStorage<N>>(
store: &FinalizeStore<N, F>,
program_id: &str,
mapping: &str,
key: Literal<N>,
) -> Result<Option<Value<N>>> {
// Prepare the program ID, mapping name, and key.
let program_id = ProgramID::from_str(program_id)?;
let mapping = Identifier::from_str(mapping)?;
let key = Plaintext::from(key);
// Retrieve the value from the finalize store.
match store.get_value_speculative(program_id, mapping, &key) {
Ok(result) => Ok(result),
Err(err) => bail!("Error getting value for program_id: {program_id}, mapping: {mapping}, key: {key}: {err}"),
}
}
/// Get the current `account` mapping balance.
fn account_balance<N: Network, F: FinalizeStorage<N>>(
store: &FinalizeStore<N, F>,
address: &Address<N>,
) -> Result<u64> {
// Retrieve the balance from the finalize store.
match get_mapping_value(store, "credits.aleo", "account", Literal::Address(*address))? {
Some(Value::Plaintext(Plaintext::Literal(Literal::U64(balance), _))) => Ok(*balance),
_ => bail!("Missing or malformed account balance for {address}"),
}
}
/// Get the current committee state from the `committee` mapping for the given validator address.
/// Returns the `committee_state` as a tuple of `(microcredits, is_open)`.
fn committee_state<N: Network, F: FinalizeStorage<N>>(
store: &FinalizeStore<N, F>,
address: &Address<N>,
) -> Result<Option<(u64, bool)>> {
// Retrieve the committee state from the finalize store.
let state = match get_mapping_value(store, "credits.aleo", "committee", Literal::Address(*address))? {
Some(Value::Plaintext(Plaintext::Struct(state, _))) => state,
None => return Ok(None),
_ => bail!("Malformed committee state for {address}"),
};
// Retrieve `microcredits` from the committee state.
let microcredits = match state.get(&Identifier::from_str("microcredits")?) {
Some(Plaintext::Literal(Literal::U64(microcredits), _)) => **microcredits,
_ => bail!("`microcredits` not found for: {address}"),
};
// Retrieve `is_open` from the committee state.
let is_open = match state.get(&Identifier::from_str("is_open")?) {
Some(Plaintext::Literal(Literal::Boolean(is_open), _)) => **is_open,
_ => bail!("`is_open` not found for: {address}"),
};
Ok(Some((microcredits, is_open)))
}
/// Get the current bond state from the `bonding` mapping for the given staker address.
/// Returns the `bond_state` as a tuple of `(validator address, microcredits)`.
fn bond_state<N: Network, F: FinalizeStorage<N>>(
store: &FinalizeStore<N, F>,
address: &Address<N>,
) -> Result<Option<(Address<N>, u64)>> {
// Retrieve the bond state from the finalize store.
let state = match get_mapping_value(store, "credits.aleo", "bonded", Literal::Address(*address))? {
Some(Value::Plaintext(Plaintext::Struct(state, _))) => state,
None => return Ok(None),
_ => bail!("Malformed bond state for {address}"),
};
// Retrieve `validator` from the bond state.
let validator = match state.get(&Identifier::from_str("validator")?) {
Some(Plaintext::Literal(Literal::Address(address), _)) => *address,
_ => bail!("`validator` not found for: {address}"),
};
// Retrieve `microcredits` from the bond state.
let microcredits = match state.get(&Identifier::from_str("microcredits")?) {
Some(Plaintext::Literal(Literal::U64(microcredits), _)) => **microcredits,
_ => bail!("`microcredits` not found for: {address}"),
};
Ok(Some((validator, microcredits)))
}
/// Get the current unbonding state from the `unbonding` mapping for the given staker address.
/// Returns the `unbond_state` as a tuple of `(microcredits, unbond_height)`.
fn unbond_state<N: Network, F: FinalizeStorage<N>>(
store: &FinalizeStore<N, F>,
address: &Address<N>,
) -> Result<Option<(u64, u32)>> {
// Retrieve the unbond state from the finalize store.
let state = match get_mapping_value(store, "credits.aleo", "unbonding", Literal::Address(*address))? {
Some(Value::Plaintext(Plaintext::Struct(state, _))) => state,
None => return Ok(None),
_ => bail!("Malformed unbond state for {address}"),
};
// Retrieve `microcredits` from the bond state.
let microcredits = match state.get(&Identifier::from_str("microcredits")?) {
Some(Plaintext::Literal(Literal::U64(microcredits), _)) => **microcredits,
_ => bail!("`microcredits` not found for: {address}"),
};
// Retrieve `height` from the bond state.
let height = match state.get(&Identifier::from_str("height")?) {
Some(Plaintext::Literal(Literal::U32(height), _)) => **height,
_ => bail!("`height` not found for: {address}"),
};
Ok(Some((microcredits, height)))
}
/// Get the current withdrawal address from the `withdraw` mapping for the given staker address.
fn withdraw_state<N: Network, F: FinalizeStorage<N>>(
store: &FinalizeStore<N, F>,
address: &Address<N>,
) -> Result<Option<Address<N>>> {
// Retrieve the withdraw state from the finalize store.
let withdrawal_address = match get_mapping_value(store, "credits.aleo", "withdraw", Literal::Address(*address))? {
Some(Value::Plaintext(Plaintext::Literal(Literal::Address(withdrawal_address), _))) => withdrawal_address,
None => return Ok(None),
_ => bail!("Malformed withdraw state for {address}"),
};
Ok(Some(withdrawal_address))
}
/// Initializes the validator and delegator balances in the finalize store.
/// Returns the private keys and balances for the validators and delegators.
fn initialize_stakers<N: Network, F: FinalizeStorage<N>>(
finalize_store: &FinalizeStore<N, F>,
num_validators: u32,
num_delegators: u32,
rng: &mut TestRng,
) -> Result<(IndexMap<PrivateKey<N>, (Address<N>, u64)>, IndexMap<PrivateKey<N>, (Address<N>, u64)>)> {
// Initialize the store for 'credits.aleo'.
let program = Program::<N>::credits()?;
for mapping in program.mappings().values() {
// Ensure that all mappings are initialized.
if !finalize_store.contains_mapping_confirmed(program.id(), mapping.name())? {
// Initialize the mappings for 'credits.aleo'.
finalize_store.initialize_mapping(*program.id(), *mapping.name())?;
}
}
let mapping = Identifier::from_str("account")?;
let mut validators: IndexMap<_, _> = Default::default();
let mut delegators: IndexMap<_, _> = Default::default();
// Initialize the balances for the validators and delegators.
for i in 0..(num_validators + num_delegators) {
// Initialize a new account.
let private_key = PrivateKey::<N>::new(rng)?;
let address = Address::try_from(&private_key)?;
let balance = 100_000_000_000_000u64;
// Add the balance directly to the finalize store.
let key = Plaintext::from(Literal::Address(address));
let value = Value::from(Literal::U64(U64::new(balance)));
finalize_store.insert_key_value(*program.id(), mapping, key, value)?;
assert_eq!(balance, account_balance(finalize_store, &address).unwrap());
// Store the validator or delegator.
if i < num_validators {
// Insert the validator into the list of validators.
validators.insert(private_key, (address, balance));
} else {
// Insert the delegator into the list of delegators.
delegators.insert(private_key, (address, balance));
}
}
Ok((validators, delegators))
}
fn execute_function<F: FinalizeStorage<CurrentNetwork>>(
process: &Process<CurrentNetwork>,
finalize_store: &FinalizeStore<CurrentNetwork, F>,
caller_private_key: &PrivateKey<CurrentNetwork>,
function: &str,
inputs: &[String],
block_height: Option<u32>,
rng: &mut TestRng,
) -> Result<()> {
// Construct the authorization.
let authorization =
process.authorize::<CurrentAleo, _>(caller_private_key, "credits.aleo", function, inputs.iter(), rng)?;
// Construct the trace.
let (_, mut trace) = process.execute::<CurrentAleo, _>(authorization, rng)?;
// Construct the block store.
let block_store = BlockStore::<CurrentNetwork, BlockMemory<_>>::open(None)?;
// Prepare the trace.
trace.prepare(Query::from(&block_store))?;
// Prove the execution.
let execution = trace.prove_execution::<CurrentAleo, _>(function, rng)?;
// Finalize the execution.
let block_height = block_height.unwrap_or(1);
// Add an atomic finalize wrapper around the finalize function.
process.finalize_execution(sample_finalize_state(block_height), finalize_store, &execution, None)?;
Ok(())
}
/// Perform a `bond_public`.
fn bond_public<F: FinalizeStorage<CurrentNetwork>>(
process: &Process<CurrentNetwork>,
finalize_store: &FinalizeStore<CurrentNetwork, F>,
caller_private_key: &PrivateKey<CurrentNetwork>,
validator_address: &Address<CurrentNetwork>,
withdrawal_address: &Address<CurrentNetwork>,
amount: u64,
rng: &mut TestRng,
) -> Result<()> {
execute_function(
process,
finalize_store,
caller_private_key,
"bond_public",
&[validator_address.to_string(), withdrawal_address.to_string(), format!("{amount}_u64")],
None,
rng,
)
}
/// Perform an `unbond_public`.
fn unbond_public<F: FinalizeStorage<CurrentNetwork>>(
process: &Process<CurrentNetwork>,
finalize_store: &FinalizeStore<CurrentNetwork, F>,
caller_private_key: &PrivateKey<CurrentNetwork>,
amount: u64,
block_height: u32,
rng: &mut TestRng,
) -> Result<()> {
execute_function(
process,
finalize_store,
caller_private_key,
"unbond_public",
&[format!("{amount}_u64")],
Some(block_height),
rng,
)
}
/// Perform a `set_validator_state`.
fn set_validator_state<F: FinalizeStorage<CurrentNetwork>>(
process: &Process<CurrentNetwork>,
finalize_store: &FinalizeStore<CurrentNetwork, F>,
caller_private_key: &PrivateKey<CurrentNetwork>,
is_open: bool,
rng: &mut TestRng,
) -> Result<()> {
execute_function(
process,
finalize_store,
caller_private_key,
"set_validator_state",
&[format!("{is_open}")],
None,
rng,
)
}
/// Perform an `unbond_delegator_as_validator`
fn unbond_delegator_as_validator<F: FinalizeStorage<CurrentNetwork>>(
process: &Process<CurrentNetwork>,
finalize_store: &FinalizeStore<CurrentNetwork, F>,
caller_private_key: &PrivateKey<CurrentNetwork>,
delegator_address: &Address<CurrentNetwork>,
rng: &mut TestRng,
) -> Result<()> {
execute_function(
process,
finalize_store,
caller_private_key,
"unbond_delegator_as_validator",
&[delegator_address.to_string()],
None,
rng,
)
}
/// Perform a `claim_unbond_public`.
fn claim_unbond_public<F: FinalizeStorage<CurrentNetwork>>(
process: &Process<CurrentNetwork>,
finalize_store: &FinalizeStore<CurrentNetwork, F>,
caller_private_key: &PrivateKey<CurrentNetwork>,
block_height: u32,
rng: &mut TestRng,
) -> Result<()> {
execute_function(process, finalize_store, caller_private_key, "claim_unbond_public", &[], Some(block_height), rng)
}
#[test]
fn test_bond_validator_simple() {
let rng = &mut TestRng::default();
// Construct the process.
let process = Process::<CurrentNetwork>::load().unwrap();
// Initialize a new finalize store.
let (store, _temp_dir) = sample_finalize_store!();
// Initialize the validators.
let (validators, _) = initialize_stakers(&store, 1, 0, rng).unwrap();
let (validator_private_key, (validator_address, _)) = validators.first().unwrap();
// Retrieve the account balance.
let public_balance = account_balance(&store, validator_address).unwrap();
// Prepare the validator amount.
let amount = MIN_VALIDATOR_STAKE;
// Sanity check the state before finalizing.
assert_eq!(committee_state(&store, validator_address).unwrap(), None);
assert_eq!(bond_state(&store, validator_address).unwrap(), None);
assert_eq!(unbond_state(&store, validator_address).unwrap(), None);
assert_eq!(withdraw_state(&store, validator_address).unwrap(), None);
assert_eq!(account_balance(&store, validator_address).unwrap(), public_balance);
/* Ensure bonding as a validator with the exact MIN_VALIDATOR_STAKE succeeds. */
test_atomic_finalize!(store, FinalizeMode::RealRun, {
// Perform the bond.
bond_public(&process, &store, validator_private_key, validator_address, validator_address, amount, rng)
.unwrap();
// Check that the committee, bond, unbond, and withdraw states are correct.
assert_eq!(committee_state(&store, validator_address).unwrap(), Some((amount, true)));
assert_eq!(bond_state(&store, validator_address).unwrap(), Some((*validator_address, amount)));
assert_eq!(unbond_state(&store, validator_address).unwrap(), None);
assert_eq!(withdraw_state(&store, validator_address).unwrap(), Some(*validator_address));
// Check that the account balance is correct.
assert_eq!(account_balance(&store, validator_address).unwrap(), public_balance - amount);
Ok(())
})
.unwrap();
// Sanity check the state after finalizing.
assert_eq!(committee_state(&store, validator_address).unwrap(), Some((amount, true)));
assert_eq!(bond_state(&store, validator_address).unwrap(), Some((*validator_address, amount)));
assert_eq!(unbond_state(&store, validator_address).unwrap(), None);
assert_eq!(withdraw_state(&store, validator_address).unwrap(), Some(*validator_address));
assert_eq!(account_balance(&store, validator_address).unwrap(), public_balance - amount);
}
#[test]
fn test_bond_validator_below_min_stake_fails() {
let rng = &mut TestRng::default();
// Construct the process.
let process = Process::<CurrentNetwork>::load().unwrap();
// Initialize a new finalize store.
let (store, _temp_dir) = sample_finalize_store!();
// Initialize the validators.
let (validators, _) = initialize_stakers(&store, 1, 0, rng).unwrap();
let (validator_private_key, (validator_address, _)) = validators.first().unwrap();
// Retrieve the account balance.
let public_balance = account_balance(&store, validator_address).unwrap();
/* Ensure bonding as a validator below the MIN_VALIDATOR_STAKE fails. */
test_atomic_finalize!(store, FinalizeMode::RealRun, {
let amount = rng.gen_range(1_000_000..MIN_VALIDATOR_STAKE);
let result =
bond_public(&process, &store, validator_private_key, validator_address, validator_address, amount, rng);
assert!(result.is_err());
// Check that the committee, bond, unbond, and withdraw states are correct.
assert_eq!(committee_state(&store, validator_address).unwrap(), None);
assert_eq!(bond_state(&store, validator_address).unwrap(), None);
assert_eq!(unbond_state(&store, validator_address).unwrap(), None);
assert_eq!(withdraw_state(&store, validator_address).unwrap(), None);
// Check that the account balance is correct.
assert_eq!(account_balance(&store, validator_address).unwrap(), public_balance);
Ok(())
})
.unwrap();
}
#[test]
fn test_bond_validator_with_insufficient_funds_fails() {
let rng = &mut TestRng::default();
// Construct the process.
let process = Process::<CurrentNetwork>::load().unwrap();
// Initialize a new finalize store.
let (store, _temp_dir) = sample_finalize_store!();
// Initialize the validators.
let (validators, _) = initialize_stakers(&store, 1, 0, rng).unwrap();
let (validator_private_key, (validator_address, _)) = validators.first().unwrap();
// Retrieve the account balance.
let public_balance = account_balance(&store, validator_address).unwrap();
/* Ensure bonding an amount larger than the account balance will fail. */
test_atomic_finalize!(store, FinalizeMode::RealRun, {
let amount = public_balance + 1;
let result =
bond_public(&process, &store, validator_private_key, validator_address, validator_address, amount, rng);
assert!(result.is_err());
// Check that the committee, bond, unbond, and withdraw states are correct.
assert_eq!(committee_state(&store, validator_address).unwrap(), None);
assert_eq!(bond_state(&store, validator_address).unwrap(), None);
assert_eq!(unbond_state(&store, validator_address).unwrap(), None);
assert_eq!(withdraw_state(&store, validator_address).unwrap(), None);
// Check that the account balance is correct.
assert_eq!(account_balance(&store, validator_address).unwrap(), public_balance);
Ok(())
})
.unwrap();
}
#[test]
fn test_bond_validator_multiple_bonds() {
let rng = &mut TestRng::default();
// Construct the process.
let process = Process::<CurrentNetwork>::load().unwrap();
// Initialize a new finalize store.
let (store, _temp_dir) = sample_finalize_store!();
// Initialize the validators.
let (validators, _) = initialize_stakers(&store, 1, 0, rng).unwrap();
let (validator_private_key, (validator_address, _)) = validators.first().unwrap();
// Retrieve the account balance.
let public_balance = account_balance(&store, validator_address).unwrap();
/* Ensure that bonding additional stake succeeds. */
test_atomic_finalize!(store, FinalizeMode::RealRun, {
/* First Bond */
// Perform the first bond.
let amount = MIN_VALIDATOR_STAKE;
assert!(amount < public_balance);
bond_public(&process, &store, validator_private_key, validator_address, validator_address, amount, rng)
.unwrap();
// Check that the committee, bond, unbond, and withdraw states are correct.
assert_eq!(committee_state(&store, validator_address).unwrap(), Some((amount, true)));
assert_eq!(bond_state(&store, validator_address).unwrap(), Some((*validator_address, amount)));
assert_eq!(unbond_state(&store, validator_address).unwrap(), None);
assert_eq!(withdraw_state(&store, validator_address).unwrap(), Some(*validator_address));
// Retrieve the account balance.
let public_balance_1 = account_balance(&store, validator_address).unwrap();
assert_eq!(public_balance_1, public_balance - amount);
/* Second Bond */
// Perform the second bond.
let amount = MIN_VALIDATOR_STAKE;
assert!(amount < public_balance_1);
bond_public(&process, &store, validator_private_key, validator_address, validator_address, amount, rng)
.unwrap();
// Check that the committee, bond, unbond, and withdraw states are correct.
assert_eq!(committee_state(&store, validator_address).unwrap(), Some((amount * 2, true)));
assert_eq!(bond_state(&store, validator_address).unwrap(), Some((*validator_address, amount * 2)));
assert_eq!(unbond_state(&store, validator_address).unwrap(), None);
assert_eq!(withdraw_state(&store, validator_address).unwrap(), Some(*validator_address));
// Retrieve the account balance.
let public_balance_2 = account_balance(&store, validator_address).unwrap();
assert_eq!(public_balance_2, public_balance_1 - amount);
Ok(())
})
.unwrap();
}
#[test]
fn test_bond_validator_to_other_validator_fails() {
let rng = &mut TestRng::default();
// Construct the process.
let process = Process::<CurrentNetwork>::load().unwrap();
// Initialize a new finalize store.
let (store, _temp_dir) = sample_finalize_store!();
// Initialize the validators.
let (validators, _) = initialize_stakers(&store, 2, 0, rng).unwrap();
let mut validators = validators.into_iter();
let (validator_private_key_1, (validator_address_1, _)) = validators.next().unwrap();
let (validator_private_key_2, (validator_address_2, _)) = validators.next().unwrap();
/* Ensure that bonding to another validator fails. */
test_atomic_finalize!(store, FinalizeMode::RealRun, {
/* Validator 1 */
// Retrieve the account balance.
let public_balance_1 = account_balance(&store, &validator_address_1).unwrap();
let public_balance_2 = account_balance(&store, &validator_address_2).unwrap();
// Perform the bond for validator 1.
let amount = MIN_VALIDATOR_STAKE;
bond_public(
&process,
&store,
&validator_private_key_1,
&validator_address_1,
&validator_address_1,
amount,
rng,
)
.unwrap();
// Check that the committee, bond, unbond, and withdraw states are correct.
assert_eq!(committee_state(&store, &validator_address_1).unwrap(), Some((amount, true)));
assert_eq!(committee_state(&store, &validator_address_2).unwrap(), None);
assert_eq!(bond_state(&store, &validator_address_1).unwrap(), Some((validator_address_1, amount)));
assert_eq!(bond_state(&store, &validator_address_2).unwrap(), None);
assert_eq!(unbond_state(&store, &validator_address_1).unwrap(), None);
assert_eq!(unbond_state(&store, &validator_address_2).unwrap(), None);
assert_eq!(withdraw_state(&store, &validator_address_1).unwrap(), Some(validator_address_1));
assert_eq!(withdraw_state(&store, &validator_address_2).unwrap(), None);
// Retrieve the account balance.
assert_eq!(account_balance(&store, &validator_address_1).unwrap(), public_balance_1 - amount);
assert_eq!(account_balance(&store, &validator_address_2).unwrap(), public_balance_2);
/* Validator 2 */
// Perform the bond for validator 2.
let amount = MIN_VALIDATOR_STAKE;
bond_public(
&process,
&store,
&validator_private_key_2,
&validator_address_2,
&validator_address_2,
amount,
rng,
)
.unwrap();
// Check that the committee, bond, unbond, and withdraw states are correct.
assert_eq!(committee_state(&store, &validator_address_1).unwrap(), Some((amount, true)));
assert_eq!(committee_state(&store, &validator_address_2).unwrap(), Some((amount, true)));
assert_eq!(bond_state(&store, &validator_address_1).unwrap(), Some((validator_address_1, amount)));
assert_eq!(bond_state(&store, &validator_address_2).unwrap(), Some((validator_address_2, amount)));
assert_eq!(unbond_state(&store, &validator_address_1).unwrap(), None);
assert_eq!(unbond_state(&store, &validator_address_2).unwrap(), None);
assert_eq!(withdraw_state(&store, &validator_address_1).unwrap(), Some(validator_address_1));
assert_eq!(withdraw_state(&store, &validator_address_2).unwrap(), Some(validator_address_2));
// Retrieve the account balance.
assert_eq!(account_balance(&store, &validator_address_1).unwrap(), public_balance_1 - amount);
assert_eq!(account_balance(&store, &validator_address_2).unwrap(), public_balance_2 - amount);
/* Bond Validator 1 to Validator 2 */
// Ensure that bonding to another validator fails.
assert!(public_balance_1 > 2 * amount, "There is not enough balance to bond to another validator.");
let result = bond_public(
&process,
&store,
&validator_private_key_1,
&validator_address_2,
&validator_address_1,
amount,
rng,
);
assert!(result.is_err());
Ok(())
})
.unwrap();
}
#[test]
fn test_bond_delegator_simple() {
let rng = &mut TestRng::default();
// Construct the process.
let process = Process::<CurrentNetwork>::load().unwrap();
// Initialize a new finalize store.
let (store, _temp_dir) = sample_finalize_store!();
// Initialize the validators and delegators.
let (validators, delegators) = initialize_stakers(&store, 1, 1, rng).unwrap();
let (validator_private_key, (validator_address, _)) = validators.first().unwrap();
let (delegator_private_key, (delegator_address, _)) = delegators.first().unwrap();
// Retrieve the account balances.
let validator_balance = account_balance(&store, validator_address).unwrap();
let delegator_balance = account_balance(&store, delegator_address).unwrap();
// Bond the validator.
let validator_amount = MIN_VALIDATOR_STAKE;
bond_public(&process, &store, validator_private_key, validator_address, validator_address, validator_amount, rng)
.unwrap();
// Prepare the delegator amount.
let delegator_amount = MIN_DELEGATOR_STAKE;
/* Ensure bonding a delegator with the exact MIN_DELEGATOR_STAKE succeeds. */
test_atomic_finalize!(store, FinalizeMode::RealRun, {
// Bond the delegator.
bond_public(
&process,
&store,
delegator_private_key,
validator_address,
delegator_address,
delegator_amount,
rng,
)
.unwrap();
// Check that the committee, bond, unbond, and withdraw states are correct.
let combined_amount = validator_amount + delegator_amount;
assert_eq!(committee_state(&store, validator_address).unwrap(), Some((combined_amount, true)));
assert_eq!(committee_state(&store, delegator_address).unwrap(), None);
assert_eq!(bond_state(&store, validator_address).unwrap(), Some((*validator_address, validator_amount)));
assert_eq!(bond_state(&store, delegator_address).unwrap(), Some((*validator_address, delegator_amount)));
assert_eq!(unbond_state(&store, validator_address).unwrap(), None);
assert_eq!(unbond_state(&store, delegator_address).unwrap(), None);
assert_eq!(withdraw_state(&store, validator_address).unwrap(), Some(*validator_address));
assert_eq!(withdraw_state(&store, delegator_address).unwrap(), Some(*delegator_address));
// Check that the balances are correct.
assert_eq!(account_balance(&store, validator_address).unwrap(), validator_balance - validator_amount);
assert_eq!(account_balance(&store, delegator_address).unwrap(), delegator_balance - delegator_amount);
Ok(())
})
.unwrap();
// Sanity check the state after finalizing.
assert_eq!(account_balance(&store, delegator_address).unwrap(), delegator_balance - delegator_amount);
}
#[test]
fn test_bond_delegator_below_min_stake_fails() {
let rng = &mut TestRng::default();
// Construct the process.
let process = Process::<CurrentNetwork>::load().unwrap();
// Initialize a new finalize store.
let (store, _temp_dir) = sample_finalize_store!();
// Initialize the validators and delegators.
let (validators, delegators) = initialize_stakers(&store, 1, 1, rng).unwrap();
let (validator_private_key, (validator_address, _)) = validators.first().unwrap();
let (delegator_private_key, (delegator_address, _)) = delegators.first().unwrap();
// Retrieve the account balance.
let validator_balance = account_balance(&store, validator_address).unwrap();
let delegator_balance = account_balance(&store, delegator_address).unwrap();
/* Ensure bonding as a delegator below the MIN_DELEGATOR_STAKE fails. */
test_atomic_finalize!(store, FinalizeMode::RealRun, {
// Bond the validator.
let validator_amount = MIN_VALIDATOR_STAKE;
bond_public(
&process,
&store,
validator_private_key,
validator_address,
validator_address,
validator_amount,
rng,
)
.unwrap();
// Bond the delegator.
let delegator_amount = rng.gen_range(1_000_000..MIN_DELEGATOR_STAKE);
let result = bond_public(
&process,
&store,
delegator_private_key,
validator_address,
delegator_address,
delegator_amount,
rng,
);
assert!(result.is_err());
// Check that the committee, bond, unbond, and withdraw states are correct.
assert_eq!(committee_state(&store, validator_address).unwrap(), Some((validator_amount, true)));
assert_eq!(committee_state(&store, delegator_address).unwrap(), None);
assert_eq!(bond_state(&store, validator_address).unwrap(), Some((*validator_address, validator_amount)));
assert_eq!(bond_state(&store, delegator_address).unwrap(), None);
assert_eq!(unbond_state(&store, validator_address).unwrap(), None);
assert_eq!(unbond_state(&store, delegator_address).unwrap(), None);
assert_eq!(withdraw_state(&store, validator_address).unwrap(), Some(*validator_address));
assert_eq!(withdraw_state(&store, delegator_address).unwrap(), None);
// Check that the account balance is correct.
assert_eq!(account_balance(&store, validator_address).unwrap(), validator_balance - validator_amount);
assert_eq!(account_balance(&store, delegator_address).unwrap(), delegator_balance);
Ok(())
})
.unwrap();
}
#[test]
fn test_bond_delegator_with_insufficient_funds_fails() {
let rng = &mut TestRng::default();
// Construct the process.
let process = Process::<CurrentNetwork>::load().unwrap();
// Initialize a new finalize store.
let (store, _temp_dir) = sample_finalize_store!();
// Initialize the validators and delegators.
let (validators, delegators) = initialize_stakers(&store, 1, 1, rng).unwrap();
let (validator_private_key, (validator_address, _)) = validators.first().unwrap();
let (delegator_private_key, (delegator_address, _)) = delegators.first().unwrap();
// Retrieve the account balance.
let validator_balance = account_balance(&store, validator_address).unwrap();
let delegator_balance = account_balance(&store, delegator_address).unwrap();
/* Ensure bonding an amount larger than the account balance will fail. */
test_atomic_finalize!(store, FinalizeMode::RealRun, {
// Bond the validator.
let validator_amount = MIN_VALIDATOR_STAKE;
bond_public(
&process,
&store,
validator_private_key,
validator_address,
validator_address,
validator_amount,
rng,
)
.unwrap();
// Bond the delegator.
let delegator_amount = delegator_balance + 1;
let result = bond_public(
&process,
&store,
delegator_private_key,
validator_address,
delegator_address,
delegator_amount,
rng,
);
assert!(result.is_err());
// Check that the committee, bond, unbond, and withdraw states are correct.
assert_eq!(committee_state(&store, validator_address).unwrap(), Some((validator_amount, true)));
assert_eq!(committee_state(&store, delegator_address).unwrap(), None);
assert_eq!(bond_state(&store, validator_address).unwrap(), Some((*validator_address, validator_amount)));
assert_eq!(bond_state(&store, delegator_address).unwrap(), None);
assert_eq!(unbond_state(&store, validator_address).unwrap(), None);
assert_eq!(unbond_state(&store, delegator_address).unwrap(), None);
assert_eq!(withdraw_state(&store, validator_address).unwrap(), Some(*validator_address));
assert_eq!(withdraw_state(&store, delegator_address).unwrap(), None);
// Check that the account balance is correct.
assert_eq!(account_balance(&store, validator_address).unwrap(), validator_balance - validator_amount);
assert_eq!(account_balance(&store, delegator_address).unwrap(), delegator_balance);
Ok(())
})
.unwrap();
}
#[test]
fn test_bond_delegator_multiple_bonds() {
let rng = &mut TestRng::default();
// Construct the process.
let process = Process::<CurrentNetwork>::load().unwrap();
// Initialize a new finalize store.
let (store, _temp_dir) = sample_finalize_store!();
// Initialize the validators and delegators.
let (validators, delegators) = initialize_stakers(&store, 1, 1, rng).unwrap();
let (validator_private_key, (validator_address, _)) = validators.first().unwrap();
let (delegator_private_key, (delegator_address, _)) = delegators.first().unwrap();
// Retrieve the account balance.
let validator_balance = account_balance(&store, validator_address).unwrap();
let delegator_balance = account_balance(&store, delegator_address).unwrap();
// Bond the validator.
let validator_amount = MIN_VALIDATOR_STAKE;
bond_public(&process, &store, validator_private_key, validator_address, validator_address, validator_amount, rng)
.unwrap();
/* Ensure that bonding additional stake as a delegator succeeds. */
test_atomic_finalize!(store, FinalizeMode::RealRun, {
/* First Bond */
// Perform the first bond.
let delegator_amount = MIN_DELEGATOR_STAKE;
assert!(delegator_amount < delegator_balance);
bond_public(
&process,
&store,
delegator_private_key,
validator_address,
delegator_address,
delegator_amount,
rng,
)
.unwrap();
// Check that the committee, bond, unbond, and withdraw states are correct.
let combined_amount = validator_amount + delegator_amount;
assert_eq!(committee_state(&store, validator_address).unwrap(), Some((combined_amount, true)));
assert_eq!(committee_state(&store, delegator_address).unwrap(), None);
assert_eq!(bond_state(&store, validator_address).unwrap(), Some((*validator_address, validator_amount)));
assert_eq!(bond_state(&store, delegator_address).unwrap(), Some((*validator_address, delegator_amount)));
assert_eq!(unbond_state(&store, validator_address).unwrap(), None);
assert_eq!(unbond_state(&store, delegator_address).unwrap(), None);
assert_eq!(withdraw_state(&store, validator_address).unwrap(), Some(*validator_address));
assert_eq!(withdraw_state(&store, delegator_address).unwrap(), Some(*delegator_address));
// Retrieve the account balance.
let validator_balance_1 = account_balance(&store, validator_address).unwrap();
let delegator_balance_1 = account_balance(&store, delegator_address).unwrap();
assert_eq!(validator_balance_1, validator_balance - validator_amount);
assert_eq!(delegator_balance_1, delegator_balance - delegator_amount);
/* Second Bond */
// Perform the second bond.
let delegator_amount = MIN_DELEGATOR_STAKE;
assert!(delegator_amount < delegator_balance_1);
bond_public(
&process,
&store,
delegator_private_key,
validator_address,
delegator_address,
delegator_amount,
rng,
)
.unwrap();
// Check that the committee, bond, unbond, and withdraw states are correct.
let combined_amount = validator_amount + delegator_amount + delegator_amount;
assert_eq!(committee_state(&store, validator_address).unwrap(), Some((combined_amount, true)));
assert_eq!(committee_state(&store, delegator_address).unwrap(), None);
assert_eq!(bond_state(&store, validator_address).unwrap(), Some((*validator_address, validator_amount)));
assert_eq!(bond_state(&store, delegator_address).unwrap(), Some((*validator_address, 2 * delegator_amount)));
assert_eq!(unbond_state(&store, validator_address).unwrap(), None);
assert_eq!(unbond_state(&store, delegator_address).unwrap(), None);
assert_eq!(withdraw_state(&store, validator_address).unwrap(), Some(*validator_address));
assert_eq!(withdraw_state(&store, delegator_address).unwrap(), Some(*delegator_address));
// Retrieve the account balance.
let validator_balance_2 = account_balance(&store, validator_address).unwrap();
let delegator_balance_2 = account_balance(&store, delegator_address).unwrap();
assert_eq!(validator_balance_2, validator_balance_1);
assert_eq!(delegator_balance_2, delegator_balance_1 - delegator_amount);
Ok(())
})
.unwrap();
}
#[test]
fn test_bond_validator_and_delegator_multiple_times() {
let rng = &mut TestRng::default();
// Construct the process.
let process = Process::<CurrentNetwork>::load().unwrap();
// Initialize a new finalize store.
let finalize_store = FinalizeStore::<CurrentNetwork, FinalizeMemory<_>>::open(None).unwrap();
// Initialize the validators and delegators.
let (validators, delegators) = initialize_stakers(&finalize_store, 1, 1, rng).unwrap();
let (validator_private_key, (validator_address, _)) = validators.first().unwrap();
let (delegator_private_key, (delegator_address, _)) = delegators.first().unwrap();
// Retrieve the account balances.
let validator_public_balance = account_balance(&finalize_store, validator_address).unwrap();
let delegator_public_balance = account_balance(&finalize_store, delegator_address).unwrap();
// Prepare the validator amount.
let validator_amount = MIN_VALIDATOR_STAKE;
// Perform the bond.
bond_public(
&process,
&finalize_store,
validator_private_key,
validator_address,
validator_address,
validator_amount,
rng,
)
.unwrap();
// Check that the committee, bond, unbond, and withdraw states are correct.
assert_eq!(committee_state(&finalize_store, validator_address).unwrap(), Some((validator_amount, true)));
assert_eq!(bond_state(&finalize_store, validator_address).unwrap(), Some((*validator_address, validator_amount)));
assert_eq!(unbond_state(&finalize_store, validator_address).unwrap(), None);
assert_eq!(withdraw_state(&finalize_store, validator_address).unwrap(), Some(*validator_address));
assert_eq!(
account_balance(&finalize_store, validator_address).unwrap(),
validator_public_balance - validator_amount
);
// Bond the delegator to the validator.
let delegator_amount = MIN_DELEGATOR_STAKE;
bond_public(
&process,
&finalize_store,
delegator_private_key,
validator_address,
delegator_address,
delegator_amount,
rng,
)
.unwrap();
// Check that the committee, bond, unbond, and withdraw states are correct.