solana-runtime 4.4.0-alpha.5

Solana runtime
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
use {
    super::Bank,
    crate::{
        bank::CollectorFeeDetails,
        inflation_rewards::{MAX_BPS, MAX_BPS_U128},
        reward_info::RewardInfo,
    },
    agave_reserved_account_keys::ReservedAccountKeys,
    log::debug,
    solana_account::{AccountSharedData, ReadableAccount, WritableAccount},
    solana_pubkey::Pubkey,
    solana_rent::Rent,
    solana_reward_info::RewardType,
    solana_runtime_transaction::{
        transaction_meta::TransactionConfiguration, transaction_with_meta::TransactionWithMeta,
    },
    solana_sdk_ids::incinerator,
    solana_svm::rent_calculator::check_static_account_rent_state_transition,
    solana_system_interface::program as system_program,
    solana_vote::vote_state_view_mut::VoteStateViewMut,
    std::{result::Result, sync::atomic::Ordering::Relaxed},
    thiserror::Error,
};

#[derive(Error, Debug, PartialEq)]
pub(super) enum DepositFeeError {
    #[error("fee account became rent paying")]
    InvalidRentPayingAccount,
    #[error("lamport overflow")]
    LamportOverflow,
    #[error("invalid fee account owner")]
    InvalidAccountOwner,
    #[error("collector is a reserved account")]
    ReservedCollector,
    #[error("invalid vote account")]
    InvalidVoteAccount,
}

/// Helper enum used to distinguish external collector types allowed by
/// SIMD-0232.
///
/// The term "external" is used to exclude the vote account itself, which is a
/// valid collector.
pub(super) enum ExternalCollectorType {
    /// A rent-exempt, non-incinerator, non-reserved account owned by the system
    /// program
    SystemAccount,
    /// Specifically, the incinerator account, denoted by `incinerator::id()`
    Incinerator,
}

#[derive(Default)]
pub struct FeeDistribution {
    deposit: u64,
    burn: u64,
}

impl FeeDistribution {
    pub fn get_deposit(&self) -> u64 {
        self.deposit
    }
}

pub(crate) fn default_system_account() -> AccountSharedData {
    AccountSharedData::new(0, 0, &system_program::id())
}

fn report_deposit_error(slot: u64, destination: &Pubkey, deposit: u64, err: DepositFeeError) {
    debug!("Burned {deposit} lamport tx fee instead of sending to {destination} due to {err}");
    datapoint_warn!(
        "bank-burned_fee",
        ("slot", slot, i64),
        ("num_lamports", deposit, i64),
        ("error", err.to_string(), String),
    );
}

impl Bank {
    // Distribute collected transaction fees for this slot to the block revenue collector
    // id for the current leader.
    //
    // Each validator is incentivized to process more transactions to earn more transaction fees.
    // Transaction fees are rewarded for the computing resource utilization cost, directly
    // proportional to their actual processing power.
    //
    // The leader is rotated according to stake-weighted leader schedule. So the opportunity of
    // earning transaction fees are fairly distributed by stake. And missing the opportunity
    // (not producing a block as a leader) earns nothing. So, being online is incentivized as a
    // form of transaction fees as well.
    pub(super) fn distribute_transaction_fee_details(&self) {
        let fee_details = self.collector_fee_details.read().unwrap();

        let FeeDistribution { deposit, burn } =
            self.calculate_reward_and_burn_fee_details(&fee_details);

        let total_burn = self.deposit_or_burn_fee(deposit).saturating_add(burn);
        self.capitalization.fetch_sub(total_burn, Relaxed);
    }

    pub fn calculate_reward_for_transaction(
        &self,
        transaction: &impl TransactionWithMeta,
        transaction_configuration: &TransactionConfiguration,
    ) -> u64 {
        let fee_details = solana_fee::calculate_fee_details(
            transaction,
            self.fee_structure().lamports_per_signature,
            transaction_configuration.priority_fee_lamports,
            self.fee_features(),
        );
        let FeeDistribution {
            deposit: reward,
            burn: _,
        } = self.calculate_reward_and_burn_fee_details(&CollectorFeeDetails::from(fee_details));
        reward
    }

    pub fn calculate_reward_and_burn_fee_details(
        &self,
        fee_details: &CollectorFeeDetails,
    ) -> FeeDistribution {
        let burn = fee_details.transaction_fee * self.burn_percent() / 100;
        let deposit = fee_details
            .priority_fee
            .saturating_add(fee_details.transaction_fee.saturating_sub(burn));
        FeeDistribution { deposit, burn }
    }

    const fn burn_percent(&self) -> u64 {
        // NOTE: burn percent is statically 50%, in case it needs to change in the future,
        // burn_percent can be bank property that being passed down from bank to bank, without
        // needing fee-rate-governor
        static_assertions::const_assert!(solana_fee_calculator::DEFAULT_BURN_PERCENT <= 100);

        solana_fee_calculator::DEFAULT_BURN_PERCENT as u64
    }

