forked from MetaMask/eth-sig-util
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
381 lines (327 loc) · 12 KB
/
index.js
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
const ethUtil = require('ethereumjs-util');
const ethAbi = require('ethereumjs-abi');
const nacl = require('tweetnacl');
nacl.util = require('tweetnacl-util');
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 {string} - Encoded representation of an object
*/
encodeData (primaryType, data, types) {
const encodedTypes = ['bytes32']
const encodedValues = [this.hashType(primaryType, types)]
for (const field of types[primaryType]) {
let value = data[field.name]
if (value !== undefined) {
if (field.type === 'string' || field.type === 'bytes') {
encodedTypes.push('bytes32')
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))
encodedValues.push(value)
} else if (field.type.lastIndexOf(']') === field.type.length - 1) {
throw new Error('Arrays currently unimplemented in encodeData')
} 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, types) {
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 }) => `${type} ${name}`).join(',')})`
}
return result
},
/**
* Finds all types within a type defintion 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, types, results = []) {
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 {string} - Hash of an object
*/
hashStruct (primaryType, data, types) {
return ethUtil.sha3(this.encodeData(primaryType, data, types))
},
/**
* Hashes the type of an object
*
* @param {string} primaryType - Root type to hash
* @param {Object} types - Type definitions
* @returns {string} - Hash of an object
*/
hashType (primaryType, types) {
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 (data) {
const sanitizedData = {}
for (const key in TYPED_MESSAGE_SCHEMA.properties) {
data[key] && (sanitizedData[key] = data[key])
}
return sanitizedData
},
/**
* Signs a typed message as per EIP-712 and returns its sha3 hash
*
* @param {Object} typedData - Types message data to sign
* @returns {string} - sha3 hash of the resulting signed message
*/
sign (typedData) {
sanitizedData = this.sanitizeData(typedData)
const parts = [Buffer.from('1901', 'hex')]
parts.push(this.hashStruct('EIP712Domain', sanitizedData.domain, sanitizedData.types))
parts.push(this.hashStruct(sanitizedData.primaryType, sanitizedData.message, sanitizedData.types))
return ethUtil.sha3(Buffer.concat(parts))
},
}
module.exports = {
TYPED_MESSAGE_SCHEMA,
TypedDataUtils,
concatSig: function (v, r, s) {
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')
},
normalize: function (input) {
if (!input) return
if (typeof input === 'number') {
const buffer = ethUtil.toBuffer(input)
input = ethUtil.bufferToHex(buffer)
}
if (typeof input !== 'string') {
var 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())
},
personalSign: function (privateKey, msgParams) {
var message = ethUtil.toBuffer(msgParams.data)
var msgHash = ethUtil.hashPersonalMessage(message)
var sig = ethUtil.ecsign(msgHash, privateKey)
var serialized = ethUtil.bufferToHex(this.concatSig(sig.v, sig.r, sig.s))
return serialized
},
recoverPersonalSignature: function (msgParams) {
const publicKey = getPublicKeyFor(msgParams)
const sender = ethUtil.publicToAddress(publicKey)
const senderHex = ethUtil.bufferToHex(sender)
return senderHex
},
extractPublicKey: function (msgParams) {
const publicKey = getPublicKeyFor(msgParams)
return '0x' + publicKey.toString('hex')
},
typedSignatureHash: function (typedData) {
const hashBuffer = typedSignatureHash(typedData)
return ethUtil.bufferToHex(hashBuffer)
},
signTypedDataLegacy: function (privateKey, msgParams) {
const msgHash = typedSignatureHash(msgParams.data)
const sig = ethUtil.ecsign(msgHash, privateKey)
return ethUtil.bufferToHex(this.concatSig(sig.v, sig.r, sig.s))
},
recoverTypedSignatureLegacy: function (msgParams) {
const msgHash = typedSignatureHash(msgParams.data)
const publicKey = recoverPublicKey(msgHash, msgParams.sig)
const sender = ethUtil.publicToAddress(publicKey)
return ethUtil.bufferToHex(sender)
},
encrypt: function(receiverPublicKey, msgParams, version) {
switch(version) {
case 'x25519-xsalsa20-poly1305':
console.log(typeof msgParams.data )
if( typeof msgParams.data == 'undefined'){
throw new Error('Cannot detect secret message, message params should be of the form {data: "secret message"} ')
}
//generate ephemeral keypair
var ephemeralKeyPair = nacl.box.keyPair()
// assemble encryption parameters - from string to UInt8
try {
var pubKeyUInt8Array = nacl.util.decodeBase64(receiverPublicKey);
} catch (err){
throw new Error('Bad public key')
}
var msgParamsUInt8Array = nacl.util.decodeUTF8(msgParams.data);
var nonce = nacl.randomBytes(nacl.box.nonceLength);
// encrypt
var encryptedMessage = nacl.box(msgParamsUInt8Array, nonce, pubKeyUInt8Array, ephemeralKeyPair.secretKey);
// handle encrypted data
var output = {
version: 'x25519-xsalsa20-poly1305',
nonce: nacl.util.encodeBase64(nonce),
ephemPublicKey: nacl.util.encodeBase64(ephemeralKeyPair.publicKey),
ciphertext: nacl.util.encodeBase64(encryptedMessage)
};
// return encrypted msg data
return output;
default:
throw new Error('Encryption type/version not supported')
}
},
decrypt: function(encryptedData, receiverPrivateKey) {
switch(encryptedData.version) {
case 'x25519-xsalsa20-poly1305':
//string to buffer to UInt8Array
var recieverPrivateKeyUint8Array = nacl_decodeHex(receiverPrivateKey)
var recieverEncryptionPrivateKey = nacl.box.keyPair.fromSecretKey(recieverPrivateKeyUint8Array).secretKey
// assemble decryption parameters
var nonce = nacl.util.decodeBase64(encryptedData.nonce);
var ciphertext = nacl.util.decodeBase64(encryptedData.ciphertext);
var ephemPublicKey = nacl.util.decodeBase64(encryptedData.ephemPublicKey);
// decrypt
var decryptedMessage = nacl.box.open(ciphertext, nonce, ephemPublicKey, recieverEncryptionPrivateKey);
// return decrypted msg data
try {
var output = nacl.util.encodeUTF8(decryptedMessage);
}catch(err) {
throw new Error('Decryption failed.')
}
if (output){
return output;
}else{
throw new Error('Decryption failed.')
}
default:
throw new Error('Encryption type/version not supported.')
}
},
getEncryptionPublicKey: function(privateKey){
var privateKeyUint8Array = nacl_decodeHex(privateKey)
var encryptionPublicKey = nacl.box.keyPair.fromSecretKey(privateKeyUint8Array).publicKey
return nacl.util.encodeBase64(encryptionPublicKey)
}
signTypedData: function (privateKey, msgParams) {
const message = TypedDataUtils.sign(msgParams.data)
const sig = ethUtil.ecsign(message, privateKey)
return ethUtil.bufferToHex(this.concatSig(sig.v, sig.r, sig.s))
},
recoverTypedSignature: function (msgParams) {
const message = TypedDataUtils.sign(msgParams.data)
const publicKey = recoverPublicKey(message, msgParams.sig)
const sender = ethUtil.publicToAddress(publicKey)
return ethUtil.bufferToHex(sender)
},
}
/**
* @param typedData - Array of data along with types, as per EIP712.
* @returns Buffer
*/
function typedSignatureHash(typedData) {
const error = new Error('Expect argument to be non-empty array')
if (typeof typedData !== 'object' || !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, sig) {
const signature = ethUtil.toBuffer(sig)
const sigParams = ethUtil.fromRpcSig(signature)
return ethUtil.ecrecover(hash, sigParams.v, sigParams.r, sigParams.s)
}
function getPublicKeyFor (msgParams) {
const message = ethUtil.toBuffer(msgParams.data)
const msgHash = ethUtil.hashPersonalMessage(message)
return recoverPublicKey(msgHash, msgParams.sig)
}
function padWithZeroes (number, length) {
var 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) {
var msgBase64 = (new Buffer(msgHex, 'hex')).toString('base64');
return nacl.util.decodeBase64(msgBase64);
}