Skip to content

Commit

Permalink
refactor ProveScreen
Browse files Browse the repository at this point in the history
  • Loading branch information
remicolin committed Aug 27, 2024
1 parent 32209f3 commit c36a691
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 115 deletions.
4 changes: 0 additions & 4 deletions app/src/components/CustomButton.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import React from 'react';
import { Button, Text } from 'tamagui';
import { bgBlue, bgGreen, textBlack } from '../utils/colors';
import useNavigationStore from '../stores/navigationStore';

interface CustomButtonProps {
text: string;
Expand All @@ -15,9 +14,6 @@ interface CustomButtonProps {
}

const CustomButton: React.FC<CustomButtonProps> = ({ text, onPress, Icon, bgColor, h, isDisabled, disabledOnPress, blueVariant }) => {
const {
toast,
} = useNavigationStore();
return (
<Button bg={bgColor ? bgColor : blueVariant ? bgBlue : bgGreen} h={blueVariant ? "$8" : "$4.5"} borderRadius="$10" mx="$3" onPress={isDisabled ? disabledOnPress : onPress}>
{Icon && <Button.Icon>{Icon}</Button.Icon>}
Expand Down
5 changes: 0 additions & 5 deletions app/src/screens/CameraScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,6 @@ const CameraScreen: React.FC<CameraScreenProps> = ({ setSheetIsOpen }) => {
<Text ml="$2" mt="$8" fontSize="$8" color={textBlack}>Open your passport on the <Text style={{ textDecorationLine: 'underline', textDecorationColor: bgGreen }}>main page</Text> to scan it.</Text>
<Text ml="$2" mt="$2" fontSize="$8" color={textBlack} style={{ opacity: 0.7 }}>Your data never leaves your device.</Text>
<XStack f={1} />

{/* <XStack justifyContent='center' alignItems='center' gap="$1.5">
<ShieldCheck color={textBlack} size={14} />
<Text color={textBlack} fontSize="$4">private and secured</Text>
</XStack> */}
</YStack>
<XStack p="$3" onPress={() => setSelectedTab("mock")} ai="center" jc="center">
<Text mt="$5" fontSize="$3" alignSelf='center' w="80%" ai="center" textAlign="center" color={textBlack}>
Expand Down
117 changes: 14 additions & 103 deletions app/src/screens/ProveScreen.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,16 @@
import React, { useState, useEffect } from 'react';
import { YStack, XStack, Text, Input, Button, Spinner, Image, useWindowDimensions, ScrollView, Fieldset } from 'tamagui';
import { Check, CheckCircle, CheckCircle2, Share, } from '@tamagui/lucide-icons';
import { attributeToPosition, DEFAULT_MAJORITY, } from '../../../common/src/constants/constants';
import USER from '../images/user.png'
import { bgGreen, borderColor, componentBgColor, componentBgColor2, separatorColor, textBlack, textColor1, textColor2 } from '../utils/colors';
import { ethers } from 'ethers';
import { Platform } from 'react-native';
import { formatAttribute, Steps } from '../utils/utils';
import { downloadZkey } from '../utils/zkeyDownload';
import { YStack, XStack, Text, Spinner, useWindowDimensions } from 'tamagui';
import { CheckCircle } from '@tamagui/lucide-icons';
import { DEFAULT_MAJORITY, } from '../../../common/src/constants/constants';
import { bgGreen, separatorColor, textBlack } from '../utils/colors';
import useUserStore from '../stores/userStore';
import useNavigationStore from '../stores/navigationStore';
import { AppType } from '../../../common/src/utils/appType';
import CustomButton from '../components/CustomButton';
import { generateCircuitInputsDisclose, generateCircuitInputsProve } from '../../../common/src/utils/generateInputs';
import { PASSPORT_ATTESTATION_ID } from '../../../common/src/constants/constants';
import axios from 'axios';
import { stringToNumber } from '../../../common/src/utils/utils';
import { generateCircuitInputsProve } from '../../../common/src/utils/generateInputs';
import { revealBitmapFromAttributes } from '../../../common/src/utils/revealBitmap';
import { getTreeFromTracker } from '../../../common/src/utils/pubkeyTree';
import { generateProof } from '../utils/prover';
import { formatProof, generateProof } from '../utils/prover';
import io, { Socket } from 'socket.io-client';
import { poseidon1 } from 'poseidon-lite';

interface ProveScreenProps {
setSheetRegisterIsOpen: (value: boolean) => void;
Expand All @@ -30,22 +20,15 @@ const ProveScreen: React.FC<ProveScreenProps> = ({ setSheetRegisterIsOpen }) =>
const [generatingProof, setGeneratingProof] = useState(false);
const selectedApp = useNavigationStore(state => state.selectedApp) as AppType;
const {
hideData,
isZkeyDownloading,
step,
toast,
setSelectedTab
} = useNavigationStore()

const {
secret,
setProofVerificationResult
} = useUserStore()

const [proofStatus, setProofStatus] = useState<string>('');

const [socket, setSocket] = useState<Socket | null>(null);

const [isConnecting, setIsConnecting] = useState(false);

const waitForSocketConnection = (socket: Socket): Promise<void> => {
Expand Down Expand Up @@ -82,7 +65,6 @@ const ProveScreen: React.FC<ProveScreenProps> = ({ setSheetRegisterIsOpen }) =>
newSocket.on('proof_verification_result', (result) => {
console.log('Proof verification result:', result);
setProofVerificationResult(JSON.parse(result));
setProofStatus(`Proof verification result: ${result}`);
console.log("result", result);
setSelectedTab(JSON.parse(result).valid ? "valid" : "wrong");
});
Expand All @@ -99,89 +81,40 @@ const ProveScreen: React.FC<ProveScreenProps> = ({ setSheetRegisterIsOpen }) =>
setIsConnecting(true);
setGeneratingProof(true);

console.log("handleProve. selectedApp", selectedApp)

if (!socket) {
throw new Error('Socket not initialized');
}

await waitForSocketConnection(socket);

setIsConnecting(false);
setProofStatus('Generating proof...');
socket.emit('proof_generation_start', { sessionId: selectedApp.userId });

// const tree = await getTreeFromTracker();

// const inputs = generateCircuitInputsDisclose(
// secret,
// PASSPORT_ATTESTATION_ID,
// passportData,
// tree as any,
// (selectedApp.disclosureOptions && selectedApp.disclosureOptions.older_than) ? selectedApp.disclosureOptions.older_than : DEFAULT_MAJORITY,
// revealBitmapFromAttributes(selectedApp.disclosureOptions as any),
// selectedApp.scope,
// stringToNumber(selectedApp.userId).toString()
// );

const user_identifier = '0xE6E4b6a802F2e0aeE5676f6010e0AF5C9CDd0a50';

const inputs = generateCircuitInputsProve(
passportData,
64, 32,
selectedApp.scope,
revealBitmapFromAttributes(selectedApp.disclosureOptions as any),
(selectedApp.disclosureOptions && selectedApp.disclosureOptions.older_than) ? selectedApp.disclosureOptions.older_than : DEFAULT_MAJORITY,
user_identifier
selectedApp.userId
);

console.log("inputs", inputs);
const localProof = await generateProof(
const rawDscProof = await generateProof(
selectedApp.circuit,
inputs,
);

setProofStatus('Sending proof to verification...');
// console.log("localProof", localProof);

const dscProof = formatProof(rawDscProof);
// Send the proof via WebSocket
const formattedLocalProof = {
const response = {
dsc: passportData.dsc,
proof: {
pi_a: [
localProof.proof.a[0],
localProof.proof.a[1],
"1"
],
pi_b: [
[localProof.proof.b[0][0], localProof.proof.b[0][1]],
[localProof.proof.b[1][0], localProof.proof.b[1][1]],
["1", "0"]
],
pi_c: [
localProof.proof.c[0],
localProof.proof.c[1],
"1"
],
protocol: "groth16",
curve: "bn128"
},
publicSignals: (localProof as any).pub_signals
dscProof: dscProof
};
console.log("formattedLocalProof", formattedLocalProof);

socket.emit('proof_generated', { sessionId: selectedApp.userId, proof: formattedLocalProof });

// Wait for verification result
const verificationResult = await new Promise((resolve) => {
socket.once('proof_verification_result', resolve);
});
console.log("response", response);

setProofStatus(`Proof verification result: ${(verificationResult)}`);
socket.emit('proof_generated', { sessionId: selectedApp.userId, proof: response });

} catch (error) {
console.error('Error in handleProve:', error);
setProofStatus(`Error: ${error || 'An unknown error occurred'}`);
} finally {
setGeneratingProof(false);
setIsConnecting(false);
Expand All @@ -193,16 +126,6 @@ const ProveScreen: React.FC<ProveScreenProps> = ({ setSheetRegisterIsOpen }) =>
passportData,
} = useUserStore();

const handleDisclosureChange = (field: string) => {
const requiredOrOptional = selectedApp.disclosureOptions[field as keyof typeof selectedApp.disclosureOptions];
if (requiredOrOptional === 'required') {
return;
}
};
const { height } = useWindowDimensions();

useEffect(() => {
}, [])

const disclosureFieldsToText = (key: string, value: string = "") => {
if (key === 'older_than') {
Expand All @@ -216,13 +139,11 @@ const ProveScreen: React.FC<ProveScreenProps> = ({ setSheetRegisterIsOpen }) =>

return (
<YStack f={1} p="$3">

{Object.keys(selectedApp.disclosureOptions as any).length > 0 ? <YStack mt="$4">
<Text fontSize="$9">
<Text fow="bold" style={{ textDecorationLine: 'underline', textDecorationColor: bgGreen }}>{selectedApp.name}</Text> is requesting you to prove the following information.
</Text>
<Text mt="$3" fontSize="$8" color={textBlack} style={{ opacity: 0.9 }}>

No <Text style={{ textDecorationLine: 'underline', textDecorationColor: bgGreen }}>other</Text> information than the one selected below will be shared with {selectedApp.name}.
</Text>
</YStack> :
Expand All @@ -233,14 +154,11 @@ const ProveScreen: React.FC<ProveScreenProps> = ({ setSheetRegisterIsOpen }) =>

<YStack mt="$6">
{selectedApp && Object.keys(selectedApp.disclosureOptions as any).map((key) => {
const key_ = key;
const keyFormatted = key_.replace(/_/g, ' ').split(' ').map((word: string) => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');

return (
<XStack key={key} gap="$3" mb="$3" ml="$3" >
<CheckCircle size={16} mt="$1.5" />
<Text fontSize="$7" color={textBlack} w="85%">
{disclosureFieldsToText(key_, (selectedApp.disclosureOptions as any)[key_])}
{disclosureFieldsToText(key, (selectedApp.disclosureOptions as any)[key])}
</Text>
</XStack>
);
Expand All @@ -263,13 +181,6 @@ const ProveScreen: React.FC<ProveScreenProps> = ({ setSheetRegisterIsOpen }) =>
})}
/>


{/* {proofStatus && (
<Text mt="$4" fontSize="$6" color={textBlack}>
{proofStatus}
</Text>
)} */}

</YStack >
);
};
Expand Down
29 changes: 26 additions & 3 deletions app/src/utils/prover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,6 @@ export const generateProof = async (
} else {
const parsedResponse = JSON.parse(response);
console.log('parsedResponse', parsedResponse);
console.log('parsedResponse.proof:', parsedResponse.proof);
console.log('parsedResponse.inputs:', parsedResponse.inputs);

return {
proof: parsedResponse.proof,
Expand All @@ -50,4 +48,29 @@ export const generateProof = async (
console.log('err', err);
throw new Error(err);
}
};
};

export const formatProof = (rawProof: any) => {
return {
proof: {
pi_a: [
rawProof.proof.a[0],
rawProof.proof.a[1],
"1"
],
pi_b: [
[rawProof.proof.b[0][0], rawProof.proof.b[0][1]],
[rawProof.proof.b[1][0], rawProof.proof.b[1][1]],
["1", "0"]
],
pi_c: [
rawProof.proof.c[0],
rawProof.proof.c[1],
"1"
],
protocol: "groth16",
curve: "bn128"
},
publicSignals: (rawProof as any).pub_signals
}
}

0 comments on commit c36a691

Please sign in to comment.