    /// Attempts to deposit the given `deposit` amount into the fee collector
    /// and vote accounts.
    ///
    /// With SIMD-0123, the `deposit` amount is split between the collector and
    /// delegators based on the block revenue commission set in the vote account.
    ///
    /// Returns lamports that must be burned if either deposit failed. 0
    /// indicates that both deposits succeeded.
    fn deposit_or_burn_fee(&self, deposit: u64) -> u64 {
        if deposit == 0 {
            return 0;
        }

        // Per SIMD-0232: the commission collector address should be fetched
        // from the state of the vote account at the beginning of the previous
        // epoch. This is the vote account state used to build the leader
        // schedule for the current epoch, which *DOES NOT* correspond to
        // `Bank::current_epoch_stakes()`.
        let feature_snapshot = self.feature_set.snapshot();
        let (collector_id, commission_bps) = if feature_snapshot.custom_commission_collector {
            let vote_account = self
                .epoch_stakes
                .get(&self.epoch)
                .and_then(|stakes| {
                    stakes
                        .stakes()
                        .vote_accounts()
                        .get(&self.leader.vote_address)
                })
                .expect("The vote account for the leader must exist");
            (
                // Protection in case the leader is on a vote state without a
                // collector id, which can happen if a dormant pre-v4 vote state
                // accrues stake.
                vote_account
                    .vote_state_view()
                    .block_revenue_collector()
                    .unwrap_or(&self.leader.id),
                // For pre-v4 vote states, defaults to the max of 10_000 bps
                vote_account.vote_state_view().block_revenue_commission(),
            )
        } else {
            (&self.leader.id, MAX_BPS)
        };

        let (validator_fee, delegator_fee) = if feature_snapshot.block_revenue_sharing {
            let clamped_commission_bps = u128::from(commission_bps.min(MAX_BPS));
            let validator_fee = u128::from(deposit)
                .checked_mul(clamped_commission_bps)
                .expect("u64 * u16 fits in a u128")
                / MAX_BPS_U128;
            let validator_fee = u64::try_from(validator_fee)
                .expect("validator fee is a portion of total fee, which fits in a u64");
            (
                validator_fee,
                deposit
                    .checked_sub(validator_fee)
                    .expect("validator fee is a portion of the total fee"),
            )
        } else {
            (deposit, 0)
        };

        let validator_fee_to_burn =
            self.try_deposit_and_report(collector_id, validator_fee, || {
                self.deposit_fees(collector_id, validator_fee)
            });

        let delegator_fee_to_burn =
            self.try_deposit_and_report(&self.leader.vote_address, delegator_fee, || {
                self.deposit_delegator_fees(&self.leader.vote_address, delegator_fee)
            });

        validator_fee_to_burn + delegator_fee_to_burn
    }

    fn try_deposit_and_report(
        &self,
        destination: &Pubkey,
        amount: u64,
        deposit_and_return_post_balance_fn: impl FnOnce() -> Result<u64, DepositFeeError>,
    ) -> u64 {
        if amount == 0 {
            return 0;
        }
        match deposit_and_return_post_balance_fn() {
            Ok(post_balance) => {
                self.report_reward(destination, amount, post_balance);
                0
            }
            Err(err) => {
                report_deposit_error(self.slot(), destination, amount, err);
                amount
            }
        }
    }

    fn report_reward(&self, destination: &Pubkey, lamports: u64, post_balance: u64) {
        self.rewards.write().unwrap().push((
            *destination,
            RewardInfo {
                reward_type: RewardType::Fee,
                lamports: lamports as i64,
                post_balance,
                commission_bps: None,
            },
        ));
    }

    // Deposits fees into a specified account and if successful, returns the new balance of that account
    fn deposit_fees(&self, collector_id: &Pubkey, fees: u64) -> Result<u64, DepositFeeError> {
        let mut account = self
            .get_account_with_fixed_root_no_cache(collector_id)
            .unwrap_or_else(default_system_account);

        let feature_snapshot = self.feature_set.snapshot();
        if feature_snapshot.custom_commission_collector {
            let pre_lamports = account.lamports();
            account
                .checked_add_lamports(fees)
                .map_err(|_| DepositFeeError::LamportOverflow)?;
            if collector_id != &self.leader.vote_address {
                Bank::collector_type_checked(
                    collector_id,
                    pre_lamports,
                    &account,
                    &self.reserved_account_keys,
                    &self.rent_collector().rent,
                    feature_snapshot.relax_post_exec_min_balance_check,
                )?;
            }
        } else {
            if !system_program::check_id(account.owner()) {
                return Err(DepositFeeError::InvalidAccountOwner);
            }

            let pre_balance = account.lamports();
            let distribution = account.checked_add_lamports(fees);
            if distribution.is_err() {
                return Err(DepositFeeError::LamportOverflow);
            }

            // rent state transition must be checked in case the account receiving the distribution
            // doesn't exist yet.
            if check_static_account_rent_state_transition(
                pre_balance,
                account.lamports(),
                account.data().len(),
                &self.rent_collector().rent,
                0, // account index isn't relevant and only used for error message
                feature_snapshot.relax_post_exec_min_balance_check,
            )
            .is_err()
            {
                return Err(DepositFeeError::InvalidRentPayingAccount);
            }
        }

        self.store_account(collector_id, &account);
        Ok(account.lamports())
    }

