2023-03-13 14:50:46 +11:00
|
|
|
import { sha256 } from "@noble/hashes/sha256";
|
2024-04-30 15:37:10 +02:00
|
|
|
import type { IDecodedMessage, IProtoMessage } from "@waku/interfaces";
|
2024-04-29 15:35:23 +05:30
|
|
|
import { isDefined } from "@waku/utils";
|
|
|
|
|
import {
|
|
|
|
|
bytesToUtf8,
|
|
|
|
|
concat,
|
|
|
|
|
numberToBytes,
|
|
|
|
|
utf8ToBytes
|
|
|
|
|
} from "@waku/utils/bytes";
|
2023-03-13 14:50:46 +11:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Deterministic Message Hashing as defined in
|
|
|
|
|
* [14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/#deterministic-message-hashing)
|
|
|
|
|
*/
|
|
|
|
|
export function messageHash(
|
|
|
|
|
pubsubTopic: string,
|
2024-04-30 15:37:10 +02:00
|
|
|
message: IProtoMessage | IDecodedMessage
|
2023-03-13 14:50:46 +11:00
|
|
|
): Uint8Array {
|
|
|
|
|
const pubsubTopicBytes = utf8ToBytes(pubsubTopic);
|
|
|
|
|
const contentTopicBytes = utf8ToBytes(message.contentTopic);
|
2024-04-30 15:37:10 +02:00
|
|
|
const timestampBytes = tryConvertTimestampToBytes(message.timestamp);
|
2023-03-13 14:50:46 +11:00
|
|
|
|
2024-04-29 15:35:23 +05:30
|
|
|
const bytes = concat(
|
|
|
|
|
[
|
2023-03-13 14:50:46 +11:00
|
|
|
pubsubTopicBytes,
|
|
|
|
|
message.payload,
|
|
|
|
|
contentTopicBytes,
|
2024-04-29 15:35:23 +05:30
|
|
|
message.meta,
|
|
|
|
|
timestampBytes
|
|
|
|
|
].filter(isDefined)
|
|
|
|
|
);
|
|
|
|
|
|
2023-03-14 15:27:47 +11:00
|
|
|
return sha256(bytes);
|
2023-03-13 14:50:46 +11:00
|
|
|
}
|
2024-01-24 18:24:03 +05:30
|
|
|
|
2024-04-30 15:37:10 +02:00
|
|
|
function tryConvertTimestampToBytes(
|
|
|
|
|
timestamp: Date | number | bigint | undefined
|
|
|
|
|
): undefined | Uint8Array {
|
|
|
|
|
if (!timestamp) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-01 15:19:35 +05:30
|
|
|
let bigIntTimestamp: bigint;
|
|
|
|
|
|
|
|
|
|
if (typeof timestamp === "bigint") {
|
|
|
|
|
bigIntTimestamp = timestamp;
|
|
|
|
|
} else {
|
|
|
|
|
bigIntTimestamp = BigInt(timestamp.valueOf()) * 1000000n;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return numberToBytes(bigIntTimestamp);
|
2024-04-30 15:37:10 +02:00
|
|
|
}
|
|
|
|
|
|
2024-01-24 18:24:03 +05:30
|
|
|
export function messageHashStr(
|
|
|
|
|
pubsubTopic: string,
|
2024-04-30 15:37:10 +02:00
|
|
|
message: IProtoMessage | IDecodedMessage
|
2024-01-24 18:24:03 +05:30
|
|
|
): string {
|
|
|
|
|
const hash = messageHash(pubsubTopic, message);
|
|
|
|
|
const hashStr = bytesToUtf8(hash);
|
|
|
|
|
return hashStr;
|
|
|
|
|
}
|