sentri-analyzer-evm 0.3.0

Sentri: EVM smart contract analyzer with static analysis and invariant checking for Ethereum, Polygon, and other EVM chains.
Documentation
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
#![allow(missing_docs)]
//! Control Flow Graph (CFG) construction and analysis.
//!
//! Builds a Control Flow Graph (CFG) from Solidity AST to enable:
//! - Execution path analysis
//! - Vulnerability detection across execution flows
//! - Data flow tracking through branches
//! - Loop detection and analysis

use crate::ast::AstFunction;
use crate::errors::{AnalysisError, AnalysisResult};
use petgraph::graph::{DiGraph, NodeIndex};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tracing::{debug, info};

/// A basic block in the control flow graph.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BasicBlock {
    /// Unique identifier for this block.
    pub id: usize,
    /// Statements in this block.
    pub statements: Vec<Statement>,
    /// Block dominates other blocks.
    pub dominates: Vec<usize>,
    /// Block is dominated by these blocks.
    pub dominated_by: Vec<usize>,
    /// Is this a loop header.
    pub is_loop_header: bool,
    /// Is this an exit block.
    pub is_exit: bool,
}

impl BasicBlock {
    /// Create a new basic block.
    pub fn new(id: usize) -> Self {
        Self {
            id,
            statements: Vec::new(),
            dominates: Vec::new(),
            dominated_by: Vec::new(),
            is_loop_header: false,
            is_exit: false,
        }
    }

    /// Add a statement to this block.
    pub fn add_statement(&mut self, stmt: Statement) {
        self.statements.push(stmt);
    }
}

/// Statement in a basic block.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Statement {
    /// Variable assignment.
    Assignment { target: String, value: String },
    /// Conditional branch.
    Branch { condition: String },
    /// State mutation.
    StateMutation { variable: String, value: String },
    /// Function call.
    FunctionCall { function: String, args: Vec<String> },
    /// Return statement.
    Return { value: Option<String> },
    /// Generic statement.
    Generic { code: String },
}

/// Control Flow Graph for a function.
#[derive(Debug, Clone)]
pub struct ControlFlowGraph {
    /// Directed graph of basic blocks.
    graph: DiGraph<BasicBlock, String>,
    /// Map from block ID to node index.
    block_map: HashMap<usize, NodeIndex>,
    /// Entry block ID.
    entry_block: usize,
    /// Exit blocks.
    exit_blocks: Vec<usize>,
    /// Next block ID to assign.
    next_id: usize,
}

impl ControlFlowGraph {
    /// Create a new CFG for a function.
    pub fn new() -> Self {
        let mut cfg = Self {
            graph: DiGraph::new(),
            block_map: HashMap::new(),
            entry_block: 0,
            exit_blocks: Vec::new(),
            next_id: 0,
        };

        // Create entry block
        let entry = cfg.new_block();
        cfg.entry_block = entry;

        cfg
    }

    /// Create a new basic block in the CFG.
    pub fn new_block(&mut self) -> usize {
        let id = self.next_id;
        self.next_id += 1;

        let block = BasicBlock::new(id);
        let node_idx = self.graph.add_node(block);
        self.block_map.insert(id, node_idx);

        id
    }

    /// Add an edge from one block to another.
    pub fn add_edge(
        &mut self,
        from: usize,
        to: usize,
        label: impl Into<String>,
    ) -> AnalysisResult<()> {
        let from_idx = self
            .block_map
            .get(&from)
            .copied()
            .ok_or_else(|| AnalysisError::cfg("Block not found"))?;

        let to_idx = self
            .block_map
            .get(&to)
            .copied()
            .ok_or_else(|| AnalysisError::cfg("Target block not found"))?;

        self.graph.add_edge(from_idx, to_idx, label.into());
        Ok(())
    }

    /// Add a statement to a block.
    pub fn add_statement(&mut self, block_id: usize, stmt: Statement) -> AnalysisResult<()> {
        let node_idx = self
            .block_map
            .get(&block_id)
            .copied()
            .ok_or_else(|| AnalysisError::cfg("Block not found"))?;

        if let Some(block) = self.graph.node_weight_mut(node_idx) {
            block.add_statement(stmt);
            Ok(())
        } else {
            Err(AnalysisError::cfg("Failed to get block"))
        }
    }

