sentri-core 0.3.0

Sentri: Core types and utilities for the Sentri multi-chain smart contract security analyzer.
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
//! Deterministic invariant expression evaluation engine.
//!
//! Supports both compile-time static evaluation and runtime evaluation.
//! All operations use checked arithmetic with explicit overflow handling.
//! No floating point. No randomness. No external I/O.

use crate::model::Expression;
use crate::types::Type;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

/// A runtime value with type information.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Value {
    /// Boolean value.
    Bool(bool),
    /// 64-bit unsigned integer.
    U64(u64),
    /// 128-bit unsigned integer.
    U128(u128),
    /// 64-bit signed integer.
    I64(i64),
    /// Address (hex string representation).
    Address(String),
}

impl Value {
    /// Get the type of this value.
    pub fn get_type(&self) -> Type {
        match self {
            Self::Bool(_) => Type::Bool,
            Self::U64(_) => Type::U64,
            Self::U128(_) => Type::U128,
            Self::I64(_) => Type::I64,
            Self::Address(_) => Type::Address,
        }
    }

    /// Convert to a boolean for conditional evaluation.
    pub fn to_bool(&self) -> Result<bool, EvaluationError> {
        match self {
            Self::Bool(b) => Ok(*b),
            Self::U64(n) => Ok(*n != 0),
            Self::U128(n) => Ok(*n != 0),
            Self::I64(n) => Ok(*n != 0),
            Self::Address(a) => Ok(!a.is_empty()),
        }
    }

    /// Safe integer conversion.
    #[allow(dead_code)]
    fn as_u64(&self) -> Result<u64, EvaluationError> {
        match self {
            Self::U64(n) => Ok(*n),
            Self::U128(n) => {
                if *n <= u64::MAX as u128 {
                    Ok(*n as u64)
                } else {
                    Err(EvaluationError::ConversionOverflow)
                }
            }
            Self::I64(n) => {
                if *n >= 0 {
                    Ok(*n as u64)
                } else {
                    Err(EvaluationError::ConversionOverflow)
                }
            }
            _ => Err(EvaluationError::TypeError),
        }
    }

    #[allow(dead_code)]
    fn as_i64(&self) -> Result<i64, EvaluationError> {
        match self {
            Self::I64(n) => Ok(*n),
            Self::U64(n) => {
                if *n <= i64::MAX as u64 {
                    Ok(*n as i64)
                } else {
                    Err(EvaluationError::ConversionOverflow)
                }
            }
            _ => Err(EvaluationError::TypeError),
        }
    }
}

impl std::fmt::Display for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Bool(b) => write!(f, "{}", b),
            Self::U64(n) => write!(f, "{}", n),
            Self::U128(n) => write!(f, "{}", n),
            Self::I64(n) => write!(f, "{}", n),
            Self::Address(a) => write!(f, "{}", a),
        }
    }
}

/// Evaluation errors.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EvaluationError {
    /// Arithmetic overflow.
    Overflow,
    /// Arithmetic underflow.
    Underflow,
    /// Type error during evaluation.
    TypeError,
    /// Division by zero.
    DivisionByZero,
    /// Undefined variable.
    UndefinedVariable(String),
    /// Undefined function.
    UndefinedFunction(String),
    /// Function argument error.
    InvalidArgument(String),
    /// Conversion overflow.
    ConversionOverflow,
    /// Custom error.
    Custom(String),
}

impl std::fmt::Display for EvaluationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Overflow => write!(f, "arithmetic overflow"),
            Self::Underflow => write!(f, "arithmetic underflow"),
            Self::TypeError => write!(f, "type error"),
            Self::DivisionByZero => write!(f, "division by zero"),
            Self::UndefinedVariable(name) => write!(f, "undefined variable '{}'", name),
            Self::UndefinedFunction(name) => write!(f, "undefined function '{}'", name),
            Self::InvalidArgument(msg) => write!(f, "invalid argument: {}", msg),
            Self::ConversionOverflow => write!(f, "conversion overflow"),
            Self::Custom(msg) => write!(f, "{}", msg),
        }
    }
}

/// Result type for evaluation operations.
pub type EvalResult<T> = Result<T, EvaluationError>;

/// Type alias for function implementations.
pub type EvalFunction = fn(&[Value]) -> EvalResult<Value>;

/// Execution context for invariant evaluation.
pub struct ExecutionContext {
    /// Current state variable values.
    pub state_vars: BTreeMap<String, Value>,
    /// Function implementations.
    pub functions: BTreeMap<String, EvalFunction>,
}

