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

chore: clean up circuits #104

Merged
merged 6 commits into from
Sep 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
pkg-manager: yarn
app-dir: ~/zk-email-verify
- run:
command: yarn test
command: yarn test -w 2
name: Run circom tests
working_directory: ~/zk-email-verify/packages/circuits

Expand Down
11 changes: 8 additions & 3 deletions packages/circuits/helpers/bigint.circom
Original file line number Diff line number Diff line change
Expand Up @@ -374,10 +374,15 @@ template BigMod(n, k) {
mod[i] <-- longdiv[1][i];
}
div[k] <-- longdiv[0][k];
component range_checks[k + 1];
component div_range_checks[k + 1];
for (var i = 0; i <= k; i++) {
range_checks[i] = Num2Bits(n);
range_checks[i].in <== div[i];
div_range_checks[i] = Num2Bits(n);
div_range_checks[i].in <== div[i];
}
component mod_range_checks[k];
for (var i = 0; i < k; i++) {
mod_range_checks[i] = Num2Bits(n);
mod_range_checks[i].in <== mod[i];
}

component mul = BigMult(n, k + 1);
Expand Down
2 changes: 1 addition & 1 deletion packages/circuits/helpers/rsa.circom
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ template RSAPad(n, k) {
if (i+8 < n*k) {
modulus_prefix += modulus_bits[i+8];
if (i % 8 == 0) {
var idx = (i - (base_len + 8)) / 8;
var idx = (i - (base_len + 8)) \ 8;
Divide-By-0 marked this conversation as resolved.
Show resolved Hide resolved
modulus_zero[idx] = IsZero();
modulus_zero[idx].in <== modulus_prefix;
padded_message_bits[i] <== 1-modulus_zero[idx].out;
Expand Down
55 changes: 0 additions & 55 deletions packages/circuits/helpers/utils.circom
Original file line number Diff line number Diff line change
Expand Up @@ -66,61 +66,6 @@ template CalculateTotal(n) {
sum <== sums[n - 1];
}

// Modulo lifted from https://sourcegraph.com/github.com/darkforest-eth/circuits/-/blob/perlin/perlin.circom and https://sourcegraph.com/github.com/zk-ml/demo/-/blob/circuits/math/circuit.circom
// input: dividend and divisor field elements in [0, sqrt(p))
// output: remainder and quotient field elements in [0, p-1] and [0, sqrt(p)
// Haven't thought about negative divisor yet. Not needed.
// -8 % 5 = 2. [-8 -> 8. 8 % 5 -> 3. 5 - 3 -> 2.]
// (-8 - 2) // 5 = -2
// -8 + 2 * 5 = 2
// check: 2 - 2 * 5 = -8
template Modulo(divisor_bits) {
signal input dividend; // -8
signal input divisor; // 5
signal output remainder; // 2
signal output quotient; // -2

component is_neg = IsNegative();
is_neg.in <== dividend;

signal output is_dividend_negative;
is_dividend_negative <== is_neg.out;

signal output dividend_adjustment;
dividend_adjustment <== 1 + is_dividend_negative * -2; // 1 or -1

signal output abs_dividend;
abs_dividend <== dividend * dividend_adjustment; // 8

signal output raw_remainder;
raw_remainder <-- abs_dividend % divisor;

signal output neg_remainder;
neg_remainder <-- divisor - raw_remainder;

if (is_dividend_negative == 1 && raw_remainder != 0) {
remainder <-- neg_remainder;
} else {
remainder <-- raw_remainder;
}

quotient <-- (dividend - remainder) / divisor; // (-8 - 2) / 5 = -2.

dividend === divisor * quotient + remainder; // -8 = 5 * -2 + 2.

component rp = MultiRangeProof(3, 128);
rp.in[0] <== divisor;
rp.in[1] <== quotient;
rp.in[2] <== dividend;
//rp.max_abs_value <== SQRT_P;

// check that 0 <= remainder < divisor
component remainderUpper = LessThan(divisor_bits);
remainderUpper.in[0] <== remainder;
remainderUpper.in[1] <== divisor;
remainderUpper.out === 1;
}

// Written by us
// n bytes per signal, n = 31 usually
template Packed2Bytes(n){
Expand Down
5 changes: 5 additions & 0 deletions packages/circuits/tests/rsa-test.circom
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
pragma circom 2.1.5;

include "../helpers/rsa.circom";

component main { public [modulus] } = RSAVerify65537(121, 17);
83 changes: 83 additions & 0 deletions packages/circuits/tests/rsa.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import fs from "fs";
import { buildMimcSponge } from "circomlibjs";
import { wasm as wasm_tester } from "circom_tester";
import { Scalar } from "ffjavascript";
import path from "path";
import { DKIMVerificationResult } from "@zk-email/helpers/src/dkim";
import { generateCircuitInputs } from "@zk-email/helpers/src/input-helpers";
import { verifyDKIMSignature } from "@zk-email/helpers/src/dkim";

exports.p = Scalar.fromString(
"21888242871839275222246405745257275088548364400416034343698204186575808495617"
);

describe("RSA", () => {
jest.setTimeout(10 * 60 * 1000); // 10 minutes

let circuit: any;
let dkimResult: DKIMVerificationResult;

beforeAll(async () => {
circuit = await wasm_tester(
path.join(__dirname, "./rsa-test.circom"),
{
// @dev During development recompile can be set to false if you are only making changes in the tests.
// This will save time by not recompiling the circuit every time.
// Compile: circom "./tests/email-verifier-test.circom" --r1cs --wasm --sym --c --wat --output "./tests/compiled-test-circuit"
recompile: true,
output: path.join(__dirname, "./compiled-test-circuit"),
include: path.join(__dirname, "../../../node_modules"),
}
);
const rawEmail = fs.readFileSync(path.join(__dirname, "./test.eml"));
dkimResult = await verifyDKIMSignature(rawEmail);
});

it("should verify rsa signature correctly", async function () {
const emailVerifierInputs = generateCircuitInputs({
rsaSignature: dkimResult.signature,
rsaPublicKey: dkimResult.publicKey,
body: dkimResult.body,
bodyHash: dkimResult.bodyHash,
message: dkimResult.message,
maxMessageLength: 640,
maxBodyLength: 768,
});


const witness = await circuit.calculateWitness({
signature: emailVerifierInputs.signature,
modulus: emailVerifierInputs.pubkey,
// TODO: generate this from the input
base_message: ["1156466847851242602709362303526378170", "191372789510123109308037416804949834", "7204", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"],
});
await circuit.checkConstraints(witness);
await circuit.assertOut(witness, {})
});

it("should fail when verifying with an incorrect signature", async function () {
const emailVerifierInputs = generateCircuitInputs({
rsaSignature: dkimResult.signature,
rsaPublicKey: dkimResult.publicKey,
body: dkimResult.body,
bodyHash: dkimResult.bodyHash,
message: dkimResult.message,
maxMessageLength: 640,
maxBodyLength: 768,
});


expect.assertions(1);
try {
const witness = await circuit.calculateWitness({
signature: emailVerifierInputs.signature,
modulus: emailVerifierInputs.pubkey,
base_message: ["1156466847851242602709362303526378171", "191372789510123109308037416804949834", "7204", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"],
});
await circuit.checkConstraints(witness);
await circuit.assertOut(witness, {})
} catch (error) {
expect((error as Error).message).toMatch("Assert Failed");
}
});
});
5 changes: 5 additions & 0 deletions packages/circuits/tests/sha256-test.circom
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
pragma circom 2.1.5;

include "../helpers/sha.circom";

component main { public [in_padded, in_len_padded_bytes] } = Sha256Bytes(640);
57 changes: 57 additions & 0 deletions packages/circuits/tests/sha256.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import fs from "fs";
import { buildMimcSponge } from "circomlibjs";
import { wasm as wasm_tester } from "circom_tester";
import { Scalar } from "ffjavascript";
import path from "path";
import { DKIMVerificationResult } from "@zk-email/helpers/src/dkim";
import { generateCircuitInputs } from "@zk-email/helpers/src/input-helpers";
import { verifyDKIMSignature } from "@zk-email/helpers/src/dkim";
import { sha256Pad, shaHash } from "@zk-email/helpers/src/shaHash";
import { MAX_HEADER_PADDED_BYTES } from "@twitter-verifier/circuits/helpers";
import { Uint8ArrayToCharArray, uint8ToBits } from "@zk-email/helpers/src/binaryFormat";

exports.p = Scalar.fromString(
"21888242871839275222246405745257275088548364400416034343698204186575808495617"
);

describe("SHA256 for email header", () => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't really an email header test right...

jest.setTimeout(10 * 60 * 1000); // 10 minutes

let circuit: any;

beforeAll(async () => {
circuit = await wasm_tester(
path.join(__dirname, "./sha256-test.circom"),
{
// @dev During development recompile can be set to false if you are only making changes in the tests.
// This will save time by not recompiling the circuit every time.
// Compile: circom "./tests/email-verifier-test.circom" --r1cs --wasm --sym --c --wat --output "./tests/compiled-test-circuit"
recompile: true,
output: path.join(__dirname, "./compiled-test-circuit"),
include: path.join(__dirname, "../../../node_modules"),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Csv we make this non relative at all or nah

}
);
});

it("should hash correctly", async function () {
const inputs = [
"0", "hello world", ""
]
for (const input of inputs) {
const [
paddedMsg,
messageLen,
] = sha256Pad(
Buffer.from(input, "ascii"), 640
)

const witness = await circuit.calculateWitness({
in_len_padded_bytes: messageLen,
in_padded: Uint8ArrayToCharArray(paddedMsg)
});

await circuit.checkConstraints(witness);
await circuit.assertOut(witness, { out: [...uint8ToBits(shaHash(Buffer.from(input, "ascii")))] })
}
});
});