Skip to content

Instantly share code, notes, and snippets.

@HarryR
Created November 26, 2018 20:35
Show Gist options
  • Save HarryR/d69ad7cab008ed53a5eca4fdc08ffcc4 to your computer and use it in GitHub Desktop.
Save HarryR/d69ad7cab008ed53a5eca4fdc08ffcc4 to your computer and use it in GitHub Desktop.
Compares the cost of mulmod versus the cost of modexp
pragma solidity ^0.5.0;
contract CompareMulExp
{
// altBN curve order
uint256 constant CURVE_ORDER = 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001;
/**
* @dev Computes (base ^ exponent) % modulus over big numbers.
*/
function modexp(uint256 base, uint256 exponent, uint256 modulus)
internal view returns (uint256)
{
bool success;
uint256[6] memory input;
uint256[1] memory output;
input[0] = 32;
input[1] = 32;
input[2] = 32;
input[3] = base;
input[4] = exponent;
input[5] = modulus;
assembly {
success := staticcall(sub(gas, 2000), 5, input, 0xc0, output, 0x20)
}
require( success );
return output[0];
}
function TestMulmod( uint256 round_count )
public pure returns(uint256)
{
uint256 t = uint256(keccak256(abi.encodePacked(round_count)));
uint256 j = t;
for( uint256 i = 0; i < round_count; i++ )
{
t = mulmod(t, j, CURVE_ORDER); // t^i
}
return t;
}
function TestModexp( uint256 round_count )
public view returns(uint256)
{
uint256 t = uint256(keccak256(abi.encodePacked(round_count)));
for( uint256 i = 0; i < round_count; i++ )
{
t = modexp(t, CURVE_ORDER - 2, CURVE_ORDER); // 1/t
}
return t;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment