Skip to content

Commit

Permalink
feat(docs): finish docstrings
Browse files Browse the repository at this point in the history
  • Loading branch information
Jon-Becker committed Nov 16, 2023
1 parent 8cb8e2c commit 9985590
Show file tree
Hide file tree
Showing 46 changed files with 275 additions and 153 deletions.
9 changes: 9 additions & 0 deletions config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ pub struct ConfigArgs {
value: String,
}

/// The [`Configuration`] struct represents the configuration of the CLI. All heimdall core modules
/// will attempt to read from this configuration when possible.
#[derive(Deserialize, Serialize, Debug)]
pub struct Configuration {
pub rpc_url: String,
Expand All @@ -41,6 +43,7 @@ pub struct Configuration {
}

#[allow(deprecated)]
/// Writes the given configuration to the disc at `$HOME/.bifrost/config.toml`.
pub fn write_config(contents: &str) {
match home_dir() {
Some(mut home) => {
Expand All @@ -60,6 +63,7 @@ pub fn write_config(contents: &str) {
}

#[allow(deprecated)]
/// Deletes the configuration file at `$HOME/.bifrost/config.toml`.
pub fn delete_config() {
match home_dir() {
Some(mut home) => {
Expand All @@ -79,6 +83,7 @@ pub fn delete_config() {
}

#[allow(deprecated)]
/// Reads the configuration file at `$HOME/.bifrost/config.toml`.
pub fn read_config() -> String {
match home_dir() {
Some(mut home) => {
Expand All @@ -104,6 +109,8 @@ pub fn read_config() -> String {
}
}

/// Returns the [`Configuration`] struct after parsing the configuration file at
/// `$HOME/.bifrost/config.toml`.
pub fn get_config() -> Configuration {
let contents = read_config();

Expand All @@ -121,6 +128,7 @@ pub fn get_config() -> Configuration {
config
}

/// update a single key/value pair in the configuration file
pub fn update_config(key: &str, value: &str) {
let mut contents = get_config();

Expand Down Expand Up @@ -153,6 +161,7 @@ pub fn update_config(key: &str, value: &str) {
write_config(&serialized_config);
}

/// The `config` command is used to display and edit the current configuration.
pub fn config(args: ConfigArgs) {
let (logger, _) = Logger::new("");
if !args.key.is_empty() {
Expand Down
4 changes: 2 additions & 2 deletions core/src/cfg/graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ lazy_static! {
static ref CONNECTING_EDGES: Mutex<Vec<String>> = Mutex::new(Vec::new());
}

// converts a VMTrace to a CFG graph
/// convert a symbolic execution [`VMTrace`] into a [`Graph`] of blocks, illustrating the
/// control-flow graph found by the symbolic execution engine.
pub fn build_cfg(
vm_trace: &VMTrace,
contract_cfg: &mut Graph<String, String>,
Expand Down Expand Up @@ -64,7 +65,6 @@ pub fn build_cfg(
}
None => {
// this node does not exist, so we need to add it to the map and the graph
println!("adding node: {}", chunk_index);
let node_index = contract_cfg.add_node(cfg_node);

if let Some(parent_node) = parent_node {
Expand Down
2 changes: 2 additions & 0 deletions core/src/cfg/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ impl CFGArgsBuilder {
}
}

/// The main entry point for the CFG module. Will generate a control flow graph of the target
/// bytecode, after performing symbolic execution and discovering all possible execution paths.
pub async fn cfg(args: CFGArgs) -> Result<Graph<String, String>, Box<dyn std::error::Error>> {
use std::time::Instant;
let now = Instant::now();
Expand Down
1 change: 1 addition & 0 deletions core/src/cfg/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use petgraph::{dot::Dot, graph::Graph};

use super::CFGArgs;

/// Write the generated CFG to a file in the `dot` graphviz format.
pub fn write_cfg_to_file(contract_cfg: &Graph<String, String>, args: &CFGArgs, output_dir: String) {
// get a new logger
let logger = Logger::default();
Expand Down
2 changes: 2 additions & 0 deletions core/src/decode/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ impl DecodeArgsBuilder {
}
}

/// The entrypoint for the decode module. This will attempt to decode the arguments of the target
/// calldata, without the ABI of the target contract.
#[allow(deprecated)]
pub async fn decode(args: DecodeArgs) -> Result<Vec<ResolvedFunction>, Box<dyn std::error::Error>> {
// set logger environment variable if not already set
Expand Down
1 change: 1 addition & 0 deletions core/src/decode/util.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use ethers::types::Transaction;
use heimdall_cache::util::encode_hex;

/// Get an explanation of the decoded transaction using the OpenAI API
pub async fn get_explanation(
decoded: String,
transaction: Transaction,
Expand Down
1 change: 1 addition & 0 deletions core/src/decompile/analyzers/solidity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ use crate::decompile::{
/// - `function` - The function to be updated with the analysis results
/// - `trace` - The TraceFactory to be updated with the analysis results
/// - `trace_parent` - The parent of the current VMTrace
/// - `conditional_map` - A map of the conditionals in the current trace
/// - `branch` - Branch metadata for the current trace. In the format of (branch_depth,
/// branch_index)
/// - @jon-becker: This will be used later to determin if a condition is a require
Expand Down
14 changes: 12 additions & 2 deletions core/src/decompile/analyzers/yul.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,18 @@ use heimdall_common::{
};

use super::super::util::*;

// converts a VMTrace to a Funciton through lexical and syntactic analysis
/// Converts a VMTrace to a Function through lexical and syntactic analysis
///
/// ## Parameters
/// - `vm_trace` - The VMTrace to be analyzed
/// - `function` - The function to be updated with the analysis results
/// - `trace` - The TraceFactory to be updated with the analysis results
/// - `trace_parent` - The parent of the current VMTrace
/// - `conditional_map` - The map of conditionals that have been jumped
///
///
/// ## Returns
/// - `function` - The function updated with the analysis results
pub fn analyze_yul(
vm_trace: &VMTrace,
function: Function,
Expand Down
28 changes: 16 additions & 12 deletions core/src/decompile/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,40 +3,43 @@ use lazy_static::lazy_static;

lazy_static! {

// The following regex is used as a detector for AND bitmasks
/// The following regex is used as a detector for AND bitmasks
pub static ref AND_BITMASK_REGEX: Regex = Regex::new(r"\(0x([a-fA-F0-9]{2}){1,32}\) & ").unwrap();

/// The following regex is used as a detector for AND bitmasks
pub static ref AND_BITMASK_REGEX_2: Regex = Regex::new(r" & \(0x([a-fA-F0-9]{2}){1,32}\)").unwrap();

// used to detect constant values
/// used to detect constant values
pub static ref CONSTANT_REGEX: Regex = Regex::new(r"^(?:(?![memorystorage\[\]]).)*$").unwrap();

// used to detect non-zero bytes within a word
/// used to detect non-zero bytes within a word
pub static ref NON_ZERO_BYTE_REGEX: Regex = Regex::new(r"[a-fA-F0-9][a-fA-F1-9]").unwrap();

// detects a parenthesis enclosed expression
/// detects a parenthesis enclosed expression
pub static ref ENCLOSED_EXPRESSION_REGEX: Regex = Regex::new(r"\(.*\)").unwrap();

// detects a memory access
/// detects a memory access
pub static ref MEM_ACCESS_REGEX: Regex = Regex::new(r"memory\[.*\]").unwrap();

// detects a storage access
/// detects a storage access
pub static ref STORAGE_ACCESS_REGEX: Regex = Regex::new(r"storage\[.*\]").unwrap();

// detects division by 1
/// detects division by 1
pub static ref DIV_BY_ONE_REGEX: Regex = Regex::new(r" \/ 0x01(?!\d)").unwrap();

// detects multiplication by 1
/// detects multiplication by 1
pub static ref MUL_BY_ONE_REGEX: Regex = Regex::new(r"\b0x01\b\s*\*\s*| \*\s*\b0x01\b").unwrap();

// memory variable regex
/// memory variable regex
pub static ref MEM_VAR_REGEX: Regex = Regex::new(r"^var_[a-zA-Z]{1,2}$").unwrap();

// extracts commas within a certain expression, not including commas within parentheses
/// extracts commas within a certain expression, not including commas within parentheses
pub static ref ARGS_SPLIT_REGEX: Regex = Regex::new(r",\s*(?![^()]*\))").unwrap();

// used to detect compiler size checks
/// used to detect compiler size checks
pub static ref VARIABLE_SIZE_CHECK_REGEX: Regex = Regex::new(r"!?\(?0(x01)? < [a-zA-Z0-9_\[\]]+\.length\)?").unwrap();

/// the static header for decompiled solidity contracts
pub static ref DECOMPILED_SOURCE_HEADER_SOL: String =
"// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
Expand All @@ -55,7 +58,8 @@ pragma solidity >=0.8.0;
/// https://heimdall.rs
".to_string();

pub static ref DECOMPILED_SOURCE_HEADER_YUL: String =
/// the static header for decompiled yul contracts
pub static ref DECOMPILED_SOURCE_HEADER_YUL: String =
"/// @title Decompiled Contract
/// @author Jonathan Becker <jonathan@jbecker.dev>
/// @custom:version heimdall-rs v{}
Expand Down
15 changes: 15 additions & 0 deletions core/src/decompile/out/abi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use serde::{Deserialize, Serialize};

use crate::decompile::{util::Function, DecompilerArgs};

/// A single named ABI token.
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct ABIToken {
pub name: String,
Expand All @@ -19,6 +20,7 @@ pub struct ABIToken {
pub type_: String,
}

/// ABI structure for a single contract function.
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct FunctionABI {
#[serde(rename = "type")]
Expand All @@ -31,6 +33,7 @@ pub struct FunctionABI {
pub constant: bool,
}

/// ABI structure for a single contract's custom error.
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct ErrorABI {
#[serde(rename = "type")]
Expand All @@ -39,6 +42,7 @@ pub struct ErrorABI {
pub inputs: Vec<ABIToken>,
}

/// ABI structure for a single contract event.
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct EventABI {
#[serde(rename = "type")]
Expand All @@ -47,13 +51,24 @@ pub struct EventABI {
pub inputs: Vec<ABIToken>,
}

/// An [`ABIStructure`] may be a function, error, or event
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub enum ABIStructure {
Function(FunctionABI),
Error(ErrorABI),
Event(EventABI),
}

/// Build the ABI for a decompiled contract.
///
/// # Arguments
/// - `args`: The [`DecompilerArgs`] used to decompile the contract.
/// - `functions`: The [`Function`]s found in the contract.
/// - `trace`: debug trace of the decompilation process.
/// - `trace_parent`: the parent of the current trace.
///
/// # Returns
/// A [`Vec`] of [`ABIStructure`]s representing the contract's ABI.
pub fn build_abi(
args: &DecompilerArgs,
functions: Vec<Function>,
Expand Down
1 change: 0 additions & 1 deletion core/src/decompile/out/postprocessers/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
pub mod solidity;
pub mod tests;
pub mod yul;
Loading

0 comments on commit 9985590

Please sign in to comment.