Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Web3 ID logging #354

Merged
merged 2 commits into from
Aug 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { APIVerifiableCredential } from '@concordium/browser-wallet-api-helpers'
import { networkConfigurationAtom } from '@popup/store/settings';
import { MetadataUrl } from '@concordium/browser-wallet-api-helpers/lib/wallet-api-types';
import { parse } from '@shared/utils/payload-helpers';
import { logError } from '@shared/utils/log-helpers';
import { VerifiableCredentialCard } from '../VerifiableCredential/VerifiableCredentialCard';

type Props = {
Expand Down Expand Up @@ -81,7 +82,10 @@ export default function AddWeb3IdCredential({ onAllow, onReject }: Props) {
}
return fetchCredentialMetadata(metadataUrl, controller);
},
() => setError(t('error.metadata')),
(e) => {
setError(t('error.metadata'));
logError(e);
},
[verifiableCredentialMetadata.loading]
);

Expand All @@ -97,7 +101,10 @@ export default function AddWeb3IdCredential({ onAllow, onReject }: Props) {
}
return fetchCredentialSchema({ url: schemaUrl }, controller);
},
() => setError(t('error.schema')),
(e) => {
setError(t('error.schema'));
logError(e);
},
[schemas.loading]
);

Expand Down Expand Up @@ -138,7 +145,10 @@ export default function AddWeb3IdCredential({ onAllow, onReject }: Props) {

return fetchLocalization(currentLanguageLocalization, controller);
},
() => setError('Failed to get localization'),
(e) => {
setError(t('error.localization'));
logError(e);
},
[metadata, i18n]
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const t: typeof en = {
metadata: en.error.metadata,
schema: en.error.schema,
attribute: en.error.attribute,
localization: en.error.localization,
},
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const t = {
metadata: 'We are unable to load the metadata for the credential.',
schema: 'We are unable to load the schema specification for the credential.',
attribute: 'The received credential is missing one or more required attributes ({{ attributeKeys }})',
localization: 'Failed to get localization',
},
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import {
import { AsyncWrapper } from '@popup/store/utils';
import { ConcordiumGRPCClient } from '@concordium/web-sdk';
import { useTranslation } from 'react-i18next';
import { noOp } from 'wallet-common-helpers';
import { logError } from '@shared/utils/log-helpers';

/**
* Retrieve the on-chain credential status for a verifiable credential in a CIS-4 credential registry contract.
Expand All @@ -36,7 +36,10 @@ export function useCredentialStatus(credential: VerifiableCredential) {
useEffect(() => {
getVerifiableCredentialStatus(client, credential.id)
.then(setStatus)
.catch(() => setStatus(VerifiableCredentialStatus.Pending));
.catch((e) => {
setStatus(VerifiableCredentialStatus.Pending);
logError(e);
});
}, [credential.id, client]);

return status;
Expand Down Expand Up @@ -83,7 +86,7 @@ export function useCredentialEntry(credential?: VerifiableCredential) {
.then((entry) => {
setCredentialEntry(entry);
})
.catch(noOp); // TODO add logging on catch?
.catch(logError);
}
}, [credential?.id, client]);

Expand Down Expand Up @@ -176,7 +179,10 @@ export function useCredentialLocalization(credential?: VerifiableCredential): Lo
// TODO Validate that localization is present for all keys.
setLocalization({ loading: false, result: res });
})
.catch(() => setLocalization({ loading: false }));
.catch((e) => {
setLocalization({ loading: false });
logError(e);
});

return () => {
abortController.abort();
Expand All @@ -199,10 +205,12 @@ export function useIssuerMetadata(issuer: string): IssuerMetadata | undefined {

useEffect(() => {
const registryContractAddress = getCredentialRegistryContractAddress(issuer);
getCredentialRegistryMetadata(client, registryContractAddress).then((res) => {
const abortController = new AbortController();
fetchIssuerMetadata(res.issuerMetadata, abortController).then(setIssuerMetadata);
});
getCredentialRegistryMetadata(client, registryContractAddress)
.then((res) => {
const abortController = new AbortController();
fetchIssuerMetadata(res.issuerMetadata, abortController).then(setIssuerMetadata).catch(logError);
})
.catch(logError);
orhoj marked this conversation as resolved.
Show resolved Hide resolved
}, [client, issuer]);

return issuerMetadata;
Expand Down Expand Up @@ -234,11 +242,13 @@ export function useFetchingEffect<T>(
const abortControllers: AbortController[] = [];

if (!credentials.loading && credentials.value.length !== 0 && !storedData.loading) {
dataFetcher(credentials.value, client, abortControllers, storedData.value).then((result) => {
if (!isCancelled && result.updateReceived) {
setStoredData(result.data);
}
});
dataFetcher(credentials.value, client, abortControllers, storedData.value)
.then((result) => {
if (!isCancelled && result.updateReceived) {
setStoredData(result.data);
}
})
.catch(logError);
}

return () => {
Expand Down
2 changes: 2 additions & 0 deletions packages/browser-wallet/src/popup/store/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import {
storedVerifiableCredentialMetadata,
sessionVerifiableCredentials,
sessionVerifiableCredentialMetadataUrls,
storedLog,
} from '@shared/storage/access';
import { ChromeStorageKey } from '@shared/storage/types';
import { atom, PrimitiveAtom, WritableAtom } from 'jotai';
Expand Down Expand Up @@ -71,6 +72,7 @@ const accessorMap: Record<ChromeStorageKey, StorageAccessor<any>> = {
sessionVerifiableCredentialMetadataUrls,
getGenesisHash
),
[ChromeStorageKey.Log]: storedLog,
};

export function resetOnUnmountAtom<V>(initial: V): PrimitiveAtom<V> {
Expand Down
2 changes: 2 additions & 0 deletions packages/browser-wallet/src/shared/storage/access.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { stringify } from '@concordium/browser-wallet-api/src/util';
import { parse } from '@shared/utils/payload-helpers';
import { VerifiableCredentialMetadata } from '@shared/utils/verifiable-credential-helpers';
import { Log } from '@shared/utils/log-helpers';
import {
ChromeStorageKey,
EncryptedData,
Expand Down Expand Up @@ -205,6 +206,7 @@ const indexedStoredAllowlist = makeIndexedStorageAccessor<Record<string, string[
ChromeStorageKey.Allowlist
);
export const storedAllowlist = useIndexedStorage(indexedStoredAllowlist, getGenesisHash);
export const storedLog = makeStorageAccessor<Log[]>('local', ChromeStorageKey.Log);

export const sessionOpenPrompt = makeStorageAccessor<boolean>('session', ChromeStorageKey.OpenPrompt);
export const sessionPasscode = makeStorageAccessor<string>('session', ChromeStorageKey.Passcode);
Expand Down
1 change: 1 addition & 0 deletions packages/browser-wallet/src/shared/storage/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export enum ChromeStorageKey {
TemporaryVerifiableCredentials = 'tempVerifiableCredentials',
TemporaryVerifiableCredentialMetadataUrls = 'tempVerifiableCredentialMetadataUrls',
Allowlist = 'allowlist',
Log = 'log',
}

export enum Theme {
Expand Down
22 changes: 22 additions & 0 deletions packages/browser-wallet/src/shared/storage/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,28 @@ export async function removeFromList<Type>(
});
}

/*
* Generic method to add an element to list in storage while ensuring that
* the list never grows beyond the provided size. If the list is still small
* enough, then the addition is prepended to the list. If the the list would have
* grown greater than the max size, then the addition is prepended to the list and
* the last element of the list is removed.
*/
orhoj marked this conversation as resolved.
Show resolved Hide resolved
export async function addToListMaxSize<Type>(
lock: string,
addition: Type,
storage: StorageAccessor<Type[]>,
size: number
): Promise<void> {
return navigator.locks.request(lock, async () => {
const list = (await storage.get()) || [];
if (list.length < size) {
return storage.set([addition].concat(list));
}
return storage.set([addition].concat(list.slice(0, list.length - 1)));
});
}

/**
* Generic method to edit/update elements in a list in storage
* Note that this replaces the element found by the findPredicate with the edit.
Expand Down
71 changes: 71 additions & 0 deletions packages/browser-wallet/src/shared/utils/log-helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { storedLog } from '@shared/storage/access';
import { addToListMaxSize } from '@shared/storage/update';
import { isDevelopmentBuild } from './environment-helpers';

const loggingLock = 'concordium_log_lock';

// Determines the maximum number of log entries that is stored
// at a time.
const LOG_MAX_ENTRIES = 100;
orhoj marked this conversation as resolved.
Show resolved Hide resolved

export enum LoggingLevel {
INFO = 'INFO',
WARN = 'WARN',
ERROR = 'ERROR',
}

export interface Log {
timestamp: number;
level: LoggingLevel;
message: string;
}

function isError(error: unknown): error is { message: string } {
return typeof error === 'object' && error !== null && 'message' in error;
}

function logForDevelopmentBuild(logEntry: Log) {
const logMessage = `[${new Date(logEntry.timestamp).toISOString()}] ${logEntry.level} ${logEntry.message}`;
switch (logEntry.level) {
case LoggingLevel.WARN:
// eslint-disable-next-line no-console
console.warn(logMessage);
break;
case LoggingLevel.ERROR:
// eslint-disable-next-line no-console
console.error(logMessage);
orhoj marked this conversation as resolved.
Show resolved Hide resolved
break;
case LoggingLevel.INFO:
default:
// eslint-disable-next-line no-console
console.log(logMessage);
break;
}
}

async function log(message: string, level: LoggingLevel) {
const timestamp = Date.now();
const logEntry: Log = {
level,
message,
timestamp,
};

if (isDevelopmentBuild()) {
logForDevelopmentBuild(logEntry);
}

await addToListMaxSize(loggingLock, logEntry, storedLog, LOG_MAX_ENTRIES);
}

export async function logErrorMessage(message: string) {
log(message, LoggingLevel.ERROR);
}

export async function logError(error: unknown) {
if (isError(error)) {
logErrorMessage(error.message);
} else {
logErrorMessage(String(error));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { Buffer } from 'buffer/';
import jsonschema from 'jsonschema';
import { applyExecutionNRGBuffer, getContractName } from './contract-helpers';
import { getNet } from './network-helpers';
import { logError } from './log-helpers';

/**
* Extracts the credential holder id from a verifiable credential id (did).
Expand Down Expand Up @@ -784,7 +785,7 @@ export async function getCredentialSchemas(
} catch (e) {
// Ignore errors that occur because we aborted, as that is expected to happen.
if (!controller.signal.aborted) {
// TODO This should be logged.
logError(e);
}
}
}
Expand Down Expand Up @@ -819,7 +820,7 @@ export async function getCredentialMetadata(
metadataUrls.push(entry.credentialInfo.metadataUrl);
}
} catch (e) {
// If we fail, the credential most likely doesn't exist and we skip it
logError(e);
}
}

Expand All @@ -839,7 +840,7 @@ export async function getCredentialMetadata(
} catch (e) {
// Ignore errors that occur because we aborted, as that is expected to happen.
if (!controller.signal.aborted) {
// TODO This should be logged.
logError(e);
}
}
}
Expand Down
Loading