Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize montgomerySub() #235

Closed
IAvecilla opened this issue Apr 12, 2024 · 0 comments · Fixed by #253
Closed

Optimize montgomerySub() #235

IAvecilla opened this issue Apr 12, 2024 · 0 comments · Fixed by #253
Assignees

Comments

@IAvecilla
Copy link
Contributor

Context: EcPairing.yul#L314

Description: The implementation of the montgomerySub(a, b) fallbacks to montgomeryAdd(a, P-b). This however can be implemented more efficiently as:

  • compute difference a - b,
  • add back P if the difference overflows.

The change gives 4% gas cost reduction.

Recommendation: Change the implementation of montgomerySub() to:

diff --git a/precompiles/EcPairing.yul b/precompiles/EcPairing.yul
index f70813e..4e0c526 100644
--- a/precompiles/EcPairing.yul
+++ b/precompiles/EcPairing.yul
@@ -319,7 +319,10 @@ object "EcPairing" {
             /// @param subtrahend The subtrahend in Montgomery form.
             /// @return ret The result of the Montgomery addition.
             function montgomerySub(minuend, subtrahend) -ret {
-                ret := montgomeryAdd(minuend, sub(P(), subtrahend))
+                ret := sub(minuend, subtrahend)
+                if lt(minuend, subtrahend) {
+                    ret := add(ret, P())
+                }
             }

             /// @notice Computes the Montgomery multiplication using the Montgomery reduction algorithm (REDC).

zkSync:

Spearbit:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant