-
Notifications
You must be signed in to change notification settings - Fork 542
/
getBip32Entropy.ts
219 lines (200 loc) · 6.5 KB
/
getBip32Entropy.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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import { BIP32Node, JsonSLIP10Node, SLIP10Node } from '@metamask/key-tree';
import {
Caveat,
PermissionConstraint,
PermissionSpecificationBuilder,
PermissionType,
PermissionValidatorConstraint,
RestrictedMethodCaveatSpecificationConstraint,
RestrictedMethodOptions,
ValidPermissionSpecification,
} from '@metamask/permission-controller';
import {
Bip32Entropy,
Bip32EntropyStruct,
SnapCaveatType,
} from '@metamask/snaps-utils';
import { Json, NonEmptyArray, assertStruct, assert } from '@metamask/utils';
import { ethErrors } from 'eth-rpc-errors';
import { array, size, type } from 'superstruct';
import { isEqual } from '../utils';
const targetKey = 'snap_getBip32Entropy';
export type GetBip32EntropyMethodHooks = {
/**
* @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 GetBip32EntropySpecificationBuilderOptions = {
methodHooks: GetBip32EntropyMethodHooks;
};
type GetBip32EntropySpecification = ValidPermissionSpecification<{
permissionType: PermissionType.RestrictedMethod;
targetKey: typeof targetKey;
methodImplementation: ReturnType<typeof getBip32EntropyImplementation>;
allowedCaveats: Readonly<NonEmptyArray<string>> | null;
validator: PermissionValidatorConstraint;
}>;
/**
* Validate a caveat path object. The object must consist of a `path` array and
* a `curve` string. Paths must start with `m`, and must contain at
* least two indices. If `ed25519` is used, this checks if all the path indices
* are hardened.
*
* @param value - The value to validate.
* @throws If the value is invalid.
*/
function validatePath(value: unknown): asserts value is Bip32Entropy {
assertStruct(
value,
Bip32EntropyStruct,
'Invalid BIP-32 entropy path definition',
ethErrors.rpc.invalidParams,
);
}
/**
* 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: size(array(Bip32EntropyStruct), 1, Infinity) }),
'Invalid BIP-32 entropy caveat',
ethErrors.rpc.internal,
);
}
/**
* The specification builder for the `snap_getBip32Entropy` permission.
* `snap_getBip32Entropy` lets the Snap control private 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_getBip32Entropy` permission.
*/
const specificationBuilder: PermissionSpecificationBuilder<
PermissionType.RestrictedMethod,
GetBip32EntropySpecificationBuilderOptions,
GetBip32EntropySpecification
> = ({ methodHooks }: GetBip32EntropySpecificationBuilderOptions) => {
return {
permissionType: PermissionType.RestrictedMethod,
targetKey,
allowedCaveats: [SnapCaveatType.PermittedDerivationPaths],
methodImplementation: getBip32EntropyImplementation(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 getBip32EntropyBuilder = Object.freeze({
targetKey,
specificationBuilder,
methodHooks: {
getMnemonic: true,
getUnlockPromise: true,
},
} as const);
/**
* Map a raw value from the `initialPermissions` to a caveat specification.
* Note that this function does not do any validation, that's handled by the
* PermissionsController when the permission is requested.
*
* @param value - The raw value from the `initialPermissions`.
* @returns The caveat specification.
*/
export function getBip32EntropyCaveatMapper(
value: Json,
): Pick<PermissionConstraint, 'caveats'> {
return {
caveats: [
{
type: SnapCaveatType.PermittedDerivationPaths,
value,
},
],
};
}
export const getBip32EntropyCaveatSpecifications: Record<
SnapCaveatType.PermittedDerivationPaths,
RestrictedMethodCaveatSpecificationConstraint
> = {
[SnapCaveatType.PermittedDerivationPaths]: Object.freeze({
type: SnapCaveatType.PermittedDerivationPaths,
decorator: (
method,
caveat: Caveat<SnapCaveatType.PermittedDerivationPaths, Bip32Entropy[]>,
) => {
return async (args) => {
const { params } = args;
validatePath(params);
const path = caveat.value.find(
(caveatPath) =>
isEqual(
params.path.slice(0, caveatPath.path.length),
caveatPath.path,
) && caveatPath.curve === params.curve,
);
if (!path) {
throw ethErrors.provider.unauthorized({
message:
'The requested path is not permitted. Allowed paths must be specified in the snap manifest.',
});
}
return await method(args);
};
},
validator: (caveat) => validateCaveatPaths(caveat),
}),
};
/**
* Builds the method implementation for `snap_getBip32Entropy`.
*
* @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 `JsonSLIP10Node`.
* @throws If the params are invalid.
*/
export function getBip32EntropyImplementation({
getMnemonic,
getUnlockPromise,
}: GetBip32EntropyMethodHooks) {
return async function getBip32Entropy(
args: RestrictedMethodOptions<Bip32Entropy>,
): Promise<JsonSLIP10Node> {
await getUnlockPromise(true);
const { params } = args;
assert(params);
const node = await SLIP10Node.fromDerivationPath({
curve: params.curve,
derivationPath: [
`bip39:${await getMnemonic()}`,
...params.path
.slice(1)
.map<BIP32Node>((index) => `bip32:${index}` as BIP32Node),
],
});
return node.toJSON();
};
}