-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathpublicKey.ts
82 lines (72 loc) · 2.59 KB
/
publicKey.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import {PublicKeyType} from "bls-eth-wasm";
import {getContext} from "./context.js";
import {bytesToHex, hexToBytes, isZeroUint8Array, validateBytes} from "../helpers/index.js";
import {PointFormat, PublicKey as IPublicKey, PublicKeyArg} from "../types.js";
import {EmptyAggregateError, InvalidLengthError, ZeroPublicKeyError} from "../errors.js";
import {PUBLIC_KEY_LENGTH_COMPRESSED, PUBLIC_KEY_LENGTH_UNCOMPRESSED} from "../constants.js";
export class PublicKey implements IPublicKey {
readonly value: PublicKeyType;
constructor(value: PublicKeyType) {
if (value.isZero()) {
throw new ZeroPublicKeyError();
}
this.value = value;
}
static fromBytes(bytes: Uint8Array): PublicKey {
const context = getContext();
const publicKey = new context.PublicKey();
if (!isZeroUint8Array(bytes)) {
if (bytes.length === PUBLIC_KEY_LENGTH_COMPRESSED) {
publicKey.deserialize(bytes);
} else if (bytes.length === PUBLIC_KEY_LENGTH_UNCOMPRESSED) {
publicKey.deserializeUncompressed(bytes);
} else {
throw new InvalidLengthError("PublicKey", bytes.length);
}
}
return new PublicKey(publicKey);
}
static fromHex(hex: string): PublicKey {
return this.fromBytes(hexToBytes(hex));
}
static aggregate(publicKeys: PublicKeyArg[]): PublicKey {
if (publicKeys.length === 0) {
throw new EmptyAggregateError();
}
const context = getContext();
const agg = new context.PublicKey();
for (const publicKey of publicKeys) {
agg.add(PublicKey.convertToPublicKeyType(publicKey));
}
return new PublicKey(agg);
}
static convertToPublicKeyType(publicKey: PublicKeyArg): PublicKeyType {
let pk: PublicKey;
if (publicKey instanceof Uint8Array) {
validateBytes(publicKey, "publicKey");
pk = PublicKey.fromBytes(publicKey);
} else {
// need to cast to herumi key instead of IPublicKey
pk = publicKey as PublicKey;
}
return pk.value;
}
toBytes(format?: PointFormat): Uint8Array {
if (format === PointFormat.uncompressed) {
return this.value.serializeUncompressed();
} else {
return this.value.serialize();
}
}
toHex(format?: PointFormat): string {
return bytesToHex(this.toBytes(format));
}
multiplyBy(_bytes: Uint8Array): PublicKey {
// TODO: I found this in the code but its not exported. Need to figure out
// how to implement
// const a = getContext();
// const randomness = new a.FR(8);
// return new PublicKey(a.mul(this.value, randomness));
throw new Error("multiplyBy is not implemented by bls-eth-wasm");
}
}