-
-
Notifications
You must be signed in to change notification settings - Fork 478
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 all commits
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
104 changes: 104 additions & 0 deletions
104
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,104 @@ | ||
| 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"), { | ||
| // The number below is big enough to almost disable the timeout which helps during tests run on unpredictablely slow hosts | ||
| 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 exists", { | ||
| 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.
|
||
| opts.logger.debug("Written keystores to keystore cache"); | ||
| } | ||
|
|
||
| return signers; | ||
| } | ||
17 changes: 17 additions & 0 deletions
17
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,17 @@ | ||
| let defaultPoolSize: number; | ||
|
|
||
| try { | ||
| if (typeof navigator !== "undefined") { | ||
| defaultPoolSize = navigator.hardwareConcurrency ?? 4; | ||
| } else { | ||
| // TODO change this line to use os.availableParallelism() once we upgrade to node v20 | ||
| 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}; | ||
14 changes: 14 additions & 0 deletions
14
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,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.
|
||
| onDecrypt?: (index: number) => void; | ||
| // Try to use the cache file if it exists | ||
| cacheFilePath?: string; | ||
| logger: Pick<Logger, "info" | "warn" | "debug">; | ||
| }; | ||
26 changes: 26 additions & 0 deletions
26
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,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 a memory (and cpu) -intensive process, since decrypting the keystore involves running a key derivation function (either pbkdf2 or scrypt) | ||
| */ | ||
| 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.
|
||
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
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
Oops, something went wrong.
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.