impl ExecutionContext {
    /// Create a new empty context.
    pub fn new() -> Self {
        Self {
            state_vars: BTreeMap::new(),
            functions: BTreeMap::new(),
        }
    }

    /// Set a state variable value.
    pub fn set_state(&mut self, name: String, value: Value) {
        self.state_vars.insert(name, value);
    }

    /// Register a built-in function.
    pub fn register_function(&mut self, name: String, func: fn(&[Value]) -> EvalResult<Value>) {
        self.functions.insert(name, func);
    }
}

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

/// Deterministic invariant expression evaluator.
pub struct Evaluator {
    context: ExecutionContext,
}

impl Evaluator {
    /// Create a new evaluator with an execution context.
    pub fn new(context: ExecutionContext) -> Self {
        Self { context }
    }

    /// Evaluate an expression against the current context.
    pub fn evaluate(&self, expr: &Expression) -> EvalResult<Value> {
        match expr {
            Expression::Boolean(b) => Ok(Value::Bool(*b)),

            Expression::Int(val) => {
                // Determine appropriate type based on value
                if *val < 0 {
                    Ok(Value::I64(*val as i64))
                } else if *val <= u64::MAX as i128 {
                    Ok(Value::U64(*val as u64))
                } else {
                    Ok(Value::U128(*val as u128))
                }
            }

            Expression::Var(name) => self
                .context
                .state_vars
                .get(name)
                .cloned()
                .ok_or_else(|| EvaluationError::UndefinedVariable(name.clone())),

            Expression::LayerVar { layer, var } => {
                // Layer-qualified variables: look up by full qualified name
                let qualified_name = format!("{}::{}", layer, var);
                self.context
                    .state_vars
                    .get(&qualified_name)
                    .cloned()
                    .or_else(|| self.context.state_vars.get(var).cloned())
                    .ok_or(EvaluationError::UndefinedVariable(qualified_name))
            }

            Expression::PhaseQualifiedVar { phase, layer, var } => {
                // Phase-qualified variables: phase::layer::var
                // For now, evaluate as layer::var (full phase support requires AA context)
                let qualified_name = format!("{}::{}::{}", phase, layer, var);
                self.context
                    .state_vars
                    .get(&qualified_name)
                    .cloned()
                    .or_else(|| {
                        let layer_var = format!("{}::{}", layer, var);
                        self.context.state_vars.get(&layer_var).cloned()
                    })
                    .or_else(|| self.context.state_vars.get(var).cloned())
                    .ok_or(EvaluationError::UndefinedVariable(qualified_name))
            }

            Expression::PhaseConstraint {
                phase: _,
                constraint,
            } => {
                // Evaluate the constraint expression
                // The phase is metadata for analysis; actual phase checking requires AA context
                self.evaluate(constraint)
            }

            Expression::CrossPhaseRelation {
                phase1: _,
                expr1,
                phase2: _,
                expr2,
                op,
            } => {
                // Evaluate cross-phase relation: expr1 op expr2
                // Phase context requires AA context for snapshot lookup
                let left_val = self.evaluate(expr1)?;
                let right_val = self.evaluate(expr2)?;
                self.eval_binary_op(&left_val, op, &right_val)
            }

            Expression::BinaryOp { left, op, right } => {
                let left_val = self.evaluate(left)?;
                let right_val = self.evaluate(right)?;
                self.eval_binary_op(&left_val, op, &right_val)
            }

            Expression::Logical { left, op, right } => {
                use crate::model::LogicalOp;

                let left_val = self.evaluate(left)?.to_bool()?;

                // Short-circuit evaluation
                match op {
                    LogicalOp::And => {
                        if !left_val {
                            return Ok(Value::Bool(false));
                        }
                        let right_val = self.evaluate(right)?.to_bool()?;
                        Ok(Value::Bool(right_val))
                    }
                    LogicalOp::Or => {
                        if left_val {
                            return Ok(Value::Bool(true));
                        }
                        let right_val = self.evaluate(right)?.to_bool()?;
                        Ok(Value::Bool(right_val))
                    }
                }
            }

            Expression::Not(expr) => {
                let val = self.evaluate(expr)?.to_bool()?;
                Ok(Value::Bool(!val))
            }

            Expression::FunctionCall { name, args } => {
                let func = self
                    .context
                    .functions
                    .get(name)
                    .ok_or_else(|| EvaluationError::UndefinedFunction(name.clone()))?;

                let arg_vals: EvalResult<Vec<Value>> =
                    args.iter().map(|arg| self.evaluate(arg)).collect();

                func(&arg_vals?)
            }

            Expression::Tuple(exprs) => {
                // For now, evaluate first expression in tuple
                if exprs.is_empty() {
                    Ok(Value::Bool(true))
                } else {
                    self.evaluate(&exprs[0])
                }
            }
        }
    }

