js-rln/src/message.ts

71 lines
1.8 KiB
TypeScript
Raw Normal View History

import type {
IDecodedMessage,
IMessage,
IRateLimitProof,
} from "@waku/interfaces";
import * as utils from "@waku/utils/bytes";
2022-09-28 14:23:10 +10:00
import { RLNInstance } from "./rln.js";
2024-02-16 00:50:14 +01:00
import { epochBytesToInt } from "./utils/index.js";
2022-09-28 14:23:10 +10:00
export function toRLNSignal(contentTopic: string, msg: IMessage): Uint8Array {
const contentTopicBytes = utils.utf8ToBytes(contentTopic ?? "");
2022-10-01 08:02:13 -04:00
return new Uint8Array([...(msg.payload ?? []), ...contentTopicBytes]);
}
export class RlnMessage<T extends IDecodedMessage> implements IDecodedMessage {
public pubsubTopic = "";
2022-09-28 14:23:10 +10:00
constructor(
public rlnInstance: RLNInstance,
public msg: T,
public rateLimitProof: IRateLimitProof | undefined
2022-09-28 14:23:10 +10:00
) {}
public verify(roots: Uint8Array[]): boolean | undefined {
2022-09-28 14:23:10 +10:00
return this.rateLimitProof
2024-02-16 01:22:43 +01:00
? this.rlnInstance.zerokit.verifyWithRoots(
this.rateLimitProof,
toRLNSignal(this.msg.contentTopic, this.msg),
...roots
) // this.rlnInstance.verifyRLNProof once issue status-im/nwaku#1248 is fixed
2022-09-28 14:23:10 +10:00
: undefined;
}
2022-10-10 09:59:24 -05:00
public verifyNoRoot(): boolean | undefined {
return this.rateLimitProof
2024-02-16 01:22:43 +01:00
? this.rlnInstance.zerokit.verifyWithNoRoot(
2022-10-10 09:59:24 -05:00
this.rateLimitProof,
toRLNSignal(this.msg.contentTopic, this.msg)
2022-10-10 09:59:24 -05:00
) // this.rlnInstance.verifyRLNProof once issue status-im/nwaku#1248 is fixed
: undefined;
}
get payload(): Uint8Array {
2022-09-28 14:23:10 +10:00
return this.msg.payload;
}
get contentTopic(): string {
2022-09-28 14:23:10 +10:00
return this.msg.contentTopic;
}
get timestamp(): Date | undefined {
return this.msg.timestamp;
}
get ephemeral(): boolean | undefined {
return this.msg.ephemeral;
}
get meta(): Uint8Array | undefined {
return this.msg.meta;
}
2022-09-28 14:23:10 +10:00
get epoch(): number | undefined {
const bytes = this.msg.rateLimitProof?.epoch;
if (!bytes) return;
return epochBytesToInt(bytes);
}
}