truent_core/model.rs
1//! Core domain models for invariant analysis.
2
3use serde::{Deserialize, Serialize};
4use std::collections::{BTreeMap, BTreeSet};
5
6/// A compiled invariant expression with metadata.
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct Invariant {
9 /// Unique identifier for the invariant.
10 pub name: String,
11
12 /// Human-readable description.
13 pub description: Option<String>,
14
15 /// The invariant expression in IR form.
16 pub expression: Expression,
17
18 /// Severity level: "critical", "high", "medium", "low".
19 pub severity: String,
20
21 /// Category: "core", "defi", "bridge", "governance", "account-abstraction", etc.
22 pub category: String,
23
24 /// Whether this invariant should always hold.
25 pub is_always_true: bool,
26
27 /// Layer scopes for cross-layer analysis (e.g., ["bundler", "account", "paymaster"]).
28 /// If empty, applies to all layers.
29 pub layers: Vec<String>,
30
31 /// Execution phases (e.g., ["validation", "execution", "settlement"]).
32 /// For AA invariants that must hold at specific phases. Empty means all phases.
33 pub phases: Vec<String>,
34}
35
36/// An expression tree representing invariant conditions.
37#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
38pub enum Expression {
39 /// Boolean literal.
40 Boolean(bool),
41
42 /// Variable reference.
43 Var(String),
44
45 /// Layer-qualified variable reference (e.g., bundler::nonce).
46 LayerVar {
47 /// Layer name (bundler, account, paymaster, protocol, entrypoint).
48 layer: String,
49 /// Variable name within the layer.
50 var: String,
51 },
52
53 /// Phase-qualified variable reference (e.g., validation::account::balance).
54 /// Checks state at a specific execution phase (validation, execution, settlement).
55 PhaseQualifiedVar {
56 /// Execution phase: "validation", "execution", or "settlement".
57 phase: String,
58 /// Layer name within that phase.
59 layer: String,
60 /// Variable name within the layer.
61 var: String,
62 },
63
64 /// Phase constraint: ensures a condition holds during a specific phase.
65 /// Example: ensure `account::balance >= min_required` during validation phase.
66 PhaseConstraint {
67 /// Phase to enforce the constraint in.
68 phase: String,
69 /// The constraint expression to hold in this phase.
70 constraint: Box<Expression>,
71 },
72
73 /// Cross-phase relation: relates variable values across two phases.
74 /// Example: `validation::account::balance >= execution::account::balance`
75 /// used to track state changes across phases.
76 CrossPhaseRelation {
77 /// First phase.
78 phase1: String,
79 /// First phase expression.
80 expr1: Box<Expression>,
81 /// Second phase.
82 phase2: String,
83 /// Second phase expression.
84 expr2: Box<Expression>,
85 /// Relation operator.
86 op: BinaryOp,
87 },
88
89 /// Integer constant.
90 Int(i128),
91
92 /// Comparison: left op right.
93 BinaryOp {
94 /// Left operand.
95 left: Box<Expression>,
96 /// Operator: ==, !=, <, >, <=, >=.
97 op: BinaryOp,
98 /// Right operand.
99 right: Box<Expression>,
100 },
101
102 /// Arithmetic: left op right, yielding a number rather than a boolean.
103 ///
104 /// Conservation properties — `sum(balances) == totalSupply`,
105 /// `reserve_a * reserve_b >= k` — are the whole point of an invariant
106 /// language, and none of them are expressible without this.
107 Arithmetic {
108 /// Left operand.
109 left: Box<Expression>,
110 /// Operator: +, -, *, /.
111 op: ArithOp,
112 /// Right operand.
113 right: Box<Expression>,
114 },
115
116 /// Logical operation: &&, ||.
117 Logical {
118 /// Left operand.
119 left: Box<Expression>,
120 /// Operator: And, Or.
121 op: LogicalOp,
122 /// Right operand.
123 right: Box<Expression>,
124 },
125
126 /// Logical negation.
127 Not(Box<Expression>),
128
129 /// Function call.
130 FunctionCall {
131 /// Function name.
132 name: String,
133 /// Arguments.
134 args: Vec<Expression>,
135 },
136
137 /// Tuple of expressions.
138 Tuple(Vec<Expression>),
139}
140
141impl std::fmt::Display for Expression {
142 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143 match self {
144 Self::Boolean(b) => write!(f, "{}", b),
145 Self::Var(v) => write!(f, "{}", v),
146 Self::LayerVar { layer, var } => write!(f, "{}::{}", layer, var),
147 Self::PhaseQualifiedVar { phase, layer, var } => {
148 write!(f, "{}::{}::{}", phase, layer, var)
149 }
150 Self::PhaseConstraint { phase, constraint } => {
151 write!(f, "({} @ {})", constraint, phase)
152 }
153 Self::CrossPhaseRelation {
154 phase1,
155 expr1,
156 phase2,
157 expr2,
158 op,
159 } => {
160 write!(f, "({}[{}] {} {}[{}])", expr1, phase1, op, expr2, phase2)
161 }
162 Self::Int(i) => write!(f, "{}", i),
163 Self::BinaryOp { left, op, right } => {
164 write!(f, "({} {} {})", left, op, right)
165 }
166 Self::Arithmetic { left, op, right } => {
167 write!(f, "({} {} {})", left, op, right)
168 }
169 Self::Logical { left, op, right } => {
170 write!(f, "({} {} {})", left, op, right)
171 }
172 Self::Not(e) => write!(f, "!({})", e),
173 Self::FunctionCall { name, args } => {
174 write!(f, "{}(", name)?;
175 for (i, arg) in args.iter().enumerate() {
176 if i > 0 {
177 write!(f, ", ")?;
178 }
179 write!(f, "{}", arg)?;
180 }
181 write!(f, ")")
182 }
183 Self::Tuple(exprs) => {
184 write!(f, "(")?;
185 for (i, e) in exprs.iter().enumerate() {
186 if i > 0 {
187 write!(f, ", ")?;
188 }
189 write!(f, "{}", e)?;
190 }
191 write!(f, ")")
192 }
193 }
194 }
195}
196
197/// Arithmetic operators for numeric expressions.
198#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
199pub enum ArithOp {
200 /// Addition.
201 Add,
202 /// Subtraction.
203 Sub,
204 /// Multiplication.
205 Mul,
206 /// Division (integer, truncating — matches EVM semantics).
207 Div,
208}
209
210impl std::fmt::Display for ArithOp {
211 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
212 match self {
213 Self::Add => write!(f, "+"),
214 Self::Sub => write!(f, "-"),
215 Self::Mul => write!(f, "*"),
216 Self::Div => write!(f, "/"),
217 }
218 }
219}
220
221/// Binary (comparison) operators for expressions.
222#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
223pub enum BinaryOp {
224 /// Equality.
225 Eq,
226 /// Not equal.
227 Neq,
228 /// Less than.
229 Lt,
230 /// Greater than.
231 Gt,
232 /// Less than or equal.
233 Lte,
234 /// Greater than or equal.
235 Gte,
236}
237
238impl std::fmt::Display for BinaryOp {
239 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
240 match self {
241 Self::Eq => write!(f, "=="),
242 Self::Neq => write!(f, "!="),
243 Self::Lt => write!(f, "<"),
244 Self::Gt => write!(f, ">"),
245 Self::Lte => write!(f, "<="),
246 Self::Gte => write!(f, ">="),
247 }
248 }
249}
250
251/// Logical operators.
252#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
253pub enum LogicalOp {
254 /// Logical AND.
255 And,
256 /// Logical OR.
257 Or,
258}
259
260impl std::fmt::Display for LogicalOp {
261 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
262 match self {
263 Self::And => write!(f, "&&"),
264 Self::Or => write!(f, "||"),
265 }
266 }
267}
268
269/// A state variable in a program.
270#[derive(Debug, Clone, Serialize, Deserialize)]
271pub struct StateVar {
272 /// Variable name.
273 pub name: String,
274
275 /// Data type (chain-specific).
276 pub type_name: String,
277
278 /// Whether it's mutable.
279 pub is_mutable: bool,
280
281 /// Visibility: "public", "private", "internal", etc.
282 pub visibility: Option<String>,
283}
284
285/// A function or entry point in a program.
286#[derive(Debug, Clone, Serialize, Deserialize)]
287pub struct FunctionModel {
288 /// Function name.
289 pub name: String,
290
291 /// Function signature/parameters.
292 pub parameters: Vec<String>,
293
294 /// Return type.
295 pub return_type: Option<String>,
296
297 /// State variables this function mutates.
298 pub mutates: BTreeSet<String>,
299
300 /// State variables this function reads.
301 pub reads: BTreeSet<String>,
302
303 /// Whether this is an entry point.
304 pub is_entry_point: bool,
305
306 /// Whether it's pure/view (doesn't mutate state).
307 pub is_pure: bool,
308}
309
310/// A complete program model extracted from source code.
311#[derive(Debug, Clone, Serialize, Deserialize)]
312pub struct ProgramModel {
313 /// Program/contract/module name.
314 pub name: String,
315
316 /// State variables.
317 pub state_vars: BTreeMap<String, StateVar>,
318
319 /// Functions/entry points.
320 pub functions: BTreeMap<String, FunctionModel>,
321
322 /// Functions → Mutations mapping (deterministic).
323 pub mutation_graph: BTreeMap<String, BTreeSet<String>>,
324
325 /// Chains supported: "solana", "evm", "move".
326 pub chain: String,
327
328 /// Source file path.
329 pub source_path: String,
330}
331
332impl ProgramModel {
333 /// Create a new program model.
334 pub fn new(name: String, chain: String, source_path: String) -> Self {
335 Self {
336 name,
337 chain,
338 source_path,
339 state_vars: BTreeMap::new(),
340 functions: BTreeMap::new(),
341 mutation_graph: BTreeMap::new(),
342 }
343 }
344
345 /// Add a state variable to the model.
346 pub fn add_state_var(&mut self, var: StateVar) {
347 self.state_vars.insert(var.name.clone(), var);
348 }
349
350 /// Add a function to the model.
351 pub fn add_function(&mut self, func: FunctionModel) {
352 self.mutation_graph
353 .insert(func.name.clone(), func.mutates.clone());
354 self.functions.insert(func.name.clone(), func);
355 }
356}
357
358/// Output from code generation.
359#[derive(Debug, Clone, Serialize, Deserialize)]
360pub struct GenerationOutput {
361 /// The generated code.
362 pub code: String,
363
364 /// Assertions injected.
365 pub assertions: Vec<String>,
366
367 /// Generated tests (if any).
368 pub tests: Option<String>,
369
370 /// Coverage percentage (0-100).
371 pub coverage_percent: u8,
372}
373
374/// Report from a simulation run.
375#[derive(Debug, Clone, Serialize, Deserialize)]
376pub struct SimulationReport {
377 /// Number of violations found.
378 pub violations: usize,
379
380 /// Violation traces.
381 pub traces: Vec<String>,
382
383 /// Coverage percentage.
384 pub coverage: f64,
385
386 /// Deterministic seed used.
387 pub seed: u64,
388}