Skip to content

Commit

Permalink
update identityKey format to contain info about network
Browse files Browse the repository at this point in the history
  • Loading branch information
Szegoo committed Oct 24, 2023
1 parent 4877c36 commit 5d6ba8c
Show file tree
Hide file tree
Showing 8 changed files with 65 additions and 53 deletions.
5 changes: 3 additions & 2 deletions src/components/Cards/AddressCard/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { Address, ChainId } from '@/contracts/types';

import styles from './index.module.scss';
import { useRelay } from '@/contexts/RelayApi';
import { Network } from 'types/types-returns/identity';
interface AddressCardProps {
data: Address;
onEdit?: () => void;
Expand Down Expand Up @@ -59,7 +60,7 @@ export const AddressCard = ({ data, onEdit }: AddressCardProps) => {
contract,
'remove_address',
{},
[chainId]
[[chainId, relay]]
);

toastSuccess('Address is removed successfully.');
Expand Down Expand Up @@ -88,8 +89,8 @@ export const AddressCard = ({ data, onEdit }: AddressCardProps) => {
decryptedAddress = IdentityKey.decryptAddress(
identityKey,
chainId,
address,
relay,
address
);

return {
Expand Down
4 changes: 2 additions & 2 deletions src/components/Modals/AddAddress/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ export const AddAddressModal = ({ open, onClose }: AddAddressModalProps) => {
const encryptedAddress = IdentityKey.encryptAddress(
identityKey,
chainId,
relay,
chainAddress
chainAddress,
relay
);

try {
Expand Down
29 changes: 8 additions & 21 deletions src/components/Modals/AddIdentity/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ export const AddIdentityModal = ({ open, onClose }: AddIdentityModalProps) => {
const { contract, fetchIdentities } = useAddressBook();
const { toastError, toastSuccess } = useToast();

const [identityNo, setIdentityNo] = useState<number | undefined>();
const [identityKey, setIdentityKey] = useState<string | undefined>();
const [nickname, setNickname] = useState<string | undefined>();
const [working, setWorking] = useState(false);
Expand All @@ -40,8 +39,11 @@ export const AddIdentityModal = ({ open, onClose }: AddIdentityModalProps) => {
toastError('Please input identity key.');
return;
}
if (identityNo === undefined) {
toastError('Please input identity no.');
const firstColonIndex = identityKey.indexOf(':');
const firstSemicolonIndex = identityKey.indexOf(';');
const identityNo = Number(identityKey.substring(firstColonIndex + 1, firstSemicolonIndex));
if (Number.isNaN(identityNo)) {
toastError("Invalid identity key.");
return;
}
if (identityNo === myIdentity) {
Expand Down Expand Up @@ -75,10 +77,9 @@ export const AddIdentityModal = ({ open, onClose }: AddIdentityModalProps) => {
onClose();
} catch (e: any) {
toastError(
`Failed to add identity. Error: ${
e.errorMessage === 'Error'
? 'Please check your balance.'
: e.errorMessage
`Failed to add identity. Error: ${e.errorMessage === 'Error'
? 'Please check your balance.'
: e.errorMessage
}`
);
setWorking(false);
Expand All @@ -89,7 +90,6 @@ export const AddIdentityModal = ({ open, onClose }: AddIdentityModalProps) => {
setNickname(undefined);
setWorking(false);
setIdentityKey(undefined);
setIdentityNo(undefined);
}, [open]);

return (
Expand Down Expand Up @@ -121,19 +121,6 @@ export const AddIdentityModal = ({ open, onClose }: AddIdentityModalProps) => {
<span>{`${(nickname || '').length}/16`}</span>
</FormHelperText>
</FormControl>
<FormControl className='form-item'>
<FormLabel>Identity No</FormLabel>
<TextField
placeholder='Enter identity no'
type='number'
required
value={identityNo}
onChange={(e) => {
const value = Number(e.target.value);
value >= 0 && setIdentityNo(value);
}}
/>
</FormControl>
<FormControl className='form-item'>
<FormLabel>Identity Key</FormLabel>
<TextField
Expand Down
7 changes: 4 additions & 3 deletions src/components/Modals/EditAddress/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { useToast } from '@/contexts/Toast';
import { useIdentity } from '@/contracts';
import { ChainId } from '@/contracts/types';
import { useRelay } from '@/contexts/RelayApi';
import { Network } from 'types/types-arguments/identity';

interface EditAddressModalProps {
open: boolean;
Expand Down Expand Up @@ -82,8 +83,8 @@ export const EditAddressModal = ({
const encryptedAddress = IdentityKey.encryptAddress(
identityKey,
chainId,
relay,
newAddress
newAddress,
relay
);

try {
Expand All @@ -93,7 +94,7 @@ export const EditAddressModal = ({
contract,
'update_address',
{},
[chainId, encryptedAddress]
[[chainId, relay === "polkadot" ? Network.polkadot : Network.kusama], encryptedAddress]
);
// Update the identity key when the user has updated his on-chain data
KeyStore.updateIdentityKey(identityNo, identityKey);
Expand Down
30 changes: 23 additions & 7 deletions src/components/Modals/ShareIdentity/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ export const ShareIdentityModal = ({
}: ShareIdentityModalProps) => {
const { identityNo, getAllChains } = useIdentity();
const { toastError, toastSuccess } = useToast();
const [chains, setChains] = useState([] as Array<{ id: number, name: string }>);
const [checks, setChecks] = useState<Record<number, boolean>>({});
const [chains, setChains] = useState([] as Array<{ id: number, name: string, relay: string }>);
const [checks, setChecks] = useState<Record<string, boolean>>({});
const [sharedKey, setSharedKey] = useState('');
const { relay } = useRelay();

Expand All @@ -46,6 +46,7 @@ export const ShareIdentityModal = ({

const getChains = async () => {
const result = await getAllChains(identityNo);
console.log(result);
setChains(result);
}

Expand All @@ -57,12 +58,27 @@ export const ShareIdentityModal = ({

const selectedChains = Object.entries(checks)
.filter((item) => item[1])
.map((item) => Number(item[0]));
.map((item) => {
if (item[0].startsWith("polkadot")) {
const chainId = item[0].substring("polkadot".length);
return {
chainId: Number(chainId),
relay: "polkadot"
};
} else {
const chainId = item[0].substring("kusama".length);
return {
chainId: Number(chainId),
relay: "kusama"
};
}
});

const identityKey = KeyStore.readIdentityKey(identityNo) || '';

console.log(selectedChains);
try {
const sharedKey = IdentityKey.getSharedKey(identityKey, selectedChains, relay);
const sharedKey = IdentityKey.getSharedKey(identityKey, selectedChains);
setSharedKey(`identityNo:${identityNo};`.concat(sharedKey));
} catch (e: any) {
toastError(`Failed to get the identity key. Error: ${e.message}`);
Expand All @@ -83,16 +99,16 @@ export const ShareIdentityModal = ({
able to access:
</Typography>
<Grid container sx={{ pt: '12px', pb: '24px' }} mb='1em'>
{chains.map(({ id, name }) => (
<Grid item key={`${id}${name}`} sx={{ flexGrow: 1 }}>
{chains.map(({ id, name, relay }) => (
<Grid item key={`${relay}${id}`} sx={{ flexGrow: 1 }}>
<FormControlLabel
label={name}
control={
<Checkbox
onChange={(e) =>
setChecks({
...checks,
[id]: e.target.checked,
[`${relay}${id}`]: e.target.checked,
})
}
/>
Expand Down
10 changes: 6 additions & 4 deletions src/contracts/identity/context.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ interface IdentityContract {
identityNo: number | null;
chains: Chains;
// These are the chains on both kusama and polkadot.
getAllChains: (_id: number) => Promise<Array<{ id: number, name: string }>>;
getAllChains: (_id: number) => Promise<Array<{ id: number, relay: string, name: string }>>;
addresses: Array<Address>;
contract: ContractPromise | undefined;
fetchIdentityNo: () => Promise<void>;
Expand All @@ -41,7 +41,7 @@ interface IdentityContract {
const defaultIdentity: IdentityContract = {
identityNo: null,
chains: {},
getAllChains: async (): Promise<Array<{ id: number, name: string }>> => {
getAllChains: async (): Promise<Array<{ id: number, relay: string, name: string }>> => {
return []
},
addresses: [],
Expand Down Expand Up @@ -218,9 +218,10 @@ const IdentityContractProvider = ({ children }: Props) => {
}
};

const getAllChains = async (no: number): Promise<Array<{ id: number, name: string }>> => {
const getAllChains = async (no: number): Promise<Array<{ id: number, relay: string, name: string }>> => {
if (!api || !contract) return [];

const chaindata = new Chaindata();
try {
const result = await contractQuery(api, '', contract, 'identity', {}, [
no,
Expand All @@ -235,7 +236,8 @@ const IdentityContractProvider = ({ children }: Props) => {
return output.addresses.map((record: any) => {
return {
id: record[0][0],
name: record[0][1]
name: record[0][1],
relay: record[0][1].toString().toLowerCase()
}
});
} catch (e) {
Expand Down
2 changes: 1 addition & 1 deletion src/pages/transfer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -161,8 +161,8 @@ const TransferPage = () => {
const decryptedAddress = IdentityKey.decryptAddress(
identityKey,
destChainId,
relay,
destAddressRaw,
relay,
);
setRecipientAddress(decryptedAddress);
} else {
Expand Down
31 changes: 18 additions & 13 deletions src/utils/identityKey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,12 @@ class IdentityKey {

const cipher = this.generateCipher();

identityKey += `${chainId}:${cipher};`;
identityKey += `${relay}${chainId}:${cipher};`;
return identityKey;
}

public static updateCipher(identityKey: string, chainId: number, relay: string): string {
const startIndex = identityKey.indexOf(`${chainId}:`);
const startIndex = identityKey.indexOf(`${relay}${chainId}:`);

if (startIndex >= 0) {
const newCipher = this.generateCipher();
Expand All @@ -72,6 +72,7 @@ class IdentityKey {

public static encryptAddress(identityKey: string, chainId: number, address: string, relay: string): string {
const cipher = this.getChainCipher(identityKey, chainId, relay);
console.log(cipher);
const cipherBase64 = Buffer.from(cipher, "base64");

const aesCtr = new aesjs.ModeOfOperation.ctr(cipherBase64);
Expand All @@ -91,36 +92,40 @@ class IdentityKey {
}

public static getChainCipher(identityKey: string, chainId: number, relay: string): string {
const startIndex = identityKey.indexOf(`${chainId}:`);
const startIndex = identityKey.indexOf(`${relay}${chainId}:`);
const chainIdAndNetwork = `${relay}${chainId}`;

if (startIndex >= 0) {
const endIndex = identityKey.indexOf(";", startIndex);
return identityKey.substring(startIndex + chainId.toString().length + 1, endIndex);
return identityKey.substring(startIndex + chainIdAndNetwork.toString().length + 1, endIndex);
} else {
throw new Error("Cannot find chainId");
}
}

public static getSharedKey(identityKey: string, selectedChains: number[], relay: string): string {
public static getSharedKey(identityKey: string, selectedChains: { chainId: number, relay: string }[]): string {
let key = JSON.parse(JSON.stringify(identityKey));
let sharedKey = "";
selectedChains.forEach((chainId) => {
if (!IdentityKey.containsChainId(key, chainId, relay)) {
key = IdentityKey.newCipher(key, chainId, relay);
throw new Error(`Cipher for chain #${chainId} not found`);
selectedChains.forEach((chain) => {
if (!IdentityKey.containsChainId(key, chain.chainId, chain.relay)) {
key = IdentityKey.newCipher(key, chain.chainId, chain.relay);
throw new Error(`Cipher for chain #${chain.relay}${chain.chainId} not found`);
}
sharedKey += `${chainId}:${IdentityKey.getChainCipher(
sharedKey += `${chain.relay}${chain.chainId}:${IdentityKey.getChainCipher(
key,
chainId,
relay
chain.chainId,
chain.relay
)};`;
});

return sharedKey;
}

public static containsChainId(identityKey: string, chainId: number, relay: string): boolean {
const startIndex = identityKey.indexOf(`${chainId}${relay}:`);
console.log(identityKey);
console.log(chainId);
console.log(relay);
const startIndex = identityKey.indexOf(`${relay}${chainId}:`);

return startIndex >= 0 ? true : false;
}
Expand Down

0 comments on commit 5d6ba8c

Please sign in to comment.