Skip to content

Commit

Permalink
Deploy claim issuer script working. Validations done and some perfect…
Browse files Browse the repository at this point in the history
…ions done into different screens. Last commit before presentation
  • Loading branch information
49513 - Diogo Rodrigues committed Jul 16, 2024
1 parent baeed71 commit eb274b4
Show file tree
Hide file tree
Showing 12 changed files with 1,392 additions and 173 deletions.
1 change: 1 addition & 0 deletions code/app/(tabs)/home/components/certificateModal.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ const styles = StyleSheet.create({
fontFamily: 'Poppins-Bold',
textAlign: 'center',
marginTop: 20,
color: Colors.url,
},
});

Expand Down
39 changes: 22 additions & 17 deletions code/app/(tabs)/home/home.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,24 +78,18 @@ const HomeScreen = () => {

const getCertificates = async () => {
try {
setSelectedCertificate(null);
setIsLoading(true);
const userWallet = await getValueFor('wallet');

const signer = useRpcProvider(config.rpc, config.deployer.privateKey);

console.log('User Wallet:', userWallet);

const identityFactory = getContractAt(config.identityFactory.address, config.identityFactory.abi, signer);
const userIdentity = await getIdentity(userWallet.address, identityFactory, signer);

const certificates = await getClaimsByTopic(userIdentity, CLAIM_TOPICS_OBJ.CERTIFICATE);
const institutions = await getClaimsByTopic(userIdentity, CLAIM_TOPICS_OBJ.INSTITUTION);
const students = await getClaimsByTopic(userIdentity, CLAIM_TOPICS_OBJ.STUDENT);

//console.log('Certificates:', certificates);
//console.log('Institutions:', institutions);
//console.log('Students:', students);
setIsLoading(false);
return certificates.map((certificate, index) => {
const institution = institutions.find(inst => inst.issuer.trim() === certificate.issuer.trim());
Expand Down Expand Up @@ -181,7 +175,8 @@ const HomeScreen = () => {

// Create the user wallet object (ethers.Wallet)
const userWallet = getWallet(savedWallet.privateKey, provider);
if (userWallet.address.toLowerCase() !== savedWallet.address) {
console.log('User Wallet:', userWallet);
if (!userWallet || userWallet.address.toLowerCase() !== savedWallet.address) {
const onCancel = () => {
setModalVisible(false);
setIsSubmitting(false);
Expand All @@ -203,28 +198,30 @@ const HomeScreen = () => {
// Add the key of the claim issuer that matches the institution code to the identity of the student that requested the certificate
// With this the student is allowing the institution to emit certificates on his behalf
const issuers = await trustedIR.getTrustedIssuersForClaimTopic(ethers.id(CLAIM_TOPICS_OBJ.INSTITUTION));
console.log('Issuers:', issuers);

let issuerFound = false;
for (const issuer of issuers) {
console.log('Issuer:', issuer);
for (const institution of config.institutions) {
if (
institution.address === issuer &&
institution.institutionID.toString() === form.institutionCode
) {
console.log('Institution:', institution);
if (institution.address === issuer && institution.institutionID === form.institutionCode) {
issuerFound = true;
const issuerWallet = getWallet(institution.wallet.privateKey, provider);
const issuerContract = getContractAt(institution.address, institution.abi, issuerWallet);
const issuerKeys = await issuerContract.getKeysByPurpose(3);
const userKeys = await userIdentity.getKeysByPurpose(3);
console.log('User Keys: ', userKeys);
if (!userKeys.includes(issuerKeys[0])) {
await addKeyToIdentity(userIdentity, userWallet, issuerWallet, 3, 1);
}
} else {
Alert.alert('Warning', 'Institution not found.');
setIsSubmitting(false);
return;
}
}
}
if (!issuerFound) {
Alert.alert('Warning', 'Institution not found.');
setIsSubmitting(false);
return;
}

// Self assign the student number and name (CLAIM_TOPICS: STUDENT)
const studentClaim = JSON.stringify({
Expand All @@ -244,6 +241,11 @@ const HomeScreen = () => {
};

const handleCertificatePress = certificate => {
console.log(certificate);
if(certificate.uri === 'Certificate hash') {
Alert.alert('Warning', 'URL not available yet. Contact the institution for more information.');
return;
}
setSelectedCertificate(certificate);
setCertificateModalVisible(true);
};
Expand Down Expand Up @@ -315,7 +317,10 @@ const HomeScreen = () => {
{selectedCertificate && (
<PasswordModal
visible={certificateModalVisible}
onDismiss={() => setCertificateModalVisible(false)}
onDismiss={() => {
setCertificateModalVisible(false);
setSelectedCertificate(null);
}}
encryptedURI={selectedCertificate.uri}
/>
)}
Expand Down
78 changes: 54 additions & 24 deletions code/app/(tabs)/validation.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,42 +18,73 @@ import { useRpcProvider } from '@/services/ethereum/scripts/utils/useRpcProvider
import { IconButton } from 'react-native-paper';
import * as DocumentPicker from 'expo-document-picker';
import * as FileSystem from 'expo-file-system';
import { getValueFor } from '@/services/storage/storage';
// import QRCodeScanner from 'react-native-qrcode-scanner';

const Validation = () => {
const [valid, setValid] = useState(false);
const [showModal, setShowModal] = useState(false);
const [certificateLink, setCertificateLink] = useState('');
const [hashedContent, setHashedContent] = useState('');
const [content, setContent] = useState('');
const [userAddress, setUserAddress] = useState('');
const [isUserAuthenticated, setIsUserAuthenticated] = useState(false);

const handleQRCodeScan = event => {
// Process the scanned QR code (event.data) as needed
console.log('Scanned QR code:', event.data);
setCertificateLink(event.data);
};

useEffect(() => {
const isUserAuthenticated = async () => {
const userWallet = await getValueFor('wallet');
console.log(userWallet);
userWallet.address ? setIsUserAuthenticated(true) : setIsUserAuthenticated(false);
};
isUserAuthenticated();
}, []);

// If the input of link is empty, clean the content
useEffect(() => {
if (!certificateLink) {
setContent('');
}
}, [certificateLink]);

const handleValidate = async () => {
// Validate the claiom that has the link to the certificate (claimTopic CERTIFICATE)
// If the claim is valid, and hash of the certificate is the same as the hash of the certificate in the claim uri field, setValid(true)
// Otherwise, setValid(false)
try {
if (!userAddress || !certificateLink) {
Alert.alert('Error', 'Please fill in all fields');
return;
} else if (!content && !certificateLink) {
Alert.alert('Error', 'Please upload a certificate or insert a URL');
return;
}
const signer = useRpcProvider(config.rpc, config.deployer.privateKey);

const identityFactory = getContractAt(config.identityFactory.address, config.identityFactory.abi, signer);
console.log(userAddress);
const userIdentity = await getIdentity(userAddress, identityFactory, signer);
if (userIdentity) {
const certificates = await getClaimsByTopic(userIdentity, CLAIM_TOPICS_OBJ.CERTIFICATE);
if(certificates.length === 0) {
console.log('Certificates:', certificates);
if (certificates.length === 0) {
Alert.alert('Error', 'No certificates found');
return;
}
const claimUri = certificates[0].uri;
console.log('claimUri:', claimUri);
if (claimUri === hash(certificateLink) || claimUri === hash(hashedContent)) {
setValid(true);
} else {
let valid = false;
for (const certificate of certificates) {
const claimUri = certificate.uri;
if (claimUri === hash(certificateLink) || claimUri === hash(content)) {
setValid(true);
valid = true;
break;
}
}
if (!valid) {
setValid(false);
}
setShowModal(true);
Expand All @@ -75,13 +106,19 @@ const Validation = () => {
const fileContents = await FileSystem.readAsStringAsync(uri, {
encoding: FileSystem.EncodingType.Base64,
});
const hashedContent = hash(fileContents);
setHashedContent(hashedContent);
setContent(fileContents);
setCertificateLink(name);
onChange(result.uri);
}
};

const handleImportOwnWallet = async () => {
const userWallet = await getValueFor('wallet');
if (userWallet) {
setUserAddress(userWallet.address);
}
};

return (
<>
<Background
Expand All @@ -99,7 +136,14 @@ const Validation = () => {
icon="account"
value={userAddress}
onChange={address => setUserAddress(address)}
outSideIconComponent={<IconButton icon="" color="black" size={20} onPress={() => {}} />}
outSideIconComponent={
<IconButton
icon={isUserAuthenticated ? 'account-plus' : ''}
color="black"
size={20}
onPress={handleImportOwnWallet}
/>
}
/>
<FormField
label="Insert Certificate Link"
Expand All @@ -117,20 +161,6 @@ const Validation = () => {
/>

<Text style={styles.or}>OR</Text>
{/* <QRCodeScanner
onRead={handleQRCodeScan}
showMarker={true}
containerStyle={{ marginTop: 16 }}
markerStyle={{ borderColor: 'red', borderRadius: 10 }}
reactivate={true}
permissionDialogMessage="Need permission to access camera"
reactivateTimeout={2000}
bottomContent={
<Text style={{ color: 'white', fontSize: 20, marginBottom: 50 }}>
Scan QR code to insert link
</Text>
}
/> */}
<ActionButton
text="Scan QR Code"
buttonStyle={styles.qrButton}
Expand Down
9 changes: 3 additions & 6 deletions code/app/emission.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ import * as DocumentPicker from 'expo-document-picker';
import * as FileSystem from 'expo-file-system';
import { ethers } from 'ethers';
import { encrypt } from '@/services/ethereum/scripts/utils/encryption/aes-256';
import hash from '@/services/ethereum/scripts/utils/encryption/hash';

const Emission = () => {
const [isSubmitting, setSubmitting] = useState(false);
const [fileInfo, setFileInfo] = useState(null);
const [fileHash, setFileHash] = useState(null);
const [form, setForm] = useState({
registrationCode: '',
courseID: '',
Expand Down Expand Up @@ -94,7 +94,7 @@ const Emission = () => {
certificate: form.certificateUri ? encrypt(form.certificateUri, form.password) : 'Certificate hash',
});

const certificateClaimUri = form.certificateUri ? form.certificateUri : fileHash;
const certificateClaimUri = form.certificateUri ? form.certificateUri : fileInfo.fileContents;

console.log('certificate claim:', certificateClaim);
// Claim institution (Institution ID, Course ID)
Expand Down Expand Up @@ -157,9 +157,6 @@ const Emission = () => {
});

setFileInfo({ uri, name, size, fileContents });

const hash = hash(fileContents);
setFileHash(hash);
}
} catch (error) {
console.error('Error picking document:', error);
Expand Down Expand Up @@ -279,7 +276,7 @@ const styles = StyleSheet.create({
},
body: {
marginTop: -20,
marginBottom: 20,
marginBottom: 40,
},
title: {
paddingTop: 5,
Expand Down
Loading

0 comments on commit eb274b4

Please sign in to comment.