    /// Evaluate a binary operation with checked arithmetic.
    fn eval_binary_op(
        &self,
        left: &Value,
        op: &crate::model::BinaryOp,
        right: &Value,
    ) -> EvalResult<Value> {
        use crate::model::BinaryOp;

        match op {
            BinaryOp::Eq => Ok(Value::Bool(left == right)),

            BinaryOp::Neq => Ok(Value::Bool(left != right)),

            BinaryOp::Lt => match (left, right) {
                (Value::U64(l), Value::U64(r)) => Ok(Value::Bool(l < r)),
                (Value::I64(l), Value::I64(r)) => Ok(Value::Bool(l < r)),
                (Value::U128(l), Value::U128(r)) => Ok(Value::Bool(l < r)),
                _ => Err(EvaluationError::TypeError),
            },

            BinaryOp::Gt => match (left, right) {
                (Value::U64(l), Value::U64(r)) => Ok(Value::Bool(l > r)),
                (Value::I64(l), Value::I64(r)) => Ok(Value::Bool(l > r)),
                (Value::U128(l), Value::U128(r)) => Ok(Value::Bool(l > r)),
                _ => Err(EvaluationError::TypeError),
            },

            BinaryOp::Lte => match (left, right) {
                (Value::U64(l), Value::U64(r)) => Ok(Value::Bool(l <= r)),
                (Value::I64(l), Value::I64(r)) => Ok(Value::Bool(l <= r)),
                (Value::U128(l), Value::U128(r)) => Ok(Value::Bool(l <= r)),
                _ => Err(EvaluationError::TypeError),
            },

            BinaryOp::Gte => match (left, right) {
                (Value::U64(l), Value::U64(r)) => Ok(Value::Bool(l >= r)),
                (Value::I64(l), Value::I64(r)) => Ok(Value::Bool(l >= r)),
                (Value::U128(l), Value::U128(r)) => Ok(Value::Bool(l >= r)),
                _ => Err(EvaluationError::TypeError),
            },
        }
    }
}

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

    #[test]
    fn test_value_type_detection() {
        assert_eq!(Value::Bool(true).get_type(), Type::Bool);
        assert_eq!(Value::U64(42).get_type(), Type::U64);
        assert_eq!(Value::I64(-42).get_type(), Type::I64);
    }

    #[test]
    fn test_simple_evaluation() {
        let ctx = ExecutionContext::new();
        let evaluator = Evaluator::new(ctx);

        let expr = Expression::Boolean(true);
        let result = evaluator.evaluate(&expr);
        assert_eq!(result, Ok(Value::Bool(true)));
    }

    #[test]
    fn test_state_variable_evaluation() {
        let mut ctx = ExecutionContext::new();
        ctx.set_state("balance".to_string(), Value::U64(100));

        let evaluator = Evaluator::new(ctx);
        let expr = Expression::Var("balance".to_string());

        let result = evaluator.evaluate(&expr);
        assert_eq!(result, Ok(Value::U64(100)));
    }

    #[test]
    fn test_comparison_evaluation() {
        let ctx = ExecutionContext::new();
        let evaluator = Evaluator::new(ctx);

        let expr = Expression::BinaryOp {
            left: Box::new(Expression::Int(10)),
            op: crate::model::BinaryOp::Lt,
            right: Box::new(Expression::Int(20)),
        };

        let result = evaluator.evaluate(&expr);
        assert_eq!(result, Ok(Value::Bool(true)));
    }

    #[test]
    fn test_logical_short_circuit() {
        let ctx = ExecutionContext::new();
        let evaluator = Evaluator::new(ctx);

        // false && (undefined_var) should not evaluate the right side
        let expr = Expression::Logical {
            left: Box::new(Expression::Boolean(false)),
            op: crate::model::LogicalOp::And,
            right: Box::new(Expression::Var("undefined".to_string())),
        };

        let result = evaluator.evaluate(&expr);
        assert_eq!(result, Ok(Value::Bool(false)));
    }
}