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
//! Type definitions for Solidity AST from solc JSON output.
//!
//! These types model the AST structure produced by `solc --combined-json ast`.
//! They enable precise analysis of control flow, data flow, and vulnerability patterns.

use serde::{Deserialize, Serialize};

/// Parse a "start:length:file" source location string
pub fn parse_src(src: &str) -> (u64, u64, u64) {
    let parts: Vec<&str> = src.split(':').collect();
    let start = parts.first().and_then(|s| s.parse().ok()).unwrap_or(0);
    let length = parts.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);
    let file = parts.get(2).and_then(|s| s.parse().ok()).unwrap_or(0);
    (start, length, file)
}

/// Convert byte offset to line number in source text
pub fn offset_to_line(source: &str, byte_offset: u64) -> usize {
    source[..std::cmp::min(byte_offset as usize, source.len())]
        .chars()
        .filter(|&c| c == '\n')
        .count()
        + 1
}

/// Source unit (whole contract file)
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SourceUnit {
    /// Node ID
    pub id: u64,
    /// Source location
    pub src: String,
    /// All nodes in this source unit
    pub nodes: Vec<AstNode>,
}

/// Contract definition
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ContractDefinition {
    /// Node ID
    pub id: u64,
    /// Source location
    pub src: String,
    /// Contract name
    pub name: String,
    /// Kind: contract | interface | library
    #[serde(rename = "contractKind")]
    pub contract_kind: String,
    /// Base contracts
    #[serde(rename = "baseContracts")]
    pub base_contracts: Vec<InheritanceSpecifier>,
    /// All members (functions, state vars, etc.)
    pub nodes: Vec<AstNode>,
    /// Linearized base contracts in order
    #[serde(rename = "linearizedBaseContracts")]
    pub linearized_base_contracts: Vec<u64>,
}

/// Base contract reference
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct InheritanceSpecifier {
    /// Base contract name
    #[serde(rename = "baseName")]
    pub base_name: Identifier,
}

/// Function definition
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct FunctionDefinition {
    /// Node ID
    pub id: u64,
    /// Source location
    pub src: String,
    /// Function name
    pub name: String,
    /// Visibility: public | external | internal | private
    pub visibility: String,
    /// State mutability: pure | view | nonpayable | payable
    #[serde(rename = "stateMutability")]
    pub state_mutability: String,
    /// Is constructor
    #[serde(rename = "isConstructor")]
    pub is_constructor: bool,
    /// Applied modifiers
    pub modifiers: Vec<ModifierInvocation>,
    /// Parameters
    pub parameters: ParameterList,
    /// Return parameters
    #[serde(rename = "returnParameters")]
    pub return_parameters: ParameterList,
    /// Function body
    pub body: Option<Block>,
}

/// Modifier invocation in a function
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ModifierInvocation {
    /// Modifier name
    #[serde(rename = "modifierName")]
    pub modifier_name: Identifier,
}

/// Parameter list
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ParameterList {
    /// Parameters
    pub parameters: Vec<VariableDeclaration>,
}

/// Variable declaration
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct VariableDeclaration {
    /// Node ID
    pub id: u64,
    /// Source location
    pub src: String,
    /// Variable name
    pub name: String,
    /// Is state variable
    #[serde(rename = "stateVariable")]
    pub state_variable: bool,
    /// Visibility
    pub visibility: String,
    /// Storage location: memory | storage | calldata
    #[serde(rename = "storageLocation")]
    pub storage_location: String,
    /// Type descriptions
    #[serde(rename = "typeName")]
    pub type_name: Option<Box<AstNode>>,
    /// Type information
    #[serde(rename = "typeDescriptions")]
    pub type_descriptions: Option<TypeDescription>,
}

/// Type description
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TypeDescription {
    /// Type identifier
    #[serde(rename = "typeIdentifier")]
    pub type_identifier: String,
    /// Type string representation
    #[serde(rename = "typeString")]
    pub type_string: String,
}

/// Code block (sequence of statements)
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Block {
    /// Node ID
    pub id: u64,
    /// Source location
    pub src: String,
    /// Statements in order
    pub statements: Vec<AstNode>,
}

