@bsv/overlay-express 2.4.2 → 2.4.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/LICENSE.txt +57 -27
  2. package/README.md +141 -56
  3. package/dist/cjs/mod.d.ts +11 -0
  4. package/dist/cjs/mod.d.ts.map +1 -0
  5. package/dist/cjs/mod.js.map +1 -1
  6. package/dist/cjs/package.json +26 -13
  7. package/dist/cjs/src/ArcadeProvider.d.ts +37 -0
  8. package/dist/cjs/src/ArcadeProvider.d.ts.map +1 -0
  9. package/dist/cjs/src/ArcadeProvider.js.map +1 -1
  10. package/dist/cjs/src/BanAwareDiscoveryStorage.d.ts +36 -0
  11. package/dist/cjs/src/BanAwareDiscoveryStorage.d.ts.map +1 -0
  12. package/dist/cjs/src/BanAwareDiscoveryStorage.js +5 -4
  13. package/dist/cjs/src/BanAwareDiscoveryStorage.js.map +1 -1
  14. package/dist/cjs/src/BanAwareLookupWrapper.d.ts +31 -0
  15. package/dist/cjs/src/BanAwareLookupWrapper.d.ts.map +1 -0
  16. package/dist/cjs/src/BanAwareLookupWrapper.js +3 -2
  17. package/dist/cjs/src/BanAwareLookupWrapper.js.map +1 -1
  18. package/dist/cjs/src/BanAwareTopicManager.d.ts +28 -0
  19. package/dist/cjs/src/BanAwareTopicManager.d.ts.map +1 -0
  20. package/dist/cjs/src/BanAwareTopicManager.js +3 -2
  21. package/dist/cjs/src/BanAwareTopicManager.js.map +1 -1
  22. package/dist/cjs/src/BanService.d.ts +81 -0
  23. package/dist/cjs/src/BanService.d.ts.map +1 -0
  24. package/dist/cjs/src/BanService.js.map +1 -1
  25. package/dist/cjs/src/ChaintracksProvider.d.ts +29 -0
  26. package/dist/cjs/src/ChaintracksProvider.d.ts.map +1 -0
  27. package/dist/cjs/src/ChaintracksProvider.js +1 -1
  28. package/dist/cjs/src/ChaintracksProvider.js.map +1 -1
  29. package/dist/cjs/src/JanitorService.d.ts +128 -0
  30. package/dist/cjs/src/JanitorService.d.ts.map +1 -0
  31. package/dist/cjs/src/JanitorService.js +108 -37
  32. package/dist/cjs/src/JanitorService.js.map +1 -1
  33. package/dist/cjs/src/OverlayExpress.d.ts +466 -0
  34. package/dist/cjs/src/OverlayExpress.d.ts.map +1 -0
  35. package/dist/cjs/src/OverlayExpress.js +307 -148
  36. package/dist/cjs/src/OverlayExpress.js.map +1 -1
  37. package/dist/cjs/src/OverlayMonitor.d.ts +197 -0
  38. package/dist/cjs/src/OverlayMonitor.d.ts.map +1 -0
  39. package/dist/cjs/src/OverlayMonitor.js +6 -4
  40. package/dist/cjs/src/OverlayMonitor.js.map +1 -1
  41. package/dist/cjs/src/ProviderChainBroadcaster.d.ts +18 -0
  42. package/dist/cjs/src/ProviderChainBroadcaster.d.ts.map +1 -0
  43. package/dist/cjs/src/ProviderChainBroadcaster.js +7 -3
  44. package/dist/cjs/src/ProviderChainBroadcaster.js.map +1 -1
  45. package/dist/cjs/src/ReorgStream.d.ts +74 -0
  46. package/dist/cjs/src/ReorgStream.d.ts.map +1 -0
  47. package/dist/cjs/src/ReorgStream.js +14 -6
  48. package/dist/cjs/src/ReorgStream.js.map +1 -1
  49. package/dist/cjs/src/generalGuide.md.d.ts +3 -0
  50. package/dist/cjs/src/generalGuide.md.d.ts.map +1 -0
  51. package/dist/cjs/src/generalGuide.md.js.map +1 -1
  52. package/dist/cjs/src/makeUserInterface.d.ts +22 -0
  53. package/dist/cjs/src/makeUserInterface.d.ts.map +1 -0
  54. package/dist/cjs/src/makeUserInterface.js +4 -4
  55. package/dist/cjs/src/makeUserInterface.js.map +1 -1
  56. package/dist/cjs/src/security/edgePolicy.d.ts +57 -0
  57. package/dist/cjs/src/security/edgePolicy.d.ts.map +1 -0
  58. package/dist/cjs/src/security/edgePolicy.js +379 -0
  59. package/dist/cjs/src/security/edgePolicy.js.map +1 -0
  60. package/dist/esm/mod.js.map +1 -1
  61. package/dist/esm/src/ArcadeProvider.js.map +1 -1
  62. package/dist/esm/src/BanAwareDiscoveryStorage.js +5 -4
  63. package/dist/esm/src/BanAwareDiscoveryStorage.js.map +1 -1
  64. package/dist/esm/src/BanAwareLookupWrapper.js +3 -2
  65. package/dist/esm/src/BanAwareLookupWrapper.js.map +1 -1
  66. package/dist/esm/src/BanAwareTopicManager.js +3 -2
  67. package/dist/esm/src/BanAwareTopicManager.js.map +1 -1
  68. package/dist/esm/src/ChaintracksProvider.js +1 -1
  69. package/dist/esm/src/ChaintracksProvider.js.map +1 -1
  70. package/dist/esm/src/JanitorService.js +84 -8
  71. package/dist/esm/src/JanitorService.js.map +1 -1
  72. package/dist/esm/src/OverlayExpress.js +290 -134
  73. package/dist/esm/src/OverlayExpress.js.map +1 -1
  74. package/dist/esm/src/ProviderChainBroadcaster.js +7 -3
  75. package/dist/esm/src/ProviderChainBroadcaster.js.map +1 -1
  76. package/dist/esm/src/ReorgStream.js +14 -6
  77. package/dist/esm/src/ReorgStream.js.map +1 -1
  78. package/dist/esm/src/makeUserInterface.js +3 -4
  79. package/dist/esm/src/makeUserInterface.js.map +1 -1
  80. package/dist/esm/src/security/edgePolicy.js +377 -0
  81. package/dist/esm/src/security/edgePolicy.js.map +1 -0
  82. package/dist/types/mod.d.ts +1 -1
  83. package/dist/types/mod.d.ts.map +1 -1
  84. package/dist/types/src/ArcadeProvider.d.ts.map +1 -1
  85. package/dist/types/src/BanAwareDiscoveryStorage.d.ts.map +1 -1
  86. package/dist/types/src/BanAwareLookupWrapper.d.ts.map +1 -1
  87. package/dist/types/src/BanAwareTopicManager.d.ts.map +1 -1
  88. package/dist/types/src/BanService.d.ts.map +1 -1
  89. package/dist/types/src/ChaintracksProvider.d.ts.map +1 -1
  90. package/dist/types/src/JanitorService.d.ts +14 -1
  91. package/dist/types/src/JanitorService.d.ts.map +1 -1
  92. package/dist/types/src/OverlayExpress.d.ts +48 -2
  93. package/dist/types/src/OverlayExpress.d.ts.map +1 -1
  94. package/dist/types/src/OverlayMonitor.d.ts.map +1 -1
  95. package/dist/types/src/ProviderChainBroadcaster.d.ts.map +1 -1
  96. package/dist/types/src/ReorgStream.d.ts.map +1 -1
  97. package/dist/types/src/generalGuide.md.d.ts +1 -1
  98. package/dist/types/src/generalGuide.md.d.ts.map +1 -1
  99. package/dist/types/src/makeUserInterface.d.ts +1 -2
  100. package/dist/types/src/makeUserInterface.d.ts.map +1 -1
  101. package/dist/types/src/security/edgePolicy.d.ts +57 -0
  102. package/dist/types/src/security/edgePolicy.d.ts.map +1 -0
  103. package/package.json +47 -25
  104. package/dist/cjs/tsconfig.cjs.tsbuildinfo +0 -1
  105. package/dist/esm/tsconfig.esm.tsbuildinfo +0 -1
  106. package/dist/types/tsconfig.types.tsbuildinfo +0 -1
  107. package/mod.ts +0 -47
  108. package/src/ArcadeProvider.ts +0 -232
  109. package/src/BanAwareDiscoveryStorage.ts +0 -91
  110. package/src/BanAwareLookupWrapper.ts +0 -95
  111. package/src/BanAwareTopicManager.ts +0 -87
  112. package/src/BanService.ts +0 -154
  113. package/src/ChaintracksProvider.ts +0 -79
  114. package/src/JanitorService.ts +0 -423
  115. package/src/OverlayExpress.ts +0 -2479
  116. package/src/OverlayMonitor.ts +0 -817
  117. package/src/ProviderChainBroadcaster.ts +0 -108
  118. package/src/ReorgStream.ts +0 -221
  119. package/src/__tests__/BanAwareDiscoveryStorage.test.ts +0 -131
  120. package/src/__tests__/BanAwareLookupWrapper.test.ts +0 -255
  121. package/src/__tests__/BanAwareTopicManager.test.ts +0 -132
  122. package/src/__tests__/BanService.test.ts +0 -310
  123. package/src/__tests__/InMemoryMigrationSource.test.ts +0 -11
  124. package/src/__tests__/JanitorService.test.ts +0 -941
  125. package/src/__tests__/OverlayExpress.test.ts +0 -1300
  126. package/src/__tests__/OverlayMonitor.test.ts +0 -255
  127. package/src/__tests__/OverlayProviders.live.test.ts +0 -43
  128. package/src/__tests__/OverlayProviders.test.ts +0 -123
  129. package/src/__tests__/README.md +0 -105
  130. package/src/__tests__/ReorgStream.test.ts +0 -66
  131. package/src/__tests__/makeUserInterface.test.ts +0 -193
  132. package/src/__tests__/setup.ts +0 -36
  133. package/src/auth-express-middleware.d.ts +0 -16
  134. package/src/generalGuide.md.ts +0 -74
  135. package/src/makeUserInterface.ts +0 -1224
