-
-
Notifications
You must be signed in to change notification settings - Fork 227
/
index.ts
596 lines (518 loc) · 19.6 KB
/
index.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
583
584
585
586
587
588
589
590
591
592
593
594
import * as ethUtil from 'ethereumjs-util';
import * as ethAbi from 'ethereumjs-abi';
import * as nacl from 'tweetnacl';
import * as naclUtil from 'tweetnacl-util';
export type TypedData = string | EIP712TypedData | EIP712TypedData[];
interface EIP712TypedData {
name: string;
type: string;
value: any;
}
export type Version = 'V1' | 'V2' | 'V3' | 'V4';
export interface EthEncryptedData {
version: string;
nonce: string;
ephemPublicKey: string;
ciphertext: string;
}
export type SignedMsgParams<D> = Required<MsgParams<D>>;
export interface MsgParams<D> {
data: D;
sig?: string;
}
interface MessageTypeProperty {
name: string;
type: string;
}
interface MessageTypes {
EIP712Domain: MessageTypeProperty[];
[additionalProperties: string]: MessageTypeProperty[];
}
export interface TypedMessage<T extends MessageTypes> {
types: T;
primaryType: keyof T;
domain: {
name?: string;
version?: string;
chainId?: number;
verifyingContract?: string;
};
message: object;
}
const TYPED_MESSAGE_SCHEMA = {
type: 'object',
properties: {
types: {
type: 'object',
additionalProperties: {
type: 'array',
items: {
type: 'object',
properties: {
name: { type: 'string' },
type: { type: 'string' },
},
required: ['name', 'type'],
},
},
},
primaryType: { type: 'string' },
domain: { type: 'object' },
message: { type: 'object' },
},
required: ['types', 'primaryType', 'domain', 'message'],
};
/**
* A collection of utility functions used for signing typed data
*/
const TypedDataUtils = {
/**
* Encodes an object by encoding and concatenating each of its members
*
* @param {string} primaryType - Root type
* @param {Object} data - Object to encode
* @param {Object} types - Type definitions
* @returns {Buffer} - Encoded representation of an object
*/
encodeData (primaryType: string, data: object, types: object, useV4 = true): Buffer {
const encodedTypes = ['bytes32'];
const encodedValues = [this.hashType(primaryType, types)];
if (useV4) {
const encodeField = (name, type, value) => {
if (types[type] !== undefined) {
// eslint-disable-next-line no-eq-null
return ['bytes32', value == null ?
'0x0000000000000000000000000000000000000000000000000000000000000000' :
ethUtil.sha3(this.encodeData(type, value, types, useV4))];
}
if (value === undefined) {
throw new Error(`missing value for field ${name} of type ${type}`);
}
if (type === 'bytes') {
return ['bytes32', ethUtil.sha3(value)];
}
if (type === 'string') {
// convert string to buffer - prevents ethUtil from interpreting strings like '0xabcd' as hex
if (typeof value === 'string') {
value = Buffer.from(value, 'utf8');
}
return ['bytes32', ethUtil.sha3(value)];
}
if (type.lastIndexOf(']') === type.length - 1) {
const parsedType = type.slice(0, type.lastIndexOf('['));
const typeValuePairs = value.map((item) => encodeField(name, parsedType, item));
return ['bytes32', ethUtil.sha3(ethAbi.rawEncode(
typeValuePairs.map(([t]) => t),
typeValuePairs.map(([, v]) => v),
))];
}
return [type, value];
};
for (const field of types[primaryType]) {
const [type, value] = encodeField(field.name, field.type, data[field.name]);
encodedTypes.push(type);
encodedValues.push(value);
}
} else {
for (const field of types[primaryType]) {
let value = data[field.name];
if (value !== undefined) {
if (field.type === 'bytes') {
encodedTypes.push('bytes32');
value = ethUtil.sha3(value);
encodedValues.push(value);
} else if (field.type === 'string') {
encodedTypes.push('bytes32');
// convert string to buffer - prevents ethUtil from interpreting strings like '0xabcd' as hex
if (typeof value === 'string') {
value = Buffer.from(value, 'utf8');
}
value = ethUtil.sha3(value);
encodedValues.push(value);
} else if (types[field.type] !== undefined) {
encodedTypes.push('bytes32');
value = ethUtil.sha3(this.encodeData(field.type, value, types, useV4));
encodedValues.push(value);
} else if (field.type.lastIndexOf(']') === field.type.length - 1) {
throw new Error('Arrays are unimplemented in encodeData; use V4 extension');
} else {
encodedTypes.push(field.type);
encodedValues.push(value);
}
}
}
}
return ethAbi.rawEncode(encodedTypes, encodedValues);
},
/**
* Encodes the type of an object by encoding a comma delimited list of its members
*
* @param {string} primaryType - Root type to encode
* @param {Object} types - Type definitions
* @returns {string} - Encoded representation of the type of an object
*/
encodeType (primaryType: string, types: object): string {
let result = '';
let deps = this.findTypeDependencies(primaryType, types).filter((dep) => dep !== primaryType);
deps = [primaryType].concat(deps.sort());
for (const type of deps) {
const children = types[type];
if (!children) {
throw new Error(`No type definition specified: ${type}`);
}
result += `${type}(${types[type].map(({ name, type: t }) => `${t} ${name}`).join(',')})`;
}
return result;
},
/**
* Finds all types within a type definition object
*
* @param {string} primaryType - Root type
* @param {Object} types - Type definitions
* @param {Array} results - current set of accumulated types
* @returns {Array} - Set of all types found in the type definition
*/
findTypeDependencies (primaryType: string, types: object, results: string[] = []): string[] {
[primaryType] = primaryType.match(/^\w*/u);
if (results.includes(primaryType) || types[primaryType] === undefined) {
return results;
}
results.push(primaryType);
for (const field of types[primaryType]) {
for (const dep of this.findTypeDependencies(field.type, types, results)) {
!results.includes(dep) && results.push(dep);
}
}
return results;
},
/**
* Hashes an object
*
* @param {string} primaryType - Root type
* @param {Object} data - Object to hash
* @param {Object} types - Type definitions
* @returns {Buffer} - Hash of an object
*/
hashStruct (primaryType: string, data: object, types: object, useV4 = true): Buffer {
return ethUtil.sha3(this.encodeData(primaryType, data, types, useV4));
},
/**
* Hashes the type of an object
*
* @param {string} primaryType - Root type to hash
* @param {Object} types - Type definitions
* @returns {Buffer} - Hash of an object
*/
hashType (primaryType: string, types: object): Buffer {
return ethUtil.sha3(this.encodeType(primaryType, types));
},
/**
* Removes properties from a message object that are not defined per EIP-712
*
* @param {Object} data - typed message object
* @returns {Object} - typed message object with only allowed fields
*/
sanitizeData<T extends MessageTypes> (data: TypedData | TypedMessage<T>): TypedMessage<T> {
const sanitizedData: Partial<TypedMessage<T>> = {};
for (const key in TYPED_MESSAGE_SCHEMA.properties) {
if (data[key]) {
sanitizedData[key] = data[key];
}
}
if ('types' in sanitizedData) {
sanitizedData.types = { EIP712Domain: [], ...sanitizedData.types };
}
return sanitizedData as Required<TypedMessage<T>>;
},
/**
* Signs a typed message as per EIP-712 and returns its sha3 hash
*
* @param {Object} typedData - Types message data to sign
* @returns {Buffer} - sha3 hash of the resulting signed message
*/
sign<T extends MessageTypes> (typedData: Partial<TypedData | TypedMessage<T>>, useV4 = true): Buffer {
const sanitizedData = this.sanitizeData(typedData);
const parts = [Buffer.from('1901', 'hex')];
parts.push(this.hashStruct('EIP712Domain', sanitizedData.domain, sanitizedData.types, useV4));
if (sanitizedData.primaryType !== 'EIP712Domain') {
parts.push(this.hashStruct(sanitizedData.primaryType, sanitizedData.message, sanitizedData.types, useV4));
}
return ethUtil.sha3(Buffer.concat(parts));
},
};
function concatSig (v: Buffer, r: Buffer, s: Buffer): string {
const rSig = ethUtil.fromSigned(r);
const sSig = ethUtil.fromSigned(s);
const vSig = ethUtil.bufferToInt(v);
const rStr = padWithZeroes(ethUtil.toUnsigned(rSig).toString('hex'), 64);
const sStr = padWithZeroes(ethUtil.toUnsigned(sSig).toString('hex'), 64);
const vStr = ethUtil.stripHexPrefix(ethUtil.intToHex(vSig));
return ethUtil.addHexPrefix(rStr.concat(sStr, vStr)).toString('hex');
}
function normalize (input: number | string): string {
if (!input) {
return undefined;
}
if (typeof input === 'number') {
const buffer = ethUtil.toBuffer(input);
input = ethUtil.bufferToHex(buffer);
}
if (typeof input !== 'string') {
let msg = 'eth-sig-util.normalize() requires hex string or integer input.';
msg += ` received ${typeof input}: ${input}`;
throw new Error(msg);
}
return ethUtil.addHexPrefix(input.toLowerCase());
}
function personalSign<T extends MessageTypes> (privateKey: Buffer, msgParams: MsgParams<TypedData | TypedMessage<T>>): string {
const message = ethUtil.toBuffer(msgParams.data);
const msgHash = ethUtil.hashPersonalMessage(message);
const sig = ethUtil.ecsign(msgHash, privateKey);
const serialized = ethUtil.bufferToHex(concatSig(sig.v, sig.r, sig.s));
return serialized;
}
function recoverPersonalSignature<T extends MessageTypes> (msgParams: SignedMsgParams<TypedData | TypedMessage<T>>): string {
const publicKey = getPublicKeyFor(msgParams);
const sender = ethUtil.publicToAddress(publicKey);
const senderHex = ethUtil.bufferToHex(sender);
return senderHex;
}
function extractPublicKey<T extends MessageTypes> (msgParams: SignedMsgParams<TypedData | TypedMessage<T>>): string {
const publicKey = getPublicKeyFor(msgParams);
return `0x${publicKey.toString('hex')}`;
}
function externalTypedSignatureHash (typedData: EIP712TypedData[]): string {
const hashBuffer = typedSignatureHash(typedData);
return ethUtil.bufferToHex(hashBuffer);
}
function signTypedDataLegacy<T extends MessageTypes> (privateKey: Buffer, msgParams: MsgParams<TypedData | TypedMessage<T>>): string {
const msgHash = typedSignatureHash(msgParams.data);
const sig = ethUtil.ecsign(msgHash, privateKey);
return ethUtil.bufferToHex(concatSig(sig.v, sig.r, sig.s));
}
function recoverTypedSignatureLegacy<T extends MessageTypes> (msgParams: SignedMsgParams<TypedData | TypedMessage<T>>): string {
const msgHash = typedSignatureHash(msgParams.data);
const publicKey = recoverPublicKey(msgHash, msgParams.sig);
const sender = ethUtil.publicToAddress(publicKey);
return ethUtil.bufferToHex(sender);
}
function encrypt<T extends MessageTypes> (receiverPublicKey: string, msgParams: MsgParams<TypedData | TypedMessage<T>>, version: string): EthEncryptedData {
switch (version) {
case 'x25519-xsalsa20-poly1305': {
if (typeof msgParams.data !== 'string') {
throw new Error('Cannot detect secret message, message params should be of the form {data: "secret message"} ');
}
// generate ephemeral keypair
const ephemeralKeyPair = nacl.box.keyPair();
// assemble encryption parameters - from string to UInt8
let pubKeyUInt8Array;
try {
pubKeyUInt8Array = naclUtil.decodeBase64(receiverPublicKey);
} catch (err) {
throw new Error('Bad public key');
}
const msgParamsUInt8Array = naclUtil.decodeUTF8(msgParams.data);
const nonce = nacl.randomBytes(nacl.box.nonceLength);
// encrypt
const encryptedMessage = nacl.box(msgParamsUInt8Array, nonce, pubKeyUInt8Array, ephemeralKeyPair.secretKey);
// handle encrypted data
const output = {
version: 'x25519-xsalsa20-poly1305',
nonce: naclUtil.encodeBase64(nonce),
ephemPublicKey: naclUtil.encodeBase64(ephemeralKeyPair.publicKey),
ciphertext: naclUtil.encodeBase64(encryptedMessage),
};
// return encrypted msg data
return output;
}
default:
throw new Error('Encryption type/version not supported');
}
}
function encryptSafely<T extends MessageTypes> (receiverPublicKey: string, msgParams: MsgParams<TypedData | TypedMessage<T>>, version: string): EthEncryptedData {
const DEFAULT_PADDING_LENGTH = 2 ** 11;
const NACL_EXTRA_BYTES = 16;
const { data } = msgParams;
if (!data) {
throw new Error('Cannot encrypt empty msg.data');
}
if (typeof data === 'object' && 'toJSON' in data) {
// remove toJSON attack vector
// TODO, check all possible children
throw new Error('Cannot encrypt with toJSON property. Please remove toJSON property');
}
// add padding
const dataWithPadding = {
data,
padding: '',
};
// calculate padding
const dataLength = Buffer.byteLength(JSON.stringify(dataWithPadding), 'utf-8');
const modVal = dataLength % DEFAULT_PADDING_LENGTH;
let padLength = 0;
// Only pad if necessary
if (modVal > 0) {
padLength = DEFAULT_PADDING_LENGTH - modVal - NACL_EXTRA_BYTES; // nacl extra bytes
}
dataWithPadding.padding = '0'.repeat(padLength);
const paddedMsgParams = { data: JSON.stringify(dataWithPadding) };
return encrypt(receiverPublicKey, paddedMsgParams, version);
}
function decrypt (encryptedData: EthEncryptedData, receiverPrivateKey: string): string {
switch (encryptedData.version) {
case 'x25519-xsalsa20-poly1305': {
// string to buffer to UInt8Array
const recieverPrivateKeyUint8Array = nacl_decodeHex(receiverPrivateKey);
const recieverEncryptionPrivateKey = nacl.box.keyPair.fromSecretKey(recieverPrivateKeyUint8Array).secretKey;
// assemble decryption parameters
const nonce = naclUtil.decodeBase64(encryptedData.nonce);
const ciphertext = naclUtil.decodeBase64(encryptedData.ciphertext);
const ephemPublicKey = naclUtil.decodeBase64(encryptedData.ephemPublicKey);
// decrypt
const decryptedMessage = nacl.box.open(ciphertext, nonce, ephemPublicKey, recieverEncryptionPrivateKey);
// return decrypted msg data
let output;
try {
output = naclUtil.encodeUTF8(decryptedMessage);
} catch (err) {
throw new Error('Decryption failed.');
}
if (output) {
return output;
}
throw new Error('Decryption failed.');
}
default:
throw new Error('Encryption type/version not supported.');
}
}
function decryptSafely (encryptedData: EthEncryptedData, receiverPrivateKey: string): string {
const dataWithPadding = JSON.parse(decrypt(encryptedData, receiverPrivateKey));
return dataWithPadding.data;
}
function getEncryptionPublicKey (privateKey: string): string {
const privateKeyUint8Array = nacl_decodeHex(privateKey);
const encryptionPublicKey = nacl.box.keyPair.fromSecretKey(privateKeyUint8Array).publicKey;
return naclUtil.encodeBase64(encryptionPublicKey);
}
/**
* A generic entry point for all typed data methods to be passed, includes a version parameter.
*/
function signTypedMessage<T extends MessageTypes> (privateKey: Buffer, msgParams: MsgParams<TypedData | TypedMessage<T>>, version: Version = 'V4'): string {
switch (version) {
case 'V1':
return signTypedDataLegacy(privateKey, msgParams);
case 'V3':
return signTypedData(privateKey, msgParams);
case 'V4':
default:
return signTypedData_v4(privateKey, msgParams);
}
}
function recoverTypedMessage<T extends MessageTypes> (msgParams: SignedMsgParams<TypedData | TypedMessage<T>>, version: Version = 'V4'): string {
switch (version) {
case 'V1':
return recoverTypedSignatureLegacy(msgParams);
case 'V3':
return recoverTypedSignature(msgParams);
case 'V4':
default:
return recoverTypedSignature_v4(msgParams);
}
}
function signTypedData<T extends MessageTypes> (privateKey: Buffer, msgParams: MsgParams<TypedData | TypedMessage<T>>): string {
const message = TypedDataUtils.sign(msgParams.data, false);
const sig = ethUtil.ecsign(message, privateKey);
return ethUtil.bufferToHex(concatSig(sig.v, sig.r, sig.s));
}
function signTypedData_v4<T extends MessageTypes> (privateKey: Buffer, msgParams: MsgParams<TypedData | TypedMessage<T>>): string {
const message = TypedDataUtils.sign(msgParams.data);
const sig = ethUtil.ecsign(message, privateKey);
return ethUtil.bufferToHex(concatSig(sig.v, sig.r, sig.s));
}
function recoverTypedSignature<T extends MessageTypes> (msgParams: SignedMsgParams<TypedData | TypedMessage<T>>): string {
const message = TypedDataUtils.sign(msgParams.data, false);
const publicKey = recoverPublicKey(message, msgParams.sig);
const sender = ethUtil.publicToAddress(publicKey);
return ethUtil.bufferToHex(sender);
}
function recoverTypedSignature_v4<T extends MessageTypes> (msgParams: SignedMsgParams<TypedData | TypedMessage<T>>): string {
const message = TypedDataUtils.sign(msgParams.data);
const publicKey = recoverPublicKey(message, msgParams.sig);
const sender = ethUtil.publicToAddress(publicKey);
return ethUtil.bufferToHex(sender);
}
export {
TYPED_MESSAGE_SCHEMA,
TypedDataUtils,
concatSig,
normalize,
personalSign,
recoverPersonalSignature,
extractPublicKey,
externalTypedSignatureHash as typedSignatureHash,
signTypedDataLegacy,
recoverTypedSignatureLegacy,
encrypt,
encryptSafely,
decrypt,
decryptSafely,
getEncryptionPublicKey,
signTypedMessage,
recoverTypedMessage,
signTypedData,
signTypedData_v4,
recoverTypedSignature,
recoverTypedSignature_v4,
};
/**
* @param typedData - Array of data along with types, as per EIP712.
* @returns Buffer
*/
function typedSignatureHash<T extends MessageTypes> (typedData: TypedData | TypedMessage<T>): Buffer {
const error = new Error('Expect argument to be non-empty array');
if (typeof typedData !== 'object' || !('length' in typedData) || !typedData.length) {
throw error;
}
const data = typedData.map(function (e) {
return e.type === 'bytes' ? ethUtil.toBuffer(e.value) : e.value;
});
const types = typedData.map(function (e) {
return e.type;
});
const schema = typedData.map(function (e) {
if (!e.name) {
throw error;
}
return `${e.type} ${e.name}`;
});
return ethAbi.soliditySHA3(
['bytes32', 'bytes32'],
[
ethAbi.soliditySHA3(new Array(typedData.length).fill('string'), schema),
ethAbi.soliditySHA3(types, data),
]
);
}
function recoverPublicKey (hash: Buffer, sig: string): Buffer {
const signature = ethUtil.toBuffer(sig);
const sigParams = ethUtil.fromRpcSig(signature);
return ethUtil.ecrecover(hash, sigParams.v, sigParams.r, sigParams.s);
}
function getPublicKeyFor<T extends MessageTypes> (msgParams: MsgParams<TypedData | TypedMessage<T>>): Buffer {
const message = ethUtil.toBuffer(msgParams.data);
const msgHash = ethUtil.hashPersonalMessage(message);
return recoverPublicKey(msgHash, msgParams.sig);
}
function padWithZeroes (number: string, length: number): string {
let myString = `${number}`;
while (myString.length < length) {
myString = `0${myString}`;
}
return myString;
}
// converts hex strings to the Uint8Array format used by nacl
function nacl_decodeHex (msgHex: string): Uint8Array {
const msgBase64 = Buffer.from(msgHex, 'hex').toString('base64');
return naclUtil.decodeBase64(msgBase64);
}