Skip to content
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

feat: add reveal srp to hd accounts. #29726

Closed
wants to merge 3 commits into from
Closed
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
3 changes: 3 additions & 0 deletions app/_locales/en/messages.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 8 additions & 1 deletion app/scripts/metamask-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ import { providerAsMiddleware } from '@metamask/eth-json-rpc-middleware';
import { debounce, throttle, memoize, wrap } from 'lodash';
import {
KeyringController,
///: BEGIN:ONLY_INCLUDE_IF(multi-srp)
KeyringTypes,
///: END:ONLY_INCLUDE_IF
keyringBuilderFactory,
} from '@metamask/keyring-controller';
import createFilterMiddleware from '@metamask/eth-json-rpc-filters';
Expand Down Expand Up @@ -5152,7 +5154,12 @@ export default class MetamaskController extends EventEmitter {
* @param {string} keyringIndex
* @returns {Promise<string>} The address of the newly-created account.
*/
async addNewAccount(accountCount, keyringIndex) {
async addNewAccount(
accountCount,
///: BEGIN:ONLY_INCLUDE_IF(multi-srp)
keyringIndex,
///: END:ONLY_INCLUDE_IF
) {
const oldAccounts = await this.keyringController.getAccounts();

const addedAccountAddress = await this.keyringController.addNewAccount(
Expand Down
8 changes: 7 additions & 1 deletion ui/components/app/srp-quiz-modal/SRPQuiz/SRPQuiz.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ export type SRPQuizProps = {
accountId: string; // The account id will be used to determine which HD keyring to use.
isOpen: boolean;
onClose: () => void;
closeAfterCompleting?: boolean;
};

export default function SRPQuiz(props: SRPQuizProps): JSX.Element {
Expand Down Expand Up @@ -227,7 +228,12 @@ export default function SRPQuiz(props: SRPQuizProps): JSX.Element {
buttons={[
{
label: t('continue'),
onClick: () => history.push(`${REVEAL_SEED_ROUTE}/${typeIndex}`),
onClick: () => {
history.push(`${REVEAL_SEED_ROUTE}/${typeIndex}`);
if (props.closeAfterCompleting) {
props.onClose();
}
},
variant: ButtonVariant.Primary,
size: ButtonSize.Lg,
'data-testid': 'srp-quiz-continue',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@ import { setAccountLabel } from '../../../store/actions';
import {
getHardwareWalletType,
getInternalAccountByAddress,
getMetaMaskKeyrings,
} from '../../../selectors';
import { isAbleToExportAccount } from '../../../helpers/utils/util';
import {
isAbleToExportAccount,
isAbleToRevealSrp,
} from '../../../helpers/utils/util';
import {
Box,
ButtonSecondary,
Expand Down Expand Up @@ -40,11 +44,16 @@ export const AccountDetailsDisplay = ({
const dispatch = useDispatch();
const trackEvent = useContext(MetaMetricsContext);
const t = useI18nContext();
const keyrings = useSelector(getMetaMaskKeyrings);

const account = useSelector((state) =>
getInternalAccountByAddress(state, address),
);
const {
metadata: { keyring },
} = useSelector((state) => getInternalAccountByAddress(state, address));
} = account;
const exportPrivateKeyFeatureEnabled = isAbleToExportAccount(keyring?.type);
const exportSRPFeatureaEnabled = isAbleToRevealSrp(account, keyrings);

const chainId = useSelector(getCurrentChainId);
const deviceName = useSelector(getHardwareWalletType);
Expand Down Expand Up @@ -74,9 +83,11 @@ export const AccountDetailsDisplay = ({
<QrCodeView Qr={{ data: address }} />
{exportPrivateKeyFeatureEnabled ? (
<ButtonSecondary
data-testid="account-details-display-export-private-key"
block
size={ButtonSecondarySize.Lg}
variant={TextVariant.bodyMd}
marginBottom={1}
onClick={() => {
trackEvent({
category: MetaMetricsEventCategory.Accounts,
Expand All @@ -86,12 +97,33 @@ export const AccountDetailsDisplay = ({
location: 'Account Details Modal',
},
});
onExportClick();
onExportClick('PrivateKey');
}}
>
{t('showPrivateKey')}
</ButtonSecondary>
) : null}
{exportSRPFeatureaEnabled ? (
<ButtonSecondary
data-testid="account-details-display-export-srp"
block
size={ButtonSecondarySize.Lg}
variant={TextVariant.bodyMd}
onClick={() => {
trackEvent({
category: MetaMetricsEventCategory.Accounts,
event: MetaMetricsEventName.KeyExportSelected,
properties: {
key_type: MetaMetricsEventKeyType.Pkey,
location: 'Account Details Modal',
},
});
onExportClick('SRP');
}}
>
{t('showSRP')}
</ButtonSecondary>
) : null}
</Box>
);
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { LavaDomeDebug } from '@lavamoat/lavadome-core';
import { fireEvent, screen } from '@testing-library/react';
import { fireEvent, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
// TODO: Remove restricted import
// eslint-disable-next-line import/no-restricted-paths
import { showPrivateKey } from '../../../../app/_locales/en/messages.json';
import {
showSRP,
// TODO: Remove restricted import
// eslint-disable-next-line import/no-restricted-paths
} from '../../../../app/_locales/en/messages.json';
import mockState from '../../../../test/data/mock-state.json';

import { renderWithProvider } from '../../../../test/jest';
import { shortenAddress } from '../../../helpers/utils/util';
import {
Expand Down Expand Up @@ -66,8 +69,10 @@ describe('AccountDetails', () => {
});

it('shows export private key contents and password field when clicked', () => {
const { queryByText, queryByPlaceholderText } = render();
const exportPrivateKeyButton = queryByText(showPrivateKey.message);
const { queryByText, queryByPlaceholderText, getByTestId } = render();
const exportPrivateKeyButton = getByTestId(
'account-details-display-export-private-key',
);
fireEvent.click(exportPrivateKeyButton);

expect(
Expand All @@ -81,8 +86,10 @@ describe('AccountDetails', () => {
it('attempts to validate password when submitted', async () => {
const password = 'password';

const { queryByPlaceholderText, queryByText } = render();
const exportPrivateKeyButton = queryByText(showPrivateKey.message);
const { queryByPlaceholderText, queryByText, getByTestId } = render();
const exportPrivateKeyButton = getByTestId(
'account-details-display-export-private-key',
);
fireEvent.click(exportPrivateKeyButton);

queryByPlaceholderText('Password').focus();
Expand Down Expand Up @@ -132,4 +139,24 @@ describe('AccountDetails', () => {

expect(accountName).toBeInTheDocument();
});

it("shows the `Show Secret Recovery Phrase` button when the account's type is a HD Keyring", () => {
render();

const showSRPButton = screen.getByText(showSRP.message);

expect(showSRPButton).toBeInTheDocument();
});

it('shows srp flow when the `Show Secret Recovery Phrase` button is clicked', async () => {
render();

const showSRPButton = screen.getByText(showSRP.message);
fireEvent.click(showSRPButton);

const securityQuizTitle = screen.getByTestId('srp-quiz-header');
await waitFor(() => {
expect(securityQuizTitle).toBeInTheDocument();
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -38,21 +38,34 @@ import {
ModalBody,
} from '../../component-library';
import { AddressCopyButton } from '../address-copy-button';
import SRPQuiz from '../../app/srp-quiz-modal';
import { AccountDetailsAuthenticate } from './account-details-authenticate';
import { AccountDetailsDisplay } from './account-details-display';
import { AccountDetailsKey } from './account-details-key';

export const AccountDetails = ({ address }) => {
export enum AttemptExportState {
None = 'None',
PrivateKey = 'PrivateKey',
SRP = 'SRP',
}

type AccountDetailsProps = { address: string };

export const AccountDetails = ({ address }: AccountDetailsProps) => {
const dispatch = useDispatch();
const t = useI18nContext();
const trackEvent = useContext(MetaMetricsContext);
const useBlockie = useSelector(getUseBlockie);
const accounts = useSelector(getMetaMaskAccountsOrdered);
const {
id: accountId,
metadata: { name },
} = useSelector((state) => getInternalAccountByAddress(state, address));
const [showHoldToReveal, setShowHoldToReveal] = useState(false);
const [attemptingExport, setAttemptingExport] = useState(false);
const [attemptingExport, setAttemptingExport] = useState<AttemptExportState>(
AttemptExportState.None,
);
const [srpQuizModalVisible, setSrpQuizModalVisible] = useState(false);

// This is only populated when the user properly authenticates
const [privateKey, setPrivateKey] = useState('');
Expand Down Expand Up @@ -80,7 +93,7 @@ export const AccountDetails = ({ address }) => {
<>
{/* This is the Modal that says "Show private key" on top and has a few states */}
<Modal
isOpen={!showHoldToReveal}
isOpen={!showHoldToReveal && !srpQuizModalVisible}
onClose={onClose}
data-testid="account-details-modal"
>
Expand All @@ -89,18 +102,32 @@ export const AccountDetails = ({ address }) => {
<ModalHeader
onClose={onClose}
onBack={
attemptingExport &&
(() => {
dispatch(hideWarning());
setPrivateKey('');
setAttemptingExport(false);
})
attemptingExport
? () => {
dispatch(hideWarning());
setPrivateKey('');
setAttemptingExport(AttemptExportState.None);
}
: undefined
}
>
{attemptingExport ? t('showPrivateKey') : avatar}
</ModalHeader>
<ModalBody>
{attemptingExport ? (
{attemptingExport === AttemptExportState.None && (
<AccountDetailsDisplay
accounts={accounts}
accountName={name}
address={address}
onExportClick={(attemptExportMode: AttemptExportState) => {
if (attemptExportMode === AttemptExportState.SRP) {
setSrpQuizModalVisible(true);
}
setAttemptingExport(attemptExportMode);
}}
/>
)}
{attemptingExport === AttemptExportState.PrivateKey && (
<>
<Box
display={Display.Flex}
Expand Down Expand Up @@ -133,13 +160,6 @@ export const AccountDetails = ({ address }) => {
/>
)}
</>
) : (
<AccountDetailsDisplay
accounts={accounts}
accountName={name}
address={address}
onExportClick={() => setAttemptingExport(true)}
/>
)}
</ModalBody>
</ModalContent>
Expand All @@ -164,6 +184,15 @@ export const AccountDetails = ({ address }) => {
}}
holdToRevealType="PrivateKey"
/>
<SRPQuiz
accountId={accountId}
isOpen={srpQuizModalVisible}
onClose={() => {
setSrpQuizModalVisible(false);
onClose();
}}
closeAfterCompleting
/>
</>
);
};
Expand Down
22 changes: 22 additions & 0 deletions ui/helpers/utils/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import bowser from 'bowser';
import { WALLET_SNAP_PERMISSION_KEY } from '@metamask/snaps-rpc-methods';
import { stripSnapPrefix } from '@metamask/snaps-utils';
import { isObject, isStrictHexString } from '@metamask/utils';
import { KeyringTypes } from '@metamask/keyring-controller';
import { CHAIN_IDS, NETWORK_TYPES } from '../../../shared/constants/network';
import { logErrorWithMessage } from '../../../shared/modules/error';
import {
Expand Down Expand Up @@ -724,6 +725,27 @@ export const isAbleToExportAccount = (keyringType = '') => {
return !keyringType.includes('Hardware') && !keyringType.includes('Snap');
};

export const isAbleToRevealSrp = (accountToExport, keyrings) => {
if (
accountToExport.type !== KeyringTypes.hd &&
accountToExport.type !== KeyringTypes.snap
) {
return false;
}

// All hd keyrings can reveal their srp.
if (accountToExport.type === KeyringTypes.hd) {
return true;
}

// For snap accounts we must check if the entropy source was from a HD keyring.
const keyringId = accountToExport.metadata.keyring.id;
const hdKeyringsIds = keyrings
.filter((keyring) => keyring.type === KeyringTypes.hd)
.map((keyring) => keyring.id);
return hdKeyringsIds.includes(keyringId);
};

/**
* Checks if a tokenId in Hex or decimal format already exists in an object.
*
Expand Down
Loading
Loading