-
Notifications
You must be signed in to change notification settings - Fork 542
/
MultiChainController.ts
563 lines (503 loc) · 16.6 KB
/
MultiChainController.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
import { AddApprovalRequest } from '@metamask/approval-controller';
import {
BaseControllerV2 as BaseController,
RestrictedControllerMessenger,
} from '@metamask/base-controller';
import {
GetPermissions,
GrantPermissions,
HasPermission,
PermissionConstraint,
} from '@metamask/permission-controller';
import { SnapKeyring } from '@metamask/snaps-types';
import {
parseAccountId,
AccountId,
parseChainId,
ChainId,
ConnectArguments,
HandlerType,
NamespaceId,
RequestArguments,
RequestNamespace,
Session,
TruncatedSnap,
SnapId,
fromEntries,
SessionNamespace,
flatten,
getSnapPermissionName,
isAccountIdArray,
Namespaces,
} from '@metamask/snaps-utils';
import { hasProperty, assert } from '@metamask/utils';
import { nanoid } from 'nanoid';
import {
GetAllSnaps,
HandleSnapRequest,
IncrementActiveReferences,
DecrementActiveReferences,
SnapEndowments,
getRunnableSnaps,
} from '../snaps';
import { getKeyringCaveatNamespaces } from '../snaps/endowments/keyring';
import { findMatchingKeyringSnaps } from './matching';
const controllerName = 'MultiChainController';
const defaultState: MultiChainControllerState = {
sessions: {},
};
type AllowedActions =
| GetAllSnaps
| IncrementActiveReferences
| DecrementActiveReferences
| HandleSnapRequest
| GetPermissions
| HasPermission
| AddApprovalRequest
| GrantPermissions;
type MultiChainControllerMessenger = RestrictedControllerMessenger<
typeof controllerName,
AllowedActions,
never,
AllowedActions['type'],
never
>;
type SessionData = {
origin: string;
requestedNamespaces: Record<NamespaceId, RequestNamespace>;
providedNamespaces: Record<NamespaceId, RequestNamespace>;
handlingSnaps: Record<NamespaceId, SnapId>;
};
type MultiChainControllerState = {
sessions: { [origin: string]: SessionData };
};
type Notify = (
origin: string,
data: { method: string; params?: Record<string, unknown> },
) => Promise<void>;
type MultiChainControllerArgs = {
notify: Notify;
messenger: MultiChainControllerMessenger;
};
// TODO(ritave): Support for legacy ethereum operations, not just snaps
export class MultiChainController extends BaseController<
typeof controllerName,
MultiChainControllerState,
MultiChainControllerMessenger
> {
readonly #notify: Notify;
/**
* Construct a new {@link MultiChainController} instance.
*
* @param args - The arguments to construct the controller with.
* @param args.messenger - The controller messenger to use.
* @param args.notify - A function that should handle JSON-RPC notifications.
*/
constructor({ messenger, notify }: MultiChainControllerArgs) {
super({
messenger,
metadata: {
sessions: { persist: false, anonymous: false },
},
name: controllerName,
state: defaultState,
});
this.#notify = notify;
}
/**
* Get an open session for the given origin.
*
* @param origin - The origin to get the session for.
* @returns The session, if it exists, or `undefined` otherwise.
*/
getSession(origin: string): SessionData | undefined {
return this.state.sessions[origin];
}
/**
* Close a session for the given origin.
*
* @param origin - The origin to close the session for.
* @throws If the session does not exist.
*/
async closeSession(origin: string): Promise<void> {
const session = this.getSession(origin);
assert(session, 'No session to close.');
await this.#notify(origin, {
method: 'multichainHack_metamask_disconnect',
});
this.update((state) => {
delete state.sessions[origin];
});
await Promise.all(
Object.values(session.handlingSnaps).map((snapId) =>
this.messagingSystem.call(
'SnapController:decrementActiveReferences',
snapId,
),
),
);
}
/**
* Handles a new connection from the given origin. This will create a new
* session, and close any existing session for the origin.
*
* @param origin - The origin to create the session for.
* @param connection - The connection arguments.
* @param connection.requiredNamespaces - The namespaces that the origin
* requires.
* @returns The session that was created.
*/
async onConnect(
origin: string,
connection: ConnectArguments,
): Promise<Session> {
const existingSession = this.getSession(origin);
if (existingSession) {
await this.closeSession(origin);
}
const snaps = this.messagingSystem.call('SnapController:getAll');
const filteredSnaps = getRunnableSnaps(snaps);
// Get available namespaces supported by currently installed Snaps.
const availableNamespaces = fromEntries(
await Promise.all(
filteredSnaps.map(async (snap) => [
snap.id,
await this.snapToNamespaces(snap),
]),
),
);
// The magical matching algorithm specified in SIP-2.
const namespaceToSnaps = findMatchingKeyringSnaps(
connection.requiredNamespaces,
availableNamespaces,
);
const permissions = this.messagingSystem.call(
'PermissionController:getPermissions',
origin,
);
// Find namespaces that can be satisfied with existing approved Snaps.
const approvedNamespacesAndSnaps = Object.entries(namespaceToSnaps).reduce<
Record<NamespaceId, SnapId[]>
>((acc, [namespace, snapIds]) => {
const approvedSnaps = snapIds.filter((snapId) => {
return (
permissions && hasProperty(permissions, getSnapPermissionName(snapId))
);
});
if (approvedSnaps.length > 0) {
acc[namespace] = approvedSnaps;
}
return acc;
}, {});
// If we either don't have a snap to handle a namespace or we have multiple we have conflicts
const hasConflicts = Object.keys(namespaceToSnaps).some(
(namespace) =>
!hasProperty(approvedNamespacesAndSnaps, namespace) ||
approvedNamespacesAndSnaps[namespace]?.length > 1,
);
// Use already approved snaps if they satisfy the requested namespaces.
const filteredNamespacesAndSnaps = hasConflicts
? namespaceToSnaps
: approvedNamespacesAndSnaps;
// Fetch possible accounts from snaps.
const possibleAccounts = await this.namespacesToAccounts(
origin,
filteredNamespacesAndSnaps,
connection.requiredNamespaces,
);
// For now we fail here if no namespaces could be matched to a snap.
// We don't fail if at least one namespace is matched to a snap.
// TODO: Decide whether this is what we want
assert(
Object.values(possibleAccounts).some(
(possibleAccount) => possibleAccount.length > 0,
),
'No installed snaps found for any requested namespace.',
);
// If currently installed Snaps / configuration doesn't solve request, we
// need to show a prompt. This is handled by `resolveConflicts`.
const resolvedAccounts = hasConflicts
? await this.resolveConflicts(origin, possibleAccounts)
: fromEntries(
Object.entries(possibleAccounts).map(
([namespace, snapAndAccounts]) => [
namespace,
snapAndAccounts[0] ?? null,
],
),
);
// Aggregate information about session namespaces.
const providedNamespaces = Object.entries(
connection.requiredNamespaces,
).reduce<Record<NamespaceId, SessionNamespace>>(
(acc, [namespaceId, namespace]) => {
const accounts = resolvedAccounts[namespaceId]?.accounts;
if (accounts) {
acc[namespaceId] = {
accounts,
chains: namespace.chains,
events: namespace.events,
methods: namespace.methods,
};
}
return acc;
},
{},
);
// Collect information about handler Snaps for each namespace.
const handlingSnaps = Object.entries(resolvedAccounts).reduce<
Record<NamespaceId, SnapId>
>((acc, [namespaceId, accountsAndSnap]) => {
if (accountsAndSnap) {
acc[namespaceId] = accountsAndSnap.snapId;
}
return acc;
}, {});
const session: SessionData = {
origin,
requestedNamespaces: connection.requiredNamespaces,
providedNamespaces,
handlingSnaps,
};
// Makes sure used Snaps aren't killed while they are serving the session.
await Promise.all(
Object.values(session.handlingSnaps).map((snapId) =>
this.messagingSystem.call(
'SnapController:incrementActiveReferences',
snapId,
),
),
);
this.update((state) => {
state.sessions[origin] = session;
});
return { namespaces: providedNamespaces };
}
/**
* Handle an incoming multichain request from the given origin. This will
* forward the request to the appropriate Snap, and return the response.
*
* @param origin - The origin to handle the request for.
* @param data - The request data.
* @param data.chainId - The chain ID for the request.
* @param data.request - The request arguments, i.e., the method and params.
* @returns The response from the Snap.
* @throws If the session does not exist, or the session does not provide the
* requested namespace.
*/
async onRequest(
origin: string,
data: { chainId: ChainId; request: RequestArguments },
): Promise<unknown> {
const session = this.getSession(origin);
assert(session, `Session for "${origin}" doesn't exist.`);
const { namespace } = parseChainId(data.chainId);
const sessionNamespace = session.providedNamespaces[namespace];
assert(
session.providedNamespaces[namespace]?.chains.includes(data.chainId),
`Session for "${origin}" is not connected to "${data.chainId}" chain.`,
);
const { method } = data.request;
assert(
sessionNamespace?.methods?.includes(method),
`Session for "${origin}" does not support ${method}`,
);
const snapId = session.handlingSnaps[namespace];
assert(snapId !== undefined);
const permissionName = getSnapPermissionName(snapId);
// Check if origin has permission to communicate with this Snap.
const hasPermission = this.messagingSystem.call(
'PermissionController:hasPermission',
origin,
permissionName,
);
// TODO: Get permission for origin connecting to snap, or get user approval.
// In the future this is where we should prompt for this permission.
// In this iteration, we will grant this permission in `onConnect`.
assert(
hasPermission,
`${origin} does not have permission to communicate with ${snapId}.`,
);
return this.snapRequest({
snapId,
origin,
method: 'handleRequest',
args: data,
});
}
/**
* Send a request to the given Snap. This calls the given method with the
* given arguments on the keyring class in the given Snap.
*
* @param options - The request options.
* @param options.snapId - The ID of the Snap to send the request to.
* @param options.origin - The origin of the request.
* @param options.method - The request method.
* @param options.args - The request params.
* @returns The response from the Snap.
*/
private async snapRequest({
snapId,
origin,
method,
args,
}: {
snapId: SnapId;
origin: string;
method: keyof SnapKeyring;
args?: unknown;
}) {
return this.messagingSystem.call('SnapController:handleRequest', {
snapId,
origin,
handler: HandlerType.SnapKeyring,
request: { method, params: args ? [args] : [] },
});
}
/**
* Get the accounts exposed by the Snap's keyring.
*
* This also verifies that the accounts returned by the snap are valid CAIP-10
* account IDs.
*
* @param origin - The origin of the request.
* @param snapId - The ID of the Snap to get the accounts from.
* @returns The accounts, or `null` if the Snap does not have any accounts, or
* the accounts are invalid (i.e., not valid CAIP-10 account IDs).
*/
private async getSnapAccounts(
origin: string,
snapId: SnapId,
): Promise<AccountId[] | null> {
try {
const result = await this.snapRequest({
snapId,
origin,
method: 'getAccounts',
});
if (isAccountIdArray(result)) {
return result;
}
} catch (error) {
// Ignore errors for now
console.error(error);
}
return null;
}
/**
* Get the namespaces for the given Snap, as described in the Snap's manifest.
*
* @param snap - The Snap to get the namespaces for.
* @returns The namespaces, or `null` if the Snap does not have any
* namespaces.
*/
private snapToNamespaces(snap: TruncatedSnap): Namespaces | null {
const permissions = this.messagingSystem.call(
'PermissionController:getPermissions',
snap.id,
);
const keyringPermission = permissions?.[SnapEndowments.Keyring];
return getKeyringCaveatNamespaces(keyringPermission);
}
/**
* Maps from an object of namespace IDs and Snap IDs, and an object of
* namespace IDs and requested namespaces, to an object of namespace IDs and
* resolved accounts, with the Snap ID providing the accounts.
*
* @param origin - The origin of the request.
* @param namespacesAndSnaps - An object of namespace IDs and Snap IDs
* providing the namespace.
* @param requestedNamespaces - An object of namespace IDs and requested
* namespaces.
* @returns An object of namespace IDs and resolved accounts, with the Snap ID
* providing the accounts.
*/
private async namespacesToAccounts(
origin: string,
namespacesAndSnaps: Record<NamespaceId, SnapId[]>,
requestedNamespaces: Record<NamespaceId, RequestNamespace>,
): Promise<Record<NamespaceId, { snapId: SnapId; accounts: AccountId[] }[]>> {
const dedupedSnaps = [
...new Set(flatten(Object.values(namespacesAndSnaps))),
] as SnapId[];
const allAccounts = await dedupedSnaps.reduce<
Promise<Record<string, AccountId[]>>
>(async (previousPromise, snapId) => {
const result = await this.getSnapAccounts(origin, snapId);
const acc = await previousPromise;
if (result) {
acc[snapId] = result;
}
return acc;
}, Promise.resolve({}));
return Object.keys(namespacesAndSnaps).reduce<
Record<NamespaceId, { snapId: SnapId; accounts: AccountId[] }[]>
>((acc, namespaceId) => {
const { chains } = requestedNamespaces[namespaceId];
const accountInAnyRequestedChain = (account: AccountId) => {
const { chainId: parsedChainId } = parseAccountId(account);
return chains.some((chainId) => chainId === parsedChainId);
};
const result = Object.entries(allAccounts)
.map(([snapId, accounts]) => ({
snapId,
accounts: accounts.filter(accountInAnyRequestedChain),
}))
.filter(({ accounts }) => accounts.length > 0);
acc[namespaceId] = result;
return acc;
}, {});
}
/**
* If multiple Snap IDs are provided for a namespace, this method will
* determine which Snap ID to use for the namespace, by showing the user a
* prompt.
*
* @param origin - The origin of the request.
* @param possibleAccounts - An object containing the accounts provided by
* each Snap ID for each namespace.
* @returns An object containing the Snap ID to use for each namespace.
*/
private async resolveConflicts(
origin: string,
possibleAccounts: Record<
NamespaceId,
{ snapId: SnapId; accounts: AccountId[] }[]
>,
): Promise<
Record<NamespaceId, { snapId: SnapId; accounts: AccountId[] } | null>
> {
// Get user approval for connection.
const id = nanoid();
const resolvedAccounts = (await this.messagingSystem.call(
'ApprovalController:addRequest',
{
origin,
id,
type: 'multichain_connect',
requestData: {
possibleAccounts,
},
},
true,
)) as Record<NamespaceId, { snapId: SnapId; accounts: AccountId[] } | null>;
// TODO: In the future, use another permission here to not give full
// permission after handshake.
// Instead we should give origin only a read-only access to list of accounts
// without allowing provider.request() talking to a snap before additional
// user approval. The additional approval would be requested in `onRequest`.
const approvedPermissions = Object.values(resolvedAccounts).reduce<
Record<string, Partial<PermissionConstraint>>
>((acc, cur) => {
if (cur !== null) {
acc[getSnapPermissionName(cur.snapId)] = {};
}
return acc;
}, {});
this.messagingSystem.call('PermissionController:grantPermissions', {
approvedPermissions,
subject: { origin },
});
return resolvedAccounts;
}
}