This repository has been archived on 2023-04-09. You can view files and clone it, but cannot push or open issues or pull requests.
chainsafe-bls/src/publicKey.ts

67 lines
1.7 KiB
TypeScript
Raw Normal View History

2019-08-05 15:48:26 +00:00
import {PrivateKey} from "./privateKey";
2019-11-27 20:58:41 +00:00
import {PublicKeyType} from "@chainsafe/eth2-bls-wasm";
import {getContext} from "./context";
import {PUBLIC_KEY_LENGTH} from "./constants";
import assert from "assert";
import {Signature} from "./signature";
2019-12-11 09:58:24 +00:00
import {EMPTY_PUBLIC_KEY} from "./helpers/utils";
2019-08-05 15:48:26 +00:00
export class PublicKey {
2019-11-27 20:58:41 +00:00
private value: PublicKeyType;
2019-08-05 15:48:26 +00:00
2019-11-27 20:58:41 +00:00
protected constructor(value: PublicKeyType) {
this.value = value;
2019-08-05 15:48:26 +00:00
}
2020-02-04 22:30:10 +00:00
2019-08-05 15:48:26 +00:00
public static fromPrivateKey(privateKey: PrivateKey): PublicKey {
2019-11-27 20:58:41 +00:00
return privateKey.toPublicKey();
}
2020-02-04 22:30:10 +00:00
public static fromBytes(bytes: Uint8Array): PublicKey {
2019-11-27 20:58:41 +00:00
const context = getContext();
const publicKey = new context.PublicKey();
2020-01-21 16:46:21 +00:00
if(!EMPTY_PUBLIC_KEY.equals(bytes)) {
2019-12-11 09:58:24 +00:00
publicKey.deserialize(bytes);
}
2019-08-05 15:48:26 +00:00
return new PublicKey(
2019-11-27 20:58:41 +00:00
publicKey
2019-08-05 15:48:26 +00:00
);
}
2019-11-27 20:58:41 +00:00
public static fromHex(value: string): PublicKey {
value = value.replace("0x", "");
assert(value.length === PUBLIC_KEY_LENGTH * 2);
const context = getContext();
2019-08-05 15:48:26 +00:00
return new PublicKey(
2019-11-27 20:58:41 +00:00
context.deserializeHexStrToPublicKey(value)
2019-08-05 15:48:26 +00:00
);
}
2019-08-28 15:18:51 +00:00
2019-11-27 20:58:41 +00:00
public static fromPublicKeyType(value: PublicKeyType): PublicKey {
return new PublicKey(value);
}
public add(other: PublicKey): PublicKey {
const agg = new PublicKey(this.value.clone());
agg.value.add(other.value);
return agg;
}
public verifyMessage(signature: Signature, messageHash: Uint8Array): boolean {
return this.value.verifyHashWithDomain(signature.getValue(), messageHash);
2019-08-28 15:18:51 +00:00
}
2020-02-04 22:30:10 +00:00
public toBytesCompressed(): Buffer {
2019-11-27 20:58:41 +00:00
return Buffer.from(this.value.serialize());
2019-08-28 15:18:51 +00:00
}
public toHexString(): string {
2020-02-19 19:15:57 +00:00
return `0x${this.toBytesCompressed().toString("hex")}`;
2019-08-28 15:18:51 +00:00
}
2019-11-27 20:58:41 +00:00
public getValue(): PublicKeyType {
return this.value;
}
2019-08-05 15:48:26 +00:00
}