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
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
#[cfg(feature = "dev-context-only-utils")]
use qualifier_attr::qualifiers;
#[cfg(feature = "metrics")]
use solana_program_runtime::program_metrics::LoadProgramMetrics;
use {
    solana_account::{AccountSharedData, ReadableAccount},
    solana_clock::Slot,
    solana_instruction_error::InstructionError,
    solana_loader_v3_interface::state::UpgradeableLoaderState,
    solana_loader_v4_interface::state::{LoaderV4State, LoaderV4Status},
    solana_program_runtime::{
        loaded_programs::{ProgramCacheForTxBatch, ProgramRuntimeEnvironment, ProgramToLoad},
        program_cache_entry::{ProgramCacheEntry, ProgramCacheEntryOwner},
    },
    solana_pubkey::Pubkey,
    solana_sbpf::elf_parser::consts::ELFMAG,
    solana_sdk_ids::{bpf_loader, bpf_loader_deprecated, bpf_loader_upgradeable, loader_v4},
    solana_svm_callback::TransactionProcessingCallback,
    solana_svm_timings::ExecuteTimings,
    solana_svm_type_overrides::sync::Arc,
    solana_transaction_error::{TransactionError, TransactionResult},
    std::sync::atomic::Ordering,
};

#[derive(Debug)]
pub(crate) enum ProgramAccountLoadResult {
    InvalidAccountData(ProgramCacheEntryOwner),
    ProgramOfLoaderV1(AccountSharedData),
    ProgramOfLoaderV2(AccountSharedData),
    ProgramOfLoaderV3(AccountSharedData, AccountSharedData, Slot),
    ProgramOfLoaderV4(AccountSharedData, Slot),
}

pub(crate) fn load_program_accounts<CB: TransactionProcessingCallback>(
    callbacks: &CB,
    pubkey: &Pubkey,
) -> Option<ProgramAccountLoadResult> {
    let program_account = callbacks.get_account_shared_data(pubkey)?;

    let load_result = if loader_v4::check_id(program_account.owner()) {
        loader_v4_get_state(program_account.data())
            .ok()
            .and_then(|state| {
                (!matches!(state.status, LoaderV4Status::Retracted)).then_some(state.slot)
            })
            .map(|slot| ProgramAccountLoadResult::ProgramOfLoaderV4(program_account, slot))
            .unwrap_or(ProgramAccountLoadResult::InvalidAccountData(
                ProgramCacheEntryOwner::LoaderV4,
            ))
    } else if bpf_loader_upgradeable::check_id(program_account.owner()) {
        if let Ok(UpgradeableLoaderState::Program {
            programdata_address,
        }) = bincode::deserialize(program_account.data())
        {
            if let Some(programdata_account) =
                callbacks.get_account_shared_data(&programdata_address)
            {
                if bpf_loader_upgradeable::check_id(programdata_account.owner()) {
                    if let Ok(UpgradeableLoaderState::ProgramData {
                        slot,
                        upgrade_authority_address: _,
                    }) = bincode::deserialize(programdata_account.data())
                    {
                        ProgramAccountLoadResult::ProgramOfLoaderV3(
                            program_account,
                            programdata_account,
                            slot,
                        )
                    } else {
                        ProgramAccountLoadResult::InvalidAccountData(
                            ProgramCacheEntryOwner::LoaderV3,
                        )
                    }
                } else {
                    ProgramAccountLoadResult::InvalidAccountData(ProgramCacheEntryOwner::LoaderV3)
                }
            } else {
                ProgramAccountLoadResult::InvalidAccountData(ProgramCacheEntryOwner::LoaderV3)
            }
        } else {
            ProgramAccountLoadResult::InvalidAccountData(ProgramCacheEntryOwner::LoaderV3)
        }
    } else if bpf_loader::check_id(program_account.owner()) {
        ProgramAccountLoadResult::ProgramOfLoaderV2(program_account)
    } else if bpf_loader_deprecated::check_id(program_account.owner()) {
        ProgramAccountLoadResult::ProgramOfLoaderV1(program_account)
    } else {
        return None;
    };

    Some(load_result)
}

/// Loads the program with the given pubkey.
///
/// If the account doesn't exist it returns `None`. If the account does exist, it must be a program
/// account (belong to one of the program loaders). Returns `Some(InvalidAccountData)` if the program
/// account is `Closed`, contains invalid data or any of the programdata accounts are invalid.
pub fn load_program_with_pubkey<CB: TransactionProcessingCallback>(
    callbacks: &CB,
    program_runtime_environment: &ProgramRuntimeEnvironment,
    pubkey: &Pubkey,
    current_slot: Slot,
    execute_timings: &mut ExecuteTimings,
) -> Option<Arc<ProgramCacheEntry>> {
    #[cfg(feature = "metrics")]
    let mut load_program_metrics = LoadProgramMetrics {
        program_id: pubkey.to_string(),
        ..LoadProgramMetrics::default()
    };
    #[cfg(not(feature = "metrics"))]
    let _ = execute_timings;

    let load_result = load_program_accounts(callbacks, pubkey)?;
    let loaded_program = match load_result {
        ProgramAccountLoadResult::InvalidAccountData(owner) => {
            Ok(ProgramCacheEntry::new_closed_tombstone(current_slot, owner))
        }

        ProgramAccountLoadResult::ProgramOfLoaderV1(program_account) => ProgramCacheEntry::load(
            program_account.owner(),
            ProgramRuntimeEnvironment::clone(program_runtime_environment),
            0,
            program_account.data(),
            #[cfg(feature = "metrics")]
            &mut load_program_metrics,
        )
        .map_err(|_| (0, ProgramCacheEntryOwner::LoaderV1)),

        ProgramAccountLoadResult::ProgramOfLoaderV2(program_account) => ProgramCacheEntry::load(
            program_account.owner(),
            ProgramRuntimeEnvironment::clone(program_runtime_environment),
            0,
            program_account.data(),
            #[cfg(feature = "metrics")]
            &mut load_program_metrics,
        )
        .map_err(|_| (0, ProgramCacheEntryOwner::LoaderV2)),

        ProgramAccountLoadResult::ProgramOfLoaderV3(
            program_account,
            programdata_account,
            deployment_slot,
        ) => programdata_account
            .data()
            .get(UpgradeableLoaderState::size_of_programdata_metadata()..)
            .ok_or(())
            .and_then(|programdata| {
                ProgramCacheEntry::load(
                    program_account.owner(),
                    ProgramRuntimeEnvironment::clone(program_runtime_environment),
                    deployment_slot,
                    programdata,
                    #[cfg(feature = "metrics")]
                    &mut load_program_metrics,
                )
                .map_err(|_| ())
            })
            .map_err(|_| (deployment_slot, ProgramCacheEntryOwner::LoaderV3)),

        ProgramAccountLoadResult::ProgramOfLoaderV4(program_account, deployment_slot) => {
            program_account
                .data()
                .get(LoaderV4State::program_data_offset()..)
                .ok_or(())
                .and_then(|elf_bytes| {
                    ProgramCacheEntry::load(
                        &loader_v4::id(),
                        ProgramRuntimeEnvironment::clone(program_runtime_environment),
                        deployment_slot,
                        elf_bytes,
                        #[cfg(feature = "metrics")]
                        &mut load_program_metrics,
                    )
                    .map_err(|_| ())
                })
                .map_err(|_| (deployment_slot, ProgramCacheEntryOwner::LoaderV4))
        }
    }
    .unwrap_or_else(|(deployment_slot, owner)| {
        let env = ProgramRuntimeEnvironment::clone(program_runtime_environment);
        ProgramCacheEntry::new_failed_verification_tombstone(deployment_slot, owner, env)
    });

    #[cfg(feature = "metrics")]
    load_program_metrics.submit_datapoint(&mut execute_timings.details);
    loaded_program.update_access_slot(current_slot);
    Some(Arc::new(loaded_program))
}

