bat-cli 0.10.0

Blockchain Auditor Toolkit (BAT)
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
use super::*;
use crate::batbelt::parser::entrypoint_parser::EntrypointParser;

use crate::config::BatConfig;
use strum::IntoEnumIterator;

use crate::batbelt::sonar::{BatSonar, SonarResult, SonarResultType};

use crate::batbelt::metadata::{BatMetadataParser, BatMetadataType, MetadataResult};
use crate::batbelt::parser::function_parser::FunctionParser;
use crate::batbelt::parser::source_code_parser::SourceCodeParser;

use crate::batbelt::BatEnumerator;
use error_stack::{FutureExt, Result, ResultExt};
use serde::{Deserialize, Serialize};

use std::{fs, vec};
use walkdir::DirEntry;

use super::MetadataError;

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FunctionSourceCodeMetadata {
    pub path: String,
    pub name: String,
    pub metadata_id: MetadataId,
    pub function_type: FunctionMetadataType,
    pub start_line_index: usize,
    pub end_line_index: usize,
}

impl BatMetadataParser<FunctionMetadataType> for FunctionSourceCodeMetadata {
    fn name(&self) -> String {
        self.name.clone()
    }
    fn path(&self) -> String {
        self.path.clone()
    }
    fn metadata_id(&self) -> MetadataId {
        self.metadata_id.clone()
    }
    fn start_line_index(&self) -> usize {
        self.start_line_index
    }
    fn end_line_index(&self) -> usize {
        self.end_line_index
    }
    fn metadata_sub_type(&self) -> FunctionMetadataType {
        self.function_type
    }
    fn get_bat_metadata_type() -> BatMetadataType {
        BatMetadataType::Function
    }
    fn metadata_name() -> String {
        "Function".to_string()
    }

    fn new(
        path: String,
        name: String,
        metadata_sub_type: FunctionMetadataType,
        start_line_index: usize,
        end_line_index: usize,
        metadata_id: MetadataId,
    ) -> Self {
        Self {
            path,
            name,
            metadata_id,
            function_type: metadata_sub_type,
            start_line_index,
            end_line_index,
        }
    }

    fn create_metadata_from_dir_entry(entry: DirEntry) -> Result<Vec<Self>, MetadataError> {
        let mut metadata_result: Vec<FunctionSourceCodeMetadata> = vec![];
        let entry_path = entry.path().to_str().unwrap().to_string();
        let file_content = fs::read_to_string(entry.path()).unwrap();
        let bat_sonar = BatSonar::new_scanned(&file_content, SonarResultType::Function);
        for result in bat_sonar.results {
            let function_type = if Self::assert_function_is_entrypoint(&entry_path, result.clone())?
            {
                FunctionMetadataType::EntryPoint
            } else if Self::assert_function_is_handler(entry_path.clone(), result.clone())? {
                FunctionMetadataType::Handler
            } else {
                FunctionMetadataType::Other
            };
            let function_metadata = FunctionSourceCodeMetadata::new(
                entry_path.clone(),
                result.name.to_string(),
                function_type,
                result.start_line_index + 1,
                result.end_line_index + 1,
                Self::create_metadata_id(),
            );
            metadata_result.push(function_metadata);
        }
        // let bat_metadata = BatMetadata::read_metadata()?;
        // bat_metadata
        //     .source_code
        //     .update_functions(metadata_result.clone())?;
        Ok(metadata_result)
    }
}

