Skip to content

[TASK] Optimize keccak256 calls using assembly #919

@alainncls

Description

@alainncls

Summary

The current use of keccak256 in Verax relies on abi.encode, which incurs additional gas costs due to memory allocation. Using inline assembly can optimize these calls and reduce gas consumption.

Objectives

  1. Research & benchmark

    • Compare gas costs between keccak256(abi.encode(...)) and an optimized version using inline assembly.
    • Provide concrete gas measurements to quantify the potential savings.
  2. Apply optimization (if confirmed)

    • Identify all instances of keccak256 calls in the codebase.
    • Replace them with an optimized inline assembly implementation where applicable.
    • Ensure correctness and maintainability of the code after optimization.

Impact

  • Reduced gas costs for hash computations.
  • Improved efficiency in attestations and other hash-dependent logic.

Example

contract TestHash {

  // 399 gas
  function expensive() external pure  {
    uint256 def =123;
    bytes32 abc;
    abc= keccak256(abi.encode(def));
  }
  
  // 229 gas
  function cheaper() external pure {
    uint256 def =123;
    bytes32 abc;
    assembly{
      let ptr:=mload(0x40)
      mstore(ptr,def)
      abc:=keccak256(ptr,0x20)
    }
  }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    Ready for development

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions