1use {
2 crate::{
3 cli::{CliCommand, CliCommandInfo, CliConfig, CliError, ProcessResult},
4 compute_budget::{ComputeUnitConfig, WithComputeUnitConfig},
5 spend_utils::{SpendAmount, resolve_spend_tx_and_check_account_balance},
6 },
7 bincode::{deserialize, serialized_size},
8 clap::{App, AppSettings, Arg, ArgMatches, SubCommand},
9 reqwest::blocking::Client,
10 serde_json::{Map, Value},
11 solana_account::Account,
12 solana_account_decoder::validator_info::{
13 self, MAX_LONG_FIELD_LENGTH, MAX_SHORT_FIELD_LENGTH, MAX_VALIDATOR_INFO, ValidatorInfo,
14 },
15 solana_clap_utils::{
16 compute_budget::{COMPUTE_UNIT_PRICE_ARG, ComputeUnitLimit, compute_unit_price_arg},
17 hidden_unless_forced,
18 input_parsers::{pubkey_of, value_of},
19 input_validators::{is_pubkey, is_url},
20 keypair::DefaultSigner,
21 },
22 solana_cli_output::{CliValidatorInfo, CliValidatorInfoVec},
23 solana_config_interface::{
24 instruction::{self as config_instruction},
25 state::{ConfigKeys, get_config_data},
26 },
27 solana_keypair::Keypair,
28 solana_message::Message,
29 solana_pubkey::Pubkey,
30 solana_remote_wallet::remote_wallet::RemoteWalletManager,
31 solana_rpc_client::nonblocking::rpc_client::RpcClient,
32 solana_signer::Signer,
33 solana_transaction::Transaction,
34 std::{error, rc::Rc},
35};
36
37pub fn check_details_length(string: String) -> Result<(), String> {
39 if string.len() > MAX_LONG_FIELD_LENGTH {
40 Err(format!(
41 "validator details longer than {MAX_LONG_FIELD_LENGTH:?}-byte limit"
42 ))
43 } else {
44 Ok(())
45 }
46}
47
48pub fn check_total_length(info: &ValidatorInfo) -> Result<(), String> {
49 let size = serialized_size(&info).unwrap();
50 let limit = MAX_VALIDATOR_INFO;
51
52 if size > limit {
53 Err(format!(
54 "Total size {size:?} exceeds limit of {limit:?} bytes"
55 ))
56 } else {
57 Ok(())
58 }
59}
60
61pub fn check_url(string: String) -> Result<(), String> {
63 is_url(string.clone())?;
64 if string.len() > MAX_SHORT_FIELD_LENGTH {
65 Err(format!(
66 "url longer than {MAX_SHORT_FIELD_LENGTH:?}-byte limit"
67 ))
68 } else {
69 Ok(())
70 }
71}
72
73pub fn is_short_field(string: String) -> Result<(), String> {
75 if string.len() > MAX_SHORT_FIELD_LENGTH {
76 Err(format!(
77 "validator field longer than {MAX_SHORT_FIELD_LENGTH:?}-byte limit"
78 ))
79 } else {
80 Ok(())
81 }
82}
83
84fn verify_keybase(
85 validator_pubkey: &Pubkey,
86 keybase_username: &Value,
87) -> Result<(), Box<dyn error::Error>> {
88 if let Some(keybase_username) = keybase_username.as_str() {
89 let url =
90 format!("https://keybase.pub/{keybase_username}/solana/validator-{validator_pubkey:?}");
91 let client = Client::new();
92 if client.head(&url).send()?.status().is_success() {
93 Ok(())
94 } else {
95 Err(format!(
96 "keybase_username could not be confirmed at: {url}. Please add this pubkey file \
97 to your keybase profile to connect"
98 )
99 .into())
100 }
101 } else {
102 Err(format!("keybase_username could not be parsed as String: {keybase_username}").into())
103 }
104}
105
106fn parse_args(matches: &ArgMatches<'_>) -> Value {
107 let mut map = Map::new();
108 map.insert(
109 "name".to_string(),
110 Value::String(matches.value_of("name").unwrap().to_string()),
111 );
112 if let Some(url) = matches.value_of("website") {
113 map.insert("website".to_string(), Value::String(url.to_string()));
114 }
115
116 if let Some(icon_url) = matches.value_of("icon_url") {
117 map.insert("iconUrl".to_string(), Value::String(icon_url.to_string()));
118 }
119 if let Some(details) = matches.value_of("details") {
120 map.insert("details".to_string(), Value::String(details.to_string()));
121 }
122 if let Some(keybase_username) = matches.value_of("keybase_username") {
123 map.insert(
124 "keybaseUsername".to_string(),
125 Value::String(keybase_username.to_string()),
126 );
127 }
128 Value::Object(map)
129}
130
131fn parse_validator_info(
132 account: &Account,
133) -> Option<(Pubkey, bool, Map<String, serde_json::value::Value>)> {
134 if account.owner != solana_config_interface::id() {
135 return None;
136 }
137 let key_list: ConfigKeys = deserialize(&account.data).ok()?;
138 if key_list.keys.len() > 1 {
139 let (validator_pubkey, is_signed) = key_list.keys[1];
140 let validator_info_string: String =
141 get_config_data(&account.data).and_then(deserialize).ok()?;
142 let validator_info: Map<_, _> = serde_json::from_str(&validator_info_string).ok()?;
143 Some((validator_pubkey, is_signed, validator_info))
144 } else {
145 None
146 }
147}
148
149pub trait ValidatorInfoSubCommands {
150 fn validator_info_subcommands(self) -> Self;
151}
152
153impl ValidatorInfoSubCommands for App<'_, '_> {
154 fn validator_info_subcommands(self) -> Self {
155 self.subcommand(
156 SubCommand::with_name("validator-info")
157 .about("Publish/get Validator info on Solana")
158 .setting(AppSettings::SubcommandRequiredElseHelp)
159 .subcommand(
160 SubCommand::with_name("publish")
161 .about("Publish Validator info on Solana")
162 .arg(
163 Arg::with_name("info_pubkey")
164 .short("p")
165 .long("info-pubkey")
166 .value_name("PUBKEY")
167 .takes_value(true)
168 .validator(is_pubkey)
169 .help("The pubkey of the Validator info account to update"),
170 )
171 .arg(
172 Arg::with_name("name")
173 .index(1)
174 .value_name("NAME")
175 .takes_value(true)
176 .required(true)
177 .validator(is_short_field)
178 .help("Validator name"),
179 )
180 .arg(
181 Arg::with_name("website")
182 .short("w")
183 .long("website")
184 .value_name("URL")
185 .takes_value(true)
186 .validator(check_url)
187 .help("Validator website url"),
188 )
189 .arg(
190 Arg::with_name("icon_url")
191 .short("i")
192 .long("icon-url")
193 .value_name("URL")
194 .takes_value(true)
195 .validator(check_url)
196 .help("Validator icon URL"),
197 )
198 .arg(
199 Arg::with_name("keybase_username")
200 .short("n")
201 .long("keybase")
202 .value_name("USERNAME")
203 .takes_value(true)
204 .validator(is_short_field)
205 .hidden(hidden_unless_forced()) .help("Validator Keybase username"),
207 )
208 .arg(
209 Arg::with_name("details")
210 .short("d")
211 .long("details")
212 .value_name("DETAILS")
213 .takes_value(true)
214 .validator(check_details_length)
215 .help("Validator description"),
216 )
217 .arg(
218 Arg::with_name("force")
219 .long("force")
220 .takes_value(false)
221 .hidden(hidden_unless_forced()) .help("Override keybase username validity check"),
223 )
224 .arg(compute_unit_price_arg()),
225 )
226 .subcommand(
227 SubCommand::with_name("get")
228 .about("Get and parse Solana Validator info")
229 .arg(
230 Arg::with_name("info_pubkey")
231 .index(1)
232 .value_name("PUBKEY")
233 .takes_value(true)
234 .validator(is_pubkey)
235 .help(
236 "The pubkey of the Validator info account; without this \
237 argument, returns all Validator info accounts",
238 ),
239 ),
240 ),
241 )
242 }
243}
244
245pub fn parse_publish_validator_info_command(
246 matches: &ArgMatches<'_>,
247 default_signer: &DefaultSigner,
248 wallet_manager: &mut Option<Rc<RemoteWalletManager>>,
249) -> Result<CliCommandInfo, CliError> {
250 let info_pubkey = pubkey_of(matches, "info_pubkey");
251 let compute_unit_price = value_of(matches, COMPUTE_UNIT_PRICE_ARG.name);
252 let validator_info = parse_args(matches);
254 Ok(CliCommandInfo {
255 command: CliCommand::PublishValidatorInfo {
256 validator_info,
257 force_keybase: matches.is_present("force"),
258 info_pubkey,
259 compute_unit_price,
260 },
261 signers: vec![default_signer.signer_from_path(matches, wallet_manager)?],
262 })
263}
264
265pub fn parse_get_validator_info_command(
266 matches: &ArgMatches<'_>,
267) -> Result<CliCommandInfo, CliError> {
268 let info_pubkey = pubkey_of(matches, "info_pubkey");
269 Ok(CliCommandInfo::without_signers(
270 CliCommand::GetValidatorInfo(info_pubkey),
271 ))
272}
273
274pub async fn process_publish_validator_info(
275 rpc_client: &RpcClient,
276 config: &CliConfig<'_>,
277 validator_info: &Value,
278 force_keybase: bool,
279 info_pubkey: Option<Pubkey>,
280 compute_unit_price: Option<u64>,
281) -> ProcessResult {
282 if let Some(string) = validator_info.get("keybaseUsername") {
284 if force_keybase {
285 println!("--force supplied, skipping Keybase verification");
286 } else {
287 let result = verify_keybase(&config.signers[0].pubkey(), string);
288 if result.is_err() {
289 result.map_err(|err| {
290 CliError::BadParameter(format!("Invalid validator keybase username: {err}"))
291 })?;
292 }
293 }
294 }
295 let validator_string = serde_json::to_string(&validator_info).unwrap();
296 let validator_info = ValidatorInfo {
297 info: validator_string,
298 };
299
300 let result = check_total_length(&validator_info);
301 if result.is_err() {
302 result.map_err(|err| {
303 CliError::BadParameter(format!("Maximum size for validator info: {err}"))
304 })?;
305 }
306
307 let all_config = rpc_client
309 .get_program_accounts(&solana_config_interface::id())
310 .await?;
311 let existing_account = all_config
312 .iter()
313 .filter(
314 |(_, account)| match deserialize::<ConfigKeys>(&account.data) {
315 Ok(key_list) => key_list.keys.contains(&(validator_info::id(), false)),
316 Err(_) => false,
317 },
318 )
319 .find(|(_, account)| {
320 let Some((validator_pubkey, true, _)) = parse_validator_info(account) else {
321 return false;
322 };
323 validator_pubkey == config.signers[0].pubkey()
324 });
325
326 let info_keypair = Keypair::new();
328 let mut info_pubkey = if let Some(pubkey) = info_pubkey {
329 pubkey
330 } else if let Some(validator_info) = existing_account {
331 validator_info.0
332 } else {
333 info_keypair.pubkey()
334 };
335
336 let balance = rpc_client.get_balance(&info_pubkey).await.unwrap_or(0);
338
339 let keys = vec![
340 (validator_info::id(), false),
341 (config.signers[0].pubkey(), true),
342 ];
343 let data_len = MAX_VALIDATOR_INFO
344 .checked_add(serialized_size(&ConfigKeys { keys: keys.clone() }).unwrap())
345 .expect("ValidatorInfo and two keys fit into a u64");
346 let lamports = rpc_client
347 .get_minimum_balance_for_rent_exemption(data_len as usize)
348 .await?;
349
350 let signers = if balance == 0 {
351 if info_pubkey != info_keypair.pubkey() {
352 println!("Account {info_pubkey:?} does not exist. Generating new keypair...");
353 info_pubkey = info_keypair.pubkey();
354 }
355 vec![config.signers[0], &info_keypair]
356 } else {
357 vec![config.signers[0]]
358 };
359
360 let compute_unit_limit = ComputeUnitLimit::Simulated;
361 let build_message = |lamports| {
362 let keys = keys.clone();
363 if balance == 0 {
364 println!(
365 "Publishing info for Validator {:?}",
366 config.signers[0].pubkey()
367 );
368 let mut instructions =
369 config_instruction::create_account_with_max_config_space::<ValidatorInfo>(
370 &config.signers[0].pubkey(),
371 &info_pubkey,
372 lamports,
373 MAX_VALIDATOR_INFO,
374 keys.clone(),
375 )
376 .with_compute_unit_config(&ComputeUnitConfig {
377 compute_unit_price,
378 compute_unit_limit,
379 });
380 instructions.extend_from_slice(&[config_instruction::store(
381 &info_pubkey,
382 true,
383 keys,
384 &validator_info,
385 )]);
386 Message::new(&instructions, Some(&config.signers[0].pubkey()))
387 } else {
388 println!(
389 "Updating Validator {:?} info at: {:?}",
390 config.signers[0].pubkey(),
391 info_pubkey
392 );
393 let instructions = vec![config_instruction::store(
394 &info_pubkey,
395 false,
396 keys,
397 &validator_info,
398 )]
399 .with_compute_unit_config(&ComputeUnitConfig {
400 compute_unit_price,
401 compute_unit_limit,
402 });
403 Message::new(&instructions, Some(&config.signers[0].pubkey()))
404 }
405 };
406
407 let latest_blockhash = rpc_client.get_latest_blockhash().await?;
409 let (message, _) = resolve_spend_tx_and_check_account_balance(
410 rpc_client,
411 false,
412 SpendAmount::Some(lamports),
413 &latest_blockhash,
414 &config.signers[0].pubkey(),
415 compute_unit_limit,
416 build_message,
417 config.commitment,
418 )
419 .await?;
420 let mut tx = Transaction::new_unsigned(message);
421 tx.try_sign(&signers, latest_blockhash)?;
422 let signature_str = rpc_client
423 .send_and_confirm_transaction_with_spinner_and_config(
424 &tx,
425 config.commitment,
426 config.send_transaction_config,
427 )
428 .await?;
429
430 println!("Success! Validator info published at: {info_pubkey:?}");
431 println!("{signature_str}");
432 Ok("".to_string())
433}
434
435pub async fn process_get_validator_info(
436 rpc_client: &RpcClient,
437 config: &CliConfig<'_>,
438 pubkey: Option<Pubkey>,
439) -> ProcessResult {
440 let validator_info: Vec<(Pubkey, Account)> = if let Some(validator_info_pubkey) = pubkey {
441 vec![(
442 validator_info_pubkey,
443 rpc_client.get_account(&validator_info_pubkey).await?,
444 )]
445 } else {
446 let all_config = rpc_client
447 .get_program_accounts(&solana_config_interface::id())
448 .await?;
449 all_config
450 .into_iter()
451 .filter(|(_, validator_info_account)| {
452 match deserialize::<ConfigKeys>(&validator_info_account.data) {
453 Ok(key_list) => key_list.keys.contains(&(validator_info::id(), false)),
454 Err(_) => false,
455 }
456 })
457 .collect()
458 };
459
460 let mut validator_info_list: Vec<CliValidatorInfo> = vec![];
461 for (validator_info_pubkey, validator_info_account) in validator_info.iter() {
462 let Some((validator_pubkey, is_signed, validator_info)) =
463 parse_validator_info(validator_info_account)
464 else {
465 continue;
466 };
467
468 if config.verbose || is_signed {
469 validator_info_list.push(CliValidatorInfo {
470 identity_pubkey: validator_pubkey.to_string(),
471 info_pubkey: validator_info_pubkey.to_string(),
472 is_signed,
473 info: validator_info,
474 });
475 }
476 }
477
478 Ok(config
479 .output_format
480 .formatted_string(&CliValidatorInfoVec::new(validator_info_list)))
481}
482
483#[cfg(test)]
484mod tests {
485 use {
486 super::*,
487 crate::clap_app::get_clap_app,
488 bincode::{serialize, serialized_size},
489 serde_json::json,
490 };
491
492 #[test]
493 fn test_check_details_length() {
494 let short_details = (0..MAX_LONG_FIELD_LENGTH).map(|_| "X").collect::<String>();
495 assert_eq!(check_details_length(short_details), Ok(()));
496
497 let long_details = (0..MAX_LONG_FIELD_LENGTH + 1)
498 .map(|_| "X")
499 .collect::<String>();
500 assert_eq!(
501 check_details_length(long_details),
502 Err(format!(
503 "validator details longer than {MAX_LONG_FIELD_LENGTH:?}-byte limit"
504 ))
505 );
506 }
507
508 #[test]
509 fn test_check_url() {
510 let url = "http://test.com";
511 assert_eq!(check_url(url.to_string()), Ok(()));
512 let long_url = "http://7cLvFwLCbyHuXQ1RGzhCMobAWYPMSZ3VbUml1CMobAWYPMSZ3VbUml1qWi1nkc3FD7zj9hzTZzMvYJ.com";
513 assert!(check_url(long_url.to_string()).is_err());
514 let non_url = "not parseable";
515 assert!(check_url(non_url.to_string()).is_err());
516 }
517
518 #[test]
519 fn test_is_short_field() {
520 let name = "Alice Validator";
521 assert_eq!(is_short_field(name.to_string()), Ok(()));
522 let long_name = "Alice 7cLvFwLCbyHuXQ1RGzhCMobAWYPMSZ3VbUml1qWi1nkc3FD7zj9hzTZzMvYJt6rY9j9hzTZzMvYJt6rY9";
523 assert!(is_short_field(long_name.to_string()).is_err());
524 }
525
526 #[test]
527 fn test_verify_keybase_username_not_string() {
528 let pubkey = solana_pubkey::new_rand();
529 let value = Value::Bool(true);
530
531 assert_eq!(
532 verify_keybase(&pubkey, &value).unwrap_err().to_string(),
533 "keybase_username could not be parsed as String: true".to_string()
534 )
535 }
536
537 #[test]
538 fn test_parse_args() {
539 let matches = get_clap_app("test", "desc", "version").get_matches_from(vec![
540 "test",
541 "validator-info",
542 "publish",
543 "Alice",
544 "-n",
545 "alice_keybase",
546 "-i",
547 "https://test.com/icon.png",
548 ]);
549 let subcommand_matches = matches.subcommand();
550 assert_eq!(subcommand_matches.0, "validator-info");
551 assert!(subcommand_matches.1.is_some());
552 let subcommand_matches = subcommand_matches.1.unwrap().subcommand();
553 assert_eq!(subcommand_matches.0, "publish");
554 assert!(subcommand_matches.1.is_some());
555 let matches = subcommand_matches.1.unwrap();
556 let expected = json!({
557 "name": "Alice",
558 "keybaseUsername": "alice_keybase",
559 "iconUrl": "https://test.com/icon.png",
560 });
561 assert_eq!(parse_args(matches), expected);
562 }
563
564 #[test]
565 fn test_validator_info_serde() {
566 let mut info = Map::new();
567 info.insert("name".to_string(), Value::String("Alice".to_string()));
568 let info_string = serde_json::to_string(&Value::Object(info)).unwrap();
569
570 let validator_info = ValidatorInfo {
571 info: info_string.clone(),
572 };
573
574 assert_eq!(serialized_size(&validator_info).unwrap(), 24);
575 assert_eq!(
576 serialize(&validator_info).unwrap(),
577 vec![
578 16, 0, 0, 0, 0, 0, 0, 0, 123, 34, 110, 97, 109, 101, 34, 58, 34, 65, 108, 105, 99,
579 101, 34, 125
580 ]
581 );
582
583 let deserialized: ValidatorInfo = deserialize(&[
584 16, 0, 0, 0, 0, 0, 0, 0, 123, 34, 110, 97, 109, 101, 34, 58, 34, 65, 108, 105, 99, 101,
585 34, 125,
586 ])
587 .unwrap();
588 assert_eq!(deserialized.info, info_string);
589 }
590
591 #[test]
592 fn test_parse_validator_info() {
593 let pubkey = solana_pubkey::new_rand();
594 let keys = vec![(validator_info::id(), false), (pubkey, true)];
595 let config = ConfigKeys { keys };
596
597 let mut info = Map::new();
598 info.insert("name".to_string(), Value::String("Alice".to_string()));
599 let info_string = serde_json::to_string(&Value::Object(info.clone())).unwrap();
600 let validator_info = ValidatorInfo { info: info_string };
601 let data = serialize(&(config, validator_info)).unwrap();
602
603 assert_eq!(
604 parse_validator_info(&Account {
605 owner: solana_config_interface::id(),
606 data,
607 ..Account::default()
608 })
609 .unwrap(),
610 (pubkey, true, info)
611 );
612 }
613
614 #[test]
615 fn test_parse_validator_info_not_validator_info_account() {
616 assert!(
617 parse_validator_info(&Account {
618 owner: solana_pubkey::new_rand(),
619 ..Account::default()
620 })
621 .is_none()
622 );
623 }
624
625 #[test]
626 fn test_parse_validator_info_empty_key_list() {
627 let config = ConfigKeys { keys: vec![] };
628 let validator_info = ValidatorInfo {
629 info: String::new(),
630 };
631 let data = serialize(&(config, validator_info)).unwrap();
632
633 assert!(
634 parse_validator_info(&Account {
635 owner: solana_config_interface::id(),
636 data,
637 ..Account::default()
638 },)
639 .is_none()
640 );
641 }
642
643 #[test]
644 fn test_validator_info_max_space() {
645 let max_short_string =
647 "Max Length String KWpP299aFCBWvWg1MHpSuaoTsud7cv8zMJsh99aAtP8X1s26yrR1".to_string();
648 let max_long_string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut libero \
650 quam, volutpat et aliquet eu, varius in mi. Aenean vestibulum ex \
651 in tristique faucibus. Maecenas in imperdiet turpis. Nullam \
652 feugiat aliquet erat. Morbi malesuada turpis sed dui pulvinar \
653 lobortis. Pellentesque a lectus eu leo nullam."
654 .to_string();
655 let mut info = Map::new();
656 info.insert("name".to_string(), Value::String(max_short_string.clone()));
657 info.insert(
658 "website".to_string(),
659 Value::String(max_short_string.clone()),
660 );
661 info.insert(
662 "keybaseUsername".to_string(),
663 Value::String(max_short_string),
664 );
665 info.insert("details".to_string(), Value::String(max_long_string));
666 let info_string = serde_json::to_string(&Value::Object(info)).unwrap();
667
668 let validator_info = ValidatorInfo { info: info_string };
669
670 assert_eq!(
671 serialized_size(&validator_info).unwrap(),
672 MAX_VALIDATOR_INFO
673 );
674 }
675}