impl FunctionSourceCodeMetadata {
    pub fn create_metadata_from_content(
        entry_path: &str,
        file_content: &str,
    ) -> Result<Vec<Self>, MetadataError> {
        let mut metadata_result: Vec<FunctionSourceCodeMetadata> = vec![];
        let bat_sonar = BatSonar::new_scanned(file_content, SonarResultType::Function);
        for result in bat_sonar.results {
            let function_type = if Self::assert_function_is_entrypoint(entry_path, result.clone())?
            {
                FunctionMetadataType::EntryPoint
            } else if Self::assert_function_is_handler(entry_path.to_string(), result.clone())? {
                FunctionMetadataType::Handler
            } else {
                FunctionMetadataType::Other
            };
            let function_metadata = FunctionSourceCodeMetadata::new(
                entry_path.to_string(),
                result.name.to_string(),
                function_type,
                result.start_line_index + 1,
                result.end_line_index + 1,
                Self::create_metadata_id(),
            );
            metadata_result.push(function_metadata);
        }
        Ok(metadata_result)
    }

    pub fn to_function_parser(&self) -> Result<FunctionParser, MetadataError> {
        FunctionParser::new_from_metadata(self.clone()).change_context(MetadataError)
    }

    fn assert_function_is_entrypoint(
        entry_path: &str,
        sonar_result: SonarResult,
    ) -> MetadataResult<bool> {
        let entrypoints_names =
            EntrypointParser::get_entrypoint_names_from_program_lib(false).unwrap();
        let config = BatConfig::get_config().unwrap();
        let lib_paths = if config.program_lib_paths.is_empty() {
            vec![config.program_lib_path.clone()]
        } else {
            config.program_lib_paths.clone()
        };
        if lib_paths.iter().any(|p| p == entry_path) {
            if entrypoints_names
                .into_iter()
                .any(|ep_name| ep_name == sonar_result.name)
            {
                Ok(true)
            } else {
                Ok(false)
            }
        } else {
            Ok(false)
        }
    }

    fn assert_function_is_handler(
        entry_path: String,
        sonar_result: SonarResult,
    ) -> MetadataResult<bool> {
        let context_names = EntrypointParser::get_all_contexts_names();
        let result_source_code = SourceCodeParser::new(
            sonar_result.name.clone(),
            entry_path,
            sonar_result.start_line_index + 1,
            sonar_result.end_line_index + 1,
        );
        let result_content = result_source_code.get_source_code_content();
        let result_parameters = get_function_parameters(result_content);
        if !result_parameters.is_empty() {
            let first_parameter = result_parameters[0].clone();
            if first_parameter.contains("Context")
                && context_names
                    .into_iter()
                    .any(|cx_name| first_parameter.contains(&cx_name))
            {
                Ok(true)
            } else {
                Ok(false)
            }
        } else {
            Ok(false)
        }
    }

    pub fn prompt_selection() -> Result<Self, MetadataError> {
        let (metadata_vec, metadata_names) = Self::prompt_types()?;
        let prompt_text = format!("Please select the {}:", Self::metadata_name().blue());
        let selection = BatDialoguer::select(prompt_text, metadata_names, None)
            .change_context(MetadataError)?;

        Ok(metadata_vec[selection].clone())
    }

    pub fn prompt_multiselection(
        select_all: bool,
        force_select: bool,
    ) -> Result<Vec<Self>, MetadataError> {
        let (metadata_vec, metadata_names) = Self::prompt_types()?;
        let prompt_text = format!("Please select the {}:", Self::metadata_name().blue());
        let selections = BatDialoguer::multiselect(
            prompt_text,
            metadata_names.clone(),
            Some(&vec![select_all; metadata_names.len()]),
            force_select,
        )
        .change_context(MetadataError)?;

        let filtered_vec = metadata_vec
            .into_iter()
            .enumerate()
            .filter_map(|(sc_index, sc_metadata)| {
                if selections.iter().any(|selection| &sc_index == selection) {
                    Some(sc_metadata)
                } else {
                    None
                }
            })
            .collect::<Vec<_>>();
        Ok(filtered_vec)
    }

