-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
Copy pathrpc.rs
8805 lines (8093 loc) · 335 KB
/
rpc.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The `rpc` module implements the Solana RPC interface.
use {
crate::{
max_slots::MaxSlots, optimistically_confirmed_bank_tracker::OptimisticallyConfirmedBank,
parsed_token_accounts::*, rpc_cache::LargestAccountsCache, rpc_health::*,
},
base64::{prelude::BASE64_STANDARD, Engine},
bincode::{config::Options, serialize},
crossbeam_channel::{unbounded, Receiver, Sender},
jsonrpc_core::{futures::future, types::error, BoxFuture, Error, Metadata, Result},
jsonrpc_derive::rpc,
solana_account_decoder::{
parse_token::{is_known_spl_token_id, token_amount_to_ui_amount, UiTokenAmount},
UiAccount, UiAccountEncoding, UiDataSliceConfig, MAX_BASE58_BYTES,
},
solana_client::connection_cache::{ConnectionCache, Protocol},
solana_entry::entry::Entry,
solana_faucet::faucet::request_airdrop_transaction,
solana_gossip::{cluster_info::ClusterInfo, contact_info::ContactInfo},
solana_ledger::{
blockstore::{Blockstore, SignatureInfosForAddress},
blockstore_db::BlockstoreError,
blockstore_meta::{PerfSample, PerfSampleV1, PerfSampleV2},
get_tmp_ledger_path,
leader_schedule_cache::LeaderScheduleCache,
},
solana_metrics::inc_new_counter_info,
solana_perf::packet::PACKET_DATA_SIZE,
solana_rpc_client_api::{
config::*,
custom_error::RpcCustomError,
deprecated_config::*,
filter::{Memcmp, MemcmpEncodedBytes, RpcFilterType},
request::{
TokenAccountsFilter, DELINQUENT_VALIDATOR_SLOT_DISTANCE,
MAX_GET_CONFIRMED_BLOCKS_RANGE, MAX_GET_CONFIRMED_SIGNATURES_FOR_ADDRESS2_LIMIT,
MAX_GET_CONFIRMED_SIGNATURES_FOR_ADDRESS_SLOT_RANGE, MAX_GET_PROGRAM_ACCOUNT_FILTERS,
MAX_GET_SIGNATURE_STATUSES_QUERY_ITEMS, MAX_GET_SLOT_LEADERS, MAX_MULTIPLE_ACCOUNTS,
MAX_RPC_VOTE_ACCOUNT_INFO_EPOCH_CREDITS_HISTORY, NUM_LARGEST_ACCOUNTS,
},
response::{Response as RpcResponse, *},
},
solana_runtime::{
accounts::AccountAddressFilter,
accounts_index::{AccountIndex, AccountSecondaryIndexes, IndexKey, ScanConfig},
bank::{Bank, TransactionSimulationResult},
bank_forks::BankForks,
commitment::{BlockCommitmentArray, BlockCommitmentCache, CommitmentSlots},
inline_spl_token::{SPL_TOKEN_ACCOUNT_MINT_OFFSET, SPL_TOKEN_ACCOUNT_OWNER_OFFSET},
inline_spl_token_2022::{self, ACCOUNTTYPE_ACCOUNT},
non_circulating_supply::calculate_non_circulating_supply,
prioritization_fee_cache::PrioritizationFeeCache,
snapshot_config::SnapshotConfig,
snapshot_utils,
},
solana_sdk::{
account::{AccountSharedData, ReadableAccount},
account_utils::StateMut,
clock::{Slot, UnixTimestamp, MAX_RECENT_BLOCKHASHES},
commitment_config::{CommitmentConfig, CommitmentLevel},
epoch_info::EpochInfo,
epoch_schedule::EpochSchedule,
exit::Exit,
feature_set,
fee_calculator::FeeCalculator,
hash::Hash,
message::SanitizedMessage,
pubkey::{Pubkey, PUBKEY_BYTES},
signature::{Keypair, Signature, Signer},
stake::state::{StakeActivationStatus, StakeState},
stake_history::StakeHistory,
system_instruction,
sysvar::stake_history,
transaction::{
self, AddressLoader, MessageHash, SanitizedTransaction, TransactionError,
VersionedTransaction, MAX_TX_ACCOUNT_LOCKS,
},
},
solana_send_transaction_service::{
send_transaction_service::{SendTransactionService, TransactionInfo},
tpu_info::NullTpuInfo,
},
solana_stake_program,
solana_storage_bigtable::Error as StorageError,
solana_streamer::socket::SocketAddrSpace,
solana_transaction_status::{
BlockEncodingOptions, ConfirmedBlock, ConfirmedTransactionStatusWithSignature,
ConfirmedTransactionWithStatusMeta, EncodedConfirmedTransactionWithStatusMeta, Reward,
RewardType, TransactionBinaryEncoding, TransactionConfirmationStatus, TransactionStatus,
UiConfirmedBlock, UiTransactionEncoding,
},
solana_vote_program::vote_state::{VoteState, MAX_LOCKOUT_HISTORY},
spl_token_2022::{
extension::StateWithExtensions,
solana_program::program_pack::Pack,
state::{Account as TokenAccount, Mint},
},
std::{
any::type_name,
cmp::{max, min},
collections::{HashMap, HashSet},
convert::TryFrom,
net::SocketAddr,
str::FromStr,
sync::{
atomic::{AtomicBool, AtomicU64, Ordering},
Arc, Mutex, RwLock,
},
time::Duration,
},
};
type RpcCustomResult<T> = std::result::Result<T, RpcCustomError>;
pub const MAX_REQUEST_BODY_SIZE: usize = 50 * (1 << 10); // 50kB
pub const PERFORMANCE_SAMPLES_LIMIT: usize = 720;
fn new_response<T>(bank: &Bank, value: T) -> RpcResponse<T> {
RpcResponse {
context: RpcResponseContext::new(bank.slot()),
value,
}
}
fn is_finalized(
block_commitment_cache: &BlockCommitmentCache,
bank: &Bank,
blockstore: &Blockstore,
slot: Slot,
) -> bool {
slot <= block_commitment_cache.highest_super_majority_root()
&& (blockstore.is_root(slot) || bank.status_cache_ancestors().contains(&slot))
}
#[derive(Debug, Default, Clone)]
pub struct JsonRpcConfig {
pub enable_rpc_transaction_history: bool,
pub enable_extended_tx_metadata_storage: bool,
pub faucet_addr: Option<SocketAddr>,
pub health_check_slot_distance: u64,
pub rpc_bigtable_config: Option<RpcBigtableConfig>,
pub max_multiple_accounts: Option<usize>,
pub account_indexes: AccountSecondaryIndexes,
pub rpc_threads: usize,
pub rpc_niceness_adj: i8,
pub full_api: bool,
pub obsolete_v1_7_api: bool,
pub rpc_scan_and_fix_roots: bool,
pub max_request_body_size: Option<usize>,
}
impl JsonRpcConfig {
pub fn default_for_test() -> Self {
Self {
full_api: true,
..Self::default()
}
}
}
#[derive(Debug, Clone)]
pub struct RpcBigtableConfig {
pub enable_bigtable_ledger_upload: bool,
pub bigtable_instance_name: String,
pub bigtable_app_profile_id: String,
pub timeout: Option<Duration>,
}
impl Default for RpcBigtableConfig {
fn default() -> Self {
let bigtable_instance_name = solana_storage_bigtable::DEFAULT_INSTANCE_NAME.to_string();
let bigtable_app_profile_id = solana_storage_bigtable::DEFAULT_APP_PROFILE_ID.to_string();
Self {
enable_bigtable_ledger_upload: false,
bigtable_instance_name,
bigtable_app_profile_id,
timeout: None,
}
}
}
#[derive(Clone)]
pub struct JsonRpcRequestProcessor {
bank_forks: Arc<RwLock<BankForks>>,
block_commitment_cache: Arc<RwLock<BlockCommitmentCache>>,
blockstore: Arc<Blockstore>,
config: JsonRpcConfig,
snapshot_config: Option<SnapshotConfig>,
#[allow(dead_code)]
validator_exit: Arc<RwLock<Exit>>,
health: Arc<RpcHealth>,
cluster_info: Arc<ClusterInfo>,
genesis_hash: Hash,
transaction_sender: Arc<Mutex<Sender<TransactionInfo>>>,
bigtable_ledger_storage: Option<solana_storage_bigtable::LedgerStorage>,
optimistically_confirmed_bank: Arc<RwLock<OptimisticallyConfirmedBank>>,
largest_accounts_cache: Arc<RwLock<LargestAccountsCache>>,
max_slots: Arc<MaxSlots>,
leader_schedule_cache: Arc<LeaderScheduleCache>,
max_complete_transaction_status_slot: Arc<AtomicU64>,
max_complete_rewards_slot: Arc<AtomicU64>,
prioritization_fee_cache: Arc<PrioritizationFeeCache>,
}
impl Metadata for JsonRpcRequestProcessor {}
impl JsonRpcRequestProcessor {
fn get_bank_with_config(&self, config: RpcContextConfig) -> Result<Arc<Bank>> {
let RpcContextConfig {
commitment,
min_context_slot,
} = config;
let bank = self.bank(commitment);
if let Some(min_context_slot) = min_context_slot {
if bank.slot() < min_context_slot {
return Err(RpcCustomError::MinContextSlotNotReached {
context_slot: bank.slot(),
}
.into());
}
}
Ok(bank)
}
#[allow(deprecated)]
fn bank(&self, commitment: Option<CommitmentConfig>) -> Arc<Bank> {
debug!("RPC commitment_config: {:?}", commitment);
let commitment = commitment.unwrap_or_default();
if commitment.is_confirmed() {
let bank = self
.optimistically_confirmed_bank
.read()
.unwrap()
.bank
.clone();
debug!("RPC using optimistically confirmed slot: {:?}", bank.slot());
return bank;
}
let slot = self
.block_commitment_cache
.read()
.unwrap()
.slot_with_commitment(commitment.commitment);
match commitment.commitment {
// Recent variant is deprecated
CommitmentLevel::Recent | CommitmentLevel::Processed => {
debug!("RPC using the heaviest slot: {:?}", slot);
}
// Root variant is deprecated
CommitmentLevel::Root => {
debug!("RPC using node root: {:?}", slot);
}
// Single variant is deprecated
CommitmentLevel::Single => {
debug!("RPC using confirmed slot: {:?}", slot);
}
// Max variant is deprecated
CommitmentLevel::Max | CommitmentLevel::Finalized => {
debug!("RPC using block: {:?}", slot);
}
CommitmentLevel::SingleGossip | CommitmentLevel::Confirmed => unreachable!(), // SingleGossip variant is deprecated
};
let r_bank_forks = self.bank_forks.read().unwrap();
r_bank_forks.get(slot).unwrap_or_else(|| {
// We log a warning instead of returning an error, because all known error cases
// are due to known bugs that should be fixed instead.
//
// The slot may not be found as a result of a known bug in snapshot creation, where
// the bank at the given slot was not included in the snapshot.
// Also, it may occur after an old bank has been purged from BankForks and a new
// BlockCommitmentCache has not yet arrived. To make this case impossible,
// BlockCommitmentCache should hold an `Arc<Bank>` everywhere it currently holds
// a slot.
//
// For more information, see https://github.com/solana-labs/solana/issues/11078
warn!(
"Bank with {:?} not found at slot: {:?}",
commitment.commitment, slot
);
r_bank_forks.root_bank()
})
}
fn genesis_creation_time(&self) -> UnixTimestamp {
self.bank(None).genesis_creation_time()
}
#[allow(clippy::too_many_arguments)]
pub fn new(
config: JsonRpcConfig,
snapshot_config: Option<SnapshotConfig>,
bank_forks: Arc<RwLock<BankForks>>,
block_commitment_cache: Arc<RwLock<BlockCommitmentCache>>,
blockstore: Arc<Blockstore>,
validator_exit: Arc<RwLock<Exit>>,
health: Arc<RpcHealth>,
cluster_info: Arc<ClusterInfo>,
genesis_hash: Hash,
bigtable_ledger_storage: Option<solana_storage_bigtable::LedgerStorage>,
optimistically_confirmed_bank: Arc<RwLock<OptimisticallyConfirmedBank>>,
largest_accounts_cache: Arc<RwLock<LargestAccountsCache>>,
max_slots: Arc<MaxSlots>,
leader_schedule_cache: Arc<LeaderScheduleCache>,
max_complete_transaction_status_slot: Arc<AtomicU64>,
max_complete_rewards_slot: Arc<AtomicU64>,
prioritization_fee_cache: Arc<PrioritizationFeeCache>,
) -> (Self, Receiver<TransactionInfo>) {
let (sender, receiver) = unbounded();
(
Self {
config,
snapshot_config,
bank_forks,
block_commitment_cache,
blockstore,
validator_exit,
health,
cluster_info,
genesis_hash,
transaction_sender: Arc::new(Mutex::new(sender)),
bigtable_ledger_storage,
optimistically_confirmed_bank,
largest_accounts_cache,
max_slots,
leader_schedule_cache,
max_complete_transaction_status_slot,
max_complete_rewards_slot,
prioritization_fee_cache,
},
receiver,
)
}
// Useful for unit testing
pub fn new_from_bank(
bank: &Arc<Bank>,
socket_addr_space: SocketAddrSpace,
connection_cache: Arc<ConnectionCache>,
) -> Self {
let genesis_hash = bank.hash();
let bank_forks = Arc::new(RwLock::new(BankForks::new_from_banks(
&[bank.clone()],
bank.slot(),
)));
let blockstore = Arc::new(Blockstore::open(&get_tmp_ledger_path!()).unwrap());
let exit = Arc::new(AtomicBool::new(false));
let cluster_info = Arc::new({
let keypair = Arc::new(Keypair::new());
let contact_info = ContactInfo::new_localhost(
&keypair.pubkey(),
solana_sdk::timing::timestamp(), // wallclock
);
ClusterInfo::new(contact_info, keypair, socket_addr_space)
});
let tpu_address = cluster_info
.my_contact_info()
.tpu(connection_cache.protocol())
.unwrap();
let (sender, receiver) = unbounded();
SendTransactionService::new::<NullTpuInfo>(
tpu_address,
&bank_forks,
None,
receiver,
&connection_cache,
1000,
1,
exit.clone(),
);
Self {
config: JsonRpcConfig::default(),
snapshot_config: None,
bank_forks,
block_commitment_cache: Arc::new(RwLock::new(BlockCommitmentCache::new(
HashMap::new(),
0,
CommitmentSlots::new_from_slot(bank.slot()),
))),
blockstore,
validator_exit: create_validator_exit(exit.clone()),
health: Arc::new(RpcHealth::new(
cluster_info.clone(),
None,
0,
exit,
Arc::clone(bank.get_startup_verification_complete()),
)),
cluster_info,
genesis_hash,
transaction_sender: Arc::new(Mutex::new(sender)),
bigtable_ledger_storage: None,
optimistically_confirmed_bank: Arc::new(RwLock::new(OptimisticallyConfirmedBank {
bank: bank.clone(),
})),
largest_accounts_cache: Arc::new(RwLock::new(LargestAccountsCache::new(30))),
max_slots: Arc::new(MaxSlots::default()),
leader_schedule_cache: Arc::new(LeaderScheduleCache::new_from_bank(bank)),
max_complete_transaction_status_slot: Arc::new(AtomicU64::default()),
max_complete_rewards_slot: Arc::new(AtomicU64::default()),
prioritization_fee_cache: Arc::new(PrioritizationFeeCache::default()),
}
}
pub fn get_account_info(
&self,
pubkey: &Pubkey,
config: Option<RpcAccountInfoConfig>,
) -> Result<RpcResponse<Option<UiAccount>>> {
let RpcAccountInfoConfig {
encoding,
data_slice,
commitment,
min_context_slot,
} = config.unwrap_or_default();
let bank = self.get_bank_with_config(RpcContextConfig {
commitment,
min_context_slot,
})?;
let encoding = encoding.unwrap_or(UiAccountEncoding::Binary);
let response = get_encoded_account(&bank, pubkey, encoding, data_slice)?;
Ok(new_response(&bank, response))
}
pub fn get_multiple_accounts(
&self,
pubkeys: Vec<Pubkey>,
config: Option<RpcAccountInfoConfig>,
) -> Result<RpcResponse<Vec<Option<UiAccount>>>> {
let RpcAccountInfoConfig {
encoding,
data_slice,
commitment,
min_context_slot,
} = config.unwrap_or_default();
let bank = self.get_bank_with_config(RpcContextConfig {
commitment,
min_context_slot,
})?;
let encoding = encoding.unwrap_or(UiAccountEncoding::Base64);
let accounts = pubkeys
.into_iter()
.map(|pubkey| get_encoded_account(&bank, &pubkey, encoding, data_slice))
.collect::<Result<Vec<_>>>()?;
Ok(new_response(&bank, accounts))
}
pub fn get_minimum_balance_for_rent_exemption(
&self,
data_len: usize,
commitment: Option<CommitmentConfig>,
) -> u64 {
self.bank(commitment)
.get_minimum_balance_for_rent_exemption(data_len)
}
pub fn get_program_accounts(
&self,
program_id: &Pubkey,
config: Option<RpcAccountInfoConfig>,
mut filters: Vec<RpcFilterType>,
with_context: bool,
) -> Result<OptionalContext<Vec<RpcKeyedAccount>>> {
let RpcAccountInfoConfig {
encoding,
data_slice: data_slice_config,
commitment,
min_context_slot,
} = config.unwrap_or_default();
let bank = self.get_bank_with_config(RpcContextConfig {
commitment,
min_context_slot,
})?;
let encoding = encoding.unwrap_or(UiAccountEncoding::Binary);
optimize_filters(&mut filters);
let keyed_accounts = {
if let Some(owner) = get_spl_token_owner_filter(program_id, &filters) {
self.get_filtered_spl_token_accounts_by_owner(&bank, program_id, &owner, filters)?
} else if let Some(mint) = get_spl_token_mint_filter(program_id, &filters) {
self.get_filtered_spl_token_accounts_by_mint(&bank, program_id, &mint, filters)?
} else {
self.get_filtered_program_accounts(&bank, program_id, filters)?
}
};
let accounts = if is_known_spl_token_id(program_id)
&& encoding == UiAccountEncoding::JsonParsed
{
get_parsed_token_accounts(bank.clone(), keyed_accounts.into_iter()).collect()
} else {
keyed_accounts
.into_iter()
.map(|(pubkey, account)| {
Ok(RpcKeyedAccount {
pubkey: pubkey.to_string(),
account: encode_account(&account, &pubkey, encoding, data_slice_config)?,
})
})
.collect::<Result<Vec<_>>>()?
};
Ok(match with_context {
true => OptionalContext::Context(new_response(&bank, accounts)),
false => OptionalContext::NoContext(accounts),
})
}
pub async fn get_inflation_reward(
&self,
addresses: Vec<Pubkey>,
config: Option<RpcEpochConfig>,
) -> Result<Vec<Option<RpcInflationReward>>> {
let config = config.unwrap_or_default();
let epoch_schedule = self.get_epoch_schedule();
let first_available_block = self.get_first_available_block().await;
let epoch = match config.epoch {
Some(epoch) => epoch,
None => epoch_schedule
.get_epoch(self.get_slot(RpcContextConfig {
commitment: config.commitment,
min_context_slot: config.min_context_slot,
})?)
.saturating_sub(1),
};
// Rewards for this epoch are found in the first confirmed block of the next epoch
let first_slot_in_epoch = epoch_schedule.get_first_slot_in_epoch(epoch.saturating_add(1));
if first_slot_in_epoch < first_available_block {
if self.bigtable_ledger_storage.is_some() {
return Err(RpcCustomError::LongTermStorageSlotSkipped {
slot: first_slot_in_epoch,
}
.into());
} else {
return Err(RpcCustomError::BlockCleanedUp {
slot: first_slot_in_epoch,
first_available_block,
}
.into());
}
}
let first_confirmed_block_in_epoch = *self
.get_blocks_with_limit(first_slot_in_epoch, 1, config.commitment)
.await?
.first()
.ok_or(RpcCustomError::BlockNotAvailable {
slot: first_slot_in_epoch,
})?;
let first_confirmed_block = if let Ok(Some(first_confirmed_block)) = self
.get_block(
first_confirmed_block_in_epoch,
Some(RpcBlockConfig::rewards_with_commitment(config.commitment).into()),
)
.await
{
first_confirmed_block
} else {
return Err(RpcCustomError::BlockNotAvailable {
slot: first_confirmed_block_in_epoch,
}
.into());
};
let addresses: Vec<String> = addresses
.into_iter()
.map(|pubkey| pubkey.to_string())
.collect();
let reward_hash: HashMap<String, Reward> = first_confirmed_block
.rewards
.unwrap_or_default()
.into_iter()
.filter_map(|reward| match reward.reward_type? {
RewardType::Staking | RewardType::Voting => addresses
.contains(&reward.pubkey)
.then(|| (reward.clone().pubkey, reward)),
_ => None,
})
.collect();
let rewards = addresses
.iter()
.map(|address| {
if let Some(reward) = reward_hash.get(address) {
return Some(RpcInflationReward {
epoch,
effective_slot: first_confirmed_block_in_epoch,
amount: reward.lamports.unsigned_abs(),
post_balance: reward.post_balance,
commission: reward.commission,
});
}
None
})
.collect();
Ok(rewards)
}
pub fn get_inflation_governor(
&self,
commitment: Option<CommitmentConfig>,
) -> RpcInflationGovernor {
self.bank(commitment).inflation().into()
}
pub fn get_inflation_rate(&self) -> RpcInflationRate {
let bank = self.bank(None);
let epoch = bank.epoch();
let inflation = bank.inflation();
let slot_in_year = bank.slot_in_year_for_inflation();
RpcInflationRate {
total: inflation.total(slot_in_year),
validator: inflation.validator(slot_in_year),
foundation: inflation.foundation(slot_in_year),
epoch,
}
}
pub fn get_epoch_schedule(&self) -> EpochSchedule {
// Since epoch schedule data comes from the genesis config, any commitment level should be
// fine
let bank = self.bank(Some(CommitmentConfig::finalized()));
*bank.epoch_schedule()
}
pub fn get_balance(
&self,
pubkey: &Pubkey,
config: RpcContextConfig,
) -> Result<RpcResponse<u64>> {
let bank = self.get_bank_with_config(config)?;
Ok(new_response(&bank, bank.get_balance(pubkey)))
}
fn get_recent_blockhash(
&self,
commitment: Option<CommitmentConfig>,
) -> Result<RpcResponse<RpcBlockhashFeeCalculator>> {
let bank = self.bank(commitment);
let blockhash = bank.confirmed_last_blockhash();
let lamports_per_signature = bank
.get_lamports_per_signature_for_blockhash(&blockhash)
.unwrap();
Ok(new_response(
&bank,
RpcBlockhashFeeCalculator {
blockhash: blockhash.to_string(),
fee_calculator: FeeCalculator::new(lamports_per_signature),
},
))
}
fn get_fees(&self, commitment: Option<CommitmentConfig>) -> Result<RpcResponse<RpcFees>> {
let bank = self.bank(commitment);
let blockhash = bank.confirmed_last_blockhash();
let lamports_per_signature = bank
.get_lamports_per_signature_for_blockhash(&blockhash)
.unwrap();
#[allow(deprecated)]
let last_valid_slot = bank
.get_blockhash_last_valid_slot(&blockhash)
.expect("bank blockhash queue should contain blockhash");
let last_valid_block_height = bank
.get_blockhash_last_valid_block_height(&blockhash)
.expect("bank blockhash queue should contain blockhash");
Ok(new_response(
&bank,
RpcFees {
blockhash: blockhash.to_string(),
fee_calculator: FeeCalculator::new(lamports_per_signature),
last_valid_slot,
last_valid_block_height,
},
))
}
fn get_fee_calculator_for_blockhash(
&self,
blockhash: &Hash,
commitment: Option<CommitmentConfig>,
) -> Result<RpcResponse<Option<RpcFeeCalculator>>> {
let bank = self.bank(commitment);
let lamports_per_signature = bank.get_lamports_per_signature_for_blockhash(blockhash);
Ok(new_response(
&bank,
lamports_per_signature.map(|lamports_per_signature| RpcFeeCalculator {
fee_calculator: FeeCalculator::new(lamports_per_signature),
}),
))
}
fn get_fee_rate_governor(&self) -> RpcResponse<RpcFeeRateGovernor> {
let bank = self.bank(None);
#[allow(deprecated)]
let fee_rate_governor = bank.get_fee_rate_governor();
new_response(
&bank,
RpcFeeRateGovernor {
fee_rate_governor: fee_rate_governor.clone(),
},
)
}
pub fn confirm_transaction(
&self,
signature: &Signature,
commitment: Option<CommitmentConfig>,
) -> Result<RpcResponse<bool>> {
let bank = self.bank(commitment);
let status = bank.get_signature_status(signature);
match status {
Some(status) => Ok(new_response(&bank, status.is_ok())),
None => Ok(new_response(&bank, false)),
}
}
fn get_block_commitment(&self, block: Slot) -> RpcBlockCommitment<BlockCommitmentArray> {
let r_block_commitment = self.block_commitment_cache.read().unwrap();
RpcBlockCommitment {
commitment: r_block_commitment
.get_block_commitment(block)
.map(|block_commitment| block_commitment.commitment),
total_stake: r_block_commitment.total_stake(),
}
}
fn get_slot(&self, config: RpcContextConfig) -> Result<Slot> {
let bank = self.get_bank_with_config(config)?;
Ok(bank.slot())
}
fn get_block_height(&self, config: RpcContextConfig) -> Result<u64> {
let bank = self.get_bank_with_config(config)?;
Ok(bank.block_height())
}
fn get_max_retransmit_slot(&self) -> Slot {
self.max_slots.retransmit.load(Ordering::Relaxed)
}
fn get_max_shred_insert_slot(&self) -> Slot {
self.max_slots.shred_insert.load(Ordering::Relaxed)
}
fn get_slot_leader(&self, config: RpcContextConfig) -> Result<String> {
let bank = self.get_bank_with_config(config)?;
Ok(bank.collector_id().to_string())
}
fn get_slot_leaders(
&self,
commitment: Option<CommitmentConfig>,
start_slot: Slot,
limit: usize,
) -> Result<Vec<Pubkey>> {
let bank = self.bank(commitment);
let (mut epoch, mut slot_index) =
bank.epoch_schedule().get_epoch_and_slot_index(start_slot);
let mut slot_leaders = Vec::with_capacity(limit);
while slot_leaders.len() < limit {
if let Some(leader_schedule) =
self.leader_schedule_cache.get_epoch_leader_schedule(epoch)
{
slot_leaders.extend(
leader_schedule
.get_slot_leaders()
.iter()
.skip(slot_index as usize)
.take(limit.saturating_sub(slot_leaders.len())),
);
} else {
return Err(Error::invalid_params(format!(
"Invalid slot range: leader schedule for epoch {epoch} is unavailable"
)));
}
epoch += 1;
slot_index = 0;
}
Ok(slot_leaders)
}
fn minimum_ledger_slot(&self) -> Result<Slot> {
match self.blockstore.slot_meta_iterator(0) {
Ok(mut metas) => match metas.next() {
Some((slot, _meta)) => Ok(slot),
None => Err(Error::invalid_request()),
},
Err(err) => {
warn!("slot_meta_iterator failed: {:?}", err);
Err(Error::invalid_request())
}
}
}
fn get_transaction_count(&self, config: RpcContextConfig) -> Result<u64> {
let bank = self.get_bank_with_config(config)?;
Ok(bank.transaction_count())
}
fn get_total_supply(&self, commitment: Option<CommitmentConfig>) -> Result<u64> {
let bank = self.bank(commitment);
Ok(bank.capitalization())
}
fn get_cached_largest_accounts(
&self,
filter: &Option<RpcLargestAccountsFilter>,
) -> Option<(u64, Vec<RpcAccountBalance>)> {
let largest_accounts_cache = self.largest_accounts_cache.read().unwrap();
largest_accounts_cache.get_largest_accounts(filter)
}
fn set_cached_largest_accounts(
&self,
filter: &Option<RpcLargestAccountsFilter>,
slot: u64,
accounts: &[RpcAccountBalance],
) {
let mut largest_accounts_cache = self.largest_accounts_cache.write().unwrap();
largest_accounts_cache.set_largest_accounts(filter, slot, accounts)
}
fn get_largest_accounts(
&self,
config: Option<RpcLargestAccountsConfig>,
) -> RpcCustomResult<RpcResponse<Vec<RpcAccountBalance>>> {
let config = config.unwrap_or_default();
let bank = self.bank(config.commitment);
if let Some((slot, accounts)) = self.get_cached_largest_accounts(&config.filter) {
Ok(RpcResponse {
context: RpcResponseContext::new(slot),
value: accounts,
})
} else {
let (addresses, address_filter) = if let Some(filter) = config.clone().filter {
let non_circulating_supply =
calculate_non_circulating_supply(&bank).map_err(|e| {
RpcCustomError::ScanError {
message: e.to_string(),
}
})?;
let addresses = non_circulating_supply.accounts.into_iter().collect();
let address_filter = match filter {
RpcLargestAccountsFilter::Circulating => AccountAddressFilter::Exclude,
RpcLargestAccountsFilter::NonCirculating => AccountAddressFilter::Include,
};
(addresses, address_filter)
} else {
(HashSet::new(), AccountAddressFilter::Exclude)
};
let accounts = bank
.get_largest_accounts(NUM_LARGEST_ACCOUNTS, &addresses, address_filter)
.map_err(|e| RpcCustomError::ScanError {
message: e.to_string(),
})?
.into_iter()
.map(|(address, lamports)| RpcAccountBalance {
address: address.to_string(),
lamports,
})
.collect::<Vec<RpcAccountBalance>>();
self.set_cached_largest_accounts(&config.filter, bank.slot(), &accounts);
Ok(new_response(&bank, accounts))
}
}
fn get_supply(
&self,
config: Option<RpcSupplyConfig>,
) -> RpcCustomResult<RpcResponse<RpcSupply>> {
let config = config.unwrap_or_default();
let bank = self.bank(config.commitment);
let non_circulating_supply =
calculate_non_circulating_supply(&bank).map_err(|e| RpcCustomError::ScanError {
message: e.to_string(),
})?;
let total_supply = bank.capitalization();
let non_circulating_accounts = if config.exclude_non_circulating_accounts_list {
vec![]
} else {
non_circulating_supply
.accounts
.iter()
.map(|pubkey| pubkey.to_string())
.collect()
};
Ok(new_response(
&bank,
RpcSupply {
total: total_supply,
circulating: total_supply - non_circulating_supply.lamports,
non_circulating: non_circulating_supply.lamports,
non_circulating_accounts,
},
))
}
fn get_vote_accounts(
&self,
config: Option<RpcGetVoteAccountsConfig>,
) -> Result<RpcVoteAccountStatus> {
let config = config.unwrap_or_default();
let filter_by_vote_pubkey = if let Some(ref vote_pubkey) = config.vote_pubkey {
Some(verify_pubkey(vote_pubkey)?)
} else {
None
};
let bank = self.bank(config.commitment);
let vote_accounts = bank.vote_accounts();
let epoch_vote_accounts = bank
.epoch_vote_accounts(bank.get_epoch_and_slot_index(bank.slot()).0)
.ok_or_else(Error::invalid_request)?;
let default_vote_state = VoteState::default();
let delinquent_validator_slot_distance = config
.delinquent_slot_distance
.unwrap_or(DELINQUENT_VALIDATOR_SLOT_DISTANCE);
let (current_vote_accounts, delinquent_vote_accounts): (
Vec<RpcVoteAccountInfo>,
Vec<RpcVoteAccountInfo>,
) = vote_accounts
.iter()
.filter_map(|(vote_pubkey, (activated_stake, account))| {
if let Some(filter_by_vote_pubkey) = filter_by_vote_pubkey {
if *vote_pubkey != filter_by_vote_pubkey {
return None;
}
}
let vote_state = account.vote_state();
let vote_state = vote_state.unwrap_or(&default_vote_state);
let last_vote = if let Some(vote) = vote_state.votes.iter().last() {
vote.slot()
} else {
0
};
let epoch_credits = vote_state.epoch_credits();
let epoch_credits = if epoch_credits.len()
> MAX_RPC_VOTE_ACCOUNT_INFO_EPOCH_CREDITS_HISTORY
{
epoch_credits
.iter()
.skip(epoch_credits.len() - MAX_RPC_VOTE_ACCOUNT_INFO_EPOCH_CREDITS_HISTORY)
.cloned()
.collect()
} else {
epoch_credits.clone()
};
Some(RpcVoteAccountInfo {
vote_pubkey: vote_pubkey.to_string(),
node_pubkey: vote_state.node_pubkey.to_string(),
activated_stake: *activated_stake,
commission: vote_state.commission,
root_slot: vote_state.root_slot.unwrap_or(0),
epoch_credits,
epoch_vote_account: epoch_vote_accounts.contains_key(vote_pubkey),
last_vote,
})
})
.partition(|vote_account_info| {
if bank.slot() >= delinquent_validator_slot_distance {
vote_account_info.last_vote > bank.slot() - delinquent_validator_slot_distance
} else {
vote_account_info.last_vote > 0
}
});
let keep_unstaked_delinquents = config.keep_unstaked_delinquents.unwrap_or_default();
let delinquent_vote_accounts = if !keep_unstaked_delinquents {
delinquent_vote_accounts
.into_iter()
.filter(|vote_account_info| vote_account_info.activated_stake > 0)
.collect::<Vec<_>>()
} else {
delinquent_vote_accounts
};
Ok(RpcVoteAccountStatus {
current: current_vote_accounts,
delinquent: delinquent_vote_accounts,
})
}