This repository was archived by the owner on Mar 5, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
Copy pathSoliditySha3.js
247 lines (204 loc) · 6.78 KB
/
SoliditySha3.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
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file SoliditySha3.js
* @author Fabian Vogelsteller <[email protected]>
* @date 2017
*/
import isArray from 'lodash/isArray';
import isObject from 'lodash/isObject';
import map from 'lodash/map';
import BN from 'bn.js';
import * as utils from './Utils.js';
const _elementaryName = (name) => {
if (name.startsWith('int[')) {
return `int256${name.slice(3)}`;
}
if (name === 'int') {
return 'int256';
}
if (name.startsWith('uint[')) {
return `uint256${name.slice(4)}`;
}
if (name === 'uint') {
return 'uint256';
}
if (name.startsWith('fixed[')) {
return `fixed128x128${name.slice(5)}`;
}
if (name === 'fixed') {
return 'fixed128x128';
}
if (name.startsWith('ufixed[')) {
return `ufixed128x128${name.slice(6)}`;
}
if (name === 'ufixed') {
return 'ufixed128x128';
}
return name;
};
// Parse N from type<N>
const _parseTypeN = (type) => {
const typesize = /^\D+(\d+).*$/.exec(type);
return typesize ? parseInt(typesize[1], 10) : null;
};
// Parse N from type[<N>]
const _parseTypeNArray = (type) => {
const arraySize = /^\D+\d*\[(\d+)\]$/.exec(type);
return arraySize ? parseInt(arraySize[1], 10) : null;
};
const _parseNumber = (arg) => {
const type = typeof arg;
if (type === 'string') {
if (utils.isHexStrict(arg)) {
return new BN(arg.replace(/0x/i, ''), 16);
} else {
return new BN(arg, 10);
}
} else if (type === 'number') {
return new BN(arg);
} else if (utils.isBigNumber(arg)) {
return new BN(arg.toString(10));
} else if (utils.isBN(arg)) {
return arg;
} else {
throw new Error(`${arg} is not a number`);
}
};
const _solidityPack = (type, value, arraySize) => {
let size, num;
type = _elementaryName(type);
if (type === 'bytes') {
if (value.replace(/^0x/i, '').length % 2 !== 0) {
throw new Error(`Invalid bytes characters ${value.length}`);
}
return value;
} else if (type === 'string') {
return utils.utf8ToHex(value);
} else if (type === 'bool') {
return value ? '01' : '00';
} else if (type.startsWith('address')) {
if (arraySize) {
size = 64;
} else {
size = 40;
}
if (!utils.isAddress(value)) {
throw new Error(`${value} is not a valid address, or the checksum is invalid.`);
}
return utils.leftPad(value.toLowerCase(), size);
}
size = _parseTypeN(type);
if (type.startsWith('bytes')) {
if (!size) {
throw new Error('bytes[] not yet supported in solidity');
}
// must be 32 byte slices when in an array
if (arraySize) {
size = 32;
}
if (size < 1 || size > 32 || size < value.replace(/^0x/i, '').length / 2) {
throw new Error(`Invalid bytes${size} for ${value}`);
}
return utils.rightPad(value, size * 2);
} else if (type.startsWith('uint')) {
if (size % 8 || size < 8 || size > 256) {
throw new Error(`Invalid uint${size} size`);
}
num = _parseNumber(value);
if (num.bitLength() > size) {
throw new Error(`Supplied uint exceeds width: ${size} vs ${num.bitLength()}`);
}
if (num.lt(new BN(0))) {
throw new Error(`Supplied uint ${num.toString()} is negative`);
}
return size ? utils.leftPad(num.toString('hex'), (size / 8) * 2) : num;
} else if (type.startsWith('int')) {
if (size % 8 || size < 8 || size > 256) {
throw new Error(`Invalid int${size} size`);
}
num = _parseNumber(value);
if (num.bitLength() > size) {
throw new Error(`Supplied int exceeds width: ${size} vs ${num.bitLength()}`);
}
if (num.lt(new BN(0))) {
return num.toTwos(size).toString('hex');
} else {
return size ? utils.leftPad(num.toString('hex'), (size / 8) * 2) : num;
}
} else {
// FIXME: support all other types
throw new Error(`Unsupported or invalid type: ${type}`);
}
};
const _processSoliditySha3Args = (arg) => {
if (isArray(arg)) {
throw new Error('Autodetection of array types is not supported.');
}
let type;
let value = '';
let hexArg, arraySize;
// if type is given
if (
isObject(arg) &&
(arg.hasOwnProperty('v') ||
arg.hasOwnProperty('t') ||
arg.hasOwnProperty('value') ||
arg.hasOwnProperty('type'))
) {
type = arg.hasOwnProperty('t') ? arg.t : arg.type;
value = arg.hasOwnProperty('v') ? arg.v : arg.value;
// otherwise try to guess the type
} else {
type = utils.toHex(arg, true);
value = utils.toHex(arg);
if (!type.startsWith('int') && !type.startsWith('uint')) {
type = 'bytes';
}
}
if ((type.startsWith('int') || type.startsWith('uint')) && typeof value === 'string' && !/^(-)?0x/i.test(value)) {
value = new BN(value);
}
// get the array size
if (isArray(value)) {
arraySize = _parseTypeNArray(type);
if (arraySize && value.length !== arraySize) {
throw new Error(`${type} is not matching the given array ${JSON.stringify(value)}`);
} else {
arraySize = value.length;
}
}
if (isArray(value)) {
hexArg = value.map((val) => {
return _solidityPack(type, val, arraySize)
.toString('hex')
.replace('0x', '');
});
return hexArg.join('');
} else {
hexArg = _solidityPack(type, value, arraySize);
return hexArg.toString('hex').replace('0x', '');
}
};
/**
* Hashes solidity values to a sha3 hash using keccak 256
*
* @method soliditySha3
* @return {Object} the sha3
*/
export const soliditySha3 = function() {
const args = Array.prototype.slice.call(arguments);
const hexArgs = map(args, _processSoliditySha3Args);
return utils.sha3(`0x${hexArgs.join('')}`);
};