js-noise/src/qr.ts

64 lines
1.9 KiB
TypeScript
Raw Normal View History

import { decode, encodeURI, fromUint8Array, toUint8Array } from "js-base64";
2022-12-03 09:37:39 -04:00
2022-12-06 22:36:03 -04:00
import { bytes32 } from "./@types/basic.js";
2022-12-03 09:37:39 -04:00
2023-01-06 13:34:32 -04:00
/**
* QR code generation
*/
2022-12-03 09:37:39 -04:00
export class QR {
constructor(
public readonly applicationName: string,
public readonly applicationVersion: string,
public readonly shardId: string,
public readonly ephemeralKey: bytes32,
public readonly committedStaticKey: bytes32
) {}
// Serializes input parameters to a base64 string for exposure through QR code (used by WakuPairing)
toString(): string {
let qr = encodeURI(this.applicationName) + ":";
qr += encodeURI(this.applicationVersion) + ":";
qr += encodeURI(this.shardId) + ":";
qr += fromUint8Array(this.ephemeralKey, true) + ":";
qr += fromUint8Array(this.committedStaticKey, true);
2022-12-03 09:37:39 -04:00
return qr;
}
2023-01-06 13:34:32 -04:00
/**
* Convert QR code into byte array
* @returns byte array serialization of a base64 encoded QR code
*/
2022-12-03 09:37:39 -04:00
toByteArray(): Uint8Array {
const enc = new TextEncoder();
return enc.encode(this.toString());
}
2023-01-06 13:34:32 -04:00
/**
* Deserializes input string in base64 to the corresponding (applicationName, applicationVersion, shardId, ephemeralKey, committedStaticKey)
* @param input input base64 encoded string
* @returns QR
*/
static from(input: string | Uint8Array): QR {
let qrStr: string;
if (input instanceof Uint8Array) {
const dec = new TextDecoder();
qrStr = dec.decode(input);
} else {
qrStr = input;
}
const values = qrStr.split(":");
2022-12-03 09:37:39 -04:00
if (values.length != 5) throw new Error("invalid qr string");
const applicationName = decode(values[0]);
const applicationVersion = decode(values[1]);
const shardId = decode(values[2]);
const ephemeralKey = toUint8Array(values[3]);
const committedStaticKey = toUint8Array(values[4]);
return new QR(applicationName, applicationVersion, shardId, ephemeralKey, committedStaticKey);
}
}