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/herumi/publicKey.ts

58 lines
1.5 KiB
TypeScript
Raw Normal View History

2020-11-25 11:39:49 +00:00
import {PublicKeyType} from "bls-eth-wasm";
2020-11-19 13:22:41 +00:00
import {getContext} from "./context";
import {EMPTY_PUBLIC_KEY} from "../constants";
import {Signature} from "./signature";
2020-11-20 09:37:44 +00:00
import {bytesToHex, hexToBytes, isEqualBytes} from "../helpers/utils";
2020-11-20 19:03:17 +00:00
import {IPublicKey} from "../interface";
2020-11-19 13:22:41 +00:00
2020-11-20 19:03:17 +00:00
export class PublicKey implements IPublicKey {
2020-11-19 13:22:41 +00:00
readonly value: PublicKeyType;
constructor(value: PublicKeyType) {
this.value = value;
}
static fromBytes(bytes: Uint8Array): PublicKey {
const context = getContext();
const publicKey = new context.PublicKey();
2020-11-20 09:37:44 +00:00
if (!isEqualBytes(EMPTY_PUBLIC_KEY, bytes)) {
2020-11-19 13:22:41 +00:00
publicKey.deserialize(bytes);
}
return new PublicKey(publicKey);
}
static fromHex(hex: string): PublicKey {
return this.fromBytes(hexToBytes(hex));
}
static aggregate(pubkeys: PublicKey[]): PublicKey {
if (pubkeys.length === 0) {
throw Error("EMPTY_AGGREGATE_ARRAY");
}
const agg = new PublicKey(pubkeys[0].value.clone());
for (const pk of pubkeys.slice(1)) {
agg.value.add(pk.value);
}
return agg;
}
2020-11-19 13:22:41 +00:00
add(other: PublicKey): PublicKey {
const agg = new PublicKey(this.value.clone());
agg.value.add(other.value);
return agg;
}
verifyMessage(signature: Signature, messageHash: Uint8Array): boolean {
return this.value.verify(signature.value, messageHash);
}
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());
}
}