fn get_program_deployment_slot<CB: TransactionProcessingCallback>(
    callbacks: &CB,
    program: &AccountSharedData,
    loader: ProgramCacheEntryOwner,
) -> TransactionResult<Slot> {
    match loader {
        ProgramCacheEntryOwner::LoaderV1 | ProgramCacheEntryOwner::LoaderV2 => {
            // V1 & V2 programs are immutable and hold no deployment metadata.
            // As long as there is *some* kind of ELF present, return slot 0.
            if program.data().starts_with(&ELFMAG) {
                Ok(0)
            } else {
                Err(TransactionError::ProgramAccountNotFound)
            }
        }
        ProgramCacheEntryOwner::LoaderV3 => {
            // V3 programs must have both a valid Program account as well as
            // a valid ProgramData account.
            if let Ok(UpgradeableLoaderState::Program {
                programdata_address,
            }) = bincode::deserialize(program.data())
            {
                let programdata = callbacks
                    .get_account_shared_data(&programdata_address)
                    .ok_or(TransactionError::ProgramAccountNotFound)?;
                if !bpf_loader_upgradeable::check_id(programdata.owner()) {
                    return Err(TransactionError::ProgramAccountNotFound);
                }
                if let Ok(UpgradeableLoaderState::ProgramData {
                    slot,
                    upgrade_authority_address: _,
                }) = bincode::deserialize(programdata.data())
                {
                    return Ok(slot);
                }
            }
            Err(TransactionError::ProgramAccountNotFound)
        }
        ProgramCacheEntryOwner::LoaderV4 => {
            // V4 programs must have valid state and must not be retracted!
            // Loader V4 state does not have a leading discriminator, and
            // `LoaderV4Status::Retracted` holds variant 0, so a gifting attack
            // can happen if we don't disallow `Retracted`.
            let slot = loader_v4_get_state(program.data())
                .ok()
                .and_then(|state| {
                    (!matches!(state.status, LoaderV4Status::Retracted)).then_some(state.slot)
                })
                .ok_or(TransactionError::ProgramAccountNotFound)?;
            Ok(slot)
        }
        ProgramCacheEntryOwner::NativeLoader => {
            // `filter_executable_program_accounts` won't pass native loader.
            unreachable!("native loader programs are not sbpf")
        }
    }
}

// Returns the set of programs to extract from the global program cache for a
// given transaction's account keys.
//
// This list should only contain valid, active programs. Closed programs MUST
// NOT be included in the search list.
//
// The global program cache searches for entries based on deployment slot, and
// a closed program has no deployment slot. If a closed program ends up in the
// search list, `replenish_program_cache` will miss during extraction, attempt
// to reload, and insert a closed tombstone, BUT it will not remove the program
// from the search list, resulting in reload loop.
#[cfg_attr(feature = "dev-context-only-utils", qualifiers(pub))]
pub(crate) fn filter_executable_program_accounts<'a, CB: TransactionProcessingCallback>(
    callbacks: &CB,
    program_cache_for_tx_batch: &ProgramCacheForTxBatch,
    keys: impl Iterator<Item = &'a Pubkey>,
) -> Vec<ProgramToLoad<'a>> {
    let mut result = Vec::new();
    for account_key in keys {
        if let Some(cache_entry) = program_cache_for_tx_batch.find(account_key) {
            cache_entry.stats.uses.fetch_add(1, Ordering::Relaxed);
        } else if let Some(account) = callbacks.get_account_shared_data(account_key) {
            // A valid program must be owned by one of the four BPF loaders.
            let loader = if loader_v4::check_id(account.owner()) {
                ProgramCacheEntryOwner::LoaderV4
            } else if bpf_loader_upgradeable::check_id(account.owner()) {
                ProgramCacheEntryOwner::LoaderV3
            } else if bpf_loader::check_id(account.owner()) {
                ProgramCacheEntryOwner::LoaderV2
            } else if bpf_loader_deprecated::check_id(account.owner()) {
                ProgramCacheEntryOwner::LoaderV1
            } else {
                continue;
            };
            // A valid program must also have a deployment slot stored.
            // If the deployment slot cannot be determined, this program is
            // likely *closed*; DON'T return it!
            let Ok(deployment_slot) = get_program_deployment_slot(callbacks, &account, loader)
            else {
                continue;
            };
            result.push(ProgramToLoad {
                program_id: account_key,
                loader,
                deployment_slot,
            });
        }
    }
    result
}

// Plucked from the now-removed Loader V4 program library.
fn loader_v4_get_state(data: &[u8]) -> Result<&LoaderV4State, InstructionError> {
    unsafe {
        let data = data
            .get(0..LoaderV4State::program_data_offset())
            .ok_or(InstructionError::AccountDataTooSmall)?
            .try_into()
            .unwrap();
        Ok(std::mem::transmute::<
            &[u8; LoaderV4State::program_data_offset()],
            &LoaderV4State,
        >(data))
    }
}

#[cfg(test)]
pub mod test_utils {
    use {
        super::*,
        solana_account::WritableAccount,
        std::{fs::File, io::Read},
    };

    pub fn load_test_program() -> Vec<u8> {
        let mut dir = std::env::current_dir().unwrap();
        dir.push("tests");
        dir.push("example-programs");
        dir.push("hello-solana");
        dir.push("hello_solana_program.so");
        let mut file = File::open(dir.clone()).expect("file not found");
        let metadata = std::fs::metadata(dir).expect("Unable to read metadata");
        let mut buffer = vec![0; metadata.len() as usize];
        file.read_exact(&mut buffer).expect("Buffer overflow");
        buffer
    }