    // Deposits delegator fees into the specified vote account and increments
    // pending delegator rewards. If successful, returns the new balance of that
    // account
    fn deposit_delegator_fees(
        &self,
        vote_address: &Pubkey,
        fees: u64,
    ) -> Result<u64, DepositFeeError> {
        let mut account = self
            .get_account_with_fixed_root_no_cache(vote_address)
            .ok_or(DepositFeeError::InvalidVoteAccount)?;

        if *account.owner() != solana_sdk_ids::vote::id() {
            return Err(DepositFeeError::InvalidVoteAccount);
        }

        let account_data = account.data_as_mut_slice();
        let mut vote_state = VoteStateViewMut::new_v4(account_data)
            .map_err(|_| DepositFeeError::InvalidVoteAccount)?;

        vote_state
            .increment_pending_delegator_rewards_checked(fees)
            .ok_or(DepositFeeError::LamportOverflow)?;

        account
            .checked_add_lamports(fees)
            .map_err(|_| DepositFeeError::LamportOverflow)?;

        self.store_account(vote_address, &account);
        Ok(account.lamports())
    }

    /// Checks if a collector account adheres to the rules outlined in SIMD-0232:
    /// * system program owned account
    /// * rent-exempt after depositing inflation rewards commission
    /// * not a reserved account
    ///
    /// Returns the kind of collector
    pub(super) fn collector_type_checked(
        collector_id: &Pubkey,
        pre_lamports: u64,
        account: &AccountSharedData,
        reserved_account_keys: &ReservedAccountKeys,
        rent: &Rent,
        relax_post_execution_balance_checks: bool,
    ) -> Result<ExternalCollectorType, DepositFeeError> {
        if !system_program::check_id(account.owner()) {
            return Err(DepositFeeError::InvalidAccountOwner);
        }

        if reserved_account_keys.is_reserved(collector_id) {
            return Err(DepositFeeError::ReservedCollector);
        }

        // Don't perform rent check on the incinerator, so that the deposit
        // always works. The incinerator is run at the end of a block
        if *collector_id == incinerator::id() {
            Ok(ExternalCollectorType::Incinerator)
        } else {
            if !rent.is_exempt(account.lamports(), account.data().len())
                && (!relax_post_execution_balance_checks || pre_lamports == 0)
            {
                Err(DepositFeeError::InvalidRentPayingAccount)
            } else {
                Ok(ExternalCollectorType::SystemAccount)
            }
        }
    }
}

#[cfg(test)]
pub mod tests {
    use {
        super::*,
        crate::genesis_utils::{create_genesis_config, create_genesis_config_with_leader},
        agave_feature_set::FeatureSet,
        proptest::prelude::*,
        solana_account::state_traits::StateMutWincode,
        solana_pubkey as pubkey,
        solana_rent::Rent,
        solana_signer::Signer,
        solana_vote_interface::state::{VoteStateV3, VoteStateV4, VoteStateVersions},
        std::sync::{Arc, RwLock},
        test_case::test_case,
    };

    #[test]
    fn test_deposit_or_burn_zero_fee() {
        let genesis = create_genesis_config(0);
        let bank = Bank::new_for_tests(&genesis.genesis_config);
        assert_eq!(bank.deposit_or_burn_fee(0), 0);
    }

