js-waku/packages/enr/src/peer_id.ts

35 lines
1.0 KiB
TypeScript
Raw Normal View History

2022-06-23 16:23:27 +10:00
import { unmarshalPrivateKey, unmarshalPublicKey } from "@libp2p/crypto/keys";
import { supportedKeys } from "@libp2p/crypto/keys";
import type { PeerId } from "@libp2p/interface";
import { peerIdFromKeys } from "@libp2p/peer-id";
2023-03-03 12:51:56 +11:00
export function createPeerIdFromPublicKey(
publicKey: Uint8Array
2023-03-03 12:51:56 +11:00
): Promise<PeerId> {
const _publicKey = new supportedKeys.secp256k1.Secp256k1PublicKey(publicKey);
return peerIdFromKeys(_publicKey.bytes, undefined);
}
export function getPublicKeyFromPeerId(peerId: PeerId): Uint8Array {
if (peerId.type !== "secp256k1") {
throw new Error("Unsupported peer id type");
}
return unmarshalPublicKey(peerId.publicKey).marshal();
}
// Only used in tests
export async function getPrivateKeyFromPeerId(
peerId: PeerId
): Promise<Uint8Array> {
if (peerId.type !== "secp256k1") {
throw new Error("Unsupported peer id type");
}
if (!peerId.privateKey) {
throw new Error("Private key not present on peer id");
}
const privateKey = await unmarshalPrivateKey(peerId.privateKey);
return privateKey.marshal();
}