js-waku/src/lib/enr/v4.ts

48 lines
1.1 KiB
TypeScript
Raw Normal View History

2022-03-07 13:33:20 +11:00
import * as secp from "@noble/secp256k1";
2022-05-20 11:05:44 +10:00
import { keccak256 } from "../crypto";
2022-03-07 13:33:20 +11:00
import { bytesToHex } from "../utils";
2022-03-07 07:51:36 +11:00
2022-02-04 14:12:00 +11:00
import { NodeId } from "./types";
2022-03-07 13:33:20 +11:00
export function compressPublicKey(publicKey: Uint8Array): Uint8Array {
const point = secp.Point.fromHex(bytesToHex(publicKey));
return point.toRawBytes(true);
}
export async function sign(
privKey: Uint8Array,
msg: Uint8Array
): Promise<Uint8Array> {
2022-05-20 10:54:48 +10:00
return secp.sign(keccak256(msg), privKey, {
2022-03-07 13:33:20 +11:00
der: false,
});
}
export function verify(
pubKey: Uint8Array,
msg: Uint8Array,
sig: Uint8Array
): boolean {
2022-03-07 13:33:20 +11:00
try {
const _sig = secp.Signature.fromCompact(sig.slice(0, 64));
2022-05-20 10:54:48 +10:00
return secp.verify(_sig, keccak256(msg), pubKey);
2022-03-07 13:33:20 +11:00
} catch {
return false;
}
}
2022-05-20 11:27:15 +10:00
function createNodeId(bytes: Uint8Array): NodeId {
if (bytes.length !== 32) {
throw new Error("NodeId must be 32 bytes in length");
}
return bytesToHex(bytes);
}
export function nodeId(pubKey: Uint8Array): NodeId {
2022-03-07 13:33:20 +11:00
const publicKey = secp.Point.fromHex(pubKey);
const uncompressedPubkey = publicKey.toRawBytes(false);
2022-05-20 10:54:48 +10:00
return createNodeId(keccak256(uncompressedPubkey.slice(1)));
}