-
Notifications
You must be signed in to change notification settings - Fork 7
/
signer.service.ts
533 lines (496 loc) · 14.7 KB
/
signer.service.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
import { BigNumber, providers, utils, Wallet } from 'ethers';
import base64url from 'base64url';
import {
TypedDataDomain,
TypedDataField,
} from '@ethersproject/abstract-signer';
import WalletConnectProvider from '@walletconnect/ethereum-provider';
import { Methods } from '@ew-did-registry/did';
import { ERROR_MESSAGES } from '../../errors/error-messages';
import { chainConfigs } from '../../config/chain.config';
import {
ExecutionEnvironment,
executionEnvironment,
} from '../../utils/detect-environment';
import {
IPubKeyAndIdentityToken,
ProviderType,
ProviderEvent,
AccountInfo,
PUBLIC_KEY,
IS_ETH_SIGNER,
SignerT,
} from './signer.types';
import { EkcSigner } from './ekc.signer';
import { computeAddress } from 'ethers/lib/utils';
import { getLogger } from '../../config/logger.config';
const {
arrayify,
keccak256,
recoverPublicKey,
getAddress,
hashMessage,
verifyMessage,
} = utils;
export type ServiceInitializer = () => Promise<void>;
/**
* Service responsible for signing messages and sending transactions to the blockchain
*
* ```typescript
* const { signerService } = await initWithPrivateKeySigner(privateKey, rpcUrl);
* signerService.signMessage(...);
* ```
*/
export class SignerService {
private _publicKey: string;
private _isEthSigner: boolean;
private _identityToken: string;
private _address: string;
private _account: string;
private _chainId: number;
private _chainName: string;
private _chainDisplayName: string;
private _servicesInitializers: ServiceInitializer[] = [];
private _walletEventListeners: { event: ProviderEvent; cb: () => void }[] =
[];
constructor(
private _signer: Required<SignerT>,
private _providerType: ProviderType
) {}
async init() {
if (executionEnvironment() === ExecutionEnvironment.BROWSER) {
this._publicKey = localStorage.getItem(PUBLIC_KEY) as string;
}
this._address = await this.signer.getAddress();
this._chainId = (await this._signer.provider.getNetwork()).chainId;
this._chainDisplayName = chainConfigs()[this._chainId].chainDisplayName;
this._chainName = chainConfigs()[this._chainId].chainName;
if (this._signer instanceof providers.JsonRpcSigner) {
this._account = (await this._signer.provider.listAccounts())[0];
} else if (this._signer instanceof Wallet) {
this._account = this._address;
}
// web app is responsible for clearing of isEthSigner on logout
if (executionEnvironment() === ExecutionEnvironment.BROWSER) {
const isEthSigner = localStorage.getItem(IS_ETH_SIGNER);
if (isEthSigner === 'true') {
this._isEthSigner = true;
} else if (isEthSigner === 'false') {
this._isEthSigner = false;
}
} else {
this._setIsEthrSigner();
}
/**
* @todo provide general way to initialize with previously saved key
*/
this.initEventHandlers();
for await (const initializer of this._servicesInitializers) {
await initializer();
}
}
/**
* Registers reinitialization of dependent service on signer reconnection
*/
onInit(initializer: ServiceInitializer) {
this._servicesInitializers.push(initializer);
}
async emit(e: ProviderEvent) {
await Promise.all(
this._walletEventListeners
.map(({ event, cb }) => {
return e === event ? cb() : null;
})
.filter(Boolean)
);
}
on(event: ProviderEvent, cb) {
this._walletEventListeners.push({ event, cb });
}
/**
* Add event handler for certain events
* @requires to be called after the connection to wallet was initialized
*/
initEventHandlers() {
const accChangedHandler = async () => {
await this.closeConnection();
await this.init();
};
if (this._providerType === ProviderType.MetaMask) {
this.on(ProviderEvent.AccountChanged, accChangedHandler);
this.on(ProviderEvent.NetworkChanged, accChangedHandler);
} else if (this._providerType === ProviderType.WalletConnect) {
this.on(ProviderEvent.SessionUpdate, accChangedHandler);
this.on(ProviderEvent.Disconnected, this.closeConnection);
}
}
async connect(signer: Required<SignerT>, providerType: ProviderType) {
this._signer = signer;
this._providerType = providerType;
await this.init();
}
/**
* The instance of the `ether` library signer in use by the service
*
* ```typescript
* signerService.signer;
* ```
*
* @return signer
*/
get signer() {
return this._signer;
}
/**
* If signer is EIP-191 compliant https://eips.ethereum.org/EIPS/eip-191.
*
* ```typescript
* signerService.isEthSigner;
* ```
*
* @return true if the signer is EIP-191 compliant.
*/
get isEthSigner() {
return this._isEthSigner;
}
/**
* Get user address.
*
* ```typescript
* signerService.address;
* ```
*
* @return user address
*/
get address() {
return this._address;
}
/**
* Get account info, including chain id, chain name and user address.
*
* ```typescript
* signerService.accountInfo;
* ```
*
* @return account info
*/
get accountInfo(): AccountInfo {
return {
account: this._account,
chainId: this._chainId,
chainName: this._chainDisplayName,
};
}
/**
* Get connection provider.
*
* ```typescript
* signerService.provider;
* ```
*
* @return connection provider
*/
get provider() {
return this._signer.provider;
}
/**
* Get current connection chain id.
*
* ```typescript
* signerService.chainId;
* ```
*
* @return chain id
*/
get chainId() {
return this._chainId;
}
/**
* Get provider type of current signer connection.
*
* ```typescript
* signerService.providerType;
* ```
*
* @return provider type
*/
get providerType() {
return this._providerType;
}
/**
* Get current user DID
*
* ```typescript
* signerService.did;
* ```
*
* @return DID
*/
get did() {
return `did:${Methods.Erc1056}:${this.chainName()}:${this._address}`;
}
/**
* Get current user DID address with hex representation of the chain id.
*
* ```typescript
* signerService.didHex;
* ```
*
* @return DID address
*/
get didHex() {
return `did:${Methods.Erc1056}:${`0x${this.chainId.toString(
16
)}`}:${this._address.toLowerCase()}`;
}
/**
* Get current user balance.
*
* ```typescript
* signerService.getBalance();
* ```
*
* @return user balance
*/
async balance() {
return this.signer.getBalance();
}
/**
* Send transaction to the blockchain.
*
* ```typescript
* signerService.send({
* to: ':0x00...0',
* data: contract.interface.encodeFunctionData(...)
* });
* ```
*
* @param {TransactionRequest} options object with options
* @return transaction receipt
*/
async send({
to,
data,
value,
}: providers.TransactionRequest): Promise<providers.TransactionReceipt> {
const tx = {
to,
from: this.address,
data,
...(value && { value: BigNumber.from(value) }),
};
const receipt = await (await this._signer.sendTransaction(tx)).wait();
return receipt;
}
/**
* Makes a (readonly) call to a smart contract.
* https://docs.ethers.io/v5/single-page/#/v5/api/providers/provider/-%23-Provider-call
*
* ```typescript
* signerService.call({
* to: ':0x00...0',
* data: contract.interface.encodeFunctionData(...)
* });
* ```
*
* @param {TransactionRequest} options object with options
* @return the result of the call
*/
async call({ to, data }: providers.TransactionRequest): Promise<string> {
const tx = { to, from: this.address, data };
const result = await this._signer.call(tx);
return result;
}
/**
* Tries to create `eth_sign` conformant signature (https://eth.wiki/json-rpc/API#eth_sign).
* Whether or not to hash the message prior to signature is depends on whether is signer EIP-191 compliant.
* When running in browser `isEthSigner` variable should be stored in local storage.
*
* ```typescript
* signerService.signMessage(arrayify('Hello World'));
* ```
*
* @param {Uint8Array} message The message to be signed. The message should have binary representation to avoid confusion of text with hexadecimal binary data
* @return the signature
*/
async signMessage(message: Uint8Array): Promise<string> {
if (this._isEthSigner === undefined) {
throw new Error(ERROR_MESSAGES.IS_ETH_SIGNER_NOT_SET);
}
const messageHash = this._isEthSigner
? message
: arrayify(hashMessage(message));
const sig = await this.signer.signMessage(messageHash);
if (getAddress(this._address) !== getAddress(verifyMessage(message, sig))) {
throw new Error(ERROR_MESSAGES.NON_ETH_SIGN_SIGNATURE);
}
return sig;
}
/**
* Tries to create conformant EIP-712 signature (https://eips.ethereum.org/EIPS/eip-712).
*
* ```typescript
* signerService.signTypedData(
* { name: 'MyToken', version: '1.0' },
* { Model: [{ name: 'name', type: 'string' }, { name: 'type', type: 'string' }] },
* { name: 'MyToken', type: 'erc721' },
* );
* ```
*
* @param {TypedDataDomain} domain EIP-712 domain object
* @param {Record<string, Array<TypedDataField>>} types EIP-712 types object
* @param {Record<string, unknown>} message EIP-712 message object
* @return the signature
*/
async signTypedData(
domain: TypedDataDomain,
types: Record<string, Array<TypedDataField>>,
message: Record<string, unknown>
): Promise<string> {
if (!this.signer?._signTypedData) {
throw new Error(ERROR_MESSAGES.SIGN_TYPED_DATA_NOT_SUPPORTED);
}
delete types['EIP712Domain'];
return await this.signer._signTypedData(domain, types, message);
}
/**
* Close connection with the signer wallet.
*
* ```typescript
* signerService.closeConnection();
* ```
*
* @return true if connection was closed
*/
async closeConnection(): Promise<boolean> {
if (this._signer instanceof WalletConnectProvider) {
await this._signer.disconnect();
} else if (this._signer instanceof EkcSigner) {
try {
await this._signer.ekc.logout({ mode: 'popup' });
return false;
} catch (error) {
getLogger().info(`error in azure logout ${(error as Error).message}`);
}
}
return true;
}
/**
* Get current user public key.
*
* ```typescript
* signerService.publicKey();
* ```
*
* @return public key
*/
async publicKey(): Promise<string> {
if (this._publicKey) return this._publicKey;
else if (this._signer instanceof Wallet) {
this._publicKey = this._signer.publicKey;
} else {
this._publicKey = (await this.publicKeyAndIdentityToken()).publicKey;
}
return this._publicKey;
}
/**
* Get current chain name.
*
* ```typescript
* signerService.chainName();
* ```
*
* @return chain name
*/
chainName(): string {
return this._chainName;
}
/**
* Generate public key and identity token for authentication purposes.
*
* ```typescript
* signerService.publicKeyAndIdentityToken();
* ```
* @param force when true recalculates token even if it is already present
* @return object with public key and identity token
*/
async publicKeyAndIdentityToken(
force = false
): Promise<IPubKeyAndIdentityToken> {
if (!this._publicKey || !this._identityToken || force) {
await this._calculatePubKeyAndIdentityToken();
}
return {
publicKey: this._publicKey,
identityToken: this._identityToken,
};
}
/**
* Generate public key and identity token for authentication purposes.
*
* @return object with public key and identity token
*/
private async _calculatePubKeyAndIdentityToken() {
const header = {
alg: 'ES256',
typ: 'JWT',
};
const encodedHeader = base64url(JSON.stringify(header));
const address = this._address;
const payload = {
iss: `did:${Methods.Erc1056}:${this.chainName()}:${address}`,
claimData: {
blockNumber: await this._signer.provider.getBlockNumber(),
},
};
const encodedPayload = base64url(JSON.stringify(payload));
const token = `0x${Buffer.from(
`${encodedHeader}.${encodedPayload}`
).toString('hex')}`;
// arrayification is necessary for WalletConnect signatures to work. eth_sign expects message in bytes: https://docs.walletconnect.org/json-rpc-api-methods/ethereum#eth_sign
// keccak256 hash is applied for Metamask to display a coherent hex value when signing
const message = arrayify(keccak256(token));
// Computation of the digest in order to recover the public key under the assumption
// that signature was performed as per the eth_sign spec (https://eth.wiki/json-rpc/API#eth_sign)
const digest = arrayify(hashMessage(message));
const sig = await this._signer.signMessage(message);
const keyFromMessage = recoverPublicKey(message, sig);
const keyFromDigest = recoverPublicKey(digest, sig);
if (getAddress(this._address) === computeAddress(keyFromMessage)) {
this._publicKey = keyFromMessage;
this._isEthSigner = false;
} else if (getAddress(this._address) === computeAddress(keyFromDigest)) {
this._publicKey = keyFromDigest;
this._isEthSigner = true;
} else {
throw new Error(ERROR_MESSAGES.NON_ETH_SIGN_SIGNATURE);
}
this._identityToken = `${encodedHeader}.${encodedPayload}.${base64url(
sig
)}`;
}
/**
* Set `_isEthSigner` value based on a signed message.
* Generates a test message and signs it.
*/
private async _setIsEthrSigner() {
// arrayification is necessary for WalletConnect signatures to work. eth_sign expects message in bytes: https://docs.walletconnect.org/json-rpc-api-methods/ethereum#eth_sign
// keccak256 hash is applied for Metamask to display a coherent hex value when signing
const message = arrayify(keccak256('0x'));
// Computation of the digest in order to recover the public key under the assumption
// that signature was performed as per the eth_sign spec (https://eth.wiki/json-rpc/API#eth_sign)
const digest = arrayify(hashMessage(message));
const sig = await this._signer.signMessage(message);
const keyFromMessage = recoverPublicKey(message, sig);
const keyFromDigest = recoverPublicKey(digest, sig);
if (getAddress(this._address) === computeAddress(keyFromMessage)) {
this._publicKey = keyFromMessage;
this._isEthSigner = false;
} else if (getAddress(this._address) === computeAddress(keyFromDigest)) {
this._publicKey = keyFromDigest;
this._isEthSigner = true;
} else {
throw new Error(ERROR_MESSAGES.NON_ETH_SIGN_SIGNATURE);
}
}
}