-
Notifications
You must be signed in to change notification settings - Fork 542
/
getBip32PublicKey.ts
166 lines (150 loc) · 4.88 KB
/
getBip32PublicKey.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import {
Caveat,
PermissionSpecificationBuilder,
PermissionType,
PermissionValidatorConstraint,
RestrictedMethodOptions,
ValidPermissionSpecification,
} from '@metamask/permission-controller';
import { BIP32Node, SLIP10Node } from '@metamask/key-tree';
import {
Bip32Entropy,
bip32entropy,
Bip32PathStruct,
SnapCaveatType,
SnapGetBip32EntropyPermissionsStruct,
} from '@metamask/snaps-utils';
import { NonEmptyArray, assertStruct } from '@metamask/utils';
import { ethErrors } from 'eth-rpc-errors';
import { boolean, enums, object, optional, type } from 'superstruct';
const targetKey = 'snap_getBip32PublicKey';
export type GetBip32PublicKeyMethodHooks = {
/**
* @returns The mnemonic of the user's primary keyring.
*/
getMnemonic: () => Promise<string>;
/**
* Waits for the extension to be unlocked.
*
* @returns A promise that resolves once the extension is unlocked.
*/
getUnlockPromise: (shouldShowUnlockRequest: boolean) => Promise<void>;
};
type GetBip32PublicKeySpecificationBuilderOptions = {
methodHooks: GetBip32PublicKeyMethodHooks;
};
type GetBip32PublicKeySpecification = ValidPermissionSpecification<{
permissionType: PermissionType.RestrictedMethod;
targetKey: typeof targetKey;
methodImplementation: ReturnType<typeof getBip32PublicKeyImplementation>;
allowedCaveats: Readonly<NonEmptyArray<string>> | null;
validator: PermissionValidatorConstraint;
}>;
type GetBip32PublicKeyParameters = {
path: ['m', ...(`${number}` | `${number}'`)[]];
curve: 'secp256k1' | 'ed25519';
compressed?: boolean;
};
export const Bip32PublicKeyArgsStruct = bip32entropy(
object({
path: Bip32PathStruct,
curve: enums(['ed225519', 'secp256k1']),
compressed: optional(boolean()),
}),
);
/**
* Validate the path values associated with a caveat. This validates that the
* value is a non-empty array with valid derivation paths and curves.
*
* @param caveat - The caveat to validate.
* @throws If the value is invalid.
*/
export function validateCaveatPaths(
caveat: Caveat<string, any>,
): asserts caveat is Caveat<string, Bip32Entropy[]> {
assertStruct(
caveat,
type({ value: SnapGetBip32EntropyPermissionsStruct }),
'Invalid BIP-32 public key caveat',
ethErrors.rpc.internal,
);
}
/**
* The specification builder for the `snap_getBip32PublicKey` permission.
* `snap_getBip32PublicKey` lets the Snap retrieve public keys for a particular
* BIP-32 node.
*
* @param options - The specification builder options.
* @param options.methodHooks - The RPC method hooks needed by the method implementation.
* @returns The specification for the `snap_getBip32PublicKey` permission.
*/
const specificationBuilder: PermissionSpecificationBuilder<
PermissionType.RestrictedMethod,
GetBip32PublicKeySpecificationBuilderOptions,
GetBip32PublicKeySpecification
> = ({ methodHooks }: GetBip32PublicKeySpecificationBuilderOptions) => {
return {
permissionType: PermissionType.RestrictedMethod,
targetKey,
allowedCaveats: [SnapCaveatType.PermittedDerivationPaths],
methodImplementation: getBip32PublicKeyImplementation(methodHooks),
validator: ({ caveats }) => {
if (
caveats?.length !== 1 ||
caveats[0].type !== SnapCaveatType.PermittedDerivationPaths
) {
throw ethErrors.rpc.invalidParams({
message: `Expected a single "${SnapCaveatType.PermittedDerivationPaths}" caveat.`,
});
}
},
};
};
export const getBip32PublicKeyBuilder = Object.freeze({
targetKey,
specificationBuilder,
methodHooks: {
getMnemonic: true,
getUnlockPromise: true,
},
} as const);
/**
* Builds the method implementation for `snap_getBip32PublicKey`.
*
* @param hooks - The RPC method hooks.
* @param hooks.getMnemonic - A function to retrieve the Secret Recovery Phrase of the user.
* @param hooks.getUnlockPromise - A function that resolves once the MetaMask extension is unlocked
* and prompts the user to unlock their MetaMask if it is locked.
* @returns The method implementation which returns a public key.
* @throws If the params are invalid.
*/
export function getBip32PublicKeyImplementation({
getMnemonic,
getUnlockPromise,
}: GetBip32PublicKeyMethodHooks) {
return async function getBip32PublicKey(
args: RestrictedMethodOptions<GetBip32PublicKeyParameters>,
): Promise<string> {
await getUnlockPromise(true);
assertStruct(
args.params,
Bip32PublicKeyArgsStruct,
'Invalid BIP-32 public key params',
ethErrors.rpc.invalidParams,
);
const { params } = args;
const node = await SLIP10Node.fromDerivationPath({
curve: params.curve,
derivationPath: [
`bip39:${await getMnemonic()}`,
...params.path
.slice(1)
.map<BIP32Node>((index) => `bip32:${index}` as BIP32Node),
],
});
if (params.compressed) {
return node.compressedPublicKey;
}
return node.publicKey;
};
}