rdubois-crypto / FreshCryptoLib

Cryptographic Primitives for Blockchain Systems (solidity, cairo, C and rust)
MIT License
121 stars 22 forks source link

Reduced FCL_Elliptic_ZZ.ecdsa_verify gas cost without `switch` ( -378 gas ) #22

Closed jayden-sudo closed 9 months ago

jayden-sudo commented 9 months ago

With the code equivalent, executing FCL_Elliptic_ZZ.ecdsa_verify reduced gas cost by 2600 gas:

Gas
Before 212970 gas
After 212592 gas

Gas Optimization Records for ecdsa_verify:

  1. Changed from calling ModExp to staticcall ModExp, reducing the number of parameters.

    1. The function was also changed to view.
  2. Replaced uint256[6] memory pointer with pointer := mload(0x40), reducing calls like MSTORE(0x40).

  3. Performed assembly optimizations.

    1. 
      // before
      eq(x, 0)
      // after
      iszero(x) ```
  4. Calldata cache, avoid frequent call of calldataload

    1. 
      function f(uint256[2] calldata rs) returns (bool success){ 
      // before 
      if (rs[0] == 0 || rs[0] >= n || rs[1] == 0 || rs[1] >= n){ return false; } 
      // after 
      uint256 r = rs[0]; 
      uint256 s = rs[1]; 
      
      } ```