2019-12-11 09:58:24 +00:00
|
|
|
/* eslint-disable require-atomic-updates */
|
2020-11-23 11:06:20 +00:00
|
|
|
import bls from "bls-eth-wasm";
|
2022-04-11 15:08:15 +00:00
|
|
|
import {NotInitializedError} from "../errors.js";
|
2019-11-27 18:21:37 +00:00
|
|
|
|
2020-11-04 13:45:02 +00:00
|
|
|
type Bls = typeof bls;
|
|
|
|
let blsGlobal: Bls | null = null;
|
2020-11-20 19:03:17 +00:00
|
|
|
let blsGlobalPromise: Promise<void> | null = null;
|
2019-11-27 18:21:37 +00:00
|
|
|
|
2020-12-03 19:09:15 +00:00
|
|
|
// Patch to fix multiVerify() calls on a browser with polyfilled NodeJS crypto
|
|
|
|
declare global {
|
|
|
|
interface Window {
|
|
|
|
msCrypto: typeof window["crypto"];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-20 19:03:17 +00:00
|
|
|
export async function setupBls(): Promise<void> {
|
2020-11-04 13:45:02 +00:00
|
|
|
if (!blsGlobal) {
|
2020-11-25 14:00:18 +00:00
|
|
|
await bls.init(bls.BLS12_381);
|
2020-12-03 00:24:30 +00:00
|
|
|
|
|
|
|
// Patch to fix multiVerify() calls on a browser with polyfilled NodeJS crypto
|
|
|
|
if (typeof window === "object") {
|
|
|
|
const crypto = window.crypto || window.msCrypto;
|
2020-12-03 19:09:15 +00:00
|
|
|
// getRandomValues is not typed in `bls-eth-wasm` because it's not meant to be exposed
|
2020-12-03 00:24:30 +00:00
|
|
|
// @ts-ignore
|
|
|
|
bls.getRandomValues = (x) => crypto.getRandomValues(x);
|
|
|
|
}
|
|
|
|
|
2020-11-04 13:45:02 +00:00
|
|
|
blsGlobal = bls;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Cache a promise for Bls instead of Bls to make sure it is initialized only once
|
2020-11-25 16:09:44 +00:00
|
|
|
export async function init(): Promise<void> {
|
2020-11-04 13:45:02 +00:00
|
|
|
if (!blsGlobalPromise) {
|
|
|
|
blsGlobalPromise = setupBls();
|
|
|
|
}
|
|
|
|
return blsGlobalPromise;
|
2019-11-27 18:21:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export function destroy(): void {
|
2020-11-04 13:45:02 +00:00
|
|
|
blsGlobal = null;
|
|
|
|
blsGlobalPromise = null;
|
2019-11-27 18:21:37 +00:00
|
|
|
}
|
|
|
|
|
2020-11-04 13:45:02 +00:00
|
|
|
export function getContext(): Bls {
|
|
|
|
if (!blsGlobal) {
|
2020-11-30 00:20:52 +00:00
|
|
|
throw new NotInitializedError("herumi");
|
2019-11-27 18:21:37 +00:00
|
|
|
}
|
2020-11-04 13:45:02 +00:00
|
|
|
return blsGlobal;
|
2020-11-04 17:40:36 +00:00
|
|
|
}
|