forked from solana-foundation/surfpool
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsvm.rs
More file actions
4853 lines (4380 loc) · 193 KB
/
svm.rs
File metadata and controls
4853 lines (4380 loc) · 193 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{
cmp::max,
collections::{BTreeMap, HashMap, HashSet, VecDeque},
str::FromStr,
time::SystemTime,
};
use agave_feature_set::{FeatureSet, enable_extend_program_checked};
use base64::{Engine, prelude::BASE64_STANDARD};
use chrono::Utc;
use convert_case::Casing;
use crossbeam_channel::{Receiver, Sender, unbounded};
use litesvm::types::{
FailedTransactionMetadata, SimulatedTransactionInfo, TransactionMetadata, TransactionResult,
};
use solana_account::{Account, AccountSharedData, ReadableAccount};
use solana_account_decoder::{
UiAccount, UiAccountData, UiAccountEncoding, UiDataSliceConfig, encode_ui_account,
parse_account_data::{AccountAdditionalDataV3, ParsedAccount, SplTokenAdditionalDataV2},
};
use solana_client::{
rpc_client::SerializableTransaction,
rpc_config::{RpcAccountInfoConfig, RpcBlockConfig, RpcTransactionLogsFilter},
rpc_filter::RpcFilterType,
rpc_response::{RpcKeyedAccount, RpcLogsResponse, RpcPerfSample},
};
use solana_clock::{Clock, Slot};
use solana_commitment_config::{CommitmentConfig, CommitmentLevel};
use solana_epoch_info::EpochInfo;
use solana_epoch_schedule::EpochSchedule;
use solana_feature_gate_interface::Feature;
use solana_genesis_config::GenesisConfig;
use solana_hash::Hash;
use solana_inflation::Inflation;
use solana_loader_v3_interface::state::UpgradeableLoaderState;
use solana_message::{
Message, VersionedMessage, inline_nonce::is_advance_nonce_instruction_data, v0::LoadedAddresses,
};
use solana_program_option::COption;
use solana_pubkey::Pubkey;
use solana_rpc_client_api::response::SlotInfo;
use solana_sdk_ids::{bpf_loader, system_program};
use solana_signature::Signature;
use solana_system_interface::instruction as system_instruction;
use solana_transaction::versioned::VersionedTransaction;
use solana_transaction_error::TransactionError;
use solana_transaction_status::{TransactionDetails, TransactionStatusMeta, UiConfirmedBlock};
use spl_token_2022_interface::extension::{
BaseStateWithExtensions, StateWithExtensions, interest_bearing_mint::InterestBearingConfig,
scaled_ui_amount::ScaledUiAmountConfig,
};
use surfpool_types::{
AccountChange, AccountProfileState, AccountSnapshot, DEFAULT_PROFILING_MAP_CAPACITY,
DEFAULT_SLOT_TIME_MS, ExportSnapshotConfig, ExportSnapshotScope, FifoMap, Idl,
OverrideInstance, ProfileResult, RpcProfileDepth, RpcProfileResultConfig,
RunbookExecutionStatusReport, SimnetEvent, SvmFeatureConfig, TransactionConfirmationStatus,
TransactionStatusEvent, UiAccountChange, UiAccountProfileState, UiProfileResult, VersionedIdl,
types::{
ComputeUnitsEstimationResult, KeyedProfileResult, UiKeyedProfileResult, UuidOrSignature,
},
};
use txtx_addon_kit::{
indexmap::IndexMap,
types::types::{AddonJsonConverter, Value},
};
use txtx_addon_network_svm::codec::idl::borsh_encode_value_to_idl_type;
use txtx_addon_network_svm_types::subgraph::idl::{
parse_bytes_to_value_with_expected_idl_type_def_ty,
parse_bytes_to_value_with_expected_idl_type_def_ty_with_leftover_bytes,
};
use uuid::Uuid;
use super::{
AccountSubscriptionData, BlockHeader, BlockIdentifier, FINALIZATION_SLOT_THRESHOLD,
GetAccountResult, GeyserBlockMetadata, GeyserEntryInfo, GeyserEvent, GeyserSlotStatus,
ProgramSubscriptionData, SLOTS_PER_EPOCH, SignatureSubscriptionData, SignatureSubscriptionType,
remote::SurfnetRemoteClient,
};
use crate::{
error::{SurfpoolError, SurfpoolResult},
rpc::utils::convert_transaction_metadata_from_canonical,
scenarios::TemplateRegistry,
storage::{OverlayStorage, Storage, new_kv_store, new_kv_store_with_default},
surfnet::{
LogsSubscriptionData, locker::is_supported_token_program, surfnet_lite_svm::SurfnetLiteSvm,
},
types::{
GeyserAccountUpdate, MintAccount, SerializableAccountAdditionalData,
SurfnetTransactionStatus, SyntheticBlockhash, TokenAccount, TransactionWithStatusMeta,
},
};
lazy_static::lazy_static! {
/// Interval (in slots) at which to perform garbage collection on the lite SVM cache.
/// About 1 hour at standard 400ms slot time.
/// Configurable via SURFPOOL_GARBAGE_COLLECTION_INTERVAL_SLOTS env var.
pub static ref GARBAGE_COLLECTION_INTERVAL_SLOTS: u64 = {
std::env::var("SURFPOOL_GARBAGE_COLLECTION_INTERVAL_SLOTS")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(9_000)
};
/// Interval (in slots) at which to checkpoint the latest slot to storage.
/// About 1 minute at standard 400ms slot time (60000ms / 400ms = 150 slots).
/// Configurable via SURFPOOL_CHECKPOINT_INTERVAL_SLOTS env var.
pub static ref CHECKPOINT_INTERVAL_SLOTS: u64 = {
std::env::var("SURFPOOL_CHECKPOINT_INTERVAL_SLOTS")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(150)
};
}
/// Helper function to apply an override to a decoded account value using dot notation
pub fn apply_override_to_decoded_account(
decoded_value: &mut Value,
path: &str,
value: &serde_json::Value,
) -> SurfpoolResult<()> {
let parts: Vec<&str> = path.split('.').collect();
if parts.is_empty() {
return Err(SurfpoolError::internal("Empty path provided for override"));
}
// Navigate to the parent of the target field
let mut current = decoded_value;
for part in &parts[..parts.len() - 1] {
match current {
Value::Object(map) => {
current = map.get_mut(&part.to_string()).ok_or_else(|| {
SurfpoolError::internal(format!(
"Path segment '{}' not found in decoded account",
part
))
})?;
}
_ => {
return Err(SurfpoolError::internal(format!(
"Cannot navigate through field '{}' - not an object",
part
)));
}
}
}
// Set the final field
let final_key = parts[parts.len() - 1];
match current {
Value::Object(map) => {
// Convert serde_json::Value to txtx Value
let txtx_value = json_to_txtx_value(value)?;
map.insert(final_key.to_string(), txtx_value);
Ok(())
}
_ => Err(SurfpoolError::internal(format!(
"Cannot set field '{}' - parent is not an object",
final_key
))),
}
}
/// Helper function to convert serde_json::Value to txtx Value
fn json_to_txtx_value(json: &serde_json::Value) -> SurfpoolResult<Value> {
match json {
serde_json::Value::Null => Ok(Value::Null),
serde_json::Value::Bool(b) => Ok(Value::Bool(*b)),
serde_json::Value::Number(n) => {
if let Some(i) = n.as_i64() {
Ok(Value::Integer(i as i128))
} else if let Some(u) = n.as_u64() {
Ok(Value::Integer(u as i128))
} else if let Some(f) = n.as_f64() {
Ok(Value::Float(f))
} else {
Err(SurfpoolError::internal(format!(
"Unable to convert number: {}",
n
)))
}
}
serde_json::Value::String(s) => Ok(Value::String(s.clone())),
serde_json::Value::Array(arr) => {
let txtx_arr: Result<Vec<Value>, _> = arr.iter().map(json_to_txtx_value).collect();
Ok(Value::Array(Box::new(txtx_arr?)))
}
serde_json::Value::Object(obj) => {
let mut txtx_obj = IndexMap::new();
for (k, v) in obj.iter() {
txtx_obj.insert(k.clone(), json_to_txtx_value(v)?);
}
Ok(Value::Object(txtx_obj))
}
}
}
pub type AccountOwner = Pubkey;
#[allow(deprecated)]
use solana_sysvar::recent_blockhashes::MAX_ENTRIES;
#[allow(deprecated)]
pub const MAX_RECENT_BLOCKHASHES_STANDARD: usize = MAX_ENTRIES;
pub fn get_txtx_value_json_converters() -> Vec<AddonJsonConverter<'static>> {
vec![
Box::new(move |value: &txtx_addon_kit::types::types::Value| {
txtx_addon_network_svm_types::SvmValue::to_json(value)
}) as AddonJsonConverter<'static>,
]
}
/// `SurfnetSvm` provides a lightweight Solana Virtual Machine (SVM) for testing and simulation.
///
/// It supports a local in-memory blockchain state,
/// remote RPC connections, transaction processing, and account management.
///
/// It also exposes channels to listen for simulation events (`SimnetEvent`) and Geyser plugin events (`GeyserEvent`).
#[derive(Clone)]
pub struct SurfnetSvm {
pub inner: SurfnetLiteSvm,
pub remote_rpc_url: Option<String>,
pub chain_tip: BlockIdentifier,
pub blocks: Box<dyn Storage<u64, BlockHeader>>,
pub transactions: Box<dyn Storage<String, SurfnetTransactionStatus>>,
pub transactions_queued_for_confirmation: VecDeque<(
VersionedTransaction,
Sender<TransactionStatusEvent>,
Option<TransactionError>,
)>,
pub transactions_queued_for_finalization: VecDeque<(
Slot,
VersionedTransaction,
Sender<TransactionStatusEvent>,
Option<TransactionError>,
)>,
pub perf_samples: VecDeque<RpcPerfSample>,
pub transactions_processed: u64,
pub latest_epoch_info: EpochInfo,
pub simnet_events_tx: Sender<SimnetEvent>,
pub geyser_events_tx: Sender<GeyserEvent>,
pub signature_subscriptions: HashMap<Signature, Vec<SignatureSubscriptionData>>,
pub account_subscriptions: AccountSubscriptionData,
pub program_subscriptions: ProgramSubscriptionData,
pub slot_subscriptions: Vec<Sender<SlotInfo>>,
pub profile_tag_map: Box<dyn Storage<String, Vec<UuidOrSignature>>>,
pub simulated_transaction_profiles: Box<dyn Storage<String, KeyedProfileResult>>,
pub executed_transaction_profiles: Box<dyn Storage<String, KeyedProfileResult>>,
pub logs_subscriptions: Vec<LogsSubscriptionData>,
pub snapshot_subscriptions: Vec<super::SnapshotSubscriptionData>,
pub updated_at: u64,
pub slot_time: u64,
pub start_time: SystemTime,
pub accounts_by_owner: Box<dyn Storage<String, Vec<String>>>,
pub account_associated_data: Box<dyn Storage<String, SerializableAccountAdditionalData>>,
pub token_accounts: Box<dyn Storage<String, TokenAccount>>,
pub token_mints: Box<dyn Storage<String, MintAccount>>,
pub token_accounts_by_owner: Box<dyn Storage<String, Vec<String>>>,
pub token_accounts_by_delegate: Box<dyn Storage<String, Vec<String>>>,
pub token_accounts_by_mint: Box<dyn Storage<String, Vec<String>>>,
pub total_supply: u64,
pub circulating_supply: u64,
pub non_circulating_supply: u64,
pub non_circulating_accounts: Vec<String>,
pub genesis_config: GenesisConfig,
pub inflation: Inflation,
/// A global monotonically increasing atomic number, which can be used to tell the order of the account update.
/// For example, when an account is updated in the same slot multiple times,
/// the update with higher write_version should supersede the one with lower write_version.
pub write_version: u64,
pub registered_idls: Box<dyn Storage<String, Vec<VersionedIdl>>>,
pub feature_set: FeatureSet,
pub instruction_profiling_enabled: bool,
pub max_profiles: usize,
pub runbook_executions: Vec<RunbookExecutionStatusReport>,
pub account_update_slots: HashMap<Pubkey, Slot>,
pub streamed_accounts: Box<dyn Storage<String, bool>>,
pub recent_blockhashes: VecDeque<(SyntheticBlockhash, i64)>,
pub scheduled_overrides: Box<dyn Storage<u64, Vec<OverrideInstance>>>,
/// Tracks accounts that have been explicitly closed by the user.
/// These accounts will not be fetched from mainnet even if they don't exist in the local cache.
pub closed_accounts: HashSet<Pubkey>,
/// The slot at which this surfnet instance started (may be non-zero when connected to remote).
/// Used as the lower bound for block reconstruction.
pub genesis_slot: Slot,
/// The `updated_at` timestamp when this surfnet started at `genesis_slot`.
/// Used to reconstruct block_time: genesis_updated_at + ((slot - genesis_slot) * slot_time)
pub genesis_updated_at: u64,
/// Storage for persisting the latest slot checkpoint.
/// Used for recovery on restart with sparse block storage.
pub slot_checkpoint: Box<dyn Storage<String, u64>>,
/// Tracks the slot at which we last persisted the checkpoint.
pub last_checkpoint_slot: u64,
}
pub const FEATURE: Feature = Feature {
activated_at: Some(0),
};
impl SurfnetSvm {
pub fn default() -> (Self, Receiver<SimnetEvent>, Receiver<GeyserEvent>) {
Self::new(None, "0").unwrap()
}
pub fn new_with_db(
database_url: Option<&str>,
surfnet_id: &str,
) -> SurfpoolResult<(Self, Receiver<SimnetEvent>, Receiver<GeyserEvent>)> {
Self::new(database_url, surfnet_id)
}
/// Explicitly shutdown the SVM, performing cleanup like WAL checkpoint for SQLite.
/// This should be called before the application exits to ensure data is persisted.
pub fn shutdown(&self) {
self.inner.shutdown();
self.blocks.shutdown();
self.transactions.shutdown();
self.token_accounts.shutdown();
self.token_mints.shutdown();
self.accounts_by_owner.shutdown();
self.token_accounts_by_owner.shutdown();
self.token_accounts_by_delegate.shutdown();
self.token_accounts_by_mint.shutdown();
self.streamed_accounts.shutdown();
self.scheduled_overrides.shutdown();
self.registered_idls.shutdown();
self.profile_tag_map.shutdown();
self.simulated_transaction_profiles.shutdown();
self.executed_transaction_profiles.shutdown();
self.account_associated_data.shutdown();
}
/// Creates a clone of the SVM with overlay storage wrappers for all database-backed fields.
/// This allows profiling transactions without affecting the underlying database.
/// All storage writes are buffered in memory and discarded when the clone is dropped.
pub fn clone_for_profiling(&self) -> Self {
let (dummy_simnet_tx, _) = crossbeam_channel::bounded(1);
let (dummy_geyser_tx, _) = crossbeam_channel::bounded(1);
Self {
inner: self.inner.clone_for_profiling(),
remote_rpc_url: self.remote_rpc_url.clone(),
chain_tip: self.chain_tip.clone(),
// Wrap all storage fields with OverlayStorage
blocks: OverlayStorage::wrap(self.blocks.clone_box()),
transactions: OverlayStorage::wrap(self.transactions.clone_box()),
profile_tag_map: OverlayStorage::wrap(self.profile_tag_map.clone_box()),
simulated_transaction_profiles: OverlayStorage::wrap(
self.simulated_transaction_profiles.clone_box(),
),
executed_transaction_profiles: OverlayStorage::wrap(
self.executed_transaction_profiles.clone_box(),
),
accounts_by_owner: OverlayStorage::wrap(self.accounts_by_owner.clone_box()),
account_associated_data: OverlayStorage::wrap(self.account_associated_data.clone_box()),
token_accounts: OverlayStorage::wrap(self.token_accounts.clone_box()),
token_mints: OverlayStorage::wrap(self.token_mints.clone_box()),
token_accounts_by_owner: OverlayStorage::wrap(self.token_accounts_by_owner.clone_box()),
token_accounts_by_delegate: OverlayStorage::wrap(
self.token_accounts_by_delegate.clone_box(),
),
token_accounts_by_mint: OverlayStorage::wrap(self.token_accounts_by_mint.clone_box()),
registered_idls: OverlayStorage::wrap(self.registered_idls.clone_box()),
streamed_accounts: OverlayStorage::wrap(self.streamed_accounts.clone_box()),
scheduled_overrides: OverlayStorage::wrap(self.scheduled_overrides.clone_box()),
// Clone non-storage fields normally
transactions_queued_for_confirmation: self.transactions_queued_for_confirmation.clone(),
transactions_queued_for_finalization: self.transactions_queued_for_finalization.clone(),
perf_samples: self.perf_samples.clone(),
transactions_processed: self.transactions_processed,
latest_epoch_info: self.latest_epoch_info.clone(),
// Use dummy channels to prevent event propagation during profiling
simnet_events_tx: dummy_simnet_tx,
geyser_events_tx: dummy_geyser_tx,
signature_subscriptions: self.signature_subscriptions.clone(),
account_subscriptions: self.account_subscriptions.clone(),
program_subscriptions: self.program_subscriptions.clone(),
// Don't clone subscriptions - profiling clone shouldn't send notifications
slot_subscriptions: Vec::new(),
logs_subscriptions: Vec::new(),
snapshot_subscriptions: Vec::new(),
updated_at: self.updated_at,
slot_time: self.slot_time,
start_time: self.start_time,
total_supply: self.total_supply,
circulating_supply: self.circulating_supply,
non_circulating_supply: self.non_circulating_supply,
non_circulating_accounts: self.non_circulating_accounts.clone(),
genesis_config: self.genesis_config.clone(),
inflation: self.inflation,
write_version: self.write_version,
feature_set: self.feature_set.clone(),
instruction_profiling_enabled: self.instruction_profiling_enabled,
max_profiles: self.max_profiles,
runbook_executions: self.runbook_executions.clone(),
account_update_slots: self.account_update_slots.clone(),
recent_blockhashes: self.recent_blockhashes.clone(),
closed_accounts: self.closed_accounts.clone(),
genesis_slot: self.genesis_slot,
genesis_updated_at: self.genesis_updated_at,
slot_checkpoint: OverlayStorage::wrap(self.slot_checkpoint.clone_box()),
last_checkpoint_slot: self.last_checkpoint_slot,
}
}
/// Creates a new instance of `SurfnetSvm`.
///
/// Returns a tuple containing the SVM instance, a receiver for simulation events, and a receiver for Geyser plugin events.
pub fn new(
database_url: Option<&str>,
surfnet_id: &str,
) -> SurfpoolResult<(Self, Receiver<SimnetEvent>, Receiver<GeyserEvent>)> {
let (simnet_events_tx, simnet_events_rx) = crossbeam_channel::bounded(1024);
let (geyser_events_tx, geyser_events_rx) = crossbeam_channel::bounded(1024);
let mut feature_set = FeatureSet::all_enabled();
// todo: remove once txtx deployments upgrade solana dependencies.
// todo: consider making this configurable via config
feature_set.deactivate(&enable_extend_program_checked::id());
let inner =
SurfnetLiteSvm::new().initialize(feature_set.clone(), database_url, surfnet_id)?;
let native_mint_account = inner
.get_account(&spl_token_interface::native_mint::ID)?
.unwrap();
let native_mint_associated_data = {
let mint = StateWithExtensions::<spl_token_2022_interface::state::Mint>::unpack(
&native_mint_account.data,
)
.unwrap();
let unix_timestamp = inner.get_sysvar::<Clock>().unix_timestamp;
let interest_bearing_config = mint
.get_extension::<InterestBearingConfig>()
.map(|x| (*x, unix_timestamp))
.ok();
let scaled_ui_amount_config = mint
.get_extension::<ScaledUiAmountConfig>()
.map(|x| (*x, unix_timestamp))
.ok();
AccountAdditionalDataV3 {
spl_token_additional_data: Some(SplTokenAdditionalDataV2 {
decimals: mint.base.decimals,
interest_bearing_config,
scaled_ui_amount_config,
}),
}
};
let parsed_mint_account = MintAccount::unpack(&native_mint_account.data).unwrap();
// Load native mint into owned account and token mint indexes
let mut accounts_by_owner_db: Box<dyn Storage<String, Vec<String>>> =
new_kv_store(&database_url, "accounts_by_owner", surfnet_id)?;
accounts_by_owner_db.store(
native_mint_account.owner.to_string(),
vec![spl_token_interface::native_mint::ID.to_string()],
)?;
let blocks_db = new_kv_store(&database_url, "blocks", surfnet_id)?;
let transactions_db = new_kv_store(&database_url, "transactions", surfnet_id)?;
let token_accounts_db = new_kv_store(&database_url, "token_accounts", surfnet_id)?;
let mut token_mints_db: Box<dyn Storage<String, MintAccount>> =
new_kv_store(&database_url, "token_mints", surfnet_id)?;
let mut account_associated_data_db: Box<
dyn Storage<String, SerializableAccountAdditionalData>,
> = new_kv_store(&database_url, "account_associated_data", surfnet_id)?;
// Store initial account associated data (native mint)
account_associated_data_db.store(
spl_token_interface::native_mint::ID.to_string(),
native_mint_associated_data.into(),
)?;
token_mints_db.store(
spl_token_interface::native_mint::ID.to_string(),
parsed_mint_account,
)?;
let token_accounts_by_owner_db: Box<dyn Storage<String, Vec<String>>> =
new_kv_store(&database_url, "token_accounts_by_owner", surfnet_id)?;
let token_accounts_by_delegate_db: Box<dyn Storage<String, Vec<String>>> =
new_kv_store(&database_url, "token_accounts_by_delegate", surfnet_id)?;
let token_accounts_by_mint_db: Box<dyn Storage<String, Vec<String>>> =
new_kv_store(&database_url, "token_accounts_by_mint", surfnet_id)?;
let streamed_accounts_db: Box<dyn Storage<String, bool>> =
new_kv_store(&database_url, "streamed_accounts", surfnet_id)?;
let scheduled_overrides_db: Box<dyn Storage<u64, Vec<OverrideInstance>>> =
new_kv_store(&database_url, "scheduled_overrides", surfnet_id)?;
let registered_idls_db: Box<dyn Storage<String, Vec<VersionedIdl>>> =
new_kv_store(&database_url, "registered_idls", surfnet_id)?;
let profile_tag_map_db: Box<dyn Storage<String, Vec<UuidOrSignature>>> =
new_kv_store(&database_url, "profile_tag_map", surfnet_id)?;
let simulated_transaction_profiles_db: Box<dyn Storage<String, KeyedProfileResult>> =
new_kv_store(&database_url, "simulated_transaction_profiles", surfnet_id)?;
let executed_transaction_profiles_db: Box<dyn Storage<String, KeyedProfileResult>> =
new_kv_store_with_default(
&database_url,
"executed_transaction_profiles",
surfnet_id,
// Use FifoMap for executed_transaction_profiles to maintain FIFO eviction behavior
// (when no on-disk DB is provided)
|| Box::new(FifoMap::<String, KeyedProfileResult>::default()),
)?;
let slot_checkpoint_db: Box<dyn Storage<String, u64>> =
new_kv_store(&database_url, "slot_checkpoint", surfnet_id)?;
// Recover chain state: prefer slot checkpoint, fall back to max block in DB
let checkpoint_slot = slot_checkpoint_db.get(&"latest_slot".to_string())?;
let max_block_slot = blocks_db
.into_iter()
.unwrap()
.max_by_key(|(slot, _): &(u64, BlockHeader)| *slot);
let chain_tip = match (checkpoint_slot, max_block_slot) {
// Prefer checkpoint if it's higher than the max stored block
(Some(checkpoint), Some((block_slot, block))) => {
if checkpoint > block_slot {
// Use checkpoint slot with synthetic blockhash
BlockIdentifier {
index: checkpoint,
hash: SyntheticBlockhash::new(checkpoint).to_string(),
}
} else {
// Use the stored block
BlockIdentifier {
index: block.block_height,
hash: block.hash,
}
}
}
(Some(checkpoint), None) => BlockIdentifier {
index: checkpoint,
hash: SyntheticBlockhash::new(checkpoint).to_string(),
},
(None, Some((_, block))) => BlockIdentifier {
index: block.block_height,
hash: block.hash,
},
(None, None) => BlockIdentifier::zero(),
};
// Initialize transactions_processed from database count for persistent storage
let transactions_processed = transactions_db.count()?;
let mut svm = Self {
inner,
remote_rpc_url: None,
chain_tip,
blocks: blocks_db,
transactions: transactions_db,
perf_samples: VecDeque::new(),
transactions_processed,
simnet_events_tx,
geyser_events_tx,
latest_epoch_info: EpochInfo {
epoch: 0,
slot_index: 0,
slots_in_epoch: SLOTS_PER_EPOCH,
absolute_slot: 0,
block_height: 0,
transaction_count: None,
},
transactions_queued_for_confirmation: VecDeque::new(),
transactions_queued_for_finalization: VecDeque::new(),
signature_subscriptions: HashMap::new(),
account_subscriptions: HashMap::new(),
program_subscriptions: HashMap::new(),
slot_subscriptions: Vec::new(),
profile_tag_map: profile_tag_map_db,
simulated_transaction_profiles: simulated_transaction_profiles_db,
executed_transaction_profiles: executed_transaction_profiles_db,
logs_subscriptions: Vec::new(),
snapshot_subscriptions: Vec::new(),
updated_at: Utc::now().timestamp_millis() as u64,
slot_time: DEFAULT_SLOT_TIME_MS,
start_time: SystemTime::now(),
accounts_by_owner: accounts_by_owner_db,
account_associated_data: account_associated_data_db,
token_accounts: token_accounts_db,
token_mints: token_mints_db,
token_accounts_by_owner: token_accounts_by_owner_db,
token_accounts_by_delegate: token_accounts_by_delegate_db,
token_accounts_by_mint: token_accounts_by_mint_db,
total_supply: 0,
circulating_supply: 0,
non_circulating_supply: 0,
non_circulating_accounts: Vec::new(),
genesis_config: GenesisConfig::default(),
inflation: Inflation::default(),
write_version: 0,
registered_idls: registered_idls_db,
feature_set,
instruction_profiling_enabled: true,
max_profiles: DEFAULT_PROFILING_MAP_CAPACITY,
runbook_executions: Vec::new(),
account_update_slots: HashMap::new(),
streamed_accounts: streamed_accounts_db,
recent_blockhashes: VecDeque::new(),
scheduled_overrides: scheduled_overrides_db,
closed_accounts: HashSet::new(),
genesis_slot: 0, // Will be updated when connecting to remote network
genesis_updated_at: Utc::now().timestamp_millis() as u64,
slot_checkpoint: slot_checkpoint_db,
last_checkpoint_slot: 0,
};
// Generate the initial synthetic blockhash
svm.chain_tip = svm.new_blockhash();
Ok((svm, simnet_events_rx, geyser_events_rx))
}
/// Applies the SVM feature configuration to the internal feature set.
///
/// This method enables or disables specific SVM features based on the provided configuration.
/// Features explicitly listed in `enable` will be activated, and features in `disable` will be deactivated.
///
/// # Arguments
/// * `config` - The feature configuration specifying which features to enable/disable.
pub fn apply_feature_config(&mut self, config: &SvmFeatureConfig) {
// Apply explicit enables
for pubkey in &config.enable {
self.feature_set.activate(pubkey, 0);
}
// Apply explicit disables
for pubkey in &config.disable {
self.feature_set.deactivate(pubkey);
}
// Rebuild inner VM with updated feature set
self.inner.apply_feature_config(self.feature_set.clone());
}
pub fn increment_write_version(&mut self) -> u64 {
self.write_version += 1;
self.write_version
}
/// Initializes the SVM with the provided epoch info and optionally notifies about remote connection.
///
/// Updates the internal epoch info, sends connection and epoch update events, and sets the clock sysvar.
///
/// # Arguments
/// * `epoch_info` - The epoch information to initialize with.
/// * `remote_ctx` - Optional remote client context for event notification.
///
pub fn initialize(
&mut self,
epoch_info: EpochInfo,
epoch_schedule: EpochSchedule,
slot_time: u64,
remote_ctx: &Option<SurfnetRemoteClient>,
do_profile_instructions: bool,
log_bytes_limit: Option<usize>,
) {
self.chain_tip = self.new_blockhash();
self.latest_epoch_info = epoch_info.clone();
// Set genesis_slot to the current slot when initializing (syncing with remote)
// This marks the starting point for this surfnet instance
self.genesis_slot = epoch_info.absolute_slot;
self.updated_at = Utc::now().timestamp_millis() as u64;
// Update genesis_updated_at to match the new genesis_slot
self.genesis_updated_at = self.updated_at;
self.slot_time = slot_time;
self.instruction_profiling_enabled = do_profile_instructions;
self.set_profiling_map_capacity(self.max_profiles);
self.inner.set_log_bytes_limit(log_bytes_limit);
let registry = TemplateRegistry::new();
for (_, template) in registry.templates.into_iter() {
let _ = self.register_idl(template.idl, None);
}
self.inner.set_sysvar(&epoch_schedule);
if let Some(remote_client) = remote_ctx {
let _ = self
.simnet_events_tx
.send(SimnetEvent::Connected(remote_client.client.url()));
}
let _ = self
.simnet_events_tx
.send(SimnetEvent::EpochInfoUpdate(epoch_info));
// Reconstruct all sysvars (RecentBlockhashes, SlotHashes, Clock)
self.reconstruct_sysvars();
}
pub fn set_profile_instructions(&mut self, do_profile_instructions: bool) {
self.instruction_profiling_enabled = do_profile_instructions;
}
pub fn set_profiling_map_capacity(&mut self, capacity: usize) {
let clamped_capacity = max(1, capacity);
self.max_profiles = clamped_capacity;
let is_on_disk_db = self.inner.db.is_some();
if !is_on_disk_db {
// when using on-disk DB, we're not using the Fifo Map to manage entries
self.executed_transaction_profiles = Box::new(FifoMap::new(clamped_capacity));
}
}
/// Airdrops a specified amount of lamports to a single public key.
///
/// # Arguments
/// * `pubkey` - The recipient public key.
/// * `lamports` - The amount of lamports to airdrop.
///
/// # Returns
/// A `TransactionResult` indicating success or failure.
#[allow(clippy::result_large_err)]
pub fn airdrop(&mut self, pubkey: &Pubkey, lamports: u64) -> SurfpoolResult<TransactionResult> {
// Capture pre-airdrop balances for the airdrop account, recipient, and system program.
let airdrop_pubkey = self.inner.airdrop_pubkey();
let airdrop_account_before = self
.get_account(&airdrop_pubkey)?
.unwrap_or_else(|| Account::default());
let recipient_account_before = self
.get_account(pubkey)?
.unwrap_or_else(|| Account::default());
let system_account_before = self
.get_account(&system_program::id())?
.unwrap_or_else(|| Account::default());
let res = self.inner.airdrop(pubkey, lamports);
let (status_tx, _rx) = unbounded();
if let Ok(ref tx_result) = res {
let slot = self.latest_epoch_info.absolute_slot;
// Capture post-airdrop balances
let airdrop_account_after = self
.get_account(&airdrop_pubkey)?
.unwrap_or_else(|| Account::default());
let recipient_account_after = self
.get_account(pubkey)?
.unwrap_or_else(|| Account::default());
let system_account_after = self
.get_account(&system_program::id())?
.unwrap_or_else(|| Account::default());
// Construct a synthetic transaction that mirrors the underlying airdrop.
let tx = VersionedTransaction {
signatures: vec![tx_result.signature],
message: VersionedMessage::Legacy(Message::new(
&[system_instruction::transfer(
&airdrop_pubkey,
pubkey,
lamports,
)],
Some(&airdrop_pubkey),
)),
};
self.transactions.store(
tx.get_signature().to_string(),
SurfnetTransactionStatus::processed(
TransactionWithStatusMeta {
slot,
transaction: tx.clone(),
meta: TransactionStatusMeta {
status: Ok(()),
fee: 5000,
pre_balances: vec![
airdrop_account_before.lamports,
recipient_account_before.lamports,
system_account_before.lamports,
],
post_balances: vec![
airdrop_account_after.lamports,
recipient_account_after.lamports,
system_account_after.lamports,
],
inner_instructions: Some(vec![]),
log_messages: Some(tx_result.logs.clone()),
pre_token_balances: Some(vec![]),
post_token_balances: Some(vec![]),
rewards: Some(vec![]),
loaded_addresses: LoadedAddresses::default(),
return_data: Some(tx_result.return_data.clone()),
compute_units_consumed: Some(tx_result.compute_units_consumed),
cost_units: None,
},
},
HashSet::from([*pubkey]),
),
)?;
self.notify_signature_subscribers(
SignatureSubscriptionType::processed(),
tx.get_signature(),
slot,
None,
);
self.notify_logs_subscribers(
tx.get_signature(),
None,
tx_result.logs.clone(),
CommitmentLevel::Processed,
);
self.transactions_queued_for_confirmation
.push_back((tx, status_tx.clone(), None));
let account = self.get_account(pubkey)?.unwrap();
self.set_account(pubkey, account)?;
}
Ok(res)
}
/// Airdrops a specified amount of lamports to a list of public keys.
///
/// # Arguments
/// * `lamports` - The amount of lamports to airdrop.
/// * `addresses` - Slice of recipient public keys.
pub fn airdrop_pubkeys(&mut self, lamports: u64, addresses: &[Pubkey]) {
for recipient in addresses {
match self.airdrop(recipient, lamports) {
Ok(_) => {
let _ = self.simnet_events_tx.send(SimnetEvent::info(format!(
"Genesis airdrop successful {}: {}",
recipient, lamports
)));
}
Err(e) => {
let _ = self.simnet_events_tx.send(SimnetEvent::error(format!(
"Genesis airdrop failed {}: {}",
recipient, e
)));
}
};
}
}
/// Returns the latest known absolute slot from the local epoch info.
pub const fn get_latest_absolute_slot(&self) -> Slot {
self.latest_epoch_info.absolute_slot
}
/// Returns the latest blockhash known by the SVM.
pub fn latest_blockhash(&self) -> solana_hash::Hash {
Hash::from_str(&self.chain_tip.hash).expect("Invalid blockhash")
}
/// Returns the latest epoch info known by the `SurfnetSvm`.
pub fn latest_epoch_info(&self) -> EpochInfo {
self.latest_epoch_info.clone()
}
/// Calculates the block time for a given slot based on genesis timestamp.
/// Returns the time in milliseconds since genesis.
pub fn calculate_block_time_for_slot(&self, slot: Slot) -> u64 {
// Calculate time relative to genesis_slot (when this surfnet started)
let slots_since_genesis = slot.saturating_sub(self.genesis_slot);
self.genesis_updated_at + (slots_since_genesis * self.slot_time)
}
/// Checks if a slot is within the valid range for sparse block storage.
/// A slot is valid if it's between genesis_slot (inclusive) and latest_slot (inclusive).
///
/// # Arguments
/// * `slot` - The slot number to check.
///
/// # Returns
/// `true` if the slot is within the valid range, `false` otherwise.
pub fn is_slot_in_valid_range(&self, slot: Slot) -> bool {
let latest_slot = self.get_latest_absolute_slot();
slot >= self.genesis_slot && slot <= latest_slot
}
/// Gets a block from storage, or reconstructs an empty block if the slot is within
/// the valid range (sparse block storage).
///
/// # Arguments
/// * `slot` - The slot number to retrieve.
///
/// # Returns
/// * `Ok(Some(BlockHeader))` - If the block exists or can be reconstructed
/// * `Ok(None)` - If the slot is outside the valid range
/// * `Err(_)` - If there was an error accessing storage
pub fn get_block_or_reconstruct(&self, slot: Slot) -> SurfpoolResult<Option<BlockHeader>> {
match self.blocks.get(&slot)? {
Some(block) => Ok(Some(block)),
None => {
if self.is_slot_in_valid_range(slot) {
Ok(Some(self.reconstruct_empty_block(slot)))
} else {
Ok(None)
}
}
}
}
/// Reconstructs an empty block header for a slot that wasn't stored.
/// This is used for sparse block storage where empty blocks are not persisted.
pub fn reconstruct_empty_block(&self, slot: Slot) -> BlockHeader {
let block_height = slot;
BlockHeader {
hash: SyntheticBlockhash::new(block_height).to_string(),
previous_blockhash: SyntheticBlockhash::new(block_height.saturating_sub(1)).to_string(),
parent_slot: slot.saturating_sub(1),
block_time: (self.calculate_block_time_for_slot(slot) / 1_000) as i64,
block_height,
signatures: vec![],
}
}
pub fn get_account_from_feature_set(&self, pubkey: &Pubkey) -> Option<Account> {
// Currently, liteSVM doesn't create feature gate accounts and store them in the vm,
// so when a user is fetching one, we make one on the fly.
// TODO: remove once https://github.com/LiteSVM/litesvm/pull/308 is released
self.feature_set.active().get(pubkey).map(|_| {
let feature_bytes = bincode::serialize(&FEATURE).unwrap();
let lamports = self
.inner
.minimum_balance_for_rent_exemption(feature_bytes.len());
Account {
lamports,
data: feature_bytes,
owner: solana_sdk_ids::feature::id(),
executable: false,
rent_epoch: 0,
}
})
}
/// Reconstructs RecentBlockhashes, SlotHashes, and Clock sysvars deterministically
/// from the current slot. Called on startup and after garbage collection to ensure
/// consistent sysvar state without requiring database persistence.
///
/// Note: SyntheticBlockhash uses chain_tip.index (relative index), while SlotHashes
/// and Clock use absolute slots (chain_tip.index + genesis_slot).
#[allow(deprecated)]
pub fn reconstruct_sysvars(&mut self) {
use solana_slot_hashes::SlotHashes;
use solana_sysvar::recent_blockhashes::{IterItem, RecentBlockhashes};
let current_index = self.chain_tip.index;
let current_absolute_slot = self.get_latest_absolute_slot();
// Calculate range for blockhashes - use relative indices for SyntheticBlockhash
let start_index = current_index.saturating_sub(MAX_RECENT_BLOCKHASHES_STANDARD as u64 - 1);
// Generate all synthetic blockhashes using relative indices (chain_tip.index style)
// This matches how new_blockhash() generates hashes
let synthetic_hashes: Vec<_> = (start_index..=current_index)
.rev()
.map(SyntheticBlockhash::new)
.collect();
// 1. Reconstruct RecentBlockhashes (last 150 blockhashes)
let recent_blockhashes_vec: Vec<_> = synthetic_hashes
.iter()
.enumerate()
.map(|(index, hash)| IterItem(index as u64, hash.hash(), 0))
.collect();
let recent_blockhashes = RecentBlockhashes::from_iter(recent_blockhashes_vec);
self.inner.set_sysvar(&recent_blockhashes);
// 2. Reconstruct SlotHashes - maps absolute slots to blockhashes
let start_absolute_slot = start_index + self.genesis_slot;
let slot_hashes_vec: Vec<_> = (start_absolute_slot..=current_absolute_slot)
.rev()
.zip(synthetic_hashes.iter())
.map(|(slot, hash)| (slot, *hash.hash()))
.collect();
let slot_hashes = SlotHashes::new(&slot_hashes_vec);
self.inner.set_sysvar(&slot_hashes);
// 3. Reconstruct Clock using absolute slot
let unix_timestamp = self.calculate_block_time_for_slot(current_absolute_slot) / 1_000;
let clock = Clock {
slot: current_absolute_slot,
epoch: self.latest_epoch_info.epoch,
unix_timestamp: unix_timestamp as i64,
epoch_start_timestamp: 0,
leader_schedule_epoch: 0,
};
self.inner.set_sysvar(&clock);
}
/// Generates and sets a new blockhash, updating the RecentBlockhashes sysvar.
///
/// # Returns
/// A new `BlockIdentifier` for the updated blockhash.
#[allow(deprecated)]
fn new_blockhash(&mut self) -> BlockIdentifier {
use solana_slot_hashes::SlotHashes;
use solana_sysvar::recent_blockhashes::{IterItem, RecentBlockhashes};
// Backup the current block hashes
let recent_blockhashes_backup = self.inner.get_sysvar::<RecentBlockhashes>();
let num_blockhashes_expected = recent_blockhashes_backup
.len()
.min(MAX_RECENT_BLOCKHASHES_STANDARD);
// Invalidate the current block hash.
// LiteSVM bug / feature: calling this method empties `sysvar::<RecentBlockhashes>()`
self.inner.expire_blockhash();
// Rebuild recent blockhashes