-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathvalidators.ts
More file actions
538 lines (499 loc) · 15.2 KB
/
validators.ts
File metadata and controls
538 lines (499 loc) · 15.2 KB
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
import { bytesToHex } from '@ethereumjs/util'
import { HistoryNetworkContentType, NetworkId, PingPongCustomPayload } from 'portalnetwork'
import { isValidEnr } from '../util.js'
const INVALID_PARAMS = -32602
type Falsy = false | '' | 0 | null | undefined | 0n
function isFalsy(value: unknown): value is Falsy {
return !!(
value === false ||
value === '' ||
value === 0 ||
Number.isNaN(value) ||
value === null ||
typeof value === 'undefined' ||
value === BigInt(0)
)
}
/**
* Returns true if a value is truthy
*
* @param value - Value to check for truthiness
*
* @deprecated This helper function should only be used temporarily until the monorepo types are explicit enough
*/
function isTruthy<T>(value: T | Falsy): value is T {
return !isFalsy(value)
}
/**
* middleware for parameters validation
* @memberof module:rpc
* @param method function to add middleware
* @param requiredParamsCount required parameters count
* @param validators array of validators
*/
export function middleware(method: any, requiredParamsCount: number, validators: any[] = []): any {
return function (params: any[] = []) {
return new Promise((resolve, reject) => {
if (params.length < requiredParamsCount) {
const error = {
code: INVALID_PARAMS,
message: `missing value for required argument ${params.length}`,
}
return reject(error)
}
for (let i = 0; i < validators.length; i++) {
if (isTruthy(validators[i])) {
for (let j = 0; j < validators[i].length; j++) {
const error = validators[i][j](params, i)
if (isTruthy(error)) {
return reject(error)
}
}
}
}
resolve(method(params))
})
}
}
/**
* @memberof module:rpc
*/
export const validators = {
/**
* address validator to ensure has `0x` prefix and 20 bytes length
* @param params parameters of method
* @param index index of parameter
*/
get address() {
return (params: any[], index: number) => {
if (typeof params[index] !== 'string') {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: argument must be a hex string`,
}
}
if (params[index].substr(0, 2) !== '0x') {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: missing 0x prefix`,
}
}
const address = params[index].substr(2)
if (!/^[0-9a-fA-F]+$/.test(address) || address.length !== 40) {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: invalid address`,
}
}
}
},
/**
* dstId validator to ensure is valid node ID
* @param params parameters of method
* @param index index of parameter
*/
get dstId() {
return (params: any[], index: number) => {
if (params[index]['raw'] !== undefined) {
params[index] = bytesToHex(Uint8Array.from(params[index]['raw'])).slice(2)
}
if (typeof params[index] !== 'string') {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: argument must be a string - received ${typeof params[
index
]}`,
}
}
if ((<string>params[index]).startsWith('0x')) {
params[index] = params[index].slice(2)
}
}
},
/**
* distance validator
* @param params parameters of method
* @param index index of parameter
*/
get distance() {
return (params: any[], index: number) => {
if (typeof params[index] !== 'number') {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: argument must be a number`,
}
}
if (params[index] < 0 || params[index] > 256) {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: argument must be a number`,
}
}
if (params[index] === 256) {
params[index] = 0
}
}
},
/**
* contentType validator to ensure is supported Content Type
* @param params parameters of method
* @param index index of parameter
*/
get history_contentType() {
return (params: any[], index: number) => {
if (typeof params[index] !== 'number') {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: argument must be a number`,
}
}
if (Object.values(HistoryNetworkContentType).includes(params[index])) {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: unsupported content type.`,
}
}
}
},
/**
* contentKey validator to ensure string has `0x` prefix and 33 bytes length
* @param params parameters of method
* @param index index of parameter
*/
get contentKey() {
return (params: any[], index: number) => {
if (typeof params[index] !== 'string') {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: argument must be a string`,
}
}
if (params[index].substr(0, 2) !== '0x') {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: hex string without 0x prefix`,
}
}
}
},
/**
* hex validator to ensure has `0x` prefix
* @param params parameters of method
* @param index index of parameter
*/
get hex() {
return (params: any[], index: number) => {
if (typeof params[index] !== 'string') {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: argument must be a hex string`,
}
}
if (params[index].substr(0, 2) !== '0x') {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: hex string without 0x prefix`,
}
}
}
},
get enr() {
return (params: any[], index: number) => {
if (typeof params[index] !== 'string') {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: enr must be string`,
}
}
if (!isValidEnr(params[index])) {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: string must be compliant with EIP-778 by starting with "enr:" and encoded using valid characters of the Base64URL encoding scheme`,
}
}
}
},
get networkId() {
return (params: any[], index: number) => {
if (!Object.values(NetworkId).includes(params[index])) {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: Network not supported`,
}
}
}
},
/**
* hex validator to validate block hash
* @param params parameters of method
* @param index index of parameter
*/
get blockHash() {
return (params: any[], index: number) => {
if (typeof params[index] !== 'string') {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: argument must be a hex string`,
}
}
if (params[index].substr(0, 2) !== '0x') {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: hex string without 0x prefix`,
}
}
const blockHash = params[index].substring(2)
if (!/^[0-9a-fA-F]+$/.test(blockHash) || blockHash.length !== 64) {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: invalid block hash`,
}
}
}
},
/**
* validator to ensure valid block integer or hash, or string option ["latest", "earliest", "pending"]
* @param params parameters of method
* @param index index of parameter
*/
get blockOption() {
return (params: any[], index: number) => {
if (typeof params[index] !== 'string') {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: argument must be a string`,
}
}
const blockOption = params[index]
if (!['latest', 'earliest', 'pending'].includes(blockOption)) {
if (blockOption.substr(0, 2) === '0x') {
const hash = this.blockHash([blockOption], 0)
// todo: make integer validator?
const integer = this.hex([blockOption], 0)
// valid if undefined
if (hash === undefined || integer === undefined) {
// valid
return
}
}
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: block option must be a valid 0x-prefixed block hash or hex integer, or "latest", "earliest" or "pending"`,
}
}
}
},
/**
* bool validator to check if type is boolean
* @param params parameters of method
* @param index index of parameter
*/
get bool() {
return (params: any[], index: number) => {
if (typeof params[index] !== 'boolean') {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: argument is not boolean`,
}
}
}
},
/**
* MB validator to check if type is positive integer
* @param params parameters of method
* @param index index of parameter
*/
get megabytes() {
return (params: any[], index: number) => {
if (
typeof params[index] !== 'number' ||
params[index] < 1 ||
!Number.isInteger(params[index])
) {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: argument is not whole number megabytes`,
}
}
}
},
/**
* validator to ensure required transaction fields are present, and checks for valid address and hex values.
* @param requiredFields array of required fields
* @returns validator function with params:
* - @param params parameters of method
* - @param index index of parameter
*/
get transaction() {
return (requiredFields: string[] = []) => {
return (params: any[], index: number) => {
if (typeof params[index] !== 'object') {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: argument must be an object`,
}
}
const tx = params[index]
for (const field of requiredFields) {
if (isFalsy(tx[field])) {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: required field ${field}`,
}
}
}
const validate = (field: any, validator: Function) => {
if (isFalsy(field)) return
const v = validator([field], 0)
if (isTruthy(v)) return v
}
// validate addresses
for (const field of [tx.to, tx.from]) {
const v = validate(field, this.address)
if (isTruthy(v)) return v
}
// validate hex
for (const field of [tx.gas, tx.gasPrice, tx.value, tx.data]) {
const v = validate(field, this.hex)
if (isTruthy(v)) return v
}
}
}
},
/**
* object validator to check if type is object with
* required keys and expected validation of values
* @param form object with keys and values of validators
* @returns validator function with params:
* - @param params parameters of method
* - @param index index of parameter
*/
get object() {
return (form: { [key: string]: Function }) => {
return (params: any[], index: number) => {
if (typeof params[index] !== 'object') {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: argument is not object`,
}
}
for (const [key, validator] of Object.entries(form)) {
const value = params[index][key]
const result = validator([value], 0)
if (isTruthy(result)) {
// add key to message for context
const originalMessage = result.message.split(':')
const message = `invalid argument ${index} for key '${key}':${originalMessage[1]}`
return { ...result, message }
}
}
}
}
},
/**
* array validator to check if each element
* of the array passes the passed-in validator
* @param validator validator to check against the elements of the array
* @returns validator function with params:
* - @param params parameters of method
* - @param index index of parameter
*/
get array() {
return (validator: Function) => {
return (params: any[], index: number) => {
if (!Array.isArray(params[index])) {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: argument is not array`,
}
}
for (const value of params[index]) {
const result = validator([value], 0)
if (isTruthy(result)) return result
}
}
}
},
/**
* validator to ensure that contains one of the string values
* @param values array of possible values
* @returns validator function with params:
* - @param params parameters of method
* - @param index index of parameter
*/
get values() {
return (values: string[]) => {
return (params: any[], index: number) => {
if (!values.includes(params[index])) {
const valueOptions = '[' + values.map((v) => `"${v}"`).join(', ') + ']'
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: argument is not one of ${valueOptions}`,
}
}
}
}
},
/**
* Validator to allow validation of an optional value
* @param validator validator to check against the value
* @returns validator function with params:
* - @param params parameters of method
* - @param index index of parameter
*/
get optional() {
return (validator: any) => {
return (params: any, index: number) => {
if (isFalsy(params[index])) {
return
}
return validator(params, index)
}
}
},
/**
* Validator that passes if any of the specified validators pass
* @param validator validator to check against the value
* @returns validator function with params:
* - @param params parameters of method
* - @param index index of parameter
*/
get either() {
return (...validators: any) => {
return (params: any, index: number) => {
if (isFalsy(params[index])) {
return
}
const results = validators.map((v: any) => v(params, index))
const numPassed = results.filter((r: any) => r === undefined).length
return numPassed > 0 ? undefined : results[0]
}
}
},
get extension() {
return (params: any[], index: number) => {
if (typeof params[index] !== 'number') {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: argument must be a number`,
}
}
if (!(params[index] in PingPongCustomPayload)) {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: argument must be a supported PingPong payload type`,
}
}
}
},
get payload() {
return (params: any[], index: number) => {
if (typeof params[index] !== 'object') {
return {
code: INVALID_PARAMS,
message: `invalid argument ${index}: argument must be an object`,
}
}
}
},
}