local_cluster.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. use crate::blocktree::create_new_tmp_ledger;
  2. use crate::cluster::Cluster;
  3. use crate::cluster_info::{Node, FULLNODE_PORT_RANGE};
  4. use crate::contact_info::ContactInfo;
  5. use crate::genesis_utils::{create_genesis_block_with_leader, GenesisBlockInfo};
  6. use crate::gossip_service::discover_cluster;
  7. use crate::replicator::Replicator;
  8. use crate::service::Service;
  9. use crate::validator::{Validator, ValidatorConfig};
  10. use solana_client::thin_client::create_client;
  11. use solana_client::thin_client::ThinClient;
  12. use solana_sdk::client::SyncClient;
  13. use solana_sdk::genesis_block::GenesisBlock;
  14. use solana_sdk::message::Message;
  15. use solana_sdk::poh_config::PohConfig;
  16. use solana_sdk::pubkey::Pubkey;
  17. use solana_sdk::signature::{Keypair, KeypairUtil};
  18. use solana_sdk::system_transaction;
  19. use solana_sdk::timing::DEFAULT_TICKS_PER_SLOT;
  20. use solana_sdk::timing::{DEFAULT_SLOTS_PER_EPOCH, DEFAULT_SLOTS_PER_SEGMENT};
  21. use solana_sdk::transaction::Transaction;
  22. use solana_stake_api::stake_instruction;
  23. use solana_storage_api::storage_contract;
  24. use solana_storage_api::storage_instruction;
  25. use solana_vote_api::vote_instruction;
  26. use solana_vote_api::vote_state::VoteState;
  27. use std::collections::HashMap;
  28. use std::fs::remove_dir_all;
  29. use std::io::{Error, ErrorKind, Result};
  30. use std::sync::Arc;
  31. pub struct ValidatorInfo {
  32. pub keypair: Arc<Keypair>,
  33. pub voting_keypair: Arc<Keypair>,
  34. pub storage_keypair: Arc<Keypair>,
  35. pub ledger_path: String,
  36. pub contact_info: ContactInfo,
  37. }
  38. pub struct ReplicatorInfo {
  39. pub replicator_storage_pubkey: Pubkey,
  40. pub ledger_path: String,
  41. }
  42. impl ReplicatorInfo {
  43. fn new(storage_pubkey: Pubkey, ledger_path: String) -> Self {
  44. Self {
  45. replicator_storage_pubkey: storage_pubkey,
  46. ledger_path,
  47. }
  48. }
  49. }
  50. pub struct ClusterValidatorInfo {
  51. pub info: ValidatorInfo,
  52. pub config: ValidatorConfig,
  53. }
  54. impl ClusterValidatorInfo {
  55. pub fn new(validator_info: ValidatorInfo, config: ValidatorConfig) -> Self {
  56. Self {
  57. info: validator_info,
  58. config,
  59. }
  60. }
  61. }
  62. #[derive(Clone, Debug)]
  63. pub struct ClusterConfig {
  64. /// The fullnode config that should be applied to every node in the cluster
  65. pub validator_configs: Vec<ValidatorConfig>,
  66. /// Number of replicators in the cluster
  67. /// Note- replicators will timeout if ticks_per_slot is much larger than the default 8
  68. pub num_replicators: usize,
  69. /// Number of nodes that are unstaked and not voting (a.k.a listening)
  70. pub num_listeners: u64,
  71. /// The stakes of each node
  72. pub node_stakes: Vec<u64>,
  73. /// The total lamports available to the cluster
  74. pub cluster_lamports: u64,
  75. pub ticks_per_slot: u64,
  76. pub slots_per_epoch: u64,
  77. pub slots_per_segment: u64,
  78. pub stakers_slot_offset: u64,
  79. pub native_instruction_processors: Vec<(String, Pubkey)>,
  80. pub poh_config: PohConfig,
  81. }
  82. impl Default for ClusterConfig {
  83. fn default() -> Self {
  84. ClusterConfig {
  85. validator_configs: vec![],
  86. num_replicators: 0,
  87. num_listeners: 0,
  88. node_stakes: vec![],
  89. cluster_lamports: 0,
  90. ticks_per_slot: DEFAULT_TICKS_PER_SLOT,
  91. slots_per_epoch: DEFAULT_SLOTS_PER_EPOCH,
  92. slots_per_segment: DEFAULT_SLOTS_PER_SEGMENT,
  93. stakers_slot_offset: DEFAULT_SLOTS_PER_EPOCH,
  94. native_instruction_processors: vec![],
  95. poh_config: PohConfig::default(),
  96. }
  97. }
  98. }
  99. pub struct LocalCluster {
  100. /// Keypair with funding to participate in the network
  101. pub funding_keypair: Keypair,
  102. /// Entry point from which the rest of the network can be discovered
  103. pub entry_point_info: ContactInfo,
  104. pub fullnode_infos: HashMap<Pubkey, ClusterValidatorInfo>,
  105. pub listener_infos: HashMap<Pubkey, ClusterValidatorInfo>,
  106. fullnodes: HashMap<Pubkey, Validator>,
  107. pub genesis_block: GenesisBlock,
  108. replicators: Vec<Replicator>,
  109. pub replicator_infos: HashMap<Pubkey, ReplicatorInfo>,
  110. }
  111. impl LocalCluster {
  112. pub fn new_with_equal_stakes(
  113. num_nodes: usize,
  114. cluster_lamports: u64,
  115. lamports_per_node: u64,
  116. ) -> Self {
  117. let stakes: Vec<_> = (0..num_nodes).map(|_| lamports_per_node).collect();
  118. let config = ClusterConfig {
  119. node_stakes: stakes,
  120. cluster_lamports,
  121. validator_configs: vec![ValidatorConfig::default(); num_nodes],
  122. ..ClusterConfig::default()
  123. };
  124. Self::new(&config)
  125. }
  126. pub fn new(config: &ClusterConfig) -> Self {
  127. assert_eq!(config.validator_configs.len(), config.node_stakes.len());
  128. let leader_keypair = Arc::new(Keypair::new());
  129. let leader_pubkey = leader_keypair.pubkey();
  130. let leader_node = Node::new_localhost_with_pubkey(&leader_keypair.pubkey());
  131. let GenesisBlockInfo {
  132. mut genesis_block,
  133. mint_keypair,
  134. voting_keypair,
  135. } = create_genesis_block_with_leader(
  136. config.cluster_lamports,
  137. &leader_pubkey,
  138. config.node_stakes[0],
  139. );
  140. genesis_block.ticks_per_slot = config.ticks_per_slot;
  141. genesis_block.slots_per_epoch = config.slots_per_epoch;
  142. genesis_block.slots_per_segment = config.slots_per_segment;
  143. genesis_block.stakers_slot_offset = config.stakers_slot_offset;
  144. genesis_block.poh_config = config.poh_config.clone();
  145. genesis_block
  146. .native_instruction_processors
  147. .extend_from_slice(&config.native_instruction_processors);
  148. let storage_keypair = Keypair::new();
  149. genesis_block.accounts.push((
  150. storage_keypair.pubkey(),
  151. storage_contract::create_validator_storage_account(leader_pubkey, 1),
  152. ));
  153. genesis_block
  154. .native_instruction_processors
  155. .push(solana_storage_program!());
  156. let (leader_ledger_path, _blockhash) = create_new_tmp_ledger!(&genesis_block);
  157. let leader_contact_info = leader_node.info.clone();
  158. let leader_storage_keypair = Arc::new(storage_keypair);
  159. let leader_voting_keypair = Arc::new(voting_keypair);
  160. let leader_server = Validator::new(
  161. leader_node,
  162. &leader_keypair,
  163. &leader_ledger_path,
  164. &leader_voting_keypair.pubkey(),
  165. &leader_voting_keypair,
  166. &leader_storage_keypair,
  167. None,
  168. true,
  169. &config.validator_configs[0],
  170. );
  171. let mut fullnodes = HashMap::new();
  172. let mut fullnode_infos = HashMap::new();
  173. fullnodes.insert(leader_pubkey, leader_server);
  174. let leader_info = ValidatorInfo {
  175. keypair: leader_keypair,
  176. voting_keypair: leader_voting_keypair,
  177. storage_keypair: leader_storage_keypair,
  178. ledger_path: leader_ledger_path,
  179. contact_info: leader_contact_info.clone(),
  180. };
  181. let cluster_leader =
  182. ClusterValidatorInfo::new(leader_info, config.validator_configs[0].clone());
  183. fullnode_infos.insert(leader_pubkey, cluster_leader);
  184. let mut cluster = Self {
  185. funding_keypair: mint_keypair,
  186. entry_point_info: leader_contact_info,
  187. fullnodes,
  188. replicators: vec![],
  189. genesis_block,
  190. fullnode_infos,
  191. replicator_infos: HashMap::new(),
  192. listener_infos: HashMap::new(),
  193. };
  194. for (stake, validator_config) in (&config.node_stakes[1..])
  195. .iter()
  196. .zip((&config.validator_configs[1..]).iter())
  197. {
  198. cluster.add_validator(validator_config, *stake);
  199. }
  200. let listener_config = ValidatorConfig {
  201. voting_disabled: true,
  202. ..config.validator_configs[0].clone()
  203. };
  204. (0..config.num_listeners).for_each(|_| cluster.add_validator(&listener_config, 0));
  205. discover_cluster(
  206. &cluster.entry_point_info.gossip,
  207. config.node_stakes.len() + config.num_listeners as usize,
  208. )
  209. .unwrap();
  210. for _ in 0..config.num_replicators {
  211. cluster.add_replicator();
  212. }
  213. discover_cluster(
  214. &cluster.entry_point_info.gossip,
  215. config.node_stakes.len() + config.num_replicators as usize,
  216. )
  217. .unwrap();
  218. cluster
  219. }
  220. pub fn exit(&self) {
  221. for node in self.fullnodes.values() {
  222. node.exit();
  223. }
  224. }
  225. pub fn close_preserve_ledgers(&mut self) {
  226. self.exit();
  227. for (_, node) in self.fullnodes.drain() {
  228. node.join().unwrap();
  229. }
  230. while let Some(replicator) = self.replicators.pop() {
  231. replicator.close();
  232. }
  233. }
  234. pub fn add_validator(&mut self, validator_config: &ValidatorConfig, stake: u64) {
  235. let client = create_client(
  236. self.entry_point_info.client_facing_addr(),
  237. FULLNODE_PORT_RANGE,
  238. );
  239. // Must have enough tokens to fund vote account and set delegate
  240. let validator_keypair = Arc::new(Keypair::new());
  241. let voting_keypair = Keypair::new();
  242. let storage_keypair = Arc::new(Keypair::new());
  243. let validator_pubkey = validator_keypair.pubkey();
  244. let validator_node = Node::new_localhost_with_pubkey(&validator_keypair.pubkey());
  245. let contact_info = validator_node.info.clone();
  246. let (ledger_path, _blockhash) = create_new_tmp_ledger!(&self.genesis_block);
  247. if validator_config.voting_disabled {
  248. // setup as a listener
  249. info!("listener {} ", validator_pubkey,);
  250. } else {
  251. // Give the validator some lamports to setup vote and storage accounts
  252. let validator_balance = Self::transfer_with_client(
  253. &client,
  254. &self.funding_keypair,
  255. &validator_pubkey,
  256. stake * 2 + 2,
  257. );
  258. info!(
  259. "validator {} balance {}",
  260. validator_pubkey, validator_balance
  261. );
  262. Self::setup_vote_and_stake_accounts(
  263. &client,
  264. &voting_keypair,
  265. &validator_keypair,
  266. stake,
  267. )
  268. .unwrap();
  269. Self::setup_storage_account(&client, &storage_keypair, &validator_keypair, false)
  270. .unwrap();
  271. }
  272. let voting_keypair = Arc::new(voting_keypair);
  273. let validator_server = Validator::new(
  274. validator_node,
  275. &validator_keypair,
  276. &ledger_path,
  277. &voting_keypair.pubkey(),
  278. &voting_keypair,
  279. &storage_keypair,
  280. Some(&self.entry_point_info),
  281. true,
  282. &validator_config,
  283. );
  284. self.fullnodes
  285. .insert(validator_keypair.pubkey(), validator_server);
  286. let validator_pubkey = validator_keypair.pubkey();
  287. let validator_info = ClusterValidatorInfo::new(
  288. ValidatorInfo {
  289. keypair: validator_keypair,
  290. voting_keypair,
  291. storage_keypair,
  292. ledger_path,
  293. contact_info,
  294. },
  295. validator_config.clone(),
  296. );
  297. if validator_config.voting_disabled {
  298. self.listener_infos.insert(validator_pubkey, validator_info);
  299. } else {
  300. self.fullnode_infos.insert(validator_pubkey, validator_info);
  301. }
  302. }
  303. fn add_replicator(&mut self) {
  304. let replicator_keypair = Arc::new(Keypair::new());
  305. let replicator_pubkey = replicator_keypair.pubkey();
  306. let storage_keypair = Arc::new(Keypair::new());
  307. let storage_pubkey = storage_keypair.pubkey();
  308. let client = create_client(
  309. self.entry_point_info.client_facing_addr(),
  310. FULLNODE_PORT_RANGE,
  311. );
  312. // Give the replicator some lamports to setup its storage accounts
  313. Self::transfer_with_client(
  314. &client,
  315. &self.funding_keypair,
  316. &replicator_keypair.pubkey(),
  317. 42,
  318. );
  319. let replicator_node = Node::new_localhost_replicator(&replicator_pubkey);
  320. Self::setup_storage_account(&client, &storage_keypair, &replicator_keypair, true).unwrap();
  321. let (replicator_ledger_path, _blockhash) = create_new_tmp_ledger!(&self.genesis_block);
  322. let replicator = Replicator::new(
  323. &replicator_ledger_path,
  324. replicator_node,
  325. self.entry_point_info.clone(),
  326. replicator_keypair,
  327. storage_keypair,
  328. )
  329. .unwrap_or_else(|err| panic!("Replicator::new() failed: {:?}", err));
  330. self.replicators.push(replicator);
  331. self.replicator_infos.insert(
  332. replicator_pubkey,
  333. ReplicatorInfo::new(storage_pubkey, replicator_ledger_path),
  334. );
  335. }
  336. fn close(&mut self) {
  337. self.close_preserve_ledgers();
  338. for ledger_path in self
  339. .fullnode_infos
  340. .values()
  341. .map(|f| &f.info.ledger_path)
  342. .chain(self.replicator_infos.values().map(|info| &info.ledger_path))
  343. {
  344. remove_dir_all(&ledger_path)
  345. .unwrap_or_else(|_| panic!("Unable to remove {}", ledger_path));
  346. }
  347. }
  348. pub fn transfer(&self, source_keypair: &Keypair, dest_pubkey: &Pubkey, lamports: u64) -> u64 {
  349. let client = create_client(
  350. self.entry_point_info.client_facing_addr(),
  351. FULLNODE_PORT_RANGE,
  352. );
  353. Self::transfer_with_client(&client, source_keypair, dest_pubkey, lamports)
  354. }
  355. fn transfer_with_client(
  356. client: &ThinClient,
  357. source_keypair: &Keypair,
  358. dest_pubkey: &Pubkey,
  359. lamports: u64,
  360. ) -> u64 {
  361. trace!("getting leader blockhash");
  362. let (blockhash, _fee_calculator) = client.get_recent_blockhash().unwrap();
  363. let mut tx = system_transaction::create_user_account(
  364. &source_keypair,
  365. dest_pubkey,
  366. lamports,
  367. blockhash,
  368. );
  369. info!(
  370. "executing transfer of {} from {} to {}",
  371. lamports,
  372. source_keypair.pubkey(),
  373. *dest_pubkey
  374. );
  375. client
  376. .retry_transfer(&source_keypair, &mut tx, 5)
  377. .expect("client transfer");
  378. client
  379. .wait_for_balance(dest_pubkey, Some(lamports))
  380. .expect("get balance")
  381. }
  382. fn setup_vote_and_stake_accounts(
  383. client: &ThinClient,
  384. vote_account: &Keypair,
  385. from_account: &Arc<Keypair>,
  386. amount: u64,
  387. ) -> Result<()> {
  388. let vote_account_pubkey = vote_account.pubkey();
  389. let node_pubkey = from_account.pubkey();
  390. // Create the vote account if necessary
  391. if client.poll_get_balance(&vote_account_pubkey).unwrap_or(0) == 0 {
  392. // 1) Create vote account
  393. let mut transaction = Transaction::new_signed_instructions(
  394. &[from_account.as_ref()],
  395. vote_instruction::create_account(
  396. &from_account.pubkey(),
  397. &vote_account_pubkey,
  398. &node_pubkey,
  399. 0,
  400. amount,
  401. ),
  402. client.get_recent_blockhash().unwrap().0,
  403. );
  404. client
  405. .retry_transfer(&from_account, &mut transaction, 5)
  406. .expect("fund vote");
  407. client
  408. .wait_for_balance(&vote_account_pubkey, Some(amount))
  409. .expect("get balance");
  410. let stake_account_keypair = Keypair::new();
  411. let stake_account_pubkey = stake_account_keypair.pubkey();
  412. let mut transaction = Transaction::new_signed_instructions(
  413. &[from_account.as_ref(), &stake_account_keypair],
  414. stake_instruction::create_stake_account_and_delegate_stake(
  415. &from_account.pubkey(),
  416. &stake_account_pubkey,
  417. &vote_account_pubkey,
  418. amount,
  419. ),
  420. client.get_recent_blockhash().unwrap().0,
  421. );
  422. client
  423. .send_and_confirm_transaction(
  424. &[from_account.as_ref(), &stake_account_keypair],
  425. &mut transaction,
  426. 5,
  427. 0,
  428. )
  429. .expect("delegate stake");
  430. client
  431. .wait_for_balance(&stake_account_pubkey, Some(amount))
  432. .expect("get balance");
  433. }
  434. info!("Checking for vote account registration");
  435. let vote_account_user_data = client.get_account_data(&vote_account_pubkey);
  436. if let Ok(Some(vote_account_user_data)) = vote_account_user_data {
  437. if let Ok(vote_state) = VoteState::deserialize(&vote_account_user_data) {
  438. if vote_state.node_pubkey == node_pubkey {
  439. info!("vote account registered");
  440. return Ok(());
  441. }
  442. }
  443. }
  444. Err(Error::new(
  445. ErrorKind::Other,
  446. "expected successful vote account registration",
  447. ))
  448. }
  449. /// Sets up the storage account for validators/replicators and assumes the funder is the owner
  450. fn setup_storage_account(
  451. client: &ThinClient,
  452. storage_keypair: &Keypair,
  453. from_keypair: &Arc<Keypair>,
  454. replicator: bool,
  455. ) -> Result<()> {
  456. let message = Message::new_with_payer(
  457. if replicator {
  458. storage_instruction::create_replicator_storage_account(
  459. &from_keypair.pubkey(),
  460. &from_keypair.pubkey(),
  461. &storage_keypair.pubkey(),
  462. 1,
  463. )
  464. } else {
  465. storage_instruction::create_validator_storage_account(
  466. &from_keypair.pubkey(),
  467. &from_keypair.pubkey(),
  468. &storage_keypair.pubkey(),
  469. 1,
  470. )
  471. },
  472. Some(&from_keypair.pubkey()),
  473. );
  474. let signer_keys = vec![from_keypair.as_ref()];
  475. let blockhash = client.get_recent_blockhash().unwrap().0;
  476. let mut transaction = Transaction::new(&signer_keys, message, blockhash);
  477. client
  478. .retry_transfer(&from_keypair, &mut transaction, 5)
  479. .map(|_signature| ())
  480. }
  481. }
  482. impl Cluster for LocalCluster {
  483. fn get_node_pubkeys(&self) -> Vec<Pubkey> {
  484. self.fullnodes.keys().cloned().collect()
  485. }
  486. fn get_validator_client(&self, pubkey: &Pubkey) -> Option<ThinClient> {
  487. self.fullnode_infos.get(pubkey).map(|f| {
  488. create_client(
  489. f.info.contact_info.client_facing_addr(),
  490. FULLNODE_PORT_RANGE,
  491. )
  492. })
  493. }
  494. fn restart_node(&mut self, pubkey: Pubkey) {
  495. // Shut down the fullnode
  496. let node = self.fullnodes.remove(&pubkey).unwrap();
  497. node.exit();
  498. node.join().unwrap();
  499. // Restart the node
  500. let fullnode_info = &self.fullnode_infos[&pubkey].info;
  501. let config = &self.fullnode_infos[&pubkey].config;
  502. let node = Node::new_localhost_with_pubkey(&fullnode_info.keypair.pubkey());
  503. if pubkey == self.entry_point_info.id {
  504. self.entry_point_info = node.info.clone();
  505. }
  506. let restarted_node = Validator::new(
  507. node,
  508. &fullnode_info.keypair,
  509. &fullnode_info.ledger_path,
  510. &fullnode_info.voting_keypair.pubkey(),
  511. &fullnode_info.voting_keypair,
  512. &fullnode_info.storage_keypair,
  513. None,
  514. true,
  515. config,
  516. );
  517. self.fullnodes.insert(pubkey, restarted_node);
  518. }
  519. }
  520. impl Drop for LocalCluster {
  521. fn drop(&mut self) {
  522. self.close();
  523. }
  524. }
  525. #[cfg(test)]
  526. mod test {
  527. use super::*;
  528. use crate::storage_stage::SLOTS_PER_TURN_TEST;
  529. use solana_runtime::epoch_schedule::MINIMUM_SLOTS_PER_EPOCH;
  530. #[test]
  531. fn test_local_cluster_start_and_exit() {
  532. solana_logger::setup();
  533. let num_nodes = 1;
  534. let cluster = LocalCluster::new_with_equal_stakes(num_nodes, 100, 3);
  535. assert_eq!(cluster.fullnodes.len(), num_nodes);
  536. assert_eq!(cluster.replicators.len(), 0);
  537. }
  538. #[test]
  539. fn test_local_cluster_start_and_exit_with_config() {
  540. solana_logger::setup();
  541. let mut validator_config = ValidatorConfig::default();
  542. validator_config.rpc_config.enable_fullnode_exit = true;
  543. validator_config.storage_slots_per_turn = SLOTS_PER_TURN_TEST;
  544. const NUM_NODES: usize = 1;
  545. let num_replicators = 1;
  546. let config = ClusterConfig {
  547. validator_configs: vec![ValidatorConfig::default(); NUM_NODES],
  548. num_replicators,
  549. node_stakes: vec![3; NUM_NODES],
  550. cluster_lamports: 100,
  551. ticks_per_slot: 8,
  552. slots_per_epoch: MINIMUM_SLOTS_PER_EPOCH as u64,
  553. ..ClusterConfig::default()
  554. };
  555. let cluster = LocalCluster::new(&config);
  556. assert_eq!(cluster.fullnodes.len(), NUM_NODES);
  557. assert_eq!(cluster.replicators.len(), num_replicators);
  558. }
  559. }