HarryR / ethsnarks

A toolkit for viable zk-SNARKS on Ethereum, Web, Mobile and Desktop
GNU Lesser General Public License v3.0
240 stars 57 forks source link

Reduce Gas cost and number of constraints for MiMC #144

Closed HarryR closed 4 years ago

HarryR commented 4 years ago

This introduces two variants of MiMC (one additional):

Both are bijective over the field, e7 requires 91 rounds, e5 requires 110 rounds (for the degree of the polynomial to exceed the order of the field, to prevent interpolation at any cost).

It also introduces a plain EVM bytecode version of the MiMC permutation, which is compatible with existing implementations, however it should use much less Gas.

The overall aim for this pull request is to reduce the on-chain and in-circuit costs of applications using MiMC, either as a hash function or as a cipher.

This also introduces a change to Truffle test reporting which displays the gas used by each Solidity test, so it's easier to keep an eye on gas cost.

Remaining:

HarryR commented 4 years ago

I'm unsure why run_test_sha256_many is failing for Linux Travis-CI build, as the branch works locally on OSX and Linux.

I introduced slight changes to sha256_many, due to adding constraints during input padding, see: https://github.com/HarryR/ethsnarks/pull/144/files#diff-4d3039dff574b788948119de402ca8d9

Edit: this was due to me building in Release mode locally, however Travis is building in Debug mode where if a constraint has no annotation an abort() will trigger.

HarryR commented 4 years ago
Compiling your contracts...
===========================
> Compiling ./test/TestMiMC.sol
> Artifacts written to /var/folders/3p/gt6d7chd7sb_hhbdwlx_z5wh0000gp/T/test-119630-71358-1roy1z5.utha
> Compiled successfully using:
   - solc: 0.5.8+commit.23d335f2.Emscripten.clang

Error: Error: Error
    at Object.run (<insert useless stacktrace here>)
    at process._tickCallback (internal/process/next_tick.js:68:7)

Yes, Truffle, Error: Error. I think you licked a bit too much lead paint there. Whatever TF they were smoking when they decided this was a good idea, a lobotomisation would probably be more fun and less permanently damaging.

HarryR commented 4 years ago

This reduces the on-chain deposit cost for ethsnarks-miximus from 1,886,206 to 1,246,306, a ~640k gas reduction, this is for a tree with 29 levels, so saving about 22k per-level...

Withdraw is reduced from 605245 to 571621, a ~33k gas reduction.

I should be able to reduce the merkle tree cost a little more with some optimisations to MerkleTree, but I will do that in a separate ticket.

Changing the circuit from e7 to e5 will reduce the number of constraints by approx 1900, and increase the on-chain cost negligibly (on-chain e5 is slightly more expensive than e7, but not by much).

I will do the MerkleTree modifications in a separate ticket.