    /// Mark a block as an exit block.
    pub fn mark_exit(&mut self, block_id: usize) -> AnalysisResult<()> {
        let node_idx = self
            .block_map
            .get(&block_id)
            .copied()
            .ok_or_else(|| AnalysisError::cfg("Block not found"))?;

        if let Some(block) = self.graph.node_weight_mut(node_idx) {
            block.is_exit = true;
            self.exit_blocks.push(block_id);
            Ok(())
        } else {
            Err(AnalysisError::cfg("Failed to get block"))
        }
    }

    /// Compute dominance relationships.
    pub fn compute_dominance(&mut self) -> AnalysisResult<()> {
        info!("Computing dominance relationships for CFG");

        // Entry block dominates all reachable blocks
        self.compute_dominators()?;

        // Compute dominated_by relationships
        let dominators: HashMap<usize, Vec<usize>> = self
            .block_map
            .iter()
            .map(|(&id, &idx)| {
                let dominates = self
                    .graph
                    .node_weight(idx)
                    .map(|b| b.dominates.clone())
                    .unwrap_or_default();
                (id, dominates)
            })
            .collect();

        for (dominator_id, dominated_blocks) in dominators {
            for dominated_id in dominated_blocks {
                let node_idx = self
                    .block_map
                    .get(&dominated_id)
                    .copied()
                    .ok_or_else(|| AnalysisError::cfg("Block not found"))?;

                if let Some(block) = self.graph.node_weight_mut(node_idx) {
                    block.dominated_by.push(dominator_id);
                }
            }
        }

        Ok(())
    }

    /// Compute immediate dominators using iterative algorithm.
    fn compute_dominators(&mut self) -> AnalysisResult<()> {
        let blocks: Vec<usize> = self.block_map.keys().copied().collect();

        if blocks.is_empty() {
            return Ok(());
        }

        // Initialize: everyone is dominated by all blocks
        let mut dominators: HashMap<usize, Vec<usize>> =
            blocks.iter().map(|&id| (id, blocks.clone())).collect();

        // Entry block only dominates itself
        if let Some(entry_doms) = dominators.get_mut(&self.entry_block) {
            entry_doms.clear();
            entry_doms.push(self.entry_block);
        }

        // Iterate until fixpoint
        let mut changed = true;
        let mut iterations = 0;
        const MAX_ITERATIONS: usize = 100;

        while changed && iterations < MAX_ITERATIONS {
            changed = false;
            iterations += 1;

            for &block_id in &blocks {
                if block_id == self.entry_block {
                    continue;
                }

                // Find predecessors
                let node_idx = self
                    .block_map
                    .get(&block_id)
                    .copied()
                    .ok_or_else(|| AnalysisError::cfg("Block not found"))?;

                let mut pred_dominators: Option<Vec<usize>> = None;

                for pred_idx in self
                    .graph
                    .neighbors_directed(node_idx, petgraph::Direction::Incoming)
                {
                    let pred_id = self
                        .graph
                        .node_weight(pred_idx)
                        .map(|b| b.id)
                        .ok_or_else(|| AnalysisError::cfg("Predecessor not found"))?;

                    let pred_doms = dominators
                        .get(&pred_id)
                        .cloned()
                        .ok_or_else(|| AnalysisError::cfg("Predecessor dominators not found"))?;

                    pred_dominators = match pred_dominators {
                        None => Some(pred_doms),
                        Some(current) => {
                            let intersection: Vec<_> = current
                                .iter()
                                .filter(|d| pred_doms.contains(d))
                                .copied()
                                .collect();
                            Some(intersection)
                        }
                    };
                }

                // dom(block) = {block} ∪ intersection(dom(predecessors))
                if let Some(mut pred_doms) = pred_dominators {
                    pred_doms.push(block_id);
                    pred_doms.sort();
                    pred_doms.dedup();

                    if let Some(old_doms) = dominators.get_mut(&block_id) {
                        if *old_doms != pred_doms {
                            *old_doms = pred_doms;
                            changed = true;
                        }
                    }
                }
            }
        }

        debug!(
            "Dominance computation converged after {} iterations",
            iterations
        );

        // Update graph with dominance info
        for (block_id, doms) in dominators {
            if let Some(node_idx) = self.block_map.get(&block_id).copied() {
                if let Some(block) = self.graph.node_weight_mut(node_idx) {
                    block.dominates = doms.into_iter().filter(|&id| id != block_id).collect();
                }
            }
        }

        Ok(())
    }

    /// Check if block `a` dominates block `b`.
    pub fn dominates(&self, a: usize, b: usize) -> bool {
        self.block_map
            .get(&a)
            .and_then(|&idx| self.graph.node_weight(idx))
            .map(|block| block.dominates.contains(&b))
            .unwrap_or(false)
    }

    /// Detect loops in the CFG.
    pub fn detect_loops(&mut self) -> AnalysisResult<Vec<Loop>> {
        info!("Detecting loops in CFG");

        let mut loops = Vec::new();

        // Back edge detection: edge to dominator = loop
        let blocks: Vec<usize> = self.block_map.keys().copied().collect();

        for &block_id in &blocks {
            let node_idx = self
                .block_map
                .get(&block_id)
                .copied()
                .ok_or_else(|| AnalysisError::cfg("Block not found"))?;

            // Collect successors first to avoid borrowing issues
            let successors: Vec<_> = self.graph.neighbors(node_idx).collect();

            for succ_idx in successors {
                let succ_id = self
                    .graph
                    .node_weight(succ_idx)
                    .map(|b| b.id)
                    .ok_or_else(|| AnalysisError::cfg("Successor not found"))?;

                // Back edge if successor dominates this block
                if self.dominates(succ_id, block_id) {
                    loops.push(Loop {
                        header: succ_id,
                        back_edges: vec![(block_id, succ_id)],
                        body_blocks: vec![succ_id],
                    });

                    // Mark as loop header
                    if let Some(block) = self.graph.node_weight_mut(succ_idx) {
                        block.is_loop_header = true;
                    }
                }
            }
        }

        info!("Found {} loops", loops.len());
        Ok(loops)
    }

    /// Get all reachable blocks from a starting block.
    pub fn reachable(&self, from: usize) -> AnalysisResult<Vec<usize>> {
        let start_idx = self
            .block_map
            .get(&from)
            .copied()
            .ok_or_else(|| AnalysisError::cfg("Block not found"))?;

        let mut reachable = Vec::new();
        let mut visited = std::collections::HashSet::new();
        let mut queue = vec![start_idx];

        while let Some(node_idx) = queue.pop() {
            if !visited.insert(node_idx) {
                continue;
            }

            if let Some(block) = self.graph.node_weight(node_idx) {
                reachable.push(block.id);
            }

            for succ_idx in self.graph.neighbors(node_idx) {
                queue.push(succ_idx);
            }
        }

        Ok(reachable)
    }

    /// Get entry block ID.
    pub fn entry(&self) -> usize {
        self.entry_block
    }

    /// Get exit block IDs.
    pub fn exits(&self) -> Vec<usize> {
        self.exit_blocks.clone()
    }

    /// Get block count.
    pub fn block_count(&self) -> usize {
        self.graph.node_count()
    }
}

impl Default for ControlFlowGraph {
    fn default() -> Self {
        Self::new()
    }
}

/// Represents a loop in the CFG.
#[derive(Debug, Clone)]
pub struct Loop {
    /// Loop header block.
    pub header: usize,
    /// Back edges (from, to).
    pub back_edges: Vec<(usize, usize)>,
    /// Blocks in loop body.
    pub body_blocks: Vec<usize>,
}

/// CFG Builder for function analysis.
pub struct CfgBuilder;

impl CfgBuilder {
    /// Build CFG from a function's AST.
    pub fn build(function: &AstFunction) -> AnalysisResult<ControlFlowGraph> {
        debug!("Building CFG for function '{}'", function.name);

        let mut cfg = ControlFlowGraph::new();

        // For now, simple linear CFG from function body
        // TODO: Parse function body statements and create appropriate branching
        let entry = cfg.entry();
        cfg.mark_exit(entry)?;

        // Compute dominance
        cfg.compute_dominance()?;

        // Detect loops
        cfg.detect_loops()?;

        Ok(cfg)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cfg_creation() {
        let mut cfg = ControlFlowGraph::new();
        let block1 = cfg.entry();
        let block2 = cfg.new_block();
        let block3 = cfg.new_block();

        assert_eq!(cfg.block_count(), 3);
        assert_eq!(block1, 0);
        assert_eq!(block2, 1);
        assert_eq!(block3, 2);
    }

    #[test]
    fn test_cfg_edges() {
        let mut cfg = ControlFlowGraph::new();
        let b1 = cfg.entry();
        let b2 = cfg.new_block();
        let b3 = cfg.new_block();

        cfg.add_edge(b1, b2, "true").ok();
        cfg.add_edge(b1, b3, "false").ok();

        assert_eq!(cfg.block_count(), 3);
    }

    #[test]
    fn test_cfg_exit_marking() {
        let mut cfg = ControlFlowGraph::new();
        let entry = cfg.entry();

        cfg.mark_exit(entry).ok();
        assert!(cfg.exits().contains(&entry));
    }
}