/// Expression statement
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ExpressionStatement {
    /// Node ID
    pub id: u64,
    /// Source location
    pub src: String,
    /// The expression
    pub expression: Option<Box<AstNode>>,
}

/// If statement
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct IfStatement {
    /// Node ID
    pub id: u64,
    /// Source location
    pub src: String,
    /// Condition
    pub condition: Box<AstNode>,
    /// True branch
    #[serde(rename = "trueBody")]
    pub true_body: Box<AstNode>,
    /// False branch (if exists)
    #[serde(rename = "falseBody")]
    pub false_body: Option<Box<AstNode>>,
}

/// For loop
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ForStatement {
    /// Node ID
    pub id: u64,
    /// Source location
    pub src: String,
}

/// While loop
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct WhileStatement {
    /// Node ID
    pub id: u64,
    /// Source location
    pub src: String,
}

/// Return statement
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ReturnStatement {
    /// Node ID
    pub id: u64,
    /// Source location
    pub src: String,
}

/// Assignment
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Assignment {
    /// Node ID
    pub id: u64,
    /// Source location
    pub src: String,
    /// Left-hand side
    #[serde(rename = "leftHandSide")]
    pub left_hand_side: Box<AstNode>,
    /// Operator
    pub operator: String,
    /// Right-hand side
    #[serde(rename = "rightHandSide")]
    pub right_hand_side: Box<AstNode>,
}

/// Function call
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct FunctionCall {
    /// Node ID
    pub id: u64,
    /// Source location
    pub src: String,
    /// The function expression
    pub expression: Box<AstNode>,
    /// Arguments
    pub arguments: Vec<AstNode>,
    /// Argument names (for named arguments)
    pub names: Vec<String>,
    /// Is try-call
    #[serde(rename = "tryCall")]
    pub try_call: bool,
}

/// Member access (e.g., obj.member)
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct MemberAccess {
    /// Node ID
    pub id: u64,
    /// Source location
    pub src: String,
    /// The object being accessed
    pub expression: Box<AstNode>,
    /// Member name
    #[serde(rename = "memberName")]
    pub member_name: String,
    /// Type descriptions
    #[serde(rename = "typeDescriptions")]
    pub type_descriptions: Option<TypeDescription>,
}

/// Array/mapping index access (e.g., arr[i])
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct IndexAccess {
    /// Node ID
    pub id: u64,
    /// Source location
    pub src: String,
    /// Base expression
    #[serde(rename = "baseExpression")]
    pub base_expression: Box<AstNode>,
    /// Index expression
    #[serde(rename = "indexExpression")]
    pub index_expression: Option<Box<AstNode>>,
}

/// Binary operation
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BinaryOperation {
    /// Node ID
    pub id: u64,
    /// Source location
    pub src: String,
    /// Operator
    pub operator: String,
    /// Left operand
    #[serde(rename = "leftExpression")]
    pub left_expression: Box<AstNode>,
    /// Right operand
    #[serde(rename = "rightExpression")]
    pub right_expression: Box<AstNode>,
    /// Common type
    #[serde(rename = "commonType")]
    pub common_type: Option<TypeDescription>,
}

/// Identifier
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Identifier {
    /// Node ID
    pub id: u64,
    /// Source location
    pub src: String,
    /// Name
    pub name: String,
    /// Referenced declaration ID
    #[serde(rename = "referencedDeclaration")]
    pub referenced_declaration: Option<u64>,
    /// Type descriptions
    #[serde(rename = "typeDescriptions")]
    pub type_descriptions: Option<TypeDescription>,
}

/// Literal value
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Literal {
    /// Node ID
    pub id: u64,
    /// Source location
    pub src: String,
    /// The value
    pub value: String,
    /// Subdenomination (for numbers)
    pub subdenomination: Option<String>,
    /// Type descriptions
    #[serde(rename = "typeDescriptions")]
    pub type_descriptions: Option<TypeDescription>,
}

