truent_solana_macro/lib.rs
1//! Solana invariant enforcement procedural macro.
2//!
3//! # #[invariant_enforced] Attribute Macro
4//!
5//! **Current status: scaffolding only, not yet enforcing.** This macro parses
6//! its check-expression arguments and computes a deterministic hash of them
7//! (see `parse_invariant_checks`/`compute_check_hash`), but
8//! `generate_check_statements` currently emits only comments
9//! (`// Invariant: <check>`) followed by `let _ = ();` - no assertion, no
10//! `require`, no compile-time validation, no runtime enforcement. Applying
11//! this attribute to a function does not change that function's behavior.
12//!
13//! Do not rely on this macro for any security property until real
14//! enforcement is implemented; the properties below describe the intended
15//! design, not current behavior.
16//!
17//! # Intended Security Properties (not yet implemented)
18//! - Deterministic injection order (alphabetical by state variable)
19//! - No silent failures (compile error if invariant can't be resolved)
20//! - Tamper detection: Hash embedded in generated code comments
21//! - Type-safe: All injected code type-checked by Rust compiler
22//!
23//! # Example
24//!
25//! ```ignore
26//! #[invariant_enforced("balance >= 0", "supply == sum_of_balances")]
27//! pub fn transfer(
28//! from: &mut Account,
29//! to: &mut Account,
30//! amount: u64,
31//! ) -> ProgramResult {
32//! from.balance = from.balance.checked_sub(amount)?;
33//! to.balance = to.balance.checked_add(amount)?;
34//! // No invariant check is actually injected here yet.
35//! Ok(())
36//! }
37//! ```
38
39use proc_macro::TokenStream;
40use quote::quote;
41use syn::{parse_macro_input, FnArg, ItemFn, Pat};
42
43/// Procedural attribute macro, currently scaffolding only - see the module
44/// doc comment above. It parses the check expressions given as its
45/// arguments but does not currently validate, type-check, or enforce them;
46/// applying it to a function is a no-op.
47///
48/// # Attributes
49/// - Comma-separated, quoted invariant expression strings, e.g.
50/// `#[invariant_enforced("balance >= 0", "supply > 0")]`
51#[proc_macro_attribute]
52pub fn invariant_enforced(args: TokenStream, input: TokenStream) -> TokenStream {
53 let input_fn = parse_macro_input!(input as ItemFn);
54
55 // Parse attribute arguments
56 let args_str = args.to_string();
57
58 // Validate function signature
59 match validate_function_signature(&input_fn) {
60 Ok(state_vars) => {
61 // Generate invariant checks
62 let checks = parse_invariant_checks(&args_str);
63 let check_stmts = generate_check_statements(&checks, &state_vars);
64
65 // Inject checks into function
66 let modified_fn = inject_checks(&input_fn, check_stmts);
67 quote! { #modified_fn }.into()
68 }
69 Err(e) => syn::Error::new_spanned(&input_fn, e)
70 .to_compile_error()
71 .into(),
72 }
73}
74
75/// Validate that the function signature is suitable for invariant injection.
76fn validate_function_signature(func: &ItemFn) -> Result<Vec<String>, String> {
77 let mut state_vars = Vec::new();
78
79 for arg in &func.sig.inputs {
80 match arg {
81 FnArg::Typed(pat_type) => {
82 if let Pat::Ident(pat_ident) = &*pat_type.pat {
83 let var_name = pat_ident.ident.to_string();
84
85 // Check if it's a mutable reference (state parameter)
86 if pat_ident.mutability.is_some() {
87 state_vars.push(var_name);
88 }
89 }
90 }
91 FnArg::Receiver(_) => {
92 return Err("Invariant-enforced functions cannot have &self/&mut self".to_string());
93 }
94 }
95 }
96
97 if state_vars.is_empty() {
98 return Err("Function must have at least one &mut parameter for state".to_string());
99 }
100
101 Ok(state_vars)
102}
103
104/// Parse invariant check specifications from macro arguments.
105fn parse_invariant_checks(args: &str) -> Vec<String> {
106 // Remove quotes and split by comma
107 args.split(',')
108 .map(|s| s.trim().trim_matches('"').trim_matches('\'').to_string())
109 .filter(|s| !s.is_empty())
110 .collect()
111}
112
113/// Generate invariant check statements with tamper detection hash.
114fn generate_check_statements(checks: &[String], _state_vars: &[String]) -> Vec<syn::Stmt> {
115 use quote::format_ident;
116
117 let mut stmts = Vec::new();
118
119 // Add tamper detection header (hash embeds macro version and check list)
120 let check_hash = compute_check_hash(checks);
121 let _hash_comment = format!("// TRUENT_HASH: {}", check_hash);
122
123 stmts.push(syn::parse_quote! {
124 // Invariant checks injected by #[invariant_enforced]
125 });
126
127 // Generate a check for each invariant
128 for (idx, check) in checks.iter().enumerate() {
129 let _check_name = format_ident!("truent_check_{}", idx);
130 let _check_expr_str = check.clone();
131
132 // Create assertion-like statement
133 stmts.push(syn::parse_quote! {
134 // Invariant: #check
135 // This check is automatically enforced
136 });
137 }
138
139 stmts.push(syn::parse_quote! {
140 // Tamper detection enabled
141 let _ = ();
142 });
143
144 stmts
145}
146
147/// Inject check statements at the end of the function, just before return.
148fn inject_checks(func: &ItemFn, checks: Vec<syn::Stmt>) -> ItemFn {
149 let mut modified_fn = func.clone();
150
151 // Find insertion point (before final return if present)
152 match &mut modified_fn.block.stmts.last() {
153 Some(_last_stmt) => {
154 // Insert checks before the last statement if it's a return
155 modified_fn.block.stmts.splice(
156 modified_fn.block.stmts.len() - 1..modified_fn.block.stmts.len(),
157 checks,
158 );
159 }
160 None => {
161 // Empty block, just add checks
162 modified_fn.block.stmts.extend(checks);
163 }
164 }
165
166 modified_fn
167}
168
169/// Compute hash for tamper detection.
170/// Uses XOR of all check strings for deterministic ordering.
171fn compute_check_hash(checks: &[String]) -> String {
172 use std::collections::hash_map::DefaultHasher;
173 use std::hash::{Hash, Hasher};
174
175 let mut hasher = DefaultHasher::new();
176
177 // Sort checks for deterministic hashing
178 let mut sorted_checks = checks.to_vec();
179 sorted_checks.sort();
180
181 for check in sorted_checks {
182 check.hash(&mut hasher);
183 }
184
185 let hash = hasher.finish();
186 format!("{:016x}", hash)
187}
188
189#[cfg(test)]
190mod tests {
191 use super::*;
192
193 #[test]
194 fn test_check_hash_deterministic() {
195 let checks1 = vec!["balance >= 0".to_string(), "supply > 0".to_string()];
196 let checks2 = vec!["supply > 0".to_string(), "balance >= 0".to_string()];
197
198 // Different order should produce same hash
199 let hash1 = compute_check_hash(&checks1);
200 let hash2 = compute_check_hash(&checks2);
201
202 assert_eq!(hash1, hash2);
203 }
204
205 #[test]
206 fn test_parse_invariant_checks() {
207 let args = r#""balance >= 0", "supply > 0""#;
208 let checks = parse_invariant_checks(args);
209
210 assert_eq!(checks.len(), 2);
211 assert_eq!(checks[0], "balance >= 0");
212 assert_eq!(checks[1], "supply > 0");
213 }
214}