    pub fn prompt_types() -> Result<(Vec<Self>, Vec<String>), MetadataError> {
        let prompt_text = format!(
            "Please select the {} {}:",
            Self::metadata_name().blue(),
            "type".blue()
        );
        let selection = BatDialoguer::select(
            prompt_text,
            FunctionMetadataType::get_colorized_type_vec(true),
            None,
        )
        .change_context(MetadataError)?;
        let selected_sub_type = FunctionMetadataType::get_type_vec()[selection];
        let metadata_vec_filtered =
            SourceCodeMetadata::get_filtered_functions(None, Some(selected_sub_type))
                .change_context(MetadataError)?;
        let metadata_names = metadata_vec_filtered
            .iter()
            .map(|metadata| {
                parse_formatted_path(
                    metadata.name(),
                    metadata.path(),
                    metadata.start_line_index(),
                )
            })
            .collect::<Vec<_>>();
        Ok((metadata_vec_filtered, metadata_names))
    }
}
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct FunctionMetadataCache {
    dependencies: Vec<MetadataId>,
    external_dependencies: Vec<String>,
}

#[derive(
    Debug,
    PartialEq,
    Clone,
    Copy,
    strum_macros::Display,
    strum_macros::EnumIter,
    Serialize,
    Deserialize,
)]
pub enum FunctionMetadataType {
    EntryPoint,
    Handler,
    Other,
}

impl BatEnumerator for FunctionMetadataType {}

pub fn get_function_parameters(function_content: String) -> Vec<String> {
    use quote::ToTokens;

    let item_fn = syn::parse_str::<syn::ItemFn>(&function_content).or_else(|_| {
        let wrapped = format!("fn __wrapper() {{ {} }}", function_content);
        syn::parse_str::<syn::ItemFn>(&wrapped)
    });

    let Ok(item_fn) = item_fn else {
        // Fallback to legacy string parsing if syn fails
        return get_function_parameters_legacy(function_content);
    };

    item_fn
        .sig
        .inputs
        .iter()
        .filter_map(|arg| match arg {
            syn::FnArg::Receiver(_) => None,
            syn::FnArg::Typed(pat_type) => {
                let name = pat_type.pat.to_token_stream().to_string();
                let ty = pat_type.ty.to_token_stream().to_string();
                Some(format!("{}: {}", name, ty))
            }
        })
        .collect()
}

fn get_function_parameters_legacy(function_content: String) -> Vec<String> {
    let content_lines = function_content.lines();
    let function_signature = get_function_signature(&function_content);
    if content_lines.clone().next().unwrap().contains('{') {
        let function_signature_tokenized = function_signature
            .trim_start_matches("pub (crate) fn ")
            .trim_start_matches("pub fn ")
            .split('(')
            .next_back()
            .unwrap()
            .trim_end_matches(')')
            .split(' ')
            .collect::<Vec<_>>();
        if function_signature_tokenized.is_empty() || function_signature_tokenized[0].is_empty() {
            return vec![];
        }
        let mut parameters: Vec<String> = vec![];
        function_signature_tokenized
            .iter()
            .enumerate()
            .fold("".to_string(), |total, current| {
                if current.1.contains(':') {
                    if !total.is_empty() {
                        parameters.push(total);
                    }
                    current.1.to_string()
                } else if current.0 == function_signature_tokenized.len() - 1 {
                    parameters.push(format!("{} {}", total, current.1));
                    total
                } else {
                    format!("{} {}", total, current.1)
                }
            });
        parameters
    } else {
        let filtered: Vec<String> = function_signature
            .lines()
            .filter(|line| line.contains(':'))
            .map(|line| line.trim().trim_end_matches(',').to_string())
            .collect();
        filtered
    }
}

pub fn get_function_signature(function_content: &str) -> String {
    let function_signature = function_content;
    let function_signature = function_signature
        .split('{')
        .next()
        .unwrap()
        .split("->")
        .next()
        .unwrap();
    function_signature.trim().to_string()
}

pub fn get_function_body(function_content: &str) -> String {
    let function_body = function_content;
    let mut body = function_body.split('{');
    body.next();
    let body = body.collect::<Vec<_>>().join("{");
    body.trim_end_matches('}').trim().to_string()
}

