Skip to content

Commit

Permalink
chore: apply prettier
Browse files Browse the repository at this point in the history
  • Loading branch information
saleel committed Oct 17, 2024
1 parent bc6f946 commit 4e9d589
Show file tree
Hide file tree
Showing 21 changed files with 1,217 additions and 1,275 deletions.
2 changes: 1 addition & 1 deletion packages/helpers/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"scripts": {
"build": "tsc",
"test": "jest tests/**/*.test.ts",
"lint": "eslint .",
"lint": "prettier --write src/**/*.ts tests/**/*.ts && eslint .",
"prepublish": "yarn lint && yarn build",
"publish": "yarn npm publish --access=public"
},
Expand Down
8 changes: 6 additions & 2 deletions packages/helpers/src/binary-format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,14 +190,18 @@ export function packedNBytesToString(packedBytes: bigint[], n: number = 31): str
}

export function packBytesIntoNBytes(messagePaddedRaw: Uint8Array | string, n = 7): Array<bigint> {
const messagePadded: Uint8Array = typeof messagePaddedRaw === 'string' ? stringToBytes(messagePaddedRaw) : messagePaddedRaw;
const messagePadded: Uint8Array =
typeof messagePaddedRaw === 'string' ? stringToBytes(messagePaddedRaw) : messagePaddedRaw;
const output: Array<bigint> = [];
for (let i = 0; i < messagePadded.length; i++) {
if (i % n === 0) {
output.push(0n);
}
const j = (i / n) | 0;
console.assert(j === output.length - 1, 'Not editing the index of the last element -- packing loop invariants bug!');
console.assert(
j === output.length - 1,
'Not editing the index of the last element -- packing loop invariants bug!',
);
output[j] += BigInt(messagePadded[i]) << BigInt((i % n) * 8);
}
return output;
Expand Down
52 changes: 11 additions & 41 deletions packages/helpers/src/chunked-zkey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@ const zkeySuffix = ['b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'];

// uncompresses single .gz file.
// returns the contents as an ArrayBuffer
export const uncompressGz = async (
arrayBuffer: ArrayBuffer,
): Promise<ArrayBuffer> => {
export const uncompressGz = async (arrayBuffer: ArrayBuffer): Promise<ArrayBuffer> => {
const output = pako.ungzip(arrayBuffer);
const buff = output.buffer;
return buff;
Expand All @@ -31,19 +29,13 @@ async function downloadWithRetries(link: string, downloadAttempts: number) {
return response;
}
}
throw new Error(
`Error downloading ${link} after ${downloadAttempts} retries`,
);
throw new Error(`Error downloading ${link} after ${downloadAttempts} retries`);
}

// GET the compressed file from the remote server, then store it with localforage
// Note that it must be stored as an uncompressed ArrayBuffer
// and named such that filename===`${name}.zkey${a}` in order for it to be found by snarkjs.
export async function downloadFromFilename(
baseUrl: string,
filename: string,
compressed = false,
) {
export async function downloadFromFilename(baseUrl: string, filename: string, compressed = false) {
const link = baseUrl + filename;

const zkeyResp = await downloadWithRetries(link, 3);
Expand All @@ -64,28 +56,18 @@ export async function downloadFromFilename(
console.log(`Storage of ${filename} successful!`);
}

export async function downloadProofFiles(
baseUrl: string,
circuitName: string,
onFileDownloaded: () => void,
) {
export async function downloadProofFiles(baseUrl: string, circuitName: string, onFileDownloaded: () => void) {
const filePromises = [];
for (const c of zkeySuffix) {
const targzFilename = `${circuitName}.zkey${c}${zkeyExtension}`;
// const itemCompressed = await localforage.getItem(targzFilename);
const item = await localforage.getItem(`${circuitName}.zkey${c}`);
if (item) {
console.log(
`${circuitName}.zkey${c}${
item ? '' : zkeyExtension
} already found in localforage!`,
);
console.log(`${circuitName}.zkey${c}${item ? '' : zkeyExtension} already found in localforage!`);
onFileDownloaded();
continue;
}
filePromises.push(
downloadFromFilename(baseUrl, targzFilename, true).then(() => onFileDownloaded()),
);
filePromises.push(downloadFromFilename(baseUrl, targzFilename, true).then(() => onFileDownloaded()));
}
console.log(filePromises);
await Promise.all(filePromises);
Expand Down Expand Up @@ -116,11 +98,7 @@ export async function verifyProof(proof: any, publicSignals: any, baseUrl: strin
const vkey = await response.json();
console.log('vkey', vkey);

const proofVerified = await snarkjs.groth16.verify(
vkey,
publicSignals,
proof,
);
const proofVerified = await snarkjs.groth16.verify(vkey, publicSignals, proof);
console.log('proofV', proofVerified);

return proofVerified;
Expand All @@ -143,24 +121,16 @@ function bigIntToArray(n: number, k: number, x: bigint) {

// taken from generation code in dizkus-circuits tests
function pubkeyToXYArrays(pk: string) {
const XArr = bigIntToArray(64, 4, BigInt(`0x${pk.slice(4, 4 + 64)}`)).map(
(el) => el.toString(),
);
const YArr = bigIntToArray(64, 4, BigInt(`0x${pk.slice(68, 68 + 64)}`)).map(
(el) => el.toString(),
);
const XArr = bigIntToArray(64, 4, BigInt(`0x${pk.slice(4, 4 + 64)}`)).map((el) => el.toString());
const YArr = bigIntToArray(64, 4, BigInt(`0x${pk.slice(68, 68 + 64)}`)).map((el) => el.toString());

return [XArr, YArr];
}

// taken from generation code in dizkus-circuits tests
function sigToRSArrays(sig: string) {
const rArr = bigIntToArray(64, 4, BigInt(`0x${sig.slice(2, 2 + 64)}`)).map(
(el) => el.toString(),
);
const sArr = bigIntToArray(64, 4, BigInt(`0x${sig.slice(66, 66 + 64)}`)).map(
(el) => el.toString(),
);
const rArr = bigIntToArray(64, 4, BigInt(`0x${sig.slice(2, 2 + 64)}`)).map((el) => el.toString());
const sArr = bigIntToArray(64, 4, BigInt(`0x${sig.slice(66, 66 + 64)}`)).map((el) => el.toString());

return [rArr, sArr];
}
Expand Down
32 changes: 9 additions & 23 deletions packages/helpers/src/dkim/dns-over-http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,7 @@ export class DoH {
* @return {*} {(Promise<string | null>)} DKIM public key or null if not found
* @memberof DoH
*/
public static async resolveDKIMPublicKey(
name: string,
dnsServerURL: string
): Promise<string | null> {
public static async resolveDKIMPublicKey(name: string, dnsServerURL: string): Promise<string | null> {
let cleanURL = dnsServerURL;
if (!cleanURL.startsWith('https://')) {
cleanURL = `https://${cleanURL}`;
Expand All @@ -47,20 +44,14 @@ export class DoH {
queryUrl.searchParams.set('type', DoH.DoHTypeTXT.toString());

const resp = await fetch(queryUrl, {
headers: {
accept: 'application/dns-json',
},
}
);
headers: {
accept: 'application/dns-json',
},
});

if (resp.status === 200) {
const out = await resp.json();
if (
typeof out === 'object' &&
out !== null &&
'Status' in out &&
'Answer' in out
) {
if (typeof out === 'object' && out !== null && 'Status' in out && 'Answer' in out) {
const result = out as DoHResponse;
if (result.Status === DoH.DoHStatusNoError && result.Answer.length > 0) {
for (const ans of result.Answer) {
Expand All @@ -73,7 +64,7 @@ export class DoH {
TXT (potentially multi-line) and DKIM (Base64 data) standards,
we can directly remove all double quotes from the DKIM public key.
*/
dkimRecord = dkimRecord.replace(/"/g, "");
dkimRecord = dkimRecord.replace(/"/g, '');
return dkimRecord;
}
}
Expand Down Expand Up @@ -124,16 +115,11 @@ export async function resolveDNSHTTP(name: string, type: string) {
}
}

const cloudflareResult = await DoH.resolveDKIMPublicKey(
name,
DoHServer.Cloudflare
);
const cloudflareResult = await DoH.resolveDKIMPublicKey(name, DoHServer.Cloudflare);

// Log an error if there is a mismatch in the result
if (googleResult !== cloudflareResult) {
console.error(
'DKIM record mismatch between Google and Cloudflare! Using Google result.'
);
console.error('DKIM record mismatch between Google and Cloudflare! Using Google result.');
}

return [googleResult];
Expand Down
30 changes: 11 additions & 19 deletions packages/helpers/src/dkim/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,18 +46,18 @@ export async function verifyDKIMSignature(
let appliedSanitization;
if (dkimResult.status.comment === 'bad signature' && enableSanitization) {
const results = await Promise.all(
sanitizers.map((sanitize) => tryVerifyDKIM(sanitize(emailStr), domain, fallbackToZKEmailDNSArchive).then((result) => ({
result,
sanitizer: sanitize.name,
}))),
sanitizers.map((sanitize) =>
tryVerifyDKIM(sanitize(emailStr), domain, fallbackToZKEmailDNSArchive).then((result) => ({
result,
sanitizer: sanitize.name,
})),
),
);

const passed = results.find((r) => r.result.status.result === 'pass');

if (passed) {
console.log(
`DKIM: Verification passed after applying sanitization "${passed.sanitizer}"`,
);
console.log(`DKIM: Verification passed after applying sanitization "${passed.sanitizer}"`);
dkimResult = passed.result;
appliedSanitization = passed.sanitizer;
}
Expand All @@ -74,9 +74,7 @@ export async function verifyDKIMSignature(
} = dkimResult;

if (result !== 'pass') {
throw new Error(
`DKIM signature verification failed for domain ${signingDomain}. Reason: ${comment}`,
);
throw new Error(`DKIM signature verification failed for domain ${signingDomain}. Reason: ${comment}`);
}

const pubKeyData = pki.publicKeyFromPem(publicKey.toString());
Expand Down Expand Up @@ -124,22 +122,16 @@ async function tryVerifyDKIM(
let domainToVerifyDKIM = domain;
if (!domainToVerifyDKIM) {
if (dkimVerifier.headerFrom.length > 1) {
throw new Error(
'Multiple From header in email and domain for verification not specified',
);
throw new Error('Multiple From header in email and domain for verification not specified');
}

domainToVerifyDKIM = dkimVerifier.headerFrom[0].split('@')[1];
}

const dkimResult = dkimVerifier.results.find(
(d: any) => d.signingDomain === domainToVerifyDKIM,
);
const dkimResult = dkimVerifier.results.find((d: any) => d.signingDomain === domainToVerifyDKIM);

if (!dkimResult) {
throw new Error(
`DKIM signature not found for domain ${domainToVerifyDKIM}`,
);
throw new Error(`DKIM signature not found for domain ${domainToVerifyDKIM}`);
}

dkimResult.headers = dkimVerifier.headers;
Expand Down
12 changes: 2 additions & 10 deletions packages/helpers/src/dkim/sanitizers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,7 @@ function revertGoogleMessageId(email: string): string {
return email;
}

const googleReplacedMessageId = getHeaderValue(
email,
'X-Google-Original-Message-ID',
);
const googleReplacedMessageId = getHeaderValue(email, 'X-Google-Original-Message-ID');

if (googleReplacedMessageId) {
return setHeaderValue(email, 'Message-ID', googleReplacedMessageId);
Expand Down Expand Up @@ -65,11 +62,6 @@ function sanitizeTabs(email: string): string {
return email.replace('=09', '\t');
}

const sanitizers = [
revertGoogleMessageId,
removeLabels,
insert13Before10,
sanitizeTabs,
];
const sanitizers = [revertGoogleMessageId, removeLabels, insert13Before10, sanitizeTabs];

export default sanitizers;
30 changes: 9 additions & 21 deletions packages/helpers/src/input-generators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ function removeSoftLineBreaks(body: string[]): string[] {
let i = 0;
while (i < body.length) {
if (
i + 2 < body.length
&& body[i] === '61' // '=' character
&& body[i + 1] === '13' // '\r' character
&& body[i + 2] === '10'
i + 2 < body.length &&
body[i] === '61' && // '=' character
body[i + 1] === '13' && // '\r' character
body[i + 2] === '10'
) {
// '\n' character
// Skip the soft line break sequence
Expand Down Expand Up @@ -94,15 +94,10 @@ export function generateEmailVerifierInputsFromDKIMResult(
dkimResult: DKIMVerificationResult,
params: InputGenerationArgs = {},
): CircuitInput {
const {
headers, body, bodyHash, publicKey, signature,
} = dkimResult;
const { headers, body, bodyHash, publicKey, signature } = dkimResult;

// SHA add padding
const [messagePadded, messagePaddedLen] = sha256Pad(
headers,
params.maxHeadersLength || MAX_HEADER_PADDED_BYTES,
);
const [messagePadded, messagePaddedLen] = sha256Pad(headers, params.maxHeadersLength || MAX_HEADER_PADDED_BYTES);

const circuitInputs: CircuitInput = {
emailHeader: Uint8ArrayToCharArray(messagePadded), // Packed into 1 byte signals
Expand All @@ -117,9 +112,7 @@ export function generateEmailVerifierInputsFromDKIMResult(

if (!params.ignoreBodyHashCheck) {
if (!body || !bodyHash) {
throw new Error(
'body and bodyHash are required when ignoreBodyHashCheck is false',
);
throw new Error('body and bodyHash are required when ignoreBodyHashCheck is false');
}

const bodyHashIndex = headers.toString().indexOf(bodyHash);
Expand All @@ -128,10 +121,7 @@ export function generateEmailVerifierInputsFromDKIMResult(
// 65 comes from the 64 at the end and the 1 bit in the start, then 63 comes from the formula to round it up to the nearest 64.
// see sha256algorithm.com for a more full explanation of padding length
const bodySHALength = Math.floor((body.length + 63 + 65) / 64) * 64;
const [bodyPadded, bodyPaddedLen] = sha256Pad(
body,
Math.max(maxBodyLength, bodySHALength),
);
const [bodyPadded, bodyPaddedLen] = sha256Pad(body, Math.max(maxBodyLength, bodySHALength));

const { precomputedSha, bodyRemaining, bodyRemainingLength } = generatePartialSHA({
body: bodyPadded,
Expand All @@ -146,9 +136,7 @@ export function generateEmailVerifierInputsFromDKIMResult(
circuitInputs.emailBody = Uint8ArrayToCharArray(bodyRemaining);

if (params.removeSoftLineBreaks) {
circuitInputs.decodedEmailBodyIn = removeSoftLineBreaks(
circuitInputs.emailBody,
);
circuitInputs.decodedEmailBodyIn = removeSoftLineBreaks(circuitInputs.emailBody);
}

if (params.enableBodyMasking) {
Expand Down
Loading

0 comments on commit 4e9d589

Please sign in to comment.