    pub fn loader_v3_program_account(programdata_address: Pubkey) -> AccountSharedData {
        let mut account = AccountSharedData::default();
        account.set_owner(bpf_loader_upgradeable::id());
        account.set_data_from_slice(
            &bincode::serialize(&UpgradeableLoaderState::Program {
                programdata_address,
            })
            .unwrap(),
        );
        account
    }

    pub fn loader_v3_programdata_account(slot: Slot, elf: &[u8]) -> AccountSharedData {
        let offset = UpgradeableLoaderState::size_of_programdata_metadata();
        let mut data = vec![0u8; offset];
        bincode::serialize_into(
            &mut data[..offset],
            &UpgradeableLoaderState::ProgramData {
                slot,
                upgrade_authority_address: None,
            },
        )
        .unwrap();
        data.extend_from_slice(elf);

        let mut account = AccountSharedData::default();
        account.set_owner(bpf_loader_upgradeable::id());
        account.set_data_from_slice(&data);
        account
    }

    pub fn loader_v4_account(slot: Slot, status: LoaderV4Status, elf: &[u8]) -> AccountSharedData {
        let mut data = vec![0u8; LoaderV4State::program_data_offset()];
        data[0..8].copy_from_slice(&slot.to_le_bytes());
        data[8..40].copy_from_slice(Pubkey::new_unique().as_ref());
        data[40..48].copy_from_slice(&(status as u64).to_le_bytes());
        data.extend_from_slice(elf);

        let mut account = AccountSharedData::default();
        account.set_owner(loader_v4::id());
        account.set_data_from_slice(&data);
        account
    }
}

#[cfg(test)]
mod tests {
    use {
        super::{test_utils::*, *},
        crate::transaction_processor::TransactionBatchProcessor,
        solana_account::WritableAccount,
        solana_hash::Hash,
        solana_keypair::Keypair,
        solana_message::compiled_instruction::CompiledInstruction,
        solana_program_runtime::{
            loaded_programs::{
                BlockRelation, ForkGraph, ProgramRuntimeEnvironment,
                get_mock_program_runtime_environment,
            },
            program_cache_entry::ProgramCacheEntryType,
            solana_sbpf::program::BuiltinProgram,
        },
        solana_sdk_ids::{bpf_loader, bpf_loader_upgradeable, native_loader},
        solana_svm_transaction::svm_message::SVMMessage,
        solana_svm_type_overrides::sync::atomic::AtomicU64,
        solana_transaction::{Transaction, sanitized::SanitizedTransaction},
        std::{cell::RefCell, collections::HashMap},
    };

    struct TestForkGraph {}

    impl ForkGraph for TestForkGraph {
        fn relationship(&self, _a: Slot, _b: Slot) -> BlockRelation {
            BlockRelation::Unknown
        }
    }

    #[derive(Default, Clone)]
    pub(crate) struct MockBankCallback {
        pub(crate) account_shared_data: RefCell<HashMap<Pubkey, AccountSharedData>>,
    }

    impl TransactionProcessingCallback for MockBankCallback {
        fn get_account_shared_data(&self, pubkey: &Pubkey) -> Option<AccountSharedData> {
            self.account_shared_data.borrow().get(pubkey).cloned()
        }
    }

    macro_rules! unwrap_as {
        ($result:expr, $variant:ident($($field:ident),*) $(,)?) => {
            let ($($field,)*) = match $result {
                Some(ProgramAccountLoadResult::$variant($($field),*)) => {
                    ($($field,)*)
                }
                other => panic!("Invalid result: {other:?}"),
            };
        };
    }

    #[test]
    fn test_load_program_accounts_unknown_owner() {
        let mock_bank = MockBankCallback::default();
        let key = Pubkey::new_unique();
        let mut account_data = AccountSharedData::default();
        account_data.set_owner(Pubkey::new_unique());
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key, account_data);
        assert!(load_program_accounts(&mock_bank, &key).is_none());