// #[cfg(debug_assertions)]
//
// mod test_function_metadata {
//
//     #[test]
//     fn test_function_parse() {
//         let test_function = "pub(crate) fn get_function_metadata_from_file_info() -> Result<Vec<FunctionMetadata>, String> {
//     let mut function_metadata_vec: Vec<FunctionMetadata> = vec![];
//     let file_info_content = function_file_info.read_content().unwrap();
//     let function_types_colored = FunctionMetadataType::get_colorized_functions_type_vec();
//     let bat_sonar = BatSonar::new_scanned(&file_info_content, SonarResultType::Function);
//     for result in bat_sonar.results {
//         let selection =
//             batbelt::cli_inputs::select(prompt_text, function_types_colored.clone(), None)?;
//         let function_type = FunctionMetadataType::get_functions_type_vec()[selection];
//         let function_metadata = FunctionMetadata::new(
//             function_file_info.path.clone(),
//             result.name.to_string(),
//             function_type,
//             result.start_line_index + 1,
//             result.end_line_index + 1,
//         );
//         function_metadata_vec.push(function_metadata);
//     }
//     Ok(function_metadata_vec)
// }";
//         let expected_function_signature = "pub(crate) fn get_function_metadata_from_file_info(
//     function_file_info: FileInfo,
//     function_file_info2: FileInfo2,
// )";
//         let expected_function_parameters = vec![
//             "function_file_info: FileInfo".to_string(),
//             "function_file_info2: FileInfo2".to_string(),
//         ];
//         let expected_function_body =
//             "let mut function_metadata_vec: Vec<FunctionMetadata> = vec![];
//     let file_info_content = function_file_info.read_content().unwrap();
//     let function_types_colored = FunctionMetadataType::get_colorized_functions_type_vec();
//     let bat_sonar = BatSonar::new_scanned(&file_info_content, SonarResultType::Function);
//     for result in bat_sonar.results {
//         let selection =
//             batbelt::cli_inputs::select(prompt_text, function_types_colored.clone(), None)?;
//         let function_type = FunctionMetadataType::get_functions_type_vec()[selection];
//         let function_metadata = FunctionMetadata::new(
//             function_file_info.path.clone(),
//             result.name.to_string(),
//             function_type,
//             result.start_line_index + 1,
//             result.end_line_index + 1,
//         );
//         function_metadata_vec.push(function_metadata);
//     }
//     Ok(function_metadata_vec)";
//         let function_parameters = get_function_parameters(test_function.to_string());
//         assert_eq!(
//             expected_function_parameters, function_parameters,
//             "wrong parameters"
//         );
//         let function_body = get_function_body(test_function);
//         assert_eq!(expected_function_body, function_body, "wrong body");
//         let function_signature = get_function_signature(test_function);
//         assert_eq!(
//             expected_function_signature, function_signature,
//             "wrong signature"
//         );
//     }
//
//     #[test]
//     fn test_handle_cache() {
//         let test_path = "./test.json";
//         let metadata_id = "1234";
//         let dependencies = vec!["asdasd".to_string()];
//         let external_dependencies = vec!["asdasdasidhasjd".to_string()];
//         let function_metadata_cache = FunctionMetadataCache {
//             dependencies,
//             external_dependencies,
//         };
//         let json = json!({ metadata_id: function_metadata_cache });
//         println!("{}", json);
//         let pretty = serde_json::to_string_pretty(&json).unwrap();
//         assert_fs::NamedTempFile::new(test_path).unwrap();
//         fs::write(test_path, pretty).unwrap();
//
//         let read_value = fs::read_to_string(test_path).unwrap();
//         let value: Value = serde_json::from_str(&read_value).unwrap();
//         let f_val: FunctionMetadataCache =
//             serde_json::from_value(value[metadata_id].clone()).unwrap();
//
//         let _test = value["bad_key"].clone();
//
//         println!("fval: {:#?}", f_val);
//     }
// }