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
Merged
Merged
Changes from 1 commit
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
09e324c
Decrypt keystores in a thread pool
wemeetagain 66d5771
Add tests
wemeetagain 65a8668
Add logs
wemeetagain 0096e30
Transfer secret ArrayBuffer back to the main thread
wemeetagain b520e04
fix progress log
wemeetagain a029871
rename 'force' to 'ignoreLockFile'
wemeetagain 7911a45
remove unused force param
wemeetagain e430bda
Fix keystore cache issue
wemeetagain a42fddd
Use higher job concurrency
wemeetagain a9de4b1
Revert "Use higher job concurrency"
wemeetagain c6ab33f
Explicitly assign args when calling decryptKeystoreDefinitions
wemeetagain 4f58946
Apply suggestions from code review
wemeetagain a096fe9
Address PR comments
wemeetagain File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
94 changes: 94 additions & 0 deletions
94
packages/cli/src/cmds/validator/keymanager/decryptKeystoreDefinitions/index.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| import {spawn, ModuleThread, Pool, QueuedTask, Worker} from "@chainsafe/threads"; | ||
| import {Signer, 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<Signer[]> { | ||
| if (opts.cacheFilePath) { | ||
| try { | ||
| const signers = await loadKeystoreCache(opts.cacheFilePath, keystoreDefinitions); | ||
| if (opts?.onDecrypt) { | ||
| opts?.onDecrypt(signers.length - 1); | ||
| } | ||
| return signers; | ||
| } catch { | ||
| // Some error loading the cache, ignore and invalidate cache | ||
| await clearKeystoreCache(opts.cacheFilePath); | ||
| } | ||
| } | ||
|
|
||
| const signers: SignerLocal[] = []; | ||
| const passwords: string[] = []; | ||
| const tasks: QueuedTask<ModuleThread<DecryptKeystoreWorkerAPI>, Uint8Array>[] = []; | ||
| const errors: Error[] = []; | ||
|
|
||
| const pool = Pool(() => spawn<DecryptKeystoreWorkerAPI>(new Worker("./worker.js")), defaultPoolSize); | ||
| for (const [index, definition] of keystoreDefinitions.entries()) { | ||
| try { | ||
| lockFilepath(definition.keystorePath); | ||
| } catch (e) { | ||
| if (opts.force) { | ||
| // Ignore error, maybe log? | ||
|
wemeetagain marked this conversation as resolved.
Resolved
|
||
| } else { | ||
| throw e; | ||
| } | ||
| } | ||
|
|
||
| const task = pool.queue((thread) => thread.decryptKeystoreDefinition(definition, Boolean(opts.force))); | ||
| tasks.push(task); | ||
| task | ||
| .then((secretKeyBytes: Uint8Array) => { | ||
| const signer: SignerLocal = { | ||
| type: SignerType.Local, | ||
| secretKey: bls.SecretKey.fromBytes(secretKeyBytes), | ||
| }; | ||
|
|
||
| signers.push(signer); | ||
| passwords.push(definition.password); | ||
|
wemeetagain marked this conversation as resolved.
Resolved
|
||
|
|
||
| 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(); | ||
|
wemeetagain marked this conversation as resolved.
Resolved
|
||
| } 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
|
||
| } | ||
|
|
||
| return signers; | ||
| } | ||
16 changes: 16 additions & 0 deletions
16
packages/cli/src/cmds/validator/keymanager/decryptKeystoreDefinitions/poolSize.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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}; | ||
12 changes: 12 additions & 0 deletions
12
packages/cli/src/cmds/validator/keymanager/decryptKeystoreDefinitions/types.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| import {LocalKeystoreDefinition} from "../interface.js"; | ||
|
|
||
| export type DecryptKeystoreWorkerAPI = { | ||
| decryptKeystoreDefinition({keystorePath, password}: LocalKeystoreDefinition, force: boolean): Promise<Uint8Array>; | ||
|
wemeetagain marked this conversation as resolved.
Resolved
|
||
| }; | ||
|
|
||
| export type KeystoreDecryptOptions = { | ||
| force?: boolean; | ||
| onDecrypt?: (index: number) => void; | ||
| // Try to use the cache file if it exists | ||
| cacheFilePath?: string; | ||
| }; | ||
22 changes: 22 additions & 0 deletions
22
packages/cli/src/cmds/validator/keymanager/decryptKeystoreDefinitions/worker.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| import fs from "node:fs"; | ||
| import {expose} from "@chainsafe/threads/worker"; | ||
| 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<Uint8Array> { | ||
| const keystore = Keystore.parse(fs.readFileSync(keystorePath, "utf8")); | ||
|
|
||
| // Memory-hogging function | ||
| return keystore.decrypt(password); | ||
| } | ||
|
|
||
| expose({decryptKeystoreDefinition} as DecryptKeystoreWorkerAPI); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
packages/cli/src/cmds/validator/signers/importExternalKeystores.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.

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