Repository navigation
Decrypt keystores in a thread pool #5357
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 11 commits
09e324c
66d5771
65a8668
0096e30
b520e04
a029871
7911a45
e430bda
a42fddd
a9de4b1
c6ab33f
4f58946
a096fe9
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| import {spawn, ModuleThread, Pool, QueuedTask, Worker} from "@chainsafe/threads"; | ||
| import {SignerLocal, SignerType} from "@lodestar/validator"; | ||
| import bls from "@chainsafe/bls"; | ||
| import {LocalKeystoreDefinition} from "../interface.js"; | ||
| import {clearKeystoreCache, loadKeystoreCache, writeKeystoreCache} from "../keystoreCache.js"; | ||
| import {lockFilepath, unlockFilepath} from "../../../../util/lockfile.js"; | ||
| import {defaultPoolSize} from "./poolSize.js"; | ||
| import {DecryptKeystoreWorkerAPI, KeystoreDecryptOptions} from "./types.js"; | ||
|
|
||
| /** | ||
| * Decrypt keystore definitions using a threadpool | ||
| */ | ||
| export async function decryptKeystoreDefinitions( | ||
| keystoreDefinitions: LocalKeystoreDefinition[], | ||
| opts: KeystoreDecryptOptions | ||
| ): Promise<SignerLocal[]> { | ||
| if (opts.cacheFilePath) { | ||
| try { | ||
| const signers = await loadKeystoreCache(opts.cacheFilePath, keystoreDefinitions); | ||
| if (opts?.onDecrypt) { | ||
| opts?.onDecrypt(signers.length - 1); | ||
| } | ||
| opts.logger.debug("Loaded keystores via keystore cache"); | ||
| return signers; | ||
| } catch { | ||
| // Some error loading the cache, ignore and invalidate cache | ||
| await clearKeystoreCache(opts.cacheFilePath); | ||
| } | ||
| } | ||
|
|
||
| const signers = new Array(keystoreDefinitions.length) as SignerLocal[]; | ||
| const passwords = new Array(keystoreDefinitions.length) as string[]; | ||
| const tasks: QueuedTask<ModuleThread<DecryptKeystoreWorkerAPI>, Uint8Array>[] = []; | ||
| const errors: Error[] = []; | ||
| const pool = Pool( | ||
| () => | ||
| spawn<DecryptKeystoreWorkerAPI>(new Worker("./worker.js"), { | ||
| // A Lodestar Node may do very expensive task at start blocking the event loop and causing | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This comment seems a bit out of place, should probably be revised. In case of loading the keys there is really nothing else going on as this is a blocking operation |
||
| // the initialization to timeout. The number below is big enough to almost disable the timeout | ||
| timeout: 5 * 60 * 1000, | ||
| }), | ||
| defaultPoolSize | ||
| ); | ||
| for (const [index, definition] of keystoreDefinitions.entries()) { | ||
| try { | ||
| lockFilepath(definition.keystorePath); | ||
| } catch (e) { | ||
| if (opts.ignoreLockFile) { | ||
| opts.logger.warn("Keystore forcefully loaded even though lockfile could not be acquired", { | ||
|
wemeetagain marked this conversation as resolved.
Resolved
|
||
| path: definition.keystorePath, | ||
| }); | ||
| } else { | ||
| throw e; | ||
| } | ||
| } | ||
|
|
||
| const task = pool.queue((thread) => thread.decryptKeystoreDefinition(definition)); | ||
| tasks.push(task); | ||
| task | ||
| .then((secretKeyBytes: Uint8Array) => { | ||
| const signer: SignerLocal = { | ||
| type: SignerType.Local, | ||
| secretKey: bls.SecretKey.fromBytes(secretKeyBytes), | ||
| }; | ||
|
|
||
| signers[index] = signer; | ||
| passwords[index] = definition.password; | ||
|
|
||
| if (opts?.onDecrypt) { | ||
| opts?.onDecrypt(index); | ||
| } | ||
| }) | ||
| .catch((e: Error) => { | ||
| // In-progress tasks can't be canceled, so there's a chance that multiple errors may be caught | ||
| // add to the list of errors | ||
| errors.push(e); | ||
| // cancel all pending tasks, no need to continue decrypting after we hit one error | ||
| for (const task of tasks) { | ||
| task.cancel(); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| try { | ||
| // only resolves if there are no errored tasks | ||
| await pool.completed(true); | ||
| } catch (e) { | ||
| // If an error occurs, the program isn't going to be running, | ||
| // so we should unlock all lockfiles we created | ||
| for (const {keystorePath} of keystoreDefinitions) { | ||
| unlockFilepath(keystorePath); | ||
| } | ||
|
|
||
| throw new AggregateError(errors); | ||
| } finally { | ||
| await pool.terminate(); | ||
| } | ||
|
|
||
| if (opts.cacheFilePath) { | ||
| await writeKeystoreCache(opts.cacheFilePath, signers, passwords); | ||
|
wemeetagain marked this conversation as resolved.
Resolved
|
||
| opts.logger.debug("Written keystores to keystore cache"); | ||
| } | ||
|
|
||
| return signers; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| let defaultPoolSize: number; | ||
|
|
||
| try { | ||
| if (typeof navigator !== "undefined") { | ||
| defaultPoolSize = navigator.hardwareConcurrency ?? 4; | ||
| } else { | ||
| defaultPoolSize = (await import("node:os")).cpus().length; | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. noting here that we should change this line to use os.availableParallelism() once we upgrade to node v20 |
||
| } | ||
| } catch (e) { | ||
| defaultPoolSize = 8; | ||
| } | ||
|
|
||
| /** | ||
| * Cross-platform aprox number of logical cores | ||
| */ | ||
| export {defaultPoolSize}; | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| import {Logger} from "@lodestar/utils"; | ||
| import {LocalKeystoreDefinition} from "../interface.js"; | ||
|
|
||
| export type DecryptKeystoreWorkerAPI = { | ||
| decryptKeystoreDefinition({keystorePath, password}: LocalKeystoreDefinition): Promise<Uint8Array>; | ||
| }; | ||
|
|
||
| export type KeystoreDecryptOptions = { | ||
| ignoreLockFile?: boolean; | ||
|
nflaig marked this conversation as resolved.
Resolved
|
||
| onDecrypt?: (index: number) => void; | ||
| // Try to use the cache file if it exists | ||
| cacheFilePath?: string; | ||
| logger: Pick<Logger, "info" | "warn" | "debug">; | ||
| }; | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| import fs from "node:fs"; | ||
| import {expose} from "@chainsafe/threads/worker"; | ||
| import {Transfer, TransferDescriptor} from "@chainsafe/threads"; | ||
| import {Keystore} from "@chainsafe/bls-keystore"; | ||
| import {LocalKeystoreDefinition} from "../interface.js"; | ||
| import {DecryptKeystoreWorkerAPI} from "./types.js"; | ||
|
|
||
| /** | ||
| * Decrypt a single keystore definition, returning the secret key as a Uint8Array | ||
| * | ||
| * NOTE: This is memory-intensive process, since decrypting the keystore involves running a key derivation function (either pbkdf2 or scrypt) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
| */ | ||
| export async function decryptKeystoreDefinition({ | ||
| keystorePath, | ||
| password, | ||
| }: LocalKeystoreDefinition): Promise<TransferDescriptor<Uint8Array>> { | ||
| const keystore = Keystore.parse(fs.readFileSync(keystorePath, "utf8")); | ||
|
|
||
| // Memory-hogging function | ||
| const secret = await keystore.decrypt(password); | ||
| // Transfer the underlying ArrayBuffer back to the main thread: https://threads.js.org/usage-advanced#transferable-objects | ||
| // This small performance gain may help in cases where this is run for many keystores | ||
| return Transfer(secret, [secret.buffer]); | ||
| } | ||
|
|
||
| expose({decryptKeystoreDefinition} as unknown as DecryptKeystoreWorkerAPI); | ||
|
nflaig marked this conversation as resolved.
Resolved
|
||

Uh oh!
There was an error while loading. Please reload this page.