This repository was archived by the owner on Feb 8, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathlightning.test.ts
More file actions
383 lines (322 loc) · 9.87 KB
/
lightning.test.ts
File metadata and controls
383 lines (322 loc) · 9.87 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
import { IBtInfo, IGetFeeEstimatesResponse } from 'beignet';
import { checkRgsHealth, getFees } from '../src/utils/lightning';
jest.mock('../src/utils/wallet', () => ({
getSelectedNetwork: jest.fn(() => 'bitcoin'),
}));
jest.mock('../src/store/helpers', () => ({
getStore: jest.fn(() => ({
settings: {
rapidGossipSyncUrl: 'https://rgs.blocktank.to/snapshots/',
},
})),
}));
describe('getFees', () => {
const MEMPOOL_URL = 'https://mempool.space/api/v1/fees/recommended';
const BLOCKTANK_URL = 'https://api1.blocktank.to/api/info';
const mockMempoolResponse: IGetFeeEstimatesResponse = {
fastestFee: 111,
halfHourFee: 110,
hourFee: 109,
minimumFee: 108,
};
const mockBlocktankResponse: IBtInfo = {
onchain: {
feeRates: {
fast: 999,
mid: 998,
slow: 997,
},
},
} as IBtInfo;
beforeEach(() => {
jest.clearAllMocks();
(global.fetch as jest.Mock) = jest.fn(url => {
if (url === MEMPOOL_URL) {
return Promise.resolve({
ok: true,
json: () => Promise.resolve(mockMempoolResponse),
});
}
if (url === BLOCKTANK_URL) {
return Promise.resolve({
ok: true,
json: () => Promise.resolve(mockBlocktankResponse),
});
}
return Promise.reject(new Error(`Unexpected URL: ${url}`));
});
});
it('should use mempool.space when both APIs succeed', async () => {
const result = await getFees();
expect(result).toEqual({
maxAllowedNonAnchorChannelRemoteFee: Math.max(25, 111 * 10),
minAllowedAnchorChannelRemoteFee: 108,
minAllowedNonAnchorChannelRemoteFee: 107,
anchorChannelFee: 109,
nonAnchorChannelFee: 110,
channelCloseMinimum: 108,
outputSpendingFee: 111,
maximumFeeEstimate: 111 * 10,
urgentOnChainSweep: 111,
});
expect(fetch).toHaveBeenCalledTimes(2);
expect(fetch).toHaveBeenCalledWith(MEMPOOL_URL);
expect(fetch).toHaveBeenCalledWith(BLOCKTANK_URL);
});
it('should use blocktank when mempool.space fails', async () => {
(global.fetch as jest.Mock) = jest.fn(url => {
if (url === MEMPOOL_URL) {
return Promise.reject('Mempool failed');
}
if (url === BLOCKTANK_URL) {
return Promise.resolve({
ok: true,
json: () => Promise.resolve(mockBlocktankResponse),
});
}
return Promise.reject(new Error(`Unexpected URL: ${url}`));
});
const result = await getFees();
expect(result).toEqual({
maxAllowedNonAnchorChannelRemoteFee: Math.max(25, 999 * 10),
minAllowedAnchorChannelRemoteFee: 997,
minAllowedNonAnchorChannelRemoteFee: 996,
anchorChannelFee: 997,
nonAnchorChannelFee: 998,
channelCloseMinimum: 997,
outputSpendingFee: 999,
maximumFeeEstimate: 999 * 10,
urgentOnChainSweep: 999,
});
expect(fetch).toHaveBeenCalledTimes(3);
});
it('should retry mempool once and succeed even if blocktank fails', async () => {
let mempoolAttempts = 0;
(global.fetch as jest.Mock) = jest.fn(url => {
if (url === MEMPOOL_URL) {
mempoolAttempts++;
return mempoolAttempts === 1
? Promise.reject('First mempool try failed')
: Promise.resolve({
ok: true,
json: () => Promise.resolve(mockMempoolResponse),
});
}
if (url === BLOCKTANK_URL) {
return Promise.reject('Blocktank failed');
}
return Promise.reject(new Error(`Unexpected URL: ${url}`));
});
const result = await getFees();
expect(result.urgentOnChainSweep).toBe(111);
expect(fetch).toHaveBeenCalledTimes(4);
expect(fetch).toHaveBeenCalledWith(MEMPOOL_URL);
expect(fetch).toHaveBeenCalledWith(BLOCKTANK_URL);
});
it('should throw error when all fetches fail', async () => {
(global.fetch as jest.Mock) = jest.fn(url => {
if (url === MEMPOOL_URL || url === BLOCKTANK_URL) {
return Promise.reject('API failed');
}
return Promise.reject(new Error(`Unexpected URL: ${url}`));
});
await expect(getFees()).rejects.toThrow();
expect(fetch).toHaveBeenCalledTimes(4);
});
it('should handle invalid mempool response', async () => {
(global.fetch as jest.Mock) = jest.fn(url => {
if (url === MEMPOOL_URL) {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({ fastestFee: 0 }),
});
}
if (url === BLOCKTANK_URL) {
return Promise.resolve({
ok: true,
json: () => Promise.resolve(mockBlocktankResponse),
});
}
return Promise.reject(new Error(`Unexpected URL: ${url}`));
});
const result = await getFees();
expect(result.urgentOnChainSweep).toBe(999);
});
it('should handle invalid blocktank response', async () => {
(global.fetch as jest.Mock) = jest.fn(url => {
if (url === MEMPOOL_URL) {
return Promise.resolve({
ok: true,
json: () => Promise.resolve(mockMempoolResponse),
});
}
if (url === BLOCKTANK_URL) {
return Promise.resolve({
ok: true,
json: () => Promise.resolve({ onchain: { feeRates: { fast: 0 } } }),
});
}
return Promise.reject(new Error(`Unexpected URL: ${url}`));
});
const result = await getFees();
expect(result.urgentOnChainSweep).toBe(111);
});
it('should handle timeout errors gracefully', async () => {
jest.useFakeTimers();
(global.fetch as jest.Mock) = jest.fn(url => {
if (url === MEMPOOL_URL) {
return new Promise(resolve => {
setTimeout(() => resolve({
ok: true,
json: () => Promise.resolve(mockMempoolResponse),
}), 15000); // longer than timeout
});
}
if (url === BLOCKTANK_URL) {
return new Promise(resolve => {
setTimeout(() => resolve({
ok: true,
json: () => Promise.resolve(mockBlocktankResponse),
}), 15000); // longer than timeout
});
}
return Promise.reject(new Error(`Unexpected URL: ${url}`));
});
const feesPromise = getFees();
jest.advanceTimersByTime(11000);
await expect(feesPromise).rejects.toThrow();
expect(fetch).toHaveBeenCalledTimes(2);
jest.useRealTimers();
});
});
describe('checkRgsHealth', () => {
const RGS_URL = 'https://rgs.blocktank.to/snapshots/';
beforeEach(() => {
jest.clearAllMocks();
});
it('should detect healthy RGS (< 24 hours old)', async () => {
const nowSeconds = Math.floor(Date.now() / 1000);
const recentTimestamp = nowSeconds - 3600 * 12; // 12 hours ago
const mockHtml = `
<a href="snapshot__calculated-at%3A${recentTimestamp}__range%3A10800-scope.lngossip">snapshot</a>
`;
(global.fetch as jest.Mock) = jest.fn(() =>
Promise.resolve({
ok: true,
text: () => Promise.resolve(mockHtml),
}),
);
const result = await checkRgsHealth();
expect(result.isOk()).toBe(true);
if (result.isOk()) {
expect(result.value.isHealthy).toBe(true);
expect(result.value.timestamp).toBe(recentTimestamp);
expect(result.value.ageHours).toBeGreaterThan(11);
expect(result.value.ageHours).toBeLessThan(13);
}
expect(fetch).toHaveBeenCalledWith(RGS_URL);
});
it('should detect stale RGS (> 24 hours old)', async () => {
const nowSeconds = Math.floor(Date.now() / 1000);
const staleTimestamp = nowSeconds - 3600 * 48; // 48 hours ago (2 days)
const mockHtml = `
<a href="snapshot__calculated-at%3A${staleTimestamp}__range%3A10800-scope.lngossip">snapshot</a>
`;
(global.fetch as jest.Mock) = jest.fn(() =>
Promise.resolve({
ok: true,
text: () => Promise.resolve(mockHtml),
}),
);
const result = await checkRgsHealth();
expect(result.isOk()).toBe(true);
if (result.isOk()) {
expect(result.value.isHealthy).toBe(false);
expect(result.value.timestamp).toBe(staleTimestamp);
expect(result.value.ageHours).toBeGreaterThan(47);
expect(result.value.ageHours).toBeLessThan(49);
}
});
it('should handle RGS endpoint returning non-200 status', async () => {
(global.fetch as jest.Mock) = jest.fn(() =>
Promise.resolve({
ok: false,
status: 404,
}),
);
const result = await checkRgsHealth();
expect(result.isErr()).toBe(true);
if (result.isErr()) {
expect(result.error.message).toContain('404');
}
});
it('should handle missing timestamp in RGS HTML', async () => {
const mockHtml = `
<a href="some-file-without-timestamp.lngossip">snapshot</a>
`;
(global.fetch as jest.Mock) = jest.fn(() =>
Promise.resolve({
ok: true,
text: () => Promise.resolve(mockHtml),
}),
);
const result = await checkRgsHealth();
expect(result.isErr()).toBe(true);
if (result.isErr()) {
expect(result.error.message).toContain('Could not parse');
}
});
it('should handle network timeout', async () => {
jest.useFakeTimers();
(global.fetch as jest.Mock) = jest.fn(() =>
new Promise(resolve => {
setTimeout(() => resolve({
ok: true,
text: () => Promise.resolve('<html></html>'),
}), 10000); // longer than 5s timeout
}),
);
const healthPromise = checkRgsHealth();
jest.advanceTimersByTime(6000);
await expect(healthPromise).resolves.toMatchObject({
isErr: expect.any(Function),
});
const result = await healthPromise;
expect(result.isErr()).toBe(true);
jest.useRealTimers();
});
it('should parse timestamp with colon delimiter', async () => {
const testTimestamp = 1762462800; // Nov 6, 2025
const mockHtml = `
<a href="snapshot__calculated-at:${testTimestamp}__range:10800-scope.lngossip">snapshot</a>
`;
(global.fetch as jest.Mock) = jest.fn(() =>
Promise.resolve({
ok: true,
text: () => Promise.resolve(mockHtml),
}),
);
const result = await checkRgsHealth();
expect(result.isOk()).toBe(true);
if (result.isOk()) {
expect(result.value.timestamp).toBe(testTimestamp);
}
});
it('should parse timestamp with percent-encoded colon', async () => {
const testTimestamp = 1762462800; // Nov 6, 2025
const mockHtml = `
<a href="snapshot__calculated-at%3A${testTimestamp}__range%3A10800-scope.lngossip">snapshot</a>
`;
(global.fetch as jest.Mock) = jest.fn(() =>
Promise.resolve({
ok: true,
text: () => Promise.resolve(mockHtml),
}),
);
const result = await checkRgsHealth();
expect(result.isOk()).toBe(true);
if (result.isOk()) {
expect(result.value.timestamp).toBe(testTimestamp);
}
});
});