forked from MetaMask/eth-sig-util
-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
257 lines (234 loc) · 8.13 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
const util = require('./util')
const abi = require('./abi')
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, useV4 = true) {
const encodedTypes = ['bytes32']
const encodedValues = [this.hashType(primaryType, types)]
if(useV4) {
const encodeField = (name, type, value) => {
if (types[type] !== undefined) {
return ['bytes32', value == null ?
'0x0000000000000000000000000000000000000000000000000000000000000000' :
util.keccak(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', util.keccak(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', util.keccak(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', util.keccak(abi.rawEncode(
typeValuePairs.map(([type]) => type),
typeValuePairs.map(([, value]) => value),
))]
}
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 = util.keccak(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 = util.keccak(value)
encodedValues.push(value)
} else if (types[field.type] !== undefined) {
encodedTypes.push('bytes32')
value = util.keccak(this.encodeData(field.type, value, types, useV4))
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 abi.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 = []) {
primaryType = primaryType.match(/^\w*/)[0]
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, useV4 = true) {
return util.keccak(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 {string} - Hash of an object
*/
hashType (primaryType, types) {
return util.keccak(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])
}
if (sanitizedData.types) {
sanitizedData.types = Object.assign({ EIP712Domain: [] }, sanitizedData.types)
}
return sanitizedData
},
/**
* Returns the hash of a typed message as per EIP-712 for signing
*
* @param {Object} typedData - Types message data to sign
* @returns {string} - sha3 hash for signing
*/
hash (typedData, useV4 = true) {
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 util.keccak(Buffer.concat(parts))
},
}
module.exports = {
TYPED_MESSAGE_SCHEMA,
TypedDataUtils,
hashForSignTypedDataLegacy: function (msgParams) {
return typedSignatureHashLegacy(msgParams.data)
},
hashForSignTypedData_v3: function (msgParams) {
return TypedDataUtils.hash(msgParams.data, false)
},
hashForSignTypedData_v4: function (msgParams) {
return TypedDataUtils.hash(msgParams.data)
},
}
/**
* @param typedData - Array of data along with types, as per EIP712.
* @returns Buffer
*/
function typedSignatureHashLegacy(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' ? util.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 abi.soliditySHA3(
['bytes32', 'bytes32'],
[
abi.soliditySHA3(new Array(typedData.length).fill('string'), schema),
abi.soliditySHA3(types, data)
]
)
}