solana_cli/
validator_info.rs

1use {
2    crate::{
3        cli::{CliCommand, CliCommandInfo, CliConfig, CliError, ProcessResult},
4        compute_budget::{ComputeUnitConfig, WithComputeUnitConfig},
5        spend_utils::{resolve_spend_tx_and_check_account_balance, SpendAmount},
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, ValidatorInfo, MAX_LONG_FIELD_LENGTH, MAX_SHORT_FIELD_LENGTH, MAX_VALIDATOR_INFO,
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::{get_config_data, ConfigKeys},
26    },
27    solana_keypair::Keypair,
28    solana_message::Message,
29    solana_pubkey::Pubkey,
30    solana_remote_wallet::remote_wallet::RemoteWalletManager,
31    solana_rpc_client::rpc_client::RpcClient,
32    solana_signer::Signer,
33    solana_transaction::Transaction,
34    std::{error, rc::Rc},
35};
36
37// Return an error if a validator details are longer than the max length.
38pub 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
61// Return an error if url field is too long or cannot be parsed.
62pub 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
73// Return an error if a validator field is longer than the max length.
74pub 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    pubkey: &Pubkey,
133    account: &Account,
134) -> Result<(Pubkey, Map<String, serde_json::value::Value>), Box<dyn error::Error>> {
135    if account.owner != solana_config_interface::id() {
136        return Err(format!("{pubkey} is not a validator info account").into());
137    }
138    let key_list: ConfigKeys = deserialize(&account.data)?;
139    if !key_list.keys.is_empty() {
140        let (validator_pubkey, _) = key_list.keys[1];
141        let validator_info_string: String = deserialize(get_config_data(&account.data)?)?;
142        let validator_info: Map<_, _> = serde_json::from_str(&validator_info_string)?;
143        Ok((validator_pubkey, validator_info))
144    } else {
145        Err(format!("{pubkey} could not be parsed as a validator info account").into())
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()) // Being phased out
206                                .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()) // Don't document this argument to discourage its use
222                                .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_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    // Prepare validator info
253    let validator_info = parse_args(matches);
254    Ok(CliCommandInfo {
255        command: CliCommand::SetValidatorInfo {
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 fn process_set_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    // Validate keybase username
283    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    // Check for existing validator-info account
308    let all_config = rpc_client.get_program_accounts(&solana_config_interface::id())?;
309    let existing_account = all_config
310        .iter()
311        .filter(
312            |(_, account)| match deserialize::<ConfigKeys>(&account.data) {
313                Ok(key_list) => key_list.keys.contains(&(validator_info::id(), false)),
314                Err(_) => false,
315            },
316        )
317        .find(|(pubkey, account)| {
318            let (validator_pubkey, _) = parse_validator_info(pubkey, account).unwrap();
319            validator_pubkey == config.signers[0].pubkey()
320        });
321
322    // Create validator-info keypair to use if info_pubkey not provided or does not exist
323    let info_keypair = Keypair::new();
324    let mut info_pubkey = if let Some(pubkey) = info_pubkey {
325        pubkey
326    } else if let Some(validator_info) = existing_account {
327        validator_info.0
328    } else {
329        info_keypair.pubkey()
330    };
331
332    // Check existence of validator-info account
333    let balance = rpc_client.get_balance(&info_pubkey).unwrap_or(0);
334
335    let keys = vec![
336        (validator_info::id(), false),
337        (config.signers[0].pubkey(), true),
338    ];
339    let data_len = MAX_VALIDATOR_INFO
340        .checked_add(serialized_size(&ConfigKeys { keys: keys.clone() }).unwrap())
341        .expect("ValidatorInfo and two keys fit into a u64");
342    let lamports = rpc_client.get_minimum_balance_for_rent_exemption(data_len as usize)?;
343
344    let signers = if balance == 0 {
345        if info_pubkey != info_keypair.pubkey() {
346            println!("Account {info_pubkey:?} does not exist. Generating new keypair...");
347            info_pubkey = info_keypair.pubkey();
348        }
349        vec![config.signers[0], &info_keypair]
350    } else {
351        vec![config.signers[0]]
352    };
353
354    let compute_unit_limit = ComputeUnitLimit::Simulated;
355    let build_message = |lamports| {
356        let keys = keys.clone();
357        if balance == 0 {
358            println!(
359                "Publishing info for Validator {:?}",
360                config.signers[0].pubkey()
361            );
362            let mut instructions =
363                config_instruction::create_account_with_max_config_space::<ValidatorInfo>(
364                    &config.signers[0].pubkey(),
365                    &info_pubkey,
366                    lamports,
367                    MAX_VALIDATOR_INFO,
368                    keys.clone(),
369                )
370                .with_compute_unit_config(&ComputeUnitConfig {
371                    compute_unit_price,
372                    compute_unit_limit,
373                });
374            instructions.extend_from_slice(&[config_instruction::store(
375                &info_pubkey,
376                true,
377                keys,
378                &validator_info,
379            )]);
380            Message::new(&instructions, Some(&config.signers[0].pubkey()))
381        } else {
382            println!(
383                "Updating Validator {:?} info at: {:?}",
384                config.signers[0].pubkey(),
385                info_pubkey
386            );
387            let instructions = vec![config_instruction::store(
388                &info_pubkey,
389                false,
390                keys,
391                &validator_info,
392            )]
393            .with_compute_unit_config(&ComputeUnitConfig {
394                compute_unit_price,
395                compute_unit_limit,
396            });
397            Message::new(&instructions, Some(&config.signers[0].pubkey()))
398        }
399    };
400
401    // Submit transaction
402    let latest_blockhash = rpc_client.get_latest_blockhash()?;
403    let (message, _) = resolve_spend_tx_and_check_account_balance(
404        rpc_client,
405        false,
406        SpendAmount::Some(lamports),
407        &latest_blockhash,
408        &config.signers[0].pubkey(),
409        compute_unit_limit,
410        build_message,
411        config.commitment,
412    )?;
413    let mut tx = Transaction::new_unsigned(message);
414    tx.try_sign(&signers, latest_blockhash)?;
415    let signature_str = rpc_client.send_and_confirm_transaction_with_spinner_and_config(
416        &tx,
417        config.commitment,
418        config.send_transaction_config,
419    )?;
420
421    println!("Success! Validator info published at: {info_pubkey:?}");
422    println!("{signature_str}");
423    Ok("".to_string())
424}
425
426pub fn process_get_validator_info(
427    rpc_client: &RpcClient,
428    config: &CliConfig,
429    pubkey: Option<Pubkey>,
430) -> ProcessResult {
431    let validator_info: Vec<(Pubkey, Account)> = if let Some(validator_info_pubkey) = pubkey {
432        vec![(
433            validator_info_pubkey,
434            rpc_client.get_account(&validator_info_pubkey)?,
435        )]
436    } else {
437        let all_config = rpc_client.get_program_accounts(&solana_config_interface::id())?;
438        all_config
439            .into_iter()
440            .filter(|(_, validator_info_account)| {
441                match deserialize::<ConfigKeys>(&validator_info_account.data) {
442                    Ok(key_list) => key_list.keys.contains(&(validator_info::id(), false)),
443                    Err(_) => false,
444                }
445            })
446            .collect()
447    };
448
449    let mut validator_info_list: Vec<CliValidatorInfo> = vec![];
450    if validator_info.is_empty() {
451        println!("No validator info accounts found");
452    }
453    for (validator_info_pubkey, validator_info_account) in validator_info.iter() {
454        let (validator_pubkey, validator_info) =
455            parse_validator_info(validator_info_pubkey, validator_info_account)?;
456        validator_info_list.push(CliValidatorInfo {
457            identity_pubkey: validator_pubkey.to_string(),
458            info_pubkey: validator_info_pubkey.to_string(),
459            info: validator_info,
460        });
461    }
462    Ok(config
463        .output_format
464        .formatted_string(&CliValidatorInfoVec::new(validator_info_list)))
465}
466
467#[cfg(test)]
468mod tests {
469    use {
470        super::*,
471        crate::clap_app::get_clap_app,
472        bincode::{serialize, serialized_size},
473        serde_json::json,
474    };
475
476    #[test]
477    fn test_check_details_length() {
478        let short_details = (0..MAX_LONG_FIELD_LENGTH).map(|_| "X").collect::<String>();
479        assert_eq!(check_details_length(short_details), Ok(()));
480
481        let long_details = (0..MAX_LONG_FIELD_LENGTH + 1)
482            .map(|_| "X")
483            .collect::<String>();
484        assert_eq!(
485            check_details_length(long_details),
486            Err(format!(
487                "validator details longer than {MAX_LONG_FIELD_LENGTH:?}-byte limit"
488            ))
489        );
490    }
491
492    #[test]
493    fn test_check_url() {
494        let url = "http://test.com";
495        assert_eq!(check_url(url.to_string()), Ok(()));
496        let long_url = "http://7cLvFwLCbyHuXQ1RGzhCMobAWYPMSZ3VbUml1CMobAWYPMSZ3VbUml1qWi1nkc3FD7zj9hzTZzMvYJ.com";
497        assert!(check_url(long_url.to_string()).is_err());
498        let non_url = "not parseable";
499        assert!(check_url(non_url.to_string()).is_err());
500    }
501
502    #[test]
503    fn test_is_short_field() {
504        let name = "Alice Validator";
505        assert_eq!(is_short_field(name.to_string()), Ok(()));
506        let long_name = "Alice 7cLvFwLCbyHuXQ1RGzhCMobAWYPMSZ3VbUml1qWi1nkc3FD7zj9hzTZzMvYJt6rY9j9hzTZzMvYJt6rY9";
507        assert!(is_short_field(long_name.to_string()).is_err());
508    }
509
510    #[test]
511    fn test_verify_keybase_username_not_string() {
512        let pubkey = solana_pubkey::new_rand();
513        let value = Value::Bool(true);
514
515        assert_eq!(
516            verify_keybase(&pubkey, &value).unwrap_err().to_string(),
517            "keybase_username could not be parsed as String: true".to_string()
518        )
519    }
520
521    #[test]
522    fn test_parse_args() {
523        let matches = get_clap_app("test", "desc", "version").get_matches_from(vec![
524            "test",
525            "validator-info",
526            "publish",
527            "Alice",
528            "-n",
529            "alice_keybase",
530            "-i",
531            "https://test.com/icon.png",
532        ]);
533        let subcommand_matches = matches.subcommand();
534        assert_eq!(subcommand_matches.0, "validator-info");
535        assert!(subcommand_matches.1.is_some());
536        let subcommand_matches = subcommand_matches.1.unwrap().subcommand();
537        assert_eq!(subcommand_matches.0, "publish");
538        assert!(subcommand_matches.1.is_some());
539        let matches = subcommand_matches.1.unwrap();
540        let expected = json!({
541            "name": "Alice",
542            "keybaseUsername": "alice_keybase",
543            "iconUrl": "https://test.com/icon.png",
544        });
545        assert_eq!(parse_args(matches), expected);
546    }
547
548    #[test]
549    fn test_validator_info_serde() {
550        let mut info = Map::new();
551        info.insert("name".to_string(), Value::String("Alice".to_string()));
552        let info_string = serde_json::to_string(&Value::Object(info)).unwrap();
553
554        let validator_info = ValidatorInfo {
555            info: info_string.clone(),
556        };
557
558        assert_eq!(serialized_size(&validator_info).unwrap(), 24);
559        assert_eq!(
560            serialize(&validator_info).unwrap(),
561            vec![
562                16, 0, 0, 0, 0, 0, 0, 0, 123, 34, 110, 97, 109, 101, 34, 58, 34, 65, 108, 105, 99,
563                101, 34, 125
564            ]
565        );
566
567        let deserialized: ValidatorInfo = deserialize(&[
568            16, 0, 0, 0, 0, 0, 0, 0, 123, 34, 110, 97, 109, 101, 34, 58, 34, 65, 108, 105, 99, 101,
569            34, 125,
570        ])
571        .unwrap();
572        assert_eq!(deserialized.info, info_string);
573    }
574
575    #[test]
576    fn test_parse_validator_info() {
577        let pubkey = solana_pubkey::new_rand();
578        let keys = vec![(validator_info::id(), false), (pubkey, true)];
579        let config = ConfigKeys { keys };
580
581        let mut info = Map::new();
582        info.insert("name".to_string(), Value::String("Alice".to_string()));
583        let info_string = serde_json::to_string(&Value::Object(info.clone())).unwrap();
584        let validator_info = ValidatorInfo { info: info_string };
585        let data = serialize(&(config, validator_info)).unwrap();
586
587        assert_eq!(
588            parse_validator_info(
589                &Pubkey::default(),
590                &Account {
591                    owner: solana_config_interface::id(),
592                    data,
593                    ..Account::default()
594                }
595            )
596            .unwrap(),
597            (pubkey, info)
598        );
599    }
600
601    #[test]
602    fn test_parse_validator_info_not_validator_info_account() {
603        assert!(parse_validator_info(
604            &Pubkey::default(),
605            &Account {
606                owner: solana_pubkey::new_rand(),
607                ..Account::default()
608            }
609        )
610        .unwrap_err()
611        .to_string()
612        .contains("is not a validator info account"));
613    }
614
615    #[test]
616    fn test_parse_validator_info_empty_key_list() {
617        let config = ConfigKeys { keys: vec![] };
618        let validator_info = ValidatorInfo {
619            info: String::new(),
620        };
621        let data = serialize(&(config, validator_info)).unwrap();
622
623        assert!(parse_validator_info(
624            &Pubkey::default(),
625            &Account {
626                owner: solana_config_interface::id(),
627                data,
628                ..Account::default()
629            },
630        )
631        .unwrap_err()
632        .to_string()
633        .contains("could not be parsed as a validator info account"));
634    }
635
636    #[test]
637    fn test_validator_info_max_space() {
638        // 70-character string
639        let max_short_string =
640            "Max Length String KWpP299aFCBWvWg1MHpSuaoTsud7cv8zMJsh99aAtP8X1s26yrR1".to_string();
641        // 300-character string
642        let max_long_string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut libero \
643                               quam, volutpat et aliquet eu, varius in mi. Aenean vestibulum ex \
644                               in tristique faucibus. Maecenas in imperdiet turpis. Nullam \
645                               feugiat aliquet erat. Morbi malesuada turpis sed dui pulvinar \
646                               lobortis. Pellentesque a lectus eu leo nullam."
647            .to_string();
648        let mut info = Map::new();
649        info.insert("name".to_string(), Value::String(max_short_string.clone()));
650        info.insert(
651            "website".to_string(),
652            Value::String(max_short_string.clone()),
653        );
654        info.insert(
655            "keybaseUsername".to_string(),
656            Value::String(max_short_string),
657        );
658        info.insert("details".to_string(), Value::String(max_long_string));
659        let info_string = serde_json::to_string(&Value::Object(info)).unwrap();
660
661        let validator_info = ValidatorInfo { info: info_string };
662
663        assert_eq!(
664            serialized_size(&validator_info).unwrap(),
665            MAX_VALIDATOR_INFO
666        );
667    }
668}