Field Overflow Remediation
How to prevent field overflow in ZK circuit arithmetic by adding range constraints on signals before operations.
Field Overflow Remediation
Overview
Related Detector: Field Overflow
Arithmetic in ZK circuits operates modulo the field prime. Overflow wraps silently, producing semantically incorrect results. The fix is to range-constrain inputs before arithmetic operations.
Recommended Fix
Before (Vulnerable)
signal input a; // Could be any 254-bit value
signal input b;
signal output product;
product <== a * b; // If a*b > p, result wraps modulo p
After (Fixed)
signal input a;
signal input b;
signal output product;
// Range-check: ensure a and b fit in 126 bits
component ra = Num2Bits(126);
ra.in <== a;
component rb = Num2Bits(126);
rb.in <== b;
product <== a * b; // 2^126 * 2^126 = 2^252 < p (safe)
Alternative Mitigations
For addition, ensure the sum stays within field bounds:
// For addition of n values, each at most k bits:
// Safe if n * 2^k < p, i.e., k + log2(n) < 254
component range = Num2Bits(64);
range.in <== value; // Each value fits in 64 bits
// Sum of up to 2^190 such values is safe
Common Mistakes
- Range-checking the result instead of the inputs: The overflow has already occurred; checking the product’s range does not prevent wrapping.
- Using insufficient bit width:
Num2Bits(128)allows values up to 2^128, but multiplying two such values gives 2^256 which exceeds the field prime.