arkworks-rs / r1cs-std

R1CS constraints for bits, fields, and elliptic curves
https://www.arkworks.rs
Apache License 2.0
133 stars 58 forks source link

Avoid deeply nested `LinearCombination`s in `EvaluationsVar::interpolate_and_evaluate` #145

Closed winderica closed 1 week ago

winderica commented 5 months ago

Description

It is observed in https://github.com/privacy-scaling-explorations/sonobe/issues/80 that stack overflow occurs when calling EvaluationsVar::interpolate_and_evaluate for large evaluation domains (e.g., when $n > 11$).

I think this happens because in EvaluationsVar::lagrange_interpolate_with_constant_offset and EvaluationsVar::lagrange_interpolate_with_non_constant_offset, we are updating the final evaluation result in a for loop, and += in each iteration wraps the current result by a new layer of LinearCombination. This produces a deeply nested LinearCombination. When we get .value() of the evaluation result, internally ConstraintSystem::assigned_value is invoked to recursively flatten the LC. Unfortunately, the number of LC layers of the evaluation result is so large that the recursion depth exceeds the OS limit, resulting in a stack overflow.

This PR fixes the above bug by calling .sum() on the iterator of addends, since this method invokes ‎AllocatedFp::add_many, which produces a flat LC.


Before we can merge this PR, please make sure that all the following items have been checked off. If any of the checklist items are not applicable, please leave them but write a little note why.

arnaucube commented 1 week ago

Hi, is there anything missing for this PR to be merged? We are interested into it since we would like to evaluate with n=16. Also, are there any chances of including this fix into the next arkworks v0.5.0 release?