79 lines
2.4 KiB
TypeScript
Raw Normal View History

2021-07-09 14:07:55 +10:00
import { Dispatch, SetStateAction } from 'react';
import { Waku, WakuMessage } from 'js-waku';
2021-08-17 16:35:08 +10:00
import { PrivateMessage, PublicKeyMessage } from './messaging/wire';
import { validatePublicKeyMessage } from './crypto';
2021-06-29 15:46:07 +10:00
import { Message } from './messaging/Messages';
import { bufToHex, equalByteArrays } from 'js-waku/lib/utils';
2021-06-29 15:46:07 +10:00
export const PublicKeyContentTopic = '/eth-pm/1/public-key/proto';
2021-08-17 16:35:08 +10:00
export const PrivateMessageContentTopic = '/eth-pm/1/private-message/proto';
export async function initWaku(): Promise<Waku> {
const waku = await Waku.create({ bootstrap: true });
// Wait to be connected to at least one peer
await new Promise((resolve, reject) => {
// If we are not connected to any peer within 10sec let's just reject
// As we are not implementing connection management in this example
setTimeout(reject, 10000);
waku.libp2p.connectionManager.on('peer:connect', () => {
resolve(null);
});
});
return waku;
}
export function handlePublicKeyMessage(
2021-08-12 15:15:56 +10:00
myAddress: string | undefined,
setter: Dispatch<SetStateAction<Map<string, Uint8Array>>>,
msg: WakuMessage
) {
console.log('Public Key Message received:', msg);
if (!msg.payload) return;
const publicKeyMsg = PublicKeyMessage.decode(msg.payload);
if (!publicKeyMsg) return;
2021-07-09 14:07:55 +10:00
if (myAddress && equalByteArrays(publicKeyMsg.ethAddress, myAddress)) return;
const res = validatePublicKeyMessage(publicKeyMsg);
console.log('Is Public Key Message valid?', res);
if (res) {
setter((prevPks: Map<string, Uint8Array>) => {
prevPks.set(
bufToHex(publicKeyMsg.ethAddress),
publicKeyMsg.encryptionPublicKey
);
return new Map(prevPks);
});
}
}
2021-08-17 16:35:08 +10:00
export async function handlePrivateMessage(
setter: Dispatch<SetStateAction<Message[]>>,
address: string,
wakuMsg: WakuMessage
) {
2021-08-17 16:35:08 +10:00
console.log('Private Message received:', wakuMsg);
if (!wakuMsg.payload) return;
2021-08-17 16:35:08 +10:00
const privateMessage = PrivateMessage.decode(wakuMsg.payload);
if (!privateMessage) {
console.log('Failed to decode Private Message');
return;
}
2021-08-17 16:35:08 +10:00
if (!equalByteArrays(privateMessage.toAddress, address)) return;
const timestamp = wakuMsg.timestamp ? wakuMsg.timestamp : new Date();
2021-08-17 16:35:08 +10:00
console.log('Message decrypted:', privateMessage.message);
setter((prevMsgs: Message[]) => {
const copy = prevMsgs.slice();
copy.push({
2021-08-17 16:35:08 +10:00
text: privateMessage.message,
timestamp: timestamp,
});
return copy;
});
}