        // The native loader is not one of the four this checks for, so a
        // builtin's account is unknown here in exactly the same way.
        let mut account_data = AccountSharedData::default();
        account_data.set_owner(native_loader::id());
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key, account_data);
        assert!(load_program_accounts(&mock_bank, &key).is_none());
    }

    #[test]
    fn test_load_program_accounts_loader_v1() {
        let mock_bank = MockBankCallback::default();
        let key = Pubkey::new_unique();

        // Fail: account not found
        assert!(load_program_accounts(&mock_bank, &key).is_none());

        let mut account_data = AccountSharedData::default();
        account_data.set_owner(bpf_loader_deprecated::id());
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key, account_data.clone());

        let result = load_program_accounts(&mock_bank, &key);
        unwrap_as!(result, ProgramOfLoaderV1(program));
        assert_eq!(program, account_data);
    }

    #[test]
    fn test_load_program_accounts_loader_v2() {
        let mock_bank = MockBankCallback::default();
        let key = Pubkey::new_unique();

        // Fail: account not found
        assert!(load_program_accounts(&mock_bank, &key).is_none());

        let mut account_data = AccountSharedData::default();
        account_data.set_owner(bpf_loader::id());
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key, account_data.clone());

        let result = load_program_accounts(&mock_bank, &key);
        unwrap_as!(result, ProgramOfLoaderV2(program));
        assert_eq!(program, account_data);
    }

    #[test]
    fn test_load_program_accounts_loader_v3() {
        let mock_bank = MockBankCallback::default();
        let program_key = Pubkey::new_unique();
        let programdata_key = Pubkey::new_unique();

        // Fail: program account not found
        assert!(load_program_accounts(&mock_bank, &program_key).is_none());

        // Fail: program account invalid state
        // The load gives up before it ever looks the programdata account up.
        let mut invalid_program_account = AccountSharedData::default();
        invalid_program_account.set_owner(bpf_loader_upgradeable::id());
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(program_key, invalid_program_account);
        let result = load_program_accounts(&mock_bank, &program_key);
        unwrap_as!(result, InvalidAccountData(owner));
        assert_eq!(owner, ProgramCacheEntryOwner::LoaderV3);

        let program_account = loader_v3_program_account(programdata_key);
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(program_key, program_account.clone());

        // Fail: programdata account missing
        let result = load_program_accounts(&mock_bank, &program_key);
        unwrap_as!(result, InvalidAccountData(owner));
        assert_eq!(owner, ProgramCacheEntryOwner::LoaderV3);

        // Fail: programdata wrong owner
        let mut programdata_account = loader_v3_programdata_account(7, &[]);
        programdata_account.set_owner(Pubkey::new_unique());
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(programdata_key, programdata_account);
        let result = load_program_accounts(&mock_bank, &program_key);
        unwrap_as!(result, InvalidAccountData(owner));
        assert_eq!(owner, ProgramCacheEntryOwner::LoaderV3);

        // Fail: programdata invalid state
        // Same here, fails the load but the last modified slot is returned.
        let mut programdata_account = AccountSharedData::default();
        programdata_account.set_owner(bpf_loader_upgradeable::id());
        programdata_account.set_data_from_slice(&[0u8; 4]); // `Uninitialized`
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(programdata_key, programdata_account);
        let result = load_program_accounts(&mock_bank, &program_key);
        unwrap_as!(result, InvalidAccountData(owner));
        assert_eq!(owner, ProgramCacheEntryOwner::LoaderV3);

        // Success
        let programdata_account = loader_v3_programdata_account(7, &[]);
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(programdata_key, programdata_account.clone());
        let result = load_program_accounts(&mock_bank, &program_key);
        unwrap_as!(
            result,
            ProgramOfLoaderV3(program, programdata, deployment_slot),
        );
        assert_eq!(program, program_account);
        assert_eq!(programdata, programdata_account);
        assert_eq!(deployment_slot, 7);
    }

    #[test]
    fn test_load_program_accounts_loader_v4() {
        let mock_bank = MockBankCallback::default();
        let key = Pubkey::new_unique();

        // Fail: account not found
        assert!(load_program_accounts(&mock_bank, &key).is_none());

        // Fail: invalid state
        let mut program_account = AccountSharedData::default();
        program_account.set_owner(loader_v4::id());
        program_account.set_data_from_slice(&[0u8; 4]); // `Uninitialized`
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key, program_account);
        let result = load_program_accounts(&mock_bank, &key);
        unwrap_as!(result, InvalidAccountData(owner));
        assert_eq!(owner, ProgramCacheEntryOwner::LoaderV4);

        // Fail: "gifted" state
        // Sized correctly, all-zeroes. Since `LoaderV4Status::Retracted` holds
        // variant `0`, we catch this case.
        let mut program_account = AccountSharedData::default();
        program_account.set_owner(loader_v4::id());
        program_account.set_data_from_slice(&[0u8; LoaderV4State::program_data_offset()]);
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key, program_account);
        let result = load_program_accounts(&mock_bank, &key);
        unwrap_as!(result, InvalidAccountData(owner));
        assert_eq!(owner, ProgramCacheEntryOwner::LoaderV4);

        // Fail: status is Retracted
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key, loader_v4_account(9, LoaderV4Status::Retracted, &[]));
        let result = load_program_accounts(&mock_bank, &key);
        unwrap_as!(result, InvalidAccountData(owner));
        assert_eq!(owner, ProgramCacheEntryOwner::LoaderV4);

        // Success: any status but `Retracted`, and the state's slot is the
        // deployment slot
        for status in [LoaderV4Status::Deployed, LoaderV4Status::Finalized] {
            let program_account = loader_v4_account(9, status, &[]);
            mock_bank
                .account_shared_data
                .borrow_mut()
                .insert(key, program_account.clone());
            let result = load_program_accounts(&mock_bank, &key);
            unwrap_as!(result, ProgramOfLoaderV4(program, deployment_slot));
            assert_eq!(program, program_account);
            assert_eq!(deployment_slot, 9);
        }
    }

    #[test]
    fn test_load_program_from_bytes() {
        let buffer = load_test_program();

        #[cfg(feature = "metrics")]
        let mut metrics = LoadProgramMetrics::default();
        let loader = bpf_loader_upgradeable::id();
        let slot: Slot = 2;
        let environment = ProgramRuntimeEnvironment::from(BuiltinProgram::new_mock());

        let result = ProgramCacheEntry::load(
            &loader,
            ProgramRuntimeEnvironment::clone(&environment),
            slot,
            &buffer,
            #[cfg(feature = "metrics")]
            &mut metrics,
        );

        assert!(result.is_ok());
    }

    #[test]
    fn test_load_program_not_found() {
        let mock_bank = MockBankCallback::default();
        let key = Pubkey::new_unique();
        let batch_processor = TransactionBatchProcessor::<TestForkGraph>::default();

        let result = load_program_with_pubkey(
            &mock_bank,
            &batch_processor.program_runtime_environment_for_epoch(50),
            &key,
            500,
            &mut ExecuteTimings::default(),
        );
        assert!(result.is_none());
    }

    #[test]
    fn test_load_program_invalid_account_data() {
        let program_key = Pubkey::new_unique();
        let programdata_key = Pubkey::new_unique();
        let mock_bank = MockBankCallback::default();
        let batch_processor = TransactionBatchProcessor::<TestForkGraph>::default();

        // Create a valid program account.
        let program_account = loader_v3_program_account(programdata_key);
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(program_key, program_account.clone());

        // Create the programdata account as loader-owned, but with no state.
        let mut programdata_account = AccountSharedData::default();
        programdata_account.set_owner(bpf_loader_upgradeable::id());
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(programdata_key, programdata_account);

        // Just like we saw earlier in `test_load_program_accounts_loader_v3`,
        // the load result should be `InvalidAccountData(owner)`.
        let result = load_program_accounts(&mock_bank, &program_key);
        unwrap_as!(result, InvalidAccountData(owner));
        assert_eq!(owner, ProgramCacheEntryOwner::LoaderV3);

        // This is key, because we should now get a `Closed` tombstone.
        let entry = load_program_with_pubkey(
            &mock_bank,
            &batch_processor.program_runtime_environment_for_epoch(20),
            &program_key,
            100, // Slot 100
            &mut ExecuteTimings::default(),
        )
        .unwrap();

        // Assert the result matches a `Closed` tombstone.
        let closed_tombstone = ProgramCacheEntry::new_closed_tombstone(
            100, // Slot 100
            ProgramCacheEntryOwner::LoaderV3,
        );
        assert_eq!(entry, Arc::new(closed_tombstone));

        // Assert that it is NOT a `FailedVerification` tombstone.
        let fv_tombstone = ProgramCacheEntry::new_failed_verification_tombstone(
            100, // Slot 100
            ProgramCacheEntryOwner::LoaderV3,
            batch_processor.program_runtime_environment_for_epoch(20),
        );
        assert_ne!(entry, Arc::new(fv_tombstone));

        // Assert that it is NOT a `DelayVisibility` tombstone.
        let dv_tombstone = ProgramCacheEntry::new_delay_visibility_tombstone(
            100, // Slot 100
            ProgramCacheEntryOwner::LoaderV3,
            Arc::default(),
        );
        assert_ne!(entry, Arc::new(dv_tombstone));
    }

    #[test]
    fn test_load_program_invalid_elf_bytes() {
        let program_key = Pubkey::new_unique();
        let programdata_key = Pubkey::new_unique();
        let mock_bank = MockBankCallback::default();
        let batch_processor = TransactionBatchProcessor::<TestForkGraph>::default();

        // Create a valid program account.
        let program_account = loader_v3_program_account(programdata_key);
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(program_key, program_account.clone());

        // Create a valid programdata account, but with invalid ELF bytes after
        // the metadata.
        let mut programdata_account = loader_v3_programdata_account(7, &[]);
        let mut data = programdata_account.data().to_vec();
        data.resize(UpgradeableLoaderState::size_of_programdata_metadata(), 0);
        data.extend_from_slice(&[0xff; 64]);
        programdata_account.set_data_from_slice(&data);
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(programdata_key, programdata_account);

        // The accounts themselves are fine, so the load result carries the
        // deployment slot the programdata account named.
        let result = load_program_accounts(&mock_bank, &program_key);
        unwrap_as!(
            result,
            ProgramOfLoaderV3(_program, _programdata, deployment_slot),
        );
        assert_eq!(deployment_slot, 7);

        // This is key, because the ELF fails to verify, so we should now get a
        // `FailedVerification` tombstone.
        let entry = load_program_with_pubkey(
            &mock_bank,
            &batch_processor.program_runtime_environment_for_epoch(20),
            &program_key,
            100, // Slot 100
            &mut ExecuteTimings::default(),
        )
        .unwrap();

        // Assert the result matches a `FailedVerification` tombstone.
        let fv_tombstone = ProgramCacheEntry::new_failed_verification_tombstone(
            7, // Deployment slot, not the current slot
            ProgramCacheEntryOwner::LoaderV3,
            batch_processor.program_runtime_environment_for_epoch(20),
        );
        assert_eq!(entry, Arc::new(fv_tombstone));

        // Assert that it is NOT a `Closed` tombstone.
        let closed_tombstone = ProgramCacheEntry::new_closed_tombstone(
            7, // Deployment slot, not the current slot
            ProgramCacheEntryOwner::LoaderV3,
        );
        assert_ne!(entry, Arc::new(closed_tombstone));

        // Assert that it is NOT a `DelayVisibility` tombstone.
        let dv_tombstone = ProgramCacheEntry::new_delay_visibility_tombstone(
            7, // Deployment slot, not the current slot
            ProgramCacheEntryOwner::LoaderV3,
            Arc::default(),
        );
        assert_ne!(entry, Arc::new(dv_tombstone));
    }

    #[test]
    fn test_load_program_program_loader_v1_or_v2() {
        let key = Pubkey::new_unique();
        let mock_bank = MockBankCallback::default();
        let mut account_data = AccountSharedData::default();
        account_data.set_owner(bpf_loader::id());
        let batch_processor = TransactionBatchProcessor::<TestForkGraph>::default();
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key, account_data.clone());

        // This should return an error
        let entry = load_program_with_pubkey(
            &mock_bank,
            &batch_processor.program_runtime_environment_for_epoch(20),
            &key,
            200,
            &mut ExecuteTimings::default(),
        )
        .unwrap();
        let loaded_program = ProgramCacheEntry::new_failed_verification_tombstone(
            0,
            ProgramCacheEntryOwner::LoaderV2,
            batch_processor.program_runtime_environment_for_epoch(20),
        );
        assert_eq!(entry, Arc::new(loaded_program));

        let buffer = load_test_program();
        account_data.set_data_from_slice(&buffer);

        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key, account_data.clone());

        let entry = load_program_with_pubkey(
            &mock_bank,
            &batch_processor.program_runtime_environment_for_epoch(20),
            &key,
            200,
            &mut ExecuteTimings::default(),
        )
        .unwrap();

        let program_runtime_environment = get_mock_program_runtime_environment();
        let expected = ProgramCacheEntry::load(
            account_data.owner(),
            ProgramRuntimeEnvironment::clone(&program_runtime_environment),
            0,
            account_data.data(),
            #[cfg(feature = "metrics")]
            &mut LoadProgramMetrics::default(),
        );

        assert_eq!(entry, Arc::new(expected.unwrap()));
    }

    #[test]
    fn test_load_program_program_loader_v3() {
        let key1 = Pubkey::new_unique();
        let key2 = Pubkey::new_unique();
        let mock_bank = MockBankCallback::default();
        let batch_processor = TransactionBatchProcessor::<TestForkGraph>::default();

        let mut account_data = AccountSharedData::default();
        account_data.set_owner(bpf_loader_upgradeable::id());

        let state = UpgradeableLoaderState::Program {
            programdata_address: key2,
        };
        account_data.set_data_from_slice(&bincode::serialize(&state).unwrap());
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key1, account_data.clone());

        let state = UpgradeableLoaderState::ProgramData {
            slot: 0,
            upgrade_authority_address: None,
        };
        let mut account_data2 = AccountSharedData::default();
        account_data2.set_data_from_slice(&bincode::serialize(&state).unwrap());
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key2, account_data2.clone());

        // The programdata account is not owned by the loader, so this is a
        // `Closed` tombstone rather than a `FailedVerification` one.
        let entry = load_program_with_pubkey(
            &mock_bank,
            &batch_processor.program_runtime_environment_for_epoch(0),
            &key1,
            0,
            &mut ExecuteTimings::default(),
        )
        .unwrap();
        let loaded_program =
            ProgramCacheEntry::new_closed_tombstone(0, ProgramCacheEntryOwner::LoaderV3);
        assert_eq!(entry, Arc::new(loaded_program));

        let mut buffer = load_test_program();
        let mut header = bincode::serialize(&state).unwrap();
        let mut complement = vec![
            0;
            std::cmp::max(
                0,
                UpgradeableLoaderState::size_of_programdata_metadata() - header.len()
            )
        ];
        header.append(&mut complement);
        header.append(&mut buffer);
        account_data.set_data_from_slice(&header);

        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key2, account_data.clone());

        let entry = load_program_with_pubkey(
            &mock_bank,
            &batch_processor.program_runtime_environment_for_epoch(20),
            &key1,
            200,
            &mut ExecuteTimings::default(),
        )
        .unwrap();

        let data = account_data.data().to_vec();
        account_data
            .set_data_from_slice(&data[UpgradeableLoaderState::size_of_programdata_metadata()..]);

        let program_runtime_environment = get_mock_program_runtime_environment();
        let expected = ProgramCacheEntry::load(
            account_data.owner(),
            ProgramRuntimeEnvironment::clone(&program_runtime_environment),
            0,
            account_data.data(),
            #[cfg(feature = "metrics")]
            &mut LoadProgramMetrics::default(),
        );
        assert_eq!(entry, Arc::new(expected.unwrap()));
    }

    #[test]
    fn test_load_program_program_loader_v4() {
        let key = Pubkey::new_unique();
        let mock_bank = MockBankCallback::default();
        let batch_processor = TransactionBatchProcessor::<TestForkGraph>::default();
        let environment = batch_processor.program_runtime_environment_for_epoch(20);

        // Retracted, closed tombstone.
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key, loader_v4_account(9, LoaderV4Status::Retracted, &[]));
        let entry = load_program_with_pubkey(
            &mock_bank,
            &environment,
            &key,
            200,
            &mut ExecuteTimings::default(),
        )
        .unwrap();
        assert!(matches!(entry.program, ProgramCacheEntryType::Closed));
        assert_eq!(entry.deployment_slot, 200);

        // No ELF, fail verification.
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key, loader_v4_account(9, LoaderV4Status::Deployed, &[]));
        let entry = load_program_with_pubkey(
            &mock_bank,
            &environment,
            &key,
            200,
            &mut ExecuteTimings::default(),
        )
        .unwrap();
        assert!(matches!(
            entry.program,
            ProgramCacheEntryType::FailedVerification(_)
        ));
        assert_eq!(entry.deployment_slot, 9);

        // Valid ELF, success.
        let mut account = loader_v4_account(9, LoaderV4Status::Deployed, &[]);
        let mut data = account.data().to_vec();
        data.extend_from_slice(&load_test_program());
        account.set_data_from_slice(&data);
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key, account);
        let entry = load_program_with_pubkey(
            &mock_bank,
            &environment,
            &key,
            200,
            &mut ExecuteTimings::default(),
        )
        .unwrap();
        assert!(matches!(entry.program, ProgramCacheEntryType::Loaded(_)));
        assert_eq!(entry.deployment_slot, 9);
        assert_eq!(entry.account_owner, ProgramCacheEntryOwner::LoaderV4);
    }

    #[test]
    fn test_load_program_environment() {
        let key = Pubkey::new_unique();
        let mock_bank = MockBankCallback::default();
        let mut account_data = AccountSharedData::default();
        account_data.set_owner(bpf_loader::id());
        let batch_processor = TransactionBatchProcessor::<TestForkGraph>::default();
        let upcoming_environment = get_mock_program_runtime_environment();
        let current_environment =
            ProgramRuntimeEnvironment::clone(&batch_processor.program_runtime_environment);
        {
            let mut epoch_boundary_preparation =
                batch_processor.epoch_boundary_preparation.write().unwrap();
            epoch_boundary_preparation.upcoming_epoch = 1;
            epoch_boundary_preparation.upcoming_environment = Some(upcoming_environment.clone());
        }
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key, account_data.clone());

        for is_upcoming_env in [false, true] {
            let result = load_program_with_pubkey(
                &mock_bank,
                &batch_processor.program_runtime_environment_for_epoch(is_upcoming_env as u64),
                &key,
                200,
                &mut ExecuteTimings::default(),
            )
            .unwrap();
            assert_ne!(
                is_upcoming_env,
                result.program.get_environment().unwrap() == &current_environment,
            );
            assert_eq!(
                is_upcoming_env,
                result.program.get_environment().unwrap() == &upcoming_environment,
            );
        }
    }

    #[test]
    fn test_get_program_deployment_slot_loader_v1_v2() {
        let mock_bank = MockBankCallback::default();
        for loader in [
            ProgramCacheEntryOwner::LoaderV1,
            ProgramCacheEntryOwner::LoaderV2,
        ] {
            // Fail: invalid state
            let mut account = AccountSharedData::default();
            assert_eq!(
                get_program_deployment_slot(&mock_bank, &account, loader).err(),
                Some(TransactionError::ProgramAccountNotFound)
            );

            // Success
            account.set_data_from_slice(&ELFMAG);
            assert_eq!(
                get_program_deployment_slot(&mock_bank, &account, loader).unwrap(),
                0 // <-- slot is always zero for both loaders
            );
        }
    }

    #[test]
    fn test_get_program_deployment_slot_loader_v3() {
        let mock_bank = MockBankCallback::default();
        let programdata_key = Pubkey::new_unique();
        let program_account = loader_v3_program_account(programdata_key);

        // Fail: program account invalid state
        let invalid_program_account =
            AccountSharedData::new(100, 100, &bpf_loader_upgradeable::id());
        assert_eq!(
            get_program_deployment_slot(
                &mock_bank,
                &invalid_program_account,
                ProgramCacheEntryOwner::LoaderV3
            )
            .err(),
            Some(TransactionError::ProgramAccountNotFound)
        );

        // Fail: programdata account missing
        assert_eq!(
            get_program_deployment_slot(
                &mock_bank,
                &program_account,
                ProgramCacheEntryOwner::LoaderV3
            )
            .err(),
            Some(TransactionError::ProgramAccountNotFound)
        );

        // Fail: programdata account not owned by the loader
        let mut programdata_account = loader_v3_programdata_account(7, &[]);
        programdata_account.set_owner(Pubkey::new_unique());
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(programdata_key, programdata_account);
        assert_eq!(
            get_program_deployment_slot(
                &mock_bank,
                &program_account,
                ProgramCacheEntryOwner::LoaderV3
            )
            .err(),
            Some(TransactionError::ProgramAccountNotFound)
        );

        // Fail: programdata invalid state
        let mut programdata_account = AccountSharedData::default();
        programdata_account.set_owner(bpf_loader_upgradeable::id());
        programdata_account.set_data_from_slice(&[0u8; 4]); // `Uninitialized`
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(programdata_key, programdata_account);
        assert_eq!(
            get_program_deployment_slot(
                &mock_bank,
                &program_account,
                ProgramCacheEntryOwner::LoaderV3
            )
            .err(),
            Some(TransactionError::ProgramAccountNotFound)
        );

        // Success
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(programdata_key, loader_v3_programdata_account(7, &[]));
        assert_eq!(
            get_program_deployment_slot(
                &mock_bank,
                &program_account,
                ProgramCacheEntryOwner::LoaderV3
            )
            .unwrap(),
            7
        );
    }

    #[test]
    fn test_get_program_deployment_slot_loader_v4() {
        let mock_bank = MockBankCallback::default();

        // Fail: invalid state
        let mut program_account = AccountSharedData::default();
        program_account.set_owner(loader_v4::id());
        program_account.set_data_from_slice(&[0u8; 4]); // `Uninitialized`
        assert_eq!(
            get_program_deployment_slot(
                &mock_bank,
                &program_account,
                ProgramCacheEntryOwner::LoaderV4
            )
            .err(),
            Some(TransactionError::ProgramAccountNotFound)
        );

        // Fail: "gifted" state
        // Sized correctly, all-zeroes. Since `LoaderV4Status::Retracted` holds
        // variant `0`, we do NOT currently catch this case.
        let mut program_account = AccountSharedData::default();
        program_account.set_owner(loader_v4::id());
        program_account.set_data_from_slice(&[0u8; LoaderV4State::program_data_offset()]);
        assert_eq!(
            get_program_deployment_slot(
                &mock_bank,
                &program_account,
                ProgramCacheEntryOwner::LoaderV4
            )
            .err(),
            Some(TransactionError::ProgramAccountNotFound)
        );

        // Fail: status is Retracted
        let account = loader_v4_account(9, LoaderV4Status::Retracted, &[]);
        assert_eq!(
            get_program_deployment_slot(&mock_bank, &account, ProgramCacheEntryOwner::LoaderV4)
                .err(),
            Some(TransactionError::ProgramAccountNotFound)
        );

        // Success
        for status in [LoaderV4Status::Deployed, LoaderV4Status::Finalized] {
            let account = loader_v4_account(9, status, &[]);
            assert_eq!(
                get_program_deployment_slot(&mock_bank, &account, ProgramCacheEntryOwner::LoaderV4)
                    .unwrap(),
                9
            );
        }
    }

    #[test]
    #[should_panic(expected = "internal error: entered unreachable code")]
    fn test_get_program_deployment_slot_native_loader() {
        let mock_bank = MockBankCallback::default();
        let mut account = AccountSharedData::default();
        account.set_owner(native_loader::id());
        let _ =
            get_program_deployment_slot(&mock_bank, &account, ProgramCacheEntryOwner::NativeLoader);
    }

    #[test]
    fn test_filter_executable_program_accounts() {
        let feepayer = Keypair::new();
        let loader_ids = [
            bpf_loader_deprecated::id(),
            bpf_loader::id(),
            bpf_loader_upgradeable::id(),
            native_loader::id(),
        ];
        let program_ids = [
            Pubkey::new_unique(),
            Pubkey::new_unique(),
            Pubkey::new_unique(),
            Pubkey::new_unique(),
        ];
        let account_ids = [
            Pubkey::new_unique(),
            Pubkey::new_unique(),
            Pubkey::new_unique(),
            Pubkey::new_unique(),
        ];

        let mut loaded_programs_for_tx_batch = ProgramCacheForTxBatch::default();
        let mock_bank = MockBankCallback::default();
        for i in 0..3 {
            loaded_programs_for_tx_batch.replenish(
                loader_ids[i],
                Arc::new(ProgramCacheEntry {
                    program: ProgramCacheEntryType::Builtin(BuiltinProgram::new_mock()),
                    account_owner: ProgramCacheEntryOwner::NativeLoader,
                    deployment_slot: 0,
                    stats: Arc::default(),
                    latest_access_slot: AtomicU64::default(),
                }),
            );
            mock_bank
                .account_shared_data
                .borrow_mut()
                .insert(loader_ids[i], AccountSharedData::new(1, 1, &program_ids[3]));
            let mut program = AccountSharedData::new(1, 1, &loader_ids[i]);
            program.set_data_from_slice(&ELFMAG);
            mock_bank
                .account_shared_data
                .borrow_mut()
                .insert(program_ids[i], program);
            mock_bank.account_shared_data.borrow_mut().insert(
                account_ids[i],
                AccountSharedData::new(1, 1, &program_ids[i]),
            );
        }

        let programdata_address = Pubkey::new_unique();
        let state = UpgradeableLoaderState::Program {
            programdata_address,
        };
        let mut program = AccountSharedData::new(1, 1, &loader_ids[2]);
        program.set_data_from_slice(&bincode::serialize(&state).unwrap());
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(program_ids[2], program);
        let state = UpgradeableLoaderState::ProgramData {
            slot: 0,
            upgrade_authority_address: None,
        };
        let mut programdata = AccountSharedData::new(1, 1, &loader_ids[2]);
        programdata.set_data_from_slice(&bincode::serialize(&state).unwrap());
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(programdata_address, programdata);

        let tx = Transaction::new_with_compiled_instructions(
            &[&feepayer],
            &[program_ids[1], program_ids[2], loader_ids[2]],
            Hash::new_unique(),
            vec![
                account_ids[0],
                account_ids[1],
                account_ids[2],
                account_ids[3],
            ],
            vec![
                CompiledInstruction::new(1, &(), vec![0, 1, 2, 3]),
                CompiledInstruction::new(2, &(), vec![0, 1, 2, 3]),
                CompiledInstruction::new(3, &(), vec![0, 1, 2, 3]),
            ],
        );
        let sanitized_tx = SanitizedTransaction::from_transaction_for_tests(tx);

        let missing_programs = filter_executable_program_accounts(
            &mock_bank,
            &loaded_programs_for_tx_batch,
            sanitized_tx.account_keys().iter(),
        );
        assert_eq!(
            missing_programs,
            &[
                ProgramToLoad {
                    program_id: &program_ids[1],
                    loader: ProgramCacheEntryOwner::LoaderV2,
                    deployment_slot: 0,
                },
                ProgramToLoad {
                    program_id: &program_ids[2],
                    loader: ProgramCacheEntryOwner::LoaderV3,
                    deployment_slot: 0,
                },
            ]
        );
    }

    #[test]
    fn test_filter_executable_program_accounts_cache_hit() {
        let mock_bank = MockBankCallback::default();
        let mut batch = ProgramCacheForTxBatch::new(10);
        let key = Pubkey::new_unique();

        let mut account = AccountSharedData::default();
        account.set_owner(bpf_loader::id());
        account.set_data_from_slice(&[1u8; 4]);
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key, account);

        let entry = Arc::new(ProgramCacheEntry::new_closed_tombstone(
            0,
            ProgramCacheEntryOwner::LoaderV2,
        ));
        batch.replenish(key, Arc::clone(&entry));

        // Already in the batch, so it is counted as used and not asked for
        // again. The account is never looked at.
        let keys = [key];
        let result = filter_executable_program_accounts(&mock_bank, &batch, keys.iter());
        assert!(result.is_empty());
        assert_eq!(entry.stats.uses.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn test_filter_executable_program_accounts_account_not_found() {
        let mock_bank = MockBankCallback::default();
        let batch = ProgramCacheForTxBatch::new(10);

        // The account does not exist, so there is no program to queue.
        let keys = [Pubkey::new_unique()];
        assert!(filter_executable_program_accounts(&mock_bank, &batch, keys.iter()).is_empty());
    }

    #[test]
    fn test_filter_executable_program_accounts_invalid_owner() {
        let mock_bank = MockBankCallback::default();
        let batch = ProgramCacheForTxBatch::new(10);

        // The account exists, but is not owned by any loader, so there is no
        // program to queue.
        let key = Pubkey::new_unique();
        let mut account = AccountSharedData::default();
        account.set_owner(Pubkey::new_unique());
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key, account);

        let keys = [key];
        assert!(filter_executable_program_accounts(&mock_bank, &batch, keys.iter()).is_empty());
    }

    #[test]
    fn test_filter_executable_program_accounts_loader_v1_v2() {
        let mock_bank = MockBankCallback::default();
        let batch = ProgramCacheForTxBatch::new(10);
        let key = Pubkey::new_unique();
        let keys = [key];

        for (owner, loader) in [
            (
                bpf_loader_deprecated::id(),
                ProgramCacheEntryOwner::LoaderV1,
            ),
            (bpf_loader::id(), ProgramCacheEntryOwner::LoaderV2),
        ] {
            // Empty data returns `ProgramAccountNotFound` for deployment slot,
            // so nothing is queued.
            let mut empty = AccountSharedData::default();
            empty.set_owner(owner);
            mock_bank
                .account_shared_data
                .borrow_mut()
                .insert(key, empty);
            assert!(filter_executable_program_accounts(&mock_bank, &batch, keys.iter()).is_empty());

            // Same goes for non-empty but zero filled data.
            let mut account = AccountSharedData::default();
            account.set_owner(owner);
            account.set_data_from_slice(&[0u8; 4]); // `Uninitialized`
            mock_bank
                .account_shared_data
                .borrow_mut()
                .insert(key, account.clone());
            assert!(filter_executable_program_accounts(&mock_bank, &batch, keys.iter()).is_empty());

            // Account must start with ELFMAG to be considered a program.
            account.set_data_from_slice(&ELFMAG);
            mock_bank
                .account_shared_data
                .borrow_mut()
                .insert(key, account);
            let result = filter_executable_program_accounts(&mock_bank, &batch, keys.iter());
            assert_eq!(result.len(), 1);
            let program_to_load = result.first().unwrap();
            assert_eq!(program_to_load.loader, loader);
            assert_eq!(program_to_load.deployment_slot, 0);
        }
    }

    #[test]
    fn test_filter_executable_program_accounts_loader_v3() {
        let mock_bank = MockBankCallback::default();
        let batch = ProgramCacheForTxBatch::new(10);
        let key = Pubkey::new_unique();
        let programdata_key = Pubkey::new_unique();
        let keys = [key];
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key, loader_v3_program_account(programdata_key));

        // Case: programdata account does not exist.
        // Can't read deployment slot, nothing is queued.
        assert!(filter_executable_program_accounts(&mock_bank, &batch, keys.iter()).is_empty());

        // Case: programdata account exists, but wrong owner.
        // Can't read deployment slot, nothing is queued.
        let mut programdata_account = loader_v3_programdata_account(7, &[]);
        programdata_account.set_owner(Pubkey::new_unique());
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(programdata_key, programdata_account);
        assert!(filter_executable_program_accounts(&mock_bank, &batch, keys.iter()).is_empty());

        // Case: programdata account exists, but wrong state.
        // Can't read deployment slot, nothing is queued.
        let mut programdata_account = AccountSharedData::default();
        programdata_account.set_owner(bpf_loader_upgradeable::id());
        programdata_account.set_data_from_slice(&[0u8; 4]); // `Uninitialized`
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(programdata_key, programdata_account);
        assert!(filter_executable_program_accounts(&mock_bank, &batch, keys.iter()).is_empty());

        // Successfully queued.
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(programdata_key, loader_v3_programdata_account(7, &[]));
        let result = filter_executable_program_accounts(&mock_bank, &batch, keys.iter());
        assert_eq!(result.len(), 1);
        let program_to_load = result.first().unwrap();
        assert_eq!(program_to_load.loader, ProgramCacheEntryOwner::LoaderV3);
        assert_eq!(program_to_load.deployment_slot, 7);
    }

    #[test]
    fn test_filter_executable_program_accounts_loader_v4() {
        let mock_bank = MockBankCallback::default();
        let batch = ProgramCacheForTxBatch::new(10);
        let key = Pubkey::new_unique();
        let keys = [key];

        // Case: program account exists, but wrong state.
        // Can't read deployment slot, nothing is queued.
        let mut too_small = AccountSharedData::default();
        too_small.set_owner(loader_v4::id());
        too_small.set_data_from_slice(&[0u8; 4]);
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key, too_small);
        assert!(filter_executable_program_accounts(&mock_bank, &batch, keys.iter()).is_empty());

        // Case: program account is sized correctly, but all-zeroes. Since
        // `LoaderV4Status::Retracted` holds variant `0`, this is a retracted
        // program, and nothing should be queued.
        let mut gifted = AccountSharedData::default();
        gifted.set_owner(loader_v4::id());
        gifted.set_data_from_slice(&[0u8; LoaderV4State::program_data_offset()]);
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key, gifted);
        assert!(filter_executable_program_accounts(&mock_bank, &batch, keys.iter()).is_empty());

        // Case: program account holds valid state, but is `Retracted`.
        // `load_program_accounts` calls this invalid, so nothing should be
        // queued here either.
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key, loader_v4_account(9, LoaderV4Status::Retracted, &[]));
        assert!(filter_executable_program_accounts(&mock_bank, &batch, keys.iter()).is_empty());

        // Successfully queued.
        mock_bank
            .account_shared_data
            .borrow_mut()
            .insert(key, loader_v4_account(9, LoaderV4Status::Deployed, &[]));
        let result = filter_executable_program_accounts(&mock_bank, &batch, keys.iter());
        assert_eq!(result.len(), 1);
        let program_to_load = result.first().unwrap();
        assert_eq!(program_to_load.loader, ProgramCacheEntryOwner::LoaderV4);
        assert_eq!(program_to_load.deployment_slot, 9);
    }

    #[test]
    fn test_loader_v4_get_state() {
        // Anything shorter than the state itself is rejected.
        for len in [0, LoaderV4State::program_data_offset().saturating_sub(1)] {
            assert!(matches!(
                loader_v4_get_state(&vec![0u8; len]),
                Err(InstructionError::AccountDataTooSmall)
            ));
        }

        // Exactly the state, and the state with program data after it, both
        // read back the fields which were written.
        for extra_bytes in [0, 8] {
            let mut account = loader_v4_account(42, LoaderV4Status::Deployed, &[]);
            let mut data = account.data().to_vec();
            data.resize(data.len().saturating_add(extra_bytes), 0);
            account.set_data_from_slice(&data);

            let state = loader_v4_get_state(account.data()).unwrap();
            assert_eq!(state.slot, 42);
            assert!(matches!(state.status, LoaderV4Status::Deployed));
        }
    }
}