main.rs 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648
  1. #![allow(clippy::arithmetic_side_effects)]
  2. use {
  3. clap::{crate_description, crate_name, value_t, values_t, values_t_or_exit, App, Arg},
  4. log::*,
  5. rand::{thread_rng, Rng},
  6. rayon::prelude::*,
  7. solana_clap_utils::{
  8. hidden_unless_forced, input_parsers::pubkey_of, input_validators::is_url_or_moniker,
  9. },
  10. solana_cli_config::{ConfigInput, CONFIG_FILE},
  11. solana_client::{
  12. rpc_client::SerializableTransaction, rpc_config::RpcBlockConfig,
  13. rpc_request::MAX_GET_CONFIRMED_BLOCKS_RANGE, transaction_executor::TransactionExecutor,
  14. },
  15. solana_clock::Slot,
  16. solana_commitment_config::CommitmentConfig,
  17. solana_gossip::gossip_service::discover,
  18. solana_hash::Hash,
  19. solana_instruction::{AccountMeta, Instruction},
  20. solana_keypair::{read_keypair_file, Keypair},
  21. solana_measure::measure::Measure,
  22. solana_message::Message,
  23. solana_program_pack::Pack,
  24. solana_pubkey::Pubkey,
  25. solana_rpc_client::rpc_client::RpcClient,
  26. solana_rpc_client_api::request::TokenAccountsFilter,
  27. solana_signature::Signature,
  28. solana_signer::Signer,
  29. solana_streamer::socket::SocketAddrSpace,
  30. solana_system_interface::{instruction as system_instruction, program as system_program},
  31. solana_transaction::Transaction,
  32. solana_transaction_status::UiTransactionEncoding,
  33. spl_generic_token::token,
  34. spl_token_interface::state::Account,
  35. std::{
  36. cmp::min,
  37. collections::VecDeque,
  38. ops::Deref,
  39. process::exit,
  40. str::FromStr,
  41. sync::{
  42. atomic::{AtomicBool, AtomicU64, Ordering},
  43. Arc, Barrier, RwLock,
  44. },
  45. thread::{sleep, Builder, JoinHandle},
  46. time::{Duration, Instant},
  47. },
  48. };
  49. #[cfg(not(any(target_env = "msvc", target_os = "freebsd")))]
  50. #[global_allocator]
  51. static GLOBAL: jemallocator::Jemalloc = jemallocator::Jemalloc;
  52. pub const MAX_RPC_CALL_RETRIES: usize = 5;
  53. pub fn poll_slot_height(client: &RpcClient) -> Slot {
  54. let mut num_retries = MAX_RPC_CALL_RETRIES;
  55. loop {
  56. let response = client.get_slot_with_commitment(CommitmentConfig::confirmed());
  57. if let Ok(slot) = response {
  58. return slot;
  59. } else {
  60. num_retries -= 1;
  61. warn!(
  62. "get_slot_height failure: {:?}. remaining retries {}",
  63. response, num_retries
  64. );
  65. }
  66. if num_retries == 0 {
  67. panic!("failed to get_slot_height(), rpc node down?")
  68. }
  69. sleep(Duration::from_millis(100));
  70. }
  71. }
  72. pub fn poll_get_latest_blockhash(client: &RpcClient) -> Option<Hash> {
  73. let mut num_retries = MAX_RPC_CALL_RETRIES;
  74. loop {
  75. let response = client.get_latest_blockhash();
  76. if let Ok(blockhash) = response {
  77. return Some(blockhash);
  78. } else {
  79. num_retries -= 1;
  80. warn!(
  81. "get_latest_blockhash failure: {:?}. remaining retries {}",
  82. response, num_retries
  83. );
  84. }
  85. if num_retries == 0 {
  86. panic!("failed to get_latest_blockhash(), rpc node down?")
  87. }
  88. sleep(Duration::from_millis(100));
  89. }
  90. }
  91. pub fn poll_get_fee_for_message(client: &RpcClient, message: &mut Message) -> (Option<u64>, Hash) {
  92. let mut num_retries = MAX_RPC_CALL_RETRIES;
  93. loop {
  94. let response = client.get_fee_for_message(message);
  95. if let Ok(fee) = response {
  96. return (Some(fee), message.recent_blockhash);
  97. } else {
  98. num_retries -= 1;
  99. warn!(
  100. "get_fee_for_message failure: {:?}. remaining retries {}",
  101. response, num_retries
  102. );
  103. let blockhash = poll_get_latest_blockhash(client).expect("blockhash");
  104. message.recent_blockhash = blockhash;
  105. }
  106. if num_retries == 0 {
  107. panic!("failed to get_fee_for_message(), rpc node down?")
  108. }
  109. sleep(Duration::from_millis(100));
  110. }
  111. }
  112. fn airdrop_lamports(client: &RpcClient, id: &Keypair, desired_balance: u64) -> bool {
  113. let starting_balance = client.get_balance(&id.pubkey()).unwrap_or(0);
  114. info!("starting balance {}", starting_balance);
  115. if starting_balance < desired_balance {
  116. let airdrop_amount = desired_balance - starting_balance;
  117. info!(
  118. "Airdropping {:?} lamports from {} for {}",
  119. airdrop_amount,
  120. client.url(),
  121. id.pubkey(),
  122. );
  123. let blockhash = client.get_latest_blockhash().unwrap();
  124. if let Err(err) =
  125. client.request_airdrop_with_blockhash(&id.pubkey(), airdrop_amount, &blockhash)
  126. {
  127. panic!(
  128. "Error requesting airdrop: {err:?} to addr: {0:?} amount: {airdrop_amount}",
  129. id.pubkey()
  130. );
  131. }
  132. let current_balance = client.get_balance(&id.pubkey()).unwrap_or_else(|e| {
  133. panic!("airdrop error {e}");
  134. });
  135. info!("current balance {}...", current_balance);
  136. if current_balance - starting_balance != airdrop_amount {
  137. info!(
  138. "Airdrop failed? {} {} {} {}",
  139. id.pubkey(),
  140. current_balance,
  141. starting_balance,
  142. airdrop_amount,
  143. );
  144. }
  145. }
  146. true
  147. }
  148. struct SeedTracker {
  149. max_created: Arc<AtomicU64>,
  150. max_closed: Arc<AtomicU64>,
  151. }
  152. #[derive(Clone)]
  153. struct TransactionSignatureTracker(Arc<RwLock<VecDeque<Signature>>>);
  154. impl TransactionSignatureTracker {
  155. fn get_random(&self) -> Option<Signature> {
  156. let signatures = self.read().unwrap();
  157. if signatures.is_empty() {
  158. None
  159. } else {
  160. let random_index = thread_rng().gen_range(0..signatures.len());
  161. let random_signature = signatures.get(random_index);
  162. random_signature.cloned()
  163. }
  164. }
  165. fn track_transactions(&self, transactions: &[Transaction]) {
  166. let mut lock = self.write().unwrap();
  167. for signature in transactions.iter().map(Transaction::get_signature) {
  168. lock.push_back(*signature);
  169. }
  170. }
  171. }
  172. impl Deref for TransactionSignatureTracker {
  173. type Target = Arc<RwLock<VecDeque<Signature>>>;
  174. fn deref(&self) -> &Self::Target {
  175. &self.0
  176. }
  177. }
  178. fn make_create_message(
  179. keypair: &Keypair,
  180. base_keypair: &Keypair,
  181. max_created_seed: Arc<AtomicU64>,
  182. num_instructions: usize,
  183. balance: u64,
  184. maybe_space: Option<u64>,
  185. mint: Option<Pubkey>,
  186. ) -> Message {
  187. let space = if mint.is_some() {
  188. Account::get_packed_len() as u64
  189. } else {
  190. maybe_space.unwrap_or_else(|| thread_rng().gen_range(0..1000))
  191. };
  192. let instructions: Vec<_> = (0..num_instructions)
  193. .flat_map(|_| {
  194. let program_id = if mint.is_some() {
  195. token::id()
  196. } else {
  197. system_program::id()
  198. };
  199. let seed = max_created_seed.fetch_add(1, Ordering::Relaxed).to_string();
  200. let to_pubkey =
  201. Pubkey::create_with_seed(&base_keypair.pubkey(), &seed, &program_id).unwrap();
  202. let mut instructions = vec![system_instruction::create_account_with_seed(
  203. &keypair.pubkey(),
  204. &to_pubkey,
  205. &base_keypair.pubkey(),
  206. &seed,
  207. balance,
  208. space,
  209. &program_id,
  210. )];
  211. if let Some(mint_address) = mint {
  212. instructions.push(
  213. spl_token_interface::instruction::initialize_account(
  214. &spl_token_interface::id(),
  215. &to_pubkey,
  216. &mint_address,
  217. &base_keypair.pubkey(),
  218. )
  219. .unwrap(),
  220. );
  221. instructions.push(
  222. spl_token_interface::instruction::approve(
  223. &spl_token_interface::id(),
  224. &to_pubkey,
  225. &base_keypair.pubkey(),
  226. &base_keypair.pubkey(),
  227. &[&base_keypair.pubkey()],
  228. 1,
  229. )
  230. .unwrap(),
  231. );
  232. }
  233. instructions
  234. })
  235. .collect();
  236. Message::new(&instructions, Some(&keypair.pubkey()))
  237. }
  238. fn make_close_message(
  239. keypair: &Keypair,
  240. base_keypair: &Keypair,
  241. max_created: &AtomicU64,
  242. max_closed: &AtomicU64,
  243. num_instructions: usize,
  244. balance: u64,
  245. spl_token: bool,
  246. ) -> Message {
  247. let instructions: Vec<_> = (0..num_instructions)
  248. .filter_map(|_| {
  249. let program_id = if spl_token {
  250. token::id()
  251. } else {
  252. system_program::id()
  253. };
  254. let max_created_seed = max_created.load(Ordering::Relaxed);
  255. let max_closed_seed = max_closed.load(Ordering::Relaxed);
  256. if max_closed_seed >= max_created_seed {
  257. return None;
  258. }
  259. let seed = max_closed.fetch_add(1, Ordering::Relaxed).to_string();
  260. let address =
  261. Pubkey::create_with_seed(&base_keypair.pubkey(), &seed, &program_id).unwrap();
  262. if spl_token {
  263. Some(
  264. spl_token_interface::instruction::close_account(
  265. &spl_token_interface::id(),
  266. &address,
  267. &keypair.pubkey(),
  268. &base_keypair.pubkey(),
  269. &[],
  270. )
  271. .unwrap(),
  272. )
  273. } else {
  274. Some(system_instruction::transfer_with_seed(
  275. &address,
  276. &base_keypair.pubkey(),
  277. seed,
  278. &program_id,
  279. &keypair.pubkey(),
  280. balance,
  281. ))
  282. }
  283. })
  284. .collect();
  285. Message::new(&instructions, Some(&keypair.pubkey()))
  286. }
  287. #[derive(Clone, Copy, Debug)]
  288. pub enum RpcBench {
  289. Version,
  290. Slot,
  291. MultipleAccounts,
  292. ProgramAccounts,
  293. TokenAccountsByOwner,
  294. Supply,
  295. TokenAccountsByDelegate,
  296. Block,
  297. Blocks,
  298. AccountInfo,
  299. Transaction,
  300. TransactionParsed,
  301. FirstAvailableBlock,
  302. }
  303. #[derive(Debug)]
  304. pub enum RpcParseError {
  305. InvalidOption,
  306. }
  307. impl FromStr for RpcBench {
  308. type Err = RpcParseError;
  309. fn from_str(s: &str) -> Result<Self, Self::Err> {
  310. match s {
  311. "account-info" => Ok(RpcBench::AccountInfo),
  312. "block" => Ok(RpcBench::Block),
  313. "blocks" => Ok(RpcBench::Blocks),
  314. "first-available-block" => Ok(RpcBench::FirstAvailableBlock),
  315. "slot" => Ok(RpcBench::Slot),
  316. "supply" => Ok(RpcBench::Supply),
  317. "multiple-accounts" => Ok(RpcBench::MultipleAccounts),
  318. "token-accounts-by-delegate" => Ok(RpcBench::TokenAccountsByDelegate),
  319. "token-accounts-by-owner" => Ok(RpcBench::TokenAccountsByOwner),
  320. "transaction" => Ok(RpcBench::Transaction),
  321. "transaction-parsed" => Ok(RpcBench::TransactionParsed),
  322. "version" => Ok(RpcBench::Version),
  323. _ => Err(RpcParseError::InvalidOption),
  324. }
  325. }
  326. }
  327. fn process_get_multiple_accounts(
  328. max_closed: &AtomicU64,
  329. max_created: &AtomicU64,
  330. stats: &mut RpcBenchStats,
  331. last_error: &mut Instant,
  332. base_keypair_pubkey: &Pubkey,
  333. program_id: &Pubkey,
  334. client: &RpcClient,
  335. ) {
  336. let start = max_closed.load(Ordering::Relaxed);
  337. let end = max_created.load(Ordering::Relaxed);
  338. let mut chunk_start = start;
  339. let chunk_size = 10;
  340. while chunk_start < end {
  341. let chunk_end = std::cmp::min(chunk_start + chunk_size, end);
  342. let addresses: Vec<_> = (chunk_start..chunk_end)
  343. .map(|seed| {
  344. Pubkey::create_with_seed(base_keypair_pubkey, &seed.to_string(), program_id)
  345. .unwrap()
  346. })
  347. .collect();
  348. chunk_start = chunk_end;
  349. let mut rpc_time = Measure::start("rpc-get-multiple-accounts");
  350. match client.get_multiple_accounts(&addresses) {
  351. Ok(accounts) => {
  352. rpc_time.stop();
  353. for account in accounts.into_iter().flatten() {
  354. if thread_rng().gen_ratio(1, 10_000) {
  355. info!(
  356. "account: lamports {:?} size: {} owner: {:?}",
  357. account.lamports,
  358. account.data.len(),
  359. account.owner
  360. );
  361. }
  362. }
  363. stats.total_success_time_us += rpc_time.as_us();
  364. stats.success += 1;
  365. }
  366. Err(e) => {
  367. rpc_time.stop();
  368. stats.total_errors_time_us += rpc_time.as_us();
  369. stats.errors += 1;
  370. if last_error.elapsed().as_secs() > 2 {
  371. info!("error: {:?}", e);
  372. *last_error = Instant::now();
  373. }
  374. debug!("error: {:?}", e);
  375. }
  376. }
  377. }
  378. }
  379. fn process_get_transaction(
  380. test_name: &'static str,
  381. transaction_signature_tracker: &TransactionSignatureTracker,
  382. client: &RpcClient,
  383. stats: &mut RpcBenchStats,
  384. last_error: &mut Instant,
  385. encoding: UiTransactionEncoding,
  386. ) {
  387. let Some(signature) = transaction_signature_tracker.get_random() else {
  388. info!("transaction: No transactions have yet been made; skipping");
  389. return;
  390. };
  391. let mut measure = Measure::start(test_name);
  392. match client.get_transaction(&signature, encoding) {
  393. Ok(_tx) => {
  394. measure.stop();
  395. stats.success += 1;
  396. stats.total_success_time_us += measure.as_us();
  397. }
  398. Err(e) => {
  399. measure.stop();
  400. stats.errors += 1;
  401. stats.total_errors_time_us += measure.as_us();
  402. if last_error.elapsed().as_secs() > 2 {
  403. info!("get_transaction error: {:?}", &e);
  404. *last_error = Instant::now();
  405. }
  406. }
  407. };
  408. }
  409. #[derive(Default)]
  410. struct RpcBenchStats {
  411. errors: u64,
  412. success: u64,
  413. total_errors_time_us: u64,
  414. total_success_time_us: u64,
  415. }
  416. #[allow(clippy::too_many_arguments)]
  417. fn run_rpc_bench_loop(
  418. rpc_bench: RpcBench,
  419. thread: usize,
  420. client: &RpcClient,
  421. base_keypair_pubkey: &Pubkey,
  422. exit: &AtomicBool,
  423. program_id: &Pubkey,
  424. max_closed: &AtomicU64,
  425. max_created: &AtomicU64,
  426. slot_height: &AtomicU64,
  427. mint: &Option<Pubkey>,
  428. transaction_signature_tracker: &TransactionSignatureTracker,
  429. ) {
  430. let mut stats = RpcBenchStats::default();
  431. let mut iters = 0;
  432. let mut last_error = Instant::now();
  433. let mut last_print = Instant::now();
  434. fn flush_stats(
  435. iters: &i32,
  436. last_print: &mut Instant,
  437. rpc_bench: &RpcBench,
  438. stats: &mut RpcBenchStats,
  439. thread: &usize,
  440. ) {
  441. info!(
  442. "t({}) rpc({:?}) iters: {} success: {} errors: {}",
  443. thread, rpc_bench, iters, stats.success, stats.errors
  444. );
  445. if stats.success > 0 {
  446. info!(
  447. " t({}) rpc({:?} average success_time: {} us",
  448. thread,
  449. rpc_bench,
  450. stats.total_success_time_us / stats.success
  451. );
  452. }
  453. if stats.errors > 0 {
  454. info!(
  455. " rpc average average errors time: {} us",
  456. stats.total_errors_time_us / stats.errors
  457. );
  458. }
  459. *last_print = Instant::now();
  460. *stats = RpcBenchStats::default();
  461. }
  462. loop {
  463. if exit.load(Ordering::Relaxed) {
  464. flush_stats(&iters, &mut last_print, &rpc_bench, &mut stats, &thread);
  465. break;
  466. }
  467. match rpc_bench {
  468. RpcBench::AccountInfo => {
  469. let start: u64 = max_closed.load(Ordering::Relaxed);
  470. let end: u64 = max_created.load(Ordering::Relaxed);
  471. let seed_range = start..end;
  472. if seed_range.is_empty() {
  473. info!("get_account_info: No accounts have yet been created; skipping");
  474. continue;
  475. }
  476. let seed = thread_rng().gen_range(seed_range).to_string();
  477. let account_pubkey =
  478. Pubkey::create_with_seed(base_keypair_pubkey, &seed, program_id).unwrap();
  479. let mut rpc_time = Measure::start("rpc-get-account-info");
  480. match client.get_account(&account_pubkey) {
  481. Ok(_account) => {
  482. rpc_time.stop();
  483. stats.success += 1;
  484. stats.total_success_time_us += rpc_time.as_us();
  485. }
  486. Err(e) => {
  487. rpc_time.stop();
  488. stats.total_errors_time_us += rpc_time.as_us();
  489. stats.errors += 1;
  490. if last_error.elapsed().as_secs() > 2 {
  491. info!("get_account_info error: {:?}", e);
  492. last_error = Instant::now();
  493. }
  494. }
  495. }
  496. }
  497. RpcBench::Block => {
  498. let slot_height = slot_height.load(Ordering::Relaxed);
  499. let mut rpc_time = Measure::start("rpc-get-block");
  500. match client.get_block_with_config(
  501. slot_height,
  502. RpcBlockConfig {
  503. commitment: Some(CommitmentConfig::confirmed()),
  504. ..Default::default()
  505. },
  506. ) {
  507. Ok(_block) => {
  508. rpc_time.stop();
  509. stats.success += 1;
  510. stats.total_success_time_us += rpc_time.as_us();
  511. }
  512. Err(e) => {
  513. rpc_time.stop();
  514. stats.total_errors_time_us += rpc_time.as_us();
  515. stats.errors += 1;
  516. if last_error.elapsed().as_secs() > 2 {
  517. info!("get_block error: {:?}", e);
  518. last_error = Instant::now();
  519. }
  520. }
  521. }
  522. }
  523. RpcBench::Blocks => {
  524. let slot_height = slot_height.load(Ordering::Relaxed);
  525. let mut rpc_time = Measure::start("rpc-get-blocks");
  526. match client.get_blocks_with_commitment(
  527. slot_height.saturating_sub(MAX_GET_CONFIRMED_BLOCKS_RANGE),
  528. Some(slot_height),
  529. CommitmentConfig::confirmed(),
  530. ) {
  531. Ok(_slots) => {
  532. rpc_time.stop();
  533. stats.success += 1;
  534. stats.total_success_time_us += rpc_time.as_us();
  535. }
  536. Err(e) => {
  537. rpc_time.stop();
  538. stats.total_errors_time_us += rpc_time.as_us();
  539. stats.errors += 1;
  540. if last_error.elapsed().as_secs() > 2 {
  541. info!("get_blocks error: {:?}", e);
  542. last_error = Instant::now();
  543. }
  544. }
  545. }
  546. }
  547. RpcBench::FirstAvailableBlock => {
  548. let mut rpc_time = Measure::start("rpc-get-first-available-block");
  549. match client.get_first_available_block() {
  550. Ok(_slot) => {
  551. rpc_time.stop();
  552. stats.success += 1;
  553. stats.total_success_time_us += rpc_time.as_us();
  554. }
  555. Err(e) => {
  556. rpc_time.stop();
  557. stats.total_errors_time_us += rpc_time.as_us();
  558. stats.errors += 1;
  559. if last_error.elapsed().as_secs() > 2 {
  560. info!("get_first_available_block error: {:?}", e);
  561. last_error = Instant::now();
  562. }
  563. }
  564. }
  565. }
  566. RpcBench::Slot => {
  567. let mut rpc_time = Measure::start("rpc-get-slot");
  568. match client.get_slot() {
  569. Ok(_slot) => {
  570. rpc_time.stop();
  571. stats.success += 1;
  572. stats.total_success_time_us += rpc_time.as_us();
  573. }
  574. Err(e) => {
  575. rpc_time.stop();
  576. stats.total_errors_time_us += rpc_time.as_us();
  577. stats.errors += 1;
  578. if last_error.elapsed().as_secs() > 2 {
  579. info!("get_slot error: {:?}", e);
  580. last_error = Instant::now();
  581. }
  582. }
  583. }
  584. }
  585. RpcBench::Supply => {
  586. let mut rpc_time = Measure::start("rpc-get-token-supply");
  587. match client.get_token_supply(&mint.unwrap()) {
  588. Ok(_ui_token_amount) => {
  589. rpc_time.stop();
  590. stats.success += 1;
  591. stats.total_success_time_us += rpc_time.as_us();
  592. }
  593. Err(e) => {
  594. rpc_time.stop();
  595. stats.total_errors_time_us += rpc_time.as_us();
  596. stats.errors += 1;
  597. if last_error.elapsed().as_secs() > 2 {
  598. info!("get_token_supply error: {:?}", e);
  599. last_error = Instant::now();
  600. }
  601. }
  602. }
  603. }
  604. RpcBench::MultipleAccounts => {
  605. process_get_multiple_accounts(
  606. max_closed,
  607. max_created,
  608. &mut stats,
  609. &mut last_error,
  610. base_keypair_pubkey,
  611. program_id,
  612. client,
  613. );
  614. }
  615. RpcBench::ProgramAccounts => {
  616. let mut rpc_time = Measure::start("rpc-get-program-accounts");
  617. match client.get_program_accounts(program_id) {
  618. Ok(accounts) => {
  619. rpc_time.stop();
  620. stats.success += 1;
  621. stats.total_success_time_us += rpc_time.as_us();
  622. if thread_rng().gen_ratio(1, 100) {
  623. info!("accounts: {} first: {:?}", accounts.len(), accounts.first());
  624. }
  625. }
  626. Err(e) => {
  627. rpc_time.stop();
  628. stats.errors += 1;
  629. stats.total_errors_time_us += rpc_time.as_us();
  630. if last_error.elapsed().as_secs() > 2 {
  631. info!("get-program-accounts error: {:?}", e);
  632. last_error = Instant::now();
  633. }
  634. }
  635. }
  636. }
  637. RpcBench::TokenAccountsByDelegate => {
  638. let mut rpc_time = Measure::start("rpc-get-token-accounts-by-delegate");
  639. let filter = TokenAccountsFilter::Mint(*mint.as_ref().unwrap());
  640. match client.get_token_accounts_by_delegate(base_keypair_pubkey, filter) {
  641. Ok(_accounts) => {
  642. rpc_time.stop();
  643. stats.success += 1;
  644. stats.total_success_time_us += rpc_time.as_us();
  645. }
  646. Err(e) => {
  647. rpc_time.stop();
  648. stats.errors += 1;
  649. stats.total_errors_time_us += rpc_time.as_us();
  650. if last_error.elapsed().as_secs() > 2 {
  651. info!("get-token-accounts-by-delegate error: {:?}", e);
  652. last_error = Instant::now();
  653. }
  654. }
  655. }
  656. }
  657. RpcBench::TokenAccountsByOwner => {
  658. let mut rpc_time = Measure::start("rpc-get-token-accounts-by-owner");
  659. let filter = TokenAccountsFilter::Mint(*mint.as_ref().unwrap());
  660. match client.get_token_accounts_by_owner(base_keypair_pubkey, filter) {
  661. Ok(_accounts) => {
  662. rpc_time.stop();
  663. stats.success += 1;
  664. stats.total_success_time_us += rpc_time.as_us();
  665. }
  666. Err(e) => {
  667. rpc_time.stop();
  668. stats.errors += 1;
  669. stats.total_errors_time_us += rpc_time.as_us();
  670. if last_error.elapsed().as_secs() > 2 {
  671. info!("get-token-accounts-by-owner error: {:?}", e);
  672. last_error = Instant::now();
  673. }
  674. }
  675. }
  676. }
  677. RpcBench::Transaction => {
  678. process_get_transaction(
  679. "rpc-get-transaction-base64",
  680. transaction_signature_tracker,
  681. client,
  682. &mut stats,
  683. &mut last_error,
  684. UiTransactionEncoding::Base64,
  685. );
  686. }
  687. RpcBench::TransactionParsed => {
  688. process_get_transaction(
  689. "rpc-get-transaction-parsed",
  690. transaction_signature_tracker,
  691. client,
  692. &mut stats,
  693. &mut last_error,
  694. UiTransactionEncoding::JsonParsed,
  695. );
  696. }
  697. RpcBench::Version => {
  698. let mut rpc_time = Measure::start("rpc-get-version");
  699. match client.get_version() {
  700. Ok(_r) => {
  701. rpc_time.stop();
  702. stats.success += 1;
  703. stats.total_success_time_us += rpc_time.as_us();
  704. }
  705. Err(_e) => {
  706. rpc_time.stop();
  707. stats.errors += 1;
  708. stats.total_errors_time_us += rpc_time.as_us();
  709. }
  710. }
  711. }
  712. }
  713. if last_print.elapsed().as_secs() > 3 {
  714. flush_stats(&iters, &mut last_print, &rpc_bench, &mut stats, &thread);
  715. }
  716. iters += 1;
  717. }
  718. }
  719. #[allow(clippy::too_many_arguments)]
  720. fn make_rpc_bench_threads(
  721. rpc_benches: Vec<RpcBench>,
  722. mint: &Option<Pubkey>,
  723. start_bench_barrier: &Arc<Barrier>,
  724. exit: &Arc<AtomicBool>,
  725. client: &Arc<RpcClient>,
  726. seed_tracker: &SeedTracker,
  727. slot_height: &Arc<AtomicU64>,
  728. base_keypair_pubkey: Pubkey,
  729. num_rpc_bench_threads: usize,
  730. transaction_signature_tracker: &TransactionSignatureTracker,
  731. ) -> Vec<JoinHandle<()>> {
  732. let program_id = if mint.is_some() {
  733. token::id()
  734. } else {
  735. system_program::id()
  736. };
  737. rpc_benches
  738. .into_iter()
  739. .flat_map(|rpc_bench| {
  740. (0..num_rpc_bench_threads).map(move |thread| {
  741. let client = client.clone();
  742. let start_bench = start_bench_barrier.clone();
  743. let exit = exit.clone();
  744. let max_closed = seed_tracker.max_closed.clone();
  745. let max_created = seed_tracker.max_created.clone();
  746. let slot_height = slot_height.clone();
  747. let transaction_signature_tracker = transaction_signature_tracker.clone();
  748. let mint = *mint;
  749. Builder::new()
  750. .name(format!("rpc-bench-{}", thread))
  751. .spawn(move || {
  752. start_bench.wait();
  753. run_rpc_bench_loop(
  754. rpc_bench,
  755. thread,
  756. &client,
  757. &base_keypair_pubkey,
  758. &exit,
  759. &program_id,
  760. &max_closed,
  761. &max_created,
  762. &slot_height,
  763. &mint,
  764. &transaction_signature_tracker,
  765. )
  766. })
  767. .unwrap()
  768. })
  769. })
  770. .collect()
  771. }
  772. #[allow(clippy::too_many_arguments)]
  773. fn run_accounts_bench(
  774. client: Arc<RpcClient>,
  775. payer_keypairs: &[&Keypair],
  776. iterations: usize,
  777. maybe_space: Option<u64>,
  778. batch_size: usize,
  779. close_nth_batch: u64,
  780. maybe_lamports: Option<u64>,
  781. num_instructions: usize,
  782. max_accounts: Option<usize>,
  783. mint: Option<Pubkey>,
  784. reclaim_accounts: bool,
  785. rpc_benches: Option<Vec<RpcBench>>,
  786. num_rpc_bench_threads: usize,
  787. ) {
  788. assert!(num_instructions > 0);
  789. info!("Targeting {}", client.url());
  790. let mut latest_blockhash = Instant::now();
  791. let mut last_log = Instant::now();
  792. let mut count = 0;
  793. let mut blockhash = poll_get_latest_blockhash(&client).expect("blockhash");
  794. let slot_height = Arc::new(AtomicU64::new(poll_slot_height(&client)));
  795. let mut tx_sent_count = 0;
  796. let mut total_accounts_created = 0;
  797. let mut total_accounts_closed = 0;
  798. let mut balances: Vec<_> = payer_keypairs
  799. .iter()
  800. .map(|keypair| client.get_balance(&keypair.pubkey()).unwrap_or(0))
  801. .collect();
  802. let mut last_balance = Instant::now();
  803. let default_max_lamports = 1000;
  804. let min_balance = maybe_lamports.unwrap_or_else(|| {
  805. let space = maybe_space.unwrap_or(default_max_lamports);
  806. client
  807. .get_minimum_balance_for_rent_exemption(space as usize)
  808. .expect("min balance")
  809. });
  810. let base_keypair = Keypair::new();
  811. let seed_tracker = SeedTracker {
  812. max_created: Arc::new(AtomicU64::default()),
  813. max_closed: Arc::new(AtomicU64::default()),
  814. };
  815. let transaction_signature_tracker =
  816. TransactionSignatureTracker(Arc::new(RwLock::new(VecDeque::with_capacity(5000))));
  817. info!("Starting balance(s): {:?}", balances);
  818. let executor = TransactionExecutor::new_with_rpc_client(client.clone());
  819. // Create and close messages both require 2 signatures, fake a 2 signature message to calculate fees
  820. let mut message = Message::new(
  821. &[
  822. Instruction::new_with_bytes(
  823. Pubkey::new_unique(),
  824. &[],
  825. vec![AccountMeta::new(Pubkey::new_unique(), true)],
  826. ),
  827. Instruction::new_with_bytes(
  828. Pubkey::new_unique(),
  829. &[],
  830. vec![AccountMeta::new(Pubkey::new_unique(), true)],
  831. ),
  832. ],
  833. None,
  834. );
  835. let exit = Arc::new(AtomicBool::new(false));
  836. let mut start_bench_barrier = Some(Arc::new(Barrier::new(
  837. // In order to unlock the benchmark threads, `wait()` must be called on each thread and then
  838. // once from this thread, after the first pass through the account creation loop.
  839. num_rpc_bench_threads + 1,
  840. )));
  841. let base_keypair_pubkey = base_keypair.pubkey();
  842. let rpc_bench_threads: Vec<_> = if let Some(rpc_benches) = rpc_benches {
  843. make_rpc_bench_threads(
  844. rpc_benches,
  845. &mint,
  846. start_bench_barrier.as_ref().unwrap(),
  847. &exit,
  848. &client,
  849. &seed_tracker,
  850. &slot_height,
  851. base_keypair_pubkey,
  852. num_rpc_bench_threads,
  853. &transaction_signature_tracker,
  854. )
  855. } else {
  856. Vec::new()
  857. };
  858. loop {
  859. if latest_blockhash.elapsed().as_millis() > 10_000 {
  860. blockhash = poll_get_latest_blockhash(&client).expect("blockhash");
  861. slot_height.store(poll_slot_height(&client), Ordering::Relaxed);
  862. latest_blockhash = Instant::now();
  863. }
  864. message.recent_blockhash = blockhash;
  865. let (fee, blockhash) = poll_get_fee_for_message(&client, &mut message);
  866. let fee = fee.expect("get_fee_for_message");
  867. let lamports = min_balance + fee;
  868. for (i, balance) in balances.iter_mut().enumerate() {
  869. if *balance < lamports || last_balance.elapsed().as_millis() > 2000 {
  870. if let Ok(b) = client.get_balance(&payer_keypairs[i].pubkey()) {
  871. *balance = b;
  872. }
  873. last_balance = Instant::now();
  874. if *balance < lamports * 2 {
  875. info!(
  876. "Balance {} is less than needed: {}, doing airdrop...",
  877. balance, lamports
  878. );
  879. if !airdrop_lamports(&client, payer_keypairs[i], lamports * 100_000) {
  880. warn!("failed airdrop, exiting");
  881. return;
  882. }
  883. }
  884. }
  885. }
  886. // Create accounts
  887. let sigs_len = executor.num_outstanding();
  888. if sigs_len < batch_size {
  889. let num_to_create = batch_size - sigs_len;
  890. if num_to_create >= payer_keypairs.len() {
  891. info!("creating {} new", num_to_create);
  892. let chunk_size = num_to_create / payer_keypairs.len();
  893. if chunk_size > 0 {
  894. for (i, keypair) in payer_keypairs.iter().enumerate() {
  895. let txs: Vec<_> = (0..chunk_size)
  896. .into_par_iter()
  897. .map(|_| {
  898. let message = make_create_message(
  899. keypair,
  900. &base_keypair,
  901. seed_tracker.max_created.clone(),
  902. num_instructions,
  903. min_balance,
  904. maybe_space,
  905. mint,
  906. );
  907. let signers: Vec<&Keypair> = vec![keypair, &base_keypair];
  908. Transaction::new(&signers, message, blockhash)
  909. })
  910. .collect();
  911. balances[i] = balances[i].saturating_sub(lamports * txs.len() as u64);
  912. info!("txs: {}", txs.len());
  913. transaction_signature_tracker.track_transactions(&txs);
  914. let new_ids = executor.push_transactions(txs);
  915. info!("ids: {}", new_ids.len());
  916. tx_sent_count += new_ids.len();
  917. total_accounts_created += num_instructions * new_ids.len();
  918. }
  919. }
  920. }
  921. if close_nth_batch > 0 {
  922. let num_batches_to_close =
  923. total_accounts_created as u64 / (close_nth_batch * batch_size as u64);
  924. let expected_closed = num_batches_to_close * batch_size as u64;
  925. let max_closed_seed = seed_tracker.max_closed.load(Ordering::Relaxed);
  926. // Close every account we've created with seed between max_closed_seed..expected_closed
  927. if max_closed_seed < expected_closed {
  928. let txs: Vec<_> = (0..expected_closed - max_closed_seed)
  929. .into_par_iter()
  930. .map(|_| {
  931. let message = make_close_message(
  932. payer_keypairs[0],
  933. &base_keypair,
  934. &seed_tracker.max_created,
  935. &seed_tracker.max_closed,
  936. 1,
  937. min_balance,
  938. mint.is_some(),
  939. );
  940. let signers: Vec<&Keypair> = vec![payer_keypairs[0], &base_keypair];
  941. Transaction::new(&signers, message, blockhash)
  942. })
  943. .collect();
  944. balances[0] = balances[0].saturating_sub(fee * txs.len() as u64);
  945. info!("close txs: {}", txs.len());
  946. transaction_signature_tracker.track_transactions(&txs);
  947. let new_ids = executor.push_transactions(txs);
  948. info!("close ids: {}", new_ids.len());
  949. tx_sent_count += new_ids.len();
  950. total_accounts_closed += new_ids.len() as u64;
  951. }
  952. }
  953. } else {
  954. let _ = executor.drain_cleared();
  955. }
  956. if let Some(start_bench) = &start_bench_barrier {
  957. // As the final barrier participant, this call to `wait()` unlocks all the bench threads
  958. start_bench.wait();
  959. }
  960. start_bench_barrier = None;
  961. count += 1;
  962. let max_accounts_met = if let Some(max_accounts) = max_accounts {
  963. total_accounts_created >= max_accounts
  964. } else {
  965. false
  966. };
  967. if last_log.elapsed().as_millis() > 3000
  968. || (count >= iterations && iterations != 0)
  969. || max_accounts_met
  970. {
  971. info!(
  972. "total_accounts_created: {} total_accounts_closed: {} tx_sent_count: {} loop_count: {} balance(s): {:?}",
  973. total_accounts_created, total_accounts_closed, tx_sent_count, count, balances
  974. );
  975. last_log = Instant::now();
  976. }
  977. if iterations != 0 && count >= iterations {
  978. info!("{iterations} iterations reached");
  979. break;
  980. }
  981. if max_accounts_met {
  982. info!(
  983. "Max account limit of {:?} reached",
  984. max_accounts.unwrap_or_default()
  985. );
  986. break;
  987. }
  988. if executor.num_outstanding() >= batch_size {
  989. sleep(Duration::from_millis(500));
  990. }
  991. }
  992. executor.close();
  993. if reclaim_accounts {
  994. let executor = TransactionExecutor::new_with_rpc_client(client.clone());
  995. loop {
  996. let max_closed_seed = seed_tracker.max_closed.load(Ordering::Relaxed);
  997. let max_created_seed = seed_tracker.max_created.load(Ordering::Relaxed);
  998. if latest_blockhash.elapsed().as_millis() > 10_000 {
  999. blockhash = poll_get_latest_blockhash(&client).expect("blockhash");
  1000. latest_blockhash = Instant::now();
  1001. }
  1002. message.recent_blockhash = blockhash;
  1003. let (fee, blockhash) = poll_get_fee_for_message(&client, &mut message);
  1004. let fee = fee.expect("get_fee_for_message");
  1005. let sigs_len = executor.num_outstanding();
  1006. if sigs_len < batch_size && max_closed_seed < max_created_seed {
  1007. let num_to_close = min(
  1008. batch_size - sigs_len,
  1009. (max_created_seed - max_closed_seed) as usize,
  1010. );
  1011. if num_to_close >= payer_keypairs.len() {
  1012. info!("closing {} accounts", num_to_close);
  1013. let chunk_size = num_to_close / payer_keypairs.len();
  1014. info!("{:?} chunk_size", chunk_size);
  1015. if chunk_size > 0 {
  1016. for (i, keypair) in payer_keypairs.iter().enumerate() {
  1017. let txs: Vec<_> = (0..chunk_size)
  1018. .into_par_iter()
  1019. .filter_map(|_| {
  1020. let message = make_close_message(
  1021. keypair,
  1022. &base_keypair,
  1023. &seed_tracker.max_created,
  1024. &seed_tracker.max_closed,
  1025. num_instructions,
  1026. min_balance,
  1027. mint.is_some(),
  1028. );
  1029. if message.instructions.is_empty() {
  1030. return None;
  1031. }
  1032. let signers: Vec<&Keypair> = vec![keypair, &base_keypair];
  1033. Some(Transaction::new(&signers, message, blockhash))
  1034. })
  1035. .collect();
  1036. balances[i] = balances[i].saturating_sub(fee * txs.len() as u64);
  1037. info!("close txs: {}", txs.len());
  1038. transaction_signature_tracker.track_transactions(&txs);
  1039. let new_ids = executor.push_transactions(txs);
  1040. info!("close ids: {}", new_ids.len());
  1041. tx_sent_count += new_ids.len();
  1042. total_accounts_closed += (num_instructions * new_ids.len()) as u64;
  1043. }
  1044. }
  1045. }
  1046. } else {
  1047. let _ = executor.drain_cleared();
  1048. }
  1049. count += 1;
  1050. if last_log.elapsed().as_millis() > 3000 || max_closed_seed >= max_created_seed {
  1051. info!(
  1052. "total_accounts_closed: {} tx_sent_count: {} loop_count: {} balance(s): {:?}",
  1053. total_accounts_closed, tx_sent_count, count, balances
  1054. );
  1055. last_log = Instant::now();
  1056. }
  1057. if max_closed_seed >= max_created_seed {
  1058. break;
  1059. }
  1060. if executor.num_outstanding() >= batch_size {
  1061. sleep(Duration::from_millis(500));
  1062. }
  1063. }
  1064. executor.close();
  1065. }
  1066. exit.store(true, Ordering::Relaxed);
  1067. for t in rpc_bench_threads {
  1068. t.join().unwrap();
  1069. }
  1070. }
  1071. fn main() {
  1072. solana_logger::setup_with_default("solana=info");
  1073. let matches = App::new(crate_name!())
  1074. .about(crate_description!())
  1075. .version(solana_version::version!())
  1076. .arg({
  1077. let arg = Arg::with_name("config_file")
  1078. .short("C")
  1079. .long("config")
  1080. .value_name("FILEPATH")
  1081. .takes_value(true)
  1082. .help("Configuration file to use");
  1083. if let Some(ref config_file) = *CONFIG_FILE {
  1084. arg.default_value(config_file)
  1085. } else {
  1086. arg
  1087. }
  1088. })
  1089. .arg(
  1090. Arg::with_name("json_rpc_url")
  1091. .short("u")
  1092. .long("url")
  1093. .value_name("URL_OR_MONIKER")
  1094. .takes_value(true)
  1095. .validator(is_url_or_moniker)
  1096. .conflicts_with("entrypoint")
  1097. .help(
  1098. "URL for Solana's JSON RPC or moniker (or their first letter): \
  1099. [mainnet-beta, testnet, devnet, localhost]",
  1100. ),
  1101. )
  1102. .arg(
  1103. Arg::with_name("entrypoint")
  1104. .long("entrypoint")
  1105. .takes_value(true)
  1106. .value_name("HOST:PORT")
  1107. .conflicts_with("json_rpc_url")
  1108. .help("RPC entrypoint address. Usually <ip>:8899"),
  1109. )
  1110. .arg(
  1111. Arg::with_name("faucet_addr")
  1112. .long("faucet")
  1113. .takes_value(true)
  1114. .value_name("HOST:PORT")
  1115. .hidden(hidden_unless_forced())
  1116. .help("Faucet entrypoint address. Usually <ip>:9900"),
  1117. )
  1118. .arg(
  1119. Arg::with_name("space")
  1120. .long("space")
  1121. .takes_value(true)
  1122. .value_name("BYTES")
  1123. .conflicts_with("mint")
  1124. .help("Size of accounts to create"),
  1125. )
  1126. .arg(
  1127. Arg::with_name("lamports")
  1128. .long("lamports")
  1129. .takes_value(true)
  1130. .value_name("LAMPORTS")
  1131. .help("How many lamports to fund each account"),
  1132. )
  1133. .arg(
  1134. Arg::with_name("identity")
  1135. .long("identity")
  1136. .takes_value(true)
  1137. .multiple(true)
  1138. .value_name("FILE")
  1139. .help("keypair file"),
  1140. )
  1141. .arg(
  1142. Arg::with_name("batch_size")
  1143. .long("batch-size")
  1144. .takes_value(true)
  1145. .value_name("BYTES")
  1146. .help("Number of transactions to send per batch"),
  1147. )
  1148. .arg(
  1149. Arg::with_name("close_nth_batch")
  1150. .long("close-frequency")
  1151. .takes_value(true)
  1152. .value_name("BYTES")
  1153. .help(
  1154. "Every `n` batches, create a batch of close transactions for \
  1155. the earliest remaining batch of accounts created. \
  1156. Note: Should be > 1 to avoid situations where the close \
  1157. transactions will be submitted before the corresponding \
  1158. create transactions have been confirmed",
  1159. ),
  1160. )
  1161. .arg(
  1162. Arg::with_name("num_instructions")
  1163. .long("num-instructions")
  1164. .takes_value(true)
  1165. .value_name("NUM_INSTRUCTIONS")
  1166. .help("Number of accounts to create on each transaction"),
  1167. )
  1168. .arg(
  1169. Arg::with_name("iterations")
  1170. .long("iterations")
  1171. .takes_value(true)
  1172. .value_name("NUM_ITERATIONS")
  1173. .help("Number of iterations to make. 0 = unlimited iterations."),
  1174. )
  1175. .arg(
  1176. Arg::with_name("max_accounts")
  1177. .long("max-accounts")
  1178. .takes_value(true)
  1179. .value_name("NUM_ACCOUNTS")
  1180. .help("Halt after client has created this number of accounts. Does not count closed accounts."),
  1181. )
  1182. .arg(
  1183. Arg::with_name("check_gossip")
  1184. .long("check-gossip")
  1185. .help("Just use entrypoint address directly"),
  1186. )
  1187. .arg(
  1188. Arg::with_name("shred_version")
  1189. .long("shred-version")
  1190. .takes_value(true)
  1191. .value_name("VERSION")
  1192. .requires("check_gossip")
  1193. .help("The shred version to use for gossip discovery"),
  1194. )
  1195. .arg(
  1196. Arg::with_name("mint")
  1197. .long("mint")
  1198. .takes_value(true)
  1199. .value_name("MINT_ADDRESS")
  1200. .help("Mint address to initialize account"),
  1201. )
  1202. .arg(
  1203. Arg::with_name("reclaim_accounts")
  1204. .long("reclaim-accounts")
  1205. .takes_value(false)
  1206. .help("Reclaim accounts after session ends; incompatible with --iterations 0"),
  1207. )
  1208. .arg(
  1209. Arg::with_name("num_rpc_bench_threads")
  1210. .long("num-rpc-bench-threads")
  1211. .takes_value(true)
  1212. .value_name("NUM_THREADS")
  1213. .help("Spawn this many RPC benching threads for each type passed by --rpc-bench"),
  1214. )
  1215. .arg(
  1216. Arg::with_name("rpc_bench")
  1217. .long("rpc-bench")
  1218. .takes_value(true)
  1219. .value_name("RPC_BENCH_TYPE(S)")
  1220. .multiple(true)
  1221. .requires_ifs(&[
  1222. ("supply", "mint"),
  1223. ("token-accounts-by-owner", "mint"),
  1224. ])
  1225. .help("Spawn a thread which calls a specific RPC method in a loop to benchmark it"),
  1226. )
  1227. .get_matches();
  1228. let skip_gossip = !matches.is_present("check_gossip");
  1229. let space = value_t!(matches, "space", u64).ok();
  1230. let lamports = value_t!(matches, "lamports", u64).ok();
  1231. let batch_size = value_t!(matches, "batch_size", usize).unwrap_or(4);
  1232. let close_nth_batch = value_t!(matches, "close_nth_batch", u64).unwrap_or(0);
  1233. let iterations = value_t!(matches, "iterations", usize).unwrap_or(10);
  1234. let max_accounts = value_t!(matches, "max_accounts", usize).ok();
  1235. let num_instructions = value_t!(matches, "num_instructions", usize).unwrap_or(1);
  1236. if num_instructions == 0 || num_instructions > 500 {
  1237. eprintln!("bad num_instructions: {num_instructions}");
  1238. exit(1);
  1239. }
  1240. let rpc_benches = values_t!(matches, "rpc_bench", String)
  1241. .map(|benches| {
  1242. benches
  1243. .into_iter()
  1244. .map(|bench| RpcBench::from_str(&bench).unwrap())
  1245. .collect()
  1246. })
  1247. .ok();
  1248. let num_rpc_bench_threads = if rpc_benches.is_none() {
  1249. 0
  1250. } else {
  1251. value_t!(matches, "num_rpc_bench_threads", usize).unwrap_or(1)
  1252. };
  1253. let mint = pubkey_of(&matches, "mint");
  1254. let payer_keypairs: Vec<_> = values_t_or_exit!(matches, "identity", String)
  1255. .iter()
  1256. .map(|keypair_string| {
  1257. read_keypair_file(keypair_string)
  1258. .unwrap_or_else(|_| panic!("bad keypair {keypair_string:?}"))
  1259. })
  1260. .collect();
  1261. let mut payer_keypair_refs: Vec<&Keypair> = vec![];
  1262. for keypair in payer_keypairs.iter() {
  1263. payer_keypair_refs.push(keypair);
  1264. }
  1265. let client = if let Some(addr) = matches.value_of("entrypoint") {
  1266. let entrypoint_addr = solana_net_utils::parse_host_port(addr).unwrap_or_else(|e| {
  1267. eprintln!("failed to parse entrypoint address: {e}");
  1268. exit(1)
  1269. });
  1270. let shred_version: Option<u16> = if !skip_gossip {
  1271. if let Ok(version) = value_t!(matches, "shred_version", u16) {
  1272. Some(version)
  1273. } else {
  1274. Some(
  1275. solana_net_utils::get_cluster_shred_version(&entrypoint_addr).unwrap_or_else(
  1276. |err| {
  1277. eprintln!("Failed to get shred version: {}", err);
  1278. exit(1);
  1279. },
  1280. ),
  1281. )
  1282. }
  1283. } else {
  1284. None
  1285. };
  1286. let rpc_addr = if !skip_gossip {
  1287. info!("Finding cluster entry: {:?}", entrypoint_addr);
  1288. let (gossip_nodes, _validators) = discover(
  1289. None, // keypair
  1290. Some(&entrypoint_addr),
  1291. None, // num_nodes
  1292. Duration::from_secs(60), // timeout
  1293. None, // find_nodes_by_pubkey
  1294. Some(&entrypoint_addr), // find_node_by_gossip_addr
  1295. None, // my_gossip_addr
  1296. shred_version.unwrap(), // my_shred_version
  1297. SocketAddrSpace::Unspecified,
  1298. )
  1299. .unwrap_or_else(|err| {
  1300. eprintln!("Failed to discover {entrypoint_addr} node: {err:?}");
  1301. exit(1);
  1302. });
  1303. info!("done found {} nodes", gossip_nodes.len());
  1304. gossip_nodes[0].rpc().unwrap()
  1305. } else {
  1306. info!("Using {:?} as the RPC address", entrypoint_addr);
  1307. entrypoint_addr
  1308. };
  1309. Arc::new(RpcClient::new_socket_with_commitment(
  1310. rpc_addr,
  1311. CommitmentConfig::confirmed(),
  1312. ))
  1313. } else {
  1314. let config = if let Some(config_file) = matches.value_of("config_file") {
  1315. solana_cli_config::Config::load(config_file).unwrap_or_default()
  1316. } else {
  1317. solana_cli_config::Config::default()
  1318. };
  1319. let (_, json_rpc_url) = ConfigInput::compute_json_rpc_url_setting(
  1320. matches.value_of("json_rpc_url").unwrap_or(""),
  1321. &config.json_rpc_url,
  1322. );
  1323. Arc::new(RpcClient::new_with_commitment(
  1324. json_rpc_url,
  1325. CommitmentConfig::confirmed(),
  1326. ))
  1327. };
  1328. run_accounts_bench(
  1329. client,
  1330. &payer_keypair_refs,
  1331. iterations,
  1332. space,
  1333. batch_size,
  1334. close_nth_batch,
  1335. lamports,
  1336. num_instructions,
  1337. max_accounts,
  1338. mint,
  1339. matches.is_present("reclaim_accounts"),
  1340. rpc_benches,
  1341. num_rpc_bench_threads,
  1342. );
  1343. }
  1344. #[cfg(test)]
  1345. pub mod test {
  1346. use {
  1347. super::*,
  1348. solana_accounts_db::{
  1349. accounts_db::ACCOUNTS_DB_CONFIG_FOR_BENCHMARKS,
  1350. accounts_index::{AccountIndex, AccountSecondaryIndexes},
  1351. },
  1352. solana_core::validator::ValidatorConfig,
  1353. solana_faucet::faucet::run_local_faucet,
  1354. solana_local_cluster::{
  1355. local_cluster::{ClusterConfig, LocalCluster},
  1356. validator_configs::make_identical_validator_configs,
  1357. },
  1358. solana_measure::measure::Measure,
  1359. solana_native_token::LAMPORTS_PER_SOL,
  1360. solana_poh_config::PohConfig,
  1361. solana_program_pack::Pack,
  1362. solana_test_validator::TestValidator,
  1363. spl_token_interface::state::{Account, Mint},
  1364. };
  1365. fn initialize_and_add_secondary_indexes(validator_config: &mut ValidatorConfig) {
  1366. if validator_config.accounts_db_config.is_none() {
  1367. validator_config.accounts_db_config = Some(ACCOUNTS_DB_CONFIG_FOR_BENCHMARKS);
  1368. }
  1369. let account_indexes = &mut validator_config
  1370. .accounts_db_config
  1371. .as_mut()
  1372. .unwrap()
  1373. .account_indexes;
  1374. if account_indexes.is_none() {
  1375. *account_indexes = Some(AccountSecondaryIndexes::default());
  1376. }
  1377. add_secondary_indexes(account_indexes.as_mut().unwrap());
  1378. add_secondary_indexes(&mut validator_config.rpc_config.account_indexes);
  1379. }
  1380. fn add_secondary_indexes(indexes: &mut AccountSecondaryIndexes) {
  1381. indexes.indexes.insert(AccountIndex::SplTokenOwner);
  1382. indexes.indexes.insert(AccountIndex::SplTokenMint);
  1383. indexes.indexes.insert(AccountIndex::ProgramId);
  1384. }
  1385. #[test]
  1386. fn test_accounts_cluster_bench() {
  1387. solana_logger::setup();
  1388. let mut validator_config = ValidatorConfig::default_for_test();
  1389. initialize_and_add_secondary_indexes(&mut validator_config);
  1390. let num_nodes = 1;
  1391. let mut config = ClusterConfig {
  1392. mint_lamports: 10_000_000,
  1393. poh_config: PohConfig::new_sleep(Duration::from_millis(50)),
  1394. node_stakes: vec![100; num_nodes],
  1395. validator_configs: make_identical_validator_configs(&validator_config, num_nodes),
  1396. ..ClusterConfig::default()
  1397. };
  1398. let cluster = LocalCluster::new(&mut config, SocketAddrSpace::Unspecified);
  1399. let iterations = 10;
  1400. let maybe_space = None;
  1401. let batch_size = 100;
  1402. let close_nth_batch = 100;
  1403. let maybe_lamports = None;
  1404. let num_instructions = 2;
  1405. let mut start = Measure::start("total accounts run");
  1406. let rpc_addr = cluster.entry_point_info.rpc().unwrap();
  1407. let client = Arc::new(RpcClient::new_socket_with_commitment(
  1408. rpc_addr,
  1409. CommitmentConfig::confirmed(),
  1410. ));
  1411. let mint = None;
  1412. let reclaim_accounts = false;
  1413. let pre_txs = client.get_transaction_count().unwrap();
  1414. run_accounts_bench(
  1415. client.clone(),
  1416. &[&cluster.funding_keypair],
  1417. iterations,
  1418. maybe_space,
  1419. batch_size,
  1420. close_nth_batch,
  1421. maybe_lamports,
  1422. num_instructions,
  1423. None,
  1424. mint,
  1425. reclaim_accounts,
  1426. Some(vec![RpcBench::ProgramAccounts]),
  1427. 1,
  1428. );
  1429. let post_txs = client.get_transaction_count().unwrap();
  1430. start.stop();
  1431. info!("{} pre {} post {}", start, pre_txs, post_txs);
  1432. }
  1433. #[test]
  1434. fn test_halt_accounts_creation_at_max() {
  1435. solana_logger::setup();
  1436. let mut validator_config = ValidatorConfig::default_for_test();
  1437. initialize_and_add_secondary_indexes(&mut validator_config);
  1438. let num_nodes = 1;
  1439. let mut config = ClusterConfig {
  1440. mint_lamports: 10_000_000,
  1441. poh_config: PohConfig::new_sleep(Duration::from_millis(50)),
  1442. node_stakes: vec![100; num_nodes],
  1443. validator_configs: make_identical_validator_configs(&validator_config, num_nodes),
  1444. ..ClusterConfig::default()
  1445. };
  1446. let cluster = LocalCluster::new(&mut config, SocketAddrSpace::Unspecified);
  1447. let iterations = 100;
  1448. let maybe_space = None;
  1449. let batch_size = 20;
  1450. let close_nth_batch = 0;
  1451. let maybe_lamports = None;
  1452. let num_instructions = 2;
  1453. let mut start = Measure::start("total accounts run");
  1454. let rpc_addr = cluster.entry_point_info.rpc().unwrap();
  1455. let client = Arc::new(RpcClient::new_socket_with_commitment(
  1456. rpc_addr,
  1457. CommitmentConfig::confirmed(),
  1458. ));
  1459. let mint = None;
  1460. let reclaim_accounts = false;
  1461. let pre_txs = client.get_transaction_count().unwrap();
  1462. run_accounts_bench(
  1463. client.clone(),
  1464. &[&cluster.funding_keypair],
  1465. iterations,
  1466. maybe_space,
  1467. batch_size,
  1468. close_nth_batch,
  1469. maybe_lamports,
  1470. num_instructions,
  1471. Some(90),
  1472. mint,
  1473. reclaim_accounts,
  1474. Some(vec![RpcBench::ProgramAccounts]),
  1475. 1,
  1476. );
  1477. let post_txs = client.get_transaction_count().unwrap();
  1478. start.stop();
  1479. info!("{} pre {} post {}", start, pre_txs, post_txs);
  1480. }
  1481. #[test]
  1482. fn test_create_then_reclaim_spl_token_accounts() {
  1483. solana_logger::setup();
  1484. let mint_keypair = Keypair::new();
  1485. let mint_pubkey = mint_keypair.pubkey();
  1486. let faucet_addr = run_local_faucet(mint_keypair, None);
  1487. let test_validator = TestValidator::with_custom_fees(
  1488. mint_pubkey,
  1489. 1,
  1490. Some(faucet_addr),
  1491. SocketAddrSpace::Unspecified,
  1492. );
  1493. let rpc_client = Arc::new(RpcClient::new_with_commitment(
  1494. test_validator.rpc_url(),
  1495. CommitmentConfig::processed(),
  1496. ));
  1497. // Created funder
  1498. let funder = Keypair::new();
  1499. let latest_blockhash = rpc_client.get_latest_blockhash().unwrap();
  1500. let signature = rpc_client
  1501. .request_airdrop_with_blockhash(&funder.pubkey(), LAMPORTS_PER_SOL, &latest_blockhash)
  1502. .unwrap();
  1503. rpc_client
  1504. .confirm_transaction_with_spinner(
  1505. &signature,
  1506. &latest_blockhash,
  1507. CommitmentConfig::confirmed(),
  1508. )
  1509. .unwrap();
  1510. // Create Mint
  1511. let spl_mint_keypair = Keypair::new();
  1512. let spl_mint_len = Mint::get_packed_len();
  1513. let spl_mint_rent = rpc_client
  1514. .get_minimum_balance_for_rent_exemption(spl_mint_len)
  1515. .unwrap();
  1516. let transaction = Transaction::new_signed_with_payer(
  1517. &[
  1518. system_instruction::create_account(
  1519. &funder.pubkey(),
  1520. &spl_mint_keypair.pubkey(),
  1521. spl_mint_rent,
  1522. spl_mint_len as u64,
  1523. &token::id(),
  1524. ),
  1525. spl_token_interface::instruction::initialize_mint(
  1526. &spl_token_interface::id(),
  1527. &spl_mint_keypair.pubkey(),
  1528. &spl_mint_keypair.pubkey(),
  1529. None,
  1530. 2,
  1531. )
  1532. .unwrap(),
  1533. ],
  1534. Some(&funder.pubkey()),
  1535. &[&funder, &spl_mint_keypair],
  1536. latest_blockhash,
  1537. );
  1538. let _sig = rpc_client
  1539. .send_and_confirm_transaction(&transaction)
  1540. .unwrap();
  1541. let account_len = Account::get_packed_len();
  1542. let minimum_balance = rpc_client
  1543. .get_minimum_balance_for_rent_exemption(account_len)
  1544. .unwrap();
  1545. let iterations = 5;
  1546. let batch_size = 100;
  1547. let close_nth_batch = 0;
  1548. let num_instructions = 4;
  1549. let mut start = Measure::start("total accounts run");
  1550. let keypair0 = Keypair::new();
  1551. let keypair1 = Keypair::new();
  1552. let keypair2 = Keypair::new();
  1553. run_accounts_bench(
  1554. rpc_client,
  1555. &[&keypair0, &keypair1, &keypair2],
  1556. iterations,
  1557. Some(account_len as u64),
  1558. batch_size,
  1559. close_nth_batch,
  1560. Some(minimum_balance),
  1561. num_instructions,
  1562. None,
  1563. Some(spl_mint_keypair.pubkey()),
  1564. true,
  1565. None,
  1566. 0,
  1567. );
  1568. start.stop();
  1569. info!("{}", start);
  1570. }
  1571. }