Skip to content

Commit

Permalink
Adding elems to dashboard
Browse files Browse the repository at this point in the history
  • Loading branch information
kevin-valerio committed Sep 26, 2024
1 parent 776cb21 commit b8c8157
Show file tree
Hide file tree
Showing 7 changed files with 324 additions and 51 deletions.
1 change: 0 additions & 1 deletion abc.out

This file was deleted.

98 changes: 98 additions & 0 deletions src/cli/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,35 @@ use crate::{
};
use anyhow::Context;
use frame_support::weights::Weight;
use ratatui::{
layout::Rect,
style::{
Color,
Modifier,
Style,
},
text::{
Line,
Span,
},
widgets::{
Block,
Borders,
List,
ListItem,
},
Frame,
};
use serde_derive::{
Deserialize,
Serialize,
};
use sp_core::crypto::AccountId32;
use std::{
fmt::{
Display,
Formatter,
},
fs,
fs::File,
io::Write,
Expand Down Expand Up @@ -70,6 +93,12 @@ pub struct Configuration {
pub show_ui: bool,
}

// impl Display for Configuration {
// fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
// write!(f)
// }
// }

impl Default for Configuration {
fn default() -> Self {
Self {
Expand Down Expand Up @@ -157,6 +186,75 @@ impl TryFrom<&PathBuf> for Configuration {
}

impl Configuration {
pub fn render_config(&self, f: &mut Frame, area: Rect) {
// Helper function to create list items for optional fields
fn format_option<'a, T: std::fmt::Debug>(
label: &'a str,
option: &'a Option<T>,
) -> ListItem<'a> {
let opt = format!("{:?}", option).replace("Some", "");
ListItem::new(Line::from(vec![
Span::raw(format!("{}: ", label)),
Span::styled(opt, Style::default().fg(Color::Yellow)),
]))
}

let items = vec![
format_option("\nCores", &self.cores),
ListItem::new(Line::from(vec![
Span::raw("Use Honggfuzz: "),
Span::styled(
format!("{}", self.use_honggfuzz),
Style::default().fg(Color::Yellow),
),
])),
format_option("Deployer Address", &self.deployer_address),
format_option("Max Messages Per Exec", &self.max_messages_per_exec),
format_option("Report Path", &self.report_path),
ListItem::new(Line::from(vec![
Span::raw("Fuzz Origin: "),
Span::styled(
format!("{}", self.fuzz_origin),
Style::default().fg(Color::Yellow),
),
])),
format_option("Default Gas Limit", &self.default_gas_limit),
format_option("Storage Deposit Limit", &self.storage_deposit_limit),
format_option("Instantiate Initial Value", &self.instantiate_initial_value),
format_option("Constructor Payload", &self.constructor_payload),
ListItem::new(Line::from(vec![
Span::raw("Verbose: "),
Span::styled(
format!("{}", self.verbose),
Style::default().fg(Color::Yellow),
),
])),
format_option(
"Instrumented Contract Path",
&self.instrumented_contract_path,
),
format_option("Fuzz Output", &self.fuzz_output),
ListItem::new(Line::from(vec![
Span::raw("Show UI: "),
Span::styled(
format!("{}", self.show_ui),
Style::default().fg(Color::Yellow),
),
])),
];

let config_list = List::new(items)
.block(
Block::default()
.borders(Borders::ALL)
.title("Configuration"),
)
.style(Style::default().fg(Color::White))
.highlight_style(Style::default().add_modifier(Modifier::BOLD))
.highlight_symbol("> ");

f.render_widget(config_list, area);
}
pub fn should_fuzz_origin(&self) -> OriginFuzzingOption {
match self.fuzz_origin {
true => EnableOriginFuzzing,
Expand Down
3 changes: 1 addition & 2 deletions src/cli/ui/custom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,7 @@ impl CustomManager {

rx.recv()??;

let ratatui =
CustomUI::new(cloned_config.fuzz_output()).context("Couldn't create the custom UI ")?;
let ratatui = CustomUI::new(&cloned_config).context("Couldn't create the custom UI ")?;

ratatui.initialize_tui()?;
Ok(())
Expand Down
58 changes: 41 additions & 17 deletions src/cli/ui/monitor/corpus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@ use crate::cli::config::{
PhinkFiles,
};
use anyhow::bail;
use chrono::Utc;
use std::{
fs,
path::PathBuf,
slice::Iter,
time::UNIX_EPOCH,
};

Expand Down Expand Up @@ -55,23 +53,49 @@ impl CorpusWatcher {
self.data().iter().map(|entry| (entry.x, entry.y)).collect()
}

// pub fn data(&mut self) -> Vec<PlotEntry> {
// let mut data: Vec<PlotEntry> = Vec::new();
// if let Ok(entries) = fs::read_dir(&self.corpus_folder) {
// let entries: Vec<_> = entries.filter_map(Result::ok).collect();
// for (i, entry) in entries.into_iter().enumerate() {
// if let Ok(metadata) = entry.metadata() {
// if let Ok(created_time) = metadata.created() {
// if let Ok(duration_since_epoch) = created_time.duration_since(UNIX_EPOCH)
// { // println!("{:?}", entry.path());
// data.push(PlotEntry::new(
// duration_since_epoch.as_millis_f64(),
// i as f64,
// ));
// }
// }
// }
// }
// }
// data.sort_by(|a, b| a.x.partial_cmp(&b.x).unwrap());
// data
// }
pub fn data(&mut self) -> Vec<PlotEntry> {
let mut data: Vec<PlotEntry> = Vec::new();
if let Ok(entries) = fs::read_dir(&self.corpus_folder) {
let entries: Vec<_> = entries.filter_map(Result::ok).collect();
let count = entries.len() as f64;
for entry in entries {
if let Ok(metadata) = entry.metadata() {
if let Ok(created_time) = metadata.created() {
if let Ok(duration_since_epoch) = created_time.duration_since(UNIX_EPOCH) {
let x = duration_since_epoch.as_secs() as f64;
data.push(PlotEntry::new(x, count));
}
}
}
let mut entries: Vec<_> = entries.filter_map(Result::ok).collect();

// Sort entries by their creation time
entries.sort_by_key(|entry| entry.metadata().unwrap().created().unwrap());

for (i, entry) in entries.into_iter().enumerate() {
let x = entry
.metadata()
.unwrap()
.created()
.unwrap()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs_f64();

data.push(PlotEntry::new(x, i as f64));
}
}
data.sort_by(|a, b| a.x.partial_cmp(&b.x).unwrap());

data
}
}
Expand Down Expand Up @@ -127,7 +151,7 @@ mod tests {
sleep(Duration::from_secs(1)); // Sleep to ensure different timestamp
let data_after_one_file = watcher.data();
assert_eq!(data_after_one_file.len(), 1217);
assert_eq!(data_after_one_file.first().unwrap().y, 1217f64); // One file, so y should be 1
assert_eq!(data_after_one_file.get(3).unwrap().y, 3f64); // One file, so y should be 1

// Add another file and check again
let mut temp_file = NamedTempFile::new_in(corpus_path.clone())?;
Expand All @@ -136,12 +160,12 @@ mod tests {
sleep(Duration::from_secs(1)); // Sleep to ensure different timestamp
let data_after_one_file = watcher.data();
assert_eq!(data_after_one_file.len(), 1218);
assert_eq!(data_after_one_file.get(2).unwrap().y, 1218f64); // Two files, so y should be 2
assert_eq!(data_after_one_file.get(2).unwrap().y, 2f64); // Two files, so y should be 2

// Check that x values (timestamps) are increasing
let second = data_after_one_file.get(40).unwrap().x; // we do 40 because if we take 2, it'll have the same timestamp
let first = data_after_one_file.first().unwrap().x;
// println!("second: {} & first: {}", second, first);
println!("second: {} & first: {}", second, first);
assert!(second > first);
Ok(())
}
Expand Down
10 changes: 9 additions & 1 deletion src/cli/ui/monitor/logs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ pub struct AFLProperties {
pub(crate) corpus_count: u32,
pub(crate) saved_crashes: u32,
pub(crate) exec_speed: u32,
pub(crate) stability: f64,
}

impl AFLProperties {
Expand Down Expand Up @@ -65,6 +66,12 @@ impl FromStr for AFLProperties {
props.last_saved_crash = cap[1].to_string();
}

if let Some(cap) = Regex::new(r"stability : (.+?)\s+│").unwrap().captures(s) {
let percentage_str = cap[1].to_string().replace("%", "");
let percentage: f64 = percentage_str.parse().unwrap();
props.stability = percentage / 100.0;
}

props.corpus_count = extract_value(s, r"corpus count : (\d+)").unwrap_or_default();
props.saved_crashes = extract_value(s, r"saved crashes : (\d+)").unwrap_or_default();
props.exec_speed = extract_value(s, r"exec speed : (\d+)").unwrap_or_default();
Expand Down Expand Up @@ -197,7 +204,7 @@ mod tests {
│ arithmetics : 0/0, 0/0, 0/0 │ pend fav : 0 │
│ known ints : 0/0, 0/0, 0/0 │ own finds : 0 │
│ dictionary : 0/0, 0/0, 0/0, 0/0 │ imported : 4 │
│havoc/splice : 0/514k, 0/992k │ stability : 100.00% │
│havoc/splice : 0/514k, 0/992k │ stability : 97.42% │
│py/custom/rq : unused, unused, unused, unused ├───────────────────────┘
│ trim/eff : disabled, n/a │ [cpu023: 51%]
└─ strategy: explore ────────── state: started :-) ──┘
Expand All @@ -217,6 +224,7 @@ mod tests {
assert_eq!(properties.last_new_find, "0 days, 0 hrs, 2 min, 49 sec");
assert_eq!(properties.last_saved_crash, "none seen yet");
assert_eq!(properties.corpus_count, 5);
assert_eq!(properties.stability, 0.9742000000000001);

Ok(())
}
Expand Down
Loading

0 comments on commit b8c8157

Please sign in to comment.