-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathprocessor-utils.js
519 lines (448 loc) · 18.5 KB
/
processor-utils.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
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
/* eslint-disable no-use-before-define */
/* eslint-disable max-len */
const { ethers } = require('ethers');
const { Scalar } = require('ffjavascript');
const Constants = require('./constants');
const smtUtils = require('./smt-utils');
const { valueToHexStr } = require('./utils');
/**
* Extract an integer from a byte array
* @param {Uint8Array} data - Byte array
* @param {Number} offset - Offset of the data array
* @param {Number} length - Length of the integer in bytes
* @returns {Number} - Extracted integer
*/
function unarrayifyInteger(data, offset, length) {
let result = 0;
for (let i = 0; i < length; i++) {
result = (result * 256) + data[offset + i];
}
return result;
}
/**
* Convert a custom rawTx:
* - preEIP155: [rlp(nonce, gasprice, gaslimit, to, value, data)|r|s|v|effectivePercentage]
* - Legacy: [rlp(nonce, gasprice, gaslimit, to, value, data, chainId, 0, 0)|r|s|v|effectivePercentage]
* to a standard raw ethereum tx: [rlp(nonce, gasprice, gaslimit, to, value, data, r, s, v)]
* @param {String} customRawTx - Custom raw transaction
* @returns {String} - Standard raw transaction
*/
function customRawTxToRawTx(customRawTx) {
const signatureCharacters = Constants.SIGNATURE_BYTES * 2;
const effectivePercentageCharacters = Constants.EFFECTIVE_PERCENTAGE_BYTES * 2;
const rlpSignData = customRawTx.slice(0, -(signatureCharacters + effectivePercentageCharacters));
const signature = `0x${customRawTx.slice(-(signatureCharacters + effectivePercentageCharacters), -effectivePercentageCharacters)}`;
const txFields = ethers.utils.RLP.decode(rlpSignData);
const signatureParams = ethers.utils.splitSignature(signature);
let rlpFields;
if (txFields[6] === undefined) {
const v = ethers.utils.hexlify(signatureParams.v);
const r = ethers.BigNumber.from(signatureParams.r).toHexString(); // does not have necessary 32 bytes
const s = ethers.BigNumber.from(signatureParams.s).toHexString(); // does not have necessary 32 bytes
rlpFields = [...txFields, v, r, s];
} else {
const v = ethers.utils.hexlify(signatureParams.v - 27 + txFields[6] * 2 + 35);
const r = ethers.BigNumber.from(signatureParams.r).toHexString(); // does not have necessary 32 bytes
const s = ethers.BigNumber.from(signatureParams.s).toHexString(); // does not have necessary 32 bytes
rlpFields = [...txFields.slice(0, -3), v, r, s];
}
return ethers.utils.RLP.encode(rlpFields);
}
/**
* Reduce an array of rawTx to a single string which will be the BatchL2Data
* @param {Array} rawTxs - Array of rawTxs
* @returns {String} - Reduced array
*/
function arrayToEncodedString(rawTxs) {
return rawTxs.reduce((previousValue, currentValue) => previousValue + currentValue.slice(2), '0x');
}
/**
* Convert a number type to a hex string starting with 0x and with a integer number of bytes
* @param {Number | BigInt | BigNumber | Object | String} num - Number
* @returns {Number} - Hex string
*/
function toHexStringRlp(num) {
let numHex;
if (typeof num === 'number' || typeof num === 'bigint' || typeof num === 'object') {
numHex = Scalar.toString(Scalar.e(num), 16);
// if it's an integer and it's value is 0, the standard is set to 0x, instead of 0x00 ( because says that always is codified in the shortest way)
if (Scalar.e(num) === Scalar.e(0)) return '0x';
} else if (typeof num === 'string') {
numHex = num.startsWith('0x') ? num.slice(2) : num;
}
numHex = (numHex.length % 2 === 1) ? (`0x0${numHex}`) : (`0x${numHex}`);
return numHex;
}
/**
* Convert a Ethereum address hex string starting with 0x and with a integer number of bytes
* @param {Number | BigInt | BigNumber | Object | String} address - address
* @returns {Number} - address hex string
*/
function addressToHexStringRlp(address) {
// empty address: deployment
if (typeof address === 'undefined' || (typeof address === 'string' && address === '0x')) {
return '0x';
}
let addressScalar;
if (typeof address === 'number' || typeof address === 'bigint' || typeof address === 'object') {
addressScalar = Scalar.e(address);
} else if (typeof address === 'string') {
const tmpAddr = address.startsWith('0x') ? address : `0x${address}`;
addressScalar = Scalar.fromString(tmpAddr, 16);
}
return `0x${Scalar.toString(addressScalar, 16).padStart(40, '0')}`;
}
/**
* Convert a standard rawTx of ethereum [rlp(nonce,gasprice,gaslimit,to,value,data,r,s,v)]
* to our custom raw tx:
* - preEIP155: [rlp(nonce,gasprice,gaslimit,to,value,data)|r|s|v|effectivePercentage]
* - Legacy: [rlp(nonce,gasprice,gaslimit,to,value,data,chainId,0,0)|r|s|v|effectivePercentage]
* @param {String} rawTx - Standard raw transaction
* @returns {String} - Custom raw transaction
*/
function rawTxToCustomRawTx(rawTx, effectivePercentage) {
const tx = ethers.utils.parseTransaction(rawTx);
let signData;
let r;
let s;
let v;
// check preEIP155
if (tx.chainId === 0 && (tx.v === 27 || tx.v === 28)) {
signData = ethers.utils.RLP.encode([
toHexStringRlp(tx.nonce),
toHexStringRlp(tx.gasPrice),
toHexStringRlp(tx.gasLimit),
addressToHexStringRlp(tx.to || '0x'),
toHexStringRlp(tx.value),
toHexStringRlp(tx.data),
]);
r = tx.r.slice(2);
s = tx.s.slice(2);
v = tx.v.toString(16).padStart(2, '0'); // 1 byte
} else {
signData = ethers.utils.RLP.encode([
toHexStringRlp(tx.nonce),
toHexStringRlp(tx.gasPrice),
toHexStringRlp(tx.gasLimit),
addressToHexStringRlp(tx.to || '0x'),
toHexStringRlp(tx.value),
toHexStringRlp(tx.data),
toHexStringRlp(tx.chainId),
'0x',
'0x',
]);
r = tx.r.slice(2);
s = tx.s.slice(2);
v = (tx.v - tx.chainId * 2 - 35 + 27).toString(16).padStart(2, '0'); // 1 byte
}
if (typeof effectivePercentage === 'undefined') {
effectivePercentage = 'ff';
}
return signData.concat(r).concat(s).concat(v).concat(effectivePercentage);
}
/**
* Decode the BatchL2Data to an array of rawTxs
* @param {String} encodedTransactions - Reduced array
* @returns {Array} - Array of rawTxs
*/
function encodedStringToArray(encodedTransactions) {
const encodedTxBytes = ethers.utils.arrayify(encodedTransactions);
const decodedRawTx = [];
let offset = 0;
while (offset < encodedTxBytes.length) {
if (encodedTxBytes[offset] === Constants.TX_CHANGE_L2_BLOCK) {
const bytesToRead = 1 + Constants.DELTA_TIMESTAMP_BYTES + Constants.INDEX_L1INFOTREE_BYTES;
const tx = ethers.utils.hexlify(encodedTxBytes.slice(offset, offset + bytesToRead));
decodedRawTx.push(tx);
offset += bytesToRead;
} else if (encodedTxBytes[offset] >= 0xf8) {
const lengthLength = encodedTxBytes[offset] - 0xf7;
if (offset + 1 + lengthLength > encodedTxBytes.length) {
throw new Error('encodedTxBytes short segment too short');
}
const length = unarrayifyInteger(encodedTxBytes, offset + 1, lengthLength);
if (offset + 1 + lengthLength + length > encodedTxBytes.length) {
throw new Error('encodedTxBytes long segment too short');
}
const bytesToRead = 1 + lengthLength + length + Constants.SIGNATURE_BYTES + Constants.EFFECTIVE_PERCENTAGE_BYTES;
decodedRawTx.push(ethers.utils.hexlify(encodedTxBytes.slice(offset, offset + bytesToRead)));
offset += bytesToRead;
} else if (encodedTxBytes[offset] >= 0xc0) {
const length = encodedTxBytes[offset] - 0xc0;
if (offset + 1 + length > encodedTxBytes.length) {
throw new Error('encodedTxBytes array too short');
}
const bytesToRead = 1 + length + Constants.SIGNATURE_BYTES + Constants.EFFECTIVE_PERCENTAGE_BYTES;
decodedRawTx.push(ethers.utils.hexlify(encodedTxBytes.slice(offset, offset + bytesToRead)));
offset += bytesToRead;
} else {
throw new Error('Error encodedStringToArray');
}
}
return decodedRawTx;
}
/**
* Decode The next string in rlp, that is 0-55 bytes long
* @param {Uint8Array} data - Byte array
* @param {Number} offset - Offset of the data array
* @returns {Object} - Return the bytes consumed and the result encoded in hex string
*/
function decodeNextShortStringRLP(encodedTxBytes, offset) {
if (encodedTxBytes[offset] >= 0xb8) {
throw new Error('Should be a short string RLP');
} else if (encodedTxBytes[offset] >= 0x80) {
const length = encodedTxBytes[offset] - 0x80;
const result = ethers.utils.hexlify(encodedTxBytes.slice(offset + 1, offset + 1 + length));
return { consumed: (1 + length), result };
} else {
return { consumed: 1, result: ethers.utils.hexlify(encodedTxBytes[offset]) };
}
}
/**
* Decode The next string in rlp
* @param {String} encodedTxBytes - Reduced array
* @returns {Array} - Array of rawTxs
*/
function decodeNextStringRLP(encodedTxBytes, offset) {
if (encodedTxBytes[offset] >= 0xb8) {
const lengthLength = encodedTxBytes[offset] - 0xb7;
const length = unarrayifyInteger(encodedTxBytes, offset + 1, lengthLength);
const result = ethers.utils.hexlify(encodedTxBytes.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length));
return { consumed: (1 + lengthLength + length), result };
}
return decodeNextShortStringRLP(encodedTxBytes, offset);
}
/**
* Decode the BatchL2Data to an array of rawTxs using the prover method
* @param {String} encodedTransactions - Reduced array
* @returns {Object} - The object contain the Array of rawTxs and the rlpSignData as the prover does
*/
function decodeCustomRawTxProverMethod(encodedTransactions) {
// should check total len before read
const encodedTxBytes = ethers.utils.arrayify(encodedTransactions);
const txDecoded = {};
let offset = 0; // in zkasm this is the p
let txListLength = 0;
let headerLength = 0;
// Decode list length
if (encodedTxBytes[offset] < 0xc0) {
throw new Error('headerList should be a list');
} else if (encodedTxBytes[offset] >= 0xf8) {
const lengthLength = encodedTxBytes[offset] - 0xf7;
txListLength = unarrayifyInteger(encodedTxBytes, offset + 1, lengthLength);
offset = offset + 1 + lengthLength;
headerLength = 1 + lengthLength;
} else if (encodedTxBytes[offset] >= 0xc0) {
txListLength = encodedTxBytes[offset] - 0xc0;
offset += 1;
headerLength = 1;
}
// Nonce read
const decodedNonce = decodeNextShortStringRLP(encodedTxBytes, offset);
offset += decodedNonce.consumed;
txDecoded.nonce = decodedNonce.result;
// GasPrice read
const decodedGasPrice = decodeNextShortStringRLP(encodedTxBytes, offset);
offset += decodedGasPrice.consumed;
txDecoded.gasPrice = decodedGasPrice.result;
// gas read
const decodedGasLimit = decodeNextShortStringRLP(encodedTxBytes, offset);
offset += decodedGasLimit.consumed;
txDecoded.gasLimit = decodedGasLimit.result;
// To READ
if (encodedTxBytes[offset] === 0x80) {
txDecoded.to = '0x';
offset += 1;
} else if (encodedTxBytes[offset] === 0x94) {
const length = 20;
txDecoded.to = ethers.utils.hexlify(encodedTxBytes.slice(offset + 1, offset + 1 + length));
offset += 1 + length;
} else {
throw new Error('To should be an address or empty');
}
// Value READ
const decodedValue = decodeNextShortStringRLP(encodedTxBytes, offset);
offset += decodedValue.consumed;
txDecoded.value = decodedValue.result;
// Data READ
const decodedData = decodeNextStringRLP(encodedTxBytes, offset);
offset += decodedData.consumed;
txDecoded.data = decodedData.result;
// Don't decode chainId if tx is legacy
if (txListLength + headerLength !== offset) {
// chainID READ
const decodedChainID = decodeNextShortStringRLP(encodedTxBytes, offset);
offset += decodedChainID.consumed;
txDecoded.chainID = decodedChainID.result;
if ((encodedTxBytes[offset] !== 0x80) || encodedTxBytes[offset + 1] !== 0x80) {
throw new Error('The last 2 values should be 0x8080');
}
offset += 2;
}
if (txListLength + headerLength !== offset) {
throw new Error('Invalid list length');
}
const rlpSignData = ethers.utils.hexlify(encodedTxBytes.slice(0, offset));
const lenR = 32;
const lenS = 32;
const lenV = 1;
const lenEffectivePercentage = 1;
txDecoded.r = ethers.utils.hexlify(encodedTxBytes.slice(offset, offset + lenR));
offset += lenR;
// r: assert to read 32 bytes
if (txDecoded.r.length !== (2 + 2 * lenR)) {
throw new Error('Invalid signature length: R');
}
txDecoded.s = ethers.utils.hexlify(encodedTxBytes.slice(offset, offset + lenS));
offset += lenS;
// s: assert to read 32 bytes
if (txDecoded.s.length !== (2 + 2 * lenS)) {
throw new Error('Invalid signature length: S');
}
txDecoded.v = ethers.utils.hexlify(encodedTxBytes.slice(offset, offset + lenV));
offset += lenV;
// v: assert to read 32 bytes
if (txDecoded.v.length !== (2 + 2 * lenV)) {
throw new Error('Invalid signature length: V');
}
txDecoded.effectivePercentage = ethers.utils.hexlify(encodedTxBytes.slice(offset, offset + lenEffectivePercentage));
offset += lenEffectivePercentage;
if (txDecoded.effectivePercentage === '0x') {
txDecoded.effectivePercentage = '0xff';
}
return { txDecoded, rlpSignData };
}
/**
* Computes the effective gas price for a transaction
* @param {String | BigInt} gasPrice in hex string or BigInt
* @param {String | BigInt} effectivePercentage in hex string or BigInt
* @returns effectiveGasPrice as BigInt
*/
function computeEffectiveGasPrice(gasPrice, effectivePercentage) {
const effectivegasPrice = Scalar.div(
Scalar.mul(Scalar.e(gasPrice), (Scalar.e(Number(effectivePercentage) + 1))),
256,
);
return effectivegasPrice;
}
/**
* Computes the L2 transaction hash from a transaction
* @param {Object} tx tx to compute l2 hash, must have nonce, gasPrice, chainID, gasLimit, to, value, data, from in hex string
* @returns computed l2 tx hash or object with txHash and dataEncoded uf returnEncoded is true
*/
async function computeL2TxHash(tx, returnEncoded = false) {
// txType 00 for pre-EIP155 (no chainID) and 01 for legacy transactions
let txType = '01';
if (typeof tx.chainID === 'undefined' || tx.chainID === '00' || tx.chainID === '0x') {
txType = '00';
}
// Add txType, nonce, gasPrice and gasLimit
let hash = `${txType}`
+ `${formatL2TxHashParam(tx.nonce, 8)}`
+ `${formatL2TxHashParam(tx.gasPrice, 32)}`
+ `${formatL2TxHashParam(tx.gasLimit, 8)}`;
// Check is deploy
if (typeof tx.to === 'undefined' || tx.to === '' || tx.to === '0x') {
hash += '01';
} else {
hash += `00${formatL2TxHashParam(tx.to, 20)}`;
}
// Add value
hash += `${formatL2TxHashParam(tx.value, 32)}`;
let { data } = tx;
// Compute data length
if (data.startsWith('0x')) {
data = data.slice(2);
}
const dataLength = Math.ceil(data.length / 2);
hash += `${formatL2TxHashParam(dataLength.toString(16), 3)}`;
if (dataLength > 0) {
hash += `${formatL2TxHashParam(data, dataLength)}`;
}
// Add chainID
if (typeof tx.chainID !== 'undefined') {
hash += `${formatL2TxHashParam(tx.chainID, 8)}`;
}
// Add from
hash += `${formatL2TxHashParam(tx.from, 20)}`;
const txHash = await smtUtils.linearPoseidon(hash);
if (returnEncoded) {
return { txHash, dataEncoded: hash };
}
return txHash;
}
/**
* Formats a tx param to compute the linear poseidon hash of l2TxHash
* @param {String} param in hex string
* @param {Number} paramLength Length of the string param, used for left zero padding
* @returns formatted param
*/
function formatL2TxHashParam(param, paramLength) {
// Convert to hex string if param is a number
if (typeof param === 'number') {
param = param.toString(16);
}
if (param.startsWith('0x')) {
param = param.slice(2);
}
// format to bytes
if (param.length % 2 === 1) {
param = `0${param}`;
}
// Checks hex correctness
if (/^[0-9a-fA-F]+$/.test(param) === false) {
throw new Error('Invalid hex string');
}
param = param.padStart(paramLength * 2, '0');
return param;
}
/**
* Decode string into a changeL2Transaction transaction type
* @param {String} _rawTx
* @returns {Object} transaction object
*/
async function decodeChangeL2BlockTx(_rawTx) {
const tx = {};
let offsetChars = 0;
const serializedTx = _rawTx.startsWith('0x') ? _rawTx.slice(2) : _rawTx;
let charsToRead = Constants.TYPE_BYTES * 2;
tx.type = parseInt(serializedTx.slice(offsetChars, offsetChars + charsToRead), 16);
offsetChars += charsToRead;
charsToRead = Constants.DELTA_TIMESTAMP_BYTES * 2;
tx.deltaTimestamp = Scalar.fromString(serializedTx.slice(offsetChars, offsetChars + charsToRead), 16);
offsetChars += charsToRead;
charsToRead = Constants.INDEX_L1INFOTREE_BYTES * 2;
tx.indexL1InfoTree = parseInt(serializedTx.slice(offsetChars, offsetChars + charsToRead), 16);
return tx;
}
/**
* Serialize transaction for the batch
* fields: [type | deltaTimestamp | indexL1InfoTree ]
* bytes: [ 1 | 4 | 4 ]
* @param {Object} tx - transaction object
* @returns {String} - Serialized tx in hexadecimal string
*/
function serializeChangeL2Block(tx) {
let data = Scalar.e(0);
let offsetBits = 0;
data = Scalar.add(data, Scalar.shl(tx.indexL1InfoTree, offsetBits));
offsetBits += Constants.INDEX_L1INFOTREE_BYTES * 8;
data = Scalar.add(data, Scalar.shl(tx.deltaTimestamp, offsetBits));
offsetBits += Constants.DELTA_TIMESTAMP_BYTES * 8;
data = Scalar.add(data, Scalar.shl(tx.type, offsetBits));
offsetBits += Constants.TYPE_BYTES * 8;
return valueToHexStr(data).padStart(offsetBits / 4, '0');
}
module.exports = {
decodeCustomRawTxProverMethod,
rawTxToCustomRawTx,
toHexStringRlp,
customRawTxToRawTx,
arrayToEncodedString,
encodedStringToArray,
addressToHexStringRlp,
computeEffectiveGasPrice,
computeL2TxHash,
decodeChangeL2BlockTx,
serializeChangeL2Block,
};