-
Notifications
You must be signed in to change notification settings - Fork 147
Expand file tree
/
Copy pathsvm.rs
More file actions
2173 lines (1988 loc) · 83.1 KB
/
svm.rs
File metadata and controls
2173 lines (1988 loc) · 83.1 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::collections::{BinaryHeap, HashMap, VecDeque};
use chrono::Utc;
use convert_case::Casing;
use crossbeam_channel::{Receiver, Sender, unbounded};
use litesvm::{
LiteSVM,
types::{
FailedTransactionMetadata, SimulatedTransactionInfo, TransactionMetadata, TransactionResult,
},
};
use solana_account::{Account, 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_response::{RpcKeyedAccount, RpcLogsResponse, RpcPerfSample},
};
use solana_clock::{Clock, MAX_RECENT_BLOCKHASHES, Slot};
use solana_commitment_config::CommitmentLevel;
use solana_epoch_info::EpochInfo;
use solana_feature_set::{FeatureSet, disable_new_loader_v3_deployments};
use solana_hash::Hash;
use solana_keypair::Keypair;
use solana_message::{Message, VersionedMessage, v0::LoadedAddresses};
use solana_pubkey::Pubkey;
use solana_rpc_client_api::response::SlotInfo;
use solana_sdk::{
genesis_config::GenesisConfig, inflation::Inflation, program_option::COption,
system_instruction, transaction::VersionedTransaction,
};
use solana_sdk_ids::system_program;
use solana_signature::Signature;
use solana_signer::Signer;
use solana_transaction_error::TransactionError;
use solana_transaction_status::{TransactionDetails, TransactionStatusMeta, UiConfirmedBlock};
use spl_token_2022::extension::{
BaseStateWithExtensions, StateWithExtensions, interest_bearing_mint::InterestBearingConfig,
scaled_ui_amount::ScaledUiAmountConfig,
};
use surfpool_types::{
AccountChange, AccountProfileState, DEFAULT_SLOT_TIME_MS, Idl, ProfileResult, RpcProfileDepth,
RpcProfileResultConfig, SimnetEvent, TransactionConfirmationStatus, TransactionStatusEvent,
UiAccountChange, UiAccountProfileState, UiProfileResult, VersionedIdl,
types::{
ComputeUnitsEstimationResult, KeyedProfileResult, UiKeyedProfileResult, UuidOrSignature,
},
};
use txtx_addon_kit::{indexmap::IndexMap, types::types::AddonJsonConverter};
use txtx_addon_network_svm_types::subgraph::idl::parse_bytes_to_value_with_expected_idl_type_def_ty;
use uuid::Uuid;
use super::{
AccountSubscriptionData, BlockHeader, BlockIdentifier, FINALIZATION_SLOT_THRESHOLD,
GetAccountResult, GeyserEvent, SLOTS_PER_EPOCH, SignatureSubscriptionData,
SignatureSubscriptionType, remote::SurfnetRemoteClient,
};
use crate::{
error::{SurfpoolError, SurfpoolResult},
rpc::utils::convert_transaction_metadata_from_canonical,
surfnet::{LogsSubscriptionData, locker::is_supported_token_program},
types::{MintAccount, SurfnetTransactionStatus, TokenAccount, TransactionWithStatusMeta},
};
pub type AccountOwner = Pubkey;
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: LiteSVM,
pub remote_rpc_url: Option<String>,
pub chain_tip: BlockIdentifier,
pub blocks: HashMap<Slot, BlockHeader>,
pub transactions: HashMap<Signature, SurfnetTransactionStatus>,
pub transactions_queued_for_confirmation:
VecDeque<(VersionedTransaction, Sender<TransactionStatusEvent>)>,
pub transactions_queued_for_finalization:
VecDeque<(Slot, VersionedTransaction, Sender<TransactionStatusEvent>)>,
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 slot_subscriptions: Vec<Sender<SlotInfo>>,
pub profile_tag_map: HashMap<String, Vec<UuidOrSignature>>,
pub simulated_transaction_profiles: HashMap<Uuid, KeyedProfileResult>,
pub executed_transaction_profiles: HashMap<Signature, KeyedProfileResult>,
pub logs_subscriptions: Vec<LogsSubscriptionData>,
pub updated_at: u64,
pub slot_time: u64,
pub accounts_registry: HashMap<Pubkey, Account>,
pub accounts_by_owner: HashMap<Pubkey, Vec<Pubkey>>,
pub account_associated_data: HashMap<Pubkey, AccountAdditionalDataV3>,
pub token_accounts: HashMap<Pubkey, TokenAccount>,
pub token_mints: HashMap<Pubkey, MintAccount>,
pub token_accounts_by_owner: HashMap<Pubkey, Vec<Pubkey>>,
pub token_accounts_by_delegate: HashMap<Pubkey, Vec<Pubkey>>,
pub token_accounts_by_mint: HashMap<Pubkey, Vec<Pubkey>>,
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: HashMap<Pubkey, BinaryHeap<VersionedIdl>>,
}
impl SurfnetSvm {
/// 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() -> (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();
// v2.2 of the solana_sdk deprecates the v3 loader, and enables the v4 loader by default.
// In order to keep the v3 deployments enabled, we need to remove the
// `disable_new_loader_v3_deployments` feature from the active set, and add it to the inactive set.
let _ = feature_set
.active
.remove(&disable_new_loader_v3_deployments::id());
feature_set
.inactive
.insert(disable_new_loader_v3_deployments::id());
let inner = LiteSVM::new()
.with_feature_set(feature_set)
.with_blockhash_check(false)
.with_sigverify(false);
(
Self {
inner,
remote_rpc_url: None,
chain_tip: BlockIdentifier::zero(),
blocks: HashMap::new(),
transactions: HashMap::new(),
perf_samples: VecDeque::new(),
transactions_processed: 0,
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(),
slot_subscriptions: Vec::new(),
profile_tag_map: HashMap::new(),
simulated_transaction_profiles: HashMap::new(),
executed_transaction_profiles: HashMap::new(),
logs_subscriptions: Vec::new(),
updated_at: Utc::now().timestamp_millis() as u64,
slot_time: DEFAULT_SLOT_TIME_MS,
accounts_registry: HashMap::new(),
accounts_by_owner: HashMap::new(),
account_associated_data: HashMap::new(),
token_accounts: HashMap::new(),
token_mints: HashMap::new(),
token_accounts_by_owner: HashMap::new(),
token_accounts_by_delegate: HashMap::new(),
token_accounts_by_mint: HashMap::new(),
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: HashMap::new(),
},
simnet_events_rx,
geyser_events_rx,
)
}
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,
slot_time: u64,
remote_ctx: &Option<SurfnetRemoteClient>,
) {
self.latest_epoch_info = epoch_info.clone();
self.updated_at = Utc::now().timestamp_millis() as u64;
self.slot_time = slot_time;
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));
let clock: Clock = Clock {
slot: self.latest_epoch_info.absolute_slot,
epoch: self.latest_epoch_info.epoch,
unix_timestamp: Utc::now().timestamp(),
epoch_start_timestamp: 0, // todo
leader_schedule_epoch: 0, // todo
};
self.inner.set_sysvar(&clock);
}
/// 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.
pub fn airdrop(&mut self, pubkey: &Pubkey, lamports: u64) -> TransactionResult {
self.updated_at = Utc::now().timestamp_millis() as u64;
let res = self.inner.airdrop(pubkey, lamports);
let (status_tx, _rx) = unbounded();
if let Ok(ref tx_result) = res {
let airdrop_keypair = Keypair::new();
let slot = self.latest_epoch_info.absolute_slot;
let account = self.inner.get_account(pubkey).unwrap();
let mut tx = VersionedTransaction::try_new(
VersionedMessage::Legacy(Message::new(
&[system_instruction::transfer(
&airdrop_keypair.pubkey(),
pubkey,
lamports,
)],
Some(&airdrop_keypair.pubkey()),
)),
&[airdrop_keypair],
)
.unwrap();
// we need the airdrop tx to store in our transactions list,
// but for it to be properly processed we need its signature to match
// the actual underlying transaction
tx.signatures[0] = tx_result.signature.clone();
let system_lamports = self
.inner
.get_account(&system_program::id())
.map(|a| a.lamports())
.unwrap_or(1);
self.transactions.insert(
tx.get_signature().clone(),
SurfnetTransactionStatus::Processed(Box::new(TransactionWithStatusMeta {
slot,
transaction: tx.clone(),
meta: TransactionStatusMeta {
status: Ok(()),
fee: 5000,
pre_balances: vec![
account.lamports,
account.lamports.saturating_sub(lamports),
system_lamports,
],
post_balances: vec![
account.lamports.saturating_sub(lamports + 5000),
account.lamports,
system_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),
},
})),
);
self.transactions_queued_for_confirmation
.push_back((tx, status_tx.clone()));
let account = self.inner.get_account(pubkey).unwrap();
let _ = self.set_account(pubkey, account);
}
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]) {
self.updated_at = Utc::now().timestamp_millis() as u64;
for recipient in addresses {
let _ = self.airdrop(recipient, lamports);
let _ = self.simnet_events_tx.send(SimnetEvent::info(format!(
"Genesis airdrop successful {}: {}",
recipient, lamports
)));
}
}
/// 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 {
self.inner.latest_blockhash()
}
/// Returns the latest epoch info known by the `SurfnetSvm`.
pub fn latest_epoch_info(&self) -> EpochInfo {
self.latest_epoch_info.clone()
}
/// 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 {
self.updated_at = Utc::now().timestamp_millis() as u64;
// cache the current blockhashes
let blockhashes = self
.inner
.get_sysvar::<solana_sdk::sysvar::recent_blockhashes::RecentBlockhashes>();
let max_entries_len = blockhashes.len().min(MAX_RECENT_BLOCKHASHES);
let mut entries = Vec::with_capacity(max_entries_len);
// note: expire blockhash has a bug with liteSVM.
// they only keep one blockhash in their RecentBlockhashes sysvar, so this function
// clears out the other valid hashes.
// so we manually rehydrate the sysvar with new latest blockhash + cached blockhashes.
self.inner.expire_blockhash();
let latest_entries = self
.inner
.get_sysvar::<solana_sdk::sysvar::recent_blockhashes::RecentBlockhashes>();
let latest_entry = latest_entries.first().unwrap();
entries.push(solana_sdk::sysvar::recent_blockhashes::IterItem(
0,
&latest_entry.blockhash,
latest_entry.fee_calculator.lamports_per_signature,
));
for (i, entry) in blockhashes.iter().enumerate() {
if i == MAX_RECENT_BLOCKHASHES - 1 {
break;
}
entries.push(solana_sdk::sysvar::recent_blockhashes::IterItem(
i as u64 + 1,
&entry.blockhash,
entry.fee_calculator.lamports_per_signature,
));
}
self.inner.set_sysvar(
&solana_sdk::sysvar::recent_blockhashes::RecentBlockhashes::from_iter(entries),
);
let mut slot_hashes = self
.inner
.get_sysvar::<solana_sdk::sysvar::slot_hashes::SlotHashes>();
slot_hashes.add(self.get_latest_absolute_slot() + 1, latest_entry.blockhash);
self.inner
.set_sysvar(&solana_sdk::sysvar::slot_hashes::SlotHashes::new(
&slot_hashes,
));
BlockIdentifier::new(
self.chain_tip.index + 1,
latest_entry.blockhash.to_string().as_str(),
)
}
/// Checks if the provided blockhash is recent (present in the RecentBlockhashes sysvar).
///
/// # Arguments
/// * `recent_blockhash` - The blockhash to check.
///
/// # Returns
/// `true` if the blockhash is recent, `false` otherwise.
pub fn check_blockhash_is_recent(&self, recent_blockhash: &Hash) -> bool {
#[allow(deprecated)]
self.inner
.get_sysvar::<solana_sdk::sysvar::recent_blockhashes::RecentBlockhashes>()
.iter()
.any(|entry| entry.blockhash == *recent_blockhash)
}
/// Sets an account in the local SVM state and notifies listeners.
///
/// # Arguments
/// * `pubkey` - The public key of the account.
/// * `account` - The [Account] to insert.
///
/// # Returns
/// `Ok(())` on success, or an error if the operation fails.
pub fn set_account(&mut self, pubkey: &Pubkey, account: Account) -> SurfpoolResult<()> {
self.updated_at = Utc::now().timestamp_millis() as u64;
self.inner
.set_account(*pubkey, account.clone())
.map_err(|e| SurfpoolError::set_account(*pubkey, e))?;
// Update the account registries and indexes
self.update_account_registries(pubkey, &account);
// Notify account subscribers
self.notify_account_subscribers(pubkey, &account);
let _ = self
.simnet_events_tx
.send(SimnetEvent::account_update(*pubkey));
Ok(())
}
pub fn update_account_registries(&mut self, pubkey: &Pubkey, account: &Account) {
// only if successful, update our indexes
if let Some(old_account) = self.accounts_registry.get(pubkey).cloned() {
self.remove_from_indexes(pubkey, &old_account);
}
// update the main registry
self.accounts_registry.insert(*pubkey, account.clone());
// add to owner index (check for duplicates)
let owner_accounts = self.accounts_by_owner.entry(account.owner).or_default();
if !owner_accounts.contains(pubkey) {
owner_accounts.push(*pubkey);
}
// if it's a token account, update token-specific indexes
if is_supported_token_program(&account.owner) {
if let Ok(token_account) = TokenAccount::unpack(&account.data) {
// index by owner -> check for duplicates
let token_owner_accounts = self
.token_accounts_by_owner
.entry(token_account.owner())
.or_default();
if !token_owner_accounts.contains(pubkey) {
token_owner_accounts.push(*pubkey);
}
// index by mint -> check for duplicates
let mint_accounts = self
.token_accounts_by_mint
.entry(token_account.mint())
.or_default();
if !mint_accounts.contains(pubkey) {
mint_accounts.push(*pubkey);
}
if let COption::Some(delegate) = token_account.delegate() {
let delegate_accounts =
self.token_accounts_by_delegate.entry(delegate).or_default();
if !delegate_accounts.contains(pubkey) {
delegate_accounts.push(*pubkey);
}
}
self.token_accounts.insert(*pubkey, token_account);
}
if let Ok(mint_account) = MintAccount::unpack(&account.data) {
self.token_mints.insert(*pubkey, mint_account);
}
if let Ok(mint) =
StateWithExtensions::<spl_token_2022::state::Mint>::unpack(&account.data)
{
let unix_timestamp = self.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();
self.account_associated_data.insert(
*pubkey,
AccountAdditionalDataV3 {
spl_token_additional_data: Some(SplTokenAdditionalDataV2 {
decimals: mint.base.decimals,
interest_bearing_config,
scaled_ui_amount_config,
}),
},
);
};
}
}
fn remove_from_indexes(&mut self, pubkey: &Pubkey, old_account: &Account) {
if let Some(accounts) = self.accounts_by_owner.get_mut(&old_account.owner) {
accounts.retain(|pk| pk != pubkey);
if accounts.is_empty() {
self.accounts_by_owner.remove(&old_account.owner);
}
}
// if it was a token account, remove from token indexes
if is_supported_token_program(&old_account.owner) {
if let Some(old_token_account) = self.token_accounts.remove(pubkey) {
if let Some(accounts) = self
.token_accounts_by_owner
.get_mut(&old_token_account.owner())
{
accounts.retain(|pk| pk != pubkey);
if accounts.is_empty() {
self.token_accounts_by_owner
.remove(&old_token_account.owner());
}
}
if let Some(accounts) = self
.token_accounts_by_mint
.get_mut(&old_token_account.mint())
{
accounts.retain(|pk| pk != pubkey);
if accounts.is_empty() {
self.token_accounts_by_mint
.remove(&old_token_account.mint());
}
}
if let COption::Some(delegate) = old_token_account.delegate() {
if let Some(accounts) = self.token_accounts_by_delegate.get_mut(&delegate) {
accounts.retain(|pk| pk != pubkey);
if accounts.is_empty() {
self.token_accounts_by_delegate.remove(&delegate);
}
}
}
}
}
}
/// Sends a transaction to the system for execution.
///
/// This function attempts to send a transaction to the blockchain. It first increments the `transactions_processed` counter.
/// Then it sends the transaction to the system and updates its status. If the transaction is successfully processed, it is
/// cached locally, and a "transaction processed" event is sent. If the transaction fails, the error is recorded and an event
/// is sent indicating the failure.
///
/// # Arguments
/// * `tx` - The transaction to send.
/// * `cu_analysis_enabled` - Whether compute unit analysis is enabled.
///
/// # Returns
/// `Ok(res)` if processed successfully, or `Err(tx_failure)` if failed.
pub fn send_transaction(
&mut self,
tx: VersionedTransaction,
cu_analysis_enabled: bool,
sigverify: bool,
) -> TransactionResult {
if sigverify && tx.verify_with_results().iter().any(|valid| !*valid) {
return Err(FailedTransactionMetadata {
err: TransactionError::SignatureFailure,
meta: TransactionMetadata::default(),
});
}
if cu_analysis_enabled {
let estimation_result = self.estimate_compute_units(&tx);
let _ = self.simnet_events_tx.try_send(SimnetEvent::info(format!(
"CU Estimation for tx: {} | Consumed: {} | Success: {} | Logs: {:?} | Error: {:?}",
tx.signatures
.first()
.map_or_else(|| "N/A".to_string(), |s| s.to_string()),
estimation_result.compute_units_consumed,
estimation_result.success,
estimation_result.log_messages,
estimation_result.error_message
)));
}
self.updated_at = Utc::now().timestamp_millis() as u64;
self.transactions_processed += 1;
if !self.check_blockhash_is_recent(tx.message.recent_blockhash()) {
let meta = TransactionMetadata::default();
let err = solana_transaction_error::TransactionError::BlockhashNotFound;
let transaction_meta = convert_transaction_metadata_from_canonical(&meta);
let _ = self
.simnet_events_tx
.try_send(SimnetEvent::transaction_processed(
transaction_meta,
Some(err.clone()),
));
return Err(FailedTransactionMetadata { err, meta });
}
self.inner.set_blockhash_check(false);
match self.inner.send_transaction(tx.clone()) {
Ok(res) => Ok(res),
Err(tx_failure) => {
let transaction_meta =
convert_transaction_metadata_from_canonical(&tx_failure.meta);
let _ = self
.simnet_events_tx
.try_send(SimnetEvent::transaction_processed(
transaction_meta,
Some(tx_failure.err.clone()),
));
Err(tx_failure)
}
}
}
/// Estimates the compute units that a transaction will consume by simulating it.
///
/// Does not commit any state changes to the SVM.
///
/// # Arguments
/// * `transaction` - The transaction to simulate.
///
/// # Returns
/// A `ComputeUnitsEstimationResult` with simulation details.
pub fn estimate_compute_units(
&self,
transaction: &VersionedTransaction,
) -> ComputeUnitsEstimationResult {
if !self.check_blockhash_is_recent(transaction.message.recent_blockhash()) {
return ComputeUnitsEstimationResult {
success: false,
compute_units_consumed: 0,
log_messages: None,
error_message: Some(
solana_transaction_error::TransactionError::BlockhashNotFound.to_string(),
),
};
}
match self.inner.simulate_transaction(transaction.clone()) {
Ok(sim_info) => ComputeUnitsEstimationResult {
success: true,
compute_units_consumed: sim_info.meta.compute_units_consumed,
log_messages: Some(sim_info.meta.logs),
error_message: None,
},
Err(failed_meta) => ComputeUnitsEstimationResult {
success: false,
compute_units_consumed: failed_meta.meta.compute_units_consumed,
log_messages: Some(failed_meta.meta.logs),
error_message: Some(failed_meta.err.to_string()),
},
}
}
/// Simulates a transaction and returns detailed simulation info or failure metadata.
///
/// # Arguments
/// * `tx` - The transaction to simulate.
///
/// # Returns
/// `Ok(SimulatedTransactionInfo)` if successful, or `Err(FailedTransactionMetadata)` if failed.
pub fn simulate_transaction(
&self,
tx: VersionedTransaction,
sigverify: bool,
) -> Result<SimulatedTransactionInfo, FailedTransactionMetadata> {
if sigverify && tx.verify_with_results().iter().any(|valid| !*valid) {
return Err(FailedTransactionMetadata {
err: TransactionError::SignatureFailure,
meta: TransactionMetadata::default(),
});
}
if !self.check_blockhash_is_recent(tx.message.recent_blockhash()) {
let meta = TransactionMetadata::default();
let err = TransactionError::BlockhashNotFound;
return Err(FailedTransactionMetadata { err, meta });
}
self.inner.simulate_transaction(tx)
}
/// Confirms transactions queued for confirmation, updates epoch/slot, and sends events.
///
/// # Returns
/// `Ok(Vec<Signature>)` with confirmed signatures, or `Err(SurfpoolError)` on error.
fn confirm_transactions(&mut self) -> Result<Vec<Signature>, SurfpoolError> {
self.updated_at = Utc::now().timestamp_millis() as u64;
let mut confirmed_transactions = vec![];
let slot = self.latest_epoch_info.slot_index;
while let Some((tx, status_tx)) = self.transactions_queued_for_confirmation.pop_front() {
let _ = status_tx.try_send(TransactionStatusEvent::Success(
TransactionConfirmationStatus::Confirmed,
));
let signature = tx.signatures[0];
let finalized_at = self.latest_epoch_info.absolute_slot + FINALIZATION_SLOT_THRESHOLD;
self.transactions_queued_for_finalization
.push_back((finalized_at, tx, status_tx));
self.notify_signature_subscribers(
SignatureSubscriptionType::confirmed(),
&signature,
slot,
None,
);
let Some(SurfnetTransactionStatus::Processed(tx_data)) =
self.transactions.get(&signature)
else {
continue;
};
self.notify_logs_subscribers(
&signature,
None,
tx_data.meta.log_messages.clone().unwrap_or(vec![]),
CommitmentLevel::Confirmed,
);
confirmed_transactions.push(signature);
}
Ok(confirmed_transactions)
}
/// Finalizes transactions queued for finalization, sending finalized events as needed.
///
/// # Returns
/// `Ok(())` on success, or `Err(SurfpoolError)` on error.
fn finalize_transactions(&mut self) -> Result<(), SurfpoolError> {
self.updated_at = Utc::now().timestamp_millis() as u64;
let current_slot = self.latest_epoch_info.absolute_slot;
let mut requeue = VecDeque::new();
while let Some((finalized_at, tx, status_tx)) =
self.transactions_queued_for_finalization.pop_front()
{
if current_slot >= finalized_at {
let _ = status_tx.try_send(TransactionStatusEvent::Success(
TransactionConfirmationStatus::Finalized,
));
let signature = &tx.signatures[0];
self.notify_signature_subscribers(
SignatureSubscriptionType::finalized(),
&signature,
self.latest_epoch_info.absolute_slot,
None,
);
let Some(tx_data) = self.transactions.get(&signature) else {
continue;
};
let logs = tx_data
.expect_processed()
.meta
.log_messages
.clone()
.unwrap_or(vec![]);
self.notify_logs_subscribers(signature, None, logs, CommitmentLevel::Finalized);
} else {
requeue.push_back((finalized_at, tx, status_tx));
}
}
// Requeue any transactions that are not yet finalized
self.transactions_queued_for_finalization
.append(&mut requeue);
Ok(())
}
/// Writes account updates to the SVM state based on the provided account update result.
///
/// # Arguments
/// * `account_update` - The account update result to process.
pub fn write_account_update(&mut self, account_update: GetAccountResult) {
self.updated_at = Utc::now().timestamp_millis() as u64;
match account_update {
GetAccountResult::FoundAccount(pubkey, account, do_update_account) => {
if do_update_account {
if let Err(e) = self.set_account(&pubkey, account.clone()) {
let _ = self
.simnet_events_tx
.send(SimnetEvent::error(e.to_string()));
}
}
}
GetAccountResult::FoundProgramAccount((pubkey, account), (_, None))
| GetAccountResult::FoundTokenAccount((pubkey, account), (_, None)) => {
if let Err(e) = self.set_account(&pubkey, account.clone()) {
let _ = self
.simnet_events_tx
.send(SimnetEvent::error(e.to_string()));
}
}
GetAccountResult::FoundProgramAccount(
(pubkey, account),
(coupled_pubkey, Some(coupled_account)),
)
| GetAccountResult::FoundTokenAccount(
(pubkey, account),
(coupled_pubkey, Some(coupled_account)),
) => {
// The data account _must_ be set first, as the program account depends on it.
if let Err(e) = self.set_account(&coupled_pubkey, coupled_account.clone()) {
let _ = self
.simnet_events_tx
.send(SimnetEvent::error(e.to_string()));
}
if let Err(e) = self.set_account(&pubkey, account.clone()) {
let _ = self
.simnet_events_tx
.send(SimnetEvent::error(e.to_string()));
}
}
GetAccountResult::None(_) => {}
}
}
pub fn confirm_current_block(&mut self) -> Result<(), SurfpoolError> {
self.updated_at = Utc::now().timestamp_millis() as u64;
// Confirm processed transactions
let confirmed_signatures = self.confirm_transactions()?;
let num_transactions = confirmed_signatures.len() as u64;
let previous_chain_tip = self.chain_tip.clone();
self.chain_tip = self.new_blockhash();
self.blocks.insert(
self.get_latest_absolute_slot(),
BlockHeader {
hash: self.chain_tip.hash.clone(),
previous_blockhash: previous_chain_tip.hash,
block_time: chrono::Utc::now().timestamp_millis(),
block_height: self.chain_tip.index,
parent_slot: self.get_latest_absolute_slot(),
signatures: confirmed_signatures,
},
);
if self.perf_samples.len() > 30 {
self.perf_samples.pop_back();
}
self.perf_samples.push_front(RpcPerfSample {
slot: self.get_latest_absolute_slot(),
num_slots: 1,
sample_period_secs: 1,
num_transactions,
num_non_vote_transactions: None,
});
self.updated_at = self.updated_at + self.slot_time;
self.latest_epoch_info.slot_index += 1;
self.latest_epoch_info.block_height = self.chain_tip.index;
self.latest_epoch_info.absolute_slot += 1;
if self.latest_epoch_info.slot_index > self.latest_epoch_info.slots_in_epoch {
self.latest_epoch_info.slot_index = 0;
self.latest_epoch_info.epoch += 1;
}
let parent_slot = self.latest_epoch_info.absolute_slot.saturating_sub(1);
let new_slot = self.latest_epoch_info.absolute_slot;
let root = new_slot.saturating_sub(FINALIZATION_SLOT_THRESHOLD);
self.notify_slot_subscribers(new_slot, parent_slot, root);
let clock: Clock = Clock {
slot: self.latest_epoch_info.absolute_slot,
epoch: self.latest_epoch_info.epoch,
unix_timestamp: Utc::now().timestamp(),
epoch_start_timestamp: 0, // todo
leader_schedule_epoch: 0, // todo
};
let _ = self
.simnet_events_tx
.send(SimnetEvent::SystemClockUpdated(clock.clone()));
self.inner.set_sysvar(&clock);
self.finalize_transactions()?;
Ok(())
}
/// Subscribes for updates on a transaction signature for a given subscription type.
///
/// # Arguments
/// * `signature` - The transaction signature to subscribe to.
/// * `subscription_type` - The type of subscription (confirmed/finalized).
///
/// # Returns
/// A receiver for slot and transaction error updates.
pub fn subscribe_for_signature_updates(
&mut self,
signature: &Signature,
subscription_type: SignatureSubscriptionType,
) -> Receiver<(Slot, Option<TransactionError>)> {
self.updated_at = Utc::now().timestamp_millis() as u64;
let (tx, rx) = unbounded();
self.signature_subscriptions
.entry(*signature)
.or_default()
.push((subscription_type, tx));
rx
}
pub fn subscribe_for_account_updates(
&mut self,
account_pubkey: &Pubkey,
encoding: Option<UiAccountEncoding>,
) -> Receiver<UiAccount> {
self.updated_at = Utc::now().timestamp_millis() as u64;
let (tx, rx) = unbounded();
self.account_subscriptions
.entry(*account_pubkey)
.or_default()
.push((encoding, tx));
rx
}
/// Notifies signature subscribers of a status update, sending slot and error info.
///
/// # Arguments
/// * `status` - The subscription type (confirmed/finalized).
/// * `signature` - The transaction signature.
/// * `slot` - The slot number.
/// * `err` - Optional transaction error.
pub fn notify_signature_subscribers(
&mut self,
status: SignatureSubscriptionType,
signature: &Signature,
slot: Slot,
err: Option<TransactionError>,
) {
self.updated_at = Utc::now().timestamp_millis() as u64;
let mut remaining = vec![];
if let Some(subscriptions) = self.signature_subscriptions.remove(signature) {
for (subscription_type, tx) in subscriptions {
if status.eq(&subscription_type) {
if tx.send((slot, err.clone())).is_err() {
// The receiver has been dropped, so we can skip notifying
continue;
}
} else {
remaining.push((subscription_type, tx));
}
}
if !remaining.is_empty() {
self.signature_subscriptions.insert(*signature, remaining);
}
}
}
pub fn notify_account_subscribers(
&mut self,
account_updated_pubkey: &Pubkey,
account: &Account,
) {
let mut remaining = vec![];
if let Some(subscriptions) = self.account_subscriptions.remove(account_updated_pubkey) {
for (encoding, tx) in subscriptions {
let config = RpcAccountInfoConfig {
encoding,
..Default::default()