    #[test_case(true; "custom_commission_collector")]
    #[test_case(false; "no_custom_commission_collector")]
    fn test_deposit_or_burn_fee(custom_commission_collector: bool) {
        #[derive(PartialEq)]
        enum Scenario {
            Normal,
            InvalidOwner,
            RentPayingAccount,
            NonDefault,
            VoteAccount,
            Incinerator,
        }

        struct TestCase {
            scenario: Scenario,
        }

        impl TestCase {
            fn new(scenario: Scenario) -> Self {
                Self { scenario }
            }
        }

        for test_case in [
            TestCase::new(Scenario::Normal),
            TestCase::new(Scenario::InvalidOwner),
            TestCase::new(Scenario::RentPayingAccount),
            TestCase::new(Scenario::NonDefault),
            TestCase::new(Scenario::VoteAccount),
            TestCase::new(Scenario::Incinerator),
        ] {
            if !custom_commission_collector {
                // Some scenarios don't make sense without a custom collector
                match test_case.scenario {
                    Scenario::NonDefault | Scenario::VoteAccount | Scenario::Incinerator => {
                        continue;
                    }
                    Scenario::Normal | Scenario::InvalidOwner | Scenario::RentPayingAccount => {}
                }
            }
            let initial_balance = 1000;
            let mut genesis =
                create_genesis_config_with_leader(0, &pubkey::new_rand(), initial_balance);
            let rent = Rent::default();
            let min_rent_exempt_balance = rent.minimum_balance(0);
            genesis.genesis_config.rent = rent; // Ensure rent is non-zero, as genesis_utils sets Rent::free by default

            // update collector id at genesis for some cases
            let maybe_collector_id = if custom_commission_collector {
                let mut maybe_collector_id = None;
                for (address, account) in genesis.genesis_config.accounts.iter_mut() {
                    if account.owner == solana_sdk_ids::vote::id() {
                        let mut vote_state =
                            VoteStateV4::deserialize(account.data(), &Pubkey::default()).unwrap();
                        let collector_id = match test_case.scenario {
                            Scenario::Normal => vote_state.block_revenue_collector,
                            Scenario::InvalidOwner
                            | Scenario::RentPayingAccount
                            | Scenario::NonDefault => Pubkey::new_unique(),
                            Scenario::Incinerator => incinerator::id(),
                            Scenario::VoteAccount => *address,
                        };
                        vote_state.block_revenue_collector = collector_id;
                        maybe_collector_id = Some(collector_id);
                        let versioned = VoteStateVersions::V4(Box::new(vote_state));
                        account.set_state(&versioned).unwrap();
                    }
                }
                maybe_collector_id
            } else {
                None
            };

            let mut bank = Bank::new_for_tests(&genesis.genesis_config);
            let mut feature_set = FeatureSet::all_enabled();
            if !custom_commission_collector {
                feature_set.deactivate(&agave_feature_set::custom_commission_collector::id());
            }
            bank.feature_set = Arc::new(feature_set);

            let collector_id = maybe_collector_id.unwrap_or(*bank.leader_id());

            let deposit = 100;
            let mut burn = 100;

            match test_case.scenario {
                Scenario::RentPayingAccount => {
                    // ensure that the account is rent-paying
                    let account = AccountSharedData::new(1, 1_000, &Pubkey::new_unique());
                    bank.store_account(&collector_id, &account);
                }
                Scenario::InvalidOwner => {
                    // ensure that account owner is invalid and fee distribution will fail
                    let account =
                        AccountSharedData::new(min_rent_exempt_balance, 0, &Pubkey::new_unique());
                    bank.store_account(&collector_id, &account);
                }
                Scenario::VoteAccount => {
                    // nothing to do, collector id already set, and vote account
                    // already exists
                }
                Scenario::Incinerator => {
                    // nothing to do, incinerator already exists
                }
                Scenario::NonDefault | Scenario::Normal => {
                    let account =
                        AccountSharedData::new(min_rent_exempt_balance, 0, &system_program::id());
                    bank.store_account(&collector_id, &account);
                }
            }

            let initial_burn = burn;
            let initial_collector_balance = bank.get_balance(&collector_id);
            burn += bank.deposit_or_burn_fee(deposit);
            let new_collector_balance = bank.get_balance(&collector_id);

            match test_case.scenario {
                Scenario::InvalidOwner | Scenario::RentPayingAccount => {
                    assert_eq!(initial_collector_balance, new_collector_balance);
                    assert_eq!(initial_burn + deposit, burn);
                    let locked_rewards = bank.rewards.read().unwrap();
                    assert!(
                        locked_rewards.is_empty(),
                        "There should be no rewards distributed"
                    );
                }
                Scenario::NonDefault
                | Scenario::Normal
                | Scenario::VoteAccount
                | Scenario::Incinerator => {
                    assert_eq!(initial_collector_balance + deposit, new_collector_balance);

                    assert_eq!(initial_burn, burn);

                    let locked_rewards = bank.rewards.read().unwrap();
                    assert_eq!(
                        locked_rewards.len(),
                        1,
                        "There should be one reward distributed"
                    );

                    let reward_info = &locked_rewards[0];
                    assert_eq!(
                        reward_info.1.lamports, deposit as i64,
                        "The reward amount should match the expected deposit"
                    );
                    assert_eq!(
                        reward_info.1.reward_type,
                        RewardType::Fee,
                        "The reward type should be Fee"
                    );
                }
            }
        }
    }

