2020-11-19 13:22:41 +00:00
|
|
|
import * as blst from "@chainsafe/blst";
|
2022-04-11 15:08:15 +00:00
|
|
|
import {bytesToHex, hexToBytes, isZeroUint8Array, randomBytes} from "../helpers/index.js";
|
|
|
|
import {SECRET_KEY_LENGTH} from "../constants.js";
|
|
|
|
import {SecretKey as ISecretKey} from "../interface.js";
|
|
|
|
import {PublicKey} from "./publicKey.js";
|
|
|
|
import {Signature} from "./signature.js";
|
|
|
|
import {ZeroSecretKeyError} from "../errors.js";
|
2019-08-05 15:48:26 +00:00
|
|
|
|
2020-11-30 18:01:13 +00:00
|
|
|
export class SecretKey implements ISecretKey {
|
2020-11-19 00:23:34 +00:00
|
|
|
readonly value: blst.SecretKey;
|
|
|
|
constructor(value: blst.SecretKey) {
|
2019-08-05 15:48:26 +00:00
|
|
|
this.value = value;
|
|
|
|
}
|
|
|
|
|
2020-11-30 18:01:13 +00:00
|
|
|
static fromBytes(bytes: Uint8Array): SecretKey {
|
2020-11-29 23:52:27 +00:00
|
|
|
// draft-irtf-cfrg-bls-signature-04 does not allow SK == 0
|
|
|
|
if (isZeroUint8Array(bytes)) {
|
2020-11-30 18:01:13 +00:00
|
|
|
throw new ZeroSecretKeyError();
|
2020-11-29 23:52:27 +00:00
|
|
|
}
|
|
|
|
|
2020-11-19 00:23:34 +00:00
|
|
|
const sk = blst.SecretKey.fromBytes(bytes);
|
2020-11-30 18:01:13 +00:00
|
|
|
return new SecretKey(sk);
|
2019-08-05 15:48:26 +00:00
|
|
|
}
|
|
|
|
|
2020-11-30 18:01:13 +00:00
|
|
|
static fromHex(hex: string): SecretKey {
|
2020-11-19 00:23:34 +00:00
|
|
|
return this.fromBytes(hexToBytes(hex));
|
2019-08-05 15:48:26 +00:00
|
|
|
}
|
|
|
|
|
2020-11-30 18:01:13 +00:00
|
|
|
static fromKeygen(entropy?: Uint8Array): SecretKey {
|
2020-11-28 19:27:59 +00:00
|
|
|
const sk = blst.SecretKey.fromKeygen(entropy || randomBytes(SECRET_KEY_LENGTH));
|
2020-11-30 18:01:13 +00:00
|
|
|
return new SecretKey(sk);
|
2019-11-28 11:13:20 +00:00
|
|
|
}
|
|
|
|
|
2020-11-25 16:09:44 +00:00
|
|
|
sign(message: Uint8Array): Signature {
|
2021-04-04 23:44:55 +00:00
|
|
|
return new Signature(this.value.sign(message).value);
|
2019-09-17 19:05:13 +00:00
|
|
|
}
|
|
|
|
|
2020-11-19 00:23:34 +00:00
|
|
|
toPublicKey(): PublicKey {
|
2021-04-04 23:44:55 +00:00
|
|
|
const pk = this.value.toPublicKey();
|
|
|
|
return new PublicKey(pk.value);
|
2019-09-17 19:05:13 +00:00
|
|
|
}
|
|
|
|
|
2020-11-25 16:09:44 +00:00
|
|
|
toBytes(): Uint8Array {
|
|
|
|
return this.value.toBytes();
|
2019-09-17 19:05:13 +00:00
|
|
|
}
|
|
|
|
|
2020-11-19 00:23:34 +00:00
|
|
|
toHex(): string {
|
|
|
|
return bytesToHex(this.toBytes());
|
2019-09-17 19:05:13 +00:00
|
|
|
}
|
2019-08-05 15:48:26 +00:00
|
|
|
}
|