Skip to content

Commit

Permalink
Merge pull request #193 from privacy-scaling-explorations/ref/browser…
Browse files Browse the repository at this point in the history
…-compatible

Improve `@zk-kit/utils` package
  • Loading branch information
cedoor committed Mar 12, 2024
2 parents 378ba66 + 97dd8b0 commit abbdc85
Show file tree
Hide file tree
Showing 35 changed files with 828 additions and 209 deletions.
2 changes: 1 addition & 1 deletion jest.config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import fs from "fs"
import type { Config } from "@jest/types"

const exclude = ["circuits", "imt.sol", "rollup-plugin-rust", "lazytower.sol", "lazytower.circom", "utils"]
const exclude = ["circuits", "imt.sol", "rollup-plugin-rust", "lazytower.sol", "lazytower.circom"]

const projects: any = fs
.readdirSync("./packages", { withFileTypes: true })
Expand Down
4 changes: 1 addition & 3 deletions packages/baby-jubjub/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,13 @@
"url": "https://github.com/privacy-scaling-explorations/zk-kit.git/issues"
},
"scripts": {
"build": "rimraf dist && rollup -c rollup.config.ts --configPlugin typescript && yarn build:iife",
"build:iife": "rollup -c rollup.iife.config.ts --configPlugin typescript",
"build": "rimraf dist && rollup -c rollup.config.ts --configPlugin typescript",
"prepublishOnly": "yarn build"
},
"publishConfig": {
"access": "public"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^25.0.7",
"@rollup/plugin-node-resolve": "^15.2.3",
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-typescript": "^11.1.6",
Expand Down
17 changes: 16 additions & 1 deletion packages/baby-jubjub/rollup.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import typescript from "@rollup/plugin-typescript"
import fs from "fs"
import cleanup from "rollup-plugin-cleanup"
import terser from "@rollup/plugin-terser"

const pkg = JSON.parse(fs.readFileSync("./package.json", "utf8"))
const banner = `/**
Expand All @@ -12,11 +13,25 @@ const banner = `/**
* @see [Github]{@link ${pkg.homepage}}
*/`

const name = pkg.name.split("/")[1].replace(/[-/]./g, (x: string) => x.toUpperCase()[1])

export default {
input: "src/index.ts",
output: [
{ file: pkg.exports["."].require, format: "cjs", banner },
{ file: pkg.exports["."].default, format: "es", banner }
{ file: pkg.exports["."].default, format: "es", banner },
{
file: pkg.iife,
name,
format: "iife",
banner
},
{
file: pkg.unpkg,
name,
format: "iife",
plugins: [terser({ output: { preamble: banner } })]
}
],
external: Object.keys(pkg.dependencies),
plugins: [typescript({ tsconfig: "./build.tsconfig.json" }), cleanup({ comments: "jsdoc" })]
Expand Down
47 changes: 0 additions & 47 deletions packages/baby-jubjub/rollup.iife.config.ts

This file was deleted.

2 changes: 1 addition & 1 deletion packages/baby-jubjub/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"extends": "../../tsconfig.json",
"include": ["src", "tests", "rollup.config.ts", "rollup.iife.config.ts"]
"include": ["src", "tests", "rollup.config.ts"]
}
1 change: 1 addition & 0 deletions packages/circuits/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"@zk-kit/eddsa-poseidon": "0.5.1",
"@zk-kit/poseidon-cipher": "0.1.1",
"@zk-kit/smt": "1.0.0",
"@zk-kit/utils": "0.5.0",
"circomkit": "0.0.24",
"mocha": "^10.2.0",
"poseidon-lite": "^0.2.0"
Expand Down
31 changes: 1 addition & 30 deletions packages/circuits/tests/common.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { Circomkit } from "circomkit"
import { readFileSync } from "fs"
import path from "path"
import { randomBytes } from "crypto"
import { Point, mulPointEscalar, r } from "@zk-kit/baby-jubjub"
import { Point, mulPointEscalar } from "@zk-kit/baby-jubjub"
import { derivePublicKey, deriveSecretScalar } from "@zk-kit/eddsa-poseidon"
import { LeanIMT } from "@zk-kit/imt"
import { poseidon2 } from "poseidon-lite"
Expand Down Expand Up @@ -34,34 +33,6 @@ export const circomkit = new Circomkit({
verbose: false
})

/**
* Returns a BabyJub-compatible random value. We create it by first generating
* a random value (initially 256 bits large) modulo the snark field size as
* described in EIP197. This results in a key size of roughly 253 bits and no
* more than 254 bits. To prevent modulo bias, we then use this efficient
* algorithm:
* http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/lib/libc/crypt/arc4random_uniform.c
* @returns A BabyJub-compatible random value.
*/
export const genRandomBabyJubValue = (): bigint => {
// Prevent modulo bias
// const lim = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000')
// const min = (lim - SNARK_FIELD_SIZE) % SNARK_FIELD_SIZE
const min = BigInt("6350874878119819312338956282401532410528162663560392320966563075034087161851")

let privKey: bigint = r

do {
const rand = BigInt(`0x${randomBytes(32).toString("hex")}`)

if (rand >= min) {
privKey = rand % r
}
} while (privKey >= r)

return privKey
}

/**
* Generate a public key from a private key
* @param privateKey the private key to generate a public key from
Expand Down
41 changes: 23 additions & 18 deletions packages/circuits/tests/ecdh.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { WitnessTester } from "circomkit"
import { deriveSecretScalar } from "@zk-kit/eddsa-poseidon"

import { circomkit, genEcdhSharedKey, genPublicKey, genRandomBabyJubValue } from "./common"
import { beBufferToBigInt, crypto } from "@zk-kit/utils"
import { circomkit, genEcdhSharedKey, genPublicKey } from "./common"

describe("ECDH Shared Key derivation circuit", () => {
let circuit: WitnessTester<["privateKey", "publicKey"], ["sharedKey"]>
Expand All @@ -14,38 +14,43 @@ describe("ECDH Shared Key derivation circuit", () => {
})

it("should correctly compute an ECDH shared key", async () => {

Check warning on line 16 in packages/circuits/tests/ecdh.test.ts

View workflow job for this annotation

GitHub Actions / style

Test has no assertions
const privateKey1 = genRandomBabyJubValue()
const privateKey2 = genRandomBabyJubValue()
const publicKey2 = genPublicKey(privateKey2)
const privateKey1 = crypto.getRandomValues(32)
const privateKey2 = crypto.getRandomValues(32)
const bgPrivateKey1 = beBufferToBigInt(Buffer.from(privateKey1))
const bgPrivateKey2 = beBufferToBigInt(Buffer.from(privateKey2))

const publicKey2 = genPublicKey(bgPrivateKey2)

// generate a shared key between the first private key and the second public key
const ecdhSharedKey = genEcdhSharedKey(privateKey1, publicKey2)
const ecdhSharedKey = genEcdhSharedKey(bgPrivateKey1, publicKey2)

const circuitInputs = {
privateKey: BigInt(deriveSecretScalar(privateKey1)),
privateKey: BigInt(deriveSecretScalar(bgPrivateKey1)),
publicKey: publicKey2
}

await circuit.expectPass(circuitInputs, { sharedKey: [ecdhSharedKey[0], ecdhSharedKey[1]] })
})

it("should generate the same shared key from the same keypairs", async () => {

Check warning on line 35 in packages/circuits/tests/ecdh.test.ts

View workflow job for this annotation

GitHub Actions / style

Test has no assertions
const privateKey1 = genRandomBabyJubValue()
const privateKey2 = genRandomBabyJubValue()
const publicKey1 = genPublicKey(privateKey1)
const publicKey2 = genPublicKey(privateKey2)
const privateKey1 = crypto.getRandomValues(32)
const privateKey2 = crypto.getRandomValues(32)
const bgPrivateKey1 = beBufferToBigInt(Buffer.from(privateKey1))
const bgPrivateKey2 = beBufferToBigInt(Buffer.from(privateKey2))
const publicKey1 = genPublicKey(bgPrivateKey1)
const publicKey2 = genPublicKey(bgPrivateKey2)

// generate a shared key between the first private key and the second public key
const ecdhSharedKey = genEcdhSharedKey(privateKey1, publicKey2)
const ecdhSharedKey2 = genEcdhSharedKey(privateKey2, publicKey1)
const ecdhSharedKey = genEcdhSharedKey(bgPrivateKey1, publicKey2)
const ecdhSharedKey2 = genEcdhSharedKey(bgPrivateKey2, publicKey1)

const circuitInputs = {
privateKey: BigInt(deriveSecretScalar(privateKey1)),
privateKey: BigInt(deriveSecretScalar(bgPrivateKey1)),
publicKey: publicKey2
}

const circuitInputs2 = {
privateKey: BigInt(deriveSecretScalar(privateKey2)),
privateKey: BigInt(deriveSecretScalar(bgPrivateKey2)),
publicKey: publicKey1
}

Expand All @@ -60,9 +65,9 @@ describe("ECDH Shared Key derivation circuit", () => {
})

it("should generate the same ECDH key consistently for the same inputs", async () => {

Check warning on line 67 in packages/circuits/tests/ecdh.test.ts

View workflow job for this annotation

GitHub Actions / style

Test has no assertions
const privateKey1 = BigInt(deriveSecretScalar(genRandomBabyJubValue()))
const privateKey2 = genRandomBabyJubValue()
const publicKey2 = genPublicKey(privateKey2)
const privateKey1 = BigInt(deriveSecretScalar(Buffer.from(crypto.getRandomValues(32))))
const privateKey2 = crypto.getRandomValues(32)
const publicKey2 = genPublicKey(beBufferToBigInt(Buffer.from(privateKey2)))

const circuitInputs = {
privateKey: privateKey1,
Expand Down
25 changes: 14 additions & 11 deletions packages/circuits/tests/poseidon-cipher.test.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import { WitnessTester } from "circomkit"
import { Nonce, PlainText, poseidonDecrypt, poseidonEncrypt, poseidonPerm } from "@zk-kit/poseidon-cipher"

import { circomkit, genEcdhSharedKey, genPublicKey, genRandomBabyJubValue } from "./common"
import { beBufferToBigInt, crypto } from "@zk-kit/utils"
import { circomkit, genEcdhSharedKey, genPublicKey } from "./common"

describe("poseidon-cipher", () => {
describe("poseidonDecrypt", () => {
let circuit: WitnessTester<["ciphertext", "nonce", "key"], ["decrypted"]>

const privateKey = genRandomBabyJubValue()
const publicKey = genPublicKey(privateKey)
const encryptionKey = genEcdhSharedKey(privateKey, publicKey)
const privateKey = crypto.getRandomValues(32)
const bgPrivateKey = beBufferToBigInt(Buffer.from(privateKey))
const publicKey = genPublicKey(bgPrivateKey)
const encryptionKey = genEcdhSharedKey(bgPrivateKey, publicKey)

const nonce: Nonce = BigInt(5)

Expand Down Expand Up @@ -96,9 +97,10 @@ describe("poseidon-cipher", () => {
describe("poseidonDecryptWithoutChecks", () => {
let circuit: WitnessTester<["ciphertext", "nonce", "key"], ["decrypted"]>

const privateKey = genRandomBabyJubValue()
const publicKey = genPublicKey(privateKey)
const encryptionKey = genEcdhSharedKey(privateKey, publicKey)
const privateKey = crypto.getRandomValues(32)
const bgPrivateKey = beBufferToBigInt(Buffer.from(privateKey))
const publicKey = genPublicKey(bgPrivateKey)
const encryptionKey = genEcdhSharedKey(bgPrivateKey, publicKey)

const plainText: PlainText<bigint> = [BigInt(0), BigInt(1)]
const nonce: Nonce = BigInt(5)
Expand Down Expand Up @@ -153,9 +155,10 @@ describe("poseidon-cipher", () => {
describe("poseidonIterations", () => {
let circuit: WitnessTester<["ciphertext", "nonce", "key"], ["decrypted"]>

const privateKey = genRandomBabyJubValue()
const publicKey = genPublicKey(privateKey)
const encryptionKey = genEcdhSharedKey(privateKey, publicKey)
const privateKey = crypto.getRandomValues(32)
const bgPrivateKey = beBufferToBigInt(Buffer.from(privateKey))
const publicKey = genPublicKey(bgPrivateKey)
const encryptionKey = genEcdhSharedKey(bgPrivateKey, publicKey)

const plainText: PlainText<bigint> = [BigInt(0), BigInt(1)]
const nonce: Nonce = BigInt(5)
Expand Down
4 changes: 2 additions & 2 deletions packages/eddsa-poseidon/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@
"@rollup/plugin-node-resolve": "^15.2.3",
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-typescript": "^11.1.6",
"blake-hash": "2.0.0",
"circomlibjs": "0.0.8",
"ffjavascript": "0.2.38",
"poseidon-lite": "0.2.0",
Expand All @@ -51,6 +50,7 @@
},
"dependencies": {
"@zk-kit/baby-jubjub": "0.2.0",
"@zk-kit/utils": "0.5.0"
"@zk-kit/utils": "0.5.0",
"buffer": "6.0.3"
}
}
12 changes: 1 addition & 11 deletions packages/eddsa-poseidon/rollup.iife.config.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import commonjs from "@rollup/plugin-commonjs"
import { nodeResolve } from "@rollup/plugin-node-resolve"
import terser from "@rollup/plugin-terser"
import typescript from "@rollup/plugin-typescript"
import fs from "fs"
import cleanup from "rollup-plugin-cleanup"
import nodePolyfills from "rollup-plugin-polyfill-node"

const pkg = JSON.parse(fs.readFileSync("./package.json", "utf8"))
const banner = `/**
Expand Down Expand Up @@ -35,13 +33,5 @@ export default {
}
],
external: [],
plugins: [
typescript({ tsconfig: "./build.tsconfig.json" }),
commonjs(),
nodeResolve({
preferBuiltins: true
}),
nodePolyfills({ include: null }),
cleanup({ comments: "jsdoc" })
]
plugins: [typescript({ tsconfig: "./build.tsconfig.json" }), commonjs(), cleanup({ comments: "jsdoc" })]
}
Loading

0 comments on commit abbdc85

Please sign in to comment.