/// Emit statement
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct EmitStatement {
    /// Node ID
    pub id: u64,
    /// Source location
    pub src: String,
    /// Event call
    #[serde(rename = "eventCall")]
    pub event_call: Box<AstNode>,
}

/// Revert statement
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RevertStatement {
    /// Node ID
    pub id: u64,
    /// Source location
    pub src: String,
    /// Error call
    #[serde(rename = "errorCall")]
    pub error_call: Option<Box<AstNode>>,
}

/// Modifier definition
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ModifierDefinition {
    /// Node ID
    pub id: u64,
    /// Source location
    pub src: String,
    /// Modifier name
    pub name: String,
    /// Parameters
    pub parameters: ParameterList,
    /// Body
    pub body: Option<Block>,
}

/// State variable declaration
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct StateVariableDeclaration {
    /// Node ID
    pub id: u64,
    /// Source location
    pub src: String,
    /// Variables
    pub variables: Vec<VariableDeclaration>,
}

/// The main AST node type — a discriminated union using serde tagging
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(tag = "nodeType")]
pub enum AstNode {
    /// Source unit
    #[serde(rename = "SourceUnit")]
    SourceUnit(SourceUnit),
    /// Contract definition
    #[serde(rename = "ContractDefinition")]
    ContractDefinition(ContractDefinition),
    /// Function definition
    #[serde(rename = "FunctionDefinition")]
    FunctionDefinition(FunctionDefinition),
    /// Modifier definition
    #[serde(rename = "ModifierDefinition")]
    ModifierDefinition(ModifierDefinition),
    /// State variable declaration
    #[serde(rename = "VariableDeclarationStatement")]
    StateVariableDeclaration(StateVariableDeclaration),
    /// Expression statement
    #[serde(rename = "ExpressionStatement")]
    ExpressionStatement(ExpressionStatement),
    /// If statement
    #[serde(rename = "IfStatement")]
    IfStatement(IfStatement),
    /// For statement
    #[serde(rename = "ForStatement")]
    ForStatement(ForStatement),
    /// While statement
    #[serde(rename = "WhileStatement")]
    WhileStatement(WhileStatement),
    /// Return statement
    #[serde(rename = "Return")]
    ReturnStatement(ReturnStatement),
    /// Assignment
    #[serde(rename = "Assignment")]
    Assignment(Assignment),
    /// Function call
    #[serde(rename = "FunctionCall")]
    FunctionCall(FunctionCall),
    /// Member access
    #[serde(rename = "MemberAccess")]
    MemberAccess(MemberAccess),
    /// Index access
    #[serde(rename = "IndexAccess")]
    IndexAccess(IndexAccess),
    /// Binary operation
    #[serde(rename = "BinaryOperation")]
    BinaryOperation(BinaryOperation),
    /// Identifier
    #[serde(rename = "Identifier")]
    Identifier(Identifier),
    /// Literal
    #[serde(rename = "Literal")]
    Literal(Literal),
    /// Block
    #[serde(rename = "Block")]
    Block(Block),
    /// Emit statement
    #[serde(rename = "EmitStatement")]
    EmitStatement(EmitStatement),
    /// Revert statement
    #[serde(rename = "RevertStatement")]
    RevertStatement(RevertStatement),
    /// Variable declaration (used in function params, etc.)
    #[serde(rename = "VariableDeclaration")]
    VariableDeclaration(VariableDeclaration),
    /// Catch other node types gracefully
    #[serde(other)]
    Other,
}

impl AstNode {
    /// Get type string if available
    pub fn get_type_string(&self) -> Option<String> {
        match self {
            AstNode::Identifier(id) => id.type_descriptions.as_ref().map(|t| t.type_string.clone()),
            AstNode::Literal(lit) => lit
                .type_descriptions
                .as_ref()
                .map(|t| t.type_string.clone()),
            AstNode::MemberAccess(ma) => {
                ma.type_descriptions.as_ref().map(|t| t.type_string.clone())
            }
            AstNode::BinaryOperation(bo) => bo.common_type.as_ref().map(|t| t.type_string.clone()),
            _ => None,
        }
    }
}