2022-04-11 15:08:15 +00:00
|
|
|
import type {SecretKeyType} from "bls-eth-wasm";
|
2020-11-19 13:22:41 +00:00
|
|
|
import {generateRandomSecretKey} from "@chainsafe/bls-keygen";
|
2022-04-11 15:08:15 +00:00
|
|
|
import {SECRET_KEY_LENGTH} from "../constants.js";
|
|
|
|
import {getContext} from "./context.js";
|
|
|
|
import {PublicKey} from "./publicKey.js";
|
|
|
|
import {Signature} from "./signature.js";
|
|
|
|
import {bytesToHex, hexToBytes} from "../helpers/index.js";
|
|
|
|
import {SecretKey as ISecretKey} from "../interface.js";
|
|
|
|
import {InvalidLengthError, ZeroSecretKeyError} from "../errors.js";
|
2020-11-19 13:22:41 +00:00
|
|
|
|
2020-11-30 18:01:13 +00:00
|
|
|
export class SecretKey implements ISecretKey {
|
2020-11-19 13:22:41 +00:00
|
|
|
readonly value: SecretKeyType;
|
|
|
|
|
|
|
|
constructor(value: SecretKeyType) {
|
2020-11-29 23:35:42 +00:00
|
|
|
if (value.isZero()) {
|
2020-11-30 18:01:13 +00:00
|
|
|
throw new ZeroSecretKeyError();
|
2020-11-29 23:35:42 +00:00
|
|
|
}
|
|
|
|
|
2020-11-19 13:22:41 +00:00
|
|
|
this.value = value;
|
|
|
|
}
|
|
|
|
|
2020-11-30 18:01:13 +00:00
|
|
|
static fromBytes(bytes: Uint8Array): SecretKey {
|
2020-11-29 13:57:08 +00:00
|
|
|
if (bytes.length !== SECRET_KEY_LENGTH) {
|
2020-11-30 18:01:13 +00:00
|
|
|
throw new InvalidLengthError("SecretKey", SECRET_KEY_LENGTH);
|
2020-11-29 13:57:08 +00:00
|
|
|
}
|
|
|
|
|
2020-11-19 13:22:41 +00:00
|
|
|
const context = getContext();
|
|
|
|
const secretKey = new context.SecretKey();
|
2020-11-25 16:09:44 +00:00
|
|
|
secretKey.deserialize(bytes);
|
2020-11-30 18:01:13 +00:00
|
|
|
return new SecretKey(secretKey);
|
2020-11-19 13:22:41 +00:00
|
|
|
}
|
|
|
|
|
2020-11-30 18:01:13 +00:00
|
|
|
static fromHex(hex: string): SecretKey {
|
2020-11-19 13:22:41 +00:00
|
|
|
return this.fromBytes(hexToBytes(hex));
|
|
|
|
}
|
|
|
|
|
2020-11-30 18:01:13 +00:00
|
|
|
static fromKeygen(entropy?: Uint8Array): SecretKey {
|
2020-11-19 14:41:45 +00:00
|
|
|
const sk = generateRandomSecretKey(entropy && Buffer.from(entropy));
|
|
|
|
return this.fromBytes(sk);
|
2020-11-19 13:22:41 +00:00
|
|
|
}
|
|
|
|
|
2020-11-25 16:09:44 +00:00
|
|
|
sign(message: Uint8Array): Signature {
|
2020-11-19 13:22:41 +00:00
|
|
|
return new Signature(this.value.sign(message));
|
|
|
|
}
|
|
|
|
|
|
|
|
toPublicKey(): PublicKey {
|
|
|
|
return new PublicKey(this.value.getPublicKey());
|
|
|
|
}
|
|
|
|
|
2020-11-25 16:09:44 +00:00
|
|
|
toBytes(): Uint8Array {
|
|
|
|
return this.value.serialize();
|
2020-11-19 13:22:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
toHex(): string {
|
|
|
|
return bytesToHex(this.toBytes());
|
|
|
|
}
|
|
|
|
}
|