    proptest! {
        #[test]
        fn test_deposit_or_burn_fee_with_delegator_rewards(
            commission in 0..=u16::MAX,
            total_fee in 0..=u64::MAX,
        ) {
            let initial_balance = 1000;
            let mut genesis =
                create_genesis_config_with_leader(0, &Pubkey::new_unique(), initial_balance);
            let rent = Rent::default();
            let min_rent_exempt_balance = rent.minimum_balance(0);
            genesis.genesis_config.rent = rent; // Ensure rent is non-zero

            let collector_id = Pubkey::new_unique();
            let mut pre_vote_account_lamports = 0;
            let mut vote_address = Pubkey::default();

            for (address, account) in genesis.genesis_config.accounts.iter_mut() {
                if account.owner == solana_sdk_ids::vote::id() {
                    let mut vote_state =
                        VoteStateV4::deserialize(account.data(), &Pubkey::default()).unwrap();
                    vote_state.block_revenue_collector = collector_id;
                    vote_state.block_revenue_commission_bps = commission;
                    let versioned = VoteStateVersions::V4(Box::new(vote_state));
                    account.set_state(&versioned).unwrap();
                    pre_vote_account_lamports = account.lamports();
                    vote_address = *address;
                    break;
                }
            };

            let mut bank = Bank::new_for_tests(&genesis.genesis_config);
            bank.feature_set = Arc::new(FeatureSet::all_enabled());

            let pre_collector_account = AccountSharedData::new(min_rent_exempt_balance, 0, &system_program::id());
            bank.store_account(&collector_id, &pre_collector_account);

            let burn = bank.deposit_or_burn_fee(total_fee);
            let new_collector_balance = bank.get_balance(&collector_id);
            let new_vote_account = bank.get_account(&vote_address).unwrap();
            let new_vote_state =
                VoteStateV4::deserialize(new_vote_account.data(), &Pubkey::default()).unwrap();
            let expected_validator_fee = u64::try_from((total_fee as u128).checked_mul(commission.min(10_000) as u128).unwrap() / 10_000u128).unwrap();
            let expected_delegator_fee = total_fee - expected_validator_fee;

            prop_assert_eq!(new_collector_balance - pre_collector_account.lamports() + new_vote_account.lamports() - pre_vote_account_lamports + burn, total_fee);

            if burn == total_fee {
                // neither deposit worked
                prop_assert_eq!(new_collector_balance, pre_collector_account.lamports());
                prop_assert_eq!(new_vote_account.lamports(), pre_vote_account_lamports);
                prop_assert_eq!(new_vote_state.pending_delegator_rewards, 0);
            } else if burn == 0 {
                // both deposits worked
                prop_assert_eq!(new_vote_state.pending_delegator_rewards, expected_delegator_fee);
                prop_assert_eq!(new_vote_account.lamports(), pre_vote_account_lamports + expected_delegator_fee);
                prop_assert_eq!(new_collector_balance, pre_collector_account.lamports() + expected_validator_fee);
            } else if burn == expected_validator_fee {
                // validator fee deposit failed
                prop_assert_eq!(new_collector_balance, pre_collector_account.lamports());
                prop_assert_eq!(new_vote_account.lamports(), pre_vote_account_lamports +expected_delegator_fee);
                prop_assert_eq!(new_vote_state.pending_delegator_rewards, expected_delegator_fee);
            } else if burn == expected_delegator_fee {
                // delegator fee deposit failed
                prop_assert_eq!(new_collector_balance, pre_collector_account.lamports() + expected_validator_fee);
                prop_assert_eq!(new_vote_account.lamports(), pre_vote_account_lamports);
                prop_assert_eq!(new_vote_state.pending_delegator_rewards, 0);
            } else {
                panic!("No other value should be possible for the burn");
            }
        }
    }

    #[test]
    fn test_deposit_fees() {
        let initial_balance = 1_000_000_000;
        let genesis = create_genesis_config(initial_balance);
        let bank = Bank::new_for_tests(&genesis.genesis_config);
        let pubkey = genesis.mint_keypair.pubkey();
        let deposit_amount = 500;

        assert_eq!(
            bank.deposit_fees(&pubkey, deposit_amount),
            Ok(initial_balance + deposit_amount),
            "New balance should be the sum of the initial balance and deposit amount"
        );
    }

    #[test]
    fn test_deposit_fees_with_overflow() {
        let initial_balance = u64::MAX;
        let genesis = create_genesis_config(initial_balance);
        let bank = Bank::new_for_tests(&genesis.genesis_config);
        let pubkey = genesis.mint_keypair.pubkey();
        let deposit_amount = 500;

        assert_eq!(
            bank.deposit_fees(&pubkey, deposit_amount),
            Err(DepositFeeError::LamportOverflow),
            "Expected an error due to lamport overflow"
        );
    }

