Skip to content

Commit

Permalink
add gas benchmark suite and minor edit to verifier
Browse files Browse the repository at this point in the history
  • Loading branch information
nalinbhardwaj committed Sep 21, 2023
1 parent 4887c97 commit c590ec9
Show file tree
Hide file tree
Showing 16 changed files with 2,230 additions and 31 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ jobs:
- run: |
cd test-vectors
npm ci
npm start
npm run generate_wycheproof
npm test
git diff --exit-code
id: test
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@
"[solidity]": {
"editor.defaultFormatter": "JuanBlanco.solidity"
},
"coverage-gutters.coverageFileNames": ["lcov.info"]
"coverage-gutters.coverageFileNames": ["lcov.info"],
"solidity.compileUsingRemoteVersion": "v0.8.21+commit.d9974bed"
}
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ The secp256r1 elliptic curve, aka P256, is interesting because it's supported by

## Usage

**Address `0xA77aB3533750B0C4b229e441fEe37f13c65A2b1F`**
**Address `0xea923BEe7108728eA2708af25e9981272193a555`**

Available on any chain. If missing, see `deploy.sh`.

Expand All @@ -19,7 +19,7 @@ bytes32 hash; // message hash
uint256 r, s; // signature
uint256 x, y; // public key
address verifier = 0xA77aB3533750B0C4b229e441fEe37f13c65A2b1F;
address verifier = 0xea923BEe7108728eA2708af25e9981272193a555;
bytes memory args = abi.encode(hash, r, s, x, y);
(bool success, bytes memory ret) = verifier.staticcall(args);
assert(success); // never reverts, always returns 0 or 1
Expand Down
24 changes: 12 additions & 12 deletions broadcast/Deploy.s.sol/84531/run-latest.json

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions script/deploy.sh
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
forge script DeployScript --via-ir --optimizer-runs=999999 --rpc-url $RPC_URL --broadcast --private-key $PRIVATE_KEY

# Update contract address
ADDR=0xA77aB3533750B0C4b229e441fEe37f13c65A2b1F
ADDR=0xea923BEe7108728eA2708af25e9981272193a555

# Verify to Etherscan
forge verify-contract $ADDR P256Verifier --optimizer-runs=999999 --constructor-args "0x" --show-standard-json-input > script/etherscan.json
Expand All @@ -13,4 +13,4 @@ forge verify-contract $ADDR P256Verifier --optimizer-runs=999999 --constructor-a
# Finally, manually verify to Etherscan

# Success
# https://goerli.basescan.org/address/0xA77aB3533750B0C4b229e441fEe37f13c65A2b1F#code
# https://goerli.basescan.org/address/0xea923BEe7108728eA2708af25e9981272193a555#code
13 changes: 9 additions & 4 deletions script/etherscan.json

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions src/P256Verifier.sol
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ contract P256Verifier {
uint256 scalar_u = mulmod(uint256(message_hash), sInv, n); // (h * s^-1) in scalar field
uint256 scalar_v = mulmod(r, sInv, n); // (r * s^-1) in scalar field

(uint256 r_x, bool mulmuladd_success) = ecZZ_mulmuladd_S_asm(
(uint256 r_x, bool mulmuladd_success) = ecZZ_mulmuladd(
pubKey[0],
pubKey[1],
scalar_u,
Expand Down Expand Up @@ -121,7 +121,7 @@ contract P256Verifier {
* returns tuple of (x coordinate of uG + vQ, boolean that is false if internal precompile staticcall fail)
* Strauss-Shamir is described well in https://stackoverflow.com/a/50994362
*/
function ecZZ_mulmuladd_S_asm(
function ecZZ_mulmuladd(
uint256 QX,
uint256 QY, // affine rep for input point Q
uint256 scalar_u,
Expand Down
56 changes: 56 additions & 0 deletions test-vectors/generate_random.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import crypto from "crypto";
import fs from "fs";

// Generate random signatures for benchmarking gas usage.
// Representative of real-world usage.
async function main() {
const vectors = [];

while (vectors.length < 1000) {
const p256 = { name: "ECDSA", namedCurve: "P-256", hash: "SHA-256" };
const key = await crypto.subtle.generateKey(p256, true, ["sign", "verify"]);
const pubKeyDer = await crypto.subtle.exportKey("spki", key.publicKey);
const pubKeyHex = Buffer.from(pubKeyDer).toString("hex");
// console.log(`Generated pubkey: ${pubKeyHex}`);

const msg: string = `deadbeef${vectors.length
.toString(16)
.padStart(4, "0")}`;
const msgBuf = Buffer.from(msg, "hex");
const msgHash = Buffer.from(await crypto.subtle.digest("SHA-256", msgBuf));
const sigRaw = await crypto.subtle.sign(p256, key.privateKey, msgBuf);

const pubKey = Buffer.from(pubKeyHex.substring(54), "hex");
assert(pubKey.length === 64, "pubkey must be 64 bytes");
const x = `${pubKey.subarray(0, 32).toString("hex")}`;
const y = `${pubKey.subarray(32).toString("hex")}`;

const r = Buffer.from(sigRaw).subarray(0, 32).toString("hex");
const s = Buffer.from(sigRaw).subarray(32, 64).toString("hex");

vectors.push({
x,
y,
r,
s,
hash: msgHash.toString("hex"),
valid: true,
msg,
comment: `generation ${vectors.length}`,
});
}

// Write to JSON
const filepath = "./random_vectors.jsonl";
console.log(`Writing ${vectors.length} vectors to ${filepath}`);
const lines = vectors.map((v) => JSON.stringify(v));
fs.writeFileSync(filepath, lines.join("\n"));
}

function assert(cond: boolean, msg: string) {
if (!cond) throw new Error(msg);
}

main()
.then(() => console.log("Done"))
.catch((err) => console.error(err));
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ async function main() {
console.log(`Deduped: ${deduped.length} vecs`);

// Write to JSON
const filepath = "./vectors.jsonl";
const filepath = "./wycheproof_vectors.jsonl";
console.log(`Writing ${deduped.length} vectors to ${filepath}`);
const lines = vectors.map((v) => JSON.stringify(v));
fs.writeFileSync(filepath, lines.join("\n"));
Expand Down
5 changes: 3 additions & 2 deletions test-vectors/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
"private": true,
"description": "",
"scripts": {
"start": "ts-node generate.ts",
"generate_wycheproof": "ts-node generate_wycheproof.ts",
"generate_random": "ts-node generate_random.ts",
"test": "ts-node test.ts"
},
"author": "",
Expand All @@ -17,4 +18,4 @@
"ts-node": "^10.9.1",
"typescript": "^5.2.2"
}
}
}
Loading

0 comments on commit c590ec9

Please sign in to comment.