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/context.ts

51 lines
1.3 KiB
TypeScript
Raw Normal View History

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";
import {NotInitializedError} from "../errors.js";
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;
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);
// 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
// @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;
}
export function destroy(): void {
2020-11-04 13:45:02 +00:00
blsGlobal = null;
blsGlobalPromise = null;
}
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");
}
2020-11-04 13:45:02 +00:00
return blsGlobal;
2020-11-04 17:40:36 +00:00
}