This repository has been archived by the owner on Feb 16, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathinteraction.ts
582 lines (539 loc) · 15.8 KB
/
interaction.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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
/**
* This module provides base classes for modeling interactions with
* keystores.
*
* It also defines several constants used throughout the API for
* categorizing messages.
*
* Integrations with new wallets should begin by creating a base class
* for that wallet by subclassing either `DirectKeystoreInteraction`
* or `IndirectKeystoreInteraction`.
*/
import Bowser from "bowser";
import { signatureNoSighashType } from "unchained-bitcoin";
/**
* Constant representing a keystore which is unsupported due to the
* kind of interaction or combination of paramters provided.
*/
export const UNSUPPORTED = "unsupported";
/**
* Constant representing a keystore pending activation by the user.
*/
export const PENDING = "pending";
/**
* Constant representing a keystore in active use.
*/
export const ACTIVE = "active";
/**
* Constant for messages at the "info" level.
*/
export const INFO = "info";
/**
* Constant for messages at the "warning" level.
*/
export const WARNING = "warning";
/**
* Constant for messages at the "error" level.
*/
export const ERROR = "error";
/**
* Enumeration of possible keystore states ([PENDING]{@link module:interaction.PENDING}|[ACTIVE]{@link module:interaction.ACTIVE}|[UNSUPPORTED]{@link module:interaction.UNSUPPORTED}).
*
*/
export const STATES = [PENDING, ACTIVE, UNSUPPORTED];
/**
* Enumeration of possible message levels ([INFO]{@link module:interaction.INFO}|[WARNING]{@link module:interaction.WARNING}|[ERROR]{@link module:interaction.ERROR}).
*/
export const LEVELS = [INFO, WARNING, ERROR];
/**
* Represents a message returned by an interaction.
*
* Message objects may have additional properties.
*/
export type Message = {
state?: typeof STATES extends readonly (infer ElementType)[]
? ElementType
: never;
level?: string;
code?: string;
text?: string;
version?: string;
action?: string;
image?: MessageImage;
messages?: Message[];
preProcessingTime?: number;
postProcessingTime?: number;
};
/**
* Represents an image in a message returned by an interaction.
*/
type MessageImage = { label: string; mimeType: string; data: string };
type MessageMethodArgs = {
state?: Message["state"];
level?: Message["level"];
code?: Message["code"] | RegExp;
text?: Message["text"] | RegExp;
version?: Message["version"] | RegExp;
};
type FormatType = "buffer" | "hex";
type FormatReturnType<T extends FormatType> = T extends "buffer"
? Buffer
: string;
/**
* Abstract base class for all keystore interactions.
*
* Concrete subclasses will want to subclass either
* `DirectKeystoreInteraction` or `IndirectKeystoreInteraction`.
*
* Defines an API for subclasses to leverage and extend.
*
* - Subclasses should not have any internal state. External tools
* (UI frameworks such as React) will maintain state and pass it
* into the interaction in order to display properly.
*
* - Subclasses may override the default constructor in order to allow
* users to pass in parameters.
*
* - Subclasses should override the `messages` method to customize
* what messages are surfaced in applications at what state of the
* user interface.
*
* - Subclasses should not try to catch all errors, instead letting
* them bubble up the stack. This allows UI developers to deal with
* them as appropriate.
*
* @example
* import {KeystoreInteraction, PENDING, ACTIVE, INFO} from "unchained-wallets";
* class DoNothingInteraction extends KeystoreInteraction {
*
* constructor({param}) {
* super();
* this.param = param;
* }
*
* messages() {
* const messages = super.messages()
* messages.push({state: PENDING, level: INFO, text: `Interaction pending: ${this.param}` code: "pending"});
* messages.push({state: ACTIVE, level: INFO, text: `Interaction active: ${this.param}` code: "active"});
* return messages;
* }
*
* }
*
* // usage
* const interaction = new DoNothingInteraction({param: "foo"});
* console.log(interaction.messageTextFor({state: ACTIVE})); // "Interaction active: foo"
* console.log(interaction.messageTextFor({state: PENDING})); // "Interaction pending: foo"
*
*/
export class KeystoreInteraction {
environment: Bowser.Parser.Parser;
/**
* Base constructor.
*
* Subclasses will often override this constructor to accept options.
*
* Just make sure to call `super()` if you do that!
*/
constructor() {
this.environment = Bowser.getParser(window.navigator.userAgent);
}
/**
* Subclasses can override this method to indicate they are not
* supported.
*
* This method has access to whatever options may have been passed
* in by the constructor as well as the ability to interact with
* `this.environment` to determine whether the functionality is
* supported. See the Bowser documentation for more details:
* https://github.com/lancedikson/bowser
*
* @example
* isSupported() {
* return this.environment.satisfies({
* * declare browsers per OS
* windows: {
* "internet explorer": ">10",
* },
* macos: {
* safari: ">10.1"
* },
*
* * per platform (mobile, desktop or tablet)
* mobile: {
* safari: '>=9',
* 'android browser': '>3.10'
* },
*
* * or in general
* chrome: "~20.1.1432",
* firefox: ">31",
* opera: ">=22",
*
* * also supports equality operator
* chrome: "=20.1.1432", * will match particular build only
*
* * and loose-equality operator
* chrome: "~20", * will match any 20.* sub-version
* chrome: "~20.1" * will match any 20.1.* sub-version (20.1.19 as well as 20.1.12.42-alpha.1)
* });
* }
*/
isSupported() {
return true;
}
/**
* Return messages array for this interaction.
*
* The messages array is a (possibly empty) array of `Message` objects.
*
* Subclasses should override this method and add messages as
* needed. Make sure to call `super.messages()` to return an empty
* messages array for you to begin populating.
*/
messages() {
const messages: Message[] = [];
return messages;
}
/**
* Return messages filtered by the given options.
*
* Multiple options can be given at once to filter along multiple
* dimensions.
*
* @example
* import {PENDING, ACTIVE} from "unchained-bitcoin";
* // Create any interaction instance
* interaction.messages().forEach(msg => console.log(msg));
* { code: "device.connect", state: "pending", level: "info", text: "Please plug in your device."}
* { code: "device.active", state: "active", level: "info", text: "Communicating with your device..."}
* { code: "device.active.warning", state: "active", level: "warning", text: "Your device will warn you about...", version: "2.x"}
* interaction.messagesFor({state: PENDING}).forEach(msg => console.log(msg));
* { code: "device.connect", state: "pending", level: "info", text: "Please plug in your device."}
* interaction.messagesFor({code: ACTIVE}).forEach(msg => console.log(msg));
* { code: "device.active", state: "active", level: "info", text: "Communicating with your device..."}
* { code: "device.active.warning", state: "active", level: "warning", text: "Your device will warn you about...", version: "2.x"}
* interaction.messagesFor({version: /^2/}).forEach(msg => console.log(msg));
* { code: "device.active", state: "active", level: "warning", text: "Your device will warn you about...", version: "2.x"}
*/
messagesFor({ state, level, code, text, version }: MessageMethodArgs) {
return this.messages().filter((message) => {
if (state && message.state !== state) {
return false;
}
if (level && message.level !== level) {
return false;
}
if (code && !(message.code || "").match(code)) {
return false;
}
if (text && !(message.text || "").match(text)) {
return false;
}
if (version && !(message.version || "").match(version)) {
return false;
}
return true;
});
}
/**
* Return whether there are any messages matching the given options.
*/
hasMessagesFor({ state, level, code, text, version }: MessageMethodArgs) {
return (
this.messagesFor({
state,
level,
code,
text,
version,
}).length > 0
);
}
/**
* Return the first message matching the given options (or `null` if none is found).
*/
messageFor({ state, level, code, text, version }: MessageMethodArgs) {
const messages = this.messagesFor({
state,
level,
code,
text,
version,
});
if (messages.length > 0) {
return messages[0];
}
return null;
}
/**
* Retrieve the text of the first message matching the given options
* (or `null` if none is found).
*/
messageTextFor({ state, level, code, text, version }: MessageMethodArgs) {
const message = this.messageFor({
state,
level,
code,
text,
version,
});
return message?.text ?? null;
}
}
/**
* Class used for describing an unsupported interaction.
*
* - Always returns `false` when the `isSupported` method is called.
*
* - Has a keystore state `unsupported` message at the `error` level.
*
* - Throws errors when attempting to call API methods such as `run`,
* `request`, and `parse`.
*
* @example
* import {UnsupportedInteraction} from "unchained-wallets";
* const interaction = new UnsupportedInteraction({text: "failure text", code: "fail"});
* console.log(interaction.isSupported()); // false
*
*/
export class UnsupportedInteraction extends KeystoreInteraction {
text: string;
code: string;
/**
* Accepts parameters to describe what is unsupported and why.
*
* The `text` should be human-readable. The `code` is for machines.
*/
constructor({ text, code }: { text: string; code: string }) {
super();
this.text = text;
this.code = code;
}
/**
* By design, this method always returns false.
*/
isSupported() {
return false;
}
/**
* Returns a single `error` level message at the `unsupported`
* state.
*/
messages() {
const messages = super.messages();
messages.push({
state: UNSUPPORTED,
level: ERROR,
code: this.code,
text: this.text,
});
return messages;
}
/**
* Throws an error.
*
*/
async run(): Promise<any> {
throw new Error(this.text);
}
/**
* Throws an error.
*
*/
request() {
throw new Error(this.text);
}
/**
* Throws an error.
*
*/
parse() {
throw new Error(this.text);
}
}
/**
* Base class for direct keystore interactions.
*
* Subclasses *must* implement a `run` method which communicates
* directly with the keystore. This method must be asynchronous
* (return a `Promise`) to accommodate delays with network, devices,
* &c.
*
* @example
* import {DirectKeystoreInteraction} from "unchained-wallets";
* class SimpleDirectInteraction extends DirectKeystoreInteraction { *
*
* constructor({param}) {
* super();
* this.param = param;
* }
*
* async run() {
* // Or do something complicated...
* return this.param;
* }
* }
*
* const interaction = new SimpleDirectInteraction({param: "foo"});
*
* const result = await interaction.run();
* console.log(result);
* // "foo"
*
*/
export class DirectKeystoreInteraction extends KeystoreInteraction {
direct: boolean;
/**
* Sets the `this.direct` property to `true`. This property can be
* utilized when introspecting on interaction classes..
*
* @constructor
*/
constructor() {
super();
this.direct = true;
}
/**
* Initiate the intended interaction and return a result.
*
* Subclasses *must* override this function. This function must
* always return a promise as it is designed to be called within an
* `await` block.
*/
async run(): Promise<void | boolean> {
throw new Error("Override the `run` method in this interaction.");
}
/**
* Throws an error.
*/
request() {
throw new Error(
"This interaction is direct and does not support a `request` method."
);
}
/**
* Throws an error.
*/
parse() {
throw new Error(
"This interaction is direct and does not support a `parse` method."
);
}
signatureFormatter<T extends FormatType = "hex">(
inputSignature: string,
format: T = "hex" as T
) {
// Ledger signatures include the SIGHASH byte (0x01) if signing for P2SH-P2WSH or P2WSH ...
// but NOT for P2SH ... This function should always return the signature with SIGHASH byte appended.
// While we don't anticipate Trezor making firmware changes to include SIGHASH bytes with signatures,
// We'll go ahead and make sure that we're not double adding the SIGHASH
// byte in case they do in the future.
const signatureWithSigHashByte = `${signatureNoSighashType(
inputSignature
)}01`;
if (format === "buffer") {
return Buffer.from(
signatureWithSigHashByte,
"hex"
) as FormatReturnType<T>;
} else {
return signatureWithSigHashByte as FormatReturnType<T>;
}
}
parseSignature<T extends FormatType = "hex">(
transactionSignature: string[],
format: T = "hex" as T
) {
return (transactionSignature || []).map((inputSignature) =>
this.signatureFormatter(inputSignature, format)
) as FormatReturnType<T>[];
}
}
/**
* Base class for indirect keystore interactions.
*
* Subclasses *must* implement two methods: `request` and `parse`.
* Application code will pass the result of calling `request` to some
* external process (HTTP request, QR code, &c.) and pass the response
* to `parse` which should return a result.
*
* @example
* import {IndirectKeystoreInteraction} from "unchained-wallets";
* class SimpleIndirectInteraction extends IndirectKeystoreInteraction { *
*
* constructor({param}) {
* super();
* this.param = param;
* }
*
* request() {
* // Construct the data to be passed to the keystore...
* return this.param;
* }
*
* parse(response) {
* // Parse data returned from the keystore...
* return response;
* }
*
* }
*
* const interaction = new SimpleIndirectInteraction({param: "foo"});
*
* const request = interaction.request();
* const response = "bar"; // Or do something complicated with `request`
* const result = interaction.parse(response);
* console.log(result);
* // "bar"
*
*/
export class IndirectKeystoreInteraction extends KeystoreInteraction {
indirect: boolean;
workflow: string[];
/**
* Sets the `this.indirect` property to `true`. This property can
* be utilized when introspecting on interaction classes.
*
* The `this.workflow` property is an array containing one or both
* of the strings `request` and/or `parse`. Their presence and
* order indicates to calling applications whether they are
* necessary and in which order they should be run.
*/
constructor() {
super();
this.indirect = true;
this.workflow = ["parse"];
}
/**
* Provide the request.
*
* Subclasses *may* override this function. It can return any kind
* of object. Strings, data for QR codes, HTTP requests, command
* lines, functions, &c. are all allowed. Whatever is appropriate
* for the interaction.
*
*/
request() {
throw new Error("Override the `request` method in this interaction.");
}
/**
* Parse the response into a result.
*
* Subclasses *must* override this function. It must accept an
* appropriate kind of `response` object and return the final result
* of this interaction.
*
*/
parse(response: Record<string, unknown> | string) {
throw new Error("Override the `parse` method in this interaction.");
}
/**
* Throws an error.
*/
async run() {
throw new Error(
"This interaction is indirect and does not support a `run` method."
);
}
}