@@ -1,255 +0,0 @@
1
- import { describe, it, expect, jest } from '@jest/globals'
2
- import { Transaction } from '@bsv/sdk'
3
- import { OverlayMonitor, analyzeOverlayAnchorTip, analyzeOverlayLookupResponse } from '../OverlayMonitor.js'
4
-
5
- describe('OverlayMonitor', () => {
6
- it('summarizes an empty lookup response', () => {
7
- const result = analyzeOverlayLookupResponse({
8
- target: 'local-overlay',
9
- url: 'https://overlay.example/lookup',
10
- probe: 'empty',
11
- service: 'ls_empty',
12
- status: 200,
13
- ok: true,
14
- responseBody: { outputs: [] },
15
- responseBytes: 14,
16
- durationMs: 5
17
- })
18
-
19
- expect(result.outputCount).toBe(0)
20
- expect(result.analyzedOutputCount).toBe(0)
21
- expect(result.warnings).toHaveLength(0)
22
- })
23
-
24
- it('reports missing subject proofs in returned BEEF', () => {
25
- const tx = new Transaction(1, [], [], 0)
26
- const result = analyzeOverlayLookupResponse({
27
- target: 'local-overlay',
28
- url: 'https://overlay.example/lookup',
29
- probe: 'proof-shape',
30
- service: 'ls_ship',
31
- status: 200,
32
- ok: true,
33
- responseBody: {
34
- outputs: [
35
- {
36
- outputIndex: 0,
37
- beef: tx.toBEEF()
38
- }
39
- ]
40
- },
41
- responseBytes: 512,
42
- durationMs: 5
43
- })
44
-
45
- expect(result.outputs[0].txid).toBe(tx.id('hex'))
46
- expect(result.outputs[0].subjectHasProof).toBe(false)
47
- expect(result.outputs[0].txCount).toBe(1)
48
- expect(result.warnings.map(warning => warning.code)).toContain('subject-proof-missing')
49
- })
50
-
51
- it('runs configured probes through Overlay Express lookup endpoints', async () => {
52
- const tx = new Transaction(1, [], [], 0)
53
- const responseBody = JSON.stringify({
54
- outputs: [
55
- {
56
- outputIndex: 0,
57
- beef: tx.toBEEF()
58
- }
59
- ]
60
- })
61
- const fetchImpl = jest.fn<typeof fetch>(async () => new Response(responseBody, { status: 200 }))
62
- const monitor = new OverlayMonitor({
63
- targets: [
64
- {
65
- name: 'local-overlay',
66
- baseUrl: 'https://overlay.example',
67
- probes: [
68
- {
69
- name: 'ship',
70
- service: 'ls_ship',
71
- query: { topics: ['tm_example'] }
72
- }
73
- ]
74
- }
75
- ],
76
- fetchImpl
77
- })
78
-
79
- const report = await monitor.runOnce()
80
-
81
- expect(fetchImpl).toHaveBeenCalledWith('https://overlay.example/lookup', expect.objectContaining({
82
- method: 'POST',
83
- body: JSON.stringify({ service: 'ls_ship', query: { topics: ['tm_example'] } })
84
- }))
85
- expect(report.summary.targetCount).toBe(1)
86
- expect(report.summary.probeCount).toBe(1)
87
- expect(report.summary.maintenanceActionCount).toBe(0)
88
- expect(report.summary.outputsMissingSubjectProof).toBe(1)
89
- })
90
-
91
- it('reports stale and mismatched BASM anchor tips', () => {
92
- const result = analyzeOverlayAnchorTip({
93
- target: 'local-overlay',
94
- url: 'https://overlay.example/requestTopicAnchorTip',
95
- probe: 'anchors',
96
- topic: 'tm_example',
97
- status: 200,
98
- ok: true,
99
- responseBody: {
100
- blockHeight: 850000,
101
- tac: '11'.repeat(32),
102
- expiredUnprovenCount: 2
103
- },
104
- responseBytes: 128,
105
- durationMs: 5,
106
- expectedTac: '22'.repeat(32),
107
- currentHeight: 850020,
108
- thresholds: {
109
- anchorTipLagBlocks: 6,
110
- expiredUnprovenCount: 0
111
- }
112
- })
113
-
114
- expect(result.warnings.map(warning => warning.code)).toEqual([
115
- 'anchor-tip-mismatch',
116
- 'anchor-stale-height',
117
- 'expired-unproven-state'
118
- ])
119
- })
120
-
121
- it('runs configured anchor probes through Overlay Express BASM endpoints', async () => {
122
- const responseBody = JSON.stringify({
123
- topic: 'tm_example',
124
- blockHeight: 850000,
125
- tac: '11'.repeat(32)
126
- })
127
- const fetchImpl = jest.fn<typeof fetch>(async () => new Response(responseBody, { status: 200 }))
128
- const monitor = new OverlayMonitor({
129
- targets: [
130
- {
131
- name: 'local-overlay',
132
- baseUrl: 'https://overlay.example',
133
- probes: [],
134
- anchorProbes: [
135
- {
136
- name: 'topic-tip',
137
- topic: 'tm_example',
138
- expectedTac: '11'.repeat(32)
139
- }
140
- ]
141
- }
142
- ],
143
- fetchImpl
144
- })
145
-
146
- const report = await monitor.runOnce()
147
-
148
- expect(fetchImpl).toHaveBeenCalledWith('https://overlay.example/requestTopicAnchorTip', expect.objectContaining({
149
- method: 'POST',
150
- headers: expect.objectContaining({ 'x-bsv-topic': 'tm_example' })
151
- }))
152
- expect(report.summary.anchorProbeCount).toBe(1)
153
- expect(report.anchorResults[0].warnings).toHaveLength(0)
154
- })
155
-
156
- it('runs configured admin maintenance actions', async () => {
157
- const fetchImpl = jest.fn<typeof fetch>(async (url) => {
158
- if (String(url).endsWith('/admin/maintainUnproven')) {
159
- return new Response(JSON.stringify({ status: 'success', data: { evictedTransactions: 1 } }), { status: 200 })
160
- }
161
- if (String(url).endsWith('/admin/startBASMSync')) {
162
- return new Response(JSON.stringify({ status: 'success', data: { synced: true } }), { status: 200 })
163
- }
164
- return new Response(JSON.stringify({ status: 'success' }), { status: 200 })
165
- })
166
- const monitor = new OverlayMonitor({
167
- targets: [
168
- {
169
- name: 'maintained-overlay',
170
- baseUrl: 'https://overlay.example',
171
- probes: [],
172
- maintenance: {
173
- adminToken: 'admin-secret',
174
- startBASMSync: true,
175
- maintainUnproven: {
176
- topics: ['tm_a', 'tm_b'],
177
- thresholdBlocks: 12
178
- }
179
- }
180
- }
181
- ],
182
- fetchImpl
183
- })
184
-
185
- const report = await monitor.runOnce()
186
-
187
- expect(fetchImpl).toHaveBeenCalledWith('https://overlay.example/admin/startBASMSync', expect.objectContaining({
188
- method: 'POST',
189
- headers: expect.objectContaining({ Authorization: 'Bearer admin-secret' }),
190
- body: JSON.stringify({})
191
- }))
192
- expect(fetchImpl).toHaveBeenCalledWith('https://overlay.example/admin/maintainUnproven', expect.objectContaining({
193
- method: 'POST',
194
- headers: expect.objectContaining({ Authorization: 'Bearer admin-secret' }),
195
- body: JSON.stringify({ topic: 'tm_a', thresholdBlocks: 12 })
196
- }))
197
- expect(fetchImpl).toHaveBeenCalledWith('https://overlay.example/admin/maintainUnproven', expect.objectContaining({
198
- method: 'POST',
199
- body: JSON.stringify({ topic: 'tm_b', thresholdBlocks: 12 })
200
- }))
201
- expect(report.maintenanceResults).toHaveLength(3)
202
- expect(report.summary.maintenanceActionCount).toBe(3)
203
- expect(report.summary.failedMaintenanceActionCount).toBe(0)
204
- })
205
-
206
- it('reports failed admin maintenance separately from probe failures', async () => {
207
- const fetchImpl = jest.fn<typeof fetch>(async () => new Response(JSON.stringify({ message: 'Forbidden' }), { status: 403 }))
208
- const monitor = new OverlayMonitor({
209
- targets: [
210
- {
211
- name: 'maintained-overlay',
212
- baseUrl: 'https://overlay.example',
213
- probes: [],
214
- maintenance: {
215
- maintainUnproven: true
216
- }
217
- }
218
- ],
219
- fetchImpl
220
- })
221
-
222
- const report = await monitor.runOnce()
223
-
224
- expect(report.summary.failedProbeCount).toBe(0)
225
- expect(report.summary.failedMaintenanceActionCount).toBe(1)
226
- expect(report.maintenanceResults[0].error).toBe('Forbidden')
227
- })
228
-
229
- it('aborts a probe that exceeds the configured timeout', async () => {
230
- // Never resolves on its own; only settles when the abort signal fires.
231
- const fetchImpl = jest.fn<typeof fetch>(async (_url, init) => await new Promise<Response>((_resolve, reject) => {
232
- init?.signal?.addEventListener('abort', () => reject(new Error('aborted')))
233
- }))
234
- const monitor = new OverlayMonitor({
235
- targets: [
236
- {
237
- name: 'slow-overlay',
238
- baseUrl: 'https://overlay.example',
239
- probes: [{ name: 'slow', service: 'ls_slow', query: {} }]
240
- }
241
- ],
242
- fetchImpl,
243
- timeoutMs: 10
244
- })
245
-
246
- const report = await monitor.runOnce()
247
-
248
- expect(fetchImpl).toHaveBeenCalledWith('https://overlay.example/lookup', expect.objectContaining({
249
- signal: expect.anything()
250
- }))
251
- expect(report.results[0].ok).toBe(false)
252
- expect(report.results[0].error).toContain('timed out')
253
- expect(report.summary.failedProbeCount).toBe(1)
254
- })
255
- })
@@ -1,43 +0,0 @@
1
- import { ArcadeProvider } from '../ArcadeProvider.js'
2
- import { ChaintracksProvider } from '../ChaintracksProvider.js'
3
-
4
- const runLive = process.env.RUN_LIVE_OVERLAY_PROVIDER_TESTS === '1'
5
- const describeLive = runLive ? describe : describe.skip
6
-
7
- describeLive('Overlay providers live integration', () => {
8
- jest.setTimeout(30000)
9
-
10
- test.each([
11
- ['mainnet', process.env.ARCADE_MAINNET_URL ?? 'https://arcade-v2-us-1.bsvblockchain.tech'],
12
- ['teratestnet', process.env.ARCADE_TTN_URL ?? 'https://arcade-v2-ttn-us-1.bsvblockchain.tech']
13
- ])('reads real %s headers through Arcade go-chaintracks', async (_label, url) => {
14
- const chaintracks = new ChaintracksProvider(url)
15
- const height = await chaintracks.currentHeight()
16
- const header = await chaintracks.findHeaderForHeight(height)
17
-
18
- expect(height).toBeGreaterThan(0)
19
- expect(header?.height).toBe(height)
20
- expect(header?.hash).toMatch(/^[0-9a-f]{64}$/)
21
- expect(header?.merkleRoot).toMatch(/^[0-9a-f]{64}$/)
22
- if (header === undefined) throw new Error('header was not returned')
23
- await expect(chaintracks.isValidRootForHeight(header.merkleRoot, height)).resolves.toBe(true)
24
- })
25
-
26
- test('fetches and validates a real mined mainnet Arcade proof', async () => {
27
- const txid = process.env.ARCADE_PROOF_TXID ?? 'f283c15af7fb9301ef35445eaa76e92d36382880078490b2f4fbae55b6f9551a'
28
- const arcadeUrl = process.env.ARCADE_MAINNET_URL ?? 'https://arcade-v2-us-1.bsvblockchain.tech'
29
- const arcade = new ArcadeProvider(arcadeUrl)
30
- const chaintracks = new ChaintracksProvider(arcadeUrl)
31
-
32
- const proof = await arcade.fetchMerkleProof(txid)
33
-
34
- expect(proof).toBeDefined()
35
- expect(proof?.txid).toBe(txid)
36
- expect(proof?.blockHeight).toBeGreaterThan(0)
37
- expect(proof?.merkleRoot).toMatch(/^[0-9a-f]{64}$/)
38
- if (proof === undefined || proof.blockHeight === undefined) {
39
- throw new Error('complete proof was not returned')
40
- }
41
- await expect(chaintracks.isValidRootForHeight(proof.merkleRoot, proof.blockHeight)).resolves.toBe(true)
42
- })
43
- })
@@ -1,123 +0,0 @@
1
- import { ArcadeProvider } from '../ArcadeProvider.js'
2
- import { ChaintracksProvider } from '../ChaintracksProvider.js'
3
- import { ProviderChainBroadcaster } from '../ProviderChainBroadcaster.js'
4
-
5
- describe('Overlay transaction providers', () => {
6
- const tx = {
7
- id: jest.fn(() => '11'.repeat(32)),
8
- toHexEF: jest.fn(() => 'efhex'),
9
- toHex: jest.fn(() => 'rawhex')
10
- } as any
11
-
12
- beforeEach(() => {
13
- jest.clearAllMocks()
14
- })
15
-
16
- it('tries the next broadcaster after a transient provider failure', async () => {
17
- const first = {
18
- broadcast: jest.fn(async () => ({
19
- status: 'error' as const,
20
- code: '503',
21
- description: 'backpressure',
22
- more: { terminal: false }
23
- }))
24
- }
25
- const second = {
26
- broadcast: jest.fn(async () => ({
27
- status: 'success' as const,
28
- txid: tx.id(),
29
- message: 'accepted'
30
- }))
31
- }
32
- const chain = new ProviderChainBroadcaster([
33
- { name: 'Arcade', broadcaster: first },
34
- { name: 'ARC', broadcaster: second }
35
- ])
36
-
37
- const response = await chain.broadcast(tx)
38
-
39
- expect(response.status).toBe('success')
40
- expect(first.broadcast).toHaveBeenCalledTimes(1)
41
- expect(second.broadcast).toHaveBeenCalledTimes(1)
42
- })
43
-
44
- it('stops on terminal double-spend failures', async () => {
45
- const first = {
46
- broadcast: jest.fn(async () => ({
47
- status: 'error' as const,
48
- code: 'DOUBLE_SPEND_ATTEMPTED',
49
- description: 'double spend',
50
- more: { terminal: true, competingTxs: ['22'.repeat(32)] }
51
- }))
52
- }
53
- const second = {
54
- broadcast: jest.fn(async () => ({
55
- status: 'success' as const,
56
- txid: tx.id(),
57
- message: 'accepted'
58
- }))
59
- }
60
- const chain = new ProviderChainBroadcaster([
61
- { name: 'Arcade', broadcaster: first },
62
- { name: 'ARC', broadcaster: second }
63
- ])
64
-
65
- const response = await chain.broadcast(tx)
66
-
67
- expect(response.status).toBe('error')
68
- if (response.status === 'error') {
69
- expect(response.code).toBe('DOUBLE_SPEND_ATTEMPTED')
70
- }
71
- expect(first.broadcast).toHaveBeenCalledTimes(1)
72
- expect(second.broadcast).not.toHaveBeenCalled()
73
- })
74
-
75
- it('classifies Arcade double-spend status as a broadcast failure', async () => {
76
- const requests: Array<{ url: string, init?: RequestInit }> = []
77
- const fetcher = jest.fn(async (url: string, init?: RequestInit) => {
78
- requests.push({ url, init })
79
- return new Response(JSON.stringify({
80
- txid: tx.id(),
81
- txStatus: 'DOUBLE_SPEND_ATTEMPTED',
82
- competingTxs: ['22'.repeat(32)]
83
- }), { status: 202 })
84
- }) as any
85
- const arcade = new ArcadeProvider('https://arcade.example/', {
86
- apiKey: 'secret',
87
- callbackUrl: 'https://overlay.example/arc-ingest',
88
- callbackToken: 'callback',
89
- fetch: fetcher
90
- })
91
-
92
- const response = await arcade.broadcast(tx)
93
-
94
- expect(response.status).toBe('error')
95
- if (response.status === 'error') {
96
- expect(response.code).toBe('DOUBLE_SPEND_ATTEMPTED')
97
- }
98
- expect(requests[0].url).toBe('https://arcade.example/tx')
99
- expect((requests[0].init?.headers as Record<string, string>).Authorization).toBe('Bearer secret')
100
- })
101
-
102
- it('validates merkle roots through go-chaintracks headers', async () => {
103
- const fetcher = jest.fn(async (url: string) => {
104
- if (url.endsWith('/height')) {
105
- return new Response(JSON.stringify({ height: 900000 }), { status: 200 })
106
- }
107
- if (url.endsWith('/header/height/900000')) {
108
- return new Response(JSON.stringify({
109
- height: 900000,
110
- hash: 'aa'.repeat(32),
111
- merkleRoot: 'bb'.repeat(32)
112
- }), { status: 200 })
113
- }
114
- return new Response('', { status: 404 })
115
- }) as any
116
- const chaintracks = new ChaintracksProvider('https://arcade.example', { fetch: fetcher })
117
-
118
- await expect(chaintracks.currentHeight()).resolves.toBe(900000)
119
- await expect(chaintracks.isValidRootForHeight('bb'.repeat(32), 900000)).resolves.toBe(true)
120
- await expect(chaintracks.isValidRootForHeight('cc'.repeat(32), 900000)).resolves.toBe(false)
121
- expect(chaintracks.reorgStreamUrl()).toBe('https://arcade.example/chaintracks/v2/reorg/stream')
122
- })
123
- })
@@ -1,105 +0,0 @@
1
- # Unit Tests for @bsv/overlay-express
2
-
3
- This directory contains comprehensive unit tests for the overlay-express library.
4
-
5
- ## Test Structure
6
-
7
- - **InMemoryMigrationSource.test.ts** - Tests for the internal migration source (tested through integration)
8
- - **makeUserInterface.test.ts** - Tests for the web UI generation function
9
- - **JanitorService.test.ts** - Tests for the janitor health check service
10
- - **OverlayExpress.test.ts** - Tests for the main OverlayExpress class
11
-
12
- ## Running Tests
13
-
14
- ```bash
15
- # Run all tests
16
- npm test
17
-
18
- # Run tests in watch mode
19
- npm run test:watch
20
-
21
- # Run tests with coverage
22
- npm run test:coverage
23
- ```
24
-
25
- ## Test Coverage
26
-
27
- The test suite covers:
28
-
29
- ### makeUserInterface
30
- - Default configuration generation
31
- - Custom UI configuration
32
- - Color customization
33
- - Font customization
34
- - Responsive design
35
- - JavaScript function inclusion
36
- - External links
37
-
38
- ### JanitorService
39
- - Constructor and initialization
40
- - Health check execution
41
- - Domain validation (valid domains, localhost, IP addresses)
42
- - URL extraction from various field types
43
- - Output health status management
44
- - Down counter increment/decrement
45
- - Output deletion on threshold
46
- - Timeout handling
47
- - Error handling
48
-
49
- ### OverlayExpress
50
- - Constructor with various parameter combinations
51
- - Admin token generation and retrieval
52
- - Port configuration
53
- - Web UI configuration
54
- - Janitor configuration
55
- - Logger configuration
56
- - Network configuration (main/test)
57
- - ChainTracker configuration
58
- - ARC API key configuration
59
- - GASP sync configuration
60
- - Verbose logging configuration
61
- - Knex (SQL) database configuration
62
- - MongoDB configuration
63
- - Topic Manager configuration
64
- - Lookup Service configuration
65
- - Engine configuration
66
- - Error handling for missing dependencies
67
- - Full integration scenarios
68
-
69
- ## Mocking Strategy
70
-
71
- The tests use Jest mocks for external dependencies:
72
- - `knex` - Database client
73
- - `mongodb` - MongoDB client
74
- - `@bsv/overlay` - Overlay services
75
- - `@bsv/sdk` - BSV SDK
76
- - `@bsv/overlay-discovery-services` - Discovery services
77
- - `chalk` - Console coloring (suppressed in tests)
78
- - `fetch` - HTTP requests (for JanitorService)
79
-
80
- ## Test Environment
81
-
82
- - **Test Framework**: Jest 29+
83
- - **TypeScript**: ts-jest preset
84
- - **Environment**: Node.js
85
- - **Coverage Tool**: Jest built-in coverage
86
-
87
- ## Writing New Tests
88
-
89
- When adding new features:
90
-
91
- 1. Create test file in `__tests__` directory
92
- 2. Follow the naming convention: `FeatureName.test.ts`
93
- 3. Use descriptive test names with `describe` and `it` blocks
94
- 4. Mock external dependencies
95
- 5. Test both success and error paths
96
- 6. Include edge cases
97
- 7. Update this README with new test coverage
98
-
99
- ## CI/CD Integration
100
-
101
- These tests are designed to run in CI/CD pipelines:
102
- - Fast execution
103
- - No external dependencies required
104
- - Comprehensive coverage
105
- - Clear error messages
@@ -1,66 +0,0 @@
1
- import { parseReorgEvent, extractSseFrames } from '../ReorgStream.js'
2
-
3
- const HASH_A = 'AABB000000000000000000000000000000000000000000000000000000000000'
4
- const HASH_B = 'ccdd000000000000000000000000000000000000000000000000000000000000'
5
-
6
- describe('parseReorgEvent', () => {
7
- it('maps a go-chaintracks ReorgEvent to handleReorg input (normalizing hashes)', () => {
8
- const event = JSON.stringify({
9
- orphanedHashes: [HASH_A, HASH_B],
10
- commonAncestor: { height: 100, hash: '00ff' },
11
- newTip: { height: 103, hash: '11ee' },
12
- depth: 3
13
- })
14
-
15
- const result = parseReorgEvent(event)
16
-
17
- expect(result).toEqual({
18
- orphanedBlockHashes: [HASH_A.toLowerCase(), HASH_B],
19
- rebuildFromHeight: 101,
20
- newTipHeight: 103
21
- })
22
- })
23
-
24
- it('falls back to depth when commonAncestor is absent (reorg past pruned history)', () => {
25
- const event = JSON.stringify({
26
- orphanedHashes: [HASH_A],
27
- commonAncestor: null,
28
- newTip: { height: 103, hash: '11ee' },
29
- depth: 3
30
- })
31
-
32
- const result = parseReorgEvent(event)
33
-
34
- // 103 - 3 + 1 = 101
35
- expect(result?.rebuildFromHeight).toBe(101)
36
- expect(result?.newTipHeight).toBe(103)
37
- })
38
-
39
- it('returns null for malformed frames', () => {
40
- expect(parseReorgEvent('not json')).toBeNull()
41
- expect(parseReorgEvent(JSON.stringify({ orphanedHashes: [] }))).toBeNull() // no newTip
42
- })
43
- })
44
-
45
- describe('extractSseFrames', () => {
46
- it('extracts complete data frames and ignores keepalive comments', () => {
47
- const buffer = 'data: {"a":1}\n\n: keepalive\n\ndata: {"b":2}\n\n'
48
- const { events, rest } = extractSseFrames(buffer)
49
- expect(events).toEqual(['{"a":1}', '{"b":2}'])
50
- expect(rest).toBe('')
51
- })
52
-
53
- it('retains a partial trailing frame in rest', () => {
54
- const buffer = 'data: {"a":1}\n\ndata: {"b":'
55
- const { events, rest } = extractSseFrames(buffer)
56
- expect(events).toEqual(['{"a":1}'])
57
- expect(rest).toBe('data: {"b":')
58
- })
59
-
60
- it('concatenates multi-line data fields within one frame', () => {
61
- const buffer = 'data: {"a":\ndata: 1}\n\n'
62
- const { events, rest } = extractSseFrames(buffer)
63
- expect(events).toEqual(['{"a":1}'])
64
- expect(rest).toBe('')
65
- })
66
- })