Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions packages/keyring-eth-money-mpc/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
28 changes: 28 additions & 0 deletions packages/keyring-eth-money-mpc/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 2 additions & 3 deletions packages/keyring-eth-money-mpc/src/cloud.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,8 @@ function readStruct<Schema>(
}

/**
* 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;

Expand Down
204 changes: 202 additions & 2 deletions packages/keyring-eth-money-mpc/src/mpc-money-keyring.test.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -28,6 +29,11 @@ const mockCheckKeyShare = jest.fn();
const mockSetActiveEpoch = jest.fn();
const mockLoadKeyShareBackup = jest.fn();
let lastNetworkManagerOptions: Record<string, unknown> | undefined;
let committedStates: Json[] = [];
const mockUpdater = jest.fn<
ReturnType<AtomicUpdater>,
Parameters<AtomicUpdater>
>();

const mockDerivedAddress = '0x1111111111111111111111111111111111111111' as Hex;
const mockSessionNonce =
Expand Down Expand Up @@ -172,6 +178,19 @@ const makeSerializedState = (overrides: Record<string, unknown> = {}) => ({
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<void>; resolve: () => void } {
let resolve!: () => void;
const promise = new Promise<void>((resolvePromise) => {
resolve = resolvePromise;
});
return { promise, resolve };
}

const makeRootSession = (statusPayload = 'data persisted') => {
const session = {
sendMessage: jest.fn(),
Expand All @@ -197,6 +216,7 @@ const makeKeyring = (
isMfaAvailable = true,
) =>
new MpcMoneyKeyring({
updater: mockUpdater,
isMfaAvailable,
cl24Lib: {} as never,
dkls23Lib: {} as never,
Expand All @@ -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');

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -451,6 +643,7 @@ describe('MpcMoneyKeyring', () => {
shareEpoch: 1,
tssSetup: '0x010203',
});
expect(committedStates).toStrictEqual([await keyring.serialize()]);
});

it.each([
Expand Down Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -1451,6 +1650,7 @@ describe('MpcMoneyKeyring', () => {
expect(await keyring.serialize()).toStrictEqual({
address: mockDerivedAddress,
});
expect(committedStates).toStrictEqual([{ address: mockDerivedAddress }]);
});

it.each([
Expand Down
Loading
Loading