    #[test_case(true, Ok(()); "allowed")]
    #[test_case(false, Err(DepositFeeError::InvalidAccountOwner); "prohibited")]
    fn test_deposit_fees_to_vote_account(
        custom_commission_collector: bool,
        expected: Result<(), DepositFeeError>,
    ) {
        let initial_balance = 1000;
        let genesis = create_genesis_config_with_leader(0, &pubkey::new_rand(), initial_balance);
        let mut bank = Bank::new_for_tests(&genesis.genesis_config);
        let mut feature_set = FeatureSet::all_enabled();
        if !custom_commission_collector {
            feature_set.deactivate(&agave_feature_set::custom_commission_collector::id());
        }
        bank.feature_set = Arc::new(feature_set);

        let pubkey = genesis.voting_keypair.pubkey();
        let deposit_amount = 500;
        let pre_lamports = bank.get_balance(&pubkey);
        assert_eq!(
            expected.map(|_| pre_lamports.saturating_add(deposit_amount)),
            bank.deposit_fees(&pubkey, deposit_amount)
        );
    }

    #[test]
    fn test_deposit_fees_reserved_account() {
        let initial_balance = 1000;
        let genesis = create_genesis_config_with_leader(0, &pubkey::new_rand(), initial_balance);
        let bank = Bank::new_for_tests(&genesis.genesis_config);
        let deposit_amount = 500;

        for id in bank.get_reserved_account_keys() {
            assert!(matches!(
                bank.deposit_fees(id, deposit_amount),
                Err(DepositFeeError::ReservedCollector) | Err(DepositFeeError::InvalidAccountOwner),
            ));
        }
    }

    #[test]
    fn test_deposit_fees_to_nonexistent_account_rent_exempt() {
        let mut genesis = create_genesis_config(0);
        let rent = Rent::default();
        genesis.genesis_config.rent = rent.clone();
        let bank = Bank::new_for_tests(&genesis.genesis_config);
        let nonexistent_pubkey = Pubkey::new_unique();

        // Fee is sufficient to make the new account rent-exempt
        let deposit_amount = rent.minimum_balance(0);

        assert!(
            bank.get_account(&nonexistent_pubkey).is_none(),
            "Account should not exist before deposit"
        );

        assert_eq!(
            bank.deposit_fees(&nonexistent_pubkey, deposit_amount),
            Ok(deposit_amount),
            "Deposit should succeed when fee is sufficient for rent-exemption"
        );

        let account = bank.get_account(&nonexistent_pubkey).unwrap();
        assert_eq!(account.lamports(), deposit_amount);
        assert_eq!(account.owner(), &system_program::id());
    }

    #[test]
    fn test_deposit_fees_to_nonexistent_account_not_rent_exempt() {
        let mut genesis = create_genesis_config(0);
        let rent = Rent::default();
        genesis.genesis_config.rent = rent.clone();
        let bank = Bank::new_for_tests(&genesis.genesis_config);
        let nonexistent_pubkey = Pubkey::new_unique();

        // Fee is insufficient to make the new account rent-exempt
        let deposit_amount = rent.minimum_balance(0) - 1;

        assert!(
            bank.get_account(&nonexistent_pubkey).is_none(),
            "Account should not exist before deposit"
        );

        assert_eq!(
            bank.deposit_fees(&nonexistent_pubkey, deposit_amount),
            Err(DepositFeeError::InvalidRentPayingAccount),
            "Deposit should fail when fee is insufficient for rent-exemption"
        );

        assert!(
            bank.get_account(&nonexistent_pubkey).is_none(),
            "Account should still not exist after failed deposit"
        );
    }

