1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
use std::future::Future;

use crate::utils::{ apply_dotenv, Pdf };
use ethers::abi::{ FixedBytes, Function, Token };
use eyre::{ eyre, ContextCompat };

use crate::types::{ AuditContract, Chains, Issue, SeverityType, Status };

use std::path::PathBuf;

use std::sync::Mutex;
use w3s::helper;

use serde_json::Value;

use std::sync::Arc;

use reqwest::Client;

use crate::constants::{ WEB3_STORAGE_API_ENDPOINT, WEB3_STORAGE_ENDPOINT };

pub trait Cmd: clap::Parser + Sized {
    fn run(self) -> eyre::Result<()>;
}

pub fn block_on<F: Future>(future: F) -> F::Output {
    let rt = tokio::runtime::Runtime::new().expect("could not start tokio rt");
    rt.block_on(future)
}

pub async fn upload_ipfs(
    report_file_path: PathBuf,
    auth_token: &String
) -> eyre::Result<(String, String)> {
    apply_dotenv()?;

    let client = Client::new();

    let report_file = report_file_path.pdf_file_check()?;

    let web3_storage_endpoint = std::env
        ::var("WEB3_STORAGE_API_ENDPOINT")
        .unwrap_or_else(|_| WEB3_STORAGE_API_ENDPOINT.to_string());

    let response = client.post(web3_storage_endpoint).bearer_auth(auth_token).send().await?;

    if !response.status().is_success() {
        return Err(eyre!("Could not upload to report. Try again"));
    }

    let content = response.text().await?;

    let api_response_data = serde_json::from_str::<Value>(&content)?;

    let api_key = &api_response_data["apiKey"].to_string().trim().replace('\"', "");

    if api_key.is_empty() {
        return Err(eyre!("Could not upload to report. Try again"));
    }

    let results = helper::upload(
        report_file.to_str().wrap_err("Invalid File Path")?,
        api_key.as_str(),
        2,
        Some(
            Arc::new(
                Mutex::new(|name, _, pos, total| {
                    if pos != 0 {
                        if pos == total {
                            println!("[+] Uploading is done\n");
                        } else {
                            let percentage = (pos * 100) / total;
                            println!("[+] Uploading {name}. Finished %{percentage:}");
                        }
                    }
                })
            )
        ),
        None,
        None,
        None
    ).await?;

    let cid: String = results[0].into();

    let report_url = format!("https://{cid}{WEB3_STORAGE_ENDPOINT}");

    Ok((cid, report_url))
}

pub fn get_message_data(
    publish_audit_function: &Function,
    chain: &Chains,
    contracts: &[AuditContract],
    project_name: [u8; 28],
    report_hash: String,
    issue_bytes: [u8; 4]
) -> eyre::Result<Vec<u8>> {
    let contract_tokens = contracts
        .iter()
        .filter(|contract| contract.chain.eq(chain))
        .map(|contract| Token::Address(contract.evm_address))
        .collect::<Vec<Token>>();

    let fixed_bytes: FixedBytes = issue_bytes.into();

    let encoded = publish_audit_function.encode_input(
        &[
            Token::Array(contract_tokens),
            Token::String(report_hash),
            Token::FixedBytes(project_name.into()),
            Token::FixedBytes(fixed_bytes),
        ]
    )?;

    Ok(encoded)
}

#[must_use]
#[allow(clippy::cast_possible_truncation)]
pub fn get_issue_bytes(issues: &[Issue]) -> [u8; 4] {
    let count_issues_by_severity = |severity| {
        issues
            .iter()
            .filter(|issue| issue.status.eq(&Status::RiskAccepted) && issue.severity.eq(severity))
            .count()
    };

    let low = count_issues_by_severity(&SeverityType::Low);
    let medium = count_issues_by_severity(&SeverityType::Medium);
    let high = count_issues_by_severity(&SeverityType::High);
    let critical = count_issues_by_severity(&SeverityType::Critical);

    (
        ((critical as u32) << 24) |
        ((high as u32) << 16) |
        ((medium as u32) << 8) |
        (low as u32)
    ).to_be_bytes()
}