2022-02-23 14:49:00 +00:00
|
|
|
import { BN } from 'bn.js'
|
|
|
|
import { derive } from 'ecies-geth'
|
|
|
|
import { ec } from 'elliptic'
|
|
|
|
import { bufToHex } from 'js-waku/build/main/lib/utils'
|
2022-02-23 14:03:14 +00:00
|
|
|
|
2022-02-23 14:49:00 +00:00
|
|
|
import { idToContentTopic } from './contentTopic'
|
|
|
|
import { hexToBuf } from './utils'
|
2022-02-23 14:03:14 +00:00
|
|
|
|
2022-02-23 14:49:00 +00:00
|
|
|
import { Identity } from '.'
|
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-02-23 14:49:00 +00:00
|
|
|
hexToBuf(key.getPublic('hex'))
|
|
|
|
)
|
|
|
|
return idToContentTopic(bufToHex(sharedSecret))
|
2022-02-23 14:03:14 +00:00
|
|
|
}
|