Skip to content

Commit

Permalink
Merge pull request #198 from zk-passport/refactor-passportData
Browse files Browse the repository at this point in the history
refactor mockPassportData generation
  • Loading branch information
0xturboblitz authored Sep 14, 2024
2 parents 01a2186 + 29929d8 commit 7e0601a
Show file tree
Hide file tree
Showing 57 changed files with 1,441 additions and 3,905 deletions.
7 changes: 5 additions & 2 deletions .github/workflows/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ jobs:
uses: actions/setup-node@v3
with:
node-version: 18

- name: Setup Rust
uses: dtolnay/rust-toolchain@stable

Expand All @@ -58,6 +57,10 @@ jobs:
working-directory: ./circuits
run: yarn lint

- name: Run Tests
- name: Run Tests (Circuits)
working-directory: ./circuits
run: yarn test

- name: Run Tests (Common)
working-directory: ./common
run: yarn test
6 changes: 3 additions & 3 deletions app/src/screens/MainScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import NextScreen from './NextScreen';
import RegisterScreen from './RegisterScreen';
import AppScreen from './AppScreen';
// import constants
import { RPC_URL, SignatureAlgorithm } from '../../../common/src/constants/constants';
import { RPC_URL, SignatureAlgorithmIndex } from '../../../common/src/constants/constants';
import { mock_csca_sha256_rsa_4096, mock_dsc_sha256_rsa_4096 } from '../../../common/src/constants/mockCertificates';
import DatePicker from 'react-native-date-picker'
import StartScreen from './StartScreen';
Expand Down Expand Up @@ -143,8 +143,8 @@ const MainScreen: React.FC = () => {
// console.log('CSCA Proof received:', cscaProof);
// if ((cscaProof !== null) && (localProof !== null)) {
// const sendTransaction = async () => {
// const sigAlgFormatted = formatSigAlgNameForCircuit(passportData.signatureAlgorithm, passportData.pubKey.exponent);
// const sigAlgIndex = SignatureAlgorithm[sigAlgFormatted as keyof typeof SignatureAlgorithm]
// const sigAlgFormatted = formatSigAlgNameForCircuit(passportData.signatureAlgorithm, passportData.pubKey.exponent); // this is old formatting
// const sigAlgIndex = SignatureAlgorithmIndex[sigAlgFormatted as keyof typeof SignatureAlgorithmIndex]
// console.log("local proof already generated, sending transaction");
// const provider = new ethers.JsonRpcProvider(RPC_URL);
// const serverResponse = await sendRegisterTransaction(localProof, cscaProof, sigAlgIndex)
Expand Down
7 changes: 4 additions & 3 deletions app/src/screens/MockDataScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ import { genMockPassportData } from '../../../common/src/utils/genMockPassportDa
import { countryCodes } from '../../../common/src/constants/constants';
import getCountryISO2 from "country-iso-3-to-2";
import { flag } from 'country-emoji';
import { getSignatureAlgorithm, getCircuitName } from '../../../common/src/utils/handleCertificate';
import { parseDSC, getCircuitName } from '../../../common/src/utils/handleCertificate';
import { downloadZkey } from '../utils/zkeyDownload';

const MockDataScreen: React.FC = () => {
const [signatureAlgorithm, setSignatureAlgorithm] = useState("rsa_sha256");
const listOfSignatureAlgorithms = ["rsa_sha1", "rsa_sha256", "rsapss_sha256"];
Expand All @@ -35,8 +36,8 @@ const MockDataScreen: React.FC = () => {
const mockPassportData = genMockPassportData(signatureAlgorithm as "rsa_sha256" | "rsa_sha1" | "rsapss_sha256", nationality as keyof typeof countryCodes, castDate(dateOfBirthDatePicker), castDate(dateOfExpiryDatePicker));
useUserStore.getState().registerPassportData(mockPassportData);
useUserStore.getState().setRegistered(true);
const sigAlgName = getSignatureAlgorithm(mockPassportData.dsc as string);
const circuitName = getCircuitName("prove", sigAlgName.signatureAlgorithm, sigAlgName.hashFunction);
const { signatureAlgorithm: sigAlg, hashFunction } = parseDSC(mockPassportData.dsc);
const circuitName = getCircuitName("prove", sigAlg, hashFunction);
downloadZkey(circuitName as any);
resolve(null);
}, 0));
Expand Down
4 changes: 2 additions & 2 deletions app/src/screens/ProveScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { generateCircuitInputsProve } from '../../../common/src/utils/generateIn
import { revealBitmapFromAttributes } from '../../../common/src/utils/revealBitmap';
import { formatProof, generateProof } from '../utils/prover';
import io, { Socket } from 'socket.io-client';
import { getCircuitName, getSignatureAlgorithm } from '../../../common/src/utils/handleCertificate';
import { getCircuitName, parseDSC } from '../../../common/src/utils/handleCertificate';
import { CircuitName } from '../utils/zkeyDownload';
import { generateCircuitInputsInApp } from '../utils/generateInputsInApp';
interface ProveScreenProps {
Expand All @@ -37,7 +37,7 @@ const ProveScreen: React.FC<ProveScreenProps> = ({ setSheetRegisterIsOpen }) =>

const [socket, setSocket] = useState<Socket | null>(null);
const [isConnecting, setIsConnecting] = useState(false);
const { signatureAlgorithm, hashFunction } = getSignatureAlgorithm(passportData.dsc as string);
const { signatureAlgorithm, hashFunction } = parseDSC(passportData.dsc);
const circuitName = getCircuitName(selectedApp.circuit, signatureAlgorithm, hashFunction);

const waitForSocketConnection = (socket: Socket): Promise<void> => {
Expand Down
4 changes: 2 additions & 2 deletions app/src/stores/userStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import {
DEFAULT_DOB,
DEFAULT_DOE,
} from '@env';
import { mockPassportData_sha256_rsa_65537 } from '../../../common/src/constants/mockPassportData';
import { PassportData, Proof } from '../../../common/src/utils/types';
import * as Keychain from 'react-native-keychain';
import * as amplitude from '@amplitude/analytics-react-native';
import { loadPassportData, loadSecret, loadSecretOrCreateIt, storePassportData } from '../utils/keychain';
import { generateDscSecret } from '../../../common/src/utils/csca';
import { genMockPassportData } from '../../../common/src/utils/genMockPassportData';

interface UserState {
passportNumber: string
Expand Down Expand Up @@ -43,7 +43,7 @@ const useUserStore = create<UserState>((set, get) => ({
dateOfExpiry: DEFAULT_DOE ?? "",
dscSecret: null,
registered: false,
passportData: mockPassportData_sha256_rsa_65537,
passportData: genMockPassportData("rsa_sha256", "FRA", "19900101", "20300101"),
secret: "",
cscaProof: null,
localProof: null,
Expand Down
13 changes: 11 additions & 2 deletions app/src/utils/generateInputsInApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
import { AppType } from '../../../common/src/utils/appType';
import { PassportData } from '../../../common/src/utils/types';
import { generateCircuitInputsProve, generateCircuitInputsRegister } from '../../../common/src/utils/generateInputs';
import { DEFAULT_MAJORITY, k_dsc, n_dsc, PASSPORT_ATTESTATION_ID } from '../../../common/src/constants/constants';
import { DEFAULT_MAJORITY, k_dsc, k_dsc_ecdsa, n_dsc, n_dsc_ecdsa, PASSPORT_ATTESTATION_ID } from '../../../common/src/constants/constants';
import { revealBitmapFromAttributes } from '../../../common/src/utils/revealBitmap';
import useUserStore from '../stores/userStore';
import { ArgumentsProve } from '../../../common/src/utils/appType'
import { parseDSC } from '../../../common/src/utils/handleCertificate';

export const generateCircuitInputsInApp = (
passportData: PassportData,
Expand All @@ -14,7 +15,15 @@ export const generateCircuitInputsInApp = (
switch (app.circuit) {
case 'register': {
const { secret, dscSecret } = useUserStore.getState();
return generateCircuitInputsRegister(secret, dscSecret as string, PASSPORT_ATTESTATION_ID, passportData, n_dsc, k_dsc);
const { signatureAlgorithm } = parseDSC(passportData.dsc);
return generateCircuitInputsRegister(
secret,
dscSecret as string,
PASSPORT_ATTESTATION_ID,
passportData,
signatureAlgorithm === 'ecdsa' ? n_dsc_ecdsa : n_dsc,
signatureAlgorithm === 'ecdsa' ? k_dsc_ecdsa : k_dsc,
);
}
case 'prove': {
const disclosureOptions = (app.arguments as ArgumentsProve).disclosureOptions || {};
Expand Down
44 changes: 5 additions & 39 deletions app/src/utils/nfcScanner.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import { NativeModules, Platform } from 'react-native';
// @ts-ignore
import PassportReader from 'react-native-passport-reader';
import { toStandardName } from '../../../common/src/utils/formatNames';
import { checkInputs } from '../utils/utils';
import { PassportData } from '../../../common/src/utils/types';
import forge from 'node-forge';
import { Buffer } from 'buffer';
import * as amplitude from '@amplitude/analytics-react-native';
import useUserStore from '../stores/userStore';
import useNavigationStore from '../stores/navigationStore';
import { getSignatureAlgorithm, getCircuitName } from '../../../common/src/utils/handleCertificate';
import { parseDSC, getCircuitName } from '../../../common/src/utils/handleCertificate';
import { downloadZkey } from './zkeyDownload';

export const scan = async (setModalProofStep: (modalProofStep: number) => void) => {
Expand Down Expand Up @@ -121,7 +120,6 @@ const handleResponseIOS = async (

const eContentBase64 = parsed.eContentBase64; // this is what we call concatenatedDataHashes in android world
const signedAttributes = parsed.signedAttributes; // this is what we call eContent in android world
const signatureAlgorithm = parsed.signatureAlgorithm;
const mrz = parsed.passportMRZ;
const signatureBase64 = parsed.signatureBase64;
console.log('dataGroupsPresent', parsed.dataGroupsPresent)
Expand All @@ -131,19 +129,12 @@ const handleResponseIOS = async (
console.log('isChipAuthenticationSupported', parsed.isChipAuthenticationSupported)
console.log('residenceAddress', parsed.residenceAddress)
console.log('passportPhoto', parsed.passportPhoto.substring(0, 100) + '...')
console.log('signatureAlgorithm', signatureAlgorithm)
console.log('encapsulatedContentDigestAlgorithm', parsed.encapsulatedContentDigestAlgorithm)
console.log('parsed.documentSigningCertificate', parsed.documentSigningCertificate)
const pem = JSON.parse(parsed.documentSigningCertificate).PEM.replace(/\n/g, '');
const certificate = forge.pki.certificateFromPem(pem);
console.log('pem', pem)

try {
const publicKey = certificate.publicKey;
//console.log('publicKey', publicKey);

const modulus = (publicKey as any).n.toString(10);

const eContentArray = Array.from(Buffer.from(signedAttributes, 'base64'));
const signedEContentArray = eContentArray.map(byte => byte > 127 ? byte - 256 : byte);

Expand All @@ -153,24 +144,18 @@ const handleResponseIOS = async (
const encryptedDigestArray = Array.from(Buffer.from(signatureBase64, 'base64')).map(byte => byte > 127 ? byte - 256 : byte);

//amplitude.track('Sig alg before conversion: ' + signatureAlgorithm);
console.log('signatureAlgorithm before conversion', signatureAlgorithm);
const passportData = {
mrz,
signatureAlgorithm: toStandardName(signatureAlgorithm),
dsc: pem,
pubKey: {
modulus: modulus,
exponent: (publicKey as any).e.toString(10),
},
dataGroupHashes: concatenatedDataHashesArraySigned,
eContent: signedEContentArray,
encryptedDigest: encryptedDigestArray,
photoBase64: "data:image/jpeg;base64," + parsed.passportPhoto,
mockUser: false
};
useUserStore.getState().registerPassportData(passportData)
const sigAlgName = getSignatureAlgorithm(pem);
const circuitName = getCircuitName("prove", sigAlgName.signatureAlgorithm, sigAlgName.hashFunction);
const { signatureAlgorithm, hashFunction } = parseDSC(pem);
const circuitName = getCircuitName("prove", signatureAlgorithm, hashFunction);
downloadZkey(circuitName as any);
useNavigationStore.getState().setSelectedTab("next");
} catch (e: any) {
Expand All @@ -191,10 +176,6 @@ const handleResponseAndroid = async (
) => {
const {
mrz,
signatureAlgorithm,
modulus,
curveName,
publicKeyQ,
eContent,
encryptedDigest,
photo,
Expand All @@ -210,22 +191,9 @@ const handleResponseAndroid = async (
//amplitude.track('Sig alg before conversion: ' + signatureAlgorithm);

const pem = "-----BEGIN CERTIFICATE-----" + documentSigningCertificate + "-----END CERTIFICATE-----"

const cert = forge.pki.certificateFromPem(pem);
console.log('cert', cert);
const publicKey = cert.publicKey;
console.log('publicKey', publicKey);

const passportData: PassportData = {
mrz: mrz.replace(/\n/g, ''),
signatureAlgorithm: toStandardName(signatureAlgorithm),
dsc: pem,
pubKey: {
modulus: modulus,
exponent: (publicKey as any).e.toString(10),
curveName: curveName,
publicKeyQ: publicKeyQ,
},
dataGroupHashes: JSON.parse(encapContent),
eContent: JSON.parse(eContent),
encryptedDigest: JSON.parse(encryptedDigest),
Expand All @@ -240,8 +208,6 @@ const handleResponseAndroid = async (
}, null, 2));

console.log('mrz', passportData.mrz);
console.log('signatureAlgorithm', passportData.signatureAlgorithm);
console.log('pubKey', passportData.pubKey);
console.log('dataGroupHashes', passportData.dataGroupHashes);
console.log('eContent', passportData.eContent);
console.log('encryptedDigest', passportData.encryptedDigest);
Expand All @@ -255,8 +221,8 @@ const handleResponseAndroid = async (
console.log("documentSigningCertificate", documentSigningCertificate)
useUserStore.getState().registerPassportData(passportData)

const sigAlgName = getSignatureAlgorithm(pem);
const circuitName = getCircuitName("prove", sigAlgName.signatureAlgorithm, sigAlgName.hashFunction);
const { signatureAlgorithm, hashFunction } = parseDSC(pem);
const circuitName = getCircuitName("prove", signatureAlgorithm, hashFunction);
downloadZkey(circuitName as any);
useNavigationStore.getState().setSelectedTab("next");
};
6 changes: 3 additions & 3 deletions app/src/utils/qrCode.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { NativeModules, Platform } from "react-native";
import { AppType, reconstructAppType } from "../../../common/src/utils/appType";
import useNavigationStore from '../stores/navigationStore';
import { getCircuitName, getSignatureAlgorithm } from "../../../common/src/utils/handleCertificate";
import { getCircuitName, parseDSC } from "../../../common/src/utils/handleCertificate";
import useUserStore from "../stores/userStore";
import { downloadZkey } from "./zkeyDownload";

Expand Down Expand Up @@ -56,8 +56,8 @@ const handleQRCodeScan = (result: string, toast: any, setSelectedApp: any, setSe
console.log(result);
const parsedJson = JSON.parse(result);
const app: AppType = reconstructAppType(parsedJson);
const dsc = useUserStore.getState().passportData?.dsc;
const sigAlgName = getSignatureAlgorithm(dsc!);
const dsc = useUserStore.getState().passportData.dsc;
const sigAlgName = parseDSC(dsc!);
const circuitName = getCircuitName(app.circuit, sigAlgName.signatureAlgorithm, sigAlgName.hashFunction);
downloadZkey(circuitName as any);
setSelectedApp(app);
Expand Down
6 changes: 1 addition & 5 deletions app/src/utils/registration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,7 @@ export async function isCommitmentRegistered(secret: string, passportData: Passp

imt.import(response.data);

const pubkey_leaf = getLeaf({
signatureAlgorithm: passportData.signatureAlgorithm,
modulus: passportData.pubKey!.modulus,
exponent: passportData.pubKey!.exponent,
});
const pubkey_leaf = getLeaf(passportData);

const formattedMrz = formatMrz(passportData.mrz);
const mrz_bytes = packBytes(formattedMrz);
Expand Down
4 changes: 2 additions & 2 deletions app/src/utils/transactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import groth16ExportSolidityCallData from './snarkjs';
import contractAddresses from "../../deployments/deployed_addresses.json";
import registerArtefacts from "../../deployments/artifacts/Deploy_Registry#OpenPassportRegister.json";
import sbtArtefacts from "../../deployments/artifacts/Deploy_Registry#SBT.json";
import { CHAIN_NAME, RELAYER_URL, RPC_URL, SignatureAlgorithm } from '../../../common/src/constants/constants';
import { CHAIN_NAME, RELAYER_URL, RPC_URL, SignatureAlgorithmIndex } from '../../../common/src/constants/constants';
import { Proof } from "../../../common/src/utils/types";
import { formatCallData_disclose, formatCallData_dsc, formatCallData_register } from "../../../common/src/utils/formatCallData";

export const sendRegisterTransaction = async (
proof: Proof,
cscaProof: Proof,
sigAlgIndex: SignatureAlgorithm
sigAlgIndex: SignatureAlgorithmIndex
) => {
const provider = new ethers.JsonRpcProvider(RPC_URL);

Expand Down
11 changes: 3 additions & 8 deletions circuits/tests/disclose/disclose.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { assert, expect } from 'chai';
import path from 'path';
import { wasm as wasm_tester } from 'circom_tester';
import { mockPassportData_sha256_rsa_65537 } from '../../../common/src/constants/mockPassportData';
import { formatMrz, packBytes } from '../../../common/src/utils/utils';
import {
attributeToPosition,
COMMITMENT_TREE_DEPTH,
PASSPORT_ATTESTATION_ID,
} from '../../../common/src/constants/constants';
import { poseidon1, poseidon2, poseidon6 } from 'poseidon-lite';
Expand All @@ -14,13 +12,14 @@ import { getLeaf } from '../../../common/src/utils/pubkeyTree';
import { generateCircuitInputsDisclose } from '../../../common/src/utils/generateInputs';
import { formatAndUnpackReveal } from '../../../common/src/utils/revealBitmap';
import crypto from 'crypto';
import { genMockPassportData } from '../../../common/src/utils/genMockPassportData';

describe('Disclose', function () {
this.timeout(0);
let inputs: any;
let circuit: any;
let w: any;
let passportData = mockPassportData_sha256_rsa_65537;
const passportData = genMockPassportData('rsa_sha256', 'FRA', '000101', '300101');
let tree: any;

before(async () => {
Expand All @@ -43,11 +42,7 @@ describe('Disclose', function () {
const scope = '@coboyApp';

// compute the commitment and insert it in the tree
const pubkey_leaf = getLeaf({
signatureAlgorithm: passportData.signatureAlgorithm,
modulus: passportData.pubKey.modulus,
exponent: passportData.pubKey.exponent,
}).toString();
const pubkey_leaf = getLeaf(passportData).toString();
const mrz_bytes = packBytes(formatMrz(passportData.mrz));
const commitment = poseidon6([
secret,
Expand Down
Loading

0 comments on commit 7e0601a

Please sign in to comment.