67 lines
1.9 KiB
TypeScript
Raw Normal View History

2022-02-04 14:12:00 +11:00
import { keys } from "libp2p-crypto";
import mh from "multihashes";
import PeerId from "peer-id";
const { keysPBM, supportedKeys } = keys;
2022-02-04 14:12:00 +11:00
import { ERR_TYPE_NOT_IMPLEMENTED } from "./constants";
import { Secp256k1Keypair } from "./secp256k1";
import { IKeypair, KeypairType } from "./types";
2022-02-04 14:12:00 +11:00
export * from "./types";
export * from "./secp256k1";
export async function generateKeypair(type: KeypairType): Promise<IKeypair> {
switch (type) {
case KeypairType.secp256k1:
return await Secp256k1Keypair.generate();
default:
throw new Error(ERR_TYPE_NOT_IMPLEMENTED);
}
}
export function createKeypair(
type: KeypairType,
privateKey?: Buffer,
publicKey?: Buffer
): IKeypair {
switch (type) {
case KeypairType.secp256k1:
return new Secp256k1Keypair(privateKey, publicKey);
default:
throw new Error(ERR_TYPE_NOT_IMPLEMENTED);
}
}
2022-01-17 14:21:23 +11:00
export function createPeerIdFromKeypair(keypair: IKeypair): PeerId {
switch (keypair.type) {
case KeypairType.secp256k1: {
// manually create a peer id to avoid expensive ops
const privKey = keypair.hasPrivateKey()
? new supportedKeys.secp256k1.Secp256k1PrivateKey(
keypair.privateKey,
keypair.publicKey
)
: undefined;
const pubKey = new supportedKeys.secp256k1.Secp256k1PublicKey(
keypair.publicKey
);
2022-02-04 14:12:00 +11:00
const id = mh.encode(pubKey.bytes, "identity");
return new PeerId(id, privKey, pubKey);
}
default:
throw new Error(ERR_TYPE_NOT_IMPLEMENTED);
}
}
export function createKeypairFromPeerId(peerId: PeerId): IKeypair {
// pub/private key bytes from peer-id are encoded in protobuf format
const pub = keysPBM.PublicKey.decode(peerId.pubKey.bytes);
return createKeypair(
pub.Type as KeypairType,
peerId.privKey ? Buffer.from(peerId.privKey.marshal()) : undefined,
Buffer.from(pub.Data)
);
}