Skip to content

Commit

Permalink
Permit users to assign labels to account addresses
Browse files Browse the repository at this point in the history
  • Loading branch information
mvines authored and mergify[bot] committed Jun 18, 2020
1 parent a25ea8e commit b297d0b
Show file tree
Hide file tree
Showing 10 changed files with 207 additions and 60 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 29 additions & 1 deletion cli-config/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Wallet settings that can be configured for long-term use
use serde_derive::{Deserialize, Serialize};
use std::io;
use std::{collections::HashMap, io, path::Path};
use url::Url;

lazy_static! {
Expand All @@ -17,6 +17,9 @@ pub struct Config {
pub json_rpc_url: String,
pub websocket_url: String,
pub keypair_path: String,

#[serde(default)]
pub address_labels: HashMap<String, String>,
}

impl Default for Config {
Expand All @@ -32,10 +35,17 @@ impl Default for Config {
// `Config::compute_websocket_url(&json_rpc_url)`
let websocket_url = "".to_string();

let mut address_labels = HashMap::new();
address_labels.insert(
"11111111111111111111111111111111".to_string(),
"System Program".to_string(),
);

Self {
json_rpc_url,
websocket_url,
keypair_path,
address_labels,
}
}
}
Expand Down Expand Up @@ -65,6 +75,24 @@ impl Config {
}
ws_url.to_string()
}

pub fn import_address_labels<P>(&mut self, filename: P) -> Result<(), io::Error>
where
P: AsRef<Path>,
{
let imports: HashMap<String, String> = crate::load_config_file(filename)?;
for (address, label) in imports.into_iter() {
self.address_labels.insert(address, label);
}
Ok(())
}

pub fn export_address_labels<P>(&self, filename: P) -> Result<(), io::Error>
where
P: AsRef<Path>,
{
crate::save_config_file(&self.address_labels, filename)
}
}

