Skip to content

Commit db3e06f

Browse files
committed
wip
1 parent 9aab7d9 commit db3e06f

File tree

9 files changed

+56
-20
lines changed

9 files changed

+56
-20
lines changed

crates/cache/src/error.rs

+5
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
1+
//! Cache errors
2+
3+
/// Generic error type for heimdall cache operations
14
#[derive(Debug, thiserror::Error)]
25
pub enum Error {
6+
/// Generic error
37
#[error("Error: {0}")]
48
Generic(String),
9+
/// An IO error occurred
510
#[error("IO error: {0}")]
611
IOError(#[from] std::io::Error),
712
}

crates/cache/src/lib.rs

+20-7
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
//! A simple cache system for heimdall-rs
2+
//! Stores objects in ~/.bifrost/cache as bincode serialized files
3+
//! Objects are stored with an expiry time, and are deleted if they are expired
4+
15
use clap::Parser;
26
use serde::{de::DeserializeOwned, Deserialize, Serialize};
37
#[allow(deprecated)]
@@ -17,6 +21,7 @@ pub(crate) mod util;
1721
override_usage = "heimdall cache <SUBCOMMAND>"
1822
)]
1923
pub struct CacheArgs {
24+
/// Cache subcommand
2025
#[clap(subcommand)]
2126
pub sub: Subcommands,
2227
}
@@ -33,12 +38,15 @@ pub struct NoArguments {}
3338
)]
3439
#[allow(clippy::large_enum_variant)]
3540
pub enum Subcommands {
41+
/// Clear the cache, removing all objects
3642
#[clap(name = "clean", about = "Removes all cached objects in ~/.bifrost/cache")]
3743
Clean(NoArguments),
3844

45+
/// List all cached objects
3946
#[clap(name = "ls", about = "Lists all cached objects in ~/.bifrost/cache")]
4047
Ls(NoArguments),
4148

49+
/// Print the size of the cache in ~/.bifrost/cache
4250
#[clap(name = "size", about = "Prints the size of the cache in ~/.bifrost/cache")]
4351
Size(NoArguments),
4452
}
@@ -47,7 +55,9 @@ pub enum Subcommands {
4755
/// The expiry time is a unix timestamp
4856
#[derive(Debug, Clone, Deserialize, Serialize)]
4957
pub struct Cache<T> {
58+
/// The value stored in the cache
5059
pub value: T,
60+
/// The expiry time of the cache object
5161
pub expiry: u64,
5262
}
5363

@@ -215,7 +225,8 @@ pub fn delete_cache(key: &str) -> Result<(), Error> {
215225
#[allow(deprecated)]
216226
pub fn read_cache<T>(key: &str) -> Result<Option<T>, Error>
217227
where
218-
T: 'static + DeserializeOwned, {
228+
T: 'static + DeserializeOwned,
229+
{
219230
let home = home_dir().ok_or(Error::Generic(
220231
"failed to get home directory. does your os support `std::env::home_dir()`?".to_string(),
221232
))?;
@@ -238,8 +249,8 @@ where
238249
.map_err(|e| Error::Generic(format!("failed to deserialize cache object: {:?}", e)))?;
239250

240251
// check if the cache has expired, if so, delete it and return None
241-
if cache.expiry <
242-
std::time::SystemTime::now()
252+
if cache.expiry
253+
< std::time::SystemTime::now()
243254
.duration_since(std::time::UNIX_EPOCH)
244255
.map_err(|e| Error::Generic(format!("failed to get current time: {:?}", e)))?
245256
.as_secs()
@@ -266,7 +277,8 @@ where
266277
#[allow(deprecated)]
267278
pub fn store_cache<T>(key: &str, value: T, expiry: Option<u64>) -> Result<(), Error>
268279
where
269-
T: Serialize, {
280+
T: Serialize,
281+
{
270282
let home = home_dir().ok_or(Error::Generic(
271283
"failed to get home directory. does your os support `std::env::home_dir()`?".to_string(),
272284
))?;
@@ -278,8 +290,8 @@ where
278290
std::time::SystemTime::now()
279291
.duration_since(std::time::UNIX_EPOCH)
280292
.map_err(|e| Error::Generic(format!("failed to get current time: {:?}", e)))?
281-
.as_secs() +
282-
60 * 60 * 24 * 90,
293+
.as_secs()
294+
+ 60 * 60 * 24 * 90,
283295
);
284296

285297
let cache = Cache { value, expiry };
@@ -304,7 +316,8 @@ pub async fn with_cache<T, F, Fut>(key: &str, func: F) -> eyre::Result<T>
304316
where
305317
T: 'static + Serialize + DeserializeOwned + Send + Sync,
306318
F: FnOnce() -> Fut + Send,
307-
Fut: std::future::Future<Output = Result<T, eyre::Report>> + Send, {
319+
Fut: std::future::Future<Output = Result<T, eyre::Report>> + Send,
320+
{
308321
// Try to read from cache
309322
match read_cache::<T>(key) {
310323
Ok(Some(cached_value)) => {

crates/cache/src/util.rs

+10-7
Original file line numberDiff line numberDiff line change
@@ -10,20 +10,20 @@ use std::{
1010
use crate::error::Error;
1111

1212
/// Decode a hex string into a bytearray
13-
pub fn decode_hex(s: &str) -> Result<Vec<u8>, ParseIntError> {
13+
pub(crate) fn decode_hex(s: &str) -> Result<Vec<u8>, ParseIntError> {
1414
(0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16)).collect()
1515
}
1616

1717
/// Encode a bytearray into a hex string
18-
pub fn encode_hex(s: Vec<u8>) -> String {
18+
pub(crate) fn encode_hex(s: Vec<u8>) -> String {
1919
s.iter().fold(String::new(), |mut acc: String, b| {
2020
write!(acc, "{b:02x}", b = b).expect("unable to write");
2121
acc
2222
})
2323
}
2424

25-
/// Prettify bytes into a human-readable format \
26-
pub fn prettify_bytes(bytes: u64) -> String {
25+
/// Prettify bytes into a human-readable format
26+
pub(crate) fn prettify_bytes(bytes: u64) -> String {
2727
if bytes < 1024 {
2828
format!("{bytes} B")
2929
} else if bytes < 1024 * 1024 {
@@ -39,7 +39,8 @@ pub fn prettify_bytes(bytes: u64) -> String {
3939
}
4040

4141
/// Write contents to a file on the disc
42-
pub fn write_file(path_str: &str, contents: &str) -> Result<(), Error> {
42+
/// If the parent directory does not exist, it will be created
43+
pub(crate) fn write_file(path_str: &str, contents: &str) -> Result<(), Error> {
4344
let path = Path::new(path_str);
4445

4546
if let Some(prefix) = path.parent() {
@@ -58,7 +59,8 @@ pub fn write_file(path_str: &str, contents: &str) -> Result<(), Error> {
5859
}
5960

6061
/// Read contents from a file on the disc
61-
pub fn read_file(path: &str) -> Result<String, Error> {
62+
/// Returns the contents as a string
63+
pub(crate) fn read_file(path: &str) -> Result<String, Error> {
6264
let path = Path::new(path);
6365
let mut file = File::open(path)
6466
.map_err(|e| Error::IOError(std::io::Error::new(std::io::ErrorKind::Other, e)))?;
@@ -68,7 +70,8 @@ pub fn read_file(path: &str) -> Result<String, Error> {
6870
}
6971

7072
/// Delete a file or directory on the disc
71-
pub fn delete_path(_path: &str) -> bool {
73+
/// Returns true if the operation was successful
74+
pub(crate) fn delete_path(_path: &str) -> bool {
7275
let path = match std::path::Path::new(_path).to_str() {
7376
Some(path) => path,
7477
None => return false,

crates/cfg/src/core/graph.rs

+3-4
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,7 @@ use petgraph::{matrix_graph::NodeIndex, Graph};
99

1010
/// convert a symbolic execution [`VMTrace`] into a [`Graph`] of blocks, illustrating the
1111
/// control-flow graph found by the symbolic execution engine.
12-
// TODO: should this be a trait for VMTrace to implement?
13-
pub fn build_cfg(
12+
pub(crate) fn build_cfg(
1413
vm_trace: &VMTrace,
1514
contract_cfg: &mut Graph<String, String>,
1615
parent_node: Option<NodeIndex<u32>>,
@@ -61,8 +60,8 @@ pub fn build_cfg(
6160
.first()
6261
.ok_or_eyre("failed to get first operation")?
6362
.last_instruction
64-
.opcode ==
65-
JUMPDEST,
63+
.opcode
64+
== JUMPDEST,
6665
)?;
6766
}
6867

crates/cfg/src/core/mod.rs

+4
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,15 @@ use super::CfgArgs;
1313
use crate::{core::graph::build_cfg, error::Error};
1414
use tracing::{debug, info};
1515

16+
/// The result of the cfg command. Contains the generated control flow graph.
1617
#[derive(Debug, Clone)]
1718
pub struct CfgResult {
19+
/// The generated control flow graph of the contract.
1820
pub graph: Graph<String, String>,
1921
}
2022

2123
impl CfgResult {
24+
/// Returns the control flow graph as a graphviz formatted string.
2225
pub fn as_dot(&self, color_edges: bool) -> String {
2326
let output = format!("{}", Dot::with_config(&self.graph, &[]));
2427

@@ -44,6 +47,7 @@ impl CfgResult {
4447
}
4548
}
4649

50+
/// Generates a control flow graph for the target contract.
4751
pub async fn cfg(args: CfgArgs) -> Result<CfgResult, Error> {
4852
// init
4953
let start_time = Instant::now();

crates/cfg/src/error.rs

+6
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
1+
//! CFG Errors
2+
3+
/// Generic error type for the CFG Module
14
#[derive(Debug, thiserror::Error)]
25
pub enum Error {
6+
/// Error when trying to fetch information from the chain
37
#[error("Fetch error: {0}")]
48
FetchError(String),
9+
/// Error when disassembling contract bytecode
510
#[error("Disassembly error: {0}")]
611
DisassemblyError(#[from] heimdall_disassembler::Error),
12+
/// Generic error
713
#[error("Internal error: {0}")]
814
Eyre(#[from] eyre::Report),
915
}

crates/cfg/src/interfaces/args.rs

+3
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use eyre::Result;
44
use heimdall_common::ether::bytecode::get_bytecode_from_target;
55
use heimdall_config::parse_url_arg;
66

7+
/// Arguments for the CFG subcommand
78
#[derive(Debug, Clone, Parser, Builder)]
89
#[clap(
910
about = "Generate a visual control flow graph for EVM bytecode",
@@ -43,12 +44,14 @@ pub struct CfgArgs {
4344
}
4445

4546
impl CfgArgs {
47+
/// Get the bytecode for the target
4648
pub async fn get_bytecode(&self) -> Result<Vec<u8>> {
4749
get_bytecode_from_target(&self.target, &self.rpc_url).await
4850
}
4951
}
5052

5153
impl CfgArgsBuilder {
54+
/// Create a new instance of the [`CfgArgsBuilder`]
5255
pub fn new() -> Self {
5356
Self {
5457
target: Some(String::new()),

crates/cfg/src/lib.rs

+3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
//! The CFG module is responsible for generating control-flow graphs from the given
2+
//! contract's source code via symbolic execution.
3+
14
mod error;
25

36
mod core;

crates/vm/src/core/opcodes/wrapped.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ impl WrappedOpcode {
2626
}
2727

2828
impl std::fmt::Display for WrappedOpcode {
29-
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
29+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3030
write!(
3131
f,
3232
"{}({})",
@@ -49,7 +49,7 @@ impl WrappedInput {
4949
}
5050

5151
impl std::fmt::Display for WrappedInput {
52-
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
52+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5353
match self {
5454
WrappedInput::Raw(u256) => write!(f, "{u256}"),
5555
WrappedInput::Opcode(opcode) => write!(f, "{opcode}"),

0 commit comments

Comments
 (0)