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
//! Core domain models for invariant analysis.
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
/// A compiled invariant expression with metadata.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Invariant {
/// Unique identifier for the invariant.
pub name: String,
/// Human-readable description.
pub description: Option<String>,
/// The invariant expression in IR form.
pub expression: Expression,
/// Severity level: "critical", "high", "medium", "low".
pub severity: String,
/// Category: "core", "defi", "bridge", "governance", "account-abstraction", etc.
pub category: String,
/// Whether this invariant should always hold.
pub is_always_true: bool,
/// Layer scopes for cross-layer analysis (e.g., ["bundler", "account", "paymaster"]).
/// If empty, applies to all layers.
pub layers: Vec<String>,
/// Execution phases (e.g., ["validation", "execution", "settlement"]).
/// For AA invariants that must hold at specific phases. Empty means all phases.
pub phases: Vec<String>,
}
/// An expression tree representing invariant conditions.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum Expression {
/// Boolean literal.
Boolean(bool),
/// Variable reference.
Var(String),
/// Layer-qualified variable reference (e.g., bundler::nonce).
LayerVar {
/// Layer name (bundler, account, paymaster, protocol, entrypoint).
layer: String,
/// Variable name within the layer.
var: String,
},
/// Phase-qualified variable reference (e.g., validation::account::balance).
/// Checks state at a specific execution phase (validation, execution, settlement).
PhaseQualifiedVar {
/// Execution phase: "validation", "execution", or "settlement".
phase: String,
/// Layer name within that phase.
layer: String,
/// Variable name within the layer.
var: String,
},
/// Phase constraint: ensures a condition holds during a specific phase.
/// Example: ensure `account::balance >= min_required` during validation phase.
PhaseConstraint {
/// Phase to enforce the constraint in.
phase: String,
/// The constraint expression to hold in this phase.
constraint: Box<Expression>,
},
/// Cross-phase relation: relates variable values across two phases.
/// Example: `validation::account::balance >= execution::account::balance`
/// used to track state changes across phases.
CrossPhaseRelation {
/// First phase.
phase1: String,
/// First phase expression.
expr1: Box<Expression>,
/// Second phase.
phase2: String,
/// Second phase expression.
expr2: Box<Expression>,
/// Relation operator.
op: BinaryOp,
},
/// Integer constant.
Int(i128),
/// Comparison: left op right.
BinaryOp {
/// Left operand.
left: Box<Expression>,
/// Operator: ==, !=, <, >, <=, >=.
op: BinaryOp,
/// Right operand.
right: Box<Expression>,
},
/// Logical operation: &&, ||.
Logical {
/// Left operand.
left: Box<Expression>,
/// Operator: And, Or.
op: LogicalOp,
/// Right operand.
right: Box<Expression>,
},
/// Logical negation.
Not(Box<Expression>),
/// Function call.
FunctionCall {
/// Function name.
name: String,
/// Arguments.
args: Vec<Expression>,
},
/// Tuple of expressions.
Tuple(Vec<Expression>),
}
impl std::fmt::Display for Expression {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Boolean(b) => write!(f, "{}", b),
Self::Var(v) => write!(f, "{}", v),
Self::LayerVar { layer, var } => write!(f, "{}::{}", layer, var),
Self::PhaseQualifiedVar { phase, layer, var } => {
write!(f, "{}::{}::{}", phase, layer, var)
}
Self::PhaseConstraint { phase, constraint } => {
write!(f, "({} @ {})", constraint, phase)
}
Self::CrossPhaseRelation {
phase1,
expr1,
phase2,
expr2,
op,
} => {
write!(f, "({}[{}] {} {}[{}])", expr1, phase1, op, expr2, phase2)
}
Self::Int(i) => write!(f, "{}", i),
Self::BinaryOp { left, op, right } => {
write!(f, "({} {} {})", left, op, right)
}
Self::Logical { left, op, right } => {
write!(f, "({} {} {})", left, op, right)
}
Self::Not(e) => write!(f, "!({})", e),
Self::FunctionCall { name, args } => {
write!(f, "{}(", name)?;
for (i, arg) in args.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{}", arg)?;
}
write!(f, ")")
}
Self::Tuple(exprs) => {
write!(f, "(")?;
for (i, e) in exprs.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{}", e)?;
}
write!(f, ")")
}
}
}
}
/// Binary operators for expressions.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum BinaryOp {
/// Equality.
Eq,
/// Not equal.
Neq,
/// Less than.
Lt,
/// Greater than.
Gt,
/// Less than or equal.
Lte,
/// Greater than or equal.
Gte,
}
impl std::fmt::Display for BinaryOp {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Eq => write!(f, "=="),
Self::Neq => write!(f, "!="),
Self::Lt => write!(f, "<"),
Self::Gt => write!(f, ">"),
Self::Lte => write!(f, "<="),
Self::Gte => write!(f, ">="),
}
}
}
/// Logical operators.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum LogicalOp {
/// Logical AND.
And,
/// Logical OR.
Or,
}
impl std::fmt::Display for LogicalOp {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::And => write!(f, "&&"),
Self::Or => write!(f, "||"),
}
}
}
/// A state variable in a program.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StateVar {
/// Variable name.
pub name: String,
/// Data type (chain-specific).
pub type_name: String,
/// Whether it's mutable.
pub is_mutable: bool,
/// Visibility: "public", "private", "internal", etc.
pub visibility: Option<String>,
}
/// A function or entry point in a program.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FunctionModel {
/// Function name.
pub name: String,
/// Function signature/parameters.
pub parameters: Vec<String>,
/// Return type.
pub return_type: Option<String>,
/// State variables this function mutates.
pub mutates: BTreeSet<String>,
/// State variables this function reads.
pub reads: BTreeSet<String>,
/// Whether this is an entry point.
pub is_entry_point: bool,
/// Whether it's pure/view (doesn't mutate state).
pub is_pure: bool,
}
/// A complete program model extracted from source code.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProgramModel {
/// Program/contract/module name.
pub name: String,
/// State variables.
pub state_vars: BTreeMap<String, StateVar>,
/// Functions/entry points.
pub functions: BTreeMap<String, FunctionModel>,
/// Functions → Mutations mapping (deterministic).
pub mutation_graph: BTreeMap<String, BTreeSet<String>>,
/// Chains supported: "solana", "evm", "move".
pub chain: String,
/// Source file path.
pub source_path: String,
}
impl ProgramModel {
/// Create a new program model.
pub fn new(name: String, chain: String, source_path: String) -> Self {
Self {
name,
chain,
source_path,
state_vars: BTreeMap::new(),
functions: BTreeMap::new(),
mutation_graph: BTreeMap::new(),
}
}
/// Add a state variable to the model.
pub fn add_state_var(&mut self, var: StateVar) {
self.state_vars.insert(var.name.clone(), var);
}
/// Add a function to the model.
pub fn add_function(&mut self, func: FunctionModel) {
self.mutation_graph
.insert(func.name.clone(), func.mutates.clone());
self.functions.insert(func.name.clone(), func);
}
}
/// Output from code generation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GenerationOutput {
/// The generated code.
pub code: String,
/// Assertions injected.
pub assertions: Vec<String>,
/// Generated tests (if any).
pub tests: Option<String>,
/// Coverage percentage (0-100).
pub coverage_percent: u8,
}
/// Report from a simulation run.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SimulationReport {
/// Number of violations found.
pub violations: usize,
/// Violation traces.
pub traces: Vec<String>,
/// Coverage percentage.
pub coverage: f64,
/// Deterministic seed used.
pub seed: u64,
}