2022-02-23 14:49:00 +00:00
|
|
|
import { BN } from 'bn.js'
|
|
|
|
import { derive } from 'ecies-geth'
|
|
|
|
import { ec } from 'elliptic'
|
2022-02-23 14:03:14 +00:00
|
|
|
|
2022-02-23 14:49:00 +00:00
|
|
|
import { idToContentTopic } from './contentTopic'
|
2022-05-25 12:42:47 +00:00
|
|
|
import { bufToHex, hexToBuf } from './utils'
|
2022-02-23 14:03:14 +00:00
|
|
|
|
2022-06-01 05:39:47 +00:00
|
|
|
import type { Identity } from './identity'
|
2022-02-23 14:03:14 +00:00
|
|
|
|
2022-02-23 14:49:00 +00:00
|
|
|
const EC = new ec('secp256k1')
|
|
|
|
const partitionsNum = new BN(5000)
|
2022-02-23 14:03:14 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Get the partitioned topic https://specs.status.im/spec/3#partitioned-topic
|
|
|
|
* @param publicKey Public key of recipient
|
|
|
|
* @returns string The Waku v2 Content Topic.
|
|
|
|
*/
|
|
|
|
export function getPartitionedTopic(publicKey: string): string {
|
2022-02-23 14:49:00 +00:00
|
|
|
const key = EC.keyFromPublic(publicKey.slice(2), 'hex')
|
|
|
|
const X = key.getPublic().getX()
|
2022-02-23 14:03:14 +00:00
|
|
|
|
2022-02-23 14:49:00 +00:00
|
|
|
const partition = X.mod(partitionsNum)
|
2022-02-23 14:03:14 +00:00
|
|
|
|
2022-02-23 14:49:00 +00:00
|
|
|
const partitionTopic = `contact-discovery-${partition.toString()}`
|
2022-02-23 14:03:14 +00:00
|
|
|
|
2022-02-23 14:49:00 +00:00
|
|
|
return idToContentTopic(partitionTopic)
|
2022-02-23 14:03:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get the negotiated topic https://specs.status.im/spec/3#negotiated-topic
|
|
|
|
* @param identity identity of user
|
|
|
|
* @param publicKey Public key of recipient
|
|
|
|
* @returns string The Waku v2 Content Topic.
|
|
|
|
*/
|
|
|
|
export async function getNegotiatedTopic(
|
|
|
|
identity: Identity,
|
|
|
|
publicKey: string
|
|
|
|
): Promise<string> {
|
2022-02-23 14:49:00 +00:00
|
|
|
const key = EC.keyFromPublic(publicKey.slice(2), 'hex')
|
2022-02-23 14:03:14 +00:00
|
|
|
const sharedSecret = await derive(
|
|
|
|
Buffer.from(identity.privateKey),
|
2022-05-25 12:42:47 +00:00
|
|
|
Buffer.concat([hexToBuf(key.getPublic('hex'))])
|
2022-02-23 14:49:00 +00:00
|
|
|
)
|
|
|
|
return idToContentTopic(bufToHex(sharedSecret))
|
2022-02-23 14:03:14 +00:00
|
|
|
}
|