2022-02-23 14:49:00 +00:00
|
|
|
import { ec } from 'elliptic'
|
2022-02-24 21:58:50 +00:00
|
|
|
import { PageDirection, utils } from 'js-waku'
|
2022-02-23 14:03:14 +00:00
|
|
|
|
2022-02-23 14:49:00 +00:00
|
|
|
import { idToContactCodeTopic } from './contentTopic'
|
|
|
|
import { ChatIdentity } from './proto/communities/v1/chat_identity'
|
2022-02-23 14:03:14 +00:00
|
|
|
|
2022-02-24 21:58:50 +00:00
|
|
|
import type { Waku } from 'js-waku'
|
|
|
|
|
2022-02-23 14:49:00 +00:00
|
|
|
const EC = new ec('secp256k1')
|
2022-02-23 14:03:14 +00:00
|
|
|
|
2022-05-25 12:42:47 +00:00
|
|
|
// TODO: rename
|
|
|
|
const hexToBuf = utils.hexToBytes
|
2022-02-23 14:49:00 +00:00
|
|
|
export { hexToBuf }
|
2022-02-23 14:03:14 +00:00
|
|
|
|
2022-05-25 12:42:47 +00:00
|
|
|
// TODO: rename
|
2022-02-23 14:03:14 +00:00
|
|
|
/**
|
|
|
|
* Return hex string with 0x prefix (commonly used for string format of a community id/public key.
|
|
|
|
*/
|
|
|
|
export function bufToHex(buf: Uint8Array): string {
|
2022-05-25 12:42:47 +00:00
|
|
|
return '0x' + utils.bytesToHex(buf)
|
2022-02-23 14:03:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export function compressPublicKey(key: Uint8Array): string {
|
2022-02-23 14:49:00 +00:00
|
|
|
const PubKey = EC.keyFromPublic(key)
|
|
|
|
return '0x' + PubKey.getPublic(true, 'hex')
|
2022-02-23 14:03:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export function genPrivateKeyWithEntropy(key: string): Uint8Array {
|
2022-02-23 14:49:00 +00:00
|
|
|
const pair = EC.genKeyPair({ entropy: key })
|
|
|
|
return hexToBuf('0x' + pair.getPrivate('hex'))
|
2022-02-23 14:03:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export async function getLatestUserNickname(
|
|
|
|
key: Uint8Array,
|
|
|
|
waku: Waku
|
|
|
|
): Promise<{ clock: number; nickname: string }> {
|
2022-02-23 14:49:00 +00:00
|
|
|
const publicKey = bufToHex(key)
|
|
|
|
let nickname = ''
|
|
|
|
let clock = 0
|
2022-02-23 14:03:14 +00:00
|
|
|
await waku.store.queryHistory([idToContactCodeTopic(publicKey)], {
|
2022-02-23 14:49:00 +00:00
|
|
|
callback: msgs =>
|
|
|
|
msgs.some(e => {
|
2022-02-23 14:03:14 +00:00
|
|
|
try {
|
|
|
|
if (e.payload) {
|
2022-02-23 14:49:00 +00:00
|
|
|
const chatIdentity = ChatIdentity.decode(e?.payload)
|
2022-02-23 14:03:14 +00:00
|
|
|
if (chatIdentity) {
|
|
|
|
if (chatIdentity?.displayName) {
|
2022-02-23 14:49:00 +00:00
|
|
|
clock = chatIdentity?.clock ?? 0
|
|
|
|
nickname = chatIdentity?.displayName
|
2022-02-23 14:03:14 +00:00
|
|
|
}
|
|
|
|
}
|
2022-02-23 14:49:00 +00:00
|
|
|
return true
|
2022-02-23 14:03:14 +00:00
|
|
|
}
|
|
|
|
} catch {
|
2022-02-23 14:49:00 +00:00
|
|
|
return false
|
2022-02-23 14:03:14 +00:00
|
|
|
}
|
|
|
|
}),
|
|
|
|
pageDirection: PageDirection.BACKWARD,
|
2022-02-23 14:49:00 +00:00
|
|
|
})
|
|
|
|
return { clock, nickname }
|
2022-02-23 14:03:14 +00:00
|
|
|
}
|