2022-06-23 16:23:27 +10:00
|
|
|
import { unmarshalPrivateKey, unmarshalPublicKey } from "@libp2p/crypto/keys";
|
|
|
|
import { supportedKeys } from "@libp2p/crypto/keys";
|
2024-01-15 16:12:01 -08:00
|
|
|
import type { PeerId } from "@libp2p/interface";
|
2022-06-23 14:03:52 +10:00
|
|
|
import { peerIdFromKeys } from "@libp2p/peer-id";
|
2021-10-26 16:58:26 +11:00
|
|
|
|
2023-03-03 12:51:56 +11:00
|
|
|
export function createPeerIdFromPublicKey(
|
2023-08-16 20:18:13 +05:30
|
|
|
publicKey: Uint8Array
|
2023-03-03 12:51:56 +11:00
|
|
|
): Promise<PeerId> {
|
|
|
|
const _publicKey = new supportedKeys.secp256k1.Secp256k1PublicKey(publicKey);
|
|
|
|
return peerIdFromKeys(_publicKey.bytes, undefined);
|
|
|
|
}
|
|
|
|
|
2023-03-03 13:06:24 +11:00
|
|
|
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(
|
2023-08-16 20:18:13 +05:30
|
|
|
peerId: PeerId
|
2023-03-03 13:06:24 +11:00
|
|
|
): 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");
|
2022-06-23 14:03:52 +10:00
|
|
|
}
|
|
|
|
|
2023-03-03 13:06:24 +11:00
|
|
|
const privateKey = await unmarshalPrivateKey(peerId.privateKey);
|
|
|
|
return privateKey.marshal();
|
2021-10-26 16:58:26 +11:00
|
|
|
}
|