    #[test_case(true; "custom_commission_collector")]
    #[test_case(false; "no_custom_commission_collector")]
    fn test_deposit_or_burn_fee_respects_relaxed_post_exec_min_balance_check(
        custom_commission_collector: bool,
    ) {
        enum CollectorState {
            InitializedToSubRentExemptMinimum,
            UninitializedToSubRentExemptMinimum,
            UninitializedToRentExempt,
        }

        for collector_state in [
            CollectorState::InitializedToSubRentExemptMinimum,
            CollectorState::UninitializedToSubRentExemptMinimum,
            CollectorState::UninitializedToRentExempt,
        ] {
            for relax_post_exec_min_balance_check in [false, true] {
                let mut genesis = create_genesis_config_with_leader(0, &pubkey::new_rand(), 1000);
                let rent = Rent::default();
                genesis.genesis_config.rent = rent.clone();

                let initialized_data_len = 64;
                let rent_exempt_minimum = rent.minimum_balance(initialized_data_len);
                assert!(rent_exempt_minimum > 1);

                let (pre_balance, deposit, should_succeed) = match collector_state {
                    CollectorState::InitializedToSubRentExemptMinimum => (
                        rent_exempt_minimum - 2,
                        1,
                        relax_post_exec_min_balance_check,
                    ),
                    CollectorState::UninitializedToSubRentExemptMinimum => (0, 1, false),
                    CollectorState::UninitializedToRentExempt => (0, rent_exempt_minimum, true),
                };
                let post_balance = pre_balance + deposit;
                let maybe_collector_id = if custom_commission_collector {
                    let mut maybe_collector_id = None;
                    for account in genesis.genesis_config.accounts.values_mut() {
                        if account.owner == solana_sdk_ids::vote::id() {
                            let mut vote_state =
                                VoteStateV4::deserialize(account.data(), &Pubkey::default())
                                    .unwrap();
                            let collector_id = Pubkey::new_unique();
                            vote_state.block_revenue_collector = collector_id;
                            maybe_collector_id = Some(collector_id);
                            let versioned = VoteStateVersions::V4(Box::new(vote_state));
                            account.set_state(&versioned).unwrap();
                        }
                    }
                    maybe_collector_id
                } else {
                    None
                };

                let mut bank = Bank::new_for_tests(&genesis.genesis_config);

                let mut feature_set = FeatureSet::all_enabled();
                if !custom_commission_collector {
                    feature_set.deactivate(&agave_feature_set::custom_commission_collector::id());
                }
                if !relax_post_exec_min_balance_check {
                    feature_set
                        .deactivate(&agave_feature_set::relax_post_exec_min_balance_check::id());
                }
                bank.feature_set = Arc::new(feature_set);

                let collector_id = maybe_collector_id.unwrap_or(*bank.leader_id());
                let account = AccountSharedData::new(
                    pre_balance,
                    initialized_data_len,
                    &system_program::id(),
                );
                bank.store_account(&collector_id, &account);

                let burned = bank.deposit_or_burn_fee(deposit);
                let rewards = bank.rewards.read().unwrap();

                // post simd-392, deposits to existing accounts are always valid because
                // they are rent-exempt before and after the deposit takes place.
                // Deposits to uninitialized accounts still must make the account rent-exempt.
                // pre simd-392, if a deposit to a rent-paying account isn't sufficient to
                // make it rent-exempt then it fails and the deposit is burned.
                if should_succeed {
                    assert_eq!(burned, 0);
                    assert_eq!(bank.get_balance(&collector_id), post_balance);
                    assert_eq!(rewards.len(), 1, "fee should be distributed to the leader");
                    assert_eq!(rewards[0].1.post_balance, post_balance);
                } else {
                    assert_eq!(burned, deposit);
                    assert_eq!(bank.get_balance(&collector_id), pre_balance);
                    assert!(
                        rewards.is_empty(),
                        "fee should be burned when the rent transition is invalid"
                    );
                }
            }
        }
    }

    #[test]
    fn test_distribute_transaction_fee_details_normal() {
        let initial_balance = 1000;
        let genesis = create_genesis_config_with_leader(0, &pubkey::new_rand(), initial_balance);
        let mut bank = Bank::new_for_tests(&genesis.genesis_config);
        let transaction_fee = 100;
        let priority_fee = 200;
        bank.collector_fee_details = RwLock::new(CollectorFeeDetails {
            transaction_fee,
            priority_fee,
        });
        let expected_burn = transaction_fee * bank.burn_percent() / 100;
        let expected_rewards = transaction_fee - expected_burn + priority_fee;

        let collector_id = *bank.leader_id();

        let initial_capitalization = bank.capitalization();
        let initial_collector_balance = bank.get_balance(&collector_id);
        bank.distribute_transaction_fee_details();
        let new_collector_balance = bank.get_balance(&collector_id);

        assert_eq!(
            initial_collector_balance + expected_rewards,
            new_collector_balance
        );
        assert_eq!(
            initial_capitalization - expected_burn,
            bank.capitalization()
        );
        let locked_rewards = bank.rewards.read().unwrap();
        assert_eq!(
            locked_rewards.len(),
            1,
            "There should be one reward distributed"
        );

        let reward_info = &locked_rewards[0];
        assert_eq!(
            reward_info.1.lamports, expected_rewards as i64,
            "The reward amount should match the expected deposit"
        );
        assert_eq!(
            reward_info.1.reward_type,
            RewardType::Fee,
            "The reward type should be Fee"
        );
    }

    #[test]
    fn test_distribute_transaction_fee_details_zero() {
        let genesis = create_genesis_config(0);
        let bank = Bank::new_for_tests(&genesis.genesis_config);
        assert_eq!(
            *bank.collector_fee_details.read().unwrap(),
            CollectorFeeDetails::default()
        );

        let initial_capitalization = bank.capitalization();
        let initial_leader_id_balance = bank.get_balance(bank.leader_id());
        bank.distribute_transaction_fee_details();
        let new_leader_id_balance = bank.get_balance(bank.leader_id());

        assert_eq!(initial_leader_id_balance, new_leader_id_balance);
        assert_eq!(initial_capitalization, bank.capitalization());
        let locked_rewards = bank.rewards.read().unwrap();
        assert!(
            locked_rewards.is_empty(),
            "There should be no rewards distributed"
        );
    }

