-
Notifications
You must be signed in to change notification settings - Fork 61
/
service.ts
744 lines (661 loc) · 19.6 KB
/
service.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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
/* Imports: External */
import { BaseService, Logger, LegacyMetrics } from '@eth-optimism/common-ts'
import express, { Request, Response } from 'express'
import promBundle from 'express-prom-bundle'
import cors from 'cors'
import { BigNumber } from 'ethers'
import { JsonRpcProvider } from '@ethersproject/providers'
import { LevelUp } from 'levelup'
import * as Sentry from '@sentry/node'
import * as Tracing from '@sentry/tracing'
/* Imports: Internal */
import { TransportDB } from '../../db/transport-db'
import {
ContextResponse,
GasPriceResponse,
EnqueueResponse,
StateRootBatchResponse,
StateRootResponse,
SyncingResponse,
TransactionBatchResponse,
TransactionResponse,
} from '../../types'
import { validators } from '../../utils'
import { L1DataTransportServiceOptions } from '../main/service'
export interface L1TransportServerOptions
extends L1DataTransportServiceOptions {
db: LevelUp
metrics: LegacyMetrics
}
const optionSettings = {
db: {
validate: validators.isLevelUP,
},
port: {
default: 7878,
validate: validators.isInteger,
},
hostname: {
default: 'localhost',
validate: validators.isString,
},
confirmations: {
validate: validators.isInteger,
},
l1RpcProvider: {
validate: (val: any) => {
return validators.isUrl(val) || validators.isJsonRpcProvider(val)
},
},
l2RpcProvider: {
validate: (val: unknown) => {
return validators.isUrl(val) || validators.isJsonRpcProvider(val)
},
},
defaultBackend: {
default: 'l1',
validate: (val: string) => {
return val === 'l1' || val === 'l2'
},
},
l1GasPriceBackend: {
default: 'l1',
validate: (val: string) => {
return val === 'l1' || val === 'l2'
},
},
}
export class L1TransportServer extends BaseService<L1TransportServerOptions> {
constructor(options: L1TransportServerOptions) {
super('L1_Transport_Server', options, optionSettings)
}
private state: {
app: express.Express
server: any
db: TransportDB
l1RpcProvider: JsonRpcProvider
l2RpcProvider: JsonRpcProvider
} = {} as any
protected async _init(): Promise<void> {
if (!this.options.db.isOpen()) {
await this.options.db.open()
}
this.state.db = new TransportDB(this.options.db, {
bssHardfork1Index: this.options.bssHardfork1Index,
})
this.state.l1RpcProvider =
typeof this.options.l1RpcProvider === 'string'
? new JsonRpcProvider(this.options.l1RpcProvider)
: this.options.l1RpcProvider
this.state.l2RpcProvider =
typeof this.options.l2RpcProvider === 'string'
? new JsonRpcProvider(this.options.l2RpcProvider)
: this.options.l2RpcProvider
this._initializeApp()
}
protected async _start(): Promise<void> {
this.state.server = this.state.app.listen(
this.options.port,
this.options.hostname
)
this.logger.info('Server started and listening', {
host: this.options.hostname,
port: this.options.port,
})
}
protected async _stop(): Promise<void> {
this.state.server.close()
}
/**
* Initializes the server application.
* Do any sort of initialization here that you want. Mostly just important that
* `_registerAllRoutes` is called at the end.
*/
private _initializeApp() {
// TODO: Maybe pass this in as a parameter instead of creating it here?
this.state.app = express()
if (this.options.useSentry) {
this._initSentry()
}
this.state.app.use(cors())
// Add prometheus middleware to express BEFORE route registering
this.state.app.use(
// This also serves metrics on port 3000 at /metrics
promBundle({
// Provide metrics registry that other metrics uses
promRegistry: this.metrics.registry,
includeMethod: true,
includePath: true,
})
)
this._registerAllRoutes()
// Sentry error handling must be after all controllers
// and before other error middleware
if (this.options.useSentry) {
this.state.app.use(Sentry.Handlers.errorHandler())
}
this.logger.info('HTTP Server Options', {
defaultBackend: this.options.defaultBackend,
l1GasPriceBackend: this.options.l1GasPriceBackend,
})
if (this.state.l1RpcProvider) {
this.logger.info('HTTP Server L1 RPC Provider initialized', {
url: this.state.l1RpcProvider.connection.url,
})
} else {
this.logger.warn('HTTP Server L1 RPC Provider not initialized')
}
if (this.state.l2RpcProvider) {
this.logger.info('HTTP Server L2 RPC Provider initialized', {
url: this.state.l2RpcProvider.connection.url,
})
} else {
this.logger.warn('HTTP Server L2 RPC Provider not initialized')
}
}
/**
* Initialize Sentry and related middleware
*/
private _initSentry() {
const sentryOptions = {
dsn: this.options.sentryDsn,
release: this.options.release,
environment: this.options.ethNetworkName,
}
this.logger = new Logger({
name: this.name,
sentryOptions,
})
Sentry.init({
...sentryOptions,
integrations: [
new Sentry.Integrations.Http({ tracing: true }),
new Tracing.Integrations.Express({
app: this.state.app,
}),
],
tracesSampleRate: this.options.sentryTraceRate,
})
this.state.app.use(Sentry.Handlers.requestHandler())
this.state.app.use(Sentry.Handlers.tracingHandler())
}
/**
* Registers a route on the server.
*
* @param method Http method type.
* @param route Route to register.
* @param handler Handler called and is expected to return a JSON response.
*/
private _registerRoute(
method: 'get', // Just handle GET for now, but could extend this with whatever.
route: string,
handler: (req?: Request, res?: Response) => Promise<any>
): void {
// TODO: Better typing on the return value of the handler function.
// TODO: Check for route collisions.
// TODO: Add a different function to allow for removing routes.
this.state.app[method](route, async (req, res) => {
const start = Date.now()
try {
const json = await handler(req, res)
const elapsed = Date.now() - start
this.logger.info('Served HTTP Request', {
method: req.method,
url: req.url,
elapsed,
})
this.logger.debug('Response body', {
method: req.method,
url: req.url,
body: json,
})
return res.json(json)
} catch (e) {
const elapsed = Date.now() - start
this.logger.error('Failed HTTP Request', {
method: req.method,
url: req.url,
elapsed,
msg: e.toString(),
stack: e.stack,
})
return res.status(400).json({
error: e.toString(),
})
}
})
}
/**
* Registers all of the server routes we want to expose.
* TODO: Link to our API spec.
*/
private _registerAllRoutes(): void {
this._registerRoute(
'get',
'/eth/syncing',
async (req): Promise<SyncingResponse> => {
const backend = req.query.backend || this.options.defaultBackend
let currentL2Block
let highestL2BlockNumber
switch (backend) {
case 'l1':
currentL2Block = await this.state.db.getLatestTransaction()
highestL2BlockNumber = await this.state.db.getHighestL2BlockNumber()
break
case 'l2':
currentL2Block =
await this.state.db.getLatestUnconfirmedTransaction()
highestL2BlockNumber =
(await this.state.db.getHighestSyncedUnconfirmedBlock()) - 1
break
default:
throw new Error(`Unknown transaction backend ${backend}`)
}
if (currentL2Block === null) {
if (highestL2BlockNumber === null) {
return {
syncing: false,
currentTransactionIndex: 0,
}
} else {
return {
syncing: true,
highestKnownTransactionIndex: highestL2BlockNumber,
currentTransactionIndex: 0,
}
}
}
if (highestL2BlockNumber > currentL2Block.index) {
return {
syncing: true,
highestKnownTransactionIndex: highestL2BlockNumber,
currentTransactionIndex: currentL2Block.index,
}
} else {
return {
syncing: false,
currentTransactionIndex: currentL2Block.index,
}
}
}
)
/**
* /eth/syncing is for l2geth, but we want to get status of syncing as the replica.
* /eth/syncing/l2 returns the actual l2 block number and current l2 block number that
* dtl synced to.
*/
this._registerRoute(
'get',
'/eth/syncing/l2',
async (req): Promise<SyncingResponse> => {
const currentL2Block =
await this.state.db.getLatestUnconfirmedTransaction()
const highestL2BlockNumber = await this.state.db.getTargetL2Block()
if (currentL2Block === null) {
if (highestL2BlockNumber === null) {
return {
syncing: false,
currentTransactionIndex: 0,
}
} else {
return {
syncing: true,
highestKnownTransactionIndex: highestL2BlockNumber,
currentTransactionIndex: 0,
}
}
}
if (highestL2BlockNumber > currentL2Block.index) {
return {
syncing: true,
highestKnownTransactionIndex: highestL2BlockNumber,
currentTransactionIndex: currentL2Block.index,
}
} else {
return {
syncing: false,
currentTransactionIndex: currentL2Block.index,
}
}
}
)
this._registerRoute(
'get',
'/eth/gasprice',
async (req): Promise<GasPriceResponse> => {
const backend = req.query.backend || this.options.l1GasPriceBackend
let gasPrice: BigNumber
if (backend === 'l1') {
gasPrice = await this.state.l1RpcProvider.getGasPrice()
} else if (backend === 'l2') {
const response = await this.state.l2RpcProvider.send(
'rollup_gasPrices',
[]
)
gasPrice = BigNumber.from(response.l1GasPrice)
} else {
throw new Error(`Unknown L1 gas price backend: ${backend}`)
}
return {
gasPrice: gasPrice.toString(),
}
}
)
this._registerRoute(
'get',
'/eth/context/latest',
async (): Promise<ContextResponse> => {
const tip = await this.state.l1RpcProvider.getBlockNumber()
const blockNumber = Math.max(0, tip - this.options.confirmations)
const block = await this.state.l1RpcProvider.getBlock(blockNumber)
return {
blockNumber: block.number,
timestamp: block.timestamp,
blockHash: block.hash,
}
}
)
this._registerRoute(
'get',
'/eth/context/blocknumber/:number',
async (req): Promise<ContextResponse> => {
const number = BigNumber.from(req.params.number).toNumber()
const tip = await this.state.l1RpcProvider.getBlockNumber()
const blockNumber = Math.max(0, tip - this.options.confirmations)
if (number > blockNumber) {
return {
blockNumber: null,
timestamp: null,
blockHash: null,
}
}
const block = await this.state.l1RpcProvider.getBlock(number)
return {
blockNumber: block.number,
timestamp: block.timestamp,
blockHash: block.hash,
}
}
)
this._registerRoute(
'get',
'/enqueue/latest',
async (): Promise<EnqueueResponse> => {
const enqueue = await this.state.db.getLatestEnqueue()
if (enqueue === null) {
return {
index: null,
target: null,
data: null,
gasLimit: null,
origin: null,
blockNumber: null,
timestamp: null,
ctcIndex: null,
}
}
const ctcIndex = await this.state.db.getTransactionIndexByQueueIndex(
enqueue.index
)
return {
...enqueue,
ctcIndex,
}
}
)
this._registerRoute(
'get',
'/enqueue/index/:index',
async (req): Promise<EnqueueResponse> => {
const enqueue = await this.state.db.getEnqueueByIndex(
BigNumber.from(req.params.index).toNumber()
)
if (enqueue === null) {
return {
index: null,
target: null,
data: null,
gasLimit: null,
origin: null,
blockNumber: null,
timestamp: null,
ctcIndex: null,
}
}
const ctcIndex = await this.state.db.getTransactionIndexByQueueIndex(
enqueue.index
)
return {
...enqueue,
ctcIndex,
}
}
)
this._registerRoute(
'get',
'/transaction/latest',
async (req): Promise<TransactionResponse> => {
const backend = req.query.backend || this.options.defaultBackend
let transaction = null
switch (backend) {
case 'l1':
transaction = await this.state.db.getLatestFullTransaction()
break
case 'l2':
transaction = await this.state.db.getLatestUnconfirmedTransaction()
break
default:
throw new Error(`Unknown transaction backend ${backend}`)
}
if (transaction === null) {
return {
transaction: null,
batch: null,
}
}
const batch = await this.state.db.getTransactionBatchByIndex(
transaction.batchIndex
)
return {
transaction,
batch,
}
}
)
this._registerRoute(
'get',
'/transaction/index/:index',
async (req): Promise<TransactionResponse> => {
const backend = req.query.backend || this.options.defaultBackend
let transaction = null
switch (backend) {
case 'l1':
transaction = await this.state.db.getFullTransactionByIndex(
BigNumber.from(req.params.index).toNumber()
)
break
case 'l2':
transaction = await this.state.db.getUnconfirmedTransactionByIndex(
BigNumber.from(req.params.index).toNumber()
)
break
default:
throw new Error(`Unknown transaction backend ${backend}`)
}
if (transaction === null) {
return {
transaction: null,
batch: null,
}
}
const batch = await this.state.db.getTransactionBatchByIndex(
transaction.batchIndex
)
return {
transaction,
batch,
}
}
)
this._registerRoute(
'get',
'/batch/transaction/latest',
async (): Promise<TransactionBatchResponse> => {
const batch = await this.state.db.getLatestTransactionBatch()
if (batch === null) {
return {
batch: null,
transactions: [],
}
}
const transactions =
await this.state.db.getFullTransactionsByIndexRange(
BigNumber.from(batch.prevTotalElements).toNumber(),
BigNumber.from(batch.prevTotalElements).toNumber() +
BigNumber.from(batch.size).toNumber()
)
return {
batch,
transactions,
}
}
)
this._registerRoute(
'get',
'/batch/transaction/index/:index',
async (req): Promise<TransactionBatchResponse> => {
const batch = await this.state.db.getTransactionBatchByIndex(
BigNumber.from(req.params.index).toNumber()
)
if (batch === null) {
return {
batch: null,
transactions: [],
}
}
const transactions =
await this.state.db.getFullTransactionsByIndexRange(
BigNumber.from(batch.prevTotalElements).toNumber(),
BigNumber.from(batch.prevTotalElements).toNumber() +
BigNumber.from(batch.size).toNumber()
)
return {
batch,
transactions,
}
}
)
this._registerRoute(
'get',
'/stateroot/latest',
async (req): Promise<StateRootResponse> => {
const backend = req.query.backend || this.options.defaultBackend
let stateRoot = null
switch (backend) {
case 'l1':
stateRoot = await this.state.db.getLatestStateRoot()
break
case 'l2':
stateRoot = await this.state.db.getLatestUnconfirmedStateRoot()
break
default:
throw new Error(`Unknown transaction backend ${backend}`)
}
if (stateRoot === null) {
return {
stateRoot: null,
batch: null,
}
}
const batch = await this.state.db.getStateRootBatchByIndex(
stateRoot.batchIndex
)
return {
stateRoot,
batch,
}
}
)
this._registerRoute(
'get',
'/stateroot/index/:index',
async (req): Promise<StateRootResponse> => {
const backend = req.query.backend || this.options.defaultBackend
let stateRoot = null
switch (backend) {
case 'l1':
stateRoot = await this.state.db.getStateRootByIndex(
BigNumber.from(req.params.index).toNumber()
)
break
case 'l2':
stateRoot = await this.state.db.getUnconfirmedStateRootByIndex(
BigNumber.from(req.params.index).toNumber()
)
break
default:
throw new Error(`Unknown transaction backend ${backend}`)
}
if (stateRoot === null) {
return {
stateRoot: null,
batch: null,
}
}
const batch = await this.state.db.getStateRootBatchByIndex(
stateRoot.batchIndex
)
return {
stateRoot,
batch,
}
}
)
this._registerRoute(
'get',
'/batch/stateroot/latest',
async (): Promise<StateRootBatchResponse> => {
const batch = await this.state.db.getLatestStateRootBatch()
if (batch === null) {
return {
batch: null,
stateRoots: [],
}
}
const stateRoots = await this.state.db.getStateRootsByIndexRange(
BigNumber.from(batch.prevTotalElements).toNumber(),
BigNumber.from(batch.prevTotalElements).toNumber() +
BigNumber.from(batch.size).toNumber()
)
return {
batch,
stateRoots,
}
}
)
this._registerRoute(
'get',
'/batch/stateroot/index/:index',
async (req): Promise<StateRootBatchResponse> => {
const batch = await this.state.db.getStateRootBatchByIndex(
BigNumber.from(req.params.index).toNumber()
)
if (batch === null) {
return {
batch: null,
stateRoots: [],
}
}
const stateRoots = await this.state.db.getStateRootsByIndexRange(
BigNumber.from(batch.prevTotalElements).toNumber(),
BigNumber.from(batch.prevTotalElements).toNumber() +
BigNumber.from(batch.size).toNumber()
)
return {
batch,
stateRoots,
}
}
)
}
}