#[cfg(test)]
Expand Down
5 changes: 4 additions & 1 deletion cli/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ use solana_stake_program::{
use solana_transaction_status::{EncodedTransaction, TransactionEncoding};
use solana_vote_program::vote_state::VoteAuthorize;
use std::{
collections::HashMap,
error,
fmt::Write as FmtWrite,
fs::File,
Expand Down Expand Up @@ -493,6 +494,7 @@ pub struct CliConfig<'a> {
pub output_format: OutputFormat,
pub commitment: CommitmentConfig,
pub send_transaction_config: RpcSendTransactionConfig,
pub address_labels: HashMap<String, String>,
}

impl CliConfig<'_> {
Expand Down Expand Up @@ -596,6 +598,7 @@ impl Default for CliConfig<'_> {
output_format: OutputFormat::Display,
commitment: CommitmentConfig::default(),
send_transaction_config: RpcSendTransactionConfig::default(),
address_labels: HashMap::new(),
}
}
}
Expand Down Expand Up @@ -1837,7 +1840,7 @@ pub fn process_command(config: &CliConfig) -> ProcessResult {
CliCommand::ShowBlockProduction { epoch, slot_limit } => {
process_show_block_production(&rpc_client, config, *epoch, *slot_limit)
}
CliCommand::ShowGossip => process_show_gossip(&rpc_client),
CliCommand::ShowGossip => process_show_gossip(&rpc_client, config),
CliCommand::ShowStakes {
use_lamports_unit,
vote_account_pubkeys,
Expand Down
22 changes: 17 additions & 5 deletions cli/src/cli_output.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use crate::{cli::build_balance_message, display::writeln_name_value};
use crate::{
cli::build_balance_message,
display::{format_labeled_address, writeln_name_value},
};
use chrono::{DateTime, NaiveDateTime, SecondsFormat, Utc};
use console::{style, Emoji};
use inflector::cases::titlecase::to_title_case;
Expand All @@ -18,7 +21,11 @@ use solana_vote_program::{
authorized_voters::AuthorizedVoters,
vote_state::{BlockTimestamp, Lockout},
};
use std::{collections::BTreeMap, fmt, time::Duration};
use std::{
collections::{BTreeMap, HashMap},
fmt,
time::Duration,
};

static WARNING: Emoji = Emoji("⚠️", "!");

Expand Down Expand Up @@ -404,10 +411,15 @@ pub struct CliValidator {
}

impl CliValidator {
pub fn new(vote_account: &RpcVoteAccountInfo, current_epoch: Epoch, version: String) -> Self {
pub fn new(
vote_account: &RpcVoteAccountInfo,
current_epoch: Epoch,
version: String,
address_labels: &HashMap<String, String>,
) -> Self {
Self {
identity_pubkey: vote_account.node_pubkey.to_string(),
vote_account_pubkey: vote_account.vote_pubkey.to_string(),
identity_pubkey: format_labeled_address(&vote_account.node_pubkey, address_labels),
vote_account_pubkey: format_labeled_address(&vote_account.vote_pubkey, address_labels),
commission: vote_account.commission,
last_vote: vote_account.last_vote,
root_slot: vote_account.root_slot,
Expand Down
13 changes: 8 additions & 5 deletions cli/src/cluster_query.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::{
cli::{CliCommand, CliCommandInfo, CliConfig, CliError, ProcessResult},
cli_output::*,
display::{new_spinner_progress_bar, println_name_value},
display::{format_labeled_address, new_spinner_progress_bar, println_name_value},
spend_utils::{resolve_spend_tx_and_check_account_balance, SpendAmount},
};
use clap::{value_t, value_t_or_exit, App, AppSettings, Arg, ArgMatches, SubCommand};
Expand Down Expand Up @@ -734,11 +734,12 @@ pub fn process_show_block_production(
let leader_schedule = leader_schedule.unwrap();

let mut leader_per_slot_index = Vec::new();
leader_per_slot_index.resize(total_slots, "?");
leader_per_slot_index.resize(total_slots, "?".to_string());
for (pubkey, leader_slots) in leader_schedule.iter() {
let pubkey = format_labeled_address(pubkey, &config.address_labels);
for slot_index in leader_slots.iter() {
if *slot_index >= start_slot_index && *slot_index <= end_slot_index {
leader_per_slot_index[*slot_index - start_slot_index] = pubkey;
leader_per_slot_index[*slot_index - start_slot_index] = pubkey.clone();
}
}
}
Expand Down Expand Up @@ -1085,7 +1086,7 @@ pub fn process_live_slots(url: &str) -> ProcessResult {
Ok("".to_string())
}

pub fn process_show_gossip(rpc_client: &RpcClient) -> ProcessResult {
pub fn process_show_gossip(rpc_client: &RpcClient, config: &CliConfig) -> ProcessResult {
let cluster_nodes = rpc_client.get_cluster_nodes()?;

fn format_port(addr: Option<SocketAddr>) -> String {
Expand All @@ -1101,7 +1102,7 @@ pub fn process_show_gossip(rpc_client: &RpcClient) -> ProcessResult {
node.gossip
.map(|addr| addr.ip().to_string())
.unwrap_or_else(|| "none".to_string()),
node.pubkey,
format_labeled_address(&node.pubkey, &config.address_labels),
format_port(node.gossip),
format_port(node.tpu),
format_port(node.rpc),
Expand Down Expand Up @@ -1235,6 +1236,7 @@ pub fn process_show_validators(
.get(&vote_account.node_pubkey)
.unwrap_or(&unknown_version)
.clone(),
&config.address_labels,
)
})
.collect();
Expand All @@ -1250,6 +1252,7 @@ pub fn process_show_validators(
.get(&vote_account.node_pubkey)
.unwrap_or(&unknown_version)
.clone(),
&config.address_labels,
)
})
.collect();
Expand Down
44 changes: 43 additions & 1 deletion cli/src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use solana_sdk::{
transaction::Transaction,
};
use solana_transaction_status::RpcTransactionStatusMeta;
use std::{fmt, io};
use std::{collections::HashMap, fmt, io};

// Pretty print a "name value"
pub fn println_name_value(name: &str, value: &str) {
Expand All @@ -27,6 +27,19 @@ pub fn writeln_name_value(f: &mut fmt::Formatter, name: &str, value: &str) -> fm
writeln!(f, "{} {}", style(name).bold(), styled_value)
}

pub fn format_labeled_address(pubkey: &str, address_labels: &HashMap<String, String>) -> String {
let label = address_labels.get(pubkey);
match label {
Some(label) => format!(
"{:.31} ({:.4}..{})",
label,
pubkey,
pubkey.split_at(pubkey.len() - 4).1
),
None => pubkey.to_string(),
}
}

pub fn println_name_value_or(name: &str, value: &str, setting_type: SettingType) {
let description = match setting_type {
SettingType::Explicit => "",
Expand Down Expand Up @@ -210,3 +223,32 @@ pub fn new_spinner_progress_bar() -> ProgressBar {
progress_bar.enable_steady_tick(100);
progress_bar
}

#[cfg(test)]
mod test {
use super::*;
use solana_sdk::pubkey::Pubkey;

#[test]
fn test_format_labeled_address() {
let pubkey = Pubkey::default().to_string();
let mut address_labels = HashMap::new();

assert_eq!(format_labeled_address(&pubkey, &address_labels), pubkey);

address_labels.insert(pubkey.to_string(), "Default Address".to_string());
assert_eq!(
&format_labeled_address(&pubkey, &address_labels),
"Default Address (1111..1111)"
);

address_labels.insert(
pubkey.to_string(),
"abcdefghijklmnopqrstuvwxyz1234567890".to_string(),
);
assert_eq!(
&format_labeled_address(&pubkey, &address_labels),
"abcdefghijklmnopqrstuvwxyz12345 (1111..1111)"
);
}
}
Loading

0 comments on commit b297d0b

Please sign in to comment.