Skip to content

Commit

Permalink
fix: lock KeyringController mutex on verifySeedPhrase (#5077)
Browse files Browse the repository at this point in the history
## Explanation

<!--
Thanks for your contribution! Take a moment to answer these questions so
that reviewers have the information they need to properly understand
your changes:

* What is the current state of things and why does it need to change?
* What is the solution your changes offer and how does it work?
* Are there any changes whose purpose might not obvious to those
unfamiliar with the domain?
* If your primary goal was to update one package but you found you had
to update another one along the way, why did you do so?
* If you had to upgrade a dependency, why did you do so?
-->
The `KeyringController.verifySeedPhrase` method was not included in the
mutable methods that lock the controller mutex because it doesn't change
the state. Though, if another operation gets somehow overlapped (e.g. a
consumer calls `addNewAccount`), the call to `verifySeedPhrase` can
potentially fail.

To fix this, this PR is moving verifySeedPhrase behind
KeyringController's mutex. Since `addNewAccount` internally calls
`verifySeedPhrase`, and having a lock on both would create a deadlock,
the `verifySeedPhrase` implementation has been moved to an internal
method.

## References

<!--
Are there any issues that this pull request is tied to?
Are there other links that reviewers should consult to understand these
changes better?
Are there client or consumer pull requests to adopt any breaking
changes?

For example:

* Fixes #12345
* Related to #67890
-->

## Changelog

<!--
If you're making any consumer-facing changes, list those changes here as
if you were updating a changelog, using the template below as a guide.

(CATEGORY is one of BREAKING, ADDED, CHANGED, DEPRECATED, REMOVED, or
FIXED. For security-related issues, follow the Security Advisory
process.)

Please take care to name the exact pieces of the API you've added or
changed (e.g. types, interfaces, functions, or methods).

If there are any breaking changes, make sure to offer a solution for
consumers to follow once they upgrade to the changes.

Finally, if you're only making changes to development scripts or tests,
you may replace the template below with "None".
-->

### `@metamask/keyring-controller`

- **FIXED**:  `verifySeedPhrase` is now mutually exclusive

## Checklist

- [ ] I've updated the test suite for new or updated code as appropriate
- [ ] I've updated documentation (JSDoc, Markdown, etc.) for new or
updated code as appropriate
- [ ] I've highlighted breaking changes using the "BREAKING" category
above as appropriate
- [ ] I've prepared draft pull requests for clients and consumer
packages to resolve any breaking changes
  • Loading branch information
mikesposito authored Dec 17, 2024
1 parent 6c2197f commit 99cd1a2
Showing 1 changed file with 53 additions and 42 deletions.
95 changes: 53 additions & 42 deletions packages/keyring-controller/src/KeyringController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -686,7 +686,7 @@ export class KeyringController extends BaseController<
}

const [addedAccountAddress] = await primaryKeyring.addAccounts(1);
await this.verifySeedPhrase();
await this.#verifySeedPhrase();

return addedAccountAddress;
});
Expand Down Expand Up @@ -1356,47 +1356,7 @@ export class KeyringController extends BaseController<
* @returns Promise resolving to the seed phrase as Uint8Array.
*/
async verifySeedPhrase(): Promise<Uint8Array> {
const primaryKeyring = this.getKeyringsByType(KeyringTypes.hd)[0] as
| EthKeyring<Json>
| undefined;
if (!primaryKeyring) {
throw new Error('No HD keyring found.');
}

assertHasUint8ArrayMnemonic(primaryKeyring);

const seedWords = primaryKeyring.mnemonic;
const accounts = await primaryKeyring.getAccounts();
/* istanbul ignore if */
if (accounts.length === 0) {
throw new Error('Cannot verify an empty keyring.');
}

// The HD Keyring Builder is a default keyring builder
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const hdKeyringBuilder = this.#getKeyringBuilderForType(KeyringTypes.hd)!;

const hdKeyring = hdKeyringBuilder();
// @ts-expect-error @metamask/eth-hd-keyring correctly handles
// Uint8Array seed phrases in the `deserialize` method.
await hdKeyring.deserialize({
mnemonic: seedWords,
numberOfAccounts: accounts.length,
});
const testAccounts = await hdKeyring.getAccounts();
/* istanbul ignore if */
if (testAccounts.length !== accounts.length) {
throw new Error('Seed phrase imported incorrect number of accounts.');
}

testAccounts.forEach((account: string, i: number) => {
/* istanbul ignore if */
if (account.toLowerCase() !== accounts[i].toLowerCase()) {
throw new Error('Seed phrase imported different accounts.');
}
});

return seedWords;
return this.#withControllerLock(async () => this.#verifySeedPhrase());
}

/**
Expand Down Expand Up @@ -1883,6 +1843,57 @@ export class KeyringController extends BaseController<
this.#setUnlocked();
}

/**
* Internal non-exclusive method to verify the seed phrase.
*
* @returns A promise resolving to the seed phrase as Uint8Array.
*/
async #verifySeedPhrase(): Promise<Uint8Array> {
this.#assertControllerMutexIsLocked();

const primaryKeyring = this.getKeyringsByType(KeyringTypes.hd)[0] as
| EthKeyring<Json>
| undefined;
if (!primaryKeyring) {
throw new Error('No HD keyring found.');
}

assertHasUint8ArrayMnemonic(primaryKeyring);

const seedWords = primaryKeyring.mnemonic;
const accounts = await primaryKeyring.getAccounts();
/* istanbul ignore if */
if (accounts.length === 0) {
throw new Error('Cannot verify an empty keyring.');
}

// The HD Keyring Builder is a default keyring builder
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const hdKeyringBuilder = this.#getKeyringBuilderForType(KeyringTypes.hd)!;

const hdKeyring = hdKeyringBuilder();
// @ts-expect-error @metamask/eth-hd-keyring correctly handles
// Uint8Array seed phrases in the `deserialize` method.
await hdKeyring.deserialize({
mnemonic: seedWords,
numberOfAccounts: accounts.length,
});
const testAccounts = await hdKeyring.getAccounts();
/* istanbul ignore if */
if (testAccounts.length !== accounts.length) {
throw new Error('Seed phrase imported incorrect number of accounts.');
}

testAccounts.forEach((account: string, i: number) => {
/* istanbul ignore if */
if (account.toLowerCase() !== accounts[i].toLowerCase()) {
throw new Error('Seed phrase imported different accounts.');
}
});

return seedWords;
}

/**
* Get the updated array of each keyring's type and
* accounts list.
Expand Down

0 comments on commit 99cd1a2

Please sign in to comment.