Stack Depth Violation
Detects stack and CPI depth limit violations in Solana programs.
Stack Depth Violation
Overview
The stack depth violation detector builds a call graph and identifies CPI chains that could exceed Solana’s maximum CPI depth of 4 levels. Programs with deep CPI chains will fail at runtime, and attackers can exploit near-limit chains to cause denial-of-service.
For remediation guidance, see Stack Depth Violation Remediation.
Why This Is an Issue
Solana enforces a maximum CPI depth of 4 levels. Program A calling Program B (depth 1) calling Program C (depth 2) and so on. If a call chain exceeds depth 4, the transaction fails. Programs that sit at depth 3 and make CPI calls leave no room for the called program to make its own CPI calls, which can cause unexpected failures in complex composable protocol interactions.
How to Resolve
Before (Vulnerable)
// Vulnerable: creates a deep CPI chain
pub fn process(ctx: Context<Process>) -> Result<()> {
// This is already called at CPI depth 2
invoke_program_b(ctx.accounts)?; // Depth 3
// Program B internally calls Program C -- Depth 4
// Program C tries CPI -- FAILS at depth 5
Ok(())
}
After (Fixed)
// Fixed: flatten CPI chain by calling programs directly
pub fn process(ctx: Context<Process>) -> Result<()> {
// Call each program at depth 1 from the top level
invoke_program_b(ctx.accounts)?; // Depth 1
invoke_program_c(ctx.accounts)?; // Depth 1
Ok(())
}
Example JSON Finding
{
"detector": "stack-depth-violation",
"severity": "high",
"confidence": 0.8,
"message": "CPI chain may exceed maximum depth of 4 levels",
"location": { "function": "process", "block": 1, "statement": 2 }
}
Detection Methodology
- CPI invocation collection: Identifies all CPI invocations within the function.
- Call graph construction: Builds a local call graph tracking CPI chains.
- Depth calculation: Computes maximum depth from each CPI location.
- Threshold comparison: Flags chains exceeding Solana’s MAX_CPI_DEPTH of 4.
Limitations
False positives: Static analysis cannot determine the runtime CPI depth at which a program is invoked. A program at depth 1 with a 3-level chain is safe, but the same program at depth 2 is not. False negatives: CPI chains through dynamically-determined program IDs cannot be fully resolved.
Related Detectors
- Compute Exhaustion — compute budget issues
- Multi-Hop CPI — dangerous multi-hop CPI patterns