2022-06-23 16:23:27 +10:00
|
|
|
import { unmarshalPrivateKey, unmarshalPublicKey } from "@libp2p/crypto/keys";
|
|
|
|
import { supportedKeys } from "@libp2p/crypto/keys";
|
2022-06-23 14:03:52 +10:00
|
|
|
import type { PeerId } from "@libp2p/interface-peer-id";
|
|
|
|
import { peerIdFromKeys } from "@libp2p/peer-id";
|
2021-10-26 16:58:26 +11:00
|
|
|
|
2022-11-02 22:25:47 +11:00
|
|
|
import { Secp256k1Keypair } from "./secp256k1.js";
|
|
|
|
import { IKeypair, KeypairType } from "./types.js";
|
2021-10-26 16:58:26 +11:00
|
|
|
|
2022-05-20 11:44:58 +10:00
|
|
|
export const ERR_TYPE_NOT_IMPLEMENTED = "Keypair type not implemented";
|
2022-11-02 22:25:47 +11:00
|
|
|
export * from "./types.js";
|
|
|
|
export * from "./secp256k1.js";
|
2021-10-26 16:58:26 +11:00
|
|
|
|
2023-03-03 12:51:56 +11:00
|
|
|
export function createPeerIdFromPublicKey(
|
|
|
|
publicKey: Uint8Array
|
|
|
|
): Promise<PeerId> {
|
|
|
|
const _publicKey = new supportedKeys.secp256k1.Secp256k1PublicKey(publicKey);
|
|
|
|
return peerIdFromKeys(_publicKey.bytes, undefined);
|
|
|
|
}
|
|
|
|
|
2021-10-26 16:58:26 +11:00
|
|
|
export function createKeypair(
|
|
|
|
type: KeypairType,
|
2022-02-16 12:11:54 +11:00
|
|
|
privateKey?: Uint8Array,
|
|
|
|
publicKey?: Uint8Array
|
2021-10-26 16:58:26 +11:00
|
|
|
): IKeypair {
|
|
|
|
switch (type) {
|
|
|
|
case KeypairType.secp256k1:
|
|
|
|
return new Secp256k1Keypair(privateKey, publicKey);
|
|
|
|
default:
|
|
|
|
throw new Error(ERR_TYPE_NOT_IMPLEMENTED);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-23 14:03:52 +10:00
|
|
|
export async function createKeypairFromPeerId(
|
|
|
|
peerId: PeerId
|
|
|
|
): Promise<IKeypair> {
|
|
|
|
let keypairType;
|
|
|
|
switch (peerId.type) {
|
|
|
|
case "RSA":
|
|
|
|
keypairType = KeypairType.rsa;
|
|
|
|
break;
|
|
|
|
case "Ed25519":
|
|
|
|
keypairType = KeypairType.ed25519;
|
|
|
|
break;
|
|
|
|
case "secp256k1":
|
|
|
|
keypairType = KeypairType.secp256k1;
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
throw new Error("Unsupported peer id type");
|
|
|
|
}
|
|
|
|
|
|
|
|
const publicKey = peerId.publicKey
|
|
|
|
? unmarshalPublicKey(peerId.publicKey)
|
|
|
|
: undefined;
|
|
|
|
const privateKey = peerId.privateKey
|
|
|
|
? await unmarshalPrivateKey(peerId.privateKey)
|
|
|
|
: undefined;
|
|
|
|
|
2022-06-23 16:06:37 +10:00
|
|
|
return createKeypair(
|
|
|
|
keypairType,
|
|
|
|
privateKey?.marshal(),
|
|
|
|
publicKey?.marshal()
|
|
|
|
);
|
2021-10-26 16:58:26 +11:00
|
|
|
}
|