    #[test]
    fn test_distribute_transaction_fee_details_overflow_failure() {
        let initial_balance = 1000;
        let genesis = create_genesis_config_with_leader(0, &pubkey::new_rand(), initial_balance);
        let mut bank = Bank::new_for_tests(&genesis.genesis_config);
        let transaction_fee = 100;
        let priority_fee = 200;
        bank.collector_fee_details = RwLock::new(CollectorFeeDetails {
            transaction_fee,
            priority_fee,
        });

        let collector_id = *bank.leader_id();

        // ensure that account balance will overflow and fee distribution will fail
        let mut account = bank.get_account(&collector_id).unwrap_or_default();
        account.set_lamports(u64::MAX);
        bank.store_account(&collector_id, &account);

        let initial_capitalization = bank.capitalization();
        let initial_collector_balance = bank.get_balance(&collector_id);
        bank.distribute_transaction_fee_details();
        let new_collector_balance = bank.get_balance(&collector_id);

        assert_eq!(initial_collector_balance, new_collector_balance);
        assert_eq!(
            initial_capitalization - transaction_fee - priority_fee,
            bank.capitalization()
        );
        let locked_rewards = bank.rewards.read().unwrap();
        assert!(
            locked_rewards.is_empty(),
            "There should be no rewards distributed"
        );
    }

    #[test]
    fn test_deposit_delegator_fees_success() {
        let genesis = create_genesis_config_with_leader(0, &pubkey::new_rand(), 1000);
        let vote_address = Pubkey::new_unique();
        let vote_state = VoteStateV4::default();
        let pre_pending_delegator_rewards = vote_state.pending_delegator_rewards;
        let versioned = VoteStateVersions::V4(Box::new(vote_state));

        let pre_balance = 1_000_000_000;
        let mut pre_account = AccountSharedData::new(
            pre_balance,
            VoteStateV4::size_of(),
            &solana_sdk_ids::vote::id(),
        );
        pre_account.set_state(&versioned).unwrap();

        let bank = Bank::new_for_tests(&genesis.genesis_config);
        bank.store_account(&vote_address, &pre_account);

        let deposit_amount = 1;
        let post_balance = bank
            .deposit_delegator_fees(&vote_address, deposit_amount)
            .unwrap();

        let post_account = bank.get_account(&vote_address).unwrap();
        assert_eq!(post_account.lamports(), pre_balance + deposit_amount);
        assert_eq!(post_account.lamports(), post_balance);
        let post_state = VoteStateV4::deserialize(post_account.data(), &vote_address).unwrap();
        assert_eq!(
            post_state.pending_delegator_rewards,
            pre_pending_delegator_rewards + deposit_amount
        );
    }

    #[test]
    fn test_deposit_delegator_fees_failure() {
        let genesis = create_genesis_config_with_leader(0, &pubkey::new_rand(), 1000);
        let vote_address = Pubkey::new_unique();
        let vote_state = VoteStateV4::default();
        let versioned = VoteStateVersions::V4(Box::new(vote_state));

        let pre_balance = 1_000_000_000;
        let mut pre_account = AccountSharedData::new(
            pre_balance,
            VoteStateV4::size_of(),
            &solana_sdk_ids::vote::id(),
        );
        pre_account.set_state(&versioned).unwrap();

        let bank = Bank::new_for_tests(&genesis.genesis_config);

        // non-existent account fails
        assert_eq!(
            bank.deposit_delegator_fees(&vote_address, 1).unwrap_err(),
            DepositFeeError::InvalidVoteAccount,
        );

        bank.store_account(&vote_address, &pre_account);

        // overflow lamports
        assert_eq!(
            bank.deposit_delegator_fees(&vote_address, u64::MAX)
                .unwrap_err(),
            DepositFeeError::LamportOverflow,
        );

        // non-vote program owner fails
        pre_account.set_owner(Pubkey::new_unique());
        bank.store_account(&vote_address, &pre_account);
        assert_eq!(
            bank.deposit_delegator_fees(&vote_address, 1).unwrap_err(),
            DepositFeeError::InvalidVoteAccount,
        );

        // non-vote state v4 fails
        let vote_state = VoteStateV3::default();
        let versioned = VoteStateVersions::V3(Box::new(vote_state));

        let pre_balance = 1_000_000_000;
        let mut pre_account = AccountSharedData::new(
            pre_balance,
            VoteStateV3::size_of(),
            &solana_sdk_ids::vote::id(),
        );
        pre_account.set_state(&versioned).unwrap();
        bank.store_account(&vote_address, &pre_account);

        assert_eq!(
            bank.deposit_delegator_fees(&vote_address, 1).unwrap_err(),
            DepositFeeError::InvalidVoteAccount,
        );
    }
}