-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathAPI.ts
More file actions
2000 lines (1881 loc) · 66.2 KB
/
API.ts
File metadata and controls
2000 lines (1881 loc) · 66.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
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Signature } from '@shardeum-foundation/lib-crypto-utils'
import { FastifyInstance, FastifyRequest } from 'fastify'
import { Server, IncomingMessage, ServerResponse } from 'http'
import { config, updateConfig, Config as ConfigInterface } from './Config'
import * as Crypto from './Crypto'
import * as State from './State'
import * as NodeList from './NodeList'
import * as P2P from './P2P'
import * as Storage from './archivedCycle/Storage'
import * as Data from './Data/Data'
import * as Cycles from './Data/Cycles'
import * as Utils from './Utils'
import { addHashesGossip } from './archivedCycle/Gossip'
import * as Logger from './Logger'
import { P2P as P2PTypes } from '@shardeum-foundation/lib-types'
import { Readable } from 'stream'
import { nestedCountersInstance } from './profiler/nestedCounters'
import { profilerInstance } from './profiler/profiler'
import * as CycleDB from './dbstore/cycles'
import * as AccountDB from './dbstore/accounts'
import * as TransactionDB from './dbstore/transactions'
import * as ReceiptDB from './dbstore/receipts'
import * as OriginalTxDB from './dbstore/originalTxsData'
import * as Collector from './Data/Collector'
import * as GossipData from './Data/GossipData'
import * as AccountDataProvider from './Data/AccountDataProvider'
import { getGlobalNetworkAccount } from './GlobalAccount'
import { cycleRecordWithShutDownMode } from './Data/Cycles'
import { isDebugMiddleware } from './DebugMode'
import { Utils as StringUtils } from '@shardeum-foundation/lib-types'
import { receivedReceiptCount, verifiedReceiptCount, successReceiptCount, failureReceiptCount } from './primary-process'
import * as ServiceQueue from './ServiceQueue'
import ticketRoutes from './routes/tickets'
import { Cycle } from './dbstore/types'
import { allowedArchiversManager } from './shardeum/allowedArchiversManager'
import { CheckpointBucket, CheckpointRadixEntry, CheckpointType } from './checkpoint/CheckpointData'
import { getCheckpointManager } from './checkpoint/Utils'
import { CheckpointStatusType, isBucketVerified } from './dbstore/checkpointStatus'
import { ArchiverLogging } from './profiler/archiverLogging'
import { checkpointStatusMap, CheckpointStatusResponse } from './checkpoint/CheckpointData'
const { version } = require('../package.json') // eslint-disable-line @typescript-eslint/no-var-requires
const TXID_LENGTH = 64
const {
MAX_CYCLES_PER_REQUEST,
MAX_ORIGINAL_TXS_PER_REQUEST,
MAX_RECEIPTS_PER_REQUEST,
MAX_ACCOUNTS_PER_REQUEST,
MAX_BETWEEN_CYCLES_PER_REQUEST,
} = config.REQUEST_LIMIT
let reachabilityAllowed = true
export function registerRoutes(server: FastifyInstance<Server, IncomingMessage, ServerResponse>): void {
type Request = FastifyRequest<{
Body: {
sender: string
sign: Signature
}
}>
/**
* ENTRY POINT: New Shardus network
*
* Consensus node zero (CZ) posts IP and port to archiver node zero (AZ).
*
* AZ adds CZ to nodelist, sets CZ as dataSender, and responds with
* nodelist + archiver join request
*
* CZ adds AZ's join reqeuest to cycle zero and sets AZ as cycleRecipient
*/
type NodeListRequest = FastifyRequest<{
Body: P2P.FirstNodeInfo & Crypto.SignedMessage
}>
server.get('/myip', function (request, reply) {
const ip = request.raw.socket.remoteAddress
reply.send({ ip })
})
server.post('/nodelist', (request: NodeListRequest, reply) => {
profilerInstance.profileSectionStart('POST_nodelist')
try {
nestedCountersInstance.countEvent('consensor', 'POST_nodelist', 1)
const signedFirstNodeInfo = request.body
ArchiverLogging.logValidatorConnection({
validatorId: signedFirstNodeInfo.nodeInfo.publicKey,
archiverId: config.ARCHIVER_IP,
timestamp: Date.now(),
status: 'CONNECTING',
handshake: {
success: false,
duration: 0,
},
})
if (State.isFirst && NodeList.isEmpty() && !NodeList.foundFirstNode) {
try {
let err = Utils.validateTypes(signedFirstNodeInfo, {
nodeInfo: 'o',
sign: 'o',
})
if (err) {
ArchiverLogging.logValidatorConnection({
validatorId: signedFirstNodeInfo.nodeInfo.publicKey,
archiverId: config.ARCHIVER_IP,
timestamp: Date.now(),
status: 'ERROR',
handshake: {
success: false,
duration: Date.now() - request.raw.socket.remotePort,
error: err,
},
})
reply.send({ success: false, error: err })
return
}
err = Utils.validateTypes(signedFirstNodeInfo.nodeInfo, {
externalIp: 's',
externalPort: 'n',
publicKey: 's',
})
if (err) {
reply.send({ success: false, error: err })
return
}
err = Utils.validateTypes(signedFirstNodeInfo.sign, {
owner: 's',
sig: 's',
})
if (err) {
reply.send({ success: false, error: err })
return
}
if (signedFirstNodeInfo.nodeInfo.publicKey !== signedFirstNodeInfo.sign.owner) {
Logger.mainLogger.error('nodeInfo.publicKey does not match signature owner', signedFirstNodeInfo)
reply.send({ success: false, error: 'nodeInfo.publicKey does not match signature owner' })
return
}
const isSignatureValid = Crypto.verify(signedFirstNodeInfo)
if (!isSignatureValid) {
Logger.mainLogger.error('Invalid signature', signedFirstNodeInfo)
reply.send({ success: false, error: 'Invalid signature' })
return
}
} catch (e) {
Logger.mainLogger.error(e)
reply.send({ success: false, error: 'Signature verification failed' })
return
}
const ip = signedFirstNodeInfo.nodeInfo.externalIp
const port = signedFirstNodeInfo.nodeInfo.externalPort
const publicKey = signedFirstNodeInfo.nodeInfo.publicKey
if (config.restrictFirstNodeSelectionByPublicKey) {
if (publicKey !== config.firstNodePublicKey) {
Logger.mainLogger.error('Invalid publicKey of first node info', signedFirstNodeInfo)
reply.send({ success: false, error: 'Invalid publicKey of first node info' })
return
}
}
if (NodeList.foundFirstNode) {
const res = NodeList.getCachedNodeList()
reply.send(res)
return
}
NodeList.toggleFirstNode()
const firstNode: NodeList.ConsensusNodeInfo = {
ip,
port,
publicKey,
}
Data.initSocketClient(firstNode)
ArchiverLogging.logValidatorConnection({
validatorId: signedFirstNodeInfo.nodeInfo.publicKey,
archiverId: config.ARCHIVER_IP,
timestamp: Date.now(),
status: 'CONNECTED',
handshake: {
success: true,
duration: Date.now() - request.raw.socket.remotePort,
},
})
// Add first node to NodeList
NodeList.addNodes(NodeList.NodeStatus.SYNCING, [firstNode])
// Setting current time for realUpdatedTimes to refresh the nodelist and full-nodelist cache
NodeList.realUpdatedTimes.set('/nodelist', Date.now())
NodeList.realUpdatedTimes.set('/full-nodelist', Date.now())
// Set first node as dataSender
const firstDataSender: Data.DataSender = {
nodeInfo: firstNode,
types: [P2PTypes.SnapshotTypes.TypeNames.CYCLE, P2PTypes.SnapshotTypes.TypeNames.STATE_METADATA],
contactTimeout: Data.createContactTimeout(firstNode.publicKey, 'This timeout is created for the first node'),
}
Data.addDataSender(firstDataSender)
let res: P2P.FirstNodeResponse
if (config.experimentalSnapshot) {
const data = {
nodeList: [firstNode],
}
if (cycleRecordWithShutDownMode) {
// For restore network to start the network from the 'restart' mode
data['restartCycleRecord'] = cycleRecordWithShutDownMode
data['dataRequestCycle'] = cycleRecordWithShutDownMode.counter
} else {
// For new network to start the network from the 'forming' mode
data['joinRequest'] = P2P.createArchiverJoinRequest()
data['dataRequestCycle'] = Cycles.getCurrentCycleCounter()
}
res = Crypto.sign<P2P.FirstNodeResponse>(data)
} else {
res = Crypto.sign<P2P.FirstNodeResponse>({
nodeList: [firstNode],
joinRequest: P2P.createArchiverJoinRequest(),
dataRequestCycle: Data.createDataRequest<P2PTypes.CycleCreatorTypes.CycleRecord>(
P2PTypes.SnapshotTypes.TypeNames.CYCLE,
Cycles.getCurrentCycleCounter(),
publicKey
),
dataRequestStateMetaData: Data.createDataRequest<P2PTypes.SnapshotTypes.StateMetaData>(
P2PTypes.SnapshotTypes.TypeNames.STATE_METADATA,
Cycles.lastProcessedMetaData,
publicKey
),
})
}
reply.send(res)
} else {
// Note, this is doing the same thing as GET /nodelist. However, it has been kept for backwards
// compatibility.
const res = NodeList.getCachedNodeList()
reply.send(res)
}
} finally {
profilerInstance.profileSectionEnd('POST_nodelist')
}
})
server.get('/nodelist', (_request, reply) => {
profilerInstance.profileSectionStart('GET_nodelist')
try {
nestedCountersInstance.countEvent('consensor', 'GET_nodelist')
const res = NodeList.getCachedNodeList()
reply.send(res)
} finally {
profilerInstance.profileSectionEnd('GET_nodelist')
}
})
server.get('/network-txs-list', (_request, reply) => {
profilerInstance.profileSectionStart('GET_network-txs-list')
try {
nestedCountersInstance.countEvent('consensor', 'network-txs-list')
const res = ServiceQueue.getTxList()
reply.send(res)
} finally {
profilerInstance.profileSectionEnd('GET_network-txs-list')
}
})
type FullNodeListRequest = FastifyRequest<{
Querystring: {
activeOnly: 'true' | 'false'
syncingOnly: 'true' | 'false'
standbyOnly: 'true' | 'false'
}
}>
server.get('/full-nodelist', (_request: FullNodeListRequest, reply) => {
profilerInstance.profileSectionStart('FULL_nodelist')
try {
nestedCountersInstance.countEvent('consensor', 'FULL_nodelist')
const query = _request.query
let activeOnly = false
let syncingOnly = false
let standbyOnly = false
if (query.activeOnly === 'true') activeOnly = true
if (query.syncingOnly === 'true') syncingOnly = true
if (query.standbyOnly === 'true') standbyOnly = true
const res = NodeList.getCachedFullNodeList(activeOnly, syncingOnly, standbyOnly)
reply.send(res)
} finally {
profilerInstance.profileSectionEnd('FULL_nodelist')
}
})
server.get(
'/removed',
{
preHandler: async (_request, reply) => {
isDebugMiddleware(_request, reply)
},
},
(_request: FullNodeListRequest, reply) => {
profilerInstance.profileSectionStart('removed')
nestedCountersInstance.countEvent('consensor', 'removed')
reply.send({ removedAndApopedNodes: Cycles.removedAndApopedNodes })
profilerInstance.profileSectionEnd('removed')
}
)
server.get('/archivers', (_request, reply) => {
profilerInstance.profileSectionStart('GET_archivers')
try {
nestedCountersInstance.countEvent('consensor', 'GET_archivers')
const activeArchivers = State.activeArchivers
.filter(
(archiver) =>
State.archiversReputation.has(archiver.publicKey) &&
State.archiversReputation.get(archiver.publicKey) === 'up'
)
.map(({ publicKey, ip, port }) => ({ publicKey, ip, port }))
const res = Crypto.sign({
activeArchivers,
})
reply.send(res)
} finally {
profilerInstance.profileSectionEnd('GET_archivers')
}
})
server.get('/allowed-archivers', async (_request, reply) => {
profilerInstance.profileSectionStart('GET_allowed_archivers')
try {
const config = allowedArchiversManager.getCurrentConfig()
if (!config) {
return reply.status(500).send({
error: 'Internal server error',
})
}
return reply.send(config)
} catch (error) {
Logger.mainLogger.error('Error serving allowed-archivers:', error)
return reply.status(500).send({
error: 'Internal server error',
})
} finally {
profilerInstance.profileSectionEnd('GET_allowed_archivers')
}
})
server.get('/nodeInfo', (request, reply) => {
if (reachabilityAllowed) {
reply.send({
publicKey: config.ARCHIVER_PUBLIC_KEY,
ip: config.ARCHIVER_IP,
port: config.ARCHIVER_PORT,
version,
time: Date.now(),
})
} else {
request.raw.socket.destroy()
}
})
server.get('/checkpoint-status', (_request, reply) => {
profilerInstance.profileSectionStart('GET_checkpoint_status')
try {
// Check if the limit query parameter is provided
const queryLimit =
_request.query && typeof (_request.query as { limit?: string | number }).limit !== 'undefined'
? Number((_request.query as { limit?: string | number }).limit)
: undefined
const maxLimit = Number(config.checkpoint.statusArraySize) || 5000
let limit: number
if (queryLimit === undefined || isNaN(queryLimit)) {
limit = Number(config.checkpoint.statusApiLimit) || 100
} else if (queryLimit > 0 && queryLimit <= maxLimit) {
limit = queryLimit
} else {
reply.send({
success: false,
error: `Invalid limit: must be > 0 and <= ${maxLimit}`,
})
return
}
const latestEntries = checkpointStatusMap.getLatestCycles(limit)
if (latestEntries.length === 0) {
reply.send({
success: false,
error: 'No checkpoint statuses found',
})
return
}
const entries: CheckpointStatusResponse = {}
for (const [cycle, hashes] of latestEntries) {
entries[cycle] = {
cycleHash: hashes.cycleHash!,
receiptHash: hashes.receiptHash!,
originalTxHash: hashes.originalTxHash!,
}
}
reply.send({
success: true,
data: entries,
})
} catch (error) {
Logger.mainLogger.error('Error serving checkpoint-status:', error)
reply.send({
success: false,
error: 'Internal server error',
})
} finally {
profilerInstance.profileSectionEnd('GET_checkpoint_status')
}
})
type CycleInfoRequest = FastifyRequest<{
Body: {
start: number
end: number
count: number
download: boolean
}
}>
server.post('/cycleinfo', async (_request: CycleInfoRequest & Request, reply) => {
profilerInstance.profileSectionStart('POST_cycleinfo')
try {
const requestData = _request.body
const result = validateRequestData(
requestData,
{
start: 'n?',
end: 'n?',
count: 'n?',
download: 'b?',
sender: 's',
sign: 'o',
},
true
)
if (!result.success) {
reply.send(Crypto.sign({ success: false, error: result.error }))
return
}
const { start, end, count, download } = _request.body
if (download !== undefined && typeof download !== 'boolean') {
reply.send(Crypto.sign({ success: false, error: `Invalid download flag` }))
return
}
const isDownload: boolean = download === true
let cycleInfo = []
if (count) {
if (count <= 0 || Number.isNaN(count)) {
reply.send(Crypto.sign({ success: false, error: `Invalid count` }))
return
}
if (count > MAX_CYCLES_PER_REQUEST) {
reply.send(Crypto.sign({ success: false, error: `Max count is ${MAX_CYCLES_PER_REQUEST}.` }))
return
}
cycleInfo = await CycleDB.queryLatestCycleRecords(count)
} else if (start || start === 0) {
const from = start
const to = end ? end : from
if (!(from >= 0 && to >= from) || Number.isNaN(from) || Number.isNaN(to)) {
Logger.mainLogger.error(`Invalid start and end counters`)
reply.send(Crypto.sign({ success: false, error: `Invalid start and end counters` }))
return
}
const cycleCount = to - from
if (cycleCount > MAX_CYCLES_PER_REQUEST) {
Logger.mainLogger.error(`Exceed maximum limit of ${MAX_CYCLES_PER_REQUEST} cycles`)
reply.send(Crypto.sign({ success: false, error: `Exceed maximum limit of ${MAX_CYCLES_PER_REQUEST} cycles` }))
return
}
cycleInfo = await CycleDB.queryCycleRecordsBetween(from, to)
if (isDownload) {
const dataInBuffer = Buffer.from(StringUtils.safeStringify(cycleInfo), 'utf-8')
const dataInStream = Readable.from(dataInBuffer)
const filename = `cycle_records_from_${from}_to_${to}`
reply.headers({
'content-disposition': `attachment; filename="${filename}"`,
'content-type': 'application/octet-stream',
})
reply.send(dataInStream)
return
}
} else {
reply.send(
Crypto.sign({
success: false,
error: 'not specified which cycle to show',
})
)
return
}
const res = Crypto.sign({
cycleInfo,
})
reply.send(res)
} finally {
profilerInstance.profileSectionEnd('POST_cycleinfo')
}
})
type CycleInfoCountRequest = FastifyRequest<{
Params: { count: string }
}>
server.get('/cycleinfo/:count', async (_request: CycleInfoCountRequest, reply) => {
profilerInstance.profileSectionStart('GET_cycleinfo')
try {
const err = Utils.validateTypes(_request.params, { count: 's' })
if (err) {
reply.send({ success: false, error: err })
return
}
let count: number = parseInt(_request.params.count)
if (count <= 0 || Number.isNaN(count)) {
reply.send({ success: false, error: `Invalid count` })
return
}
if (count > MAX_CYCLES_PER_REQUEST) count = MAX_CYCLES_PER_REQUEST
const res = await Cycles.getLatestCycleRecords(count)
reply.send(res)
} finally {
profilerInstance.profileSectionEnd('GET_cycleinfo')
}
})
type ReceiptRequest = FastifyRequest<{
Body: {
count: number
start: number
end: number
startCycle: number
endCycle: number
type: string
page: number
txId: string
txIdList: string[]
}
}>
server.post('/originalTx', async (_request: ReceiptRequest & Request, reply) => {
profilerInstance.profileSectionStart('POST_originalTx')
try {
const requestData = _request.body
const result = validateRequestData(requestData, {
count: 'n?',
start: 'n?',
end: 'n?',
startCycle: 'n?',
endCycle: 'n?',
type: 's?',
page: 'n?',
txId: 's?',
txIdList: 'a?',
sender: 's',
sign: 'o',
})
if (!result.success) {
reply.send(Crypto.sign({ success: false, error: result.error }))
return
}
const { count, start, end, startCycle, endCycle, type, page, txId, txIdList } = _request.body
let originalTxs: (OriginalTxDB.OriginalTxData | OriginalTxDB.OriginalTxDataCount)[] | number = []
if (count) {
if (count <= 0 || Number.isNaN(count)) {
reply.send(Crypto.sign({ success: false, error: `Invalid count` }))
return
}
if (count > MAX_ORIGINAL_TXS_PER_REQUEST) {
reply.send(Crypto.sign({ success: false, error: `Max count is ${MAX_ORIGINAL_TXS_PER_REQUEST}` }))
return
}
originalTxs = await OriginalTxDB.queryLatestOriginalTxs(count)
} else if (txId) {
if (txId.length !== TXID_LENGTH) {
reply.send(
Crypto.sign({
success: false,
error: `Invalid txId ${txId}`,
})
)
return
}
const originalTx = await OriginalTxDB.queryOriginalTxDataByTxId(txId)
if (originalTx) originalTxs.push(originalTx)
} else if (txIdList) {
if (txIdList.length > MAX_ORIGINAL_TXS_PER_REQUEST) {
reply.send(
Crypto.sign({
success: false,
error: `Exceed maximum limit of ${MAX_ORIGINAL_TXS_PER_REQUEST} original transactions`,
})
)
return
}
for (const [txId, txTimestamp] of txIdList) {
if (typeof txId !== 'string' || txId.length !== TXID_LENGTH || typeof txTimestamp !== 'number') {
reply.send(
Crypto.sign({
success: false,
error: `Invalid txId ${txId} in the List`,
})
)
return
}
const originalTx = await OriginalTxDB.queryOriginalTxDataByTxId(txId, txTimestamp)
if (originalTx) originalTxs.push(originalTx)
}
} else if (start || start === 0) {
const from = start
const to = end ? end : from
if (!(from >= 0 && to >= from) || Number.isNaN(from) || Number.isNaN(to)) {
reply.send(
Crypto.sign({
success: false,
error: `Invalid start and end counters`,
})
)
return
}
const count = to - from
if (count > MAX_ORIGINAL_TXS_PER_REQUEST) {
reply.send(
Crypto.sign({
success: false,
error: `Exceed maximum limit of ${MAX_ORIGINAL_TXS_PER_REQUEST} original transactions`,
})
)
return
}
originalTxs = await OriginalTxDB.queryOriginalTxsData(from, count + 1)
} else if (startCycle || startCycle === 0) {
const from = startCycle
const to = endCycle ? endCycle : from
if (!(from >= 0 && to >= from) || Number.isNaN(from) || Number.isNaN(to)) {
reply.send(
Crypto.sign({
success: false,
error: `Invalid startCycle and endCycle counters`,
})
)
return
}
const count = to - from
if (count > MAX_BETWEEN_CYCLES_PER_REQUEST) {
reply.send(
Crypto.sign({
success: false,
error: `Exceed maximum limit of ${MAX_BETWEEN_CYCLES_PER_REQUEST} cycles`,
})
)
return
}
if (type === 'tally') {
originalTxs = await OriginalTxDB.queryOriginalTxDataCountByCycles(from, to)
} else if (type === 'count') {
originalTxs = await OriginalTxDB.queryOriginalTxDataCount(from, to)
} else {
let skip = 0
const limit = MAX_ORIGINAL_TXS_PER_REQUEST
if (page) {
if (page < 1 || Number.isNaN(page)) {
reply.send(Crypto.sign({ success: false, error: `Invalid page number` }))
return
}
skip = page - 1
if (skip > 0) skip = skip * limit
}
originalTxs = await OriginalTxDB.queryOriginalTxsData(skip, limit, from, to)
}
}
const res = Crypto.sign({
originalTxs,
})
reply.send(res)
} finally {
profilerInstance.profileSectionEnd('POST_originalTx')
}
})
server.post('/receipt', async (_request: ReceiptRequest & Request, reply) => {
profilerInstance.profileSectionStart('POST_receipt')
try {
const requestData = _request.body
const result = validateRequestData(requestData, {
count: 'n?',
start: 'n?',
end: 'n?',
startCycle: 'n?',
endCycle: 'n?',
type: 's?',
page: 'n?',
txId: 's?',
txIdList: 'a?',
sender: 's',
sign: 'o',
})
if (!result.success) {
reply.send(Crypto.sign({ success: false, error: result.error }))
return
}
const { count, start, end, startCycle, endCycle, type, page, txId, txIdList } = _request.body
let receipts: (ReceiptDB.Receipt | ReceiptDB.ReceiptCount)[] | number = []
if (count) {
if (count <= 0 || Number.isNaN(count)) {
reply.send(Crypto.sign({ success: false, error: `Invalid count` }))
return
}
if (count > MAX_RECEIPTS_PER_REQUEST) {
reply.send(Crypto.sign({ success: false, error: `Max count is ${MAX_RECEIPTS_PER_REQUEST}` }))
return
}
receipts = await ReceiptDB.queryLatestReceipts(count)
} else if (txId) {
if (txId.length !== TXID_LENGTH) {
reply.send(
Crypto.sign({
success: false,
error: `Invalid txId ${txId}`,
})
)
return
}
const receipt = await ReceiptDB.queryReceiptByReceiptId(txId)
if (receipt) receipts.push(receipt)
} else if (txIdList) {
if (txIdList.length > MAX_RECEIPTS_PER_REQUEST) {
reply.send(
Crypto.sign({
success: false,
error: `Exceed maximum limit of ${MAX_RECEIPTS_PER_REQUEST} receipts`,
})
)
return
}
for (const [txId, txTimestamp] of txIdList) {
if (typeof txId !== 'string' || txId.length !== TXID_LENGTH || typeof txTimestamp !== 'number') {
reply.send(
Crypto.sign({
success: false,
error: `Invalid txId ${txId} in the List`,
})
)
return
}
const receipt = await ReceiptDB.queryReceiptByReceiptId(txId, txTimestamp)
if (receipt) receipts.push(receipt)
}
} else if (start || start === 0) {
const from = start
const to = end ? end : from
if (!(from >= 0 && to >= from) || Number.isNaN(from) || Number.isNaN(to)) {
reply.send(
Crypto.sign({
success: false,
error: `Invalid start and end counters`,
})
)
return
}
const count = to - from
if (count > MAX_RECEIPTS_PER_REQUEST) {
reply.send(
Crypto.sign({
success: false,
error: `Exceed maximum limit of ${MAX_RECEIPTS_PER_REQUEST} receipts`,
})
)
return
}
receipts = await ReceiptDB.queryReceipts(from, count + 1)
} else if (startCycle || startCycle === 0) {
const from = startCycle
const to = endCycle ? endCycle : from
if (!(from >= 0 && to >= from) || Number.isNaN(from) || Number.isNaN(to)) {
reply.send(
Crypto.sign({
success: false,
error: `Invalid startCycle and endCycle counters`,
})
)
return
}
const count = to - from
if (count > MAX_BETWEEN_CYCLES_PER_REQUEST) {
reply.send(
Crypto.sign({
success: false,
error: `Exceed maximum limit of ${MAX_BETWEEN_CYCLES_PER_REQUEST} cycles`,
})
)
return
}
if (type === 'tally') {
receipts = await ReceiptDB.queryReceiptCountByCycles(from, to)
} else if (type === 'count') {
receipts = await ReceiptDB.queryReceiptCountBetweenCycles(from, to)
} else {
let skip = 0
const limit = MAX_RECEIPTS_PER_REQUEST
if (page) {
if (page < 1 || Number.isNaN(page)) {
reply.send(Crypto.sign({ success: false, error: `Invalid page number` }))
return
}
skip = page - 1
if (skip > 0) skip = skip * limit
}
receipts = await ReceiptDB.queryReceiptsBetweenCycles(skip, limit, from, to)
}
}
const res = Crypto.sign({
receipts,
})
reply.send(res)
} finally {
profilerInstance.profileSectionEnd('POST_receipt')
}
})
type AccountRequest = FastifyRequest<{
Body: {
count: number
start: number
end: number
startCycle: number
endCycle: number
page: number
accountId: string
}
}>
server.post('/account', async (_request: AccountRequest & Request, reply) => {
profilerInstance.profileSectionStart('POST_account')
try {
const requestData = _request.body
const result = validateRequestData(requestData, {
count: 'n?',
start: 'n?',
end: 'n?',
startCycle: 'n?',
endCycle: 'n?',
page: 'n?',
accountId: 's?',
sender: 's',
sign: 'o',
})
if (!result.success) {
reply.send(Crypto.sign({ success: false, error: result.error }))
return
}
let accounts: AccountDB.AccountsCopy | AccountDB.AccountsCopy[] | number = []
let totalAccounts = 0
let res
const { count, start, end, startCycle, endCycle, page, accountId } = _request.body
if (count) {
if (count <= 0 || Number.isNaN(count)) {
reply.send(Crypto.sign({ success: false, error: `Invalid count` }))
return
}
if (count > MAX_ACCOUNTS_PER_REQUEST) {
reply.send(Crypto.sign({ success: false, error: `Max count is ${MAX_ACCOUNTS_PER_REQUEST}` }))
return
}
accounts = await AccountDB.queryLatestAccounts(count)
res = { accounts }
} else if (start || start === 0) {
const from = start
const to = end ? end : from
if (!(from >= 0 && to >= from) || Number.isNaN(from) || Number.isNaN(to)) {
reply.send(
Crypto.sign({
success: false,
error: `Invalid start and end counters`,
})
)
return
}
const count = to - from
if (count > MAX_ACCOUNTS_PER_REQUEST) {
reply.send(
Crypto.sign({
success: false,
error: `Exceed maximum limit of ${MAX_ACCOUNTS_PER_REQUEST} accounts`,
})
)
return
}
accounts = await AccountDB.queryAccounts(from, count + 1)
res = { accounts }
} else if (startCycle || startCycle === 0) {
const from = startCycle
const to = endCycle ? endCycle : from
if (!(from >= 0 && to >= from) || Number.isNaN(from) || Number.isNaN(to)) {
reply.send(
Crypto.sign({
success: false,
error: `Invalid startCycle and endCycle counters`,
})
)
return
}
const count = to - from
if (count > MAX_BETWEEN_CYCLES_PER_REQUEST) {
reply.send(
Crypto.sign({
success: false,
error: `Exceed maximum limit of ${MAX_BETWEEN_CYCLES_PER_REQUEST} cycles to query accounts Count`,
})
)
return
}
totalAccounts = await AccountDB.queryAccountCountBetweenCycles(from, to)
if (page) {
if (page < 1 || Number.isNaN(page)) {
reply.send(Crypto.sign({ success: false, error: `Invalid page number` }))
return
}
let skip = page - 1
const limit = MAX_ACCOUNTS_PER_REQUEST
if (skip > 0) skip = skip * limit
accounts = await AccountDB.queryAccountsBetweenCycles(skip, limit, from, to)
res = { accounts, totalAccounts }
} else {
res = { totalAccounts }
}
} else if (accountId) {
accounts = await AccountDB.queryAccountByAccountId(accountId)
res = { accounts }
} else {
reply.send(
Crypto.sign({
success: false,
error: 'not specified which account to show',
})
)
return
}
reply.send(Crypto.sign(res))
} finally {
profilerInstance.profileSectionEnd('POST_account')
}
})
type TransactionRequest = FastifyRequest<{
Body: {
count: number
start: number
end: number
startCycle: number
endCycle: number
txId: string
page: number
appReceiptId: string
}
}>
server.post('/transaction', async (_request: TransactionRequest & Request, reply) => {
profilerInstance.profileSectionStart('POST_transaction')
try {
const requestData = _request.body
const result = validateRequestData(requestData, {
count: 'n?',
start: 'n?',
end: 'n?',
txId: 's?',
appReceiptId: 's?',
startCycle: 'n?',
endCycle: 'n?',
page: 'n?',
sender: 's',
sign: 'o',
})
if (!result.success) {
reply.send(Crypto.sign({ success: false, error: result.error }))
return
}
const { count, start, end, txId, appReceiptId, startCycle, endCycle, page } = _request.body
let transactions: TransactionDB.Transaction | TransactionDB.Transaction[] = []
let totalTransactions = 0
let res
if (count) {
if (count <= 0 || Number.isNaN(count)) {
reply.send(Crypto.sign({ success: false, error: `Invalid count` }))
return
}
if (count > MAX_ACCOUNTS_PER_REQUEST) {
reply.send(Crypto.sign({ success: false, error: `Max count is ${MAX_ACCOUNTS_PER_REQUEST}` }))
return
}