js-rln/src/epoch.ts

31 lines
865 B
TypeScript
Raw Normal View History

2022-10-10 07:25:38 -05:00
import debug from "debug";
2022-09-28 13:05:10 +10:00
const DefaultEpochUnitSeconds = 10; // the rln-relay epoch length in seconds
2022-10-10 07:25:38 -05:00
const log = debug("waku:rln:epoch");
2022-09-28 13:05:10 +10:00
export function dateToEpoch(
timestamp: Date,
epochUnitSeconds: number = DefaultEpochUnitSeconds
2022-09-28 13:51:53 +10:00
): number {
const time = timestamp.getTime();
2022-10-10 07:25:38 -05:00
const epoch = Math.floor(time / 1000 / epochUnitSeconds);
log("generated epoch", epoch);
return epoch;
2022-09-28 13:51:53 +10:00
}
export function epochIntToBytes(epoch: number): Uint8Array {
2022-09-28 13:53:47 +10:00
const bytes = new Uint8Array(32);
const db = new DataView(bytes.buffer);
db.setUint32(0, epoch, true);
2022-10-10 07:25:38 -05:00
log("encoded epoch", epoch, bytes);
2022-09-28 13:53:47 +10:00
return bytes;
2022-09-28 13:51:53 +10:00
}
export function epochBytesToInt(bytes: Uint8Array): number {
2022-10-10 08:48:26 -05:00
const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
2022-10-10 07:25:38 -05:00
const epoch = dv.getUint32(0, true);
log("decoded epoch", epoch, bytes);
return epoch;
2022-09-28 13:05:10 +10:00
}