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, stdout::writeln_stdout},
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 writeln_stdout(format_args!(
286 "--force supplied, skipping Keybase verification"
287 ))?;
288 } else {
289 let result = verify_keybase(&config.signers[0].pubkey(), string);
290 if result.is_err() {
291 result.map_err(|err| {
292 CliError::BadParameter(format!("Invalid validator keybase username: {err}"))
293 })?;
294 }
295 }
296 }
297 let validator_string = serde_json::to_string(&validator_info).unwrap();
298 let validator_info = ValidatorInfo {
299 info: validator_string,
300 };
301
302 let result = check_total_length(&validator_info);
303 if result.is_err() {
304 result.map_err(|err| {
305 CliError::BadParameter(format!("Maximum size for validator info: {err}"))
306 })?;
307 }
308
309 let all_config = rpc_client
311 .get_program_accounts(&solana_config_interface::id())
312 .await?;
313 let existing_account = all_config
314 .iter()
315 .filter(
316 |(_, account)| match deserialize::<ConfigKeys>(&account.data) {
317 Ok(key_list) => key_list.keys.contains(&(validator_info::id(), false)),
318 Err(_) => false,
319 },
320 )
321 .find(|(_, account)| {
322 let Some((validator_pubkey, true, _)) = parse_validator_info(account) else {
323 return false;
324 };
325 validator_pubkey == config.signers[0].pubkey()
326 });
327
328 let info_keypair = Keypair::new();
330 let mut info_pubkey = if let Some(pubkey) = info_pubkey {
331 pubkey
332 } else if let Some(validator_info) = existing_account {
333 validator_info.0
334 } else {
335 info_keypair.pubkey()
336 };
337
338 let balance = rpc_client.get_balance(&info_pubkey).await.unwrap_or(0);
340
341 let keys = vec![
342 (validator_info::id(), false),
343 (config.signers[0].pubkey(), true),
344 ];
345 let data_len = MAX_VALIDATOR_INFO
346 .checked_add(serialized_size(&ConfigKeys { keys: keys.clone() }).unwrap())
347 .expect("ValidatorInfo and two keys fit into a u64");
348 let lamports = rpc_client
349 .get_minimum_balance_for_rent_exemption(data_len as usize)
350 .await?;
351
352 let signers = if balance == 0 {
353 if info_pubkey != info_keypair.pubkey() {
354 writeln_stdout(format_args!(
355 "Account {info_pubkey:?} does not exist. Generating new keypair..."
356 ))?;
357 info_pubkey = info_keypair.pubkey();
358 }
359 vec![config.signers[0], &info_keypair]
360 } else {
361 vec![config.signers[0]]
362 };
363
364 let compute_unit_limit = ComputeUnitLimit::Simulated;
365 if balance == 0 {
366 writeln_stdout(format_args!(
367 "Publishing info for Validator {:?}",
368 config.signers[0].pubkey()
369 ))?;
370 } else {
371 writeln_stdout(format_args!(
372 "Updating Validator {:?} info at: {:?}",
373 config.signers[0].pubkey(),
374 info_pubkey
375 ))?;
376 }
377 let build_message = |lamports| {
378 let keys = keys.clone();
379 if balance == 0 {
380 let mut instructions =
381 config_instruction::create_account_with_max_config_space::<ValidatorInfo>(
382 &config.signers[0].pubkey(),
383 &info_pubkey,
384 lamports,
385 MAX_VALIDATOR_INFO,
386 keys.clone(),
387 )
388 .with_compute_unit_config(&ComputeUnitConfig {
389 compute_unit_price,
390 compute_unit_limit,
391 });
392 instructions.extend_from_slice(&[config_instruction::store(
393 &info_pubkey,
394 true,
395 keys,
396 &validator_info,
397 )]);
398 Message::new(&instructions, Some(&config.signers[0].pubkey()))
399 } else {
400 let instructions = vec![config_instruction::store(
401 &info_pubkey,
402 false,
403 keys,
404 &validator_info,
405 )]
406 .with_compute_unit_config(&ComputeUnitConfig {
407 compute_unit_price,
408 compute_unit_limit,
409 });
410 Message::new(&instructions, Some(&config.signers[0].pubkey()))
411 }
412 };
413
414 let latest_blockhash = rpc_client.get_latest_blockhash().await?;
416 let (message, _) = resolve_spend_tx_and_check_account_balance(
417 rpc_client,
418 false,
419 SpendAmount::Some(lamports),
420 &latest_blockhash,
421 &config.signers[0].pubkey(),
422 compute_unit_limit,
423 build_message,
424 config.commitment,
425 )
426 .await?;
427 let mut tx = Transaction::new_unsigned(message);
428 tx.try_sign(&signers, latest_blockhash)?;
429 let signature_str = rpc_client
430 .send_and_confirm_transaction_with_spinner_and_config(
431 &tx,
432 config.commitment,
433 config.send_transaction_config,
434 )
435 .await?;
436
437 writeln_stdout(format_args!(
438 "Success! Validator info published at: {info_pubkey:?}"
439 ))?;
440 writeln_stdout(format_args!("{signature_str}"))?;
441 Ok("".to_string())
442}
443
444pub async fn process_get_validator_info(
445 rpc_client: &RpcClient,
446 config: &CliConfig<'_>,
447 pubkey: Option<Pubkey>,
448) -> ProcessResult {
449 let validator_info: Vec<(Pubkey, Account)> = if let Some(validator_info_pubkey) = pubkey {
450 vec![(
451 validator_info_pubkey,
452 rpc_client.get_account(&validator_info_pubkey).await?,
453 )]
454 } else {
455 let all_config = rpc_client
456 .get_program_accounts(&solana_config_interface::id())
457 .await?;
458 all_config
459 .into_iter()
460 .filter(|(_, validator_info_account)| {
461 match deserialize::<ConfigKeys>(&validator_info_account.data) {
462 Ok(key_list) => key_list.keys.contains(&(validator_info::id(), false)),
463 Err(_) => false,
464 }
465 })
466 .collect()
467 };
468
469 let mut validator_info_list: Vec<CliValidatorInfo> = vec![];
470 for (validator_info_pubkey, validator_info_account) in validator_info.iter() {
471 let Some((validator_pubkey, is_signed, validator_info)) =
472 parse_validator_info(validator_info_account)
473 else {
474 continue;
475 };
476
477 if config.verbose || is_signed {
478 validator_info_list.push(CliValidatorInfo {
479 identity_pubkey: validator_pubkey.to_string(),
480 info_pubkey: validator_info_pubkey.to_string(),
481 is_signed,
482 info: validator_info,
483 });
484 }
485 }
486
487 Ok(config
488 .output_format
489 .formatted_string(&CliValidatorInfoVec::new(validator_info_list)))
490}
491
492#[cfg(test)]
493mod tests {
494 use {
495 super::*,
496 crate::clap_app::get_clap_app,
497 bincode::{serialize, serialized_size},
498 serde_json::json,
499 };
500
501 #[test]
502 fn test_check_details_length() {
503 let short_details = (0..MAX_LONG_FIELD_LENGTH).map(|_| "X").collect::<String>();
504 assert_eq!(check_details_length(short_details), Ok(()));
505
506 let long_details = (0..MAX_LONG_FIELD_LENGTH + 1)
507 .map(|_| "X")
508 .collect::<String>();
509 assert_eq!(
510 check_details_length(long_details),
511 Err(format!(
512 "validator details longer than {MAX_LONG_FIELD_LENGTH:?}-byte limit"
513 ))
514 );
515 }
516
517 #[test]
518 fn test_check_url() {
519 let url = "http://test.com";
520 assert_eq!(check_url(url.to_string()), Ok(()));
521 let long_url = "http://7cLvFwLCbyHuXQ1RGzhCMobAWYPMSZ3VbUml1CMobAWYPMSZ3VbUml1qWi1nkc3FD7zj9hzTZzMvYJ.com";
522 assert!(check_url(long_url.to_string()).is_err());
523 let non_url = "not parseable";
524 assert!(check_url(non_url.to_string()).is_err());
525 }
526
527 #[test]
528 fn test_is_short_field() {
529 let name = "Alice Validator";
530 assert_eq!(is_short_field(name.to_string()), Ok(()));
531 let long_name = "Alice 7cLvFwLCbyHuXQ1RGzhCMobAWYPMSZ3VbUml1qWi1nkc3FD7zj9hzTZzMvYJt6rY9j9hzTZzMvYJt6rY9";
532 assert!(is_short_field(long_name.to_string()).is_err());
533 }
534
535 #[test]
536 fn test_verify_keybase_username_not_string() {
537 let pubkey = solana_pubkey::new_rand();
538 let value = Value::Bool(true);
539
540 assert_eq!(
541 verify_keybase(&pubkey, &value).unwrap_err().to_string(),
542 "keybase_username could not be parsed as String: true".to_string()
543 )
544 }
545
546 #[test]
547 fn test_parse_args() {
548 let matches = get_clap_app("test", "desc", "version").get_matches_from(vec![
549 "test",
550 "validator-info",
551 "publish",
552 "Alice",
553 "-n",
554 "alice_keybase",
555 "-i",
556 "https://test.com/icon.png",
557 ]);
558 let subcommand_matches = matches.subcommand();
559 assert_eq!(subcommand_matches.0, "validator-info");
560 assert!(subcommand_matches.1.is_some());
561 let subcommand_matches = subcommand_matches.1.unwrap().subcommand();
562 assert_eq!(subcommand_matches.0, "publish");
563 assert!(subcommand_matches.1.is_some());
564 let matches = subcommand_matches.1.unwrap();
565 let expected = json!({
566 "name": "Alice",
567 "keybaseUsername": "alice_keybase",
568 "iconUrl": "https://test.com/icon.png",
569 });
570 assert_eq!(parse_args(matches), expected);
571 }
572
573 #[test]
574 fn test_validator_info_serde() {
575 let mut info = Map::new();
576 info.insert("name".to_string(), Value::String("Alice".to_string()));
577 let info_string = serde_json::to_string(&Value::Object(info)).unwrap();
578
579 let validator_info = ValidatorInfo {
580 info: info_string.clone(),
581 };
582
583 assert_eq!(serialized_size(&validator_info).unwrap(), 24);
584 assert_eq!(
585 serialize(&validator_info).unwrap(),
586 vec![
587 16, 0, 0, 0, 0, 0, 0, 0, 123, 34, 110, 97, 109, 101, 34, 58, 34, 65, 108, 105, 99,
588 101, 34, 125
589 ]
590 );
591
592 let deserialized: ValidatorInfo = deserialize(&[
593 16, 0, 0, 0, 0, 0, 0, 0, 123, 34, 110, 97, 109, 101, 34, 58, 34, 65, 108, 105, 99, 101,
594 34, 125,
595 ])
596 .unwrap();
597 assert_eq!(deserialized.info, info_string);
598 }
599
600 #[test]
601 fn test_parse_validator_info() {
602 let pubkey = solana_pubkey::new_rand();
603 let keys = vec![(validator_info::id(), false), (pubkey, true)];
604 let config = ConfigKeys { keys };
605
606 let mut info = Map::new();
607 info.insert("name".to_string(), Value::String("Alice".to_string()));
608 let info_string = serde_json::to_string(&Value::Object(info.clone())).unwrap();
609 let validator_info = ValidatorInfo { info: info_string };
610 let data = serialize(&(config, validator_info)).unwrap();
611
612 assert_eq!(
613 parse_validator_info(&Account {
614 owner: solana_config_interface::id(),
615 data,
616 ..Account::default()
617 })
618 .unwrap(),
619 (pubkey, true, info)
620 );
621 }
622
623 #[test]
624 fn test_parse_validator_info_not_validator_info_account() {
625 assert!(
626 parse_validator_info(&Account {
627 owner: solana_pubkey::new_rand(),
628 ..Account::default()
629 })
630 .is_none()
631 );
632 }
633
634 #[test]
635 fn test_parse_validator_info_empty_key_list() {
636 let config = ConfigKeys { keys: vec![] };
637 let validator_info = ValidatorInfo {
638 info: String::new(),
639 };
640 let data = serialize(&(config, validator_info)).unwrap();
641
642 assert!(
643 parse_validator_info(&Account {
644 owner: solana_config_interface::id(),
645 data,
646 ..Account::default()
647 },)
648 .is_none()
649 );
650 }
651
652 #[test]
653 fn test_validator_info_max_space() {
654 let max_short_string =
656 "Max Length String KWpP299aFCBWvWg1MHpSuaoTsud7cv8zMJsh99aAtP8X1s26yrR1".to_string();
657 let max_long_string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut libero \
659 quam, volutpat et aliquet eu, varius in mi. Aenean vestibulum ex \
660 in tristique faucibus. Maecenas in imperdiet turpis. Nullam \
661 feugiat aliquet erat. Morbi malesuada turpis sed dui pulvinar \
662 lobortis. Pellentesque a lectus eu leo nullam."
663 .to_string();
664 let mut info = Map::new();
665 info.insert("name".to_string(), Value::String(max_short_string.clone()));
666 info.insert(
667 "website".to_string(),
668 Value::String(max_short_string.clone()),
669 );
670 info.insert(
671 "keybaseUsername".to_string(),
672 Value::String(max_short_string),
673 );
674 info.insert("details".to_string(), Value::String(max_long_string));
675 let info_string = serde_json::to_string(&Value::Object(info)).unwrap();
676
677 let validator_info = ValidatorInfo { info: info_string };
678
679 assert_eq!(
680 serialized_size(&validator_info).unwrap(),
681 MAX_VALIDATOR_INFO
682 );
683 }
684}