2020-11-25 11:39:49 +00:00
|
|
|
import {SecretKeyType} from "bls-eth-wasm";
|
2020-11-19 13:22:41 +00:00
|
|
|
import {generateRandomSecretKey} from "@chainsafe/bls-keygen";
|
|
|
|
import {SECRET_KEY_LENGTH} from "../constants";
|
|
|
|
import {getContext} from "./context";
|
|
|
|
import {PublicKey} from "./publicKey";
|
|
|
|
import {Signature} from "./signature";
|
2020-11-28 19:52:32 +00:00
|
|
|
import {bytesToHex, hexToBytes} from "../helpers";
|
2020-11-20 19:03:17 +00:00
|
|
|
import {IPrivateKey} from "../interface";
|
2020-11-19 13:22:41 +00:00
|
|
|
|
2020-11-20 19:03:17 +00:00
|
|
|
export class PrivateKey implements IPrivateKey {
|
2020-11-19 13:22:41 +00:00
|
|
|
readonly value: SecretKeyType;
|
|
|
|
|
|
|
|
constructor(value: SecretKeyType) {
|
|
|
|
this.value = value;
|
|
|
|
}
|
|
|
|
|
|
|
|
static fromBytes(bytes: Uint8Array): PrivateKey {
|
2020-11-29 13:57:08 +00:00
|
|
|
if (bytes.length !== SECRET_KEY_LENGTH) {
|
|
|
|
throw Error(`Private key should have ${SECRET_KEY_LENGTH} bytes`);
|
|
|
|
}
|
|
|
|
|
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-19 13:22:41 +00:00
|
|
|
return new PrivateKey(secretKey);
|
|
|
|
}
|
|
|
|
|
|
|
|
static fromHex(hex: string): PrivateKey {
|
|
|
|
return this.fromBytes(hexToBytes(hex));
|
|
|
|
}
|
|
|
|
|
|
|
|
static fromKeygen(entropy?: Uint8Array): PrivateKey {
|
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());
|
|
|
|
}
|
|
|
|
}
|