This repository has been archived by the owner on Mar 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
validator.ts
667 lines (585 loc) · 16.2 KB
/
validator.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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
const newrelic = require("newrelic");
import {
calcFee,
calcIntrinsicGas,
validateHexNumber,
validateHexString,
} from "../util";
import { BlockParameter, BlockSpecifier } from "./types";
import { logger } from "../base/logger";
import { InvalidParamsError, RpcError } from "./error";
import { CKB_SUDT_ID, RPC_MAX_GAS_LIMIT } from "./constant";
import { HexNumber, HexString } from "@ckb-lumos/base";
import { envConfig } from "../base/env-config";
import { GodwokenClient } from "@godwoken-web3/godwoken";
import { EthRegistryAddress } from "../base/address";
/**
* middleware for parameters validation
* @param {Function} method function to add middleware
* @param {number} requiredParamsCount required parameters count
* @param {Function[]} validators array of validator
*/
export function middleware(
method: (args: any[] | any) => any | Promise<any>,
requiredParamsCount: number,
validators: any[] = []
): any {
return async function (params: any[] = []): Promise<any> {
if (params.length < requiredParamsCount) {
throw new InvalidParamsError(
`missing value for required argument ${params.length}`
);
}
for (let i = 0; i < validators.length; i++) {
if (!validators[i]) {
throw new Error(`validator ${i} not found!`);
}
const err = validators[i](params, i);
if (err) {
throw new RpcError(err.code, err.message, err.data);
}
}
try {
return await newrelic.startSegment(method.name, true, async () => {
return await method(params);
});
} catch (err: any) {
logger.error(
`JSONRPC Server Error: [${method.name}] ${err} ${err.stack}`
);
throw new RpcError(err.code, err.message, err.data);
}
};
}
export const validators = {
/**
* hex validator to ensure has "0x" prefix
* @param {any[]} params parameters of method
* @param {number} index index of parameter
*/
/**
* hex string validator
* @param {any[]} params parameters of method
* @param {number} index index of parameter
*/
hexString(params: any[], index: number) {
return verifyHexString(params[index], index);
},
hexNumber(params: any[], index: number) {
return verifyHexNumber(params[index], index);
},
/**
* Hex number | "latest" | "earliest" | "pending"
* @param params
* @param index
* @returns
*/
blockParameter(params: any[], index: number) {
return verifyBlockParameter(params[index], index);
},
/**
* hex validator to validate block hash
* @param {any[]} params parameters of method
* @param {number} index index of parameter
*/
blockHash(params: any[], index: number) {
return verifyBlockHash(params[index], index);
},
/**
* hex validator to validate transaction hash
* @param {any[]} params parameters of method
* @param {number} index index of parameter
*/
txHash(params: any[], index: number) {
return verifyTxHash(params[index], index);
},
/**
* hex validator to validate block hash
* @param {any[]} params parameters of method
* @param {number} index index of parameter
*/
address(params: any[], index: number) {
return verifyAddress(params[index], index);
},
/**
* bool validator to check if type is boolean
* @param {any[]} params parameters of method
* @param {number} index index of parameter
*/
bool(params: any[], index: number) {
return verifyBoolean(params[index], index);
},
ethCallParams(params: any[], index: number) {
return verifyEthCallObject(params[index], index);
},
ethEstimateGasParams(params: any[], index: number) {
return verifyEstimateGasCallObject(params[index], index);
},
newFilterParams(params: any[], index: number) {
return verifyNewFilterObj(params[index], index);
},
};
//****** standalone verify function ********/
export function verifyBoolean(
bool: any,
index: number
): InvalidParamsError | undefined {
if (typeof bool !== "boolean") {
return invalidParamsError(index, `argument is not boolean`);
}
return undefined;
}
export function verifyHexNumber(
hexNumber: string,
index: number
): InvalidParamsError | undefined {
if (typeof hexNumber !== "string") {
return invalidParamsError(
index,
`hexNumber argument must be a string type`
);
}
if (!hexNumber.startsWith("0x")) {
return invalidParamsError(index, `hexNumber without 0x prefix`);
}
if (!validateHexNumber(hexNumber)) {
return invalidParamsError(index, `invalid hexNumber token`);
}
return undefined;
}
export function verifyHexString(
hexString: any,
index: number
): InvalidParamsError | undefined {
if (typeof hexString !== "string") {
return invalidParamsError(
index,
`hexString argument must be a string type`
);
}
if (!hexString.startsWith("0x")) {
return invalidParamsError(index, `hexString without 0x prefix`);
}
if (hexString.length % 2 !== 0) {
return invalidParamsError(index, `hexString must has even length`);
}
if (!validateHexString(hexString)) {
return invalidParamsError(index, `invalid hexString token`);
}
return undefined;
}
export function verifyAddress(
address: any,
index: number
): InvalidParamsError | undefined {
const err = verifyHexString(address, index);
if (err) {
return err.padContext("address");
}
if (address.substring(2).length !== 40) {
return invalidParamsError(
index,
`expect address has 20 bytes, but getting ${
address.substring(2).length / 2
} bytes`
);
}
return undefined;
}
export function verifyBlockHash(
blockHash: any,
index: number
): InvalidParamsError | undefined {
const err = verifyHexString(blockHash, index);
if (err) {
return err.padContext("blockHash");
}
if (blockHash.substring(2).length !== 64) {
return invalidParamsError(
index,
`expect blockHash has 32 bytes, but getting ${
blockHash.substring(2).length / 2
} bytes`
);
}
return undefined;
}
export function verifyTxHash(
txHash: any,
index: number
): InvalidParamsError | undefined {
const err = verifyHexString(txHash, index);
if (err) {
return err.padContext("txHash");
}
if (txHash.substring(2).length !== 64) {
return invalidParamsError(
index,
`expect txHash has 32 bytes, but getting ${
txHash.substring(2).length / 2
} bytes`
);
}
return undefined;
}
export function verifyBlockParameter(
blockParameter: BlockParameter,
index: number
): InvalidParamsError | undefined {
if (
blockParameter === "latest" ||
blockParameter === "earliest" ||
blockParameter === "pending"
) {
return undefined;
}
if (typeof blockParameter === "object") {
const err = verifyBlockSpecifier(blockParameter, index);
if (err) {
return err.padContext("blockSpecifier");
}
} else {
const err = verifyHexNumber(blockParameter, index);
if (err) {
return err.padContext("blockParameter block number");
}
}
return undefined;
}
export function verifyBlockSpecifier(
blockSpecifier: BlockSpecifier,
index: number
) {
if (typeof blockSpecifier !== "object") {
return invalidParamsError(index, `blockSpecifier must be an object`);
}
if (blockSpecifier.blockHash == null && blockSpecifier.blockNumber == null) {
return invalidParamsError(
index,
"blockSpecifier has no blockHash and blockNumber"
);
}
if (blockSpecifier.blockHash != null && blockSpecifier.blockNumber != null) {
return invalidParamsError(
index,
"blockHash and blockNumber can not exits at same time"
);
}
if (
blockSpecifier.requireCanonical != null &&
typeof blockSpecifier.requireCanonical !== "boolean"
) {
return invalidParamsError(index, "requireCanonical should be boolean type");
}
if (blockSpecifier.blockNumber != null) {
const err = verifyHexNumber(blockSpecifier.blockNumber, index);
if (err) {
return err.padContext("blockSpecifier block number");
}
}
if (blockSpecifier.blockHash != null) {
const err = verifyBlockHash(blockSpecifier.blockHash, index);
if (err) {
return err.padContext("blockSpecifier block hash");
}
}
return undefined;
}
export function verifyOptEthCallObject(
callObj: any,
index: number
): InvalidParamsError | undefined {
if (typeof callObj !== "object") {
return invalidParamsError(index, `argument must be an object`);
}
const from = callObj.from;
const to = callObj.to;
const gasPrice = callObj.gasPrice;
const gasLimit = callObj.gas;
const value = callObj.value;
const data = callObj.data;
// validate `to`
if (to != null) {
const toErr = verifyAddress(to, index);
if (toErr) {
return toErr.padContext("callObj to address");
}
}
// validate `from`
if (from != null) {
const fromErr = verifyAddress(from, index);
if (fromErr) {
return fromErr.padContext("callObj from address");
}
}
// validate `gasPrice`
if (gasPrice != null) {
const gasErr = verifyHexNumber(gasPrice, index);
if (gasErr) {
return gasErr.padContext("callObj gasPrice");
}
}
// validate `gasLimit`
if (gasLimit != null) {
const gasLimitErr = verifyGasLimit(gasLimit, index);
if (gasLimitErr) {
return gasLimitErr.padContext("callObj");
}
}
// validate `value`
if (value != null) {
const valueErr = verifyHexNumber(value, index);
if (valueErr) {
return valueErr.padContext("callObj value");
}
}
// validate `data`
if (data != null) {
const dataErr = verifyHexString(data, index);
if (dataErr) {
return dataErr.padContext("callObj data");
}
}
return undefined;
}
export function verifyEthCallObject(
callObj: any,
index: number
): InvalidParamsError | undefined {
const err = verifyOptEthCallObject(callObj, index);
if (err) {
return err.padContext("eth_call");
}
// to is required
if (callObj.to == null) {
return invalidParamsError(index, `eth_call to address is required!`);
}
return undefined;
}
export function verifyEstimateGasCallObject(
callObj: any,
index: number
): InvalidParamsError | undefined {
const err = verifyOptEthCallObject(callObj, index);
if (err) {
return err.padContext("eth_estimateGas");
}
return undefined;
}
export function verifyFilterTopicString(
topic: any,
index: number
): InvalidParamsError | undefined {
const err = verifyHexString(topic, index);
if (err) {
return err.padContext("topic string");
}
if (topic.substring(2).length !== 64) {
return invalidParamsError(
index,
`expect topic string has 32 bytes, but getting ${
topic.substring(2).length / 2
} bytes`
);
}
return undefined;
}
export function verifyFilterTopic(
topic: any,
index: number
): InvalidParamsError | undefined {
// topic type: export type FilterTopic = HexString | null | HexString[] (../src/cache/type.ts)
if (!Array.isArray(topic)) {
return topic == null ? undefined : verifyFilterTopicString(topic, index);
}
for (const t of topic) {
if (t == null) continue;
const err = verifyFilterTopicString(t, index);
if (err) {
return err.padContext("topicString[] array");
}
}
return undefined;
}
export function verifyNewFilterObj(
filterObj: any,
index: number
): InvalidParamsError | undefined {
if (typeof filterObj !== "object") {
return invalidParamsError(index, `filter argument must be an object`);
}
const fromBlock = filterObj.fromBlock;
const toBlock = filterObj.toBlock;
const address = filterObj.address;
const topics = filterObj.topics;
// validate `fromBlock`
if (fromBlock != null) {
const fromBlockErr = verifyBlockParameter(fromBlock, index);
if (fromBlockErr) {
return fromBlockErr.padContext("filter fromBlock");
}
}
// validate `toBlock`
if (toBlock != null) {
const toBlockErr = verifyBlockParameter(toBlock, index);
if (toBlockErr) {
return toBlockErr.padContext("filter toBlock");
}
}
// validate `address`
if (address != null) {
if (Array.isArray(address)) {
for (const addr of address) {
const addressErr = verifyAddress(addr, index);
if (addressErr) {
return addressErr.padContext("filter address[] Array");
}
}
} else {
const addressErr = verifyAddress(address, index);
if (addressErr) {
return addressErr.padContext("filter address");
}
}
}
// validate `topics`
if (topics != null) {
if (!Array.isArray(topics)) {
return invalidParamsError(index, `filter topics must be an array`);
}
for (const topic of topics) {
const topicErr = verifyFilterTopic(topic, index);
if (topicErr) {
return topicErr.padContext("filter topic[] Array");
}
}
}
return undefined;
}
export function verifyGasLimit(
gasLimit: HexNumber,
index: number
): InvalidParamsError | undefined {
const gasLimitErr = verifyHexNumber(gasLimit, index);
if (gasLimitErr) {
return gasLimitErr.padContext("gasLimit");
}
if (BigInt(gasLimit) > BigInt(RPC_MAX_GAS_LIMIT)) {
return invalidParamsError(
index,
`gas limit ${gasLimit} exceeds rpc gas limit of ${RPC_MAX_GAS_LIMIT}`
);
}
return undefined;
}
export function verifyGasPrice(
gasPrice: HexNumber,
index: number
): InvalidParamsError | undefined {
const gasPriceErr = verifyHexNumber(gasPrice, index);
if (gasPriceErr) {
return gasPriceErr.padContext("gasPrice");
}
if (
envConfig.minGasPrice != null &&
BigInt(gasPrice) < BigInt(envConfig.minGasPrice)
) {
return invalidParamsError(
index,
`minimal gas price ${envConfig.minGasPrice} required. got ${BigInt(
gasPrice
).toString(10)}`
);
}
return undefined;
}
export function verifyL2TxFee(
fee: HexNumber,
serializedL2Tx: HexString,
index: number
): InvalidParamsError | undefined {
const feeErr = verifyHexNumber(fee, index);
if (feeErr) {
return feeErr.padContext("L2Tx Fee");
}
const txErr = verifyHexString(serializedL2Tx, index);
if (txErr) {
return txErr.padContext("L2Tx Fee");
}
const feeRate = BigInt(envConfig.feeRate || 0);
const requiredFee = calcFee(serializedL2Tx, feeRate);
if (BigInt(fee) < requiredFee) {
return invalidParamsError(
index,
`minimal l2tx fee ${requiredFee.toString(10)} required. got ${BigInt(
fee
).toString(10)}`
);
}
return undefined;
}
export function verifyIntrinsicGas(
to: HexString | undefined,
input: HexString | undefined,
gas: HexNumber,
index: number
) {
const intrinsicGas = calcIntrinsicGas(to, input);
if (BigInt(gas) < intrinsicGas) {
return invalidParamsError(
index,
`intrinsic Gas too low ${gas.toString()}, require ${intrinsicGas.toString()}`
);
}
return undefined;
}
export async function checkBalance(
rpc: GodwokenClient,
from: HexString,
value?: HexNumber,
gas?: HexNumber,
gasPrice?: HexNumber
): Promise<{ requiredBalance: bigint; balance: bigint }> {
const registryAddress: EthRegistryAddress = new EthRegistryAddress(from);
const balance = await rpc.getBalance(
registryAddress.serialize(),
+CKB_SUDT_ID
);
const txValue: bigint = value == null || value === "0x" ? 0n : BigInt(value);
const txGas: bigint = gas == null || gas === "0x" ? 0n : BigInt(gas);
const txGasPrice: bigint =
gasPrice == null || gasPrice === "0x" ? 0n : BigInt(gasPrice);
const requiredBalance = txGas * txGasPrice + txValue;
return {
balance,
requiredBalance,
};
}
export async function verifyEnoughBalance(
rpc: GodwokenClient,
from: HexString,
value: HexNumber | undefined,
gas: HexNumber | undefined,
gasPrice: HexNumber | undefined,
index: number
) {
const { balance, requiredBalance } = await checkBalance(
rpc,
from,
value,
gas,
gasPrice
);
if (balance < requiredBalance) {
return invalidParamsError(
index,
`insufficient balance, require ${requiredBalance.toString()}, got ${balance}`
);
}
return undefined;
}
//******* end of standalone verify function ********/
// some utils function
function invalidParamsError(index: number, message: string) {
return new InvalidParamsError(`invalid argument ${index}: ${message}`);
}