diff --git a/packages/keyring-eth-money-mpc/CHANGELOG.md b/packages/keyring-eth-money-mpc/CHANGELOG.md index 2c4756e5f..50f0b531e 100644 --- a/packages/keyring-eth-money-mpc/CHANGELOG.md +++ b/packages/keyring-eth-money-mpc/CHANGELOG.md @@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Changed + +- **BREAKING:** Convert `MpcMoneyKeyring` to `AtomicKeyring` and require an `updater` constructor option ([#726](https://github.com/MetaMask/accounts/pull/726)) + - Register an atomic builder with a controller that supports atomic keyrings and forward its updater. + - Run networking outside the controller mutex and persist runtime state changes through atomic updates, including read-only setup. + - Preserve existing serialized states and retain committed updates when an operation later fails. + ## [0.5.0] ### Added diff --git a/packages/keyring-eth-money-mpc/README.md b/packages/keyring-eth-money-mpc/README.md index f1cf1e0fa..8d37bd2ae 100644 --- a/packages/keyring-eth-money-mpc/README.md +++ b/packages/keyring-eth-money-mpc/README.md @@ -4,6 +4,34 @@ A Keyring for Ethereum money accounts that uses Multi-Party Computation (MPC) fo The default export is the V1 `MpcMoneyKeyring` implementation. A V2 adapter that wraps it is available from `@metamask/eth-money-mpc-keyring/v2`. +## Atomic state updates + +`MpcMoneyKeyring` extends `AtomicKeyring` and requires an `updater` constructor option. +Use a `KeyringController` version with atomic-keyring support and register an atomic builder that forwards the controller's updater: + +```typescript +import type { KeyringBuilderContext } from '@metamask/keyring-controller'; + +import { MpcMoneyKeyring } from '@metamask/eth-money-mpc-keyring'; + +// options contains the remaining MpcMoneyKeyringOpts constructor options. +const builder = Object.assign( + ({ update }: KeyringBuilderContext) => + new MpcMoneyKeyring({ ...options, updater: update }), + { type: MpcMoneyKeyring.type, atomic: true as const }, +); +``` + +Setup, signing, rotation, and sync hold the keyring's own write lock, not the controller mutex. +Share checks use a shared read lock. +The controller mutex is acquired only for state commits through the updater. +This includes address-only setup in read-only mode. +The V2 adapter delegates to the same atomic V1 instance and needs no separate updater. + +`serialize` and `getAccounts` return the current state without waiting for network operations. +Committed updates survive later operation errors. Existing serialized states remain compatible. +Setup must still be called explicitly after registration, outside construction or vault restoration. + ## MFA The backend decides which signature requests require MFA, using [`getMfaRequirement`](https://github.com/MetaMask/core/tree/main/packages/money-account-mfa-whitelist). The keyring doesn't check the request itself, so the backend can change its whitelist without a client update. diff --git a/packages/keyring-eth-money-mpc/src/cloud.ts b/packages/keyring-eth-money-mpc/src/cloud.ts index 8675d3b58..b4e4b6346 100644 --- a/packages/keyring-eth-money-mpc/src/cloud.ts +++ b/packages/keyring-eth-money-mpc/src/cloud.ts @@ -67,9 +67,8 @@ function readStruct( } /** - * Cloud HTTP calls must finish within this window. Keyring methods run under - * the controller mutex, so a backend that never responds would block every - * keyring operation until the client restarts. + * Bound cloud HTTP calls so an unresponsive backend does not indefinitely + * block subsequent operations on this keyring. */ const CLOUD_REQUEST_TIMEOUT_MS = 30_000; diff --git a/packages/keyring-eth-money-mpc/src/mpc-money-keyring.test.ts b/packages/keyring-eth-money-mpc/src/mpc-money-keyring.test.ts index 0e2bd6999..15495b3fb 100644 --- a/packages/keyring-eth-money-mpc/src/mpc-money-keyring.test.ts +++ b/packages/keyring-eth-money-mpc/src/mpc-money-keyring.test.ts @@ -1,6 +1,7 @@ /* eslint-disable @typescript-eslint/explicit-function-return-type */ import { hashPersonalMessage } from '@ethereumjs/util'; -import { KeyRoot } from '@metamask/keyring-sdk'; +import { isAtomicKeyring, KeyRoot } from '@metamask/keyring-sdk'; +import type { AtomicUpdater } from '@metamask/keyring-sdk'; import { bytesToHex } from '@metamask/utils'; import type { Hex, Json } from '@metamask/utils'; @@ -28,6 +29,11 @@ const mockCheckKeyShare = jest.fn(); const mockSetActiveEpoch = jest.fn(); const mockLoadKeyShareBackup = jest.fn(); let lastNetworkManagerOptions: Record | undefined; +let committedStates: Json[] = []; +const mockUpdater = jest.fn< + ReturnType, + Parameters +>(); const mockDerivedAddress = '0x1111111111111111111111111111111111111111' as Hex; const mockSessionNonce = @@ -172,6 +178,19 @@ const makeSerializedState = (overrides: Record = {}) => ({ const encodeText = (value: string): Uint8Array => new TextEncoder().encode(value); +/** + * Create a gate for controlling an asynchronous operation in a test. + * + * @returns A promise and a function that resolves it. + */ +function createGate(): { promise: Promise; resolve: () => void } { + let resolve!: () => void; + const promise = new Promise((resolvePromise) => { + resolve = resolvePromise; + }); + return { promise, resolve }; +} + const makeRootSession = (statusPayload = 'data persisted') => { const session = { sendMessage: jest.fn(), @@ -197,6 +216,7 @@ const makeKeyring = ( isMfaAvailable = true, ) => new MpcMoneyKeyring({ + updater: mockUpdater, isMfaAvailable, cl24Lib: {} as never, dkls23Lib: {} as never, @@ -216,6 +236,14 @@ const deserializeState = async ( describe('MpcMoneyKeyring', () => { beforeEach(() => { lastNetworkManagerOptions = undefined; + committedStates = []; + mockUpdater.mockImplementation(async (keyring, action) => { + await action(); + if (!(keyring instanceof MpcMoneyKeyring)) { + throw new Error('Unexpected keyring'); + } + committedStates.push(await keyring.serialize()); + }); const mockedUtil = jest.requireMock('./util'); @@ -264,11 +292,175 @@ describe('MpcMoneyKeyring', () => { expect(keyring.type).toBe('MPC Money Keyring'); }); + describe('atomic updates', () => { + it('brands the keyring as atomic', () => { + expect(isAtomicKeyring(makeKeyring())).toBe(true); + }); + + it('hydrates state without invoking the updater', async () => { + const keyring = makeKeyring(); + await deserializeState(keyring); + + expect(mockUpdater).not.toHaveBeenCalled(); + }); + + it('keeps snapshot reads available while a write waits for the network', async () => { + const keyring = makeKeyring(); + await deserializeState(keyring); + const started = createGate(); + const network = createGate(); + mockLoadKeyShareBackup.mockImplementationOnce(async () => { + started.resolve(); + await network.promise; + return { + encryptedKeyShare: encodeText('{}'), + epoch: 2, + }; + }); + mockThresholdKeyFromJson.mockReturnValueOnce(makeThresholdKey()); + + const sync = keyring.syncKeyShare(); + await started.promise; + try { + expect(await keyring.serialize()).toStrictEqual(makeSerializedState()); + expect(await keyring.getAccounts()).toStrictEqual([mockDerivedAddress]); + expect(mockUpdater).not.toHaveBeenCalled(); + } finally { + network.resolve(); + await sync; + } + + expect(mockUpdater).toHaveBeenCalledWith(keyring, expect.any(Function)); + expect(committedStates).toStrictEqual([ + makeSerializedState({ shareEpoch: 2, tssSetup: null }), + ]); + }); + + it('does not expose a mutation before the updater runs its action', async () => { + const keyring = makeKeyring(); + await deserializeState(keyring); + mockThresholdKeyFromJson.mockReturnValueOnce(makeThresholdKey()); + const started = createGate(); + const commit = createGate(); + mockUpdater.mockImplementationOnce(async (_keyring, action) => { + started.resolve(); + await commit.promise; + await action(); + }); + + const sync = keyring.syncKeyShare(); + await started.promise; + try { + expect(await keyring.serialize()).toStrictEqual(makeSerializedState()); + } finally { + commit.resolve(); + await sync; + } + + expect(await keyring.serialize()).toStrictEqual( + makeSerializedState({ tssSetup: null }), + ); + }); + + it('waits for a write before checking the resulting share epoch', async () => { + const keyring = makeKeyring(); + await deserializeState(keyring); + const started = createGate(); + const network = createGate(); + mockLoadKeyShareBackup.mockImplementationOnce(async () => { + started.resolve(); + await network.promise; + return { encryptedKeyShare: encodeText('{}'), epoch: 2 }; + }); + mockThresholdKeyFromJson.mockReturnValueOnce(makeThresholdKey()); + mockCheckKeyShare.mockResolvedValueOnce({ + latestShareEpoch: 2, + latestBackupEpoch: 2, + activeEpoch: 2, + }); + + const sync = keyring.syncKeyShare(); + await started.promise; + const check = keyring.checkKeyShare(); + expect(mockCheckKeyShare).not.toHaveBeenCalled(); + network.resolve(); + await sync; + expect(await check).toBe(true); + }); + + it('runs share checks in parallel without committing state', async () => { + const keyring = makeKeyring(); + await deserializeState(keyring); + const bothStarted = createGate(); + const network = createGate(); + let started = 0; + mockCheckKeyShare.mockImplementation(async () => { + started += 1; + if (started === 2) { + bothStarted.resolve(); + } + await network.promise; + return { + latestShareEpoch: 1, + latestBackupEpoch: 1, + activeEpoch: 1, + }; + }); + + const first = keyring.checkKeyShare(); + const second = keyring.checkKeyShare(); + await bothStarted.promise; + network.resolve(); + + expect(await Promise.all([first, second])).toStrictEqual([true, true]); + expect(mockUpdater).not.toHaveBeenCalled(); + }); + + it('propagates an updater rejection without starting TSS signing', async () => { + const keyring = makeKeyring(); + await deserializeState(keyring); + const session = makeRootSession('signing completed'); + mockCreateSession.mockResolvedValueOnce(session); + mockUpdater.mockRejectedValueOnce(new Error('Keyring detached')); + + await expect( + keyring.signPersonalMessage(mockDerivedAddress, '0x1234'), + ).rejects.toThrow('Keyring detached'); + + expect(mockDklsSign).not.toHaveBeenCalled(); + expect(session.disconnect).toHaveBeenCalledTimes(1); + expect(await keyring.serialize()).toStrictEqual(makeSerializedState()); + + // A rejected commit must release the keyring's write lock. + mockCreateSession.mockResolvedValueOnce(session); + await keyring.signPersonalMessage(mockDerivedAddress, '0x1234'); + expect(mockDklsSign).toHaveBeenCalledTimes(1); + }); + + it('retains committed setup when network cleanup fails', async () => { + const keyring = makeKeyring(); + await deserializeState(keyring, makeSerializedState({ tssSetup: null })); + const session = makeRootSession('signing completed'); + session.disconnect.mockRejectedValueOnce(new Error('Disconnect failed')); + mockCreateSession.mockResolvedValueOnce(session); + + await expect( + keyring.signPersonalMessage(mockDerivedAddress, '0x1234'), + ).rejects.toThrow('Disconnect failed'); + + expect(committedStates).toStrictEqual([ + makeSerializedState({ tssSetup: '0x010203' }), + ]); + expect(await keyring.serialize()).toStrictEqual(committedStates[0]); + }); + }); + it('wires network manager options', () => { const transportToken = jest.fn().mockResolvedValue('transport-token'); const webSocket = { send: jest.fn() }; const keyring = new MpcMoneyKeyring({ + updater: mockUpdater, isMfaAvailable: true, cl24Lib: {} as never, dkls23Lib: {} as never, @@ -451,6 +643,7 @@ describe('MpcMoneyKeyring', () => { shareEpoch: 1, tssSetup: '0x010203', }); + expect(committedStates).toStrictEqual([await keyring.serialize()]); }); it.each([ @@ -686,6 +879,7 @@ describe('MpcMoneyKeyring', () => { shareEpoch: mockShareEpoch, tssSetup: null, }); + expect(committedStates).toStrictEqual([await keyring.serialize()]); }); it('setup is a no-op when already initialized', async () => { @@ -818,6 +1012,7 @@ describe('MpcMoneyKeyring', () => { shareEpoch: 2, tssSetup: null, }); + expect(committedStates).toStrictEqual([await keyring.serialize()]); }); it('checks whether local and backend epochs match', async () => { @@ -1165,6 +1360,10 @@ describe('MpcMoneyKeyring', () => { expect(await keyring.serialize()).toStrictEqual( expect.objectContaining({ tssSetup: null }), ); + expect(committedStates).toStrictEqual([ + makeSerializedState(), + makeSerializedState({ tssSetup: null }), + ]); }); it('serializes concurrent sign calls', async () => { @@ -1192,7 +1391,7 @@ describe('MpcMoneyKeyring', () => { expect(maxInFlight).toBe(1); }); - it('serializes sign, rotate, and sync on one op queue', async () => { + it('serializes sign, rotate, and sync with the write lock', async () => { const keyring = makeKeyring(); await deserializeState(keyring); @@ -1451,6 +1650,7 @@ describe('MpcMoneyKeyring', () => { expect(await keyring.serialize()).toStrictEqual({ address: mockDerivedAddress, }); + expect(committedStates).toStrictEqual([{ address: mockDerivedAddress }]); }); it.each([ diff --git a/packages/keyring-eth-money-mpc/src/mpc-money-keyring.ts b/packages/keyring-eth-money-mpc/src/mpc-money-keyring.ts index fbf7b2059..972881dd7 100644 --- a/packages/keyring-eth-money-mpc/src/mpc-money-keyring.ts +++ b/packages/keyring-eth-money-mpc/src/mpc-money-keyring.ts @@ -8,7 +8,7 @@ import type { } from '@metamask/eth-sig-util'; import { hashEIP7702Authorization } from '@metamask/eth-sig-util'; import { Purpose } from '@metamask/key-derivation-purposes'; -import { KeyRoot } from '@metamask/keyring-sdk'; +import { AtomicKeyring, KeyRoot } from '@metamask/keyring-sdk'; import { CL24DKM, CL24ThresholdKeySerializer } from '@metamask/mfa-wallet-cl24'; import type { CL24ThresholdKey } from '@metamask/mfa-wallet-cl24'; import { Dkls23TssLib } from '@metamask/mfa-wallet-dkls23'; @@ -181,7 +181,10 @@ function shareBindings( * * The controller keyring type is `'MPC Money Keyring'`. */ -export class MpcMoneyKeyring implements MpcMoneyKeyringContract { +export class MpcMoneyKeyring + extends AtomicKeyring + implements MpcMoneyKeyringContract +{ /** * Keyring type registered with the controller. */ @@ -207,8 +210,6 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { readonly #getPrimaryMnemonic: MpcMoneyKeyringOpts['getPrimaryMnemonic']; - #opQueue: Promise = Promise.resolve(); - /** * Create a keyring bound to the given cloud and relayer endpoints. * @@ -218,6 +219,7 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { * @param opts - TSS libraries, backend URLs, and token callbacks. */ constructor(opts: MpcMoneyKeyringOpts) { + super({ updater: opts.updater }); this.isReadOnly = !opts.isMfaAvailable; this.#dkm = new CL24DKM(opts.cl24Lib); this.#tss = new Dkls23TssLib(opts.dkls23Lib); @@ -320,7 +322,7 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { * @returns Resolves when the keyring is initialized. */ async setup(): Promise { - return this.#serializeOp(async () => { + return this.withWriteLock(async () => { if (this.isReadOnly) { if (!this.#state) { await this.#setupAddressOnly(); @@ -360,10 +362,13 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { throw new Error('MpcMoneyKeyring: no MPC key for this profile'); } - this.#state = { + const nextState: MpcMoneyKeyringAccountState = { status: 'address-only', address: publicKeyToAddressHex(hexToBytes(publicKey)), }; + await this.update(() => { + this.#state = nextState; + }); } /** @@ -394,7 +399,7 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { * @returns Resolves when rotation and activation complete. */ async rotateKeyShares(): Promise { - return this.#serializeOp(async () => { + return this.withWriteLock(async () => { const state = this.#assertState(); const { netCreds, serverNetId, shareEpoch } = state; let { keyShare } = state; @@ -453,7 +458,7 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { epoch: nextEpoch, }); - this.#applyKeyState({ + await this.#applyKeyState({ ...state, keyShare, shareEpoch: nextEpoch, @@ -468,17 +473,19 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { * @returns Whether all remote epochs match the local share epoch. */ async checkKeyShare(): Promise { - const { shareEpoch } = this.#assertState(); - const token = await this.#getProfileToken(); - const check = await checkKeyShareRemote({ - baseURL: this.#cloudURL, - token, + return this.withReadLock(async () => { + const { shareEpoch } = this.#assertState(); + const token = await this.#getProfileToken(); + const check = await checkKeyShareRemote({ + baseURL: this.#cloudURL, + token, + }); + return ( + check.latestShareEpoch === shareEpoch && + check.latestBackupEpoch === shareEpoch && + check.activeEpoch === shareEpoch + ); }); - return ( - check.latestShareEpoch === shareEpoch && - check.latestBackupEpoch === shareEpoch && - check.activeEpoch === shareEpoch - ); } /** @@ -489,7 +496,7 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { * @returns Resolves when the local share has been refreshed. */ async syncKeyShare(): Promise { - return this.#serializeOp(async () => { + return this.withWriteLock(async () => { const state = this.#assertState(); const token = await this.#getProfileToken({ twoFactor: true }); const { encryptedKeyShare, epoch } = await loadKeyShareBackup({ @@ -497,7 +504,7 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { token, }); const keyShare = await this.#decryptKeyShare(encryptedKeyShare); - this.#applyKeyState({ + await this.#applyKeyState({ ...state, keyShare, shareEpoch: epoch, @@ -708,7 +715,7 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { epoch: INITIAL_SHARE_EPOCH, }); - this.#applyKeyState({ + await this.#applyKeyState({ keyShare, netCreds, serverNetId, @@ -752,7 +759,7 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { clientNetId: netCreds.partyId, }); - this.#applyKeyState({ + await this.#applyKeyState({ keyShare, netCreds, serverNetId, @@ -766,7 +773,7 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { hash: Uint8Array, request: MoneyAccountSignatureRequest, ): Promise { - return this.#serializeOp(async () => { + return this.withWriteLock(async () => { const state = this.#assertState(); const { keyShare, netCreds, serverNetId, shareEpoch } = state; let { tssSetup } = state; @@ -822,7 +829,7 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { bindings, tssSetup, ); - this.#applyKeyState({ ...state, tssSetup }); + await this.#applyKeyState({ ...state, tssSetup }); let ethSignature: Uint8Array; try { @@ -838,7 +845,7 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { // Any error drops the cached TSS setup. A failed sign may have // consumed it, including a transport failure, so the next sign // rebuilds setup with the peer instead of reusing it. - this.#applyKeyState({ ...state, tssSetup: null }); + await this.#applyKeyState({ ...state, tssSetup: null }); throw error; } try { @@ -946,27 +953,14 @@ export class MpcMoneyKeyring implements MpcMoneyKeyringContract { } } - async #serializeOp( - operation: () => Promise, - ): Promise { - const previous = this.#opQueue; - let release!: () => void; - this.#opQueue = new Promise((resolve) => { - release = resolve; - }); - await previous; - try { - return await operation(); - } finally { - release(); - } - } - - #applyKeyState(state: MpcMoneyKeyringState): void { - this.#state = { + async #applyKeyState(state: MpcMoneyKeyringState): Promise { + const nextState: MpcMoneyKeyringAccountState = { status: 'initialized', ...state, }; + await this.update(() => { + this.#state = nextState; + }); } #assertState(): MpcMoneyKeyringState { diff --git a/packages/keyring-eth-money-mpc/src/types.ts b/packages/keyring-eth-money-mpc/src/types.ts index 10a44d335..d84a91326 100644 --- a/packages/keyring-eth-money-mpc/src/types.ts +++ b/packages/keyring-eth-money-mpc/src/types.ts @@ -1,3 +1,4 @@ +import type { AtomicUpdater } from '@metamask/keyring-sdk'; import type { EthKeyring } from '@metamask/keyring-utils'; import type { CL24DKM, CL24ThresholdKey } from '@metamask/mfa-wallet-cl24'; import type { Dkls23TssLib } from '@metamask/mfa-wallet-dkls23'; @@ -59,6 +60,10 @@ export type Cl24Lib = ConstructorParameters[0]; export type Dkls23Lib = ConstructorParameters[0]; export type MpcMoneyKeyringOpts = { + /** + * Controller callback used to commit state changes to the vault. + */ + updater: AtomicUpdater; /** * Whether the client can provide a 2FA profile token. *