-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathAPI.test.ts
More file actions
2917 lines (2429 loc) · 93.3 KB
/
API.test.ts
File metadata and controls
2917 lines (2429 loc) · 93.3 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 { describe, expect, it, beforeEach, afterEach, jest } from '@jest/globals'
import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify'
import { Signature } from '@shardeum-foundation/lib-crypto-utils'
// Mock all dependencies before importing the module
jest.mock('../../../src/Config', () => ({
config: {
ARCHIVER_IP: '127.0.0.1',
ARCHIVER_PORT: 4000,
ARCHIVER_PUBLIC_KEY: 'test-public-key',
ARCHIVER_SECRET_KEY: 'test-secret-key',
VERBOSE: false,
limitToArchiversOnly: false,
DevPublicKey: 'dev-public-key',
experimentalSnapshot: false,
restrictFirstNodeSelectionByPublicKey: false,
firstNodePublicKey: 'first-node-public-key',
maxRecordsPerRequest: 1000,
REQUEST_LIMIT: {
MAX_CYCLES_PER_REQUEST: 100,
MAX_ORIGINAL_TXS_PER_REQUEST: 1000,
MAX_RECEIPTS_PER_REQUEST: 1000,
MAX_ACCOUNTS_PER_REQUEST: 1000,
MAX_BETWEEN_CYCLES_PER_REQUEST: 100,
},
checkpoint: {
bucketConfig: {
allowCheckpointUpdates: false,
},
statusApiLimit: 100,
statusArraySize: 5000,
},
},
updateConfig: jest.fn(),
}))
jest.mock('../../../src/Crypto', () => ({
sign: jest.fn((data: any) => ({ ...data, sign: { owner: 'test-owner', sig: 'test-sig' } })),
verify: jest.fn(() => true),
}))
jest.mock('../../../src/State', () => ({
isFirst: false,
isActive: true,
activeArchivers: [],
archiversReputation: new Map(),
otherArchivers: [],
}))
jest.mock('../../../src/NodeList', () => ({
isEmpty: jest.fn(() => true),
foundFirstNode: false,
toggleFirstNode: jest.fn(),
addNodes: jest.fn(),
getCachedNodeList: jest.fn(() => ({ nodeList: [] })),
getCachedFullNodeList: jest.fn(() => ({ nodeList: [] })),
realUpdatedTimes: new Map(),
NodeStatus: {
SYNCING: 'syncing',
},
}))
jest.mock('../../../src/P2P', () => ({
createArchiverJoinRequest: jest.fn(() => ({ publicKey: 'test-public-key' })),
postJson: jest.fn(() => Promise.resolve(null)),
}))
jest.mock('../../../src/archivedCycle/Storage')
jest.mock('../../../src/Data/Data', () => ({
initSocketClient: jest.fn(),
createContactTimeout: jest.fn(),
addDataSender: jest.fn(),
createDataRequest: jest.fn(),
dataSenders: new Map(),
socketClients: new Map(),
sendLeaveRequest: jest.fn(),
}))
jest.mock('../../../src/Data/Cycles', () => ({
getCurrentCycleCounter: jest.fn(() => 0),
lastProcessedMetaData: {},
removedAndApopedNodes: [],
getLatestCycleRecords: jest.fn(),
}))
jest.mock('../../../src/Utils', () => ({
validateTypes: jest.fn(() => null),
getRandomItemFromArr: jest.fn(() => []),
}))
jest.mock('../../../src/archivedCycle/Gossip')
jest.mock('../../../src/Logger', () => ({
mainLogger: {
error: jest.fn(),
info: jest.fn(),
debug: jest.fn(),
warn: jest.fn(),
},
}))
jest.mock('../../../src/profiler/nestedCounters', () => ({
nestedCountersInstance: {
countEvent: jest.fn(),
},
}))
jest.mock('../../../src/profiler/profiler', () => ({
profilerInstance: {
profileSectionStart: jest.fn(),
profileSectionEnd: jest.fn(),
},
}))
jest.mock('../../../src/dbstore/cycles', () => ({
queryLatestCycleRecords: jest.fn(() => []),
queryCycleRecordsBetween: jest.fn(() => []),
queryCyleCount: jest.fn(() => 0),
}))
jest.mock('../../../src/dbstore/accounts', () => ({
queryLatestAccounts: jest.fn(() => []),
queryAccounts: jest.fn(() => []),
queryAccountCountBetweenCycles: jest.fn(() => 0),
queryAccountsBetweenCycles: jest.fn(() => []),
queryAccountByAccountId: jest.fn(() => null),
queryAccountCount: jest.fn(() => 0),
}))
jest.mock('../../../src/dbstore/transactions', () => ({
queryLatestTransactions: jest.fn(() => []),
queryTransactions: jest.fn(() => []),
queryTransactionCountBetweenCycles: jest.fn(() => 0),
queryTransactionsBetweenCycles: jest.fn(() => []),
queryTransactionByTxId: jest.fn(() => null),
queryTransactionByAccountId: jest.fn(() => null),
queryTransactionCount: jest.fn(() => 0),
}))
jest.mock('../../../src/dbstore/receipts', () => ({
queryLatestReceipts: jest.fn(() => []),
queryReceiptByReceiptId: jest.fn(() => null),
queryReceipts: jest.fn(() => []),
queryReceiptCountByCycles: jest.fn(() => []),
queryReceiptCountBetweenCycles: jest.fn(() => 0),
queryReceiptsBetweenCycles: jest.fn(() => []),
queryReceiptCount: jest.fn(() => 0),
}))
jest.mock('../../../src/dbstore/originalTxsData', () => ({
queryLatestOriginalTxs: jest.fn(() => []),
queryOriginalTxDataByTxId: jest.fn(() => null),
queryOriginalTxsData: jest.fn(() => []),
queryOriginalTxDataCountByCycles: jest.fn(() => []),
queryOriginalTxDataCount: jest.fn(() => 0),
}))
jest.mock('../../../src/Data/Collector')
jest.mock('../../../src/Data/GossipData')
jest.mock('../../../src/Data/AccountDataProvider')
jest.mock('../../../src/GlobalAccount', () => ({
getGlobalNetworkAccount: jest.fn(() => 'mock-network-account-hash'),
}))
jest.mock('../../../src/DebugMode', () => ({
isDebugMiddleware: jest.fn((req, reply) => {}),
}))
jest.mock('../../../src/primary-process', () => ({
receivedReceiptCount: 100,
verifiedReceiptCount: 80,
successReceiptCount: 70,
failureReceiptCount: 10,
}))
jest.mock('../../../src/ServiceQueue', () => ({
getTxList: jest.fn(() => []),
}))
jest.mock('../../../src/routes/tickets', () => ({
default: jest.fn((fastify: any, opts: any, done: any) => done()),
}))
jest.mock('../../../src/shardeum/allowedArchiversManager', () => ({
allowedArchiversManager: {
getCurrentConfig: jest.fn(() => ({ allowedArchivers: [] })),
isArchiverAllowed: jest.fn(() => true),
},
}))
jest.mock('../../../src/checkpoint/CheckpointData', () => {
const actualMap = new Map()
const mockStatusMap = {
entries: jest.fn(() => Array.from(actualMap.entries())),
set: jest.fn((key, value) => actualMap.set(key, value)),
getLatestCycles: jest.fn(() => []),
_getActualMap: () => actualMap, // For test access
}
return {
checkpointStatusMap: mockStatusMap,
CheckpointBucket: jest.fn(),
CheckpointType: {
Cycle: 0,
OriginalTx: 1,
Receipt: 2,
},
CheckpointData: class MockCheckpointData {},
}
})
jest.mock('../../../src/checkpoint/Utils', () => ({
getCheckpointManager: jest.fn(),
}))
jest.mock('../../../src/dbstore/checkpointStatus', () => ({
isBucketVerified: jest.fn(() => Promise.resolve(false)),
CheckpointStatusType: {
CYCLE: 0,
RECEIPT: 1,
ORIGINAL_TX: 2,
},
}))
jest.mock('../../../src/profiler/archiverLogging', () => ({
ArchiverLogging: {
logValidatorConnection: jest.fn(),
},
}))
// Import the functions to test after all mocks are set up
import { registerRoutes, validateRequestData, RequestDataType, queryFromArchivers } from '../../../src/API'
import * as Crypto from '../../../src/Crypto'
import * as State from '../../../src/State'
import * as NodeList from '../../../src/NodeList'
import * as Utils from '../../../src/Utils'
import * as P2P from '../../../src/P2P'
import { config } from '../../../src/Config'
import * as Cycles from '../../../src/Data/Cycles'
import { allowedArchiversManager } from '../../../src/shardeum/allowedArchiversManager'
import { getGlobalNetworkAccount } from '../../../src/GlobalAccount'
import * as Data from '../../../src/Data/Data'
import { isBucketVerified } from '../../../src/dbstore/checkpointStatus'
import { getCheckpointManager } from '../../../src/checkpoint/Utils'
import { checkpointStatusMap, CheckpointBucket, BucketHashes } from '../../../src/checkpoint/CheckpointData'
describe('API', () => {
let mockFastify: FastifyInstance
let mockRequest: FastifyRequest
let mockReply: FastifyReply
let registeredRoutes: Map<string, Map<string, Function>>
beforeEach(() => {
// Initialize route registry
registeredRoutes = new Map()
registeredRoutes.set('GET', new Map())
registeredRoutes.set('POST', new Map())
registeredRoutes.set('PATCH', new Map())
// Setup mock reply
mockReply = {
status: jest.fn().mockReturnThis(),
send: jest.fn().mockReturnThis(),
headers: jest.fn().mockReturnThis(),
code: jest.fn().mockReturnThis(),
} as unknown as FastifyReply
// Setup mock request
mockRequest = {
raw: {
socket: {
remoteAddress: '192.168.1.1',
remotePort: 12345,
destroy: jest.fn(),
},
},
query: {},
params: {},
body: {},
} as unknown as FastifyRequest
// Setup mock fastify instance
mockFastify = {
get: jest.fn((path: string, ...args: any[]) => {
const handler = args[args.length - 1]
const getRoutes = registeredRoutes.get('GET') || new Map()
getRoutes.set(path, handler)
registeredRoutes.set('GET', getRoutes)
}),
post: jest.fn((path: string, ...args: any[]) => {
const handler = args[args.length - 1]
const postRoutes = registeredRoutes.get('POST') || new Map()
postRoutes.set(path, handler)
registeredRoutes.set('POST', postRoutes)
}),
patch: jest.fn((path: string, ...args: any[]) => {
const handler = args[args.length - 1]
const patchRoutes = registeredRoutes.get('PATCH') || new Map()
patchRoutes.set(path, handler)
registeredRoutes.set('PATCH', patchRoutes)
}),
register: jest.fn(),
} as unknown as FastifyInstance
jest.clearAllMocks()
})
afterEach(() => {
jest.clearAllMocks()
})
describe('registerRoutes', () => {
it('should register all routes', () => {
registerRoutes(mockFastify)
// Check that routes are registered
expect(mockFastify.get).toHaveBeenCalled()
expect(mockFastify.post).toHaveBeenCalled()
expect(mockFastify.patch).toHaveBeenCalled()
expect(mockFastify.register).toHaveBeenCalled()
})
})
describe('GET /myip', () => {
let handler: Function
beforeEach(() => {
registerRoutes(mockFastify)
handler = registeredRoutes.get('GET')?.get('/myip')!
})
it('should return the client IP address', () => {
handler(mockRequest, mockReply)
expect(mockReply.send).toHaveBeenCalledWith({ ip: '192.168.1.1' })
})
it('should handle IPv6 addresses', () => {
const ipv6Request = {
...mockRequest,
raw: {
socket: {
remoteAddress: '::1',
remotePort: 12345,
destroy: jest.fn(),
},
},
} as unknown as FastifyRequest
handler(ipv6Request, mockReply)
expect(mockReply.send).toHaveBeenCalledWith({ ip: '::1' })
})
})
describe('GET /nodeInfo', () => {
let handler: Function
beforeEach(() => {
registerRoutes(mockFastify)
handler = registeredRoutes.get('GET')?.get('/nodeInfo')!
})
it('should return node information when reachability is allowed', () => {
const mockDate = 1234567890
jest.spyOn(Date, 'now').mockReturnValue(mockDate)
handler(mockRequest, mockReply)
expect(mockReply.send).toHaveBeenCalledWith({
publicKey: 'test-public-key',
ip: '127.0.0.1',
port: 4000,
version: expect.any(String),
time: mockDate,
})
})
})
describe('GET /status', () => {
let handler: Function
beforeEach(() => {
registerRoutes(mockFastify)
handler = registeredRoutes.get('GET')?.get('/status')!
})
it('should return signed status with isActive', async () => {
;(State as any).isActive = true
;(Crypto.sign as jest.Mock).mockReturnValue({
status: { isActive: true },
sign: { owner: 'test-owner', sig: 'test-sig' },
})
await handler(mockRequest, mockReply)
expect(Crypto.sign).toHaveBeenCalledWith({
status: { isActive: true },
})
expect(mockReply.send).toHaveBeenCalledWith({
status: { isActive: true },
sign: { owner: 'test-owner', sig: 'test-sig' },
})
})
})
describe('GET /archivers', () => {
let handler: Function
beforeEach(() => {
registerRoutes(mockFastify)
handler = registeredRoutes.get('GET')?.get('/archivers')!
})
it('should return active archivers with "up" reputation', () => {
;(State as any).activeArchivers = [
{ publicKey: 'archiver1', ip: '10.0.0.1', port: 4000 },
{ publicKey: 'archiver2', ip: '10.0.0.2', port: 4000 },
{ publicKey: 'archiver3', ip: '10.0.0.3', port: 4000 },
]
;(State as any).archiversReputation = new Map([
['archiver1', 'up'],
['archiver2', 'up'],
['archiver3', 'down'],
])
handler(mockRequest, mockReply)
expect(Crypto.sign).toHaveBeenCalledWith({
activeArchivers: [
{ publicKey: 'archiver1', ip: '10.0.0.1', port: 4000 },
{ publicKey: 'archiver2', ip: '10.0.0.2', port: 4000 },
],
})
})
it('should return empty array when no archivers are up', () => {
;(State as any).activeArchivers = [{ publicKey: 'archiver1', ip: '10.0.0.1', port: 4000 }]
;(State as any).archiversReputation = new Map([['archiver1', 'down']])
handler(mockRequest, mockReply)
expect(Crypto.sign).toHaveBeenCalledWith({
activeArchivers: [],
})
})
})
describe('validateRequestData', () => {
beforeEach(() => {
;(Utils.validateTypes as jest.Mock).mockReturnValue(null)
;(Crypto.verify as jest.Mock).mockReturnValue(true)
})
it('should validate request data successfully', () => {
const data = {
sender: 'test-sender',
sign: { owner: 'test-sender', sig: 'test-sig' },
someData: 'test',
}
const result = validateRequestData(data, { sender: 's', sign: 'o', someData: 's' })
expect(result).toEqual({ success: true })
expect(Utils.validateTypes).toHaveBeenCalledWith(data, { sender: 's', sign: 'o', someData: 's' })
expect(Crypto.verify).toHaveBeenCalledWith(data)
})
it('should fail when data types are invalid', () => {
;(Utils.validateTypes as jest.Mock).mockReturnValue('Invalid type')
const data = {
sender: 'test-sender',
sign: { owner: 'test-sender', sig: 'test-sig' },
}
const result = validateRequestData(data, { sender: 's', sign: 'o' })
expect(result).toEqual({ success: false, error: 'Invalid request data Invalid type' })
})
it('should fail when sender and sign owner do not match', () => {
const data = {
sender: 'test-sender',
sign: { owner: 'different-owner', sig: 'test-sig' },
}
const result = validateRequestData(data, { sender: 's', sign: 'o' })
expect(result).toEqual({ success: false, error: 'Data sender publicKey and sign owner key does not match' })
})
it('should fail when signature is invalid', () => {
;(Crypto.verify as jest.Mock).mockReturnValue(false)
const data = {
sender: 'test-sender',
sign: { owner: 'test-sender', sig: 'test-sig' },
}
const result = validateRequestData(data, { sender: 's', sign: 'o' })
expect(result).toEqual({ success: false, error: 'Invalid signature' })
})
it('should check allowed archivers when limitToArchiversOnly is true', () => {
;(config as any).limitToArchiversOnly = true
;(allowedArchiversManager.isArchiverAllowed as jest.Mock).mockReturnValue(false)
;(State as any).activeArchivers = []
const data = {
sender: 'test-sender',
sign: { owner: 'test-sender', sig: 'test-sig' },
}
const result = validateRequestData(data, { sender: 's', sign: 'o' })
expect(result).toEqual({ success: false, error: 'Data request sender is not an authorized archiver' })
expect(allowedArchiversManager.isArchiverAllowed).toHaveBeenCalledWith('test-sender')
// Reset
;(config as any).limitToArchiversOnly = false
})
it('should allow DevPublicKey even when not in allowed archivers', () => {
;(config as any).limitToArchiversOnly = true
;(config as any).DevPublicKey = 'dev-sender'
;(allowedArchiversManager.isArchiverAllowed as jest.Mock).mockReturnValue(false)
const data = {
sender: 'dev-sender',
sign: { owner: 'dev-sender', sig: 'test-sig' },
}
const result = validateRequestData(data, { sender: 's', sign: 'o' })
expect(result).toEqual({ success: true })
// Reset
;(config as any).limitToArchiversOnly = false
;(config as any).DevPublicKey = 'dev-public-key'
})
it('should skip archiver check when skipArchiverCheck is true', () => {
;(config as any).limitToArchiversOnly = true
;(allowedArchiversManager.isArchiverAllowed as jest.Mock).mockReturnValue(false)
const data = {
sender: 'test-sender',
sign: { owner: 'test-sender', sig: 'test-sig' },
}
const result = validateRequestData(data, { sender: 's', sign: 'o' }, true)
expect(result).toEqual({ success: true })
expect(allowedArchiversManager.isArchiverAllowed).not.toHaveBeenCalled()
// Reset
;(config as any).limitToArchiversOnly = false
})
})
describe('GET /config', () => {
let handler: Function
beforeEach(() => {
registerRoutes(mockFastify)
// Find the handler with preHandler
const calls = (mockFastify.get as jest.Mock).mock.calls
const configCall = calls.find((call) => call[0] === '/config')
if (configCall) {
handler = configCall[configCall.length - 1] as Function
}
})
it('should return config without secret key', () => {
handler(mockRequest, mockReply)
expect(mockReply.send).toHaveBeenCalledWith(
expect.objectContaining({
ARCHIVER_IP: '127.0.0.1',
ARCHIVER_PORT: 4000,
ARCHIVER_PUBLIC_KEY: 'test-public-key',
ARCHIVER_SECRET_KEY: '',
VERBOSE: false,
})
)
})
it('should always return empty string for ARCHIVER_SECRET_KEY', () => {
;(config as any).ARCHIVER_SECRET_KEY = 'super-secret-key'
handler(mockRequest, mockReply)
const sentConfig = (mockReply.send as jest.Mock).mock.calls[0][0] as any
expect(sentConfig.ARCHIVER_SECRET_KEY).toBe('')
// Reset
;(config as any).ARCHIVER_SECRET_KEY = 'test-secret-key'
})
})
describe('GET /nodelist', () => {
let handler: Function
beforeEach(() => {
registerRoutes(mockFastify)
handler = registeredRoutes.get('GET')?.get('/nodelist')!
})
it('should return cached node list', () => {
const mockNodeList = {
nodeList: [
{ ip: '10.0.0.1', port: 9001, publicKey: 'node1' },
{ ip: '10.0.0.2', port: 9002, publicKey: 'node2' },
],
}
;(NodeList.getCachedNodeList as jest.Mock).mockReturnValue(mockNodeList)
handler(mockRequest, mockReply)
expect(NodeList.getCachedNodeList).toHaveBeenCalled()
expect(mockReply.send).toHaveBeenCalledWith(mockNodeList)
})
})
describe('GET /full-nodelist', () => {
let handler: Function
beforeEach(() => {
registerRoutes(mockFastify)
handler = registeredRoutes.get('GET')?.get('/full-nodelist')!
})
it('should return full node list without filters', () => {
const mockNodeList = { nodeList: [] }
;(NodeList.getCachedFullNodeList as jest.Mock).mockReturnValue(mockNodeList)
handler(mockRequest, mockReply)
expect(NodeList.getCachedFullNodeList).toHaveBeenCalledWith(false, false, false)
expect(mockReply.send).toHaveBeenCalledWith(mockNodeList)
})
it('should filter by activeOnly', () => {
mockRequest.query = { activeOnly: 'true' }
const mockNodeList = { nodeList: [] }
;(NodeList.getCachedFullNodeList as jest.Mock).mockReturnValue(mockNodeList)
handler(mockRequest, mockReply)
expect(NodeList.getCachedFullNodeList).toHaveBeenCalledWith(true, false, false)
})
it('should filter by syncingOnly', () => {
mockRequest.query = { syncingOnly: 'true' }
const mockNodeList = { nodeList: [] }
;(NodeList.getCachedFullNodeList as jest.Mock).mockReturnValue(mockNodeList)
handler(mockRequest, mockReply)
expect(NodeList.getCachedFullNodeList).toHaveBeenCalledWith(false, true, false)
})
it('should filter by standbyOnly', () => {
mockRequest.query = { standbyOnly: 'true' }
const mockNodeList = { nodeList: [] }
;(NodeList.getCachedFullNodeList as jest.Mock).mockReturnValue(mockNodeList)
handler(mockRequest, mockReply)
expect(NodeList.getCachedFullNodeList).toHaveBeenCalledWith(false, false, true)
})
it('should handle multiple filters', () => {
mockRequest.query = { activeOnly: 'true', syncingOnly: 'true' }
const mockNodeList = { nodeList: [] }
;(NodeList.getCachedFullNodeList as jest.Mock).mockReturnValue(mockNodeList)
handler(mockRequest, mockReply)
expect(NodeList.getCachedFullNodeList).toHaveBeenCalledWith(true, true, false)
})
})
describe('GET /allowed-archivers', () => {
let handler: Function
beforeEach(() => {
registerRoutes(mockFastify)
handler = registeredRoutes.get('GET')?.get('/allowed-archivers')!
})
it('should return allowed archivers config', async () => {
const mockConfig = {
allowedArchivers: ['archiver1', 'archiver2'],
}
;(allowedArchiversManager.getCurrentConfig as jest.Mock).mockReturnValue(mockConfig)
await handler(mockRequest, mockReply)
expect(allowedArchiversManager.getCurrentConfig).toHaveBeenCalled()
expect(mockReply.send).toHaveBeenCalledWith(mockConfig)
})
it('should return 500 when config is not available', async () => {
;(allowedArchiversManager.getCurrentConfig as jest.Mock).mockReturnValue(null)
await handler(mockRequest, mockReply)
expect(mockReply.status).toHaveBeenCalledWith(500)
expect(mockReply.send).toHaveBeenCalledWith({
error: 'Internal server error',
})
})
it('should handle errors', async () => {
;(allowedArchiversManager.getCurrentConfig as jest.Mock).mockImplementation(() => {
throw new Error('Config error')
})
await handler(mockRequest, mockReply)
expect(mockReply.status).toHaveBeenCalledWith(500)
expect(mockReply.send).toHaveBeenCalledWith({
error: 'Internal server error',
})
})
})
describe('POST /nodelist', () => {
let handler: Function
beforeEach(() => {
registerRoutes(mockFastify)
handler = registeredRoutes.get('POST')?.get('/nodelist')!
jest.clearAllMocks()
})
describe('when archiver is first and nodelist is empty', () => {
beforeEach(() => {
;(State as any).isFirst = true
;(NodeList.isEmpty as jest.Mock).mockReturnValue(true)
;(NodeList as any).foundFirstNode = false
})
afterEach(() => {
;(State as any).isFirst = false
;(NodeList as any).foundFirstNode = false
})
it('should process valid first node info', () => {
const firstNodeInfo = {
nodeInfo: {
externalIp: '10.0.0.1',
externalPort: 9001,
publicKey: 'first-node-key',
},
sign: {
owner: 'first-node-key',
sig: 'valid-signature',
},
}
;(Crypto.verify as jest.Mock).mockReturnValue(true)
;(Crypto.sign as jest.Mock).mockReturnValue({
nodeList: [{ ip: '10.0.0.1', port: 9001, publicKey: 'first-node-key' }],
joinRequest: { publicKey: 'test-public-key' },
dataRequestCycle: {},
dataRequestStateMetaData: {},
sign: { owner: 'test-owner', sig: 'test-sig' },
})
handler({ ...mockRequest, body: firstNodeInfo }, mockReply)
expect(NodeList.toggleFirstNode).toHaveBeenCalled()
expect(NodeList.addNodes).toHaveBeenCalledWith('syncing', [
{
ip: '10.0.0.1',
port: 9001,
publicKey: 'first-node-key',
},
])
expect(mockReply.send).toHaveBeenCalledWith(
expect.objectContaining({
nodeList: expect.any(Array),
joinRequest: expect.any(Object),
})
)
})
it('should reject invalid node info types', () => {
const invalidNodeInfo = {
nodeInfo: {
externalIp: 123, // Should be string
externalPort: 9001,
publicKey: 'first-node-key',
},
sign: {
owner: 'first-node-key',
sig: 'valid-signature',
},
}
;(Utils.validateTypes as jest.Mock).mockReturnValue('Invalid type for externalIp')
handler({ ...mockRequest, body: invalidNodeInfo }, mockReply)
expect(mockReply.send).toHaveBeenCalledWith({
success: false,
error: 'Invalid type for externalIp',
})
expect(NodeList.toggleFirstNode).not.toHaveBeenCalled()
})
it('should reject when publicKey does not match owner', () => {
const mismatchedNodeInfo = {
nodeInfo: {
externalIp: '10.0.0.1',
externalPort: 9001,
publicKey: 'first-node-key',
},
sign: {
owner: 'different-key',
sig: 'valid-signature',
},
}
;(Utils.validateTypes as jest.Mock).mockReturnValue(null)
handler({ ...mockRequest, body: mismatchedNodeInfo }, mockReply)
expect(mockReply.send).toHaveBeenCalledWith({
success: false,
error: 'nodeInfo.publicKey does not match signature owner',
})
})
it('should reject invalid signature', () => {
const invalidSigNodeInfo = {
nodeInfo: {
externalIp: '10.0.0.1',
externalPort: 9001,
publicKey: 'first-node-key',
},
sign: {
owner: 'first-node-key',
sig: 'invalid-signature',
},
}
;(Utils.validateTypes as jest.Mock).mockReturnValue(null)
;(Crypto.verify as jest.Mock).mockReturnValue(false)
handler({ ...mockRequest, body: invalidSigNodeInfo }, mockReply)
expect(mockReply.send).toHaveBeenCalledWith({
success: false,
error: 'Invalid signature',
})
})
it('should reject wrong publicKey when restrictFirstNodeSelectionByPublicKey is true', () => {
;(config as any).restrictFirstNodeSelectionByPublicKey = true
;(config as any).firstNodePublicKey = 'expected-key'
const wrongKeyNodeInfo = {
nodeInfo: {
externalIp: '10.0.0.1',
externalPort: 9001,
publicKey: 'wrong-key',
},
sign: {
owner: 'wrong-key',
sig: 'valid-signature',
},
}
;(Utils.validateTypes as jest.Mock).mockReturnValue(null)
;(Crypto.verify as jest.Mock).mockReturnValue(true)
handler({ ...mockRequest, body: wrongKeyNodeInfo }, mockReply)
expect(mockReply.send).toHaveBeenCalledWith({
success: false,
error: 'Invalid publicKey of first node info',
})
// Reset
;(config as any).restrictFirstNodeSelectionByPublicKey = false
})
it('should return cached nodelist if first node already found', () => {
;(NodeList as any).foundFirstNode = true
const cachedNodeList = { nodeList: [{ ip: '10.0.0.1', port: 9001 }] }
;(NodeList.getCachedNodeList as jest.Mock).mockReturnValue(cachedNodeList)
const nodeInfo = {
nodeInfo: {
externalIp: '10.0.0.1',
externalPort: 9001,
publicKey: 'first-node-key',
},
sign: {
owner: 'first-node-key',
sig: 'valid-signature',
},
}
handler({ ...mockRequest, body: nodeInfo }, mockReply)
expect(mockReply.send).toHaveBeenCalledWith(cachedNodeList)
expect(NodeList.toggleFirstNode).not.toHaveBeenCalled()
})
})
describe('when archiver is not first or nodelist is not empty', () => {
it('should return cached nodelist', () => {
;(State as any).isFirst = false
const cachedNodeList = { nodeList: [] }
;(NodeList.getCachedNodeList as jest.Mock).mockReturnValue(cachedNodeList)
const nodeInfo = {
nodeInfo: {
externalIp: '10.0.0.1',
externalPort: 9001,
publicKey: 'some-node-key',
},
sign: {
owner: 'some-node-key',
sig: 'valid-signature',
},
}
handler({ ...mockRequest, body: nodeInfo }, mockReply)
expect(mockReply.send).toHaveBeenCalledWith(cachedNodeList)
})
})
})
describe('GET /get-network-account', () => {
let handler: Function
beforeEach(() => {
registerRoutes(mockFastify)
handler = registeredRoutes.get('GET')?.get('/get-network-account')!
})
it('should return network account hash by default', () => {
const mockNetworkHash = 'mock-network-account-hash'
;(Crypto.sign as jest.Mock).mockReturnValueOnce({
networkAccountHash: mockNetworkHash,
sign: { owner: 'test-owner', sig: 'test-sig' },
})
handler(mockRequest, mockReply)
expect(mockReply.send).toHaveBeenCalledWith({
networkAccountHash: mockNetworkHash,
sign: { owner: 'test-owner', sig: 'test-sig' },
})
})
it('should return full network account when hash=false', () => {
const mockNetworkAccount = { id: 'network-account', data: {} }
;(getGlobalNetworkAccount as jest.Mock).mockReturnValue(mockNetworkAccount)
;(Crypto.sign as jest.Mock).mockReturnValueOnce({
networkAccount: mockNetworkAccount,
sign: { owner: 'test-owner', sig: 'test-sig' },
})
mockRequest.query = { hash: 'false' }
handler(mockRequest, mockReply)
expect(getGlobalNetworkAccount).toHaveBeenCalledWith(false)
expect(mockReply.send).toHaveBeenCalledWith({
networkAccount: mockNetworkAccount,
sign: { owner: 'test-owner', sig: 'test-sig' },
})
})
})
describe('queryFromArchivers', () => {
beforeEach(() => {
jest.clearAllMocks()
;(P2P.postJson as jest.Mock).mockReset()
;(Utils.getRandomItemFromArr as jest.Mock).mockReturnValue([
{ ip: '10.0.0.1', port: 4000 },
{ ip: '10.0.0.2', port: 4000 },
{ ip: '10.0.0.3', port: 4000 },
])
// Reset Crypto.sign to default behavior
;(Crypto.sign as jest.Mock).mockImplementation((data: any) => ({
...data,
sign: { owner: 'test-owner', sig: 'test-sig' },
}))
})
it('should query cycle info from archivers', async () => {
const mockResponse = {
cycleInfo: [{ counter: 1 }, { counter: 2 }],
sign: { owner: 'archiver1', sig: 'sig1' },
sender: 'archiver1',
}
;(P2P.postJson as jest.Mock<any>).mockResolvedValue(mockResponse)
;(Crypto.verify as jest.Mock).mockReturnValue(true)
const result = await queryFromArchivers(RequestDataType.CYCLE, { start: 1, end: 2 })
expect(P2P.postJson).toHaveBeenCalledWith(
'http://10.0.0.1:4000/cycleinfo',
expect.objectContaining({
start: 1,
end: 2,
sender: 'test-public-key',
}),
undefined
)
expect(result).toEqual(mockResponse)
})
it('should query receipt data from archivers', async () => {
const mockResponse = {
receipts: [{ receiptId: 'r1' }],
sign: { owner: 'archiver1', sig: 'sig1' },
sender: 'archiver1',
}